sgl-3d 0.9.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
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
//! Instances: each one's state, mobility, ambient cube, private motion
//! history and deformation, its object record and its ray entry, with the
//! `Scene` operations that add, read, change and remove them.
use super::deformation::InstanceDeformation;
use super::models::Model;
use super::objects::{Objects, ShaderData};
use super::origin::translated;
use super::rays::instances::RayInstances;
use super::shadow_clusters::PosedClusters;
use super::slots::Slots;
use super::static_edits::posed_bounds;
use super::{Scene, SceneError};
use crate::content::identity::{Identity, InstanceId, ModelId};
use crate::content::instance::{InstanceState, Mobility};
use crate::shading::uniforms::{
    OBJECT_CAPTURE_VISIBLE, OBJECT_DEFORMING, OBJECT_STATIC, OBJECT_VISIBLE, ObjectUniform,
};
use crate::static_lighting::AmbientCube;
use glam::{Mat4, Vec3};

pub(crate) struct Instance {
    pub state: InstanceState,
    pub mobility: Mobility,
    pub baked_irradiance: AmbientCube,
    /// A static instance's caster clusters' and groups' world bounds, in
    /// its model's mesh order, which local-light shadow faces test; empty
    /// for a moving instance, which they test whole.
    pub casters: Vec<PosedClusters>,
    /// A moving instance's pose and model in the last submitted frame, when
    /// it was visible in it.
    submitted: Option<(Mat4, ModelId)>,
    /// Its written record's motion is from before the last submitted frame.
    stale: bool,
    /// Its pose of its model's deformation, when the model deforms.
    pub deformation: Option<InstanceDeformation>,
    /// The data its materials' shaders read (`Scene::set_instance_shader_data`),
    /// and as it was in the last submitted frame, none before it was in one.
    pub shader_data: [f32; 4],
    submitted_shader_data: Option<[f32; 4]>,
    /// Its written shader data's last submitted frame's is from before the
    /// last submitted frame.
    shader_stale: bool,
    /// What the frame being rendered draws of it, which a finished frame
    /// commits; none when it was added since the frame began.
    rendered: Option<Shown>,
}

/// What a frame draws of an instance (`Scene::begin_frame`).
#[derive(Clone, Copy)]
struct Shown {
    pose: Mat4,
    model: ModelId,
    visible: bool,
    shader_data: [f32; 4],
}

impl Instance {
    fn new(
        state: InstanceState,
        mobility: Mobility,
        model: &Model,
        deformation: Option<InstanceDeformation>,
    ) -> Self {
        let mut instance = Self {
            state,
            mobility,
            baked_irradiance: AmbientCube::default(),
            casters: Vec::new(),
            submitted: None,
            stale: false,
            deformation,
            shader_data: [0.; 4],
            submitted_shader_data: None,
            shader_stale: false,
            rendered: None,
        };
        instance.pose_casters(model);
        instance
    }

    /// Places a static instance's caster bounds at its pose on `model`, its
    /// model's current geometry.
    fn pose_casters(&mut self, model: &Model) {
        if self.mobility == Mobility::Static {
            self.casters = model.caster_bounds(self.state.pose);
        }
    }

    /// Its object record's bits: static, `visible`, `capture_visible` and
    /// deforming, which the GPU draw lists' cull reads.
    pub fn flags(&self) -> u32 {
        let bit = |on: bool, bit: u32| if on { bit } else { 0 };
        bit(self.mobility == Mobility::Static, OBJECT_STATIC)
            | bit(self.state.visible, OBJECT_VISIBLE)
            | bit(self.state.capture_visible, OBJECT_CAPTURE_VISIBLE)
            | bit(self.deformation.is_some(), OBJECT_DEFORMING)
    }

    /// Whether the next frame measures a moving instance's motion from a
    /// pose of `model`, however the frame being rendered ends: the last
    /// finished frame showed it with `model`, and the frame being rendered,
    /// if one is, draws it shown with `model` too, since finishing that frame
    /// makes its record the pose motion is measured from (F-13).
    fn last_pose_applies(&self, model: ModelId) -> bool {
        self.mobility == Mobility::Moving
            && self
                .submitted
                .is_some_and(|(_, submitted)| submitted == model)
            && self
                .rendered
                .is_none_or(|shown| shown.visible && shown.model == model)
    }

