---
title: Render3D
description: Render static and skinned meshes with PBR materials, shared vertex
  deformation, shadows, sorted transparency, bloom and custom HDR effects.
source_url: https://tide-engine.dev/packages/render3d
source_file: docs/packages/render3d.md
source_revision: 36904d8e07dd044bd665de823e6b8022ed4f4248
source_worktree: modified
documentation_sha256: ea38a553efadfaf8a016c33e947825b8c4d3d2005abcf32eb4f4a64094909e97
documentation_scope: Website source checkout; not matched to an installed Tide
  release. Check tide version and the project toolchain.
---

<a id="render3d"></a>

# Render3D

`render3d` is an optional package for 3D meshes with opaque, cutout and transparent materials. Add mesh and material components to match entities, then spawn directional, point or spot lights. The package draws shadows, lights meshes into an HDR target and presents through one camera. Lights and ambient irradiance default to zero; with neither configured, only material emission contributes.

<a id="add-the-package"></a>

## Add the package

In a checkout or installation containing the package:

```sh
tide add render3d
```

Its line in `tide.packages` is `render3d`, and its namespace is `Render3D`. The package contains Tide rendering passes and a small C helper for transparent-object sorting. Games that omit the package compile and ship none of it. The engine's [drawing APIs](https://tide-engine.dev/game/3d.md) remain available without it.

<a id="meshes-and-materials"></a>

## Meshes and materials

Supply a cube mesh at `art/cube.obj`, then spawn a white cube, a directional light and a spotlight:

```csharp
asset Render3D.Mesh3D Cube = "art/cube.obj";

scene Main;

event(Spawned) Build(with Main)
{
    Spawn(Transform,
        Render3D.MeshRenderer { mesh = Cube },
        Render3D.Material { baseColor = Color.white });
    Spawn(Render3D.DirectionalLight { radiance = float3(2) });
    Spawn(Transform { localPosition = float3(0, 3, -2) },
        Render3D.SpotLight { direction = float3(0, -3, 2),
                             intensity = float3(25), castShadows = true });
}

[Before(Render3D.Stages.Prepare)]
view ConfigureRenderer(mut Render3D.Renderer renderer)
{
    renderer.camera.position = float3(0, 2, -5);
    renderer.camera.rotation = quaternion.LookRotation(float3(0, -2, 5), float3(0, 1, 0));
}
```

