sim-engine 0.4.2

A validated high-performance visualization engine for simulations
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
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
//! Stable object addressing and bounded scene lifetime.

use super::{
    Arc, Color, Error, Fog3d, Lighting3d, Mesh3d, MeshStyle3d, NEXT_SCENE3D_ID, Ordering,
    RetainedMesh3d, Texture3dError, TextureMaterial3d, Transform3d, WireframeStyle3d, fmt, texture,
    validate_mesh_source_style, validate_mesh_style, validate_scene3d_transform,
};

#[cfg(test)]
mod tests;
#[cfg(test)]
pub(super) use tests::verify_scene_accounting;

/// Stable scene handle for a retained 3D object.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Object3dId {
    pub(super) scene_id: u64,
    pub(super) object_id: u64,
    slot: usize,
}

impl Object3dId {
    /// Returns the stable scene-local numeric value for diagnostics.
    ///
    /// Equality and hashing also include private scene provenance. Store the
    /// complete handle, rather than only this number, in host object maps.
    pub const fn get(self) -> u64 {
        self.object_id
    }
}

/// One retained mesh reference plus its independent model transform and style.
#[derive(Clone)]
pub struct Mesh3dInstance {
    pub(super) id: Object3dId,
    pub(super) mesh: RetainedMesh3d,
    pub(super) transform: Transform3d,
    pub(super) style: MeshStyle3d,
    pub(super) visible: bool,
}

impl Mesh3dInstance {
    fn new(
        id: Object3dId,
        mesh: &RetainedMesh3d,
        transform: Transform3d,
        style: MeshStyle3d,
    ) -> Self {
        Self {
            id,
            mesh: mesh.clone(),
            transform,
            style,
            visible: true,
        }
    }

    /// Returns the stable scene object identifier.
    pub const fn id(&self) -> Object3dId {
        self.id
    }

    /// Returns the retained GPU mesh reference.
    pub const fn mesh(&self) -> &RetainedMesh3d {
        &self.mesh
    }

    /// Returns this object's model-to-world transform.
    pub const fn transform(&self) -> Transform3d {
        self.transform
    }

    /// Returns its extensible surface/edge material bundle.
    pub const fn style(&self) -> MeshStyle3d {
        self.style
    }

    /// Returns whether this object participates in drawing and render counts.
    pub const fn is_visible(&self) -> bool {
        self.visible
    }

    /// Returns explicit edge presentation when enabled for this object.
    pub const fn wireframe(&self) -> Option<WireframeStyle3d> {
        self.style.wireframe_style()
    }
}

/// Ready 3D visual state rendered with one camera and depth attachment.
pub struct Scene3d {
    pub(super) scene_id: u64,
    pub(super) background: Color,
    pub(super) lighting: Lighting3d,
    pub(super) fog: Option<Fog3d>,
    pub(super) instances: Vec<Mesh3dInstance>,
    pub(super) next_object_id: u64,
    pub(super) renderer_identity: Option<Arc<()>>,
    slots: Vec<ObjectSlot>,
    free_slot: Option<usize>,
    resources: Vec<ResourceUsage>,
    resource_totals: ResourceTotals,
    visible_count: usize,
    budget: Scene3dBudget,
}

#[derive(Clone)]
struct ObjectSlot {
    dense_index: Option<usize>,
    next_free: Option<usize>,
}

#[derive(Clone, Copy)]
struct ResourceUsage {
    key: (u8, usize),
    references: usize,
    bytes: usize,
}

#[derive(Default)]
struct ResourceTotals {
    bytes: [usize; 4],
    counts: [usize; 4],
}

pub(super) struct DynamicSceneMeshChange {
    index: usize,
    outgoing: [ResourceUsage; 4],
    resources: Option<Vec<ResourceUsage>>,
}

impl DynamicSceneMeshChange {
    pub(super) fn object_index(&self) -> usize {
        self.index
    }
}

/// Bounds scene-owned slots and distinct retained mesh allocations.
///
/// Object storage includes dense instances, reusable lookup slots and resource
/// accounting. Mesh CPU/GPU bytes are deduplicated by allocation identity. Host
/// references outside this scene and in-flight driver allocations are excluded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Scene3dBudget {
    max_objects: usize,
    max_storage_bytes: usize,
    max_mesh_cpu_bytes: usize,
    max_mesh_gpu_bytes: usize,
    max_texture_cpu_bytes: usize,
    max_texture_gpu_bytes: usize,
}

