noesis_runtime 0.12.1

Rust bindings for the Noesis GUI Native SDK: load XAML UI, drive the view and renderer, and write custom controls in Rust. Renderer-agnostic; Bevy integration lives in noesis_bevy.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
// C++ subclasses that satisfy the Noesis pure-virtual `RenderDevice`,
// `Texture`, and `RenderTarget` contracts by trampolining into the Rust-side
// vtable supplied at construction. Plus the C-ABI factory functions the Rust
// `register()` helper calls. The C ABI surface is declared in noesis_shim.h.

#include "noesis_shim.h"

#include <NsCore/Noesis.h>
#include <NsCore/Ptr.h>
#include <NsRender/RenderDevice.h>
#include <NsRender/RenderTarget.h>
#include <NsRender/Texture.h>

#include <cstdint>
#include <utility>
#include <vector>

namespace {

class RustRenderDevice;

// ─── RustTexture ────────────────────────────────────────────────────────────
//
// Stores the metadata Noesis exposes through const-getters as plain members so
// the getters are zero-overhead. Holds a back-pointer to its parent device so
// the destructor can call `drop_texture`. The device outlives all textures it
// produced because Rust drops the device only AFTER dropping the
// `noesis_render_device_destroy` reference, which transitively releases
// every Noesis-held `Ptr<Texture>`.

class RustTexture final : public Noesis::Texture {
public:
    RustTexture(RustRenderDevice* device, uint64_t handle,
                uint32_t width, uint32_t height,
                Noesis::TextureFormat::Enum format,
                bool has_mipmaps, bool inverted, bool has_alpha)
        : mDevice(device)
        , mHandle(handle)
        , mWidth(width)
        , mHeight(height)
        , mFormat(format)
        , mHasMipMaps(has_mipmaps)
        , mInverted(inverted)
        , mHasAlpha(has_alpha)
    {}

    ~RustTexture();

    uint32_t GetWidth() const override { return mWidth; }
    uint32_t GetHeight() const override { return mHeight; }
    bool HasMipMaps() const override { return mHasMipMaps; }
    bool IsInverted() const override { return mInverted; }
    bool HasAlpha() const override { return mHasAlpha; }

    uint64_t handle() const { return mHandle; }
    Noesis::TextureFormat::Enum format() const { return mFormat; }

private:
    RustRenderDevice* mDevice;
    uint64_t mHandle;
    uint32_t mWidth;
    uint32_t mHeight;
    Noesis::TextureFormat::Enum mFormat;
    bool mHasMipMaps;
    bool mInverted;
    bool mHasAlpha;
};

// ─── RustRenderTarget ───────────────────────────────────────────────────────
//
// Holds the resolve `RustTexture` as a `Ptr<>` so its lifetime is tied to the
// render target. `GetTexture` returns the raw pointer; Noesis treats the
// returned `Texture*` as borrowed.

class RustRenderTarget final : public Noesis::RenderTarget {
public:
    RustRenderTarget(RustRenderDevice* device, uint64_t handle,
                     Noesis::Ptr<RustTexture> resolve)
        : mDevice(device)
        , mHandle(handle)
        , mResolve(std::move(resolve))
    {}

    ~RustRenderTarget();

    Noesis::Texture* GetTexture() override { return mResolve.GetPtr(); }

    uint64_t handle() const { return mHandle; }

private:
    RustRenderDevice* mDevice;
    uint64_t mHandle;
    Noesis::Ptr<RustTexture> mResolve;
};

// ─── RustRenderDevice ───────────────────────────────────────────────────────

class RustRenderDevice final : public Noesis::RenderDevice {
public:
    RustRenderDevice(const noesis_render_device_vtable* vtable, void* userdata)
        : mVtable(*vtable)
        , mUserdata(userdata)
    {}

    // Runs when Noesis releases the device's last `Ptr<>` — past which no vtable
    // callback fires. Frees the boxed impl here, not in the caller's `destroy`,
    // so `mUserdata` outlives every callback. Members are all values, so the
    // dtor body is the final event.
    ~RustRenderDevice() override { mVtable.drop_userdata(mUserdata); }

