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
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
//! The acceleration structures on a device that traces rays in hardware,
//! built and bound as a frame builds them. Each test reports itself
//! unsupported, never passed, where the adapter has no ray queries.
use super::RayTracingStats;
use crate::asset::{Asset, CpuMesh, Vertex};
use crate::shading::{RayQueryForm, SCENE_RAYS_QUERY_OPAQUE, bind, compose};
use crate::test_support;
use crate::{InstanceState, Mobility, Scene};
use glam::{Mat4, Vec3};

/// A mesh of `triangles` separate triangles about `centre`.
fn triangles(centre: Vec3, triangles: u32) -> CpuMesh {
    let vertices = (0..triangles * 3)
        .map(|vertex| {
            let corner = [[-0.5, -0.5], [0.5, -0.5], [0., 0.5]][vertex as usize % 3];
            let layer = (vertex / 3) as f32 * 0.01;
            Vertex {
                tangent: [0.; 4],
                lightmap_bounds: [0., 0., 1., 1.],
                lightmap_uv: [0.; 2],
                position: (centre + Vec3::new(corner[0], corner[1], layer)).to_array(),
                normal: [0., 0., 1.],
                uv: [0.; 2],
                color: [1.; 4],
            }
        })
        .collect();
    CpuMesh {
        vertices,
        indices: (0..triangles * 3).collect(),
        material: 0,
        deformation: Default::default(),
    }
}

/// An opaque asset of `meshes`.
fn asset(meshes: Vec<CpuMesh>) -> Asset {
    let mut asset = test_support::cube();
    asset.meshes = meshes;
    asset
}

/// Adds a capture-visible `mobility` instance of `model` at `pose`.
fn place(
    gpu: (&wgpu::Device, &wgpu::Queue),
    scene: &mut Scene,
    model: crate::ModelId,
    pose: Mat4,
    mobility: Mobility,
) -> crate::InstanceId {
    scene
        .add_instance(
            gpu.0,
            gpu.1,
            InstanceState {
                pose,
                ..InstanceState::new(model)
            },
            mobility,
        )
        .unwrap()
}

/// Builds `scene`'s acceleration structures for a frame seen from `eye`,
/// in the baseline form, records them, submits and finishes the frame, as
/// a renderer's frame does, and returns what the frame held.
fn build(gpu: (&wgpu::Device, &wgpu::Queue), scene: &mut Scene, eye: Vec3) -> RayTracingStats {
    build_in(gpu, scene, eye, RayQueryForm::Baseline)
}

/// `build` in the query form `form`.
fn build_in(
    (device, queue): (&wgpu::Device, &wgpu::Queue),
    scene: &mut Scene,
    eye: Vec3,
    form: RayQueryForm,
) -> RayTracingStats {
    let stats = scene
        .prepare_acceleration_structures(device, queue, eye, form)
        .expect("the device holds a TLAS");
    let mut encoder = device.create_command_encoder(&Default::default());
    scene.encode_acceleration_structures(&mut encoder);
    queue.submit([encoder.finish()]);
    scene.finish_frame();
    stats
}

/// Binds `scene`'s TLAS at the entry a tracing pass binds it at, in a
/// compute pass that dispatches once: wgpu then requires it, and every
/// BLAS it names, built.
fn bind_tlas((device, queue): (&wgpu::Device, &wgpu::Queue), scene: &Scene) {
    let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
        label: Some("TLAS test"),
        entries: &[bind::tlas_entry()],
    });
    let source =
        compose(&[&SCENE_RAYS_QUERY_OPAQUE]) + "@compute @workgroup_size(1) fn bind_tlas() {}\n";
    let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
        label: Some("TLAS test"),
        source: wgpu::ShaderSource::Wgsl(source.into()),
    });
    let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
        label: Some("TLAS test"),
        layout: Some(
            &device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: None,
                bind_group_layouts: &[None, None, None, Some(&layout)],
                immediate_size: 0,
            }),
        ),
        module: &module,
        entry_point: Some("bind_tlas"),
        compilation_options: Default::default(),
        cache: None,
    });
    let tlas = scene
        .acceleration_structures()
        .expect("structures were built")
        .tlas()
        .0;
    let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
        label: Some("TLAS test"),
        layout: &layout,
        entries: &[wgpu::BindGroupEntry {
            binding: bind::hardware::SCENE_TLAS,
            resource: tlas.as_binding(),
        }],
    });
    let mut encoder = device.create_command_encoder(&Default::default());
    {
        let mut pass = encoder.begin_compute_pass(&Default::default());
        pass.set_pipeline(&pipeline);
        pass.set_bind_group(3, &group, &[]);
        pass.dispatch_workgroups(1, 1, 1);
    }
    queue.submit([encoder.finish()]);
}