    /// Whether it names `model` now and is visible or has a submitted
    /// record (a moving instance visible in the last finished frame), or
    /// the frame being rendered showed it with `model`. The submitted
    /// record's model is not compared: a swap that made it differ already
    /// raised the signal, which only a finished frame that began after the
    /// swap, and so drew the new model, retires.
    fn shows(&self, model: ModelId) -> bool {
        (self.state.model == model && (self.state.visible || self.submitted.is_some()))
            || self
                .rendered
                .is_some_and(|shown| shown.visible && shown.model == model)
    }

    /// The pose motion is measured from: a moving instance's pose in the
    /// last submitted frame while that pose applies, else its current pose,
    /// which writes no motion.
    fn previous_pose(&self) -> Mat4 {
        match (self.mobility, self.submitted) {
            (Mobility::Moving, Some((pose, model))) if model == self.state.model => pose,
            _ => self.state.pose,
        }
    }

    /// Its object record.
    fn record(&self) -> ObjectUniform {
        let [deformed_positions, previous_positions, deformed_normals] = self
            .deformation
            .as_ref()
            .map_or([0; 3], |deformation| deformation.record);
        ObjectUniform {
            model: self.state.pose.to_cols_array_2d(),
            previous_model: self.previous_pose().to_cols_array_2d(),
            baked_irradiance: self.baked_irradiance.packed(),
            flags: self.flags(),
            deformed_positions,
            previous_positions,
            deformed_normals,
        }
    }

    /// Its shader data, this frame's and the last submitted frame's, from
    /// which its shaders' motion is measured: this frame's before it was in
    /// one.
    fn shader_record(&self) -> ShaderData {
        [
            self.shader_data,
            self.submitted_shader_data.unwrap_or(self.shader_data),
        ]
    }

    /// Its bounds in its model's space: as deformed, when it deforms.
    pub fn bounds(&self, model: &Model) -> [Vec3; 2] {
        self.deformation
            .as_ref()
            .map_or(model.bounds, |deformation| deformation.bounds)
    }

    /// Mesh `mesh`'s bounds in its model's space as the instance shows it.
    pub fn mesh_bounds(&self, model: &Model, mesh: usize) -> Option<[Vec3; 2]> {
        match &self.deformation {
            Some(deformation) => Some(deformation.mesh_bounds[mesh]),
            None => model.meshes[mesh].ranges.bounds(),
        }
    }
}

/// A pose a record and the ray source can take.
fn validate_pose(pose: Mat4) -> Result<(), SceneError> {
    if !pose.is_finite() || !pose.inverse().is_finite() {
        return Err(SceneError::InvalidPose);
    }
    Ok(())
}

pub(crate) struct Instances {
    pub slots: Slots<InstanceId, Instance>,
    pub objects: Objects,
    /// Live static and moving instances.
    counts: [usize; 2],
    /// Changes that no motion vector describes (M-9), counted as raised:
    /// appearances, departures, showing or hiding, model and geometry
    /// replacement, a static instance moved, a moving one moved where its
    /// last submitted pose does not apply, and material edits that change
    /// what their users draw (`Scene::set_material`). A moving instance's
    /// move from its submitted pose, deformation and vertex functions write
    /// motion and do not raise it. The count the frame being rendered saw,
    /// and the count the last finished frame saw: a finished frame retires
    /// what was raised before it began.
    rigid: [u64; 3],
    /// The instances whose shader data was set since the last submitted
    /// frame (`set_shader_data`), repeats and removed ones included, and
    /// how many of them the frame being rendered saw.
    shader_edits: Vec<InstanceId>,
    shader_edits_rendered: usize,
}

/// `Instances::rigid`'s counts.
const RAISED: usize = 0;
const RENDERED: usize = 1;
const COMMITTED: usize = 2;

/// Raises the rigid-change signal `rigid` (`Instances::rigid`) when
/// `changed`.
fn raise_rigid(rigid: &mut [u64; 3], changed: bool) {
    if changed {
        rigid[RAISED] = rigid[RAISED].wrapping_add(1);
    }
}

/// `Instances::counts`' index of a mobility.
fn kind(mobility: Mobility) -> usize {
    match mobility {
        Mobility::Static => 0,
        Mobility::Moving => 1,
    }
}

impl Instances {
    pub fn new(device: &wgpu::Device) -> Self {
        Self {
            slots: Slots::default(),
            objects: Objects::new(device),
            counts: [0; 2],
            rigid: [0; 3],
            shader_edits: Vec::new(),
            shader_edits_rendered: 0,
        }
    }

