euv-core 0.49.4

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
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
use super::*;

/// Constructors for `PointLight3D`.
impl PointLight3D {
    /// Creates a physically based 3D point light from sRGB `color`, `intensity`, and `radius`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space center position.
    /// - `Color` - sRGB emission color.
    /// - `f32` - Luminous intensity multiplier.
    /// - `f32` - Maximum influence radius in meters.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured point light.
    #[must_use]
    pub fn new(position: Vec3, color: Color, intensity: f32, radius: f32) -> Self {
        Self {
            position,
            color: Vec3::from_color(color),
            intensity: intensity.max(0.0),
            radius: radius.max(0.25),
            cast_shadows: false,
        }
    }
}

/// Constructors for `SpotLight3D`.
impl SpotLight3D {
    /// Creates a physically based 3D spotlight from position, direction, sRGB color, intensity, range, and cone half-angles in degrees.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space emitter origin.
    /// - `Vec3` - Beam direction vector (normalized automatically).
    /// - `Color` - sRGB emission color.
    /// - `f32` - Luminous intensity multiplier.
    /// - `f32` - Maximum beam range in meters.
    /// - `(f32, f32)` - `(inner_half_angle_deg, outer_half_angle_deg)` cone angles.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured spotlight.
    #[must_use]
    pub fn new(
        position: Vec3,
        direction: Vec3,
        color: Color,
        intensity: f32,
        range: f32,
        cone_deg: (f32, f32),
    ) -> Self {
        let (inner_deg, outer_deg): (f32, f32) = cone_deg;
        let clamped_inner: f32 = inner_deg.clamp(1.0, 80.0);
        let clamped_outer: f32 = outer_deg.clamp(clamped_inner + 1.0, 88.0);
        Self {
            position,
            direction: direction.normalize(),
            color: Vec3::from_color(color),
            intensity: intensity.max(0.0),
            range: range.max(0.5),
            inner_cos: clamped_inner.to_radians().cos(),
            outer_cos: clamped_outer.to_radians().cos(),
        }
    }
}

/// Default pre-allocated 16x9x16 `LightClusterGrid3D`.
impl Default for LightClusterGrid3D {
    /// Creates an empty pre-allocated `LightClusterGrid3D` ready for zero-allocation per-frame light binning.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready clustered light grid.
    fn default() -> Self {
        let total_froxels: usize =
            LIGHT_CLUSTER_GRID_X * LIGHT_CLUSTER_GRID_Y * LIGHT_CLUSTER_GRID_Z;
        Self {
            near_plane: 0.3,
            far_plane: 420.0,
            log_depth_scale: (LIGHT_CLUSTER_GRID_Z as f32) / (420.0_f32 / 0.3_f32).ln(),
            depth_slice_max: [420.0; LIGHT_CLUSTER_GRID_Z],
            active_light_count: 0,
            total_assignments: 0,
            packed_lights: Vec::with_capacity(LIGHT_CLUSTER_MAX_LIGHTS),
            cluster_counts: vec![0_u16; total_froxels],
            cluster_indices: vec![0_u16; total_froxels * LIGHT_CLUSTER_MAX_PER_FROXEL],
        }
    }
}