// The smallest build: one BLAS of one triangle and one TLAS instance.
// Plausible defects: the TLAS left unbuilt, or naming a BLAS never built
// (bookkeeping committed for work never recorded); the ray source without
// `BLAS_INPUT`; a first vertex or index the source does not hold; a custom
// index past 24 bits; or a TLAS a pass cannot bind at the shared entry.
// wgpu's validation refuses each when the frame is submitted or the TLAS
// bound, the independent oracle; and the structures hold the scene's one
// triangle.
#[test]
fn one_triangle_builds_and_binds() {
    let Some((device, queue)) = test_support::ray_tracing_device(|limits| limits) else {
        return;
    };
    let gpu = (&device, &queue);
    let mut scene = Scene::new(&device, &queue);
    let model = scene
        .add_asset(&device, &queue, asset(vec![triangles(Vec3::ZERO, 1)]))
        .unwrap()
        .model;
    place(gpu, &mut scene, model, Mat4::IDENTITY, Mobility::Static);
    let validation = device.push_error_scope(wgpu::ErrorFilter::Validation);
    let stats = build(gpu, &mut scene, Vec3::Z * 5.);
    bind_tlas(gpu, &scene);
    device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
    let error = pollster::block_on(validation.pop());
    assert!(error.is_none(), "{error:?}");
    assert_eq!(
        stats,
        RayTracingStats {
            hardware: 1,
            portable: 0,
            left_out: 0,
        }
    );
    let resources = scene.diagnostic_resources();
    assert_eq!((resources.blases, resources.blas_triangles), (1, 1));
}

/// `asset` with its material's alpha mode `alpha`.
fn with_alpha(mut asset: Asset, alpha: crate::AlphaMode) -> Asset {
    asset.materials[0].alpha = alpha;
    asset
}

/// The entry indices the TLAS holds, in order, and their masks.
fn held(scene: &Scene) -> Vec<(u32, u8)> {
    scene
        .acceleration_structures()
        .expect("structures were built")
        .tlas()
        .0
        .get()
        .iter()
        .map_while(|instance| instance.as_ref())
        .map(|instance| (instance.custom_data, instance.mask))
        .collect()
}

