Device Layer & Render Graph

engine-render-device (render/device/) is internal to the renderers; scene and material records never contain device handles. Native Metal and browser WebGPU share the same render graph for the stage's cameras and materials, subviews, UI, and encoded SDR presentation (The stage). Native MetalFX and ray tracing encode through explicit graph native nodes with declared resources.

Ownership and API

  • Handles & retention — Buffer, Texture, Sampler, Shader, BindLayout, BindGroup, and Pipeline are typed Arc-backed handles belonging to one DeviceId. Bind groups retain their resources; pipelines retain shader and layout descriptions; a submission retains everything it references through GPU completion. A Draw<'a> handed to a backend borrows its pipeline, bind group, buffers, dynamic offsets, and optional visibility handle: the graph retains each once per submission, so encoding draws moves no reference counts and backends keep nothing per draw.
  • Bind-group cache & dynamic uniforms — Graph::execute resolves each distinct (layout, bindings) set once per graph via an open-addressed table keyed by binding words, probing Device::find_bind_group with raw BindingViews before building handles on a miss. Ordinary buffers include offset and size in the key; dynamic uniform bindings use offset 0 in the group and carry 256-byte-aligned per-draw offsets separately. Ephemeral groups (upload-slab non-dynamic ranges, pooled transients) retire after two slot rotations and a submission. Persistent-only groups move to an LRU retained set (cap 8,192) and stay cached until unused past the retention horizon and orphaned (checked via Arc::strong_count). WebGPU skips setBindGroup when group and offsets match; Metal tracks bound encoder state and updates only changed dynamic offsets.
  • Buffers, textures & samplers — Buffers carry BufferUse flags (storage, uniform, vertex, index, indirect). Textures are 2D, 2D array (1–256 layers), cube, or cube array (1–42 cubes), with mip counts and 1x/4x 2D attachments with explicit resolves. Arrays and cubes are sampled-only. An Rgba8Unorm texture created with srgb_view exposes Device::create_srgb_view, an Rgba8UnormSrgb view of the same storage (Metal pixel-format view, WebGPU viewFormats) that blends and writes in linear light — used by the UI toolkit's linear-light blending. Samplers support independent min/mag/mip filters, clamp/repeat/mirror, LOD limits, anisotropy, and CompareGreaterEqual comparison sampling alongside Depth2D for shadow maps. Colour::EncodedSdr and Colour::Data label interpretation independently of storage format (Colour C3).
  • Vertex-pulling indirect draws — A raster draw has geometry iff its vertex entry has inputs, except a vertex-pulling entry (no inputs, reading storage buffers via SV_VertexID/SV_InstanceID) may supply an index buffer for an indexed indirect draw.
  • Depth sampling & buffer copies — Single-sample depth attachments can be loaded through a typed depth binding (depth-only view on WebGPU for depth-stencil textures); sampling a writable attachment and depth readback are rejected. Declared Graph::copy_buffers passes support buffer copies on both backends. Submission callbacks (Box<dyn FnOnce()>) publish state only after graph execution and queue submission.
  • Shader reflection & stage limits — ShaderCode carries offline Slang output, entry names, and reflected descriptors. build/device-shaders.ts verifies parameter types, declaration order, entry bindings, and emitted slots. WebGPU uses group-0 declaration-order slots with explicit per-stage visibility derived by compiling each entry point individually (build/slang.ts) so Slang's dead-code elimination determines visibility. Metal binds resources to both stages. Shared structured records use 16-byte vectors/arrays and checked host offsets.
  • Pipelines — Presentation uses a procedural fullscreen triangle; UI fetches 32-byte storage vertices by SV_VertexID; scene and stage shaders pull vertices from storage buffers or use reflected vertex inputs. Pipelines publish Pending, Ready, or Failed(message) asynchronously and never fall back to an unrelated pipeline.
  • Test hooks — Device::refuse_uploads_after(n) forces upload refusal after n uploads on the next frame for backpressure testing. The testing feature exports LifetimeDevice for downstream crate tests.

Build-Time Metal Libraries

