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, andPipelineare typedArc-backed handles belonging to oneDeviceId. Bind groups retain their resources; pipelines retain shader and layout descriptions; a submission retains everything it references through GPU completion. ADraw<'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::executeresolves each distinct(layout, bindings)set once per graph via an open-addressed table keyed by binding words, probingDevice::find_bind_groupwith rawBindingViews 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 viaArc::strong_count). WebGPU skipssetBindGroupwhen group and offsets match; Metal tracks bound encoder state and updates only changed dynamic offsets. - Buffers, textures & samplers — Buffers carry
BufferUseflags (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. AnRgba8Unormtexture created withsrgb_viewexposesDevice::create_srgb_view, anRgba8UnormSrgbview of the same storage (Metal pixel-format view, WebGPUviewFormats) 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, andCompareGreaterEqualcomparison sampling alongsideDepth2Dfor shadow maps.Colour::EncodedSdrandColour::Datalabel 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_bufferspasses support buffer copies on both backends. Submission callbacks (Box<dyn FnOnce()>) publish state only after graph execution and queue submission. - Shader reflection & stage limits —
ShaderCodecarries offline Slang output, entry names, and reflected descriptors.build/device-shaders.tsverifies 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 publishPending,Ready, orFailed(message)asynchronously and never fall back to an unrelated pipeline. - Test hooks —
Device::refuse_uploads_after(n)forces upload refusal afternuploads on the next frame for backpressure testing. Thetestingfeature exportsLifetimeDevicefor 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_pipelineandcreate_compute_pipelinedecompress withlibcompression, create the library vianewLibraryWithDataon a global queue, and specialize function constants identically to source compiles. Hand-written MSL (such as the ray tracer) still usesnewLibraryWithSource. - Flags & identity — Compiles with
MTLCompileOptionsdefaults (-fmetal-math-mode=fast -fmetal-math-fp32-functions=fast) targeting the build host OS/Metal version. EachMetalLibraryembeds 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=1adds-frecord-sources -gline-tables-onlyfor 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 --iosalso compiles each library foriphoneosandiphonesimulatorSDKs intometal-iphoneos/andmetal-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 returnsfalsewhen the next slot is still in flight or the device has failed. A GPU-bound host callswait_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 returnsfalsewithout 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—FrameLocalbuffers 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 fromDevice::transient_textureonce 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—checkvalidates accesses and caches the transient plan (re-planned inexecuteonly if the graph grew);compilereturnsResult<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::importdeduplicates textures, buffers, samplers, texture heaps, and pipelines into compact indices.GraphBindingis 16 bytes;GraphDrawholds 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.ComputeCodecarries offline MSL/WGSL, buffer-only layouts, and workgroup sizes;StorageWriteinitializes outputs and participates in RAW/WAR/WAW tracking (including later vertex/indirect reads).
Surfaces, Readback, Errors and Threading
- Surfaces & presentation — WebGPU (
webgpu.hvia pinned emdawnwebgpu) configures RGBA8/BGRA8 UNORM withWGPUSurfaceColorManagement(sRGB colour space, standard SDR tone mapping, opaque/FIFO). Metal (objc2-metal) draws to a borrowed SDLCAMetalLayer(BGRA8 UNORM, sRGB metadata).Presentationapplies the display gamma LUT once to the encoded scene/UI image and preserves alpha (no sRGB attachments). Surface readback permission is opt-in (framebufferOnlydisabled only for test/capture). - Async readbacks —
Graph::readbackreturns a single-use ticket (Pending→ tightly packed RGBA8/BGRA8/RGBA16Float/RGBA32Float bytes orFailed), rejecting duplicate scheduling. Metal copies to shared storage; WebGPU copies toMAP_READ | COPY_DSTand callsmapAsync. - Occlusion queries — Draws may attach a
Visibilityhandle (shared across draws/passes), backed by Metal boolean visibility buffers and WebGPU occlusion query sets, publishingReadyand 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::nativedeclares all read/written buffers and textures before encoding and exposes only those handles plus the command buffer to aNativeCommandimplementingNativeContexton 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 withsampleTimestampscalibration.Device::set_pass_timingtoggles timing at runtime on Metal (WebGPU requiresENGINE_PASS_TIMESat 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-localMemoryScopeowners:scene-textures,scene-geometry,scene-instances,targets,shadows,lighting,characters,ui, andother.
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):
cargo test --locked -p engine-render-devicetests/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.