// Plausible defects: a model past the device's BLAS limits, an instance
// past its TLAS capacity, a mesh's dangling index or a mesh without a whole
// triangle reaching wgpu (whose validation refuses the frame), the nearest instances left out rather than the farthest, a
// predicate instance (a masked mesh) or one rays pass through (blended
// only) given to the TLAS, one not capture-visible counted, or a material's
// alpha mode edited without its users' ray class following. The oracles
// are wgpu's validation and the architecture's rules over the test's
// content, on a device whose limits the test lowered: four primitives a
// BLAS, two instances a TLAS.
#[test]
fn what_the_device_cannot_hold_is_left_out_and_counted() {
    let Some((device, queue)) = test_support::ray_tracing_device(|limits| wgpu::Limits {
        max_blas_primitive_count: 4,
        max_tlas_instance_count: 2,
        ..limits
    }) else {
        return;
    };
    let gpu = (&device, &queue);
    let mut scene = Scene::new(&device, &queue);
    // One triangle and an index past it, which the scene accepts and the
    // BLAS must not take (wgpu refuses a count of indices not a multiple of
    // three), and a mesh with no whole triangle, whose geometry holds none
    // and keeps the next mesh's geometry index its own.
    let mut dangling = triangles(Vec3::ZERO, 1);
    dangling.indices.push(0);
    let mut empty = triangles(Vec3::X, 1);
    empty.indices.truncate(2);
    let small = scene
        .add_asset(&device, &queue, asset(vec![dangling, empty]))
        .unwrap();
    // Five triangles: one more than a BLAS holds.
    let large = scene
        .add_asset(&device, &queue, asset(vec![triangles(Vec3::ZERO, 5)]))
        .unwrap()
        .model;
    let masked = scene
        .add_asset(
            &device,
            &queue,
            test_support::masked(test_support::cube(), 0.5),
        )
        .unwrap()
        .model;
    let blended = scene
        .add_asset(
            &device,
            &queue,
            with_alpha(
                test_support::cube(),
                crate::AlphaMode::Blend {
                    receives_screen_space_reflections: false,
                    keeps_specular: false,
                },
            ),
        )
        .unwrap()
        .model;
    let at = |z: f32| Mat4::from_translation(Vec3::Z * z);
    let near = place(gpu, &mut scene, small.model, at(0.), Mobility::Static);
    let middle = place(gpu, &mut scene, small.model, at(-10.), Mobility::Moving);
    place(gpu, &mut scene, small.model, at(-20.), Mobility::Static);
    place(gpu, &mut scene, large, at(0.), Mobility::Static);
    place(gpu, &mut scene, masked, at(0.), Mobility::Static);
    place(gpu, &mut scene, blended, at(0.), Mobility::Static);
    let hidden = place(gpu, &mut scene, small.model, at(1.), Mobility::Static);
    scene
        .set_instance(
            &queue,
            hidden,
            InstanceState {
                capture_visible: false,
                ..*scene.instance(hidden).unwrap()
            },
        )
        .unwrap();
    let eye = Vec3::Z * 5.;
    let validation = device.push_error_scope(wgpu::ErrorFilter::Validation);
    // The TLAS holds the two nearest instances of the small model; the
    // farthest and the large model's are left out, and with the masked
    // model's the portable BVHs cover them.
    let stats = build(gpu, &mut scene, eye);
    assert_eq!(
        stats,
        RayTracingStats {
            hardware: 2,
            portable: 3,
            left_out: 2,
        }
    );
    let index = |id: crate::InstanceId| crate::content::identity::Identity::index(id) as u32;
    let mut kept = held(&scene);
    kept.sort_unstable();
    assert_eq!(
        kept,
        [
            (index(near), super::MASK_STATIC),
            (index(middle), super::MASK_MOVING)
        ]
    );
    bind_tlas(gpu, &scene);
    // Masked, the small model's instances are predicate instances: the
    // portable BVHs cover all three and its BLAS is dropped.
    let opaque = scene.material(small.materials[0]).unwrap();
    let mask = crate::SurfaceMaterial {
        alpha: crate::AlphaMode::Mask { cutoff: 0.5 },
        ..opaque
    };
    scene
        .set_material(&queue, small.materials[0], mask)
        .unwrap();
    assert_eq!(
        build(gpu, &mut scene, eye),
        RayTracingStats {
            hardware: 0,
            portable: 5,
            left_out: 1,
        }
    );
    assert_eq!(scene.diagnostic_resources().blases, 0);
    // Opaque again, it is built again.
    scene
        .set_material(&queue, small.materials[0], opaque)
        .unwrap();
    assert_eq!(build(gpu, &mut scene, eye), stats);
    bind_tlas(gpu, &scene);
    device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
    let error = pollster::block_on(validation.pop());
    assert!(error.is_none(), "{error:?}");
}

/// `material`'s values in `scene` with its alpha mode `alpha`.
fn realpha(
    queue: &wgpu::Queue,
    scene: &mut Scene,
    material: crate::MaterialId,
    alpha: crate::AlphaMode,
) {
    let values = scene.material(material).unwrap();
    scene
        .set_material(queue, material, crate::SurfaceMaterial { alpha, ..values })
        .unwrap();
}

