scena 1.3.0

A Rust-native scene-graph renderer with typed scene state, glTF assets, and explicit prepare/render lifecycles.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
use crate::assets::Assets;
use crate::diagnostics::PrepareError;
use crate::geometry::{Aabb, GeometryDesc, GeometryTopology, GeometryVertex};
use crate::scene::{NodeKey, Scene, Transform, Vec3};

use super::DeformationInputs;
use super::lighting::PreparedLights;
use super::transforms::{compose_transform, transform_position, transform_primitive};

#[derive(Clone, Copy)]
pub(super) struct ShadowOccluder {
    a: Vec3,
    b: Vec3,
    c: Vec3,
}

pub(super) fn collect_shadow_occluders<F>(
    scene: &Scene,
    assets: Option<&Assets<F>>,
    origin_shift: Vec3,
) -> Result<Vec<ShadowOccluder>, PrepareError> {
    let mut occluders = Vec::new();

    for (renderable, transform) in scene.renderables() {
        for primitive in renderable.primitives() {
            let primitive = transform_primitive(primitive, transform, origin_shift);
            let [a, b, c] = primitive.vertices();
            occluders.push(ShadowOccluder {
                a: a.position,
                b: b.position,
                c: c.position,
            });
        }
    }

    let Some(assets) = assets else {
        return Ok(occluders);
    };

    for (node, mesh, transform) in scene.mesh_nodes() {
        let geometry = assets
            .geometry(mesh.geometry())
            .ok_or(PrepareError::GeometryNotFound {
                node,
                geometry: mesh.geometry(),
            })?;
        let vertices = shadow_vertices(
            node,
            &geometry,
            DeformationInputs {
                morph_weights: scene.morph_weights(node),
                skin_matrices: scene.skin_matrices(node).as_deref(),
            },
        )?;
        append_shadow_geometry(
            &mut occluders,
            &geometry,
            &vertices,
            transform,
            origin_shift,
        );
    }

    for (node, instance_set, node_transform) in scene.instance_set_nodes() {
        let geometry =
            assets
                .geometry(instance_set.geometry())
                .ok_or(PrepareError::GeometryNotFound {
                    node,
                    geometry: instance_set.geometry(),
                })?;
        let vertices = shadow_vertices(node, &geometry, DeformationInputs::default())?;
        for instance in instance_set.instances() {
            append_shadow_geometry(
                &mut occluders,
                &geometry,
                &vertices,
                compose_transform(node_transform, instance.transform()),
                origin_shift,
            );
        }
    }

    Ok(occluders)
}

pub(super) fn collect_shadow_projection_points<F>(
    scene: &Scene,
    assets: Option<&Assets<F>>,
    origin_shift: Vec3,
) -> Result<Vec<Vec3>, PrepareError> {
    let mut points = Vec::new();

    for (renderable, transform) in scene.renderables() {
        for primitive in renderable.primitives() {
            let primitive = transform_primitive(primitive, transform, origin_shift);
            for vertex in primitive.vertices() {
                points.push(vertex.position);
            }
        }
    }

    let Some(assets) = assets else {
        return Ok(points);
    };

    for (node, mesh, transform) in scene.mesh_nodes() {
        let geometry = assets
            .geometry(mesh.geometry())
            .ok_or(PrepareError::GeometryNotFound {
                node,
                geometry: mesh.geometry(),
            })?;
        let skin_matrices = scene.skin_matrices(node);
        let deformation = DeformationInputs {
            morph_weights: scene.morph_weights(node),
            skin_matrices: skin_matrices.as_deref(),
        };
        append_shadow_projection_points(
            &mut points,
            node,
            &geometry,
            deformation,
            transform,
            origin_shift,
        )?;
    }

    for (node, instance_set, node_transform) in scene.instance_set_nodes() {
        let geometry =
            assets
                .geometry(instance_set.geometry())
                .ok_or(PrepareError::GeometryNotFound {
                    node,
                    geometry: instance_set.geometry(),
                })?;
        for instance in instance_set.instances() {
            append_shadow_projection_points(
                &mut points,
                node,
                &geometry,
                DeformationInputs::default(),
                compose_transform(node_transform, instance.transform()),
                origin_shift,
            )?;
        }
    }

    Ok(points)
}