/// 3D frustum froxel binning and Cook-Torrance GGX local light evaluation for `LightClusterGrid3D`.
impl LightClusterGrid3D {
    /// Returns whether any local point or spot lights are active in the current frame.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when at least one local light is binned.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn has_active_lights(&self) -> bool {
        self.get_active_light_count() > 0
    }

    /// Bins all `point_lights` and `spot_lights` into the 16x9x16 logarithmic-Z camera frustum grid without heap allocations.
    ///
    /// # Arguments
    ///
    /// - `&Camera3D` - Active 3D perspective camera.
    /// - `f32` - Viewport width-to-height aspect ratio.
    /// - `&[PointLight3D]` - Active world-space point lights.
    /// - `&[SpotLight3D]` - Active world-space spotlights.
    pub fn build_clusters(
        &mut self,
        camera: &Camera3D,
        aspect: f32,
        point_lights: &[PointLight3D],
        spot_lights: &[SpotLight3D],
    ) {
        let near_p: f32 = camera.get_near().max(0.15);
        let far_p: f32 = camera.get_far().max(near_p + 1.0);
        let log_scale: f32 = (LIGHT_CLUSTER_GRID_Z as f32) / (far_p / near_p).ln().max(1.0e-4);
        self.set_near_plane(near_p);
        self.set_far_plane(far_p);
        self.set_log_depth_scale(log_scale);
        let depth_ratio: f32 = far_p / near_p;
        {
            let Self {
                depth_slice_max, ..
            } = self;
            for (slice_idx, slot) in depth_slice_max.iter_mut().enumerate() {
                let frac: f32 = ((slice_idx + 1) as f32) / (LIGHT_CLUSTER_GRID_Z as f32);
                *slot = near_p * depth_ratio.powf(frac);
            }
        }
        let cam_pos: Vec3 = camera.get_position();
        let cam_fwd: Vec3 = camera.forward();
        let cam_right: Vec3 = camera.right();
        let cam_up: Vec3 = cam_right.cross(cam_fwd).normalize();
        let half_h: f32 = (camera.get_fov_deg().to_radians() * 0.5).tan().max(0.05);
        let half_w: f32 = half_h * aspect.max(0.1);
        let inv_half_w: f32 = 1.0 / half_w;
        let inv_half_h: f32 = 1.0 / half_h;
        let mut assignments: usize = 0;
        let active_count: usize = {
            let Self {
                packed_lights,
                cluster_counts,
                cluster_indices,
                ..
            } = self;
            packed_lights.clear();
            if point_lights.is_empty() && spot_lights.is_empty() {
                cluster_counts.fill(0);
                0
            } else {
                cluster_counts.fill(0);
                for point_light in point_lights.iter() {
                    if packed_lights.len() >= LIGHT_CLUSTER_MAX_LIGHTS {
                        break;
                    }
                    let rad: f32 = point_light.get_radius().max(0.25);
                    let intensity: f32 = point_light.get_intensity();
                    if intensity <= 1.0e-4 {
                        continue;
                    }
                    let light_pos: Vec3 = point_light.get_position();
                    let col: Vec3 = point_light.get_color().scale(intensity);
                    let light_idx: u16 = packed_lights.len() as u16;
                    packed_lights.push(PackedLocalLight {
                        pos_inv_r2: [
                            light_pos.get_x(),
                            light_pos.get_y(),
                            light_pos.get_z(),
                            1.0 / (rad * rad),
                        ],
                        radiance_radius: [col.get_x(), col.get_y(), col.get_z(), rad],
                        dir_outer_cos: [0.0, -1.0, 0.0, -2.0],
                        inv_cone_span: [0.0; 4],
                    });
                    assignments += Self::bin_sphere_into_froxels(
                        (cam_pos, cam_right, cam_up, cam_fwd),
                        (inv_half_w, inv_half_h, near_p, far_p, log_scale),
                        (light_pos, rad, light_idx),
                        cluster_counts,
                        cluster_indices,
                    );
                }
                for spot_light in spot_lights.iter() {
                    if packed_lights.len() >= LIGHT_CLUSTER_MAX_LIGHTS {
                        break;
                    }
                    let range: f32 = spot_light.get_range().max(0.5);
                    let intensity: f32 = spot_light.get_intensity();
                    if intensity <= 1.0e-4 {
                        continue;
                    }
                    let light_pos: Vec3 = spot_light.get_position();
                    let light_dir: Vec3 = spot_light.get_direction().normalize();
                    let col: Vec3 = spot_light.get_color().scale(intensity);
                    let outer_cos: f32 = spot_light.get_outer_cos();
                    let span: f32 = (spot_light.get_inner_cos() - outer_cos).max(SPOT_CONE_MIN_EPS);
                    let light_idx: u16 = packed_lights.len() as u16;
                    packed_lights.push(PackedLocalLight {
                        pos_inv_r2: [
                            light_pos.get_x(),
                            light_pos.get_y(),
                            light_pos.get_z(),
                            1.0 / (range * range),
                        ],
                        radiance_radius: [col.get_x(), col.get_y(), col.get_z(), range],
                        dir_outer_cos: [
                            light_dir.get_x(),
                            light_dir.get_y(),
                            light_dir.get_z(),
                            outer_cos,
                        ],
                        inv_cone_span: [1.0 / span, 0.0, 0.0, 0.0],
                    });
                    let cone_center: Vec3 = light_pos.add(light_dir.scale(range * 0.45));
                    let cone_bound_rad: f32 = range * 0.45;
                    assignments += Self::bin_sphere_into_froxels(
                        (cam_pos, cam_right, cam_up, cam_fwd),
                        (inv_half_w, inv_half_h, near_p, far_p, log_scale),
                        (cone_center, cone_bound_rad, light_idx),
                        cluster_counts,
                        cluster_indices,
                    );
                }
                packed_lights.len()
            }
        };
        self.set_active_light_count(active_count);
        self.set_total_assignments(assignments);
    }

    /// Bins a single light bounding sphere into all overlapped `(x, y, z)` froxels and returns the assignment count.
    ///
    /// # Arguments
    ///
    /// - `(Vec3, Vec3, Vec3, Vec3)` - Camera `(position, right, up, forward)` basis.
    /// - `(f32, f32, f32, f32, f32)` - `(inv_half_w, inv_half_h, near_p, far_p, log_scale)` frustum parameters.
    /// - `(Vec3, f32, u16)` - `(sphere_center, sphere_radius, light_index)`.
    /// - `&mut [u16]` - Mutable froxel count table.
    /// - `&mut [u16]` - Mutable flat froxel index array.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of froxels updated for this light.
    fn bin_sphere_into_froxels(
        cam_basis: (Vec3, Vec3, Vec3, Vec3),
        frustum_params: (f32, f32, f32, f32, f32),
        sphere: (Vec3, f32, u16),
        cluster_counts: &mut [u16],
        cluster_indices: &mut [u16],
    ) -> usize {
        let (cam_pos, cam_right, cam_up, cam_fwd): (Vec3, Vec3, Vec3, Vec3) = cam_basis;
        let (inv_half_w, inv_half_h, near_p, far_p, log_scale): (f32, f32, f32, f32, f32) =
            frustum_params;
        let (center, radius, light_idx): (Vec3, f32, u16) = sphere;
        let rel: Vec3 = center.sub(cam_pos);
        let vz: f32 = rel.dot(cam_fwd);
        let z_min: f32 = vz - radius;
        let z_max: f32 = vz + radius;
        if z_max <= near_p || z_min >= far_p {
            return 0;
        }
        let vx: f32 = rel.dot(cam_right);
        let vy: f32 = rel.dot(cam_up);
        let z_proj: f32 = vz.max(near_p);
        let inv_z: f32 = 1.0 / z_proj;
        let ndc_cx: f32 = vx * inv_z * inv_half_w;
        let ndc_cy: f32 = vy * inv_z * inv_half_h;
        let pad_x: f32 = if z_min <= near_p {
            (radius / vz.max(2.0) * inv_half_w).clamp(0.35, 1.35)
        } else {
            (radius / z_min) * inv_half_w
        };
        let pad_y: f32 = if z_min <= near_p {
            (radius / vz.max(2.0) * inv_half_h).clamp(0.35, 1.35)
        } else {
            (radius / z_min) * inv_half_h
        };
        let min_u: f32 = (ndc_cx - pad_x) * 0.5 + 0.5;
        let max_u: f32 = (ndc_cx + pad_x) * 0.5 + 0.5;
        let min_v: f32 = 0.5 - (ndc_cy + pad_y) * 0.5;
        let max_v: f32 = 0.5 - (ndc_cy - pad_y) * 0.5;
        let out_u: bool = max_u < 0.0 || min_u > 1.0;
        let out_v: bool = max_v < 0.0 || min_v > 1.0;
        if out_u || out_v {
            return 0;
        }
        let gx_max: usize = LIGHT_CLUSTER_GRID_X - 1;
        let gy_max: usize = LIGHT_CLUSTER_GRID_Y - 1;
        let gz_max: usize = LIGHT_CLUSTER_GRID_Z - 1;
        let cx0: usize =
            ((min_u.clamp(0.0, 1.0) * (LIGHT_CLUSTER_GRID_X as f32)).floor() as usize).min(gx_max);
        let cx1: usize =
            ((max_u.clamp(0.0, 1.0) * (LIGHT_CLUSTER_GRID_X as f32)).floor() as usize).min(gx_max);
        let cy0: usize =
            ((min_v.clamp(0.0, 1.0) * (LIGHT_CLUSTER_GRID_Y as f32)).floor() as usize).min(gy_max);
        let cy1: usize =
            ((max_v.clamp(0.0, 1.0) * (LIGHT_CLUSTER_GRID_Y as f32)).floor() as usize).min(gy_max);
        let cz0: usize = ((((z_min.max(near_p) / near_p).ln()) * log_scale)
            .floor()
            .max(0.0) as usize)
            .min(gz_max);
        let cz1: usize = ((((z_max.min(far_p) / near_p).ln()) * log_scale)
            .floor()
            .max(0.0) as usize)
            .min(gz_max);
        let slice_stride: usize = LIGHT_CLUSTER_GRID_X * LIGHT_CLUSTER_GRID_Y;
        let mut count_added: usize = 0;
        for cz in cz0..=cz1 {
            let z_off: usize = cz * slice_stride;
            for cy in cy0..=cy1 {
                let y_off: usize = z_off + cy * LIGHT_CLUSTER_GRID_X;
                for cx in cx0..=cx1 {
                    let froxel: usize = y_off + cx;
                    let cur: usize = cluster_counts[froxel] as usize;
                    if cur < LIGHT_CLUSTER_MAX_PER_FROXEL {
                        cluster_indices[froxel * LIGHT_CLUSTER_MAX_PER_FROXEL + cur] = light_idx;
                        cluster_counts[froxel] = (cur + 1) as u16;
                        count_added += 1;
                    }
                }
            }
        }
        count_added
    }

    /// Evaluates all local point and spot lights assigned to the pixel's 3D froxel using UE5 windowed inverse-square PBR attenuation and Cook-Torrance GGX specular.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Pixel world-space surface position.
    /// - `Vec3` - Unit outward surface normal.
    /// - `Vec3` - Unit view direction pointing from surface toward camera.
    /// - `(Vec3, Vec3, f32, f32)` - `(base_albedo, f0_specular, alpha2_ggx, diffuse_scale)`.
    /// - `(f32, f32, f32)` - `(uv_x, uv_y, linear_depth)` normalized screen UV in `[0, 1]` and camera depth.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Summed linear HDR direct radiance contributed by local clustered lights.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn evaluate_pixel(
        &self,
        world_pos: Vec3,
        normal: Vec3,
        view_dir: Vec3,
        material_terms: (Vec3, Vec3, f32, f32),
        screen_depth: (f32, f32, f32),
    ) -> Vec3 {
        if self.get_active_light_count() == 0 {
            return Vec3::zero();
        }
        let (uv_x, uv_y, linear_depth): (f32, f32, f32) = screen_depth;
        let near_p: f32 = self.get_near_plane();
        if linear_depth < near_p || linear_depth > self.get_far_plane() {
            return Vec3::zero();
        }
        let cx: usize = ((uv_x.clamp(0.0, 0.9999) * (LIGHT_CLUSTER_GRID_X as f32)) as usize)
            .min(LIGHT_CLUSTER_GRID_X - 1);
        let cy: usize = ((uv_y.clamp(0.0, 0.9999) * (LIGHT_CLUSTER_GRID_Y as f32)) as usize)
            .min(LIGHT_CLUSTER_GRID_Y - 1);
        let cz: usize = ((((linear_depth / near_p).ln()) * self.get_log_depth_scale()).max(0.0)
            as usize)
            .min(LIGHT_CLUSTER_GRID_Z - 1);
        let froxel: usize = (cz * LIGHT_CLUSTER_GRID_Y + cy) * LIGHT_CLUSTER_GRID_X + cx;
        let Self {
            packed_lights,
            cluster_counts,
            cluster_indices,
            ..
        } = self;
        let light_count: usize = cluster_counts[froxel] as usize;
        if light_count == 0 {
            return Vec3::zero();
        }
        let (albedo, f0, alpha2, diffuse_scale): (Vec3, Vec3, f32, f32) = material_terms;
        let n_dot_v: f32 = normal.dot(view_dir).max(0.04);
        let idx_base: usize = froxel * LIGHT_CLUSTER_MAX_PER_FROXEL;
        let mut accum: Vec3 = Vec3::zero();
        for slot in 0..light_count {
            let light: PackedLocalLight = packed_lights[cluster_indices[idx_base + slot] as usize];
            let to_light: Vec3 = Vec3::new(
                light.pos_inv_r2[0] - world_pos.get_x(),
                light.pos_inv_r2[1] - world_pos.get_y(),
                light.pos_inv_r2[2] - world_pos.get_z(),
            );
            let dist_sq: f32 = to_light.length_sq();
            let ratio_sq: f32 = dist_sq * light.pos_inv_r2[3];
            if ratio_sq >= 1.0 {
                continue;
            }
            let inv_dist: f32 = 1.0 / dist_sq.max(1.0e-4).sqrt();
            let light_dir: Vec3 = to_light.scale(inv_dist);
            let n_dot_l: f32 = normal.dot(light_dir);
            if n_dot_l <= 0.0 {
                continue;
            }
            let mut spot_factor: f32 = 1.0;
            if light.dir_outer_cos[3] > -1.5 {
                let beam_dir: Vec3 = Vec3::new(
                    light.dir_outer_cos[0],
                    light.dir_outer_cos[1],
                    light.dir_outer_cos[2],
                );
                let cos_theta: f32 = (-light_dir.get_x()) * beam_dir.get_x()
                    + (-light_dir.get_y()) * beam_dir.get_y()
                    + (-light_dir.get_z()) * beam_dir.get_z();
                if cos_theta <= light.dir_outer_cos[3] {
                    continue;
                }
                let raw_spot: f32 =
                    ((cos_theta - light.dir_outer_cos[3]) * light.inv_cone_span[0]).clamp(0.0, 1.0);
                spot_factor = raw_spot * raw_spot;
            }
            let window: f32 = (1.0 - ratio_sq * ratio_sq).max(0.0);
            let atten: f32 = (window * window * spot_factor) / (dist_sq + 1.0);
            let half_vec: Vec3 = light_dir.add(view_dir).normalize();
            let n_dot_h: f32 = normal.dot(half_vec).max(0.0);
            let v_dot_h: f32 = view_dir.dot(half_vec).clamp(0.0, 1.0);
            let denom: f32 = n_dot_h * n_dot_h * (alpha2 - 1.0) + 1.0;
            let ggx_d: f32 = alpha2 / (PI * denom * denom).max(1.0e-4);
            let one_minus_vh: f32 = 1.0 - v_dot_h;
            let pow5: f32 =
                one_minus_vh * one_minus_vh * one_minus_vh * one_minus_vh * one_minus_vh;
            let fresnel: Vec3 = f0.add(Vec3::splat(1.0).sub(f0).scale(pow5));
            let spec_scalar: f32 = (ggx_d * 0.25) / (n_dot_l.max(0.08) + n_dot_v);
            let diffuse_rgb: Vec3 = albedo.scale(diffuse_scale * (1.0 / PI));
            let brdf_rgb: Vec3 = diffuse_rgb.add(fresnel.scale(spec_scalar.min(4.0)));
            let light_rad: Vec3 = Vec3::new(
                light.radiance_radius[0],
                light.radiance_radius[1],
                light.radiance_radius[2],
            );
            accum = accum.add(brdf_rgb.mul(light_rad).scale(n_dot_l * atten));
        }
        accum
    }

    /// Evaluates fast Lambertian linear-HDR local irradiance from the 3D froxel grid without `ln()` or GGX specular overhead (tuned for coarse deferred probe injection).
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space surface position.
    /// - `Vec3` - Unit outward surface normal.
    /// - `(f32, f32, f32)` - `(uv_x, uv_y, linear_depth)` normalized screen UV in `[0, 1]` and camera depth.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Summed linear HDR local diffuse irradiance RGB.
    #[must_use]
    pub fn evaluate_irradiance_fast(
        &self,
        world_pos: Vec3,
        normal: Vec3,
        screen_depth: (f32, f32, f32),
    ) -> Vec3 {
        if self.get_active_light_count() == 0 {
            return Vec3::zero();
        }
        let (uv_x, uv_y, linear_depth): (f32, f32, f32) = screen_depth;
        if linear_depth < self.get_near_plane() || linear_depth > self.get_far_plane() {
            return Vec3::zero();
        }
        let cx: usize = ((uv_x.clamp(0.0, 0.9999) * (LIGHT_CLUSTER_GRID_X as f32)) as usize)
            .min(LIGHT_CLUSTER_GRID_X - 1);
        let cy: usize = ((uv_y.clamp(0.0, 0.9999) * (LIGHT_CLUSTER_GRID_Y as f32)) as usize)
            .min(LIGHT_CLUSTER_GRID_Y - 1);
        let Self {
            depth_slice_max,
            packed_lights,
            cluster_counts,
            cluster_indices,
            ..
        } = self;
        let mut cz: usize = 0;
        if linear_depth > depth_slice_max[7] {
            cz = 8;
        }
        if linear_depth > depth_slice_max[cz + 3] {
            cz += 4;
        }
        if linear_depth > depth_slice_max[cz + 1] {
            cz += 2;
        }
        if linear_depth > depth_slice_max[cz] {
            cz += 1;
        }
        let froxel: usize = (cz * LIGHT_CLUSTER_GRID_Y + cy) * LIGHT_CLUSTER_GRID_X + cx;
        let light_count: usize = cluster_counts[froxel] as usize;
        if light_count == 0 {
            return Vec3::zero();
        }
        let idx_base: usize = froxel * LIGHT_CLUSTER_MAX_PER_FROXEL;
        let mut accum_r: f32 = 0.0;
        let mut accum_g: f32 = 0.0;
        let mut accum_b: f32 = 0.0;
        let wx: f32 = world_pos.get_x();
        let wy: f32 = world_pos.get_y();
        let wz: f32 = world_pos.get_z();
        let nx: f32 = normal.get_x();
        let ny: f32 = normal.get_y();
        let nz: f32 = normal.get_z();
        for slot in 0..light_count {
            let light: PackedLocalLight = packed_lights[cluster_indices[idx_base + slot] as usize];
            let dx: f32 = light.pos_inv_r2[0] - wx;
            let dy: f32 = light.pos_inv_r2[1] - wy;
            let dz: f32 = light.pos_inv_r2[2] - wz;
            let dist_sq: f32 = dx.mul_add(dx, dy.mul_add(dy, dz * dz));
            let ratio_sq: f32 = dist_sq * light.pos_inv_r2[3];
            if ratio_sq >= 1.0 {
                continue;
            }
            let ndotl_raw: f32 = dx.mul_add(nx, dy.mul_add(ny, dz * nz));
            if ndotl_raw <= 0.0 {
                continue;
            }
            let inv_dist: f32 = 1.0 / dist_sq.max(1.0e-4).sqrt();
            let mut spot_factor: f32 = 1.0;
            if light.dir_outer_cos[3] > -1.5 {
                let cos_theta: f32 = -(dx * light.dir_outer_cos[0]
                    + dy * light.dir_outer_cos[1]
                    + dz * light.dir_outer_cos[2])
                    * inv_dist;
                if cos_theta <= light.dir_outer_cos[3] {
                    continue;
                }
                let raw_spot: f32 =
                    ((cos_theta - light.dir_outer_cos[3]) * light.inv_cone_span[0]).clamp(0.0, 1.0);
                spot_factor = raw_spot * raw_spot;
            }
            let window: f32 = (1.0 - ratio_sq * ratio_sq).max(0.0);
            let scale: f32 =
                (window * window * spot_factor * ndotl_raw * inv_dist) / (dist_sq + 1.0);
            accum_r = light.radiance_radius[0].mul_add(scale, accum_r);
            accum_g = light.radiance_radius[1].mul_add(scale, accum_g);
            accum_b = light.radiance_radius[2].mul_add(scale, accum_b);
        }
        Vec3::new(accum_r, accum_g, accum_b)
    }

    /// Returns the number of local lights assigned to a specific 3D froxel `(cx, cy, cz)`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Froxel X coordinate in `0..16`.
    /// - `usize` - Froxel Y coordinate in `0..9`.
    /// - `usize` - Froxel Z coordinate in `0..16`.
    ///
    /// # Returns
    ///
    /// - `usize` - Count of binned lights in that froxel.
    #[must_use]
    pub fn froxel_light_count(&self, cx: usize, cy: usize, cz: usize) -> usize {
        let out_xy: bool = cx >= LIGHT_CLUSTER_GRID_X || cy >= LIGHT_CLUSTER_GRID_Y;
        if out_xy || cz >= LIGHT_CLUSTER_GRID_Z {
            return 0;
        }
        let Self { cluster_counts, .. } = self;
        let froxel: usize = (cz * LIGHT_CLUSTER_GRID_Y + cy) * LIGHT_CLUSTER_GRID_X + cx;
        cluster_counts[froxel] as usize
    }
}