// The structures in the candidate form, and material edits that move a
// mesh between masked and not. Plausible defects: a masked model given no
// BLAS and left on the portable BVHs in the candidate form; after such an
// edit, a model's BLAS kept with its old geometry flags (a mesh made masked
// then cuts out only through re-traces of its committed hits, step by step
// against the ray's budget) or rebuilt under the budget, behind fresh
// models, a frame or more later; a deforming instance's BLAS kept with its
// old flags; and, falling back to the baseline form, masked models kept in
// the TLAS, or opaque models' BLASes built again for nothing. The oracles
// are wgpu's validation and the architecture's rules over the test's
// content, counted through `counters`: a build per BLAS made.
#[test]
fn the_candidate_form_holds_masked_models_and_rebuilds_them_when_edited() {
    let Some((device, queue)) = test_support::ray_tracing_device(|limits| limits) else {
        return;
    };
    let gpu = (&device, &queue);
    let validation = device.push_error_scope(wgpu::ErrorFilter::Validation);
    let mut scene = Scene::new(&device, &queue);
    let edited = scene
        .add_asset(&device, &queue, asset(vec![triangles(Vec3::ZERO, 1)]))
        .unwrap();
    let masked = scene
        .add_asset(
            &device,
            &queue,
            test_support::masked(test_support::cube(), 0.5),
        )
        .unwrap()
        .model;
    // One skinned triangle, whole on its one joint.
    let mut skinned = triangles(Vec3::ZERO, 1);
    skinned.deformation.influences = vec![
        crate::deformation::Influence {
            joints: [0; 4],
            weights: [1., 0., 0., 0.],
        };
        3
    ];
    let skinned = scene
        .add_asset(&device, &queue, asset(vec![skinned]))
        .unwrap();
    let at = |x: f32, z: f32| Mat4::from_translation(Vec3::new(x, 0., z));
    place(gpu, &mut scene, edited.model, at(0., -2.), Mobility::Static);
    place(gpu, &mut scene, masked, at(3., 0.), Mobility::Static);
    let deforming = place(
        gpu,
        &mut scene,
        skinned.model,
        at(-3., 0.),
        Mobility::Moving,
    );
    scene
        .set_instance_deformation(&queue, deforming, &[Mat4::IDENTITY], &[])
        .unwrap();
    let eye = Vec3::Z * 5.;
    let build = |scene: &mut Scene, form| {
        let before = crate::counters::snapshot();
        let stats = build_in(gpu, scene, eye, form);
        let counted = crate::counters::snapshot().since(&before);
        (stats, [counted.blas_builds, counted.deformed_blas_builds])
    };
    let stats = |hardware, portable| RayTracingStats {
        hardware,
        portable,
        left_out: 0,
    };
    // The masked model has a BLAS and its instance joins the TLAS.
    assert_eq!(
        build(&mut scene, RayQueryForm::Candidates),
        (stats(3, 0), [2, 1])
    );
    assert_eq!(
        build(&mut scene, RayQueryForm::Candidates),
        (stats(3, 0), [0, 0])
    );
    // Masked now, the edited model's BLAS and the deforming instance's are
    // built again at once, the model's outside the budget: a fresh model
    // nearer the eye spends all of it, so a second fresh one waits.
    let mut vertices = triangles(Vec3::ZERO, 1);
    let corner = vertices.vertices[0];
    vertices
        .vertices
        .resize(super::blas::MOST_VERTICES_PER_FRAME as usize, corner);
    let large = scene
        .add_asset(&device, &queue, asset(vec![vertices]))
        .unwrap()
        .model;
    let small = scene
        .add_asset(&device, &queue, asset(vec![triangles(Vec3::ZERO, 1)]))
        .unwrap()
        .model;
    place(gpu, &mut scene, large, at(0., 1.), Mobility::Static);
    place(gpu, &mut scene, small, at(0., -20.), Mobility::Static);
    let mask = crate::AlphaMode::Mask { cutoff: 0.5 };
    realpha(&queue, &mut scene, edited.materials[0], mask);
    realpha(&queue, &mut scene, skinned.materials[0], mask);
    assert_eq!(
        build(&mut scene, RayQueryForm::Candidates),
        (stats(4, 1), [2, 1])
    );
    assert_eq!(
        build(&mut scene, RayQueryForm::Candidates),
        (stats(5, 0), [1, 0])
    );
    // Opaque again, the edited model's BLAS is built again.
    realpha(
        &queue,
        &mut scene,
        edited.materials[0],
        crate::AlphaMode::Opaque,
    );
    assert_eq!(
        build(&mut scene, RayQueryForm::Candidates),
        (stats(5, 0), [1, 0])
    );
    realpha(&queue, &mut scene, edited.materials[0], mask);
    assert_eq!(
        build(&mut scene, RayQueryForm::Candidates),
        (stats(5, 0), [1, 0])
    );
    // Fallen back to the baseline form, the masked models leave the TLAS
    // for the portable BVHs, the deforming instance's BLAS is made again
    // with every geometry opaque, and the opaque models keep theirs.
    assert_eq!(
        build(&mut scene, RayQueryForm::Baseline),
        (stats(3, 2), [0, 1])
    );
    assert_eq!(scene.diagnostic_resources().blases, 3);
    bind_tlas(gpu, &scene);
    device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
    let error = pollster::block_on(validation.pop());
    assert!(error.is_none(), "{error:?}");
}

