gizmo-renderer 0.9.1

A custom ECS and physics engine aimed for realistic simulations.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
use crate::gpu_types::Vertex;
use crate::pipeline::{load_shader, load_shader_composed, SceneState};

// Single source of truth for the deferred G-buffer render-target formats.
//
// These are a TIGHT coupling, not a style preference: the G-buffer textures and
// *every* pipeline that renders into them (the geometry pass here, plus decals,
// forward blends, etc.) must declare an identical `ColorTargetState.format`, or
// wgpu aborts the whole frame with a validation error the instant that pipeline
// is drawn. A stray `Rgba16Float` on the decal pipeline caused exactly that
// crash (see decal.rs). Reference these constants instead of the raw literals so
// the formats can never silently drift apart again.
// Albedo is **sRGB**, and the difference is not cosmetic. What is written here is linear light,
// and linear 8-bit spends its codes where the eye has least: the perceptual range 0–32/255 gets
// **4 codes** in a linear target against 32 in an sRGB one, and the first linear code already
// sits at a perceptual 12.7/255. Measured through the real pipeline, albedo 0.004 and 0.0045
// rendered **byte-identically** before this changed. That range is not a corner case for this
// engine — its flagship level is a night city whose frame medians sit at 1–14/255. Alpha carries
// metallic and is untouched by the transfer function, and the byte budget is unchanged, so this
// costs nothing. Guarded by `golden_render_tests::two_different_dark_materials_do_not_render_identically`.
pub const GBUFFER_ALBEDO_METALLIC_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8UnormSrgb;
pub const GBUFFER_NORMAL_ROUGHNESS_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
// World position is Rgba16Float and CANNOT be upgraded to Rgba32Float: the four G-buffer
// MRTs share a `max_color_attachment_bytes_per_sample` budget of 32 (the WebGPU-guaranteed
// limit). Current cost: 4 (albedo Rgba8) + 8 (normal Rgba16F) + 8 (position Rgba16F) +
// 8 (tangent Rgba16F) = 28 ≤ 32. Rgba32Float position would make it 36 > 32 and wgpu
// rejects the pipeline. (The gbuffer.wgsl header comment claiming Rgba32Float was stale.)
//
// **The precision this used to cost is no longer paid, and the way out was not a wider format.**
// The budget is about the bytes, not about what goes in them. Absolute coordinates in f16
// quantise to 6 cm at 100 m from the origin, 50 cm at 1 km and a full metre at 2 km — against a
// nearest-cascade shadow texel of 4.3 mm, so a city-sized level sampled its shadows, view vector
// and fog from a position rounded to the nearest half-metre. Measured: moving an entire scene
// 2 km from the origin changed **9.7 %** of the frame. `gbuffer.wgsl` now writes the position
// relative to the camera and every reader adds it back, which keeps the same eight bytes and puts
// the stored values at view scale, where f16 is good to centimetres anywhere in the world.
// `golden_render_tests::a_scene_renders_the_same_two_kilometres_from_the_origin` is the guard,
// and it was checked against the old form, where it fails.
//
// The other half of that `.w` slot turned out to be worse than quantisation and is now fixed:
// subsurface goes in the integer part and anisotropy in the fraction, so the pack has to `floor`
// the integer part or subsurface's own fraction lands in anisotropy's slot. It did not, and the
// result was not noise but inversion — subsurface 0.234 with anisotropy 0 decoded as 0.82, and
// the same subsurface with anisotropy 1 decoded as 0. Pinned by
// `gbuffer_packing_tests::subsurface_and_anisotropy_survive_the_round_trip`, which fails on the
// old form. Subsurface is still quantised to 1 %, which the `/100` decode always implied.
pub const GBUFFER_WORLD_POSITION_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
pub const GBUFFER_WORLD_TANGENT_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;

/// G-Buffer textures, pipelines and bind groups for the deferred rendering path.
pub struct DeferredState {
    // G-buffer colour targets
    pub albedo_metallic_tex: wgpu::Texture,
    pub albedo_metallic_view: wgpu::TextureView,
    pub normal_roughness_tex: wgpu::Texture,
    pub normal_roughness_view: wgpu::TextureView,
    pub world_position_tex: wgpu::Texture,
    pub world_position_view: wgpu::TextureView,
    pub world_tangent_tex: wgpu::Texture,
    pub world_tangent_view: wgpu::TextureView,

