Lighting, Shadows & Post-Processing

Classic Lighting

Material::Lit surfaces under LightingModel::Classic (default) evaluate Lambert diffuse and Blinn-Phong specular in encoded colour space:

text
colour * (ambient + sum(light * falloff * shadow * max(N·L, 0)))
  + sum(light * falloff * shadow * specular * max(N·H, 0)^shininess)
  + emissive
  • Falloff — Point and spot lights use (1 - (d / range)^2)^2, reaching zero at range. Spot lights multiply by a smoothstep between outer and inner half-angle cosines. Directional and ambient lights have no falloff.
  • Limits — Up to MAX_LIGHTS (16) primary directional, point, and spot lights per camera (ambient lights sum separately). Directional lights take priority, then brightest/largest-range lights (LightSet::dropped counts overflow).
  • Clustered local lights — Up to MAX_CLUSTERED_LIGHTS (1024) additional non-shadow-casting local lights bin into a 16 × 9 × 16 screen-tile/depth grid (LightSet::clustered), so dense torch-lit scenes evaluate only the lights reaching each pixel.
  • Normal maps — Lit sprites and tangent-bearing meshes sample tangent-space normal maps (+Y up / along bitangent; sprite flips mirror normals).

Physically Based Lighting (PBR)

Setting Camera::lighting = LightingModel::Pbr shades lit surfaces with Burley diffuse and GGX specular in photometric units (shaders/stage_pbr.slang), matching Bevy's StandardMaterial conventions:

  • Material parameters — MeshMaterial provides perceptual roughness (default 0.5), metallic (0.0), and reflectance (0.5). Sprites and tilemaps shade as fully rough dielectrics (reflectance = 0.5).
  • BRDF — F0 = mix(0.16 * reflectance^2, base, metallic), alpha = clamp(roughness, 0.089, 1)^2, Burley diffuse, GGX D with correlated Smith visibility, Schlick Fresnel, and multiscatter compensation via polynomial F_ab.
  • Light units — Point and spot intensities are in lumens (÷ 4π to candela), directional in lux, with window^2 / max(d^2, 0.0001) falloff and optional spherical area radius (Light::radius, Karis representative point).
  • Exposure & linear light — Camera::exposure_ev100 (default 9.7) scales direct, ambient, and emissive radiance by 2^-ev100 / 1.2. Use Dynamic::Hdr on PBR cameras so lighting and blending run in linear RGBA16F before final sRGB encoding.

Shadows

Lights with cast_shadow render reverse-Z depth tiles into a transient shadow atlas (up to MAX_SHADOW_TILES = 16 tiles per camera, default 512×512 texels) when at least one visible lit surface receives shadows and a caster lies within reach:

  • Directional — One orthographic tile fitted to the camera frustum's bounding sphere (capped by range if positive), snapped in whole texels to eliminate shimmer.
  • Spot — One perspective tile covering the cone.
  • Point — Six cube-face tiles; the fragment shader selects the dominant offset axis.

Filtered Shadows

Light::with_filtered_shadows(depth_bias, normal_bias) (e.g. 0.08, 0.6) and with_shadow_size(texels) (up to 2048) enable world-space normal/depth biasing and Gaussian PCF filtering: Castano's 9-tap hardware comparison filter (4×4 footprint) for directional and spot lights, and an 8-tap orthonormal-basis filter for point lights.

HDR Post-Processing

An Sdr camera draws straight into its target with zero float textures or post passes (StageRenderer::post_report reports zeros). Setting Camera::dynamic = Dynamic::Hdr renders into a linear RGBA16F texture (decoding sRGB textures/tints to linear before lighting and blending) and runs an ordered PostChain:

  1. Exposure(multiplier)
  2. Bloom
  3. Tonemap — Clamp, Reinhard, Aces (Narkowicz fit, default), or Filmic (the engine's highlight-rolling filmic curve)
  4. Grade — Lift, gamma, gain, and saturation in linear space
  5. Custom steps anywhere in the chain

Adjacent built-ins fuse into one composite pass. A trailing custom step followed only by exposure/tonemap/grade also fuses into the final composite (postFragmentFused), eliminating an intermediate float texture and pass.

Bloom

  • Bloom::default() — Fast tight blur: half-size first level, 2×2 box downsamples, 4-tap additive upsamples.
  • Bloom::natural() — Resolution-independent physically motivated bloom (Jimenez 2014): Height(512) first level, 13-tap Karis-weighted downsample, 3×3 tent upsample, curved level weights, and energy-conserving blend (intensity = 0.15).

Temporal Anti-Aliasing & Upscaling

  • Camera::temporal (Temporal { feedback }) — Applies an 8-sample Halton (2, 3) sub-pixel projection jitter and resolves against depth-reprojected YCoCg-clamped history (postTemporal) using alternating per-camera float histories.
  • Temporal upscaling — Combining temporal with render_scale < 1.0 resolves and upscales in one pass (postTemporalUpscale), accumulating sub-pixel detail across frames.

Native MetalFX & Ray-Traced Shadows (macOS)

  • MetalFX (metalfx feature) — StageRenderer::set_metalfx(true) routes temporal upscaling through Apple's MetalFX temporal scaler via a graph native node when supported by the GPU (falling back to the stage's own resolve otherwise).
  • Ray-traced shadows (ray-tracing feature) — StageRenderer::set_ray_traced_shadows(Some(strength)) traces sun occlusion for static meshes on HDR perspective cameras via engine_render::ray_tracing, respecting alpha-tested and alpha-blended casters.

Custom Materials & Post Steps

Custom Surface Materials (shaders/stage_material.slang)

Implement struct CustomMaterial : IStageMaterial with MaterialOutput evaluate(MaterialInput):

  • MaterialInput provides world, normal, tangent, uv, colour, view, time, frontFacing, emissive, plus helpers param(i), sampleColour(slot, uv), sampleData(slot, uv), scene, worldNormal, and defaultOutput.
  • MaterialOutput returns colour, alpha, emissive, world-space normal, specular, and shininess.
  • Register with StageRenderer::register_material (up to 4 textures, 8 float4 param rows) or register_wide_material (up to 8 textures, 128 param rows). Set MaterialDesc::lit to join the stage's lighting and shadow loop (shaders/stage_light.slang).
  • Create instances with Stage::create_material_instance, configure via set_material_params / set_material_texture, and attach to Sprite::custom or MeshMaterial::custom.

Custom Post Steps (shaders/stage_post_custom.slang)

Implement struct CustomPost : IStagePost with float4 evaluate(PostInput) (uv, pixel, size, colour, time, param(i), sampleSource(uv), sampleExtra(slot, uv), and sampleDepth(pixel) when PostDesc::depth is enabled). Register with register_post (up to 128 param rows and 4 extra textures) and add PostEffect::Custom(...) to a camera's PostChain.

Building Host Shaders

Compile host .slang materials and post steps into Rust modules and Metal/WGSL shader payloads with build/stage-materials.ts:

sh
bun build/stage-materials.ts \
  --out build/stage-shaders \
  --material shaders/water.slang \
  --post shaders/fade.slang \
  [--ios] [--web]

Include the generated .rs file in the host crate (include!(concat!(env!("STAGE_SHADERS"), "/water.rs"))) and pass the generated shader descriptor to MaterialDesc or PostDesc. Passing --ios embeds cfg-selected metal/, metal-iphonesimulator/, and metal-iphoneos/ libraries automatically.