// A model re-pended for its opacity keeps its geometry, so its BLAS's
// compaction entry from before must not stand for its new BLAS. Plausible
// defect: the older entry left in Bevy's queue beside the new BLAS's,
// never looked at because a frame's compaction budget ran out before it,
// so both prepare the new BLAS's compaction, which wgpu refuses the second
// time (`CompactionPreparingAlready`, a validation error), or the older
// entry outlives the BLAS it was queued for. The oracles are wgpu's
// validation and the architecture's rule that each built BLAS is compacted
// once, counted through `counters`, with the device polled after each
// frame so that a prepared compaction is ready by the next.
#[test]
fn a_re_pended_model_is_compacted_once() {
    let Some((device, queue)) = test_support::ray_tracing_device(|limits| limits) else {
        return;
    };
    let gpu = (&device, &queue);
    let validation = device.push_error_scope(wgpu::ErrorFilter::Validation);
    let mut scene = Scene::new(&device, &queue);
    // A model of the budget's vertices: its compaction spends a frame's
    // compaction budget.
    let mut vertices = triangles(Vec3::ZERO, 1);
    let corner = vertices.vertices[0];
    vertices
        .vertices
        .resize(super::blas::MOST_VERTICES_PER_FRAME as usize, corner);
    let large = scene
        .add_asset(&device, &queue, asset(vec![vertices]))
        .unwrap()
        .model;
    place(gpu, &mut scene, large, Mat4::IDENTITY, Mobility::Static);
    let eye = Vec3::Z * 5.;
    let frame = |scene: &mut Scene| {
        let before = crate::counters::snapshot();
        build_in(gpu, scene, eye, RayQueryForm::Candidates);
        device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
        let counted = crate::counters::snapshot().since(&before);
        [counted.blas_builds, counted.blas_compactions]
    };
    assert_eq!(frame(&mut scene), [1, 0]);
    // The large model's compaction is prepared, and the edited model's BLAS
    // is built and queued behind it.
    let edited = scene
        .add_asset(&device, &queue, asset(vec![triangles(Vec3::ZERO, 1)]))
        .unwrap();
    let behind = Mat4::from_translation(Vec3::Z * -2.);
    place(gpu, &mut scene, edited.model, behind, Mobility::Static);
    assert_eq!(frame(&mut scene), [1, 0]);
    // Masked now, the edited model is re-pended in a frame whose
    // compaction budget the large model spends, so its first entry is never
    // looked at.
    let mask = crate::AlphaMode::Mask { cutoff: 0.5 };
    realpha(&queue, &mut scene, edited.materials[0], mask);
    assert_eq!(frame(&mut scene), [1, 1]);
    // Its new BLAS is prepared and compacted once.
    let mut compactions = 0;
    for _ in 0..4 {
        let [builds, compacted] = frame(&mut scene);
        assert_eq!(builds, 0);
        compactions += compacted;
    }
    assert_eq!(compactions, 1);
    bind_tlas(gpu, &scene);
    device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
    let error = pollster::block_on(validation.pop());
    assert!(error.is_none(), "{error:?}");
}

/// One frame of `scene` through `renderer` into `output`, submitted and
/// finished unless `abandoned`.
fn frame(
    (device, queue): (&wgpu::Device, &wgpu::Queue),
    (renderer, scene): (&mut crate::Renderer, &mut Scene),
    settings: &crate::settings::Settings,
    output: &wgpu::TextureView,
    abandoned: bool,
) -> RayTracingStats {
    let eye = Vec3::new(0., 1., 6.);
    let input = crate::FrameInput::new(crate::Camera {
        view: glam::camera::rh::view::look_at_mat4(eye, Vec3::ZERO, Vec3::Y),
        projection: crate::perspective(1., 1., 0.1),
        eye,
    });
    let mut encoder = device.create_command_encoder(&Default::default());
    renderer.render(
        device,
        queue,
        &mut encoder,
        scene,
        &input,
        settings,
        output,
        None,
    );
    if !abandoned {
        queue.submit([encoder.finish()]);
        renderer.finish_frame(scene);
        device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
    }
    renderer.ray_tracing_stats()
}