pub(super) fn directional_shadow_factor(
    position: Vec3,
    lights: &PreparedLights,
    occluders: &[ShadowOccluder],
) -> f32 {
    let Some(ray_direction) = lights.primary_shadow_ray_direction() else {
        return 1.0;
    };
    let origin = add_vec3(position, scale_vec3(ray_direction, 0.01));
    if occluders
        .iter()
        .any(|occluder| ray_intersects_triangle(origin, ray_direction, *occluder))
    {
        0.18
    } else {
        1.0
    }
}

fn shadow_vertices(
    node: NodeKey,
    geometry: &GeometryDesc,
    deformation: DeformationInputs<'_>,
) -> Result<Vec<GeometryVertex>, PrepareError> {
    let morphed_vertices = deformation
        .morph_weights
        .and_then(|weights| geometry.morphed_vertices(weights));
    let base_vertices = morphed_vertices
        .as_deref()
        .unwrap_or_else(|| geometry.vertices());
    match deformation.skin_matrices {
        Some(matrices) => geometry
            .skinned_vertices(base_vertices, matrices)
            .map(|vertices| vertices.unwrap_or_else(|| base_vertices.to_vec()))
            .map_err(|error| PrepareError::InvalidSkinGeometry {
                node,
                reason: format!("{error:?}"),
            }),
        None if geometry.skin().is_some() => Err(PrepareError::InvalidSkinGeometry {
            node,
            reason: "skinned geometry is missing a scene skin binding".to_string(),
        }),
        None => Ok(base_vertices.to_vec()),
    }
}

fn append_shadow_geometry(
    occluders: &mut Vec<ShadowOccluder>,
    geometry: &GeometryDesc,
    vertices: &[GeometryVertex],
    transform: Transform,
    origin_shift: Vec3,
) {
    if geometry.topology() != GeometryTopology::Triangles {
        return;
    }
    for triangle in geometry.indices().chunks_exact(3) {
        occluders.push(ShadowOccluder {
            a: transform_position(
                vertices[triangle[0] as usize].position,
                transform,
                origin_shift,
            ),
            b: transform_position(
                vertices[triangle[1] as usize].position,
                transform,
                origin_shift,
            ),
            c: transform_position(
                vertices[triangle[2] as usize].position,
                transform,
                origin_shift,
            ),
        });
    }
}

/// Computes the light-space view-projection matrix for a directional light.
/// Returns an orthographic `light_from_world` whose frustum tightly encloses
/// the world-space AABB of `occluders` along `light_direction`. The shader
/// projects fragment world positions through this matrix and samples the
/// shadow texture written by the shadow caster pass; closes the
/// `LightCamera` portion of scena-wgpu-architect F3 (Phase 1B).
///
/// Returned matrix is column-major 4x4 to match the WGSL `mat4x4<f32>` upload
/// layout used elsewhere in the renderer.
pub(super) fn directional_light_view_projection(
    light_direction: Vec3,
    occluders: &[ShadowOccluder],
) -> [f32; 16] {
    directional_light_view_projection_from_points(
        light_direction,
        occluders
            .iter()
            .flat_map(|occluder| [occluder.a, occluder.b, occluder.c]),
    )
}

