sgl-3d 0.4.2

Caller-driven 3D rendering for SGL games, native and in the browser (WebGPU)
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
use super::*;
use glam::camera;
use glam::{DVec3, DVec4};
use wasm_bindgen_test::wasm_bindgen_test;

const MAP: u32 = 2048;

fn shadow(cascades: u32) -> DirectionalShadow {
    DirectionalShadow {
        distance: 200.,
        cascades,
    }
}

/// A deterministic sequence in 0..1.
struct Sequence(u64);

impl Sequence {
    fn next(&mut self) -> f64 {
        self.0 = self
            .0
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        (self.0 >> 11) as f64 / (1u64 << 53) as f64
    }

    fn between(&mut self, low: f64, high: f64) -> f64 {
        low + (high - low) * self.next()
    }
}

/// `point` in `cascade`'s clip space, in double precision from the
/// matrix the shaders use.
fn clip(cascade: &Cascade, point: DVec3) -> DVec3 {
    let clip = cascade.clip_from_world.as_dmat4() * point.extend(1.);
    clip.truncate() / clip.w
}

/// Whether `cascade`'s map holds `point`: inside its square and its depth
/// range, as directional_shadow.wgsl tests it.
fn holds(cascade: &Cascade, point: DVec3) -> bool {
    let p = clip(cascade, point);
    p.x.abs() <= 1. && p.y.abs() <= 1. && (0. ..=1.).contains(&p.z)
}

// Plausible defects: a centre not snapped to the texel grid, snapped in a
// space the light's rotation does not keep, or a diameter that follows the
// camera's orientation, any of which makes a still shadow shimmer as the
// camera moves. The oracle is the map itself: a fixed world point, projected
// by each pose's cascade, lands on texel coordinates that differ between
// poses by whole texels.
#[wasm_bindgen_test(unsupported = test)]
fn a_fixed_point_moves_by_whole_texels_as_the_camera_moves_and_turns() {
    let projection = crate::perspective(1.1, 16. / 9., 0.3);
    let points = [
        DVec3::new(13.7, 2.3, -41.9),
        DVec3::new(-3.1, 0.2, -6.4),
        DVec3::new(120.5, -8.25, 77.125),
    ];
    for direction in [
        Vec3::new(0.6, -1., -0.4),
        Vec3::new(-180., 220., 260.).normalize() * -1.,
        Vec3::NEG_Y,
    ] {
        let mut sequence = Sequence(7);
        let poses: Vec<Mat4> = (0..12)
            .map(|_| {
                let eye = Vec3::new(
                    sequence.between(-60., 60.) as f32,
                    sequence.between(0.5, 30.) as f32,
                    sequence.between(-60., 60.) as f32,
                );
                let yaw = sequence.between(-3.1, 3.1) as f32;
                let pitch = sequence.between(-0.6, 0.4) as f32;
                let forward = Vec3::new(
                    yaw.sin() * pitch.cos(),
                    pitch.sin(),
                    -yaw.cos() * pitch.cos(),
                );
                camera::rh::view::look_to_mat4(eye, forward, Vec3::Y)
            })
            .collect();
        let fits: Vec<Cascades> = poses
            .iter()
            .map(|&view| {
                Cascades::camera(view, projection, direction, &shadow(4), MAP, DVec3::ZERO)
            })
            .collect();
        for (index, first) in fits[0].as_slice().iter().enumerate() {
            for later in &fits[1..] {
                let later = &later.as_slice()[index];
                for point in points {
                    let texels = |cascade: &Cascade| {
                        let p = clip(cascade, point);
                        (p.truncate() * 0.5 + 0.5) * f64::from(MAP)
                    };
                    let moved = texels(later) - texels(first);
                    let fraction = (moved - moved.round()).abs();
                    assert!(
                        fraction.max_element() < 0.01,
                        "cascade {index}, light {direction:?}: {point:?} moved {moved:?} texels"
                    );
                }
            }
        }
    }
}

