Stage Overview & Renderer

The stage is Xodó's unified scene API and renderer for 2D, 2.5D, and 3D games. Its core lives in two crates that hosts opt into directly:

  • engine-stage (stage/) — Headless CPU scene model (transforms, cameras, visibility, sorting, culling, picking, and text layout via harfrust and skrifa).
  • engine-stage-render (stage/render/) — Draws stage draw lists through the device layer.

Optional world capabilities (regions, cells and portals, terrain, skeletal skinning, converted assets, and built-in world materials) live in separate crates under stage/ (World capabilities), so small 2D/3D hosts never link or pay for them.

Scene Model

Stage is a retained store. The host creates nodes, cameras, meshes, and textures, mutates them through typed handles, and destroys them. The stage owns no schedule, ECS, or game loop.

  • Handles — Id<Kind> (NodeId, CameraId, TextureId, MeshId) packs a slot index and generation. Destroying an occupant bumps the generation so stale handles return None or false (to_bits / from_bits serialize a handle as one integer).
  • Nodes — Each node has an optional parent, a Transform (translation, rotation quaternion, scale), visible, a LayerMask of render layers, and optional drawables or lights. World space is right-handed and Y-up; a camera looks down its node's -Z, so larger Z is nearer.
  • Dirty tracking — Setters mark a node dirty; update refreshes each changed subtree from its topmost dirty ancestor, caching world matrices and inherited visibility. revision counts changes so hosts can skip redrawing static frames. Setting an identical value is a no-op; edit_sprite / edit_mesh bump revision only on change. Render layers are per node and not inherited.
  • Textures — The stage stores a texture's dimensions and Filter (Nearest or Linear) for UV math and batching; pixel data lives in StageRenderer.
  • Sprites — Texture, optional atlas rectangle in texels, world size, anchor, tint, flips, optional nine-slice (texel borders + world-units-per-texel scale), BlendMode (Alpha, Premultiplied, Additive, Add, Multiply, Screen), Material (Unlit or Lit), AlphaMode, optional normal texture, emissive colour, cast_shadow / receive_shadow, sorting layer, and z_offset.
  • Meshes — MeshData (positions, normals, UVs, optional tangents and vertex colours, 32-bit triangle indices; counter-clockwise outward, V down) is validated by MeshData::info (MeshInfo counts and bounds under MeshId); the renderer owns GPU buffers. MeshData::plane and cuboid build primitives. Nodes carry a MeshDrawable (mesh, MeshMaterial, draw, cast_shadow, receive_shadow, layer, z_offset). MeshDrawable::caster creates a shadow-only caster. MeshMaterial::late > 0 draws after opaque surfaces and regions before blended draws in ascending order; depth_test = false draws over existing depth without writing depth; MeshMaterial::ambient (default 1.0) scales classic ambient light. Stage::set_cloud_shadows shades directional lights by the coastal cloud deck (shaders/scene/coastal_sky.slang).
  • Lights — Ambient, Directional, Point (range), or Spot (range, inner/outer half-angles), with colour, intensity, cast_shadow, and shadow bias. Position is the node's; direction is its -Z.
  • Cameras — Sit on a node (scale ignored) with a Projection, Viewport (target fractions), Target (window drawable or texture), optional clear colour, ascending order, LayerMask, YSort, Resolution, and pixel_snap.

Projections & Virtual Resolution

Projection is #[non_exhaustive]. Aspect always comes from the camera's picture (viewport or virtual resolution), keeping clip Z in 0..1 and clip W:

  • Orthographic { height, near, far } — height camera-space units tall; near and far may be negative. For 2.5D top-down views, Projection::tilted_orthographic(ground_height, pitch, distance, depth) and Transform::orbit(target, yaw, pitch, distance) set up a pitched orthographic camera over the XZ ground plane.
  • Perspective { fov_y, near, far } — Vertical field of view in radians with positive near and far and perspective-correct UV interpolation.
  • Resolution — Native fills the viewport; Letterbox { size, integer } centres a virtual resolution (largest integer multiple when integer is true) with clear-coloured bars that ignore draws and picks; Scale { size, mode } fills via Stretch or Cover. screen_to_virtual and virtual_to_screen map coordinates to the virtual grid.
  • pixel_snap — Snaps each sprite's lower-left corner to whole picture pixels in parallel projections so pixel art never shimmers (sorting and picking still use true node positions).
  • Low-resolution upscaling — Render into a small nearest-filtered texture target and call Stage::create_upscale(source, layer, order, integer) to letterbox it onto the window at crisp integer scale.