    pub fn get(&self, id: InstanceId) -> Result<&Instance, SceneError> {
        self.slots.get(id).ok_or(SceneError::UnknownInstance)
    }

    fn write(&self, queue: &wgpu::Queue, id: InstanceId) {
        let instance = self.slots.get(id).expect("a live instance");
        self.objects.write(queue, id.index(), &instance.record());
    }

    fn write_shader_data(&self, queue: &wgpu::Queue, id: InstanceId) {
        let instance = self.slots.get(id).expect("a live instance");
        self.objects
            .write_shader_data(queue, id.index(), &instance.shader_record());
    }

    /// Sets instance `id`'s shader data and writes it.
    pub fn set_shader_data(&mut self, queue: &wgpu::Queue, id: InstanceId, data: [f32; 4]) {
        self.slots.get_mut(id).expect("a live instance").shader_data = data;
        self.shader_edits.push(id);
        self.write_shader_data(queue, id);
    }

    /// The live instances whose shader data differs from the last
    /// submitted frame's, each once or more; none that was in no submitted
    /// frame, which has no last submitted data.
    pub fn shader_data_edited(&self) -> impl Iterator<Item = &Instance> + '_ {
        self.shader_edits
            .iter()
            .filter_map(|&id| self.slots.get(id))
            .filter(|instance| {
                instance
                    .submitted_shader_data
                    .is_some_and(|submitted| submitted != instance.shader_data)
            })
    }

    /// Geometry replacement, or a material edit that changes what `model`'s
    /// meshes draw, can uncover old pixels without any pose motion.
    /// Include prior visible users even when the new geometry/position is
    /// culled: those the last finished frame or the frame being rendered
    /// showed, which the next frame follows.
    pub fn geometry_changed(&mut self, model: ModelId) {
        let changed = self.slots.iter().any(|(_, instance)| instance.shows(model));
        raise_rigid(&mut self.rigid, changed);
    }

    /// Rewrites the object records of `model`'s instances.
    pub fn write_of_model(&self, queue: &wgpu::Queue, model: ModelId) {
        for (id, instance) in self.slots.iter() {
            if instance.state.model == model {
                self.objects.write(queue, id.index(), &instance.record());
            }
        }
    }

    /// Room for `count` records, rewriting every record and every instance's
    /// shader data when the buffers grow.
    fn reserve(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        count: usize,
    ) -> Result<(), SceneError> {
        if self.objects.reserve(device, count)? {
            for (id, instance) in self.slots.iter() {
                self.objects.write(queue, id.index(), &instance.record());
                self.objects
                    .write_shader_data(queue, id.index(), &instance.shader_record());
            }
        }
        Ok(())
    }

    /// Places the caster bounds of the static instances of `model` (`id`)
    /// after its geometry was replaced.
    pub fn pose_casters(&mut self, model: &Model, id: ModelId) {
        for (_, instance) in self.slots.iter_mut() {
            if instance.state.model == id {
                instance.pose_casters(model);
            }
        }
    }

    /// The poses of the static instances of `model`.
    pub fn static_poses(&self, model: ModelId) -> impl Iterator<Item = Mat4> + '_ {
        self.slots
            .iter()
            .filter(move |(_, instance)| {
                instance.mobility == Mobility::Static && instance.state.model == model
            })
            .map(|(_, instance)| instance.state.pose)
    }

    /// Moves the render origin by `by` (`Scene::move_origin`): each
    /// instance's pose and the pose its motion is measured from, so a
    /// static instance still writes no motion and a moving one the same, a
    /// static instance's caster bounds, every object record in one write,
    /// and each rigid instance's ray entry. The write zeroes the records of
    /// removed indices below the highest live one, which no draw or ray
    /// reads until an instance reuses the index and writes its own.
    pub fn move_origin(
        &mut self,
        queue: &wgpu::Queue,
        by: Vec3,
        models: &super::models::Models,
        rays: &mut RayInstances,
    ) {
        let mut records = Vec::new();
        for (id, instance) in self.slots.iter_mut() {
            instance.state.pose = translated(instance.state.pose, by);
            if let Some((pose, _)) = &mut instance.submitted {
                *pose = translated(*pose, by);
            }
            if let Some(shown) = &mut instance.rendered {
                shown.pose = translated(shown.pose, by);
            }
            let model = models
                .slots
                .get(instance.state.model)
                .expect("an instance's model lives");
            instance.pose_casters(model);
            rays.set(id.index(), model.ray, instance.state.pose);
            if records.len() <= id.index() {
                records.resize(id.index() + 1, bytemuck::Zeroable::zeroed());
            }
            records[id.index()] = instance.record();
        }
        self.objects.write_all(queue, &records);
    }

    /// Commits a submitted frame, as it drew each instance it drew
    /// (`prepare_frame`): a moving instance's pose and deformation become
    /// the ones its motion is measured from while it was visible, and its
    /// shader data the one its shaders' motion is. The rigid changes and
    /// shader-data edits made before the frame began are retired. An
    /// instance added since commits nothing, and edits made since stay for
    /// the next frame.
    pub fn finish_frame(&mut self) {
        self.rigid[COMMITTED] = self.rigid[RENDERED];
        self.shader_edits.drain(..self.shader_edits_rendered);
        self.shader_edits_rendered = 0;
        for (_, instance) in self.slots.iter_mut() {
            let Some(shown) = instance.rendered.take() else {
                continue;
            };
            // What the written records hold as previous, which a later
            // write keeps current: a rewrite is due where it changes.
            let shader_on_gpu = instance
                .submitted_shader_data
                .unwrap_or(instance.shader_data);
            instance.shader_stale |= shader_on_gpu != shown.shader_data;
            instance.submitted_shader_data = Some(shown.shader_data);
            if let Some(deformation) = &mut instance.deformation {
                deformation.finish(shown.visible);
            }
            if instance.mobility == Mobility::Moving {
                let on_gpu = instance.previous_pose();
                instance.submitted = shown.visible.then_some((shown.pose, shown.model));
                instance.stale |= instance.previous_pose() != on_gpu;
            }
        }
    }

    /// Begins a frame: rewrites the records of moving instances not posed
    /// since the last submitted frame, whose motion it ended, and of
    /// deforming instances, whose deformed vertices this frame shows, and
    /// the shader data of instances whose data the last submitted frame
    /// changed, replaces `work` with the deformations the frame writes,
    /// and records what the frame draws of each instance, with the rigid
    /// changes and shader-data edits made so far, for `finish_frame`.
    pub fn prepare_frame(
        &mut self,
        queue: &wgpu::Queue,
        models: &super::models::Models,
        work: &mut Vec<crate::shading::deformation::DeformDispatch>,
    ) {
        work.clear();
        self.rigid[RENDERED] = self.rigid[RAISED];
        self.shader_edits_rendered = self.shader_edits.len();
        for (id, instance) in self.slots.iter_mut() {
            let deforms = if let Some(deformation) = &mut instance.deformation {
                let model = models.slots.get(instance.state.model);
                let model = model.and_then(|model| model.deformation.as_ref());
                deformation.prepare(model.expect("a deforming instance's model deforms"), work);
                true
            } else {
                false
            };
            if instance.stale || deforms {
                instance.stale = false;
                self.objects.write(queue, id.index(), &instance.record());
            }
            if instance.shader_stale {
                instance.shader_stale = false;
                self.objects
                    .write_shader_data(queue, id.index(), &instance.shader_record());
            }
            instance.rendered = Some(Shown {
                pose: instance.state.pose,
                model: instance.state.model,
                visible: instance.state.visible,
                shader_data: instance.shader_data,
            });
        }
    }
}