    // Geometry pass (writes to 4 MRTs)
    pub gbuffer_pipeline: wgpu::RenderPipeline,
    /// The same pipeline with back-face culling off, for a material that declared itself
    /// [`double-sided`](crate::components::Material::is_double_sided).
    ///
    /// The flag and its builder have existed all along and only `gizmo-studio` acted on them, so
    /// a cloth or a leaf authored double-sided showed both faces in the editor and lost its back
    /// faces in the game — the deferred path culled unconditionally. Two pipelines rather than a
    /// per-draw state because wgpu bakes the cull mode into the pipeline.
    pub gbuffer_double_sided_pipeline: wgpu::RenderPipeline,

    // Z-Prepass (Depth only)
    pub z_prepass_pipeline: wgpu::RenderPipeline,
    /// Depth for double-sided geometry. Needed alongside the G-buffer variant, not instead of it:
    /// the prepass owns the depth these fragments are tested against, so culling here would
    /// discard the back face's depth and leave the G-buffer pass drawing it against whatever was
    /// behind.
    pub z_prepass_double_sided_pipeline: wgpu::RenderPipeline,

    // Lighting pass (fullscreen triangle → HDR texture)
    pub lighting_pipeline: wgpu::RenderPipeline,

    // Bind group used by the lighting pass to read the G-buffers
    pub gbuffer_bind_group_layout: wgpu::BindGroupLayout,
    pub gbuffer_bind_group: wgpu::BindGroup,
    pub gbuf_sampler: wgpu::Sampler,

    pub width: u32,
    pub height: u32,
}

impl DeferredState {
    pub fn new(device: &wgpu::Device, scene: &SceneState, width: u32, height: u32) -> Self {
        let (
            albedo_metallic_tex,
            albedo_metallic_view,
            normal_roughness_tex,
            normal_roughness_view,
            world_position_tex,
            world_position_view,
            world_tangent_tex,
            world_tangent_view,
            gbuf_sampler,
        ) = Self::create_gbuffer_textures(device, width, height);

        let gbuffer_bind_group_layout = Self::create_gbuffer_layout(device);

        let gbuffer_bind_group = Self::create_gbuffer_bind_group(
            device,
            &gbuffer_bind_group_layout,
            &albedo_metallic_view,
            &normal_roughness_view,
            &world_position_view,
            &world_tangent_view,
            &gbuf_sampler,
        );

        let z_prepass_pipeline =
            Self::create_z_prepass_pipeline(device, scene, Some(wgpu::Face::Back), "Z-Prepass Pipeline");
        let z_prepass_double_sided_pipeline =
            Self::create_z_prepass_pipeline(device, scene, None, "Z-Prepass TwoSided Pipeline");
        let gbuffer_pipeline =
            Self::create_gbuffer_pipeline(device, scene, Some(wgpu::Face::Back), "GBuffer Pipeline");
        let gbuffer_double_sided_pipeline =
            Self::create_gbuffer_pipeline(device, scene, None, "GBuffer TwoSided Pipeline");
        let lighting_pipeline =
            Self::create_lighting_pipeline(device, scene, &gbuffer_bind_group_layout);

        Self {
            albedo_metallic_tex,
            albedo_metallic_view,
            normal_roughness_tex,
            normal_roughness_view,
            world_position_tex,
            world_position_view,
            world_tangent_tex,
            world_tangent_view,
            gbuffer_pipeline,
            gbuffer_double_sided_pipeline,
            z_prepass_pipeline,
            z_prepass_double_sided_pipeline,
            lighting_pipeline,
            gbuffer_bind_group_layout,
            gbuffer_bind_group,
            gbuf_sampler,
            width,
            height,
        }
    }