impl Scene3dBudget {
    /// Creates nonzero object, storage, recovery-topology and GPU-buffer limits.
    pub fn new(
        max_objects: usize,
        max_storage_bytes: usize,
        max_mesh_cpu_bytes: usize,
        max_mesh_gpu_bytes: usize,
    ) -> Result<Self, Scene3dError> {
        if [
            max_objects,
            max_storage_bytes,
            max_mesh_cpu_bytes,
            max_mesh_gpu_bytes,
        ]
        .contains(&0)
        {
            return Err(Scene3dError::InvalidBudget);
        }
        Ok(Self {
            max_objects,
            max_storage_bytes,
            max_mesh_cpu_bytes,
            max_mesh_gpu_bytes,
            max_texture_cpu_bytes: 64 * 1024 * 1024,
            max_texture_gpu_bytes: 64 * 1024 * 1024,
        })
    }
    /// Maximum simultaneous live objects; removed lookup slots can be reused.
    pub const fn max_objects(self) -> usize {
        self.max_objects
    }
    /// Maximum retained CPU bookkeeping capacity in bytes.
    pub const fn max_storage_bytes(self) -> usize {
        self.max_storage_bytes
    }
    /// Maximum distinct source topology capacity in bytes.
    pub const fn max_mesh_cpu_bytes(self) -> usize {
        self.max_mesh_cpu_bytes
    }
    /// Maximum distinct mesh buffer bytes referenced by the scene.
    pub const fn max_mesh_gpu_bytes(self) -> usize {
        self.max_mesh_gpu_bytes
    }
    /// Sets deduplicated texture recovery/GPU texel limits; zero prohibits
    /// textured resources. Mesh and bookkeeping limits remain independent.
    pub const fn with_texture_limits(mut self, cpu_bytes: usize, gpu_bytes: usize) -> Self {
        self.max_texture_cpu_bytes = cpu_bytes;
        self.max_texture_gpu_bytes = gpu_bytes;
        self
    }
    /// Maximum distinct retained texture-pixel capacity in bytes.
    pub const fn max_texture_cpu_bytes(self) -> usize {
        self.max_texture_cpu_bytes
    }
    /// Maximum distinct nominal GPU texture texel bytes.
    pub const fn max_texture_gpu_bytes(self) -> usize {
        self.max_texture_gpu_bytes
    }
}

impl Default for Scene3dBudget {
    fn default() -> Self {
        Self {
            max_objects: 65_536,
            max_storage_bytes: 64 * 1024 * 1024,
            max_mesh_cpu_bytes: 256 * 1024 * 1024,
            max_mesh_gpu_bytes: 256 * 1024 * 1024,
            max_texture_cpu_bytes: 64 * 1024 * 1024,
            max_texture_gpu_bytes: 64 * 1024 * 1024,
        }
    }
}

/// Bounded scene resource whose limit rejected a mutation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Scene3dBudgetResource {
    /// Distinct retained CPU texture-pixel capacities.
    TextureCpuBytes,
    /// Distinct nominal GPU texture texel-storage bytes.
    TextureGpuBytes,
    /// Simultaneously live object count.
    Objects,
    /// Dense instances, lookup slots and allocation-accounting storage.
    StorageBytes,
    /// Distinct retained source topology bytes.
    MeshCpuBytes,
    /// Distinct retained GPU mesh buffer bytes.
    MeshGpuBytes,
}

/// Current scene-owned capacities and unique mesh allocations, excluding drivers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Scene3dStatistics {
    object_count: usize,
    slot_capacity: usize,
    storage_bytes: usize,
    mesh_count: usize,
    mesh_cpu_bytes: usize,
    mesh_gpu_bytes: usize,
    texture_count: usize,
    texture_cpu_bytes: usize,
    texture_gpu_bytes: usize,
}

impl Scene3dStatistics {
    /// Distinct shared textures referenced by live objects, including hidden ones.
    pub const fn texture_count(self) -> usize {
        self.texture_count
    }
    /// Unique retained texture-pixel capacity, excluding fixed binding metadata.
    pub const fn texture_cpu_bytes(self) -> usize {
        self.texture_cpu_bytes
    }
    /// Unique nominal GPU texel storage, excluding driver overhead.
    pub const fn texture_gpu_bytes(self) -> usize {
        self.texture_gpu_bytes
    }
    /// Number of live objects, including hidden ones.
    pub const fn object_count(self) -> usize {
        self.object_count
    }
    /// Retained lookup-slot capacity, reused after removals.
    pub const fn slot_capacity(self) -> usize {
        self.slot_capacity
    }
    /// CPU bookkeeping capacity; does not include source topology.
    pub const fn storage_bytes(self) -> usize {
        self.storage_bytes
    }
    /// Distinct retained GPU meshes, not the number of references.
    pub const fn mesh_count(self) -> usize {
        self.mesh_count
    }
    /// Unique source topology bytes; two GPU uploads of one source count once.
    pub const fn mesh_cpu_bytes(self) -> usize {
        self.mesh_cpu_bytes
    }
    /// Unique GPU buffer bytes; excludes opaque driver/in-flight allocations.
    pub const fn mesh_gpu_bytes(self) -> usize {
        self.mesh_gpu_bytes
    }
}

/// Accounting for an immutable mesh rebinding, including old/new overlap.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Scene3dMeshUpdateReport {
    statistics: Scene3dStatistics,
    peak_mesh_cpu_bytes: usize,
    peak_mesh_gpu_bytes: usize,
    peak_texture_cpu_bytes: usize,
    peak_texture_gpu_bytes: usize,
}