// The structures through the renderer's frames, on frames that trace
// world-space rays. Plausible defects: builds committed for an abandoned
// frame (wgpu's validation then refuses the next frame's TLAS, which names
// a BLAS never built), or an abandoned frame's builds recorded by a later
// frame that traces nothing, against the ray source as it then is; a
// deforming instance's BLAS not rebuilt when its deformation changes, or
// rebuilt when it does not; a model's BLAS built again every frame, or
// compacted never or more than once (Bevy's queue compacts each once);
// the structures kept with the setting off, or not built again when it
// is turned on. The oracles are wgpu's validation and the architecture's
// rules, counted through `counters`. Whether the builds follow the deform
// pass shows only in what rays hit, which the hardware trace's oracle test
// checks.
#[test]
fn frames_build_the_structures_after_their_deformations() {
    let Some((device, queue)) = test_support::ray_tracing_device(|limits| limits) else {
        return;
    };
    let gpu = (&device, &queue);
    let validation = device.push_error_scope(wgpu::ErrorFilter::Validation);
    let mut scene = Scene::new(&device, &queue);
    let opaque = scene
        .add_asset(&device, &queue, asset(vec![triangles(Vec3::ZERO, 2)]))
        .unwrap()
        .model;
    place(gpu, &mut scene, opaque, Mat4::IDENTITY, Mobility::Static);
    let masked = scene
        .add_asset(
            &device,
            &queue,
            test_support::masked(test_support::cube(), 0.5),
        )
        .unwrap()
        .model;
    place(
        gpu,
        &mut scene,
        masked,
        Mat4::from_translation(Vec3::X * 3.),
        Mobility::Static,
    );
    // One skinned triangle, whole on its one joint.
    let mut skinned = triangles(Vec3::ZERO, 1);
    skinned.deformation.influences = vec![
        crate::deformation::Influence {
            joints: [0; 4],
            weights: [1., 0., 0., 0.],
        };
        3
    ];
    let skinned = scene
        .add_asset(&device, &queue, asset(vec![skinned]))
        .unwrap()
        .model;
    let deforming = place(
        gpu,
        &mut scene,
        skinned,
        Mat4::from_translation(Vec3::X * -3.),
        Mobility::Moving,
    );
    let pose = |scene: &mut Scene, lift: f32| {
        scene
            .set_instance_deformation(
                &queue,
                deforming,
                &[Mat4::from_translation(Vec3::Y * lift)],
                &[],
            )
            .unwrap();
    };
    let mut settings = crate::settings::Settings {
        screen_space_reflections: crate::settings::ScreenSpaceReflections::Half,
        world_space_reflections: crate::settings::WorldSpaceReflections::Moving,
        hardware_ray_tracing: true,
        ..Default::default()
    };
    let size = [64, 64];
    let mut renderer = crate::Renderer::for_test(&device, &queue, size, &settings);
    let output = crate::view::targets::target(
        &device,
        "acceleration structure frames",
        size,
        crate::shading::gbuffer::COLOR,
    );
    let frame = |renderer: &mut crate::Renderer,
                 scene: &mut Scene,
                 settings: &crate::settings::Settings,
                 abandoned: bool| {
        let before = crate::counters::snapshot();
        let stats = frame(gpu, (renderer, scene), settings, &output, abandoned);
        (stats, crate::counters::snapshot().since(&before))
    };
    let counts = |counted: &crate::counters::Counters| {
        [
            counted.blas_builds,
            counted.deformed_blas_builds,
            counted.tlas_builds,
        ]
    };
    // Under the form the renderer takes on this device's backend: the
    // baseline holds the opaque model's BLAS and the deforming instance's,
    // the masked model a predicate instance on the portable BVHs; the
    // candidate form holds the masked model's BLAS too.
    let (models, held) = match RayQueryForm::of_backend(device.adapter_info().backend) {
        RayQueryForm::Baseline => (
            1,
            RayTracingStats {
                hardware: 2,
                portable: 1,
                left_out: 0,
            },
        ),
        RayQueryForm::Candidates => (
            2,
            RayTracingStats {
                hardware: 3,
                portable: 0,
                left_out: 0,
            },
        ),
    };
    // The first frame builds the models' BLASes, the deforming instance's
    // and the TLAS.
    pose(&mut scene, 0.5);
    let (stats, counted) = frame(&mut renderer, &mut scene, &settings, false);
    assert_eq!(stats, held);
    assert_eq!(counts(&counted), [models, 1, 1]);
    // Each model's BLAS is compacted once, in whichever later frame finds
    // it ready.
    let mut compactions = 0;
    // An abandoned frame commits nothing, and a frame that traces no rays
    // records nothing of it: the next traced frame records its
    // deformation's build again.
    pose(&mut scene, 0.25);
    let (_, abandoned) = frame(&mut renderer, &mut scene, &settings, true);
    assert_eq!(counts(&abandoned), [0, 1, 1]);
    compactions += abandoned.blas_compactions;
    let untraced = crate::settings::Settings {
        world_space_reflections: crate::settings::WorldSpaceReflections::Off,
        ..settings
    };
    let (stats, counted) = frame(&mut renderer, &mut scene, &untraced, false);
    assert_eq!(stats, RayTracingStats::default());
    assert_eq!(counts(&counted), [0, 0, 0]);
    compactions += counted.blas_compactions;
    let (stats, counted) = frame(&mut renderer, &mut scene, &settings, false);
    assert_eq!(stats, held);
    assert_eq!(counts(&counted), [0, 1, 1]);
    compactions += counted.blas_compactions;
    // A deformation unchanged since the last submitted frame keeps its
    // BLAS.
    for _ in 0..6 {
        let (stats, counted) = frame(&mut renderer, &mut scene, &settings, false);
        assert_eq!(stats, held);
        assert_eq!(counts(&counted), [0, 0, 1]);
        compactions += counted.blas_compactions;
    }
    assert_eq!(compactions, models);
    // Off frees the structures; on builds them again.
    settings.hardware_ray_tracing = false;
    let (stats, counted) = frame(&mut renderer, &mut scene, &settings, false);
    assert_eq!(stats, RayTracingStats::default());
    assert_eq!(counts(&counted), [0, 0, 0]);
    assert!(scene.acceleration_structures().is_none());
    assert_eq!(scene.diagnostic_resources().blases, 0);
    settings.hardware_ray_tracing = true;
    let (stats, counted) = frame(&mut renderer, &mut scene, &settings, false);
    assert_eq!(stats, held);
    assert_eq!(counts(&counted), [models, 1, 1]);
    bind_tlas(gpu, &scene);
    device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
    let error = pollster::block_on(validation.pop());
    assert!(error.is_none(), "{error:?}");
}