/// Cascade construction, orthographic shadow rasterization, and PCF sampling for `VsmCascade`.
impl VsmCascade {
    /// Creates a new `VsmCascade` with `resolution x resolution` depth storage and `half_extent_m` world radius.
    ///
    /// # Arguments
    ///
    /// - `usize` - Shadow map edge resolution in texels (`>= 32`).
    /// - `f32` - World-space half-extent in meters.
    ///
    /// # Returns
    ///
    /// - `Self` - Pre-allocated VSM cascade.
    #[must_use]
    pub fn new(resolution: usize, half_extent_m: f32) -> Self {
        let res: usize = resolution.max(32);
        let total: usize = res * res;
        Self {
            resolution: res,
            half_extent_m: half_extent_m.max(8.0),
            snapped_center: Vec3::zero(),
            light_right: Vec3::new(1.0, 0.0, 0.0),
            light_up: Vec3::new(0.0, 0.0, 1.0),
            light_forward: Vec3::new(0.0, 1.0, 0.0),
            depth_min: -160.0,
            depth_max: 160.0,
            static_valid: false,
            static_depth: vec![1.0; total],
            active_depth: vec![1.0; total],
        }
    }

    /// Computes texel-snapped light-space orthonormal basis and center for `focus_pos` and `sun_dir`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Camera focus point in world space.
    /// - `Vec3` - Unit vector pointing toward the directional sun.
    ///
    /// # Returns
    ///
    /// - `(Vec3, Vec3, Vec3, Vec3)` - `(snapped_center, light_right, light_up, light_forward)`.
    #[must_use]
    fn compute_snapped_basis(&self, focus_pos: Vec3, sun_dir: Vec3) -> (Vec3, Vec3, Vec3, Vec3) {
        let fwd: Vec3 = sun_dir.normalize();
        let ref_up: Vec3 = if fwd.get_y().abs() > 0.95 {
            Vec3::new(0.0, 0.0, 1.0)
        } else {
            Vec3::new(0.0, 1.0, 0.0)
        };
        let right: Vec3 = ref_up.cross(fwd).normalize();
        let up: Vec3 = fwd.cross(right).normalize();
        let texel_world: f32 = (self.get_half_extent_m() * 2.0) / (self.get_resolution() as f32);
        let snap_step: f32 = (texel_world * 16.0).max(2.0);
        let proj_r: f32 = (focus_pos.dot(right) / snap_step).floor() * snap_step;
        let proj_u: f32 = (focus_pos.dot(up) / snap_step).floor() * snap_step;
        let proj_f: f32 = (focus_pos.dot(fwd) / snap_step).floor() * snap_step;
        let snapped: Vec3 = right
            .scale(proj_r)
            .add(up.scale(proj_u))
            .add(fwd.scale(proj_f));
        (snapped, right, up, fwd)
    }