impl Scene3dMeshUpdateReport {
    /// Unique old-plus-new texture-pixel capacity during rebinding.
    pub const fn peak_texture_cpu_bytes(self) -> usize {
        self.peak_texture_cpu_bytes
    }
    /// Unique old-plus-new GPU texel bytes during rebinding, not driver retirement.
    pub const fn peak_texture_gpu_bytes(self) -> usize {
        self.peak_texture_gpu_bytes
    }
    /// Accepted scene capacities and unique resource bytes.
    pub const fn statistics(self) -> Scene3dStatistics {
        self.statistics
    }
    /// Unique old-plus-new topology bytes during the rebind.
    pub const fn peak_mesh_cpu_bytes(self) -> usize {
        self.peak_mesh_cpu_bytes
    }
    /// Unique old-plus-new buffer bytes during the rebind, not driver retirement.
    pub const fn peak_mesh_gpu_bytes(self) -> usize {
        self.peak_mesh_gpu_bytes
    }
}

impl Scene3d {
    /// Creates an empty scene with a normalized opaque clear color.
    pub fn new(background: Color) -> Result<Self, Scene3dError> {
        Self::with_budget(background, Scene3dBudget::default())
    }

    /// Creates a lazily allocated scene with explicit live-resource limits.
    pub fn with_budget(background: Color, budget: Scene3dBudget) -> Result<Self, Scene3dError> {
        if !background.is_normalized() || background.alpha() != 1.0 {
            return Err(Scene3dError::InvalidBackground);
        }
        Self::with_alpha_background_and_budget(background, budget)
    }

    /// Creates an empty scene with a normalized straight-linear RGBA clear color.
    /// Offscreen clear RGB is premultiplied; transparent black preserves alpha
    /// for later target composition. This explicit API accepts alpha below one.
    pub fn with_alpha_background(background: Color) -> Result<Self, Scene3dError> {
        Self::with_alpha_background_and_budget(background, Scene3dBudget::default())
    }