// What a game is told of the hardware path, on a device without ray queries
// and on one with them. Plausible defects: the hardware path reported in
// effect on a device that has no ray queries, which then traces the
// portable BVHs, or no reason given; or a reason given where it runs. The
// oracle is the device each frame ran on: one requested without the
// feature, and one with it.
#[test]
fn the_renderer_reports_whether_the_hardware_path_traces() {
    let settings = crate::settings::Settings {
        screen_space_reflections: crate::settings::ScreenSpaceReflections::Half,
        world_space_reflections: crate::settings::WorldSpaceReflections::Moving,
        hardware_ray_tracing: true,
        ..Default::default()
    };
    let devices = [
        test_support::device(),
        test_support::ray_tracing_device(|limits| limits),
    ];
    for (ray_queries, device) in [false, true].into_iter().zip(devices) {
        let Some((device, queue)) = device else {
            return;
        };
        let gpu = (&device, &queue);
        let mut scene = Scene::new(&device, &queue);
        let model = scene
            .add_asset(&device, &queue, asset(vec![triangles(Vec3::ZERO, 1)]))
            .unwrap()
            .model;
        place(gpu, &mut scene, model, Mat4::IDENTITY, Mobility::Static);
        let size = [16, 16];
        let mut renderer = crate::Renderer::for_test(&device, &queue, size, &settings);
        let output = crate::view::targets::target(
            &device,
            "ray tracing reports",
            size,
            crate::shading::gbuffer::COLOR,
        );
        let stats = frame(gpu, (&mut renderer, &mut scene), &settings, &output, false);
        assert_eq!(renderer.ray_tracing_in_effect(&settings), ray_queries);
        assert_eq!(renderer.ray_tracing_error().is_none(), ray_queries);
        assert_eq!(stats.hardware, u32::from(ray_queries));
        let off = crate::settings::Settings {
            hardware_ray_tracing: false,
            ..settings
        };
        frame(gpu, (&mut renderer, &mut scene), &off, &output, false);
        assert!(!renderer.ray_tracing_in_effect(&off));
        assert!(
            renderer.ray_tracing_error().is_none(),
            "nothing asked for it"
        );
    }
}