Log inGet started

Ray tracing

Updated December 5, 2026

Two backends, one surface

Ray tracing always works — only the backend differs:

  • hardware — the device granted hardware ray query (native Vulkan/DX12/Metal). Rays traverse a GPU BLAS/TLAS.
  • compute — no hardware ray query (e.g. the web/WebGPU path). The engine gathers the scene into a triangle buffer, builds a bounding-volume hierarchy over it, and your zeroTrace* calls walk that hierarchy in software.

You write the SAME shader either way — the zeroTraceAny / zeroTraceClosest WGSL surface is identical, so a ray-tracing pass is backend-agnostic. Check the backend if you want to scale ray budgets:

local backend = renderer.raytraceCapability()   -- "hardware" | "compute"
renderer.setRaytrace(true)                       -- build the scene structure each frame

setRaytrace(true) is required — it gates the per-frame acceleration-structure build, so it costs nothing until a ray-tracing effect is active.

The trace surface: an acceleration_structure binding

Ray tracing rides the .computeShader abstraction (guides { path: "types/computeShader" }). Declare one acceleration_structure binding in bindings.yaml and the engine wires it to the scene structure and generates the trace helpers — you never write @group/@binding, enable wgpu_ray_query, or any backend-specific code:

bindings:
  - { name: out_tex,    kind: storage2d, format: rgba16f }
  - { name: scene_tlas, kind: acceleration_structure }

That makes the trace surface available in shader.wgsl, identical on both backends:

// Closest hit. `instance` is the hit object's render slot, `bary` the
// barycentrics, `primitive` the triangle's index within the structure that was
// traversed, and `attr` its row in the shared attribute table.
struct ZeroHit { hit: bool, t: f32, instance: u32, primitive: u32, bary: vec2<f32>, attr: u32 };
fn zeroTraceClosest(origin: vec3<f32>, dir: vec3<f32>, t_min: f32, t_max: f32) -> ZeroHit;

// Terminate-on-first-hit over every traced surface — for occlusion rays.
fn zeroTraceAny(origin: vec3<f32>, dir: vec3<f32>, t_min: f32, t_max: f32) -> bool;

// Terminate-on-first-hit over the surfaces that block light — for shadow rays
// toward a light. A surface whose `Model` states `castsShadows = false` (a
// lamp's glass, a bulb around its light) lets the light through, as it does in
// the raster shadow maps, and `zeroTraceClosest` still meets it.
fn zeroTraceShadow(origin: vec3<f32>, dir: vec3<f32>, t_min: f32, t_max: f32) -> bool;

primitive numbers the triangle within the backend's own structure, and each backend numbers its own way — the software backend orders the scene triangles by the hierarchy it built over them, which it rebuilds whenever the scene changes. To name a surface across frames or across backends, shade from zeroHitSurface(hit) / zeroMaterial(...) or from instance, both of which are stable.

zeroHitInstances[slot] is the record behind a slot: material (the index zeroMaterial takes) and bounds, the world-space sphere that holds the instance's mesh (centre in xyz, radius in w, 0 where the mesh states no box). A pass that walks the slots can find the scene's instances of a kind (the ones whose material emits, say) and aim rays at them through their spheres.

Both helpers pass through the cut-away texels of an alpha-tested surface — a material whose cutoff drops fragments, such as a leaf card — by the rule its own raster keeps them by: a texel stays where base_color.a * base_color_texture.a (at the hit's UV, after the material's uv_scale / uv_offset) reaches the material's alpha_cutoff. The engine reads each such texture's alpha into a coverage layer once, outside the trace, so a pass pays the test only on the triangles of a cutout surface; opaque geometry traces as it would without one.

zeroMaterial(index).base_color is the colour the surface draws with on average: the material's base_color times the mean colour of its base_color_texture, in linear light (for an alpha-tested material, the mean of the texels it keeps). The engine measures each base-colour texture on the GPU when its texels change (an upload, a hot reload, a streamed level), so a dark wood texture under a white base_color bounces the light a dark surface does. A texture's mean lands a few frames after it is first worn; until then the hit reads the property alone. The alpha is the property's.

A ray-tracing pass is a kind = "compute" render-feature pass; the engine binds the scene structure to your declared slot:

ctx.enqueue {
    kind = "compute", program = "my_rt_shader",
    storage = { out_tex = rt.guid },
    dispatch = { x = gx, y = gy, z = 1 },
    phase = "afterLighting",
}

The screen-space recipe (shadows, AO, reflections)