Queries & Picking

  • camera_view returns CameraView (view, projection, view-projection and inverse, viewport, and content pixel rectangle).
  • screen_to_ray, screen_to_world(point, depth), screen_to_plane(point, plane_point, normal), and world_to_screen operate in target pixels (origin top-left).
  • pick and pick_all return sprite nodes hit by the pointer ray front-to-back, respecting camera layers and excluding letterbox bars.

Ordering, Culling, and Batching

A camera draws visible nodes intersecting its LayerMask whose geometry touches its clip volume (near-plane clipped for sprites; bounding-sphere culled for meshes).

  • Opaque & cutout drawables (AlphaMode::Opaque, Cutout(threshold)) write depth and draw first, grouped by bindings (mesh, textures, lit, sidedness) into instanced batches ordered nearest-first. Mirrored mesh instances (negative determinant) batch separately (SurfaceBatch::mirrored) with flipped face culling.
  • Blended drawables (AlphaMode::Blend) follow, sorted by sorting layer, depth key (camera-space Z + z_offset, or negated world Y on YSort layers), secondary key, and creation order, testing opaque depth without writing it. A camera allocates a Depth32Float transient only when it draws opaque geometry.
  • Sprite vs. surface path — Unlit blended sprites without emission take the fast sprite path (instances, batches). Meshes and lit/opaque/cutout/emissive sprites take the surface path (surface.instances, surface.batches). DrawList::steps interleaves both in exact draw order.

Draw List

Stage::build_draw_list(camera, window_size, &mut DrawList) populates reusable CPU buffers:

  • Camera target, size, viewport, content rectangle, scissor, and view-projection matrix.
  • instances: Vec<SpriteInstance> — 96-byte #[repr(C)] quads checked against shaders/stage_sprite.slang by build/device-shaders.ts.
  • batches: Vec<Batch> and surface batches, plus drawn/culled counts.

StageRenderer

StageRenderer holds no device; each call borrows &mut dyn Device. It compiles shaders/stage_sprite.slang and shaders/stage_surface.slang in the background, creating pipelines lazily per target format, blend mode, depth mode, and sidedness.

Textures & Mip Chains

  • create_texture(stage, w, h, rgba, filter), create_target, resize_target, write_texture, resize_texture, destroy_texture.
  • create_texture_with_mips accepts a host mip chain; create_texture_generating_mips builds 2×2 linear-light alpha-weighted mips on the CPU.
  • create_texture_from_source streams an RgbaMipSource across frames within the device's per-frame upload budget, resuming at the next unsubmitted row if backpressured.
  • PNG decoding is outside the crate (use engine_platform::load_png or a host decoder to pass RGBA8).

Meshes & Dynamic Updates

  • create_mesh(stage, &MeshData), create_dynamic_mesh, destroy_mesh. Vertices are 64-byte records pulled from storage buffers; indices are 32-bit.
  • update_mesh(stage, id, &MeshUpdate { ... }) updates geometry and bounds. Dynamic meshes accept partial attribute updates at the same vertex count; static meshes require all attributes. Oversized transfers stream across frames while cameras continue drawing the previous complete revision. DrawableReport::mesh_uploads and mesh_bytes track transfers.

Recording Frames & Pass Selection

record(device, stage, graph, window) appends one raster pass per enabled camera to the host's Graph, returning Ready, Pending (while pipelines compile or uploads defer), or Failed(message).

Passes and resources follow actual camera usage:

  • A 2D sprite camera records a single sprite pass with no depth buffer, light buffer, or shadow atlas — even if other layers contain lights or 3D geometry.
  • StageRenderer::report counts camera passes, depth buffers, light buffers, shadow passes, and shadow tiles.
  • read_target(graph, texture) schedules an async readback; capture runs full frames and returns RGBA8 pixels for tests and screenshots.

Multisampling (MSAA)

Camera::msaa selects Msaa::Off (default), Msaa::X2 (falls back to 4× if unsupported), or Msaa::X4. Multisampled cameras draw into memoryless transient colour/depth attachments resolved in the same pass. SDR cameras resolve directly into full-viewport clearing targets; any HDR camera can enable MSAA before its post chain. StageRenderer::msaa_report tracks multisampled cameras and attachments.

Render Scale

Camera::render_scale (default 1.0, clamped to 0.25..=1.0) renders the camera and its post chain at reduced resolution and upscales over the viewport via postUpscale in shaders/stage_post.slang, with optional contrast-limited sharpening (StageRenderer::set_upscale_sharpness).

  • Cameras that compose over another camera's output (such as a world over a sky) use Camera::backdrop so the HDR picture starts from the decoded backdrop texture and can still scale cleanly.
  • Hosts can drive render_scale dynamically from GPU frame time using engine_core::dynamic_resolution::DynamicResolution.