viewport-lib 0.19.0

3D viewport rendering library
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
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
use crate::resources::*;

/// Instanced-draw pipelines, the shared per-instance storage buffer, and the
/// per-material bind group cache. Created lazily by `ensure_instanced_pipelines`
/// and `ensure_hdr_instanced_pipelines`.
#[derive(Default)]
pub(crate) struct InstancingResources {
    /// Bind group layout for the instanced storage buffer + textures (group 1).
    pub(crate) bind_group_layout: Option<wgpu::BindGroupLayout>,
    /// Storage buffer for per-instance data.
    pub(crate) storage_buf: Option<wgpu::Buffer>,
    /// Current capacity (in number of instances) of the storage buffer.
    pub(crate) storage_capacity: usize,
    /// Per-texture-key bind groups for the instanced path.
    ///
    /// Each entry combines the shared instance storage buffer (binding 0) with
    /// one specific texture combination (bindings 1-4). Keyed by
    /// (albedo_id, normal_map_id, ao_map_id) using u64::MAX for fallback slots.
    /// Invalidated when the storage buffer is resized.
    pub(crate) bind_groups: std::collections::HashMap<(u64, u64, u64), wgpu::BindGroup>,
    /// Instanced solid render pipeline (TriangleList, opaque).
    pub(crate) solid_pipeline: Option<wgpu::RenderPipeline>,
    /// Two-sided (`cull_mode: None`) variant of `solid_pipeline` for
    /// `Identical` backface-policy meshes.
    pub(crate) solid_two_sided_pipeline: Option<wgpu::RenderPipeline>,
    /// Instanced transparent render pipeline (TriangleList, alpha blending).
    pub(crate) transparent_pipeline: Option<wgpu::RenderPipeline>,
    /// Instanced shadow render pipeline (depth-only).
    pub(crate) shadow_pipeline: Option<wgpu::RenderPipeline>,
    /// Two-sided (`cull_mode: None` + two-sided depth bias) variant of
    /// `shadow_pipeline` for `Identical` backface-policy batches.
    pub(crate) shadow_two_sided_pipeline: Option<wgpu::RenderPipeline>,
    /// Per-cascade uniform buffers for the shadow pipeline (64 bytes each, one mat4x4).
    pub(crate) shadow_cascade_bufs: [Option<wgpu::Buffer>; 4],
    /// Per-cascade bind groups for the shadow pipeline group 0.
    pub(crate) shadow_cascade_bgs: [Option<wgpu::BindGroup>; 4],
    /// HDR-pass instanced solid pipeline (direct draw path).
    pub(crate) hdr_solid_pipeline: Option<wgpu::RenderPipeline>,
    /// Two-sided (`cull_mode: None`) variant of `hdr_solid_pipeline`
    /// for `Identical` backface-policy meshes (direct draw path).
    pub(crate) hdr_solid_two_sided_pipeline: Option<wgpu::RenderPipeline>,
    pub(crate) hdr_transparent_pipeline: Option<wgpu::RenderPipeline>,
    /// Instanced HDR pipeline with additive blend, no depth write. Used by
    /// `MeshInstanceItem` batches that opt into [`SpriteBlend::Additive`].
    pub(crate) hdr_additive_pipeline: Option<wgpu::RenderPipeline>,
    /// Instanced HDR pipeline with premultiplied-alpha blend, no depth write.
    /// Used by `MeshInstanceItem` batches with [`SpriteBlend::Premultiplied`].
    pub(crate) hdr_premultiplied_pipeline: Option<wgpu::RenderPipeline>,
}

/// GPU-culling inputs and pipelines. The per-instance AABBs and per-batch meta
/// are scene-global (camera-independent); the cull OUTPUTS (visibility indices,
/// indirect args, counters) are per-viewport and live in `ViewportCullState`.
/// Pipelines are created lazily by `ensure_cull_instance_pipelines`.
#[derive(Default)]
pub(crate) struct CullResources {
    /// Per-instance world-space AABB buffer. Rebuilt on batch cache miss.
    pub(crate) aabb_buf: Option<wgpu::Buffer>,
    pub(crate) aabb_capacity: usize,
    /// Per-batch metadata buffer. Rebuilt on batch cache miss.
    pub(crate) batch_meta_buf: Option<wgpu::Buffer>,
    pub(crate) batch_meta_capacity: usize,
    /// Bind group layout for instanced cull pipelines (group 1).
    /// Extends the instance BGL with binding 5: visibility_indices storage buffer.
    pub(crate) bind_group_layout: Option<wgpu::BindGroupLayout>,
    /// HDR-pass solid instanced pipeline using `vs_main_cull` (indirect draw path).
    pub(crate) hdr_solid_pipeline: Option<wgpu::RenderPipeline>,
    /// Two-sided (`cull_mode: None`) variant of `hdr_solid_pipeline`
    /// for `Identical` backface-policy meshes (indirect draw path).
    pub(crate) hdr_solid_two_sided_pipeline: Option<wgpu::RenderPipeline>,
    /// OIT-pass transparent instanced pipeline using `vs_main_cull` (indirect draw path).
    pub(crate) oit_pipeline: Option<wgpu::RenderPipeline>,
    /// Shadow instanced cull pipeline (depth-only, uses `vs_shadow_cull`).
    pub(crate) shadow_pipeline: Option<wgpu::RenderPipeline>,
    /// Two-sided (`cull_mode: None` + two-sided depth bias) variant of
    /// `shadow_pipeline` for `Identical` backface-policy batches.
    pub(crate) shadow_two_sided_pipeline: Option<wgpu::RenderPipeline>,
    /// BGL for shadow cull instance group: binding 0 (instances) + binding 5 (visibility_indices).
    pub(crate) shadow_bgl: Option<wgpu::BindGroupLayout>,
}