// Plausible defects: slice corners taken at the wrong depths or from the
// wrong projection, a diameter or centre that leaves part of a slice outside
// its map, a depth range that cuts receivers off, far bounds that leave a gap
// before the shadow distance, an overlap the next cascade does not cover
// where the shading blends into it, a first cascade that starts at the eye
// when an orthographic near plane lies behind it, or a next cascade that
// starts after a far bound behind the eye. The oracle draws points the
// camera sees, by projecting candidates through its own view and projection,
// and checks that the cascade the shading selects for each (the first whose
// far bound lies beyond its view depth) holds it, as does the next one
// across the overlap.
#[wasm_bindgen_test(unsupported = test)]
fn every_visible_point_within_the_shadow_distance_falls_inside_its_cascade() {
    // Each camera with the region its view space holds at a view depth d:
    // x within centre.x ± (slope.x d + half.x), y likewise, beyond the view
    // depth of its near plane.
    struct Camera {
        projection: Mat4,
        slope: DVec3,
        half: DVec3,
        centre: DVec3,
        near: f64,
    }
    let perspective = |fov: f32, aspect: f32, near: f32| {
        let tan = f64::from((fov / 2.).tan());
        Camera {
            projection: crate::perspective(fov, aspect, near),
            slope: DVec3::new(tan * f64::from(aspect), tan, 0.),
            half: DVec3::ZERO,
            centre: DVec3::ZERO,
            near: f64::from(near),
        }
    };
    let cameras = [
        perspective(1.1, 16. / 9., 0.3),
        perspective(0.4, 1., 0.05),
        perspective(2.2, 21. / 9., 1.),
        Camera {
            projection: camera::rh::proj::directx::orthographic(-30., 50., -20., 25., 400., 0.5),
            slope: DVec3::ZERO,
            half: DVec3::new(40., 22.5, 0.),
            centre: DVec3::new(10., 2.5, 0.),
            near: 0.5,
        },
        // Its near plane 40 m behind the eye.
        Camera {
            projection: camera::rh::proj::directx::orthographic(-40., 40., -25., 25., 200., -40.),
            slope: DVec3::ZERO,
            half: DVec3::new(40., 25., 0.),
            centre: DVec3::ZERO,
            near: -40.,
        },
        // 400 m behind it, so that cascades end behind the eye too.
        Camera {
            projection: camera::rh::proj::directx::orthographic(-40., 40., -25., 25., 200., -400.),
            slope: DVec3::ZERO,
            half: DVec3::new(40., 25., 0.),
            centre: DVec3::ZERO,
            near: -400.,
        },
    ];
    let directions = [
        Vec3::new(0.6, -1., -0.4),
        Vec3::new(0.05, -1., 0.02),
        Vec3::new(-1., -0.1, 0.3),
    ];
    let mut sequence = Sequence(11);
    for camera in &cameras {
        let projection = camera.projection;
        for direction in directions {
            for count in 1..=4 {
                let eye = Vec3::new(17., 4., -230.);
                let view = camera::rh::view::look_to_mat4(eye, Vec3::new(0.3, -0.2, -1.), Vec3::Y);
                let shadow = shadow(count);
                let cascades =
                    Cascades::camera(view, projection, direction, &shadow, MAP, DVec3::ZERO);
                let cascades = cascades.as_slice();
                assert_eq!(cascades.len(), count as usize);
                let clip_from_world = (projection * view).as_dmat4();
                let world_from_view = view.inverse().as_dmat4();
                let mut seen = 0;
                while seen < 3000 {
                    // A candidate in the camera's view space, a little wider
                    // than what it sees, kept when the camera's clip volume
                    // holds it.
                    let depth = sequence.between(camera.near, f64::from(shadow.distance));
                    let reach = (camera.slope * depth + camera.half) * 1.2;
                    let candidate = DVec4::new(
                        camera.centre.x + sequence.between(-reach.x, reach.x),
                        camera.centre.y + sequence.between(-reach.y, reach.y),
                        -depth,
                        1.,
                    );
                    let world = (world_from_view * candidate).truncate();
                    let c = clip_from_world * world.extend(1.);
                    let device = c.truncate() / c.w;
                    if c.w <= 0. || device.x.abs() > 1. || device.y.abs() > 1. || device.z > 1. {
                        continue;
                    }
                    seen += 1;
                    let index = cascades
                        .iter()
                        .position(|cascade| depth < f64::from(cascade.far_bound))
                        .unwrap_or(cascades.len() - 1);
                    assert!(
                        holds(&cascades[index], world),
                        "{count} cascades, light {direction:?}: cascade {index} misses a point at depth {depth}"
                    );
                    let overlap = f64::from(next_near_bound(cascades[index].far_bound));
                    if index + 1 < cascades.len() && depth >= overlap {
                        assert!(
                            holds(&cascades[index + 1], world),
                            "{count} cascades: cascade {} misses a blended point at depth {depth}",
                            index + 1
                        );
                    }
                }
                let last = cascades.last().unwrap().far_bound;
                assert!(
                    (last - shadow.distance).abs() < 1e-3,
                    "the last cascade ends at {last}, not the shadow distance"
                );
            }
        }
    }
}