    void dropTexture(uint64_t h) { mVtable.drop_texture(mUserdata, h); }
    void dropRenderTarget(uint64_t h) { mVtable.drop_render_target(mUserdata, h); }

    // ── RenderDevice virtuals ──────────────────────────────────────────────

    const Noesis::DeviceCaps& GetCaps() const override {
        if (!mCapsValid) {
            mVtable.get_caps(mUserdata, &mCaps);
            mCapsValid = true;
        }
        return mCaps;
    }

    Noesis::Ptr<Noesis::RenderTarget> CreateRenderTarget(
        const char* label, uint32_t width, uint32_t height,
        uint32_t sampleCount, bool needsStencil) override
    {
        noesis_render_target_binding b{};
        mVtable.create_render_target(mUserdata, label, width, height,
                                     sampleCount, needsStencil, &b);
        return makeRenderTarget(b);
    }

    Noesis::Ptr<Noesis::RenderTarget> CloneRenderTarget(
        const char* label, Noesis::RenderTarget* surface) override
    {
        const auto src = static_cast<RustRenderTarget*>(surface);
        noesis_render_target_binding b{};
        // Cloning an inert handle-0 source yields another inert wrapper (b stays
        // zero) rather than forwarding a handle the Rust impl never created.
        if (src->handle() != 0) {
            mVtable.clone_render_target(mUserdata, label, src->handle(), &b);
        }
        return makeRenderTarget(b);
    }

    Noesis::Ptr<Noesis::Texture> CreateTexture(
        const char* label, uint32_t width, uint32_t height, uint32_t numLevels,
        Noesis::TextureFormat::Enum format, const void** data) override
    {
        noesis_texture_binding b{};
        mVtable.create_texture(mUserdata, label, width, height, numLevels,
                               static_cast<uint32_t>(format), data, &b);
        return makeTexture(b, format);
    }

    void UpdateTexture(Noesis::Texture* texture, uint32_t level,
                       uint32_t x, uint32_t y, uint32_t width, uint32_t height,
                       const void* data) override
    {
        const auto* t = static_cast<RustTexture*>(texture);
        if (t->handle() == 0) return;  // inert handle-0 texture; skip callback
        mVtable.update_texture(mUserdata, t->handle(), level, x, y, width, height,
                               static_cast<uint32_t>(t->format()), data);
    }

    void EndUpdatingTextures(Noesis::Texture** textures, uint32_t count) override {
        if (count == 0) return;
        std::vector<uint64_t> handles;
        handles.reserve(count);
        for (uint32_t i = 0; i < count; ++i) {
            // Drop inert handle-0 textures so the Rust impl never sees a handle
            // it did not create.
            const uint64_t h = static_cast<RustTexture*>(textures[i])->handle();
            if (h != 0) handles.push_back(h);
        }
        if (handles.empty()) return;
        mVtable.end_updating_textures(mUserdata, handles.data(),
                                      static_cast<uint32_t>(handles.size()));
    }

    void BeginOffscreenRender() override { mVtable.begin_offscreen_render(mUserdata); }
    void EndOffscreenRender()   override { mVtable.end_offscreen_render(mUserdata); }
    void BeginOnscreenRender()  override { mVtable.begin_onscreen_render(mUserdata); }
    void EndOnscreenRender()    override { mVtable.end_onscreen_render(mUserdata); }

    void SetRenderTarget(Noesis::RenderTarget* surface) override {
        // An inert handle-0 target (failed create) forwards nothing; see
        // makeRenderTarget. The same guard applies to the tile/resolve paths.
        const uint64_t h = static_cast<RustRenderTarget*>(surface)->handle();
        if (h == 0) return;
        mVtable.set_render_target(mUserdata, h);
    }

    void BeginTile(Noesis::RenderTarget* surface, const Noesis::Tile& tile) override {
        const uint64_t h = static_cast<RustRenderTarget*>(surface)->handle();
        if (h == 0) return;
        mVtable.begin_tile(mUserdata, h, &tile);
    }