    /// Creates an alpha-capable offscreen scene with explicit resource limits.
    pub fn with_alpha_background_and_budget(
        background: Color,
        budget: Scene3dBudget,
    ) -> Result<Self, Scene3dError> {
        if !background.is_normalized() {
            return Err(Scene3dError::InvalidBackground);
        }
        let scene_id = NEXT_SCENE3D_ID
            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
                current.checked_add(1)
            })
            .map_err(|_| Scene3dError::SceneIdExhausted)?;
        Ok(Self {
            scene_id,
            background,
            lighting: Lighting3d::default(),
            fog: None,
            instances: Vec::new(),
            next_object_id: 0,
            renderer_identity: None,
            slots: Vec::new(),
            free_slot: None,
            resources: Vec::new(),
            resource_totals: ResourceTotals::default(),
            visible_count: 0,
            budget,
        })
    }

    /// Replaces validated ambient and directional scene illumination.
    pub fn set_lighting(&mut self, lighting: Lighting3d) {
        self.lighting = lighting;
    }
    /// Returns scene illumination; surfaces remain Unlit unless explicitly opted in.
    pub const fn lighting(&self) -> Lighting3d {
        self.lighting
    }
    /// Replaces or disables camera-forward distance fog without changing topology.
    pub fn set_fog(&mut self, fog: Option<Fog3d>) {
        self.fog = fog;
    }
    /// Returns optional scene fog; only explicitly participating surfaces use it.
    pub const fn fog(&self) -> Option<Fog3d> {
        self.fog
    }

    /// Adds a retained object and returns a stable handle for later updates.
    pub fn try_push(
        &mut self,
        mesh: &RetainedMesh3d,
        transform: Transform3d,
        style: MeshStyle3d,
    ) -> Result<Object3dId, Scene3dError> {
        validate_mesh_style(mesh, style)?;
        validate_scene3d_transform(transform)?;
        self.validate_mesh_owner(mesh)?;
        check_scene_limit(
            Scene3dBudgetResource::Objects,
            self.budget.max_objects,
            self.instances.len().saturating_add(1),
        )?;
        let next_object_id = self
            .next_object_id
            .checked_add(1)
            .ok_or(Scene3dError::ObjectIdExhausted)?;
        let keys = mesh_resources(mesh);
        self.validate_resource_change(&keys, None)?;
        self.reserve_storage(
            1,
            usize::from(self.free_slot.is_none()),
            self.missing_resources(&keys),
        )?;
        let slot = self.free_slot.unwrap_or(self.slots.len());
        let id = Object3dId {
            scene_id: self.scene_id,
            object_id: self.next_object_id,
            slot,
        };
        if let Some(free) = self.free_slot {
            self.free_slot = self.slots[free].next_free;
            self.slots[free] = ObjectSlot {
                dense_index: Some(self.instances.len()),
                next_free: None,
            };
        } else {
            self.slots.push(ObjectSlot {
                dense_index: Some(self.instances.len()),
                next_free: None,
            });
        }
        for resource in keys {
            self.add_resource(resource);
        }
        self.renderer_identity = Some(Arc::clone(&mesh.renderer_identity));
        self.instances
            .push(Mesh3dInstance::new(id, mesh, transform, style));
        self.visible_count += 1;
        self.next_object_id = next_object_id;
        Ok(id)
    }

    /// Returns the normalized straight-linear RGBA target clear color.
    pub const fn background(&self) -> Color {
        self.background
    }

    /// Changes only the normalized straight-linear RGBA clear color, accepting
    /// alpha in `0..=1` even on a scene created with the opaque constructor.
    /// This explicit mutation performs no allocation, geometry update or upload;
    /// IDs, resources, capacities, materials and the environment are untouched.
    /// Non-finite or out-of-range channels return `InvalidBackground` without
    /// changing the previous color. Rendering premultiplies clear RGB exactly
    /// as it does for `with_alpha_background`.
    pub fn set_background(&mut self, background: Color) -> Result<(), Scene3dError> {
        if !background.is_normalized() {
            return Err(Scene3dError::InvalidBackground);
        }
        self.background = background;
        Ok(())
    }

    /// Returns objects in host insertion order; depth determines visibility.
    pub fn instances(&self) -> &[Mesh3dInstance] {
        &self.instances
    }

    /// Returns the number of independently transformed objects.
    pub fn object_count(&self) -> usize {
        self.instances.len()
    }

    /// Returns the configured simultaneous-live and retained-capacity limits.
    pub const fn budget(&self) -> Scene3dBudget {
        self.budget
    }

    /// Returns deduplicated allocation accounting in constant time without
    /// allocating scratch.
    pub fn statistics(&self) -> Scene3dStatistics {
        Scene3dStatistics {
            texture_count: self.resource_totals.counts[3],
            texture_cpu_bytes: self.resource_totals.bytes[2],
            texture_gpu_bytes: self.resource_totals.bytes[3],
            object_count: self.instances.len(),
            slot_capacity: self.slots.capacity(),
            storage_bytes: storage_bytes(
                self.instances.capacity(),
                self.slots.capacity(),
                self.resources.capacity(),
            ),
            mesh_count: self.resource_totals.counts[1],
            mesh_cpu_bytes: self.resource_totals.bytes[0],
            mesh_gpu_bytes: self.resource_totals.bytes[1],
        }
    }

    /// Resolves a live scene-provenance-checked handle in constant time.
    pub fn instance(&self, object_id: Object3dId) -> Result<&Mesh3dInstance, Scene3dError> {
        let index = self.instance_index(object_id)?;
        Ok(&self.instances[index])
    }

    /// Removes an object, preserving survivor IDs and insertion order.
    ///
    /// Removal shifts dense storage in O(N); transform/style/visibility lookups
    /// remain O(1). Lookup slots are reused with never-repeated numeric IDs.
    /// The returned instance owns its retired mesh reference. Dropping it releases
    /// that reference, not necessarily in-flight driver memory.
    pub fn remove(&mut self, object_id: Object3dId) -> Result<Mesh3dInstance, Scene3dError> {
        let index = self.instance_index(object_id)?;
        let removed = self.instances.remove(index);
        for instance in &self.instances[index..] {
            if let Some(dense) = &mut self.slots[instance.id.slot].dense_index {
                *dense -= 1;
            }
        }
        self.slots[object_id.slot] = ObjectSlot {
            dense_index: None,
            next_free: self.free_slot,
        };
        self.free_slot = Some(object_id.slot);
        for resource in mesh_resources(&removed.mesh) {
            self.remove_resource(resource.key);
        }
        if removed.visible {
            self.visible_count -= 1;
        }
        Ok(removed)
    }

    /// Attaches/replaces (`Some`) or removes (`None`) only this object's texture
    /// material, sharing all existing topology and attribute buffers. There are
    /// no geometry/texture uploads, GPU allocations or GPU copies. Existing mesh
    /// aliases and other objects retain their materials; IDs, transform, style,
    /// visibility and reserved mesh capacity are unchanged.
    ///
    /// Rebinding validates object provenance, texture device ownership, UVs and
    /// final scene resource/storage limits before publication. Fallible scene
    /// bookkeeping reservation may be needed. The returned report uses the same
    /// unique old-plus-incoming overlap accounting as `set_mesh`; it does not
    /// impose a new peak limit or promise immediate in-flight GPU retirement.
    /// Detaching retains UVs for later rebinding and does not create geometry.
    pub fn set_texture_material(
        &mut self,
        object_id: Object3dId,
        material: Option<&TextureMaterial3d>,
    ) -> Result<Scene3dMeshUpdateReport, Scene3dError> {
        let mesh = self.instance(object_id)?.mesh();
        let replacement = match material {
            Some(material) => texture::attach_material(&mesh.renderer_identity, mesh, material)
                .map_err(Scene3dError::Texture)?,
            None => mesh.without_material(),
        };
        self.set_mesh(object_id, &replacement)
    }

    /// Rebinds only this object to an immutable mesh after complete validation.
    ///
    /// Shared users of the old mesh are unchanged. Transform, style, visibility
    /// and ID survive. The accepted resource limits apply to final scene state;
    /// replacement overlap is at most old plus incoming mesh and is reported.
    /// Synchronous errors preserve all live visual state. In-flight submissions
    /// retain their old GPU references; no immediate driver retirement is promised.
    pub fn set_mesh(
        &mut self,
        object_id: Object3dId,
        mesh: &RetainedMesh3d,
    ) -> Result<Scene3dMeshUpdateReport, Scene3dError> {
        let index = self.instance_index(object_id)?;
        self.validate_mesh_owner(mesh)?;
        validate_mesh_style(mesh, self.instances[index].style)?;
        let incoming = mesh_resources(mesh);
        let outgoing = mesh_resources(&self.instances[index].mesh);
        let [
            peak_mesh_cpu_bytes,
            peak_mesh_gpu_bytes,
            peak_texture_cpu_bytes,
            peak_texture_gpu_bytes,
        ] = self.validate_resource_change(&incoming, Some(&outgoing))?;
        let removed_keys = outgoing
            .iter()
            .filter(|resource| {
                !incoming.iter().any(|r| r.key == resource.key)
                    && self
                        .resources
                        .binary_search_by_key(&resource.key, |r| r.key)
                        .ok()
                        .is_some_and(|i| self.resources[i].references == 1)
            })
            .count();
        self.reserve_storage(
            0,
            0,
            self.missing_resources(&incoming)
                .saturating_sub(removed_keys),
        )?;
        for resource in outgoing {
            self.remove_resource(resource.key);
        }
        for resource in incoming {
            self.add_resource(resource);
        }
        self.instances[index].mesh = mesh.clone();
        Ok(Scene3dMeshUpdateReport {
            statistics: self.statistics(),
            peak_mesh_cpu_bytes,
            peak_mesh_gpu_bytes,
            peak_texture_cpu_bytes,
            peak_texture_gpu_bytes,
        })
    }

    pub(super) fn prepare_dynamic_mesh_change(
        &self,
        object_id: Object3dId,
        source: &Mesh3d,
        gpu_bytes: usize,
        replace_buffers: bool,
    ) -> Result<DynamicSceneMeshChange, Scene3dError> {
        let index = self.instance_index(object_id)?;
        validate_mesh_source_style(source, self.instances[index].style)?;
        let outgoing = mesh_resources(&self.instances[index].mesh);
        let mut incoming = outgoing;
        incoming[0].key.1 = source.vertices().as_ptr() as usize;
        incoming[0].bytes = source.recovery_memory_bytes();
        if replace_buffers {
            // Real Arc allocation identities cannot be null. This temporary
            // key proves new-bundle accounting before any GPU allocation.
            incoming[1].key.1 = 0;
        }
        incoming[1].bytes = gpu_bytes;
        self.prepare_resource_change(index, incoming, outgoing)
    }

    pub(super) fn prepare_dynamic_texture_change(
        &self,
        object_id: Object3dId,
        cpu_bytes: usize,
        gpu_bytes: usize,
        detached: bool,
    ) -> Result<DynamicSceneMeshChange, Scene3dError> {
        let index = self.instance_index(object_id)?;
        let outgoing = mesh_resources(&self.instances[index].mesh);
        let mut incoming = outgoing;
        // The candidate CPU chain has a distinct allocation even when its
        // enclosing texture handle and GPU allocation are uniquely reused.
        incoming[2].key.1 = 0;
        incoming[2].bytes = cpu_bytes;
        incoming[3].bytes = gpu_bytes;
        if detached {
            incoming[3].key.1 = 0;
        }
        self.prepare_resource_change(index, incoming, outgoing)
    }

    fn prepare_resource_change(
        &self,
        index: usize,
        incoming: [ResourceUsage; 4],
        outgoing: [ResourceUsage; 4],
    ) -> Result<DynamicSceneMeshChange, Scene3dError> {
        self.validate_resource_change(&incoming, Some(&outgoing))?;
        let retired = outgoing
            .iter()
            .filter(|resource| {
                !incoming
                    .iter()
                    .any(|candidate| candidate.key == resource.key)
                    && self
                        .resources
                        .binary_search_by_key(&resource.key, |entry| entry.key)
                        .ok()
                        .is_some_and(|index| self.resources[index].references == 1)
            })
            .count();
        let additional = self.missing_resources(&incoming).saturating_sub(retired);
        let mut capacity = planned_capacity(
            &self.resources,
            additional,
            self.budget.max_objects.saturating_mul(4),
        );
        if storage_bytes(self.instances.capacity(), self.slots.capacity(), capacity)
            > self.budget.max_storage_bytes
        {
            capacity = self
                .resources
                .capacity()
                .max(self.resources.len().saturating_add(additional));
        }
        check_scene_limit(
            Scene3dBudgetResource::StorageBytes,
            self.budget.max_storage_bytes,
            storage_bytes(self.instances.capacity(), self.slots.capacity(), capacity),
        )?;
        let resources = replacement_capacity(&self.resources, capacity)?;
        check_scene_limit(
            Scene3dBudgetResource::StorageBytes,
            self.budget.max_storage_bytes,
            storage_bytes(
                self.instances.capacity(),
                self.slots.capacity(),
                resources
                    .as_ref()
                    .map_or(self.resources.capacity(), Vec::capacity),
            ),
        )?;
        Ok(DynamicSceneMeshChange {
            index,
            outgoing,
            resources,
        })
    }

    pub(super) fn commit_dynamic_mesh_change(
        &mut self,
        change: DynamicSceneMeshChange,
        mesh: RetainedMesh3d,
    ) -> Scene3dStatistics {
        if let Some(resources) = change.resources {
            self.resources = resources;
        }
        for resource in change.outgoing {
            self.remove_resource(resource.key);
        }
        for resource in mesh_resources(&mesh) {
            self.add_resource(resource);
        }
        self.instances[change.index].mesh = mesh;
        self.statistics()
    }

    pub(super) fn commit_dynamic_texture_change(&mut self, change: DynamicSceneMeshChange) {
        if let Some(resources) = change.resources {
            self.resources = resources;
        }
        for resource in change.outgoing {
            self.remove_resource(resource.key);
        }
        for resource in mesh_resources(&self.instances[change.index].mesh) {
            self.add_resource(resource);
        }
    }

    /// Returns the number of objects currently participating in rendering in
    /// constant time.
    pub fn visible_object_count(&self) -> usize {
        self.visible_count
    }

    /// Replaces one object's model transform without touching retained topology.
    pub fn set_transform(
        &mut self,
        object_id: Object3dId,
        transform: Transform3d,
    ) -> Result<(), Scene3dError> {
        validate_scene3d_transform(transform)?;
        let instance = self.instance_mut(object_id)?;
        instance.transform = transform;
        Ok(())
    }

    /// Replaces one object's complete extensible visual material bundle.
    pub fn set_style(
        &mut self,
        object_id: Object3dId,
        style: MeshStyle3d,
    ) -> Result<(), Scene3dError> {
        let instance = self.instance_mut(object_id)?;
        validate_mesh_style(&instance.mesh, style)?;
        instance.style = style;
        Ok(())
    }

    /// Shows or hides one object without releasing retained topology.
    pub fn set_visible(
        &mut self,
        object_id: Object3dId,
        visible: bool,
    ) -> Result<(), Scene3dError> {
        let index = self.instance_index(object_id)?;
        let instance = &mut self.instances[index];
        if instance.visible != visible {
            if visible {
                self.visible_count += 1;
            } else {
                self.visible_count -= 1;
            }
            instance.visible = visible;
        }
        Ok(())
    }

    /// Enables or disables explicit visible/hidden edges for one object.
    pub fn set_wireframe(
        &mut self,
        object_id: Object3dId,
        wireframe: Option<WireframeStyle3d>,
    ) -> Result<(), Scene3dError> {
        let instance = self.instance_mut(object_id)?;
        let surface = instance.style.surface_style();
        let style = match (surface, wireframe) {
            (Some(surface), Some(wireframe)) => {
                MeshStyle3d::surface(surface).with_wireframe(wireframe)
            }
            (Some(surface), None) => MeshStyle3d::surface(surface),
            (None, Some(wireframe)) => MeshStyle3d::wireframe(wireframe),
            (None, None) => return Err(Scene3dError::EmptyStyle),
        };
        validate_mesh_style(&instance.mesh, style)?;
        instance.style = style;
        Ok(())
    }

    fn instance_mut(&mut self, object_id: Object3dId) -> Result<&mut Mesh3dInstance, Scene3dError> {
        let index = self.instance_index(object_id)?;
        Ok(&mut self.instances[index])
    }

    fn instance_index(&self, object_id: Object3dId) -> Result<usize, Scene3dError> {
        let index = (object_id.scene_id == self.scene_id)
            .then_some(())
            .and_then(|()| self.slots.get(object_id.slot))
            .and_then(|slot| slot.dense_index)
            .filter(|&index| {
                self.instances
                    .get(index)
                    .is_some_and(|instance| instance.id == object_id)
            });
        index.ok_or(Scene3dError::ObjectNotFound { object_id })
    }

    fn validate_mesh_owner(&self, mesh: &RetainedMesh3d) -> Result<(), Scene3dError> {
        if mesh
            .material()
            .is_some_and(|material| !material.texture().belongs_to(&mesh.renderer_identity))
        {
            return Err(Scene3dError::RendererMismatch);
        }
        if self
            .renderer_identity
            .as_ref()
            .is_some_and(|identity| !Arc::ptr_eq(identity, &mesh.renderer_identity))
        {
            Err(Scene3dError::RendererMismatch)
        } else {
            Ok(())
        }
    }

    fn missing_resources(&self, incoming: &[ResourceUsage]) -> usize {
        incoming
            .iter()
            .filter(|r| {
                r.bytes > 0
                    && self
                        .resources
                        .binary_search_by_key(&r.key, |r| r.key)
                        .is_err()
            })
            .count()
    }

    fn add_resource(&mut self, resource: ResourceUsage) {
        if resource.bytes == 0 {
            return;
        }
        match self
            .resources
            .binary_search_by_key(&resource.key, |r| r.key)
        {
            Ok(index) => self.resources[index].references += 1,
            Err(index) => {
                self.resources.insert(index, resource);
                let category = resource.key.0 as usize;
                self.resource_totals.bytes[category] += resource.bytes;
                self.resource_totals.counts[category] += 1;
            }
        }
    }

    fn remove_resource(&mut self, key: (u8, usize)) {
        if let Ok(index) = self.resources.binary_search_by_key(&key, |r| r.key) {
            self.resources[index].references -= 1;
            if self.resources[index].references == 0 {
                // Unique texture updates can already have changed the live
                // resource's capacity, so retire the bytes stored in the table.
                let removed = self.resources.remove(index);
                let category = removed.key.0 as usize;
                self.resource_totals.bytes[category] -= removed.bytes;
                self.resource_totals.counts[category] -= 1;
            }
        }
    }

    fn validate_resource_change(
        &self,
        incoming: &[ResourceUsage],
        outgoing: Option<&[ResourceUsage]>,
    ) -> Result<[usize; 4], Scene3dError> {
        let mut bytes = self.resource_totals.bytes;
        for resource in incoming {
            if self
                .resources
                .binary_search_by_key(&resource.key, |r| r.key)
                .is_err()
            {
                bytes[resource.key.0 as usize] =
                    bytes[resource.key.0 as usize].saturating_add(resource.bytes);
            }
        }
        let peak = bytes;
        for resource in outgoing.into_iter().flatten() {
            if !incoming.iter().any(|r| r.key == resource.key)
                && self
                    .resources
                    .binary_search_by_key(&resource.key, |r| r.key)
                    .ok()
                    .is_some_and(|i| self.resources[i].references == 1)
            {
                bytes[resource.key.0 as usize] -= resource.bytes;
            }
        }
        check_scene_limit(
            Scene3dBudgetResource::MeshCpuBytes,
            self.budget.max_mesh_cpu_bytes,
            bytes[0],
        )?;
        check_scene_limit(
            Scene3dBudgetResource::MeshGpuBytes,
            self.budget.max_mesh_gpu_bytes,
            bytes[1],
        )?;
        check_scene_limit(
            Scene3dBudgetResource::TextureCpuBytes,
            self.budget.max_texture_cpu_bytes,
            bytes[2],
        )?;
        check_scene_limit(
            Scene3dBudgetResource::TextureGpuBytes,
            self.budget.max_texture_gpu_bytes,
            bytes[3],
        )?;
        Ok(peak)
    }

    fn reserve_storage(
        &mut self,
        instances: usize,
        slots: usize,
        resources: usize,
    ) -> Result<(), Scene3dError> {
        let mut capacities = [
            planned_capacity(&self.instances, instances, self.budget.max_objects),
            planned_capacity(&self.slots, slots, self.budget.max_objects),
            planned_capacity(
                &self.resources,
                resources,
                self.budget.max_objects.saturating_mul(4),
            ),
        ];
        if storage_bytes(capacities[0], capacities[1], capacities[2])
            > self.budget.max_storage_bytes
        {
            capacities = [
                self.instances
                    .capacity()
                    .max(self.instances.len().saturating_add(instances)),
                self.slots
                    .capacity()
                    .max(self.slots.len().saturating_add(slots)),
                self.resources
                    .capacity()
                    .max(self.resources.len().saturating_add(resources)),
            ];
        }
        let planned_bytes = storage_bytes(capacities[0], capacities[1], capacities[2]);
        check_scene_limit(
            Scene3dBudgetResource::StorageBytes,
            self.budget.max_storage_bytes,
            planned_bytes,
        )?;
        let new_instances = replacement_capacity(&self.instances, capacities[0])?;
        let new_slots = replacement_capacity(&self.slots, capacities[1])?;
        let new_resources = replacement_capacity(&self.resources, capacities[2])?;
        let bytes = storage_bytes(
            new_instances
                .as_ref()
                .map_or(self.instances.capacity(), Vec::capacity),
            new_slots
                .as_ref()
                .map_or(self.slots.capacity(), Vec::capacity),
            new_resources
                .as_ref()
                .map_or(self.resources.capacity(), Vec::capacity),
        );
        check_scene_limit(
            Scene3dBudgetResource::StorageBytes,
            self.budget.max_storage_bytes,
            bytes,
        )?;
        if let Some(values) = new_instances {
            self.instances = values;
        }
        if let Some(values) = new_slots {
            self.slots = values;
        }
        if let Some(values) = new_resources {
            self.resources = values;
        }
        Ok(())
    }

    pub(super) fn rebuild_resource_keys(&mut self) {
        // Recovery preserves topology sharing and distinct mesh count, so the
        // existing table capacity suffices. New GPU allocation identities replace
        // old keys only after the complete recovery candidate has been accepted.
        self.resources.clear();
        self.resource_totals = ResourceTotals::default();
        self.visible_count = 0;
        for index in 0..self.instances.len() {
            for resource in mesh_resources(&self.instances[index].mesh) {
                self.add_resource(resource);
            }
            if self.instances[index].visible {
                self.visible_count += 1;
            }
        }
    }
}