The native device compiles no source for the engine's generated shaders. build/metal-libraries.ts compiles every generated MSL module with xcrun metal to a .metallib, compresses it with LZFSE (compression_tool), and emits target/build/device-shaders/metal/NAME.lzfse plus a small metal/NAME.rs wrapper. Native builds embed the compressed MetalLibrary with empty ShaderCode::source; web builds carry WGSL source and never build Metal libraries.

  • Loading — create_pipeline and create_compute_pipeline decompress with libcompression, create the library via newLibraryWithData on a global queue, and specialize function constants identically to source compiles. Hand-written MSL (such as the ray tracer) still uses newLibraryWithSource.
  • Flags & identity — Compiles with MTLCompileOptions defaults (-fmetal-math-mode=fast -fmetal-math-fp32-functions=fast) targeting the build host OS/Metal version. Each MetalLibrary embeds the build-time SHA-256 of its MSL so digests match across runs.
  • Caching & debugging — Libraries cache in target/build/metal-libraries/ by compiler version, flags, and MSL digest so unchanged modules are not rewritten despite compiler UUIDs. ENGINE_METAL_DEBUG=1 adds -frecord-sources -gline-tables-only for GPU captures (disallowed in release builds). LZFSE was chosen over zlib and LZ4 as the smallest format that decompresses faster than a cached runtime compile.
  • iOS — bun build/build.ts shaders --ios also compiles each library for iphoneos and iphonesimulator SDKs into metal-iphoneos/ and metal-iphonesimulator/ (iOS).
  • Prerequisite — Xcode's Metal toolchain (xcodebuild -downloadComponent MetalToolchain).

Attachment Lifetimes and Resolves

The graph folds a colour resolve into the immediately preceding raster pass when that pass writes the multisample source in the same view and does not use the destination; other resolves remain separate passes.

Single-pass transient colour and depth/stencil attachments automatically receive attachment_only at allocation (owned by the graph, never caller-specified, and part of pool identity). Apple GPUs use memoryless backing; other Metal GPUs use private backing. Both Metal and WebGPU discard the attachment after the pass or resolve without storing the multisample source. Sources read later (e.g., depth for temporal reconstruction or contact shadows) retain storage.

Frame Uploads and Retirement

  • Configuration & backpressure — Config { frames_in_flight, upload_bytes_per_frame } is mandatory with no default. The shared UI defaults to 2 slots and 64 MiB per submission. begin_frame() polls GPU completion and returns false when the next slot is still in flight or the device has failed. A GPU-bound host calls wait_frame_slot() instead of sleeping and retrying: on Metal it blocks until the frame holding the next slot completes; on the web it returns the slot's state immediately. Any upload exceeding the remaining frame allowance returns false without consuming capacity; callers defer it and never draw partially initialized data.
  • Upload ring & blit batching — Metal uses one persistently mapped shared buffer per frame slot for both blit staging and transient input slices, batching uploads into a shared blit encoder closed before graph/native/readback commands and submission. WebGPU allocates a per-slot GPU ring buffer written via wgpuQueueWriteBuffer. Both align transient slices to 256 bytes, obey 4-byte buffer copy rules and 256-byte texture row pitch, and require all uploads before graph encoding.
  • FrameLocal & FrameSlotBuffer — FrameLocal buffers belong to one frame slot and are written only after that slot completes. FrameSlotBuffer (render/device/src/frame_slot_buffer.rs) owns one buffer per slot, growing by doubling so per-frame inputs (UI vertices, stage instances) keep stable buffer identities and hit the retained bind-group cache.
  • Submission retirement & pools — Completion is GPU completion (Metal command-buffer polling; WebGPU queue/map callbacks). Shutdown polls until idle(). Transient attachments are reused from Device::transient_texture once no in-flight graph or frame holds them (idle cached bind groups do not block reuse). Readback buffers pool per frame slot and request index, growing on demand. WebGPU explicitly destroys buffers and textures on last release.