impl Scene {
    /// Places a model. A static instance is expected to stay as added; a
    /// moving one to be posed every frame. Mobility is fixed for its life.
    /// An instance of a deforming model moves, and starts at its bind pose.
    pub fn add_instance(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        state: InstanceState,
        mobility: Mobility,
    ) -> Result<InstanceId, SceneError> {
        self.edited();
        let deforms = self.models.get(state.model)?.deformation.is_some();
        validate_pose(state.pose)?;
        if deforms && mobility == Mobility::Static {
            return Err(SceneError::DeformingModel);
        }
        let count = self.instances.slots.next_index() + 1;
        let kind_count = self.instances.counts[kind(mobility)] + 1;
        let reserved = self
            .ray_instances
            .reserve(device, queue, &mut self.rays, count, mobility, kind_count)
            .and_then(|_| self.instances.reserve(device, queue, count))
            .and_then(|_| {
                let model = self.models.get(state.model)?;
                model
                    .deformation
                    .as_ref()
                    .map(|model| InstanceDeformation::add(device, queue, &mut self.rays, model))
                    .transpose()
            });
        self.refresh_scene_group(device);
        let deformation = reserved?;
        let index = self.instances.slots.next_index();
        let meshes = self.candidate_meshes(state.model, self.models.get(state.model)?);
        let deformed = deformation
            .as_ref()
            .map(|deformation| deformation.mesh_bounds.as_slice());
        let mirrored = state.pose.determinant() < 0.;
        if let Err(error) = self
            .candidates
            .place(index, (state.model, &meshes), mirrored, deformed)
        {
            if let Some(deformation) = deformation {
                deformation.free(&mut self.rays);
            }
            return Err(error);
        }
        let shaded = self.shaded_bounds(self.models.get(state.model)?);
        let model = self.models.get_mut(state.model)?;
        model.instances += 1;
        if mobility == Mobility::Static {
            self.static_edits.record(posed_bounds(shaded, state.pose));
        }
        let id = self
            .instances
            .slots
            .insert(Instance::new(state, mobility, model, deformation));
        self.instances.counts[kind(mobility)] += 1;
        raise_rigid(&mut self.instances.rigid, state.visible);
        self.write_instance(queue, id);
        // Its index may be a removed instance's.
        self.instances.write_shader_data(queue, id);
        Ok(id)
    }