fn mesh_resources(mesh: &RetainedMesh3d) -> [ResourceUsage; 4] {
    [
        ResourceUsage {
            key: (0, mesh.source.vertices().as_ptr() as usize),
            references: 1,
            bytes: mesh.recovery_memory_bytes(),
        },
        ResourceUsage {
            key: (1, Arc::as_ptr(&mesh.vertex_buffer) as usize),
            references: 1,
            bytes: mesh.gpu_allocation_bytes(),
        },
        ResourceUsage {
            key: (
                2,
                mesh.material()
                    .map_or(0, |material| material.texture().identity_key()),
            ),
            references: 1,
            bytes: mesh
                .material()
                .map_or(0, |material| material.texture().recovery_memory_bytes()),
        },
        ResourceUsage {
            key: (
                3,
                mesh.material()
                    .map_or(0, |material| material.texture().identity_key()),
            ),
            references: 1,
            bytes: mesh
                .material()
                .map_or(0, |material| material.texture().gpu_allocation_bytes()),
        },
    ]
}

fn check_scene_limit(
    resource: Scene3dBudgetResource,
    limit: usize,
    actual: usize,
) -> Result<(), Scene3dError> {
    if actual > limit {
        Err(Scene3dError::BudgetExceeded {
            resource,
            limit,
            actual,
        })
    } else {
        Ok(())
    }
}