Most effects shade what the camera already sees: reconstruct each pixel's world position from the depth buffer, trace from there, and darken/tint the scene colour. The pieces:

  • @scene.depth via a texture_depth binding — the depth buffer (textureLoad returns the [0,1] clip depth). The range is reversed: 1.0 is the near plane, 0.0 is the far plane and what empty sky clears to, and a nearer surface reads GREATER. So d > 0.0 is the test for "a surface was drawn here", and zero_linear_depth_through(d, view_proj, camera_position), given camera.viewData()'s viewProj and position, is the one conversion to metres, for a perspective or an orthographic camera at any near and far plane alike.
  • @scene.color / @scene.normal via texture2d bindings — the lit scene colour and (deferred path) the G-buffer normal.
  • @scene.material via a texture2d binding declared sample: uint — the deferred path's base colour + metallic + roughness, Rgba8Uint-packed and unpacked through @builtin::shaderModules.gbuffer_material. A trace tinting its result by what the surface reflects reads this rather than @scene.color, which already carries how brightly the surface was lit. renderFeature.assetType's README carries the full @scene.* table — every channel, its format, and the phase it is valid from.
  • @frame.camera via a read-only buffer binding — the reserved per-render- target camera buffer: 18×vec4<f32> = inverse view-projection (columns [0..4), column-major) + camera world position ([4].xyz) + the previous render's view-projection (columns [5..9)), which projects a point into the picture that render left — what @scene.colorHistory and a G-buffer channel read under readsPrevious hold — + the view-projection itself (columns [9..13)), which projects a world point onto the view being drawn, + the sub-pixel offset it carries ([13].xy) + the view-projection with no sub-pixel offset (columns [14..18)). Bind it through inputs (inputs = { cam = "@frame.camera" }) and reconstruct world position as inv_vp * vec4(ndc, 1) (with ndc.y = 1 - 2*uv.y for the wgpu top-left convention). The matrix inverts the reversed range, so ndc.z takes a depth sample directly, ndc.z = 1 is the near plane and ndc.z = 0 the far one. The engine resolves it against the camera CURRENTLY being drawn, so the effect is correct in the live viewport AND in offscreen captures / RTT from a different camera. (renderer.mainCameraView() returns the same {16 inverse VP, 3 position} for the main camera if a script needs it on the Luau side; inside a pass, prefer @frame.camera so offscreen renders reconstruct against their own camera.)
let depth = textureLoad(scene_depth, coord, 0);
let ndc = vec3<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth);
let inv_vp = mat4x4<f32>(cam[0], cam[1], cam[2], cam[3]);  // cam = @frame.camera
let wh = inv_vp * vec4<f32>(ndc, 1.0);
let world_pos = wh.xyz / wh.w;
let occluded = zeroTraceShadow(world_pos + n * 0.05, to_light, 0.0, 1000.0);  // hard shadow

Soft shadows / AO cast a small cone or hemisphere of jittered rays and average the result. The fragment passes that follow are single-input, so a screen-space effect typically does its compositing IN the compute pass (read @scene.color, write the shaded result to an RT) and then a plain blit copies the RT to the screen.

Samples

Two built-in passes are the reference implementations:

  • rt_shadows (@builtin::renderFeatures.rt_shadows) — hard + soft ray-traced shadows: reconstruct world position, cast shadow rays toward the sun via zeroTraceShadow, darken by the occluded fraction.
  • traced ambient occlusion (@builtin::systems.ambientOcclusion.ao_trace): a cosine-weighted hemisphere of short rays per texel, the estimate the ambient occlusion effect takes with traced = true. Its settings live in @builtin::systems.ambientOcclusion.ao; see the cost section below.

Read them with bash { command: "cat /zero/source/libs/@builtin/renderFeatures/rt_shadows.renderFeature/init.luau" } and adapt. Create one with renderer.feature.create("rt_shadows").

What tracing a screen-space effect costs

A screen-space RT effect casts a number of rays per pixel it shades, and that product — rays × pixels — is what the pass costs. It is linear in both, and it does not move with the scene's entity count: a ray walks the depth of the structure rather than its contents, so halving the geometry in the scene leaves the pass where it was.

That is why the resolution the effect shades at is worth as much as its ray count, and why both belong under one knob. Traced ambient occlusion is the worked example:

local ao = require("@builtin::systems.ambientOcclusion.ao")

renderer.setRaytrace(true)
ao.set({ intensity = 0.9, traced = true, quality = "medium" })   -- low | medium | high | ultra
ao.qualityLevels()                 -- the rays and grid resolution of each
ao.stats()                         -- the estimator, grid and rays the running pass ran
qualityrays per pixelgrid resolutionrays per 1920×1080 frame
low3half1.6 M
medium6half3.1 M
high6full12.4 M
ultra12full24.9 M

Measured on a discrete GPU with hardware ray query, at 1920×1080, in an optimized build of a scene of ~170 renderables and four point lights: the trace pass costs about 2 ms per million rays. medium spends 5-6 ms of GPU on it and high 26 ms; the frame that scene draws in 16 ms without occlusion draws in 17-20 ms at medium and 38 ms at high.

