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
//! Screen-space decal pipeline (D1 + D2 + D5).

use crate::resources::mesh::mesh_store::MeshId;
use crate::resources::{DeviceResources, DualPipeline};
use wgpu::util::DeviceExt as _;

// ---------------------------------------------------------------------------
// GPU-internal types
// ---------------------------------------------------------------------------

/// Flat uniform buffer matching the WGSL `DecalUniform` struct (144 bytes).
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct DecalUniformRaw {
    pub inv_transform: [[f32; 4]; 4], // 64 bytes
    pub blend_mode: u32,              //  4
    pub alpha: f32,                   //  4
    pub normal_blend_strength: f32,   //  4
    pub has_normal: u32,              //  4
    // D3
    pub roughness: f32,         //  4
    pub metallic: f32,          //  4
    pub has_roughness_tex: u32, //  4
    pub has_metallic_tex: u32,  //  4
    // D4 -- vec2 pairs, 8-byte aligned
    pub uv_offset: [f32; 2], //  8
    pub uv_scale: [f32; 2],  //  8
    // D6
    pub emissive: f32,         //  4
    pub has_emissive_tex: u32, //  4
    // D7
    pub edge_fade: f32, //  4
    pub _pad: u32,      //  4  (alignment gap before D8)
    // D8
    pub projection: u32,          //  4  (0 = Planar, 1 = TriPlanar)
    pub tri_blend_sharpness: f32, //  4
    pub _pad2: u32,               //  4  (pad to 144-byte struct size)
    pub _pad3: u32,               //  4
                                  // total: 144 bytes
}

/// Per-draw GPU data for one [`DecalItem`](crate::renderer::DecalItem).
///
/// `Clone` is cheap: the buffer and bind group are reference-counted GPU
/// handles, so cloning bumps a refcount rather than reallocating. This lets the
/// per-frame decal cache hand the same GPU resources to the draw list without
/// rebuilding them.
#[derive(Clone)]
pub(crate) struct DecalGpuItem {
    pub blend_mode: crate::renderer::DecalBlendMode,
    pub _uniform_buf: wgpu::Buffer,
    pub bind_group: wgpu::BindGroup,
    /// Decal model matrix (local-space unit cube -> world). Used at draw time
    /// to compute a per-decal scissor rect so the fullscreen decal quad only
    /// shades the decal's screen footprint instead of the whole framebuffer.
    pub model: glam::Mat4,
    /// Whether this decal is selected. Selected decals contribute to the decal
    /// outline mask so a ring is traced around their footprint.
    pub selected: bool,
}

/// Per-draw GPU data for one non-receiver surface in the decal exclude pass (D5).
pub(crate) struct DecalExcludeGpuItem {
    pub mesh_id: MeshId,
    pub _uniform_buf: wgpu::Buffer,
    pub bind_group: wgpu::BindGroup,
}