    /// Recreate G-buffer textures and bind groups when the window is resized.
    pub fn resize(&mut self, device: &wgpu::Device, width: u32, height: u32) {
        if self.width == width && self.height == height {
            return;
        }
        let (
            albedo_metallic_tex,
            albedo_metallic_view,
            normal_roughness_tex,
            normal_roughness_view,
            world_position_tex,
            world_position_view,
            world_tangent_tex,
            world_tangent_view,
            gbuf_sampler,
        ) = Self::create_gbuffer_textures(device, width, height);

        self.gbuffer_bind_group = Self::create_gbuffer_bind_group(
            device,
            &self.gbuffer_bind_group_layout,
            &albedo_metallic_view,
            &normal_roughness_view,
            &world_position_view,
            &world_tangent_view,
            &gbuf_sampler,
        );

        self.albedo_metallic_tex = albedo_metallic_tex;
        self.albedo_metallic_view = albedo_metallic_view;
        self.normal_roughness_tex = normal_roughness_tex;
        self.normal_roughness_view = normal_roughness_view;
        self.world_position_tex = world_position_tex;
        self.world_position_view = world_position_view;
        self.world_tangent_tex = world_tangent_tex;
        self.world_tangent_view = world_tangent_view;
        self.gbuf_sampler = gbuf_sampler;
        self.width = width;
        self.height = height;
    }

    // ── helpers ─────────────────────────────────────────────────────────────