Halving the grid is worth four rays, and at this scale the occlusion is the same: occlusion is low-frequency almost everywhere, and a depth-aware upsample carries the coarse grid back to the frame without crossing a silhouette. Budget the same way for an effect of your own — count the rays a frame casts before writing the shader, because that number is the answer.

The cost the trace does not carry is the filter behind it. A few rays per pixel leave visible noise, and a denoiser (an asset implementing the denoiser interface, @builtin::systems.denoising.svgf the built-in one) is what makes that ray count usable: it carries each pixel's estimate across frames and smooths across matching pixels, 1 + iterations dispatches at the size of the signal it is handed, so filtering the traced grid before the upsample costs a quarter of filtering the frame.

Testing the software backend on a hardware machine

Launch with --force-rt-compute (or ZERO_FORCE_RT_COMPUTE=1) to select the software backend even where hardware ray query exists — so the same effect can be verified on the path web users get. renderer.raytraceCapability() then reports "compute".

What keeping the structure current costs

A ray walks a structure built over the scene's geometry, and keeping that structure describing the scene is work a frame pays before it traces anything. renderer.raytraceStats() is what that work reads as:

local s = renderer.raytraceStats()
print(s.backend, s.triangles, s.staticTriangles, s.dynamicTriangles)
print(s.fullRebuilds, s.partialRebuilds, s.reusedFrames, s.trianglesRebuilt)

On the software backend the structure has two partitions: the STATIC one — the front of the triangle buffer, with its own subtree — and the DYNAMIC one after it. The first build files everything it meets under the static partition, so turning ray tracing on builds the scene once. A renderable that moves leaves the static partition on that frame without a rebuild of the scene (its triangles there are overwritten with ones no ray meets) and joins the dynamic one, as does geometry that arrives after the first build. A frame in which renderables changed re-emits and re-sorts the dynamic partition alone and leaves every static triangle where the device already holds it, so a scene where a few things move stops paying for all of it.

The whole structure is rebuilt, filing settled geometry under the static partition again, once re-emitting the settled geometry the dynamic partition holds, each renderable since it last moved, has cost as much as one rebuild of the scene, or once more than half of the static partition is triangles left behind by renderables that moved out. A renderable is settled on every frame it does not change, and geometry the structure meets for the first time is settled already, so it is the work spent re-emitting geometry while it stands still, not a count of frames, that moves it across. Geometry that stands for a frame or two between moves, as anything updated on a tick of its own does, is re-emitted for those frames and stays on the dynamic side.

The counters are cumulative over the session: sample, run the scene, sample again. trianglesRebuilt divided by triangles is how many whole-structure rebuilds those frames amounted to — a scene of 7,310 triangles with one moving cube reads 12 triangles per moving frame rather than 7,310.

The triangle buffer and the hierarchy over it are each bound whole as one storage binding, so the structure holds at most triangleLimit triangles on the device it runs on (renderer.deviceLimits() names the binding). A scene past that is traced in its own order up to the limit: whole renderables after it are left out, renderablesLeftOut and trianglesLeftOut count them, and the engine log names the shortfall once it changes. A ray passes through where a renderable left out stands, and the rest of the frame draws.

On the hardware backend the same call reports what the driver holds: blas (one per unique static mesh, plus one per skinned instance), blasBuilt for the last frame's submission, and tlasInstances.

Notes

  • The software (compute) backend traverses a bounding-volume hierarchy the engine builds over the gathered scene triangles, so a ray costs the depth of the tree rather than the triangle count. The build is CPU-side, and what a frame rebuilds of it is what moved — see the section above.
  • Both backends fill the whole of ZeroHit and resolve zeroHitSurface / zeroMaterial through the same tables, so an effect reads the same on either.
  • The cutout test reads one engine-owned texture, zeroHitCoverage, bound beside the hit tables: a sampled texture of the stage's sixteen, and no storage buffer.
  • Eight storage buffers per shader stage is what a device guarantees, and declaring an acceleration_structure spends some of them on engine-owned tables: three on the hardware backend (what zeroHitSurface / zeroMaterial read), five on the software backend (those, plus the scene triangles and the hierarchy). A ray-tracing .computeShader therefore has three buffer bindings of its own — pack several inputs into one buffer rather than declaring a slot each. The compile counts a shader's buffers as the software backend binds them on every device, so a shader past the budget there is refused when it is compiled, on a GPU with hardware ray queries too, with the buffers it declared named in the reason.
  • The scene structure includes off-screen geometry (rays aren't limited to the camera frustum), so shadows and reflections from objects outside the view are correct.
  • documentation
  • guide