pub(in crate::render) fn directional_light_view_projection_from_points(
    light_direction: Vec3,
    points: impl IntoIterator<Item = Vec3>,
) -> [f32; 16] {
    // Light forward = direction the light travels. Build an orthonormal basis.
    let forward = normalize_or(light_direction, Vec3::new(0.0, 0.0, -1.0));
    let world_up = if forward.y.abs() > 0.99 {
        Vec3::new(1.0, 0.0, 0.0)
    } else {
        Vec3::new(0.0, 1.0, 0.0)
    };
    let right = normalize_or(cross_vec3(world_up, forward), Vec3::new(1.0, 0.0, 0.0));
    let up = cross_vec3(forward, right);

    // Project all occluder vertices into the light-view basis, then build an
    // orthographic projection that fits the resulting AABB. min/max is the
    // tight light-space bounding box.
    let mut any = false;
    let mut min = Vec3::new(f32::INFINITY, f32::INFINITY, f32::INFINITY);
    let mut max = Vec3::new(f32::NEG_INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY);
    for vertex in points {
        any = true;
        let lx = dot_vec3(right, vertex);
        let ly = dot_vec3(up, vertex);
        let lz = dot_vec3(forward, vertex);
        min = Vec3::new(min.x.min(lx), min.y.min(ly), min.z.min(lz));
        max = Vec3::new(max.x.max(lx), max.y.max(ly), max.z.max(lz));
    }
    if !any {
        return identity_matrix4();
    }

    // Pad slightly so receivers near the AABB edges aren't clipped, and so
    // self-shadow acne lands inside the [near, far] window the projection
    // covers.
    let pad = ((max.x - min.x) + (max.y - min.y) + (max.z - min.z)) * 0.05;
    min = Vec3::new(min.x - pad, min.y - pad, min.z - pad);
    max = Vec3::new(max.x + pad, max.y + pad, max.z + pad);

    // Orthographic projection mapping light-view [min..max] → clip [-1..1] x
    // [-1..1] x [0..1] (WebGPU/wgpu Z range). Composed with the view rotation
    // expressing world → light-view-space.
    let inv_x = 1.0 / (max.x - min.x).max(f32::EPSILON);
    let inv_y = 1.0 / (max.y - min.y).max(f32::EPSILON);
    let inv_z = 1.0 / (max.z - min.z).max(f32::EPSILON);

    // light_from_world = ortho * view. Compose by hand so the column-major
    // upload layout matches WGSL.
    //
    // view matrix (world → light-view-space, column-major):
    //   col0 = (right.x, up.x, forward.x, 0)
    //   col1 = (right.y, up.y, forward.y, 0)
    //   col2 = (right.z, up.z, forward.z, 0)
    //   col3 = (0, 0, 0, 1)
    //
    // ortho matrix (light-view → clip, column-major, depth in [0..1]):
    //   col0 = (2 * inv_x, 0, 0, 0)
    //   col1 = (0, 2 * inv_y, 0, 0)
    //   col2 = (0, 0, inv_z, 0)
    //   col3 = (-(max.x + min.x) * inv_x,
    //           -(max.y + min.y) * inv_y,
    //           -min.z * inv_z,
    //           1)
    //
    // Combined column-major light_from_world:
    let cm = |x: f32, y: f32, z: f32, w: f32| [x, y, z, w];
    let col0 = cm(
        2.0 * right.x * inv_x,
        2.0 * up.x * inv_y,
        forward.x * inv_z,
        0.0,
    );
    let col1 = cm(
        2.0 * right.y * inv_x,
        2.0 * up.y * inv_y,
        forward.y * inv_z,
        0.0,
    );
    let col2 = cm(
        2.0 * right.z * inv_x,
        2.0 * up.z * inv_y,
        forward.z * inv_z,
        0.0,
    );
    let col3 = cm(
        -(max.x + min.x) * inv_x,
        -(max.y + min.y) * inv_y,
        -min.z * inv_z,
        1.0,
    );
    [
        col0[0], col0[1], col0[2], col0[3], col1[0], col1[1], col1[2], col1[3], col2[0], col2[1],
        col2[2], col2[3], col3[0], col3[1], col3[2], col3[3],
    ]
}

fn append_shadow_projection_points(
    points: &mut Vec<Vec3>,
    node: NodeKey,
    geometry: &GeometryDesc,
    deformation: DeformationInputs<'_>,
    transform: Transform,
    origin_shift: Vec3,
) -> Result<(), PrepareError> {
    if geometry.topology() != GeometryTopology::Triangles {
        return Ok(());
    }
    if deformation.morph_weights.is_none()
        && deformation.skin_matrices.is_none()
        && geometry.skin().is_none()
    {
        append_transformed_bounds_points(points, geometry.bounds(), transform, origin_shift);
        return Ok(());
    }

    let vertices = shadow_vertices(node, geometry, deformation)?;
    for vertex in vertices {
        points.push(transform_position(vertex.position, transform, origin_shift));
    }
    Ok(())
}