`Render3D.Mesh3D` is a transparent [type alias](https://tide-engine.dev/language/namespaces.md#type-aliases) for `Mesh<Render3D.MeshVertex>`. With `using Render3D;`, write `asset Mesh3D Cube = "art/cube.obj";`. See [Mesh assets](https://tide-engine.dev/game/assets.md#meshes) for supported imports. `MeshVertex` contains `float3 position`, `float3 normal`, `float4 tangent`, `float2 uv` and `Color color`, which defaults to white. Meshes follow the entity's stored `Transform` hierarchy. Because this static mesh layout declares `float4 tangent`, its import generates missing UV tangents and splits vertices at opposing generated handedness seams. Layouts without tangents or with `float3 tangent`, and skinned meshes, retain their prior imports; see the [tangent import rules](https://tide-engine.dev/game/assets.md#meshes).

These are **match entities**: create them with ordinary `Spawn`, not `local Spawn`. `Material` contains attached local resource fields, which currently prevent placing it on local-world entities. Its texture and shader stay on each machine, outside match snapshots and hashes; its ordinary material fields and the mesh asset handle are match data. See [Local fields](https://tide-engine.dev/game/local-state.md#local-fields).

Both `MeshRenderer` and `Material` must be present for an entity to draw or cast a shadow. Their fields are:

| Component field | Default | Meaning |
|---|---|---|
| `MeshRenderer.mesh` | No asset | `Asset<Render3D.Mesh3D>` to draw |
| `MeshRenderer.visible` | `true` | Draw the mesh and allow it to cast shadows |
| `MeshRenderer.castShadows` | `true` | Include the visible mesh in the shadow pass |
| `Material.baseColor` | `Color.white` | Display-space RGB tint |
| `Material.mode` | `Render3D.SurfaceMode.Opaque` | Opaque, alpha-tested `Cutout`, or alpha-blended `Transparent` |
| `Material.alphaCutoff` | `0.5` | Cutout threshold, from 0 to 1 |
| `Material.doubleSided` | `false` | Draw both sides, turning the shading frame toward the viewed side |
| `Material.metallic` | `0` | Metallic weight, from 0 to 1 |
| `Material.roughness` | `0.5` | Surface roughness; lighting clamps it to 0.05–1 |
| `Material.emission` | `float3(0)` | Linear HDR emission, which may exceed 1 |
| `Material.normalScale` | `1` | Tangent-space normal map's XY strength |
| `Material.occlusionStrength` | `1` | Blend between no occlusion and the mask's red channel |
| `Material.heightScale` | `0` | Height-map UV parallax strength; 0 disables it |
| `Material.uvScale` | `float2(1)` | Texture-coordinate scale |
| `Material.uvOffset` | `float2(0)` | Texture-coordinate offset |
| `Material.receiveShadows` | `true` | Apply available light shadows to this surface |
| `Material.baseMap` | `Render3D.White` | Attached local `Texture`, white by default |
| `Material.normalMap` | `default` (empty) | Attached local `[Raw] Texture` for tangent-space normals; empty uses the geometric normal |
| `Material.maskMap` | `default` (empty) | Attached local `[Raw] Texture` for ORM; empty leaves occlusion at 1 and the material scalars unchanged |
| `Material.emissionMap` | `default` (empty) | Attached local display-space emission texture; empty uses `emission` directly |
| `Material.heightMap` | `default` (empty) | Attached local `[Raw] Texture` for numeric height; empty disables parallax |
| `Material.uv` | `Render3D.StandardUV` | Attached local callback adjusting UVs before parallax |
| `Material.coverage` | `Render3D.StandardCoverage` | Attached local callback adjusting alpha and cutoff |
| `Material.shader` | `Render3D.Lit { surface = Render3D.StandardSurface }` | Attached local shader binding |
| `Material.vertex` | `null` | Optional attached local `Render3D.Deform` binding, shared by color and shadows |

The base map, base color and vertex color each supply display-space RGB. The shader decodes each to linear light before multiplying them into albedo. Their alpha channels multiply without color conversion. Assign maps, callbacks or `shader` through a mutable `Material` parameter in a view before preparation. Numeric material fields are match state: change them in match code or send a [command](https://tide-engine.dev/game/commands.md) from a local control. A captured surface callback can make local shading comparisons without changing match data.

<a id="a-complete-example"></a>

## A complete example

**Mesh materials, multiple lights and shadows** ([Run example](https://tide-engine.dev/examples/render3d/?stats))

```tide
settings { title = "Render3D: PBR, shadows and custom surfaces"; }
scene Main;

asset Render3D.Mesh3D sphere = "assets/render3d/sphere.obj";
asset Render3D.Mesh3D cube = "assets/render3d/cube.obj";

component Bands { local bool configured; }
component Sun { }
local singleton Controls
{
    bool lightsCreated;
    float exposure = 1;
    float sunlight = 5;
    bool shadows = true;
    float yaw = 0.64;
    float pitch = 0.38;
    float distance = 10.8;
    bool dragging;
    float pinch;
    int firstFinger;
    int secondFinger;
    bool open = true;
}

event(Spawned) BuildScene(with Main)
{
    Spawn(Render3D.MeshRenderer { mesh = cube },
          Render3D.Material { baseColor = Color(0.46, 0.49, 0.54), roughness = 0.9 },
          Transform { localPosition = float3(0, -0.15, 0), localScale = float3(10, 0.3, 7) });
    Spawn(Render3D.MeshRenderer { mesh = sphere },
          Render3D.Material { baseColor = Color(0.86, 0.2, 0.12), roughness = 0.25 },
          Transform { localPosition = float3(-2.1, 0.9, 0), localScale = float3(0.9) });
    Spawn(Render3D.MeshRenderer { mesh = sphere },
          Render3D.Material { baseColor = Color(1, 0.78, 0.33), metallic = 1, roughness = 0.22 },
          Transform { localPosition = float3(0, 0.9, 0), localScale = float3(0.9) });
    Spawn(Render3D.MeshRenderer { mesh = sphere }, Bands {},
          Render3D.Material { baseColor = Color(0.12, 0.72, 0.62), roughness = 0.5 },
          Transform { localPosition = float3(2.1, 0.9, 0), localScale = float3(0.9, 1.2, 0.9) });
    Spawn(Render3D.MeshRenderer { mesh = cube },
          Render3D.Material { baseColor = Color(0.23, 0.36, 0.65), roughness = 0.7 },
          Transform { localPosition = float3(0, 0.55, 2), localScale = float3(1.1),
                      localRotation = quaternion.Euler(float3(0, 30deg, 0)) });
}

// Local lights can be adjusted by this machine's UI.
[Before(Render3D.Stages.Prepare)]
view BuildLights(mut Controls controls)
{
    if (controls.lightsCreated) return;
    controls.lightsCreated = true;
    local Spawn(Sun {}, Render3D.DirectionalLight { direction = float3(-1, -2, 1), radiance = float3(5) });
    local Spawn(Render3D.DirectionalLight {
        direction = float3(1, -0.4, -1), radiance = float3(0.12, 0.18, 0.3), castShadows = false
    });
    local Spawn(Transform { localPosition = float3(2.1, 4, -1) }, Render3D.SpotLight {
        direction = float3(0, -1, 0.3), intensity = float3(10, 20, 30), range = 8,
        innerAngle = 25deg, outerAngle = 55deg, castShadows = true
    });
    local Spawn(Transform { localPosition = float3(-3, 2, -2) }, Render3D.PointLight {
        intensity = float3(6, 1.5, 0.5), range = 7
    });
}

// A material changes a numeric surface, while the package owns lighting/passes.
void Striped(Render3D.SurfaceInput input, mut Render3D.Surface surface)
{
    float band = Math.Sin(input.world.y * 10 + input.world.x * 2);
    surface.roughness = band > 0 ? 0.14 : 0.8;
    if (band < 0) surface.albedo *= 0.25;
}

[Before(Render3D.Stages.Prepare)]
view SetCustomSurface(mut Bands bands, mut Render3D.Material material)
{
    if (bands.configured) return;
    material.shader = Render3D.Lit { surface = Striped };
    bands.configured = true;
}

[Before(Render3D.Stages.Prepare)]
view ConfigureSun(mut local Render3D.DirectionalLight light, with local Sun, Controls controls)
{
    light.radiance = float3(controls.sunlight);
}

[Before(Render3D.Stages.Prepare)]
view CameraAndLight(mut Render3D.Renderer renderer, mut Controls controls, Devices devices)
{
    // GUI coordinates count down from the top; device coordinates count up.
    float panelTop = Screen.height - (controls.open ? 208 : 96);
    var pointer = devices.pointer;
    if (pointer.press.down) controls.dragging = Screen.Flip(pointer.position).y < panelTop;
    if (!pointer.press.pressed) controls.dragging = false;
    mut int fingers = 0;
    mut float2 firstPosition = float2(0);
    mut float2 secondPosition = float2(0);
    mut int firstId = 0;
    mut int secondId = 0;
    foreach (var touch in devices.touchscreen.touches)
    {
        if (!touch.press.pressed || Screen.Flip(touch.startPosition).y >= panelTop) continue;
        if (fingers == 0)
        {
            firstPosition = touch.position;
            firstId = touch.id;
        }
        if (fingers == 1)
        {
            secondPosition = touch.position;
            secondId = touch.id;
        }
        fingers += 1;
    }
    if (fingers >= 2)
    {
        float span = Math.Distance(firstPosition, secondPosition);
        if (controls.pinch > 0 && firstId == controls.firstFinger && secondId == controls.secondFinger)
            controls.distance *= controls.pinch / Math.Max(span, 1);
        controls.pinch = span;
        controls.firstFinger = firstId;
        controls.secondFinger = secondId;
        controls.dragging = false;
    }
    else
    {
        controls.pinch = 0;
        if (controls.dragging)
        {
            controls.yaw -= pointer.delta.x * 0.008;
            controls.pitch -= pointer.delta.y * 0.008;
        }
    }
    if (Screen.Flip(devices.mouse.position).y < panelTop)
        controls.distance *= Math.Pow(0.85, devices.mouse.scroll.y);
    controls.pitch = Math.Clamp(controls.pitch, 0.08, 1.35);
    controls.distance = Math.Clamp(controls.distance, 4, 18);
    float3 target = float3(0, controls.open ? -0.8 : 0.5, 0);
    float3 eye = target + float3(Math.Sin(controls.yaw) * Math.Cos(controls.pitch),
        Math.Sin(controls.pitch), -Math.Cos(controls.yaw) * Math.Cos(controls.pitch)) * controls.distance;
    renderer.camera = Render3D.Camera {
        position = eye,
        rotation = quaternion.LookRotation(target - eye, float3(0, 1, 0)),
        verticalFov = 45deg
    };
    renderer.exposure = controls.exposure;
    renderer.shadows = controls.shadows;
    // Cover the exhibits and their ground shadows at every zoom distance.
    renderer.shadowRange = controls.distance + 8;
    renderer.shadowDistance = 30;
}

[After(Render3D.Stages.Present)]
view Overlay(mut Controls controls)
{
    GUI.SetTheme(GUITheme { radius = 6 });
    // Leave the bottom-right stats line its own 40-pixel corner.
    GUILayout.Area(Rect(12, Screen.height - (controls.open ? 208 : 96), Screen.width - 24, controls.open ? 196 : 44))
    {
        GUILayout.Horizontal()
        {
            if (GUILayout.Button(controls.open ? "Hide controls" : "Controls")) controls.open = !controls.open;
            if (GUILayout.Button("Reset camera"))
            {
                controls.yaw = 0.64;
                controls.pitch = 0.38;
                controls.distance = 10.8;
            }
        }
        if (controls.open)
        {
            GUILayout.Label("Drag / swipe to orbit; pinch to zoom");
            GUILayout.Horizontal()
            {
                if (GUILayout.Button("Zoom +")) controls.distance = Math.Max(4, controls.distance - 1);
                if (GUILayout.Button("Zoom -")) controls.distance = Math.Min(18, controls.distance + 1);
            }
            GUILayout.Slider("Exposure", controls.exposure, 0.25, 3);
            GUILayout.Slider("Sunlight", controls.sunlight, 0, 12);
            GUILayout.Toggle("Shadows", controls.shadows);
        }
    }
}
```



Drag the scene to orbit, or tap the frame and use one finger to orbit. In these embedded examples, use the zoom buttons or a two-finger pinch; the wheel scrolls the documentation page. **Open separately** also enables wheel zoom. **Reset camera** restores the initial view; **Hide controls** reveals more of the scene. The example keeps slider drags out of the camera gesture.

<a id="material-maps-and-ambient-occlusion"></a>

## Material maps and ambient occlusion

| Map | Channels | How it combines with the material |
|---|---|---|
| `baseMap` | Display-space RGB, linear alpha | RGB multiplies decoded `baseColor` and vertex color; alpha multiplies their alpha |
| `normalMap` | Numeric RGB, centered at `(0.5, 0.5, 1)` | Tangent-space normal; XY is scaled by `normalScale` |
| `maskMap` | **R** occlusion, **G** roughness, **B** metallic | AO blends by `occlusionStrength`; G and B multiply the roughness and metallic scalars |
| `emissionMap` | Display-space RGB | Decoded to linear light, then multiplied by linear HDR `emission` |
| `heightMap` | Numeric R, centered at `0.5` | Offsets UVs according to camera direction and `heightScale` |

With positive `heightScale`, brighter height values are raised and darker values
are recessed; `0.5` is the undisplaced surface. A negative scale reverses the
relief. Height parallax changes texture coordinates, not geometry or depth.

Only `baseMap` defaults to `Render3D.White`; all four optional maps start empty. Unused optional maps are not sampled, including an empty emission map on an emissive material. `Render3D.FlatNormal` is available for explicit assignment when a flat normal texture is wanted.

Normal, ORM and height images contain numbers; color compression or sRGB decoding would change their meaning. Base and emission maps contain display-space color. A white mask leaves scalar values unchanged; `metallic = 0` or `emission = float3(0)` still gives no metallic or emission contribution even when a map is assigned.

`normalMap`, `maskMap` and `heightMap` are declared `[Raw] local Texture` fields. Bind `[Raw]` image assets so all channels reach the shader as numbers, including where alpha is zero. These fields also accept another Raw texture field, a `[Raw] Grid2<Color>` field/asset or `default`; ordinary color textures are rejected. `baseMap` and `emissionMap` remain ordinary color textures.

```csharp
asset Texture paint = "art/paint.png";
[Raw] asset Texture bumps = "art/normal.png";
[Raw] asset Texture packed = "art/orm.png";
[Raw] asset Texture heights = "art/height.png";

[Before(Render3D.Stages.Prepare)]
view BindMaps(mut Render3D.Material material)
{
    material.baseMap = paint;
    material.normalMap = bumps;
    material.maskMap = packed;
    material.heightMap = heights;
}
```

The field annotation controls numeric sampling, including through GPU texture helpers. It does not create a new texture type or let a Raw image pass through an ordinary `Texture` local, return value or draw argument. See [Textures that are numbers](https://tide-engine.dev/game/shaders.md#textures-that-are-numbers) for the complete binding rules.

Set `Renderer.ambientIrradiance` to a nonnegative **linear** RGB irradiance to see diffuse ambient light. Its default is zero. The contribution is `albedo * (1 - metallic) * ambientIrradiance * occlusion / Math.PI`. AO affects this diffuse indirect term; it does not darken direct lights or emission. There is no environment specular reflection or automatic occlusion bake. With zero ambient irradiance, an AO slider has no lighting contribution to change.

Height mapping is a single-sample UV parallax offset. It changes the sampled pattern as you orbit; it does not move vertices, change depth, create a new silhouette or displace shadow geometry. Use modest scales, especially near grazing angles. This is not tessellation, relief mapping or refraction.

**Normal, height, ORM, emission, cutout shadows and blending** ([Run example](https://tide-engine.dev/examples/render3d-materials/?stats))

```tide
settings { title = "Render3D: maps, cutout shadows and transparency"; }
scene Main;

asset Render3D.Mesh3D cube = "assets/render3d/cube.obj";
asset Render3D.Mesh3D sphere = "assets/render3d/sphere.obj";
asset Render3D.Mesh3D card = "assets/render3d/quad.obj";
asset Texture tiles = "assets/render3d/tiles-base.png";
asset Texture glow = "assets/render3d/tiles-emission.png";
asset Texture leaves = "assets/render3d/leaves.png";
[Raw] asset Texture normals = "assets/render3d/tiles-normal.png";
[Raw] asset Texture orm = "assets/render3d/tiles-orm.png";
[Raw] asset Texture heights = "assets/render3d/tiles-height.png";

component Mapped { }
component Foliage { }
component Glass { }
command SetHeight { float scale; }

command(SetHeight change, PlayerID sender) ApplyHeight(mut Render3D.Material material, with Mapped)
{
    material.heightScale = Math.Clamp(change.scale, 0, 0.08);
}

local singleton Controls
{
    bool lightsCreated;
    int exhibit;
    bool open = true;
    bool useOrm = true;
    float normal = 1;
    float ao = 1;
    float emission = 1;
    float roughness = 0.65;
    float metallic = 1;
    float height = 1;
    float sentHeight = 1;
    float cutoff = 0.5;
    float opacity = 0.45;
    float ambient = 0.8;
    bool shadows = true;
    float yaw = 0.35;
    float pitch = 0.30;
    float distance = 1; // Zoom multiplier over the distance fitting the active exhibit.
    bool dragging;
    float pinch;
    int firstFinger;
    int secondFinger;
}

event(Spawned) BuildScene(with Main)
{
    Spawn(Render3D.MeshRenderer { mesh = cube },
        Render3D.Material { baseColor = Color(0.34, 0.36, 0.39), roughness = 0.9 },
        Transform { localPosition = float3(0, -0.12, 0), localScale = float3(18, 0.24, 7) });
    // Three exhibits spaced apart: the buttons move the camera between them.
    Spawn(Mapped {}, Render3D.MeshRenderer { mesh = cube },
        Render3D.Material { roughness = 1, metallic = 1, emission = float3(5), heightScale = 0.08 },
        Transform { localPosition = float3(0, 1.05, 0), localScale = float3(1.8),
                    localRotation = quaternion.Euler(0, -20deg, 0) });
    Spawn(Foliage {}, Render3D.MeshRenderer { mesh = card },
        Render3D.Material { mode = Render3D.SurfaceMode.Cutout, doubleSided = true, roughness = 0.8 },
        Transform { localPosition = float3(-5, 1.4, 0), localScale = float3(2.4, 2.8, 1) });
    Spawn(Render3D.MeshRenderer { mesh = sphere },
        Render3D.Material { baseColor = Color(0.95, 0.7, 0.15), roughness = 0.28 },
        Transform { localPosition = float3(5, 0.8, 0.8), localScale = float3(0.8) });
    // Separate, nonintersecting cards make object sorting easy to inspect.
    Spawn(Glass {}, Render3D.MeshRenderer { mesh = card },
        Render3D.Material { mode = Render3D.SurfaceMode.Transparent, doubleSided = true,
                           baseColor = Color(0.12, 0.85, 0.75), roughness = 0.25 },
        Transform { localPosition = float3(4.65, 1.1, -0.55), localScale = float3(1.8, 2.2, 1) });
    Spawn(Glass {}, Render3D.MeshRenderer { mesh = card },
        Render3D.Material { mode = Render3D.SurfaceMode.Transparent, doubleSided = true,
                           baseColor = Color(0.95, 0.26, 0.4), roughness = 0.25 },
        Transform { localPosition = float3(5.35, 1.1, 0.15), localScale = float3(1.8, 2.2, 1) });
}

[Before(Render3D.Stages.Prepare)]
view Lights(mut Controls controls)
{
    if (controls.lightsCreated) return;
    controls.lightsCreated = true;
    local Spawn(Render3D.DirectionalLight {
        direction = float3(0.7, -1.3, 0.8), radiance = float3(4)
    });
    local Spawn(Render3D.DirectionalLight {
        direction = float3(-1, -0.3, -1), radiance = float3(0.3, 0.4, 0.6), castShadows = false
    });
}

// Captures are ordinary values. Texture resources stay on Material.
void AdjustMaps(Render3D.SurfaceInput input, mut Render3D.Surface surface,
    float normal, float ao, float emission, float roughness, float metallic, bool useOrm)
{
    surface.normal = Math.Normalize(Math.Lerp(input.normal, surface.normal, normal));
    surface.occlusion = useOrm ? Math.Lerp(1, surface.occlusion, ao) : 1;
    surface.emission *= emission;
    surface.roughness = useOrm ? surface.roughness * roughness : roughness;
    surface.metallic = useOrm ? surface.metallic * metallic : metallic;
}

void AdjustCutoff(Render3D.SurfaceInput input, mut Render3D.Coverage coverage, float cutoff)
{
    coverage.cutoff = cutoff;
}

void AdjustOpacity(Render3D.SurfaceInput input, mut Render3D.Coverage coverage, float opacity)
{
    coverage.alpha *= opacity;
}

[Before(Render3D.Stages.Prepare)]
view MapMaterial(mut Render3D.Material material, with Mapped, Controls controls)
{
    material.baseMap = tiles;
    material.normalMap = normals;
    material.maskMap = orm;
    material.emissionMap = glow;
    material.heightMap = heights;
    float normal = controls.normal;
    float ao = controls.ao;
    float emission = controls.emission;
    float roughness = controls.roughness;
    float metallic = controls.metallic;
    bool useOrm = controls.useOrm;
    material.shader = Render3D.Lit {
        surface = (Render3D.SurfaceInput input, mut Render3D.Surface surface) =>
            AdjustMaps(input, surface, normal, ao, emission, roughness, metallic, useOrm)
    };
}

[Before(Render3D.Stages.Prepare)]
view LeafMaterial(mut Render3D.Material material, with Foliage, Controls controls)
{
    material.baseMap = leaves;
    float cutoff = controls.cutoff;
    material.coverage = (Render3D.SurfaceInput input, mut Render3D.Coverage coverage) =>
        AdjustCutoff(input, coverage, cutoff);
}

[Before(Render3D.Stages.Prepare)]
view GlassMaterial(mut Render3D.Material material, with Glass, Controls controls)
{
    float opacity = controls.opacity;
    material.coverage = (Render3D.SurfaceInput input, mut Render3D.Coverage coverage) =>
        AdjustOpacity(input, coverage, opacity);
}

[Before(Render3D.Stages.Prepare)]
view Camera(mut Render3D.Renderer renderer, mut Controls controls, Devices devices)
{
    float panelHeight = controls.open ? (controls.exhibit == 0 ? 256 : 200) : 96;
    float panelTop = Screen.height - panelHeight;
    var pointer = devices.pointer;
    if (pointer.press.down) controls.dragging = Screen.Flip(pointer.position).y < panelTop;
    if (!pointer.press.pressed) controls.dragging = false;
    mut int fingers = 0;
    mut float2 firstPosition = float2(0);
    mut float2 secondPosition = float2(0);
    mut int firstId = 0;
    mut int secondId = 0;
    foreach (var touch in devices.touchscreen.touches)
    {
        if (!touch.press.pressed || Screen.Flip(touch.startPosition).y >= panelTop) continue;
        if (fingers == 0)
        {
            firstPosition = touch.position;
            firstId = touch.id;
        }
        if (fingers == 1)
        {
            secondPosition = touch.position;
            secondId = touch.id;
        }
        fingers += 1;
    }
    if (fingers >= 2)
    {
        float span = Math.Distance(firstPosition, secondPosition);
        if (controls.pinch > 0 && firstId == controls.firstFinger && secondId == controls.secondFinger)
            controls.distance *= controls.pinch / Math.Max(span, 1);
        controls.pinch = span;
        controls.firstFinger = firstId;
        controls.secondFinger = secondId;
        controls.dragging = false;
    }
    else
    {
        controls.pinch = 0;
        if (controls.dragging)
        {
            controls.yaw -= pointer.delta.x * 0.008;
            controls.pitch -= pointer.delta.y * 0.008;
        }
    }
    if (Screen.Flip(devices.mouse.position).y < panelTop)
        controls.distance *= Math.Pow(0.85, devices.mouse.scroll.y);
    controls.pitch = Math.Clamp(controls.pitch, 0.05, 1.3);
    controls.distance = Math.Clamp(controls.distance, 0.55, 2.5);
    float x = controls.exhibit == 1 ? -5 : (controls.exhibit == 2 ? 5 : 0);
    // Bounds cover the rotated unit cube (scaled 1.8), leaf card, or both glass
    // cards and their sphere. The floor is a receiver, not part of the exhibit.
    float3 center = float3(x, controls.exhibit == 1 ? 1.4 : (controls.exhibit == 2 ? 1.1 : 1.05),
        controls.exhibit == 2 ? 0.525 : 0);
    float3 half = controls.exhibit == 1 ? float3(1.2, 1.4, 0)
        : (controls.exhibit == 2 ? float3(1.25, 1.1, 1.075) : float3(1.16, 0.9, 1.16));
    float cosPitch = Math.Cos(controls.pitch);
    float sinPitch = Math.Sin(controls.pitch);
    float3 outward = float3(Math.Sin(controls.yaw) * cosPitch, sinPitch, -Math.Cos(controls.yaw) * cosPitch);
    float3 right = float3(Math.Cos(controls.yaw), 0, Math.Sin(controls.yaw));
    float3 up = Math.Cross(-outward, right);
    float height = Math.Max(Screen.height, 1);
    float tanHalf = Math.Tan(45deg * 0.5);
    // Center the exhibit in the space above the panel, with a 15% inset.
    float ndcY = Math.Clamp(panelHeight / height, 0, 0.9);
    float halfVisible = (1 - ndcY) * 0.85;
    float top = ndcY + halfVisible;
    float bottom = ndcY - halfVisible;
    float horizontal = Math.Max(Screen.width / height, 0.1) * tanHalf * 0.85;
    mut float centerDepth = 1;
    for (var i = 0; i < 8; i++)
    {
        float3 corner = half * float3((i & 1) == 0 ? -1 : 1,
            (i & 2) == 0 ? -1 : 1, (i & 4) == 0 ? -1 : 1);
        float y = Math.Dot(corner, up);
        float z = Math.Dot(corner, -outward);
        centerDepth = Math.Max(centerDepth, Math.Abs(Math.Dot(corner, right)) / horizontal - z);
        centerDepth = Math.Max(centerDepth, (y - top * tanHalf * z) / (halfVisible * tanHalf));
        centerDepth = Math.Max(centerDepth, (bottom * tanHalf * z - y) / (halfVisible * tanHalf));
        centerDepth = Math.Max(centerDepth, 0.2 - z);
    }
    // Zoom scales the fitted distance; it is never clamped back to that fit.
    float distance = centerDepth * (cosPitch + ndcY * tanHalf * sinPitch) / cosPitch * controls.distance;
    float dy = ndcY * distance * tanHalf / (cosPitch + ndcY * tanHalf * sinPitch);
    float3 target = center - float3(0, dy, 0);
    float3 eye = target + outward * distance;
    renderer.camera = Render3D.Camera {
        position = eye, rotation = quaternion.LookRotation(target - eye, float3(0, 1, 0)), verticalFov = 45deg
    };
    renderer.background = Color(0.086, 0.086, 0.094);
    renderer.ambientIrradiance = float3(controls.ambient);
    renderer.shadows = controls.shadows;
    // Spend shadow detail on the active exhibit, including its ground shadow.
    renderer.shadowRange = Math.Dot(center - eye, -outward) + Math.Length(half) + 4;
}

[After(Render3D.Stages.Present)]
view Overlay(mut Controls controls, with Mapped)
{
    GUI.SetTheme(GUITheme { radius = 6 });
    float panelHeight = controls.open ? (controls.exhibit == 0 ? 256 : 200) : 96;
    // A collapsed toolbar sits above the stats corner instead of covering it.
    GUILayout.Area(Rect(12, Screen.height - panelHeight, Screen.width - 24, controls.open ? panelHeight - 12 : 44))
    {
        GUILayout.Horizontal()
        {
            if (GUILayout.Button(controls.open ? "Hide" : "Controls")) controls.open = !controls.open;
            if (GUILayout.Button("Reset"))
            {
                controls.yaw = 0.35;
                controls.pitch = 0.30;
                controls.distance = 1;
            }
            if (GUILayout.Button("Zoom +")) controls.distance = Math.Max(0.55, controls.distance * 0.85);
            if (GUILayout.Button("Zoom -")) controls.distance = Math.Min(2.5, controls.distance / 0.85);
        }
        if (controls.open)
        {
            GUILayout.Horizontal()
            {
                if (GUILayout.Button("PBR maps")) controls.exhibit = 0;
                if (GUILayout.Button("Cutout")) controls.exhibit = 1;
                if (GUILayout.Button("Blend")) controls.exhibit = 2;
            }
            if (controls.exhibit == 0)
            {
                GUILayout.Horizontal()
                {
                    GUILayout.Slider("Normal", controls.normal, 0, 2);
                    GUILayout.Slider("Height", controls.height, 0, 1);
                }
                GUILayout.Horizontal()
                {
                    GUILayout.Slider("AO", controls.ao, 0, 1);
                    GUILayout.Slider("Emission", controls.emission, 0, 3);
                }
                GUILayout.Horizontal()
                {
                    GUILayout.Slider("Roughness", controls.roughness, 0.05, 1);
                    GUILayout.Slider("Metallic", controls.metallic, 0, 1);
                }
                GUILayout.Toggle("ORM texture", controls.useOrm);
            }
            if (controls.exhibit == 1)
            {
                GUILayout.Label("Alpha test also cuts the shadow");
                GUILayout.Slider("Cutoff", controls.cutoff, 0.05, 0.95);
                GUILayout.Toggle("Shadows", controls.shadows);
                GUILayout.Label("Orbit behind the double-sided leaves");
            }
            if (controls.exhibit == 2)
            {
                GUILayout.Label("Orbit around overlapping colored cards");
                GUILayout.Slider("Opacity", controls.opacity, 0, 1);
                GUILayout.Label("Opaque sphere draws before sorted cards");
                GUILayout.Label("No refraction or transparent shadows");
            }
            GUILayout.Label("Drag / swipe to orbit; pinch to zoom");
        }
    }
    // Height is match material data. Use the ordinary command path to edit it.
    if (controls.height != controls.sentHeight)
    {
        this.Send(SetHeight { scale = controls.height * 0.08 });
        controls.sentHeight = controls.height;
    }
}
```



Choose **PBR maps**, **Cutout** or **Blend** to move between the exhibits. In PBR maps, compare zero/positive normal and height strengths, turn ORM off, then vary roughness, metallic, AO and emission. AO is visible because this demo explicitly supplies ambient irradiance. The height slider changes the material through an ordinary targeted command. In Cutout, adjust the cutoff and watch the leaf shadow change with it. Orbit behind the leaves to see both sides. In Blend, adjust opacity and orbit around the overlapping cards and opaque sphere. The demo's original PNGs and quad are reproducible with `python docs/examples/assets/render3d/make_materials.py` in a checkout.

<a id="cutout-transparency-and-sidedness"></a>

## Cutout, transparency and sidedness

`SurfaceMode.Opaque` ignores alpha for visibility and writes depth. `Cutout` discards fragments whose multiplied alpha is below `alphaCutoff`; retained fragments draw opaquely and write depth. Its shadow pass uses the same UV, height, alpha and coverage rules, so holes also cut the shadow. Use cutout for leaves, fences and other surfaces with holes.

`Transparent` draws after opaque and cutout geometry, with source-alpha blending and depth testing, without writing depth. Transparent objects sort back to front for the camera; transparent materials do not cast shadows. This is object sorting, not per-triangle sorting: intersecting cards, nested surfaces and a mesh whose triangles overlap itself can blend incorrectly. Separate meshes can help when an object has distinct layers. Transparency supplies no refraction or physically modeled glass transmission.

`doubleSided = true` disables back-face culling and flips the shading frame for the viewed back side. It is useful for a thin leaf or card. A closed transparent mesh can expose both front and back surfaces; object sorting does not solve ordering inside that mesh.

<a id="skinned-meshes"></a>

## Skinned meshes

`Render3D.SkinnedMesh3D` aliases `SkinnedMesh<Render3D.MeshVertex>`. Use a
`SkinnedMeshRenderer` with the same `Material` component, lights and shadow
settings as a static mesh:

```csharp
asset Render3D.SkinnedMesh3D hero = "art/hero.glb";

event(Spawned) Character(with Main)
{
    Spawn(Transform, Render3D.SkinnedMeshRenderer { mesh = hero }, Render3D.Material);
}

[Before(Render3D.Stages.Prepare)]
view Animate(mut Render3D.SkinnedMeshRenderer mesh, Time time)
{
    mesh.pose = hero.animations.walk.Sample(time.t, Playback.Loop);
}
```

The `mesh` field is an `Asset<SkinnedMesh3D>` reference, preserving shared model
identity and imported LOD. The attached local `pose` defaults to `null`, which
draws authored rest. An explicitly invalid pose skips drawing. The package
snapshots the render pose during preparation and uses it for every shadow and
color pass. It does not choose clips, advance playback clocks or extract root
motion. Games can sample a local pose or forward a pose from their match state;
see [animation](https://tide-engine.dev/game/animation.md).

Skinned normal and height maps need authored UV tangents: the static tangent
generator does not generate skinned tangents. Skinning and custom deformation
also need explicit conservative bounds to enable culling. Transparent sorting
uses the mesh's existing bounds/LOD center, or its origin; it does not track the
animated silhouette. Static and skinned transparent objects sort together.

<a id="vertex-deformation"></a>

## Vertex deformation

Configure `Material.vertex` with an explicit stage binding:

```csharp
void Bend(Render3D.VertexInput input, mut Render3D.MeshVertex vertex)
{
    float amount = 0.25;
    float slope = 2 * amount * vertex.position.y;
    vertex.position.x += amount * vertex.position.y * vertex.position.y;
    vertex.normal = Math.Normalize(float3(vertex.normal.x,
        vertex.normal.y - slope * vertex.normal.x, vertex.normal.z));
    float3 tangent = vertex.tangent.xyz;
    vertex.tangent = float4(Math.Normalize(float3(
        tangent.x + slope * tangent.y, tangent.y, tangent.z)), vertex.tangent.w);
}

[Before(Render3D.Stages.Prepare)]
view ConfigureVertex(mut Render3D.Material material)
{
    material.vertex = Render3D.Deform { vertex = Bend };
}
```

The mutable vertex is mesh-local, after skinning and before the object's world
transform. `VertexInput.world` is its world position before the callback;
`localToWorld` is the effective draw transform, and `eye` is the main camera in
both color and shadow passes. The callback can change position, normal, tangent,
UV and color. Update normals/tangents when the deformation requires it; changing
position does not derive them automatically. Plain captures become shared draw
uniforms. Set `material.vertex = null` to restore the ordinary static path and
its automatic bounds. A present unconfigured stage retains the engine's normal
skip-draw behavior.

<a id="camera-and-renderer"></a>

## Camera and renderer

`Render3D.Renderer` is a local singleton on each machine. Configure it in a `[Before(Render3D.Stages.Prepare)]` view, as in the cube example above.

`Render3D.Camera` looks along its rotation's `+z`, with `+y` up. Its fields are:

| Field | Default | Units |
|---|---|---|
| `position` | `float3(0, 2, -5)` | World position |
| `rotation` | `quaternion.identity` | Camera rotation |
| `verticalFov` | `60deg` | **Radians**, as with `float4x4.PerspectiveFov`; a `deg` literal converts to radians |
| `near` | `0.1` | Distance to the near plane |
| `far` | `1000` | Distance to the far plane |

| Renderer setting | Default | Meaning |
|---|---|---|
| `enabled` | `true` | Run the package's renderer |
| `camera` | Defaults above | This machine's camera |
| `background` | `Color(0.06, 0.08, 0.12)` | Display-space background, decoded before rendering |
| `exposure` | `1` | Linear multiplier before tone mapping; 2 doubles the light |
| `defaultPresent` | `true` | Run the stock exposure, tone-map and sRGB presentation pass |
| `bloom` | Disabled | Built-in scene-linear bloom settings |
| `postEffects` | Empty list | Ordered custom HDR callbacks after bloom |
| `ambientIrradiance` | `float3(0)` | Linear diffuse ambient irradiance, multiplied by material AO |
| `maxLights` | `32` | Maximum retained lights; negative values act as 0 |
| `shadows` | `true` | Enable shadow casting and sampling |
| `maxShadowMaps` | `8` | Shadow-view budget, clamped to 0–16 |
| `shadowResolution` | `2048` | Requested atlas cell size in pixels, including gutters |
| `shadowCascades` | `4` | Camera-fitted directional cascade count, clamped to 0–4; 0 selects a fixed volume |
| `shadowRange` | `40` | Farthest camera-forward distance receiving cascaded shadows, limited by `camera.far` |
| `shadowCenter` | `float3(0)` | World-space center of fixed directional volumes; used when `shadowCascades = 0` |
| `shadowExtent` | `10` | Half-width and half-height of fixed directional volumes, in world units |
| `shadowDistance` | `40` | Cascade caster reach toward the light, or fixed-volume total depth, in world units |
| `shadowNear` | `0.05` | Point/spot shadow near plane, in world units; at least 0.001 |
| `shadowBias` | `0.0005` | Constant normalized depth offset, scaled for each cascade's texel size and depth span |
| `shadowSlopeBias` | `0.002` | Additional offset as the surface turns away from the light, scaled the same way |

The package retains its window-sized `Format.Rgba16f` scene target and depth atlas in `Renderer`, resizing as needed. The depth resource ID survives atlas resizing. Setting `enabled = false` before preparation disposes them; re-enabling recreates them. `Render3D.Dispose(renderer)` also releases them explicitly; an enabled renderer recreates them on its next preparation. An enabled renderer still presents its background when there is no match.

Leave the resource and derived fields to the package. Call `Render3D.Dispose` before `Render3D.Stages.Prepare`. Recorded draws run after the views finish, so disposing after `Present` still invalidates that frame's rendering and presentation.

<a id="light-components"></a>

## Light components

`DirectionalLight`, `PointLight` and `SpotLight` can belong to match entities (`Spawn`) or machine-local entities (`local Spawn`). All three default to `enabled = true` and `priority = 0`. Directional lights default to `castShadows = true`; point and spot lights default to `false`.

| Component field | Default | Meaning |
|---|---|---|
| `DirectionalLight.direction` | `float3(1, -2, 1)` | Local direction photons travel |
| `DirectionalLight.radiance` | `float3(4)` | Linear RGB light, independent of distance |
| `PointLight.intensity`, `SpotLight.intensity` | `float3(10)` | Linear RGB light at one world unit, before range/cone attenuation |
| `PointLight.range`, `SpotLight.range` | `10` | Finite range in world units; nonpositive values disable the light |
| `SpotLight.direction` | `float3(0, 0, 1)` | Local cone axis, pointing away from the light |
| `SpotLight.innerAngle` | `25deg` | Full cone opening at full strength |
| `SpotLight.outerAngle` | `40deg` | Full outer cone opening |

Positions and directions come from `World.LocalToWorld`: the stored transform hierarchy, without presentation interpolation. The matrix transforms local directions, including its scale, then the package normalizes them. Without a transform on the entity or its ancestors, the matrix is identity. Light ranges remain in world units.

Radiance and intensity clamp negative channels to zero. Point and spot lights use inverse-square falloff with a 0.01-world-unit distance floor and a smooth window that reaches zero at `range`. Their intensity describes the unwindowed light at one world unit. Spot angles are **radians**; `deg` literals convert to radians. `outerAngle` clamps to 1–179 degrees and `innerAngle` to 0–`outerAngle`. Light fades smoothly between the cones; equal angles give a hard edge.

Each frame, the renderer keeps up to `maxLights` lights in descending `priority`. Equal priorities retain collection order: directionals, then spots, then points, with match entities before local entities within each kind. `Renderer.droppedLights` counts otherwise eligible lights excluded by this limit. There is no `Renderer.sun` field; configure a directional light through its component.

<a id="shadows"></a>

## Shadows

Shadow depth reads and comparison references remain forward (0 near, 1 far), including shadow bias. The renderer converts these at its depth-storage boundary; reversed float storage needs no change to the package's shadow formulas.


Directional lights follow the camera by default. `shadowCascades = 4` divides the visible depth range into four overlapping slices, with finer shadow detail near the camera. `shadowRange = 40` is the farthest camera-forward distance receiving these shadows, limited by `camera.far`. Set it to the distance your game needs: a smaller range gives the same texture resolution to a smaller part of the scene.

Each cascade fits a stable sphere around its frustum slice and snaps its light-space placement to the shadow texel grid. Splits combine evenly spaced and logarithmic distances. Shadows blend over the last 10% of each slice; the last cascade fades to fully lit at `shadowRange`. `shadowDistance` extends the casting volume toward the light, allowing off-camera geometry within that reach to shadow visible surfaces. This is a caster reach, separate from the camera's shadow range.

Set `shadowCascades = 0` when you need a single fixed directional volume. Its orthographic box uses `shadowCenter`, `shadowExtent` and `shadowDistance` as its center, half-width/half-height and total depth. Move `shadowCenter` yourself in this mode. Values 1–4 select that many camera-fitted cascades; `shadowCenter` and `shadowExtent` are unused. Spot shadow volumes follow their cone; point shadows cover six faces. Surfaces outside a shadow view are unshadowed by that view.

Shadow allocation follows the retained light order. A directional light needs one atlas cell per cascade, or one cell in fixed mode; a spot needs one and a point needs six. Each light's cells are contiguous and allocated together or not at all. A shadow request that cannot fit in `maxShadowMaps` still illuminates without shadows; later requests can use the remaining cells. For example, a four-cascade directional light and a shadowed point light require a budget of at least ten views. Point/spot lights whose range does not exceed the effective shadow near plane also illuminate without shadows. `Renderer.unshadowedLights` counts retained lights requesting shadows that receive none, including when shadows are globally disabled.

Shadow edges use a normalized 3×3 tent filter reconstructed with four bilinear depth comparisons. The sampling weights follow the fractional texel position, without random jitter. The biases are normalized comparison-depth offsets, not world distances. Cascades scale them for their world-space texel size and depth span; fixed, point and spot views apply the values directly. Too little bias can produce self-shadowing, while too much separates shadows from their casters.

Vulkan devices whose depth format does not support linear comparison filtering retain the backend's nearest-comparison fallback, with reduced edge quality.

The atlas uses the smallest square grid that fits the allocated views. Each cell has a two-pixel gutter on every edge, so its usable interior is `cellSize - 4` pixels per side. The atlas limit is 4096 pixels per side or the device's smaller limit; `shadowResolution` clamps to 16 through `floor(atlasLimit / gridSize)`. `Renderer.activeShadowResolution` reports the actual cell size, including gutters; `Renderer.atlasSize` reports the atlas side length. Gutters, filtering and cascade snapping use the actual dimensions, including on smaller devices.

One default directional light uses four 2048-pixel cells in a 4096-square atlas on devices supporting that size. Eight views use a 3×3 grid: the default request yields 1365-pixel cells in a 4095-pixel atlas. On a device limited to 2048, those cases use 1024- and 682-pixel cells respectively. Set a lower `shadowResolution` to reduce shadow memory and rasterization work; halving the atlas side uses one quarter as many depth texels.

With no allocated shadow views, including `shadows = false`, the renderer retains the atlas size (initially 16×16), clears it to far depth and reports `activeShadowResolution = 0`. The depth resource remains valid for the shader's bound sampler. Disabling shadows skips shadow drawing and sampling; lights and emission still render.

<a id="frame-order-and-drawing-ui"></a>

## Frame order and drawing UI

The package owns these named view stages, in order:

| Stage | Work |
|---|---|
| `Render3D.Stages.Prepare` | Prepare retained targets and reset per-frame light data |
| `Render3D.Stages.Lights` | Collect and select lights, allocate shadow views and clear the atlas |
| `Render3D.Stages.Shadows` | Draw all visible shadow casters |
| `Render3D.Stages.Color` | Set the scene camera and clear the HDR target |
| `Render3D.Stages.Opaque` | Draw opaque meshes with their materials |
| `Render3D.Stages.Transparent` | Draw sorted transparent meshes after opaque/cutout geometry |
| `Render3D.Stages.PostPrepare` | Reset `Renderer.output` to the current linear HDR scene |
| `Render3D.Stages.Bloom` | Apply enabled built-in bloom |
| `Render3D.Stages.PostProcess` | Apply the ordered custom HDR effect chain |
| `Render3D.Stages.Present` | Apply exposure, tone map and present to the window |

Every caster finishes before color drawing starts. Configure camera, lighting, textures and shader bindings with `[Before(Render3D.Stages.Prepare)]`. Draw ordinary window UI with `[After(Render3D.Stages.Present)]`:

```csharp
[After(Render3D.Stages.Present)]
view Hud()
{
    Draw.Text("Render3D", float2(0, 160), 20, Color.white);
}
```

Ordinary compatible mesh draws can batch when their shader, mesh, texture, uniforms and draw state match. Different material values can split batches; the package does not put every material into one draw.

<a id="custom-surfaces"></a>

## Custom surfaces

`Render3D.Lit` takes a `Func<Render3D.SurfaceInput, mut Render3D.Surface, void>` callback. The shader initializes the surface from the material, then calls it before evaluating lighting. The default `Render3D.StandardSurface` leaves it unchanged.

```csharp
void StripedSurface(Render3D.SurfaceInput input, mut Render3D.Surface surface)
{
    float stripe = Math.Step(0.5, Math.Frac(input.uv.x * 8));
    surface.albedo *= Math.Lerp(0.35, 1, stripe);
}

[Before(Render3D.Stages.Prepare)]
view ConfigureMaterials(mut Render3D.Material material)
{
    material.shader = Render3D.Lit { surface = StripedSurface };
}
```

| Callback data | Meaning |
|---|---|
| `SurfaceInput.world` | World-space position |
| `SurfaceInput.normal` | World-space geometric normal |
| `SurfaceInput.tangent`, `SurfaceInput.bitangent` | World-space tangent frame, including transform/UV handedness |
| `SurfaceInput.uv` | Scaled/offset UVs for the UV hook; final UVs, including parallax, for coverage and surface |
| `SurfaceInput.viewDirection` | Normalized direction from the surface toward the camera |
| `Surface.albedo` | Linear RGB reflectance |
| `Surface.normal` | World-space shading normal |
| `Surface.roughness`, `Surface.metallic` | Roughness and metallic weight |
| `Surface.emission` | Linear HDR emission |
| `Surface.occlusion` | Ambient diffuse occlusion, default 1 |

`Material.uv` is an attached local `Func<Render3D.SurfaceInput, mut float2, void>` and runs after scale/offset, before height parallax. `Material.coverage` is an attached local `Func<Render3D.SurfaceInput, mut Render3D.Coverage, void>` and runs after alpha sampling; `Coverage` contains `alpha = 1` and `cutoff = 0.5`. The package initializes those from the material and multiplied alpha before invoking the hook. The same hooks run for cutout shadows. A surface callback runs after the maps initialize `Surface`; it cannot change fragment coverage.

Use `Render3D.SrgbToLinear` when supplying display-space colors inside a callback. Owned captures of plain values, including numeric structs, work with the existing [callable rules](https://tide-engine.dev/language/functions.md#function-values); resources and heap values cannot be captured. The original `Lit { surface = CustomSurface }` form remains valid. Surface and coverage callbacks change appearance; use the separate [vertex binding](https://tide-engine.dev/packages/render3d.md#vertex-deformation) to deform geometry.

<a id="bloom-and-post-processing"></a>

## Bloom and post-processing

Bloom runs after transparent rendering and before custom effects, exposure and
tone mapping. Its threshold is measured in scene-linear HDR light, so changing
exposure does not change which light is extracted. It uses quarter-resolution
targets, a soft knee and separable blur, then adds the glow to the HDR scene.

| `BloomSettings` field | Default | Range |
|---|---|---|
| `enabled` | `false` | Enable bloom |
| `threshold` | `1` | 0–65504 |
| `softness` | `1` | Soft-knee half-width, 0–65504 |
| `intensity` | `0.25` | 0–16; zero bypasses bloom |
| `radius` | `1` | Blur spacing in quarter-resolution pixels, 0–8 |
| `iterations` | `2` | Horizontal/vertical blur pairs, 1–4 |

`PostEffect` aliases `Func<Texture, RenderTarget, bool>`. Each callback receives
the current linear HDR source and a distinct package-owned destination. Fully
overwrite the destination and return `true` to publish it. Return `false` to
bypass the effect. Default callbacks bypass safely. The list order is the pass
order, and captured numeric settings are copied when the callback is created.
Keep outputs linear and do not tone-map or encode sRGB inside the chain.

```csharp
struct TintSettings { float3 multiplier; }

frag Tint(Vertex vertex, out Color color, Texture source, TintSettings settings)
{
    Color sample = source.Sample(vertex.uv);
    color = Color(float3(sample.r, sample.g, sample.b) * settings.multiplier, 1);
}

bool ApplyTint(Texture source, RenderTarget destination, float3 multiplier)
{
    Draw.Blit(source, destination, Tint, TintSettings { multiplier = multiplier });
    return true;
}

[Before(Render3D.Stages.Prepare)]
view ConfigureEffects(mut Render3D.Renderer renderer)
{
    renderer.bloom.enabled = true;
    float3 multiplier = float3(1, 0.9, 0.8);
    renderer.postEffects = [
        (Texture source, RenderTarget destination) => ApplyTint(source, destination, multiplier)
    ];
}
```

For a pass that also samples game-owned singleton textures, use a staged view
with explicit shader bindings. Between `PostPrepare` and `Present`, read
`renderer.output`, obtain `Render3D.NextPostTarget(renderer)`, draw your pass,
then call `Render3D.CommitPost(renderer)`. Repeated `NextPostTarget` calls before
a commit return the same destination. Set `defaultPresent = false` for a custom
final presentation; scene rendering and the HDR effect chain still run.

Scratch targets are allocated only when used and retained across frames.
The original scene target remains available as `renderer.hdr`. Dispose the
renderer before recording, as described above; recorded effects also depend on
their retained sources and destinations.

**Skinning, shared deformation, bloom and an HDR tint pass** ([Run example](https://tide-engine.dev/examples/render3d-effects/?stats))

```tide
settings { title = "Render3D: skinning, deformation and bloom"; }
scene Main;
asset Render3D.SkinnedMesh3D ribbon = "assets/render3d/ribbon.gltf";
asset Render3D.Mesh3D sphere = "assets/render3d/sphere.obj";
asset Render3D.Mesh3D cube = "assets/render3d/cube.obj";
component Ribbon { }
component Warped { }
local singleton Controls
{
    bool lightsCreated;
    bool open = true;
    bool play = true;
    bool animate = true;
    bool deform = true;
    bool bloom = true;
    bool tint;
    float seconds;
    float bend = 0.3;
    float glow = 0.6;
    float exposure = 1;
    float yaw = 0.35;
    float pitch = 0.3;
    float distance = 1;
    bool dragging;
    float pinch;
    int firstFinger;
    int secondFinger;
}

event(Spawned) Build(with Main)
{
    Spawn(Ribbon, Warped, Render3D.SkinnedMeshRenderer { mesh = ribbon },
        Render3D.Material { baseColor = Color(0.1, 0.65, 0.9), roughness = 0.4,
                            emission = float3(0.1, 1.5, 3), doubleSided = true },
        Transform { localPosition = float3(-0.4, 1.3, 0) });
    Spawn(Warped, Render3D.MeshRenderer { mesh = sphere },
        Render3D.Material { baseColor = Color(1, 0.2, 0.08), emission = float3(6, 0.4, 0.1), roughness = 0.3 },
        Transform { localPosition = float3(1.8, 1, 0), localScale = float3(0.7) });
    Spawn(Render3D.MeshRenderer { mesh = cube }, Render3D.Material { roughness = 1 },
        Transform { localPosition = float3(0, -0.15, 0), localScale = float3(14, 0.3, 7) });
}

// This example owns its animation clock. Render3D only consumes the pose.
[Before(Render3D.Stages.Prepare)]
view Configure(mut Render3D.Renderer renderer, mut Controls controls)
{
    if (controls.play) controls.seconds += Frame.dt;
    if (!controls.lightsCreated)
    {
        controls.lightsCreated = true;
        local Spawn(Render3D.DirectionalLight { direction = float3(0.7, -1.5, 0.9), radiance = float3(3) });
    }
    renderer.bloom.enabled = controls.bloom;
    renderer.bloom.intensity = controls.glow;
    renderer.exposure = controls.exposure;
    renderer.postEffects.Clear();
    if (controls.tint)
    {
        float3 multiplier = float3(1.2, 0.85, 0.65);
        renderer.postEffects.Add((Texture source, RenderTarget destination) => ApplyTint(source, destination, multiplier));
    }
}

[Before(Render3D.Stages.Prepare), After(Configure)]
view AnimateRibbon(mut Render3D.SkinnedMeshRenderer mesh, with Ribbon, Controls controls)
{
    mesh.pose = null;
    if (controls.animate)
        mesh.pose = ribbon.animations.slide.Sample((Math.Sin(controls.seconds) + 1) * 0.5);
}

void Bend(Render3D.VertexInput input, mut Render3D.MeshVertex vertex, float amount)
{
    float slope = 2 * amount * vertex.position.y;
    vertex.position.x += amount * vertex.position.y * vertex.position.y;
    vertex.normal = Math.Normalize(float3(vertex.normal.x, vertex.normal.y - slope * vertex.normal.x, vertex.normal.z));
    float3 tangent = vertex.tangent.xyz;
    vertex.tangent = float4(Math.Normalize(float3(tangent.x + slope * tangent.y, tangent.y, tangent.z)), vertex.tangent.w);
}

[Before(Render3D.Stages.Prepare), After(Configure)]
view ConfigureDeform(mut Render3D.Material material, with Warped, Controls controls)
{
    material.vertex = null;
    if (controls.deform)
    {
        float amount = controls.bend;
        material.vertex = Render3D.Deform {
            vertex = (Render3D.VertexInput input, mut Render3D.MeshVertex vertex) => Bend(input, vertex, amount)
        };
    }
}

struct TintSettings { float3 multiplier; }
frag Tint(Vertex vertex, out Color color, Texture source, TintSettings settings)
{
    Color sample = source.Sample(vertex.uv);
    color = Color(float3(sample.r, sample.g, sample.b) * settings.multiplier, 1);
}

bool ApplyTint(Texture source, RenderTarget destination, float3 multiplier)
{
    Draw.Blit(source, destination, Tint, TintSettings { multiplier = multiplier });
    return true;
}

[Before(Render3D.Stages.Prepare)]
view Camera(mut Render3D.Renderer renderer, mut Controls controls, Devices devices)
{
    float panelHeight = controls.open ? 272 : 96;
    float panelTop = Screen.height - panelHeight;
    var pointer = devices.pointer;
    if (pointer.press.down) controls.dragging = Screen.Flip(pointer.position).y < panelTop;
    if (!pointer.press.pressed) controls.dragging = false;
    mut int fingers = 0;
    mut float2 firstPosition = float2(0);
    mut float2 secondPosition = float2(0);
    mut int firstId = 0;
    mut int secondId = 0;
    foreach (var touch in devices.touchscreen.touches)
    {
        if (!touch.press.pressed || Screen.Flip(touch.startPosition).y >= panelTop) continue;
        if (fingers == 0)
        {
            firstPosition = touch.position;
            firstId = touch.id;
        }
        if (fingers == 1)
        {
            secondPosition = touch.position;
            secondId = touch.id;
        }
        fingers += 1;
    }
    if (fingers >= 2)
    {
        float span = Math.Distance(firstPosition, secondPosition);
        if (controls.pinch > 0 && firstId == controls.firstFinger && secondId == controls.secondFinger)
            controls.distance *= controls.pinch / Math.Max(span, 1);
        controls.pinch = span;
        controls.firstFinger = firstId;
        controls.secondFinger = secondId;
        controls.dragging = false;
    }
    else
    {
        controls.pinch = 0;
        if (controls.dragging)
        {
            controls.yaw -= pointer.delta.x * 0.008;
            controls.pitch -= pointer.delta.y * 0.008;
        }
    }
    if (Screen.Flip(devices.mouse.position).y < panelTop)
        controls.distance *= Math.Pow(0.85, devices.mouse.scroll.y);
    controls.pitch = Math.Clamp(controls.pitch, 0.05, 1.3);
    controls.distance = Math.Clamp(controls.distance, 0.55, 2.5);
    // Includes the ribbon at all animation/deformation settings and the sphere.
    float3 center = float3(-0.2, 1.3, 0);
    float3 half = float3(3.1, 1.4, 1.1);
    float cosPitch = Math.Cos(controls.pitch);
    float sinPitch = Math.Sin(controls.pitch);
    float3 outward = float3(Math.Sin(controls.yaw) * cosPitch, sinPitch, -Math.Cos(controls.yaw) * cosPitch);
    float3 right = float3(Math.Cos(controls.yaw), 0, Math.Sin(controls.yaw));
    float3 up = Math.Cross(-outward, right);
    float height = Math.Max(Screen.height, 1);
    float tanHalf = Math.Tan(45deg * 0.5);
    // Center the exhibit in the space above the panel, with a 15% inset.
    float ndcY = Math.Clamp(panelHeight / height, 0, 0.9);
    float halfVisible = (1 - ndcY) * 0.85;
    float top = ndcY + halfVisible;
    float bottom = ndcY - halfVisible;
    float horizontal = Math.Max(Screen.width / height, 0.1) * tanHalf * 0.85;
    mut float centerDepth = 1;
    for (var i = 0; i < 8; i++)
    {
        float3 corner = half * float3((i & 1) == 0 ? -1 : 1,
            (i & 2) == 0 ? -1 : 1, (i & 4) == 0 ? -1 : 1);
        float y = Math.Dot(corner, up);
        float z = Math.Dot(corner, -outward);
        centerDepth = Math.Max(centerDepth, Math.Abs(Math.Dot(corner, right)) / horizontal - z);
        centerDepth = Math.Max(centerDepth, (y - top * tanHalf * z) / (halfVisible * tanHalf));
        centerDepth = Math.Max(centerDepth, (bottom * tanHalf * z - y) / (halfVisible * tanHalf));
        centerDepth = Math.Max(centerDepth, 0.2 - z);
    }
    // Zoom scales the fitted distance; it is never clamped back to that fit.
    float distance = centerDepth * (cosPitch + ndcY * tanHalf * sinPitch) / cosPitch * controls.distance;
    float dy = ndcY * distance * tanHalf / (cosPitch + ndcY * tanHalf * sinPitch);
    float3 target = center - float3(0, dy, 0);
    float3 eye = target + outward * distance;
    renderer.camera = Render3D.Camera {
        position = eye, rotation = quaternion.LookRotation(target - eye, float3(0, 1, 0)), verticalFov = 45deg
    };
    renderer.background = Color(0.086, 0.086, 0.094);
    renderer.ambientIrradiance = float3(0.3);
    renderer.shadows = true;
    // Include the deformed exhibit and its ground shadow at every zoom distance.
    renderer.shadowRange = Math.Dot(center - eye, -outward) + Math.Length(half) + 4;
}

[After(Render3D.Stages.Present)]
view Overlay(mut Controls controls)
{
    GUI.SetTheme(GUITheme { radius = 6 });
    float panelHeight = controls.open ? 272 : 96;
    GUILayout.Area(Rect(12, Screen.height - panelHeight, Screen.width - 24, controls.open ? panelHeight - 52 : 44))
    {
        GUILayout.Horizontal()
        {
            if (GUILayout.Button(controls.open ? "Hide" : "Controls")) controls.open = !controls.open;
            if (GUILayout.Button("Reset")) { controls.yaw = 0.35; controls.pitch = 0.3; controls.distance = 1; }
            if (GUILayout.Button("Zoom +")) controls.distance = Math.Max(0.55, controls.distance * 0.85);
            if (GUILayout.Button("Zoom -")) controls.distance = Math.Min(2.5, controls.distance / 0.85);
        }
        if (controls.open)
        {
            GUILayout.Horizontal() { GUILayout.Toggle("Play", controls.play); GUILayout.Toggle("Pose", controls.animate); }
            GUILayout.Horizontal() { GUILayout.Toggle("Deform", controls.deform); GUILayout.Toggle("Bloom", controls.bloom); }
            GUILayout.Slider("Bend", controls.bend, -0.6, 0.6);
            GUILayout.Slider("Glow", controls.glow, 0, 2);
            GUILayout.Horizontal() { GUILayout.Toggle("Warm tint", controls.tint); GUILayout.Slider("Exposure", controls.exposure, 0.25, 2); }
            GUILayout.Label("Drag / swipe to orbit; pinch to zoom");
        }
    }
}
```



Toggle **Pose** to compare animation with authored rest, then vary **Bend** and
watch the geometry and its shadow move together. **Bloom** and **Glow** control
the built-in effect; **Warm tint** inserts a custom HDR pass. Pause the example
with **Play** to compare settings on the same pose. Drag/swipe to orbit and use
the zoom buttons or pinch; standalone launches also support wheel zoom. Stats
are enabled, with the collapsed toolbar clear of the stats corner.

<a id="lighting-and-current-limits"></a>

## Lighting and current limits

Lighting uses a metallic-roughness BRDF with GGX specular, Smith visibility, Schlick Fresnel and Lambert diffuse. Direct contributions from all retained lights are summed with optional diffuse ambient irradiance; nonnegative emission is added once, including with zero lights. Presentation multiplies linear HDR RGB by `exposure`, applies Reinhard tone mapping (`x / (1 + x)`) and encodes sRGB once. Keep callback emission and lighting values linear; do not encode them before presentation.

Base-map sampling currently filters display-space texels **before** decoding them to linear light. This can produce different edges and mip colors from linear-light filtering; automatic hardware sRGB sampling is not part of this slice. On devices unable to render into float targets, the engine's existing [RGBA8 fallback](https://tide-engine.dev/game/render-targets.md#what-a-target-holds) clips HDR values before tone mapping.

The current path draws static and skinned mesh assets. It has no `LightMode`, baked or area lights, environment specular, GI, probes or light baker. Model texture and metallic/roughness import is not automatic: declare and bind the maps explicitly. Height is UV parallax and transparency is sorted alpha blending, subject to the limits above.


<a id="foliage"></a>

## Foliage

The forest quality path uses authored branch/leaf wind response, mapped leaf
normals/transmittance, complete coverage-preserving texture mips and a distant
source-mesh impostor prototype. See the [forest benchmark](https://github.com/Tide-Engine/tide-engine/tree/dev/bench/forest)
for reproducible assets and moving-camera controls.

`WindResponse { bend, flutter, branchPhase, leafPhase }` is the explicit authored
overload of `ApplyWind`. Phases are cycles; no color/UV convention is imposed.
Keep weights/phases locally constant for the analytic normal correction and
keep connected branch responses compatible. The original scalar overload is
unchanged. A surface callback can read `input.mask` after mapping: raw AO,
roughness, metallic and artist alpha, default `(1,1,0,1)`. The forest uses alpha
as additional optical transmittance for thin leaves.

Configure `renderer.fog` before preparation:

```csharp
renderer.fog = Render3D.FogSettings {
    enabled = true, density = 0.00065, start = 0,
    color = Render3D.SrgbToLinear(float3(0.69, 0.76, 0.82))
};
```

Fog color is linear HDR. The same distance fog affects all `Lit` surfaces after
lighting/emission and before exposure/tonemapping, including terrain. It starts
disabled; nonpositive density bypasses it. Custom shaders apply it explicitly.

Static `MeshRenderer.meshOverride`, `hidden` and `hideShadows` are attached local
controls, configured before `Prepare`, leaving the match's mesh identity and
visibility untouched. Overrides are shared by color and shadow passes; `hidden`
suppresses both and `hideShadows` only suppresses shadows.

`Material.colorOverride` and `fade` are also local. Set `ditherFade = true` for
ordered geometry coverage: outgoing `fade = 1-t` and incoming `fade = -t` use
complementary pixel cells while retaining the leaf texture's cutout threshold.
The package prepares the effective `renderColor` once before lighting, using
the existing instance color budget. Configure these before `Prepare`. This
ordered crossfade does not provide temporal antialiasing.

`Material.impostor` optionally selects the baked hemisphere atlas path, using
`baseMap` for albedo/coverage, raw `normalMap` for model normals/depth and raw
`maskMap` for ORM/artist alpha. When enabled, the package dispatches its internal
`ImpostorDeform` vertex stage and `ImpostorLit` fragment stage. Set the settings'
`wind` and `bend` for shared whole-card sway; their default wind strength is
zero. This path reserves existing corner fields for its projection payload, so
use the offline baker's layout/settings and conservative full card bounds.
The prototype stores one nearest rest-pose layer, with blended views and
optional depth-plane parallax. Disoccluded geometry and independent leaf/branch
animation are not reconstructed. Depth testing, lighting position and fog
still use the proxy card's geometry.
Impostors do not cast shadows. Only the three baked maps are interpreted;
ordinary UV, height-map and emission-map controls do not apply. Constant
emission and the configured surface callback remain available.

Use `Cutout` and `doubleSided = true` for leaf cards. `ThinLeaf` returns a
surface callback with shared numeric settings:

```csharp
material.shader = Render3D.Lit {
    surface = Render3D.ThinLeaf(Render3D.LeafSettings {
        transmission = 0.4,
        transmissionColor = float3(0.75, 1, 0.4),
        thickness = 0.2
    })
};
```

Transmission defaults to 0.5, with white linear RGB tint and zero thickness.
Strength/tint clamp to 0..1; nonnegative optical thickness attenuates by
`exp(-thickness)`. Transmitted diffuse light reduces the reflected diffuse
fraction; specular stays unchanged. Each light's attenuation and shadow visibility
apply on both sides. Leaf shadows still use opaque/cutout depth: this thin-sheet
approximation does not model colored shadows or transport through multiple leaves.
Ordinary surfaces default to zero transmission. Custom callbacks can call
`ApplyThinLeaf(surface, settings)` to compose it with their own surface edits.

Capture the same `Wind` values for all plants in a frame through the shared
vertex hook. Inside a view before `Stages.Prepare`, with a game-owned local
`seconds` clock:

```csharp
var wind = Render3D.Wind { time = seconds, strength = 0.3 };
material.vertex = Render3D.Deform {
    vertex = (Render3D.VertexInput input, mut Render3D.MeshVertex vertex) =>
        Render3D.ApplyWind(input, vertex, wind, 0.01, 0.01)
};
material.customBounds = true;
material.boundsCenter = float3(0, 5, 0);
material.boundsSize = float3(10, 12, 10);
```

Advance the clock with `Frame.dt` and wrap it periodically. The example bounds
assume an upright ten-unit tree; fit them to the actual asset and maximum wind
movement. Bounds are the **full mesh-local size after deformation**, before its
transform. Attached local `customBounds` defaults false; `boundsCenter` and
`boundsSize` default zero. They enable culling in color and every shadow pass,
including skinned materials, restoring destination state afterward. Negative or
nonfinite sizes retain the draw. Undersized bounds can hide visible branches.

`Wind.direction` is normalized world XZ, default `(1, 0.3)`. `strength` defaults
to 0.3, `speed` to 1, `gustScale` to 0.04 cycles/world unit, `gustSpeed` to 0.8
cycles/second, `gustStrength` to 0.5 and `time` to zero seconds. Nearby roots
sample coherent travelling gusts. `ApplyWind` takes independent bend and flutter
responses, anchors local y <= 0, and corrects normals/tangents. Bend has world
distance per squared local height; flutter has world distance per local height.
Strength clamps to 0..10, responses/gustStrength to 0..1, speed/gustSpeed to
0..30, gustScale to 0..1 and height to 0..10000. The helper preserves vertex
color and UVs and infers no asset weight channels. A custom callback using color
as wind weights must restore its intended material tint/alpha explicitly.

The repository's [forest stress scene](https://github.com/Tide-Engine/tide-engine/blob/dev/bench/forest/README.md) exercises the ordinary
mesh/material path with ground/canopy/wide presets, travel/orbit controls and
three mesh levels selected every frame through local mesh references. Ordered
crossfades connect these levels and a 24-view atlas baked from the actual
source tree meshes. Authored DDS chains preserve leaf/impostor alpha coverage
at the material cutoff, with Raw normal/depth and mask maps. Native and web
backends preserve those mip chains; Unity's current draw recorder retains only
the base image. The atlas remains a rest-pose proxy; Gaussian splats are not
implemented. The README records controls, reproduction and measurement limits.