    /// Writes instance `id`'s object record and its ray entry, which the
    /// hardware path reads for a deforming instance too.
    fn write_instance(&mut self, queue: &wgpu::Queue, id: InstanceId) {
        self.instances.write(queue, id);
        let instance = self.instances.slots.get(id).expect("a live instance");
        let (ray, pose) = (
            self.drawn_model(instance.state.model).ray,
            instance.state.pose,
        );
        self.ray_instances.set(id.index(), ray, pose);
    }

    /// Changes without a motion vector, visible now or before their
    /// departure (M-9). Deliberately conservative across frustum and
    /// occlusion culling: a culled new state can still expose history at
    /// the old one. A finished frame clears what was raised before it
    /// began.
    pub(crate) fn rigid_objects_changed(&self) -> bool {
        self.instances.rigid[RAISED] != self.instances.rigid[COMMITTED]
    }

    /// An instance's current state.
    pub fn instance(&self, id: InstanceId) -> Result<&InstanceState, SceneError> {
        Ok(&self.instances.get(id)?.state)
    }

    /// Replaces an instance's state. A state naming another model clears its
    /// ambient cube, and a moving instance then has no motion until a frame
    /// shows it. A deforming instance keeps its model, as does one of a
    /// rigid model with a deforming one: remove and add it instead.
    pub fn set_instance(
        &mut self,
        queue: &wgpu::Queue,
        id: InstanceId,
        state: InstanceState,
    ) -> Result<(), SceneError> {
        let previous = self.instances.get(id)?.state.model;
        let deforms = self.models.get(state.model)?.deformation.is_some();
        // A game may set every pose each frame: only a change rays see is
        // an edit, a deforming instance's only while the hardware path
        // traces it.
        let old = self.instances.get(id)?.state;
        if old != state && (old.capture_visible || state.capture_visible) {
            if deforms {
                self.deformation_edited();
            } else {
                self.edited();
            }
        }
        validate_pose(state.pose)?;
        if previous != state.model && (deforms || self.instances.get(id)?.deformation.is_some()) {
            return Err(SceneError::DeformingModel);
        }
        // Its candidates name its model's meshes and, by whether its pose
        // mirrors, their sets.
        let mirrored = |pose: glam::Mat4| pose.determinant() < 0.;
        if previous != state.model || mirrored(old.pose) != mirrored(state.pose) {
            let meshes = self.candidate_meshes(state.model, self.models.get(state.model)?);
            let deformed = self
                .instances
                .get(id)?
                .deformation
                .as_ref()
                .map(|deformation| deformation.mesh_bounds.as_slice());
            self.candidates.place(
                id.index(),
                (state.model, &meshes),
                mirrored(state.pose),
                deformed,
            )?;
        }
        if previous != state.model {
            self.models.get_mut(previous)?.instances -= 1;
            self.models.get_mut(state.model)?.instances += 1;
        }
        let before = self.shaded_bounds(self.models.get(previous)?);
        let after = self.shaded_bounds(self.models.get(state.model)?);
        let instance = self.instances.slots.get_mut(id).unwrap();
        if previous != state.model {
            instance.baked_irradiance = AmbientCube::default();
        }
        if instance.mobility == Mobility::Static && instance.state != state {
            self.static_edits
                .record(posed_bounds(before, instance.state.pose));
            self.static_edits.record(posed_bounds(after, state.pose));
        }
        let placed = instance.state.pose != state.pose || previous != state.model;
        // A moving instance whose last submitted pose applies to the new
        // state writes its move as motion, which TAA follows per pixel; any
        // other change has no motion vector and re-arms the view (M-9).
        // Between a frame's submission and `finish_frame` that pose is the
        // frame's own record as much as the last finished frame's.
        let motion_describes_it = state.visible && instance.last_pose_applies(state.model);
        raise_rigid(
            &mut self.instances.rigid,
            (old.visible || state.visible)
                && (old.visible != state.visible || (placed && !motion_describes_it)),
        );
        instance.state = state;
        instance.stale = false;
        if placed {
            instance.pose_casters(self.models.get(state.model)?);
        }
        self.write_instance(queue, id);
        Ok(())
    }