impl DeviceResources {
    /// Ensure the instanced pipelines and bind group layout are created.
    /// Called lazily when the instanced draw path is first needed.
    pub(crate) fn ensure_instanced_pipelines(&mut self, device: &wgpu::Device) {
        if self.instancing.bind_group_layout.is_some() {
            return; // Already initialized.
        }

        // Instanced bind group layout (group 1 for instanced pipelines).
        // binding 0: instance storage buffer
        // binding 1-4: albedo texture, sampler, normal map, AO map
        // Co-located in group 1 to stay within iced's max_bind_groups = 2.
        let instance_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("instance_bgl"),
            entries: &[
                // binding 0: instance storage buffer
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Storage { read_only: true },
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
                // binding 1: albedo texture
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                // binding 2: sampler
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
                // binding 3: normal map texture
                wgpu::BindGroupLayoutEntry {
                    binding: 3,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                // binding 4: AO map texture
                wgpu::BindGroupLayoutEntry {
                    binding: 4,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
            ],
        });

        // Instanced mesh shader.
        let instanced_shader = {
            let base = include_str!(concat!(env!("OUT_DIR"), "/mesh_instanced.wgsl"));
            let composed = crate::resources::mesh_sidecar::registry::compose_shader(
                base,
                &self.deform.registrations,
            );
            crate::resources::builders::wgsl_module(device, "mesh_instanced_shader", composed)
        };

        let instanced_layout = crate::resources::mesh::mesh_pipelines::instanced_pipeline_layout(
            device,
            "instanced_pipeline_layout",
            &self.camera_bind_group_layout,
            &instance_bgl,
            self.deform
                .enabled
                .then_some(&self.deform.bind_group_layout),
        );
        let ldr_inst = crate::resources::mesh::mesh_pipelines::build_ldr_instanced_mesh_pipelines(
            device,
            &instanced_layout,
            &instanced_shader,
            self.target_format,
            self.sample_count,
        );
        let solid_instanced = ldr_inst.solid;
        let solid_two_sided_instanced = ldr_inst.solid_two_sided;
        let transparent_instanced = ldr_inst.transparent;

        // Shadow instanced pipeline.
        let shadow_instanced_shader = crate::resources::builders::wgsl_module(
            device,
            "shadow_instanced_shader",
            crate::resources::builders::wgsl_source!("shadow_instanced"),
        );

        // Shadow instanced uses the shadow bind group layout (group 0) + instance_bgl (group 1).
        // Re-derive the shadow BGL from the existing shadow_bind_group.
        let shadow_bgl = crate::resources::builders::uniform_bgl(
            device,
            "shadow_bgl_for_instanced",
            wgpu::ShaderStages::VERTEX,
        );

        let shadow_instanced_layout =
            device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("shadow_instanced_pipeline_layout"),
                bind_group_layouts: &[&shadow_bgl, &instance_bgl],
                push_constant_ranges: &[],
            });

        // Front-cull for closed solids; `cull_mode: None` + the two-sided bias for
        // two-sided (`Identical`) batches, so a single-winding foliage card still
        // casts when its front face points away from the light. Mirrors the
        // per-object `shadow_pipeline` / `shadow_pipeline_two_sided` split.
        let make_shadow_instanced =
            |label: &str, cull_mode: Option<wgpu::Face>, bias: wgpu::DepthBiasState| {
                device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                    label: Some(label),
                    layout: Some(&shadow_instanced_layout),
                    vertex: wgpu::VertexState {
                        module: &shadow_instanced_shader,
                        entry_point: Some("vs_main"),
                        buffers: &[Vertex::buffer_layout()],
                        compilation_options: wgpu::PipelineCompilationOptions::default(),
                    },
                    fragment: None,
                    primitive: wgpu::PrimitiveState {
                        topology: wgpu::PrimitiveTopology::TriangleList,
                        cull_mode,
                        ..Default::default()
                    },
                    depth_stencil: Some(wgpu::DepthStencilState {
                        format: wgpu::TextureFormat::Depth32Float,
                        depth_write_enabled: true,
                        depth_compare: wgpu::CompareFunction::Less,
                        stencil: wgpu::StencilState::default(),
                        bias,
                    }),
                    multisample: wgpu::MultisampleState::default(),
                    multiview: None,
                    cache: None,
                })
            };
        let shadow_instanced = make_shadow_instanced(
            "shadow_instanced_pipeline",
            Some(wgpu::Face::Front),
            crate::resources::mesh::mesh_pipelines::CSM_SHADOW_BIAS,
        );
        let shadow_instanced_two_sided = make_shadow_instanced(
            "shadow_instanced_two_sided_pipeline",
            None,
            crate::resources::mesh::mesh_pipelines::CSM_SHADOW_BIAS_TWO_SIDED,
        );

        // Allocate 4 per-cascade uniform buffers (64 bytes each = one mat4x4) and
        // create bind groups for shadow_instanced_pipeline group 0.
        // Each cascade has its own small buffer so we can write_buffer(buf, 0, ...) without
        // dynamic offsets (shadow_instanced.wgsl group 0 binds a single uniform, not an array).
        let cascade_bufs: [wgpu::Buffer; 4] = std::array::from_fn(|i| {
            device.create_buffer(&wgpu::BufferDescriptor {
                label: Some(&format!("shadow_instanced_cascade_buf_{i}")),
                size: 64, // sizeof(mat4x4<f32>)
                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            })
        });
        let cascade_bgs: [wgpu::BindGroup; 4] = std::array::from_fn(|i| {
            device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some(&format!("shadow_instanced_cascade_bg_{i}")),
                layout: &shadow_bgl,
                entries: &[wgpu::BindGroupEntry {
                    binding: 0,
                    resource: cascade_bufs[i].as_entire_binding(),
                }],
            })
        });
        self.instancing.shadow_cascade_bufs = cascade_bufs.map(Some);
        self.instancing.shadow_cascade_bgs = cascade_bgs.map(Some);

        self.instancing.bind_group_layout = Some(instance_bgl);
        self.instancing.solid_pipeline = Some(solid_instanced);
        self.instancing.solid_two_sided_pipeline = Some(solid_two_sided_instanced);
        self.instancing.transparent_pipeline = Some(transparent_instanced);
        self.instancing.shadow_pipeline = Some(shadow_instanced);
        self.instancing.shadow_two_sided_pipeline = Some(shadow_instanced_two_sided);
    }

    /// Ensure the HDR instanced pipelines exist. Called after
    /// `ensure_instanced_pipelines` so that `instance_bind_group_layout` is
    /// available. Idempotent: returns immediately if the pipelines already
    /// exist or if the BGL hasn't been created yet.
    pub(crate) fn ensure_hdr_instanced_pipelines(&mut self, device: &wgpu::Device) {
        if self.instancing.hdr_solid_pipeline.is_some() {
            return;
        }
        let Some(ref instance_bgl) = self.instancing.bind_group_layout else {
            return;
        };

        let inst_shader = {
            let base = include_str!(concat!(env!("OUT_DIR"), "/mesh_instanced.wgsl"));
            let composed = crate::resources::mesh_sidecar::registry::compose_shader(
                base,
                &self.deform.registrations,
            );
            crate::resources::builders::wgsl_module(device, "mesh_instanced_shader_hdr", composed)
        };
        let inst_layout = crate::resources::mesh::mesh_pipelines::instanced_pipeline_layout(
            device,
            "hdr_instanced_pipeline_layout",
            &self.camera_bind_group_layout,
            instance_bgl,
            self.deform
                .enabled
                .then_some(&self.deform.bind_group_layout),
        );
        let hdr_inst = crate::resources::mesh::mesh_pipelines::build_hdr_instanced_mesh_pipelines(
            device,
            &inst_layout,
            &inst_shader,
        );
        self.instancing.hdr_solid_pipeline = Some(hdr_inst.solid);
        self.instancing.hdr_solid_two_sided_pipeline = Some(hdr_inst.solid_two_sided);
        self.instancing.hdr_transparent_pipeline = Some(hdr_inst.transparent);
        self.instancing.hdr_additive_pipeline = Some(hdr_inst.additive);
        self.instancing.hdr_premultiplied_pipeline = Some(hdr_inst.premultiplied);
    }

    /// Ensure the OIT instanced pipeline exists. Called after
    /// `ensure_instanced_pipelines` so that `instance_bind_group_layout` is
    /// available. Idempotent: returns immediately if the pipeline already
    /// exists or if the BGL hasn't been created yet.
    pub(crate) fn ensure_oit_instanced_pipeline(&mut self, device: &wgpu::Device) {
        if self.oit.instanced_pipeline.is_some() {
            return;
        }
        let Some(ref instance_bgl) = self.instancing.bind_group_layout else {
            return;
        };

        let instanced_oit_shader = {
            let base = include_str!(concat!(env!("OUT_DIR"), "/mesh_instanced_oit.wgsl"));
            let composed = crate::resources::mesh_sidecar::registry::compose_shader(
                base,
                &self.deform.registrations,
            );
            crate::resources::builders::wgsl_module(device, "mesh_instanced_oit_shader", composed)
        };
        let instanced_oit_layout =
            crate::resources::mesh::mesh_pipelines::instanced_pipeline_layout(
                device,
                "oit_instanced_pipeline_layout",
                &self.camera_bind_group_layout,
                instance_bgl,
                self.deform
                    .enabled
                    .then_some(&self.deform.bind_group_layout),
            );
        let pipeline = crate::resources::mesh::mesh_pipelines::build_oit_instanced_pipeline(
            device,
            &instanced_oit_layout,
            &instanced_oit_shader,
            "oit_instanced_pipeline",
            "vs_main",
        );

        self.oit.instanced_pipeline = Some(pipeline);
    }

    /// Upload instance data to the storage buffer, resizing if needed.
    /// Returns the bind group for the instance storage buffer.
    pub(crate) fn upload_instance_data(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        data: &[InstanceData],
    ) {
        if data.is_empty() {
            return;
        }

        let _bgl = self
            .instancing
            .bind_group_layout
            .as_ref()
            .expect("ensure_instanced_pipelines must be called first");

        // Clamp to the device's max_storage_buffer_binding_size so bind group
        // creation never panics regardless of scene size.
        let max_instances = (device.limits().max_storage_buffer_binding_size as usize)
            / std::mem::size_of::<InstanceData>();
        let data = &data[..data.len().min(max_instances)];

        let needed = data.len();
        if needed > self.instancing.storage_capacity {
            // Grow with 2x strategy, capped at the device limit.
            let new_cap = (needed * 2).max(64).min(max_instances);
            let buf_size = (new_cap * std::mem::size_of::<InstanceData>()) as u64;
            self.instancing.storage_buf = Some(device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("instance_storage_buf"),
                size: buf_size,
                usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            }));
            self.instancing.storage_capacity = new_cap;

            // Invalidate all per-texture-key bind groups; they reference the old buffer.
            self.instancing.bind_groups.clear();
        }

        queue.write_buffer(
            self.instancing.storage_buf.as_ref().unwrap(),
            0,
            bytemuck::cast_slice(data),
        );
    }

    /// Upload the shared cull inputs: per-instance AABBs and per-batch metadata.
    ///
    /// These are the same for every viewport (they do not depend on the camera),
    /// so they live on `DeviceResources`. The per-viewport cull outputs are
    /// allocated separately by `ViewportCullState::ensure_outputs`. Buffers grow
    /// with the same 2x strategy as `upload_instance_data`. Call on every batch
    /// cache miss, immediately after `upload_instance_data`.
    pub(crate) fn upload_cull_inputs(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        aabbs: &[crate::resources::types::InstanceAabb],
        metas: &[crate::resources::types::BatchMeta],
    ) {
        // --- AABB buffer (per-instance) ---
        let max_instances = (device.limits().max_storage_buffer_binding_size as usize)
            / std::mem::size_of::<crate::resources::types::InstanceAabb>();
        let aabbs = &aabbs[..aabbs.len().min(max_instances)];

        if aabbs.len() > self.cull.aabb_capacity {
            let new_cap = (aabbs.len() * 2).max(64).min(max_instances);
            self.cull.aabb_buf = Some(device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("instance_aabb_buf"),
                size: (new_cap * std::mem::size_of::<crate::resources::types::InstanceAabb>())
                    as u64,
                usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            }));
            self.cull.aabb_capacity = new_cap;
        }
        if !aabbs.is_empty() {
            queue.write_buffer(
                self.cull.aabb_buf.as_ref().unwrap(),
                0,
                bytemuck::cast_slice(aabbs),
            );
        }

        // --- Batch meta buffer (per-batch) ---
        let max_batches = (device.limits().max_storage_buffer_binding_size as usize)
            / std::mem::size_of::<crate::resources::types::BatchMeta>();
        let metas = &metas[..metas.len().min(max_batches)];
        let batch_count = metas.len();

        if batch_count > self.cull.batch_meta_capacity {
            let new_cap = (batch_count * 2).max(16).min(max_batches);
            let meta_size =
                (new_cap * std::mem::size_of::<crate::resources::types::BatchMeta>()) as u64;
            self.cull.batch_meta_buf = Some(device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("batch_meta_buf"),
                size: meta_size,
                usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            }));
            self.cull.batch_meta_capacity = new_cap;
        }

        if !metas.is_empty() {
            queue.write_buffer(
                self.cull.batch_meta_buf.as_ref().unwrap(),
                0,
                bytemuck::cast_slice(metas),
            );
        }
    }

    /// Ensure the GPU-driven cull variant pipelines and BGL are created.
    ///
    /// Must be called after `ensure_instanced_pipelines`.  Idempotent.
    pub(crate) fn ensure_cull_instance_pipelines(&mut self, device: &wgpu::Device) {
        if self.cull.bind_group_layout.is_some() {
            return;
        }

        let Some(ref _instance_bgl) = self.instancing.bind_group_layout else {
            return; // ensure_instanced_pipelines must be called first.
        };

        // Cull BGL = instance_bgl bindings 0-4 + binding 5: visibility_indices (read, VERTEX).
        let cull_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("instance_cull_bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Storage { read_only: true },
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 3,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 4,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                // binding 5: visibility_indices (written by compute cull pass, read in vertex shader)
                wgpu::BindGroupLayoutEntry {
                    binding: 5,
                    visibility: wgpu::ShaderStages::VERTEX,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Storage { read_only: true },
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
            ],
        });

        // HDR solid cull pipeline: Rgba16Float target, vs_main_cull, back-face cull.
        let instanced_shader = {
            let base = include_str!(concat!(env!("OUT_DIR"), "/mesh_instanced.wgsl"));
            let composed = crate::resources::mesh_sidecar::registry::compose_shader(
                base,
                &self.deform.registrations,
            );
            crate::resources::builders::wgsl_module(device, "mesh_instanced_shader_cull", composed)
        };
        let inst_cull_layout = crate::resources::mesh::mesh_pipelines::instanced_pipeline_layout(
            device,
            "hdr_instanced_cull_pipeline_layout",
            &self.camera_bind_group_layout,
            &cull_bgl,
            self.deform
                .enabled
                .then_some(&self.deform.bind_group_layout),
        );
        let hdr_solid_cull =
            crate::resources::mesh::mesh_pipelines::build_hdr_instanced_cull_pipeline(
                device,
                &inst_cull_layout,
                &instanced_shader,
            );
        let hdr_solid_cull_two_sided =
            crate::resources::mesh::mesh_pipelines::build_hdr_instanced_cull_two_sided_pipeline(
                device,
                &inst_cull_layout,
                &instanced_shader,
            );

        // OIT cull pipeline: Rgba16Float + R8Unorm targets, vs_main_cull, no depth write.
        let oit_shader = {
            let base = include_str!(concat!(env!("OUT_DIR"), "/mesh_instanced_oit.wgsl"));
            let composed = crate::resources::mesh_sidecar::registry::compose_shader(
                base,
                &self.deform.registrations,
            );
            crate::resources::builders::wgsl_module(
                device,
                "mesh_instanced_oit_shader_cull",
                composed,
            )
        };
        let oit_cull_layout = crate::resources::mesh::mesh_pipelines::instanced_pipeline_layout(
            device,
            "oit_instanced_cull_pipeline_layout",
            &self.camera_bind_group_layout,
            &cull_bgl,
            self.deform
                .enabled
                .then_some(&self.deform.bind_group_layout),
        );
        let oit_cull = crate::resources::mesh::mesh_pipelines::build_oit_instanced_pipeline(
            device,
            &oit_cull_layout,
            &oit_shader,
            "oit_instanced_cull_pipeline",
            "vs_main_cull",
        );

        self.cull.bind_group_layout = Some(cull_bgl);
        self.cull.hdr_solid_pipeline = Some(hdr_solid_cull);
        self.cull.hdr_solid_two_sided_pipeline = Some(hdr_solid_cull_two_sided);
        self.cull.oit_pipeline = Some(oit_cull);

        // Shadow instanced cull pipeline.
        // Uses a minimal BGL for group 1: binding 0 (instances) + binding 5 (visibility_indices).
        // Group 0 reuses the existing shadow cascade BGL (single mat4x4 uniform).
        let shadow_cull_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("shadow_cull_instance_bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Storage { read_only: true },
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 5,
                    visibility: wgpu::ShaderStages::VERTEX,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Storage { read_only: true },
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
            ],
        });
        // Recreate the shadow cascade BGL (same definition as in ensure_instanced_pipelines).
        let shadow_bgl_for_cull = crate::resources::builders::uniform_bgl(
            device,
            "shadow_bgl_for_cull",
            wgpu::ShaderStages::VERTEX,
        );
        let shadow_cull_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("shadow_instanced_cull_pipeline_layout"),
            bind_group_layouts: &[&shadow_bgl_for_cull, &shadow_cull_bgl],
            push_constant_ranges: &[],
        });
        let shadow_cull_shader = crate::resources::builders::wgsl_module(
            device,
            "shadow_instanced_cull_shader",
            crate::resources::builders::wgsl_source!("shadow_instanced"),
        );
        // Front-cull for closed solids; `cull_mode: None` + the two-sided bias for
        // two-sided (`Identical`) batches (see the direct-path shadow pipelines above).
        let make_shadow_cull =
            |label: &str, cull_mode: Option<wgpu::Face>, bias: wgpu::DepthBiasState| {
                device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                    label: Some(label),
                    layout: Some(&shadow_cull_layout),
                    vertex: wgpu::VertexState {
                        module: &shadow_cull_shader,
                        entry_point: Some("vs_shadow_cull"),
                        buffers: &[Vertex::buffer_layout()],
                        compilation_options: wgpu::PipelineCompilationOptions::default(),
                    },
                    fragment: None,
                    primitive: wgpu::PrimitiveState {
                        topology: wgpu::PrimitiveTopology::TriangleList,
                        cull_mode,
                        ..Default::default()
                    },
                    depth_stencil: Some(wgpu::DepthStencilState {
                        format: wgpu::TextureFormat::Depth32Float,
                        depth_write_enabled: true,
                        depth_compare: wgpu::CompareFunction::Less,
                        stencil: wgpu::StencilState::default(),
                        bias,
                    }),
                    multisample: wgpu::MultisampleState::default(),
                    multiview: None,
                    cache: None,
                })
            };
        let shadow_instanced_cull = make_shadow_cull(
            "shadow_instanced_cull_pipeline",
            Some(wgpu::Face::Front),
            crate::resources::mesh::mesh_pipelines::CSM_SHADOW_BIAS,
        );
        let shadow_instanced_cull_two_sided = make_shadow_cull(
            "shadow_instanced_cull_two_sided_pipeline",
            None,
            crate::resources::mesh::mesh_pipelines::CSM_SHADOW_BIAS_TWO_SIDED,
        );
        self.cull.shadow_pipeline = Some(shadow_instanced_cull);
        self.cull.shadow_two_sided_pipeline = Some(shadow_instanced_cull_two_sided);
        self.cull.shadow_bgl = Some(shadow_cull_bgl);
    }

    /// Get or create the shadow cull instance bind group for a given cascade index.
    ///
    /// Binds `instance_storage_buf` (binding 0) and `shadow_vis_bufs[cascade_idx]` (binding 5).
    /// Returns `None` if the required buffers or BGL are not yet allocated.
    pub(crate) fn get_shadow_cull_instance_bind_group<'a>(
        &self,
        shadow_cull: &'a mut crate::resources::ShadowCullState,
        device: &wgpu::Device,
        cascade_idx: usize,
    ) -> Option<&'a wgpu::BindGroup> {
        if shadow_cull.shadow_cull_instance_bgs[cascade_idx].is_none() {
            let bgl = self.cull.shadow_bgl.as_ref()?;
            let inst_buf = self.instancing.storage_buf.as_ref()?;
            let vis_buf = shadow_cull.shadow_vis_bufs[cascade_idx].as_ref()?;
            let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some(&format!("shadow_cull_instance_bg_{cascade_idx}")),
                layout: bgl,
                entries: &[
                    wgpu::BindGroupEntry {
                        binding: 0,
                        resource: inst_buf.as_entire_binding(),
                    },
                    wgpu::BindGroupEntry {
                        binding: 5,
                        resource: vis_buf.as_entire_binding(),
                    },
                ],
            });
            shadow_cull.shadow_cull_instance_bgs[cascade_idx] = Some(bg);
        }
        shadow_cull.shadow_cull_instance_bgs[cascade_idx].as_ref()
    }

    /// Get or create a cull-path bind group for the instanced cull pipeline.
    ///
    /// Identical to `get_instance_bind_group` but uses `instance_cull_bind_group_layout`
    /// and includes the `visibility_index_buf` at binding 5.
    pub(crate) fn get_instance_cull_bind_group<'a>(
        &self,
        cull_state: &'a mut crate::resources::ViewportCullState,
        device: &wgpu::Device,
        albedo_id: Option<crate::resources::TextureId>,
        normal_map_id: Option<crate::resources::TextureId>,
        ao_map_id: Option<crate::resources::TextureId>,
    ) -> Option<&'a wgpu::BindGroup> {
        let key = (
            albedo_id.map(|t| t.raw()).unwrap_or(u64::MAX),
            normal_map_id.map(|t| t.raw()).unwrap_or(u64::MAX),
            ao_map_id.map(|t| t.raw()).unwrap_or(u64::MAX),
        );

        if !cull_state.instance_cull_bind_groups.contains_key(&key) {
            let bgl = self.cull.bind_group_layout.as_ref()?;
            let inst_buf = self.instancing.storage_buf.as_ref()?;
            let vis_buf = cull_state.visibility_index_buf.as_ref()?;

            let albedo_view = match albedo_id {
                Some(id) if self.content.textures.get(id).is_some() => {
                    &self.content.textures.get(id).unwrap().view
                }
                _ => &self.fallback_texture.view,
            };
            let normal_view = match normal_map_id {
                Some(id) if self.content.textures.get(id).is_some() => {
                    &self.content.textures.get(id).unwrap().view
                }
                _ => &self.fallback_normal_map_view,
            };
            let ao_view = match ao_map_id {
                Some(id) if self.content.textures.get(id).is_some() => {
                    &self.content.textures.get(id).unwrap().view
                }
                _ => &self.fallback_ao_map_view,
            };

            let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("instance_cull_tex_bg"),
                layout: bgl,
                entries: &[
                    wgpu::BindGroupEntry {
                        binding: 0,
                        resource: inst_buf.as_entire_binding(),
                    },
                    wgpu::BindGroupEntry {
                        binding: 1,
                        resource: wgpu::BindingResource::TextureView(albedo_view),
                    },
                    wgpu::BindGroupEntry {
                        binding: 2,
                        resource: wgpu::BindingResource::Sampler(&self.material_sampler),
                    },
                    wgpu::BindGroupEntry {
                        binding: 3,
                        resource: wgpu::BindingResource::TextureView(normal_view),
                    },
                    wgpu::BindGroupEntry {
                        binding: 4,
                        resource: wgpu::BindingResource::TextureView(ao_view),
                    },
                    wgpu::BindGroupEntry {
                        binding: 5,
                        resource: vis_buf.as_entire_binding(),
                    },
                ],
            });
            cull_state.instance_cull_bind_groups.insert(key, bg);
        }

        cull_state.instance_cull_bind_groups.get(&key)
    }

    /// Get or create a combined instance+texture bind group for the instanced pipeline.
    ///
    /// The bind group combines the shared instance storage buffer (binding 0) with the
    /// texture views for the given material key (bindings 1-4). Results are cached by key.
    ///
    /// `u64::MAX` in any key component means "use fallback texture for that slot".
    pub(crate) fn get_instance_bind_group(
        &mut self,
        device: &wgpu::Device,
        albedo_id: Option<crate::resources::TextureId>,
        normal_map_id: Option<crate::resources::TextureId>,
        ao_map_id: Option<crate::resources::TextureId>,
    ) -> Option<&wgpu::BindGroup> {
        let key = (
            albedo_id.map(|t| t.raw()).unwrap_or(u64::MAX),
            normal_map_id.map(|t| t.raw()).unwrap_or(u64::MAX),
            ao_map_id.map(|t| t.raw()).unwrap_or(u64::MAX),
        );

        if !self.instancing.bind_groups.contains_key(&key) {
            let bgl = self.instancing.bind_group_layout.as_ref()?;
            let buf = self.instancing.storage_buf.as_ref()?;

            let albedo_view = match albedo_id {
                Some(id) if self.content.textures.get(id).is_some() => {
                    &self.content.textures.get(id).unwrap().view
                }
                _ => &self.fallback_texture.view,
            };
            let normal_view = match normal_map_id {
                Some(id) if self.content.textures.get(id).is_some() => {
                    &self.content.textures.get(id).unwrap().view
                }
                _ => &self.fallback_normal_map_view,
            };
            let ao_view = match ao_map_id {
                Some(id) if self.content.textures.get(id).is_some() => {
                    &self.content.textures.get(id).unwrap().view
                }
                _ => &self.fallback_ao_map_view,
            };

            let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("instance_tex_bg"),
                layout: bgl,
                entries: &[
                    wgpu::BindGroupEntry {
                        binding: 0,
                        resource: buf.as_entire_binding(),
                    },
                    wgpu::BindGroupEntry {
                        binding: 1,
                        resource: wgpu::BindingResource::TextureView(albedo_view),
                    },
                    wgpu::BindGroupEntry {
                        binding: 2,
                        resource: wgpu::BindingResource::Sampler(&self.material_sampler),
                    },
                    wgpu::BindGroupEntry {
                        binding: 3,
                        resource: wgpu::BindingResource::TextureView(normal_view),
                    },
                    wgpu::BindGroupEntry {
                        binding: 4,
                        resource: wgpu::BindingResource::TextureView(ao_view),
                    },
                ],
            });
            self.instancing.bind_groups.insert(key, bg);
        }

        self.instancing.bind_groups.get(&key)
    }

    /// Upload one [`MeshInstanceItem`] batch and return draw data.
    ///
    /// Builds a per-batch instance storage buffer in the layout expected by
    /// `mesh_instanced.wgsl`'s `InstanceData` struct, allocates a one-shot
    /// bind group against `instance_bind_group_layout`, and packages it into
    /// a [`MeshInstanceGpuData`]. The host is expected to rebuild this once
    /// per frame for moving particle systems.
    ///
    /// Lighting flags are filled with unlit defaults: the shader receives the
    /// per-instance colour with the optional albedo sampled on top, without
    /// going through shadow or lighting math.
    pub(crate) fn upload_mesh_instance(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        item: &crate::renderer::MeshInstanceItem,
    ) -> Option<crate::resources::types::MeshInstanceGpuData> {
        self.upload_mesh_instance_from(device, queue, item, item.mesh_id, None)
    }

    /// Build a mesh-instance batch from a subset of an item's instances drawn
    /// with a chosen mesh. `indices` selects which instances to include (and in
    /// what order); `None` uses every instance in order. `mesh_id` overrides the
    /// item's own mesh, which is how LOD draws the same item at several detail
    /// levels: one call per level with that level's mesh and its instances.
    pub(crate) fn upload_mesh_instance_from(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        item: &crate::renderer::MeshInstanceItem,
        mesh_id: crate::resources::mesh::mesh_store::MeshId,
        indices: Option<&[u32]>,
    ) -> Option<crate::resources::types::MeshInstanceGpuData> {
        let instance_count = match indices {
            Some(idx) => idx.len() as u32,
            None => item.transforms.len() as u32,
        };
        if instance_count == 0 {
            return None;
        }

        // Per-instance struct must match `InstanceData` in `mesh_instanced.wgsl`
        // and `resources::types::InstanceData` (176 bytes).
        #[repr(C)]
        #[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
        struct GpuInstanceData {
            model: [[f32; 4]; 4],
            colour: [f32; 4],
            selected: u32,
            wireframe: u32,
            ambient: f32,
            diffuse: f32,
            specular: f32,
            shininess: f32,
            has_texture: u32,
            use_pbr: u32,
            metallic: f32,
            roughness: f32,
            has_normal_map: u32,
            has_ao_map: u32,
            unlit: u32,
            receive_shadows: u32,
            use_flat: u32,
            _pad_inst1: u32,
            uv_transform: [f32; 4],
            ao_range: [f32; 2],
            _pad_ao_range: [f32; 2],
        }

        const _: () = assert!(std::mem::size_of::<GpuInstanceData>() == 176);

        let has_texture = if item
            .texture_id
            .is_some_and(|id| self.content.textures.get(id).is_some())
        {
            1u32
        } else {
            0u32
        };

        let build = |i: usize| -> GpuInstanceData {
            GpuInstanceData {
                model: item.transforms[i],
                colour: item.colours.get(i).copied().unwrap_or([1.0, 1.0, 1.0, 1.0]),
                selected: 0,
                wireframe: 0,
                ambient: 1.0,
                diffuse: 0.0,
                specular: 0.0,
                shininess: 0.0,
                has_texture,
                use_pbr: 0,
                metallic: 0.0,
                roughness: 0.0,
                has_normal_map: 0,
                has_ao_map: 0,
                unlit: 1,
                receive_shadows: 0,
                use_flat: 1,
                _pad_inst1: 0,
                uv_transform: [0.0, 0.0, 1.0, 1.0],
                ao_range: [0.0, 1.0],
                _pad_ao_range: [0.0, 0.0],
            }
        };
        let instances: Vec<GpuInstanceData> = match indices {
            Some(idx) => idx.iter().map(|&i| build(i as usize)).collect(),
            None => (0..item.transforms.len()).map(build).collect(),
        };

        let instance_bytes = bytemuck::cast_slice(&instances);
        let instance_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("mesh_instance_buf"),
            size: instance_bytes
                .len()
                .max(std::mem::size_of::<GpuInstanceData>()) as u64,
            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        queue.write_buffer(&instance_buf, 0, instance_bytes);

        let bgl = self.instancing.bind_group_layout.as_ref()?;
        let albedo_view = match item.texture_id {
            Some(id) if self.content.textures.get(id).is_some() => {
                &self.content.textures.get(id).unwrap().view
            }
            _ => &self.fallback_texture.view,
        };
        let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("mesh_instance_bg"),
            layout: bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: instance_buf.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::TextureView(albedo_view),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: wgpu::BindingResource::Sampler(&self.material_sampler),
                },
                wgpu::BindGroupEntry {
                    binding: 3,
                    resource: wgpu::BindingResource::TextureView(&self.fallback_normal_map_view),
                },
                wgpu::BindGroupEntry {
                    binding: 4,
                    resource: wgpu::BindingResource::TextureView(&self.fallback_ao_map_view),
                },
            ],
        });

        Some(crate::resources::types::MeshInstanceGpuData {
            mesh_id,
            instance_count,
            bind_group,
            blend: item.blend,
            _instance_buf: instance_buf,
        })
    }
}