// A probe capture selects the first cascade that holds a position. Plausible
// defects: a cascade cube smaller than what the faces see out to its bound,
// or bounds that stop short of the distance. The oracle draws points in the
// cube around the capture's centre and checks that the first cascade whose
// bound exceeds the point's distance along every axis holds it.
#[wasm_bindgen_test(unsupported = test)]
fn every_point_a_capture_sees_within_the_shadow_distance_falls_inside_its_cascade() {
    let center = Vec3::new(-41., 3.5, 812.);
    let mut sequence = Sequence(3);
    for direction in [Vec3::new(0.6, -1., -0.4), Vec3::NEG_Y] {
        let cascades = Cascades::capture(center, direction, &shadow(4), MAP, DVec3::ZERO);
        let cascades = cascades.as_slice();
        for _ in 0..4000 {
            let offset = DVec3::new(
                sequence.between(-200., 200.),
                sequence.between(-200., 200.),
                sequence.between(-200., 200.),
            );
            let reach = offset.abs().max_element();
            let index = cascades
                .iter()
                .position(|cascade| reach < f64::from(cascade.far_bound))
                .unwrap();
            assert!(
                holds(&cascades[index], center.as_dvec3() + offset),
                "cascade {index} misses a point {reach} m out"
            );
        }
    }
}

// Godot places the cascades' far bounds
// (`_light_instance_setup_directional_shadow` with `DirectionalLight3D`'s
// default splits of 0.1, 0.2 and 0.5): each but the last ends that share of the way from the camera's near plane
// to the shadow's distance, and the last at the distance; 2 and 3 cascades
// take the first one and two shares. Plausible defects: shares measured from
// the view origin rather than the near plane, the wrong shares for fewer
// cascades (the last ones, or rescaled), or the last cascade stopping short
// of or beyond the distance. The oracle is Godot's formula over its default
// shares, worked by hand: a camera whose near plane is 0.3 m with a 150.3 m
// shadow (a 150 m range), and a probe capture, whose cascades start at its
// centre, with a 40 m one.
#[wasm_bindgen_test(unsupported = test)]
fn cascade_bounds_are_godots_splits_of_the_range_from_the_near_plane() {
    let view = camera::rh::view::look_to_mat4(Vec3::new(3., 2., 1.), Vec3::NEG_Z, Vec3::Y);
    let projection = crate::perspective(1.1, 16. / 9., 0.3);
    let camera: [&[f32]; 4] = [
        &[150.3],
        &[15.3, 150.3],
        &[15.3, 30.3, 150.3],
        &[15.3, 30.3, 75.3, 150.3],
    ];
    let capture: [&[f32]; 4] = [&[40.], &[4., 40.], &[4., 8., 40.], &[4., 8., 20., 40.]];
    for (count, (camera, capture)) in (1..=4u32).zip(camera.into_iter().zip(capture)) {
        let fits = [
            (
                "camera",
                camera,
                Cascades::camera(
                    view,
                    projection,
                    Vec3::NEG_Y,
                    &DirectionalShadow {
                        distance: 150.3,
                        cascades: count,
                    },
                    MAP,
                    DVec3::ZERO,
                ),
            ),
            (
                "capture",
                capture,
                Cascades::capture(
                    Vec3::new(5., 1., -3.),
                    Vec3::NEG_Y,
                    &DirectionalShadow {
                        distance: 40.,
                        cascades: count,
                    },
                    MAP,
                    DVec3::ZERO,
                ),
            ),
        ];
        for (label, expected, cascades) in fits {
            let bounds: Vec<f32> = cascades
                .as_slice()
                .iter()
                .map(|cascade| cascade.far_bound)
                .collect();
            assert!(
                bounds.len() == expected.len()
                    && bounds
                        .iter()
                        .zip(expected)
                        .all(|(a, b)| (a - b).abs() < 1e-3),
                "{label}, {count} cascades: bounds {bounds:?}, not {expected:?}"
            );
        }
    }
}