    void EndTile(Noesis::RenderTarget* surface) override {
        const uint64_t h = static_cast<RustRenderTarget*>(surface)->handle();
        if (h == 0) return;
        mVtable.end_tile(mUserdata, h);
    }

    void ResolveRenderTarget(Noesis::RenderTarget* surface,
                             const Noesis::Tile* tiles, uint32_t numTiles) override
    {
        const uint64_t h = static_cast<RustRenderTarget*>(surface)->handle();
        if (h == 0) return;
        mVtable.resolve_render_target(mUserdata, h, tiles, numTiles);
    }

    void* MapVertices(uint32_t bytes) override { return mVtable.map_vertices(mUserdata, bytes); }
    void  UnmapVertices() override            { mVtable.unmap_vertices(mUserdata); }
    void* MapIndices(uint32_t bytes) override  { return mVtable.map_indices(mUserdata, bytes); }
    void  UnmapIndices() override             { mVtable.unmap_indices(mUserdata); }

    void DrawBatch(const Noesis::Batch& batch) override {
        mVtable.draw_batch(mUserdata, &batch);
    }

private:
    Noesis::Ptr<RustTexture> makeTexture(const noesis_texture_binding& b,
                                         Noesis::TextureFormat::Enum format) {
        return Noesis::MakePtr<RustTexture>(this, b.handle, b.width, b.height,
                                            format, b.has_mipmaps, b.inverted, b.has_alpha);
    }

    Noesis::Ptr<Noesis::RenderTarget> makeRenderTarget(
        const noesis_render_target_binding& b)
    {
        // Resolve textures are always RGBA8. That's what Noesis uses for the
        // composited surface. (The Rust impl is free to pick a wgpu format
        // internally as long as that mapping is consistent with how it reads
        // back via UpdateTexture.)
        return Noesis::MakePtr<RustRenderTarget>(
            this, b.handle,
            makeTexture(b.resolve_texture, Noesis::TextureFormat::RGBA8));
    }

    noesis_render_device_vtable mVtable;
    void* mUserdata;
    mutable Noesis::DeviceCaps mCaps{};
    mutable bool mCapsValid = false;
};

// Definitions outside the class bodies because each destructor needs the full
// `RustRenderDevice` definition to call `drop*`.

RustTexture::~RustTexture() {
    // A handle of 0 marks an inert wrapper: the Rust impl panicked or rejected
    // the create call and left `out` zero-initialised, so there is no resource
    // to drop and it never handed us this handle. Forwarding 0 would trip the
    // nonzero-handle assertion in the Rust trampoline (swallowed per call).
    if (mHandle != 0) mDevice->dropTexture(mHandle);
}

RustRenderTarget::~RustRenderTarget() {
    if (mHandle != 0) mDevice->dropRenderTarget(mHandle);  // inert handle; see above
}

}  // namespace

// ─── Factory C ABI ──────────────────────────────────────────────────────────

extern "C" void* noesis_render_device_create(
    const noesis_render_device_vtable* vtable, void* userdata)
{
    if (!vtable) return nullptr;
    Noesis::Ptr<RustRenderDevice> device =
        Noesis::MakePtr<RustRenderDevice>(vtable, userdata);
    // MakePtr returns refcount = 1. GiveOwnership clears the smart pointer
    // without decrementing, transferring the +1 to the C-ABI caller.
    return device.GiveOwnership();
}

extern "C" void noesis_render_device_destroy(void* device) {
    if (!device) return;
    static_cast<Noesis::RenderDevice*>(device)->Release();
}

// ─── Offscreen / glyph-cache tuning ─────────────────────────────────────────
//
// Non-virtual configuration on the `Noesis::RenderDevice` base, applied to the
// device the renderer draws with. Width/height of 0 means automatic. These
// affect resource sizing only, so they are plain pass-through setters; no-ops
// on a NULL device.