    fn create_gbuffer_textures(
        device: &wgpu::Device,
        w: u32,
        h: u32,
    ) -> (
        wgpu::Texture,
        wgpu::TextureView,
        wgpu::Texture,
        wgpu::TextureView,
        wgpu::Texture,
        wgpu::TextureView,
        wgpu::Texture,
        wgpu::TextureView,
        wgpu::Sampler,
    ) {
        let mk = |label: &str, fmt: wgpu::TextureFormat| {
            let t = device.create_texture(&wgpu::TextureDescriptor {
                label: Some(label),
                size: wgpu::Extent3d {
                    width: w,
                    height: h,
                    depth_or_array_layers: 1,
                },
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format: fmt,
                usage: wgpu::TextureUsages::RENDER_ATTACHMENT
                    | wgpu::TextureUsages::TEXTURE_BINDING,
                view_formats: &[],
            });
            let v = t.create_view(&wgpu::TextureViewDescriptor::default());
            (t, v)
        };

        let (a, av) = mk("gbuf_albedo_metallic", GBUFFER_ALBEDO_METALLIC_FORMAT);
        let (n, nv) = mk("gbuf_normal_roughness", GBUFFER_NORMAL_ROUGHNESS_FORMAT);
        let (p, pv) = mk("gbuf_world_position", GBUFFER_WORLD_POSITION_FORMAT);
        let (t, tv) = mk("gbuf_world_tangent", GBUFFER_WORLD_TANGENT_FORMAT);

        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            address_mode_u: wgpu::AddressMode::ClampToEdge,
            address_mode_v: wgpu::AddressMode::ClampToEdge,
            mag_filter: wgpu::FilterMode::Nearest,
            min_filter: wgpu::FilterMode::Nearest,
            ..Default::default()
        });

        (a, av, n, nv, p, pv, t, tv, sampler)
    }

    fn create_gbuffer_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {
        device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("gbuffer_bind_group_layout"),
            entries: &[
                // albedo_metallic
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        multisampled: false,
                        view_dimension: wgpu::TextureViewDimension::D2,
                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
                    },
                    count: None,
                },
                // normal_roughness
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        multisampled: false,
                        view_dimension: wgpu::TextureViewDimension::D2,
                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
                    },
                    count: None,
                },
                // world_position
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        multisampled: false,
                        view_dimension: wgpu::TextureViewDimension::D2,
                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
                    },
                    count: None,
                },
                // nearest sampler
                wgpu::BindGroupLayoutEntry {
                    binding: 3,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::NonFiltering),
                    count: None,
                },
                // world_tangent
                wgpu::BindGroupLayoutEntry {
                    binding: 4,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        multisampled: false,
                        view_dimension: wgpu::TextureViewDimension::D2,
                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
                    },
                    count: None,
                },
            ],
        })
    }

    fn create_gbuffer_bind_group(
        device: &wgpu::Device,
        layout: &wgpu::BindGroupLayout,
        albedo_v: &wgpu::TextureView,
        normal_v: &wgpu::TextureView,
        pos_v: &wgpu::TextureView,
        tangent_v: &wgpu::TextureView,
        sampler: &wgpu::Sampler,
    ) -> wgpu::BindGroup {
        device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("gbuffer_bind_group"),
            layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(albedo_v),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::TextureView(normal_v),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: wgpu::BindingResource::TextureView(pos_v),
                },
                wgpu::BindGroupEntry {
                    binding: 3,
                    resource: wgpu::BindingResource::Sampler(sampler),
                },
                wgpu::BindGroupEntry {
                    binding: 4,
                    resource: wgpu::BindingResource::TextureView(tangent_v),
                },
            ],
        })
    }

    fn create_gbuffer_pipeline(
        device: &wgpu::Device,
        scene: &SceneState,
        cull_mode: Option<wgpu::Face>,
        label: &str,
    ) -> wgpu::RenderPipeline {
        let shader = load_shader(
            device,
            "demo/assets/shaders/gbuffer.wgsl",
            include_str!("shaders/gbuffer.wgsl"),
            "GBuffer Shader",
        );

        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("GBuffer Pipeline Layout"),
            bind_group_layouts: &[
                Some(&scene.global_bind_group_layout),   // 0: SceneUniforms
                Some(&scene.texture_bind_group_layout),  // 1: albedo texture
                Some(&scene.shadow_bind_group_layout), // 2: shadow (unused in G-pass but slot must exist)
                Some(&scene.skeleton_bind_group_layout), // 3: skeleton
                Some(&scene.instance_bind_group_layout), // 4: instances
            ],
            immediate_size: 0,
        });

        device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some(label),
            layout: Some(&layout),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("vs_main"),
                compilation_options: Default::default(),
                buffers: &[Vertex::desc()],
            },
            fragment: Some(wgpu::FragmentState {
                module: &shader,
                entry_point: Some("fs_main"),
                compilation_options: Default::default(),
                targets: &[
                    // RT0: albedo_metallic
                    Some(wgpu::ColorTargetState {
                        format: GBUFFER_ALBEDO_METALLIC_FORMAT,
                        blend: None,
                        write_mask: wgpu::ColorWrites::ALL,
                    }),
                    // RT1: normal_roughness
                    Some(wgpu::ColorTargetState {
                        format: GBUFFER_NORMAL_ROUGHNESS_FORMAT,
                        blend: None,
                        write_mask: wgpu::ColorWrites::ALL,
                    }),
                    // RT2: world_position
                    Some(wgpu::ColorTargetState {
                        format: GBUFFER_WORLD_POSITION_FORMAT,
                        blend: None,
                        write_mask: wgpu::ColorWrites::ALL,
                    }),
                    // RT3: world_tangent
                    Some(wgpu::ColorTargetState {
                        format: GBUFFER_WORLD_TANGENT_FORMAT,
                        blend: None,
                        write_mask: wgpu::ColorWrites::ALL,
                    }),
                ],
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode,
                ..Default::default()
            },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: wgpu::TextureFormat::Depth32Float,
                depth_write_enabled: Some(false),
                depth_compare: Some(wgpu::CompareFunction::LessEqual),
                stencil: wgpu::StencilState::default(),
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState::default(),
            multiview_mask: None,
            cache: None,
        })
    }

    fn create_z_prepass_pipeline(
        device: &wgpu::Device,
        scene: &SceneState,
        cull_mode: Option<wgpu::Face>,
        label: &str,
    ) -> wgpu::RenderPipeline {
        let shader = load_shader(
            device,
            "demo/assets/shaders/gbuffer.wgsl",
            include_str!("shaders/gbuffer.wgsl"),
            "Z-Prepass Shader",
        );

        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("Z-Prepass Pipeline Layout"),
            bind_group_layouts: &[
                Some(&scene.global_bind_group_layout),   // 0: SceneUniforms
                Some(&scene.texture_bind_group_layout), // 1: albedo texture (unused but required by shader layout)
                Some(&scene.shadow_bind_group_layout),  // 2: shadow
                Some(&scene.skeleton_bind_group_layout), // 3: skeleton
                Some(&scene.instance_bind_group_layout), // 4: instances
            ],
            immediate_size: 0,
        });

        device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some(label),
            layout: Some(&layout),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("vs_main"),
                compilation_options: Default::default(),
                buffers: &[Vertex::desc()],
            },
            fragment: None, // NO COLOR TARGETS!
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode,
                ..Default::default()
            },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: wgpu::TextureFormat::Depth32Float,
                depth_write_enabled: Some(true),
                depth_compare: Some(wgpu::CompareFunction::Less),
                stencil: wgpu::StencilState::default(),
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState::default(),
            multiview_mask: None,
            cache: None,
        })
    }

    fn create_lighting_pipeline(
        device: &wgpu::Device,
        scene: &SceneState,
        gbuffer_layout: &wgpu::BindGroupLayout,
    ) -> wgpu::RenderPipeline {
        let shader = load_shader_composed(
            device,
            "demo/assets/shaders/deferred_lighting.wgsl",
            include_str!("shaders/deferred_lighting.wgsl"),
            "Deferred Lighting Shader",
        );

        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("Deferred Lighting Layout"),
            bind_group_layouts: &[
                Some(&scene.global_bind_group_layout), // 0: SceneUniforms
                Some(&scene.shadow_bind_group_layout), // 1: shadow CSM
                Some(gbuffer_layout),                  // 2: G-buffers
            ],
            immediate_size: 0,
        });

        device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("Deferred Lighting Pipeline"),
            layout: Some(&layout),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("vs_main"),
                compilation_options: Default::default(),
                buffers: &[], // fullscreen triangle — no vertex buffer
            },
            fragment: Some(wgpu::FragmentState {
                module: &shader,
                entry_point: Some("fs_main"),
                compilation_options: Default::default(),
                targets: &[Some(wgpu::ColorTargetState {
                    format: wgpu::TextureFormat::Rgba16Float,
                    blend: None,
                    write_mask: wgpu::ColorWrites::ALL,
                })],
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                cull_mode: None,
                ..Default::default()
            },
            depth_stencil: None, // no depth write in lighting pass
            multisample: wgpu::MultisampleState::default(),
            multiview_mask: None,
            cache: None,
        })
    }
}