// A shadow's distance is only its reach (AR-5): `DirectionalLight::shadow`
// being `None` is its off switch. Plausible defects: a distance at or
// before where the cascades start, nonfinite, or NaN casting no shadow, or
// reaching the fit and making nonfinite cascades. The oracle is Godot's
// bound, by hand: the distance at least 1 mm beyond where the cascades
// start (the camera's 0.3 m near plane, a capture's centre), and at most
// the 8192 m top of `directional_shadow_max_distance`'s range.
#[wasm_bindgen_test(unsupported = test)]
fn a_distance_out_of_range_shadows_to_the_nearer_bound() {
    let view = camera::rh::view::look_to_mat4(Vec3::new(3., 2., 1.), Vec3::NEG_Z, Vec3::Y);
    let projection = crate::perspective(1.1, 16. / 9., 0.3);
    for (distance, camera, capture) in [
        (0., 0.301, 0.001),
        (-5., 0.301, 0.001),
        (0.2, 0.301, 0.2),
        (f32::NAN, 0.301, 0.001),
        (f32::NEG_INFINITY, 0.301, 0.001),
        (f32::INFINITY, 8192., 8192.),
        (1e9, 8192., 8192.),
    ] {
        let shadow = DirectionalShadow {
            distance,
            cascades: 1,
        };
        let fits = [
            (
                "camera",
                camera,
                Cascades::camera(view, projection, Vec3::NEG_Y, &shadow, MAP, DVec3::ZERO),
            ),
            (
                "capture",
                capture,
                Cascades::capture(
                    Vec3::new(5., 1., -3.),
                    Vec3::NEG_Y,
                    &shadow,
                    MAP,
                    DVec3::ZERO,
                ),
            ),
        ];
        for (label, expected, cascades) in fits {
            let [cascade] = cascades.as_slice() else {
                panic!("{label}: distance {distance} cast no shadow");
            };
            assert!(
                (cascade.far_bound - expected).abs() < 1e-4 * expected.max(1.)
                    && cascade.clip_from_world.is_finite(),
                "{label}: distance {distance} reaches {}, not {expected}",
                cascade.far_bound
            );
        }
    }
}

// Plausible defects: the texel grid snapped in the render frame, so moving
// the render origin by a distance that is no whole number of texels in light
// space shifts every shadow texel for a frame; or the origin taken into light
// space in single precision, so a far origin loses the grid. The oracle is
// the map: with the camera where it was in the world, a fixed world point
// lands on the same texel coordinates, but for whole texels, before and
// after the move, whatever the origin's magnitude.
#[wasm_bindgen_test(unsupported = test)]
fn moving_the_render_origin_shifts_no_shadow_texel() {
    let projection = crate::perspective(1.1, 16. / 9., 0.3);
    let far = DVec3::new(10_000_000.375, -2_500.5, -20_000_000.625);
    for direction in [
        Vec3::new(0.6, -1., -0.4),
        Vec3::new(-0.3, -1., 0.8),
        Vec3::NEG_Y,
    ] {
        for (first, moved) in [
            (DVec3::ZERO, DVec3::new(731.37, 12.6, -409.81)),
            (far, far + DVec3::new(1024., 0., -2048.)),
            (far, far + DVec3::new(-77.7, 3.3, 129.9)),
        ] {
            let eye = first + DVec3::new(5.25, 20., -3.5);
            let forward = Vec3::new(0.3, -0.4, -1.).normalize();
            let fit = |origin: DVec3| {
                let view =
                    camera::rh::view::look_to_mat4((eye - origin).as_vec3(), forward, Vec3::Y);
                Cascades::camera(view, projection, direction, &shadow(4), MAP, origin)
            };
            let (before, after) = (fit(first), fit(moved));
            for (index, (before, after)) in
                before.as_slice().iter().zip(after.as_slice()).enumerate()
            {
                for offset in [
                    DVec3::new(13.7, 2.3, -41.9),
                    DVec3::new(-3.1, -18.8, -6.4),
                    DVec3::new(60.5, -8.25, -77.125),
                ] {
                    let point = eye + offset;
                    let texels = |cascade: &Cascade, origin: DVec3| {
                        let p = clip(cascade, point - origin);
                        (p.truncate() * 0.5 + 0.5) * f64::from(MAP)
                    };
                    let shift = texels(after, moved) - texels(before, first);
                    let fraction = (shift - shift.round()).abs();
                    assert!(
                        fraction.max_element() < 0.01,
                        "cascade {index}, light {direction:?}, origin {first:?} to {moved:?}: shifted {shift:?} texels"
                    );
                }
            }
        }
    }
}