/// Build the flat uniform for a decal. Pure: no GPU access, so it can also feed
/// the content hash used to cache GPU resources across frames.
pub(crate) fn decal_uniform_raw(item: &crate::renderer::DecalItem) -> DecalUniformRaw {
    let model = glam::Mat4::from_cols_array_2d(&item.transform);
    let inv_transform = model.inverse().to_cols_array_2d();

    let blend_mode_u32 = match item.blend_mode {
        crate::renderer::DecalBlendMode::Replace => 0u32,
        crate::renderer::DecalBlendMode::Multiply => 1u32,
        // Additive uses a separate pipeline; shader logic is identical to Replace.
        crate::renderer::DecalBlendMode::Additive => 0u32,
    };

    let (projection_u32, tri_blend_sharpness) = match item.projection {
        crate::renderer::DecalProjection::Planar => (0u32, 1.0f32),
        crate::renderer::DecalProjection::TriPlanar { blend_sharpness } => {
            (1u32, blend_sharpness.max(0.1))
        }
        crate::renderer::DecalProjection::Cylindrical { facing } => {
            let code = match facing {
                crate::renderer::CylindricalFacing::Outward => 2u32,
                crate::renderer::CylindricalFacing::Inward => 3u32,
            };
            (code, 0.0f32)
        }
    };

    let has_normal = item.normal_texture_id.is_some() as u32;
    let has_roughness_tex = item.roughness_texture_id.is_some() as u32;
    let has_metallic_tex = item.metallic_texture_id.is_some() as u32;
    let has_emissive_tex = item.emissive_texture_id.is_some() as u32;

    DecalUniformRaw {
        inv_transform,
        blend_mode: blend_mode_u32,
        alpha: item.alpha,
        normal_blend_strength: if has_normal != 0 {
            item.normal_blend_strength
        } else {
            0.0
        },
        has_normal,
        roughness: item.roughness,
        metallic: item.metallic,
        has_roughness_tex,
        has_metallic_tex,
        uv_offset: item.uv_offset,
        uv_scale: item.uv_scale,
        emissive: item.emissive,
        has_emissive_tex,
        edge_fade: item.edge_fade.clamp(0.0, 0.5),
        _pad: 0,
        projection: projection_u32,
        tri_blend_sharpness,
        _pad2: 0,
        _pad3: 0,
    }
}

/// Content hash for a decal, covering everything that affects its GPU
/// resources: the uniform bytes, the bound texture ids, and the blend mode
/// (which the uniform does not distinguish between Replace and Additive but
/// which selects a different pipeline at draw time).
///
/// Two decals with the same hash produce identical GPU resources, so the cache
/// can reuse one across frames instead of rebuilding a buffer and bind group.
pub(crate) fn hash_decal_item(item: &crate::renderer::DecalItem) -> u64 {
    use std::hash::Hasher as _;
    let raw = decal_uniform_raw(item);
    let mut h = std::collections::hash_map::DefaultHasher::new();
    h.write(bytemuck::bytes_of(&raw));
    h.write_u8(item.blend_mode as u8);
    h.write_u64(item.texture_id.raw());
    for id in [
        item.normal_texture_id,
        item.roughness_texture_id,
        item.metallic_texture_id,
        item.emissive_texture_id,
    ] {
        h.write_u8(id.is_some() as u8);
        h.write_u64(id.map(|t| t.raw()).unwrap_or(0));
    }
    h.finish()
}

// ---------------------------------------------------------------------------
// Cluster resources
// ---------------------------------------------------------------------------

/// Screen-space decal pipelines and their bind group layouts.
///
/// All fields are lazily built: the render pipelines and item BGL by
/// `ensure_decal_pipeline`, the exclude pipeline by `ensure_decal_exclude_pipeline`,
/// and `depth_bgl` / `sampler` by `ensure_hdr_shared`.
#[derive(Default)]
pub(crate) struct DecalResources {
    /// Replace-blend decal pipeline (LDR + HDR). None until first decal is submitted.
    pub(crate) replace_pipeline: Option<DualPipeline>,
    /// Multiply-blend decal pipeline (LDR + HDR). None until first decal is submitted.
    pub(crate) multiply_pipeline: Option<DualPipeline>,
    /// Additive-blend decal pipeline (LDR + HDR). None until first decal is submitted.
    pub(crate) additive_pipeline: Option<DualPipeline>,
    /// BGL for group 1 of the decal pass: depth texture + stencil texture bindings.
    pub(crate) depth_bgl: Option<wgpu::BindGroupLayout>,
    /// BGL for group 2 of the decal pass: uniform buffer + albedo texture + sampler.
    pub(crate) item_bgl: Option<wgpu::BindGroupLayout>,
    /// Linear-clamp sampler used by the decal fragment shader.
    pub(crate) sampler: Option<wgpu::Sampler>,
    /// Pipeline that writes stencil = 0 for non-receiver surfaces (D5).
    pub(crate) exclude_pipeline: Option<wgpu::RenderPipeline>,
    /// BGL for group 1 of the decal exclude pass: one model matrix uniform buffer.
    pub(crate) exclude_obj_bgl: Option<wgpu::BindGroupLayout>,
    /// Pipeline that stamps a selected decal's footprint into the R8 outline
    /// mask. Reuses the decal colour pass's bind groups (camera, depth+stencil,
    /// per-decal uniform). None until first selected decal is submitted.
    pub(crate) outline_mask_pipeline: Option<wgpu::RenderPipeline>,
    /// Fullscreen edge-detect pipeline that traces the outline ring from the
    /// decal outline mask onto the HDR colour target with alpha blending.
    pub(crate) outline_edge_pipeline: Option<wgpu::RenderPipeline>,
    /// BGL for the edge-detect pass: mask texture + sampler + edge uniform.
    pub(crate) outline_edge_bgl: Option<wgpu::BindGroupLayout>,
    /// Cached outline-mask target and edge bind group, rebuilt only when the
    /// viewport size changes so the outline pass allocates nothing per frame.
    pub(crate) outline_targets: Option<DecalOutlineTargets>,
}