fn append_transformed_bounds_points(
    points: &mut Vec<Vec3>,
    bounds: Aabb,
    transform: Transform,
    origin_shift: Vec3,
) {
    for corner in bounds_corners(bounds) {
        points.push(transform_position(corner, transform, origin_shift));
    }
}

fn bounds_corners(bounds: Aabb) -> [Vec3; 8] {
    let min = bounds.min;
    let max = bounds.max;
    [
        Vec3::new(min.x, min.y, min.z),
        Vec3::new(max.x, min.y, min.z),
        Vec3::new(min.x, max.y, min.z),
        Vec3::new(max.x, max.y, min.z),
        Vec3::new(min.x, min.y, max.z),
        Vec3::new(max.x, min.y, max.z),
        Vec3::new(min.x, max.y, max.z),
        Vec3::new(max.x, max.y, max.z),
    ]
}

fn normalize_or(value: Vec3, fallback: Vec3) -> Vec3 {
    let length = dot_vec3(value, value).sqrt();
    if length <= f32::EPSILON || !length.is_finite() {
        return fallback;
    }
    Vec3::new(value.x / length, value.y / length, value.z / length)
}

const fn identity_matrix4() -> [f32; 16] {
    [
        1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
    ]
}

fn ray_intersects_triangle(origin: Vec3, direction: Vec3, triangle: ShadowOccluder) -> bool {
    let edge1 = subtract_vec3(triangle.b, triangle.a);
    let edge2 = subtract_vec3(triangle.c, triangle.a);
    let h = cross_vec3(direction, edge2);
    let determinant = dot_vec3(edge1, h);
    if determinant.abs() <= 0.000_001 {
        return false;
    }
    let inverse_determinant = determinant.recip();
    let s = subtract_vec3(origin, triangle.a);
    let u = inverse_determinant * dot_vec3(s, h);
    if !(0.0..=1.0).contains(&u) {
        return false;
    }
    let q = cross_vec3(s, edge1);
    let v = inverse_determinant * dot_vec3(direction, q);
    if v < 0.0 || u + v > 1.0 {
        return false;
    }
    let t = inverse_determinant * dot_vec3(edge2, q);
    t > 0.001
}

fn add_vec3(left: Vec3, right: Vec3) -> Vec3 {
    Vec3::new(left.x + right.x, left.y + right.y, left.z + right.z)
}

fn subtract_vec3(left: Vec3, right: Vec3) -> Vec3 {
    Vec3::new(left.x - right.x, left.y - right.y, left.z - right.z)
}

fn scale_vec3(value: Vec3, scale: f32) -> Vec3 {
    Vec3::new(value.x * scale, value.y * scale, value.z * scale)
}

fn dot_vec3(left: Vec3, right: Vec3) -> f32 {
    left.x * right.x + left.y * right.y + left.z * right.z
}

fn cross_vec3(left: Vec3, right: Vec3) -> Vec3 {
    Vec3::new(
        left.y * right.z - left.z * right.y,
        left.z * right.x - left.x * right.z,
        left.x * right.y - left.y * right.x,
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn shadow_projection_from_points_matches_triangle_vertices() {
        let points = bounds_corners(Aabb::new(
            Vec3::new(-1.0, -0.5, -0.25),
            Vec3::new(1.0, 0.5, 0.25),
        ));
        let occluders = [
            ShadowOccluder {
                a: points[0],
                b: points[1],
                c: points[2],
            },
            ShadowOccluder {
                a: points[3],
                b: points[4],
                c: points[5],
            },
            ShadowOccluder {
                a: points[6],
                b: points[7],
                c: points[0],
            },
        ];
        let light_direction = Vec3::new(-0.2, -1.0, -0.35);

        let from_points = directional_light_view_projection_from_points(light_direction, points);
        let from_triangles = directional_light_view_projection(light_direction, &occluders);

        for (left, right) in from_points.iter().zip(from_triangles.iter()) {
            assert!((left - right).abs() < 1e-6);
        }
    }
}