scena 1.7.2

A Rust-native scene-graph renderer with typed scene state, glTF assets, and explicit prepare/render lifecycles.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
use super::super::prepare::PreparedGpuLightUniform;
use super::light_assignment::LightAssignmentResources;
use crate::scene::{ClippingPlane, SectionBox};

/// Phase 5.4 follow-up: the WGSL fragment shader source moved into
/// a sibling `.wgsl` file so this Rust module stays under doctor's
/// per-module significant-lines budget. The shader still compiles
/// the same — `include_str!` produces a static `&'static str`.
/// Instanced shader contract: `draw.world_from_model * instance_world_from_model * vec4<f32>(in.position, 1.0)`
/// and `let normal_from_model = draw.normal_from_model * instance_normal_from_model`.
#[cfg(test)]
pub(super) const GPU_COLOR_CONTRACT_WGSL: &str = include_str!("../color_contract.wgsl");
pub(super) const GPU_TRIANGLE_SHADER: &str = concat!(
    include_str!("output_shader.wgsl"),
    "\n",
    include_str!("../area_ltc_tables.wgsl"),
    "\n",
    include_str!("../area_ltc.wgsl"),
    "\n",
    include_str!("../pbr_brdf.wgsl"),
    "\n",
    include_str!("../color_contract.wgsl")
);
pub(super) const GPU_TRIANGLE_SHADER_TEXTURE_2D: &str = concat!(
    include_str!("output_shader_texture_2d.wgsl"),
    "\n",
    include_str!("../area_ltc_tables.wgsl"),
    "\n",
    include_str!("../area_ltc.wgsl"),
    "\n",
    include_str!("../pbr_brdf.wgsl"),
    "\n",
    include_str!("../color_contract.wgsl")
);

pub(super) const MAX_OUTPUT_CLIPPING_PLANES: usize = 16;
const OUTPUT_UNIFORM_BASE_FLOAT_COUNT: usize = 696;
const OUTPUT_UNIFORM_FLOAT_COUNT: usize =
    OUTPUT_UNIFORM_BASE_FLOAT_COUNT + MAX_OUTPUT_CLIPPING_PLANES * 4 + 4;
pub(super) const OUTPUT_UNIFORM_BYTE_LEN: u64 = 3056;

pub(super) use super::draw_uniform::{
    DRAW_UNIFORM_ENTRY_STRIDE, create_draw_bind_group, create_draw_bind_group_layout,
    create_draw_uniform_buffer, encode_draw_uniform_bytes,
};

pub(super) fn create_output_bind_group_layout(
    device: &wgpu::Device,
    include_tiled_light_storage: bool,
) -> wgpu::BindGroupLayout {
    let mut entries = vec![
        wgpu::BindGroupLayoutEntry {
            binding: 0,
            visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
            ty: wgpu::BindingType::Buffer {
                ty: wgpu::BufferBindingType::Uniform,
                has_dynamic_offset: false,
                min_binding_size: None,
            },
            count: None,
        },
        wgpu::BindGroupLayoutEntry {
            binding: 1,
            visibility: wgpu::ShaderStages::FRAGMENT,
            ty: wgpu::BindingType::Texture {
                sample_type: wgpu::TextureSampleType::Depth,
                view_dimension: wgpu::TextureViewDimension::D2,
                multisampled: false,
            },
            count: None,
        },
        wgpu::BindGroupLayoutEntry {
            binding: 2,
            visibility: wgpu::ShaderStages::FRAGMENT,
            ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison),
            count: None,
        },
        // Phase 1C step 1: env cubemap. Placeholder when unset — gated
        // on environment_diffuse_intensity.w in the fragment shader.
        wgpu::BindGroupLayoutEntry {
            binding: 3,
            visibility: wgpu::ShaderStages::FRAGMENT,
            ty: wgpu::BindingType::Texture {
                sample_type: wgpu::TextureSampleType::Float { filterable: true },
                view_dimension: wgpu::TextureViewDimension::Cube,
                multisampled: false,
            },
            count: None,
        },
        wgpu::BindGroupLayoutEntry {
            binding: 4,
            visibility: wgpu::ShaderStages::FRAGMENT,
            ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
            count: None,
        },
        // Opaque scene color sampled by the transparent transmission pass.
        // This is the minimum real renderer capability for glass proof:
        // transparent fragments can refract/blur the already-rendered
        // background instead of relying on alpha blend alone.
        wgpu::BindGroupLayoutEntry {
            binding: 6,
            visibility: wgpu::ShaderStages::FRAGMENT,
            ty: wgpu::BindingType::Texture {
                sample_type: wgpu::TextureSampleType::Float { filterable: true },
                view_dimension: wgpu::TextureViewDimension::D2,
                multisampled: false,
            },
            count: None,
        },
        wgpu::BindGroupLayoutEntry {
            binding: 7,
            visibility: wgpu::ShaderStages::FRAGMENT,
            ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
            count: None,
        },
    ];
    if include_tiled_light_storage {
        // TiledLightAssignment: per-tile light records for scenes that exceed
        // the fixed 16-light uniform lane without silently truncating. WebGL2
        // exposes zero fragment-stage storage buffers, so the texture-2D
        // browser shader intentionally stays on the uniform light arrays.
        entries.push(wgpu::BindGroupLayoutEntry {
            binding: 5,
            visibility: wgpu::ShaderStages::FRAGMENT,
            ty: wgpu::BindingType::Buffer {
                ty: wgpu::BufferBindingType::Storage { read_only: true },
                has_dynamic_offset: false,
                min_binding_size: None,
            },
            count: None,
        });
        entries.push(wgpu::BindGroupLayoutEntry {
            binding: 8,
            visibility: wgpu::ShaderStages::FRAGMENT,
            ty: wgpu::BindingType::Buffer {
                ty: wgpu::BufferBindingType::Storage { read_only: true },
                has_dynamic_offset: false,
                min_binding_size: None,
            },
            count: None,
        });
        entries.push(wgpu::BindGroupLayoutEntry {
            binding: 9,
            visibility: wgpu::ShaderStages::FRAGMENT,
            ty: wgpu::BindingType::Buffer {
                ty: wgpu::BufferBindingType::Storage { read_only: true },
                has_dynamic_offset: false,
                min_binding_size: None,
            },
            count: None,
        });
    }
    device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
        label: Some("scena.output.bind_group_layout"),
        entries: &entries,
    })
}