fn storage_bytes(instances: usize, slots: usize, resources: usize) -> usize {
    instances
        .saturating_mul(std::mem::size_of::<Mesh3dInstance>())
        .saturating_add(slots.saturating_mul(std::mem::size_of::<ObjectSlot>()))
        .saturating_add(resources.saturating_mul(std::mem::size_of::<ResourceUsage>()))
}

fn replacement_capacity<T: Clone>(
    current: &Vec<T>,
    capacity: usize,
) -> Result<Option<Vec<T>>, Scene3dError> {
    if capacity <= current.capacity() {
        return Ok(None);
    }
    let mut values = Vec::new();
    values
        .try_reserve_exact(capacity)
        .map_err(|_| Scene3dError::AllocationFailed {
            requested_bytes: capacity.saturating_mul(std::mem::size_of::<T>()),
        })?;
    values.extend_from_slice(current);
    Ok(Some(values))
}

fn planned_capacity<T>(current: &Vec<T>, additional: usize, maximum: usize) -> usize {
    let needed = current.len().saturating_add(additional);
    if needed <= current.capacity() {
        current.capacity()
    } else {
        needed
            .max(current.capacity().saturating_mul(2))
            .min(maximum)
    }
}

/// Rejection reason for 3D scene visual state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Scene3dError {
    /// Texture material rebinding failed validation before scene mutation.
    Texture(Texture3dError),
    /// Lambert surface requires one normalized model normal per source vertex.
    MissingNormals,
    /// Each explicit scene budget limit must be nonzero.
    InvalidBudget,
    /// The incoming mesh belongs to another logical renderer generation.
    RendererMismatch,
    /// A mutation would exceed a configured live-resource or storage limit.
    BudgetExceeded {
        /// Rejected resource category.
        resource: Scene3dBudgetResource,
        /// Configured maximum.
        limit: usize,
        /// Required count or bytes.
        actual: usize,
    },
    /// The clear color must be normalized; legacy constructors also require opaque alpha.
    InvalidBackground,
    /// Surface and wireframe were both disabled.
    EmptyStyle,
    /// The selected surface/edge modes have no corresponding mesh topology.
    StyleHasNoMatchingGeometry,
    /// A model transform cannot be represented portably by the GPU shader.
    InvalidTransform,
    /// No more process-unique scene identifiers can be allocated.
    SceneIdExhausted,
    /// No more stable object identifiers can be allocated.
    ObjectIdExhausted,
    /// CPU storage for another retained object could not be reserved.
    AllocationFailed {
        /// Additional bytes requested for the rejected object.
        requested_bytes: usize,
    },
    /// An object update referenced a missing stable handle.
    ObjectNotFound {
        /// Stable handle that is absent from this scene.
        object_id: Object3dId,
    },
}