/// Per-object uniform: world transform, material properties, selection state, and wireframe mode.
///
/// Layout (256 bytes, 16-byte aligned):
/// - model:                    [[f32;4];4] = 64 bytes  offset   0
/// - colour:                     [f32;4]   = 16 bytes  offset  64  (base_colour.xyz + opacity)
/// - selected:                   u32      =  4 bytes  offset  80
/// - wireframe:                  u32      =  4 bytes  offset  84
/// - ambient:                    f32      =  4 bytes  offset  88
/// - diffuse:                    f32      =  4 bytes  offset  92
/// - specular:                   f32      =  4 bytes  offset  96
/// - shininess:                  f32      =  4 bytes  offset 100
/// - has_texture:                u32      =  4 bytes  offset 104
/// - use_pbr:                    u32      =  4 bytes  offset 108
/// - metallic:                   f32      =  4 bytes  offset 112
/// - roughness:                  f32      =  4 bytes  offset 116
/// - has_normal_map:             u32      =  4 bytes  offset 120
/// - has_ao_map:                 u32      =  4 bytes  offset 124
/// - has_attribute:              u32      =  4 bytes  offset 128
/// - scalar_min:                 f32      =  4 bytes  offset 132
/// - scalar_max:                 f32      =  4 bytes  offset 136
/// - _pad_scalar:                u32      =  4 bytes  offset 140
/// - nan_colour:                 [f32;4]   = 16 bytes  offset 144
/// - use_nan_colour:              u32      =  4 bytes  offset 160
/// - use_matcap:                 u32      =  4 bytes  offset 164
/// - matcap_blendable:           u32      =  4 bytes  offset 168
/// - unlit:                      u32      =  4 bytes  offset 172
/// - use_face_colour:             u32      =  4 bytes  offset 176
/// - uv_vis_mode:                u32      =  4 bytes  offset 180  (0=off 1=checker 2=grid 3=localcheck 4=localrad)
/// - uv_vis_scale:               f32      =  4 bytes  offset 184
/// - backface_policy:            u32      =  4 bytes  offset 188  (0=Cull 1=Identical 2=DifferentColour)
/// - backface_colour:            [f32;4]   = 16 bytes  offset 192
/// - has_warp:                   u32      =  4 bytes  offset 208
/// - warp_scale:                 f32      =  4 bytes  offset 212
/// - has_position_override:      u32      =  4 bytes  offset 216
/// - has_normal_override:        u32      =  4 bytes  offset 220
/// - emissive:                   [f32;3]  = 12 bytes  offset 224
/// - use_flat:                   u32      =  4 bytes  offset 236  (1=flat shading, recover N from world_pos derivatives)
/// - alpha_mode:                 u32      =  4 bytes  offset 240  (0=Opaque, 1=Mask, 2=Blend)
/// - alpha_cutoff:               f32      =  4 bytes  offset 244
/// - has_metallic_roughness_tex: u32      =  4 bytes  offset 248
/// - has_emissive_tex:           u32      =  4 bytes  offset 252
/// - uv_transform:               [f32;4]  = 16 bytes  offset 256  (offset.xy, scale.xy)
/// - deform_flags:               u32      =  4 bytes  offset 272  (bit i = deformer slot i active)
/// - _pad_after_deform:          u32      =  4 bytes  offset 276  (align next vec2 to 8)
/// - ao_range:                   [f32;2]  =  8 bytes  offset 280
/// - metallic_range:             [f32;2]  =  8 bytes  offset 288
/// - roughness_range:            [f32;2]  =  8 bytes  offset 296
/// Total: 304 bytes
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct ObjectUniform {
    pub(crate) model: [[f32; 4]; 4], //  64 bytes, offset   0
    pub(crate) colour: [f32; 4],     //  16 bytes, offset  64
    pub(crate) selected: u32,        //   4 bytes, offset  80
    pub(crate) wireframe: u32,       //   4 bytes, offset  84
    pub(crate) ambient: f32,         //   4 bytes, offset  88
    pub(crate) diffuse: f32,         //   4 bytes, offset  92
    pub(crate) specular: f32,        //   4 bytes, offset  96
    pub(crate) shininess: f32,       //   4 bytes, offset 100
    pub(crate) has_texture: u32,     //   4 bytes, offset 104
    pub(crate) use_pbr: u32,         //   4 bytes, offset 108
    pub(crate) metallic: f32,        //   4 bytes, offset 112
    pub(crate) roughness: f32,       //   4 bytes, offset 116
    pub(crate) has_normal_map: u32,  //   4 bytes, offset 120
    pub(crate) has_ao_map: u32,      //   4 bytes, offset 124
    pub(crate) has_attribute: u32,   //   4 bytes, offset 128
    pub(crate) scalar_min: f32,      //   4 bytes, offset 132
    pub(crate) scalar_max: f32,      //   4 bytes, offset 136
    /// 1 = sample the shadow atlas, 0 = treat the fragment as unshadowed.
    /// Wired from `ItemSettings.receive_shadows`.
    pub(crate) receive_shadows: u32, //   4 bytes, offset 140
    pub(crate) nan_colour: [f32; 4], //  16 bytes, offset 144
    pub(crate) use_nan_colour: u32,  //   4 bytes, offset 160
    pub(crate) use_matcap: u32,      //   4 bytes, offset 164
    pub(crate) matcap_blendable: u32, //   4 bytes, offset 168
    pub(crate) unlit: u32,           //   4 bytes, offset 172
    pub(crate) use_face_colour: u32, //   4 bytes, offset 176
    pub(crate) uv_vis_mode: u32,     //   4 bytes, offset 180
    pub(crate) uv_vis_scale: f32,    //   4 bytes, offset 184
    pub(crate) backface_policy: u32, //   4 bytes, offset 188  (0=Cull 1=Identical 2=DifferentColour)
    pub(crate) backface_colour: [f32; 4], //  16 bytes, offset 192
    pub(crate) has_warp: u32,        //   4 bytes, offset 208
    pub(crate) warp_scale: f32,      //   4 bytes, offset 212
    /// 1 when a per-vertex position storage buffer is bound at group 1 binding 13.
    /// Wired from `GpuMesh::position_override_buffer.is_some()`.
    pub(crate) has_position_override: u32, //   4 bytes, offset 216
    /// 1 when a per-vertex normal storage buffer is bound at group 1 binding 14.
    pub(crate) has_normal_override: u32, //   4 bytes, offset 220
    pub(crate) emissive: [f32; 3],   //  12 bytes, offset 224
    /// 1 = recover the shading normal from screen-space derivatives of
    /// `world_pos` (`ShadingModel::Flat`); 0 = use the interpolated vertex
    /// normal (or TBN normal map when bound).
    pub(crate) use_flat: u32, //   4 bytes, offset 236
    pub(crate) alpha_mode: u32,      //   4 bytes, offset 240  (0=Opaque, 1=Mask, 2=Blend)
    pub(crate) alpha_cutoff: f32,    //   4 bytes, offset 244
    pub(crate) has_metallic_roughness_tex: u32, //   4 bytes, offset 248
    pub(crate) has_emissive_tex: u32, //   4 bytes, offset 252
    /// Per-material UV transform applied to every texture sample.
    /// `[offset_x, offset_y, scale_x, scale_y]`. Defaults to `(0, 0, 1, 1)`
    /// (identity). Lets atlas-packed materials share one mesh instance.
    pub(crate) uv_transform: [f32; 4], //  16 bytes, offset 256
    /// Bit `i` set when deformer slot `i` is active for this draw. Zero when
    /// no deformer registry has attached data for this mesh.
    pub(crate) deform_flags: u32, //   4 bytes, offset 272
    pub(crate) _pad_after_deform: u32, //   4 bytes, offset 276 (align next vec2 to 8)
    /// Min/max remap applied to the AO map's R sample (identity `[0, 1]`).
    /// Mirrors `Material::ao_range`.
    pub(crate) ao_range: [f32; 2], //   8 bytes, offset 280
    /// Min/max remap applied to the metallic sample (B channel of the MR
    /// texture). Identity `[0, 1]`. Mirrors `Material::metallic_range`.
    pub(crate) metallic_range: [f32; 2], //   8 bytes, offset 288
    /// Min/max remap applied to the roughness sample (G channel of the MR
    /// texture). Identity `[0, 1]`. Mirrors `Material::roughness_range`.
    pub(crate) roughness_range: [f32; 2], //   8 bytes, offset 296
}