pub(super) fn create_output_uniform_buffer(device: &wgpu::Device) -> wgpu::Buffer {
    device.create_buffer(&wgpu::BufferDescriptor {
        label: Some("scena.output.uniform"),
        size: OUTPUT_UNIFORM_BYTE_LEN,
        usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
        mapped_at_creation: false,
    })
}

#[allow(clippy::too_many_arguments)]
pub(super) fn create_output_bind_group(
    device: &wgpu::Device,
    layout: &wgpu::BindGroupLayout,
    uniform: &wgpu::Buffer,
    shadow_view: &wgpu::TextureView,
    shadow_sampler: &wgpu::Sampler,
    environment_cubemap_view: &wgpu::TextureView,
    environment_sampler: &wgpu::Sampler,
    transmission_color_view: &wgpu::TextureView,
    transmission_color_sampler: &wgpu::Sampler,
    light_assignment: Option<&LightAssignmentResources>,
) -> wgpu::BindGroup {
    let mut entries = vec![
        wgpu::BindGroupEntry {
            binding: 0,
            resource: uniform.as_entire_binding(),
        },
        wgpu::BindGroupEntry {
            binding: 1,
            resource: wgpu::BindingResource::TextureView(shadow_view),
        },
        wgpu::BindGroupEntry {
            binding: 2,
            resource: wgpu::BindingResource::Sampler(shadow_sampler),
        },
        wgpu::BindGroupEntry {
            binding: 3,
            resource: wgpu::BindingResource::TextureView(environment_cubemap_view),
        },
        wgpu::BindGroupEntry {
            binding: 4,
            resource: wgpu::BindingResource::Sampler(environment_sampler),
        },
        wgpu::BindGroupEntry {
            binding: 6,
            resource: wgpu::BindingResource::TextureView(transmission_color_view),
        },
        wgpu::BindGroupEntry {
            binding: 7,
            resource: wgpu::BindingResource::Sampler(transmission_color_sampler),
        },
    ];
    if let Some(light_assignment) = light_assignment {
        entries.push(wgpu::BindGroupEntry {
            binding: 5,
            resource: light_assignment.records.as_entire_binding(),
        });
        entries.push(wgpu::BindGroupEntry {
            binding: 8,
            resource: light_assignment.tile_indices.as_entire_binding(),
        });
        entries.push(wgpu::BindGroupEntry {
            binding: 9,
            resource: light_assignment.tiles.as_entire_binding(),
        });
    }
    device.create_bind_group(&wgpu::BindGroupDescriptor {
        label: Some("scena.output.bind_group"),
        layout,
        entries: &entries,
    })
}

pub(super) struct OutputUniformUpload {
    pub(super) exposure_ev: f32,
    pub(super) view_from_world: [f32; 16],
    pub(super) clip_from_view: [f32; 16],
    pub(super) clip_from_world: [f32; 16],
    pub(super) light_from_world: [f32; 16],
    pub(super) camera_position: [f32; 3],
    pub(super) viewport: [f32; 2],
    pub(super) near_far: [f32; 2],
    pub(super) color_management: [f32; 4],
    pub(super) lighting: PreparedGpuLightUniform,
    pub(super) clipping_planes: [[f32; 4]; MAX_OUTPUT_CLIPPING_PLANES],
    pub(super) clipping_control: [f32; 4],
}

pub(super) fn encode_clipping_uniform(
    clipping_planes: &[ClippingPlane],
    section_box: Option<SectionBox>,
) -> ([[f32; 4]; MAX_OUTPUT_CLIPPING_PLANES], [f32; 4]) {
    let mut encoded = [[0.0; 4]; MAX_OUTPUT_CLIPPING_PLANES];
    let mut count = 0usize;
    for plane in clipping_planes
        .iter()
        .take(MAX_OUTPUT_CLIPPING_PLANES)
        .copied()
    {
        encoded[count] = plane_uniform(plane);
        count += 1;
    }
    let section_start = count;
    let mut has_section = false;
    let mut inverted_section = false;
    if let Some(section_box) = section_box {
        inverted_section = section_box.inverted();
        for plane in section_box.planes() {
            if count == MAX_OUTPUT_CLIPPING_PLANES {
                break;
            }
            encoded[count] = plane_uniform(plane);
            count += 1;
            has_section = true;
        }
    }

    (
        encoded,
        [
            count as f32,
            section_start as f32,
            if inverted_section { 1.0 } else { 0.0 },
            if has_section { 1.0 } else { 0.0 },
        ],
    )
}

pub(super) fn encode_output_uniform(
    upload: OutputUniformUpload,
) -> [u8; OUTPUT_UNIFORM_BYTE_LEN as usize] {
    let exposure_ev = if upload.exposure_ev.is_finite() {
        upload.exposure_ev
    } else {
        0.0
    };
    let mut values = [0.0; OUTPUT_UNIFORM_FLOAT_COUNT];
    values[0..16].copy_from_slice(&upload.view_from_world);
    values[16..32].copy_from_slice(&upload.clip_from_view);
    values[32..48].copy_from_slice(&upload.clip_from_world);
    values[48..64].copy_from_slice(&upload.light_from_world);
    values[64] = upload.camera_position[0];
    values[65] = upload.camera_position[1];
    values[66] = upload.camera_position[2];
    values[67] = 2.0_f32.powf(exposure_ev);
    values[68] = upload.viewport[0];
    values[69] = upload.viewport[1];
    values[70] = upload.near_far[0];
    values[71] = upload.near_far[1];
    values[72..76].copy_from_slice(&upload.color_management);
    let mut offset = 76;
    offset = encode_vec4_array(
        &mut values,
        offset,
        &upload.lighting.directional_light_direction_intensity,
    );
    offset = encode_vec4_array(
        &mut values,
        offset,
        &upload.lighting.directional_light_color,
    );
    offset = encode_vec4_array(
        &mut values,
        offset,
        &upload.lighting.directional_shadow_control,
    );
    offset = encode_vec4_array(
        &mut values,
        offset,
        &upload.lighting.point_light_position_intensity,
    );
    offset = encode_vec4_array(
        &mut values,
        offset,
        &upload.lighting.point_light_color_range,
    );
    offset = encode_vec4_array(
        &mut values,
        offset,
        &upload.lighting.spot_light_position_intensity,
    );
    offset = encode_vec4_array(
        &mut values,
        offset,
        &upload.lighting.spot_light_direction_cones,
    );
    offset = encode_vec4_array(&mut values, offset, &upload.lighting.spot_light_cone_range);
    offset = encode_vec4_array(&mut values, offset, &upload.lighting.spot_light_color_range);
    offset = encode_vec4_array(
        &mut values,
        offset,
        &upload.lighting.area_light_position_flux,
    );
    offset = encode_vec4_array(
        &mut values,
        offset,
        &upload.lighting.area_light_axis_x_shape,
    );
    offset = encode_vec4_array(
        &mut values,
        offset,
        &upload.lighting.area_light_axis_y_range,
    );
    offset = encode_vec4_array(&mut values, offset, &upload.lighting.area_light_color);
    values[offset..offset + 4].copy_from_slice(&upload.lighting.light_counts);
    offset += 4;
    values[offset..offset + 4].copy_from_slice(&upload.lighting.environment_diffuse_intensity);
    offset += 4;
    values[offset..offset + 4].copy_from_slice(&upload.lighting.environment_specular_intensity);
    offset += 4;
    for (index, plane) in upload.clipping_planes.into_iter().enumerate() {
        let plane_offset = offset + index * 4;
        values[plane_offset..plane_offset + 4].copy_from_slice(&plane);
    }
    let clipping_control_offset = offset + MAX_OUTPUT_CLIPPING_PLANES * 4;
    values[clipping_control_offset..clipping_control_offset + 4]
        .copy_from_slice(&upload.clipping_control);
    let mut bytes = [0; OUTPUT_UNIFORM_BYTE_LEN as usize];
    for (index, value) in values.into_iter().enumerate() {
        bytes[index * 4..index * 4 + 4].copy_from_slice(&value.to_ne_bytes());
    }
    bytes
}