impl fmt::Display for Scene3dError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Texture(error) => write!(formatter, "3D scene material: {error}"),
            Self::MissingNormals => write!(
                formatter,
                "Lambert surface requires application-supplied model normals"
            ),
            Self::InvalidBudget => write!(formatter, "3D scene budget limits must be nonzero"),
            Self::RendererMismatch => {
                write!(formatter, "3D mesh belongs to another renderer generation")
            }
            Self::BudgetExceeded {
                resource,
                limit,
                actual,
            } => write!(
                formatter,
                "3D scene {resource:?} budget exceeded: {actual} > {limit}"
            ),
            Self::InvalidBackground => write!(
                formatter,
                "3D scene background must be normalized; legacy constructors also require opaque alpha"
            ),
            Self::EmptyStyle => write!(formatter, "3D object requires a surface or wireframe"),
            Self::StyleHasNoMatchingGeometry => write!(
                formatter,
                "3D object style has no matching triangles or display edges"
            ),
            Self::InvalidTransform => {
                write!(
                    formatter,
                    "3D model transform is outside the portable shader envelope"
                )
            }
            Self::SceneIdExhausted => write!(formatter, "3D scene identifiers exhausted"),
            Self::ObjectIdExhausted => write!(formatter, "3D scene object identifiers exhausted"),
            Self::AllocationFailed { requested_bytes } => write!(
                formatter,
                "could not reserve {requested_bytes} bytes for another 3D scene object"
            ),
            Self::ObjectNotFound { object_id } => write!(
                formatter,
                "3D scene object {} does not exist in this scene",
                object_id.get()
            ),
        }
    }
}

impl Error for Scene3dError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Texture(error) => Some(error),
            _ => None,
        }
    }
}