/// Persistent GPU resources for the decal outline pass, keyed by viewport size.
/// Only the edge uniform contents change per frame (refreshed with
/// `queue.write_buffer`); the texture, view, buffer, and bind group are reused.
pub(crate) struct DecalOutlineTargets {
    pub(crate) width: u32,
    pub(crate) height: u32,
    /// R8 mask the selected decals stamp their footprint into.
    pub(crate) mask_view: wgpu::TextureView,
    /// Retained so the view stays valid; not read directly.
    pub(crate) _mask_tex: wgpu::Texture,
    /// Edge-detect uniform (outline colour, width, viewport size).
    pub(crate) edge_uniform_buf: wgpu::Buffer,
    /// Edge-detect bind group: mask view + sampler + edge uniform.
    pub(crate) edge_bind_group: wgpu::BindGroup,
}

// ---------------------------------------------------------------------------
// Pipeline init and upload (impl DeviceResources)
// ---------------------------------------------------------------------------

impl DeviceResources {
    /// Lazily create the decal render pipelines and item bind group layout.
    ///
    /// No-op if already created.  Requires `decal_depth_bgl` to exist (created
    /// by `ensure_hdr_shared`).
    pub(crate) fn ensure_decal_pipeline(&mut self, device: &wgpu::Device) {
        if self.decal.replace_pipeline.is_some() {
            return;
        }

        let shader = crate::resources::builders::wgsl_module(
            device,
            "decal_shader",
            crate::resources::builders::wgsl_source!("decal"),
        );

        let tex2d_entry = |binding: u32| wgpu::BindGroupLayoutEntry {
            binding,
            visibility: wgpu::ShaderStages::FRAGMENT,
            ty: wgpu::BindingType::Texture {
                sample_type: wgpu::TextureSampleType::Float { filterable: true },
                view_dimension: wgpu::TextureViewDimension::D2,
                multisampled: false,
            },
            count: None,
        };

        // Group 2: per-item uniforms + textures.
        //  0: DecalUniform buffer
        //  1: albedo texture
        //  2: sampler (shared by all texture slots)
        //  3: normal map    (D2; fallback_texture when absent)
        //  4: roughness map (D3; fallback_texture when absent)
        //  5: metallic map  (D3; fallback_texture when absent)
        //  6: emissive map  (D6; fallback_texture when absent)
        let item_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("decal_item_bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
                tex2d_entry(1),
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
                tex2d_entry(3), // D2: normal map
                tex2d_entry(4), // D3: roughness map
                tex2d_entry(5), // D3: metallic map
                tex2d_entry(6), // D6: emissive map
            ],
        });

        let depth_bgl = self
            .decal
            .depth_bgl
            .as_ref()
            .expect("decal_depth_bgl must exist before ensure_decal_pipeline");

        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("decal_pipeline_layout"),
            bind_group_layouts: &[&self.camera_bind_group_layout, depth_bgl, &item_bgl],
            push_constant_ranges: &[],
        });

        // No depth attachment: decals read depth as a texture, they do not write
        // to the depth buffer. Blend mode is the only thing that varies.
        let make = |fmt: wgpu::TextureFormat, blend: wgpu::BlendState| {
            crate::resources::builders::build_fullscreen_pipeline(
                device,
                "decal_pipeline",
                &layout,
                &shader,
                fmt,
                Some(blend),
            )
        };

        let replace_blend = wgpu::BlendState::ALPHA_BLENDING;
        // Multiply: result.rgb = dst.rgb * src.rgb; result.a = dst.a.
        let multiply_blend = wgpu::BlendState {
            color: wgpu::BlendComponent {
                src_factor: wgpu::BlendFactor::Zero,
                dst_factor: wgpu::BlendFactor::Src,
                operation: wgpu::BlendOperation::Add,
            },
            alpha: wgpu::BlendComponent {
                src_factor: wgpu::BlendFactor::Zero,
                dst_factor: wgpu::BlendFactor::One,
                operation: wgpu::BlendOperation::Add,
            },
        };
        // Additive: result.rgb = dst.rgb + src.rgb * src.a; result.a = dst.a.
        // src.a modulates the additive contribution so alpha still controls intensity.
        let additive_blend = wgpu::BlendState {
            color: wgpu::BlendComponent {
                src_factor: wgpu::BlendFactor::SrcAlpha,
                dst_factor: wgpu::BlendFactor::One,
                operation: wgpu::BlendOperation::Add,
            },
            alpha: wgpu::BlendComponent {
                src_factor: wgpu::BlendFactor::Zero,
                dst_factor: wgpu::BlendFactor::One,
                operation: wgpu::BlendOperation::Add,
            },
        };

        self.decal.item_bgl = Some(item_bgl);
        self.decal.replace_pipeline = Some(DualPipeline {
            ldr: make(self.target_format, replace_blend),
            hdr: make(wgpu::TextureFormat::Rgba16Float, replace_blend),
        });
        self.decal.multiply_pipeline = Some(DualPipeline {
            ldr: make(self.target_format, multiply_blend),
            hdr: make(wgpu::TextureFormat::Rgba16Float, multiply_blend),
        });
        self.decal.additive_pipeline = Some(DualPipeline {
            ldr: make(self.target_format, additive_blend),
            hdr: make(wgpu::TextureFormat::Rgba16Float, additive_blend),
        });
    }

    /// Lazily create the decal outline mask + edge-detect pipelines.
    ///
    /// No-op if already created. Requires `ensure_decal_pipeline` to have run
    /// first (it creates `item_bgl`) and `depth_bgl` to exist (created by
    /// `ensure_hdr_shared`). The mask pipeline reuses the decal colour pass's
    /// three bind groups, so no new per-decal resources are needed.
    pub(crate) fn ensure_decal_outline_pipelines(&mut self, device: &wgpu::Device) {
        if self.decal.outline_mask_pipeline.is_some() {
            return;
        }

        let (Some(depth_bgl), Some(item_bgl)) =
            (self.decal.depth_bgl.as_ref(), self.decal.item_bgl.as_ref())
        else {
            return;
        };

        // Mask pipeline: stamp the decal footprint into an R8 mask.
        let mask_shader = crate::resources::builders::wgsl_module(
            device,
            "decal_outline_mask_shader",
            crate::resources::builders::wgsl_source!("decal_outline_mask"),
        );
        let mask_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("decal_outline_mask_layout"),
            bind_group_layouts: &[&self.camera_bind_group_layout, depth_bgl, item_bgl],
            push_constant_ranges: &[],
        });
        let mask_pipeline = crate::resources::builders::build_fullscreen_pipeline(
            device,
            "decal_outline_mask_pipeline",
            &mask_layout,
            &mask_shader,
            crate::resources::MASK_COLOR_FORMAT,
            None,
        );

        // Edge pipeline: ring edge-detect over the mask, blended onto HDR.
        let edge_shader = crate::resources::builders::wgsl_module(
            device,
            "decal_outline_edge_shader",
            crate::resources::builders::wgsl_source!("outline_edge"),
        );
        let edge_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("decal_outline_edge_bgl"),
            entries: &[
                crate::resources::builders::texture_entry(0, wgpu::ShaderStages::FRAGMENT),
                crate::resources::builders::sampler_entry(1, wgpu::ShaderStages::FRAGMENT),
                crate::resources::builders::uniform_entry(2, wgpu::ShaderStages::FRAGMENT),
            ],
        });
        let edge_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("decal_outline_edge_layout"),
            bind_group_layouts: &[&edge_bgl],
            push_constant_ranges: &[],
        });
        let edge_pipeline = crate::resources::builders::build_fullscreen_pipeline(
            device,
            "decal_outline_edge_pipeline",
            &edge_layout,
            &edge_shader,
            wgpu::TextureFormat::Rgba16Float,
            Some(wgpu::BlendState::ALPHA_BLENDING),
        );

        self.decal.outline_mask_pipeline = Some(mask_pipeline);
        self.decal.outline_edge_pipeline = Some(edge_pipeline);
        self.decal.outline_edge_bgl = Some(edge_bgl);
    }

    /// Ensure the persistent decal-outline mask target and edge bind group exist
    /// at `(w, h)`, rebuilding only when the size changes. This keeps the outline
    /// pass allocation-free per frame: only the edge uniform contents are
    /// refreshed (by the caller, via `queue.write_buffer`). Call after
    /// `ensure_decal_outline_pipelines`.
    pub(crate) fn ensure_decal_outline_targets(&mut self, device: &wgpu::Device, w: u32, h: u32) {
        if let Some(t) = &self.decal.outline_targets {
            if t.width == w && t.height == h {
                return;
            }
        }
        let (Some(edge_bgl), Some(sampler)) = (
            self.decal.outline_edge_bgl.as_ref(),
            self.decal.sampler.as_ref(),
        ) else {
            return;
        };

        let mask_tex = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("decal_outline_mask_tex"),
            size: wgpu::Extent3d {
                width: w,
                height: h,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: crate::resources::MASK_COLOR_FORMAT,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
            view_formats: &[],
        });
        let mask_view = mask_tex.create_view(&wgpu::TextureViewDescriptor::default());
        let edge_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("decal_outline_edge_uniform_buf"),
            size: std::mem::size_of::<crate::resources::OutlineEdgeUniform>() as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let edge_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("decal_outline_edge_bg"),
            layout: edge_bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(&mask_view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(sampler),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: edge_uniform_buf.as_entire_binding(),
                },
            ],
        });
        self.decal.outline_targets = Some(DecalOutlineTargets {
            width: w,
            height: h,
            mask_view,
            _mask_tex: mask_tex,
            edge_uniform_buf,
            edge_bind_group,
        });
    }

    /// Create the per-viewport depth+stencil bind group used by the decal pass.
    ///
    /// Must be called after `ensure_hdr_shared` (which creates `decal_depth_bgl`).
    /// Rebuilt when the viewport is resized.
    pub(crate) fn create_decal_depth_bg(
        &self,
        device: &wgpu::Device,
        depth_only_view: &wgpu::TextureView,
        stencil_only_view: &wgpu::TextureView,
    ) -> wgpu::BindGroup {
        let bgl = self
            .decal
            .depth_bgl
            .as_ref()
            .expect("decal_depth_bgl not created");
        device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("decal_depth_bg"),
            layout: bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(depth_only_view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::TextureView(stencil_only_view),
                },
            ],
        })
    }

    /// Upload one [`DecalItem`](crate::renderer::DecalItem) to GPU and return the per-draw data.
    ///
    /// Panics if called before `ensure_decal_pipeline`.
    pub(crate) fn upload_decal_item(
        &self,
        device: &wgpu::Device,
        item: &crate::renderer::DecalItem,
    ) -> DecalGpuItem {
        let model = glam::Mat4::from_cols_array_2d(&item.transform);
        let raw = decal_uniform_raw(item);

        let uniform_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("decal_uniform_buf"),
            contents: bytemuck::bytes_of(&raw),
            usage: wgpu::BufferUsages::UNIFORM,
        });

        let resolve_tex = |id: Option<crate::resources::TextureId>| -> &wgpu::TextureView {
            id.and_then(|i| self.content.textures.get(i))
                .map(|t| &t.view)
                .unwrap_or(&self.fallback_texture.view)
        };

        let tex_view = self
            .content
            .textures
            .get(item.texture_id)
            .map(|t| &t.view)
            .unwrap_or(&self.fallback_texture.view);
        let normal_view = resolve_tex(item.normal_texture_id);
        let roughness_view = resolve_tex(item.roughness_texture_id);
        let metallic_view = resolve_tex(item.metallic_texture_id);
        let emissive_view = resolve_tex(item.emissive_texture_id);

        let bgl = self
            .decal
            .item_bgl
            .as_ref()
            .expect("ensure_decal_pipeline not called");

        let sampler = self
            .decal
            .sampler
            .as_ref()
            .expect("decal_sampler not created");

        let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("decal_item_bg"),
            layout: bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: uniform_buf.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::TextureView(tex_view),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: wgpu::BindingResource::Sampler(sampler),
                },
                wgpu::BindGroupEntry {
                    binding: 3,
                    resource: wgpu::BindingResource::TextureView(normal_view),
                },
                wgpu::BindGroupEntry {
                    binding: 4,
                    resource: wgpu::BindingResource::TextureView(roughness_view),
                },
                wgpu::BindGroupEntry {
                    binding: 5,
                    resource: wgpu::BindingResource::TextureView(metallic_view),
                },
                wgpu::BindGroupEntry {
                    binding: 6,
                    resource: wgpu::BindingResource::TextureView(emissive_view),
                },
            ],
        });

        DecalGpuItem {
            blend_mode: item.blend_mode,
            _uniform_buf: uniform_buf,
            bind_group,
            model,
            selected: item.settings.selected,
        }
    }

    /// Lazily create the decal exclude pipeline and its object BGL (D5).
    ///
    /// No-op if already created. Must be called after `camera_bind_group_layout` exists.
    pub(crate) fn ensure_decal_exclude_pipeline(&mut self, device: &wgpu::Device) {
        if self.decal.exclude_pipeline.is_some() {
            return;
        }

        let shader = crate::resources::builders::wgsl_module(
            device,
            "decal_exclude_shader",
            crate::resources::builders::wgsl_source!("decal_exclude"),
        );

        let obj_bgl = crate::resources::builders::uniform_bgl(
            device,
            "decal_exclude_obj_bgl",
            wgpu::ShaderStages::VERTEX,
        );

        let layout = crate::resources::builders::standard_scene_layout(
            device,
            "decal_exclude_pipeline_layout",
            &self.camera_bind_group_layout,
            &obj_bgl,
        );

        // Vertex layout: position only (location 0, Float32x3).
        // Stride matches the full Vertex struct (64 bytes) but we only read pos.
        let vertex_layout = wgpu::VertexBufferLayout {
            array_stride: 64,
            step_mode: wgpu::VertexStepMode::Vertex,
            attributes: &[wgpu::VertexAttribute {
                format: wgpu::VertexFormat::Float32x3,
                offset: 0,
                shader_location: 0,
            }],
        };

        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("decal_exclude_pipeline"),
            layout: Some(&layout),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("vs_main"),
                buffers: &[vertex_layout],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: &shader,
                entry_point: Some("fs_main"),
                targets: &[],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                cull_mode: None,
                ..Default::default()
            },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: wgpu::TextureFormat::Depth24PlusStencil8,
                depth_write_enabled: false,
                depth_compare: wgpu::CompareFunction::LessEqual,
                stencil: wgpu::StencilState {
                    front: wgpu::StencilFaceState {
                        compare: wgpu::CompareFunction::Always,
                        fail_op: wgpu::StencilOperation::Keep,
                        depth_fail_op: wgpu::StencilOperation::Keep,
                        pass_op: wgpu::StencilOperation::Replace,
                    },
                    back: wgpu::StencilFaceState {
                        compare: wgpu::CompareFunction::Always,
                        fail_op: wgpu::StencilOperation::Keep,
                        depth_fail_op: wgpu::StencilOperation::Keep,
                        pass_op: wgpu::StencilOperation::Replace,
                    },
                    read_mask: 0xff,
                    write_mask: 0xff,
                },
                // Slight negative bias so the re-projected geometry reliably passes
                // the LessEqual depth test against values written by the opaque pass.
                // Without this, floating-point rounding differences between two
                // separate render passes of the same geometry can cause the depth
                // test to fail intermittently, leaving stencil un-written.
                bias: wgpu::DepthBiasState {
                    constant: -2,
                    slope_scale: 0.0,
                    clamp: 0.0,
                },
            }),
            multisample: wgpu::MultisampleState::default(),
            multiview: None,
            cache: None,
        });

        self.decal.exclude_obj_bgl = Some(obj_bgl);
        self.decal.exclude_pipeline = Some(pipeline);
    }

    /// Upload one non-receiver surface for the decal exclude pass and return per-draw data.
    ///
    /// Panics if called before `ensure_decal_exclude_pipeline`.
    pub(crate) fn upload_decal_exclude_item(
        &self,
        device: &wgpu::Device,
        mesh_id: MeshId,
        model: [[f32; 4]; 4],
    ) -> DecalExcludeGpuItem {
        let uniform_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("decal_exclude_uniform_buf"),
            contents: bytemuck::cast_slice(&model),
            usage: wgpu::BufferUsages::UNIFORM,
        });

        let bgl = self
            .decal
            .exclude_obj_bgl
            .as_ref()
            .expect("ensure_decal_exclude_pipeline not called");

        let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("decal_exclude_obj_bg"),
            layout: bgl,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: uniform_buf.as_entire_binding(),
            }],
        });

        DecalExcludeGpuItem {
            mesh_id,
            _uniform_buf: uniform_buf,
            bind_group,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::hash_decal_item;
    use crate::renderer::{DecalBlendMode, DecalItem};

    #[test]
    fn identical_decals_hash_equal() {
        let a = DecalItem {
            texture_id: crate::resources::TextureId(3),
            ..DecalItem::default()
        };
        let b = a.clone();
        assert_eq!(hash_decal_item(&a), hash_decal_item(&b));
    }

    #[test]
    fn blend_mode_changes_hash() {
        // Replace and Additive encode the same uniform bytes but select
        // different pipelines, so they must not share a cache entry.
        let replace = DecalItem {
            blend_mode: DecalBlendMode::Replace,
            ..DecalItem::default()
        };
        let additive = DecalItem {
            blend_mode: DecalBlendMode::Additive,
            ..DecalItem::default()
        };
        assert_ne!(hash_decal_item(&replace), hash_decal_item(&additive));
    }

    #[test]
    fn texture_and_transform_change_hash() {
        let base = DecalItem::default();
        let tex = DecalItem {
            texture_id: crate::resources::TextureId(7),
            ..DecalItem::default()
        };
        assert_ne!(hash_decal_item(&base), hash_decal_item(&tex));

        let mut moved = DecalItem::default();
        moved.transform[3][0] = 5.0;
        assert_ne!(hash_decal_item(&base), hash_decal_item(&moved));
    }
}