viewport-lib 0.18.3

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

use crate::resources::mesh_store::MeshId;
use crate::resources::{DualPipeline, ViewportGpuResources};
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).
pub(crate) struct DecalGpuItem {
    pub blend_mode: crate::renderer::DecalBlendMode,
    pub _uniform_buf: wgpu::Buffer,
    pub bind_group: wgpu::BindGroup,
}

/// 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,
}

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

impl ViewportGpuResources {
    /// 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 = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("decal_shader"),
            source: wgpu::ShaderSource::Wgsl(
                include_str!(concat!(env!("OUT_DIR"), "/decal.wgsl")).into(),
            ),
        });

        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: &[],
        });

        let make = |fmt: wgpu::TextureFormat, blend: wgpu::BlendState| {
            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                label: Some("decal_pipeline"),
                layout: Some(&layout),
                vertex: wgpu::VertexState {
                    module: &shader,
                    entry_point: Some("vs_main"),
                    buffers: &[],
                    compilation_options: wgpu::PipelineCompilationOptions::default(),
                },
                fragment: Some(wgpu::FragmentState {
                    module: &shader,
                    entry_point: Some("fs_main"),
                    targets: &[Some(wgpu::ColorTargetState {
                        format: fmt,
                        blend: Some(blend),
                        write_mask: wgpu::ColorWrites::ALL,
                    })],
                    compilation_options: wgpu::PipelineCompilationOptions::default(),
                }),
                primitive: wgpu::PrimitiveState {
                    topology: wgpu::PrimitiveTopology::TriangleList,
                    cull_mode: None,
                    ..Default::default()
                },
                // No depth attachment: decals read depth as a texture, they do not
                // write to the depth buffer.
                depth_stencil: None,
                multisample: wgpu::MultisampleState::default(),
                multiview: None,
                cache: None,
            })
        };

        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),
        });
    }

    /// 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 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;

        let raw = 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,
        };

        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<u64>| -> &wgpu::TextureView {
            id.and_then(|i| self.textures.get(i as usize))
                .map(|t| &t.view)
                .unwrap_or(&self.fallback_texture.view)
        };

        let tex_view = self
            .textures
            .get(item.texture_id as usize)
            .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,
        }
    }

    /// 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 = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("decal_exclude_shader"),
            source: wgpu::ShaderSource::Wgsl(
                include_str!(concat!(env!("OUT_DIR"), "/decal_exclude.wgsl")).into(),
            ),
        });

        let obj_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("decal_exclude_obj_bgl"),
            entries: &[wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: wgpu::ShaderStages::VERTEX,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Uniform,
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            }],
        });

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

        // 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,
        }
    }
}