    /// Removes an instance. Its index is reused under a new identity.
    pub fn remove_instance(&mut self, id: InstanceId) -> Result<(), SceneError> {
        self.edited();
        let mut instance = self
            .instances
            .slots
            .remove(id)
            .ok_or(SceneError::UnknownInstance)?;
        raise_rigid(
            &mut self.instances.rigid,
            instance.state.visible || instance.submitted.is_some(),
        );
        self.candidates.remove(id.index());
        if let Some(deformation) = instance.deformation.take() {
            deformation.free(&mut self.rays);
        }
        let shaded = self.shaded_bounds(self.drawn_model(instance.state.model));
        let model = self
            .models
            .get_mut(instance.state.model)
            .expect("an instance's model lives");
        model.instances -= 1;
        self.instances.counts[kind(instance.mobility)] -= 1;
        if instance.mobility == Mobility::Static {
            self.static_edits
                .record(posed_bounds(shaded, instance.state.pose));
        }
        Ok(())
    }

    /// Supplies a moving instance's interpolated baked field, in world axes.
    /// A state naming another model clears it. A static instance takes baked
    /// diffuse light from lightmap charts and the irradiance atlas instead,
    /// and is refused.
    /// Returns `SceneError::InvalidIrradiance` for any channel outside the
    /// finite `0..=65504` range, retaining the instance's previous cube.
    pub fn set_instance_baked_irradiance(
        &mut self,
        queue: &wgpu::Queue,
        id: InstanceId,
        cube: AmbientCube,
    ) -> Result<(), SceneError> {
        self.edited();
        let instance = self
            .instances
            .slots
            .get_mut(id)
            .ok_or(SceneError::UnknownInstance)?;
        if instance.mobility == Mobility::Static {
            return Err(SceneError::StaticInstance);
        }
        if !crate::static_lighting::valid_irradiance(&cube.irradiance) {
            return Err(SceneError::InvalidIrradiance);
        }
        instance.baked_irradiance = cube;
        self.instances
            .objects
            .write_baked_irradiance(queue, id.index(), cube);
        Ok(())
    }
}

#[cfg(all(test, not(target_arch = "wasm32")))]
mod temporal_recovery_tests {
    use super::*;