    /// Projects a world-space point into normalized cascade UV coordinates and linear shadow depth `[0.0, 1.0]`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space position to project.
    ///
    /// # Returns
    ///
    /// - `(f32, f32, f32)` - `(u_norm, v_norm, depth_norm)` where smaller `depth_norm` is closer to the sun.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn project_world_point(&self, world_pos: Vec3) -> (f32, f32, f32) {
        let rel: Vec3 = world_pos.sub(self.get_snapped_center());
        let inv_span: f32 = 0.5 / self.get_half_extent_m().max(1.0);
        let coord_u: f32 = rel.dot(self.get_light_right()) * inv_span + 0.5;
        let coord_v: f32 = rel.dot(self.get_light_up()) * inv_span + 0.5;
        let light_z: f32 = rel.dot(self.get_light_forward());
        let depth_span: f32 = (self.get_depth_max() - self.get_depth_min()).max(1.0);
        let depth_norm: f32 = (self.get_depth_max() - light_z) / depth_span;
        (coord_u, coord_v, depth_norm)
    }

    /// Rasterizes a world-space triangle `(v0, v1, v2)` into the target shadow depth slice (`min` depth = closest to sun).
    ///
    /// # Arguments
    ///
    /// - `&mut [f32]` - Destination shadow depth buffer (`len == resolution * resolution`).
    /// - `usize` - Shadow map edge resolution.
    /// - `[(f32, f32, f32); 3]` - Projected `(u_norm, v_norm, depth_norm)` triangle vertices.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    fn rasterize_shadow_tri(depth_buf: &mut [f32], res: usize, verts: [(f32, f32, f32); 3]) {
        let res_f: f32 = res as f32;
        let x0: f32 = verts[0].0 * res_f;
        let y0: f32 = verts[0].1 * res_f;
        let z0: f32 = verts[0].2;
        let x1: f32 = verts[1].0 * res_f;
        let y1: f32 = verts[1].1 * res_f;
        let z1: f32 = verts[1].2;
        let x2: f32 = verts[2].0 * res_f;
        let y2: f32 = verts[2].1 * res_f;
        let z2: f32 = verts[2].2;
        let area: f32 = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0);
        if area.abs() < 0.05 {
            return;
        }
        let max_i: i32 = (res as i32) - 1;
        let min_x: i32 = (x0.min(x1).min(x2).floor() as i32).max(0);
        let max_x: i32 = (x0.max(x1).max(x2).ceil() as i32).min(max_i);
        let min_y: i32 = (y0.min(y1).min(y2).floor() as i32).max(0);
        let max_y: i32 = (y0.max(y1).max(y2).ceil() as i32).min(max_i);
        if min_x > max_x || min_y > max_y {
            return;
        }
        let inv_area: f32 = 1.0 / area;
        for py in min_y..=max_y {
            let fy: f32 = (py as f32) + 0.5;
            let row_off: usize = (py as usize) * res;
            for px in min_x..=max_x {
                let fx: f32 = (px as f32) + 0.5;
                let w0: f32 = ((x1 - fx) * (y2 - fy) - (y1 - fy) * (x2 - fx)) * inv_area;
                let w1: f32 = ((x2 - fx) * (y0 - fy) - (y2 - fy) * (x0 - fx)) * inv_area;
                let w2: f32 = 1.0 - w0 - w1;
                if w0 >= -1.0e-4 && w1 >= -1.0e-4 && w2 >= -1.0e-4 {
                    let depth_val: f32 = (w0 * z0 + w1 * z1 + w2 * z2).clamp(0.0, 1.0);
                    let slot: &mut f32 = &mut depth_buf[row_off + (px as usize)];
                    if depth_val < *slot {
                        *slot = depth_val;
                    }
                }
            }
        }
    }

    /// Rebuilds the cached static shadow map buffer for all static shadow-casting objects inside this cascade's bounds.
    ///
    /// # Arguments
    ///
    /// - `&[SceneObject3D]` - World scene objects.
    /// - `&[MeshLodChain]` - Shared world mesh library.
    fn rebuild_static_depth(&mut self, objects: &[SceneObject3D], mesh_lib: &[MeshLodChain]) {
        let res: usize = self.get_resolution();
        let center: Vec3 = self.get_snapped_center();
        let reach: f32 = self.get_half_extent_m() * 1.5;
        let right: Vec3 = self.get_light_right();
        let up: Vec3 = self.get_light_up();
        let fwd: Vec3 = self.get_light_forward();
        let inv_span: f32 = 0.5 / self.get_half_extent_m().max(1.0);
        let depth_max: f32 = self.get_depth_max();
        let inv_depth_span: f32 = 1.0 / (depth_max - self.get_depth_min()).max(1.0);
        {
            let Self { static_depth, .. } = self;
            static_depth.fill(1.0);
            for obj in objects.iter() {
                if !obj.get_ray_trace_caster() || obj.get_is_dynamic() {
                    continue;
                }
                let wb: AxisAlignedBox3D = obj.get_world_bounds();
                let obj_center: Vec3 = wb.center();
                let rel_c: Vec3 = obj_center.sub(center);
                let limit: f32 = reach + wb.radius();
                if rel_c.get_x().abs() > limit && rel_c.get_z().abs() > limit {
                    continue;
                }
                let Some(mesh) = mesh_lib
                    .get(obj.get_mesh_id())
                    .and_then(|chain: &MeshLodChain| chain.get_levels().last())
                else {
                    continue;
                };
                let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
                let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
                let model: Mat4 = obj.get_transform().to_mat4();
                for tri in indices.iter() {
                    let (i0, i1, i2): (usize, usize, usize) =
                        (tri[0] as usize, tri[1] as usize, tri[2] as usize);
                    let out_01: bool = i0 >= verts.len() || i1 >= verts.len();
                    if out_01 || i2 >= verts.len() {
                        continue;
                    }
                    let w0: Vec3 = model.mul_point3(verts[i0].get_position()).sub(center);
                    let w1: Vec3 = model.mul_point3(verts[i1].get_position()).sub(center);
                    let w2: Vec3 = model.mul_point3(verts[i2].get_position()).sub(center);
                    let p0: (f32, f32, f32) = (
                        w0.dot(right) * inv_span + 0.5,
                        w0.dot(up) * inv_span + 0.5,
                        (depth_max - w0.dot(fwd)) * inv_depth_span,
                    );
                    let p1: (f32, f32, f32) = (
                        w1.dot(right) * inv_span + 0.5,
                        w1.dot(up) * inv_span + 0.5,
                        (depth_max - w1.dot(fwd)) * inv_depth_span,
                    );
                    let p2: (f32, f32, f32) = (
                        w2.dot(right) * inv_span + 0.5,
                        w2.dot(up) * inv_span + 0.5,
                        (depth_max - w2.dot(fwd)) * inv_depth_span,
                    );
                    Self::rasterize_shadow_tri(static_depth.as_mut_slice(), res, [p0, p1, p2]);
                }
            }
        }
        self.set_static_valid(true);
    }

    /// Copies the cached static shadow depth into `active_depth` and overlays dynamic shadow casters.
    ///
    /// # Arguments
    ///
    /// - `&[SceneObject3D]` - World scene objects.
    /// - `&[MeshLodChain]` - Shared world mesh library.
    fn overlay_dynamic_depth(&mut self, objects: &[SceneObject3D], mesh_lib: &[MeshLodChain]) {
        let res: usize = self.get_resolution();
        let center: Vec3 = self.get_snapped_center();
        let right: Vec3 = self.get_light_right();
        let up: Vec3 = self.get_light_up();
        let fwd: Vec3 = self.get_light_forward();
        let inv_span: f32 = 0.5 / self.get_half_extent_m().max(1.0);
        let depth_max: f32 = self.get_depth_max();
        let inv_depth_span: f32 = 1.0 / (depth_max - self.get_depth_min()).max(1.0);
        let Self {
            static_depth,
            active_depth,
            ..
        } = self;
        active_depth.copy_from_slice(static_depth.as_slice());
        for obj in objects.iter() {
            if !obj.get_ray_trace_caster() || !obj.get_is_dynamic() {
                continue;
            }
            let Some(mesh) = mesh_lib
                .get(obj.get_mesh_id())
                .and_then(|chain: &MeshLodChain| chain.get_levels().last())
            else {
                continue;
            };
            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
            let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
            let model: Mat4 = obj.get_transform().to_mat4();
            for tri in indices.iter() {
                let (i0, i1, i2): (usize, usize, usize) =
                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
                let out_01: bool = i0 >= verts.len() || i1 >= verts.len();
                if out_01 || i2 >= verts.len() {
                    continue;
                }
                let w0: Vec3 = model.mul_point3(verts[i0].get_position()).sub(center);
                let w1: Vec3 = model.mul_point3(verts[i1].get_position()).sub(center);
                let w2: Vec3 = model.mul_point3(verts[i2].get_position()).sub(center);
                let p0: (f32, f32, f32) = (
                    w0.dot(right) * inv_span + 0.5,
                    w0.dot(up) * inv_span + 0.5,
                    (depth_max - w0.dot(fwd)) * inv_depth_span,
                );
                let p1: (f32, f32, f32) = (
                    w1.dot(right) * inv_span + 0.5,
                    w1.dot(up) * inv_span + 0.5,
                    (depth_max - w1.dot(fwd)) * inv_depth_span,
                );
                let p2: (f32, f32, f32) = (
                    w2.dot(right) * inv_span + 0.5,
                    w2.dot(up) * inv_span + 0.5,
                    (depth_max - w2.dot(fwd)) * inv_depth_span,
                );
                Self::rasterize_shadow_tri(active_depth.as_mut_slice(), res, [p0, p1, p2]);
            }
        }
    }

    /// Evaluates 4-tap rotated Poisson PCF shadow visibility at `world_pos` if inside this cascade's bounds.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space surface position.
    /// - `Vec3` - Unit outward surface normal for normal-offset acne prevention.
    /// - `Vec3` - Unit vector pointing toward the sun.
    ///
    /// # Returns
    ///
    /// - `Option<f32>` - Visibility in `[VSM_SHADOW_FLOOR, 1.0]`, or `None` if outside this cascade.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn sample_pcf(&self, world_pos: Vec3, normal: Vec3, sun_dir: Vec3) -> Option<f32> {
        if !self.get_static_valid() {
            return None;
        }
        let texel_m: f32 = (self.get_half_extent_m() * 2.0) / (self.get_resolution() as f32);
        let biased_pos: Vec3 = world_pos.add(normal.scale(texel_m * 0.65));
        let (coord_u, coord_v, depth_norm): (f32, f32, f32) = self.project_world_point(biased_pos);
        if !(0.02..=0.98).contains(&coord_u)
            || !(0.02..=0.98).contains(&coord_v)
            || !(0.0..=1.0).contains(&depth_norm)
        {
            return None;
        }
        let res: usize = self.get_resolution();
        let res_f: f32 = res as f32;
        let max_idx: usize = res - 1;
        let n_dot_l: f32 = normal.dot(sun_dir).clamp(0.05, 1.0);
        let slope_bias: f32 = (0.0022 * (1.0 - n_dot_l) + 0.0014).clamp(0.0012, 0.008);
        let cmp_depth: f32 = depth_norm - slope_bias;
        let base_tx: f32 = coord_u * res_f;
        let base_ty: f32 = coord_v * res_f;
        let Self { active_depth, .. } = self;
        let mut lit_taps: f32 = 0.0;
        for &(ox, oy) in VSM_PCF_OFFSETS_4.iter() {
            let tx: usize = ((base_tx + ox).floor().max(0.0) as usize).min(max_idx);
            let ty: usize = ((base_ty + oy).floor().max(0.0) as usize).min(max_idx);
            if cmp_depth <= active_depth[ty * res + tx] {
                lit_taps += 0.25;
            }
        }
        Some(VSM_SHADOW_FLOOR + (1.0 - VSM_SHADOW_FLOOR) * lit_taps)
    }
}