Graph Declaration and Lowering

  • Graph::check & Graph::compile — check validates accesses and caches the transient plan (re-planned in execute only if the graph grew); compile returns Result<Plan, Failed> with explicit RAW/WAR/WAW dependencies and transient lifetimes. Graph recording and planning storage is recycled per thread (up to 4 nested graphs).
  • Imports & compact draws — Graph::import deduplicates textures, buffers, samplers, texture heaps, and pipelines into compact indices. GraphBinding is 16 bytes; GraphDraw holds inline room for 40 bindings without spilling. Layouts cache their dynamic entries so encoding visits only per-draw offsets.
  • Hazard rules & execution order — Passes declare reads and writes via attachments, draws, compute layouts, and readbacks; uninitialized reads, self-feedback, and usage mismatches fail compilation. Execution preserves insertion order (including transparent ordering).
  • Graph-local transient reuse — A transient is allocated on first use and returned to a graph-local free list at its last pass so subsequent non-overlapping transients of identical description reuse it within the same frame. Transients are never aliased across descriptions or with imports.
  • Nested views & compute — subview(parent, name) records explicit nested view identity while sharing graph resource identities and dependencies. Both backends run one ordered graphics queue, deriving transitions and barriers from pass boundaries. ComputeCode carries offline MSL/WGSL, buffer-only layouts, and workgroup sizes; StorageWrite initializes outputs and participates in RAW/WAR/WAW tracking (including later vertex/indirect reads).

Surfaces, Readback, Errors and Threading

  • Surfaces & presentation — WebGPU (webgpu.h via pinned emdawnwebgpu) configures RGBA8/BGRA8 UNORM with WGPUSurfaceColorManagement (sRGB colour space, standard SDR tone mapping, opaque/FIFO). Metal (objc2-metal) draws to a borrowed SDL CAMetalLayer (BGRA8 UNORM, sRGB metadata). Presentation applies the display gamma LUT once to the encoded scene/UI image and preserves alpha (no sRGB attachments). Surface readback permission is opt-in (framebufferOnly disabled only for test/capture).
  • Async readbacks — Graph::readback returns a single-use ticket (Pending → tightly packed RGBA8/BGRA8/RGBA16Float/RGBA32Float bytes or Failed), rejecting duplicate scheduling. Metal copies to shared storage; WebGPU copies to MAP_READ | COPY_DST and calls mapAsync.
  • Occlusion queries — Draws may attach a Visibility handle (shared across draws/passes), backed by Metal boolean visibility buffers and WebGPU occlusion query sets, publishing Ready and boolean visibility after GPU completion.
  • Errors & threading — Declaration and async errors return Failed; invalid ownership/ordering asserts; queue failure is terminal. All device calls occur on the single GPU-owning thread. Browser callbacks publish state only and never block; Metal compiler callbacks publish with release/acquire semantics. Decode and asset workers never touch the device API.

UI and Scene Coexistence

engine_gfx::Renderer (gfx/src/renderer.rs) drives both platforms via shaders/ui.slang (textured/untextured geometry, glyph quads, modulation, rotated/flipped quads, gamma ramp). Logical sizing, clipping, and SDL blend modes (NONE, BLEND, ADD, MOD, MUL, premultiplied) follow SDL 3.4 equations in encoded SDR space (Colour C3). UI uploads are admitted before scene recorders so scene streaming cannot starve the HUD. On Metal, SDL creates a Metal view and lends its CAMetalLayer to the device; scene passes record before UI composition on the same device.

Native Feature Nodes and Diagnostics

  • Native nodes — Graph::native declares all read/written buffers and textures before encoding and exposes only those handles plus the command buffer to a NativeCommand implementing NativeContext on Metal (used by the stage's MetalFX scaler and ray-traced shadows); WebGPU rejects native nodes. Multiple colour attachments are supported on both backends.
  • Pass timers (ENGINE_PASS_TIMES) — On Metal, per-submission counter buffers sample render/compute/blit stage boundaries, clipping overlapping tile-GPU intervals and resolving after completion with sampleTimestamps calibration. Device::set_pass_timing toggles timing at runtime on Metal (WebGPU requires ENGINE_PASS_TIMES at device creation); off allocates no counter buffers.
  • Memory by owner — memory_ledger() (render/device/src/device.rs) estimates live buffer and texture bytes (packed mip chain × layers × samples; alignment, memoryless savings, and native RT structures excluded) under thread-local MemoryScope owners: scene-textures, scene-geometry, scene-instances, targets, shadows, lighting, characters, ui, and other.

Boundaries and Validation

Deferred / out of scope: Vulkan, async compute queues, subresource hazards, cross-description or cross-frame transient aliasing, and binary pipeline archives.

Run tests from the Xodó root (Metal tests require display access):

sh
cargo test --locked -p engine-render-device

tests/device_graph.rs covers graph compilation and hazards; tests/metal_device.rs runs the Metal backend headless on the GPU, including a build-time library compiled with xcrun metal.