    // A hidden or removed object, or replaced geometry, can uncover
    // zero-motion background. Observe changes through real scene mutations,
    // rather than setting the temporal signal directly.
    #[test]
    fn rigid_recovery_tracks_departures_until_submission_and_ignores_unchanged_poses() {
        let Some((device, queue)) = crate::test_support::device() else {
            return;
        };
        let mut scene = Scene::new(&device, &queue);
        let model = scene
            .add_asset(&device, &queue, crate::test_support::cube())
            .unwrap()
            .model;
        let mut state = InstanceState {
            model,
            pose: Mat4::IDENTITY,
            visible: true,
            capture_visible: true,
        };
        let id = scene
            .add_instance(&device, &queue, state, Mobility::Moving)
            .unwrap();
        assert!(
            scene.rigid_objects_changed(),
            "appearance exposes new temporal content"
        );
        scene.test_frame(&device, &queue);
        scene.set_instance(&queue, id, state).unwrap();
        assert!(
            !scene.rigid_objects_changed(),
            "repeated game pose writes must not suppress stabilization"
        );
        scene
            .set_model(
                &device,
                &queue,
                model,
                crate::PreparedModel::new(Vec::new()).unwrap(),
            )
            .unwrap();
        assert!(
            scene.rigid_objects_changed(),
            "same-ID geometry removal uncovers history even though instance pose and identity are unchanged"
        );
        scene.test_frame(&device, &queue);
        state.visible = false;
        scene.set_instance(&queue, id, state).unwrap();
        assert!(
            scene.rigid_objects_changed(),
            "hiding a previously visible object is a departure"
        );
        scene.test_frame(&device, &queue);
        state.pose = Mat4::IDENTITY;
        scene.set_instance(&queue, id, state).unwrap();
        assert!(
            !scene.rigid_objects_changed(),
            "fully hidden rigid motion has no visible history"
        );
        state.visible = true;
        scene.set_instance(&queue, id, state).unwrap();
        scene.test_frame(&device, &queue);
        scene.remove_instance(id).unwrap();
        assert!(
            scene.rigid_objects_changed(),
            "removal must retain departure evidence after its slot is gone"
        );
        scene.test_frame(&device, &queue);
        assert!(
            !scene.rigid_objects_changed(),
            "only submission retires departure evidence"
        );
    }

    // Plausible defects: a moving instance's move, which its motion vectors
    // describe, re-arms the whole view (so a scene with anything moving never
    // rests); or a change that writes no motion vector does not. The
    // expected values are M-9's rule: a pose change of a moving instance
    // whose last submitted pose applies (visible in that frame and now, the
    // same model) leaves the signal down, wherever it moves; every change M-5
    // and M-4 give no motion (another model, hidden, shown after a hidden
    // frame, a hidden new instance shown and moved before its first
    // submitted frame, a static instance moved) raises it until a frame is
    // submitted.
    #[test]
    fn rigid_recovery_leaves_moves_with_motion_to_the_pixels() {
        let Some((device, queue)) = crate::test_support::device() else {
            return;
        };
        let mut scene = Scene::new(&device, &queue);
        let mut add_model = || {
            scene
                .add_asset(&device, &queue, crate::test_support::cube())
                .unwrap()
                .model
        };
        let (model, other) = (add_model(), add_model());
        let at = |x: f32| Mat4::from_translation(Vec3::new(x, 0., 0.));
        let shown = |model| InstanceState {
            model,
            pose: Mat4::IDENTITY,
            visible: true,
            capture_visible: true,
        };
        let moving = scene
            .add_instance(&device, &queue, shown(model), Mobility::Moving)
            .unwrap();
        let fixed = scene
            .add_instance(&device, &queue, shown(model), Mobility::Static)
            .unwrap();
        let mut state = InstanceState {
            pose: at(0.5),
            ..shown(model)
        };
        scene.test_frame(&device, &queue);
        let expect = |scene: &mut Scene, change: InstanceState, id, raised: bool, what: &str| {
            scene.set_instance(&queue, id, change).unwrap();
            assert_eq!(scene.rigid_objects_changed(), raised, "{what}");
            scene.test_frame(&device, &queue);
            assert!(
                !scene.rigid_objects_changed(),
                "{what}: only submission retires it"
            );
        };
        for (x, what) in [
            (0.5, "a moving instance moved from its submitted pose"),
            (1000., "a moving instance moved out of view"),
            (0.75, "a moving instance moved back into view"),
        ] {
            state.pose = at(x);
            expect(&mut scene, state, moving, false, what);
        }
        state.model = other;
        expect(
            &mut scene,
            state,
            moving,
            true,
            "a moving instance given another model",
        );
        state.pose = at(1.);
        expect(
            &mut scene,
            state,
            moving,
            false,
            "the next move of the other model",
        );
        state.visible = false;
        expect(&mut scene, state, moving, true, "a moving instance hidden");
        state = InstanceState {
            pose: at(2.),
            ..shown(other)
        };
        expect(
            &mut scene,
            state,
            moving,
            true,
            "a moving instance shown elsewhere after a hidden frame",
        );
        expect(
            &mut scene,
            InstanceState {
                pose: at(0.25),
                ..shown(model)
            },
            fixed,
            true,
            "a static instance moved",
        );
        let fresh = scene
            .add_instance(
                &device,
                &queue,
                InstanceState {
                    visible: false,
                    ..shown(model)
                },
                Mobility::Moving,
            )
            .unwrap();
        assert!(
            !scene.rigid_objects_changed(),
            "a hidden instance added shows nothing"
        );
        scene
            .set_instance(
                &queue,
                fresh,
                InstanceState {
                    pose: at(3.),
                    ..shown(model)
                },
            )
            .unwrap();
        assert!(
            scene.rigid_objects_changed(),
            "an instance with no submitted frame shown and moved"
        );
    }