/// Default 2-cascade `VirtualShadowMap`.
impl Default for VirtualShadowMap {
    /// Creates a `VirtualShadowMap` with 256x256 near (`36m`) and far (`120m`) cascades.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready two-cascade virtual shadow map.
    fn default() -> Self {
        Self::with_resolution(VSM_DEFAULT_CASCADE_RES)
    }
}

/// Static page cache management and multi-cascade PCF sampling for `VirtualShadowMap`.
impl VirtualShadowMap {
    /// Constructs a `VirtualShadowMap` with both cascades sized to `resolution x resolution`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Per-cascade shadow map edge resolution in texels (`>= 32`).
    ///
    /// # Returns
    ///
    /// - `Self` - Pre-allocated two-cascade virtual shadow map.
    #[must_use]
    pub fn with_resolution(resolution: usize) -> Self {
        Self {
            cascade_near: VsmCascade::new(resolution, VSM_CASCADE_NEAR_EXTENT_M),
            cascade_far: VsmCascade::new(resolution, VSM_CASCADE_FAR_EXTENT_M),
            cached_sun_dir: Vec3::zero(),
            cached_static_epoch: u64::MAX,
            static_cache_hits: 0,
            static_rebuilds: 0,
        }
    }

    /// Invalidates both static shadow cascades so the next update re-rasterizes static geometry cleanly.
    pub fn invalidate(&mut self) {
        self.get_mut_cascade_near().set_static_valid(false);
        self.get_mut_cascade_far().set_static_valid(false);
    }