const _: () = assert!(std::mem::size_of::<ObjectUniform>() == 304);
/// Per-instance GPU data for instanced rendering. Matches the WGSL `InstanceData` struct.
///
/// Layout: 176 bytes.
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct InstanceData {
    pub(crate) model: [[f32; 4]; 4], //  64 bytes, offset   0
    pub(crate) colour: [f32; 4],     //  16 bytes, offset  64
    pub(crate) selected: u32,        //   4 bytes, offset  80
    pub(crate) wireframe: u32,       //   4 bytes, offset  84
    pub(crate) ambient: f32,         //   4 bytes, offset  88
    pub(crate) diffuse: f32,         //   4 bytes, offset  92
    pub(crate) specular: f32,        //   4 bytes, offset  96
    pub(crate) shininess: f32,       //   4 bytes, offset 100
    pub(crate) has_texture: u32,     //   4 bytes, offset 104
    pub(crate) use_pbr: u32,         //   4 bytes, offset 108
    pub(crate) metallic: f32,        //   4 bytes, offset 112
    pub(crate) roughness: f32,       //   4 bytes, offset 116
    pub(crate) has_normal_map: u32,  //   4 bytes, offset 120
    pub(crate) has_ao_map: u32,      //   4 bytes, offset 124
    pub(crate) unlit: u32,           //   4 bytes, offset 128
    /// 1 = sample the shadow atlas, 0 = treat the fragment as unshadowed.
    pub(crate) receive_shadows: u32, //   4 bytes, offset 132
    /// 1 = recover the shading normal from screen-space derivatives of
    /// `world_pos` (`ShadingModel::Flat`).
    pub(crate) use_flat: u32, //   4 bytes, offset 136
    pub(crate) _pad_inst: u32,       //   4 bytes, offset 140
    /// Per-material UV transform; mirrors `ObjectUniform::uv_transform`.
    /// `[offset_x, offset_y, scale_x, scale_y]`.
    pub(crate) uv_transform: [f32; 4], //  16 bytes, offset 144
    /// Min/max remap applied to the AO map's R sample (identity `[0, 1]`).
    /// Mirrors `Material::ao_range`. The instanced mesh shaders do not sample
    /// the MR texture today, so `metallic_range` / `roughness_range` are
    /// intentionally absent from `InstanceData`.
    pub(crate) ao_range: [f32; 2], //   8 bytes, offset 160
    pub(crate) _pad_ao_range: [f32; 2], //  8 bytes, offset 168 (struct stride to 16B)
}