    // Plausible defect: a material edit that adds or removes what its
    // users draw, with nothing moving, leaves the view-wide signal down, so
    // the camera at rest fades the change in over many frames. The expected
    // values are Frame item 11's rule: an edit raises the signal, until a
    // submitted frame, exactly when it changes what a visible instance's
    // meshes draw; shading alone, or a material nothing visible draws with,
    // does not.
    #[test]
    fn material_edits_that_change_what_is_drawn_rearm_until_submission() {
        use crate::{AlphaMode, MaterialShader, SurfaceMaterial};
        let Some((device, queue)) = crate::test_support::device() else {
            return;
        };
        let mut scene = Scene::new(&device, &queue);
        let shader = crate::test_support::add_test_shader(&mut scene);
        let mut material = |visible: bool| {
            let ids = scene
                .add_asset(&device, &queue, crate::test_support::cube())
                .unwrap();
            let state = InstanceState {
                visible,
                ..InstanceState::new(ids.model)
            };
            scene
                .add_instance(&device, &queue, state, Mobility::Moving)
                .unwrap();
            ids.materials[0]
        };
        let (shown, hidden) = (material(true), material(false));
        let base = scene.material(shown).unwrap();
        let masked = |cutoff| SurfaceMaterial {
            alpha: AlphaMode::Mask { cutoff },
            ..base
        };
        let blended = |receives_screen_space_reflections, keeps_specular| SurfaceMaterial {
            alpha: AlphaMode::Blend {
                receives_screen_space_reflections,
                keeps_specular,
            },
            ..base
        };
        let edits = [
            (
                "visibility group",
                base,
                SurfaceMaterial {
                    visibility_group: base.visibility_group ^ 2,
                    ..base
                },
                true,
            ),
            ("opaque to masked", base, masked(0.5), true),
            ("mask cutoff", masked(0.5), masked(0.75), true),
            (
                "masked base alpha",
                masked(0.5),
                SurfaceMaterial {
                    base: [base.base[0], base.base[1], base.base[2], 0.25],
                    ..masked(0.5)
                },
                true,
            ),
            ("opaque to blended", base, blended(false, false), true),
            (
                "masked to blended",
                masked(0.5),
                blended(false, false),
                true,
            ),
            (
                "transmissive",
                base,
                SurfaceMaterial {
                    transmission: 1.,
                    ..base
                },
                true,
            ),
            (
                "blended receiver",
                blended(false, false),
                blended(true, false),
                true,
            ),
            (
                "double-sided",
                base,
                SurfaceMaterial {
                    double_sided: !base.double_sided,
                    ..base
                },
                true,
            ),
            (
                "shader",
                base,
                SurfaceMaterial {
                    shader: Some(MaterialShader {
                        shader,
                        displacement_bound: 0.,
                    }),
                    ..base
                },
                true,
            ),
            (
                "colour",
                base,
                SurfaceMaterial {
                    base: [0.25, 0.5, 0.75, base.base[3]],
                    ..base
                },
                false,
            ),
            (
                "blended specular",
                blended(false, false),
                blended(false, true),
                false,
            ),
        ];
        for (name, before, after, draws) in edits {
            for (id, users) in [(shown, "a visible instance"), (hidden, "nothing visible")] {
                scene.set_material(&queue, id, before).unwrap();
                scene.test_frame(&device, &queue);
                scene.set_material(&queue, id, after).unwrap();
                let expected = draws && id == shown;
                assert_eq!(
                    scene.rigid_objects_changed(),
                    expected,
                    "{name} edit of a material {users} draws with"
                );
                scene.test_frame(&device, &queue);
                assert!(
                    !scene.rigid_objects_changed(),
                    "{name}: only submission retires the edit"
                );
            }
        }
    }
}