extern "C" void noesis_render_device_set_offscreen_width(void* device, uint32_t width) {
    if (!device) return;
    static_cast<Noesis::RenderDevice*>(device)->SetOffscreenWidth(width);
}

extern "C" void noesis_render_device_set_offscreen_height(void* device, uint32_t height) {
    if (!device) return;
    static_cast<Noesis::RenderDevice*>(device)->SetOffscreenHeight(height);
}

extern "C" void noesis_render_device_set_offscreen_sample_count(void* device, uint32_t count) {
    if (!device) return;
    static_cast<Noesis::RenderDevice*>(device)->SetOffscreenSampleCount(count);
}

extern "C" void noesis_render_device_set_offscreen_default_num_surfaces(void* device, uint32_t num) {
    if (!device) return;
    static_cast<Noesis::RenderDevice*>(device)->SetOffscreenDefaultNumSurfaces(num);
}

extern "C" void noesis_render_device_set_offscreen_max_num_surfaces(void* device, uint32_t num) {
    if (!device) return;
    static_cast<Noesis::RenderDevice*>(device)->SetOffscreenMaxNumSurfaces(num);
}

extern "C" void noesis_render_device_set_glyph_cache_width(void* device, uint32_t width) {
    if (!device) return;
    static_cast<Noesis::RenderDevice*>(device)->SetGlyphCacheWidth(width);
}

extern "C" void noesis_render_device_set_glyph_cache_height(void* device, uint32_t height) {
    if (!device) return;
    static_cast<Noesis::RenderDevice*>(device)->SetGlyphCacheHeight(height);
}

extern "C" uint32_t noesis_render_device_get_offscreen_width(const void* device) {
    if (!device) return 0;
    return static_cast<const Noesis::RenderDevice*>(device)->GetOffscreenWidth();
}

extern "C" uint32_t noesis_render_device_get_offscreen_height(const void* device) {
    if (!device) return 0;
    return static_cast<const Noesis::RenderDevice*>(device)->GetOffscreenHeight();
}

extern "C" uint32_t noesis_render_device_get_offscreen_sample_count(const void* device) {
    if (!device) return 0;
    return static_cast<const Noesis::RenderDevice*>(device)->GetOffscreenSampleCount();
}

extern "C" uint32_t noesis_render_device_get_offscreen_default_num_surfaces(const void* device) {
    if (!device) return 0;
    return static_cast<const Noesis::RenderDevice*>(device)->GetOffscreenDefaultNumSurfaces();
}

extern "C" uint32_t noesis_render_device_get_offscreen_max_num_surfaces(const void* device) {
    if (!device) return 0;
    return static_cast<const Noesis::RenderDevice*>(device)->GetOffscreenMaxNumSurfaces();
}

extern "C" uint32_t noesis_render_device_get_glyph_cache_width(const void* device) {
    if (!device) return 0;
    return static_cast<const Noesis::RenderDevice*>(device)->GetGlyphCacheWidth();
}

extern "C" uint32_t noesis_render_device_get_glyph_cache_height(const void* device) {
    if (!device) return 0;
    return static_cast<const Noesis::RenderDevice*>(device)->GetGlyphCacheHeight();
}

extern "C" uint64_t noesis_texture_get_handle(const void* texture) {
    if (!texture) return 0;
    return static_cast<const RustTexture*>(
               static_cast<const Noesis::Texture*>(texture))->handle();
}

extern "C" uint64_t noesis_render_target_get_handle(const void* surface) {
    if (!surface) return 0;
    return static_cast<const RustRenderTarget*>(
               static_cast<const Noesis::RenderTarget*>(surface))->handle();
}

// ─── Test-only entrypoints ─────────────────────────────────────────────────
//
// Gated by the `test-utils` Cargo feature (which sets NOESIS_TEST_UTILS).
// Production builds omit them entirely.

#ifdef NOESIS_TEST_UTILS

