viewport-lib 0.16.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
use super::*;

impl ViewportGpuResources {
    /// Upload an RGBA texture to the GPU and return its texture ID.
    ///
    /// The ID can be stored in `Material::texture_id` to apply the texture to objects.
    /// `rgba_data` must be exactly `width * height * 4` bytes in RGBA8 format.
    ///
    /// # Errors
    ///
    /// Returns [`ViewportError::InvalidTextureData`](crate::error::ViewportError::InvalidTextureData) if the data length is incorrect.
    pub fn upload_texture(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        width: u32,
        height: u32,
        rgba_data: &[u8],
    ) -> crate::error::ViewportResult<u64> {
        let expected = (width * height * 4) as usize;
        if rgba_data.len() != expected {
            return Err(crate::error::ViewportError::InvalidTextureData {
                expected,
                actual: rgba_data.len(),
            });
        }

        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("user_texture"),
            size: wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba8UnormSrgb,
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        });

        queue.write_texture(
            wgpu::TexelCopyTextureInfo {
                texture: &texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            rgba_data,
            wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(width * 4),
                rows_per_image: Some(height),
            },
            wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
        );

        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("user_texture_sampler"),
            address_mode_u: wgpu::AddressMode::Repeat,
            address_mode_v: wgpu::AddressMode::Repeat,
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            mipmap_filter: wgpu::FilterMode::Nearest,
            ..Default::default()
        });
        let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("user_texture_bg"),
            layout: &self.texture_bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(&view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(&sampler),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: wgpu::BindingResource::TextureView(&self.fallback_normal_map_view),
                },
                wgpu::BindGroupEntry {
                    binding: 3,
                    resource: wgpu::BindingResource::TextureView(&self.fallback_ao_map_view),
                },
            ],
        });

        let id = self.textures.len() as u64;
        self.texture_allocated_bytes += (width * height * 4) as u64;
        self.textures.push(GpuTexture {
            texture,
            view,
            sampler,
            bind_group,
        });
        tracing::debug!(texture_id = id, width, height, "texture uploaded");
        Ok(id)
    }

    /// Upload an RGBA texture as a normal map and return its texture ID.
    ///
    /// Uses Rgba8Unorm format (not sRGB) so values are linear : required for correct
    /// normal map decoding. `rgba_data` must be `width * height * 4` bytes.
    pub fn upload_normal_map(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        width: u32,
        height: u32,
        rgba_data: &[u8],
    ) -> crate::error::ViewportResult<u64> {
        let expected = (width * height * 4) as usize;
        if rgba_data.len() != expected {
            return Err(crate::error::ViewportError::InvalidTextureData {
                expected,
                actual: rgba_data.len(),
            });
        }

        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("normal_map_texture"),
            size: wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba8Unorm,
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        });

        queue.write_texture(
            wgpu::TexelCopyTextureInfo {
                texture: &texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            rgba_data,
            wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(width * 4),
                rows_per_image: Some(height),
            },
            wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
        );

        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("normal_map_sampler"),
            address_mode_u: wgpu::AddressMode::Repeat,
            address_mode_v: wgpu::AddressMode::Repeat,
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            mipmap_filter: wgpu::FilterMode::Nearest,
            ..Default::default()
        });
        let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("normal_map_bg"),
            layout: &self.texture_bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(&self.fallback_texture.view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(&sampler),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: wgpu::BindingResource::TextureView(&view),
                },
                wgpu::BindGroupEntry {
                    binding: 3,
                    resource: wgpu::BindingResource::TextureView(&self.fallback_ao_map_view),
                },
            ],
        });

        let id = self.textures.len() as u64;
        self.texture_allocated_bytes += (width * height * 4) as u64;
        self.textures.push(GpuTexture {
            texture,
            view,
            sampler,
            bind_group,
        });
        tracing::debug!(texture_id = id, width, height, "normal map uploaded");
        Ok(id)
    }

    // -----------------------------------------------------------------------
    // Async texture upload
    // -----------------------------------------------------------------------

    /// Non-blocking texture upload.
    ///
    /// Writes RGBA data into a staging buffer on the calling thread. The GPU
    /// copy is submitted on the next `prepare_scene` call. The texture is
    /// invisible for exactly one frame.
    ///
    /// ```text
    /// Frame N:   upload_texture_async(...) -> PendingTextureId
    /// Frame N+1: is_upload_ready(id) -> true
    ///            promote_texture(id) -> Some(texture_id)
    /// ```
    ///
    /// `rgba` must be exactly `width * height * 4` bytes in RGBA8 format.
    pub fn upload_texture_async(
        &mut self,
        device: &wgpu::Device,
        width: u32,
        height: u32,
        rgba: &[u8],
    ) -> crate::error::ViewportResult<PendingTextureId> {
        let expected = (width * height * 4) as usize;
        if rgba.len() != expected {
            return Err(crate::error::ViewportError::InvalidTextureData {
                expected,
                actual: rgba.len(),
            });
        }

        // Compute the row stride aligned to the GPU copy requirement.
        let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
        let raw_bpr = width * 4;
        let aligned_bytes_per_row = (raw_bpr + align - 1) / align * align;
        let staging_size = aligned_bytes_per_row as u64 * height as u64;

        // Acquire a staging buffer from the pool (or allocate fresh on first use).
        // The returned buffer is already mapped for writing.
        let (staging_buf, pool_band) = self.staging_pool.acquire(device, staging_size);
        {
            let mut mapped = staging_buf.slice(..).get_mapped_range_mut();
            if aligned_bytes_per_row == raw_bpr {
                // No padding needed -- copy in one shot.
                mapped[..rgba.len()].copy_from_slice(rgba);
            } else {
                // Write each row, leaving padding bytes uninitialised.
                for row in 0..height as usize {
                    let src = row * raw_bpr as usize..(row + 1) * raw_bpr as usize;
                    let dst_start = row * aligned_bytes_per_row as usize;
                    mapped[dst_start..dst_start + raw_bpr as usize]
                        .copy_from_slice(&rgba[src]);
                }
            }
        }
        staging_buf.unmap();

        // Create the GPU texture. It will be filled by a copy_buffer_to_texture
        // command issued at the start of the next prepare_scene call.
        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("async_user_texture"),
            size: wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba8UnormSrgb,
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        });
        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("async_user_texture_sampler"),
            address_mode_u: wgpu::AddressMode::Repeat,
            address_mode_v: wgpu::AddressMode::Repeat,
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            mipmap_filter: wgpu::FilterMode::Nearest,
            ..Default::default()
        });
        let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("async_user_texture_bg"),
            layout: &self.texture_bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(&view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(&sampler),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: wgpu::BindingResource::TextureView(
                        &self.fallback_normal_map_view,
                    ),
                },
                wgpu::BindGroupEntry {
                    binding: 3,
                    resource: wgpu::BindingResource::TextureView(&self.fallback_ao_map_view),
                },
            ],
        });

        let pending_id = self.next_pending_texture_id;
        self.next_pending_texture_id += 1;

        self.pending_texture_uploads.push(PendingUploadEntry {
            pending_id,
            gpu_texture: GpuTexture {
                texture,
                view,
                sampler,
                bind_group,
            },
            staging_buf,
            pool_band,
            width,
            height,
            aligned_bytes_per_row,
            data_bytes: expected as u64,
            copy_submitted: false,
            ready: false,
        });

        tracing::debug!(pending_id, width, height, "async texture upload queued");
        Ok(PendingTextureId(pending_id))
    }

    /// Check whether the GPU copy for `id` has completed.
    ///
    /// Returns `false` on the frame the upload was submitted (the frame
    /// containing the `prepare_scene` call following `upload_texture_async`).
    /// Returns `true` on all subsequent frames. Stays `true` until
    /// `promote_texture` consumes the entry.
    pub fn is_upload_ready(&self, id: PendingTextureId) -> bool {
        self.pending_texture_uploads
            .iter()
            .find(|e| e.pending_id == id.0)
            .map_or(false, |e| e.ready)
    }

    /// Promote a completed async upload to a live texture ID.
    ///
    /// Returns the `u64` ID to store in `Material::texture_id`.
    /// Returns `None` if `id` is unknown or `is_upload_ready` is still false.
    pub fn promote_texture(&mut self, id: PendingTextureId) -> Option<u64> {
        let pos = self
            .pending_texture_uploads
            .iter()
            .position(|e| e.pending_id == id.0 && e.ready)?;

        // swap_remove is O(1) and preserves correctness since entries are
        // identified by pending_id, not position.
        let entry = self.pending_texture_uploads.swap_remove(pos);
        // Return the staging buffer to the pool; the GPU copy completed one frame ago.
        self.staging_pool.release(entry.staging_buf, entry.pool_band);

        let texture_id = self.textures.len() as u64;
        self.texture_allocated_bytes += entry.data_bytes;
        self.textures.push(entry.gpu_texture);

        tracing::debug!(
            texture_id,
            width = entry.width,
            height = entry.height,
            "async texture promoted"
        );
        Some(texture_id)
    }

    // -----------------------------------------------------------------------
    // VRAM budget query
    // -----------------------------------------------------------------------

    /// Current GPU memory usage for user-uploaded textures.
    ///
    /// Counts bytes from `upload_texture`, `upload_normal_map`, and
    /// `promote_texture`. Internal resources (shadow maps, colourmaps,
    /// IBL, post-processing targets) are not included.
    pub fn texture_memory_stats(&self) -> TextureMemoryStats {
        TextureMemoryStats {
            used_bytes: self.texture_allocated_bytes,
            texture_count: self.textures.len() as u32,
        }
    }

    // -----------------------------------------------------------------------
    // Per-frame async upload processing (called from prepare_scene_internal)
    // -----------------------------------------------------------------------

    /// Advance the async texture upload state machine.
    ///
    /// Called at the start of each `prepare_scene_internal`:
    /// 1. Marks entries whose copy was submitted on the previous frame as ready.
    /// 2. Submits `copy_buffer_to_texture` commands for newly queued entries.
    pub(crate) fn submit_pending_texture_uploads(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
    ) {
        if self.pending_texture_uploads.is_empty() {
            return;
        }

        // Step 1: entries submitted last frame are now safe to promote.
        for entry in &mut self.pending_texture_uploads {
            if entry.copy_submitted && !entry.ready {
                entry.ready = true;
            }
        }

        // Step 2: submit copy commands for entries not yet issued.
        let has_new = self
            .pending_texture_uploads
            .iter()
            .any(|e| !e.copy_submitted);
        if !has_new {
            return;
        }

        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("async_texture_copy"),
        });

        for entry in &mut self.pending_texture_uploads {
            if entry.copy_submitted {
                continue;
            }
            encoder.copy_buffer_to_texture(
                wgpu::TexelCopyBufferInfo {
                    buffer: &entry.staging_buf,
                    layout: wgpu::TexelCopyBufferLayout {
                        offset: 0,
                        bytes_per_row: Some(entry.aligned_bytes_per_row),
                        rows_per_image: Some(entry.height),
                    },
                },
                wgpu::TexelCopyTextureInfo {
                    texture: &entry.gpu_texture.texture,
                    mip_level: 0,
                    origin: wgpu::Origin3d::ZERO,
                    aspect: wgpu::TextureAspect::All,
                },
                wgpu::Extent3d {
                    width: entry.width,
                    height: entry.height,
                    depth_or_array_layers: 1,
                },
            );
            entry.copy_submitted = true;
        }

        queue.submit(std::iter::once(encoder.finish()));
    }

    /// Get or create a cached material bind group for (albedo, normal_map, ao_map) texture combo.
    ///
    /// `u64::MAX` sentinel means "use fallback texture for that slot".
    /// The bind group is cached in `material_bind_groups` keyed by the 3-tuple.
    #[allow(dead_code)]
    pub(crate) fn get_material_bind_group(
        &mut self,
        device: &wgpu::Device,
        albedo_id: Option<u64>,
        normal_map_id: Option<u64>,
        ao_map_id: Option<u64>,
    ) -> &wgpu::BindGroup {
        let key = (
            albedo_id.unwrap_or(u64::MAX),
            normal_map_id.unwrap_or(u64::MAX),
            ao_map_id.unwrap_or(u64::MAX),
        );

        if !self.material_bind_groups.contains_key(&key) {
            let albedo_view = match albedo_id {
                Some(id) if (id as usize) < self.textures.len() => &self.textures[id as usize].view,
                _ => &self.fallback_texture.view,
            };
            let normal_view = match normal_map_id {
                Some(id) if (id as usize) < self.textures.len() => &self.textures[id as usize].view,
                _ => &self.fallback_normal_map_view,
            };
            let ao_view = match ao_map_id {
                Some(id) if (id as usize) < self.textures.len() => &self.textures[id as usize].view,
                _ => &self.fallback_ao_map_view,
            };

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

        self.material_bind_groups.get(&key).unwrap()
    }

    /// Rebuild `mesh.object_bind_group` so it includes the texture views, LUT, and scalar
    /// buffer for the given material + attribute key. Called from `prepare()` when
    /// `mesh.last_tex_key` differs from the current frame's material/attribute state.
    ///
    /// The bind group layout is `object_bgl`:
    ///   binding 0 -> object uniform buffer
    ///   binding 1 -> albedo texture view
    ///   binding 2 -> material sampler (also used for LUT sampling)
    ///   binding 3 -> normal map view
    ///   binding 4 -> AO map view
    ///   binding 5 -> LUT (colourmap) texture view
    ///   binding 6 -> scalar attribute storage buffer
    pub(crate) fn update_mesh_texture_bind_group(
        &mut self,
        device: &wgpu::Device,
        mesh_id: crate::resources::mesh_store::MeshId,
        albedo_id: Option<u64>,
        normal_map_id: Option<u64>,
        ao_map_id: Option<u64>,
        lut_id: Option<ColourmapId>,
        active_attr: Option<&str>,
        matcap_id: Option<crate::resources::MatcapId>,
        warp_attr: Option<&str>,
        metallic_roughness_id: Option<u64>,
        emissive_texture_id: Option<u64>,
    ) {
        let hash_str = |name: &str| -> u64 {
            use std::hash::{Hash, Hasher};
            let mut h = std::collections::hash_map::DefaultHasher::new();
            name.hash(&mut h);
            h.finish()
        };
        let attr_hash = active_attr.map(|n| hash_str(n)).unwrap_or(u64::MAX);
        let warp_hash = warp_attr.map(|n| hash_str(n)).unwrap_or(u64::MAX);

        // The last two slots track GPU position/normal override (re)bind events.
        // Bumped by `set_*_override_buffer` / `clear_*_override`, so a fresh
        // override forces a bind-group rebuild here.
        let (pos_override_gen, nrm_override_gen) = {
            let Some(mesh) = self.mesh_store.get(mesh_id) else {
                return;
            };
            (mesh.position_override_gen, mesh.normal_override_gen)
        };

        let key = (
            albedo_id.unwrap_or(u64::MAX),
            normal_map_id.unwrap_or(u64::MAX),
            ao_map_id.unwrap_or(u64::MAX),
            lut_id.map(|id| id.0 as u64).unwrap_or(u64::MAX),
            attr_hash,
            matcap_id.map(|id| id.index as u64).unwrap_or(u64::MAX),
            warp_hash,
            metallic_roughness_id.unwrap_or(u64::MAX),
            emissive_texture_id.unwrap_or(u64::MAX),
            pos_override_gen,
            nrm_override_gen,
        );

        {
            let Some(mesh) = self.mesh_store.get(mesh_id) else {
                return;
            };
            if mesh.last_tex_key == key {
                return;
            }
        }

        let albedo_view = match albedo_id {
            Some(id) if (id as usize) < self.textures.len() => &self.textures[id as usize].view,
            _ => &self.fallback_texture.view,
        };
        let normal_view = match normal_map_id {
            Some(id) if (id as usize) < self.textures.len() => &self.textures[id as usize].view,
            _ => &self.fallback_normal_map_view,
        };
        let ao_view = match ao_map_id {
            Some(id) if (id as usize) < self.textures.len() => &self.textures[id as usize].view,
            _ => &self.fallback_ao_map_view,
        };
        let lut_view = match lut_id {
            Some(id) if id.0 < self.colourmap_views.len() => &self.colourmap_views[id.0],
            _ => &self.fallback_lut_view,
        };

        let Some(mesh) = self.mesh_store.get_mut(mesh_id) else {
            return;
        };

        let scalar_buf: &wgpu::Buffer = match active_attr {
            Some(name) => {
                let found_vertex = mesh.attribute_buffers.get(name);
                let found_face = mesh.face_attribute_buffers.get(name);
                found_vertex
                    .or(found_face)
                    .unwrap_or(&self.fallback_scalar_buf)
            }
            None => &self.fallback_scalar_buf,
        };

        let face_colour_buf: &wgpu::Buffer = match active_attr {
            Some(name) => mesh
                .face_colour_buffers
                .get(name)
                .unwrap_or(&self.fallback_face_colour_buf),
            None => &self.fallback_face_colour_buf,
        };

        // Resolve matcap texture view : fallback to 1x1 white when no matcap active.
        let matcap_view: &wgpu::TextureView = match matcap_id {
            Some(id) if id.index < self.matcap_views.len() => &self.matcap_views[id.index],
            _ => self
                .fallback_matcap_view
                .as_ref()
                .unwrap_or(&self.fallback_texture.view),
        };

        let warp_buf: &wgpu::Buffer = match warp_attr {
            Some(name) => mesh
                .vector_attribute_buffers
                .get(name)
                .unwrap_or(&self.fallback_warp_buf),
            None => &self.fallback_warp_buf,
        };

        let position_override_buf: &wgpu::Buffer = mesh
            .position_override_buffer
            .as_ref()
            .unwrap_or(&self.fallback_position_override_buf);
        let normal_override_buf: &wgpu::Buffer = mesh
            .normal_override_buffer
            .as_ref()
            .unwrap_or(&self.fallback_normal_override_buf);

        let metallic_roughness_view: &wgpu::TextureView = match metallic_roughness_id {
            Some(id) if (id as usize) < self.textures.len() => &self.textures[id as usize].view,
            _ => &self.fallback_metallic_roughness_texture_view,
        };
        let emissive_view: &wgpu::TextureView = match emissive_texture_id {
            Some(id) if (id as usize) < self.textures.len() => &self.textures[id as usize].view,
            _ => &self.fallback_emissive_texture_view,
        };

        mesh.object_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("object_bind_group"),
            layout: &self.object_bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: mesh.object_uniform_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: wgpu::BindingResource::TextureView(lut_view),
                },
                wgpu::BindGroupEntry {
                    binding: 6,
                    resource: scalar_buf.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 7,
                    resource: wgpu::BindingResource::TextureView(matcap_view),
                },
                wgpu::BindGroupEntry {
                    binding: 8,
                    resource: face_colour_buf.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 9,
                    resource: warp_buf.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 10,
                    resource: wgpu::BindingResource::Sampler(&self.lut_sampler),
                },
                wgpu::BindGroupEntry {
                    binding: 11,
                    resource: wgpu::BindingResource::TextureView(metallic_roughness_view),
                },
                wgpu::BindGroupEntry {
                    binding: 12,
                    resource: wgpu::BindingResource::TextureView(emissive_view),
                },
                wgpu::BindGroupEntry {
                    binding: 13,
                    resource: position_override_buf.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 14,
                    resource: normal_override_buf.as_entire_binding(),
                },
            ],
        });
        mesh.last_tex_key = key;
    }

    /// Upload a 256-sample RGBA colourmap to the GPU and return its `ColourmapId`.
    ///
    /// The returned ID can be stored in `SceneRenderItem::colourmap_id`.
    /// Use `BuiltinColourmap` variants + [`Self::builtin_colourmap_id`] for the built-in presets.
    pub fn upload_colourmap(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        rgba_data: &[[u8; 4]; 256],
    ) -> ColourmapId {
        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("lut_texture"),
            size: wgpu::Extent3d {
                width: 256,
                height: 1,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba8Unorm,
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        });
        let flat: Vec<u8> = rgba_data.iter().flat_map(|p| p.iter().copied()).collect();
        queue.write_texture(
            wgpu::TexelCopyTextureInfo {
                texture: &texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            &flat,
            wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(256 * 4),
                rows_per_image: Some(1),
            },
            wgpu::Extent3d {
                width: 256,
                height: 1,
                depth_or_array_layers: 1,
            },
        );
        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
        let id = ColourmapId(self.colourmap_textures.len());
        self.colourmap_textures.push(texture);
        self.colourmap_views.push(view);
        self.colourmaps_cpu.push(*rgba_data);
        id
    }

    /// Return the CPU-side colourmap LUT for `id` as 256 RGBA8 entries, or `None` if the id is invalid.
    ///
    /// Useful for any non-GPU colourmap output: PDF export, table cell colouring, custom legend
    /// widgets, or sampling a colour at a specific scalar value. The data is always in memory
    /// (kept for GPU upload) so this accessor is free.
    pub fn get_colourmap_rgba(&self, id: ColourmapId) -> Option<&[[u8; 4]; 256]> {
        self.colourmaps_cpu.get(id.0)
    }

    /// Return the `ColourmapId` for a built-in preset.
    ///
    /// Call [`Self::ensure_colourmaps_initialized`] first (done automatically by
    /// `ViewportRenderer::prepare`).  Panics if colourmaps have not been initialized yet.
    pub fn builtin_colourmap_id(&self, preset: BuiltinColourmap) -> ColourmapId {
        self.builtin_colourmap_ids
            .expect("call ensure_colourmaps_initialized before using built-in colourmaps")
            [preset as usize]
    }

    /// Ensure built-in colourmaps are uploaded to the GPU.
    ///
    /// Called automatically by `ViewportRenderer::prepare()` on the first frame.
    /// Safe to call multiple times : no-op after first invocation.
    pub fn ensure_colourmaps_initialized(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) {
        if self.colourmaps_initialized {
            return;
        }
        let viridis = self.upload_colourmap(
            device,
            queue,
            &crate::resources::colourmap_data::viridis_rgba(),
        );
        let plasma = self.upload_colourmap(
            device,
            queue,
            &crate::resources::colourmap_data::plasma_rgba(),
        );
        let greyscale = self.upload_colourmap(
            device,
            queue,
            &crate::resources::colourmap_data::greyscale_rgba(),
        );
        let coolwarm = self.upload_colourmap(
            device,
            queue,
            &crate::resources::colourmap_data::coolwarm_rgba(),
        );
        let rainbow = self.upload_colourmap(
            device,
            queue,
            &crate::resources::colourmap_data::rainbow_rgba(),
        );
        let magma = self.upload_colourmap(
            device,
            queue,
            &crate::resources::colourmap_data::magma_rgba(),
        );
        let inferno = self.upload_colourmap(
            device,
            queue,
            &crate::resources::colourmap_data::inferno_rgba(),
        );
        let turbo = self.upload_colourmap(
            device,
            queue,
            &crate::resources::colourmap_data::turbo_rgba(),
        );
        let jet = self.upload_colourmap(device, queue, &crate::resources::colourmap_data::jet_rgba());
        let rdbu = self.upload_colourmap(
            device,
            queue,
            &crate::resources::colourmap_data::rdbu_r_rgba(),
        );
        self.builtin_colourmap_ids = Some([
            viridis, plasma, greyscale, coolwarm, rainbow, magma, inferno, turbo, jet, rdbu,
        ]);
        self.colourmaps_initialized = true;
    }

    // -----------------------------------------------------------------------
    // Matcap texture API
    // -----------------------------------------------------------------------

    /// Upload a 256×256 RGBA matcap texture and return its `MatcapId`.
    ///
    /// `rgba_data` must be exactly `256 * 256 * 4 = 262_144` bytes.
    /// Set `blendable = true` for matcaps whose alpha channel tints the base
    /// geometry colour; `false` for static matcaps that fully replace the colour.
    ///
    /// # Errors
    ///
    /// Returns [`ViewportError::InvalidTextureData`](crate::error::ViewportError::InvalidTextureData)
    /// if `rgba_data` has the wrong length.
    pub fn upload_matcap(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        rgba_data: &[u8],
        blendable: bool,
    ) -> crate::error::ViewportResult<crate::resources::MatcapId> {
        let (width, height) = (256u32, 256u32);
        let expected = (width * height * 4) as usize;
        if rgba_data.len() != expected {
            return Err(crate::error::ViewportError::InvalidTextureData {
                expected,
                actual: rgba_data.len(),
            });
        }

        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("matcap_texture"),
            size: wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba8Unorm,
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        });
        queue.write_texture(
            wgpu::TexelCopyTextureInfo {
                texture: &texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            rgba_data,
            wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(width * 4),
                rows_per_image: Some(height),
            },
            wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
        );

        // Ensure the shared clamp sampler is created.
        if self.matcap_sampler.is_none() {
            self.matcap_sampler = Some(device.create_sampler(&wgpu::SamplerDescriptor {
                label: Some("matcap_sampler"),
                address_mode_u: wgpu::AddressMode::ClampToEdge,
                address_mode_v: wgpu::AddressMode::ClampToEdge,
                mag_filter: wgpu::FilterMode::Linear,
                min_filter: wgpu::FilterMode::Linear,
                mipmap_filter: wgpu::FilterMode::Nearest,
                ..Default::default()
            }));
        }

        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
        let index = self.matcap_textures.len();
        self.matcap_textures.push(texture);
        self.matcap_views.push(view);

        // Lazily initialise the fallback matcap view to binding 7 of the
        // first uploaded texture (a plain white 1×1 is fine as fallback).
        if self.fallback_matcap_view.is_none() {
            self.fallback_matcap_view = Some(
                self.fallback_texture
                    .texture
                    .create_view(&wgpu::TextureViewDescriptor::default()),
            );
        }

        tracing::debug!(matcap_index = index, blendable, "matcap uploaded");
        Ok(crate::resources::MatcapId { index, blendable })
    }

    /// Return the `MatcapId` for a built-in preset.
    ///
    /// Panics if called before the renderer has run at least one prepare pass
    /// (which calls [`Self::ensure_matcaps_initialized`] automatically).
    pub fn builtin_matcap_id(
        &self,
        preset: crate::resources::BuiltinMatcap,
    ) -> crate::resources::MatcapId {
        self.builtin_matcap_ids
            .expect("call ensure_matcaps_initialized (or run one prepare frame) before using built-in matcaps")
            [preset as usize]
    }

    /// Upload the eight built-in matcaps to the GPU if not already done.
    ///
    /// Called automatically by `ViewportRenderer::prepare()`. Safe to call
    /// multiple times : no-op after first invocation.
    pub fn ensure_matcaps_initialized(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) {
        if self.matcaps_initialized {
            return;
        }
        use crate::resources::matcap_data;
        let clay = self
            .upload_matcap(device, queue, &matcap_data::clay(), true)
            .unwrap();
        let wax = self
            .upload_matcap(device, queue, &matcap_data::wax(), true)
            .unwrap();
        let candy = self
            .upload_matcap(device, queue, &matcap_data::candy(), true)
            .unwrap();
        let flat = self
            .upload_matcap(device, queue, &matcap_data::flat(), true)
            .unwrap();
        let ceramic = self
            .upload_matcap(device, queue, &matcap_data::ceramic(), false)
            .unwrap();
        let jade = self
            .upload_matcap(device, queue, &matcap_data::jade(), false)
            .unwrap();
        let mud = self
            .upload_matcap(device, queue, &matcap_data::mud(), false)
            .unwrap();
        let normal = self
            .upload_matcap(device, queue, &matcap_data::normal(), false)
            .unwrap();
        self.builtin_matcap_ids = Some([clay, wax, candy, flat, ceramic, jade, mud, normal]);
        self.matcaps_initialized = true;
    }
}