const _: () = assert!(std::mem::size_of::<InstanceData>() == 176);
/// Per-instance GPU data for the object-ID pick pass.
///
/// Stores only the model matrix and a sentinel object ID : none of the material
/// fields needed by the full [`InstanceData`] struct.
///
/// Layout (80 bytes):
/// - model_c0..model_c3: vec4<f32> x 4 = 64 bytes (model matrix, column-major)
/// - object_id: u32                     =  4 bytes  (sentinel: scene_items_index + 1)
/// - _pad: [u32; 3]                     = 12 bytes  (align to 16)
/// Total: 80 bytes
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct PickInstance {
    pub(crate) model_c0: [f32; 4],
    pub(crate) model_c1: [f32; 4],
    pub(crate) model_c2: [f32; 4],
    pub(crate) model_c3: [f32; 4],
    pub(crate) object_id: u32,
    pub(crate) _pad: [u32; 3],
}

const _: () = assert!(std::mem::size_of::<PickInstance>() == 80);
/// Per-instance world-space AABB, uploaded to GPU for the compute cull pass.
///
/// Layout (32 bytes):
/// - min:         [f32; 3] = 12 bytes, offset  0
/// - batch_index: u32      =  4 bytes, offset 12 (index into batch_meta_buf)
/// - max:         [f32; 3] = 12 bytes, offset 16
/// - _pad:        u32      =  4 bytes, offset 28
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct InstanceAabb {
    pub(crate) min: [f32; 3],
    pub(crate) batch_index: u32,
    pub(crate) max: [f32; 3],
    /// 1 = item participates in shadow casting, 0 = skipped during shadow cull.
    pub(crate) cast_shadows: u32,
}