    /// Synchronizes both shadow cascades with `world`, reusing cached static shadow pages whenever sun, static epoch, and snapped cascade centers are unchanged.
    ///
    /// # Arguments
    ///
    /// - `&World3D` - Active 3D world supplying camera, sun, objects, and mesh library.
    pub fn update_from_world(&mut self, world: &World3D) {
        let sun_dir: Vec3 = world.get_sun().get_direction().normalize();
        let cam: Camera3D = world.get_camera();
        let focus_near: Vec3 = cam.get_position().add(cam.forward().scale(18.0));
        let focus_far: Vec3 = cam.get_position().add(cam.forward().scale(48.0));
        let static_epoch: u64 = world.get_static_bvh_rebuilds();
        let sun_changed: bool = self.get_cached_sun_dir().dot(sun_dir) < 0.9998;
        let epoch_changed: bool = self.get_cached_static_epoch() != static_epoch;
        let objects: &[SceneObject3D] = world.get_objects().as_slice();
        let mesh_lib: &[MeshLodChain] = world.get_mesh_library().as_slice();
        let mut rebuilt_any: bool = false;
        let mut hit_any: bool = false;
        {
            let near_c: &mut VsmCascade = self.get_mut_cascade_near();
            let (snap_c, r_b, u_b, f_b): (Vec3, Vec3, Vec3, Vec3) =
                near_c.compute_snapped_basis(focus_near, sun_dir);
            let moved: bool = near_c.get_snapped_center().sub(snap_c).length_sq() > 1.0e-3;
            let dirty_light: bool = !near_c.get_static_valid() || sun_changed;
            let dirty_world: bool = epoch_changed || moved;
            if dirty_light || dirty_world {
                near_c.set_snapped_center(snap_c);
                near_c.set_light_right(r_b);
                near_c.set_light_up(u_b);
                near_c.set_light_forward(f_b);
                near_c.rebuild_static_depth(objects, mesh_lib);
                rebuilt_any = true;
            } else {
                hit_any = true;
            }
            near_c.overlay_dynamic_depth(objects, mesh_lib);
        }
        {
            let far_c: &mut VsmCascade = self.get_mut_cascade_far();
            let (snap_c, r_b, u_b, f_b): (Vec3, Vec3, Vec3, Vec3) =
                far_c.compute_snapped_basis(focus_far, sun_dir);
            let moved: bool = far_c.get_snapped_center().sub(snap_c).length_sq() > 1.0e-3;
            let dirty_light: bool = !far_c.get_static_valid() || sun_changed;
            let dirty_world: bool = epoch_changed || moved;
            if dirty_light || dirty_world {
                far_c.set_snapped_center(snap_c);
                far_c.set_light_right(r_b);
                far_c.set_light_up(u_b);
                far_c.set_light_forward(f_b);
                far_c.rebuild_static_depth(objects, mesh_lib);
                rebuilt_any = true;
            } else {
                hit_any = true;
            }
            far_c.overlay_dynamic_depth(objects, mesh_lib);
        }
        self.set_cached_sun_dir(sun_dir);
        self.set_cached_static_epoch(static_epoch);
        if rebuilt_any {
            self.set_static_rebuilds(self.get_static_rebuilds().saturating_add(1));
        } else if hit_any {
            self.set_static_cache_hits(self.get_static_cache_hits().saturating_add(1));
        }
    }

    /// Samples multi-cascade 4-tap PCF shadow visibility at `world_pos`, preferring the high-resolution near cascade and falling back to the far cascade.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space surface position.
    /// - `Vec3` - Unit outward surface normal.
    /// - `Vec3` - Unit directional sun vector.
    ///
    /// # Returns
    ///
    /// - `f32` - Smooth sun visibility in `[0.22, 1.0]` (`1.0` outside both cascades).
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn sample_visibility(&self, world_pos: Vec3, normal: Vec3, sun_dir: Vec3) -> f32 {
        if let Some(near_vis) = self
            .get_cascade_near()
            .sample_pcf(world_pos, normal, sun_dir)
        {
            return near_vis;
        }
        if let Some(far_vis) = self
            .get_cascade_far()
            .sample_pcf(world_pos, normal, sun_dir)
        {
            return far_vis;
        }
        1.0
    }
}