// One-shot frame scenario that exercises every Noesis virtual the device
// implements, in the documented frame-protocol order. Lets all Ptr<>s die at
// function exit so drop_texture / drop_render_target fire and the Rust mock
// can observe the cleanup ordering.
//
// Used by tests/render_device.rs.
extern "C" void noesis_test_run_frame_scenario(void* device_ptr) {
    auto* device = static_cast<RustRenderDevice*>(device_ptr);

    // ── Caps query (cached after first call) ───────────────────────────────
    (void)device->GetCaps();

    // ── Create textures ────────────────────────────────────────────────────
    static const uint32_t pixels4x4_rgba8[16] = {
        0xff0000ff, 0xff00ff00, 0xffff0000, 0xffffffff,
        0xff0000ff, 0xff00ff00, 0xffff0000, 0xffffffff,
        0xff0000ff, 0xff00ff00, 0xffff0000, 0xffffffff,
        0xff0000ff, 0xff00ff00, 0xffff0000, 0xffffffff,
    };
    const void* immutable_data[1] = { pixels4x4_rgba8 };

    Noesis::Ptr<Noesis::Texture> t_immutable = device->CreateTexture(
        "t_immutable", 4, 4, 1, Noesis::TextureFormat::RGBA8, immutable_data);

    Noesis::Ptr<Noesis::Texture> t_dynamic = device->CreateTexture(
        "t_dynamic", 16, 16, 1, Noesis::TextureFormat::R8, nullptr);

    static const uint8_t patch4x4_r8[16] = {
        0x10, 0x20, 0x30, 0x40,
        0x50, 0x60, 0x70, 0x80,
        0x90, 0xa0, 0xb0, 0xc0,
        0xd0, 0xe0, 0xf0, 0xff,
    };
    device->UpdateTexture(t_dynamic.GetPtr(), 0, 2, 2, 4, 4, patch4x4_r8);

    Noesis::Texture* dirty[1] = { t_dynamic.GetPtr() };
    device->EndUpdatingTextures(dirty, 1);

    // ── Create render target ───────────────────────────────────────────────
    Noesis::Ptr<Noesis::RenderTarget> rt = device->CreateRenderTarget(
        "rt_main", 256, 256, 1, true);

    // ── Offscreen phase ────────────────────────────────────────────────────
    device->BeginOffscreenRender();
    device->SetRenderTarget(rt.GetPtr());
    Noesis::Tile tile = { 0, 0, 256, 256 };
    device->BeginTile(rt.GetPtr(), tile);

    (void)device->MapVertices(96);
    device->UnmapVertices();
    (void)device->MapIndices(36);
    device->UnmapIndices();

    Noesis::Batch offscreen_batch{};
    offscreen_batch.shader.v = Noesis::Shader::Path_Solid;
    offscreen_batch.numVertices = 4;
    offscreen_batch.numIndices = 6;
    device->DrawBatch(offscreen_batch);

    device->EndTile(rt.GetPtr());
    device->ResolveRenderTarget(rt.GetPtr(), &tile, 1);
    device->EndOffscreenRender();

    // ── Onscreen phase ─────────────────────────────────────────────────────
    device->BeginOnscreenRender();

    (void)device->MapVertices(96);
    device->UnmapVertices();
    (void)device->MapIndices(36);
    device->UnmapIndices();

    Noesis::Batch onscreen_batch{};
    onscreen_batch.shader.v = Noesis::Shader::RGBA;
    onscreen_batch.numVertices = 4;
    onscreen_batch.numIndices = 6;
    device->DrawBatch(onscreen_batch);

    device->EndOnscreenRender();

    // ── Clone (exercises clone_render_target) ──────────────────────────────
    Noesis::Ptr<Noesis::RenderTarget> rt_clone = device->CloneRenderTarget(
        "rt_clone", rt.GetPtr());
    (void)rt_clone;

    // Function exit destroys (in reverse declaration order):
    //   rt_clone     → drop_render_target(clone) + drop_texture(clone resolve)
    //   rt           → drop_render_target(main)  + drop_texture(main resolve)
    //   t_dynamic    → drop_texture(dynamic)
    //   t_immutable  → drop_texture(immutable)
}

#endif  // NOESIS_TEST_UTILS