const _: () = assert!(std::mem::size_of::<InstanceAabb>() == 32);
/// Per-batch metadata read by the GPU cull pass.
///
/// One entry per batch in the `batch_meta` storage buffer attached to a
/// [`CullSubmission`](crate::plugin_api::CullSubmission). Layout (32 bytes,
/// 16-byte aligned):
///
/// - `index_count`:     `u32` - index range used by this batch's draw
/// - `first_index`:     `u32` - index buffer offset (typically 0)
/// - `instance_offset`: `u32` - first instance for this batch in the AABB buffer
/// - `instance_count`:  `u32` - number of instances belonging to this batch
/// - `vis_offset`:      `u32` - first slot in the visibility output buffer
/// - `is_transparent`:  `u32` - `1` marks a transparent batch
/// - `_pad`:            `[u32; 2]`
///
/// `vis_offset` is a prefix sum of `instance_count` across batches; for a
/// scene where instances are laid out contiguously per batch it equals
/// `instance_offset`.
#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct BatchMeta {
    /// Mesh index count for one instance.
    pub index_count: u32,
    /// First index offset into the bound index buffer.
    pub first_index: u32,
    /// Offset into the instance AABB buffer where this batch begins.
    pub instance_offset: u32,
    /// Number of instances in the batch.
    pub instance_count: u32,
    /// First slot in the visibility output buffer this batch writes to.
    pub vis_offset: u32,
    /// `1` if the batch is transparent, `0` for opaque.
    pub is_transparent: u32,
    /// Padding to keep the struct 16-byte aligned.
    pub _pad: [u32; 2],
}

const _: () = assert!(std::mem::size_of::<BatchMeta>() == 32);