fn encode_vec4_array<const N: usize>(
    values: &mut [f32],
    offset: usize,
    array: &[[f32; 4]; N],
) -> usize {
    let mut offset = offset;
    for value in array {
        values[offset..offset + 4].copy_from_slice(value);
        offset += 4;
    }
    offset
}

fn plane_uniform(plane: ClippingPlane) -> [f32; 4] {
    [
        plane.normal().x,
        plane.normal().y,
        plane.normal().z,
        plane.distance(),
    ]
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn output_uniform_buffer_matches_wgsl_uniform_layout() {
        assert_eq!(
            OUTPUT_UNIFORM_BYTE_LEN, 3056,
            "CameraUniform stores view, projection, and view-projection matrices plus \
             camera/exposure, viewport/depth, color-management, widened punctual-light arrays, \
             area-light arrays, \
             directional-shadow-control, environment, and sixteen clipping-plane uniforms — per-draw model + normal matrices live on the new \
             DrawUniform bind group at @group(2)"
        );
        let (clipping_planes, clipping_control) = encode_clipping_uniform(&[], None);
        assert_eq!(
            encode_output_uniform(OutputUniformUpload {
                exposure_ev: 0.0,
                view_from_world: identity_clip_from_world(),
                clip_from_view: identity_clip_from_world(),
                clip_from_world: identity_clip_from_world(),
                light_from_world: identity_clip_from_world(),
                camera_position: [0.0, 0.0, 2.0],
                viewport: [128.0, 64.0],
                near_far: [0.1, 1000.0],
                color_management: [1.0, 0.0, 0.0, 0.0],
                lighting: PreparedGpuLightUniform::default(),
                clipping_planes,
                clipping_control,
            })
            .len(),
            OUTPUT_UNIFORM_BYTE_LEN as usize
        );
    }

    #[test]
    fn capability_clipping_plane_max_matches_shader_uniform_array() {
        assert_eq!(
            crate::Capabilities::for_backend(crate::Backend::WebGl2).max_clipping_planes as usize,
            MAX_OUTPUT_CLIPPING_PLANES,
            "WebGL2 max_clipping_planes must match the GPU clipping uniform array"
        );
        assert_eq!(
            crate::Capabilities::for_backend(crate::Backend::HeadlessGpu).max_clipping_planes
                as usize,
            MAX_OUTPUT_CLIPPING_PLANES,
            "HeadlessGpu max_clipping_planes must match the GPU clipping uniform array"
        );
        assert_eq!(
            crate::Capabilities::for_backend(crate::Backend::WebGpu).max_clipping_planes as usize,
            MAX_OUTPUT_CLIPPING_PLANES,
            "WebGpu max_clipping_planes must match the GPU clipping uniform array"
        );
    }

    #[test]
    fn clipping_uniform_encodes_user_planes_and_section_box_together() {
        let user = ClippingPlane::new(crate::Vec3::X, 0.25);
        let section = SectionBox::from_bounds(crate::Aabb::new(
            crate::Vec3::new(-1.0, -2.0, -3.0),
            crate::Vec3::new(1.0, 2.0, 3.0),
        ))
        .with_inverted(true);

        let (planes, control) = encode_clipping_uniform(&[user], Some(section));

        assert_eq!(control, [7.0, 1.0, 1.0, 1.0]);
        assert_eq!(planes[0], [1.0, 0.0, 0.0, 0.25]);
        assert_eq!(planes[1], [1.0, 0.0, 0.0, 1.0]);
        assert_eq!(planes[2], [-1.0, -0.0, -0.0, 1.0]);
    }

    #[test]
    fn triangle_shader_contains_khronos_pbr_neutral_tonemapper() {
        assert!(
            GPU_COLOR_CONTRACT_WGSL.contains("scena.color_contract.wgsl")
                && GPU_COLOR_CONTRACT_WGSL.contains("pbr_neutral_tonemap")
                && GPU_COLOR_CONTRACT_WGSL.contains("SCENA_PBR_NEUTRAL_START_COMPRESSION")
                && GPU_COLOR_CONTRACT_WGSL.contains("SCENA_PBR_NEUTRAL_DESATURATION")
                && GPU_TRIANGLE_SHADER.contains("scena.color_contract.wgsl")
                && GPU_TRIANGLE_SHADER_TEXTURE_2D.contains("scena.color_contract.wgsl")
                && GPU_TRIANGLE_SHADER.contains("color_management_mode > 1.5"),
            "native/WebGPU shader must expose the Khronos PBR Neutral tone-mapping branch; \
             WaterBottle screenshots must not be tuned through private color constants"
        );
    }

    #[test]
    fn triangle_shader_uses_camera_projection_uniform() {
        let raw_clip_space_assignment =
            ["out.position = vec4<f32>(in.position", ", 1.0);"].join("");
        assert!(
            GPU_TRIANGLE_SHADER.contains("clip_from_world")
                && GPU_TRIANGLE_SHADER.contains("world_from_model")
                && GPU_TRIANGLE_SHADER.contains("normal_from_model")
                && GPU_TRIANGLE_SHADER.contains("view_from_world")
                && GPU_TRIANGLE_SHADER.contains("clip_from_view")
                && GPU_TRIANGLE_SHADER.contains("camera_position_exposure")
                && GPU_TRIANGLE_SHADER.contains("viewport_near_far")
                && GPU_TRIANGLE_SHADER.contains("color_management"),
            "GPU shader uniform must expose model, normal, view, projection, view-projection, \
             camera position, viewport/depth, and color-management metadata"
        );
        assert!(
            !GPU_TRIANGLE_SHADER.contains(&raw_clip_space_assignment),
            "GPU vertex shader must not treat world-space positions as clip-space coordinates"
        );
        assert!(
            GPU_TRIANGLE_SHADER.contains("@location(2) normal: vec3<f32>")
                && GPU_TRIANGLE_SHADER.contains("@location(3) tex_coord0: vec2<f32>")
                && GPU_TRIANGLE_SHADER.contains("base_color_uv_offset_scale")
                && GPU_TRIANGLE_SHADER.contains("base_color_uv_rotation")
                && GPU_TRIANGLE_SHADER.contains(
                    "textureSample(base_color_texture, base_color_sampler, transformed_uv, material_layer)"
                ),
            "GPU shader must receive normals + TEXCOORD_0 from prepared vertex data and \
             route base-color sampling through the material layer index for array batching"
        );
    }

    #[test]
    fn triangle_shader_declares_material_texture_bindings() {
        // Plan line 778 / RFC 866 commit 2: every material texture role binds
        // a `texture_2d_array<f32>` so the same WGSL pipeline serves the
        // per-material 1-layer fall-back and the batched N-layer path. The
        // MaterialUniform carries `material_layer_index` so sampling can
        // route into the correct layer.
        assert!(
            GPU_TRIANGLE_SHADER.contains("@group(1) @binding(0)")
                && GPU_TRIANGLE_SHADER.contains("var base_color_sampler: sampler")
                && GPU_TRIANGLE_SHADER.contains("@group(1) @binding(1)")
                && GPU_TRIANGLE_SHADER.contains("var base_color_texture: texture_2d_array<f32>")
                && GPU_TRIANGLE_SHADER.contains("@group(1) @binding(2)")
                && GPU_TRIANGLE_SHADER.contains("var<uniform> material: MaterialUniform")
                && GPU_TRIANGLE_SHADER.contains("@group(1) @binding(3)")
                && GPU_TRIANGLE_SHADER.contains("var normal_sampler: sampler")
                && GPU_TRIANGLE_SHADER.contains("@group(1) @binding(4)")
                && GPU_TRIANGLE_SHADER.contains("var normal_texture: texture_2d_array<f32>")
                && GPU_TRIANGLE_SHADER.contains("@group(1) @binding(5)")
                && GPU_TRIANGLE_SHADER.contains("var metallic_roughness_sampler: sampler")
                && GPU_TRIANGLE_SHADER.contains("@group(1) @binding(6)")
                && GPU_TRIANGLE_SHADER
                    .contains("var metallic_roughness_texture: texture_2d_array<f32>")
                && GPU_TRIANGLE_SHADER.contains("@group(1) @binding(7)")
                && GPU_TRIANGLE_SHADER.contains("var occlusion_sampler: sampler")
                && GPU_TRIANGLE_SHADER.contains("@group(1) @binding(8)")
                && GPU_TRIANGLE_SHADER.contains("var occlusion_texture: texture_2d_array<f32>")
                && GPU_TRIANGLE_SHADER.contains("@group(1) @binding(9)")
                && GPU_TRIANGLE_SHADER.contains("var emissive_sampler: sampler")
                && GPU_TRIANGLE_SHADER.contains("@group(1) @binding(10)")
                && GPU_TRIANGLE_SHADER.contains("var emissive_texture: texture_2d_array<f32>")
                && GPU_TRIANGLE_SHADER.contains("@group(1) @binding(11)")
                && GPU_TRIANGLE_SHADER.contains("var clearcoat_sampler: sampler")
                && GPU_TRIANGLE_SHADER.contains("@group(1) @binding(12)")
                && GPU_TRIANGLE_SHADER.contains("var clearcoat_texture: texture_2d_array<f32>")
                && GPU_TRIANGLE_SHADER.contains("@group(1) @binding(13)")
                && GPU_TRIANGLE_SHADER.contains("var clearcoat_roughness_sampler: sampler")
                && GPU_TRIANGLE_SHADER.contains("@group(1) @binding(14)")
                && GPU_TRIANGLE_SHADER
                    .contains("var clearcoat_roughness_texture: texture_2d_array<f32>")
                && GPU_TRIANGLE_SHADER.contains("@group(1) @binding(15)")
                && GPU_TRIANGLE_SHADER.contains("var clearcoat_normal_sampler: sampler")
                && GPU_TRIANGLE_SHADER.contains("@group(1) @binding(16)")
                && GPU_TRIANGLE_SHADER
                    .contains("var clearcoat_normal_texture: texture_2d_array<f32>")
                && GPU_TRIANGLE_SHADER.contains("@group(1) @binding(17)")
                && GPU_TRIANGLE_SHADER.contains("var sheen_color_sampler: sampler")
                && GPU_TRIANGLE_SHADER.contains("@group(1) @binding(18)")
                && GPU_TRIANGLE_SHADER.contains("var sheen_color_texture: texture_2d_array<f32>")
                && GPU_TRIANGLE_SHADER.contains("@group(1) @binding(19)")
                && GPU_TRIANGLE_SHADER.contains("var sheen_roughness_sampler: sampler")
                && GPU_TRIANGLE_SHADER.contains("@group(1) @binding(20)")
                && GPU_TRIANGLE_SHADER
                    .contains("var sheen_roughness_texture: texture_2d_array<f32>")
                && GPU_TRIANGLE_SHADER.contains("@group(1) @binding(21)")
                && GPU_TRIANGLE_SHADER.contains("var anisotropy_sampler: sampler")
                && GPU_TRIANGLE_SHADER.contains("@group(1) @binding(22)")
                && GPU_TRIANGLE_SHADER.contains("var anisotropy_texture: texture_2d_array<f32>")
                && GPU_TRIANGLE_SHADER.contains("@group(1) @binding(23)")
                && GPU_TRIANGLE_SHADER.contains("var iridescence_sampler: sampler")
                && GPU_TRIANGLE_SHADER.contains("@group(1) @binding(24)")
                && GPU_TRIANGLE_SHADER.contains("var iridescence_texture: texture_2d_array<f32>")
                && GPU_TRIANGLE_SHADER.contains("@group(1) @binding(25)")
                && GPU_TRIANGLE_SHADER.contains("var iridescence_thickness_sampler: sampler")
                && GPU_TRIANGLE_SHADER.contains("@group(1) @binding(26)")
                && GPU_TRIANGLE_SHADER
                    .contains("var iridescence_thickness_texture: texture_2d_array<f32>")
                && GPU_TRIANGLE_SHADER.contains("material_layer_index: vec4<u32>")
                && GPU_TRIANGLE_SHADER.contains("textureSample(base_color_texture"),
            "GPU fragment shader must expose material texture bindings as 2D-array views \
             with material_layer_index so per-material and array-batched paths share one shader"
        );
    }

    #[test]
    fn triangle_shader_texture_2d_variant_declares_webgl2_material_bindings() {
        assert!(
            GPU_TRIANGLE_SHADER_TEXTURE_2D.contains(
                "var base_color_texture: texture_2d<f32>"
            ) && GPU_TRIANGLE_SHADER_TEXTURE_2D.contains("var normal_texture: texture_2d<f32>")
                && GPU_TRIANGLE_SHADER_TEXTURE_2D
                    .contains("var metallic_roughness_texture: texture_2d<f32>")
                && GPU_TRIANGLE_SHADER_TEXTURE_2D
                    .contains("var clearcoat_texture: texture_2d<f32>")
                && GPU_TRIANGLE_SHADER_TEXTURE_2D
                    .contains("var clearcoat_roughness_texture: texture_2d<f32>")
                && GPU_TRIANGLE_SHADER_TEXTURE_2D
                    .contains("var clearcoat_normal_texture: texture_2d<f32>")
                && GPU_TRIANGLE_SHADER_TEXTURE_2D
                    .contains("var sheen_color_texture: texture_2d<f32>")
                && GPU_TRIANGLE_SHADER_TEXTURE_2D
                    .contains("var sheen_roughness_texture: texture_2d<f32>")
                && GPU_TRIANGLE_SHADER_TEXTURE_2D
                    .contains("var anisotropy_texture: texture_2d<f32>")
                && GPU_TRIANGLE_SHADER_TEXTURE_2D
                    .contains("var iridescence_texture: texture_2d<f32>")
                && GPU_TRIANGLE_SHADER_TEXTURE_2D
                    .contains("var iridescence_thickness_texture: texture_2d<f32>")
                && GPU_TRIANGLE_SHADER_TEXTURE_2D.contains(
                    "let base_color_sample = textureSample(base_color_texture, base_color_sampler, transformed_uv)"
                )
                && !GPU_TRIANGLE_SHADER_TEXTURE_2D.contains("var<storage")
                && !GPU_TRIANGLE_SHADER_TEXTURE_2D.contains("tiled_light_records")
                && !GPU_TRIANGLE_SHADER_TEXTURE_2D.contains("light_tile_indices")
                && !GPU_TRIANGLE_SHADER_TEXTURE_2D.contains("light_tiles")
                && !GPU_TRIANGLE_SHADER_TEXTURE_2D
                    .contains("textureSample(base_color_texture, base_color_sampler, transformed_uv, material_layer)"),
            "WebGL2 uses a texture_2d material shader variant because wgpu 29's GL backend \
             samples material texture arrays as black in Chromium WebGL2, and it must not \
             declare fragment storage buffers because WebGL2 exposes a zero-storage limit"
        );
    }

    #[test]
    fn triangle_shader_samples_all_material_texture_roles() {
        assert!(
            GPU_TRIANGLE_SHADER.contains("textureSample(base_color_texture")
                && GPU_TRIANGLE_SHADER.contains("textureSample(normal_texture")
                && GPU_TRIANGLE_SHADER.contains("textureSample(metallic_roughness_texture")
                && GPU_TRIANGLE_SHADER.contains("textureSample(occlusion_texture")
                && GPU_TRIANGLE_SHADER.contains("textureSample(emissive_texture")
                && GPU_TRIANGLE_SHADER.contains("textureSample(clearcoat_texture")
                && GPU_TRIANGLE_SHADER.contains("textureSample(clearcoat_roughness_texture")
                && GPU_TRIANGLE_SHADER.contains("textureSample(clearcoat_normal_texture")
                && GPU_TRIANGLE_SHADER.contains("textureSample(sheen_color_texture")
                && GPU_TRIANGLE_SHADER.contains("textureSample(sheen_roughness_texture")
                && GPU_TRIANGLE_SHADER.contains("textureSample(anisotropy_texture")
                && GPU_TRIANGLE_SHADER.contains("textureSample(iridescence_texture")
                && GPU_TRIANGLE_SHADER.contains("textureSample(iridescence_thickness_texture")
                && GPU_TRIANGLE_SHADER.contains("base_color_factor")
                && GPU_TRIANGLE_SHADER.contains("emissive_strength")
                && GPU_TRIANGLE_SHADER.contains("clearcoat_factors")
                && GPU_TRIANGLE_SHADER.contains("sheen_factors")
                && GPU_TRIANGLE_SHADER.contains("anisotropy_factors")
                && GPU_TRIANGLE_SHADER.contains("iridescence_factors")
                && GPU_TRIANGLE_SHADER.contains("metallic_roughness_alpha"),
            "GPU material shader must sample every prepared glTF material texture role and \
             consume material factor uniforms before backend material parity can be claimed"
        );
    }

    #[test]
    fn triangle_shader_applies_clearcoat_lobe_in_native_and_webgl2_variants() {
        for (name, shader) in [
            ("texture_2d_array", GPU_TRIANGLE_SHADER),
            ("texture_2d", GPU_TRIANGLE_SHADER_TEXTURE_2D),
        ] {
            assert!(
                shader.contains("clearcoat_light_contribution")
                    && shader.contains("let clearcoat_factor = clamp(material.clearcoat_factors.x * clearcoat_sample.r, 0.0, 1.0);")
                    && shader.contains("let clearcoat_roughness = clamp(material.clearcoat_factors.y * clearcoat_roughness_sample.g, 0.04, 1.0);")
                    && shader.contains("let clearcoat_normal_scale = material.clearcoat_factors.z;")
                    && shader.contains("shaded += clearcoat_light_contribution(clearcoat_normal, view, incoming, radiance, clearcoat_factor, clearcoat_roughness);"),
                "{name} shader must apply KHR_materials_clearcoat factors plus clearcoat, roughness, and normal texture channels instead of silently dropping them"
            );
        }
    }

    #[test]
    fn triangle_shader_applies_sheen_lobe_in_native_and_webgl2_variants() {
        for (name, shader) in [
            ("texture_2d_array", GPU_TRIANGLE_SHADER),
            ("texture_2d", GPU_TRIANGLE_SHADER_TEXTURE_2D),
        ] {
            assert!(
                shader.contains("sheen_light_contribution")
                    && shader.contains("let sheen_color = material.sheen_factors.rgb * sheen_color_sample.rgb;")
                    && shader.contains("let sheen_roughness = clamp(material.sheen_factors.a * sheen_roughness_sample.a, 0.04, 1.0);")
                    && shader.contains("shaded += sheen_light_contribution(normal, view, incoming, radiance, sheen_color, sheen_roughness);"),
                "{name} shader must apply KHR_materials_sheen color and roughness texture channels instead of silently dropping them"
            );
        }
    }

    #[test]
    fn triangle_shader_applies_sheen_environment_lobe_in_native_and_webgl2_variants() {
        for (name, shader) in [
            ("texture_2d_array", GPU_TRIANGLE_SHADER),
            ("texture_2d", GPU_TRIANGLE_SHADER_TEXTURE_2D),
        ] {
            assert!(
                shader.contains("sheen_environment_lighting")
                    && shader.contains("environment += sheen_environment_lighting(normal, view, sheen_color, sheen_roughness);"),
                "{name} shader must apply KHR_materials_sheen under environment lighting; \
                 direct-light-only sheen cannot prove satin/fabric material presets"
            );
        }
    }

    #[test]
    fn triangle_shader_applies_scene_color_transmission_in_native_and_webgl2_variants() {
        for (name, shader) in [
            ("texture_2d_array", GPU_TRIANGLE_SHADER),
            ("texture_2d", GPU_TRIANGLE_SHADER_TEXTURE_2D),
        ] {
            assert!(
                shader.contains("var transmission_color_texture: texture_2d<f32>")
                    && shader.contains("var transmission_color_sampler: sampler")
                    && shader.contains("transmission_factors: vec4<f32>")
                    && shader.contains("physical_transmission_color(")
                    && shader.contains("let ior = max(material.transmission_factors.y, 1.01);")
                    && shader.contains("let thickness = max(material.transmission_factors.z, 0.0);")
                    && shader.contains("let view_dir = normalize(view);")
                    && shader.contains("let normal_dir = normalize(normal);")
                    && shader.contains("let refracted = refract(-view_dir, normal_dir, 1.0 / ior);")
                    && shader.contains("let thickness_scale = 0.004 + min(thickness, 1.0) * 0.028;")
                    && shader.contains("let blur_px = roughness * roughness * 48.0;")
                    && shader.contains("let refraction_mix = clamp(0.58 + roughness * 0.40 + rim_fresnel * 0.10, 0.58, 0.96);")
                    && shader.contains("let refracted_blurred =")
                    && shader.contains("let rim_fresnel = pow(1.0 - n_dot_v, 5.0);")
                    && shader.contains("let reflection_weight = clamp(0.08 + rim_fresnel * 0.42 + (1.0 - transmission) * 0.10, 0.08, 0.50);")
                    && shader.contains("let tint_strength = clamp(transmission * 0.035, 0.0, 0.035);")
                    && shader.contains("return vec4<f32>(mix(transmitted, reflected, reflection_weight), 1.0);")
                    && shader.contains(
                        "textureSample(transmission_color_texture, transmission_color_sampler"
                    ),
                "{name} shader must sample opaque scene color with IOR/thickness refraction \
                 and roughness blur; alpha-blend-only glass is not enough for Round E material proof"
            );
        }
    }

    #[test]
    fn triangle_shader_applies_material_screen_space_reflections_in_native_and_webgl2_variants() {
        for (name, shader) in [
            ("texture_2d_array", GPU_TRIANGLE_SHADER),
            ("texture_2d", GPU_TRIANGLE_SHADER_TEXTURE_2D),
        ] {
            assert!(
                shader.contains("screen_space_material_reflection(")
                    && shader.contains("camera.color_management.z")
                    && shader.contains("let ssr_active = step(0.001, strength) * step(0.5, metallic);")
                    && shader.contains("let reflection = reflect(-view_dir, normal_dir);")
                    && shader.contains("let raw_reflected_uv = uv + vec2<f32>(reflection.x, -reflection.y) * reflect_scale;")
                    && shader.contains("let edge_fade = smoothstep(0.0, 0.02, edge_distance);")
                    && shader.contains(
                        "textureSample(transmission_color_texture, transmission_color_sampler, reflected_uv"
                    )
                    && shader.contains(
                        "let weight = clamp(ssr_active * strength * metallic * (0.38 + fresnel * 0.52) * (1.0 - roughness * 0.55) * edge_fade"
                    ),
                "{name} shader must sample opaque scene color for high-metallic material SSR; \
                 floor-only post reflections do not prove chrome/mirror material reflections"
            );
        }
    }

    #[test]
    fn triangle_shader_applies_anisotropy_lobe_in_native_and_webgl2_variants() {
        for (name, shader) in [
            ("texture_2d_array", GPU_TRIANGLE_SHADER),
            ("texture_2d", GPU_TRIANGLE_SHADER_TEXTURE_2D),
        ] {
            assert!(
                shader.contains("anisotropy_light_contribution")
                    && shader.contains("let anisotropy_direction = anisotropy_sample.rg * 2.0 - vec2<f32>(1.0, 1.0);")
                    && shader.contains("let anisotropy_strength = clamp(material.anisotropy_factors.x * anisotropy_sample.b, 0.0, 1.0);")
                    && shader.contains("material.anisotropy_factors.y")
                    && shader.contains("world_tangent")
                    && shader.contains("tangent_handedness")
                    && shader.contains("shaded += anisotropy_light_contribution(base, metallic, roughness, normal, world_tangent, tangent_handedness, view, incoming, radiance, anisotropy_strength, anisotropy_rotation, anisotropy_direction);"),
                "{name} shader must apply KHR_materials_anisotropy direction, strength, and rotation instead of silently dropping them"
            );
        }
    }

    #[test]
    fn triangle_shader_applies_iridescence_lobe_in_native_and_webgl2_variants() {
        for (name, shader) in [
            ("texture_2d_array", GPU_TRIANGLE_SHADER),
            ("texture_2d", GPU_TRIANGLE_SHADER_TEXTURE_2D),
        ] {
            assert!(
                shader.contains("iridescence_light_contribution")
                    && shader.contains("let iridescence_factor = clamp(material.iridescence_factors.x * iridescence_sample.r, 0.0, 1.0);")
                    && shader.contains("let iridescence_thickness = mix(material.iridescence_factors.z, material.iridescence_factors.w, clamp(iridescence_thickness_sample.g, 0.0, 1.0));")
                    && shader.contains("material.iridescence_factors.y")
                    && shader.contains("shaded += iridescence_light_contribution(base, metallic, roughness, normal, view, incoming, radiance, iridescence_factor, iridescence_ior, iridescence_thickness);"),
                "{name} shader must apply KHR_materials_iridescence factor, IOR, and thickness texture channels instead of silently dropping them"
            );
        }
    }

    #[test]
    fn triangle_shader_applies_dispersion_lobe_in_native_and_webgl2_variants() {
        for (name, shader) in [
            ("texture_2d_array", GPU_TRIANGLE_SHADER),
            ("texture_2d", GPU_TRIANGLE_SHADER_TEXTURE_2D),
        ] {
            assert!(
                shader.contains("dispersion_light_contribution")
                    && shader.contains("dispersion_factors: vec4<f32>")
                    && shader.contains("let dispersion_factor = max(material.dispersion_factors.x, 0.0);")
                    && shader.contains("material.dispersion_factors.y")
                    && shader.contains("shaded += dispersion_light_contribution(base, metallic, roughness, normal, view, incoming, radiance, dispersion_factor, dispersion_ior);"),
                "{name} shader must apply KHR_materials_dispersion factor and IOR spread instead of silently dropping them"
            );
        }
    }

    #[test]
    fn triangle_shader_applies_occlusion_strength_to_lit_pbr_output() {
        for (name, shader) in [
            ("texture_2d_array", GPU_TRIANGLE_SHADER),
            ("texture_2d", GPU_TRIANGLE_SHADER_TEXTURE_2D),
        ] {
            assert!(
                shader.contains(
                    "let occlusion_applied = mix(1.0, occlusion_sample, occlusion_strength)"
                ) && shader.contains("shaded_rgb = (direct + environment) * occlusion_applied;")
                    && !shader.contains("shaded_rgb = (direct + environment) * occlusion_sample;"),
                "{name} shader must apply glTF occlusionTexture.strength in the lit PBR branch"
            );
        }
    }

    #[test]
    fn triangle_shader_discards_alpha_masked_fragments() {
        assert!(
            GPU_TRIANGLE_SHADER.contains("material.metallic_roughness_alpha.z > 0.0")
                && GPU_TRIANGLE_SHADER.contains("base.a < material.metallic_roughness_alpha.z")
                && GPU_TRIANGLE_SHADER.contains("discard;"),
            "GPU material shader must apply alpha-mask cutoff after base-color texture sampling"
        );
    }

    #[test]
    fn triangle_shader_consumes_gpu_punctual_light_uniforms() {
        assert!(
            GPU_TRIANGLE_SHADER.contains("struct LightingUniform")
                && GPU_TRIANGLE_SHADER.contains("directional_light_direction_intensity")
                && GPU_TRIANGLE_SHADER.contains("point_light_position_intensity")
                && GPU_TRIANGLE_SHADER.contains("spot_light_direction_cones")
                && GPU_TRIANGLE_SHADER.contains("area_light_position_flux")
                && GPU_TRIANGLE_SHADER.contains("area_light_sample_position")
                && GPU_TRIANGLE_SHADER.contains("ltc_area_light_specular_contribution")
                && GPU_TRIANGLE_SHADER.contains("ltc_lookup_tables")
                && GPU_TRIANGLE_SHADER.contains("LTC_TABLE_1")
                && GPU_TRIANGLE_SHADER.contains("pbr_light_contribution")
                && GPU_TRIANGLE_SHADER.contains("fresnel_schlick")
                && GPU_TRIANGLE_SHADER.contains("distribution_ggx")
                && GPU_TRIANGLE_SHADER.contains("visibility_ggx_correlated")
                && GPU_TRIANGLE_SHADER.contains("brdf_specular_ggx"),
            "GPU PBR shader must consume prepared directional, point, spot, and area light uniforms \
             through a GGX/Smith/Schlick BRDF before backend PBR lighting can be claimed"
        );
    }

    #[test]
    fn triangle_shader_contains_ltc_area_light_specular_path_for_both_texture_layouts() {
        for (name, shader) in [
            ("texture_2d_array", GPU_TRIANGLE_SHADER),
            ("texture_2d", GPU_TRIANGLE_SHADER_TEXTURE_2D),
        ] {
            assert!(
                shader.contains("fn ltc_area_light_specular_contribution")
                    && shader.contains("fn ltc_area_light_polygon")
                    && shader.contains("fn ltc_evaluate_specular_polygon")
                    && shader.contains("fn ltc_lookup_tables")
                    && shader.contains("LTC_TABLE_1")
                    && shader.contains("LTC_TABLE_2")
                    && shader.contains("fn ltc_integrate_edge")
                    && shader.contains("fn ltc_clip_quad_to_horizon")
                    && shader.contains("shaded += ltc_area_light_specular_contribution("),
                "{name} shader must include the same fitted-table linearly-transformed-cosine area-light specular path as the CPU reference"
            );
        }
    }

    #[test]
    fn triangle_shader_avoids_pow_in_hot_pbr_fragment_paths() {
        for (name, shader) in [
            ("texture_2d_array", GPU_TRIANGLE_SHADER),
            ("texture_2d", GPU_TRIANGLE_SHADER_TEXTURE_2D),
        ] {
            assert!(
                shader.contains("fn pow4(value: f32) -> f32")
                    && shader.contains("fn pow5(value: f32) -> f32")
                    && shader.contains("pow5(1.0 - clamp(cos_theta")
                    && shader.contains("pow4(distance / range)")
                    && !shader.contains("pow(1.0 - clamp(cos_theta")
                    && !shader.contains("pow(distance / range"),
                "{name} shader must use multiply-chain pow4/pow5 helpers in the PBR hot path \
                 because WebGL2 drivers can lower generic pow() expensively"
            );
        }
    }

    #[test]
    fn triangle_shader_consumes_gpu_environment_light_uniforms() {
        assert!(
            GPU_TRIANGLE_SHADER.contains("environment_diffuse_intensity")
                && GPU_TRIANGLE_SHADER.contains("environment_specular_intensity")
                && GPU_TRIANGLE_SHADER.contains("has_environment_light")
                && GPU_TRIANGLE_SHADER.contains("pbr_environment_lighting")
                && GPU_TRIANGLE_SHADER.contains("split_sum_brdf_approx"),
            "GPU PBR shader must consume prepared environment irradiance/specular uniforms \
             before backend IBL lighting can be claimed"
        );
    }

    #[test]
    fn triangle_shader_applies_clearcoat_lobe_to_environment_ibl() {
        for (name, shader) in [
            ("texture_2d_array", GPU_TRIANGLE_SHADER),
            ("texture_2d", GPU_TRIANGLE_SHADER_TEXTURE_2D),
        ] {
            assert!(
                shader.contains("fn clearcoat_environment_lighting(")
                    && shader.contains(
                        "environment += clearcoat_environment_lighting(clearcoat_normal, view, clearcoat_factor, clearcoat_roughness);"
                    ),
                "{name} shader must add a separate clearcoat specular IBL lobe; \
                 direct-light clearcoat alone makes coated materials read like ordinary glossy plastic under HDR"
            );
        }
    }

    #[test]
    fn triangle_shader_applies_anisotropy_lobe_to_environment_ibl() {
        for (name, shader) in [
            ("texture_2d_array", GPU_TRIANGLE_SHADER),
            ("texture_2d", GPU_TRIANGLE_SHADER_TEXTURE_2D),
        ] {
            assert!(
                shader.contains("fn anisotropy_environment_lighting(")
                    && shader.contains(
                        "environment += anisotropy_environment_lighting(base.rgb, metallic, roughness, normal, world_tangent, in.tangent.w, view, anisotropy_strength, material.anisotropy_factors.y, anisotropy_direction);"
                    ),
                "{name} shader must route anisotropy into environment IBL; \
                 direct-light-only anisotropy leaves brushed metal with round HDR highlights"
            );
        }
    }

    #[test]
    fn triangle_shader_uses_prepared_irradiance_for_diffuse_ibl() {
        for (name, shader) in [
            ("texture_2d_array", GPU_TRIANGLE_SHADER),
            ("texture_2d", GPU_TRIANGLE_SHADER_TEXTURE_2D),
        ] {
            assert!(
                shader.contains(
                    "let diffuse_irradiance = camera.lighting.environment_diffuse_intensity.rgb"
                ) && shader.contains(
                    "diffuse_energy * base * diffuse_irradiance * camera.lighting.environment_diffuse_intensity.w"
                ) && !shader.contains(
                    "textureSampleLevel(environment_cubemap, environment_sampler, normal, 0.0).rgb"
                ),
                "{name} shader must use prepared diffuse irradiance for diffuse IBL; \
                 sampling raw HDR radiance in the surface-normal direction makes real HDR \
                 environments dark and high-contrast"
            );
        }
    }

    #[test]
    fn triangle_shader_samples_directional_shadow_map_in_fragment() {
        // Phase 1B step 2: the GPU pipeline sources shadow attenuation from a
        // hardware depth-comparison sample of the directional light's depth
        // map (`shadow_map` + `shadow_sampler` bindings, projected through
        // `camera.light_from_world`), not from a CPU-baked per-vertex
        // attribute. The fragment shader multiplies directional radiance by
        // the per-fragment GPU shadow factor.
        assert!(
            GPU_TRIANGLE_SHADER.contains("textureSampleCompareLevel(shadow_map, shadow_sampler"),
            "GPU PBR lighting must sample the hardware-comparison shadow_map texture \
             with shadow_sampler so opt-in shadowed directional lights project real depth"
        );
        assert!(
            GPU_TRIANGLE_SHADER.contains("camera.light_from_world * vec4<f32>(world_position"),
            "GPU shadow path must reproject world position through camera.light_from_world \
             so the shadow lookup is in light-clip space, not world space"
        );
        assert!(
            GPU_TRIANGLE_SHADER.contains("* gpu_shadow"),
            "GPU PBR fragment must scale directional radiance by the GPU-sampled shadow factor \
             instead of multiplying by the (now retired) CPU shadow_visibility attribute"
        );
        assert!(
            GPU_TRIANGLE_SHADER.contains("directional_shadow_control[i].x > 0.5")
                && GPU_TRIANGLE_SHADER.contains("let gpu_shadow = select(")
                && GPU_TRIANGLE_SHADER.contains("directional_shadow_factor(world_position)")
                && GPU_TRIANGLE_SHADER.contains("* gpu_shadow"),
            "GPU PBR fragment must sample the directional shadow map only when a \
             shadow-casting directional light was prepared; non-shadowed lights must not \
             be multiplied by a placeholder shadow texture"
        );
    }

    #[test]
    fn triangle_shader_multiplies_area_lights_by_prepared_area_shadow_visibility() {
        for (name, shader) in [
            ("texture_2d_array", GPU_TRIANGLE_SHADER),
            ("texture_2d", GPU_TRIANGLE_SHADER_TEXTURE_2D),
        ] {
            assert!(
                shader.contains("let area_shadow_visibility = clamp(shadow_visibility, 0.0, 1.0)")
                    && shader.contains(
                        "area_light_radiance(i, sample_position, world_position) * area_shadow_visibility"
                    ),
                "{name} shader must consume prepared area-light visibility so finite emitters \
                 can produce soft penumbra instead of unshadowed area-light radiance"
            );
        }
    }

    #[test]
    fn triangle_shader_builds_tangent_space_normal_from_normal_map() {
        assert!(
            GPU_TRIANGLE_SHADER.contains("@location(4) tangent: vec4<f32>")
                && GPU_TRIANGLE_SHADER.contains("let normal_texture_sample = textureSample(normal_texture")
                && !GPU_TRIANGLE_SHADER.contains("let normal_sample = textureSample(normal_texture")
                && GPU_TRIANGLE_SHADER.contains(
                    "let bitangent = normalize(cross(world_normal, world_tangent) * in.tangent.w);"
                )
                && GPU_TRIANGLE_SHADER.contains(
                    "normal_sample.x * world_tangent + normal_sample.y * bitangent + normal_sample.z * world_normal",
                ),
            "GPU normal mapping must use a prepared tangent basis instead of treating the \
             normal texture as a scalar visibility multiplier"
        );
    }

    fn identity_clip_from_world() -> [f32; 16] {
        [
            1.0, 0.0, 0.0, 0.0, //
            0.0, 1.0, 0.0, 0.0, //
            0.0, 0.0, 1.0, 0.0, //
            0.0, 0.0, 0.0, 1.0,
        ]
    }
}