#[cfg(test)]
mod gbuffer_packing_tests {
    /// Mirror of `gbuffer.wgsl`'s `packed_ss_aniso`.
    fn pack(subsurface: f32, anisotropy: f32) -> f32 {
        (0.5 + 0.49 * anisotropy) + (100.0 * subsurface).floor()
    }

    /// Mirror of `deferred_lighting.wgsl`'s decode of `pos_sample.w`.
    fn unpack(w: f32) -> (f32, f32) {
        let subsurface = w.floor() / 100.0;
        let anisotropy = ((w - w.floor() - 0.5) / 0.49).clamp(0.0, 1.0);
        (subsurface, anisotropy)
    }

    /// The two values packed into the world-position target's `.w` come back out independently.
    ///
    /// They did not. The pack was `100.0 * subsurface` without the `floor`, and the decode reads
    /// the integer part as subsurface and the fraction as anisotropy — which only works when
    /// `100 · subsurface` is *already* an integer. When it is not, subsurface's own fraction lands
    /// in anisotropy's slot: subsurface 0.234 with anisotropy 0 decoded as 0.82, and the same
    /// subsurface with anisotropy 1 decoded as 0. Exactly inverted, which is worse than noise —
    /// a material with no anisotropy rendered as though it were fully anisotropic.
    ///
    /// This is a mirror test, in the same spirit as `csm`'s `shader_shadow_fade_matches_the_rust
    /// _mirror`: the arithmetic lives in WGSL and cannot be reached from here, so it is restated
    /// and pinned. Change one side and change the other.
    #[test]
    fn subsurface_and_anisotropy_survive_the_round_trip() {
        for &s in &[0.0f32, 0.07, 0.234, 0.5, 0.777, 0.999, 1.0] {
            for &a in &[0.0f32, 0.25, 0.5, 1.0] {
                let (ds, da) = unpack(pack(s, a));
                // Subsurface is deliberately quantised to 1 % — the `/100` decode always was.
                assert!(
                    (ds - s).abs() <= 0.011,
                    "subsurface {s} came back as {ds} (anisotropy {a})"
                );
                assert!(
                    (da - a).abs() <= 0.02,
                    "anisotropy {a} came back as {da} — subsurface {s} is leaking into its slot"
                );
            }
        }
    }
}