Skip to main content

euv_core/game/engine3d/renderer/
impl.rs

1use super::*;
2
3/// Persistent work-stealing multi-core thread pool for `Engine3dWorkerPool`.
4#[cfg(not(target_arch = "wasm32"))]
5impl Engine3dWorkerPool {
6    /// Creates a warm persistent worker pool sized to host CPU cores (`1..=24` total threads including caller) with extended lock-free spin-before-park dispatch.
7    ///
8    /// # Returns
9    ///
10    /// - `Self` - Initialized worker pool with zero per-frame thread spawn overhead.
11    #[must_use]
12    pub(crate) fn new() -> Self {
13        let total: usize = available_parallelism()
14            .map(usize::from)
15            .unwrap_or(4)
16            .clamp(1, ENGINE3D_WORKER_MAX_THREADS);
17        let requested_workers: usize = total.saturating_sub(1);
18        let mut slots: Vec<Engine3dWorkerSlot> = Vec::with_capacity(requested_workers);
19        for _ in 0..requested_workers {
20            slots.push(Engine3dWorkerSlot::default());
21        }
22        let shared: Arc<Engine3dPoolShared> = Arc::new(Engine3dPoolShared {
23            active_job: AtomicUsize::new(0),
24            active_workers: AtomicUsize::new(0),
25            caller_parked: AlignedAtomicUsize {
26                value: AtomicUsize::new(0),
27            },
28            caller_lock: Mutex::new(()),
29            wake_caller: Condvar::new(),
30            slots,
31        });
32        let mut spawned_count: usize = 0;
33        for idx in 0..requested_workers {
34            let shared_clone: Arc<Engine3dPoolShared> = Arc::clone(&shared);
35            let name: String = format!("{ENGINE3D_WORKER_PREFIX}-{idx}");
36            let spawn_res: io::Result<JoinHandle<()>> =
37                Builder::new().name(name).spawn(move || {
38                    let slot: &Engine3dWorkerSlot = &shared_clone.slots[idx];
39                    let mut seen_epoch: usize = 0;
40                    loop {
41                        let mut spins: u32 = 0;
42                        let job_ptr: usize = loop {
43                            let cur_epoch: usize = slot.epoch.load(Ordering::Acquire);
44                            if cur_epoch != seen_epoch {
45                                let ptr: usize = shared_clone.active_job.load(Ordering::Acquire);
46                                if ptr != 0 {
47                                    seen_epoch = cur_epoch;
48                                    break ptr;
49                                }
50                            }
51                            if spins < ENGINE3D_WORKER_SPIN_LIMIT {
52                                spins += 1;
53                                spin_loop();
54                                continue;
55                            }
56                            let Ok(mut guard) = slot.lock.lock() else {
57                                return;
58                            };
59                            slot.parked.store(1, Ordering::SeqCst);
60                            let parked_ptr: Option<usize> = loop {
61                                let locked_epoch: usize = slot.epoch.load(Ordering::SeqCst);
62                                if locked_epoch != seen_epoch {
63                                    let ptr: usize =
64                                        shared_clone.active_job.load(Ordering::Acquire);
65                                    if ptr != 0 {
66                                        seen_epoch = locked_epoch;
67                                        break Some(ptr);
68                                    }
69                                }
70                                let Ok(next_guard) = slot.wake.wait(guard) else {
71                                    break None;
72                                };
73                                guard = next_guard;
74                            };
75                            slot.parked.store(0, Ordering::SeqCst);
76                            let Some(ptr) = parked_ptr else {
77                                return;
78                            };
79                            break ptr;
80                        };
81                        // SAFETY: Caller keeps `Engine3dJob` pinned on its stack until `workers_done >= active_workers`.
82                        let job: &Engine3dJob = unsafe { &*(job_ptr as *const Engine3dJob) };
83                        run_engine3d_job_loop(job);
84                        let expected: usize = shared_clone.active_workers.load(Ordering::Acquire);
85                        let finished: usize =
86                            job.workers_done.value.fetch_add(1, Ordering::SeqCst) + 1;
87                        if finished >= expected
88                            && shared_clone.caller_parked.value.load(Ordering::SeqCst) != 0
89                        {
90                            let _guard: Result<
91                                MutexGuard<'_, ()>,
92                                PoisonError<MutexGuard<'_, ()>>,
93                            > = shared_clone.caller_lock.lock();
94                            shared_clone.wake_caller.notify_one();
95                        }
96                    }
97                });
98            if spawn_res.is_ok() {
99                spawned_count += 1;
100            } else {
101                break;
102            }
103        }
104        Self {
105            worker_count: spawned_count,
106            dispatch_lock: Mutex::new(()),
107            shared,
108        }
109    }
110}
111
112/// Structure-of-Arrays allocation and disjoint raw pointer helpers for `RtProbeGridSoa`.
113impl RtProbeGridSoa {
114    /// Resizes all 13 SoA probe arrays to `len` elements without reallocating once capacity suffices.
115    ///
116    /// # Arguments
117    ///
118    /// - `&Self` - Mutable SoA probe grid.
119    /// - `usize` - Total probe count `gw * gh`.
120    pub(crate) fn resize(&mut self, len: usize) {
121        let Self {
122            shadow,
123            refl_r,
124            refl_g,
125            refl_b,
126            gi_r,
127            gi_g,
128            gi_b,
129            ao,
130            depth,
131            nx,
132            ny,
133            nz,
134            world_x,
135            world_y,
136            world_z,
137            valid,
138        } = self;
139        if shadow.len() == len {
140            return;
141        }
142        shadow.resize(len, 1.0);
143        refl_r.resize(len, 0.0);
144        refl_g.resize(len, 0.0);
145        refl_b.resize(len, 0.0);
146        gi_r.resize(len, 0.0);
147        gi_g.resize(len, 0.0);
148        gi_b.resize(len, 0.0);
149        ao.resize(len, 1.0);
150        depth.resize(len, 0.0);
151        nx.resize(len, 0.0);
152        ny.resize(len, 1.0);
153        nz.resize(len, 0.0);
154        world_x.resize(len, 0.0);
155        world_y.resize(len, 0.0);
156        world_z.resize(len, 0.0);
157        valid.resize(len, 0);
158    }
159
160    /// Returns whether this SoA probe grid is empty.
161    ///
162    /// # Arguments
163    ///
164    /// - `&Self` - SoA probe grid reference.
165    ///
166    /// # Returns
167    ///
168    /// - `bool` - `true` when zero probes are stored.
169    #[inline(always)]
170    #[must_use]
171    pub(crate) fn is_empty(&self) -> bool {
172        let Self { valid, .. } = self;
173        valid.is_empty()
174    }
175
176    /// Captures base writable addresses for parallel disjoint-tile writes across Barrier 1 workers.
177    ///
178    /// # Arguments
179    ///
180    /// - `&Self` - Mutable SoA probe grid.
181    ///
182    /// # Returns
183    ///
184    /// - `RtProbeGridMutPtrs` - Raw base pointer bundle for disjoint tile writes.
185    #[must_use]
186    pub(crate) fn mut_ptrs(&mut self) -> RtProbeGridMutPtrs {
187        let Self {
188            shadow,
189            refl_r,
190            refl_g,
191            refl_b,
192            gi_r,
193            gi_g,
194            gi_b,
195            ao,
196            depth,
197            nx,
198            ny,
199            nz,
200            world_x,
201            world_y,
202            world_z,
203            valid,
204        } = self;
205        RtProbeGridMutPtrs {
206            shadow: shadow.as_mut_ptr() as usize,
207            refl_r: refl_r.as_mut_ptr() as usize,
208            refl_g: refl_g.as_mut_ptr() as usize,
209            refl_b: refl_b.as_mut_ptr() as usize,
210            gi_r: gi_r.as_mut_ptr() as usize,
211            gi_g: gi_g.as_mut_ptr() as usize,
212            gi_b: gi_b.as_mut_ptr() as usize,
213            ao: ao.as_mut_ptr() as usize,
214            depth: depth.as_mut_ptr() as usize,
215            nx: nx.as_mut_ptr() as usize,
216            ny: ny.as_mut_ptr() as usize,
217            nz: nz.as_mut_ptr() as usize,
218            world_x: world_x.as_mut_ptr() as usize,
219            world_y: world_y.as_mut_ptr() as usize,
220            world_z: world_z.as_mut_ptr() as usize,
221            valid: valid.as_mut_ptr() as usize,
222        }
223    }
224}
225
226/// Disjoint probe writes into `RtProbeGridSoa` via raw base addresses.
227impl RtProbeGridMutPtrs {
228    /// Marks probe `idx` as invalid sky with zeroed radiance.
229    ///
230    /// # Arguments
231    ///
232    /// - `&Self` - Raw pointer bundle.
233    /// - `usize` - Disjoint probe linear index `gy * gw + gx`.
234    #[inline(always)]
235    pub(crate) unsafe fn write_invalid(&self, idx: usize) {
236        let Self { valid, .. } = *self;
237        // SAFETY: Caller guarantees `idx` lies within this tile's strictly disjoint probe rectangle.
238        unsafe {
239            *(valid as *mut u8).add(idx) = 0;
240        }
241    }
242
243    /// Writes a probe's world-space surface position at disjoint index `idx` for next-frame temporal validation.
244    ///
245    /// # Arguments
246    ///
247    /// - `&Self` - Raw pointer bundle.
248    /// - `usize` - Disjoint probe linear index `gy * gw + gx`.
249    /// - `Vec3` - World-space surface position.
250    #[inline(always)]
251    pub(crate) unsafe fn write_world_pos(&self, idx: usize, world_p: Vec3) {
252        let Self {
253            world_x: p_wx,
254            world_y: p_wy,
255            world_z: p_wz,
256            ..
257        } = *self;
258        // SAFETY: Caller guarantees `idx` lies within this tile's strictly disjoint probe rectangle.
259        unsafe {
260            *(p_wx as *mut f32).add(idx) = world_p.get_x();
261            *(p_wy as *mut f32).add(idx) = world_p.get_y();
262            *(p_wz as *mut f32).add(idx) = world_p.get_z();
263        }
264    }
265
266    /// Writes a valid traced probe into all 13 SoA arrays at disjoint index `idx`.
267    ///
268    /// # Arguments
269    ///
270    /// - `&Self` - Raw pointer bundle.
271    /// - `usize` - Disjoint probe linear index `gy * gw + gx`.
272    /// - `(f32, f32, f32)` - Scalar terms `(shadow, ao, depth)`.
273    /// - `(Vec3, Vec3, Vec3)` - Vector terms `(refl, gi, normal)`.
274    #[inline(always)]
275    pub(crate) unsafe fn write_valid(
276        &self,
277        idx: usize,
278        scalars: (f32, f32, f32),
279        vectors: (Vec3, Vec3, Vec3),
280    ) {
281        let Self {
282            shadow: p_shadow,
283            refl_r: p_rr,
284            refl_g: p_rg,
285            refl_b: p_rb,
286            gi_r: p_gr,
287            gi_g: p_gg,
288            gi_b: p_gb,
289            ao: p_ao,
290            depth: p_depth,
291            nx: p_nx,
292            ny: p_ny,
293            nz: p_nz,
294            valid: p_valid,
295            ..
296        } = *self;
297        let (shadow, ao, depth): (f32, f32, f32) = scalars;
298        let (refl, gi, normal): (Vec3, Vec3, Vec3) = vectors;
299        // SAFETY: Caller guarantees `idx` lies within this tile's strictly disjoint probe rectangle.
300        unsafe {
301            *(p_shadow as *mut f32).add(idx) = shadow;
302            *(p_rr as *mut f32).add(idx) = refl.get_x();
303            *(p_rg as *mut f32).add(idx) = refl.get_y();
304            *(p_rb as *mut f32).add(idx) = refl.get_z();
305            *(p_gr as *mut f32).add(idx) = gi.get_x();
306            *(p_gg as *mut f32).add(idx) = gi.get_y();
307            *(p_gb as *mut f32).add(idx) = gi.get_z();
308            *(p_ao as *mut f32).add(idx) = ao;
309            *(p_depth as *mut f32).add(idx) = depth;
310            *(p_nx as *mut f32).add(idx) = normal.get_x();
311            *(p_ny as *mut f32).add(idx) = normal.get_y();
312            *(p_nz as *mut f32).add(idx) = normal.get_z();
313            *(p_valid as *mut u8).add(idx) = 1;
314        }
315    }
316}
317
318/// Zero-initialized constructor helper for fixed-capacity stack `RtProbeRowStack`.
319impl Default for RtProbeRowStack {
320    /// Returns a zeroed L1-resident single-row probe buffer with `valid = 0` across all `PROBE_ROW_STACK_CAP` lanes.
321    ///
322    /// # Returns
323    ///
324    /// - `Self` - Ready stack-allocated probe row buffer.
325    fn default() -> Self {
326        Self {
327            shadow: [1.0; PROBE_ROW_STACK_CAP],
328            refl_r: [0.0; PROBE_ROW_STACK_CAP],
329            refl_g: [0.0; PROBE_ROW_STACK_CAP],
330            refl_b: [0.0; PROBE_ROW_STACK_CAP],
331            gi_r: [0.0; PROBE_ROW_STACK_CAP],
332            gi_g: [0.0; PROBE_ROW_STACK_CAP],
333            gi_b: [0.0; PROBE_ROW_STACK_CAP],
334            ao: [1.0; PROBE_ROW_STACK_CAP],
335            depth: [0.0; PROBE_ROW_STACK_CAP],
336            nx: [0.0; PROBE_ROW_STACK_CAP],
337            ny: [1.0; PROBE_ROW_STACK_CAP],
338            nz: [0.0; PROBE_ROW_STACK_CAP],
339            valid: [0; PROBE_ROW_STACK_CAP],
340        }
341    }
342}
343
344/// Borrowed row view constructor for `RtProbeRowStack`.
345impl RtProbeRowStack {
346    /// Borrows the active `0..gw` prefix of this stack row as a zero-copy `RtProbeRowView`.
347    ///
348    /// # Arguments
349    ///
350    /// - `&Self` - Stack probe row reference.
351    /// - `usize` - Active probe grid width `gw <= 256`.
352    ///
353    /// # Returns
354    ///
355    /// - `RtProbeRowView<'_>` - Zero-copy borrowed SoA row view.
356    #[inline(always)]
357    #[must_use]
358    pub(crate) fn as_view(&self, gw: usize) -> RtProbeRowView<'_> {
359        let Self {
360            shadow,
361            refl_r,
362            refl_g,
363            refl_b,
364            gi_r,
365            gi_g,
366            gi_b,
367            ao,
368            depth,
369            nx,
370            ny,
371            nz,
372            valid,
373        } = self;
374        RtProbeRowView {
375            shadow: &shadow[..gw],
376            refl_r: &refl_r[..gw],
377            refl_g: &refl_g[..gw],
378            refl_b: &refl_b[..gw],
379            gi_r: &gi_r[..gw],
380            gi_g: &gi_g[..gw],
381            gi_b: &gi_b[..gw],
382            ao: &ao[..gw],
383            depth: &depth[..gw],
384            nx: &nx[..gw],
385            ny: &ny[..gw],
386            nz: &nz[..gw],
387            valid: &valid[..gw],
388        }
389    }
390}
391
392/// Default empty per-thread probe row denoise scratch state.
393impl Default for RtProbeRowScratch {
394    /// Creates an empty per-thread 2-row probe denoise scratch cache invalidated at generation `0`.
395    ///
396    /// # Returns
397    ///
398    /// - `Self` - Ready per-thread probe row scratch state.
399    fn default() -> Self {
400        Self {
401            frame_gen: 0,
402            cached_gy_a: usize::MAX,
403            cached_gy_b: usize::MAX,
404            buf_a: RtProbeRowStack::default(),
405            buf_b: RtProbeRowStack::default(),
406        }
407    }
408}
409
410/// 4-corner SIMD bilateral probe cell loader and vectorized 1x/4x upsampler for `CachedProbeCell`.
411impl CachedProbeCell {
412    /// Returns an empty invalid probe cell sentinel.
413    ///
414    /// # Returns
415    ///
416    /// - `Self` - Invalid cell with `vmask == 0`.
417    #[inline(always)]
418    #[must_use]
419    pub(crate) fn empty() -> Self {
420        Self {
421            depth: [0.0; 4],
422            shadow: [0.0; 4],
423            refl_r: [0.0; 4],
424            refl_g: [0.0; 4],
425            refl_b: [0.0; 4],
426            gi_r: [0.0; 4],
427            gi_g: [0.0; 4],
428            gi_b: [0.0; 4],
429            ao: [0.0; 4],
430            tol_scale: [0.0; 4],
431            tol_bias: [0.0; 4],
432            valid_u32: [0; 4],
433            vmask: 0,
434        }
435    }
436
437    /// Loads a single bilinear probe corner `i` into `cell`, returning its bitmask contribution (`1 << i` or `0`).
438    ///
439    /// # Arguments
440    ///
441    /// - `&mut Self` - Destination cell updated in-place.
442    /// - `usize` - Corner lane index `0..4`.
443    /// - `&RtProbeRowView<'_>` - Source probe row.
444    /// - `usize` - Column index `gx`.
445    /// - `(f32, f32, f32)` - Surface normal `(snx, sny, snz)`.
446    /// - `(bool, bool)` - `(do_refl, gi_active)` flags.
447    ///
448    /// # Returns
449    ///
450    /// - `u8` - `1 << i` when corner passes validity and normal agreement, else `0`.
451    #[inline(always)]
452    fn load_corner(
453        cell: &mut Self,
454        item_index: usize,
455        row: &RtProbeRowView<'_>,
456        gx: usize,
457        sn: (f32, f32, f32),
458        flags: (bool, bool),
459    ) -> u8 {
460        if row.valid[gx] != 0 {
461            let (snx, sny, snz): (f32, f32, f32) = sn;
462            let ndot: f32 = snx.mul_add(row.nx[gx], sny.mul_add(row.ny[gx], snz * row.nz[gx]));
463            if ndot >= 0.78 {
464                let (do_refl, gi_active): (bool, bool) = flags;
465                cell.valid_u32[item_index] = u32::MAX;
466                if ndot > 0.95 {
467                    cell.tol_scale[item_index] = 0.58;
468                    cell.tol_bias[item_index] = 2.4;
469                } else {
470                    cell.tol_scale[item_index] = 0.20;
471                    cell.tol_bias[item_index] = 0.75;
472                }
473                cell.depth[item_index] = row.depth[gx];
474                cell.shadow[item_index] = row.shadow[gx];
475                if do_refl {
476                    cell.refl_r[item_index] = row.refl_r[gx];
477                    cell.refl_g[item_index] = row.refl_g[gx];
478                    cell.refl_b[item_index] = row.refl_b[gx];
479                }
480                if gi_active {
481                    cell.gi_r[item_index] = row.gi_r[gx];
482                    cell.gi_g[item_index] = row.gi_g[gx];
483                    cell.gi_b[item_index] = row.gi_b[gx];
484                    cell.ao[item_index] = row.ao[gx];
485                }
486                return 1_u8 << item_index;
487            }
488        }
489        cell.valid_u32[item_index] = 0;
490        0
491    }
492
493    /// Loads and normal-filters the 4 bilinear corner probes `(r0/r1, gx0/gx1)` in-place into `cell` once per `(gx0, gx1, tid)` span without copying or closure calls.
494    ///
495    /// # Arguments
496    ///
497    /// - `&mut Self` - Destination 16-byte-aligned SIMD probe cell updated in-place.
498    /// - `&RtProbeRowView<'_>` - Top probe row `gy0`.
499    /// - `&RtProbeRowView<'_>` - Bottom probe row `gy1`.
500    /// - `(usize, usize)` - Column indices `(gx0, gx1)`.
501    /// - `Vec3` - Pixel unit shading normal.
502    /// - `(bool, bool)` - `(do_refl, gi_active)` flags to skip unneeded channels.
503    #[inline(always)]
504    pub(crate) fn load_into(
505        cell: &mut Self,
506        r0: &RtProbeRowView<'_>,
507        r1: &RtProbeRowView<'_>,
508        gx_pair: (usize, usize),
509        normal: Vec3,
510        flags: (bool, bool),
511    ) {
512        let (gx0, gx1): (usize, usize) = gx_pair;
513        let sn: (f32, f32, f32) = (normal.get_x(), normal.get_y(), normal.get_z());
514        let mut vmask: u8 = Self::load_corner(cell, 0, r0, gx0, sn, flags);
515        vmask |= Self::load_corner(cell, 1, r0, gx1, sn, flags);
516        vmask |= Self::load_corner(cell, 2, r1, gx0, sn, flags);
517        vmask |= Self::load_corner(cell, 3, r1, gx1, sn, flags);
518        cell.vmask = vmask;
519    }
520
521    /// Shifts a cached `(gx, gx+1)` cell one column right in place for `(gx+1, gx+2)`, reusing corners `1 -> 0` and `3 -> 2` and loading only the 2 new right-hand probes.
522    ///
523    /// # Arguments
524    ///
525    /// - `&mut Self` - Cached cell updated in place.
526    /// - `&RtProbeRowView<'_>` - Top probe row `gy0`.
527    /// - `&RtProbeRowView<'_>` - Bottom probe row `gy1`.
528    /// - `usize` - New right-hand column index `gx + 2`.
529    /// - `Vec3` - Pixel unit shading normal.
530    /// - `(bool, bool)` - `(do_refl, gi_active)` flags.
531    #[inline(always)]
532    pub(crate) fn shift_right_in_place(
533        cell: &mut Self,
534        r0: &RtProbeRowView<'_>,
535        r1: &RtProbeRowView<'_>,
536        gx_new: usize,
537        normal: Vec3,
538        flags: (bool, bool),
539    ) {
540        let (do_refl, gi_active): (bool, bool) = flags;
541        cell.valid_u32[0] = cell.valid_u32[1];
542        cell.valid_u32[2] = cell.valid_u32[3];
543        cell.tol_scale[0] = cell.tol_scale[1];
544        cell.tol_scale[2] = cell.tol_scale[3];
545        cell.tol_bias[0] = cell.tol_bias[1];
546        cell.tol_bias[2] = cell.tol_bias[3];
547        cell.depth[0] = cell.depth[1];
548        cell.depth[2] = cell.depth[3];
549        cell.shadow[0] = cell.shadow[1];
550        cell.shadow[2] = cell.shadow[3];
551        if do_refl {
552            cell.refl_r[0] = cell.refl_r[1];
553            cell.refl_r[2] = cell.refl_r[3];
554            cell.refl_g[0] = cell.refl_g[1];
555            cell.refl_g[2] = cell.refl_g[3];
556            cell.refl_b[0] = cell.refl_b[1];
557            cell.refl_b[2] = cell.refl_b[3];
558        }
559        if gi_active {
560            cell.gi_r[0] = cell.gi_r[1];
561            cell.gi_r[2] = cell.gi_r[3];
562            cell.gi_g[0] = cell.gi_g[1];
563            cell.gi_g[2] = cell.gi_g[3];
564            cell.gi_b[0] = cell.gi_b[1];
565            cell.gi_b[2] = cell.gi_b[3];
566            cell.ao[0] = cell.ao[1];
567            cell.ao[2] = cell.ao[3];
568        }
569        let sn: (f32, f32, f32) = (normal.get_x(), normal.get_y(), normal.get_z());
570        let mut vmask: u8 = ((cell.vmask & 2) >> 1) | ((cell.vmask & 8) >> 1);
571        vmask |= Self::load_corner(cell, 1, r0, gx_new, sn, flags);
572        vmask |= Self::load_corner(cell, 3, r1, gx_new, sn, flags);
573        cell.vmask = vmask;
574    }
575
576    /// Evaluates bilateral probe upsampling for 4 horizontal pixels lying within the same cached `(gx0, gx1)` cell, reading depths from `out.depths[off..off+4]` and writing into `out` at `off <= 28`.
577    ///
578    /// # Arguments
579    ///
580    /// - `&Self` - Pre-packed 4-corner probe cell.
581    /// - `[f32; 4]` - Horizontal fractional coordinates `fx` of the 4 pixels.
582    /// - `(f32, f32)` - Vertical bilinear weights `(wy0, wy1)`.
583    /// - `(bool, bool, bool)` - `(check_shadow_edge, do_refl, gi_active)`.
584    /// - `(&mut RunScratch32, usize)` - Destination 32-pixel L1 scratch (containing `depths`) and lane offset `off <= 28`.
585    ///
586    /// # Returns
587    ///
588    /// - `bool` - `true` when all 4 pixels succeeded without requiring edge fallback rays.
589    #[inline(always)]
590    #[must_use]
591    pub(crate) fn sample_4x_same_cell(
592        cell: &Self,
593        fx_4: [f32; 4],
594        wy: (f32, f32),
595        flags: (bool, bool, bool),
596        dst: (&mut RunScratch32, usize),
597    ) -> bool {
598        let vmask: u8 = cell.vmask;
599        if vmask == 0 {
600            return false;
601        }
602        let (out, off): (&mut RunScratch32, usize) = dst;
603        let (wy0, wy1): (f32, f32) = wy;
604        let (check_shadow_edge, do_refl, gi_active): (bool, bool, bool) = flags;
605        #[cfg(target_arch = "aarch64")]
606        {
607            // SAFETY: `off <= 28` guarantees `off + 4 <= 32` inside `RunScratch32`, and NEON `vld1q_f32`/`vst1q_f32` support arbitrary 4-byte-aligned element offsets.
608            unsafe {
609                let zero: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(0.0);
610                let one: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(1.0);
611                let eps: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(1e-4);
612                let d_4: core::arch::aarch64::float32x4_t =
613                    core::arch::aarch64::vld1q_f32(out.depths.as_ptr().add(off));
614                let fx_v: core::arch::aarch64::float32x4_t =
615                    core::arch::aarch64::vld1q_f32(fx_4.as_ptr());
616                let wx0_v: core::arch::aarch64::float32x4_t =
617                    core::arch::aarch64::vsubq_f32(one, fx_v);
618                let wy0_v: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(wy0);
619                let wy1_v: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(wy1);
620                let bw0: core::arch::aarch64::float32x4_t =
621                    core::arch::aarch64::vmulq_f32(wx0_v, wy0_v);
622                let bw1: core::arch::aarch64::float32x4_t =
623                    core::arch::aarch64::vmulq_f32(fx_v, wy0_v);
624                let bw2: core::arch::aarch64::float32x4_t =
625                    core::arch::aarch64::vmulq_f32(wx0_v, wy1_v);
626                let bw3: core::arch::aarch64::float32x4_t =
627                    core::arch::aarch64::vmulq_f32(fx_v, wy1_v);
628                let tol_hi: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
629                    core::arch::aarch64::vdupq_n_f32(2.4),
630                    d_4,
631                    core::arch::aarch64::vdupq_n_f32(0.58),
632                );
633                let inv_tol_hi: core::arch::aarch64::float32x4_t = Renderer3D::neon_rcp_4x(tol_hi);
634                let mut tol_lo_ready: bool = false;
635                let mut tol_lo: core::arch::aarch64::float32x4_t = zero;
636                let mut inv_tol_lo: core::arch::aarch64::float32x4_t = zero;
637                let mut w_sum: core::arch::aarch64::float32x4_t = zero;
638                let mut s_sum: core::arch::aarch64::float32x4_t = zero;
639                let mut s_min: core::arch::aarch64::float32x4_t =
640                    core::arch::aarch64::vdupq_n_f32(2.0);
641                let mut s_max: core::arch::aarch64::float32x4_t =
642                    core::arch::aarch64::vdupq_n_f32(-1.0);
643                let mut rr_sum: core::arch::aarch64::float32x4_t = zero;
644                let mut rg_sum: core::arch::aarch64::float32x4_t = zero;
645                let mut rb_sum: core::arch::aarch64::float32x4_t = zero;
646                let mut gr_sum: core::arch::aarch64::float32x4_t = zero;
647                let mut gg_sum: core::arch::aarch64::float32x4_t = zero;
648                let mut gb_sum: core::arch::aarch64::float32x4_t = zero;
649                let mut ao_sum: core::arch::aarch64::float32x4_t = zero;
650                for char_item in 0..4_usize {
651                    if (vmask & (1_u8 << char_item)) == 0 {
652                        continue;
653                    }
654                    let bw_c: core::arch::aarch64::float32x4_t = match char_item {
655                        0 => bw0,
656                        1 => bw1,
657                        2 => bw2,
658                        _ => bw3,
659                    };
660                    let (tol_c, inv_tol_c): (
661                        core::arch::aarch64::float32x4_t,
662                        core::arch::aarch64::float32x4_t,
663                    ) = if cell.tol_scale[char_item] > 0.4 {
664                        (tol_hi, inv_tol_hi)
665                    } else {
666                        if !tol_lo_ready {
667                            tol_lo = core::arch::aarch64::vfmaq_f32(
668                                core::arch::aarch64::vdupq_n_f32(0.75),
669                                d_4,
670                                core::arch::aarch64::vdupq_n_f32(0.20),
671                            );
672                            inv_tol_lo = Renderer3D::neon_rcp_4x(tol_lo);
673                            tol_lo_ready = true;
674                        }
675                        (tol_lo, inv_tol_lo)
676                    };
677                    let d_diff: core::arch::aarch64::float32x4_t =
678                        core::arch::aarch64::vabsq_f32(core::arch::aarch64::vsubq_f32(
679                            d_4,
680                            core::arch::aarch64::vdupq_n_f32(cell.depth[char_item]),
681                        ));
682                    let in_tol: core::arch::aarch64::uint32x4_t =
683                        core::arch::aarch64::vcleq_f32(d_diff, tol_c);
684                    let wt_raw: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
685                        eps,
686                        bw_c,
687                        core::arch::aarch64::vfmsq_f32(one, d_diff, inv_tol_c),
688                    );
689                    let wt: core::arch::aarch64::float32x4_t =
690                        core::arch::aarch64::vbslq_f32(in_tol, wt_raw, zero);
691                    w_sum = core::arch::aarch64::vaddq_f32(w_sum, wt);
692                    let sh_c: core::arch::aarch64::float32x4_t =
693                        core::arch::aarch64::vdupq_n_f32(cell.shadow[char_item]);
694                    s_sum = core::arch::aarch64::vfmaq_f32(s_sum, wt, sh_c);
695                    if check_shadow_edge {
696                        s_min = core::arch::aarch64::vminq_f32(
697                            s_min,
698                            core::arch::aarch64::vbslq_f32(
699                                in_tol,
700                                sh_c,
701                                core::arch::aarch64::vdupq_n_f32(2.0),
702                            ),
703                        );
704                        s_max = core::arch::aarch64::vmaxq_f32(
705                            s_max,
706                            core::arch::aarch64::vbslq_f32(
707                                in_tol,
708                                sh_c,
709                                core::arch::aarch64::vdupq_n_f32(-1.0),
710                            ),
711                        );
712                    }
713                    if do_refl {
714                        rr_sum = core::arch::aarch64::vfmaq_f32(
715                            rr_sum,
716                            wt,
717                            core::arch::aarch64::vdupq_n_f32(cell.refl_r[char_item]),
718                        );
719                        rg_sum = core::arch::aarch64::vfmaq_f32(
720                            rg_sum,
721                            wt,
722                            core::arch::aarch64::vdupq_n_f32(cell.refl_g[char_item]),
723                        );
724                        rb_sum = core::arch::aarch64::vfmaq_f32(
725                            rb_sum,
726                            wt,
727                            core::arch::aarch64::vdupq_n_f32(cell.refl_b[char_item]),
728                        );
729                    }
730                    if gi_active {
731                        gr_sum = core::arch::aarch64::vfmaq_f32(
732                            gr_sum,
733                            wt,
734                            core::arch::aarch64::vdupq_n_f32(cell.gi_r[char_item]),
735                        );
736                        gg_sum = core::arch::aarch64::vfmaq_f32(
737                            gg_sum,
738                            wt,
739                            core::arch::aarch64::vdupq_n_f32(cell.gi_g[char_item]),
740                        );
741                        gb_sum = core::arch::aarch64::vfmaq_f32(
742                            gb_sum,
743                            wt,
744                            core::arch::aarch64::vdupq_n_f32(cell.gi_b[char_item]),
745                        );
746                        ao_sum = core::arch::aarch64::vfmaq_f32(
747                            ao_sum,
748                            wt,
749                            core::arch::aarch64::vdupq_n_f32(cell.ao[char_item]),
750                        );
751                    }
752                }
753                if core::arch::aarch64::vminvq_f32(w_sum) <= 1e-5 {
754                    return false;
755                }
756                if check_shadow_edge {
757                    let near_m: core::arch::aarch64::uint32x4_t =
758                        core::arch::aarch64::vcltq_f32(d_4, core::arch::aarch64::vdupq_n_f32(42.0));
759                    let edge_m: core::arch::aarch64::uint32x4_t = core::arch::aarch64::vandq_u32(
760                        near_m,
761                        core::arch::aarch64::vcgtq_f32(
762                            core::arch::aarch64::vsubq_f32(s_max, s_min),
763                            core::arch::aarch64::vdupq_n_f32(0.12),
764                        ),
765                    );
766                    if core::arch::aarch64::vmaxvq_u32(edge_m) != 0 {
767                        return false;
768                    }
769                }
770                let inv_ws: core::arch::aarch64::float32x4_t = Renderer3D::neon_rcp_4x(w_sum);
771                core::arch::aarch64::vst1q_f32(
772                    out.shadow.as_mut_ptr().add(off),
773                    core::arch::aarch64::vmulq_f32(s_sum, inv_ws),
774                );
775                if do_refl {
776                    core::arch::aarch64::vst1q_f32(
777                        out.refl_r.as_mut_ptr().add(off),
778                        core::arch::aarch64::vmulq_f32(rr_sum, inv_ws),
779                    );
780                    core::arch::aarch64::vst1q_f32(
781                        out.refl_g.as_mut_ptr().add(off),
782                        core::arch::aarch64::vmulq_f32(rg_sum, inv_ws),
783                    );
784                    core::arch::aarch64::vst1q_f32(
785                        out.refl_b.as_mut_ptr().add(off),
786                        core::arch::aarch64::vmulq_f32(rb_sum, inv_ws),
787                    );
788                }
789                if gi_active {
790                    core::arch::aarch64::vst1q_f32(
791                        out.gi_r.as_mut_ptr().add(off),
792                        core::arch::aarch64::vmulq_f32(gr_sum, inv_ws),
793                    );
794                    core::arch::aarch64::vst1q_f32(
795                        out.gi_g.as_mut_ptr().add(off),
796                        core::arch::aarch64::vmulq_f32(gg_sum, inv_ws),
797                    );
798                    core::arch::aarch64::vst1q_f32(
799                        out.gi_b.as_mut_ptr().add(off),
800                        core::arch::aarch64::vmulq_f32(gb_sum, inv_ws),
801                    );
802                    core::arch::aarch64::vst1q_f32(
803                        out.ao.as_mut_ptr().add(off),
804                        core::arch::aarch64::vmulq_f32(ao_sum, inv_ws),
805                    );
806                }
807            }
808            true
809        }
810        #[cfg(target_arch = "x86_64")]
811        {
812            // SAFETY: `off <= 28` guarantees `off + 4 <= 32` inside `RunScratch32`, and SSE2 is mandatory on `x86_64`.
813            unsafe {
814                let zero: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_setzero_ps();
815                let one: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(1.0);
816                let eps: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(1e-4);
817                let abs_mask: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(-0.0);
818                let d_4: core::arch::x86_64::__m128 =
819                    core::arch::x86_64::_mm_loadu_ps(out.depths.as_ptr().add(off));
820                let fx_v: core::arch::x86_64::__m128 =
821                    core::arch::x86_64::_mm_loadu_ps(fx_4.as_ptr());
822                let wx0_v: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(one, fx_v);
823                let wy0_v: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(wy0);
824                let wy1_v: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(wy1);
825                let bw0: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(wx0_v, wy0_v);
826                let bw1: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(fx_v, wy0_v);
827                let bw2: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(wx0_v, wy1_v);
828                let bw3: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(fx_v, wy1_v);
829                let tol_hi: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
830                    core::arch::x86_64::_mm_mul_ps(d_4, core::arch::x86_64::_mm_set1_ps(0.58)),
831                    core::arch::x86_64::_mm_set1_ps(2.4),
832                );
833                let inv_tol_hi: core::arch::x86_64::__m128 =
834                    core::arch::x86_64::_mm_div_ps(one, tol_hi);
835                let mut tol_lo_ready: bool = false;
836                let mut tol_lo: core::arch::x86_64::__m128 = zero;
837                let mut inv_tol_lo: core::arch::x86_64::__m128 = zero;
838                let mut w_sum: core::arch::x86_64::__m128 = zero;
839                let mut s_sum: core::arch::x86_64::__m128 = zero;
840                let mut s_min: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(2.0);
841                let mut s_max: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(-1.0);
842                let mut rr_sum: core::arch::x86_64::__m128 = zero;
843                let mut rg_sum: core::arch::x86_64::__m128 = zero;
844                let mut rb_sum: core::arch::x86_64::__m128 = zero;
845                let mut gr_sum: core::arch::x86_64::__m128 = zero;
846                let mut gg_sum: core::arch::x86_64::__m128 = zero;
847                let mut gb_sum: core::arch::x86_64::__m128 = zero;
848                let mut ao_sum: core::arch::x86_64::__m128 = zero;
849                for color_item in 0..4_usize {
850                    if (vmask & (1_u8 << color_item)) == 0 {
851                        continue;
852                    }
853                    let bw_c: core::arch::x86_64::__m128 = match color_item {
854                        0 => bw0,
855                        1 => bw1,
856                        2 => bw2,
857                        _ => bw3,
858                    };
859                    let (tol_c, inv_tol_c): (
860                        core::arch::x86_64::__m128,
861                        core::arch::x86_64::__m128,
862                    ) = if cell.tol_scale[color_item] > 0.4 {
863                        (tol_hi, inv_tol_hi)
864                    } else {
865                        if !tol_lo_ready {
866                            tol_lo = core::arch::x86_64::_mm_add_ps(
867                                core::arch::x86_64::_mm_mul_ps(
868                                    d_4,
869                                    core::arch::x86_64::_mm_set1_ps(0.20),
870                                ),
871                                core::arch::x86_64::_mm_set1_ps(0.75),
872                            );
873                            inv_tol_lo = core::arch::x86_64::_mm_div_ps(one, tol_lo);
874                            tol_lo_ready = true;
875                        }
876                        (tol_lo, inv_tol_lo)
877                    };
878                    let d_diff: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_andnot_ps(
879                        abs_mask,
880                        core::arch::x86_64::_mm_sub_ps(
881                            d_4,
882                            core::arch::x86_64::_mm_set1_ps(cell.depth[color_item]),
883                        ),
884                    );
885                    let in_tol: core::arch::x86_64::__m128 =
886                        core::arch::x86_64::_mm_cmple_ps(d_diff, tol_c);
887                    let wt_raw: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
888                        eps,
889                        core::arch::x86_64::_mm_mul_ps(
890                            bw_c,
891                            core::arch::x86_64::_mm_sub_ps(
892                                one,
893                                core::arch::x86_64::_mm_mul_ps(d_diff, inv_tol_c),
894                            ),
895                        ),
896                    );
897                    let wt: core::arch::x86_64::__m128 =
898                        core::arch::x86_64::_mm_and_ps(in_tol, wt_raw);
899                    w_sum = core::arch::x86_64::_mm_add_ps(w_sum, wt);
900                    let sh_c: core::arch::x86_64::__m128 =
901                        core::arch::x86_64::_mm_set1_ps(cell.shadow[color_item]);
902                    s_sum = core::arch::x86_64::_mm_add_ps(
903                        s_sum,
904                        core::arch::x86_64::_mm_mul_ps(wt, sh_c),
905                    );
906                    if check_shadow_edge {
907                        let sh_min_cand: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_or_ps(
908                            core::arch::x86_64::_mm_and_ps(in_tol, sh_c),
909                            core::arch::x86_64::_mm_andnot_ps(
910                                in_tol,
911                                core::arch::x86_64::_mm_set1_ps(2.0),
912                            ),
913                        );
914                        let sh_max_cand: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_or_ps(
915                            core::arch::x86_64::_mm_and_ps(in_tol, sh_c),
916                            core::arch::x86_64::_mm_andnot_ps(
917                                in_tol,
918                                core::arch::x86_64::_mm_set1_ps(-1.0),
919                            ),
920                        );
921                        s_min = core::arch::x86_64::_mm_min_ps(s_min, sh_min_cand);
922                        s_max = core::arch::x86_64::_mm_max_ps(s_max, sh_max_cand);
923                    }
924                    if do_refl {
925                        rr_sum = core::arch::x86_64::_mm_add_ps(
926                            rr_sum,
927                            core::arch::x86_64::_mm_mul_ps(
928                                wt,
929                                core::arch::x86_64::_mm_set1_ps(cell.refl_r[color_item]),
930                            ),
931                        );
932                        rg_sum = core::arch::x86_64::_mm_add_ps(
933                            rg_sum,
934                            core::arch::x86_64::_mm_mul_ps(
935                                wt,
936                                core::arch::x86_64::_mm_set1_ps(cell.refl_g[color_item]),
937                            ),
938                        );
939                        rb_sum = core::arch::x86_64::_mm_add_ps(
940                            rb_sum,
941                            core::arch::x86_64::_mm_mul_ps(
942                                wt,
943                                core::arch::x86_64::_mm_set1_ps(cell.refl_b[color_item]),
944                            ),
945                        );
946                    }
947                    if gi_active {
948                        gr_sum = core::arch::x86_64::_mm_add_ps(
949                            gr_sum,
950                            core::arch::x86_64::_mm_mul_ps(
951                                wt,
952                                core::arch::x86_64::_mm_set1_ps(cell.gi_r[color_item]),
953                            ),
954                        );
955                        gg_sum = core::arch::x86_64::_mm_add_ps(
956                            gg_sum,
957                            core::arch::x86_64::_mm_mul_ps(
958                                wt,
959                                core::arch::x86_64::_mm_set1_ps(cell.gi_g[color_item]),
960                            ),
961                        );
962                        gb_sum = core::arch::x86_64::_mm_add_ps(
963                            gb_sum,
964                            core::arch::x86_64::_mm_mul_ps(
965                                wt,
966                                core::arch::x86_64::_mm_set1_ps(cell.gi_b[color_item]),
967                            ),
968                        );
969                        ao_sum = core::arch::x86_64::_mm_add_ps(
970                            ao_sum,
971                            core::arch::x86_64::_mm_mul_ps(
972                                wt,
973                                core::arch::x86_64::_mm_set1_ps(cell.ao[color_item]),
974                            ),
975                        );
976                    }
977                }
978                if core::arch::x86_64::_mm_movemask_ps(core::arch::x86_64::_mm_cmple_ps(
979                    w_sum,
980                    core::arch::x86_64::_mm_set1_ps(1e-5),
981                )) != 0
982                {
983                    return false;
984                }
985                if check_shadow_edge {
986                    let near_m: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_cmplt_ps(
987                        d_4,
988                        core::arch::x86_64::_mm_set1_ps(42.0),
989                    );
990                    let edge_m: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_and_ps(
991                        near_m,
992                        core::arch::x86_64::_mm_cmpgt_ps(
993                            core::arch::x86_64::_mm_sub_ps(s_max, s_min),
994                            core::arch::x86_64::_mm_set1_ps(0.12),
995                        ),
996                    );
997                    if core::arch::x86_64::_mm_movemask_ps(edge_m) != 0 {
998                        return false;
999                    }
1000                }
1001                let inv_ws: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_div_ps(one, w_sum);
1002                core::arch::x86_64::_mm_storeu_ps(
1003                    out.shadow.as_mut_ptr().add(off),
1004                    core::arch::x86_64::_mm_mul_ps(s_sum, inv_ws),
1005                );
1006                if do_refl {
1007                    core::arch::x86_64::_mm_storeu_ps(
1008                        out.refl_r.as_mut_ptr().add(off),
1009                        core::arch::x86_64::_mm_mul_ps(rr_sum, inv_ws),
1010                    );
1011                    core::arch::x86_64::_mm_storeu_ps(
1012                        out.refl_g.as_mut_ptr().add(off),
1013                        core::arch::x86_64::_mm_mul_ps(rg_sum, inv_ws),
1014                    );
1015                    core::arch::x86_64::_mm_storeu_ps(
1016                        out.refl_b.as_mut_ptr().add(off),
1017                        core::arch::x86_64::_mm_mul_ps(rb_sum, inv_ws),
1018                    );
1019                }
1020                if gi_active {
1021                    core::arch::x86_64::_mm_storeu_ps(
1022                        out.gi_r.as_mut_ptr().add(off),
1023                        core::arch::x86_64::_mm_mul_ps(gr_sum, inv_ws),
1024                    );
1025                    core::arch::x86_64::_mm_storeu_ps(
1026                        out.gi_g.as_mut_ptr().add(off),
1027                        core::arch::x86_64::_mm_mul_ps(gg_sum, inv_ws),
1028                    );
1029                    core::arch::x86_64::_mm_storeu_ps(
1030                        out.gi_b.as_mut_ptr().add(off),
1031                        core::arch::x86_64::_mm_mul_ps(gb_sum, inv_ws),
1032                    );
1033                    core::arch::x86_64::_mm_storeu_ps(
1034                        out.ao.as_mut_ptr().add(off),
1035                        core::arch::x86_64::_mm_mul_ps(ao_sum, inv_ws),
1036                    );
1037                }
1038            }
1039            true
1040        }
1041        #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
1042        {
1043            // SAFETY: `off <= 28` guarantees `off + 4 <= 32` inside `RunScratch32`; `simd128` is enabled on `wasm32`.
1044            unsafe {
1045                let zero: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(0.0);
1046                let one: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(1.0);
1047                let eps: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(1e-4);
1048                let d_4: core::arch::wasm32::v128 =
1049                    core::arch::wasm32::v128_load(out.depths.as_ptr().add(off).cast());
1050                let fx_v: core::arch::wasm32::v128 =
1051                    core::arch::wasm32::v128_load(fx_4.as_ptr().cast());
1052                let wx0_v: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(one, fx_v);
1053                let wy0_v: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(wy0);
1054                let wy1_v: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(wy1);
1055                let bw0: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(wx0_v, wy0_v);
1056                let bw1: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(fx_v, wy0_v);
1057                let bw2: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(wx0_v, wy1_v);
1058                let bw3: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(fx_v, wy1_v);
1059                let tol_hi: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
1060                    core::arch::wasm32::f32x4_mul(d_4, core::arch::wasm32::f32x4_splat(0.58)),
1061                    core::arch::wasm32::f32x4_splat(2.4),
1062                );
1063                let inv_tol_hi: core::arch::wasm32::v128 =
1064                    core::arch::wasm32::f32x4_div(one, tol_hi);
1065                let mut tol_lo_ready: bool = false;
1066                let mut tol_lo: core::arch::wasm32::v128 = zero;
1067                let mut inv_tol_lo: core::arch::wasm32::v128 = zero;
1068                let mut w_sum: core::arch::wasm32::v128 = zero;
1069                let mut s_sum: core::arch::wasm32::v128 = zero;
1070                let mut s_min: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(2.0);
1071                let mut s_max: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(-1.0);
1072                let mut rr_sum: core::arch::wasm32::v128 = zero;
1073                let mut rg_sum: core::arch::wasm32::v128 = zero;
1074                let mut rb_sum: core::arch::wasm32::v128 = zero;
1075                let mut gr_sum: core::arch::wasm32::v128 = zero;
1076                let mut gg_sum: core::arch::wasm32::v128 = zero;
1077                let mut gb_sum: core::arch::wasm32::v128 = zero;
1078                let mut ao_sum: core::arch::wasm32::v128 = zero;
1079                for cell_item in 0..4_usize {
1080                    if (vmask & (1_u8 << cell_item)) == 0 {
1081                        continue;
1082                    }
1083                    let bw_c: core::arch::wasm32::v128 = match cell_item {
1084                        0 => bw0,
1085                        1 => bw1,
1086                        2 => bw2,
1087                        _ => bw3,
1088                    };
1089                    let (tol_c, inv_tol_c): (core::arch::wasm32::v128, core::arch::wasm32::v128) =
1090                        if cell.tol_scale[cell_item] > 0.4 {
1091                            (tol_hi, inv_tol_hi)
1092                        } else {
1093                            if !tol_lo_ready {
1094                                tol_lo = core::arch::wasm32::f32x4_add(
1095                                    core::arch::wasm32::f32x4_mul(
1096                                        d_4,
1097                                        core::arch::wasm32::f32x4_splat(0.20),
1098                                    ),
1099                                    core::arch::wasm32::f32x4_splat(0.75),
1100                                );
1101                                inv_tol_lo = core::arch::wasm32::f32x4_div(one, tol_lo);
1102                                tol_lo_ready = true;
1103                            }
1104                            (tol_lo, inv_tol_lo)
1105                        };
1106                    let d_diff: core::arch::wasm32::v128 =
1107                        core::arch::wasm32::f32x4_abs(core::arch::wasm32::f32x4_sub(
1108                            d_4,
1109                            core::arch::wasm32::f32x4_splat(cell.depth[cell_item]),
1110                        ));
1111                    let in_tol: core::arch::wasm32::v128 =
1112                        core::arch::wasm32::f32x4_le(d_diff, tol_c);
1113                    let wt_raw: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
1114                        eps,
1115                        core::arch::wasm32::f32x4_mul(
1116                            bw_c,
1117                            core::arch::wasm32::f32x4_sub(
1118                                one,
1119                                core::arch::wasm32::f32x4_mul(d_diff, inv_tol_c),
1120                            ),
1121                        ),
1122                    );
1123                    let wt: core::arch::wasm32::v128 = core::arch::wasm32::v128_and(in_tol, wt_raw);
1124                    w_sum = core::arch::wasm32::f32x4_add(w_sum, wt);
1125                    let sh_c: core::arch::wasm32::v128 =
1126                        core::arch::wasm32::f32x4_splat(cell.shadow[cell_item]);
1127                    s_sum = core::arch::wasm32::f32x4_add(
1128                        s_sum,
1129                        core::arch::wasm32::f32x4_mul(wt, sh_c),
1130                    );
1131                    if check_shadow_edge {
1132                        s_min = core::arch::wasm32::f32x4_pmin(
1133                            s_min,
1134                            core::arch::wasm32::v128_bitselect(
1135                                sh_c,
1136                                core::arch::wasm32::f32x4_splat(2.0),
1137                                in_tol,
1138                            ),
1139                        );
1140                        s_max = core::arch::wasm32::f32x4_pmax(
1141                            s_max,
1142                            core::arch::wasm32::v128_bitselect(
1143                                sh_c,
1144                                core::arch::wasm32::f32x4_splat(-1.0),
1145                                in_tol,
1146                            ),
1147                        );
1148                    }
1149                    if do_refl {
1150                        rr_sum = core::arch::wasm32::f32x4_add(
1151                            rr_sum,
1152                            core::arch::wasm32::f32x4_mul(
1153                                wt,
1154                                core::arch::wasm32::f32x4_splat(cell.refl_r[cell_item]),
1155                            ),
1156                        );
1157                        rg_sum = core::arch::wasm32::f32x4_add(
1158                            rg_sum,
1159                            core::arch::wasm32::f32x4_mul(
1160                                wt,
1161                                core::arch::wasm32::f32x4_splat(cell.refl_g[cell_item]),
1162                            ),
1163                        );
1164                        rb_sum = core::arch::wasm32::f32x4_add(
1165                            rb_sum,
1166                            core::arch::wasm32::f32x4_mul(
1167                                wt,
1168                                core::arch::wasm32::f32x4_splat(cell.refl_b[cell_item]),
1169                            ),
1170                        );
1171                    }
1172                    if gi_active {
1173                        gr_sum = core::arch::wasm32::f32x4_add(
1174                            gr_sum,
1175                            core::arch::wasm32::f32x4_mul(
1176                                wt,
1177                                core::arch::wasm32::f32x4_splat(cell.gi_r[cell_item]),
1178                            ),
1179                        );
1180                        gg_sum = core::arch::wasm32::f32x4_add(
1181                            gg_sum,
1182                            core::arch::wasm32::f32x4_mul(
1183                                wt,
1184                                core::arch::wasm32::f32x4_splat(cell.gi_g[cell_item]),
1185                            ),
1186                        );
1187                        gb_sum = core::arch::wasm32::f32x4_add(
1188                            gb_sum,
1189                            core::arch::wasm32::f32x4_mul(
1190                                wt,
1191                                core::arch::wasm32::f32x4_splat(cell.gi_b[cell_item]),
1192                            ),
1193                        );
1194                        ao_sum = core::arch::wasm32::f32x4_add(
1195                            ao_sum,
1196                            core::arch::wasm32::f32x4_mul(
1197                                wt,
1198                                core::arch::wasm32::f32x4_splat(cell.ao[cell_item]),
1199                            ),
1200                        );
1201                    }
1202                }
1203                if core::arch::wasm32::i32x4_bitmask(core::arch::wasm32::f32x4_le(
1204                    w_sum,
1205                    core::arch::wasm32::f32x4_splat(1e-5),
1206                )) != 0
1207                {
1208                    return false;
1209                }
1210                if check_shadow_edge {
1211                    let near_m: core::arch::wasm32::v128 =
1212                        core::arch::wasm32::f32x4_lt(d_4, core::arch::wasm32::f32x4_splat(18.0));
1213                    let edge_m: core::arch::wasm32::v128 = core::arch::wasm32::v128_and(
1214                        near_m,
1215                        core::arch::wasm32::f32x4_gt(
1216                            core::arch::wasm32::f32x4_sub(s_max, s_min),
1217                            core::arch::wasm32::f32x4_splat(0.12),
1218                        ),
1219                    );
1220                    if core::arch::wasm32::v128_any_true(edge_m) {
1221                        return false;
1222                    }
1223                }
1224                let inv_ws: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_div(one, w_sum);
1225                core::arch::wasm32::v128_store(
1226                    out.shadow.as_mut_ptr().add(off).cast(),
1227                    core::arch::wasm32::f32x4_mul(s_sum, inv_ws),
1228                );
1229                if do_refl {
1230                    core::arch::wasm32::v128_store(
1231                        out.refl_r.as_mut_ptr().add(off).cast(),
1232                        core::arch::wasm32::f32x4_mul(rr_sum, inv_ws),
1233                    );
1234                    core::arch::wasm32::v128_store(
1235                        out.refl_g.as_mut_ptr().add(off).cast(),
1236                        core::arch::wasm32::f32x4_mul(rg_sum, inv_ws),
1237                    );
1238                    core::arch::wasm32::v128_store(
1239                        out.refl_b.as_mut_ptr().add(off).cast(),
1240                        core::arch::wasm32::f32x4_mul(rb_sum, inv_ws),
1241                    );
1242                }
1243                if gi_active {
1244                    core::arch::wasm32::v128_store(
1245                        out.gi_r.as_mut_ptr().add(off).cast(),
1246                        core::arch::wasm32::f32x4_mul(gr_sum, inv_ws),
1247                    );
1248                    core::arch::wasm32::v128_store(
1249                        out.gi_g.as_mut_ptr().add(off).cast(),
1250                        core::arch::wasm32::f32x4_mul(gg_sum, inv_ws),
1251                    );
1252                    core::arch::wasm32::v128_store(
1253                        out.gi_b.as_mut_ptr().add(off).cast(),
1254                        core::arch::wasm32::f32x4_mul(gb_sum, inv_ws),
1255                    );
1256                    core::arch::wasm32::v128_store(
1257                        out.ao.as_mut_ptr().add(off).cast(),
1258                        core::arch::wasm32::f32x4_mul(ao_sum, inv_ws),
1259                    );
1260                }
1261            }
1262            true
1263        }
1264        #[cfg(not(target_arch = "aarch64"))]
1265        #[cfg(not(target_arch = "x86_64"))]
1266        #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
1267        {
1268            for (lane, &fx) in fx_4.iter().enumerate() {
1269                let dst_i: usize = off + lane;
1270                let depth_l: f32 = out.depths[dst_i];
1271                let wx0: f32 = 1.0 - fx;
1272                let bws: [f32; 4] = [wx0 * wy0, fx * wy0, wx0 * wy1, fx * wy1];
1273                let (vm, sh, s_min, s_max, rf, gi, ao): (u32, f32, f32, f32, Vec3, Vec3, f32) =
1274                    Self::sample_1x(cell, bws, depth_l, (do_refl, gi_active));
1275                let edge_max_d: f32 = if cfg!(target_arch = "wasm32") {
1276                    18.0
1277                } else {
1278                    42.0
1279                };
1280                if vm == 0 || (check_shadow_edge && depth_l < edge_max_d && (s_max - s_min) > 0.12)
1281                {
1282                    return false;
1283                }
1284                out.shadow[dst_i] = sh;
1285                if do_refl {
1286                    out.refl_r[dst_i] = rf.get_x();
1287                    out.refl_g[dst_i] = rf.get_y();
1288                    out.refl_b[dst_i] = rf.get_z();
1289                }
1290                if gi_active {
1291                    out.gi_r[dst_i] = gi.get_x();
1292                    out.gi_g[dst_i] = gi.get_y();
1293                    out.gi_b[dst_i] = gi.get_z();
1294                    out.ao[dst_i] = ao;
1295                }
1296            }
1297            true
1298        }
1299    }
1300
1301    /// Evaluates bilateral probe upsampling for a single pixel against a cached 4-corner SIMD cell.
1302    ///
1303    /// # Arguments
1304    ///
1305    /// - `&Self` - Pre-packed 4-corner probe cell.
1306    /// - `[f32; 4]` - Bilinear corner weights `[w00, w10, w01, w11]`.
1307    /// - `f32` - Pixel linear depth.
1308    /// - `(bool, bool)` - `(do_refl, gi_active)` flags.
1309    ///
1310    /// # Returns
1311    ///
1312    /// - `(u32, f32, f32, f32, Vec3, Vec3, f32)` - `(valid_matches, shadow, s_min, s_max, refl, gi, ao)`.
1313    #[inline(always)]
1314    #[must_use]
1315    pub(crate) fn sample_1x(
1316        cell: &Self,
1317        bws: [f32; 4],
1318        depth: f32,
1319        flags: (bool, bool),
1320    ) -> (u32, f32, f32, f32, Vec3, Vec3, f32) {
1321        if cell.vmask == 0 {
1322            return (0, 1.0, 2.0, -1.0, Vec3::zero(), Vec3::zero(), 1.0);
1323        }
1324        let (do_refl, gi_active): (bool, bool) = flags;
1325        #[cfg(target_arch = "aarch64")]
1326        {
1327            // SAFETY: `CachedProbeCell` arrays are 16-byte aligned; NEON is mandatory on `aarch64`.
1328            unsafe {
1329                let d_v: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(depth);
1330                let c_depth: core::arch::aarch64::float32x4_t =
1331                    core::arch::aarch64::vld1q_f32(cell.depth.as_ptr());
1332                let c_tscale: core::arch::aarch64::float32x4_t =
1333                    core::arch::aarch64::vld1q_f32(cell.tol_scale.as_ptr());
1334                let c_tbias: core::arch::aarch64::float32x4_t =
1335                    core::arch::aarch64::vld1q_f32(cell.tol_bias.as_ptr());
1336                let c_vbits: core::arch::aarch64::uint32x4_t =
1337                    core::arch::aarch64::vld1q_u32(cell.valid_u32.as_ptr());
1338                let d_diff: core::arch::aarch64::float32x4_t =
1339                    core::arch::aarch64::vabsq_f32(core::arch::aarch64::vsubq_f32(d_v, c_depth));
1340                let tol: core::arch::aarch64::float32x4_t =
1341                    core::arch::aarch64::vfmaq_f32(c_tbias, d_v, c_tscale);
1342                let in_tol: core::arch::aarch64::uint32x4_t = core::arch::aarch64::vandq_u32(
1343                    c_vbits,
1344                    core::arch::aarch64::vcleq_f32(d_diff, tol),
1345                );
1346                let one: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(1.0);
1347                let zero: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(0.0);
1348                let bws_v: core::arch::aarch64::float32x4_t =
1349                    core::arch::aarch64::vld1q_f32(bws.as_ptr());
1350                let inv_tol: core::arch::aarch64::float32x4_t = Renderer3D::neon_rcp_4x(tol);
1351                let wt_raw: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
1352                    core::arch::aarch64::vdupq_n_f32(1e-4),
1353                    bws_v,
1354                    core::arch::aarch64::vfmsq_f32(one, d_diff, inv_tol),
1355                );
1356                let wt: core::arch::aarch64::float32x4_t =
1357                    core::arch::aarch64::vbslq_f32(in_tol, wt_raw, zero);
1358                let w_sum: f32 = core::arch::aarch64::vaddvq_f32(wt);
1359                if w_sum <= 1e-5 {
1360                    return (0, 1.0, 2.0, -1.0, Vec3::zero(), Vec3::zero(), 1.0);
1361                }
1362                let inv_ws: f32 = 1.0 / w_sum;
1363                let c_shadow: core::arch::aarch64::float32x4_t =
1364                    core::arch::aarch64::vld1q_f32(cell.shadow.as_ptr());
1365                let sh: f32 =
1366                    core::arch::aarch64::vaddvq_f32(core::arch::aarch64::vmulq_f32(wt, c_shadow))
1367                        * inv_ws;
1368                let (s_min, s_max): (f32, f32) = if gi_active {
1369                    (sh, sh)
1370                } else {
1371                    (
1372                        core::arch::aarch64::vminvq_f32(core::arch::aarch64::vbslq_f32(
1373                            in_tol,
1374                            c_shadow,
1375                            core::arch::aarch64::vdupq_n_f32(2.0),
1376                        )),
1377                        core::arch::aarch64::vmaxvq_f32(core::arch::aarch64::vbslq_f32(
1378                            in_tol,
1379                            c_shadow,
1380                            core::arch::aarch64::vdupq_n_f32(-1.0),
1381                        )),
1382                    )
1383                };
1384                let refl: Vec3 = if do_refl {
1385                    let rr: f32 = core::arch::aarch64::vaddvq_f32(core::arch::aarch64::vmulq_f32(
1386                        wt,
1387                        core::arch::aarch64::vld1q_f32(cell.refl_r.as_ptr()),
1388                    )) * inv_ws;
1389                    let rg: f32 = core::arch::aarch64::vaddvq_f32(core::arch::aarch64::vmulq_f32(
1390                        wt,
1391                        core::arch::aarch64::vld1q_f32(cell.refl_g.as_ptr()),
1392                    )) * inv_ws;
1393                    let rb: f32 = core::arch::aarch64::vaddvq_f32(core::arch::aarch64::vmulq_f32(
1394                        wt,
1395                        core::arch::aarch64::vld1q_f32(cell.refl_b.as_ptr()),
1396                    )) * inv_ws;
1397                    Vec3::new(rr, rg, rb)
1398                } else {
1399                    Vec3::zero()
1400                };
1401                let (gi, ao): (Vec3, f32) = if gi_active {
1402                    let gr: f32 = core::arch::aarch64::vaddvq_f32(core::arch::aarch64::vmulq_f32(
1403                        wt,
1404                        core::arch::aarch64::vld1q_f32(cell.gi_r.as_ptr()),
1405                    )) * inv_ws;
1406                    let gg: f32 = core::arch::aarch64::vaddvq_f32(core::arch::aarch64::vmulq_f32(
1407                        wt,
1408                        core::arch::aarch64::vld1q_f32(cell.gi_g.as_ptr()),
1409                    )) * inv_ws;
1410                    let gb: f32 = core::arch::aarch64::vaddvq_f32(core::arch::aarch64::vmulq_f32(
1411                        wt,
1412                        core::arch::aarch64::vld1q_f32(cell.gi_b.as_ptr()),
1413                    )) * inv_ws;
1414                    let ao_v: f32 =
1415                        core::arch::aarch64::vaddvq_f32(core::arch::aarch64::vmulq_f32(
1416                            wt,
1417                            core::arch::aarch64::vld1q_f32(cell.ao.as_ptr()),
1418                        )) * inv_ws;
1419                    (Vec3::new(gr, gg, gb), ao_v)
1420                } else {
1421                    (Vec3::zero(), 1.0)
1422                };
1423                (1, sh, s_min, s_max, refl, gi, ao)
1424            }
1425        }
1426        #[cfg(target_arch = "x86_64")]
1427        {
1428            // SAFETY: `CachedProbeCell` arrays are 16-byte aligned; SSE2 is mandatory on `x86_64`.
1429            unsafe {
1430                let d_v: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(depth);
1431                let c_depth: core::arch::x86_64::__m128 =
1432                    core::arch::x86_64::_mm_load_ps(cell.depth.as_ptr());
1433                let c_tscale: core::arch::x86_64::__m128 =
1434                    core::arch::x86_64::_mm_load_ps(cell.tol_scale.as_ptr());
1435                let c_tbias: core::arch::x86_64::__m128 =
1436                    core::arch::x86_64::_mm_load_ps(cell.tol_bias.as_ptr());
1437                let c_vbits: core::arch::x86_64::__m128 =
1438                    core::arch::x86_64::_mm_castsi128_ps(core::arch::x86_64::_mm_load_si128(
1439                        cell.valid_u32
1440                            .as_ptr()
1441                            .cast::<core::arch::x86_64::__m128i>(),
1442                    ));
1443                let abs_mask: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(-0.0);
1444                let d_diff: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_andnot_ps(
1445                    abs_mask,
1446                    core::arch::x86_64::_mm_sub_ps(d_v, c_depth),
1447                );
1448                let tol: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
1449                    c_tbias,
1450                    core::arch::x86_64::_mm_mul_ps(d_v, c_tscale),
1451                );
1452                let in_tol: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_and_ps(
1453                    c_vbits,
1454                    core::arch::x86_64::_mm_cmple_ps(d_diff, tol),
1455                );
1456                let one: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(1.0);
1457                let bws_v: core::arch::x86_64::__m128 =
1458                    core::arch::x86_64::_mm_loadu_ps(bws.as_ptr());
1459                let wt_raw: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
1460                    core::arch::x86_64::_mm_set1_ps(1e-4),
1461                    core::arch::x86_64::_mm_mul_ps(
1462                        bws_v,
1463                        core::arch::x86_64::_mm_sub_ps(
1464                            one,
1465                            core::arch::x86_64::_mm_div_ps(d_diff, tol),
1466                        ),
1467                    ),
1468                );
1469                let wt: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_and_ps(in_tol, wt_raw);
1470                let w_sum: f32 = Renderer3D::sse_hsum_4x(wt);
1471                if w_sum <= 1e-5 {
1472                    return (0, 1.0, 2.0, -1.0, Vec3::zero(), Vec3::zero(), 1.0);
1473                }
1474                let inv_ws: f32 = 1.0 / w_sum;
1475                let c_shadow: core::arch::x86_64::__m128 =
1476                    core::arch::x86_64::_mm_load_ps(cell.shadow.as_ptr());
1477                let sh: f32 =
1478                    Renderer3D::sse_hsum_4x(core::arch::x86_64::_mm_mul_ps(wt, c_shadow)) * inv_ws;
1479                let (s_min, s_max): (f32, f32) = if gi_active {
1480                    (sh, sh)
1481                } else {
1482                    let s_min_v: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_or_ps(
1483                        core::arch::x86_64::_mm_and_ps(in_tol, c_shadow),
1484                        core::arch::x86_64::_mm_andnot_ps(
1485                            in_tol,
1486                            core::arch::x86_64::_mm_set1_ps(2.0),
1487                        ),
1488                    );
1489                    let s_max_v: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_or_ps(
1490                        core::arch::x86_64::_mm_and_ps(in_tol, c_shadow),
1491                        core::arch::x86_64::_mm_andnot_ps(
1492                            in_tol,
1493                            core::arch::x86_64::_mm_set1_ps(-1.0),
1494                        ),
1495                    );
1496                    (
1497                        Renderer3D::sse_hmin_4x(s_min_v),
1498                        Renderer3D::sse_hmax_4x(s_max_v),
1499                    )
1500                };
1501                let refl: Vec3 = if do_refl {
1502                    let rr: f32 = Renderer3D::sse_hsum_4x(core::arch::x86_64::_mm_mul_ps(
1503                        wt,
1504                        core::arch::x86_64::_mm_load_ps(cell.refl_r.as_ptr()),
1505                    )) * inv_ws;
1506                    let rg: f32 = Renderer3D::sse_hsum_4x(core::arch::x86_64::_mm_mul_ps(
1507                        wt,
1508                        core::arch::x86_64::_mm_load_ps(cell.refl_g.as_ptr()),
1509                    )) * inv_ws;
1510                    let rb: f32 = Renderer3D::sse_hsum_4x(core::arch::x86_64::_mm_mul_ps(
1511                        wt,
1512                        core::arch::x86_64::_mm_load_ps(cell.refl_b.as_ptr()),
1513                    )) * inv_ws;
1514                    Vec3::new(rr, rg, rb)
1515                } else {
1516                    Vec3::zero()
1517                };
1518                let (gi, ao): (Vec3, f32) = if gi_active {
1519                    let gr: f32 = Renderer3D::sse_hsum_4x(core::arch::x86_64::_mm_mul_ps(
1520                        wt,
1521                        core::arch::x86_64::_mm_load_ps(cell.gi_r.as_ptr()),
1522                    )) * inv_ws;
1523                    let gg: f32 = Renderer3D::sse_hsum_4x(core::arch::x86_64::_mm_mul_ps(
1524                        wt,
1525                        core::arch::x86_64::_mm_load_ps(cell.gi_g.as_ptr()),
1526                    )) * inv_ws;
1527                    let gb: f32 = Renderer3D::sse_hsum_4x(core::arch::x86_64::_mm_mul_ps(
1528                        wt,
1529                        core::arch::x86_64::_mm_load_ps(cell.gi_b.as_ptr()),
1530                    )) * inv_ws;
1531                    let ao_v: f32 = Renderer3D::sse_hsum_4x(core::arch::x86_64::_mm_mul_ps(
1532                        wt,
1533                        core::arch::x86_64::_mm_load_ps(cell.ao.as_ptr()),
1534                    )) * inv_ws;
1535                    (Vec3::new(gr, gg, gb), ao_v)
1536                } else {
1537                    (Vec3::zero(), 1.0)
1538                };
1539                (1, sh, s_min, s_max, refl, gi, ao)
1540            }
1541        }
1542        #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
1543        {
1544            // SAFETY: `CachedProbeCell` arrays are 16-byte aligned; `simd128` is enabled on `wasm32`.
1545            unsafe {
1546                let d_v: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(depth);
1547                let c_depth: core::arch::wasm32::v128 =
1548                    core::arch::wasm32::v128_load(cell.depth.as_ptr().cast());
1549                let c_tscale: core::arch::wasm32::v128 =
1550                    core::arch::wasm32::v128_load(cell.tol_scale.as_ptr().cast());
1551                let c_tbias: core::arch::wasm32::v128 =
1552                    core::arch::wasm32::v128_load(cell.tol_bias.as_ptr().cast());
1553                let c_vbits: core::arch::wasm32::v128 =
1554                    core::arch::wasm32::v128_load(cell.valid_u32.as_ptr().cast());
1555                let d_diff: core::arch::wasm32::v128 =
1556                    core::arch::wasm32::f32x4_abs(core::arch::wasm32::f32x4_sub(d_v, c_depth));
1557                let tol: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
1558                    c_tbias,
1559                    core::arch::wasm32::f32x4_mul(d_v, c_tscale),
1560                );
1561                let in_tol: core::arch::wasm32::v128 = core::arch::wasm32::v128_and(
1562                    c_vbits,
1563                    core::arch::wasm32::f32x4_le(d_diff, tol),
1564                );
1565                let one: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(1.0);
1566                let bws_v: core::arch::wasm32::v128 =
1567                    core::arch::wasm32::v128_load(bws.as_ptr().cast());
1568                let wt_raw: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
1569                    core::arch::wasm32::f32x4_splat(1e-4),
1570                    core::arch::wasm32::f32x4_mul(
1571                        bws_v,
1572                        core::arch::wasm32::f32x4_sub(
1573                            one,
1574                            core::arch::wasm32::f32x4_div(d_diff, tol),
1575                        ),
1576                    ),
1577                );
1578                let wt: core::arch::wasm32::v128 = core::arch::wasm32::v128_and(in_tol, wt_raw);
1579                let w_sum: f32 = Renderer3D::wasm_hsum_4x(wt);
1580                if w_sum <= 1e-5 {
1581                    return (0, 1.0, 2.0, -1.0, Vec3::zero(), Vec3::zero(), 1.0);
1582                }
1583                let inv_ws: f32 = 1.0 / w_sum;
1584                let c_shadow: core::arch::wasm32::v128 =
1585                    core::arch::wasm32::v128_load(cell.shadow.as_ptr().cast());
1586                let sh: f32 =
1587                    Renderer3D::wasm_hsum_4x(core::arch::wasm32::f32x4_mul(wt, c_shadow)) * inv_ws;
1588                let (s_min, s_max): (f32, f32) = if gi_active {
1589                    (sh, sh)
1590                } else {
1591                    let s_min_v: core::arch::wasm32::v128 = core::arch::wasm32::v128_bitselect(
1592                        c_shadow,
1593                        core::arch::wasm32::f32x4_splat(2.0),
1594                        in_tol,
1595                    );
1596                    let s_max_v: core::arch::wasm32::v128 = core::arch::wasm32::v128_bitselect(
1597                        c_shadow,
1598                        core::arch::wasm32::f32x4_splat(-1.0),
1599                        in_tol,
1600                    );
1601                    (
1602                        Renderer3D::wasm_hmin_4x(s_min_v),
1603                        Renderer3D::wasm_hmax_4x(s_max_v),
1604                    )
1605                };
1606                let refl: Vec3 = if do_refl {
1607                    let rr: f32 = Renderer3D::wasm_hsum_4x(core::arch::wasm32::f32x4_mul(
1608                        wt,
1609                        core::arch::wasm32::v128_load(cell.refl_r.as_ptr().cast()),
1610                    )) * inv_ws;
1611                    let rg: f32 = Renderer3D::wasm_hsum_4x(core::arch::wasm32::f32x4_mul(
1612                        wt,
1613                        core::arch::wasm32::v128_load(cell.refl_g.as_ptr().cast()),
1614                    )) * inv_ws;
1615                    let rb: f32 = Renderer3D::wasm_hsum_4x(core::arch::wasm32::f32x4_mul(
1616                        wt,
1617                        core::arch::wasm32::v128_load(cell.refl_b.as_ptr().cast()),
1618                    )) * inv_ws;
1619                    Vec3::new(rr, rg, rb)
1620                } else {
1621                    Vec3::zero()
1622                };
1623                let (gi, ao): (Vec3, f32) = if gi_active {
1624                    let gr: f32 = Renderer3D::wasm_hsum_4x(core::arch::wasm32::f32x4_mul(
1625                        wt,
1626                        core::arch::wasm32::v128_load(cell.gi_r.as_ptr().cast()),
1627                    )) * inv_ws;
1628                    let gg: f32 = Renderer3D::wasm_hsum_4x(core::arch::wasm32::f32x4_mul(
1629                        wt,
1630                        core::arch::wasm32::v128_load(cell.gi_g.as_ptr().cast()),
1631                    )) * inv_ws;
1632                    let gb: f32 = Renderer3D::wasm_hsum_4x(core::arch::wasm32::f32x4_mul(
1633                        wt,
1634                        core::arch::wasm32::v128_load(cell.gi_b.as_ptr().cast()),
1635                    )) * inv_ws;
1636                    let ao_v: f32 = Renderer3D::wasm_hsum_4x(core::arch::wasm32::f32x4_mul(
1637                        wt,
1638                        core::arch::wasm32::v128_load(cell.ao.as_ptr().cast()),
1639                    )) * inv_ws;
1640                    (Vec3::new(gr, gg, gb), ao_v)
1641                } else {
1642                    (Vec3::zero(), 1.0)
1643                };
1644                (1, sh, s_min, s_max, refl, gi, ao)
1645            }
1646        }
1647        #[cfg(not(target_arch = "aarch64"))]
1648        #[cfg(not(target_arch = "x86_64"))]
1649        #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
1650        {
1651            let mut w_sum: f32 = 0.0;
1652            let mut s_sum: f32 = 0.0;
1653            let mut s_min: f32 = 2.0;
1654            let mut s_max: f32 = -1.0;
1655            let mut rr_sum: f32 = 0.0;
1656            let mut rg_sum: f32 = 0.0;
1657            let mut rb_sum: f32 = 0.0;
1658            let mut gr_sum: f32 = 0.0;
1659            let mut gg_sum: f32 = 0.0;
1660            let mut gb_sum: f32 = 0.0;
1661            let mut ao_sum: f32 = 0.0;
1662            let mut valid_matches: u32 = 0;
1663            let mut rem: u8 = cell.vmask;
1664            while rem != 0 {
1665                let item_index: usize = rem.trailing_zeros() as usize;
1666                rem &= rem - 1;
1667                let tol: f32 = depth.mul_add(cell.tol_scale[item_index], cell.tol_bias[item_index]);
1668                let d_diff: f32 = (depth - cell.depth[item_index]).abs();
1669                if d_diff > tol {
1670                    continue;
1671                }
1672                let wt: f32 = bws[item_index].mul_add(1.0 - d_diff / tol, 1e-4);
1673                w_sum += wt;
1674                let sh: f32 = cell.shadow[item_index];
1675                s_sum = sh.mul_add(wt, s_sum);
1676                s_min = s_min.min(sh);
1677                s_max = s_max.max(sh);
1678                if do_refl {
1679                    rr_sum = cell.refl_r[item_index].mul_add(wt, rr_sum);
1680                    rg_sum = cell.refl_g[item_index].mul_add(wt, rg_sum);
1681                    rb_sum = cell.refl_b[item_index].mul_add(wt, rb_sum);
1682                }
1683                if gi_active {
1684                    gr_sum = cell.gi_r[item_index].mul_add(wt, gr_sum);
1685                    gg_sum = cell.gi_g[item_index].mul_add(wt, gg_sum);
1686                    gb_sum = cell.gi_b[item_index].mul_add(wt, gb_sum);
1687                    ao_sum = cell.ao[item_index].mul_add(wt, ao_sum);
1688                }
1689                valid_matches += 1;
1690            }
1691            if valid_matches > 0 && w_sum > 1e-5 {
1692                let inv_ws: f32 = 1.0 / w_sum;
1693                (
1694                    valid_matches,
1695                    s_sum * inv_ws,
1696                    s_min,
1697                    s_max,
1698                    Vec3::new(rr_sum * inv_ws, rg_sum * inv_ws, rb_sum * inv_ws),
1699                    Vec3::new(gr_sum * inv_ws, gg_sum * inv_ws, gb_sum * inv_ws),
1700                    ao_sum * inv_ws,
1701                )
1702            } else {
1703                (0, 1.0, 2.0, -1.0, Vec3::zero(), Vec3::zero(), 1.0)
1704            }
1705        }
1706    }
1707}
1708
1709/// Borrowed row view helper for `RtProbeGridSoa`.
1710impl RtProbeGridSoa {
1711    /// Borrows row `gy` of width `gw` from this full SoA grid as a zero-copy `RtProbeRowView`.
1712    ///
1713    /// # Arguments
1714    ///
1715    /// - `&Self` - Full SoA probe grid reference.
1716    /// - `usize` - Coarse probe row index `gy`.
1717    /// - `usize` - Coarse probe grid width `gw`.
1718    ///
1719    /// # Returns
1720    ///
1721    /// - `RtProbeRowView<'_>` - Zero-copy borrowed SoA row view.
1722    #[inline(always)]
1723    #[must_use]
1724    pub(crate) fn row_view(&self, gy: usize, gw: usize) -> RtProbeRowView<'_> {
1725        let Self {
1726            shadow,
1727            refl_r,
1728            refl_g,
1729            refl_b,
1730            gi_r,
1731            gi_g,
1732            gi_b,
1733            ao,
1734            depth,
1735            nx,
1736            ny,
1737            nz,
1738            valid,
1739            ..
1740        } = self;
1741        let source_val: usize = gy * gw;
1742        let event_ref: usize = source_val + gw;
1743        RtProbeRowView {
1744            shadow: &shadow[source_val..event_ref],
1745            refl_r: &refl_r[source_val..event_ref],
1746            refl_g: &refl_g[source_val..event_ref],
1747            refl_b: &refl_b[source_val..event_ref],
1748            gi_r: &gi_r[source_val..event_ref],
1749            gi_g: &gi_g[source_val..event_ref],
1750            gi_b: &gi_b[source_val..event_ref],
1751            ao: &ao[source_val..event_ref],
1752            depth: &depth[source_val..event_ref],
1753            nx: &nx[source_val..event_ref],
1754            ny: &ny[source_val..event_ref],
1755            nz: &nz[source_val..event_ref],
1756            valid: &valid[source_val..event_ref],
1757        }
1758    }
1759}
1760
1761/// Default zero-allocation UE5-class `Renderer3D` with identity motion-vector matrices and pre-allocated subsystems.
1762impl Default for Renderer3D {
1763    /// Creates an empty `Renderer3D` initialized with identity previous projection, Hi-Z pyramid, Lumen cache, VSM, Clustered Lighting, TSR, and frame governor.
1764    ///
1765    /// # Returns
1766    ///
1767    /// - `Self` - Ready UE5-class 3D renderer.
1768    fn default() -> Self {
1769        Self {
1770            color_buffer: Vec::new(),
1771            aa_buffer: Vec::new(),
1772            depth_buffer: Vec::new(),
1773            g_tri_idx: Vec::new(),
1774            luma_buffer: Vec::new(),
1775            shaded_tris: Vec::new(),
1776            smooth_tris: Vec::new(),
1777            nanite_dags_cache: Vec::new(),
1778            cached_rdg_schedule: RenderGraphSchedule3D::default(),
1779            cached_rdg_key: 0,
1780            last_executed_rdg_passes: 0,
1781            rgba_scratch: Vec::new(),
1782            rt_probes: RtProbeGridSoa::default(),
1783            prev_rt_probes: RtProbeGridSoa::default(),
1784            has_probe_history: false,
1785            prev_probe_gw: 0,
1786            prev_probe_gh: 0,
1787            prev_probe_rt_mode: RayTracingMode::default(),
1788            prev_sun_dir: Vec3::zero(),
1789            rt_probes_wide_denoised: RtProbeGridSoa::default(),
1790            bloom_a: Vec::new(),
1791            bloom_b: Vec::new(),
1792            bloom_tile_active: Vec::new(),
1793            visible_scratch: Vec::new(),
1794            cluster_ranges_scratch: Vec::new(),
1795            projected_verts_scratch: Vec::new(),
1796            unique_meshes_scratch: HashSet::new(),
1797            saved_objs_scratch: Vec::new(),
1798            raster_tris_scratch: Vec::new(),
1799            tile_counts_scratch: Vec::new(),
1800            tile_offsets_scratch: Vec::new(),
1801            tile_cursors_scratch: Vec::new(),
1802            tile_tri_indices_scratch: Vec::new(),
1803            gpu_target: GpuCompositeTarget::default(),
1804            has_taa_history: false,
1805            prev_vp_m0: 0.0,
1806            prev_view_proj: Mat4::identity(),
1807            has_prev_vp: false,
1808            prev_render_dims: (0, 0),
1809            prev_rt_step: 0,
1810            hiz_pyramid: HiZPyramid::default(),
1811            hiz_occluder_flags_scratch: Vec::new(),
1812            lumen_cache: LumenRadianceCache::default(),
1813            light_clusters: LightClusterGrid3D::default(),
1814            virtual_shadow_map: VirtualShadowMap::default(),
1815            tsr_upscaler: TsrUpscaler::default(),
1816            tsr_internal_scratch: Vec::new(),
1817            frame_governor: AdaptiveFrameGovernor::default(),
1818            render_graph: RenderGraph3D::default(),
1819            rt_stride_bias: 0,
1820            geom_chunks_scratch: Vec::new(),
1821            adapted_exposure: 1.0,
1822            frame_index: 0,
1823            last_world_revision: 0,
1824            last_quality_fingerprint: 0,
1825            taa_accumulated_frames: 0,
1826            cached_world_reuses: 0,
1827            width: 0,
1828            height: 0,
1829            last_stats: RenderStats3D::default(),
1830            sky_lut: Vec::new(),
1831            sky_lut_key: 0,
1832            aces_lut: Self::build_aces3d_lut(),
1833            reserved_object_cap: 0,
1834            reserved_mesh_cap: 0,
1835        }
1836    }
1837}
1838
1839/// High-FPS UE5-class Deferred GGX PBR + Persistent Multi-Core Tiled SIMD BVH4/BVH8 + Lumen GI + Volumetric Fog + SIMD Bloom + Morphological AA/TAA renderer.
1840impl Renderer3D {
1841    /// Builds the 1025-entry L1-resident ACES filmic + sRGB gamma LUT for zero-`powf` sky and scalar tonemapping.
1842    ///
1843    /// # Returns
1844    ///
1845    /// - `Vec<u8>` - Precomputed sRGB byte LUT of length `ACES3D_LUT_SIZE`.
1846    #[must_use]
1847    fn build_aces3d_lut() -> Vec<u8> {
1848        let mut table: Vec<u8> = Vec::with_capacity(ACES3D_LUT_SIZE);
1849        let max_idx_f: f32 = (ACES3D_LUT_SIZE - 1) as f32;
1850        for slot in 0..ACES3D_LUT_SIZE {
1851            if slot + 1 >= ACES3D_LUT_SIZE {
1852                table.push(255);
1853            } else {
1854                let norm_u: f32 = (slot as f32) / max_idx_f;
1855                let linear_val: f32 = ACES3D_LUT_KNEE * norm_u / (1.0 - norm_u);
1856                let num: f32 = linear_val * (2.51 * linear_val + 0.03);
1857                let den: f32 = linear_val * (2.43 * linear_val + 0.59) + 0.14;
1858                let mapped: f32 = (num / den).clamp(0.0, 1.0);
1859                let srgb: f32 = mapped.powf(1.0 / 2.2);
1860                table.push((srgb.clamp(0.0, 1.0) * 255.0 + 0.5) as u8);
1861            }
1862        }
1863        table
1864    }
1865
1866    /// Maps a linear HDR RGB triple to RGBA8 via `aces_lut` with zero `powf` calls.
1867    ///
1868    /// # Arguments
1869    ///
1870    /// - `&[u8]` - Precomputed ACES+sRGB LUT (`ACES3D_LUT_SIZE`).
1871    /// - `Vec3` - Exposed linear HDR radiance.
1872    ///
1873    /// # Returns
1874    ///
1875    /// - `[u8; 4]` - Tone-mapped RGBA8 pixel with opaque alpha `255`.
1876    #[inline(always)]
1877    #[must_use]
1878    fn lut_aces3d_rgba8(aces_lut: &[u8], exposed: Vec3) -> [u8; 4] {
1879        let max_idx: usize = ACES3D_LUT_SIZE - 1;
1880        let max_f: f32 = max_idx as f32;
1881        let rx: f32 = exposed.get_x().max(0.0);
1882        let gx: f32 = exposed.get_y().max(0.0);
1883        let bx: f32 = exposed.get_z().max(0.0);
1884        let ri: usize = (((rx / (rx + ACES3D_LUT_KNEE)) * max_f + 0.5) as usize).min(max_idx);
1885        let gi: usize = (((gx / (gx + ACES3D_LUT_KNEE)) * max_f + 0.5) as usize).min(max_idx);
1886        let bi: usize = (((bx / (bx + ACES3D_LUT_KNEE)) * max_f + 0.5) as usize).min(max_idx);
1887        [aces_lut[ri], aces_lut[gi], aces_lut[bi], 255]
1888    }
1889
1890    /// Deterministic fast 2D hash returning `[0.0, 1.0]` for procedural 3D atmospheric cloud strata and night stars.
1891    ///
1892    /// # Arguments
1893    ///
1894    /// - `i32` - Integer cell X coordinate.
1895    /// - `i32` - Integer cell Y coordinate.
1896    ///
1897    /// # Returns
1898    ///
1899    /// - `f32` - Pseudo-random scalar in `[0.0, 1.0]`.
1900    #[cfg_attr(not(target_arch = "wasm32"), inline)]
1901    #[must_use]
1902    fn sky_hash_2d(ix: i32, iy: i32) -> f32 {
1903        let mut bits: u32 = (ix as u32)
1904            .wrapping_mul(374_761_393)
1905            .wrapping_add((iy as u32).wrapping_mul(668_265_263));
1906        bits = (bits ^ (bits >> 13)).wrapping_mul(1_274_126_177);
1907        bits ^= bits >> 16;
1908        ((bits & 0x00FF_FFFF) as f32) * (1.0 / 16_777_215.0)
1909    }
1910
1911    /// Smooth cubic Hermite value noise for layered volumetric-look sky clouds.
1912    ///
1913    /// # Arguments
1914    ///
1915    /// - `f32` - Continuous U coordinate.
1916    /// - `f32` - Continuous V coordinate.
1917    ///
1918    /// # Returns
1919    ///
1920    /// - `f32` - Interpolated noise sample in `[0.0, 1.0]`.
1921    #[cfg_attr(not(target_arch = "wasm32"), inline)]
1922    #[must_use]
1923    fn sky_value_noise(coord_u: f32, coord_v: f32) -> f32 {
1924        let fu: f32 = coord_u.floor();
1925        let fv: f32 = coord_v.floor();
1926        let iu: i32 = fu as i32;
1927        let iv: i32 = fv as i32;
1928        let tu: f32 = coord_u - fu;
1929        let tv: f32 = coord_v - fv;
1930        let su: f32 = tu * tu * (3.0 - 2.0 * tu);
1931        let sv: f32 = tv * tv * (3.0 - 2.0 * tv);
1932        let v00: f32 = Self::sky_hash_2d(iu, iv);
1933        let v10: f32 = Self::sky_hash_2d(iu + 1, iv);
1934        let v01: f32 = Self::sky_hash_2d(iu, iv + 1);
1935        let v11: f32 = Self::sky_hash_2d(iu + 1, iv + 1);
1936        let top: f32 = v00 + (v10 - v00) * su;
1937        let bot: f32 = v01 + (v11 - v01) * su;
1938        top + (bot - top) * sv
1939    }
1940
1941    /// Multi-octave domain-rotated fractional Brownian motion for layered cirrus and backlit cumulus clouds.
1942    ///
1943    /// # Arguments
1944    ///
1945    /// - `f32` - Cloud dome X coordinate.
1946    /// - `f32` - Cloud dome Z coordinate.
1947    ///
1948    /// # Returns
1949    ///
1950    /// - `f32` - Normalized cloud density in `[0.0, 1.0]`.
1951    #[cfg_attr(not(target_arch = "wasm32"), inline)]
1952    #[must_use]
1953    fn sky_cloud_fbm(coord_x: f32, coord_z: f32) -> f32 {
1954        let mut sum: f32 = 0.0;
1955        let mut amp: f32 = 0.54;
1956        let mut norm: f32 = 0.0;
1957        let mut px: f32 = coord_x;
1958        let mut pz: f32 = coord_z;
1959        for _ in 0..4usize {
1960            sum += Self::sky_value_noise(px, pz) * amp;
1961            norm += amp;
1962            let nx: f32 = px * 1.72 - pz * 0.58 + 11.4;
1963            let nz: f32 = px * 0.58 + pz * 1.72 + 6.7;
1964            px = nx;
1965            pz = nz;
1966            amp *= 0.50;
1967        }
1968        if norm > 0.0 { sum / norm } else { 0.0 }
1969    }
1970
1971    /// Computes a deterministic 64-bit key fingerprinting `sun` lighting and atmosphere colors.
1972    ///
1973    /// # Arguments
1974    ///
1975    /// - `&DirectionalLight3D` - Active directional sun & sky configuration.
1976    ///
1977    /// # Returns
1978    ///
1979    /// - `u64` - Non-zero fingerprint invalidating the sky LUT on atmosphere changes.
1980    #[must_use]
1981    fn sky_sun_fingerprint(sun: &DirectionalLight3D) -> u64 {
1982        let dir: Vec3 = sun.get_direction();
1983        let hor: Vec3 = sun.get_sky_horizon();
1984        let zen: Vec3 = sun.get_sky_zenith();
1985        let col: Vec3 = sun.get_color();
1986        let words: [u32; 13] = [
1987            dir.get_x().to_bits(),
1988            dir.get_y().to_bits(),
1989            dir.get_z().to_bits(),
1990            hor.get_x().to_bits(),
1991            hor.get_y().to_bits(),
1992            hor.get_z().to_bits(),
1993            zen.get_x().to_bits(),
1994            zen.get_y().to_bits(),
1995            zen.get_z().to_bits(),
1996            col.get_x().to_bits(),
1997            col.get_y().to_bits(),
1998            col.get_z().to_bits(),
1999            sun.get_time_of_day().to_bits(),
2000        ];
2001        let mut hash: u64 = 0xCBF2_9CE4_8422_2325;
2002        for word in words.into_iter() {
2003            hash ^= word as u64;
2004            hash = hash.wrapping_mul(0x0100_0000_01B3);
2005        }
2006        hash.max(1)
2007    }
2008
2009    /// Evaluates physically inspired Rayleigh + Mie sky radiance with layered backlit clouds and night starfield along `dir` (excluding the sharp solar core added at full pixel resolution).
2010    ///
2011    /// # Arguments
2012    ///
2013    /// - `Vec3` - Unit view or reflection direction.
2014    /// - `&DirectionalLight3D` - Active sky & sun lighting parameters.
2015    ///
2016    /// # Returns
2017    ///
2018    /// - `Vec3` - Linear HDR atmospheric dome radiance.
2019    #[must_use]
2020    fn eval_atmospheric_dome(dir: Vec3, sun: &DirectionalLight3D) -> Vec3 {
2021        let up: f32 = dir.get_y().clamp(0.0, 1.0);
2022        let elev_mix: f32 = up.powf(0.58);
2023        let horizon_band: f32 = (1.0 - up) * (1.0 - up) * (1.0 - up);
2024        let sun_dir: Vec3 = sun.get_direction();
2025        let sun_col: Vec3 = sun.get_color();
2026        let sun_dot: f32 = dir.dot(sun_dir).max(0.0);
2027        let sd2: f32 = sun_dot * sun_dot;
2028        let sd4: f32 = sd2 * sd2;
2029        let sd8: f32 = sd4 * sd4;
2030        let hour: f32 = sun.get_time_of_day().rem_euclid(24.0);
2031        let is_night: bool = !(5.8..=19.2).contains(&hour);
2032        let is_sunset: bool = (5.5..7.5).contains(&hour) || (16.5..19.5).contains(&hour);
2033        let mut col: Vec3 = sun
2034            .get_sky_horizon()
2035            .lerp(sun.get_sky_zenith(), elev_mix)
2036            .add(sun.get_sky_horizon().scale(horizon_band * 0.22));
2037        let mie_strength: f32 = if is_sunset {
2038            0.55
2039        } else if is_night {
2040            0.18
2041        } else {
2042            0.34
2043        };
2044        col = col.add(
2045            sun_col.scale((sd4 * 0.24 + sd8 * 0.42 + horizon_band * sd2 * 0.38) * mie_strength),
2046        );
2047        if is_night && up > 0.08 {
2048            let star_u: f32 = (dir.get_x() / (up + 0.35)) * 42.0;
2049            let star_v: f32 = (dir.get_z() / (up + 0.35)) * 42.0;
2050            let star_h: f32 = Self::sky_hash_2d(star_u.floor() as i32, star_v.floor() as i32);
2051            if star_h > 0.992 {
2052                let star_bright: f32 = ((star_h - 0.992) * 125.0) * (up * 1.4).clamp(0.0, 1.0);
2053                col = col.add(Vec3::new(0.85, 0.92, 1.15).scale(star_bright * 1.45));
2054            }
2055        }
2056        if up > 0.015 {
2057            let proj_inv: f32 = 1.0 / (up + 0.14);
2058            let cloud_u: f32 = dir.get_x() * proj_inv * 0.95;
2059            let cloud_v: f32 = dir.get_z() * proj_inv * 0.95;
2060            let warp: f32 = Self::sky_value_noise(cloud_u * 0.7 + 2.3, cloud_v * 0.7 - 1.9);
2061            let raw_c: f32 =
2062                Self::sky_cloud_fbm(cloud_u + (warp - 0.5) * 0.85, cloud_v + (warp - 0.5) * 0.65);
2063            let rim_c: f32 = Self::sky_cloud_fbm(
2064                cloud_u + sun_dir.get_x() * 0.22,
2065                cloud_v + sun_dir.get_z() * 0.22,
2066            );
2067            let horizon_fade: f32 = ((up - 0.015) * 9.0).clamp(0.0, 1.0);
2068            let density_thresh: f32 = if is_night { 0.38 } else { 0.44 };
2069            let cov: f32 = ((raw_c - density_thresh) * 3.1).clamp(0.0, 1.0);
2070            let cloud_alpha: f32 = cov * cov * (3.0 - 2.0 * cov) * horizon_fade * 0.84;
2071            if cloud_alpha > 0.005 {
2072                let silver_rim: f32 =
2073                    ((raw_c - rim_c) * 3.2 + 0.25).clamp(0.0, 1.0) * (0.28 + 0.72 * sd4);
2074                let cloud_col: Vec3 = if is_sunset {
2075                    let base_shadow: Vec3 = Vec3::new(0.11, 0.07, 0.18);
2076                    let warm_belly: Vec3 = Vec3::new(1.18, 0.42, 0.34);
2077                    let gold_rim: Vec3 = Vec3::new(2.25, 1.28, 0.56);
2078                    base_shadow
2079                        .lerp(
2080                            warm_belly,
2081                            (0.25 + 0.75 * horizon_band + sd2 * 0.45).clamp(0.0, 1.0),
2082                        )
2083                        .add(gold_rim.scale(silver_rim * 0.88))
2084                } else if is_night {
2085                    let storm_core: Vec3 = Vec3::new(0.024, 0.036, 0.082);
2086                    let neon_glow: Vec3 = Vec3::new(0.24, 0.12, 0.36).lerp(
2087                        Vec3::new(0.08, 0.28, 0.42),
2088                        (dir.get_x() * 0.5 + 0.5).clamp(0.0, 1.0),
2089                    );
2090                    storm_core
2091                        .lerp(neon_glow, (horizon_band * 0.85 + 0.18).clamp(0.0, 1.0))
2092                        .add(sun_col.scale(silver_rim * 0.35))
2093                } else {
2094                    let cool_base: Vec3 = Vec3::new(0.46, 0.56, 0.72);
2095                    let bright_top: Vec3 = Vec3::new(1.38, 1.36, 1.32);
2096                    cool_base.lerp(bright_top, (0.45 + 0.55 * silver_rim).clamp(0.0, 1.0))
2097                };
2098                col = col.lerp(cloud_col, cloud_alpha);
2099            }
2100        }
2101        col
2102    }
2103
2104    /// Rebuilds the pre-baked hemi-octahedral `sky_lut` only when `sun` changes (`0.00 ms` steady state).
2105    ///
2106    /// # Arguments
2107    ///
2108    /// - `&DirectionalLight3D` - Active directional sun & sky configuration.
2109    fn ensure_sky_lut(&mut self, sun: &DirectionalLight3D) {
2110        let key: u64 = Self::sky_sun_fingerprint(sun);
2111        let needed: usize = SKY3D_LUT_W * SKY3D_LUT_H;
2112        let Self {
2113            sky_lut,
2114            sky_lut_key,
2115            ..
2116        } = self;
2117        if *sky_lut_key == key && sky_lut.len() == needed {
2118            return;
2119        }
2120        if sky_lut.len() != needed {
2121            sky_lut.resize(needed, [0.0; 3]);
2122        }
2123        let inv_w: f32 = 1.0 / ((SKY3D_LUT_W - 1) as f32);
2124        let inv_h: f32 = 1.0 / ((SKY3D_LUT_H - 1) as f32);
2125        let lut_ptr: usize = sky_lut.as_mut_ptr() as usize;
2126        let sun_copy: DirectionalLight3D = *sun;
2127        parallel_for_ranges(SKY3D_LUT_H, 16, |y0: usize, y1: usize| {
2128            let base: *mut [f32; 3] = lut_ptr as *mut [f32; 3];
2129            for row_idx in y0..y1 {
2130                let sv: f32 = (row_idx as f32) * inv_h * 2.0 - 1.0;
2131                // SAFETY: `parallel_for_ranges` partitions `[0, SKY3D_LUT_H)` into disjoint rows of `sky_lut`.
2132                let row: &mut [[f32; 3]] =
2133                    unsafe { from_raw_parts_mut(base.add(row_idx * SKY3D_LUT_W), SKY3D_LUT_W) };
2134                for (col_idx, dst) in row.iter_mut().enumerate() {
2135                    let su: f32 = (col_idx as f32) * inv_w * 2.0 - 1.0;
2136                    let oct_px: f32 = 0.5 * (su + sv);
2137                    let oct_pz: f32 = 0.5 * (su - sv);
2138                    let oct_py: f32 = (1.0 - oct_px.abs() - oct_pz.abs()).max(0.0);
2139                    let dir: Vec3 = Vec3::new(oct_px, oct_py, oct_pz).normalize();
2140                    let col: Vec3 = Self::eval_atmospheric_dome(dir, &sun_copy);
2141                    *dst = [col.get_x(), col.get_y(), col.get_z()];
2142                }
2143            }
2144        });
2145        *sky_lut_key = key;
2146    }
2147
2148    /// Bilinearly samples the pre-baked hemi-octahedral `sky_lut` along unnormalized or unit ray `dir` and adds full-resolution solar/lunar disk radiance.
2149    ///
2150    /// # Arguments
2151    ///
2152    /// - `&[[f32; 3]]` - Pre-baked hemi-octahedral sky dome LUT (`SKY3D_LUT_W * SKY3D_LUT_H`).
2153    /// - `Vec3` - View or reflection ray direction.
2154    /// - `&DirectionalLight3D` - Active directional sun & sky configuration.
2155    ///
2156    /// # Returns
2157    ///
2158    /// - `Vec3` - Linear HDR sky radiance including clouds, stars, and crisp sun/moon disk.
2159    #[inline(always)]
2160    #[must_use]
2161    fn sample_sky_lut(sky_lut: &[[f32; 3]], dir: Vec3, sun: &DirectionalLight3D) -> Vec3 {
2162        if sky_lut.len() < SKY3D_LUT_W * SKY3D_LUT_H {
2163            return Self::sample_sky(dir, sun);
2164        }
2165        let rx: f32 = dir.get_x();
2166        let ry: f32 = dir.get_y().max(0.0);
2167        let rz: f32 = dir.get_z();
2168        let inv_l1: f32 = 1.0 / (rx.abs() + ry + rz.abs()).max(1.0e-5);
2169        let oct_px: f32 = rx * inv_l1;
2170        let oct_pz: f32 = rz * inv_l1;
2171        let max_x: usize = SKY3D_LUT_W - 1;
2172        let max_y: usize = SKY3D_LUT_H - 1;
2173        let lut_u: f32 =
2174            ((0.5 * (oct_px + oct_pz) + 0.5) * (max_x as f32)).clamp(0.0, max_x as f32);
2175        let lut_v: f32 =
2176            ((0.5 * (oct_px - oct_pz) + 0.5) * (max_y as f32)).clamp(0.0, max_y as f32);
2177        let x0: usize = (lut_u as usize).min(max_x);
2178        let y0: usize = (lut_v as usize).min(max_y);
2179        let x1: usize = (x0 + 1).min(max_x);
2180        let y1: usize = (y0 + 1).min(max_y);
2181        let tx: f32 = lut_u - (x0 as f32);
2182        let ty: f32 = lut_v - (y0 as f32);
2183        let om_tx: f32 = 1.0 - tx;
2184        let om_ty: f32 = 1.0 - ty;
2185        let w00: f32 = om_tx * om_ty;
2186        let w10: f32 = tx * om_ty;
2187        let w01: f32 = om_tx * ty;
2188        let w11: f32 = tx * ty;
2189        let r0: usize = y0 * SKY3D_LUT_W;
2190        let r1: usize = y1 * SKY3D_LUT_W;
2191        let c00: [f32; 3] = sky_lut[r0 + x0];
2192        let c10: [f32; 3] = sky_lut[r0 + x1];
2193        let c01: [f32; 3] = sky_lut[r1 + x0];
2194        let c11: [f32; 3] = sky_lut[r1 + x1];
2195        let mut col: Vec3 = Vec3::new(
2196            c00[0] * w00 + c10[0] * w10 + c01[0] * w01 + c11[0] * w11,
2197            c00[1] * w00 + c10[1] * w10 + c01[1] * w01 + c11[1] * w11,
2198            c00[2] * w00 + c10[2] * w10 + c01[2] * w01 + c11[2] * w11,
2199        );
2200        let sun_dir: Vec3 = sun.get_direction();
2201        let raw_dot: f32 = dir.dot(sun_dir);
2202        if raw_dot > 0.0 {
2203            let sun_dot: f32 = raw_dot / dir.length().max(1.0e-5);
2204            if sun_dot > 0.9945 {
2205                let disk: f32 = ((sun_dot - 0.9945) * (1.0 / 0.0055)).clamp(0.0, 1.0);
2206                let disk_s: f32 = disk * disk * (3.0 - 2.0 * disk);
2207                col = col.add(sun.get_color().scale(disk_s * 4.2 + 0.55));
2208            } else if sun_dot > 0.94 {
2209                let halo: f32 = ((sun_dot - 0.94) * (1.0 / 0.06)).clamp(0.0, 1.0);
2210                let h2: f32 = halo * halo;
2211                col = col.add(sun.get_color().scale(h2 * h2 * 0.65));
2212            }
2213        }
2214        col
2215    }
2216
2217    /// Evaluates physically inspired Rayleigh + Mie atmospheric sky, clouds, and HDR solar disk radiance along `dir`.
2218    ///
2219    /// # Arguments
2220    ///
2221    /// - `Vec3` - Unit view or reflection direction.
2222    /// - `&DirectionalLight3D` - Active sky & sun lighting parameters.
2223    ///
2224    /// # Returns
2225    ///
2226    /// - `Vec3` - Linear HDR sky radiance.
2227    #[must_use]
2228    pub fn sample_sky(dir: Vec3, sun: &DirectionalLight3D) -> Vec3 {
2229        let mut col: Vec3 = Self::eval_atmospheric_dome(dir, sun);
2230        let sun_dot: f32 = dir.dot(sun.get_direction()).max(0.0);
2231        if sun_dot > 0.9945 {
2232            let disk: f32 = ((sun_dot - 0.9945) * (1.0 / 0.0055)).clamp(0.0, 1.0);
2233            let disk_s: f32 = disk * disk * (3.0 - 2.0 * disk);
2234            col = col.add(sun.get_color().scale(disk_s * 4.2 + 0.55));
2235        } else if sun_dot > 0.94 {
2236            let halo: f32 = ((sun_dot - 0.94) * (1.0 / 0.06)).clamp(0.0, 1.0);
2237            let h2: f32 = halo * halo;
2238            col = col.add(sun.get_color().scale(h2 * h2 * 0.65));
2239        }
2240        col
2241    }
2242
2243    /// Reconstructs exact world-space position for pixel `(px, py)` at camera depth `depth`.
2244    ///
2245    /// # Arguments
2246    ///
2247    /// - `&DeferredFrameContext` - Shared per-frame camera basis.
2248    /// - `usize` - Pixel X coordinate.
2249    /// - `usize` - Pixel Y coordinate.
2250    /// - `f32` - Linear camera-space depth (`1 / inv_w`).
2251    ///
2252    /// # Returns
2253    ///
2254    /// - `(Vec3, Vec3)` - `(world_pos, unnormalized_view_ray_dir)`.
2255    #[inline(always)]
2256    #[must_use]
2257    fn pixel_world_pos(
2258        frame_context: &DeferredFrameContext,
2259        px: usize,
2260        py: usize,
2261        depth: f32,
2262    ) -> (Vec3, Vec3) {
2263        let ndc_x: f32 = 2.0 * (((px as f32) + 0.5) * frame_context.inv_width) - 1.0;
2264        let ndc_y: f32 = 1.0 - 2.0 * (((py as f32) + 0.5) * frame_context.inv_height);
2265        let ray_vec: Vec3 = frame_context
2266            .camera_forward
2267            .add(frame_context.camera_right_scaled.scale(ndc_x))
2268            .add(frame_context.camera_up_scaled.scale(ndc_y));
2269        (
2270            frame_context.camera_position.add(ray_vec.scale(depth)),
2271            ray_vec,
2272        )
2273    }
2274
2275    /// Shades a single BVH closest-hit surface given its world-space normal and PBR material.
2276    ///
2277    /// # Arguments
2278    ///
2279    /// - `Vec3` - Hit world-space unit surface normal.
2280    /// - `PbrMaterial` - Hit surface PBR material.
2281    /// - `&DirectionalLight3D` - Active directional sun light.
2282    /// - `bool` - Enables secondary hemisphere sky energy conservation for multi-bounce Lumen GI.
2283    ///
2284    /// # Returns
2285    ///
2286    /// - `Vec3` - Linear HDR hit radiance.
2287    #[inline(always)]
2288    #[must_use]
2289    fn shade_surface_hit(
2290        hit_n: Vec3,
2291        mat: PbrMaterial,
2292        sun: &DirectionalLight3D,
2293        multi_bounce: bool,
2294    ) -> Vec3 {
2295        let h_nl: f32 = hit_n.dot(sun.get_direction()).abs().max(0.18);
2296        let mut col: Vec3 = mat
2297            .get_base_color()
2298            .mul(sun.get_color().scale(h_nl))
2299            .add(mat.get_emissive());
2300        if multi_bounce {
2301            let sky_hemi: Vec3 = sun.get_sky_horizon().lerp(
2302                sun.get_sky_zenith(),
2303                (hit_n.get_y() * 0.5 + 0.5).clamp(0.0, 1.0),
2304            );
2305            col = col.add(mat.get_base_color().mul(sky_hemi.scale(0.32)));
2306        }
2307        col
2308    }
2309
2310    /// Computes four blue-noise-rotated hemisphere Lumen GI/AO `(dir, inv_dir)` rays for a triangle normal.
2311    ///
2312    /// # Arguments
2313    ///
2314    /// - `Vec3` - Camera-facing unit surface normal.
2315    /// - `usize` - Starting slot offset inside `GI_HEMI_RING_16` rotated per frame.
2316    ///
2317    /// # Returns
2318    ///
2319    /// - `[(Vec3, Vec3); 4]` - Four `(gi_dir, inv_gi_dir)` ray tuples.
2320    #[cfg_attr(not(target_arch = "wasm32"), inline)]
2321    #[must_use]
2322    fn compute_gi_ray_quad(vec_value: Vec3, ring_offset: usize) -> [(Vec3, Vec3); 4] {
2323        let mut dirs: [(Vec3, Vec3); 4] = [(vec_value, vec_value); 4];
2324        for (idx, slot) in dirs.iter_mut().enumerate() {
2325            let jit_arr: [f32; 3] = GI_HEMI_RING_16[(ring_offset + idx) & 15];
2326            let base_jit: Vec3 = Vec3::new(jit_arr[0], jit_arr[1], jit_arr[2]);
2327            let jit: Vec3 = if vec_value.dot(base_jit) < -0.15 {
2328                base_jit.scale(-1.0)
2329            } else {
2330                base_jit
2331            };
2332            let gi_dir: Vec3 = vec_value.add(jit).normalize();
2333            *slot = (gi_dir, Ray3D::safe_inv_vec(gi_dir));
2334        }
2335        dirs
2336    }
2337
2338    /// Performs branchless 4-wide SIMD reverse-Z depth testing and G-Buffer triangle ID updates across a contiguous horizontal span inside a tile-local L1 buffer.
2339    ///
2340    /// # Arguments
2341    ///
2342    /// - `&mut [f32]` - Contiguous tile-local reverse-Z depth span.
2343    /// - `&mut [u32]` - Contiguous tile-local G-Buffer triangle ID span.
2344    /// - `f32` - Starting `1/w` depth at the left edge of the span.
2345    /// - `f32` - Per-pixel `1/w` derivative `d_inv_w_dx`.
2346    /// - `u32` - Triangle ID to write on depth pass.
2347    ///
2348    /// # Returns
2349    ///
2350    /// - `bool` - `true` when at least one pixel in this span passed the depth test.
2351    #[inline(always)]
2352    fn raster_span_simd(
2353        d_span: &mut [f32],
2354        g_span: &mut [u32],
2355        mut inv_w: f32,
2356        d_inv_w_dx: f32,
2357        tri_id: u32,
2358    ) -> bool {
2359        let len: usize = d_span.len();
2360        let mut wrote: bool = false;
2361        let mut idx: usize = 0;
2362        #[cfg(target_arch = "aarch64")]
2363        if len >= 4 {
2364            // SAFETY: `d_span` and `g_span` share identical length `len`, and `idx + 4 <= len` on every iteration; NEON is mandatory on `aarch64`.
2365            unsafe {
2366                let d_ptr: *mut f32 = d_span.as_mut_ptr();
2367                let g_ptr: *mut u32 = g_span.as_mut_ptr();
2368                let init: [f32; 4] = [
2369                    inv_w,
2370                    inv_w + d_inv_w_dx,
2371                    inv_w + d_inv_w_dx * 2.0,
2372                    inv_w + d_inv_w_dx * 3.0,
2373                ];
2374                let mut v_w: core::arch::aarch64::float32x4_t =
2375                    core::arch::aarch64::vld1q_f32(init.as_ptr());
2376                let v_step: core::arch::aarch64::float32x4_t =
2377                    core::arch::aarch64::vdupq_n_f32(d_inv_w_dx * 4.0);
2378                let v_tid: core::arch::aarch64::uint32x4_t =
2379                    core::arch::aarch64::vdupq_n_u32(tri_id);
2380                let mut any_hit: core::arch::aarch64::uint32x4_t =
2381                    core::arch::aarch64::vdupq_n_u32(0);
2382                while idx + 4 <= len {
2383                    let cur_d: core::arch::aarch64::float32x4_t =
2384                        core::arch::aarch64::vld1q_f32(d_ptr.add(idx));
2385                    let cmp: core::arch::aarch64::uint32x4_t =
2386                        core::arch::aarch64::vcgtq_f32(v_w, cur_d);
2387                    let cur_g: core::arch::aarch64::uint32x4_t =
2388                        core::arch::aarch64::vld1q_u32(g_ptr.add(idx));
2389                    let next_d: core::arch::aarch64::float32x4_t =
2390                        core::arch::aarch64::vbslq_f32(cmp, v_w, cur_d);
2391                    let next_g: core::arch::aarch64::uint32x4_t =
2392                        core::arch::aarch64::vbslq_u32(cmp, v_tid, cur_g);
2393                    core::arch::aarch64::vst1q_f32(d_ptr.add(idx), next_d);
2394                    core::arch::aarch64::vst1q_u32(g_ptr.add(idx), next_g);
2395                    any_hit = core::arch::aarch64::vorrq_u32(any_hit, cmp);
2396                    v_w = core::arch::aarch64::vaddq_f32(v_w, v_step);
2397                    idx += 4;
2398                }
2399                if core::arch::aarch64::vmaxvq_u32(any_hit) != 0 {
2400                    wrote = true;
2401                }
2402                inv_w += d_inv_w_dx * (idx as f32);
2403            }
2404        }
2405        #[cfg(target_arch = "x86_64")]
2406        if len >= 4 {
2407            // SAFETY: `d_span` and `g_span` share identical length `len`, and `idx + 4 <= len` on every iteration; SSE2 is mandatory on `x86_64`.
2408            unsafe {
2409                let d_ptr: *mut f32 = d_span.as_mut_ptr();
2410                let g_ptr: *mut u32 = g_span.as_mut_ptr();
2411                let init: [f32; 4] = [
2412                    inv_w,
2413                    inv_w + d_inv_w_dx,
2414                    inv_w + d_inv_w_dx * 2.0,
2415                    inv_w + d_inv_w_dx * 3.0,
2416                ];
2417                let mut v_w: core::arch::x86_64::__m128 =
2418                    core::arch::x86_64::_mm_loadu_ps(init.as_ptr());
2419                let v_step: core::arch::x86_64::__m128 =
2420                    core::arch::x86_64::_mm_set1_ps(d_inv_w_dx * 4.0);
2421                let v_tid: core::arch::x86_64::__m128i =
2422                    core::arch::x86_64::_mm_set1_epi32(tri_id as i32);
2423                let mut any_mask: i32 = 0;
2424                while idx + 4 <= len {
2425                    let cur_d: core::arch::x86_64::__m128 =
2426                        core::arch::x86_64::_mm_loadu_ps(d_ptr.add(idx));
2427                    let cmp: core::arch::x86_64::__m128 =
2428                        core::arch::x86_64::_mm_cmpgt_ps(v_w, cur_d);
2429                    let matrix_elems: i32 = core::arch::x86_64::_mm_movemask_ps(cmp);
2430                    if matrix_elems != 0 {
2431                        any_mask |= matrix_elems;
2432                        let next_d: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_or_ps(
2433                            core::arch::x86_64::_mm_and_ps(cmp, v_w),
2434                            core::arch::x86_64::_mm_andnot_ps(cmp, cur_d),
2435                        );
2436                        core::arch::x86_64::_mm_storeu_ps(d_ptr.add(idx), next_d);
2437                        let cmp_i: core::arch::x86_64::__m128i =
2438                            core::arch::x86_64::_mm_castps_si128(cmp);
2439                        let cur_g: core::arch::x86_64::__m128i =
2440                            core::arch::x86_64::_mm_loadu_si128(
2441                                g_ptr.add(idx).cast::<core::arch::x86_64::__m128i>(),
2442                            );
2443                        let next_g: core::arch::x86_64::__m128i = core::arch::x86_64::_mm_or_si128(
2444                            core::arch::x86_64::_mm_and_si128(cmp_i, v_tid),
2445                            core::arch::x86_64::_mm_andnot_si128(cmp_i, cur_g),
2446                        );
2447                        core::arch::x86_64::_mm_storeu_si128(
2448                            g_ptr.add(idx).cast::<core::arch::x86_64::__m128i>(),
2449                            next_g,
2450                        );
2451                    }
2452                    v_w = core::arch::x86_64::_mm_add_ps(v_w, v_step);
2453                    idx += 4;
2454                }
2455                if any_mask != 0 {
2456                    wrote = true;
2457                }
2458                inv_w += d_inv_w_dx * (idx as f32);
2459            }
2460        }
2461        #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
2462        if len >= 4 {
2463            // SAFETY: `d_span` and `g_span` share identical length `len`, and `idx + 4 <= len` on every iteration; `simd128` is enabled on `wasm32`.
2464            unsafe {
2465                let d_ptr: *mut f32 = d_span.as_mut_ptr();
2466                let g_ptr: *mut u32 = g_span.as_mut_ptr();
2467                let init: [f32; 4] = [
2468                    inv_w,
2469                    inv_w + d_inv_w_dx,
2470                    inv_w + d_inv_w_dx * 2.0,
2471                    inv_w + d_inv_w_dx * 3.0,
2472                ];
2473                let mut v_w: core::arch::wasm32::v128 =
2474                    core::arch::wasm32::v128_load(init.as_ptr().cast());
2475                let v_step: core::arch::wasm32::v128 =
2476                    core::arch::wasm32::f32x4_splat(d_inv_w_dx * 4.0);
2477                let v_tid: core::arch::wasm32::v128 = core::arch::wasm32::u32x4_splat(tri_id);
2478                let mut any_hit: core::arch::wasm32::v128 = core::arch::wasm32::u32x4_splat(0);
2479                while idx + 4 <= len {
2480                    let cur_d: core::arch::wasm32::v128 =
2481                        core::arch::wasm32::v128_load(d_ptr.add(idx).cast());
2482                    let cmp: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_gt(v_w, cur_d);
2483                    let cur_g: core::arch::wasm32::v128 =
2484                        core::arch::wasm32::v128_load(g_ptr.add(idx).cast());
2485                    let next_d: core::arch::wasm32::v128 =
2486                        core::arch::wasm32::v128_bitselect(v_w, cur_d, cmp);
2487                    let next_g: core::arch::wasm32::v128 =
2488                        core::arch::wasm32::v128_bitselect(v_tid, cur_g, cmp);
2489                    core::arch::wasm32::v128_store(d_ptr.add(idx).cast(), next_d);
2490                    core::arch::wasm32::v128_store(g_ptr.add(idx).cast(), next_g);
2491                    any_hit = core::arch::wasm32::v128_or(any_hit, cmp);
2492                    v_w = core::arch::wasm32::f32x4_add(v_w, v_step);
2493                    idx += 4;
2494                }
2495                if core::arch::wasm32::v128_any_true(any_hit) {
2496                    wrote = true;
2497                }
2498                inv_w += d_inv_w_dx * (idx as f32);
2499            }
2500        }
2501        while idx < len {
2502            if inv_w > d_span[idx] {
2503                d_span[idx] = inv_w;
2504                g_span[idx] = tri_id;
2505                wrote = true;
2506            }
2507            inv_w += d_inv_w_dx;
2508            idx += 1;
2509        }
2510        wrote
2511    }
2512
2513    /// Fused Barrier 1 worker executing L1-hot `64x64` tiled G-Buffer clear, binned SIMD triangle rasterization, visible-tri bitset marking, and coherent 2x2 probe packet raytracing.
2514    ///
2515    /// # Arguments
2516    ///
2517    /// - `&DeferredFrameContext` - Immutable per-frame camera, sun, and RT parameters.
2518    /// - `&TileRasterProbeInputs<'_>` - Read-only binned triangles, shading records, BVH4/BVH8, and object-space dynamic instances.
2519    /// - `usize` - Inclusive start tile index.
2520    /// - `usize` - Exclusive end tile index.
2521    /// - `(usize, usize, RtProbeGridMutPtrs)` - Writable base addresses `(depth_base, gtri_base, probe_ptrs)`.
2522    ///
2523    /// # Returns
2524    ///
2525    /// - `(usize, usize)` - `(total_rays, probe_reproj_hits)` traced and reused across `[tile_start..tile_end)`.
2526    unsafe fn raster_and_trace_tiles(
2527        frame_context: &DeferredFrameContext,
2528        inputs: &TileRasterProbeInputs<'_>,
2529        tile_start: usize,
2530        tile_end: usize,
2531        outputs: (usize, usize, RtProbeGridMutPtrs),
2532    ) -> (usize, usize) {
2533        let (depth_base, gtri_base, probe_ptrs): (usize, usize, RtProbeGridMutPtrs) = outputs;
2534        let width_val: usize = frame_context.width;
2535        let height_val: usize = frame_context.height;
2536        let gw: usize = frame_context.grid_width;
2537        let gh: usize = frame_context.grid_height;
2538        let step: usize = frame_context.raytrace_step;
2539        let half_step: usize = step / 2;
2540        let tile_px: usize = inputs.tile_px;
2541        let tiles_x: usize = inputs.tiles_x;
2542        let use_soft_shadows: bool =
2543            frame_context.raytrace_mode == RayTracingMode::FullPathTracedGi;
2544        let multi_bounce_refl: bool = frame_context.reflection_bounces >= 2;
2545        let sun_dir: Vec3 = frame_context.sun.get_direction();
2546        let inv_sun: Vec3 = frame_context.inv_sun_dir;
2547        let soft_rays: [(Vec3, Vec3); 16] = frame_context.soft_shadow_rays;
2548        let frame_idx_cur: usize = frame_context.frame_index;
2549        let _: usize = frame_idx_cur;
2550        let gi_ring_offset: usize = 0;
2551        let mut local_depth_uninit: [MaybeUninit<f32>;
2552            ENGINE3D_TILE_MAX_PX * ENGINE3D_TILE_MAX_PX] =
2553            [const { MaybeUninit::uninit() }; ENGINE3D_TILE_MAX_PX * ENGINE3D_TILE_MAX_PX];
2554        let mut local_gtri_uninit: [MaybeUninit<u32>; ENGINE3D_TILE_MAX_PX * ENGINE3D_TILE_MAX_PX] =
2555            [const { MaybeUninit::uninit() }; ENGINE3D_TILE_MAX_PX * ENGINE3D_TILE_MAX_PX];
2556        let mut static_shadow_cache: u32 = u32::MAX;
2557        let mut dyn_shadow_cache: u32 = u32::MAX;
2558        let mut gi_cache: [(u32, [(Vec3, Vec3); 4]); 4] =
2559            [(u32::MAX, [(Vec3::zero(), Vec3::zero()); 4]); 4];
2560        let mut gi_cache_cursor: usize = 0;
2561        let mut total_rays: usize = 0;
2562        let mut reproj_hits: usize = 0;
2563        for tile_id in tile_start..tile_end {
2564            let tx: usize = tile_id % tiles_x;
2565            let ty: usize = tile_id / tiles_x;
2566            let px0: usize = tx * tile_px;
2567            let py0: usize = ty * tile_px;
2568            let px1: usize = (px0 + tile_px).min(width_val);
2569            let py1: usize = (py0 + tile_px).min(height_val);
2570            let tw: usize = px1 - px0;
2571            let th: usize = py1 - py0;
2572            let t_pixels: usize = tw * th;
2573            if t_pixels == 0 {
2574                continue;
2575            }
2576            // SAFETY: Immediately fills all `t_pixels` elements with `0.0` / `u32::MAX` before creating initialized slices.
2577            let (local_depth, local_gtri): (&mut [f32], &mut [u32]) = unsafe {
2578                let dp: *mut f32 = local_depth_uninit.as_mut_ptr().cast::<f32>();
2579                let gp: *mut u32 = local_gtri_uninit.as_mut_ptr().cast::<u32>();
2580                let ds: &mut [f32] = from_raw_parts_mut(dp, t_pixels);
2581                let gs: &mut [u32] = from_raw_parts_mut(gp, t_pixels);
2582                ds.fill(0.0);
2583                gs.fill(u32::MAX);
2584                (ds, gs)
2585            };
2586            let bin_start: usize = inputs.tile_offsets[tile_id] as usize;
2587            let bin_end: usize = inputs.tile_offsets[tile_id + 1] as usize;
2588            let px0_i: i32 = px0 as i32;
2589            let px1_last_i: i32 = (px1 - 1) as i32;
2590            let py0_i: i32 = py0 as i32;
2591            let py1_last_i: i32 = (py1 - 1) as i32;
2592            for &tri_slot in inputs.tile_tri_indices[bin_start..bin_end].iter() {
2593                let tri: &RasterTri2D = &inputs.raster_tris[tri_slot as usize];
2594                let py_start: i32 = tri.min_y.max(py0_i);
2595                let py_end: i32 = tri.max_y.min(py1_last_i);
2596                if py_start > py_end {
2597                    continue;
2598                }
2599                let dy: f32 = (py_start - tri.min_y) as f32;
2600                let mut w0_row: f32 = tri.dw_dy[0].mul_add(dy, tri.w_start[0]);
2601                let mut w1_row: f32 = tri.dw_dy[1].mul_add(dy, tri.w_start[1]);
2602                let mut w2_row: f32 = tri.dw_dy[2].mul_add(dy, tri.w_start[2]);
2603                let mut inv_w_row: f32 = tri.d_inv_w_dy.mul_add(dy, tri.inv_w_start);
2604                let mut row_off: usize = ((py_start - py0_i) as usize) * tw;
2605                let min_x: i32 = tri.min_x;
2606                let k_tile_min: i32 = (px0_i - min_x).max(0);
2607                let k_tile_max: i32 = (px1_last_i - min_x).min(tri.span_max);
2608                if k_tile_min > k_tile_max {
2609                    continue;
2610                }
2611                let k_tile_min_f: f32 = k_tile_min as f32;
2612                let k_tile_max_f: f32 = k_tile_max as f32;
2613                let tri_id: u32 = tri.tri_id;
2614                let slopes: [f32; 3] = tri.slopes;
2615                let neg_inv_slopes: [f32; 3] = tri.neg_inv_slopes;
2616                let d_inv_w_dx: f32 = tri.d_inv_w_dx;
2617                for _py in py_start..=py_end {
2618                    let vals: [f32; 3] = [w0_row + 1e-5, w1_row + 1e-5, w2_row + 1e-5];
2619                    let mut k_lo: f32 = k_tile_min_f;
2620                    let mut k_hi: f32 = k_tile_max_f;
2621                    let mut valid_span: bool = true;
2622                    for event_ref in 0..3 {
2623                        let slope: f32 = slopes[event_ref];
2624                        let val: f32 = vals[event_ref];
2625                        if slope > 1e-9 {
2626                            k_lo = k_lo.max((val * neg_inv_slopes[event_ref]).ceil());
2627                        } else if slope < -1e-9 {
2628                            k_hi = k_hi.min((val * neg_inv_slopes[event_ref]).floor());
2629                        } else if val < 0.0 {
2630                            valid_span = false;
2631                            break;
2632                        }
2633                    }
2634                    if valid_span && k_lo <= k_hi {
2635                        let start_k: i32 = (k_lo as i32).max(k_tile_min);
2636                        let end_k: i32 = (k_hi as i32).min(k_tile_max);
2637                        if start_k <= end_k {
2638                            let inv_w_start_k: f32 = d_inv_w_dx.mul_add(start_k as f32, inv_w_row);
2639                            let lx0: usize = (min_x + start_k - px0_i) as usize;
2640                            let lx1: usize = (min_x + end_k - px0_i) as usize;
2641                            let _: bool = Self::raster_span_simd(
2642                                &mut local_depth[(row_off + lx0)..=(row_off + lx1)],
2643                                &mut local_gtri[(row_off + lx0)..=(row_off + lx1)],
2644                                inv_w_start_k,
2645                                d_inv_w_dx,
2646                                tri_id,
2647                            );
2648                        }
2649                    }
2650                    w0_row += tri.dw_dy[0];
2651                    w1_row += tri.dw_dy[1];
2652                    w2_row += tri.dw_dy[2];
2653                    inv_w_row += tri.d_inv_w_dy;
2654                    row_off += tw;
2655                }
2656            }
2657            for ly in 0..th {
2658                let dst_off: usize = (py0 + ly) * width_val + px0;
2659                let src_off: usize = ly * tw;
2660                // SAFETY: Tiles cover strictly disjoint `(px0..px1) x (py0..py1)` rectangles inside the global G-Buffer.
2661                unsafe {
2662                    (depth_base as *mut f32)
2663                        .add(dst_off)
2664                        .copy_from_nonoverlapping(local_depth.as_ptr().add(src_off), tw);
2665                    (gtri_base as *mut u32)
2666                        .add(dst_off)
2667                        .copy_from_nonoverlapping(local_gtri.as_ptr().add(src_off), tw);
2668                }
2669            }
2670            if step == 0 {
2671                continue;
2672            }
2673            let gx0: usize = px0 / step;
2674            let gx1: usize = px1.div_ceil(step).min(gw);
2675            let gy0: usize = py0 / step;
2676            let gy1: usize = py1.div_ceil(step).min(gh);
2677            let mut gy_base: usize = gy0;
2678            while gy_base < gy1 {
2679                let mut gx_base: usize = gx0;
2680                while gx_base < gx1 {
2681                    let coords: [(usize, usize); 4] = [
2682                        (gx_base, gy_base),
2683                        (gx_base + 1, gy_base),
2684                        (gx_base, gy_base + 1),
2685                        (gx_base + 1, gy_base + 1),
2686                    ];
2687                    let mut valid_mask: u8 = 0;
2688                    let mut shadow_mask: u8 = 0;
2689                    let mut refl_mask: u8 = 0;
2690                    let mut gi_mask: u8 = 0;
2691                    let mut p_idx_4: [usize; 4] = [0; 4];
2692                    let mut tid_4: [usize; 4] = [0; 4];
2693                    let mut depth_4: [f32; 4] = [0.0; 4];
2694                    let mut world_p_4: [Vec3; 4] = [Vec3::zero(); 4];
2695                    let mut origin_4: [Vec3; 4] = [Vec3::zero(); 4];
2696                    let mut normal_4: [Vec3; 4] = [Vec3::zero(); 4];
2697                    let mut ray_vec_4: [Vec3; 4] = [Vec3::zero(); 4];
2698                    let reuse_block: bool = inputs.prev_probes.is_some()
2699                        && (((gx_base >> 1) + (gy_base >> 1) + inputs.probe_checker_parity) & 1)
2700                            != 0;
2701                    let mut sh_pkt: RayPacket4 = RayPacket4 {
2702                        ox: [0.0; 4],
2703                        oy: [0.0; 4],
2704                        oz: [0.0; 4],
2705                        dx: [sun_dir.get_x(); 4],
2706                        dy: [sun_dir.get_y(); 4],
2707                        dz: [sun_dir.get_z(); 4],
2708                        ix: [inv_sun.get_x(); 4],
2709                        iy: [inv_sun.get_y(); 4],
2710                        iz: [inv_sun.get_z(); 4],
2711                    };
2712                    let mut refl_dir_4: [Vec3; 4] = [Vec3::zero(); 4];
2713                    let mut refl_pkt: RayPacket4 = sh_pkt;
2714                    let mut gi_dir_4: [Vec3; 4] = [Vec3::zero(); 4];
2715                    let mut gi_pkt: RayPacket4 = sh_pkt;
2716                    let mut out_shadow: [f32; 4] = [1.0; 4];
2717                    let mut out_refl: [Vec3; 4] = [frame_context.sun.get_sky_horizon(); 4];
2718                    let mut out_gi: [Vec3; 4] = [Vec3::zero(); 4];
2719                    let mut out_ao: [f32; 4] = [1.0; 4];
2720                    let mut prev_valid_mask: u8 = 0;
2721                    let mut prev_shadow_4: [f32; 4] = [1.0; 4];
2722                    let mut prev_refl_4: [Vec3; 4] = [frame_context.sun.get_sky_horizon(); 4];
2723                    let mut prev_gi_4: [Vec3; 4] = [Vec3::zero(); 4];
2724                    let mut prev_ao_4: [f32; 4] = [1.0; 4];
2725                    for lane in 0..4 {
2726                        let (gx, gy): (usize, usize) = coords[lane];
2727                        if gx >= gx1 || gy >= gy1 {
2728                            continue;
2729                        }
2730                        let pidx: usize = gy * gw + gx;
2731                        p_idx_4[lane] = pidx;
2732                        let px: usize = (gx * step + half_step).min(width_val - 1);
2733                        let py: usize = (gy * step + half_step).min(height_val - 1);
2734                        let l_off: usize = (py - py0) * tw + (px - px0);
2735                        let tid: u32 = local_gtri[l_off];
2736                        if tid == u32::MAX {
2737                            // SAFETY: Probe index `(gx, gy)` belongs exclusively to this tile.
2738                            unsafe {
2739                                probe_ptrs.write_invalid(pidx);
2740                            }
2741                            continue;
2742                        }
2743                        let inv_w: f32 = local_depth[l_off];
2744                        let depth: f32 = 1.0 / inv_w.max(1e-6);
2745                        let tri_idx: usize = tid as usize;
2746                        let tri: &GShadeTri = &inputs.shaded_tris[tri_idx];
2747                        let (world_p, ray_vec): (Vec3, Vec3) =
2748                            Self::pixel_world_pos(frame_context, px, py, depth);
2749                        let origin: Vec3 = world_p.add(tri.shade_n.scale(0.08));
2750                        let bit: u8 = 1_u8 << lane;
2751                        valid_mask |= bit;
2752                        tid_4[lane] = tri_idx;
2753                        depth_4[lane] = depth;
2754                        world_p_4[lane] = world_p;
2755                        origin_4[lane] = origin;
2756                        normal_4[lane] = tri.shade_n;
2757                        ray_vec_4[lane] = ray_vec;
2758                        if (reuse_block || inputs.same_camera_pose)
2759                            && let Some(prev) = inputs.prev_probes
2760                        {
2761                            let reproj_cand: Option<(usize, f32)> = if inputs.same_camera_pose {
2762                                Some((pidx, depth))
2763                            } else {
2764                                LumenRadianceCache::reproject_world_to_prev_probe(
2765                                    world_p,
2766                                    &inputs.prev_view_proj,
2767                                    inputs.prev_render_dims,
2768                                    (inputs.prev_rt_step, inputs.prev_gw, inputs.prev_gh),
2769                                )
2770                                .map(
2771                                    |reproj: LumenReprojectedProbe| {
2772                                        (reproj.get_prev_index(), reproj.get_prev_depth())
2773                                    },
2774                                )
2775                            };
2776                            if let Some((prev_idx, reproj_depth)) = reproj_cand
2777                                && prev_idx < prev.valid.len()
2778                                && prev.valid[prev_idx] != 0
2779                            {
2780                                let wdx: f32 = world_p.get_x() - prev.world_x[prev_idx];
2781                                let wdy: f32 = world_p.get_y() - prev.world_y[prev_idx];
2782                                let wdz: f32 = world_p.get_z() - prev.world_z[prev_idx];
2783                                let wdist_sq: f32 = wdx.mul_add(wdx, wdy.mul_add(wdy, wdz * wdz));
2784                                let ndot: f32 = tri.shade_n.get_x().mul_add(
2785                                    prev.nx[prev_idx],
2786                                    tri.shade_n.get_y().mul_add(
2787                                        prev.ny[prev_idx],
2788                                        tri.shade_n.get_z() * prev.nz[prev_idx],
2789                                    ),
2790                                );
2791                                let max_wdist: f32 = depth.mul_add(0.018, 0.30);
2792                                let d_tol: f32 = reproj_depth.mul_add(0.08, 0.25);
2793                                if wdist_sq <= max_wdist * max_wdist
2794                                    && ndot >= 0.94
2795                                    && (reproj_depth - prev.depth[prev_idx]).abs() <= d_tol
2796                                {
2797                                    let p_sh: f32 = prev.shadow[prev_idx];
2798                                    let p_rf: Vec3 = Vec3::new(
2799                                        prev.refl_r[prev_idx],
2800                                        prev.refl_g[prev_idx],
2801                                        prev.refl_b[prev_idx],
2802                                    );
2803                                    let p_gi: Vec3 = Vec3::new(
2804                                        prev.gi_r[prev_idx],
2805                                        prev.gi_g[prev_idx],
2806                                        prev.gi_b[prev_idx],
2807                                    );
2808                                    let p_ao: f32 = prev.ao[prev_idx];
2809                                    if reuse_block {
2810                                        out_shadow[lane] = p_sh;
2811                                        out_refl[lane] = p_rf;
2812                                        out_gi[lane] = p_gi;
2813                                        out_ao[lane] = p_ao;
2814                                        reproj_hits += 1;
2815                                        continue;
2816                                    }
2817                                    prev_valid_mask |= bit;
2818                                    prev_shadow_4[lane] = p_sh;
2819                                    prev_refl_4[lane] = p_rf;
2820                                    prev_gi_4[lane] = p_gi;
2821                                    prev_ao_4[lane] = p_ao;
2822                                }
2823                            }
2824                        }
2825                        if let Some(clusters) = inputs.light_clusters {
2826                            let uv_x: f32 = ((px as f32) + 0.5) * frame_context.inv_width;
2827                            let uv_y: f32 = ((py as f32) + 0.5) * frame_context.inv_height;
2828                            let local_irrad: Vec3 = clusters.evaluate_irradiance_fast(
2829                                world_p,
2830                                tri.shade_n,
2831                                (uv_x, uv_y, depth),
2832                            );
2833                            out_gi[lane] = out_gi[lane].add(local_irrad);
2834                        }
2835                        let pattern: usize = (gx & 1) | ((gy & 1) << 1);
2836                        let blue_slot: usize = (gx.wrapping_mul(73) ^ gy.wrapping_mul(151)) & 15;
2837                        if tri.n_dot_l > 0.02 {
2838                            if inputs.use_vsm_far_shadows
2839                                && depth > 42.0
2840                                && let Some(vsm) = inputs.vsm
2841                            {
2842                                out_shadow[lane] =
2843                                    vsm.sample_visibility(world_p, tri.shade_n, sun_dir);
2844                            } else {
2845                                shadow_mask |= bit;
2846                                total_rays += 1;
2847                                let (s_dir, s_inv): (Vec3, Vec3) = if use_soft_shadows {
2848                                    soft_rays[blue_slot]
2849                                } else {
2850                                    (sun_dir, inv_sun)
2851                                };
2852                                sh_pkt.ox[lane] = origin.get_x();
2853                                sh_pkt.oy[lane] = origin.get_y();
2854                                sh_pkt.oz[lane] = origin.get_z();
2855                                sh_pkt.dx[lane] = s_dir.get_x();
2856                                sh_pkt.dy[lane] = s_dir.get_y();
2857                                sh_pkt.dz[lane] = s_dir.get_z();
2858                                sh_pkt.ix[lane] = s_inv.get_x();
2859                                sh_pkt.iy[lane] = s_inv.get_y();
2860                                sh_pkt.iz[lane] = s_inv.get_z();
2861                            }
2862                        }
2863                        if tri.do_refl {
2864                            let view_in: Vec3 = ray_vec.normalize();
2865                            let rdir: Vec3 = view_in.reflect(tri.shade_n).normalize();
2866                            refl_dir_4[lane] = rdir;
2867                            if depth > 52.0 || (tri.mat_refl < 0.30 && depth > 34.0) {
2868                                out_refl[lane] =
2869                                    Self::sample_sky_lut(inputs.sky_lut, rdir, &frame_context.sun);
2870                            } else {
2871                                let rinv: Vec3 = Ray3D::safe_inv_vec(rdir);
2872                                refl_mask |= bit;
2873                                total_rays += 1;
2874                                refl_pkt.ox[lane] = origin.get_x();
2875                                refl_pkt.oy[lane] = origin.get_y();
2876                                refl_pkt.oz[lane] = origin.get_z();
2877                                refl_pkt.dx[lane] = rdir.get_x();
2878                                refl_pkt.dy[lane] = rdir.get_y();
2879                                refl_pkt.dz[lane] = rdir.get_z();
2880                                refl_pkt.ix[lane] = rinv.get_x();
2881                                refl_pkt.iy[lane] = rinv.get_y();
2882                                refl_pkt.iz[lane] = rinv.get_z();
2883                            }
2884                        }
2885                        if use_soft_shadows {
2886                            if depth > 48.0 {
2887                                out_gi[lane] = out_gi[lane]
2888                                    .add(frame_context.sun.get_sky_horizon().scale(0.18));
2889                                out_ao[lane] = 0.88;
2890                            } else if depth > 22.0
2891                                && let Some(cache) = inputs.lumen_cache
2892                                && let Some((cached_irrad, cached_ao, _)) = cache.lookup(
2893                                    world_p,
2894                                    tri.shade_n,
2895                                    frame_context.camera_position,
2896                                )
2897                            {
2898                                out_gi[lane] = out_gi[lane].add(cached_irrad.scale(0.36));
2899                                out_ao[lane] = cached_ao;
2900                            } else {
2901                                let quad: [(Vec3, Vec3); 4] = if gi_cache[0].0 == tid {
2902                                    gi_cache[0].1
2903                                } else if gi_cache[1].0 == tid {
2904                                    gi_cache[1].1
2905                                } else if gi_cache[2].0 == tid {
2906                                    gi_cache[2].1
2907                                } else if gi_cache[3].0 == tid {
2908                                    gi_cache[3].1
2909                                } else {
2910                                    let computed: [(Vec3, Vec3); 4] =
2911                                        Self::compute_gi_ray_quad(tri.shade_n, gi_ring_offset);
2912                                    gi_cache[gi_cache_cursor] = (tid, computed);
2913                                    gi_cache_cursor = (gi_cache_cursor + 1) & 3;
2914                                    computed
2915                                };
2916                                let (gdir, ginv): (Vec3, Vec3) = quad[pattern];
2917                                gi_dir_4[lane] = gdir;
2918                                gi_mask |= bit;
2919                                total_rays += 1;
2920                                gi_pkt.ox[lane] = origin.get_x();
2921                                gi_pkt.oy[lane] = origin.get_y();
2922                                gi_pkt.oz[lane] = origin.get_z();
2923                                gi_pkt.dx[lane] = gdir.get_x();
2924                                gi_pkt.dy[lane] = gdir.get_y();
2925                                gi_pkt.dz[lane] = gdir.get_z();
2926                                gi_pkt.ix[lane] = ginv.get_x();
2927                                gi_pkt.iy[lane] = ginv.get_y();
2928                                gi_pkt.iz[lane] = ginv.get_z();
2929                            }
2930                        }
2931                    }
2932                    if shadow_mask != 0 {
2933                        let occ: u8 = World3D::trace_any_shadow_packet4_with_instances(
2934                            inputs.static_bvh,
2935                            inputs.dyn_instances,
2936                            inputs.local_bvhs,
2937                            &sh_pkt,
2938                            shadow_mask,
2939                            (0.05, 140.0),
2940                            (&mut static_shadow_cache, &mut dyn_shadow_cache),
2941                        );
2942                        let mut matrix_elems: u8 = occ;
2943                        while matrix_elems != 0 {
2944                            let lane: usize = matrix_elems.trailing_zeros() as usize;
2945                            matrix_elems &= matrix_elems - 1;
2946                            out_shadow[lane] = 0.22;
2947                        }
2948                    }
2949                    if refl_mask != 0 {
2950                        let refl_hits: [Option<(f32, Vec3, PbrMaterial)>; 4] = if refl_mask
2951                            .count_ones()
2952                            >= 2
2953                        {
2954                            World3D::trace_closest_packet4_with_instances(
2955                                inputs.static_bvh,
2956                                inputs.dyn_instances,
2957                                inputs.local_bvhs,
2958                                &refl_pkt,
2959                                refl_mask,
2960                                (0.08, 100.0),
2961                            )
2962                        } else {
2963                            let lane: usize = refl_mask.trailing_zeros() as usize;
2964                            let rdir: Vec3 = refl_dir_4[lane];
2965                            let rinv: Vec3 =
2966                                Vec3::new(refl_pkt.ix[lane], refl_pkt.iy[lane], refl_pkt.iz[lane]);
2967                            let mut single: [Option<(f32, Vec3, PbrMaterial)>; 4] = [None; 4];
2968                            single[lane] = World3D::trace_closest_with_instances(
2969                                inputs.static_bvh,
2970                                inputs.dyn_instances,
2971                                inputs.local_bvhs,
2972                                (origin_4[lane], rdir, rinv),
2973                                (0.08, 100.0),
2974                            );
2975                            single
2976                        };
2977                        let mut rm: u8 = refl_mask;
2978                        while rm != 0 {
2979                            let lane: usize = rm.trailing_zeros() as usize;
2980                            rm &= rm - 1;
2981                            let rdir: Vec3 = refl_dir_4[lane];
2982                            out_refl[lane] = match refl_hits[lane] {
2983                                Some((hit_t, hit_n, hit_mat)) => {
2984                                    let mut hit_rad: Vec3 = Self::shade_surface_hit(
2985                                        hit_n,
2986                                        hit_mat,
2987                                        &frame_context.sun,
2988                                        use_soft_shadows,
2989                                    );
2990                                    if multi_bounce_refl
2991                                        && hit_t < 30.0
2992                                        && depth_4[lane] < 32.0
2993                                        && hit_mat.get_reflectivity() > 0.55
2994                                    {
2995                                        let p2: Vec3 = origin_4[lane]
2996                                            .add(rdir.scale(hit_t))
2997                                            .add(hit_n.scale(0.08));
2998                                        let r2: Vec3 = rdir.reflect(hit_n).normalize();
2999                                        let inv_r2: Vec3 = Ray3D::safe_inv_vec(r2);
3000                                        total_rays += 1;
3001                                        let bounce2: Vec3 =
3002                                            match World3D::trace_closest_with_instances(
3003                                                inputs.static_bvh,
3004                                                inputs.dyn_instances,
3005                                                inputs.local_bvhs,
3006                                                (p2, r2, inv_r2),
3007                                                (0.08, 56.0),
3008                                            ) {
3009                                                Some((_, n2, m2)) => Self::shade_surface_hit(
3010                                                    n2,
3011                                                    m2,
3012                                                    &frame_context.sun,
3013                                                    false,
3014                                                ),
3015                                                None => Self::sample_sky_lut(
3016                                                    inputs.sky_lut,
3017                                                    r2,
3018                                                    &frame_context.sun,
3019                                                ),
3020                                            };
3021                                        hit_rad = hit_rad.lerp(
3022                                            bounce2,
3023                                            (hit_mat.get_reflectivity() * 0.45).clamp(0.0, 0.5),
3024                                        );
3025                                    }
3026                                    hit_rad
3027                                }
3028                                None => {
3029                                    Self::sample_sky_lut(inputs.sky_lut, rdir, &frame_context.sun)
3030                                }
3031                            };
3032                        }
3033                    }
3034                    if gi_mask != 0 {
3035                        let gi_hits: [Option<(f32, Vec3, PbrMaterial)>; 4] =
3036                            if gi_mask.count_ones() >= 2 {
3037                                World3D::trace_closest_packet4_with_instances(
3038                                    inputs.static_bvh,
3039                                    inputs.dyn_instances,
3040                                    inputs.local_bvhs,
3041                                    &gi_pkt,
3042                                    gi_mask,
3043                                    (0.06, 20.0),
3044                                )
3045                            } else {
3046                                let lane: usize = gi_mask.trailing_zeros() as usize;
3047                                let gdir: Vec3 = gi_dir_4[lane];
3048                                let ginv: Vec3 =
3049                                    Vec3::new(gi_pkt.ix[lane], gi_pkt.iy[lane], gi_pkt.iz[lane]);
3050                                let mut single: [Option<(f32, Vec3, PbrMaterial)>; 4] = [None; 4];
3051                                single[lane] = World3D::trace_closest_with_instances(
3052                                    inputs.static_bvh,
3053                                    inputs.dyn_instances,
3054                                    inputs.local_bvhs,
3055                                    (origin_4[lane], gdir, ginv),
3056                                    (0.06, 20.0),
3057                                );
3058                                single
3059                            };
3060                        let mut gm: u8 = gi_mask;
3061                        while gm != 0 {
3062                            let lane: usize = gm.trailing_zeros() as usize;
3063                            gm &= gm - 1;
3064                            let gdir: Vec3 = gi_dir_4[lane];
3065                            match gi_hits[lane] {
3066                                Some((dist, hit_n, hit_mat)) => {
3067                                    let mut bounce: Vec3 = Self::shade_surface_hit(
3068                                        hit_n,
3069                                        hit_mat,
3070                                        &frame_context.sun,
3071                                        true,
3072                                    );
3073                                    if let Some(cache) = inputs.lumen_cache {
3074                                        let hit_pos: Vec3 = origin_4[lane].add(gdir.scale(dist));
3075                                        if let Some((cached_irrad, _, _)) = cache.lookup(
3076                                            hit_pos,
3077                                            hit_n,
3078                                            frame_context.camera_position,
3079                                        ) {
3080                                            bounce = bounce.add(
3081                                                hit_mat
3082                                                    .get_base_color()
3083                                                    .mul(cached_irrad.scale(0.55)),
3084                                            );
3085                                        }
3086                                    }
3087                                    let falloff: f32 = (1.0 - dist / 20.0).clamp(0.14, 1.0);
3088                                    out_gi[lane] = out_gi[lane].add(bounce.scale(0.36 * falloff));
3089                                    out_ao[lane] = 0.42 + 0.58 * (dist / 14.0).clamp(0.0, 1.0);
3090                                }
3091                                None => {
3092                                    out_gi[lane] = out_gi[lane].add(
3093                                        Self::sample_sky_lut(
3094                                            inputs.sky_lut,
3095                                            gdir,
3096                                            &frame_context.sun,
3097                                        )
3098                                        .scale(0.20),
3099                                    );
3100                                    out_ao[lane] = 1.0;
3101                                }
3102                            }
3103                        }
3104                    }
3105                    let mut blend_m: u8 = prev_valid_mask;
3106                    while blend_m != 0 {
3107                        let lane: usize = blend_m.trailing_zeros() as usize;
3108                        blend_m &= blend_m - 1;
3109                        let sh_diff: f32 = (out_shadow[lane] - prev_shadow_4[lane]).abs();
3110                        let sh_w: f32 = if sh_diff > 0.35 { 0.85 } else { 0.42 };
3111                        out_shadow[lane] =
3112                            prev_shadow_4[lane] + (out_shadow[lane] - prev_shadow_4[lane]) * sh_w;
3113                        let rf_delta: f32 = out_refl[lane].sub(prev_refl_4[lane]).length_sq();
3114                        let rf_w: f32 = if rf_delta > 0.45 { 0.85 } else { 0.45 };
3115                        out_refl[lane] = prev_refl_4[lane].lerp(out_refl[lane], rf_w);
3116                        out_gi[lane] = prev_gi_4[lane].lerp(out_gi[lane], 0.42);
3117                        out_ao[lane] = prev_ao_4[lane] + (out_ao[lane] - prev_ao_4[lane]) * 0.42;
3118                    }
3119                    let mut vm: u8 = valid_mask;
3120                    while vm != 0 {
3121                        let lane: usize = vm.trailing_zeros() as usize;
3122                        vm &= vm - 1;
3123                        let _: (usize, Vec3) = (tid_4[lane], ray_vec_4[lane]);
3124                        // SAFETY: Probe index `p_idx_4[lane]` lies within this tile's strictly disjoint probe rectangle.
3125                        unsafe {
3126                            probe_ptrs.write_valid(
3127                                p_idx_4[lane],
3128                                (out_shadow[lane], out_ao[lane], depth_4[lane]),
3129                                (out_refl[lane], out_gi[lane], normal_4[lane]),
3130                            );
3131                            probe_ptrs.write_world_pos(p_idx_4[lane], world_p_4[lane]);
3132                        }
3133                    }
3134                    gx_base += 2;
3135                }
3136                gy_base += 2;
3137            }
3138        }
3139        (total_rays, reproj_hits)
3140    }
3141
3142    /// Populates a single L1-stack SoA probe row `dst` (`gw <= 512`) for probe row `gy` with zero heap allocations, optionally skipping GI/AO 3x3 bilateral filtering when GI holds smooth analytic local lighting.
3143    ///
3144    /// # Arguments
3145    ///
3146    /// - `&RtProbeGridSoa` - Full raw probe SoA grid written by Barrier 1.
3147    /// - `usize` - Coarse probe grid width `gw <= 512`.
3148    /// - `usize` - Coarse probe grid height `gh`.
3149    /// - `usize` - Target probe row index `gy`.
3150    /// - `(bool, bool)` - `(denoise_shadow_refl, denoise_gi_ao)` bilateral flags.
3151    /// - `&mut RtProbeRowStack` - Destination L1-stack single-row SoA buffer.
3152    fn populate_probe_row_stack(
3153        raw: &RtProbeGridSoa,
3154        gw: usize,
3155        gh: usize,
3156        gy: usize,
3157        denoise_flags: (bool, bool),
3158        dst: &mut RtProbeRowStack,
3159    ) {
3160        let (denoise, denoise_gi): (bool, bool) = denoise_flags;
3161        let row_start: usize = gy * gw;
3162        let row_end: usize = row_start + gw;
3163        if !denoise {
3164            dst.shadow[..gw].copy_from_slice(&raw.shadow[row_start..row_end]);
3165            dst.refl_r[..gw].copy_from_slice(&raw.refl_r[row_start..row_end]);
3166            dst.refl_g[..gw].copy_from_slice(&raw.refl_g[row_start..row_end]);
3167            dst.refl_b[..gw].copy_from_slice(&raw.refl_b[row_start..row_end]);
3168            dst.gi_r[..gw].copy_from_slice(&raw.gi_r[row_start..row_end]);
3169            dst.gi_g[..gw].copy_from_slice(&raw.gi_g[row_start..row_end]);
3170            dst.gi_b[..gw].copy_from_slice(&raw.gi_b[row_start..row_end]);
3171            dst.ao[..gw].copy_from_slice(&raw.ao[row_start..row_end]);
3172            dst.depth[..gw].copy_from_slice(&raw.depth[row_start..row_end]);
3173            dst.nx[..gw].copy_from_slice(&raw.nx[row_start..row_end]);
3174            dst.ny[..gw].copy_from_slice(&raw.ny[row_start..row_end]);
3175            dst.nz[..gw].copy_from_slice(&raw.nz[row_start..row_end]);
3176            dst.valid[..gw].copy_from_slice(&raw.valid[row_start..row_end]);
3177            return;
3178        }
3179        let y0: usize = gy.saturating_sub(1);
3180        let y1: usize = (gy + 1).min(gh - 1);
3181        let raw_valid: &[u8] = raw.valid.as_slice();
3182        let raw_depth: &[f32] = raw.depth.as_slice();
3183        let raw_nx: &[f32] = raw.nx.as_slice();
3184        let raw_ny: &[f32] = raw.ny.as_slice();
3185        let raw_nz: &[f32] = raw.nz.as_slice();
3186        let raw_shadow: &[f32] = raw.shadow.as_slice();
3187        let raw_rr: &[f32] = raw.refl_r.as_slice();
3188        let raw_rg: &[f32] = raw.refl_g.as_slice();
3189        let raw_rb: &[f32] = raw.refl_b.as_slice();
3190        if !denoise_gi {
3191            dst.gi_r[..gw].copy_from_slice(&raw.gi_r[row_start..row_end]);
3192            dst.gi_g[..gw].copy_from_slice(&raw.gi_g[row_start..row_end]);
3193            dst.gi_b[..gw].copy_from_slice(&raw.gi_b[row_start..row_end]);
3194            dst.ao[..gw].copy_from_slice(&raw.ao[row_start..row_end]);
3195            for gx in 0..gw {
3196                let idx: usize = row_start + gx;
3197                if raw_valid[idx] == 0 {
3198                    dst.valid[gx] = 0;
3199                    continue;
3200                }
3201                let c_depth: f32 = raw_depth[idx];
3202                let c_nx: f32 = raw_nx[idx];
3203                let c_ny: f32 = raw_ny[idx];
3204                let c_nz: f32 = raw_nz[idx];
3205                let x0: usize = gx.saturating_sub(1);
3206                let x1: usize = (gx + 1).min(gw - 1);
3207                let depth_tol: f32 = c_depth.mul_add(0.22, 0.75);
3208                let inv_depth_tol: f32 = 1.0 / depth_tol;
3209                let mut w_sum: f32 = 0.0;
3210                let mut s_sum: f32 = 0.0;
3211                let mut rr_sum: f32 = 0.0;
3212                let mut rg_sum: f32 = 0.0;
3213                let mut rb_sum: f32 = 0.0;
3214                for ny in y0..=y1 {
3215                    let row_off: usize = ny * gw;
3216                    let row_wt_diag: f32 = if ny == gy { 1.0 } else { 0.6 };
3217                    let row_wt_center: f32 = if ny == gy { 1.8 } else { 1.0 };
3218                    for nx in x0..=x1 {
3219                        let nb_i: usize = row_off + nx;
3220                        if raw_valid[nb_i] == 0 {
3221                            continue;
3222                        }
3223                        let ndot: f32 = c_nx.mul_add(
3224                            raw_nx[nb_i],
3225                            c_ny.mul_add(raw_ny[nb_i], c_nz * raw_nz[nb_i]),
3226                        );
3227                        if ndot < 0.75 {
3228                            continue;
3229                        }
3230                        let d_diff: f32 = (c_depth - raw_depth[nb_i]).abs();
3231                        if d_diff > depth_tol {
3232                            continue;
3233                        }
3234                        let spatial: f32 = if nx == gx { row_wt_center } else { row_wt_diag };
3235                        let width_val: f32 = spatial * (1.0 - d_diff * inv_depth_tol);
3236                        w_sum += width_val;
3237                        s_sum = raw_shadow[nb_i].mul_add(width_val, s_sum);
3238                        rr_sum = raw_rr[nb_i].mul_add(width_val, rr_sum);
3239                        rg_sum = raw_rg[nb_i].mul_add(width_val, rg_sum);
3240                        rb_sum = raw_rb[nb_i].mul_add(width_val, rb_sum);
3241                    }
3242                }
3243                dst.valid[gx] = 1;
3244                dst.depth[gx] = c_depth;
3245                dst.nx[gx] = c_nx;
3246                dst.ny[gx] = c_ny;
3247                dst.nz[gx] = c_nz;
3248                if w_sum > 1e-4 {
3249                    let inv_w: f32 = 1.0 / w_sum;
3250                    dst.shadow[gx] = s_sum * inv_w;
3251                    dst.refl_r[gx] = rr_sum * inv_w;
3252                    dst.refl_g[gx] = rg_sum * inv_w;
3253                    dst.refl_b[gx] = rb_sum * inv_w;
3254                } else {
3255                    dst.shadow[gx] = raw_shadow[idx];
3256                    dst.refl_r[gx] = raw_rr[idx];
3257                    dst.refl_g[gx] = raw_rg[idx];
3258                    dst.refl_b[gx] = raw_rb[idx];
3259                }
3260            }
3261            return;
3262        }
3263        let raw_gr: &[f32] = raw.gi_r.as_slice();
3264        let raw_gg: &[f32] = raw.gi_g.as_slice();
3265        let raw_gb: &[f32] = raw.gi_b.as_slice();
3266        let raw_ao: &[f32] = raw.ao.as_slice();
3267        for gx in 0..gw {
3268            let idx: usize = row_start + gx;
3269            if raw_valid[idx] == 0 {
3270                dst.valid[gx] = 0;
3271                continue;
3272            }
3273            let c_depth: f32 = raw_depth[idx];
3274            let c_nx: f32 = raw_nx[idx];
3275            let c_ny: f32 = raw_ny[idx];
3276            let c_nz: f32 = raw_nz[idx];
3277            let x0: usize = gx.saturating_sub(1);
3278            let x1: usize = (gx + 1).min(gw - 1);
3279            let depth_tol: f32 = c_depth.mul_add(0.22, 0.75);
3280            let inv_depth_tol: f32 = 1.0 / depth_tol;
3281            let mut w_sum: f32 = 0.0;
3282            let mut s_sum: f32 = 0.0;
3283            let mut rr_sum: f32 = 0.0;
3284            let mut rg_sum: f32 = 0.0;
3285            let mut rb_sum: f32 = 0.0;
3286            let mut gi_r: f32 = 0.0;
3287            let mut gi_g: f32 = 0.0;
3288            let mut gi_b: f32 = 0.0;
3289            let mut ao_sum: f32 = 0.0;
3290            for ny in y0..=y1 {
3291                let row_off: usize = ny * gw;
3292                let row_wt_diag: f32 = if ny == gy { 1.0 } else { 0.6 };
3293                let row_wt_center: f32 = if ny == gy { 1.8 } else { 1.0 };
3294                for nx in x0..=x1 {
3295                    let nb_i: usize = row_off + nx;
3296                    if raw_valid[nb_i] == 0 {
3297                        continue;
3298                    }
3299                    let ndot: f32 = c_nx.mul_add(
3300                        raw_nx[nb_i],
3301                        c_ny.mul_add(raw_ny[nb_i], c_nz * raw_nz[nb_i]),
3302                    );
3303                    if ndot < 0.75 {
3304                        continue;
3305                    }
3306                    let d_diff: f32 = (c_depth - raw_depth[nb_i]).abs();
3307                    if d_diff > depth_tol {
3308                        continue;
3309                    }
3310                    let spatial: f32 = if nx == gx { row_wt_center } else { row_wt_diag };
3311                    let width_val: f32 = spatial * (1.0 - d_diff * inv_depth_tol);
3312                    w_sum += width_val;
3313                    s_sum = raw_shadow[nb_i].mul_add(width_val, s_sum);
3314                    rr_sum = raw_rr[nb_i].mul_add(width_val, rr_sum);
3315                    rg_sum = raw_rg[nb_i].mul_add(width_val, rg_sum);
3316                    rb_sum = raw_rb[nb_i].mul_add(width_val, rb_sum);
3317                    gi_r = raw_gr[nb_i].mul_add(width_val, gi_r);
3318                    gi_g = raw_gg[nb_i].mul_add(width_val, gi_g);
3319                    gi_b = raw_gb[nb_i].mul_add(width_val, gi_b);
3320                    ao_sum = raw_ao[nb_i].mul_add(width_val, ao_sum);
3321                }
3322            }
3323            dst.valid[gx] = 1;
3324            dst.depth[gx] = c_depth;
3325            dst.nx[gx] = c_nx;
3326            dst.ny[gx] = c_ny;
3327            dst.nz[gx] = c_nz;
3328            if w_sum > 1e-4 {
3329                let inv_w: f32 = 1.0 / w_sum;
3330                dst.shadow[gx] = s_sum * inv_w;
3331                dst.refl_r[gx] = rr_sum * inv_w;
3332                dst.refl_g[gx] = rg_sum * inv_w;
3333                dst.refl_b[gx] = rb_sum * inv_w;
3334                dst.gi_r[gx] = gi_r * inv_w;
3335                dst.gi_g[gx] = gi_g * inv_w;
3336                dst.gi_b[gx] = gi_b * inv_w;
3337                dst.ao[gx] = ao_sum * inv_w;
3338            } else {
3339                dst.shadow[gx] = raw_shadow[idx];
3340                dst.refl_r[gx] = raw_rr[idx];
3341                dst.refl_g[gx] = raw_rg[idx];
3342                dst.refl_b[gx] = raw_rb[idx];
3343                dst.gi_r[gx] = raw_gr[idx];
3344                dst.gi_g[gx] = raw_gg[idx];
3345                dst.gi_b[gx] = raw_gb[idx];
3346                dst.ao[gx] = raw_ao[idx];
3347            }
3348        }
3349    }
3350
3351    /// Fallback full-grid bilateral denoiser for ultra-wide viewports (`gw > 256`, e.g. 4K).
3352    ///
3353    /// # Arguments
3354    ///
3355    /// - `&RtProbeGridSoa` - Raw input SoA probe grid.
3356    /// - `usize` - Coarse grid width `gw`.
3357    /// - `usize` - Coarse grid height `gh`.
3358    /// - `&mut RtProbeGridSoa` - Pre-allocated denoised output SoA grid.
3359    fn denoise_wide_grid(raw: &RtProbeGridSoa, gw: usize, gh: usize, dst: &mut RtProbeGridSoa) {
3360        dst.resize(gw * gh);
3361        let dst_ptrs: RtProbeGridMutPtrs = dst.mut_ptrs();
3362        let grain: usize = (gh / 24).clamp(2, 8);
3363        parallel_for_ranges(gh, grain, |gy0: usize, gy1: usize| {
3364            let raw_valid: &[u8] = raw.valid.as_slice();
3365            let raw_depth: &[f32] = raw.depth.as_slice();
3366            let raw_nx: &[f32] = raw.nx.as_slice();
3367            let raw_ny: &[f32] = raw.ny.as_slice();
3368            let raw_nz: &[f32] = raw.nz.as_slice();
3369            let raw_shadow: &[f32] = raw.shadow.as_slice();
3370            let raw_rr: &[f32] = raw.refl_r.as_slice();
3371            let raw_rg: &[f32] = raw.refl_g.as_slice();
3372            let raw_rb: &[f32] = raw.refl_b.as_slice();
3373            let raw_gr: &[f32] = raw.gi_r.as_slice();
3374            let raw_gg: &[f32] = raw.gi_g.as_slice();
3375            let raw_gb: &[f32] = raw.gi_b.as_slice();
3376            let raw_ao: &[f32] = raw.ao.as_slice();
3377            for gy in gy0..gy1 {
3378                let row_start: usize = gy * gw;
3379                let y0: usize = gy.saturating_sub(1);
3380                let y1: usize = (gy + 1).min(gh - 1);
3381                for gx in 0..gw {
3382                    let idx: usize = row_start + gx;
3383                    if raw_valid[idx] == 0 {
3384                        // SAFETY: `parallel_for_ranges` yields strictly disjoint rows `[gy0..gy1)`.
3385                        unsafe {
3386                            dst_ptrs.write_invalid(idx);
3387                        }
3388                        continue;
3389                    }
3390                    let c_depth: f32 = raw_depth[idx];
3391                    let c_nx: f32 = raw_nx[idx];
3392                    let c_ny: f32 = raw_ny[idx];
3393                    let c_nz: f32 = raw_nz[idx];
3394                    let x0: usize = gx.saturating_sub(1);
3395                    let x1: usize = (gx + 1).min(gw - 1);
3396                    let depth_tol: f32 = c_depth.mul_add(0.22, 0.75);
3397                    let inv_depth_tol: f32 = 1.0 / depth_tol;
3398                    let mut w_sum: f32 = 0.0;
3399                    let mut s_sum: f32 = 0.0;
3400                    let mut rr_sum: f32 = 0.0;
3401                    let mut rg_sum: f32 = 0.0;
3402                    let mut rb_sum: f32 = 0.0;
3403                    let mut gi_r: f32 = 0.0;
3404                    let mut gi_g: f32 = 0.0;
3405                    let mut gi_b: f32 = 0.0;
3406                    let mut ao_sum: f32 = 0.0;
3407                    for ny in y0..=y1 {
3408                        let row_off: usize = ny * gw;
3409                        let same_y: bool = ny == gy;
3410                        for nx in x0..=x1 {
3411                            let nb_i: usize = row_off + nx;
3412                            if raw_valid[nb_i] == 0 {
3413                                continue;
3414                            }
3415                            let ndot: f32 = c_nx.mul_add(
3416                                raw_nx[nb_i],
3417                                c_ny.mul_add(raw_ny[nb_i], c_nz * raw_nz[nb_i]),
3418                            );
3419                            if ndot < 0.75 {
3420                                continue;
3421                            }
3422                            let d_diff: f32 = (c_depth - raw_depth[nb_i]).abs();
3423                            if d_diff > depth_tol {
3424                                continue;
3425                            }
3426                            let spatial: f32 = if nx == gx && same_y {
3427                                1.8
3428                            } else if nx == gx || same_y {
3429                                1.0
3430                            } else {
3431                                0.6
3432                            };
3433                            let width_val: f32 = spatial * (1.0 - d_diff * inv_depth_tol);
3434                            w_sum += width_val;
3435                            s_sum = raw_shadow[nb_i].mul_add(width_val, s_sum);
3436                            rr_sum = raw_rr[nb_i].mul_add(width_val, rr_sum);
3437                            rg_sum = raw_rg[nb_i].mul_add(width_val, rg_sum);
3438                            rb_sum = raw_rb[nb_i].mul_add(width_val, rb_sum);
3439                            gi_r = raw_gr[nb_i].mul_add(width_val, gi_r);
3440                            gi_g = raw_gg[nb_i].mul_add(width_val, gi_g);
3441                            gi_b = raw_gb[nb_i].mul_add(width_val, gi_b);
3442                            ao_sum = raw_ao[nb_i].mul_add(width_val, ao_sum);
3443                        }
3444                    }
3445                    let (sh, rr, rg, rb, gr, gg, gb, ao): (f32, f32, f32, f32, f32, f32, f32, f32) =
3446                        if w_sum > 1e-4 {
3447                            let inv_w: f32 = 1.0 / w_sum;
3448                            (
3449                                s_sum * inv_w,
3450                                rr_sum * inv_w,
3451                                rg_sum * inv_w,
3452                                rb_sum * inv_w,
3453                                gi_r * inv_w,
3454                                gi_g * inv_w,
3455                                gi_b * inv_w,
3456                                ao_sum * inv_w,
3457                            )
3458                        } else {
3459                            (
3460                                raw_shadow[idx],
3461                                raw_rr[idx],
3462                                raw_rg[idx],
3463                                raw_rb[idx],
3464                                raw_gr[idx],
3465                                raw_gg[idx],
3466                                raw_gb[idx],
3467                                raw_ao[idx],
3468                            )
3469                        };
3470                    // SAFETY: `idx` belongs exclusively to disjoint row `gy` in `[gy0..gy1)`.
3471                    unsafe {
3472                        dst_ptrs.write_valid(
3473                            idx,
3474                            (sh, ao, c_depth),
3475                            (
3476                                Vec3::new(rr, rg, rb),
3477                                Vec3::new(gr, gg, gb),
3478                                Vec3::new(c_nx, c_ny, c_nz),
3479                            ),
3480                        );
3481                    }
3482                }
3483            }
3484        });
3485    }
3486
3487    /// Evaluates a symmetric 5-tap SIMD Gaussian bloom kernel (`0.08, 0.22, 0.40, 0.22, 0.08`) on 16-byte-aligned `[f32; 4]` RGB0 taps.
3488    ///
3489    /// # Arguments
3490    ///
3491    /// - `[f32; 4]` - Tap at offset `-2`.
3492    /// - `[f32; 4]` - Tap at offset `-1`.
3493    /// - `[f32; 4]` - Center tap `0`.
3494    /// - `[f32; 4]` - Tap at offset `+1`.
3495    /// - `[f32; 4]` - Tap at offset `+2`.
3496    ///
3497    /// # Returns
3498    ///
3499    /// - `[f32; 4]` - Filtered linear HDR bloom RGB0 vector.
3500    #[inline(always)]
3501    #[must_use]
3502    fn blur_bloom_tap5(
3503        c0: [f32; 4],
3504        c1: [f32; 4],
3505        c2: [f32; 4],
3506        c3: [f32; 4],
3507        c4: [f32; 4],
3508    ) -> [f32; 4] {
3509        #[cfg(target_arch = "aarch64")]
3510        {
3511            let mut out: [f32; 4] = [0.0; 4];
3512            // SAFETY: Stack `[f32; 4]` arrays are valid 16-byte values; NEON is mandatory on `aarch64`.
3513            unsafe {
3514                let s04: core::arch::aarch64::float32x4_t = core::arch::aarch64::vaddq_f32(
3515                    core::arch::aarch64::vld1q_f32(c0.as_ptr()),
3516                    core::arch::aarch64::vld1q_f32(c4.as_ptr()),
3517                );
3518                let s13: core::arch::aarch64::float32x4_t = core::arch::aarch64::vaddq_f32(
3519                    core::arch::aarch64::vld1q_f32(c1.as_ptr()),
3520                    core::arch::aarch64::vld1q_f32(c3.as_ptr()),
3521                );
3522                let v2: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
3523                    core::arch::aarch64::vld1q_f32(c2.as_ptr()),
3524                    core::arch::aarch64::vdupq_n_f32(0.40),
3525                );
3526                let acc: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
3527                    core::arch::aarch64::vfmaq_f32(v2, s13, core::arch::aarch64::vdupq_n_f32(0.22)),
3528                    s04,
3529                    core::arch::aarch64::vdupq_n_f32(0.08),
3530                );
3531                core::arch::aarch64::vst1q_f32(out.as_mut_ptr(), acc);
3532            }
3533            out
3534        }
3535        #[cfg(target_arch = "x86_64")]
3536        {
3537            let mut out: [f32; 4] = [0.0; 4];
3538            // SAFETY: Stack `[f32; 4]` arrays are valid 16-byte values; SSE2 is mandatory on `x86_64`.
3539            unsafe {
3540                let s04: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
3541                    core::arch::x86_64::_mm_loadu_ps(c0.as_ptr()),
3542                    core::arch::x86_64::_mm_loadu_ps(c4.as_ptr()),
3543                );
3544                let s13: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
3545                    core::arch::x86_64::_mm_loadu_ps(c1.as_ptr()),
3546                    core::arch::x86_64::_mm_loadu_ps(c3.as_ptr()),
3547                );
3548                let v2: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(
3549                    core::arch::x86_64::_mm_loadu_ps(c2.as_ptr()),
3550                    core::arch::x86_64::_mm_set1_ps(0.40),
3551                );
3552                let acc: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
3553                    core::arch::x86_64::_mm_add_ps(
3554                        v2,
3555                        core::arch::x86_64::_mm_mul_ps(s13, core::arch::x86_64::_mm_set1_ps(0.22)),
3556                    ),
3557                    core::arch::x86_64::_mm_mul_ps(s04, core::arch::x86_64::_mm_set1_ps(0.08)),
3558                );
3559                core::arch::x86_64::_mm_storeu_ps(out.as_mut_ptr(), acc);
3560            }
3561            out
3562        }
3563        #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
3564        {
3565            let mut out: [f32; 4] = [0.0; 4];
3566            // SAFETY: Stack `[f32; 4]` arrays are valid 16-byte values; `simd128` is enabled on `wasm32`.
3567            unsafe {
3568                let s04: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
3569                    core::arch::wasm32::v128_load(c0.as_ptr().cast()),
3570                    core::arch::wasm32::v128_load(c4.as_ptr().cast()),
3571                );
3572                let s13: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
3573                    core::arch::wasm32::v128_load(c1.as_ptr().cast()),
3574                    core::arch::wasm32::v128_load(c3.as_ptr().cast()),
3575                );
3576                let v2: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(
3577                    core::arch::wasm32::v128_load(c2.as_ptr().cast()),
3578                    core::arch::wasm32::f32x4_splat(0.40),
3579                );
3580                let acc: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
3581                    core::arch::wasm32::f32x4_add(
3582                        v2,
3583                        core::arch::wasm32::f32x4_mul(s13, core::arch::wasm32::f32x4_splat(0.22)),
3584                    ),
3585                    core::arch::wasm32::f32x4_mul(s04, core::arch::wasm32::f32x4_splat(0.08)),
3586                );
3587                core::arch::wasm32::v128_store(out.as_mut_ptr().cast(), acc);
3588            }
3589            out
3590        }
3591        #[cfg(not(target_arch = "aarch64"))]
3592        #[cfg(not(target_arch = "x86_64"))]
3593        #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
3594        {
3595            [
3596                (c0[0] + c4[0]).mul_add(0.08, (c1[0] + c3[0]).mul_add(0.22, c2[0] * 0.40)),
3597                (c0[1] + c4[1]).mul_add(0.08, (c1[1] + c3[1]).mul_add(0.22, c2[1] * 0.40)),
3598                (c0[2] + c4[2]).mul_add(0.08, (c1[2] + c3[2]).mul_add(0.22, c2[2] * 0.40)),
3599                0.0,
3600            ]
3601        }
3602    }
3603
3604    /// Runs the horizontal 5-tap Gaussian bloom blur plus wide anamorphic horizontal neon streak taps over a band of active rows.
3605    ///
3606    /// # Arguments
3607    ///
3608    /// - `usize` - Quarter-res bloom width `bw` (`>= 3`).
3609    /// - `&[[f32; 4]]` - Full source bloom buffer.
3610    /// - `usize` - Inclusive starting row `y_start`.
3611    /// - `&mut [[f32; 4]]` - Disjoint mutable output row band.
3612    fn blur_bloom_horiz_band(
3613        border_width: usize,
3614        src: &[[f32; 4]],
3615        y_start: usize,
3616        dst_band: &mut [[f32; 4]],
3617    ) {
3618        let band_rows: usize = dst_band.len() / border_width;
3619        let max_x: usize = border_width - 1;
3620        for local_y in 0..band_rows {
3621            let src_row_off: usize = (y_start + local_y) * border_width;
3622            let dst_row_off: usize = local_y * border_width;
3623            let src_row: &[[f32; 4]] = &src[src_row_off..(src_row_off + border_width)];
3624            let dst_row: &mut [[f32; 4]] = &mut dst_band[dst_row_off..(dst_row_off + border_width)];
3625            if border_width >= 17 {
3626                for pos_x in 0..8_usize {
3627                    let core: [f32; 4] = Self::blur_bloom_tap5(
3628                        src_row[pos_x.saturating_sub(2)],
3629                        src_row[pos_x.saturating_sub(1)],
3630                        src_row[pos_x],
3631                        src_row[(pos_x + 1).min(max_x)],
3632                        src_row[(pos_x + 2).min(max_x)],
3633                    );
3634                    let m4: [f32; 4] = src_row[pos_x.saturating_sub(4)];
3635                    let p4: [f32; 4] = src_row[(pos_x + 4).min(max_x)];
3636                    let m8: [f32; 4] = src_row[pos_x.saturating_sub(8)];
3637                    let p8: [f32; 4] = src_row[(pos_x + 8).min(max_x)];
3638                    dst_row[pos_x] = [
3639                        (m4[0] + p4[0]).mul_add(0.10, (m8[0] + p8[0]).mul_add(0.04, core[0])),
3640                        (m4[1] + p4[1]).mul_add(0.12, (m8[1] + p8[1]).mul_add(0.05, core[1])),
3641                        (m4[2] + p4[2]).mul_add(0.17, (m8[2] + p8[2]).mul_add(0.08, core[2])),
3642                        0.0,
3643                    ];
3644                }
3645                for pos_x in 8..(border_width - 8) {
3646                    let core: [f32; 4] = Self::blur_bloom_tap5(
3647                        src_row[pos_x - 2],
3648                        src_row[pos_x - 1],
3649                        src_row[pos_x],
3650                        src_row[pos_x + 1],
3651                        src_row[pos_x + 2],
3652                    );
3653                    let m4: [f32; 4] = src_row[pos_x - 4];
3654                    let p4: [f32; 4] = src_row[pos_x + 4];
3655                    let m8: [f32; 4] = src_row[pos_x - 8];
3656                    let p8: [f32; 4] = src_row[pos_x + 8];
3657                    dst_row[pos_x] = [
3658                        (m4[0] + p4[0]).mul_add(0.10, (m8[0] + p8[0]).mul_add(0.04, core[0])),
3659                        (m4[1] + p4[1]).mul_add(0.12, (m8[1] + p8[1]).mul_add(0.05, core[1])),
3660                        (m4[2] + p4[2]).mul_add(0.17, (m8[2] + p8[2]).mul_add(0.08, core[2])),
3661                        0.0,
3662                    ];
3663                }
3664                for pos_x in (border_width - 8)..border_width {
3665                    let core: [f32; 4] = Self::blur_bloom_tap5(
3666                        src_row[pos_x.saturating_sub(2)],
3667                        src_row[pos_x.saturating_sub(1)],
3668                        src_row[pos_x],
3669                        src_row[(pos_x + 1).min(max_x)],
3670                        src_row[(pos_x + 2).min(max_x)],
3671                    );
3672                    let m4: [f32; 4] = src_row[pos_x.saturating_sub(4)];
3673                    let p4: [f32; 4] = src_row[(pos_x + 4).min(max_x)];
3674                    let m8: [f32; 4] = src_row[pos_x.saturating_sub(8)];
3675                    let p8: [f32; 4] = src_row[(pos_x + 8).min(max_x)];
3676                    dst_row[pos_x] = [
3677                        (m4[0] + p4[0]).mul_add(0.10, (m8[0] + p8[0]).mul_add(0.04, core[0])),
3678                        (m4[1] + p4[1]).mul_add(0.12, (m8[1] + p8[1]).mul_add(0.05, core[1])),
3679                        (m4[2] + p4[2]).mul_add(0.17, (m8[2] + p8[2]).mul_add(0.08, core[2])),
3680                        0.0,
3681                    ];
3682                }
3683            } else {
3684                for pos_x in 0..border_width {
3685                    dst_row[pos_x] = Self::blur_bloom_tap5(
3686                        src_row[pos_x.saturating_sub(2)],
3687                        src_row[pos_x.saturating_sub(1)],
3688                        src_row[pos_x],
3689                        src_row[(pos_x + 1).min(max_x)],
3690                        src_row[(pos_x + 2).min(max_x)],
3691                    );
3692                }
3693            }
3694        }
3695    }
3696
3697    /// Runs the vertical 5-tap bloom blur pass over a band of rows with row-hoisted slices.
3698    ///
3699    /// # Arguments
3700    ///
3701    /// - `usize` - Quarter-res bloom width `bw`.
3702    /// - `usize` - Quarter-res bloom height `bh`.
3703    /// - `&[[f32; 4]]` - Full horizontally blurred bloom buffer.
3704    /// - `usize` - Inclusive starting row `y_start`.
3705    /// - `&mut [[f32; 4]]` - Disjoint mutable output row band.
3706    fn blur_bloom_vert_band(
3707        border_width: usize,
3708        bh: usize,
3709        src: &[[f32; 4]],
3710        y_start: usize,
3711        dst_band: &mut [[f32; 4]],
3712    ) {
3713        let band_rows: usize = dst_band.len() / border_width;
3714        let max_y: usize = bh - 1;
3715        for local_y in 0..band_rows {
3716            let coord_y: usize = y_start + local_y;
3717            let o0: usize = coord_y.saturating_sub(2) * border_width;
3718            let o1: usize = coord_y.saturating_sub(1) * border_width;
3719            let o2: usize = coord_y * border_width;
3720            let o3: usize = (coord_y + 1).min(max_y) * border_width;
3721            let o4: usize = (coord_y + 2).min(max_y) * border_width;
3722            let r0: &[[f32; 4]] = &src[o0..(o0 + border_width)];
3723            let r1: &[[f32; 4]] = &src[o1..(o1 + border_width)];
3724            let r2: &[[f32; 4]] = &src[o2..(o2 + border_width)];
3725            let r3: &[[f32; 4]] = &src[o3..(o3 + border_width)];
3726            let r4: &[[f32; 4]] = &src[o4..(o4 + border_width)];
3727            let dst_off: usize = local_y * border_width;
3728            let dst_row: &mut [[f32; 4]] = &mut dst_band[dst_off..(dst_off + border_width)];
3729            for pos_x in 0..border_width {
3730                dst_row[pos_x] =
3731                    Self::blur_bloom_tap5(r0[pos_x], r1[pos_x], r2[pos_x], r3[pos_x], r4[pos_x]);
3732            }
3733        }
3734    }
3735
3736    /// Tests whether row `by` is marked active in the 576-bit `bloom_row_bits` mask (or falls past 576 rows).
3737    ///
3738    /// # Arguments
3739    ///
3740    /// - `&[u64; 9]` - Snapshot of non-zero bloom row bitmask.
3741    /// - `usize` - Quarter-res bloom row index `by`.
3742    ///
3743    /// # Returns
3744    ///
3745    /// - `bool` - `true` when row `by` may contain non-zero HDR bloom radiance.
3746    #[inline(always)]
3747    #[must_use]
3748    fn bloom_row_is_active(bits: &[u64; 9], by: usize) -> bool {
3749        let word: usize = by >> 6;
3750        if word >= bits.len() {
3751            return true;
3752        }
3753        (bits[word] & (1_u64 << (by & 63))) != 0
3754    }
3755
3756    /// Runs a sparse-row SIMD 5-tap separable Gaussian bloom blur fused with `bloom_tile_active` generation, skipping empty rows completely.
3757    ///
3758    /// # Arguments
3759    ///
3760    /// - `usize` - Quarter-res bloom width.
3761    /// - `usize` - Quarter-res bloom height.
3762    /// - `&mut [[f32; 4]]` - Input bloom buffer (receives final blurred output).
3763    /// - `&mut [[f32; 4]]` - Intermediate horizontal scratch buffer.
3764    /// - `&mut [u8]` - Output tile-activity mask (`len >= bw * bh`).
3765    /// - `&[u64; 9]` - Active input row bitmask populated during Barrier 2.
3766    ///
3767    /// # Returns
3768    ///
3769    /// - `bool` - `true` when at least one bloom tile requires compositing in Barrier 3.
3770    #[must_use]
3771    fn blur_bloom_and_mask(
3772        border_width: usize,
3773        bh: usize,
3774        buf_a: &mut [[f32; 4]],
3775        buf_b: &mut [[f32; 4]],
3776        tile_active: &mut [u8],
3777        row_bits: &[u64; 9],
3778    ) -> bool {
3779        let min_len: usize = border_width * bh;
3780        if border_width < 3
3781            || bh < 3
3782            || buf_a.len() < min_len
3783            || buf_b.len() < min_len
3784            || tile_active.len() < min_len
3785        {
3786            return false;
3787        }
3788        if min_len >= 96_000 && bh >= 64 {
3789            let grain: usize = (bh / 16).clamp(8, 24);
3790            let src_a: &[[f32; 4]] = &buf_a[..min_len];
3791            let dst_b_base: usize = buf_b.as_mut_ptr() as usize;
3792            parallel_for_ranges(bh, grain, |y0: usize, y1: usize| {
3793                // SAFETY: `parallel_for_ranges` partitions `0..bh` into disjoint row bands within `buf_b[..min_len]`.
3794                let out_band: &mut [[f32; 4]] = unsafe {
3795                    from_raw_parts_mut(
3796                        (dst_b_base as *mut [f32; 4]).add(y0 * border_width),
3797                        (y1 - y0) * border_width,
3798                    )
3799                };
3800                Self::blur_bloom_horiz_band(border_width, src_a, y0, out_band);
3801            });
3802            let src_b: &[[f32; 4]] = &buf_b[..min_len];
3803            let dst_a_base: usize = buf_a.as_mut_ptr() as usize;
3804            parallel_for_ranges(bh, grain, |y0: usize, y1: usize| {
3805                // SAFETY: `parallel_for_ranges` partitions `0..bh` into disjoint row bands within `buf_a[..min_len]`.
3806                let out_band: &mut [[f32; 4]] = unsafe {
3807                    from_raw_parts_mut(
3808                        (dst_a_base as *mut [f32; 4]).add(y0 * border_width),
3809                        (y1 - y0) * border_width,
3810                    )
3811                };
3812                Self::blur_bloom_vert_band(border_width, bh, src_b, y0, out_band);
3813            });
3814            return Self::build_bloom_tile_mask(border_width, bh, &buf_a[..min_len], tile_active);
3815        }
3816        let max_y: usize = bh - 1;
3817        let max_x: usize = border_width - 1;
3818        for coord_y in 0..bh {
3819            let r_off: usize = coord_y * border_width;
3820            if Self::bloom_row_is_active(row_bits, coord_y) {
3821                Self::blur_bloom_horiz_band(
3822                    border_width,
3823                    &buf_a[..min_len],
3824                    coord_y,
3825                    &mut buf_b[r_off..(r_off + border_width)],
3826                );
3827            } else {
3828                let near_active: bool =
3829                    Self::bloom_row_is_active(row_bits, coord_y.saturating_sub(2))
3830                        || Self::bloom_row_is_active(row_bits, coord_y.saturating_sub(1))
3831                        || Self::bloom_row_is_active(row_bits, (coord_y + 1).min(max_y))
3832                        || Self::bloom_row_is_active(row_bits, (coord_y + 2).min(max_y));
3833                if near_active {
3834                    buf_b[r_off..(r_off + border_width)].fill([0.0; 4]);
3835                }
3836            }
3837        }
3838        let mut any_active: bool = false;
3839        let mut row_cell_hot: [u8; 1024] = [0; 1024];
3840        let mut prev_cell_hot: [u8; 1024] = [0; 1024];
3841        let use_fused_mask: bool = border_width <= 1024;
3842        for sample_y in 0..bh {
3843            let y_m2: usize = sample_y.saturating_sub(2);
3844            let y_m1: usize = sample_y.saturating_sub(1);
3845            let y_p1: usize = (sample_y + 1).min(max_y);
3846            let y_p2: usize = (sample_y + 2).min(max_y);
3847            let vert_active: bool = Self::bloom_row_is_active(row_bits, y_m2)
3848                || Self::bloom_row_is_active(row_bits, y_m1)
3849                || Self::bloom_row_is_active(row_bits, sample_y)
3850                || Self::bloom_row_is_active(row_bits, y_p1)
3851                || Self::bloom_row_is_active(row_bits, y_p2);
3852            let dst_off: usize = sample_y * border_width;
3853            if !vert_active {
3854                let adj_active: bool = sample_y > 0
3855                    && (Self::bloom_row_is_active(row_bits, sample_y.saturating_sub(3))
3856                        || Self::bloom_row_is_active(row_bits, y_m2)
3857                        || Self::bloom_row_is_active(row_bits, y_m1));
3858                if adj_active || !use_fused_mask {
3859                    buf_a[dst_off..(dst_off + border_width)].fill([0.0; 4]);
3860                }
3861                if use_fused_mask {
3862                    row_cell_hot[..border_width].fill(0);
3863                }
3864            } else {
3865                let r0: &[[f32; 4]] =
3866                    &buf_b[(y_m2 * border_width)..(y_m2 * border_width + border_width)];
3867                let r1: &[[f32; 4]] =
3868                    &buf_b[(y_m1 * border_width)..(y_m1 * border_width + border_width)];
3869                let r2: &[[f32; 4]] =
3870                    &buf_b[(sample_y * border_width)..(sample_y * border_width + border_width)];
3871                let r3: &[[f32; 4]] =
3872                    &buf_b[(y_p1 * border_width)..(y_p1 * border_width + border_width)];
3873                let r4: &[[f32; 4]] =
3874                    &buf_b[(y_p2 * border_width)..(y_p2 * border_width + border_width)];
3875                let dst_row: &mut [[f32; 4]] = &mut buf_a[dst_off..(dst_off + border_width)];
3876                for pos_x in 0..border_width {
3877                    let item_val: [f32; 4] = Self::blur_bloom_tap5(
3878                        r0[pos_x], r1[pos_x], r2[pos_x], r3[pos_x], r4[pos_x],
3879                    );
3880                    dst_row[pos_x] = item_val;
3881                    if use_fused_mask {
3882                        let hot: bool = item_val[0].max(item_val[1]).max(item_val[2]) >= 0.015;
3883                        row_cell_hot[pos_x] = u8::from(hot);
3884                    }
3885                }
3886            }
3887            if use_fused_mask && sample_y > 0 {
3888                let prev_off: usize = (sample_y - 1) * border_width;
3889                let mask_row: &mut [u8] = &mut tile_active[prev_off..(prev_off + border_width)];
3890                for bx in 0..border_width {
3891                    let bx1: usize = (bx + 1).min(max_x);
3892                    let active: u8 = prev_cell_hot[bx]
3893                        | prev_cell_hot[bx1]
3894                        | row_cell_hot[bx]
3895                        | row_cell_hot[bx1];
3896                    mask_row[bx] = active;
3897                    if active != 0 {
3898                        any_active = true;
3899                    }
3900                }
3901            }
3902            if use_fused_mask {
3903                prev_cell_hot[..border_width].copy_from_slice(&row_cell_hot[..border_width]);
3904            }
3905        }
3906        if use_fused_mask {
3907            let last_off: usize = max_y * border_width;
3908            let mask_row: &mut [u8] = &mut tile_active[last_off..(last_off + border_width)];
3909            for bx in 0..border_width {
3910                let bx1: usize = (bx + 1).min(max_x);
3911                let active: u8 = prev_cell_hot[bx] | prev_cell_hot[bx1];
3912                mask_row[bx] = active;
3913                if active != 0 {
3914                    any_active = true;
3915                }
3916            }
3917            any_active
3918        } else {
3919            Self::build_bloom_tile_mask(border_width, bh, &buf_a[..min_len], tile_active)
3920        }
3921    }
3922
3923    /// Computes 4-lane reciprocal square root `1 / sqrt(max(v, 1e-12))` via SSE2/scalar Newton-Raphson refinement.
3924    ///
3925    /// # Arguments
3926    ///
3927    /// - `[f32; 4]` - Four non-negative squared lengths.
3928    ///
3929    /// # Returns
3930    ///
3931    /// - `[f32; 4]` - 23-bit accurate reciprocal square roots.
3932    #[cfg(not(target_arch = "aarch64"))]
3933    #[cfg(not(target_arch = "x86_64"))]
3934    #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
3935    #[inline(always)]
3936    #[must_use]
3937    fn rsqrt_4x(item_val: [f32; 4]) -> [f32; 4] {
3938        [
3939            1.0 / item_val[0].max(1e-12).sqrt(),
3940            1.0 / item_val[1].max(1e-12).sqrt(),
3941            1.0 / item_val[2].max(1e-12).sqrt(),
3942            1.0 / item_val[3].max(1e-12).sqrt(),
3943        ]
3944    }
3945
3946    /// Computes 4-lane reciprocal `1.0 / max(v, 1e-6)` using NEON/SSE2/WASM SIMD128 vector division.
3947    ///
3948    /// # Arguments
3949    ///
3950    /// - `[f32; 4]` - Four denominator values.
3951    ///
3952    /// # Returns
3953    ///
3954    /// - `[f32; 4]` - Four reciprocals.
3955    #[inline(always)]
3956    #[must_use]
3957    fn recip_4x(item_val: [f32; 4]) -> [f32; 4] {
3958        #[cfg(target_arch = "aarch64")]
3959        {
3960            let mut out: [f32; 4] = [0.0; 4];
3961            // SAFETY: Stack `[f32; 4]` arrays are valid 16-byte values; NEON is mandatory on `aarch64`.
3962            unsafe {
3963                let pos_x: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmaxq_f32(
3964                    core::arch::aarch64::vld1q_f32(item_val.as_ptr()),
3965                    core::arch::aarch64::vdupq_n_f32(1e-6),
3966                );
3967                let inv: core::arch::aarch64::float32x4_t = Self::neon_rcp_4x(pos_x);
3968                core::arch::aarch64::vst1q_f32(out.as_mut_ptr(), inv);
3969            }
3970            out
3971        }
3972        #[cfg(target_arch = "x86_64")]
3973        {
3974            let mut out: [f32; 4] = [0.0; 4];
3975            // SAFETY: Stack `[f32; 4]` arrays are valid 16-byte values; SSE2 is mandatory on `x86_64`.
3976            unsafe {
3977                let coord_x: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ps(
3978                    core::arch::x86_64::_mm_loadu_ps(item_val.as_ptr()),
3979                    core::arch::x86_64::_mm_set1_ps(1e-6),
3980                );
3981                let inv: core::arch::x86_64::__m128 =
3982                    core::arch::x86_64::_mm_div_ps(core::arch::x86_64::_mm_set1_ps(1.0), coord_x);
3983                core::arch::x86_64::_mm_storeu_ps(out.as_mut_ptr(), inv);
3984            }
3985            out
3986        }
3987        #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
3988        {
3989            let mut out: [f32; 4] = [0.0; 4];
3990            // SAFETY: Stack `[f32; 4]` arrays are valid 16-byte values; `simd128` is enabled on `wasm32`.
3991            unsafe {
3992                let sample_x: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmax(
3993                    core::arch::wasm32::v128_load(item_val.as_ptr().cast()),
3994                    core::arch::wasm32::f32x4_splat(1e-6),
3995                );
3996                let inv: core::arch::wasm32::v128 =
3997                    core::arch::wasm32::f32x4_div(core::arch::wasm32::f32x4_splat(1.0), sample_x);
3998                core::arch::wasm32::v128_store(out.as_mut_ptr().cast(), inv);
3999            }
4000            out
4001        }
4002        #[cfg(not(target_arch = "aarch64"))]
4003        #[cfg(not(target_arch = "x86_64"))]
4004        #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
4005        {
4006            [
4007                1.0 / item_val[0].max(1e-6),
4008                1.0 / item_val[1].max(1e-6),
4009                1.0 / item_val[2].max(1e-6),
4010                1.0 / item_val[3].max(1e-6),
4011            ]
4012        }
4013    }
4014
4015    /// Computes horizontal sum across all 4 SSE2 `f32` lanes.
4016    ///
4017    /// # Arguments
4018    ///
4019    /// - `core::arch::x86_64::__m128` - Four-lane vector.
4020    ///
4021    /// # Returns
4022    ///
4023    /// - `f32` - Sum of all four lanes.
4024    #[cfg(target_arch = "x86_64")]
4025    #[inline(always)]
4026    pub(crate) unsafe fn sse_hsum_4x(item_val: core::arch::x86_64::__m128) -> f32 {
4027        // SAFETY: Caller guarantees `x86_64` SSE2 execution context.
4028        unsafe {
4029            let hi: core::arch::x86_64::__m128 =
4030                core::arch::x86_64::_mm_movehl_ps(item_val, item_val);
4031            let s1: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(item_val, hi);
4032            let s2: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ss(
4033                s1,
4034                core::arch::x86_64::_mm_shuffle_ps::<0x55>(s1, s1),
4035            );
4036            core::arch::x86_64::_mm_cvtss_f32(s2)
4037        }
4038    }
4039
4040    /// Computes horizontal minimum across all 4 SSE2 `f32` lanes.
4041    ///
4042    /// # Arguments
4043    ///
4044    /// - `core::arch::x86_64::__m128` - Four-lane vector.
4045    ///
4046    /// # Returns
4047    ///
4048    /// - `f32` - Minimum lane value.
4049    #[cfg(target_arch = "x86_64")]
4050    #[inline(always)]
4051    pub(crate) unsafe fn sse_hmin_4x(item_val: core::arch::x86_64::__m128) -> f32 {
4052        // SAFETY: Caller guarantees `x86_64` SSE2 execution context.
4053        unsafe {
4054            let hi: core::arch::x86_64::__m128 =
4055                core::arch::x86_64::_mm_movehl_ps(item_val, item_val);
4056            let m1: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_min_ps(item_val, hi);
4057            let m2: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_min_ss(
4058                m1,
4059                core::arch::x86_64::_mm_shuffle_ps::<0x55>(m1, m1),
4060            );
4061            core::arch::x86_64::_mm_cvtss_f32(m2)
4062        }
4063    }
4064
4065    /// Computes horizontal maximum across all 4 SSE2 `f32` lanes.
4066    ///
4067    /// # Arguments
4068    ///
4069    /// - `core::arch::x86_64::__m128` - Four-lane vector.
4070    ///
4071    /// # Returns
4072    ///
4073    /// - `f32` - Maximum lane value.
4074    #[cfg(target_arch = "x86_64")]
4075    #[inline(always)]
4076    pub(crate) unsafe fn sse_hmax_4x(item_val: core::arch::x86_64::__m128) -> f32 {
4077        // SAFETY: Caller guarantees `x86_64` SSE2 execution context.
4078        unsafe {
4079            let hi: core::arch::x86_64::__m128 =
4080                core::arch::x86_64::_mm_movehl_ps(item_val, item_val);
4081            let m1: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ps(item_val, hi);
4082            let m2: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ss(
4083                m1,
4084                core::arch::x86_64::_mm_shuffle_ps::<0x55>(m1, m1),
4085            );
4086            core::arch::x86_64::_mm_cvtss_f32(m2)
4087        }
4088    }
4089
4090    /// Evaluates linear interpolation `a + (b - a) * t` across 4 SSE2 lanes.
4091    ///
4092    /// # Arguments
4093    ///
4094    /// - `core::arch::x86_64::__m128` - Start vector `a`.
4095    /// - `core::arch::x86_64::__m128` - End vector `b`.
4096    /// - `core::arch::x86_64::__m128` - Blend factor `t`.
4097    ///
4098    /// # Returns
4099    ///
4100    /// - `core::arch::x86_64::__m128` - Interpolated vector.
4101    #[cfg(target_arch = "x86_64")]
4102    #[inline(always)]
4103    unsafe fn sse_lerp_4x(
4104        alpha_val: core::arch::x86_64::__m128,
4105        blue_val: core::arch::x86_64::__m128,
4106        blend_factor: core::arch::x86_64::__m128,
4107    ) -> core::arch::x86_64::__m128 {
4108        // SAFETY: Caller guarantees `x86_64` SSE2 execution context.
4109        unsafe {
4110            core::arch::x86_64::_mm_add_ps(
4111                alpha_val,
4112                core::arch::x86_64::_mm_mul_ps(
4113                    core::arch::x86_64::_mm_sub_ps(blue_val, alpha_val),
4114                    blend_factor,
4115                ),
4116            )
4117        }
4118    }
4119
4120    /// Computes horizontal sum across all 4 WebAssembly SIMD128 `f32` lanes.
4121    ///
4122    /// # Arguments
4123    ///
4124    /// - `core::arch::wasm32::v128` - Four-lane `f32x4` vector.
4125    ///
4126    /// # Returns
4127    ///
4128    /// - `f32` - Sum of all four lanes.
4129    #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
4130    #[inline(always)]
4131    pub(crate) fn wasm_hsum_4x(item_val: core::arch::wasm32::v128) -> f32 {
4132        (core::arch::wasm32::f32x4_extract_lane::<0>(item_val)
4133            + core::arch::wasm32::f32x4_extract_lane::<1>(item_val))
4134            + (core::arch::wasm32::f32x4_extract_lane::<2>(item_val)
4135                + core::arch::wasm32::f32x4_extract_lane::<3>(item_val))
4136    }
4137
4138    /// Computes horizontal minimum across all 4 WebAssembly SIMD128 `f32` lanes.
4139    ///
4140    /// # Arguments
4141    ///
4142    /// - `core::arch::wasm32::v128` - Four-lane `f32x4` vector.
4143    ///
4144    /// # Returns
4145    ///
4146    /// - `f32` - Minimum lane value.
4147    #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
4148    #[inline(always)]
4149    pub(crate) fn wasm_hmin_4x(item_val: core::arch::wasm32::v128) -> f32 {
4150        core::arch::wasm32::f32x4_extract_lane::<0>(item_val)
4151            .min(core::arch::wasm32::f32x4_extract_lane::<1>(item_val))
4152            .min(
4153                core::arch::wasm32::f32x4_extract_lane::<2>(item_val)
4154                    .min(core::arch::wasm32::f32x4_extract_lane::<3>(item_val)),
4155            )
4156    }
4157
4158    /// Computes horizontal maximum across all 4 WebAssembly SIMD128 `f32` lanes.
4159    ///
4160    /// # Arguments
4161    ///
4162    /// - `core::arch::wasm32::v128` - Four-lane `f32x4` vector.
4163    ///
4164    /// # Returns
4165    ///
4166    /// - `f32` - Maximum lane value.
4167    #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
4168    #[inline(always)]
4169    pub(crate) fn wasm_hmax_4x(item_val: core::arch::wasm32::v128) -> f32 {
4170        core::arch::wasm32::f32x4_extract_lane::<0>(item_val)
4171            .max(core::arch::wasm32::f32x4_extract_lane::<1>(item_val))
4172            .max(
4173                core::arch::wasm32::f32x4_extract_lane::<2>(item_val)
4174                    .max(core::arch::wasm32::f32x4_extract_lane::<3>(item_val)),
4175            )
4176    }
4177
4178    /// Evaluates linear interpolation `a + (b - a) * t` across 4 WebAssembly SIMD128 lanes.
4179    ///
4180    /// # Arguments
4181    ///
4182    /// - `core::arch::wasm32::v128` - Start vector `a`.
4183    /// - `core::arch::wasm32::v128` - End vector `b`.
4184    /// - `core::arch::wasm32::v128` - Blend factor `t`.
4185    ///
4186    /// # Returns
4187    ///
4188    /// - `core::arch::wasm32::v128` - Interpolated vector.
4189    #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
4190    #[inline(always)]
4191    fn wasm_lerp_4x(
4192        alpha_val: core::arch::wasm32::v128,
4193        blue_val: core::arch::wasm32::v128,
4194        blend_factor: core::arch::wasm32::v128,
4195    ) -> core::arch::wasm32::v128 {
4196        core::arch::wasm32::f32x4_add(
4197            alpha_val,
4198            core::arch::wasm32::f32x4_mul(
4199                core::arch::wasm32::f32x4_sub(blue_val, alpha_val),
4200                blend_factor,
4201            ),
4202        )
4203    }
4204
4205    /// Evaluates linear interpolation `a + (b - a) * t` across 4 NEON lanes.
4206    ///
4207    /// # Arguments
4208    ///
4209    /// - `core::arch::aarch64::float32x4_t` - Start vector `a`.
4210    /// - `core::arch::aarch64::float32x4_t` - End vector `b`.
4211    /// - `core::arch::aarch64::float32x4_t` - Blend factor `t`.
4212    ///
4213    /// # Returns
4214    ///
4215    /// - `core::arch::aarch64::float32x4_t` - Interpolated vector.
4216    #[cfg(target_arch = "aarch64")]
4217    #[inline(always)]
4218    unsafe fn neon_lerp_4x(
4219        alpha_val: core::arch::aarch64::float32x4_t,
4220        blue_val: core::arch::aarch64::float32x4_t,
4221        blend_factor: core::arch::aarch64::float32x4_t,
4222    ) -> core::arch::aarch64::float32x4_t {
4223        // SAFETY: Caller guarantees ARM64 NEON execution context.
4224        unsafe {
4225            core::arch::aarch64::vfmaq_f32(
4226                alpha_val,
4227                core::arch::aarch64::vsubq_f32(blue_val, alpha_val),
4228                blend_factor,
4229            )
4230        }
4231    }
4232
4233    /// Evaluates architectural curtain-wall mullions, multi-hue interior office depth gradients, and illuminated ground-floor retail storefronts for one world point.
4234    ///
4235    /// Analytically integrates a periodic unit-period pulse `[edge_a, edge_b)` over a pixel footprint `filter_w` so high-frequency stripes and window grids converge smoothly to their exact average coverage `edge_b - edge_a` at Nyquist without shimmering.
4236    ///
4237    /// # Arguments
4238    ///
4239    /// - `f32` - Continuous periodic pattern coordinate.
4240    /// - `f32` - Pulse rising edge inside `[0.0, 1.0)`.
4241    /// - `f32` - Pulse falling edge inside `(edge_a, 1.0]`.
4242    /// - `f32` - Screen-space derivative width in pattern-space units.
4243    ///
4244    /// # Returns
4245    ///
4246    /// - `f32` - Analytical box-filtered coverage in `[0.0, 1.0]`.
4247    #[inline(always)]
4248    #[must_use]
4249    fn box_pulse(coord: f32, edge_a: f32, edge_b: f32, filter_w: f32) -> f32 {
4250        let width: f32 = edge_b - edge_a;
4251        let fw: f32 = filter_w.max(1.0e-4);
4252        let x0: f32 = coord - 0.5 * fw;
4253        let x1: f32 = coord + 0.5 * fw;
4254        let f0: f32 = x0.floor();
4255        let f1: f32 = x1.floor();
4256        let i0: f32 = f0 * width + (x0 - f0 - edge_a).clamp(0.0, width);
4257        let i1: f32 = f1 * width + (x1 - f1 - edge_a).clamp(0.0, width);
4258        ((i1 - i0) / fw).clamp(0.0, 1.0)
4259    }
4260
4261    /// Analytically integrates a single non-periodic interval `[lo, hi]` over a pixel footprint `filter_w`.
4262    ///
4263    /// # Arguments
4264    ///
4265    /// - `f32` - Continuous coordinate.
4266    /// - `f32` - Interval lower bound.
4267    /// - `f32` - Interval upper bound.
4268    /// - `f32` - Pixel footprint width in coordinate units.
4269    ///
4270    /// # Returns
4271    ///
4272    /// - `f32` - Analytical box-filtered interval coverage in `[0.0, 1.0]`.
4273    #[inline(always)]
4274    #[must_use]
4275    fn box_band(coord: f32, lo: f32, hi: f32, filter_w: f32) -> f32 {
4276        let fw: f32 = filter_w.max(1.0e-4);
4277        let x0: f32 = coord - 0.5 * fw;
4278        let x1: f32 = coord + 0.5 * fw;
4279        ((x1.min(hi) - x0.max(lo)) / fw).clamp(0.0, 1.0)
4280    }
4281
4282    /// Analytically integrates a step transition at `edge` over a pixel footprint `filter_w`.
4283    ///
4284    /// # Arguments
4285    ///
4286    /// - `f32` - Continuous coordinate.
4287    /// - `f32` - Step transition position.
4288    /// - `f32` - Pixel footprint width in coordinate units.
4289    ///
4290    /// # Returns
4291    ///
4292    /// - `f32` - Analytical box-filtered step coverage in `[0.0, 1.0]`.
4293    #[inline(always)]
4294    #[must_use]
4295    fn box_step(coord: f32, edge: f32, filter_w: f32) -> f32 {
4296        let fw: f32 = filter_w.max(1.0e-4);
4297        ((coord - edge) / fw + 0.5).clamp(0.0, 1.0)
4298    }
4299
4300    /// Evaluates architectural curtain-wall glazing, sunlit office interiors, metallic mullions, and warm storefront bays with analytical Nyquist box-filter anti-aliasing and per-cell coherence blending.
4301    ///
4302    /// # Arguments
4303    ///
4304    /// - `(f32, f32, f32, f32)` - `(u_coord, world_y, depth, inv_height)`.
4305    /// - `(Vec3, Vec3, f32)` - Base `(albedo, emissive, reflectivity)`.
4306    ///
4307    /// # Returns
4308    ///
4309    /// - `(Vec3, Vec3, f32)` - Updated `(albedo, emissive, reflectivity)`.
4310    #[inline(always)]
4311    #[must_use]
4312    fn eval_facade_detail(
4313        coords: (f32, f32, f32, f32),
4314        surf: (Vec3, Vec3, f32),
4315    ) -> (Vec3, Vec3, f32) {
4316        let (u_coord, world_y, depth, inv_height): (f32, f32, f32, f32) = coords;
4317        let (base, emissive, refl): (Vec3, Vec3, f32) = surf;
4318        let world_px_size: f32 = (depth * inv_height * 2.10).max(0.015);
4319        if world_y > 0.25 && world_y < 3.25 {
4320            let su: f32 = u_coord * 0.34;
4321            let su_fl: f32 = su.floor();
4322            let fy: f32 = (world_y - 0.25) * (1.0 / 3.0);
4323            let fw_su: f32 = world_px_size * 0.34;
4324            let fw_fy: f32 = world_px_size * (1.0 / 3.0);
4325            let pu: f32 = Self::box_pulse(su, 0.08, 0.92, fw_su);
4326            let pv: f32 = Self::box_band(fy, 0.08, 0.92, fw_fy);
4327            let pane_w: f32 = (pu * pv).clamp(0.0, 1.0);
4328            let frame_col: Vec3 = base.scale(0.55);
4329            if pane_w > 0.01 {
4330                let shop_h: u32 = ((su_fl as i32).wrapping_mul(73_856_093)) as u32;
4331                let cell_coh: f32 = (1.0 - ((fw_su - 0.22) * (1.0 / 0.56)).clamp(0.0, 1.0)).powi(2);
4332                let grad: f32 = (1.12 - fy * 0.52).clamp(0.45, 1.15);
4333                let shop_glow: Vec3 = match shop_h % 5 {
4334                    0 | 1 => Vec3::new(1.18, 0.78, 0.36),
4335                    2 => Vec3::new(0.28, 0.88, 1.18),
4336                    3 => Vec3::new(1.12, 0.32, 0.68),
4337                    _ => Vec3::new(0.0, 0.0, 0.0),
4338                };
4339                let avg_shop: Vec3 = Vec3::new(0.75, 0.55, 0.52);
4340                let eff_glow: Vec3 = avg_shop.lerp(shop_glow, cell_coh);
4341                let next_base: Vec3 = frame_col.lerp(base.scale(0.42), pane_w);
4342                let next_em: Vec3 = emissive.add(eff_glow.scale(pane_w * grad * 0.92));
4343                return (next_base, next_em, (refl + 0.34 * pane_w).min(0.95));
4344            }
4345            return (frame_col, emissive, refl * 0.65);
4346        }
4347        if world_y < 3.45 {
4348            return (base.scale(0.68), emissive, refl * 0.75);
4349        }
4350        let su: f32 = u_coord * 0.48;
4351        let su_fl: f32 = su.floor();
4352        let sy: f32 = world_y * 0.33;
4353        let sy_fl: f32 = sy.floor();
4354        let fy_win: f32 = sy - sy_fl;
4355        let fw_su: f32 = world_px_size * 0.48;
4356        let fw_sy: f32 = world_px_size * 0.33;
4357        let pane_u: f32 = Self::box_pulse(su, 0.14, 0.86, fw_su);
4358        let pane_v: f32 = Self::box_pulse(sy, 0.18, 0.84, fw_sy);
4359        let pane_w: f32 = (pane_u * pane_v).clamp(0.0, 1.0);
4360        let spandrel_cov: f32 = Self::box_pulse(sy, 0.14, 0.88, fw_sy);
4361        let spandrel_shade: f32 = 0.70 + 0.14 * spandrel_cov;
4362        let wall_base: Vec3 = base.scale(spandrel_shade);
4363        if pane_w <= 0.01 {
4364            return (wall_base, emissive, refl * 0.72);
4365        }
4366        let cell_fw: f32 = fw_su.max(fw_sy);
4367        let ct: f32 = ((cell_fw - 0.18) * (1.0 / 0.56)).clamp(0.0, 1.0);
4368        let cell_coh: f32 = 1.0 - ct * ct * (3.0 - 2.0 * ct);
4369        let cell_x: i32 = su_fl as i32;
4370        let cell_y: i32 = sy_fl as i32;
4371        let h_bits: u32 = ((cell_x.wrapping_mul(73_856_093))
4372            ^ (cell_y.wrapping_mul(19_349_663))
4373            ^ ((cell_x.wrapping_add(cell_y)).wrapping_mul(83_492_791)))
4374            as u32;
4375        let bucket: u32 = h_bits % 11;
4376        let room_level: f32 = 0.68 + (((h_bits >> 8) & 15) as f32) * 0.032;
4377        let blind_grad: f32 = (0.48 + 0.66 * (1.0 - fy_win)).clamp(0.38, 1.14);
4378        let room_scale: f32 = room_level * (0.78 + (blind_grad - 0.78) * cell_coh);
4379        let (cell_tint, cell_em, cell_refl_add): (f32, Vec3, f32) = match bucket {
4380            0 | 4 => (0.86, Vec3::new(1.24, 0.86, 0.42).scale(room_scale), 0.14),
4381            1 => (0.84, Vec3::new(0.28, 0.86, 1.24).scale(room_scale), 0.18),
4382            2 => (
4383                0.88,
4384                Vec3::new(0.96, 0.94, 0.88).scale(room_scale * 0.82),
4385                0.16,
4386            ),
4387            3 => (
4388                0.84,
4389                Vec3::new(1.06, 0.34, 0.72).scale(room_scale * 0.86),
4390                0.18,
4391            ),
4392            _ => (
4393                (0.36 + 0.22 * fy_win).clamp(0.32, 0.62),
4394                Vec3::new(0.0, 0.0, 0.0),
4395                0.36,
4396            ),
4397        };
4398        let avg_tint: f32 = 0.64;
4399        let avg_em: Vec3 = Vec3::new(0.32, 0.27, 0.24);
4400        let avg_refl_add: f32 = 0.27;
4401        let eff_tint: f32 = avg_tint + (cell_tint - avg_tint) * cell_coh;
4402        let eff_em: Vec3 = avg_em.lerp(cell_em, cell_coh);
4403        let eff_refl_add: f32 = avg_refl_add + (cell_refl_add - avg_refl_add) * cell_coh;
4404        (
4405            wall_base.lerp(base.scale(eff_tint), pane_w),
4406            emissive.add(eff_em.scale(pane_w)),
4407            (refl + eff_refl_add * pane_w).min(0.96),
4408        )
4409    }
4410
4411    /// Evaluates continuous closed-loop stadium arc length for boulevard markings and streetlights.
4412    ///
4413    /// # Arguments
4414    ///
4415    /// - `f32` - World X coordinate in meters.
4416    /// - `f32` - World Z coordinate in meters.
4417    ///
4418    /// # Returns
4419    ///
4420    /// - `f32` - Continuous arc-length coordinate `road_s` along the 962.12m closed loop.
4421    #[inline(always)]
4422    #[must_use]
4423    fn eval_loop_arc_s(wpx: f32, wpz: f32) -> f32 {
4424        if wpz < -140.0 {
4425            let ry: f32 = -(wpz + 140.0);
4426            let rx: f32 = -(wpx - 64.0);
4427            let rx_safe: f32 = if rx.abs() < 1.0e-5 && ry.abs() < 1.0e-5 {
4428                1.0
4429            } else {
4430                rx
4431            };
4432            return 140.0 + 64.0 * ry.atan2(rx_safe);
4433        }
4434        if wpz > 140.0 {
4435            let ry: f32 = wpz - 140.0;
4436            let rx: f32 = wpx - 64.0;
4437            let rx_safe: f32 = if rx.abs() < 1.0e-5 && ry.abs() < 1.0e-5 {
4438                1.0
4439            } else {
4440                rx
4441            };
4442            return 621.06193 + 64.0 * ry.atan2(rx_safe);
4443        }
4444        if wpx <= 64.0 { -wpz } else { 481.06193 + wpz }
4445    }
4446
4447    /// Evaluates physically-based closed-loop wet boulevard asphalt with a 3-zone wetness model (dry matte aggregate, capillary-darkened porous damp halo, and crisp meniscus standing water with Beer-Lambert depth tint, Snell refraction parallax, animated micro-ripples, and physical `F0 = 0.02` Schlick Fresnel), seamless stadium markings, tiled sidewalks, and the eastern sunlit coastal ocean bay.
4448    ///
4449    /// # Arguments
4450    ///
4451    /// - `(f32, f32, f32, f32)` - `(world_x, world_z, depth, inv_height)`.
4452    /// - `(Vec3, f32, f32, f32)` - `(view_dir, fresnel_t, metallic, world_time_secs)`.
4453    /// - `Vec3` - Base road material albedo.
4454    ///
4455    /// # Returns
4456    ///
4457    /// - `(Vec3, f32)` - Updated `(albedo, calibrated_reflectivity)`.
4458    #[inline(always)]
4459    #[must_use]
4460    fn eval_road_detail(
4461        coords: (f32, f32, f32, f32),
4462        optics: (Vec3, f32, f32, f32),
4463        base: Vec3,
4464    ) -> (Vec3, f32) {
4465        let (wpx, wpz, depth, inv_height): (f32, f32, f32, f32) = coords;
4466        let (view_dir, fresnel_t, metallic, world_time): (Vec3, f32, f32, f32) = optics;
4467        let world_px_size: f32 = (depth * inv_height * 2.10).max(0.018);
4468        let fw_x: f32 = world_px_size * 1.15;
4469        let fw_z: f32 = world_px_size * 2.35;
4470        let fw_xz: f32 = fw_x.hypot(fw_z);
4471        let spine_z: f32 = wpz.clamp(-140.0, 140.0);
4472        let rel_x: f32 = wpx - 64.0;
4473        let rel_z: f32 = wpz - spine_z;
4474        let d_spine: f32 = rel_x.hypot(rel_z);
4475        let road_u: f32 = d_spine - 64.0;
4476        let abs_u: f32 = road_u.abs();
4477        let (rad_x, rad_z): (f32, f32) = if d_spine > 1.0e-4 {
4478            (rel_x / d_spine, rel_z / d_spine)
4479        } else {
4480            (-1.0, 0.0)
4481        };
4482        let tan_x: f32 = -rad_z;
4483        let tan_z: f32 = rad_x;
4484        let fw_u: f32 = (rad_x.abs() * fw_x + rad_z.abs() * fw_z).max(0.015);
4485        let arc_scale: f32 = if wpz.abs() > 140.0 {
4486            64.0 / d_spine.max(16.0)
4487        } else {
4488            1.0
4489        };
4490        let fw_s: f32 = ((tan_x.abs() * fw_x + tan_z.abs() * fw_z) * arc_scale).max(0.015);
4491        let refl_fresnel: f32 = (0.18 + 0.82 * fresnel_t + metallic * 0.25).clamp(0.18, 0.95);
4492        let inv_refl_f: f32 = 1.0 / refl_fresnel;
4493        let f_water: f32 = 0.02 + 0.98 * fresnel_t;
4494        let d_bay_t: f32 = ((d_spine - 77.8) * (1.0 / 0.6)).clamp(0.0, 1.0);
4495        let bay_w: f32 =
4496            Self::box_step(wpx, 144.0, fw_x) * (d_bay_t * d_bay_t * (3.0 - 2.0 * d_bay_t));
4497        if bay_w >= 0.999 {
4498            let shore_d: f32 = (wpx - 144.0).max(0.0);
4499            let shallow_t: f32 = Self::fast_exp_neg_3d(shore_d * 0.055);
4500            let deep_col: Vec3 = Vec3::new(0.005, 0.044, 0.118);
4501            let shallow_col: Vec3 = Vec3::new(0.018, 0.165, 0.205);
4502            let warp_a: f32 = Self::sky_value_noise(
4503                wpx * 0.075 - world_time * 0.14,
4504                wpz * 0.065 + world_time * 0.09,
4505            ) * 2.4;
4506            let wave_p: f32 =
4507                (wpx * 0.23 + wpz * 0.11 + warp_a - world_time * 1.35).sin() * 0.5 + 0.5;
4508            let cloud_var: f32 = 0.84
4509                + 0.24
4510                    * Self::sky_value_noise(
4511                        wpx * 0.018 - world_time * 0.025,
4512                        wpz * 0.018 + world_time * 0.015,
4513                    );
4514            let sw_t: f32 = (shore_d * (1.0 / 1.8)).clamp(0.0, 1.0);
4515            let seawall_shadow: f32 = 0.46 + 0.54 * (sw_t * sw_t * (3.0 - 2.0 * sw_t));
4516            let body_col: Vec3 = deep_col
4517                .lerp(shallow_col, shallow_t)
4518                .scale((0.92 + 0.16 * wave_p) * cloud_var * seawall_shadow);
4519            let surf_n: f32 = Self::sky_value_noise(
4520                wpx * 0.48 - world_time * 0.55,
4521                wpz * 0.34 + world_time * 0.18,
4522            );
4523            let surf_n2: f32 =
4524                Self::sky_value_noise(wpx * 1.35 + 3.1, wpz * 1.15 - world_time * 0.40);
4525            let surf_wave: f32 =
4526                (shore_d * 1.65 - world_time * 1.95 + surf_n * 3.4).sin() * 0.5 + 0.5;
4527            let shore_band: f32 = Self::fast_exp_neg_3d(shore_d * 0.38);
4528            let lace_t: f32 =
4529                ((surf_n * 0.62 + surf_n2 * 0.38 + shore_band * 0.42 - 0.32) * 2.5).clamp(0.0, 1.0);
4530            let lace: f32 = lace_t * lace_t * (3.0 - 2.0 * lace_t);
4531            let foam_aa: f32 = 1.0 - ((fw_xz - 0.25) * 1.0).clamp(0.0, 1.0);
4532            let foam_w: f32 = ((shore_band * (0.45 + 0.55 * surf_wave) * lace
4533                + Self::fast_exp_neg_3d(shore_d * 2.2) * 0.65)
4534                * foam_aa)
4535                .clamp(0.0, 0.94);
4536            let ocean_col: Vec3 = body_col.lerp(Vec3::new(0.84, 0.90, 0.94), foam_w);
4537            let ocean_refl: f32 = ((f_water * (1.0 - foam_w)) * inv_refl_f).clamp(0.0, 1.0);
4538            return (ocean_col, ocean_refl);
4539        }
4540        let tm: f32 = ((depth - 14.0) * (1.0 / 34.0)).clamp(0.0, 1.0);
4541        let micro_fade: f32 = (1.0 - tm * tm * (3.0 - 2.0 * tm))
4542            * (1.0 - ((fw_xz - 0.05) * (1.0 / 0.17)).clamp(0.0, 1.0));
4543        let agg_h: f32 = if micro_fade > 0.005 {
4544            let a0: f32 = Self::sky_value_noise(wpx * 8.5, wpz * 8.5);
4545            let a1: f32 = Self::sky_value_noise(wpx * 24.0 + 7.3, wpz * 24.0 - 4.1);
4546            a0.mul_add(0.48, a1 * 0.52)
4547        } else {
4548            0.5
4549        };
4550        let grain_n: f32 = agg_h - 0.5;
4551        let seam_u: f32 = Self::box_pulse(wpx * 0.45, 0.0, 0.045, fw_x * 0.45);
4552        let seam_v: f32 = Self::box_pulse(wpz * 0.45, 0.0, 0.045, fw_z * 0.45);
4553        let seam_cov: f32 = (seam_u + seam_v - seam_u * seam_v).clamp(0.0, 1.0);
4554        let tile_seam: f32 = 1.0 - 0.26 * seam_cov;
4555        if abs_u > 14.2 {
4556            let plaza_base: Vec3 = if d_spine < 64.0 {
4557                Vec3::new(0.32, 0.34, 0.37)
4558            } else {
4559                Vec3::new(0.26, 0.28, 0.32)
4560            };
4561            let east_mask: f32 = d_bay_t * d_bay_t * (3.0 - 2.0 * d_bay_t);
4562            let seawall_coping: f32 = Self::box_band(wpx, 142.4, 144.0, fw_x) * east_mask;
4563            let seawall_lip: f32 = Self::box_band(wpx, 143.65, 144.0, fw_x) * east_mask;
4564            let sea_spray: f32 = Self::fast_exp_neg_3d((144.0 - wpx).max(0.0) * 0.65) * east_mask;
4565            let coping_col: Vec3 = Vec3::new(0.42, 0.44, 0.46)
4566                .lerp(Vec3::new(0.22, 0.24, 0.27), seawall_lip)
4567                .scale(1.0 - 0.28 * sea_spray);
4568            let land_col: Vec3 = plaza_base
4569                .scale(tile_seam)
4570                .lerp(coping_col, seawall_coping)
4571                .scale(1.0 + grain_n * 0.10 * micro_fade);
4572            let land_refl: f32 = ((0.025 + 0.04 * fresnel_t) * inv_refl_f).clamp(0.0, 1.0);
4573            if bay_w <= 1.0e-4 {
4574                return (land_col, land_refl);
4575            }
4576            let shallow_col: Vec3 = Vec3::new(0.018, 0.165, 0.205);
4577            let ocean_refl: f32 = (f_water * inv_refl_f).clamp(0.0, 1.0);
4578            return (
4579                land_col.lerp(shallow_col, bay_w),
4580                land_refl * (1.0 - bay_w) + ocean_refl * bay_w,
4581            );
4582        }
4583        let road_s: f32 = Self::eval_loop_arc_s(wpx, wpz);
4584        let curb_w: f32 = Self::box_step(abs_u, 10.2, fw_u);
4585        let walk_w: f32 = Self::box_step(abs_u, 10.8, fw_u);
4586        let om_curb: f32 = 1.0 - curb_w;
4587        let inner_lin: f32 = 1.0 - ((abs_u - 3.65).abs() * 0.85).clamp(0.0, 1.0);
4588        let outer_lin: f32 = 1.0 - ((abs_u - 6.85).abs() * 0.95).clamp(0.0, 1.0);
4589        let tire_wear: f32 =
4590            (inner_lin * inner_lin + outer_lin * outer_lin).clamp(0.0, 1.0) * om_curb;
4591        let gutter_band: f32 = (1.0 - ((abs_u - 9.55).abs() * 2.2).clamp(0.0, 1.0)) * om_curb;
4592        let cpg_t: f32 = ((10.18 - abs_u) * (1.0 / 0.46)).clamp(0.0, 1.0);
4593        let curb_pool_guard: f32 = cpg_t * cpg_t * (3.0 - 2.0 * cpg_t);
4594        let center_crown: f32 = (1.0 - (abs_u * 0.65).clamp(0.0, 1.0)) * om_curb;
4595        let tp_fade: f32 = ((depth - 54.0) * (1.0 / 86.0)).clamp(0.0, 1.0);
4596        let puddle_fade: f32 = 1.0 - tp_fade * tp_fade * (3.0 - 2.0 * tp_fade);
4597        let (wet_porosity, water_mask, water_depth): (f32, f32, f32) =
4598            if puddle_fade > 1.0e-3 && om_curb > 1.0e-3 {
4599                let n0: f32 = Self::sky_value_noise(wpx * 0.13 + 3.1, wpz * 0.075 - 1.7);
4600                let n1: f32 = Self::sky_value_noise(wpx * 0.38 - 5.4, wpz * 0.22 + 2.9);
4601                let n2: f32 = Self::sky_value_noise(wpx * 1.45 + 8.7, wpz * 1.05 - 4.3);
4602                let wet_field: f32 =
4603                    n0 * 0.56 + n1 * 0.28 + n2 * 0.16 + tire_wear * 0.13 + gutter_band * 0.17
4604                        - center_crown * 0.22;
4605                let wp_t: f32 = ((wet_field - 0.45) * (1.0 / 0.15)).clamp(0.0, 1.0);
4606                let wp_val: f32 = wp_t * wp_t * (3.0 - 2.0 * wp_t) * om_curb * puddle_fade;
4607                let shore_micro: f32 =
4608                    grain_n * 0.058 * (0.28 + 0.72 * micro_fade) + (n2 - 0.5) * 0.045;
4609                let puddle_h: f32 = wet_field + shore_micro;
4610                let shore_w: f32 = (0.020 + fw_xz * 0.042).clamp(0.020, 0.095);
4611                let wm_t: f32 = ((puddle_h - (0.60 - shore_w)) / (2.0 * shore_w)).clamp(0.0, 1.0);
4612                let wm_val: f32 =
4613                    wm_t * wm_t * (3.0 - 2.0 * wm_t) * om_curb * curb_pool_guard * puddle_fade;
4614                let wd_val: f32 = ((wet_field - 0.58) * 3.8).clamp(0.0, 1.0) * wm_val;
4615                (wp_val, wm_val, wd_val)
4616            } else {
4617                (0.0, 0.0, 0.0)
4618            };
4619        let dry_base: Vec3 = Vec3::new(
4620            base.get_x().mul_add(1.38, 0.036),
4621            base.get_y().mul_add(1.38, 0.038),
4622            base.get_z().mul_add(1.38, 0.042),
4623        );
4624        let dry_scale: f32 = (1.0 + grain_n * 0.34 * micro_fade)
4625            * (1.0 - 0.14 * tire_wear)
4626            * (1.0 - 0.22 * gutter_band);
4627        let mut road_col: Vec3 = dry_base.scale(dry_scale);
4628        let yellow_w: f32 = Self::box_band(abs_u, 0.135, 0.305, fw_u) * om_curb;
4629        if yellow_w > 0.005 {
4630            let paint_vis: f32 = 0.94 + grain_n * 0.16 * micro_fade;
4631            road_col = road_col.lerp(
4632                Vec3::new(0.92, 0.65, 0.10).scale(paint_vis),
4633                yellow_w * 0.95,
4634            );
4635        }
4636        let dash_on: f32 = Self::box_pulse(road_s * 0.12472407, 0.0, 0.42, fw_s * 0.12472407);
4637        let lane_w: f32 = Self::box_band(abs_u, 4.565, 4.735, fw_u) * dash_on * om_curb;
4638        let shoulder_w: f32 = Self::box_band(abs_u, 9.15, 9.35, fw_u) * om_curb;
4639        let straight_t: f32 = ((134.0 - wpz.abs()) * 0.125).clamp(0.0, 1.0);
4640        let straight_w: f32 = straight_t * straight_t * (3.0 - 2.0 * straight_t);
4641        let cross_z_w: f32 = Self::box_pulse(
4642            (road_s + 18.0) * 0.02494481,
4643            0.455,
4644            0.545,
4645            fw_s * 0.02494481,
4646        ) * straight_w;
4647        let cross_x_w: f32 = Self::box_band(abs_u, 0.55, 8.65, fw_u);
4648        let cross_bar: f32 = Self::box_pulse(road_u * 0.85, 0.0, 0.50, fw_u * 0.85);
4649        let cross_w: f32 = cross_z_w * cross_x_w * cross_bar * 0.88 * om_curb;
4650        let white_w: f32 = shoulder_w.max(lane_w).max(cross_w);
4651        if white_w > 0.005 {
4652            let paint_vis: f32 = 0.92 + grain_n * 0.14 * micro_fade;
4653            road_col = road_col.lerp(Vec3::new(0.82, 0.85, 0.90).scale(paint_vis), white_w * 0.92);
4654        }
4655        let damp_col: Vec3 = Vec3::new(
4656            road_col.get_x().max(1.0e-4).powf(1.35) * 0.60,
4657            road_col.get_y().max(1.0e-4).powf(1.35) * 0.60,
4658            road_col.get_z().max(1.0e-4).powf(1.35) * 0.60,
4659        );
4660        let mut final_road_col: Vec3 = road_col.lerp(damp_col, wet_porosity);
4661        let mut ripple_mod: f32 = 0.0;
4662        if water_mask > 0.005 {
4663            let rf_d: f32 = 1.0 - ((depth - 24.0) * (1.0 / 48.0)).clamp(0.0, 1.0);
4664            let rf_w: f32 = ((water_depth - 0.03) * (1.0 / 0.23)).clamp(0.0, 1.0);
4665            let ripple_fade: f32 = rf_d * rf_d * (3.0 - 2.0 * rf_d) * rf_w;
4666            let (rx_rip, rz_rip): (f32, f32) = if ripple_fade > 0.005 {
4667                let rw1: f32 = wpx * 2.4 + wpz * 1.5 - world_time * 1.85;
4668                let rw2: f32 = -wpx * 1.8 + wpz * 3.1 - world_time * 2.35;
4669                let gx: f32 = ((rw1.cos() * 2.4 - rw2.cos() * 1.8) * 0.0028 * ripple_fade)
4670                    .clamp(-0.018, 0.018);
4671                let gz: f32 = ((rw1.cos() * 1.5 + rw2.cos() * 3.1) * 0.0028 * ripple_fade)
4672                    .clamp(-0.018, 0.018);
4673                ripple_mod = (gx + gz) * 1.6;
4674                (gx, gz)
4675            } else {
4676                (0.0, 0.0)
4677            };
4678            let inv_vy: f32 = 1.0 / (view_dir.get_y() + 0.35).max(0.35);
4679            let sh_x: f32 =
4680                -view_dir.get_x() * inv_vy * (water_depth * 0.032) + rx_rip * (water_depth * 1.65);
4681            let sh_z: f32 =
4682                -view_dir.get_z() * inv_vy * (water_depth * 0.032) + rz_rip * (water_depth * 1.65);
4683            let sub_u: f32 = road_u + sh_x * rad_x + sh_z * rad_z;
4684            let sub_abs_u: f32 = sub_u.abs();
4685            let sub_s: f32 = road_s + sh_x * tan_x + sh_z * tan_z;
4686            let mut sub_base: Vec3 = dry_base.scale(dry_scale);
4687            let sy_w: f32 = Self::box_band(sub_abs_u, 0.135, 0.305, fw_u) * om_curb;
4688            if sy_w > 0.005 {
4689                sub_base = sub_base.lerp(
4690                    Vec3::new(0.92, 0.65, 0.10).scale(0.92 + grain_n * 0.14 * micro_fade),
4691                    sy_w * 0.95,
4692                );
4693            }
4694            let sd_on: f32 = Self::box_pulse(sub_s * 0.12472407, 0.0, 0.42, fw_s * 0.12472407);
4695            let sl_w: f32 = Self::box_band(sub_abs_u, 4.565, 4.735, fw_u) * sd_on * om_curb;
4696            let ss_w: f32 = Self::box_band(sub_abs_u, 9.15, 9.35, fw_u) * om_curb;
4697            let sc_z: f32 =
4698                Self::box_pulse((sub_s + 18.0) * 0.02494481, 0.455, 0.545, fw_s * 0.02494481)
4699                    * straight_w;
4700            let sc_w: f32 = sc_z
4701                * Self::box_band(sub_abs_u, 0.55, 8.65, fw_u)
4702                * Self::box_pulse(sub_u * 0.85, 0.0, 0.50, fw_u * 0.85)
4703                * 0.88
4704                * om_curb;
4705            let sw_w: f32 = ss_w.max(sl_w).max(sc_w);
4706            if sw_w > 0.005 {
4707                sub_base = sub_base.lerp(
4708                    Vec3::new(0.82, 0.85, 0.90).scale(0.90 + grain_n * 0.12 * micro_fade),
4709                    sw_w * 0.92,
4710                );
4711            }
4712            let meniscus_t: f32 = (water_depth * (1.0 / 0.22)).clamp(0.0, 1.0);
4713            let meniscus_rim: f32 =
4714                1.0 - 0.18 * (1.0 - meniscus_t * meniscus_t * (3.0 - 2.0 * meniscus_t));
4715            let sub_col: Vec3 = Vec3::new(
4716                sub_base.get_x().max(1.0e-4).powf(1.35)
4717                    * 0.58
4718                    * Self::fast_exp_neg_3d(water_depth * 1.15)
4719                    * meniscus_rim,
4720                sub_base.get_y().max(1.0e-4).powf(1.35)
4721                    * 0.58
4722                    * Self::fast_exp_neg_3d(water_depth * 0.88)
4723                    * meniscus_rim,
4724                sub_base.get_z().max(1.0e-4).powf(1.35)
4725                    * 0.58
4726                    * Self::fast_exp_neg_3d(water_depth * 0.72)
4727                    * meniscus_rim,
4728            );
4729            final_road_col = final_road_col.lerp(sub_col, water_mask);
4730        }
4731        let dry_target: f32 = 0.015 + 0.03 * fresnel_t + tire_wear * 0.015;
4732        let damp_target: f32 = 0.04 + 0.22 * fresnel_t;
4733        let water_target: f32 = (f_water + ripple_mod).clamp(0.02, 0.82);
4734        let surf_target: f32 = dry_target * (1.0 - wet_porosity) + damp_target * wet_porosity;
4735        let road_target_blend: f32 = surf_target * (1.0 - water_mask) + water_target * water_mask;
4736        let road_refl: f32 = (road_target_blend * inv_refl_f).clamp(0.0, 1.0);
4737        if curb_w <= 1.0e-4 && walk_w <= 1.0e-4 {
4738            return (final_road_col, road_refl);
4739        }
4740        let curb_col: Vec3 = Vec3::new(0.38, 0.40, 0.44).scale(1.0 + grain_n * 0.10 * micro_fade);
4741        let walk_col: Vec3 =
4742            Vec3::new(0.25, 0.27, 0.31).scale(tile_seam * (1.0 + grain_n * 0.10 * micro_fade));
4743        let final_col: Vec3 = final_road_col.lerp(curb_col, curb_w).lerp(walk_col, walk_w);
4744        let walk_refl: f32 = ((0.025 + 0.04 * fresnel_t) * inv_refl_f).clamp(0.0, 1.0);
4745        let final_refl: f32 = road_refl * om_curb + walk_refl * curb_w;
4746        (final_col, final_refl)
4747    }
4748
4749    /// Fast rational approximation of `exp(-x)` for `x >= 0.0` used in 3D coastal ocean optics.
4750    ///
4751    /// # Arguments
4752    ///
4753    /// - `f32` - Non-negative exponent magnitude `x`.
4754    ///
4755    /// # Returns
4756    ///
4757    /// - `f32` - Approximate `exp(-x)` in `(0.0, 1.0]`.
4758    #[inline(always)]
4759    #[must_use]
4760    fn fast_exp_neg_3d(pos_x: f32) -> f32 {
4761        if pos_x <= 0.0 {
4762            return 1.0;
4763        }
4764        let x2: f32 = pos_x * pos_x;
4765        1.0 / (1.0 + pos_x + 0.48 * x2 + 0.235 * x2 * pos_x)
4766    }
4767
4768    /// Branchless minimax polynomial approximation of `(sin(phase), cos(phase))` for animated 3D ocean waves.
4769    ///
4770    /// # Arguments
4771    ///
4772    /// - `f32` - Input phase angle in radians.
4773    ///
4774    /// # Returns
4775    ///
4776    /// - `(f32, f32)` - Approximate `(sin(phase), cos(phase))`.
4777    #[inline(always)]
4778    #[must_use]
4779    fn fast_sin_cos_3d(phase: f32) -> (f32, f32) {
4780        let quad_f: f32 = (phase * (2.0 / PI)).round();
4781        let rem_rad: f32 = phase - quad_f * FRAC_PI_2;
4782        let rem_sq: f32 = rem_rad * rem_rad;
4783        let sin_rem: f32 = rem_rad
4784            * (1.0 + rem_sq * (-0.166_666_57 + rem_sq * (0.008_333_026 - rem_sq * 0.000_198_074)));
4785        let cos_rem: f32 = 1.0 + rem_sq * (-0.5 + rem_sq * (0.041_666_64 - rem_sq * 0.001_388_839));
4786        match (quad_f as i32) & 3 {
4787            0 => (sin_rem, cos_rem),
4788            1 => (cos_rem, -sin_rem),
4789            2 => (-sin_rem, -cos_rem),
4790            _ => (-cos_rem, sin_rem),
4791        }
4792    }
4793
4794    /// Evaluates photorealistic animated Beer-Lambert liquid ocean radiance matching `/water` optics: 5-octave multi-directional Gerstner waves, Schlick Fresnel reflections, emerald subsurface wave-crest glow, foreground caustics, GGX sun glitter, animated shoreline sea-foam, and marine horizon mist.
4795    ///
4796    /// # Arguments
4797    ///
4798    /// - `&DeferredFrameContext` - Immutable per-frame camera, sun, and animation clock context.
4799    /// - `&[[f32; 3]]` - Pre-baked hemi-octahedral sky dome LUT.
4800    /// - `(Vec3, Vec3, f32)` - `(world_pos, unit_view_to_camera, linear_depth)`.
4801    /// - `(f32, Vec3)` - `(sun_shadow, rt_probe_reflection)`.
4802    ///
4803    /// # Returns
4804    ///
4805    /// - `Vec3` - Linear HDR ocean surface radiance prior to exposure and ACES tonemapping.
4806    #[inline(always)]
4807    #[must_use]
4808    fn eval_ocean_water_radiance(
4809        frame_context: &DeferredFrameContext,
4810        sky_lut: &[[f32; 3]],
4811        geom: (Vec3, Vec3, f32),
4812        lighting: (f32, Vec3),
4813    ) -> Vec3 {
4814        let (world_p, view_dir, depth): (Vec3, Vec3, f32) = geom;
4815        let (shadow, rt_refl): (f32, Vec3) = lighting;
4816        let sim_t: f32 = frame_context.world_time_secs;
4817        let wx_orig: f32 = world_p.get_x();
4818        let wz_orig: f32 = world_p.get_z();
4819        let pixel_foot: f32 = depth * frame_context.inv_height * 2.15;
4820        let mut wx: f32 = wx_orig;
4821        let mut wz: f32 = wz_orig;
4822        let mut wave_h: f32 = 0.0;
4823        let mut dh_dx: f32 = 0.0;
4824        let mut dh_dz: f32 = 0.0;
4825        for wave in OCEAN3D_WAVE_SPECTRUM.iter() {
4826            let freq: f32 = wave[2];
4827            let aa_arg: f32 = pixel_foot * freq * 0.30;
4828            if aa_arg > 3.8 {
4829                break;
4830            }
4831            let dir_x: f32 = wave[0];
4832            let dir_z: f32 = wave[1];
4833            let amp: f32 = wave[3];
4834            let aa_sq: f32 = aa_arg * aa_arg;
4835            let aa_w: f32 = 1.0 / (1.0 + aa_sq);
4836            let phase: f32 = (wx * dir_x + wz * dir_z) * freq + sim_t * wave[4];
4837            let (sin_p, cos_p): (f32, f32) = Self::fast_sin_cos_3d(phase);
4838            let sharp_e: f32 = Self::fast_exp_neg_3d(1.0 - sin_p);
4839            wave_h += amp * (sharp_e - 0.40) * aa_w;
4840            let slope: f32 = amp * freq * sharp_e * cos_p * aa_w;
4841            dh_dx += slope * dir_x;
4842            dh_dz += slope * dir_z;
4843            let warp_s: f32 = cos_p * amp * 0.78 * aa_w;
4844            wx += warp_s * dir_x;
4845            wz += warp_s * dir_z;
4846        }
4847        if pixel_foot < 0.90 {
4848            let cap_aa: f32 = 1.0 / (1.0 + (pixel_foot * 3.8) * (pixel_foot * 3.8));
4849            let c1: f32 = Self::fast_sin_cos_3d(wx_orig * 2.6 + wz_orig * 3.8 + sim_t * 3.4).1
4850                * 0.085
4851                * cap_aa;
4852            let c2: f32 = Self::fast_sin_cos_3d(-wx_orig * 3.4 + wz_orig * 4.2 - sim_t * 4.1).1
4853                * 0.068
4854                * cap_aa;
4855            dh_dx += c1 * 0.58 - c2 * 0.62;
4856            dh_dz += c1 * 0.81 + c2 * 0.78;
4857        }
4858        let near_steep: f32 = 1.48 + 0.58 * Self::fast_exp_neg_3d(depth * 0.015);
4859        dh_dx *= near_steep;
4860        dh_dz *= near_steep;
4861        let inv_nlen: f32 = 1.0 / (dh_dx * dh_dx + 1.0 + dh_dz * dh_dz).sqrt();
4862        let nx: f32 = -dh_dx * inv_nlen;
4863        let ny: f32 = inv_nlen;
4864        let nz: f32 = -dh_dz * inv_nlen;
4865        let vx: f32 = view_dir.get_x();
4866        let vy: f32 = view_dir.get_y();
4867        let vz: f32 = view_dir.get_z();
4868        let ndv: f32 = (nx * vx + ny * vy + nz * vz).clamp(0.004, 1.0);
4869        let om_ndv: f32 = 1.0 - ndv;
4870        let om2: f32 = om_ndv * om_ndv;
4871        let fresnel: f32 = (0.0204 + 0.9796 * om2 * om2 * om_ndv).clamp(0.024, 0.84);
4872        let two_ndv: f32 = 2.0 * ndv;
4873        let refl_dir: Vec3 = Vec3::new(
4874            two_ndv * nx - vx,
4875            (two_ndv * ny - vy).max(0.010),
4876            two_ndv * nz - vz,
4877        );
4878        let sky_raw: Vec3 = Self::sample_sky_lut(sky_lut, refl_dir, &frame_context.sun);
4879        let sun_dir: Vec3 = frame_context.sun.get_direction();
4880        let sun_col: Vec3 = frame_context.sun.get_color();
4881        let sun_luma: f32 =
4882            (sun_col.get_x() * 0.30 + sun_col.get_y() * 0.55 + sun_col.get_z() * 0.15)
4883                .clamp(0.45, 1.40);
4884        let az_dx: f32 = refl_dir.get_x() - sun_dir.get_x();
4885        let az_dz: f32 = refl_dir.get_z() - sun_dir.get_z();
4886        let az_dist_sq: f32 = az_dx * az_dx + az_dz * az_dz;
4887        let sun_az_glow: f32 = Self::fast_exp_neg_3d(az_dist_sq * 48.0);
4888        let sky_elev: f32 = (refl_dir.get_y() * 2.4).clamp(0.0, 1.0);
4889        let sky_fade: f32 = 1.0 - sky_elev * 0.72;
4890        let marine_refl: Vec3 = Vec3::new(
4891            ((0.003 * sky_fade + 0.18 * sun_az_glow) * sun_luma)
4892                + sky_raw.get_x().min(1.2) * (0.025 + 0.14 * sun_az_glow),
4893            ((0.068 * sky_fade + 0.16 * sun_az_glow) * sun_luma)
4894                + sky_raw.get_y().min(1.2) * (0.12 + 0.10 * sun_az_glow),
4895            ((0.142 * sky_fade + 0.11 * sun_az_glow) * sun_luma)
4896                + sky_raw.get_z().min(1.2) * (0.20 + 0.08 * sun_az_glow),
4897        );
4898        let near_sss: f32 = 0.24 + 0.76 * Self::fast_exp_neg_3d(depth * 0.0065);
4899        let crest_elev: f32 = ((wave_h + 0.075) * 3.35).clamp(0.0, 1.0);
4900        let sss_back: f32 =
4901            (-(vx * sun_dir.get_x() + vy * sun_dir.get_y() + vz * sun_dir.get_z()) * 0.5 + 0.5)
4902                .clamp(0.0, 1.0);
4903        let sss_term: f32 = crest_elev * crest_elev * (0.42 + 0.58 * sss_back) * near_sss;
4904        let caustic: f32 = if depth < 76.0 {
4905            let cf: f32 = Self::fast_exp_neg_3d(depth * 0.036) * (1.0 - fresnel);
4906            let c_warp: f32 =
4907                Self::sky_value_noise(wx_orig * 0.24 + sim_t * 0.18, wz_orig * 0.24 - sim_t * 0.14)
4908                    * 2.8;
4909            let ca: f32 =
4910                Self::fast_sin_cos_3d(wx_orig * 0.62 + wz_orig * 0.44 + c_warp + sim_t * 1.15).0;
4911            let cb: f32 = Self::fast_sin_cos_3d(
4912                -wx_orig * 0.48 + wz_orig * 0.78 - c_warp * 0.7 - sim_t * 0.92,
4913            )
4914            .1;
4915            let cn: f32 = (ca * 0.55 + cb * 0.45).abs();
4916            cn * cn * cf * 0.16
4917        } else {
4918            0.0
4919        };
4920        let body_col: Vec3 = Vec3::new(
4921            (0.0004 + 0.0020 * sss_term) * sun_luma,
4922            (0.052 + 0.365 * sss_term + caustic * 0.92) * sun_luma,
4923            (0.105 + 0.480 * sss_term + caustic * 1.14) * sun_luma,
4924        );
4925        let hx_u: f32 = vx + sun_dir.get_x();
4926        let hy_u: f32 = vy + sun_dir.get_y();
4927        let hz_u: f32 = vz + sun_dir.get_z();
4928        let inv_hlen: f32 = 1.0 / (hx_u * hx_u + hy_u * hy_u + hz_u * hz_u).sqrt().max(1.0e-5);
4929        let ndh: f32 = ((nx * hx_u + ny * hy_u + nz * hz_u) * inv_hlen).max(0.0);
4930        let ndh2: f32 = ndh * ndh;
4931        let a1_sq: f32 = 0.000_095;
4932        let d1_den: f32 = ndh2 * (a1_sq - 1.0) + 1.0;
4933        let ggx_tight: f32 = (a1_sq / (PI * d1_den * d1_den)).min(28.0);
4934        let a2_sq: f32 = 0.000_52;
4935        let d2_den: f32 = ndh2 * (a2_sq - 1.0) + 1.0;
4936        let ggx_mid: f32 = (a2_sq / (PI * d2_den * d2_den)).min(5.2);
4937        let glint_t: f32 = ((ndh - 0.980) * (1.0 / 0.018)).clamp(0.0, 1.0);
4938        let glint_sharp: f32 = glint_t * glint_t * (3.0 - 2.0 * glint_t);
4939        let spec_scale: f32 =
4940            (ggx_tight * 0.56 + ggx_mid * 0.12 + glint_sharp * 0.68) * (0.45 + 0.55 * shadow);
4941        let spec_col: Vec3 = sun_col.scale(spec_scale);
4942        let near_shore_rt: f32 = Self::fast_exp_neg_3d(depth * 0.026) * 0.24;
4943        let combined_refl: Vec3 = marine_refl.lerp(rt_refl, near_shore_rt);
4944        let refl_weight: f32 = (fresnel * 0.50 + 0.022).clamp(0.022, 0.58);
4945        let mut col: Vec3 = body_col.lerp(combined_refl, refl_weight).add(spec_col);
4946        let dx_shore: f32 = (wx_orig.abs() - CITY_ISLAND_HALF_X).max(0.0);
4947        let dz_shore: f32 = (CITY_ISLAND_Z_MIN - wz_orig)
4948            .max(0.0)
4949            .max((wz_orig - CITY_ISLAND_Z_MAX).max(0.0));
4950        if dx_shore < 4.8 && dz_shore < 4.8 {
4951            let shore_dist: f32 = (dx_shore * dx_shore + dz_shore * dz_shore).sqrt();
4952            if shore_dist < 4.8 {
4953                let surge: f32 =
4954                    Self::fast_sin_cos_3d(sim_t * 2.1 + wx_orig * 0.35 + wz_orig * 0.35).0 * 0.55;
4955                let eff_dist: f32 = (shore_dist + surge).max(0.0);
4956                let band_lin: f32 = 1.0 - (eff_dist * (1.0 / 3.6)).clamp(0.0, 1.0);
4957                let foam_band: f32 = band_lin * band_lin;
4958                let lacy_a: f32 = Self::sky_value_noise(wx_orig * 1.45 + 3.7, wz_orig * 1.45 - 2.1);
4959                let lacy_b: f32 = Self::sky_value_noise(
4960                    wx_orig * 3.8 - sim_t * 0.55,
4961                    wz_orig * 3.8 + sim_t * 0.42,
4962                );
4963                let foam_t: f32 = ((lacy_a * 0.55 + lacy_b * 0.45 - 0.36) * 2.4).clamp(0.0, 1.0);
4964                let foam_alpha: f32 =
4965                    (foam_band * (0.28 + 0.72 * foam_t * foam_t * (3.0 - 2.0 * foam_t)) * 0.84)
4966                        .clamp(0.0, 0.85);
4967                if foam_alpha > 0.01 {
4968                    let foam_col: Vec3 = Vec3::new(0.84, 0.90, 0.94).scale(0.65 + 0.45 * sun_luma);
4969                    col = col.lerp(foam_col, foam_alpha);
4970                }
4971            }
4972        }
4973        if frame_context.fog_on {
4974            let fog_t: f32 = (1.0 - Self::fast_exp_neg_3d(depth * 0.000_65)).clamp(0.0, 0.22);
4975            if fog_t > 0.005 {
4976                let horiz_raw: Vec3 = frame_context.sun.get_sky_horizon();
4977                let marine_mist: Vec3 = Vec3::new(
4978                    (0.010 + 0.06 * sun_az_glow) * sun_luma + horiz_raw.get_x().min(1.0) * 0.05,
4979                    (0.068 + 0.05 * sun_az_glow) * sun_luma + horiz_raw.get_y().min(1.0) * 0.12,
4980                    (0.118 + 0.04 * sun_az_glow) * sun_luma + horiz_raw.get_z().min(1.0) * 0.18,
4981                );
4982                col = col.lerp(marine_mist, fog_t);
4983            }
4984        }
4985        col
4986    }
4987
4988    /// Evaluates a pipelined 4-wide reciprocal `1.0 / x` via NEON estimate plus one Newton-Raphson refinement (~22-bit precision, eliminating divider stalls).
4989    ///
4990    /// # Arguments
4991    ///
4992    /// - `core::arch::aarch64::float32x4_t` - Strictly positive denominator vector `x`.
4993    ///
4994    /// # Returns
4995    ///
4996    /// - `core::arch::aarch64::float32x4_t` - Refined 4-wide reciprocal `1.0 / x`.
4997    #[cfg(target_arch = "aarch64")]
4998    #[inline(always)]
4999    pub(crate) unsafe fn neon_rcp_4x(
5000        pos_x: core::arch::aarch64::float32x4_t,
5001    ) -> core::arch::aarch64::float32x4_t {
5002        // SAFETY: Caller guarantees ARM64 NEON execution context and positive `x`.
5003        unsafe {
5004            let est: core::arch::aarch64::float32x4_t = core::arch::aarch64::vrecpeq_f32(pos_x);
5005            core::arch::aarch64::vmulq_f32(est, core::arch::aarch64::vrecpsq_f32(pos_x, est))
5006        }
5007    }
5008
5009    /// Const-specialized vectorized 4-pixel Cook-Torrance GGX PBR, procedural surface detail (`0=Plain`, `1=Road`, `2=Facade`), reflection, volumetric fog, and ACES tonemap kernel reading from L1 `RunScratch32` at `off`.
5010    ///
5011    /// # Arguments
5012    ///
5013    /// - `&DeferredFrameContext` - Shared per-frame camera, sun, and fog configuration.
5014    /// - `&GShadeTri` - Precomputed triangle PBR record shared by the run.
5015    /// - `(Vec3, Vec3)` - Starting unnormalized primary ray and horizontal ray step `(raw_ray, ray_dx)`.
5016    /// - `(&RunScratch32, usize)` - L1-hot run scratch and 4-pixel-aligned lane offset `off <= 28`.
5017    /// - `SpanShadeOut<'_>` - Writable 16-byte RGBA, 4-byte luma, and optional HDR bloom slot.
5018    ///
5019    /// # Returns
5020    ///
5021    /// - `bool` - `true` when the optional bloom slot received non-zero HDR excess radiance.
5022    #[inline(always)]
5023    fn shade_span_4x_specialized<const DETAIL: u8>(
5024        frame_context: &DeferredFrameContext,
5025        tri: &GShadeTri,
5026        rays: (Vec3, Vec3),
5027        src_run: (&RunScratch32, usize),
5028        dst: SpanShadeOut<'_>,
5029    ) -> bool {
5030        let (raw_ray, ray_dx): (Vec3, Vec3) = rays;
5031        let (run, off): (&RunScratch32, usize) = src_run;
5032        let SpanShadeOut {
5033            rgba: c_dst,
5034            luma: l_dst,
5035            bloom: bloom_slot,
5036        } = dst;
5037        let sun_dir: Vec3 = frame_context.sun.get_direction();
5038        let sun_col: Vec3 = frame_context.sun.get_color();
5039        let sky_horizon: Vec3 = frame_context.sun.get_sky_horizon();
5040        let sn: Vec3 = tri.shade_n;
5041        let mut exp_r_arr: [f32; 4] = [0.0; 4];
5042        let mut exp_g_arr: [f32; 4] = [0.0; 4];
5043        let mut exp_b_arr: [f32; 4] = [0.0; 4];
5044        #[cfg(target_arch = "aarch64")]
5045        {
5046            // SAFETY: Stack `[f32; 4]` and 16-byte-aligned `RunScratch32` (`off <= 28`) are valid; NEON is mandatory on `aarch64`.
5047            unsafe {
5048                let zero: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(0.0);
5049                let one: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(1.0);
5050                let two: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(2.0);
5051                let lane_idx_arr: [f32; 4] = [0.0, 1.0, 2.0, 3.0];
5052                let lane_idx: core::arch::aarch64::float32x4_t =
5053                    core::arch::aarch64::vld1q_f32(lane_idx_arr.as_ptr());
5054                let rx: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5055                    core::arch::aarch64::vdupq_n_f32(raw_ray.get_x()),
5056                    core::arch::aarch64::vdupq_n_f32(ray_dx.get_x()),
5057                    lane_idx,
5058                );
5059                let ry: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5060                    core::arch::aarch64::vdupq_n_f32(raw_ray.get_y()),
5061                    core::arch::aarch64::vdupq_n_f32(ray_dx.get_y()),
5062                    lane_idx,
5063                );
5064                let rz: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5065                    core::arch::aarch64::vdupq_n_f32(raw_ray.get_z()),
5066                    core::arch::aarch64::vdupq_n_f32(ray_dx.get_z()),
5067                    lane_idx,
5068                );
5069                let len_sq: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmaxq_f32(
5070                    core::arch::aarch64::vfmaq_f32(
5071                        core::arch::aarch64::vfmaq_f32(
5072                            core::arch::aarch64::vmulq_f32(rz, rz),
5073                            ry,
5074                            ry,
5075                        ),
5076                        rx,
5077                        rx,
5078                    ),
5079                    core::arch::aarch64::vdupq_n_f32(1e-12),
5080                );
5081                let mut inv_l: core::arch::aarch64::float32x4_t =
5082                    core::arch::aarch64::vrsqrteq_f32(len_sq);
5083                inv_l = core::arch::aarch64::vmulq_f32(
5084                    inv_l,
5085                    core::arch::aarch64::vrsqrtsq_f32(
5086                        core::arch::aarch64::vmulq_f32(len_sq, inv_l),
5087                        inv_l,
5088                    ),
5089                );
5090                let ndv_num: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5091                    core::arch::aarch64::vdupq_n_f32(-sn.dot(raw_ray)),
5092                    core::arch::aarch64::vdupq_n_f32(-sn.dot(ray_dx)),
5093                    lane_idx,
5094                );
5095                let ndv_raw: core::arch::aarch64::float32x4_t =
5096                    core::arch::aarch64::vmulq_f32(ndv_num, inv_l);
5097                let ndv: core::arch::aarch64::float32x4_t = core::arch::aarch64::vminq_f32(
5098                    core::arch::aarch64::vmaxq_f32(ndv_raw, core::arch::aarch64::vdupq_n_f32(0.02)),
5099                    one,
5100                );
5101                let f_om: core::arch::aarch64::float32x4_t =
5102                    core::arch::aarch64::vsubq_f32(one, ndv);
5103                let f_om2: core::arch::aarch64::float32x4_t =
5104                    core::arch::aarch64::vmulq_f32(f_om, f_om);
5105                let fresnel_t: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
5106                    core::arch::aarch64::vmulq_f32(f_om2, f_om2),
5107                    f_om,
5108                );
5109                let vdl_num: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5110                    core::arch::aarch64::vdupq_n_f32(-sun_dir.dot(raw_ray)),
5111                    core::arch::aarch64::vdupq_n_f32(-sun_dir.dot(ray_dx)),
5112                    lane_idx,
5113                );
5114                let vdl: core::arch::aarch64::float32x4_t =
5115                    core::arch::aarch64::vmulq_f32(vdl_num, inv_l);
5116                let sh_v: core::arch::aarch64::float32x4_t =
5117                    core::arch::aarch64::vld1q_f32(run.shadow.as_ptr().add(off));
5118                let (spec_r, spec_g, spec_b): (
5119                    core::arch::aarch64::float32x4_t,
5120                    core::arch::aarch64::float32x4_t,
5121                    core::arch::aarch64::float32x4_t,
5122                ) = if tri.n_dot_l > 0.0 {
5123                    let ndl_v: core::arch::aarch64::float32x4_t =
5124                        core::arch::aarch64::vdupq_n_f32(tri.n_dot_l);
5125                    let ndh_u: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmaxq_f32(
5126                        core::arch::aarch64::vaddq_f32(ndl_v, ndv_raw),
5127                        zero,
5128                    );
5129                    let h_lsq: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmaxq_f32(
5130                        core::arch::aarch64::vfmaq_f32(two, two, vdl),
5131                        core::arch::aarch64::vdupq_n_f32(1e-6),
5132                    );
5133                    let ndh_sq: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
5134                        core::arch::aarch64::vmulq_f32(ndh_u, ndh_u),
5135                        Self::neon_rcp_4x(h_lsq),
5136                    );
5137                    let ggx_den: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5138                        one,
5139                        ndh_sq,
5140                        core::arch::aarch64::vdupq_n_f32(tri.alpha2 - 1.0),
5141                    );
5142                    let ggx_term: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5143                        core::arch::aarch64::vdupq_n_f32(1e-4),
5144                        core::arch::aarch64::vmulq_f32(ggx_den, ggx_den),
5145                        core::arch::aarch64::vdupq_n_f32(PI),
5146                    );
5147                    let vis_den: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5148                        core::arch::aarch64::vdupq_n_f32(0.08),
5149                        ndv,
5150                        core::arch::aarch64::vdupq_n_f32(tri.n_dot_l.max(0.06)),
5151                    );
5152                    let spec_num: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
5153                        core::arch::aarch64::vdupq_n_f32(0.25 * tri.alpha2 * tri.n_dot_l),
5154                        sh_v,
5155                    );
5156                    let spec_s: core::arch::aarch64::float32x4_t = core::arch::aarch64::vminq_f32(
5157                        core::arch::aarch64::vmulq_f32(
5158                            spec_num,
5159                            Self::neon_rcp_4x(core::arch::aarch64::vmulq_f32(ggx_term, vis_den)),
5160                        ),
5161                        core::arch::aarch64::vdupq_n_f32(4.5),
5162                    );
5163                    let fr_r: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5164                        core::arch::aarch64::vdupq_n_f32(tri.f0.get_x()),
5165                        core::arch::aarch64::vdupq_n_f32(1.0 - tri.f0.get_x()),
5166                        fresnel_t,
5167                    );
5168                    let fr_g: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5169                        core::arch::aarch64::vdupq_n_f32(tri.f0.get_y()),
5170                        core::arch::aarch64::vdupq_n_f32(1.0 - tri.f0.get_y()),
5171                        fresnel_t,
5172                    );
5173                    let fr_b: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5174                        core::arch::aarch64::vdupq_n_f32(tri.f0.get_z()),
5175                        core::arch::aarch64::vdupq_n_f32(1.0 - tri.f0.get_z()),
5176                        fresnel_t,
5177                    );
5178                    (
5179                        core::arch::aarch64::vmulq_f32(
5180                            fr_r,
5181                            core::arch::aarch64::vmulq_f32(
5182                                core::arch::aarch64::vdupq_n_f32(sun_col.get_x()),
5183                                spec_s,
5184                            ),
5185                        ),
5186                        core::arch::aarch64::vmulq_f32(
5187                            fr_g,
5188                            core::arch::aarch64::vmulq_f32(
5189                                core::arch::aarch64::vdupq_n_f32(sun_col.get_y()),
5190                                spec_s,
5191                            ),
5192                        ),
5193                        core::arch::aarch64::vmulq_f32(
5194                            fr_b,
5195                            core::arch::aarch64::vmulq_f32(
5196                                core::arch::aarch64::vdupq_n_f32(sun_col.get_z()),
5197                                spec_s,
5198                            ),
5199                        ),
5200                    )
5201                } else {
5202                    (zero, zero, zero)
5203                };
5204                let d_v: core::arch::aarch64::float32x4_t =
5205                    core::arch::aarch64::vld1q_f32(run.depths.as_ptr().add(off));
5206                let wpy: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5207                    core::arch::aarch64::vdupq_n_f32(frame_context.camera_position.get_y()),
5208                    ry,
5209                    d_v,
5210                );
5211                let mut sb_r: core::arch::aarch64::float32x4_t =
5212                    core::arch::aarch64::vdupq_n_f32(tri.mat_base.get_x());
5213                let mut sb_g: core::arch::aarch64::float32x4_t =
5214                    core::arch::aarch64::vdupq_n_f32(tri.mat_base.get_y());
5215                let mut sb_b: core::arch::aarch64::float32x4_t =
5216                    core::arch::aarch64::vdupq_n_f32(tri.mat_base.get_z());
5217                let mut em_r: core::arch::aarch64::float32x4_t =
5218                    core::arch::aarch64::vdupq_n_f32(tri.mat_emissive.get_x());
5219                let mut em_g: core::arch::aarch64::float32x4_t =
5220                    core::arch::aarch64::vdupq_n_f32(tri.mat_emissive.get_y());
5221                let mut em_b: core::arch::aarch64::float32x4_t =
5222                    core::arch::aarch64::vdupq_n_f32(tri.mat_emissive.get_z());
5223                let mut s_refl: core::arch::aarch64::float32x4_t =
5224                    core::arch::aarch64::vdupq_n_f32(tri.mat_refl);
5225                if DETAIL == 2 {
5226                    let u_coord_v: core::arch::aarch64::float32x4_t = if sn.get_x().abs() > 0.5 {
5227                        core::arch::aarch64::vfmaq_f32(
5228                            core::arch::aarch64::vdupq_n_f32(frame_context.camera_position.get_z()),
5229                            rz,
5230                            d_v,
5231                        )
5232                    } else {
5233                        core::arch::aarch64::vfmaq_f32(
5234                            core::arch::aarch64::vdupq_n_f32(frame_context.camera_position.get_x()),
5235                            rx,
5236                            d_v,
5237                        )
5238                    };
5239                    let mut u_a: [f32; 4] = [0.0; 4];
5240                    let mut y_a: [f32; 4] = [0.0; 4];
5241                    let mut d_a: [f32; 4] = [0.0; 4];
5242                    core::arch::aarch64::vst1q_f32(u_a.as_mut_ptr(), u_coord_v);
5243                    core::arch::aarch64::vst1q_f32(y_a.as_mut_ptr(), wpy);
5244                    core::arch::aarch64::vst1q_f32(d_a.as_mut_ptr(), d_v);
5245                    let mut nr_a: [f32; 4] = [0.0; 4];
5246                    let mut ng_a: [f32; 4] = [0.0; 4];
5247                    let mut nb_a: [f32; 4] = [0.0; 4];
5248                    let mut er_a: [f32; 4] = [0.0; 4];
5249                    let mut eg_a: [f32; 4] = [0.0; 4];
5250                    let mut eb_a: [f32; 4] = [0.0; 4];
5251                    let mut rf_a: [f32; 4] = [0.0; 4];
5252                    for lane in 0..4usize {
5253                        let (sb, em, rf): (Vec3, Vec3, f32) = Self::eval_facade_detail(
5254                            (u_a[lane], y_a[lane], d_a[lane], frame_context.inv_height),
5255                            (tri.mat_base, tri.mat_emissive, tri.mat_refl),
5256                        );
5257                        nr_a[lane] = sb.get_x();
5258                        ng_a[lane] = sb.get_y();
5259                        nb_a[lane] = sb.get_z();
5260                        er_a[lane] = em.get_x();
5261                        eg_a[lane] = em.get_y();
5262                        eb_a[lane] = em.get_z();
5263                        rf_a[lane] = rf;
5264                    }
5265                    sb_r = core::arch::aarch64::vld1q_f32(nr_a.as_ptr());
5266                    sb_g = core::arch::aarch64::vld1q_f32(ng_a.as_ptr());
5267                    sb_b = core::arch::aarch64::vld1q_f32(nb_a.as_ptr());
5268                    em_r = core::arch::aarch64::vld1q_f32(er_a.as_ptr());
5269                    em_g = core::arch::aarch64::vld1q_f32(eg_a.as_ptr());
5270                    em_b = core::arch::aarch64::vld1q_f32(eb_a.as_ptr());
5271                    s_refl = core::arch::aarch64::vld1q_f32(rf_a.as_ptr());
5272                } else if DETAIL == 1 {
5273                    let m_r: core::arch::aarch64::uint32x4_t = core::arch::aarch64::vcltq_f32(
5274                        core::arch::aarch64::vabsq_f32(wpy),
5275                        core::arch::aarch64::vdupq_n_f32(0.15),
5276                    );
5277                    if core::arch::aarch64::vmaxvq_u32(m_r) != 0 {
5278                        let wpx_v: core::arch::aarch64::float32x4_t =
5279                            core::arch::aarch64::vfmaq_f32(
5280                                core::arch::aarch64::vdupq_n_f32(
5281                                    frame_context.camera_position.get_x(),
5282                                ),
5283                                rx,
5284                                d_v,
5285                            );
5286                        let wpz_v: core::arch::aarch64::float32x4_t =
5287                            core::arch::aarch64::vfmaq_f32(
5288                                core::arch::aarch64::vdupq_n_f32(
5289                                    frame_context.camera_position.get_z(),
5290                                ),
5291                                rz,
5292                                d_v,
5293                            );
5294                        let mut x_a: [f32; 4] = [0.0; 4];
5295                        let mut z_a: [f32; 4] = [0.0; 4];
5296                        let mut d_a: [f32; 4] = [0.0; 4];
5297                        let mut rx_a: [f32; 4] = [0.0; 4];
5298                        let mut ry_a: [f32; 4] = [0.0; 4];
5299                        let mut rz_a: [f32; 4] = [0.0; 4];
5300                        let mut ft_a: [f32; 4] = [0.0; 4];
5301                        let mut m_a: [u32; 4] = [0; 4];
5302                        core::arch::aarch64::vst1q_f32(x_a.as_mut_ptr(), wpx_v);
5303                        core::arch::aarch64::vst1q_f32(z_a.as_mut_ptr(), wpz_v);
5304                        core::arch::aarch64::vst1q_f32(d_a.as_mut_ptr(), d_v);
5305                        core::arch::aarch64::vst1q_f32(rx_a.as_mut_ptr(), rx);
5306                        core::arch::aarch64::vst1q_f32(ry_a.as_mut_ptr(), ry);
5307                        core::arch::aarch64::vst1q_f32(rz_a.as_mut_ptr(), rz);
5308                        core::arch::aarch64::vst1q_f32(ft_a.as_mut_ptr(), fresnel_t);
5309                        core::arch::aarch64::vst1q_u32(m_a.as_mut_ptr(), m_r);
5310                        let mut nr_a: [f32; 4] = [tri.mat_base.get_x(); 4];
5311                        let mut ng_a: [f32; 4] = [tri.mat_base.get_y(); 4];
5312                        let mut nb_a: [f32; 4] = [tri.mat_base.get_z(); 4];
5313                        let mut rf_a: [f32; 4] = [tri.mat_refl; 4];
5314                        for lane in 0..4usize {
5315                            if m_a[lane] != 0 {
5316                                let (sb, rf): (Vec3, f32) = Self::eval_road_detail(
5317                                    (x_a[lane], z_a[lane], d_a[lane], frame_context.inv_height),
5318                                    (
5319                                        Vec3::new(-rx_a[lane], -ry_a[lane], -rz_a[lane]),
5320                                        ft_a[lane],
5321                                        tri.metallic,
5322                                        frame_context.world_time_secs,
5323                                    ),
5324                                    tri.mat_base,
5325                                );
5326                                nr_a[lane] = sb.get_x();
5327                                ng_a[lane] = sb.get_y();
5328                                nb_a[lane] = sb.get_z();
5329                                rf_a[lane] = rf;
5330                            }
5331                        }
5332                        sb_r = core::arch::aarch64::vld1q_f32(nr_a.as_ptr());
5333                        sb_g = core::arch::aarch64::vld1q_f32(ng_a.as_ptr());
5334                        sb_b = core::arch::aarch64::vld1q_f32(nb_a.as_ptr());
5335                        s_refl = core::arch::aarch64::vld1q_f32(rf_a.as_ptr());
5336                    }
5337                }
5338                let kd_scale: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmaxq_f32(
5339                    core::arch::aarch64::vmulq_f32(
5340                        core::arch::aarch64::vdupq_n_f32(tri.diffuse_scale),
5341                        core::arch::aarch64::vfmsq_f32(
5342                            one,
5343                            fresnel_t,
5344                            core::arch::aarch64::vdupq_n_f32(0.55),
5345                        ),
5346                    ),
5347                    core::arch::aarch64::vdupq_n_f32(0.08),
5348                );
5349                let dir_s: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
5350                    core::arch::aarch64::vmulq_f32(
5351                        core::arch::aarch64::vdupq_n_f32(tri.n_dot_l),
5352                        sh_v,
5353                    ),
5354                    kd_scale,
5355                );
5356                let ao_s: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
5357                    core::arch::aarch64::vld1q_f32(run.ao.as_ptr().add(off)),
5358                    core::arch::aarch64::vdupq_n_f32(0.44),
5359                );
5360                let lit_r: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5361                    core::arch::aarch64::vfmaq_f32(
5362                        core::arch::aarch64::vld1q_f32(run.gi_r.as_ptr().add(off)),
5363                        core::arch::aarch64::vdupq_n_f32(tri.ambient_sky.get_x()),
5364                        ao_s,
5365                    ),
5366                    core::arch::aarch64::vdupq_n_f32(sun_col.get_x()),
5367                    dir_s,
5368                );
5369                let lit_g: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5370                    core::arch::aarch64::vfmaq_f32(
5371                        core::arch::aarch64::vld1q_f32(run.gi_g.as_ptr().add(off)),
5372                        core::arch::aarch64::vdupq_n_f32(tri.ambient_sky.get_y()),
5373                        ao_s,
5374                    ),
5375                    core::arch::aarch64::vdupq_n_f32(sun_col.get_y()),
5376                    dir_s,
5377                );
5378                let lit_b: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5379                    core::arch::aarch64::vfmaq_f32(
5380                        core::arch::aarch64::vld1q_f32(run.gi_b.as_ptr().add(off)),
5381                        core::arch::aarch64::vdupq_n_f32(tri.ambient_sky.get_z()),
5382                        ao_s,
5383                    ),
5384                    core::arch::aarch64::vdupq_n_f32(sun_col.get_z()),
5385                    dir_s,
5386                );
5387                let mut rad_r: core::arch::aarch64::float32x4_t = core::arch::aarch64::vaddq_f32(
5388                    core::arch::aarch64::vfmaq_f32(spec_r, sb_r, lit_r),
5389                    em_r,
5390                );
5391                let mut rad_g: core::arch::aarch64::float32x4_t = core::arch::aarch64::vaddq_f32(
5392                    core::arch::aarch64::vfmaq_f32(spec_g, sb_g, lit_g),
5393                    em_g,
5394                );
5395                let mut rad_b: core::arch::aarch64::float32x4_t = core::arch::aarch64::vaddq_f32(
5396                    core::arch::aarch64::vfmaq_f32(spec_b, sb_b, lit_b),
5397                    em_b,
5398                );
5399                if tri.do_refl {
5400                    let refl_f: core::arch::aarch64::float32x4_t = core::arch::aarch64::vminq_f32(
5401                        core::arch::aarch64::vmaxq_f32(
5402                            core::arch::aarch64::vfmaq_f32(
5403                                core::arch::aarch64::vdupq_n_f32(0.18 + tri.metallic * 0.25),
5404                                fresnel_t,
5405                                core::arch::aarch64::vdupq_n_f32(0.82),
5406                            ),
5407                            core::arch::aarch64::vdupq_n_f32(0.18),
5408                        ),
5409                        core::arch::aarch64::vdupq_n_f32(0.95),
5410                    );
5411                    let refl_b: core::arch::aarch64::float32x4_t = core::arch::aarch64::vminq_f32(
5412                        core::arch::aarch64::vmaxq_f32(
5413                            core::arch::aarch64::vmulq_f32(s_refl, refl_f),
5414                            zero,
5415                        ),
5416                        core::arch::aarch64::vdupq_n_f32(0.82),
5417                    );
5418                    let rr_v: core::arch::aarch64::float32x4_t =
5419                        core::arch::aarch64::vld1q_f32(run.refl_r.as_ptr().add(off));
5420                    let rg_v: core::arch::aarch64::float32x4_t =
5421                        core::arch::aarch64::vld1q_f32(run.refl_g.as_ptr().add(off));
5422                    let rb_v: core::arch::aarch64::float32x4_t =
5423                        core::arch::aarch64::vld1q_f32(run.refl_b.as_ptr().add(off));
5424                    rad_r = Self::neon_lerp_4x(rad_r, rr_v, refl_b);
5425                    rad_g = Self::neon_lerp_4x(rad_g, rg_v, refl_b);
5426                    rad_b = Self::neon_lerp_4x(rad_b, rb_v, refl_b);
5427                }
5428                if frame_context.fog_on {
5429                    let pos_y: core::arch::aarch64::float32x4_t =
5430                        core::arch::aarch64::vmaxq_f32(wpy, zero);
5431                    let h_att: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmaxq_f32(
5432                        Self::neon_rcp_4x(core::arch::aarch64::vfmaq_f32(
5433                            one,
5434                            pos_y,
5435                            core::arch::aarch64::vdupq_n_f32(0.045),
5436                        )),
5437                        core::arch::aarch64::vdupq_n_f32(0.32),
5438                    );
5439                    let fd: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
5440                        core::arch::aarch64::vmulq_f32(
5441                            d_v,
5442                            core::arch::aarch64::vdupq_n_f32(frame_context.inv_fog_distance),
5443                        ),
5444                        h_att,
5445                    );
5446                    let fog_t: core::arch::aarch64::float32x4_t = core::arch::aarch64::vminq_f32(
5447                        core::arch::aarch64::vmaxq_f32(
5448                            core::arch::aarch64::vmulq_f32(
5449                                fd,
5450                                Self::neon_rcp_4x(core::arch::aarch64::vaddq_f32(one, fd)),
5451                            ),
5452                            zero,
5453                        ),
5454                        core::arch::aarch64::vdupq_n_f32(0.85),
5455                    );
5456                    let sun_align: core::arch::aarch64::float32x4_t =
5457                        core::arch::aarch64::vmaxq_f32(core::arch::aarch64::vnegq_f32(vdl), zero);
5458                    let sa2: core::arch::aarch64::float32x4_t =
5459                        core::arch::aarch64::vmulq_f32(sun_align, sun_align);
5460                    let shaft55: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
5461                        core::arch::aarch64::vmulq_f32(
5462                            core::arch::aarch64::vmulq_f32(sa2, sa2),
5463                            fog_t,
5464                        ),
5465                        core::arch::aarch64::vfmaq_f32(
5466                            core::arch::aarch64::vdupq_n_f32(0.35 * 0.55),
5467                            sh_v,
5468                            core::arch::aarch64::vdupq_n_f32(0.65 * 0.55),
5469                        ),
5470                    );
5471                    let fog_r: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5472                        core::arch::aarch64::vdupq_n_f32(sky_horizon.get_x()),
5473                        core::arch::aarch64::vdupq_n_f32(sun_col.get_x()),
5474                        shaft55,
5475                    );
5476                    let fog_g: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5477                        core::arch::aarch64::vdupq_n_f32(sky_horizon.get_y()),
5478                        core::arch::aarch64::vdupq_n_f32(sun_col.get_y()),
5479                        shaft55,
5480                    );
5481                    let fog_b: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
5482                        core::arch::aarch64::vdupq_n_f32(sky_horizon.get_z()),
5483                        core::arch::aarch64::vdupq_n_f32(sun_col.get_z()),
5484                        shaft55,
5485                    );
5486                    rad_r = Self::neon_lerp_4x(rad_r, fog_r, fog_t);
5487                    rad_g = Self::neon_lerp_4x(rad_g, fog_g, fog_t);
5488                    rad_b = Self::neon_lerp_4x(rad_b, fog_b, fog_t);
5489                }
5490                let exp_s: core::arch::aarch64::float32x4_t =
5491                    core::arch::aarch64::vdupq_n_f32(frame_context.exposure_scale);
5492                core::arch::aarch64::vst1q_f32(
5493                    exp_r_arr.as_mut_ptr(),
5494                    core::arch::aarch64::vmulq_f32(rad_r, exp_s),
5495                );
5496                core::arch::aarch64::vst1q_f32(
5497                    exp_g_arr.as_mut_ptr(),
5498                    core::arch::aarch64::vmulq_f32(rad_g, exp_s),
5499                );
5500                core::arch::aarch64::vst1q_f32(
5501                    exp_b_arr.as_mut_ptr(),
5502                    core::arch::aarch64::vmulq_f32(rad_b, exp_s),
5503                );
5504            }
5505        }
5506        #[cfg(target_arch = "x86_64")]
5507        {
5508            // SAFETY: Stack `[f32; 4]` and 16-byte-aligned `RunScratch32` (`off <= 28`) are valid; SSE2 is mandatory on `x86_64`.
5509            unsafe {
5510                let zero: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_setzero_ps();
5511                let one: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(1.0);
5512                let two: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(2.0);
5513                let abs_mask: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(-0.0);
5514                let lane_idx_arr: [f32; 4] = [0.0, 1.0, 2.0, 3.0];
5515                let lane_idx: core::arch::x86_64::__m128 =
5516                    core::arch::x86_64::_mm_loadu_ps(lane_idx_arr.as_ptr());
5517                let rx: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5518                    core::arch::x86_64::_mm_set1_ps(raw_ray.get_x()),
5519                    core::arch::x86_64::_mm_mul_ps(
5520                        core::arch::x86_64::_mm_set1_ps(ray_dx.get_x()),
5521                        lane_idx,
5522                    ),
5523                );
5524                let ry: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5525                    core::arch::x86_64::_mm_set1_ps(raw_ray.get_y()),
5526                    core::arch::x86_64::_mm_mul_ps(
5527                        core::arch::x86_64::_mm_set1_ps(ray_dx.get_y()),
5528                        lane_idx,
5529                    ),
5530                );
5531                let rz: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5532                    core::arch::x86_64::_mm_set1_ps(raw_ray.get_z()),
5533                    core::arch::x86_64::_mm_mul_ps(
5534                        core::arch::x86_64::_mm_set1_ps(ray_dx.get_z()),
5535                        lane_idx,
5536                    ),
5537                );
5538                let len_sq: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ps(
5539                    core::arch::x86_64::_mm_add_ps(
5540                        core::arch::x86_64::_mm_add_ps(
5541                            core::arch::x86_64::_mm_mul_ps(rx, rx),
5542                            core::arch::x86_64::_mm_mul_ps(ry, ry),
5543                        ),
5544                        core::arch::x86_64::_mm_mul_ps(rz, rz),
5545                    ),
5546                    core::arch::x86_64::_mm_set1_ps(1e-12),
5547                );
5548                let est: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_rsqrt_ps(len_sq);
5549                let inv_l: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(
5550                    core::arch::x86_64::_mm_mul_ps(core::arch::x86_64::_mm_set1_ps(0.5), est),
5551                    core::arch::x86_64::_mm_sub_ps(
5552                        core::arch::x86_64::_mm_set1_ps(3.0),
5553                        core::arch::x86_64::_mm_mul_ps(
5554                            core::arch::x86_64::_mm_mul_ps(len_sq, est),
5555                            est,
5556                        ),
5557                    ),
5558                );
5559                let ndv_num: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5560                    core::arch::x86_64::_mm_set1_ps(-sn.dot(raw_ray)),
5561                    core::arch::x86_64::_mm_mul_ps(
5562                        core::arch::x86_64::_mm_set1_ps(-sn.dot(ray_dx)),
5563                        lane_idx,
5564                    ),
5565                );
5566                let ndv_raw: core::arch::x86_64::__m128 =
5567                    core::arch::x86_64::_mm_mul_ps(ndv_num, inv_l);
5568                let ndv: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_min_ps(
5569                    core::arch::x86_64::_mm_max_ps(ndv_raw, core::arch::x86_64::_mm_set1_ps(0.02)),
5570                    one,
5571                );
5572                let f_om: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(one, ndv);
5573                let f_om2: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(f_om, f_om);
5574                let fresnel_t: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(
5575                    core::arch::x86_64::_mm_mul_ps(f_om2, f_om2),
5576                    f_om,
5577                );
5578                let vdl_num: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5579                    core::arch::x86_64::_mm_set1_ps(-sun_dir.dot(raw_ray)),
5580                    core::arch::x86_64::_mm_mul_ps(
5581                        core::arch::x86_64::_mm_set1_ps(-sun_dir.dot(ray_dx)),
5582                        lane_idx,
5583                    ),
5584                );
5585                let vdl: core::arch::x86_64::__m128 =
5586                    core::arch::x86_64::_mm_mul_ps(vdl_num, inv_l);
5587                let sh_v: core::arch::x86_64::__m128 =
5588                    core::arch::x86_64::_mm_loadu_ps(run.shadow.as_ptr().add(off));
5589                let (spec_r, spec_g, spec_b): (
5590                    core::arch::x86_64::__m128,
5591                    core::arch::x86_64::__m128,
5592                    core::arch::x86_64::__m128,
5593                ) = if tri.n_dot_l > 0.0 {
5594                    let ndl_v: core::arch::x86_64::__m128 =
5595                        core::arch::x86_64::_mm_set1_ps(tri.n_dot_l);
5596                    let ndh_u: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ps(
5597                        core::arch::x86_64::_mm_add_ps(ndl_v, ndv_raw),
5598                        zero,
5599                    );
5600                    let h_lsq: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ps(
5601                        core::arch::x86_64::_mm_add_ps(
5602                            two,
5603                            core::arch::x86_64::_mm_mul_ps(two, vdl),
5604                        ),
5605                        core::arch::x86_64::_mm_set1_ps(1e-6),
5606                    );
5607                    let ndh_sq: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_div_ps(
5608                        core::arch::x86_64::_mm_mul_ps(ndh_u, ndh_u),
5609                        h_lsq,
5610                    );
5611                    let ggx_den: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5612                        one,
5613                        core::arch::x86_64::_mm_mul_ps(
5614                            ndh_sq,
5615                            core::arch::x86_64::_mm_set1_ps(tri.alpha2 - 1.0),
5616                        ),
5617                    );
5618                    let ggx_term: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5619                        core::arch::x86_64::_mm_set1_ps(1e-4),
5620                        core::arch::x86_64::_mm_mul_ps(
5621                            core::arch::x86_64::_mm_mul_ps(ggx_den, ggx_den),
5622                            core::arch::x86_64::_mm_set1_ps(PI),
5623                        ),
5624                    );
5625                    let vis_den: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5626                        core::arch::x86_64::_mm_set1_ps(0.08),
5627                        core::arch::x86_64::_mm_mul_ps(
5628                            ndv,
5629                            core::arch::x86_64::_mm_set1_ps(tri.n_dot_l.max(0.06)),
5630                        ),
5631                    );
5632                    let spec_num: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(
5633                        core::arch::x86_64::_mm_set1_ps(0.25 * tri.alpha2 * tri.n_dot_l),
5634                        sh_v,
5635                    );
5636                    let spec_s: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_min_ps(
5637                        core::arch::x86_64::_mm_div_ps(
5638                            spec_num,
5639                            core::arch::x86_64::_mm_mul_ps(ggx_term, vis_den),
5640                        ),
5641                        core::arch::x86_64::_mm_set1_ps(4.5),
5642                    );
5643                    let fr_r: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5644                        core::arch::x86_64::_mm_set1_ps(tri.f0.get_x()),
5645                        core::arch::x86_64::_mm_mul_ps(
5646                            core::arch::x86_64::_mm_set1_ps(1.0 - tri.f0.get_x()),
5647                            fresnel_t,
5648                        ),
5649                    );
5650                    let fr_g: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5651                        core::arch::x86_64::_mm_set1_ps(tri.f0.get_y()),
5652                        core::arch::x86_64::_mm_mul_ps(
5653                            core::arch::x86_64::_mm_set1_ps(1.0 - tri.f0.get_y()),
5654                            fresnel_t,
5655                        ),
5656                    );
5657                    let fr_b: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5658                        core::arch::x86_64::_mm_set1_ps(tri.f0.get_z()),
5659                        core::arch::x86_64::_mm_mul_ps(
5660                            core::arch::x86_64::_mm_set1_ps(1.0 - tri.f0.get_z()),
5661                            fresnel_t,
5662                        ),
5663                    );
5664                    (
5665                        core::arch::x86_64::_mm_mul_ps(
5666                            fr_r,
5667                            core::arch::x86_64::_mm_mul_ps(
5668                                core::arch::x86_64::_mm_set1_ps(sun_col.get_x()),
5669                                spec_s,
5670                            ),
5671                        ),
5672                        core::arch::x86_64::_mm_mul_ps(
5673                            fr_g,
5674                            core::arch::x86_64::_mm_mul_ps(
5675                                core::arch::x86_64::_mm_set1_ps(sun_col.get_y()),
5676                                spec_s,
5677                            ),
5678                        ),
5679                        core::arch::x86_64::_mm_mul_ps(
5680                            fr_b,
5681                            core::arch::x86_64::_mm_mul_ps(
5682                                core::arch::x86_64::_mm_set1_ps(sun_col.get_z()),
5683                                spec_s,
5684                            ),
5685                        ),
5686                    )
5687                } else {
5688                    (zero, zero, zero)
5689                };
5690                let d_v: core::arch::x86_64::__m128 =
5691                    core::arch::x86_64::_mm_loadu_ps(run.depths.as_ptr().add(off));
5692                let wpy: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5693                    core::arch::x86_64::_mm_set1_ps(frame_context.camera_position.get_y()),
5694                    core::arch::x86_64::_mm_mul_ps(ry, d_v),
5695                );
5696                let mut sb_r: core::arch::x86_64::__m128 =
5697                    core::arch::x86_64::_mm_set1_ps(tri.mat_base.get_x());
5698                let mut sb_g: core::arch::x86_64::__m128 =
5699                    core::arch::x86_64::_mm_set1_ps(tri.mat_base.get_y());
5700                let mut sb_b: core::arch::x86_64::__m128 =
5701                    core::arch::x86_64::_mm_set1_ps(tri.mat_base.get_z());
5702                let mut em_r: core::arch::x86_64::__m128 =
5703                    core::arch::x86_64::_mm_set1_ps(tri.mat_emissive.get_x());
5704                let mut em_g: core::arch::x86_64::__m128 =
5705                    core::arch::x86_64::_mm_set1_ps(tri.mat_emissive.get_y());
5706                let mut em_b: core::arch::x86_64::__m128 =
5707                    core::arch::x86_64::_mm_set1_ps(tri.mat_emissive.get_z());
5708                let mut s_refl: core::arch::x86_64::__m128 =
5709                    core::arch::x86_64::_mm_set1_ps(tri.mat_refl);
5710                if DETAIL == 2 {
5711                    let u_coord_v: core::arch::x86_64::__m128 = if sn.get_x().abs() > 0.5 {
5712                        core::arch::x86_64::_mm_add_ps(
5713                            core::arch::x86_64::_mm_set1_ps(frame_context.camera_position.get_z()),
5714                            core::arch::x86_64::_mm_mul_ps(rz, d_v),
5715                        )
5716                    } else {
5717                        core::arch::x86_64::_mm_add_ps(
5718                            core::arch::x86_64::_mm_set1_ps(frame_context.camera_position.get_x()),
5719                            core::arch::x86_64::_mm_mul_ps(rx, d_v),
5720                        )
5721                    };
5722                    let mut u_a: [f32; 4] = [0.0; 4];
5723                    let mut y_a: [f32; 4] = [0.0; 4];
5724                    let mut d_a: [f32; 4] = [0.0; 4];
5725                    core::arch::x86_64::_mm_storeu_ps(u_a.as_mut_ptr(), u_coord_v);
5726                    core::arch::x86_64::_mm_storeu_ps(y_a.as_mut_ptr(), wpy);
5727                    core::arch::x86_64::_mm_storeu_ps(d_a.as_mut_ptr(), d_v);
5728                    let mut nr_a: [f32; 4] = [0.0; 4];
5729                    let mut ng_a: [f32; 4] = [0.0; 4];
5730                    let mut nb_a: [f32; 4] = [0.0; 4];
5731                    let mut er_a: [f32; 4] = [0.0; 4];
5732                    let mut eg_a: [f32; 4] = [0.0; 4];
5733                    let mut eb_a: [f32; 4] = [0.0; 4];
5734                    let mut rf_a: [f32; 4] = [0.0; 4];
5735                    for lane in 0..4usize {
5736                        let (sb, em, rf): (Vec3, Vec3, f32) = Self::eval_facade_detail(
5737                            (u_a[lane], y_a[lane], d_a[lane], frame_context.inv_height),
5738                            (tri.mat_base, tri.mat_emissive, tri.mat_refl),
5739                        );
5740                        nr_a[lane] = sb.get_x();
5741                        ng_a[lane] = sb.get_y();
5742                        nb_a[lane] = sb.get_z();
5743                        er_a[lane] = em.get_x();
5744                        eg_a[lane] = em.get_y();
5745                        eb_a[lane] = em.get_z();
5746                        rf_a[lane] = rf;
5747                    }
5748                    sb_r = core::arch::x86_64::_mm_loadu_ps(nr_a.as_ptr());
5749                    sb_g = core::arch::x86_64::_mm_loadu_ps(ng_a.as_ptr());
5750                    sb_b = core::arch::x86_64::_mm_loadu_ps(nb_a.as_ptr());
5751                    em_r = core::arch::x86_64::_mm_loadu_ps(er_a.as_ptr());
5752                    em_g = core::arch::x86_64::_mm_loadu_ps(eg_a.as_ptr());
5753                    em_b = core::arch::x86_64::_mm_loadu_ps(eb_a.as_ptr());
5754                    s_refl = core::arch::x86_64::_mm_loadu_ps(rf_a.as_ptr());
5755                } else if DETAIL == 1 {
5756                    let m_r: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_cmplt_ps(
5757                        core::arch::x86_64::_mm_andnot_ps(abs_mask, wpy),
5758                        core::arch::x86_64::_mm_set1_ps(0.15),
5759                    );
5760                    let m_mask: i32 = core::arch::x86_64::_mm_movemask_ps(m_r);
5761                    if m_mask != 0 {
5762                        let wpx_v: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5763                            core::arch::x86_64::_mm_set1_ps(frame_context.camera_position.get_x()),
5764                            core::arch::x86_64::_mm_mul_ps(rx, d_v),
5765                        );
5766                        let wpz_v: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5767                            core::arch::x86_64::_mm_set1_ps(frame_context.camera_position.get_z()),
5768                            core::arch::x86_64::_mm_mul_ps(rz, d_v),
5769                        );
5770                        let mut x_a: [f32; 4] = [0.0; 4];
5771                        let mut z_a: [f32; 4] = [0.0; 4];
5772                        let mut d_a: [f32; 4] = [0.0; 4];
5773                        let mut rx_a: [f32; 4] = [0.0; 4];
5774                        let mut ry_a: [f32; 4] = [0.0; 4];
5775                        let mut rz_a: [f32; 4] = [0.0; 4];
5776                        let mut ft_a: [f32; 4] = [0.0; 4];
5777                        core::arch::x86_64::_mm_storeu_ps(x_a.as_mut_ptr(), wpx_v);
5778                        core::arch::x86_64::_mm_storeu_ps(z_a.as_mut_ptr(), wpz_v);
5779                        core::arch::x86_64::_mm_storeu_ps(d_a.as_mut_ptr(), d_v);
5780                        core::arch::x86_64::_mm_storeu_ps(rx_a.as_mut_ptr(), rx);
5781                        core::arch::x86_64::_mm_storeu_ps(ry_a.as_mut_ptr(), ry);
5782                        core::arch::x86_64::_mm_storeu_ps(rz_a.as_mut_ptr(), rz);
5783                        core::arch::x86_64::_mm_storeu_ps(ft_a.as_mut_ptr(), fresnel_t);
5784                        let mut nr_a: [f32; 4] = [tri.mat_base.get_x(); 4];
5785                        let mut ng_a: [f32; 4] = [tri.mat_base.get_y(); 4];
5786                        let mut nb_a: [f32; 4] = [tri.mat_base.get_z(); 4];
5787                        let mut rf_a: [f32; 4] = [tri.mat_refl; 4];
5788                        for lane in 0..4usize {
5789                            if (m_mask & (1 << lane)) != 0 {
5790                                let (sb, rf): (Vec3, f32) = Self::eval_road_detail(
5791                                    (x_a[lane], z_a[lane], d_a[lane], frame_context.inv_height),
5792                                    (
5793                                        Vec3::new(-rx_a[lane], -ry_a[lane], -rz_a[lane]),
5794                                        ft_a[lane],
5795                                        tri.metallic,
5796                                        frame_context.world_time_secs,
5797                                    ),
5798                                    tri.mat_base,
5799                                );
5800                                nr_a[lane] = sb.get_x();
5801                                ng_a[lane] = sb.get_y();
5802                                nb_a[lane] = sb.get_z();
5803                                rf_a[lane] = rf;
5804                            }
5805                        }
5806                        sb_r = core::arch::x86_64::_mm_loadu_ps(nr_a.as_ptr());
5807                        sb_g = core::arch::x86_64::_mm_loadu_ps(ng_a.as_ptr());
5808                        sb_b = core::arch::x86_64::_mm_loadu_ps(nb_a.as_ptr());
5809                        s_refl = core::arch::x86_64::_mm_loadu_ps(rf_a.as_ptr());
5810                    }
5811                }
5812                let kd_scale: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ps(
5813                    core::arch::x86_64::_mm_mul_ps(
5814                        core::arch::x86_64::_mm_set1_ps(tri.diffuse_scale),
5815                        core::arch::x86_64::_mm_sub_ps(
5816                            one,
5817                            core::arch::x86_64::_mm_mul_ps(
5818                                fresnel_t,
5819                                core::arch::x86_64::_mm_set1_ps(0.55),
5820                            ),
5821                        ),
5822                    ),
5823                    core::arch::x86_64::_mm_set1_ps(0.08),
5824                );
5825                let dir_s: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(
5826                    core::arch::x86_64::_mm_mul_ps(
5827                        core::arch::x86_64::_mm_set1_ps(tri.n_dot_l),
5828                        sh_v,
5829                    ),
5830                    kd_scale,
5831                );
5832                let ao_s: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(
5833                    core::arch::x86_64::_mm_loadu_ps(run.ao.as_ptr().add(off)),
5834                    core::arch::x86_64::_mm_set1_ps(0.44),
5835                );
5836                let lit_r: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5837                    core::arch::x86_64::_mm_add_ps(
5838                        core::arch::x86_64::_mm_loadu_ps(run.gi_r.as_ptr().add(off)),
5839                        core::arch::x86_64::_mm_mul_ps(
5840                            core::arch::x86_64::_mm_set1_ps(tri.ambient_sky.get_x()),
5841                            ao_s,
5842                        ),
5843                    ),
5844                    core::arch::x86_64::_mm_mul_ps(
5845                        core::arch::x86_64::_mm_set1_ps(sun_col.get_x()),
5846                        dir_s,
5847                    ),
5848                );
5849                let lit_g: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5850                    core::arch::x86_64::_mm_add_ps(
5851                        core::arch::x86_64::_mm_loadu_ps(run.gi_g.as_ptr().add(off)),
5852                        core::arch::x86_64::_mm_mul_ps(
5853                            core::arch::x86_64::_mm_set1_ps(tri.ambient_sky.get_y()),
5854                            ao_s,
5855                        ),
5856                    ),
5857                    core::arch::x86_64::_mm_mul_ps(
5858                        core::arch::x86_64::_mm_set1_ps(sun_col.get_y()),
5859                        dir_s,
5860                    ),
5861                );
5862                let lit_b: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5863                    core::arch::x86_64::_mm_add_ps(
5864                        core::arch::x86_64::_mm_loadu_ps(run.gi_b.as_ptr().add(off)),
5865                        core::arch::x86_64::_mm_mul_ps(
5866                            core::arch::x86_64::_mm_set1_ps(tri.ambient_sky.get_z()),
5867                            ao_s,
5868                        ),
5869                    ),
5870                    core::arch::x86_64::_mm_mul_ps(
5871                        core::arch::x86_64::_mm_set1_ps(sun_col.get_z()),
5872                        dir_s,
5873                    ),
5874                );
5875                let mut rad_r: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5876                    core::arch::x86_64::_mm_add_ps(
5877                        spec_r,
5878                        core::arch::x86_64::_mm_mul_ps(sb_r, lit_r),
5879                    ),
5880                    em_r,
5881                );
5882                let mut rad_g: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5883                    core::arch::x86_64::_mm_add_ps(
5884                        spec_g,
5885                        core::arch::x86_64::_mm_mul_ps(sb_g, lit_g),
5886                    ),
5887                    em_g,
5888                );
5889                let mut rad_b: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5890                    core::arch::x86_64::_mm_add_ps(
5891                        spec_b,
5892                        core::arch::x86_64::_mm_mul_ps(sb_b, lit_b),
5893                    ),
5894                    em_b,
5895                );
5896                if tri.do_refl {
5897                    let refl_f: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_min_ps(
5898                        core::arch::x86_64::_mm_max_ps(
5899                            core::arch::x86_64::_mm_add_ps(
5900                                core::arch::x86_64::_mm_set1_ps(0.18 + tri.metallic * 0.25),
5901                                core::arch::x86_64::_mm_mul_ps(
5902                                    fresnel_t,
5903                                    core::arch::x86_64::_mm_set1_ps(0.82),
5904                                ),
5905                            ),
5906                            core::arch::x86_64::_mm_set1_ps(0.18),
5907                        ),
5908                        core::arch::x86_64::_mm_set1_ps(0.95),
5909                    );
5910                    let refl_b: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_min_ps(
5911                        core::arch::x86_64::_mm_max_ps(
5912                            core::arch::x86_64::_mm_mul_ps(s_refl, refl_f),
5913                            zero,
5914                        ),
5915                        core::arch::x86_64::_mm_set1_ps(0.82),
5916                    );
5917                    let rr_v: core::arch::x86_64::__m128 =
5918                        core::arch::x86_64::_mm_loadu_ps(run.refl_r.as_ptr().add(off));
5919                    let rg_v: core::arch::x86_64::__m128 =
5920                        core::arch::x86_64::_mm_loadu_ps(run.refl_g.as_ptr().add(off));
5921                    let rb_v: core::arch::x86_64::__m128 =
5922                        core::arch::x86_64::_mm_loadu_ps(run.refl_b.as_ptr().add(off));
5923                    rad_r = Self::sse_lerp_4x(rad_r, rr_v, refl_b);
5924                    rad_g = Self::sse_lerp_4x(rad_g, rg_v, refl_b);
5925                    rad_b = Self::sse_lerp_4x(rad_b, rb_v, refl_b);
5926                }
5927                if frame_context.fog_on {
5928                    let pos_y: core::arch::x86_64::__m128 =
5929                        core::arch::x86_64::_mm_max_ps(wpy, zero);
5930                    let h_att: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ps(
5931                        core::arch::x86_64::_mm_div_ps(
5932                            one,
5933                            core::arch::x86_64::_mm_add_ps(
5934                                one,
5935                                core::arch::x86_64::_mm_mul_ps(
5936                                    pos_y,
5937                                    core::arch::x86_64::_mm_set1_ps(0.045),
5938                                ),
5939                            ),
5940                        ),
5941                        core::arch::x86_64::_mm_set1_ps(0.32),
5942                    );
5943                    let fd: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(
5944                        core::arch::x86_64::_mm_mul_ps(
5945                            d_v,
5946                            core::arch::x86_64::_mm_set1_ps(frame_context.inv_fog_distance),
5947                        ),
5948                        h_att,
5949                    );
5950                    let fog_t: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_min_ps(
5951                        core::arch::x86_64::_mm_max_ps(
5952                            core::arch::x86_64::_mm_div_ps(
5953                                fd,
5954                                core::arch::x86_64::_mm_add_ps(one, fd),
5955                            ),
5956                            zero,
5957                        ),
5958                        core::arch::x86_64::_mm_set1_ps(0.85),
5959                    );
5960                    let sun_align: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ps(
5961                        core::arch::x86_64::_mm_xor_ps(vdl, abs_mask),
5962                        zero,
5963                    );
5964                    let sa2: core::arch::x86_64::__m128 =
5965                        core::arch::x86_64::_mm_mul_ps(sun_align, sun_align);
5966                    let shaft55: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(
5967                        core::arch::x86_64::_mm_mul_ps(
5968                            core::arch::x86_64::_mm_mul_ps(sa2, sa2),
5969                            fog_t,
5970                        ),
5971                        core::arch::x86_64::_mm_add_ps(
5972                            core::arch::x86_64::_mm_set1_ps(0.35 * 0.55),
5973                            core::arch::x86_64::_mm_mul_ps(
5974                                sh_v,
5975                                core::arch::x86_64::_mm_set1_ps(0.65 * 0.55),
5976                            ),
5977                        ),
5978                    );
5979                    let fog_r: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5980                        core::arch::x86_64::_mm_set1_ps(sky_horizon.get_x()),
5981                        core::arch::x86_64::_mm_mul_ps(
5982                            core::arch::x86_64::_mm_set1_ps(sun_col.get_x()),
5983                            shaft55,
5984                        ),
5985                    );
5986                    let fog_g: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5987                        core::arch::x86_64::_mm_set1_ps(sky_horizon.get_y()),
5988                        core::arch::x86_64::_mm_mul_ps(
5989                            core::arch::x86_64::_mm_set1_ps(sun_col.get_y()),
5990                            shaft55,
5991                        ),
5992                    );
5993                    let fog_b: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
5994                        core::arch::x86_64::_mm_set1_ps(sky_horizon.get_z()),
5995                        core::arch::x86_64::_mm_mul_ps(
5996                            core::arch::x86_64::_mm_set1_ps(sun_col.get_z()),
5997                            shaft55,
5998                        ),
5999                    );
6000                    rad_r = Self::sse_lerp_4x(rad_r, fog_r, fog_t);
6001                    rad_g = Self::sse_lerp_4x(rad_g, fog_g, fog_t);
6002                    rad_b = Self::sse_lerp_4x(rad_b, fog_b, fog_t);
6003                }
6004                let exp_s: core::arch::x86_64::__m128 =
6005                    core::arch::x86_64::_mm_set1_ps(frame_context.exposure_scale);
6006                core::arch::x86_64::_mm_storeu_ps(
6007                    exp_r_arr.as_mut_ptr(),
6008                    core::arch::x86_64::_mm_mul_ps(rad_r, exp_s),
6009                );
6010                core::arch::x86_64::_mm_storeu_ps(
6011                    exp_g_arr.as_mut_ptr(),
6012                    core::arch::x86_64::_mm_mul_ps(rad_g, exp_s),
6013                );
6014                core::arch::x86_64::_mm_storeu_ps(
6015                    exp_b_arr.as_mut_ptr(),
6016                    core::arch::x86_64::_mm_mul_ps(rad_b, exp_s),
6017                );
6018            }
6019        }
6020        #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
6021        {
6022            // SAFETY: Stack `[f32; 4]` and 16-byte-aligned `RunScratch32` (`off <= 28`) are valid; `simd128` is enabled on `wasm32`.
6023            unsafe {
6024                let zero: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(0.0);
6025                let one: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(1.0);
6026                let two: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(2.0);
6027                let lane_idx_arr: [f32; 4] = [0.0, 1.0, 2.0, 3.0];
6028                let lane_idx: core::arch::wasm32::v128 =
6029                    core::arch::wasm32::v128_load(lane_idx_arr.as_ptr().cast());
6030                let rx: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6031                    core::arch::wasm32::f32x4_splat(raw_ray.get_x()),
6032                    core::arch::wasm32::f32x4_mul(
6033                        core::arch::wasm32::f32x4_splat(ray_dx.get_x()),
6034                        lane_idx,
6035                    ),
6036                );
6037                let ry: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6038                    core::arch::wasm32::f32x4_splat(raw_ray.get_y()),
6039                    core::arch::wasm32::f32x4_mul(
6040                        core::arch::wasm32::f32x4_splat(ray_dx.get_y()),
6041                        lane_idx,
6042                    ),
6043                );
6044                let rz: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6045                    core::arch::wasm32::f32x4_splat(raw_ray.get_z()),
6046                    core::arch::wasm32::f32x4_mul(
6047                        core::arch::wasm32::f32x4_splat(ray_dx.get_z()),
6048                        lane_idx,
6049                    ),
6050                );
6051                let len_sq: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmax(
6052                    core::arch::wasm32::f32x4_add(
6053                        core::arch::wasm32::f32x4_add(
6054                            core::arch::wasm32::f32x4_mul(rx, rx),
6055                            core::arch::wasm32::f32x4_mul(ry, ry),
6056                        ),
6057                        core::arch::wasm32::f32x4_mul(rz, rz),
6058                    ),
6059                    core::arch::wasm32::f32x4_splat(1e-12),
6060                );
6061                let inv_l: core::arch::wasm32::v128 =
6062                    core::arch::wasm32::f32x4_div(one, core::arch::wasm32::f32x4_sqrt(len_sq));
6063                let ndv_num: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6064                    core::arch::wasm32::f32x4_splat(-sn.dot(raw_ray)),
6065                    core::arch::wasm32::f32x4_mul(
6066                        core::arch::wasm32::f32x4_splat(-sn.dot(ray_dx)),
6067                        lane_idx,
6068                    ),
6069                );
6070                let ndv_raw: core::arch::wasm32::v128 =
6071                    core::arch::wasm32::f32x4_mul(ndv_num, inv_l);
6072                let ndv: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmin(
6073                    core::arch::wasm32::f32x4_pmax(ndv_raw, core::arch::wasm32::f32x4_splat(0.02)),
6074                    one,
6075                );
6076                let f_om: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(one, ndv);
6077                let f_om2: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(f_om, f_om);
6078                let fresnel_t: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(
6079                    core::arch::wasm32::f32x4_mul(f_om2, f_om2),
6080                    f_om,
6081                );
6082                let vdl_num: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6083                    core::arch::wasm32::f32x4_splat(-sun_dir.dot(raw_ray)),
6084                    core::arch::wasm32::f32x4_mul(
6085                        core::arch::wasm32::f32x4_splat(-sun_dir.dot(ray_dx)),
6086                        lane_idx,
6087                    ),
6088                );
6089                let vdl: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(vdl_num, inv_l);
6090                let sh_v: core::arch::wasm32::v128 =
6091                    core::arch::wasm32::v128_load(run.shadow.as_ptr().add(off).cast());
6092                let (spec_r, spec_g, spec_b): (
6093                    core::arch::wasm32::v128,
6094                    core::arch::wasm32::v128,
6095                    core::arch::wasm32::v128,
6096                ) = if tri.n_dot_l > 0.0 {
6097                    let ndl_v: core::arch::wasm32::v128 =
6098                        core::arch::wasm32::f32x4_splat(tri.n_dot_l);
6099                    let ndh_u: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmax(
6100                        core::arch::wasm32::f32x4_add(ndl_v, ndv_raw),
6101                        zero,
6102                    );
6103                    let h_lsq: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmax(
6104                        core::arch::wasm32::f32x4_add(two, core::arch::wasm32::f32x4_mul(two, vdl)),
6105                        core::arch::wasm32::f32x4_splat(1e-6),
6106                    );
6107                    let ndh_sq: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_div(
6108                        core::arch::wasm32::f32x4_mul(ndh_u, ndh_u),
6109                        h_lsq,
6110                    );
6111                    let ggx_den: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6112                        one,
6113                        core::arch::wasm32::f32x4_mul(
6114                            ndh_sq,
6115                            core::arch::wasm32::f32x4_splat(tri.alpha2 - 1.0),
6116                        ),
6117                    );
6118                    let ggx_term: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6119                        core::arch::wasm32::f32x4_splat(1e-4),
6120                        core::arch::wasm32::f32x4_mul(
6121                            core::arch::wasm32::f32x4_mul(ggx_den, ggx_den),
6122                            core::arch::wasm32::f32x4_splat(PI),
6123                        ),
6124                    );
6125                    let vis_den: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6126                        core::arch::wasm32::f32x4_splat(0.08),
6127                        core::arch::wasm32::f32x4_mul(
6128                            ndv,
6129                            core::arch::wasm32::f32x4_splat(tri.n_dot_l.max(0.06)),
6130                        ),
6131                    );
6132                    let spec_num: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(
6133                        core::arch::wasm32::f32x4_splat(0.25 * tri.alpha2 * tri.n_dot_l),
6134                        sh_v,
6135                    );
6136                    let spec_s: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmin(
6137                        core::arch::wasm32::f32x4_div(
6138                            spec_num,
6139                            core::arch::wasm32::f32x4_mul(ggx_term, vis_den),
6140                        ),
6141                        core::arch::wasm32::f32x4_splat(4.5),
6142                    );
6143                    let fr_r: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6144                        core::arch::wasm32::f32x4_splat(tri.f0.get_x()),
6145                        core::arch::wasm32::f32x4_mul(
6146                            core::arch::wasm32::f32x4_splat(1.0 - tri.f0.get_x()),
6147                            fresnel_t,
6148                        ),
6149                    );
6150                    let fr_g: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6151                        core::arch::wasm32::f32x4_splat(tri.f0.get_y()),
6152                        core::arch::wasm32::f32x4_mul(
6153                            core::arch::wasm32::f32x4_splat(1.0 - tri.f0.get_y()),
6154                            fresnel_t,
6155                        ),
6156                    );
6157                    let fr_b: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6158                        core::arch::wasm32::f32x4_splat(tri.f0.get_z()),
6159                        core::arch::wasm32::f32x4_mul(
6160                            core::arch::wasm32::f32x4_splat(1.0 - tri.f0.get_z()),
6161                            fresnel_t,
6162                        ),
6163                    );
6164                    (
6165                        core::arch::wasm32::f32x4_mul(
6166                            fr_r,
6167                            core::arch::wasm32::f32x4_mul(
6168                                core::arch::wasm32::f32x4_splat(sun_col.get_x()),
6169                                spec_s,
6170                            ),
6171                        ),
6172                        core::arch::wasm32::f32x4_mul(
6173                            fr_g,
6174                            core::arch::wasm32::f32x4_mul(
6175                                core::arch::wasm32::f32x4_splat(sun_col.get_y()),
6176                                spec_s,
6177                            ),
6178                        ),
6179                        core::arch::wasm32::f32x4_mul(
6180                            fr_b,
6181                            core::arch::wasm32::f32x4_mul(
6182                                core::arch::wasm32::f32x4_splat(sun_col.get_z()),
6183                                spec_s,
6184                            ),
6185                        ),
6186                    )
6187                } else {
6188                    (zero, zero, zero)
6189                };
6190                let d_v: core::arch::wasm32::v128 =
6191                    core::arch::wasm32::v128_load(run.depths.as_ptr().add(off).cast());
6192                let wpy: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6193                    core::arch::wasm32::f32x4_splat(frame_context.camera_position.get_y()),
6194                    core::arch::wasm32::f32x4_mul(ry, d_v),
6195                );
6196                let mut sb_r: core::arch::wasm32::v128 =
6197                    core::arch::wasm32::f32x4_splat(tri.mat_base.get_x());
6198                let mut sb_g: core::arch::wasm32::v128 =
6199                    core::arch::wasm32::f32x4_splat(tri.mat_base.get_y());
6200                let mut sb_b: core::arch::wasm32::v128 =
6201                    core::arch::wasm32::f32x4_splat(tri.mat_base.get_z());
6202                let mut em_r: core::arch::wasm32::v128 =
6203                    core::arch::wasm32::f32x4_splat(tri.mat_emissive.get_x());
6204                let mut em_g: core::arch::wasm32::v128 =
6205                    core::arch::wasm32::f32x4_splat(tri.mat_emissive.get_y());
6206                let mut em_b: core::arch::wasm32::v128 =
6207                    core::arch::wasm32::f32x4_splat(tri.mat_emissive.get_z());
6208                let mut s_refl: core::arch::wasm32::v128 =
6209                    core::arch::wasm32::f32x4_splat(tri.mat_refl);
6210                if DETAIL == 2 {
6211                    let u_coord_v: core::arch::wasm32::v128 = if sn.get_x().abs() > 0.5 {
6212                        core::arch::wasm32::f32x4_add(
6213                            core::arch::wasm32::f32x4_splat(frame_context.camera_position.get_z()),
6214                            core::arch::wasm32::f32x4_mul(rz, d_v),
6215                        )
6216                    } else {
6217                        core::arch::wasm32::f32x4_add(
6218                            core::arch::wasm32::f32x4_splat(frame_context.camera_position.get_x()),
6219                            core::arch::wasm32::f32x4_mul(rx, d_v),
6220                        )
6221                    };
6222                    let mut u_a: [f32; 4] = [0.0; 4];
6223                    let mut y_a: [f32; 4] = [0.0; 4];
6224                    let mut d_a: [f32; 4] = [0.0; 4];
6225                    core::arch::wasm32::v128_store(u_a.as_mut_ptr().cast(), u_coord_v);
6226                    core::arch::wasm32::v128_store(y_a.as_mut_ptr().cast(), wpy);
6227                    core::arch::wasm32::v128_store(d_a.as_mut_ptr().cast(), d_v);
6228                    let mut nr_a: [f32; 4] = [0.0; 4];
6229                    let mut ng_a: [f32; 4] = [0.0; 4];
6230                    let mut nb_a: [f32; 4] = [0.0; 4];
6231                    let mut er_a: [f32; 4] = [0.0; 4];
6232                    let mut eg_a: [f32; 4] = [0.0; 4];
6233                    let mut eb_a: [f32; 4] = [0.0; 4];
6234                    let mut rf_a: [f32; 4] = [0.0; 4];
6235                    for lane in 0..4usize {
6236                        let (sb, em, rf): (Vec3, Vec3, f32) = Self::eval_facade_detail(
6237                            (u_a[lane], y_a[lane], d_a[lane], frame_context.inv_height),
6238                            (tri.mat_base, tri.mat_emissive, tri.mat_refl),
6239                        );
6240                        nr_a[lane] = sb.get_x();
6241                        ng_a[lane] = sb.get_y();
6242                        nb_a[lane] = sb.get_z();
6243                        er_a[lane] = em.get_x();
6244                        eg_a[lane] = em.get_y();
6245                        eb_a[lane] = em.get_z();
6246                        rf_a[lane] = rf;
6247                    }
6248                    sb_r = core::arch::wasm32::v128_load(nr_a.as_ptr().cast());
6249                    sb_g = core::arch::wasm32::v128_load(ng_a.as_ptr().cast());
6250                    sb_b = core::arch::wasm32::v128_load(nb_a.as_ptr().cast());
6251                    em_r = core::arch::wasm32::v128_load(er_a.as_ptr().cast());
6252                    em_g = core::arch::wasm32::v128_load(eg_a.as_ptr().cast());
6253                    em_b = core::arch::wasm32::v128_load(eb_a.as_ptr().cast());
6254                    s_refl = core::arch::wasm32::v128_load(rf_a.as_ptr().cast());
6255                } else if DETAIL == 1 {
6256                    let m_r: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_lt(
6257                        core::arch::wasm32::f32x4_abs(wpy),
6258                        core::arch::wasm32::f32x4_splat(0.15),
6259                    );
6260                    let m_mask: u32 = core::arch::wasm32::i32x4_bitmask(m_r) as u32;
6261                    if m_mask != 0 {
6262                        let wpx_v: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6263                            core::arch::wasm32::f32x4_splat(frame_context.camera_position.get_x()),
6264                            core::arch::wasm32::f32x4_mul(rx, d_v),
6265                        );
6266                        let wpz_v: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6267                            core::arch::wasm32::f32x4_splat(frame_context.camera_position.get_z()),
6268                            core::arch::wasm32::f32x4_mul(rz, d_v),
6269                        );
6270                        let mut x_a: [f32; 4] = [0.0; 4];
6271                        let mut z_a: [f32; 4] = [0.0; 4];
6272                        let mut d_a: [f32; 4] = [0.0; 4];
6273                        let mut rx_a: [f32; 4] = [0.0; 4];
6274                        let mut ry_a: [f32; 4] = [0.0; 4];
6275                        let mut rz_a: [f32; 4] = [0.0; 4];
6276                        let mut ft_a: [f32; 4] = [0.0; 4];
6277                        core::arch::wasm32::v128_store(x_a.as_mut_ptr().cast(), wpx_v);
6278                        core::arch::wasm32::v128_store(z_a.as_mut_ptr().cast(), wpz_v);
6279                        core::arch::wasm32::v128_store(d_a.as_mut_ptr().cast(), d_v);
6280                        core::arch::wasm32::v128_store(rx_a.as_mut_ptr().cast(), rx);
6281                        core::arch::wasm32::v128_store(ry_a.as_mut_ptr().cast(), ry);
6282                        core::arch::wasm32::v128_store(rz_a.as_mut_ptr().cast(), rz);
6283                        core::arch::wasm32::v128_store(ft_a.as_mut_ptr().cast(), fresnel_t);
6284                        let mut nr_a: [f32; 4] = [tri.mat_base.get_x(); 4];
6285                        let mut ng_a: [f32; 4] = [tri.mat_base.get_y(); 4];
6286                        let mut nb_a: [f32; 4] = [tri.mat_base.get_z(); 4];
6287                        let mut rf_a: [f32; 4] = [tri.mat_refl; 4];
6288                        for lane in 0..4usize {
6289                            if (m_mask & (1_u32 << lane)) != 0 {
6290                                let (sb, rf): (Vec3, f32) = Self::eval_road_detail(
6291                                    (x_a[lane], z_a[lane], d_a[lane], frame_context.inv_height),
6292                                    (
6293                                        Vec3::new(-rx_a[lane], -ry_a[lane], -rz_a[lane]),
6294                                        ft_a[lane],
6295                                        tri.metallic,
6296                                        frame_context.world_time_secs,
6297                                    ),
6298                                    tri.mat_base,
6299                                );
6300                                nr_a[lane] = sb.get_x();
6301                                ng_a[lane] = sb.get_y();
6302                                nb_a[lane] = sb.get_z();
6303                                rf_a[lane] = rf;
6304                            }
6305                        }
6306                        sb_r = core::arch::wasm32::v128_load(nr_a.as_ptr().cast());
6307                        sb_g = core::arch::wasm32::v128_load(ng_a.as_ptr().cast());
6308                        sb_b = core::arch::wasm32::v128_load(nb_a.as_ptr().cast());
6309                        s_refl = core::arch::wasm32::v128_load(rf_a.as_ptr().cast());
6310                    }
6311                }
6312                let kd_scale: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmax(
6313                    core::arch::wasm32::f32x4_mul(
6314                        core::arch::wasm32::f32x4_splat(tri.diffuse_scale),
6315                        core::arch::wasm32::f32x4_sub(
6316                            one,
6317                            core::arch::wasm32::f32x4_mul(
6318                                fresnel_t,
6319                                core::arch::wasm32::f32x4_splat(0.55),
6320                            ),
6321                        ),
6322                    ),
6323                    core::arch::wasm32::f32x4_splat(0.08),
6324                );
6325                let dir_s: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(
6326                    core::arch::wasm32::f32x4_mul(
6327                        core::arch::wasm32::f32x4_splat(tri.n_dot_l),
6328                        sh_v,
6329                    ),
6330                    kd_scale,
6331                );
6332                let ao_s: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(
6333                    core::arch::wasm32::v128_load(run.ao.as_ptr().add(off).cast()),
6334                    core::arch::wasm32::f32x4_splat(0.44),
6335                );
6336                let lit_r: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6337                    core::arch::wasm32::f32x4_add(
6338                        core::arch::wasm32::v128_load(run.gi_r.as_ptr().add(off).cast()),
6339                        core::arch::wasm32::f32x4_mul(
6340                            core::arch::wasm32::f32x4_splat(tri.ambient_sky.get_x()),
6341                            ao_s,
6342                        ),
6343                    ),
6344                    core::arch::wasm32::f32x4_mul(
6345                        core::arch::wasm32::f32x4_splat(sun_col.get_x()),
6346                        dir_s,
6347                    ),
6348                );
6349                let lit_g: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6350                    core::arch::wasm32::f32x4_add(
6351                        core::arch::wasm32::v128_load(run.gi_g.as_ptr().add(off).cast()),
6352                        core::arch::wasm32::f32x4_mul(
6353                            core::arch::wasm32::f32x4_splat(tri.ambient_sky.get_y()),
6354                            ao_s,
6355                        ),
6356                    ),
6357                    core::arch::wasm32::f32x4_mul(
6358                        core::arch::wasm32::f32x4_splat(sun_col.get_y()),
6359                        dir_s,
6360                    ),
6361                );
6362                let lit_b: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6363                    core::arch::wasm32::f32x4_add(
6364                        core::arch::wasm32::v128_load(run.gi_b.as_ptr().add(off).cast()),
6365                        core::arch::wasm32::f32x4_mul(
6366                            core::arch::wasm32::f32x4_splat(tri.ambient_sky.get_z()),
6367                            ao_s,
6368                        ),
6369                    ),
6370                    core::arch::wasm32::f32x4_mul(
6371                        core::arch::wasm32::f32x4_splat(sun_col.get_z()),
6372                        dir_s,
6373                    ),
6374                );
6375                let mut rad_r: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6376                    core::arch::wasm32::f32x4_add(
6377                        spec_r,
6378                        core::arch::wasm32::f32x4_mul(sb_r, lit_r),
6379                    ),
6380                    em_r,
6381                );
6382                let mut rad_g: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6383                    core::arch::wasm32::f32x4_add(
6384                        spec_g,
6385                        core::arch::wasm32::f32x4_mul(sb_g, lit_g),
6386                    ),
6387                    em_g,
6388                );
6389                let mut rad_b: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6390                    core::arch::wasm32::f32x4_add(
6391                        spec_b,
6392                        core::arch::wasm32::f32x4_mul(sb_b, lit_b),
6393                    ),
6394                    em_b,
6395                );
6396                if tri.do_refl {
6397                    let refl_f: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmin(
6398                        core::arch::wasm32::f32x4_pmax(
6399                            core::arch::wasm32::f32x4_add(
6400                                core::arch::wasm32::f32x4_splat(0.18 + tri.metallic * 0.25),
6401                                core::arch::wasm32::f32x4_mul(
6402                                    fresnel_t,
6403                                    core::arch::wasm32::f32x4_splat(0.82),
6404                                ),
6405                            ),
6406                            core::arch::wasm32::f32x4_splat(0.18),
6407                        ),
6408                        core::arch::wasm32::f32x4_splat(0.95),
6409                    );
6410                    let refl_b: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmin(
6411                        core::arch::wasm32::f32x4_pmax(
6412                            core::arch::wasm32::f32x4_mul(s_refl, refl_f),
6413                            zero,
6414                        ),
6415                        core::arch::wasm32::f32x4_splat(0.82),
6416                    );
6417                    let rr_v: core::arch::wasm32::v128 =
6418                        core::arch::wasm32::v128_load(run.refl_r.as_ptr().add(off).cast());
6419                    let rg_v: core::arch::wasm32::v128 =
6420                        core::arch::wasm32::v128_load(run.refl_g.as_ptr().add(off).cast());
6421                    let rb_v: core::arch::wasm32::v128 =
6422                        core::arch::wasm32::v128_load(run.refl_b.as_ptr().add(off).cast());
6423                    rad_r = Self::wasm_lerp_4x(rad_r, rr_v, refl_b);
6424                    rad_g = Self::wasm_lerp_4x(rad_g, rg_v, refl_b);
6425                    rad_b = Self::wasm_lerp_4x(rad_b, rb_v, refl_b);
6426                }
6427                if frame_context.fog_on {
6428                    let pos_y: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmax(wpy, zero);
6429                    let h_att: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmax(
6430                        core::arch::wasm32::f32x4_div(
6431                            one,
6432                            core::arch::wasm32::f32x4_add(
6433                                one,
6434                                core::arch::wasm32::f32x4_mul(
6435                                    pos_y,
6436                                    core::arch::wasm32::f32x4_splat(0.045),
6437                                ),
6438                            ),
6439                        ),
6440                        core::arch::wasm32::f32x4_splat(0.32),
6441                    );
6442                    let fd: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(
6443                        core::arch::wasm32::f32x4_mul(
6444                            d_v,
6445                            core::arch::wasm32::f32x4_splat(frame_context.inv_fog_distance),
6446                        ),
6447                        h_att,
6448                    );
6449                    let fog_t: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmin(
6450                        core::arch::wasm32::f32x4_pmax(
6451                            core::arch::wasm32::f32x4_div(
6452                                fd,
6453                                core::arch::wasm32::f32x4_add(one, fd),
6454                            ),
6455                            zero,
6456                        ),
6457                        core::arch::wasm32::f32x4_splat(0.85),
6458                    );
6459                    let sun_align: core::arch::wasm32::v128 =
6460                        core::arch::wasm32::f32x4_pmax(core::arch::wasm32::f32x4_neg(vdl), zero);
6461                    let sa2: core::arch::wasm32::v128 =
6462                        core::arch::wasm32::f32x4_mul(sun_align, sun_align);
6463                    let shaft55: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(
6464                        core::arch::wasm32::f32x4_mul(
6465                            core::arch::wasm32::f32x4_mul(sa2, sa2),
6466                            fog_t,
6467                        ),
6468                        core::arch::wasm32::f32x4_add(
6469                            core::arch::wasm32::f32x4_splat(0.35 * 0.55),
6470                            core::arch::wasm32::f32x4_mul(
6471                                sh_v,
6472                                core::arch::wasm32::f32x4_splat(0.65 * 0.55),
6473                            ),
6474                        ),
6475                    );
6476                    let fog_r: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6477                        core::arch::wasm32::f32x4_splat(sky_horizon.get_x()),
6478                        core::arch::wasm32::f32x4_mul(
6479                            core::arch::wasm32::f32x4_splat(sun_col.get_x()),
6480                            shaft55,
6481                        ),
6482                    );
6483                    let fog_g: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6484                        core::arch::wasm32::f32x4_splat(sky_horizon.get_y()),
6485                        core::arch::wasm32::f32x4_mul(
6486                            core::arch::wasm32::f32x4_splat(sun_col.get_y()),
6487                            shaft55,
6488                        ),
6489                    );
6490                    let fog_b: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
6491                        core::arch::wasm32::f32x4_splat(sky_horizon.get_z()),
6492                        core::arch::wasm32::f32x4_mul(
6493                            core::arch::wasm32::f32x4_splat(sun_col.get_z()),
6494                            shaft55,
6495                        ),
6496                    );
6497                    rad_r = Self::wasm_lerp_4x(rad_r, fog_r, fog_t);
6498                    rad_g = Self::wasm_lerp_4x(rad_g, fog_g, fog_t);
6499                    rad_b = Self::wasm_lerp_4x(rad_b, fog_b, fog_t);
6500                }
6501                let exp_s: core::arch::wasm32::v128 =
6502                    core::arch::wasm32::f32x4_splat(frame_context.exposure_scale);
6503                core::arch::wasm32::v128_store(
6504                    exp_r_arr.as_mut_ptr().cast(),
6505                    core::arch::wasm32::f32x4_mul(rad_r, exp_s),
6506                );
6507                core::arch::wasm32::v128_store(
6508                    exp_g_arr.as_mut_ptr().cast(),
6509                    core::arch::wasm32::f32x4_mul(rad_g, exp_s),
6510                );
6511                core::arch::wasm32::v128_store(
6512                    exp_b_arr.as_mut_ptr().cast(),
6513                    core::arch::wasm32::f32x4_mul(rad_b, exp_s),
6514                );
6515            }
6516        }
6517        #[cfg(not(target_arch = "aarch64"))]
6518        #[cfg(not(target_arch = "x86_64"))]
6519        #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
6520        {
6521            let rx: [f32; 4] = [
6522                raw_ray.get_x(),
6523                raw_ray.get_x() + ray_dx.get_x(),
6524                raw_ray.get_x() + ray_dx.get_x() * 2.0,
6525                raw_ray.get_x() + ray_dx.get_x() * 3.0,
6526            ];
6527            let ry: [f32; 4] = [
6528                raw_ray.get_y(),
6529                raw_ray.get_y() + ray_dx.get_y(),
6530                raw_ray.get_y() + ray_dx.get_y() * 2.0,
6531                raw_ray.get_y() + ray_dx.get_y() * 3.0,
6532            ];
6533            let rz: [f32; 4] = [
6534                raw_ray.get_z(),
6535                raw_ray.get_z() + ray_dx.get_z(),
6536                raw_ray.get_z() + ray_dx.get_z() * 2.0,
6537                raw_ray.get_z() + ray_dx.get_z() * 3.0,
6538            ];
6539            let len_sq: [f32; 4] = [
6540                rx[0].mul_add(rx[0], ry[0].mul_add(ry[0], rz[0] * rz[0])),
6541                rx[1].mul_add(rx[1], ry[1].mul_add(ry[1], rz[1] * rz[1])),
6542                rx[2].mul_add(rx[2], ry[2].mul_add(ry[2], rz[2] * rz[2])),
6543                rx[3].mul_add(rx[3], ry[3].mul_add(ry[3], rz[3] * rz[3])),
6544            ];
6545            let inv_len: [f32; 4] = Self::rsqrt_4x(len_sq);
6546            let cpx: f32 = frame_context.camera_position.get_x();
6547            let cpy: f32 = frame_context.camera_position.get_y();
6548            let cpz: f32 = frame_context.camera_position.get_z();
6549            let facade_u_is_z: bool = sn.get_x().abs() > 0.5;
6550            for lane in 0..4 {
6551                let s_i: usize = off + lane;
6552                let inv_l: f32 = inv_len[lane];
6553                let vtx: f32 = -rx[lane] * inv_l;
6554                let vty: f32 = -ry[lane] * inv_l;
6555                let vtz: f32 = -rz[lane] * inv_l;
6556                let ndv_raw: f32 = sn
6557                    .get_x()
6558                    .mul_add(vtx, sn.get_y().mul_add(vty, sn.get_z() * vtz));
6559                let ndv: f32 = ndv_raw.clamp(0.02, 1.0);
6560                let f_om: f32 = 1.0 - ndv;
6561                let f_om2: f32 = f_om * f_om;
6562                let fresnel_t: f32 = f_om2 * f_om2 * f_om;
6563                let vdl: f32 = sun_dir
6564                    .get_x()
6565                    .mul_add(vtx, sun_dir.get_y().mul_add(vty, sun_dir.get_z() * vtz));
6566                let spec_col: Vec3 = if tri.n_dot_l > 0.0 {
6567                    let ndh_unnorm: f32 = (tri.n_dot_l + ndv_raw).max(0.0);
6568                    let h_len_sq: f32 = 2.0_f32.mul_add(vdl, 2.0).max(1e-6);
6569                    let ndh_sq: f32 = (ndh_unnorm * ndh_unnorm) / h_len_sq;
6570                    let ggx_denom: f32 = ndh_sq.mul_add(tri.alpha2 - 1.0, 1.0);
6571                    let spec_num: f32 = (0.25 * tri.alpha2 * tri.n_dot_l) * run.shadow[s_i];
6572                    let ggx_term: f32 = (ggx_denom * ggx_denom).mul_add(PI, 1e-4);
6573                    let vis_den: f32 = ndv.mul_add(tri.n_dot_l.max(0.06), 0.08);
6574                    let spec_s: f32 = (spec_num / (ggx_term * vis_den)).min(4.5);
6575                    let fresnel_rgb: Vec3 =
6576                        tri.f0.add(Vec3::splat(1.0).sub(tri.f0).scale(fresnel_t));
6577                    fresnel_rgb.mul(sun_col.scale(spec_s))
6578                } else {
6579                    Vec3::zero()
6580                };
6581                let depth: f32 = run.depths[s_i];
6582                let wpx: f32 = rx[lane].mul_add(depth, cpx);
6583                let wpy: f32 = ry[lane].mul_add(depth, cpy);
6584                let wpz: f32 = rz[lane].mul_add(depth, cpz);
6585                let mut surf_base: Vec3 = tri.mat_base;
6586                let mut surf_emissive: Vec3 = tri.mat_emissive;
6587                let mut surf_refl: f32 = tri.mat_refl;
6588                if DETAIL == 2 {
6589                    let u_coord: f32 = if facade_u_is_z { wpz } else { wpx };
6590                    let (nb, ne, nr): (Vec3, Vec3, f32) = Self::eval_facade_detail(
6591                        (u_coord, wpy, depth, frame_context.inv_height),
6592                        (surf_base, surf_emissive, surf_refl),
6593                    );
6594                    surf_base = nb;
6595                    surf_emissive = ne;
6596                    surf_refl = nr;
6597                } else if DETAIL == 1 && wpy.abs() < 0.15 {
6598                    let (nb, nr): (Vec3, f32) = Self::eval_road_detail(
6599                        (wpx, wpz, depth, frame_context.inv_height),
6600                        (
6601                            Vec3::new(vtx, vty, vtz),
6602                            fresnel_t,
6603                            tri.metallic,
6604                            frame_context.world_time_secs,
6605                        ),
6606                        surf_base,
6607                    );
6608                    surf_base = nb;
6609                    surf_refl = nr;
6610                }
6611                let kd_scale: f32 = (tri.diffuse_scale * (1.0 - fresnel_t * 0.55)).max(0.08);
6612                let direct: Vec3 = sun_col.scale(tri.n_dot_l * run.shadow[s_i] * kd_scale);
6613                let indirect: Vec3 = tri.ambient_sky.scale(0.44 * run.ao[s_i]).add(Vec3::new(
6614                    run.gi_r[s_i],
6615                    run.gi_g[s_i],
6616                    run.gi_b[s_i],
6617                ));
6618                let mut radiance: Vec3 = surf_base
6619                    .mul(direct.add(indirect))
6620                    .add(spec_col)
6621                    .add(surf_emissive);
6622                if tri.do_refl {
6623                    let refl_fresnel: f32 =
6624                        (0.18 + 0.82 * fresnel_t + tri.metallic * 0.25).clamp(0.18, 0.95);
6625                    let refl_blend: f32 = (surf_refl * refl_fresnel).clamp(0.0, 0.82);
6626                    radiance = radiance.lerp(
6627                        Vec3::new(run.refl_r[s_i], run.refl_g[s_i], run.refl_b[s_i]),
6628                        refl_blend,
6629                    );
6630                }
6631                if frame_context.fog_on {
6632                    let height_atten: f32 = if wpy > 0.0 {
6633                        (1.0 / (1.0 + wpy * 0.045)).max(0.32)
6634                    } else {
6635                        1.0
6636                    };
6637                    let fd: f32 = depth * frame_context.inv_fog_distance * height_atten;
6638                    let fog_t: f32 = (fd / (1.0 + fd)).clamp(0.0, 0.85);
6639                    let sun_align: f32 = (-vdl).max(0.0);
6640                    let sa2: f32 = sun_align * sun_align;
6641                    let shaft: f32 = sa2 * sa2 * fog_t * (0.35 + 0.65 * run.shadow[s_i]);
6642                    let fog_col: Vec3 = sky_horizon.add(sun_col.scale(shaft * 0.55));
6643                    radiance = radiance.lerp(fog_col, fog_t);
6644                }
6645                let exposed: Vec3 = radiance.scale(frame_context.exposure_scale);
6646                exp_r_arr[lane] = exposed.get_x();
6647                exp_g_arr[lane] = exposed.get_y();
6648                exp_b_arr[lane] = exposed.get_z();
6649            }
6650        }
6651        let (rgba_4, luma_4): ([[u8; 4]; 4], [u8; 4]) =
6652            Vec3::aces_rgba8_luma_4x(exp_r_arr, exp_g_arr, exp_b_arr);
6653        c_dst[0..4].copy_from_slice(&rgba_4[0]);
6654        c_dst[4..8].copy_from_slice(&rgba_4[1]);
6655        c_dst[8..12].copy_from_slice(&rgba_4[2]);
6656        c_dst[12..16].copy_from_slice(&rgba_4[3]);
6657        l_dst[0..4].copy_from_slice(&luma_4);
6658        if let Some((b_lane, b_cell)) = bloom_slot {
6659            let er: f32 = (exp_r_arr[b_lane] - 1.05).max(0.0);
6660            let eg: f32 = (exp_g_arr[b_lane] - 1.05).max(0.0);
6661            let eb: f32 = (exp_b_arr[b_lane] - 1.05).max(0.0);
6662            *b_cell = [er, eg, eb, 0.0];
6663            let rg_pos: bool = er > 0.0 || eg > 0.0;
6664            rg_pos || eb > 0.0
6665        } else {
6666            false
6667        }
6668    }
6669
6670    /// Loops `shade_span_4x_specialized<DETAIL>` across up to 32 pixels of one triangle run with zero probe register pressure.
6671    ///
6672    /// # Arguments
6673    ///
6674    /// - `&DeferredFrameContext` - Per-frame shading context.
6675    /// - `&GShadeTri` - Precomputed triangle PBR record.
6676    /// - `(usize, usize, Vec3, Vec3)` - `(px_start, count, start_raw_ray, ray_dx)`.
6677    /// - `&RunScratch32` - Pre-upsampled 32-pixel L1 probe & depth arrays.
6678    /// - `&mut RunRowOut<'_>` - Writable scanline color, luma, and bloom outputs.
6679    ///
6680    /// # Returns
6681    ///
6682    /// - `bool` - `true` when any pixel in the chunk emitted non-zero HDR bloom.
6683    #[inline(always)]
6684    fn shade_run_32_loop<const DETAIL: u8>(
6685        frame_context: &DeferredFrameContext,
6686        tri: &GShadeTri,
6687        span: (usize, usize, Vec3, Vec3),
6688        run: &RunScratch32,
6689        out: &mut RunRowOut<'_>,
6690    ) -> bool {
6691        let (px_start, count, mut raw_ray, ray_dx): (usize, usize, Vec3, Vec3) = span;
6692        let write_bloom_row: bool = out.write_bloom;
6693        let bloom_row_off: usize = out.bloom_off;
6694        let ray_dx_4: Vec3 = ray_dx.scale(4.0);
6695        let b_lane: usize = (4 - (px_start & 3)) & 3;
6696        let mut any_bloom: bool = false;
6697        let mut off: usize = 0;
6698        while off < count {
6699            let cur_px: usize = px_start + off;
6700            let base_c: usize = cur_px * 4;
6701            let bloom_slot: Option<(usize, &mut [f32; 4])> = if write_bloom_row {
6702                let bidx: usize = bloom_row_off + ((cur_px + b_lane) >> 2);
6703                if bidx < out.bloom_band.len() {
6704                    Some((b_lane, &mut out.bloom_band[bidx]))
6705                } else {
6706                    None
6707                }
6708            } else {
6709                None
6710            };
6711            if Self::shade_span_4x_specialized::<DETAIL>(
6712                frame_context,
6713                tri,
6714                (raw_ray, ray_dx),
6715                (run, off),
6716                SpanShadeOut {
6717                    rgba: &mut out.color[base_c..(base_c + 16)],
6718                    luma: &mut out.luma[cur_px..(cur_px + 4)],
6719                    bloom: bloom_slot,
6720                },
6721            ) {
6722                any_bloom = true;
6723            }
6724            raw_ray = raw_ray.add(ray_dx_4);
6725            off += 4;
6726        }
6727        any_bloom
6728    }
6729
6730    /// Outlined zero-spill leaf kernel for plain PBR triangles (`DETAIL = 0`).
6731    ///
6732    /// # Arguments
6733    ///
6734    /// - `&DeferredFrameContext` - Per-frame shading context.
6735    /// - `&GShadeTri` - Triangle PBR record.
6736    /// - `(usize, usize, Vec3, Vec3)` - `(px_start, count, start_raw_ray, ray_dx)`.
6737    /// - `&RunScratch32` - L1-hot run scratch.
6738    /// - `&mut RunRowOut<'_>` - Writable scanline output slices.
6739    ///
6740    /// # Returns
6741    ///
6742    /// - `bool` - `true` when bloom radiance was emitted.
6743    #[inline(never)]
6744    fn shade_run_plain_32(
6745        frame_context: &DeferredFrameContext,
6746        tri: &GShadeTri,
6747        span: (usize, usize, Vec3, Vec3),
6748        run: &RunScratch32,
6749        out: &mut RunRowOut<'_>,
6750    ) -> bool {
6751        Self::shade_run_32_loop::<0>(frame_context, tri, span, run, out)
6752    }
6753
6754    /// Outlined zero-spill leaf kernel for procedural asphalt road triangles (`DETAIL = 1`).
6755    ///
6756    /// # Arguments
6757    ///
6758    /// - `&DeferredFrameContext` - Per-frame shading context.
6759    /// - `&GShadeTri` - Triangle PBR record.
6760    /// - `(usize, usize, Vec3, Vec3)` - `(px_start, count, start_raw_ray, ray_dx)`.
6761    /// - `&RunScratch32` - L1-hot run scratch.
6762    /// - `&mut RunRowOut<'_>` - Writable scanline output slices.
6763    ///
6764    /// # Returns
6765    ///
6766    /// - `bool` - `true` when bloom radiance was emitted.
6767    #[inline(never)]
6768    fn shade_run_road_32(
6769        frame_context: &DeferredFrameContext,
6770        tri: &GShadeTri,
6771        span: (usize, usize, Vec3, Vec3),
6772        run: &RunScratch32,
6773        out: &mut RunRowOut<'_>,
6774    ) -> bool {
6775        let (px_start, count, start_raw_ray, ray_dx): (usize, usize, Vec3, Vec3) = span;
6776        if count == 0 {
6777            return false;
6778        }
6779        let cam: Vec3 = frame_context.camera_position;
6780        let last_off: usize = count.saturating_sub(1);
6781        let p0: Vec3 = cam.add(start_raw_ray.scale(run.depths[0]));
6782        let p1: Vec3 = cam.add(
6783            start_raw_ray
6784                .add(ray_dx.scale(last_off as f32))
6785                .scale(run.depths[last_off]),
6786        );
6787        if p0.get_x() <= 143.5 && p1.get_x() <= 143.5 {
6788            return Self::shade_run_32_loop::<1>(frame_context, tri, span, run, out);
6789        }
6790        let d0: f32 = (p0.get_x() - 64.0).hypot(p0.get_z() - p0.get_z().clamp(-140.0, 140.0));
6791        let d1: f32 = (p1.get_x() - 64.0).hypot(p1.get_z() - p1.get_z().clamp(-140.0, 140.0));
6792        if p0.get_x() > 144.2 && p1.get_x() > 144.2 && d0 > 78.5 && d1 > 78.5 {
6793            return Self::shade_run_ocean_32(frame_context, tri, span, run, out);
6794        }
6795        let mut any_bloom: bool = Self::shade_run_32_loop::<1>(frame_context, tri, span, run, out);
6796        let mut raw_ray: Vec3 = start_raw_ray;
6797        let sky_lut: &[[f32; 3]] = out.sky_lut;
6798        let aces_lut: &[u8] = out.aces_lut;
6799        for off in 0..count {
6800            let depth: f32 = run.depths[off];
6801            let world_p: Vec3 = cam.add(raw_ray.scale(depth));
6802            let wpx: f32 = world_p.get_x();
6803            if wpx > 144.0 {
6804                let wpz: f32 = world_p.get_z();
6805                let d_spine: f32 = (wpx - 64.0).hypot(wpz - wpz.clamp(-140.0, 140.0));
6806                if d_spine > 78.2 {
6807                    let px: usize = px_start + off;
6808                    let view_dir: Vec3 = raw_ray.normalize().scale(-1.0);
6809                    let rt_refl: Vec3 =
6810                        Vec3::new(run.refl_r[off], run.refl_g[off], run.refl_b[off]);
6811                    let radiance: Vec3 = Self::eval_ocean_water_radiance(
6812                        frame_context,
6813                        sky_lut,
6814                        (world_p, view_dir, depth),
6815                        (run.shadow[off], rt_refl),
6816                    );
6817                    let exposed: Vec3 = radiance.scale(frame_context.exposure_scale);
6818                    let rgba: [u8; 4] = Self::lut_aces3d_rgba8(aces_lut, exposed);
6819                    let cidx: usize = px * 4;
6820                    out.color[cidx..(cidx + 4)].copy_from_slice(&rgba);
6821                    out.luma[px] =
6822                        (((rgba[0] as u32) * 77 + (rgba[1] as u32) * 150 + (rgba[2] as u32) * 29)
6823                            >> 8) as u8;
6824                    if out.write_bloom && (px & 3) == 0 {
6825                        let bidx: usize = out.bloom_off + (px >> 2);
6826                        if bidx < out.bloom_band.len() {
6827                            let er: f32 = (exposed.get_x() - 1.15).max(0.0);
6828                            let eg: f32 = (exposed.get_y() - 1.15).max(0.0);
6829                            let eb: f32 = (exposed.get_z() - 1.15).max(0.0);
6830                            out.bloom_band[bidx] = [er, eg, eb, 0.0];
6831                            if er + eg + eb > 0.0 {
6832                                any_bloom = true;
6833                            }
6834                        }
6835                    }
6836                }
6837            }
6838            raw_ray = raw_ray.add(ray_dx);
6839        }
6840        any_bloom
6841    }
6842
6843    /// Outlined zero-spill leaf kernel for animated photorealistic ocean water triangles (`DETAIL = 3`).
6844    ///
6845    /// # Arguments
6846    ///
6847    /// - `&DeferredFrameContext` - Per-frame shading context.
6848    /// - `&GShadeTri` - Triangle PBR record.
6849    /// - `(usize, usize, Vec3, Vec3)` - `(px_start, count, start_raw_ray, ray_dx)`.
6850    /// - `&RunScratch32` - L1-hot run scratch.
6851    /// - `&mut RunRowOut<'_>` - Writable scanline output slices.
6852    ///
6853    /// # Returns
6854    ///
6855    /// - `bool` - `true` when bloom radiance was emitted.
6856    #[inline(never)]
6857    fn shade_run_ocean_32(
6858        frame_context: &DeferredFrameContext,
6859        tri: &GShadeTri,
6860        span: (usize, usize, Vec3, Vec3),
6861        run: &RunScratch32,
6862        out: &mut RunRowOut<'_>,
6863    ) -> bool {
6864        let _: &GShadeTri = tri;
6865        let (px_start, count, start_raw_ray, ray_dx): (usize, usize, Vec3, Vec3) = span;
6866        let mut raw_ray: Vec3 = start_raw_ray;
6867        let mut any_bloom: bool = false;
6868        let sky_lut: &[[f32; 3]] = out.sky_lut;
6869        let aces_lut: &[u8] = out.aces_lut;
6870        for off in 0..count {
6871            let px: usize = px_start + off;
6872            let depth: f32 = run.depths[off];
6873            let world_p: Vec3 = frame_context.camera_position.add(raw_ray.scale(depth));
6874            let view_dir: Vec3 = raw_ray.normalize().scale(-1.0);
6875            let rt_refl: Vec3 = Vec3::new(run.refl_r[off], run.refl_g[off], run.refl_b[off]);
6876            let radiance: Vec3 = Self::eval_ocean_water_radiance(
6877                frame_context,
6878                sky_lut,
6879                (world_p, view_dir, depth),
6880                (run.shadow[off], rt_refl),
6881            );
6882            let exposed: Vec3 = radiance.scale(frame_context.exposure_scale);
6883            let rgba: [u8; 4] = Self::lut_aces3d_rgba8(aces_lut, exposed);
6884            let cidx: usize = px * 4;
6885            out.color[cidx..(cidx + 4)].copy_from_slice(&rgba);
6886            out.luma[px] =
6887                (((rgba[0] as u32) * 77 + (rgba[1] as u32) * 150 + (rgba[2] as u32) * 29) >> 8)
6888                    as u8;
6889            if out.write_bloom && (px & 3) == 0 {
6890                let bidx: usize = out.bloom_off + (px >> 2);
6891                if bidx < out.bloom_band.len() {
6892                    let er: f32 = (exposed.get_x() - 1.15).max(0.0);
6893                    let eg: f32 = (exposed.get_y() - 1.15).max(0.0);
6894                    let eb: f32 = (exposed.get_z() - 1.15).max(0.0);
6895                    out.bloom_band[bidx] = [er, eg, eb, 0.0];
6896                    if er + eg + eb > 0.0 {
6897                        any_bloom = true;
6898                    }
6899                }
6900            }
6901            raw_ray = raw_ray.add(ray_dx);
6902        }
6903        any_bloom
6904    }
6905
6906    /// Outlined zero-spill leaf kernel for procedural architectural facade triangles (`DETAIL = 2`).
6907    ///
6908    /// # Arguments
6909    ///
6910    /// - `&DeferredFrameContext` - Per-frame shading context.
6911    /// - `&GShadeTri` - Triangle PBR record.
6912    /// - `(usize, usize, Vec3, Vec3)` - `(px_start, count, start_raw_ray, ray_dx)`.
6913    /// - `&RunScratch32` - L1-hot run scratch.
6914    /// - `&mut RunRowOut<'_>` - Writable scanline output slices.
6915    ///
6916    /// # Returns
6917    ///
6918    /// - `bool` - `true` when bloom radiance was emitted.
6919    #[inline(never)]
6920    fn shade_run_facade_32(
6921        frame_context: &DeferredFrameContext,
6922        tri: &GShadeTri,
6923        span: (usize, usize, Vec3, Vec3),
6924        run: &RunScratch32,
6925        out: &mut RunRowOut<'_>,
6926    ) -> bool {
6927        Self::shade_run_32_loop::<2>(frame_context, tri, span, run, out)
6928    }
6929
6930    /// Stage A probe-only leaf kernel upsampling up to 32 consecutive pixels of `tid` into L1-hot `RunScratch32` with zero PBR register pressure.
6931    ///
6932    /// # Arguments
6933    ///
6934    /// - `(&GShadeTri, u32, bool, bool)` - `(tri, tid, rt_active, gi_active)`.
6935    /// - `&ProbeBandContext<'_>` - Probe rows and horizontal bilinear stepping context.
6936    /// - `(&mut (usize, u32), &mut CachedProbeCell, &mut RunScratch32)` - Reusable cell and L1 scratch.
6937    /// - `(&[u32], &[f32], usize, usize)` - `(g_row, d_row, px_start, w)`.
6938    /// - `(&mut usize, &mut i32)` - `(gx_cur, sub_x)` updated for the upsampled count.
6939    ///
6940    /// # Returns
6941    ///
6942    /// - `usize` - Number of validated pixels (`0, 4, 8, ..., 32`) populated into `RunScratch32`.
6943    #[inline(never)]
6944    fn upsample_run_probes_32(
6945        tri_info: (&GShadeTri, u32, bool, bool),
6946        probe_ctx: &ProbeBandContext<'_>,
6947        cache: (&mut (usize, u32), &mut CachedProbeCell, &mut RunScratch32),
6948        rows: (&[u32], &[f32], usize, usize),
6949        cursor: (&mut usize, &mut i32),
6950    ) -> usize {
6951        let (tri, tid, rt_active, gi_active): (&GShadeTri, u32, bool, bool) = tri_info;
6952        let ProbeBandContext {
6953            top_row: probe_r0,
6954            bottom_row: probe_r1,
6955            wy0,
6956            wy1,
6957            gw_max,
6958            step2_i32,
6959            fx_lut,
6960        } = *probe_ctx;
6961        let (cached_probe_key, cached_cell, run): (
6962            &mut (usize, u32),
6963            &mut CachedProbeCell,
6964            &mut RunScratch32,
6965        ) = cache;
6966        let (g_row, d_row, px_start, width_val): (&[u32], &[f32], usize, usize) = rows;
6967        let (gx_ref, sub_ref): (&mut usize, &mut i32) = cursor;
6968        let check_shadow_edge: bool = !gi_active && tri.n_dot_l > 0.02;
6969        let mut run_len: usize = 0;
6970        while run_len < 32 {
6971            let px: usize = px_start + run_len;
6972            if px + 4 > width_val
6973                || g_row[px] != tid
6974                || g_row[px + 1] != tid
6975                || g_row[px + 2] != tid
6976                || g_row[px + 3] != tid
6977            {
6978                break;
6979            }
6980            let depths: [f32; 4] =
6981                Self::recip_4x([d_row[px], d_row[px + 1], d_row[px + 2], d_row[px + 3]]);
6982            run.depths[run_len..(run_len + 4)].copy_from_slice(&depths);
6983            run_len += 4;
6984        }
6985        if run_len == 0 {
6986            return 0;
6987        }
6988        if !rt_active {
6989            let mut sub_out: i32 = *sub_ref + ((run_len as i32) * 2);
6990            let mut gx_out: usize = *gx_ref;
6991            while sub_out >= step2_i32 {
6992                sub_out -= step2_i32;
6993                gx_out += 1;
6994            }
6995            *gx_ref = gx_out;
6996            *sub_ref = sub_out;
6997            return run_len;
6998        }
6999        let mut gx_cur: usize = *gx_ref;
7000        let mut sub_x: i32 = *sub_ref;
7001        let mut item_index: usize = 0;
7002        'run: while item_index < run_len {
7003            if sub_x >= 0 && gx_cur < gw_max {
7004                let gx0: usize = gx_cur;
7005                let gx1: usize = gx_cur + 1;
7006                let probe_key: (usize, u32) = ((gx0 << 16) | gx1, tid);
7007                if *cached_probe_key != probe_key {
7008                    let prev_adj: bool =
7009                        gx0 > 0 && *cached_probe_key == ((((gx0 - 1) << 16) | gx0), tid);
7010                    *cached_probe_key = probe_key;
7011                    if prev_adj {
7012                        CachedProbeCell::shift_right_in_place(
7013                            cached_cell,
7014                            probe_r0,
7015                            probe_r1,
7016                            gx1,
7017                            tri.shade_n,
7018                            (tri.do_refl, gi_active),
7019                        );
7020                    } else {
7021                        CachedProbeCell::load_into(
7022                            cached_cell,
7023                            probe_r0,
7024                            probe_r1,
7025                            (gx0, gx1),
7026                            tri.shade_n,
7027                            (tri.do_refl, gi_active),
7028                        );
7029                    }
7030                }
7031                let rem_in_cell: usize = (((step2_i32 - 1 - sub_x) >> 1) as usize) + 1;
7032                let mut avail: usize = (run_len - item_index).min(rem_in_cell);
7033                let mut ran_4x: bool = false;
7034                while avail >= 4 {
7035                    let base_s: usize = sub_x as usize;
7036                    let fx_4: [f32; 4] = [
7037                        fx_lut[base_s.min(15)],
7038                        fx_lut[(base_s + 2).min(15)],
7039                        fx_lut[(base_s + 4).min(15)],
7040                        fx_lut[(base_s + 6).min(15)],
7041                    ];
7042                    if !CachedProbeCell::sample_4x_same_cell(
7043                        cached_cell,
7044                        fx_4,
7045                        (wy0, wy1),
7046                        (check_shadow_edge, tri.do_refl, gi_active),
7047                        (run, item_index),
7048                    ) {
7049                        break 'run;
7050                    }
7051                    item_index += 4;
7052                    sub_x += 8;
7053                    avail -= 4;
7054                    ran_4x = true;
7055                }
7056                if avail > 0 {
7057                    if ran_4x {
7058                        let back: usize = 4 - avail;
7059                        let off_back: usize = item_index - back;
7060                        let s_back: usize = (sub_x - (back as i32) * 2) as usize;
7061                        let fx_4: [f32; 4] = [
7062                            fx_lut[s_back.min(15)],
7063                            fx_lut[(s_back + 2).min(15)],
7064                            fx_lut[(s_back + 4).min(15)],
7065                            fx_lut[(s_back + 6).min(15)],
7066                        ];
7067                        if !CachedProbeCell::sample_4x_same_cell(
7068                            cached_cell,
7069                            fx_4,
7070                            (wy0, wy1),
7071                            (check_shadow_edge, tri.do_refl, gi_active),
7072                            (run, off_back),
7073                        ) {
7074                            break 'run;
7075                        }
7076                        item_index += avail;
7077                        sub_x += (avail as i32) * 2;
7078                    } else {
7079                        for _ in 0..avail {
7080                            let fx: f32 = fx_lut[(sub_x as usize).min(15)];
7081                            let wx0: f32 = 1.0 - fx;
7082                            let bws: [f32; 4] = [wx0 * wy0, fx * wy0, wx0 * wy1, fx * wy1];
7083                            let depth_i: f32 = run.depths[item_index];
7084                            let (vm, sh, s_min, s_max, rf, gi, ao): (
7085                                u32,
7086                                f32,
7087                                f32,
7088                                f32,
7089                                Vec3,
7090                                Vec3,
7091                                f32,
7092                            ) = CachedProbeCell::sample_1x(
7093                                cached_cell,
7094                                bws,
7095                                depth_i,
7096                                (tri.do_refl, gi_active),
7097                            );
7098                            let edge_max_d: f32 = if cfg!(target_arch = "wasm32") {
7099                                18.0
7100                            } else {
7101                                42.0
7102                            };
7103                            if vm == 0
7104                                || (check_shadow_edge
7105                                    && depth_i < edge_max_d
7106                                    && (s_max - s_min) > 0.12)
7107                            {
7108                                break 'run;
7109                            }
7110                            run.shadow[item_index] = sh;
7111                            if tri.do_refl {
7112                                run.refl_r[item_index] = rf.get_x();
7113                                run.refl_g[item_index] = rf.get_y();
7114                                run.refl_b[item_index] = rf.get_z();
7115                            }
7116                            if gi_active {
7117                                run.gi_r[item_index] = gi.get_x();
7118                                run.gi_g[item_index] = gi.get_y();
7119                                run.gi_b[item_index] = gi.get_z();
7120                                run.ao[item_index] = ao;
7121                            }
7122                            item_index += 1;
7123                            sub_x += 2;
7124                        }
7125                    }
7126                }
7127                if sub_x >= step2_i32 {
7128                    sub_x -= step2_i32;
7129                    gx_cur += 1;
7130                }
7131            } else {
7132                let (gx0, gx1): (usize, usize) = if sub_x <= 0 && gx_cur == 0 {
7133                    (0, gw_max.min(1))
7134                } else {
7135                    (gw_max, gw_max)
7136                };
7137                let probe_key: (usize, u32) = ((gx0 << 16) | gx1, tid);
7138                if *cached_probe_key != probe_key {
7139                    *cached_probe_key = probe_key;
7140                    CachedProbeCell::load_into(
7141                        cached_cell,
7142                        probe_r0,
7143                        probe_r1,
7144                        (gx0, gx1),
7145                        tri.shade_n,
7146                        (tri.do_refl, gi_active),
7147                    );
7148                }
7149                let bws: [f32; 4] = [wy0, 0.0, wy1, 0.0];
7150                let depth_i: f32 = run.depths[item_index];
7151                let (vm, sh, s_min, s_max, rf, gi, ao): (u32, f32, f32, f32, Vec3, Vec3, f32) =
7152                    CachedProbeCell::sample_1x(cached_cell, bws, depth_i, (tri.do_refl, gi_active));
7153                let edge_max_d: f32 = if cfg!(target_arch = "wasm32") {
7154                    18.0
7155                } else {
7156                    42.0
7157                };
7158                if vm == 0 || (check_shadow_edge && depth_i < edge_max_d && (s_max - s_min) > 0.12)
7159                {
7160                    break 'run;
7161                }
7162                run.shadow[item_index] = sh;
7163                if tri.do_refl {
7164                    run.refl_r[item_index] = rf.get_x();
7165                    run.refl_g[item_index] = rf.get_y();
7166                    run.refl_b[item_index] = rf.get_z();
7167                }
7168                if gi_active {
7169                    run.gi_r[item_index] = gi.get_x();
7170                    run.gi_g[item_index] = gi.get_y();
7171                    run.gi_b[item_index] = gi.get_z();
7172                    run.ao[item_index] = ao;
7173                }
7174                item_index += 1;
7175                sub_x += 2;
7176                if sub_x >= step2_i32 {
7177                    sub_x -= step2_i32;
7178                    gx_cur += 1;
7179                }
7180            }
7181        }
7182        let out_count: usize = item_index & !3;
7183        if out_count == item_index {
7184            *gx_ref = gx_cur;
7185            *sub_ref = sub_x;
7186        } else {
7187            let mut final_sub: i32 = *sub_ref + ((out_count as i32) * 2);
7188            let mut final_gx: usize = *gx_ref;
7189            while final_sub >= step2_i32 {
7190                final_sub -= step2_i32;
7191                final_gx += 1;
7192            }
7193            *gx_ref = final_gx;
7194            *sub_ref = final_sub;
7195        }
7196        out_count
7197    }
7198
7199    /// Shades an entire contiguous horizontal run of 4-pixel spans belonging to triangle `tid` in 32-pixel L1-hot decoupled stages (`upsample_run_probes_32` + const-specialized leaf shader).
7200    ///
7201    /// # Arguments
7202    ///
7203    /// - `&DeferredFrameContext` - Per-frame camera, sun, and fog configuration.
7204    /// - `(&GShadeTri, u32, bool, bool)` - `(tri, tid, rt_active, gi_active)`.
7205    /// - `&ProbeBandContext<'_>` - Probe rows and horizontal bilinear stepping context.
7206    /// - `(&mut (usize, u32), &mut CachedProbeCell, &mut RunScratch32)` - Reusable cell and 32-pixel L1 scratch.
7207    /// - `(&[u32], &[f32], RunRowOut<'_>)` - Scanline G-Buffer, depth, and writable output buffers.
7208    /// - `(&mut usize, &mut Vec3, Vec3, &mut usize, &mut i32)` - Scanline cursor `(px, raw_ray, ray_dx, gx_cur, sub_x)`.
7209    ///
7210    /// # Returns
7211    ///
7212    /// - `bool` - `true` when any 4-pixel span in the run emitted non-zero HDR bloom radiance.
7213    #[inline(always)]
7214    fn shade_tri_run_4x(
7215        frame_context: &DeferredFrameContext,
7216        tri_info: (&GShadeTri, u32, bool, bool),
7217        probe_ctx: &ProbeBandContext<'_>,
7218        cache: (&mut (usize, u32), &mut CachedProbeCell, &mut RunScratch32),
7219        rows: (&[u32], &[f32], RunRowOut<'_>),
7220        state: (&mut usize, &mut Vec3, Vec3, &mut usize, &mut i32),
7221    ) -> bool {
7222        let (tri, tid, _, _): (&GShadeTri, u32, bool, bool) = tri_info;
7223        let (cached_probe_key, cached_cell, run): (
7224            &mut (usize, u32),
7225            &mut CachedProbeCell,
7226            &mut RunScratch32,
7227        ) = cache;
7228        let (g_row, d_row, mut out_row): (&[u32], &[f32], RunRowOut<'_>) = rows;
7229        let (px_ref, raw_ray_ref, ray_dx, gx_ref, sub_ref): (
7230            &mut usize,
7231            &mut Vec3,
7232            Vec3,
7233            &mut usize,
7234            &mut i32,
7235        ) = state;
7236        let width_val: usize = frame_context.width;
7237        let sn: Vec3 = tri.shade_n;
7238        let detail_kind: u8 =
7239            if tri.surface_detail == SurfaceDetailMode::OceanWater && sn.get_y() > 0.90 {
7240                3
7241            } else if tri.surface_detail == SurfaceDetailMode::ArchitecturalFacade
7242                && sn.get_y().abs() < 0.25
7243                && tri.mat_emissive.length_sq() < 0.02
7244            {
7245                2
7246            } else if tri.surface_detail == SurfaceDetailMode::RoadSurface && sn.get_y() > 0.92 {
7247                1
7248            } else {
7249                0
7250            };
7251        let mut any_bloom: bool = false;
7252        loop {
7253            let px0: usize = *px_ref;
7254            let count: usize = Self::upsample_run_probes_32(
7255                tri_info,
7256                probe_ctx,
7257                (cached_probe_key, cached_cell, run),
7258                (g_row, d_row, px0, width_val),
7259                (gx_ref, sub_ref),
7260            );
7261            if count == 0 {
7262                break;
7263            }
7264            let hit: bool = match detail_kind {
7265                3 => Self::shade_run_ocean_32(
7266                    frame_context,
7267                    tri,
7268                    (px0, count, *raw_ray_ref, ray_dx),
7269                    run,
7270                    &mut out_row,
7271                ),
7272                2 => Self::shade_run_facade_32(
7273                    frame_context,
7274                    tri,
7275                    (px0, count, *raw_ray_ref, ray_dx),
7276                    run,
7277                    &mut out_row,
7278                ),
7279                1 => Self::shade_run_road_32(
7280                    frame_context,
7281                    tri,
7282                    (px0, count, *raw_ray_ref, ray_dx),
7283                    run,
7284                    &mut out_row,
7285                ),
7286                _ => Self::shade_run_plain_32(
7287                    frame_context,
7288                    tri,
7289                    (px0, count, *raw_ray_ref, ray_dx),
7290                    run,
7291                    &mut out_row,
7292                ),
7293            };
7294            if hit {
7295                any_bloom = true;
7296            }
7297            *px_ref = px0 + count;
7298            *raw_ray_ref = raw_ray_ref.add(ray_dx.scale(count as f32));
7299            if count < 32 {
7300                break;
7301            }
7302        }
7303        let _: u32 = tid;
7304        any_bloom
7305    }
7306
7307    /// Fused Barrier 2 worker running streaming 2-row L1 joint-bilateral probe denoise plus vectorized 4-pixel SIMD Cook-Torrance GGX PBR shading, SIMD ACES tonemap, and bloom extraction.
7308    ///
7309    /// # Arguments
7310    ///
7311    /// - `&DeferredFrameContext` - Shared per-frame camera, sun, and RT settings.
7312    /// - `&ShadeBandInputs<'_>` - Read-only depth, G-Buffer IDs, shading records, raw SoA probes, static BVH, and dynamic instances.
7313    /// - `(usize, &mut [u8], &mut [u8], &mut [[f32; 4]])` - `(py_start, color band, luma band, bloom band)`.
7314    ///
7315    /// # Returns
7316    ///
7317    /// - `(usize, bool)` - `(edge_rays_traced, band_emitted_nonzero_bloom)`.
7318    fn shade_deferred_band(
7319        frame_context: &DeferredFrameContext,
7320        inputs: &ShadeBandInputs<'_>,
7321        outputs: (usize, &mut [u8], &mut [u8], &mut [[f32; 4]]),
7322    ) -> (usize, bool) {
7323        let depth_buf: &[f32] = inputs.depth_buf;
7324        let g_tri_idx: &[u32] = inputs.g_tri_idx;
7325        let shaded_tris: &[GShadeTri] = inputs.shaded_tris;
7326        let raw_probes: &RtProbeGridSoa = inputs.raw_probes;
7327        let (py_start, color_band, luma_band, bloom_band): (
7328            usize,
7329            &mut [u8],
7330            &mut [u8],
7331            &mut [[f32; 4]],
7332        ) = outputs;
7333        let width_val: usize = frame_context.width;
7334        let gw: usize = frame_context.grid_width;
7335        let gh: usize = frame_context.grid_height;
7336        let gw_max: usize = gw.saturating_sub(1);
7337        let gh_max: usize = gh.saturating_sub(1);
7338        let border_width: usize = frame_context.bloom_width;
7339        let rt_step: usize = frame_context.raytrace_step.max(1);
7340        let step_f: f32 = rt_step as f32;
7341        let inv_step: f32 = 1.0 / step_f;
7342        let step2_i32: i32 = (rt_step * 2) as i32;
7343        let init_sub_x: i32 = 1 - (rt_step as i32);
7344        let inv_step2: f32 = 0.5 * inv_step;
7345        let mut fx_lut: [f32; 16] = [0.0; 16];
7346        let lut_len: usize = (rt_step * 2).min(16);
7347        for (idx, slot) in fx_lut.iter_mut().take(lut_len).enumerate() {
7348            *slot = (idx as f32) * inv_step2;
7349        }
7350        let sun_dir: Vec3 = frame_context.sun.get_direction();
7351        let inv_sun: Vec3 = frame_context.inv_sun_dir;
7352        let sun_col: Vec3 = frame_context.sun.get_color();
7353        let sky_horizon: Vec3 = frame_context.sun.get_sky_horizon();
7354        let rt_active: bool = frame_context.raytrace_mode != RayTracingMode::Off
7355            && frame_context.raytrace_step > 0
7356            && !raw_probes.is_empty();
7357        let gi_active: bool = (frame_context.raytrace_mode == RayTracingMode::FullPathTracedGi
7358            || frame_context.has_clustered_lights)
7359            && rt_active;
7360        let band_rows: usize = luma_band.len() / width_val.max(1);
7361        let ray_dx: Vec3 = frame_context
7362            .camera_right_scaled
7363            .scale(2.0 * frame_context.inv_width);
7364        let ndc_x0: f32 = frame_context.inv_width - 1.0;
7365        let mut edge_rays: usize = 0;
7366        let mut bloom_emitted: bool = false;
7367        let mut static_shadow_cache: u32 = u32::MAX;
7368        let mut dyn_shadow_cache: u32 = u32::MAX;
7369        let use_stack_denoise: bool = rt_active && gw <= PROBE_ROW_STACK_CAP;
7370        let mut a_is_r0: bool = true;
7371        let mut run_scratch: RunScratch32 = RunScratch32 {
7372            depths: [1.0; 32],
7373            shadow: [1.0; 32],
7374            refl_r: [sky_horizon.get_x(); 32],
7375            refl_g: [sky_horizon.get_y(); 32],
7376            refl_b: [sky_horizon.get_z(); 32],
7377            gi_r: [0.0; 32],
7378            gi_g: [0.0; 32],
7379            gi_b: [0.0; 32],
7380            ao: [1.0; 32],
7381        };
7382        PROBE_ROW_SCRATCH.with(|cell: &RefCell<Box<RtProbeRowScratch>>| {
7383            let mut guard: RefMut<'_, Box<RtProbeRowScratch>> = cell.borrow_mut();
7384            let scratch: &mut RtProbeRowScratch = guard.as_mut();
7385            if scratch.frame_gen != frame_context.probe_frame_generation {
7386                scratch.frame_gen = frame_context.probe_frame_generation;
7387                scratch.cached_gy_a = usize::MAX;
7388                scratch.cached_gy_b = usize::MAX;
7389            }
7390            for local_y in 0..band_rows {
7391                let py: usize = py_start + local_y;
7392                let row_off: usize = py * width_val;
7393                let out_row_luma: usize = local_y * width_val;
7394                let out_row_rgba: usize = out_row_luma * 4;
7395                let write_bloom_row: bool =
7396                    frame_context.bloom_on && (py & 3) == 0 && border_width > 0;
7397                let mut row_bloom_hit: bool = false;
7398                let bloom_row_off: usize = if write_bloom_row {
7399                    (local_y / 4) * border_width
7400                } else {
7401                    0
7402                };
7403                let ndc_y: f32 = 1.0 - 2.0 * (((py as f32) + 0.5) * frame_context.inv_height);
7404                let row_base_dir: Vec3 = frame_context
7405                    .camera_forward
7406                    .add(frame_context.camera_up_scaled.scale(ndc_y));
7407                let gy_f: f32 = (((py as f32) + 0.5) * inv_step - 0.5).clamp(0.0, gh_max as f32);
7408                let gy0: usize = (gy_f as usize).min(gh_max);
7409                let gy1: usize = (gy0 + 1).min(gh_max);
7410                let fy: f32 = gy_f - (gy0 as f32);
7411                let wy0: f32 = 1.0 - fy;
7412                let wy1: f32 = fy;
7413                if use_stack_denoise {
7414                    if gy0 == scratch.cached_gy_a {
7415                        a_is_r0 = true;
7416                    } else if gy0 == scratch.cached_gy_b {
7417                        a_is_r0 = false;
7418                    } else {
7419                        a_is_r0 = true;
7420                        Self::populate_probe_row_stack(
7421                            raw_probes,
7422                            gw,
7423                            gh,
7424                            gy0,
7425                            (inputs.denoise_probes, inputs.denoise_gi_channels),
7426                            &mut scratch.buf_a,
7427                        );
7428                        scratch.cached_gy_a = gy0;
7429                    }
7430                    if gy1 != gy0 {
7431                        if a_is_r0 && gy1 != scratch.cached_gy_b {
7432                            Self::populate_probe_row_stack(
7433                                raw_probes,
7434                                gw,
7435                                gh,
7436                                gy1,
7437                                (inputs.denoise_probes, inputs.denoise_gi_channels),
7438                                &mut scratch.buf_b,
7439                            );
7440                            scratch.cached_gy_b = gy1;
7441                        } else if !a_is_r0 && gy1 != scratch.cached_gy_a {
7442                            Self::populate_probe_row_stack(
7443                                raw_probes,
7444                                gw,
7445                                gh,
7446                                gy1,
7447                                (inputs.denoise_probes, inputs.denoise_gi_channels),
7448                                &mut scratch.buf_a,
7449                            );
7450                            scratch.cached_gy_a = gy1;
7451                        }
7452                    }
7453                }
7454                let (probe_r0, probe_r1): (RtProbeRowView<'_>, RtProbeRowView<'_>) =
7455                    if use_stack_denoise {
7456                        let (v0, v_other): (RtProbeRowView<'_>, RtProbeRowView<'_>) = if a_is_r0 {
7457                            (scratch.buf_a.as_view(gw), scratch.buf_b.as_view(gw))
7458                        } else {
7459                            (scratch.buf_b.as_view(gw), scratch.buf_a.as_view(gw))
7460                        };
7461                        if gy1 == gy0 { (v0, v0) } else { (v0, v_other) }
7462                    } else if rt_active {
7463                        let grid: &RtProbeGridSoa = if !inputs.wide_denoised_probes.is_empty() {
7464                            inputs.wide_denoised_probes
7465                        } else {
7466                            raw_probes
7467                        };
7468                        (grid.row_view(gy0, gw), grid.row_view(gy1, gw))
7469                    } else {
7470                        (scratch.buf_a.as_view(0), scratch.buf_a.as_view(0))
7471                    };
7472                let mut cached_probe_key: (usize, u32) = (usize::MAX, u32::MAX);
7473                let mut cached_cell: CachedProbeCell = CachedProbeCell::empty();
7474                let mut raw_ray: Vec3 =
7475                    row_base_dir.add(frame_context.camera_right_scaled.scale(ndc_x0));
7476                let mut gx_cur: usize = 0;
7477                let mut sub_x: i32 = init_sub_x;
7478                let g_row: &[u32] = &g_tri_idx[row_off..(row_off + width_val)];
7479                let d_row: &[f32] = &depth_buf[row_off..(row_off + width_val)];
7480                let c_row: &mut [u8] =
7481                    &mut color_band[out_row_rgba..(out_row_rgba + width_val * 4)];
7482                let l_row: &mut [u8] = &mut luma_band[out_row_luma..(out_row_luma + width_val)];
7483                let mut px: usize = 0;
7484                while px < width_val {
7485                    let tid: u32 = g_row[px];
7486                    if tid == u32::MAX {
7487                        let sky_hdr: Vec3 =
7488                            Self::sample_sky_lut(inputs.sky_lut, raw_ray, &frame_context.sun);
7489                        let exposed: Vec3 = sky_hdr.scale(frame_context.exposure_scale);
7490                        let rgba: [u8; 4] = Self::lut_aces3d_rgba8(inputs.aces_lut, exposed);
7491                        let luma: u8 = (((rgba[0] as u32) * 77
7492                            + (rgba[1] as u32) * 150
7493                            + (rgba[2] as u32) * 29)
7494                            >> 8) as u8;
7495                        if write_bloom_row && (px & 3) == 0 {
7496                            let bidx: usize = bloom_row_off + (px >> 2);
7497                            if bidx < bloom_band.len() {
7498                                let er: f32 = (exposed.get_x() - 1.15).max(0.0);
7499                                let eg: f32 = (exposed.get_y() - 1.15).max(0.0);
7500                                let eb: f32 = (exposed.get_z() - 1.15).max(0.0);
7501                                bloom_band[bidx] = [er, eg, eb, 0.0];
7502                                if er + eg + eb > 0.0 {
7503                                    bloom_emitted = true;
7504                                    row_bloom_hit = true;
7505                                }
7506                            }
7507                        }
7508                        let cidx_sky: usize = px * 4;
7509                        c_row[cidx_sky..(cidx_sky + 4)].copy_from_slice(&rgba);
7510                        l_row[px] = luma;
7511                        raw_ray = raw_ray.add(ray_dx);
7512                        sub_x += 2;
7513                        if sub_x >= step2_i32 {
7514                            sub_x -= step2_i32;
7515                            gx_cur += 1;
7516                        }
7517                        px += 1;
7518                        continue;
7519                    }
7520                    if px + 4 <= width_val
7521                        && g_row[px + 1] == tid
7522                        && g_row[px + 2] == tid
7523                        && g_row[px + 3] == tid
7524                        && shaded_tris[tid as usize].smooth_idx == u32::MAX
7525                    {
7526                        let tri: &GShadeTri = &shaded_tris[tid as usize];
7527                        let prev_px: usize = px;
7528                        let probe_band: ProbeBandContext<'_> = ProbeBandContext {
7529                            top_row: &probe_r0,
7530                            bottom_row: &probe_r1,
7531                            wy0,
7532                            wy1,
7533                            gw_max,
7534                            step2_i32,
7535                            fx_lut: &fx_lut,
7536                        };
7537                        let hit_b: bool = Self::shade_tri_run_4x(
7538                            frame_context,
7539                            (tri, tid, rt_active, gi_active),
7540                            &probe_band,
7541                            (&mut cached_probe_key, &mut cached_cell, &mut run_scratch),
7542                            (
7543                                g_row,
7544                                d_row,
7545                                RunRowOut {
7546                                    color: c_row,
7547                                    luma: l_row,
7548                                    write_bloom: write_bloom_row,
7549                                    bloom_off: bloom_row_off,
7550                                    bloom_band,
7551                                    sky_lut: inputs.sky_lut,
7552                                    aces_lut: inputs.aces_lut,
7553                                },
7554                            ),
7555                            (&mut px, &mut raw_ray, ray_dx, &mut gx_cur, &mut sub_x),
7556                        );
7557                        if hit_b {
7558                            bloom_emitted = true;
7559                            row_bloom_hit = true;
7560                        }
7561                        if px != prev_px {
7562                            continue;
7563                        }
7564                    }
7565                    let cidx: usize = px * 4;
7566                    let tri: &GShadeTri = &shaded_tris[tid as usize];
7567                    let depth: f32 = 1.0 / d_row[px].max(1e-6);
7568                    let world_p_px: Vec3 = frame_context.camera_position.add(raw_ray.scale(depth));
7569                    if tri.smooth_idx != u32::MAX
7570                        && let Some(smooth_tri) = inputs.smooth_tris.get(tri.smooth_idx as usize)
7571                    {
7572                        let smooth_rgba: [u8; 4] = Self::shade_pixel_principled_smooth(
7573                            frame_context,
7574                            inputs,
7575                            tri,
7576                            smooth_tri,
7577                            (px, py),
7578                            (world_p_px, raw_ray, depth),
7579                        );
7580                        c_row[cidx..(cidx + 4)].copy_from_slice(&smooth_rgba);
7581                        l_row[px] = (((smooth_rgba[0] as u32) * 77
7582                            + (smooth_rgba[1] as u32) * 150
7583                            + (smooth_rgba[2] as u32) * 29)
7584                            >> 8) as u8;
7585                        raw_ray = raw_ray.add(ray_dx);
7586                        sub_x += 2;
7587                        if sub_x >= step2_i32 {
7588                            sub_x -= step2_i32;
7589                            gx_cur += 1;
7590                        }
7591                        px += 1;
7592                        continue;
7593                    }
7594                    let mut shadow: f32 = 1.0;
7595                    let mut refl: Vec3 = sky_horizon;
7596                    let mut gi_col: Vec3 = Vec3::zero();
7597                    let mut ao: f32 = 1.0;
7598                    if rt_active {
7599                        let (gx0, gx1, fx): (usize, usize, f32) = if sub_x <= 0 && gx_cur == 0 {
7600                            (0, gw_max.min(1), 0.0)
7601                        } else if gx_cur >= gw_max {
7602                            (gw_max, gw_max, 0.0)
7603                        } else {
7604                            (gx_cur, gx_cur + 1, fx_lut[(sub_x as usize).min(15)])
7605                        };
7606                        let probe_key: (usize, u32) = ((gx0 << 16) | gx1, tid);
7607                        if cached_probe_key != probe_key {
7608                            cached_probe_key = probe_key;
7609                            CachedProbeCell::load_into(
7610                                &mut cached_cell,
7611                                &probe_r0,
7612                                &probe_r1,
7613                                (gx0, gx1),
7614                                tri.shade_n,
7615                                (tri.do_refl, gi_active),
7616                            );
7617                        }
7618                        let wx0: f32 = 1.0 - fx;
7619                        let wx1: f32 = fx;
7620                        let bws: [f32; 4] = [wx0 * wy0, wx1 * wy0, wx0 * wy1, wx1 * wy1];
7621                        let (valid_matches, sh_b, s_min, s_max, rf_b, gi_b, ao_b): (
7622                            u32,
7623                            f32,
7624                            f32,
7625                            f32,
7626                            Vec3,
7627                            Vec3,
7628                            f32,
7629                        ) = CachedProbeCell::sample_1x(
7630                            &cached_cell,
7631                            bws,
7632                            depth,
7633                            (tri.do_refl, gi_active),
7634                        );
7635                        let edge_max_d: f32 = if cfg!(target_arch = "wasm32") {
7636                            18.0
7637                        } else {
7638                            42.0
7639                        };
7640                        let need_exact_shadow: bool = tri.n_dot_l > 0.02
7641                            && depth < edge_max_d
7642                            && (valid_matches == 0 || (!gi_active && (s_max - s_min) > 0.12));
7643                        if need_exact_shadow {
7644                            let origin: Vec3 = world_p_px.add(tri.shade_n.scale(0.08));
7645                            edge_rays += 1;
7646                            shadow = if World3D::trace_any_shadow_with_instances(
7647                                inputs.static_bvh,
7648                                inputs.dyn_instances,
7649                                inputs.local_bvhs,
7650                                (origin, sun_dir, inv_sun),
7651                                (0.05, 140.0),
7652                                (&mut static_shadow_cache, &mut dyn_shadow_cache),
7653                            ) {
7654                                0.22
7655                            } else {
7656                                1.0
7657                            };
7658                        } else if valid_matches > 0 {
7659                            shadow = sh_b;
7660                        }
7661                        if tri.do_refl {
7662                            if valid_matches > 0 {
7663                                refl = rf_b;
7664                            } else if depth < 32.0 {
7665                                let origin: Vec3 = world_p_px.add(tri.shade_n.scale(0.08));
7666                                let refl_dir: Vec3 =
7667                                    raw_ray.normalize().reflect(tri.shade_n).normalize();
7668                                let inv_refl: Vec3 = Ray3D::safe_inv_vec(refl_dir);
7669                                edge_rays += 1;
7670                                refl = match World3D::trace_closest_with_instances(
7671                                    inputs.static_bvh,
7672                                    inputs.dyn_instances,
7673                                    inputs.local_bvhs,
7674                                    (origin, refl_dir, inv_refl),
7675                                    (0.08, 96.0),
7676                                ) {
7677                                    Some((_, hit_n, hit_mat)) => Self::shade_surface_hit(
7678                                        hit_n,
7679                                        hit_mat,
7680                                        &frame_context.sun,
7681                                        gi_active,
7682                                    ),
7683                                    None => Self::sample_sky_lut(
7684                                        inputs.sky_lut,
7685                                        refl_dir,
7686                                        &frame_context.sun,
7687                                    ),
7688                                };
7689                            } else {
7690                                let refl_dir: Vec3 =
7691                                    raw_ray.normalize().reflect(tri.shade_n).normalize();
7692                                refl = Self::sample_sky_lut(
7693                                    inputs.sky_lut,
7694                                    refl_dir,
7695                                    &frame_context.sun,
7696                                );
7697                            }
7698                        }
7699                        if gi_active && valid_matches > 0 {
7700                            gi_col = gi_b;
7701                            ao = ao_b;
7702                        }
7703                    }
7704                    let view_in: Vec3 = raw_ray.normalize();
7705                    let view_to_cam: Vec3 = view_in.scale(-1.0);
7706                    let ndv_raw: f32 = tri.shade_n.dot(view_to_cam);
7707                    let ndv: f32 = ndv_raw.clamp(0.02, 1.0);
7708                    let f_om: f32 = 1.0 - ndv;
7709                    let f_om2: f32 = f_om * f_om;
7710                    let fresnel_t: f32 = f_om2 * f_om2 * f_om;
7711                    let v_dot_l: f32 = view_to_cam.dot(sun_dir);
7712                    let spec_col: Vec3 = if tri.n_dot_l > 0.0 {
7713                        let ndh_unnorm: f32 = (tri.n_dot_l + ndv_raw).max(0.0);
7714                        let h_len_sq: f32 = 2.0_f32.mul_add(v_dot_l, 2.0).max(1e-6);
7715                        let ndh_sq: f32 = (ndh_unnorm * ndh_unnorm) / h_len_sq;
7716                        let ggx_denom: f32 = ndh_sq.mul_add(tri.alpha2 - 1.0, 1.0);
7717                        let spec_num: f32 = (0.25 * tri.alpha2 * tri.n_dot_l) * shadow;
7718                        let ggx_term: f32 = (ggx_denom * ggx_denom).mul_add(PI, 1e-4);
7719                        let vis_den: f32 = ndv.mul_add(tri.n_dot_l.max(0.06), 0.08);
7720                        let spec_scalar: f32 = (spec_num / (ggx_term * vis_den)).min(4.5);
7721                        let fresnel_rgb: Vec3 =
7722                            tri.f0.add(Vec3::splat(1.0).sub(tri.f0).scale(fresnel_t));
7723                        fresnel_rgb.mul(sun_col.scale(spec_scalar))
7724                    } else {
7725                        Vec3::zero()
7726                    };
7727                    let mut surf_base: Vec3 = tri.mat_base;
7728                    let mut surf_emissive: Vec3 = tri.mat_emissive;
7729                    let mut surf_refl: f32 = tri.mat_refl;
7730                    match tri.surface_detail {
7731                        SurfaceDetailMode::ArchitecturalFacade
7732                            if tri.shade_n.get_y().abs() < 0.25
7733                                && surf_emissive.length_sq() < 0.02 =>
7734                        {
7735                            let u_coord: f32 = if tri.shade_n.get_x().abs() > 0.5 {
7736                                world_p_px.get_z()
7737                            } else {
7738                                world_p_px.get_x()
7739                            };
7740                            let (nb, ne, nr): (Vec3, Vec3, f32) = Self::eval_facade_detail(
7741                                (u_coord, world_p_px.get_y(), depth, frame_context.inv_height),
7742                                (surf_base, surf_emissive, surf_refl),
7743                            );
7744                            surf_base = nb;
7745                            surf_emissive = ne;
7746                            surf_refl = nr;
7747                        }
7748                        SurfaceDetailMode::RoadSurface
7749                            if tri.shade_n.get_y() > 0.92 && world_p_px.get_y().abs() < 0.15 =>
7750                        {
7751                            let (nb, nr): (Vec3, f32) = Self::eval_road_detail(
7752                                (
7753                                    world_p_px.get_x(),
7754                                    world_p_px.get_z(),
7755                                    depth,
7756                                    frame_context.inv_height,
7757                                ),
7758                                (
7759                                    view_to_cam,
7760                                    fresnel_t,
7761                                    tri.metallic,
7762                                    frame_context.world_time_secs,
7763                                ),
7764                                surf_base,
7765                            );
7766                            surf_base = nb;
7767                            surf_refl = nr;
7768                        }
7769                        _ => {}
7770                    }
7771                    let is_east_coastal_bay: bool = tri.surface_detail
7772                        == SurfaceDetailMode::RoadSurface
7773                        && tri.shade_n.get_y() > 0.92
7774                        && world_p_px.get_y().abs() < 0.15
7775                        && world_p_px.get_x() > 144.0
7776                        && {
7777                            let bay_spine_z: f32 = world_p_px.get_z().clamp(-140.0, 140.0);
7778                            (world_p_px.get_x() - 64.0).hypot(world_p_px.get_z() - bay_spine_z)
7779                                > 78.2
7780                        };
7781                    let radiance: Vec3 = if (tri.surface_detail == SurfaceDetailMode::OceanWater
7782                        && tri.shade_n.get_y() > 0.90)
7783                        || is_east_coastal_bay
7784                    {
7785                        Self::eval_ocean_water_radiance(
7786                            frame_context,
7787                            inputs.sky_lut,
7788                            (world_p_px, view_to_cam, depth),
7789                            (shadow, refl),
7790                        )
7791                    } else {
7792                        let kd_scale: f32 =
7793                            (tri.diffuse_scale * (1.0 - fresnel_t * 0.55)).max(0.08);
7794                        let direct: Vec3 = sun_col.scale(tri.n_dot_l * shadow * kd_scale);
7795                        let indirect: Vec3 = tri.ambient_sky.scale(0.44 * ao).add(gi_col);
7796                        let mut lit: Vec3 = surf_base
7797                            .mul(direct.add(indirect))
7798                            .add(spec_col)
7799                            .add(surf_emissive);
7800                        if tri.do_refl {
7801                            let refl_fresnel: f32 =
7802                                (0.18 + 0.82 * fresnel_t + tri.metallic * 0.25).clamp(0.18, 0.95);
7803                            let refl_blend: f32 = (surf_refl * refl_fresnel).clamp(0.0, 0.82);
7804                            lit = lit.lerp(refl, refl_blend);
7805                        }
7806                        if frame_context.fog_on {
7807                            let py_world: f32 = world_p_px.get_y();
7808                            let height_atten: f32 = if py_world > 0.0 {
7809                                (1.0 / (1.0 + py_world * 0.045)).max(0.32)
7810                            } else {
7811                                1.0
7812                            };
7813                            let fd: f32 = depth * frame_context.inv_fog_distance * height_atten;
7814                            let fog_t: f32 = (fd / (1.0 + fd)).clamp(0.0, 0.85);
7815                            let sun_align: f32 = (-v_dot_l).max(0.0);
7816                            let sa2: f32 = sun_align * sun_align;
7817                            let shaft: f32 = sa2 * sa2 * fog_t * (0.35 + 0.65 * shadow);
7818                            let fog_col: Vec3 = sky_horizon.add(sun_col.scale(shaft * 0.55));
7819                            lit = lit.lerp(fog_col, fog_t);
7820                        }
7821                        lit
7822                    };
7823                    let exposed: Vec3 = radiance.scale(frame_context.exposure_scale);
7824                    if write_bloom_row && (px & 3) == 0 {
7825                        let bidx: usize = bloom_row_off + (px >> 2);
7826                        if bidx < bloom_band.len() {
7827                            let er: f32 = (exposed.get_x() - 1.05).max(0.0);
7828                            let eg: f32 = (exposed.get_y() - 1.05).max(0.0);
7829                            let eb: f32 = (exposed.get_z() - 1.05).max(0.0);
7830                            bloom_band[bidx] = [er, eg, eb, 0.0];
7831                            let rg_pos: bool = er > 0.0 || eg > 0.0;
7832                            if rg_pos || eb > 0.0 {
7833                                bloom_emitted = true;
7834                                row_bloom_hit = true;
7835                            }
7836                        }
7837                    }
7838                    let rgba: [u8; 4] = Self::lut_aces3d_rgba8(inputs.aces_lut, exposed);
7839                    c_row[cidx..(cidx + 4)].copy_from_slice(&rgba);
7840                    l_row[px] =
7841                        (((rgba[0] as u32) * 77 + (rgba[1] as u32) * 150 + (rgba[2] as u32) * 29)
7842                            >> 8) as u8;
7843                    raw_ray = raw_ray.add(ray_dx);
7844                    sub_x += 2;
7845                    if sub_x >= step2_i32 {
7846                        sub_x -= step2_i32;
7847                        gx_cur += 1;
7848                    }
7849                    px += 1;
7850                }
7851                if row_bloom_hit {
7852                    let by: usize = py >> 2;
7853                    let word: usize = by >> 6;
7854                    if word < inputs.bloom_row_bits.len() {
7855                        let _: u64 = inputs.bloom_row_bits[word]
7856                            .fetch_or(1_u64 << (by & 63), Ordering::Relaxed);
7857                    }
7858                }
7859            }
7860        });
7861        (edge_rays, bloom_emitted)
7862    }
7863
7864    /// Samples the quarter-resolution HDR bloom buffer using row-hoisted coordinates for active bloom tiles.
7865    ///
7866    /// # Arguments
7867    ///
7868    /// - `&[[f32; 4]]` - Blurred quarter-resolution HDR bloom slice.
7869    /// - `(usize, usize, usize)` - Row offsets and max X `(bloom_r0, bloom_r1, bw_max)`.
7870    /// - `(usize, f32, f32)` - Tile column and fractional weights `(bx0, tx, ty)`.
7871    ///
7872    /// # Returns
7873    ///
7874    /// - `[f32; 3]` - Bilinearly filtered bloom RGB radiance.
7875    #[inline(always)]
7876    #[must_use]
7877    fn sample_bloom_bilinear_row(
7878        bloom: &[[f32; 4]],
7879        row_info: (usize, usize, usize),
7880        tap: (usize, f32, f32),
7881    ) -> [f32; 3] {
7882        let (r0, r1, bw_max): (usize, usize, usize) = row_info;
7883        let (bx0, tx, ty): (usize, f32, f32) = tap;
7884        let bx1: usize = (bx0 + 1).min(bw_max);
7885        let c00: [f32; 4] = bloom[r0 + bx0];
7886        let c10: [f32; 4] = bloom[r0 + bx1];
7887        let c01: [f32; 4] = bloom[r1 + bx0];
7888        let c11: [f32; 4] = bloom[r1 + bx1];
7889        let omt_x: f32 = 1.0 - tx;
7890        let omt_y: f32 = 1.0 - ty;
7891        let w00: f32 = omt_x * omt_y;
7892        let w10: f32 = tx * omt_y;
7893        let w01: f32 = omt_x * ty;
7894        let w11: f32 = tx * ty;
7895        [
7896            c00[0].mul_add(w00, c10[0].mul_add(w10, c01[0].mul_add(w01, c11[0] * w11))),
7897            c00[1].mul_add(w00, c10[1].mul_add(w10, c01[1].mul_add(w01, c11[1] * w11))),
7898            c00[2].mul_add(w00, c10[2].mul_add(w10, c01[2].mul_add(w01, c11[2] * w11))),
7899        ]
7900    }
7901
7902    /// Populates `bloom_tile_active` (`1` where any bilinear corner contributes `>= 1` RGB LSB) and returns whether any tile is active.
7903    ///
7904    /// # Arguments
7905    ///
7906    /// - `usize` - Quarter-resolution bloom grid width.
7907    /// - `usize` - Quarter-resolution bloom grid height.
7908    /// - `&[[f32; 4]]` - Blurred quarter-resolution HDR bloom buffer.
7909    /// - `&mut [u8]` - Output tile-activity mask slice (`len >= bw * bh`).
7910    ///
7911    /// # Returns
7912    ///
7913    /// - `bool` - `true` when at least one bloom tile requires sampling in `post_process_band`.
7914    #[must_use]
7915    fn build_bloom_tile_mask(
7916        border_width: usize,
7917        bh: usize,
7918        bloom: &[[f32; 4]],
7919        tile_active: &mut [u8],
7920    ) -> bool {
7921        let len: usize = border_width * bh;
7922        let short_bloom: bool = len == 0 || bloom.len() < len;
7923        if short_bloom || tile_active.len() < len {
7924            return false;
7925        }
7926        let bw_max: usize = border_width - 1;
7927        let bh_max: usize = bh - 1;
7928        let mut any_active: bool = false;
7929        for by in 0..bh {
7930            let r0: usize = by * border_width;
7931            let r1: usize = (by + 1).min(bh_max) * border_width;
7932            for bx in 0..border_width {
7933                let bx1: usize = (bx + 1).min(bw_max);
7934                let c00: [f32; 4] = bloom[r0 + bx];
7935                let c10: [f32; 4] = bloom[r0 + bx1];
7936                let c01: [f32; 4] = bloom[r1 + bx];
7937                let c11: [f32; 4] = bloom[r1 + bx1];
7938                let max_r: f32 = c00[0].max(c10[0]).max(c01[0]).max(c11[0]);
7939                let max_g: f32 = c00[1].max(c10[1]).max(c01[1]).max(c11[1]);
7940                let max_b: f32 = c00[2].max(c10[2]).max(c01[2]).max(c11[2]);
7941                let active: bool = max_r.max(max_g).max(max_b) >= 0.015;
7942                tile_active[r0 + bx] = u8::from(active);
7943                if active {
7944                    any_active = true;
7945                }
7946            }
7947        }
7948        any_active
7949    }
7950
7951    /// Loads one 4-byte RGBA pixel at `idx` from `src` into an ARM64 NEON `uint8x8_t` duplicated vector.
7952    ///
7953    /// # Arguments
7954    ///
7955    /// - `&[u8]` - Source RGBA8 pixel buffer.
7956    /// - `usize` - Byte offset (`idx + 4 <= src.len()`).
7957    ///
7958    /// # Returns
7959    ///
7960    /// - `core::arch::aarch64::uint8x8_t` - Replicated RGBA byte vector.
7961    #[cfg(target_arch = "aarch64")]
7962    #[inline(always)]
7963    unsafe fn neon_load_px_u8(src: &[u8], idx: usize) -> core::arch::aarch64::uint8x8_t {
7964        // SAFETY: Caller guarantees `idx + 4 <= src.len()` and ARM64 NEON execution context.
7965        unsafe {
7966            let word: u32 = src.as_ptr().add(idx).cast::<u32>().read_unaligned();
7967            core::arch::aarch64::vreinterpret_u8_u32(core::arch::aarch64::vdup_n_u32(word))
7968        }
7969    }
7970
7971    /// Fused Barrier 3 post-process pass applying 16-pixel SIMD flat-span copy, Geometry-Aware FXAA 3.11 + 8-step Morphological AA, 9-tap variance-clamped TAA, and active-tile bilinear HDR Bloom directly into output memory.
7972    ///
7973    /// # Arguments
7974    ///
7975    /// - `(usize, usize, usize, usize)` - Dimensions `(w, h, bloom_w, bloom_h)`.
7976    /// - `&PostProcessInputs<'_>` - Read-only color, luma, G-Buffer IDs, bloom, bloom mask, and TAA history.
7977    /// - `(bool, bool, bool)` - Flags `(use_fxaa, use_taa, use_bloom)`.
7978    /// - `(usize, *mut u8, usize)` - `(y_start, writable band RGBA base pointer, band row count)`.
7979    unsafe fn post_process_band(
7980        dims: (usize, usize, usize, usize),
7981        inputs: &PostProcessInputs<'_>,
7982        flags: (bool, bool, bool),
7983        band: (usize, *mut u8, usize),
7984    ) {
7985        let (width_val, height_val, border_width, bh): (usize, usize, usize, usize) = dims;
7986        let src: &[u8] = inputs.color_src;
7987        let luma: &[u8] = inputs.luma;
7988        let g_tri_idx: &[u32] = inputs.g_tri_idx;
7989        let bloom: &[[f32; 4]] = inputs.bloom;
7990        let bloom_active: &[u8] = inputs.bloom_tile_active;
7991        let history: &[u8] = inputs.taa_history;
7992        let (use_fxaa, use_taa, use_bloom): (bool, bool, bool) = flags;
7993        let (y_start, dst_ptr, band_rows): (usize, *mut u8, usize) = band;
7994        let row_bytes: usize = width_val * 4;
7995        let bloom_len: usize = border_width * bh;
7996        let has_bloom: bool = use_bloom
7997            && bloom_len > 0
7998            && bloom.len() >= bloom_len
7999            && bloom_active.len() >= bloom_len;
8000        let bw_max: usize = border_width.saturating_sub(1);
8001        let bh_max: usize = bh.saturating_sub(1);
8002        let has_taa: bool = use_taa && history.len() == src.len();
8003        let w_i32: i32 = width_val as i32;
8004        let h_i32: i32 = height_val as i32;
8005        for local_y in 0..band_rows {
8006            let coord_y: usize = y_start + local_y;
8007            let src_off: usize = coord_y * row_bytes;
8008            let dst_off: usize = local_y * row_bytes;
8009            if !use_fxaa && !has_bloom && !has_taa {
8010                // SAFETY: Caller guarantees `dst_ptr` covers `band_rows * row_bytes` disjoint writable bytes,
8011                // and `src_off + row_bytes <= src.len()` since `y < h`.
8012                unsafe {
8013                    dst_ptr
8014                        .add(dst_off)
8015                        .copy_from_nonoverlapping(src.as_ptr().add(src_off), row_bytes);
8016                }
8017                continue;
8018            }
8019            let by0: usize = (coord_y >> 2).min(bh_max);
8020            let by1: usize = (by0 + 1).min(bh_max);
8021            let ty: f32 = ((coord_y & 3) as f32) * 0.25;
8022            let bloom_r0: usize = by0 * border_width;
8023            let bloom_r1: usize = by1 * border_width;
8024            let edge_row: bool = coord_y == 0 || coord_y + 1 >= height_val;
8025            let simple_row: bool = !use_fxaa || edge_row;
8026            if simple_row || width_val < 3 {
8027                for pos_x in 0..width_val {
8028                    let scale_factor: usize = src_off + pos_x * 4;
8029                    let dc: usize = dst_off + pos_x * 4;
8030                    let mut red_val: i32 = src[scale_factor] as i32;
8031                    let mut green_val: i32 = src[scale_factor + 1] as i32;
8032                    let mut blue_val: i32 = src[scale_factor + 2] as i32;
8033                    if has_bloom {
8034                        let bx0: usize = (pos_x >> 2).min(bw_max);
8035                        if bloom_active[bloom_r0 + bx0] != 0 {
8036                            let tx: f32 = ((pos_x & 3) as f32) * 0.25;
8037                            let bl: [f32; 3] = Self::sample_bloom_bilinear_row(
8038                                bloom,
8039                                (bloom_r0, bloom_r1, bw_max),
8040                                (bx0, tx, ty),
8041                            );
8042                            red_val = (red_val + (bl[0] * 64.0) as i32).min(255);
8043                            green_val = (green_val + (bl[1] * 64.0) as i32).min(255);
8044                            blue_val = (blue_val + (bl[2] * 64.0) as i32).min(255);
8045                        }
8046                    }
8047                    // SAFETY: `dc + 4 <= band_rows * row_bytes` and `[u8; 4]` has alignment 1.
8048                    unsafe {
8049                        dst_ptr.add(dc).cast::<[u8; 4]>().write([
8050                            red_val as u8,
8051                            green_val as u8,
8052                            blue_val as u8,
8053                            255,
8054                        ]);
8055                    }
8056                }
8057                continue;
8058            }
8059            let last_px: usize = (width_val - 1) * 4;
8060            // SAFETY: `w >= 3`, so both first and last 4-byte pixels lie within `dst_off..dst_off + row_bytes`.
8061            unsafe {
8062                dst_ptr
8063                    .add(dst_off)
8064                    .copy_from_nonoverlapping(src.as_ptr().add(src_off), 4);
8065                dst_ptr
8066                    .add(dst_off + last_px)
8067                    .copy_from_nonoverlapping(src.as_ptr().add(src_off + last_px), 4);
8068            }
8069            let row: usize = coord_y * width_val;
8070            let row_up: usize = (coord_y - 1) * width_val;
8071            let row_dn: usize = (coord_y + 1) * width_val;
8072            let y_i32: i32 = coord_y as i32;
8073            let luma_c: &[u8] = &luma[row..(row + width_val)];
8074            let luma_u: &[u8] = &luma[row_up..(row_up + width_val)];
8075            let luma_d: &[u8] = &luma[row_dn..(row_dn + width_val)];
8076            let bloom_row_mask: &[u8] = if has_bloom {
8077                &bloom_active[bloom_r0..(bloom_r0 + border_width)]
8078            } else {
8079                &[]
8080            };
8081            let row_has_bloom: bool =
8082                has_bloom && bloom_row_mask.iter().any(|&flag: &u8| flag != 0);
8083            let mut coord_x: usize = 1;
8084            let x_end: usize = width_val - 1;
8085            while coord_x < x_end {
8086                #[cfg(target_arch = "aarch64")]
8087                if coord_x + 16 <= x_end {
8088                    let lc_u8: u8 = luma_c[coord_x];
8089                    if luma_c[coord_x + 4] == lc_u8
8090                        && luma_u[coord_x] == lc_u8
8091                        && luma_d[coord_x] == lc_u8
8092                    {
8093                        let no_bloom_16: bool = !row_has_bloom || {
8094                            let t0: usize = (coord_x >> 2).min(bw_max);
8095                            let t1: usize = (t0 + 1).min(bw_max);
8096                            let t2: usize = (t0 + 2).min(bw_max);
8097                            let t3: usize = (t0 + 3).min(bw_max);
8098                            let t4: usize = ((coord_x + 15) >> 2).min(bw_max);
8099                            (bloom_row_mask[t0]
8100                                | bloom_row_mask[t1]
8101                                | bloom_row_mask[t2]
8102                                | bloom_row_mask[t3]
8103                                | bloom_row_mask[t4])
8104                                == 0
8105                        };
8106                        if no_bloom_16 {
8107                            // SAFETY: `x >= 1` and `x + 16 <= w - 1`, so all 16-byte loads and 1-byte boundaries are in bounds.
8108                            let flat_16: bool = unsafe {
8109                                let splat: core::arch::aarch64::uint8x16_t =
8110                                    core::arch::aarch64::vdupq_n_u8(lc_u8);
8111                                let c16: core::arch::aarch64::uint8x16_t =
8112                                    core::arch::aarch64::vld1q_u8(luma_c.as_ptr().add(coord_x));
8113                                let u16_v: core::arch::aarch64::uint8x16_t =
8114                                    core::arch::aarch64::vld1q_u8(luma_u.as_ptr().add(coord_x));
8115                                let d16: core::arch::aarch64::uint8x16_t =
8116                                    core::arch::aarch64::vld1q_u8(luma_d.as_ptr().add(coord_x));
8117                                let eq_all: core::arch::aarch64::uint8x16_t =
8118                                    core::arch::aarch64::vandq_u8(
8119                                        core::arch::aarch64::vandq_u8(
8120                                            core::arch::aarch64::vceqq_u8(c16, splat),
8121                                            core::arch::aarch64::vceqq_u8(u16_v, splat),
8122                                        ),
8123                                        core::arch::aarch64::vceqq_u8(d16, splat),
8124                                    );
8125                                core::arch::aarch64::vminvq_u8(eq_all) == 0xFF
8126                                    && luma_c[coord_x - 1] == lc_u8
8127                                    && luma_c[coord_x + 16] == lc_u8
8128                                    && luma_u[coord_x - 1] == lc_u8
8129                                    && luma_u[coord_x + 16] == lc_u8
8130                                    && luma_d[coord_x - 1] == lc_u8
8131                                    && luma_d[coord_x + 16] == lc_u8
8132                            };
8133                            let rgba_uniform: bool = flat_16
8134                                && (!has_taa || {
8135                                    let base_px_off: usize = (row + coord_x) * 4;
8136                                    let px0_bytes: &[u8] = &src[base_px_off..(base_px_off + 4)];
8137                                    let row_span_bytes: usize = 18 * 4;
8138                                    let up_slice: &[u8] = &src[((row_up + coord_x - 1) * 4)
8139                                        ..((row_up + coord_x - 1) * 4 + row_span_bytes)];
8140                                    let mid_slice: &[u8] = &src[((row + coord_x - 1) * 4)
8141                                        ..((row + coord_x - 1) * 4 + row_span_bytes)];
8142                                    let dn_slice: &[u8] = &src[((row_dn + coord_x - 1) * 4)
8143                                        ..((row_dn + coord_x - 1) * 4 + row_span_bytes)];
8144                                    mid_slice == up_slice
8145                                        && mid_slice == dn_slice
8146                                        && mid_slice[..68] == mid_slice[4..72]
8147                                        && &mid_slice[..4] == px0_bytes
8148                                });
8149                            if rgba_uniform {
8150                                let sc16: usize = (row + coord_x) * 4;
8151                                let dc16: usize = dst_off + coord_x * 4;
8152                                // SAFETY: 64-byte range `[dc16..dc16+64]` lies strictly within this band row.
8153                                unsafe {
8154                                    dst_ptr
8155                                        .add(dc16)
8156                                        .copy_from_nonoverlapping(src.as_ptr().add(sc16), 64);
8157                                }
8158                                coord_x += 16;
8159                                continue;
8160                            }
8161                        }
8162                    }
8163                }
8164                #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
8165                if !has_taa && coord_x + 16 <= x_end {
8166                    let no_bloom_16: bool = !row_has_bloom || {
8167                        let t0: usize = (coord_x >> 2).min(bw_max);
8168                        let t1: usize = (t0 + 1).min(bw_max);
8169                        let t2: usize = (t0 + 2).min(bw_max);
8170                        let t3: usize = (t0 + 3).min(bw_max);
8171                        let t4: usize = ((coord_x + 15) >> 2).min(bw_max);
8172                        (bloom_row_mask[t0]
8173                            | bloom_row_mask[t1]
8174                            | bloom_row_mask[t2]
8175                            | bloom_row_mask[t3]
8176                            | bloom_row_mask[t4])
8177                            == 0
8178                    };
8179                    if no_bloom_16 {
8180                        // SAFETY: `x >= 1` and `x + 16 <= w - 1`, so `x - 1..x + 15`, `x..x + 16`, and `x + 1..x + 17` all lie within `0..w`.
8181                        let skip_n: usize = unsafe {
8182                            let c_w: core::arch::wasm32::v128 = core::arch::wasm32::v128_load(
8183                                luma_c.as_ptr().add(coord_x - 1).cast(),
8184                            );
8185                            let c_m: core::arch::wasm32::v128 =
8186                                core::arch::wasm32::v128_load(luma_c.as_ptr().add(coord_x).cast());
8187                            let c_e: core::arch::wasm32::v128 = core::arch::wasm32::v128_load(
8188                                luma_c.as_ptr().add(coord_x + 1).cast(),
8189                            );
8190                            let u_m: core::arch::wasm32::v128 =
8191                                core::arch::wasm32::v128_load(luma_u.as_ptr().add(coord_x).cast());
8192                            let d_m: core::arch::wasm32::v128 =
8193                                core::arch::wasm32::v128_load(luma_d.as_ptr().add(coord_x).cast());
8194                            let lmax: core::arch::wasm32::v128 = core::arch::wasm32::u8x16_max(
8195                                core::arch::wasm32::u8x16_max(
8196                                    core::arch::wasm32::u8x16_max(c_m, u_m),
8197                                    core::arch::wasm32::u8x16_max(d_m, c_e),
8198                                ),
8199                                c_w,
8200                            );
8201                            let lmin: core::arch::wasm32::v128 = core::arch::wasm32::u8x16_min(
8202                                core::arch::wasm32::u8x16_min(
8203                                    core::arch::wasm32::u8x16_min(c_m, u_m),
8204                                    core::arch::wasm32::u8x16_min(d_m, c_e),
8205                                ),
8206                                c_w,
8207                            );
8208                            let contrast: core::arch::wasm32::v128 =
8209                                core::arch::wasm32::i8x16_sub(lmax, lmin);
8210                            let ge3_mask: u32 =
8211                                core::arch::wasm32::u8x16_bitmask(core::arch::wasm32::u8x16_ge(
8212                                    contrast,
8213                                    core::arch::wasm32::u8x16_splat(3),
8214                                )) as u32;
8215                            if ge3_mask == 0 {
8216                                16
8217                            } else if (ge3_mask & 0x00FF) == 0 {
8218                                8
8219                            } else if (ge3_mask & 0x000F) == 0 {
8220                                4
8221                            } else {
8222                                0
8223                            }
8224                        };
8225                        if skip_n != 0 {
8226                            let sc_n: usize = (row + coord_x) * 4;
8227                            let dc_n: usize = dst_off + coord_x * 4;
8228                            // SAFETY: `skip_n <= 16` and `x + skip_n <= x_end < w`, so `skip_n * 4` bytes stay strictly within this band row.
8229                            unsafe {
8230                                dst_ptr
8231                                    .add(dc_n)
8232                                    .copy_from_nonoverlapping(src.as_ptr().add(sc_n), skip_n * 4);
8233                            }
8234                            coord_x += skip_n;
8235                            continue;
8236                        }
8237                    }
8238                }
8239                #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
8240                if has_taa && coord_x + 16 <= x_end {
8241                    let lc_u8: u8 = luma_c[coord_x];
8242                    if luma_c[coord_x + 4] == lc_u8
8243                        && luma_u[coord_x] == lc_u8
8244                        && luma_d[coord_x] == lc_u8
8245                    {
8246                        let no_bloom_16: bool = !row_has_bloom || {
8247                            let t0: usize = (coord_x >> 2).min(bw_max);
8248                            let t1: usize = (t0 + 1).min(bw_max);
8249                            let t2: usize = (t0 + 2).min(bw_max);
8250                            let t3: usize = (t0 + 3).min(bw_max);
8251                            let t4: usize = ((coord_x + 15) >> 2).min(bw_max);
8252                            (bloom_row_mask[t0]
8253                                | bloom_row_mask[t1]
8254                                | bloom_row_mask[t2]
8255                                | bloom_row_mask[t3]
8256                                | bloom_row_mask[t4])
8257                                == 0
8258                        };
8259                        if no_bloom_16 {
8260                            // SAFETY: `x >= 1` and `x + 16 <= w - 1`, so all 16-byte loads and 1-byte boundaries are in bounds.
8261                            let flat_16: bool = unsafe {
8262                                let splat: core::arch::wasm32::v128 =
8263                                    core::arch::wasm32::u8x16_splat(lc_u8);
8264                                let c16: core::arch::wasm32::v128 = core::arch::wasm32::v128_load(
8265                                    luma_c.as_ptr().add(coord_x).cast(),
8266                                );
8267                                let u16_v: core::arch::wasm32::v128 = core::arch::wasm32::v128_load(
8268                                    luma_u.as_ptr().add(coord_x).cast(),
8269                                );
8270                                let d16: core::arch::wasm32::v128 = core::arch::wasm32::v128_load(
8271                                    luma_d.as_ptr().add(coord_x).cast(),
8272                                );
8273                                let eq_all: core::arch::wasm32::v128 = core::arch::wasm32::v128_and(
8274                                    core::arch::wasm32::v128_and(
8275                                        core::arch::wasm32::u8x16_eq(c16, splat),
8276                                        core::arch::wasm32::u8x16_eq(u16_v, splat),
8277                                    ),
8278                                    core::arch::wasm32::u8x16_eq(d16, splat),
8279                                );
8280                                core::arch::wasm32::u8x16_all_true(eq_all)
8281                                    && luma_c[coord_x - 1] == lc_u8
8282                                    && luma_c[coord_x + 16] == lc_u8
8283                                    && luma_u[coord_x - 1] == lc_u8
8284                                    && luma_u[coord_x + 16] == lc_u8
8285                                    && luma_d[coord_x - 1] == lc_u8
8286                                    && luma_d[coord_x + 16] == lc_u8
8287                            };
8288                            if flat_16 {
8289                                let sc16: usize = (row + coord_x) * 4;
8290                                let dc16: usize = dst_off + coord_x * 4;
8291                                // SAFETY: 64-byte range `[dc16..dc16+64]` lies strictly within this band row.
8292                                unsafe {
8293                                    dst_ptr
8294                                        .add(dc16)
8295                                        .copy_from_nonoverlapping(src.as_ptr().add(sc16), 64);
8296                                }
8297                                coord_x += 16;
8298                                continue;
8299                            }
8300                        }
8301                    }
8302                }
8303                #[cfg(target_arch = "x86_64")]
8304                if !has_taa && coord_x + 16 <= x_end {
8305                    let no_bloom_16: bool = !row_has_bloom || {
8306                        let t0: usize = (coord_x >> 2).min(bw_max);
8307                        let t1: usize = (t0 + 1).min(bw_max);
8308                        let t2: usize = (t0 + 2).min(bw_max);
8309                        let t3: usize = (t0 + 3).min(bw_max);
8310                        let t4: usize = ((coord_x + 15) >> 2).min(bw_max);
8311                        (bloom_row_mask[t0]
8312                            | bloom_row_mask[t1]
8313                            | bloom_row_mask[t2]
8314                            | bloom_row_mask[t3]
8315                            | bloom_row_mask[t4])
8316                            == 0
8317                    };
8318                    if no_bloom_16 {
8319                        // SAFETY: `x >= 1` and `x + 16 <= w - 1`, so `x - 1..x + 15`, `x..x + 16`, and `x + 1..x + 17` all lie within `0..w`.
8320                        let skip_n: usize = unsafe {
8321                            let c_w: core::arch::x86_64::__m128i =
8322                                core::arch::x86_64::_mm_loadu_si128(
8323                                    luma_c.as_ptr().add(coord_x - 1).cast(),
8324                                );
8325                            let c_m: core::arch::x86_64::__m128i =
8326                                core::arch::x86_64::_mm_loadu_si128(
8327                                    luma_c.as_ptr().add(coord_x).cast(),
8328                                );
8329                            let c_e: core::arch::x86_64::__m128i =
8330                                core::arch::x86_64::_mm_loadu_si128(
8331                                    luma_c.as_ptr().add(coord_x + 1).cast(),
8332                                );
8333                            let u_m: core::arch::x86_64::__m128i =
8334                                core::arch::x86_64::_mm_loadu_si128(
8335                                    luma_u.as_ptr().add(coord_x).cast(),
8336                                );
8337                            let d_m: core::arch::x86_64::__m128i =
8338                                core::arch::x86_64::_mm_loadu_si128(
8339                                    luma_d.as_ptr().add(coord_x).cast(),
8340                                );
8341                            let lmax: core::arch::x86_64::__m128i =
8342                                core::arch::x86_64::_mm_max_epu8(
8343                                    core::arch::x86_64::_mm_max_epu8(
8344                                        core::arch::x86_64::_mm_max_epu8(c_m, u_m),
8345                                        core::arch::x86_64::_mm_max_epu8(d_m, c_e),
8346                                    ),
8347                                    c_w,
8348                                );
8349                            let lmin: core::arch::x86_64::__m128i =
8350                                core::arch::x86_64::_mm_min_epu8(
8351                                    core::arch::x86_64::_mm_min_epu8(
8352                                        core::arch::x86_64::_mm_min_epu8(c_m, u_m),
8353                                        core::arch::x86_64::_mm_min_epu8(d_m, c_e),
8354                                    ),
8355                                    c_w,
8356                                );
8357                            let contrast: core::arch::x86_64::__m128i =
8358                                core::arch::x86_64::_mm_subs_epu8(lmax, lmin);
8359                            let lt3: core::arch::x86_64::__m128i =
8360                                core::arch::x86_64::_mm_cmpeq_epi8(
8361                                    core::arch::x86_64::_mm_subs_epu8(
8362                                        contrast,
8363                                        core::arch::x86_64::_mm_set1_epi8(2),
8364                                    ),
8365                                    core::arch::x86_64::_mm_setzero_si128(),
8366                                );
8367                            let ge3_mask: u32 =
8368                                (!core::arch::x86_64::_mm_movemask_epi8(lt3) as u32) & 0xFFFF;
8369                            if ge3_mask == 0 {
8370                                16
8371                            } else if (ge3_mask & 0x00FF) == 0 {
8372                                8
8373                            } else if (ge3_mask & 0x000F) == 0 {
8374                                4
8375                            } else {
8376                                0
8377                            }
8378                        };
8379                        if skip_n != 0 {
8380                            let sc_n: usize = (row + coord_x) * 4;
8381                            let dc_n: usize = dst_off + coord_x * 4;
8382                            // SAFETY: `skip_n <= 16` and `x + skip_n <= x_end < w`, so `skip_n * 4` bytes stay strictly within this band row.
8383                            unsafe {
8384                                dst_ptr
8385                                    .add(dc_n)
8386                                    .copy_from_nonoverlapping(src.as_ptr().add(sc_n), skip_n * 4);
8387                            }
8388                            coord_x += skip_n;
8389                            continue;
8390                        }
8391                    }
8392                }
8393                #[cfg(target_arch = "x86_64")]
8394                if has_taa && coord_x + 16 <= x_end {
8395                    let lc_u8: u8 = luma_c[coord_x];
8396                    if luma_c[coord_x + 4] == lc_u8
8397                        && luma_u[coord_x] == lc_u8
8398                        && luma_d[coord_x] == lc_u8
8399                    {
8400                        let no_bloom_16: bool = !row_has_bloom || {
8401                            let t0: usize = (coord_x >> 2).min(bw_max);
8402                            let t1: usize = (t0 + 1).min(bw_max);
8403                            let t2: usize = (t0 + 2).min(bw_max);
8404                            let t3: usize = (t0 + 3).min(bw_max);
8405                            let t4: usize = ((coord_x + 15) >> 2).min(bw_max);
8406                            (bloom_row_mask[t0]
8407                                | bloom_row_mask[t1]
8408                                | bloom_row_mask[t2]
8409                                | bloom_row_mask[t3]
8410                                | bloom_row_mask[t4])
8411                                == 0
8412                        };
8413                        if no_bloom_16 {
8414                            // SAFETY: `x >= 1` and `x + 16 <= w - 1`, so all 16-byte loads and 1-byte boundaries are in bounds.
8415                            let flat_16: bool = unsafe {
8416                                let splat: core::arch::x86_64::__m128i =
8417                                    core::arch::x86_64::_mm_set1_epi8(lc_u8 as i8);
8418                                let c16: core::arch::x86_64::__m128i =
8419                                    core::arch::x86_64::_mm_loadu_si128(
8420                                        luma_c.as_ptr().add(coord_x).cast(),
8421                                    );
8422                                let u16_v: core::arch::x86_64::__m128i =
8423                                    core::arch::x86_64::_mm_loadu_si128(
8424                                        luma_u.as_ptr().add(coord_x).cast(),
8425                                    );
8426                                let d16: core::arch::x86_64::__m128i =
8427                                    core::arch::x86_64::_mm_loadu_si128(
8428                                        luma_d.as_ptr().add(coord_x).cast(),
8429                                    );
8430                                let eq_all: core::arch::x86_64::__m128i =
8431                                    core::arch::x86_64::_mm_and_si128(
8432                                        core::arch::x86_64::_mm_and_si128(
8433                                            core::arch::x86_64::_mm_cmpeq_epi8(c16, splat),
8434                                            core::arch::x86_64::_mm_cmpeq_epi8(u16_v, splat),
8435                                        ),
8436                                        core::arch::x86_64::_mm_cmpeq_epi8(d16, splat),
8437                                    );
8438                                core::arch::x86_64::_mm_movemask_epi8(eq_all) == 0xFFFF
8439                                    && luma_c[coord_x - 1] == lc_u8
8440                                    && luma_c[coord_x + 16] == lc_u8
8441                                    && luma_u[coord_x - 1] == lc_u8
8442                                    && luma_u[coord_x + 16] == lc_u8
8443                                    && luma_d[coord_x - 1] == lc_u8
8444                                    && luma_d[coord_x + 16] == lc_u8
8445                            };
8446                            if flat_16 {
8447                                let sc16: usize = (row + coord_x) * 4;
8448                                let dc16: usize = dst_off + coord_x * 4;
8449                                // SAFETY: 64-byte range `[dc16..dc16+64]` lies strictly within this band row.
8450                                unsafe {
8451                                    dst_ptr
8452                                        .add(dc16)
8453                                        .copy_from_nonoverlapping(src.as_ptr().add(sc16), 64);
8454                                }
8455                                coord_x += 16;
8456                                continue;
8457                            }
8458                        }
8459                    }
8460                }
8461                #[cfg(not(target_arch = "aarch64"))]
8462                #[cfg(not(target_arch = "x86_64"))]
8463                #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
8464                {
8465                    let no_bloom_8: bool = coord_x + 8 <= x_end
8466                        && (!row_has_bloom
8467                            || (bloom_row_mask[(coord_x >> 2).min(bw_max)] == 0
8468                                && bloom_row_mask[((coord_x + 4) >> 2).min(bw_max)] == 0
8469                                && bloom_row_mask[((coord_x + 7) >> 2).min(bw_max)] == 0));
8470                    if no_bloom_8 {
8471                        let lc_u8: u8 = luma_c[coord_x];
8472                        let splat: u64 = (lc_u8 as u64) * 0x0101_0101_0101_0101_u64;
8473                        // SAFETY: `x >= 1` and `x + 8 <= w - 1`, so all 8-byte unaligned loads and boundary bytes are in bounds.
8474                        let flat_8: bool = unsafe {
8475                            let c8: u64 =
8476                                luma_c.as_ptr().add(coord_x).cast::<u64>().read_unaligned();
8477                            let u8_w: u64 =
8478                                luma_u.as_ptr().add(coord_x).cast::<u64>().read_unaligned();
8479                            let d8: u64 =
8480                                luma_d.as_ptr().add(coord_x).cast::<u64>().read_unaligned();
8481                            c8 == splat
8482                                && u8_w == splat
8483                                && d8 == splat
8484                                && luma_c[coord_x - 1] == lc_u8
8485                                && luma_c[coord_x + 8] == lc_u8
8486                                && luma_u[coord_x - 1] == lc_u8
8487                                && luma_u[coord_x + 8] == lc_u8
8488                                && luma_d[coord_x - 1] == lc_u8
8489                                && luma_d[coord_x + 8] == lc_u8
8490                        };
8491                        if flat_8 {
8492                            let sc8: usize = (row + coord_x) * 4;
8493                            let dc8: usize = dst_off + coord_x * 4;
8494                            // SAFETY: 32-byte range `[dc8..dc8+32]` lies strictly within this band row.
8495                            unsafe {
8496                                dst_ptr
8497                                    .add(dc8)
8498                                    .copy_from_nonoverlapping(src.as_ptr().add(sc8), 32);
8499                            }
8500                            coord_x += 8;
8501                            continue;
8502                        }
8503                    }
8504                }
8505                #[cfg(target_arch = "aarch64")]
8506                if coord_x + 6 <= x_end {
8507                    let no_bloom_4: bool = !row_has_bloom
8508                        || (bloom_row_mask[(coord_x >> 2).min(bw_max)]
8509                            | bloom_row_mask[((coord_x + 3) >> 2).min(bw_max)])
8510                            == 0;
8511                    if no_bloom_4 {
8512                        // SAFETY: `x >= 1` and `x + 6 <= w - 1`, so 8-byte luma loads at `x - 1` and 16-byte RGBA loads at `x - 1` and `x + 1` stay strictly within row bounds.
8513                        let handled_4: bool = unsafe {
8514                            let lc_w: core::arch::aarch64::uint8x8_t =
8515                                core::arch::aarch64::vld1_u8(luma_c.as_ptr().add(coord_x - 1));
8516                            let lu_w: core::arch::aarch64::uint8x8_t =
8517                                core::arch::aarch64::vld1_u8(luma_u.as_ptr().add(coord_x - 1));
8518                            let ld_w: core::arch::aarch64::uint8x8_t =
8519                                core::arch::aarch64::vld1_u8(luma_d.as_ptr().add(coord_x - 1));
8520                            let c_mid: core::arch::aarch64::uint8x8_t =
8521                                core::arch::aarch64::vext_u8::<1>(lc_w, lc_w);
8522                            let c_east: core::arch::aarch64::uint8x8_t =
8523                                core::arch::aarch64::vext_u8::<2>(lc_w, lc_w);
8524                            let u_mid: core::arch::aarch64::uint8x8_t =
8525                                core::arch::aarch64::vext_u8::<1>(lu_w, lu_w);
8526                            let d_mid: core::arch::aarch64::uint8x8_t =
8527                                core::arch::aarch64::vext_u8::<1>(ld_w, ld_w);
8528                            let lmax: core::arch::aarch64::uint8x8_t = core::arch::aarch64::vmax_u8(
8529                                core::arch::aarch64::vmax_u8(
8530                                    core::arch::aarch64::vmax_u8(c_mid, u_mid),
8531                                    core::arch::aarch64::vmax_u8(d_mid, c_east),
8532                                ),
8533                                lc_w,
8534                            );
8535                            let lmin: core::arch::aarch64::uint8x8_t = core::arch::aarch64::vmin_u8(
8536                                core::arch::aarch64::vmin_u8(
8537                                    core::arch::aarch64::vmin_u8(c_mid, u_mid),
8538                                    core::arch::aarch64::vmin_u8(d_mid, c_east),
8539                                ),
8540                                lc_w,
8541                            );
8542                            let contrast_v: core::arch::aarch64::uint8x8_t =
8543                                core::arch::aarch64::vsub_u8(lmax, lmin);
8544                            let ge3_mask: u32 = core::arch::aarch64::vget_lane_u32::<0>(
8545                                core::arch::aarch64::vreinterpret_u32_u8(
8546                                    core::arch::aarch64::vcge_u8(
8547                                        contrast_v,
8548                                        core::arch::aarch64::vdup_n_u8(3),
8549                                    ),
8550                                ),
8551                            );
8552                            if ge3_mask == 0 {
8553                                let sc4: usize = (row + coord_x) * 4;
8554                                let dc4: usize = dst_off + coord_x * 4;
8555                                if !has_taa {
8556                                    let px4: core::arch::aarch64::uint8x16_t =
8557                                        core::arch::aarch64::vld1q_u8(src.as_ptr().add(sc4));
8558                                    core::arch::aarch64::vst1q_u8(dst_ptr.add(dc4), px4);
8559                                } else {
8560                                    let su_a: core::arch::aarch64::uint8x16_t =
8561                                        core::arch::aarch64::vld1q_u8(
8562                                            src.as_ptr().add((row_up + coord_x - 1) * 4),
8563                                        );
8564                                    let su_b: core::arch::aarch64::uint8x16_t =
8565                                        core::arch::aarch64::vld1q_u8(
8566                                            src.as_ptr().add((row_up + coord_x + 1) * 4),
8567                                        );
8568                                    let su_m: core::arch::aarch64::uint8x16_t =
8569                                        core::arch::aarch64::vextq_u8::<4>(su_a, su_b);
8570                                    let sc_a: core::arch::aarch64::uint8x16_t =
8571                                        core::arch::aarch64::vld1q_u8(
8572                                            src.as_ptr().add((row + coord_x - 1) * 4),
8573                                        );
8574                                    let sc_b: core::arch::aarch64::uint8x16_t =
8575                                        core::arch::aarch64::vld1q_u8(
8576                                            src.as_ptr().add((row + coord_x + 1) * 4),
8577                                        );
8578                                    let sc_m: core::arch::aarch64::uint8x16_t =
8579                                        core::arch::aarch64::vextq_u8::<4>(sc_a, sc_b);
8580                                    let sd_a: core::arch::aarch64::uint8x16_t =
8581                                        core::arch::aarch64::vld1q_u8(
8582                                            src.as_ptr().add((row_dn + coord_x - 1) * 4),
8583                                        );
8584                                    let sd_b: core::arch::aarch64::uint8x16_t =
8585                                        core::arch::aarch64::vld1q_u8(
8586                                            src.as_ptr().add((row_dn + coord_x + 1) * 4),
8587                                        );
8588                                    let sd_m: core::arch::aarch64::uint8x16_t =
8589                                        core::arch::aarch64::vextq_u8::<4>(sd_a, sd_b);
8590                                    let min_u: core::arch::aarch64::uint8x16_t =
8591                                        core::arch::aarch64::vminq_u8(
8592                                            core::arch::aarch64::vminq_u8(su_a, su_m),
8593                                            su_b,
8594                                        );
8595                                    let max_u: core::arch::aarch64::uint8x16_t =
8596                                        core::arch::aarch64::vmaxq_u8(
8597                                            core::arch::aarch64::vmaxq_u8(su_a, su_m),
8598                                            su_b,
8599                                        );
8600                                    let min_c: core::arch::aarch64::uint8x16_t =
8601                                        core::arch::aarch64::vminq_u8(
8602                                            core::arch::aarch64::vminq_u8(sc_a, sc_m),
8603                                            sc_b,
8604                                        );
8605                                    let max_c: core::arch::aarch64::uint8x16_t =
8606                                        core::arch::aarch64::vmaxq_u8(
8607                                            core::arch::aarch64::vmaxq_u8(sc_a, sc_m),
8608                                            sc_b,
8609                                        );
8610                                    let min_d: core::arch::aarch64::uint8x16_t =
8611                                        core::arch::aarch64::vminq_u8(
8612                                            core::arch::aarch64::vminq_u8(sd_a, sd_m),
8613                                            sd_b,
8614                                        );
8615                                    let max_d: core::arch::aarch64::uint8x16_t =
8616                                        core::arch::aarch64::vmaxq_u8(
8617                                            core::arch::aarch64::vmaxq_u8(sd_a, sd_m),
8618                                            sd_b,
8619                                        );
8620                                    let box_min: core::arch::aarch64::uint8x16_t =
8621                                        core::arch::aarch64::vminq_u8(
8622                                            core::arch::aarch64::vminq_u8(min_u, min_c),
8623                                            min_d,
8624                                        );
8625                                    let box_max: core::arch::aarch64::uint8x16_t =
8626                                        core::arch::aarch64::vmaxq_u8(
8627                                            core::arch::aarch64::vmaxq_u8(max_u, max_c),
8628                                            max_d,
8629                                        );
8630                                    let hist_v: core::arch::aarch64::uint8x16_t =
8631                                        core::arch::aarch64::vld1q_u8(history.as_ptr().add(sc4));
8632                                    let hist_c: core::arch::aarch64::uint8x16_t =
8633                                        core::arch::aarch64::vminq_u8(
8634                                            core::arch::aarch64::vmaxq_u8(hist_v, box_min),
8635                                            box_max,
8636                                        );
8637                                    let w_cur: core::arch::aarch64::uint8x8_t =
8638                                        core::arch::aarch64::vdup_n_u8(192);
8639                                    let w_his: core::arch::aarch64::uint8x8_t =
8640                                        core::arch::aarch64::vdup_n_u8(64);
8641                                    let lo_sum: core::arch::aarch64::uint16x8_t =
8642                                        core::arch::aarch64::vmlal_u8(
8643                                            core::arch::aarch64::vmull_u8(
8644                                                core::arch::aarch64::vget_low_u8(sc_m),
8645                                                w_cur,
8646                                            ),
8647                                            core::arch::aarch64::vget_low_u8(hist_c),
8648                                            w_his,
8649                                        );
8650                                    let hi_sum: core::arch::aarch64::uint16x8_t =
8651                                        core::arch::aarch64::vmlal_u8(
8652                                            core::arch::aarch64::vmull_u8(
8653                                                core::arch::aarch64::vget_high_u8(sc_m),
8654                                                w_cur,
8655                                            ),
8656                                            core::arch::aarch64::vget_high_u8(hist_c),
8657                                            w_his,
8658                                        );
8659                                    let blended: core::arch::aarch64::uint8x16_t =
8660                                        core::arch::aarch64::vcombine_u8(
8661                                            core::arch::aarch64::vrshrn_n_u16::<8>(lo_sum),
8662                                            core::arch::aarch64::vrshrn_n_u16::<8>(hi_sum),
8663                                        );
8664                                    core::arch::aarch64::vst1q_u8(dst_ptr.add(dc4), blended);
8665                                }
8666                                true
8667                            } else {
8668                                false
8669                            }
8670                        };
8671                        if handled_4 {
8672                            coord_x += 4;
8673                            continue;
8674                        }
8675                    }
8676                }
8677                let lc: i32 = luma_c[coord_x] as i32;
8678                let ln: i32 = luma_u[coord_x] as i32;
8679                let ls: i32 = luma_d[coord_x] as i32;
8680                let le: i32 = luma_c[coord_x + 1] as i32;
8681                let lw: i32 = luma_c[coord_x - 1] as i32;
8682                let lmax: i32 = lc.max(ln).max(ls).max(le).max(lw);
8683                let lmin: i32 = lc.min(ln).min(ls).min(le).min(lw);
8684                let contrast: i32 = lmax - lmin;
8685                let dpi_scale: usize = (row + coord_x) * 4;
8686                let dc: usize = dst_off + coord_x * 4;
8687                if contrast < 3 {
8688                    let pix_bloom: bool =
8689                        row_has_bloom && bloom_row_mask[(coord_x >> 2).min(bw_max)] != 0;
8690                    if !pix_bloom {
8691                        if !has_taa {
8692                            // SAFETY: 4-byte copy within valid `src` and `dst_ptr` row bounds.
8693                            unsafe {
8694                                dst_ptr
8695                                    .add(dc)
8696                                    .copy_from_nonoverlapping(src.as_ptr().add(dpi_scale), 4);
8697                            }
8698                            coord_x += 1;
8699                            continue;
8700                        }
8701                        if contrast == 0 {
8702                            let lc_u8: u8 = lc as u8;
8703                            if luma_u[coord_x - 1] == lc_u8
8704                                && luma_u[coord_x + 1] == lc_u8
8705                                && luma_d[coord_x - 1] == lc_u8
8706                                && luma_d[coord_x + 1] == lc_u8
8707                            {
8708                                // SAFETY: 4-byte copy within valid `src` and `dst_ptr` row bounds.
8709                                unsafe {
8710                                    dst_ptr
8711                                        .add(dc)
8712                                        .copy_from_nonoverlapping(src.as_ptr().add(dpi_scale), 4);
8713                                }
8714                                coord_x += 1;
8715                                continue;
8716                            }
8717                        }
8718                    }
8719                }
8720                let (geom_edge, run_fxaa): (bool, bool) = if contrast >= 3 {
8721                    let tid_c: u32 = g_tri_idx[row + coord_x];
8722                    let edge_v_id: bool = tid_c != g_tri_idx[row_up + coord_x]
8723                        || tid_c != g_tri_idx[row_dn + coord_x];
8724                    let edge_h_id: bool = tid_c != g_tri_idx[row + coord_x - 1]
8725                        || tid_c != g_tri_idx[row + coord_x + 1];
8726                    let ge: bool = edge_v_id || edge_h_id;
8727                    (ge, contrast >= 7 || ge)
8728                } else {
8729                    (false, false)
8730                };
8731                let mut rgb: [i32; 3] = [
8732                    src[dpi_scale] as i32,
8733                    src[dpi_scale + 1] as i32,
8734                    src[dpi_scale + 2] as i32,
8735                ];
8736                if run_fxaa {
8737                    let lnw: i32 = luma[row_up + coord_x - 1] as i32;
8738                    let lne: i32 = luma[row_up + coord_x + 1] as i32;
8739                    let lsw: i32 = luma[row_dn + coord_x - 1] as i32;
8740                    let lse: i32 = luma[row_dn + coord_x + 1] as i32;
8741                    let edge_h: i32 = (lnw + lne - 2 * ln).abs()
8742                        + 2 * (lw + le - 2 * lc).abs()
8743                        + (lsw + lse - 2 * ls).abs();
8744                    let edge_v: i32 = (lnw + lsw - 2 * lw).abs()
8745                        + 2 * (ln + ls - 2 * lc).abs()
8746                        + (lne + lse - 2 * le).abs();
8747                    let is_horiz: bool = edge_h >= edge_v;
8748                    let (l_neg, l_pos): (i32, i32) = if is_horiz { (ln, ls) } else { (lw, le) };
8749                    let grad_neg: i32 = (l_neg - lc).abs();
8750                    let grad_pos: i32 = (l_pos - lc).abs();
8751                    let step_sign: i32 = if grad_neg >= grad_pos { -1 } else { 1 };
8752                    let grad_steep: i32 = grad_neg.max(grad_pos);
8753                    let l_other: i32 = if step_sign < 0 { l_neg } else { l_pos };
8754                    let edge_avg_2: i32 = lc + l_other;
8755                    let grad_thresh_2: i32 = (grad_steep >> 1).max(3);
8756                    let (perp_dx, perp_dy, tan_dx, tan_dy): (i32, i32, i32, i32) = if is_horiz {
8757                        (0, step_sign, 1, 0)
8758                    } else {
8759                        (step_sign, 0, 0, 1)
8760                    };
8761                    let x_i32: i32 = coord_x as i32;
8762                    let mut dist_neg: i32 = MLAA_MAX_WALK_STEPS as i32;
8763                    let mut end_neg_delta: i32 = 0;
8764                    for source_val in 1..=(MLAA_MAX_WALK_STEPS as i32) {
8765                        let sx: i32 = x_i32 - tan_dx * source_val;
8766                        let sy: i32 = y_i32 - tan_dy * source_val;
8767                        let ox: i32 = sx + perp_dx;
8768                        let oy: i32 = sy + perp_dy;
8769                        let oob_sx: bool = sx < 0 || sx >= w_i32;
8770                        let oob_sy: bool = sy < 0 || sy >= h_i32;
8771                        let oob_ox: bool = ox < 0 || ox >= w_i32;
8772                        let oob_oy: bool = oy < 0 || oy >= h_i32;
8773                        let oob_a: bool = oob_sx || oob_sy;
8774                        let oob_b: bool = oob_ox || oob_oy;
8775                        if oob_a || oob_b {
8776                            dist_neg = source_val;
8777                            break;
8778                        }
8779                        let pair_sum: i32 = (luma[(sy as usize) * width_val + (sx as usize)]
8780                            as i32)
8781                            + (luma[(oy as usize) * width_val + (ox as usize)] as i32);
8782                        let delta: i32 = pair_sum - edge_avg_2;
8783                        if delta.abs() >= grad_thresh_2 {
8784                            dist_neg = source_val;
8785                            end_neg_delta = delta;
8786                            break;
8787                        }
8788                    }
8789                    let mut dist_pos: i32 = MLAA_MAX_WALK_STEPS as i32;
8790                    let mut end_pos_delta: i32 = 0;
8791                    for scale_val in 1..=(MLAA_MAX_WALK_STEPS as i32) {
8792                        let sx: i32 = x_i32 + tan_dx * scale_val;
8793                        let sy: i32 = y_i32 + tan_dy * scale_val;
8794                        let ox: i32 = sx + perp_dx;
8795                        let oy: i32 = sy + perp_dy;
8796                        let oob_sx: bool = sx < 0 || sx >= w_i32;
8797                        let oob_sy: bool = sy < 0 || sy >= h_i32;
8798                        let oob_ox: bool = ox < 0 || ox >= w_i32;
8799                        let oob_oy: bool = oy < 0 || oy >= h_i32;
8800                        let oob_a: bool = oob_sx || oob_sy;
8801                        let oob_b: bool = oob_ox || oob_oy;
8802                        if oob_a || oob_b {
8803                            dist_pos = scale_val;
8804                            break;
8805                        }
8806                        let pair_sum: i32 = (luma[(sy as usize) * width_val + (sx as usize)]
8807                            as i32)
8808                            + (luma[(oy as usize) * width_val + (ox as usize)] as i32);
8809                        let delta: i32 = pair_sum - edge_avg_2;
8810                        if delta.abs() >= grad_thresh_2 {
8811                            dist_pos = scale_val;
8812                            end_pos_delta = delta;
8813                            break;
8814                        }
8815                    }
8816                    let center_lt_avg: bool = (lc * 2) < edge_avg_2;
8817                    let (closer_dist, closer_delta): (i32, i32) = if dist_neg <= dist_pos {
8818                        (dist_neg, end_neg_delta)
8819                    } else {
8820                        (dist_pos, end_pos_delta)
8821                    };
8822                    let good_span: bool = (closer_delta < 0) != center_lt_avg;
8823                    let span_total: f32 = ((dist_neg + dist_pos).max(1)) as f32;
8824                    let morph_blend: f32 = if good_span {
8825                        (0.5 - ((closer_dist as f32) - 0.5).max(0.0) / span_total).clamp(0.0, 0.5)
8826                    } else {
8827                        0.0
8828                    };
8829                    let avg_8: i32 = ((ln + ls + le + lw) * 2 + lnw + lne + lsw + lse + 6) / 12;
8830                    let subpix_raw: f32 =
8831                        (((avg_8 - lc).abs() as f32) / (contrast.max(1) as f32)).clamp(0.0, 1.0);
8832                    let subpix_s: f32 = subpix_raw * subpix_raw * (3.0 - 2.0 * subpix_raw);
8833                    let subpix_blend: f32 =
8834                        subpix_s * subpix_s * if geom_edge { 0.52 } else { 0.32 };
8835                    let final_blend: f32 = morph_blend.max(subpix_blend).clamp(0.0, 0.58);
8836                    let blend_q8: i32 = (final_blend * 256.0).round() as i32;
8837                    if blend_q8 > 0 {
8838                        let nx: usize = (x_i32 + perp_dx).clamp(0, w_i32 - 1) as usize;
8839                        let ny: usize = (y_i32 + perp_dy).clamp(0, h_i32 - 1) as usize;
8840                        let n_sc: usize = (ny * width_val + nx) * 4;
8841                        let keep_q8: i32 = 256 - blend_q8;
8842                        for ch in 0..3 {
8843                            rgb[ch] =
8844                                ((rgb[ch] * keep_q8 + (src[n_sc + ch] as i32) * blend_q8 + 128)
8845                                    >> 8)
8846                                    .clamp(0, 255);
8847                        }
8848                    }
8849                }
8850                if has_taa {
8851                    let flat_3x3: bool = if contrast == 0 {
8852                        let lc_u8: u8 = lc as u8;
8853                        let diag_top: bool = luma[row_up + coord_x - 1] == lc_u8
8854                            && luma[row_up + coord_x + 1] == lc_u8;
8855                        let diag_bot: bool = luma[row_dn + coord_x - 1] == lc_u8
8856                            && luma[row_dn + coord_x + 1] == lc_u8;
8857                        diag_top && diag_bot
8858                    } else {
8859                        false
8860                    };
8861                    if !flat_3x3 {
8862                        let hr: i32 = history[dpi_scale] as i32;
8863                        let hg: i32 = history[dpi_scale + 1] as i32;
8864                        let hb: i32 = history[dpi_scale + 2] as i32;
8865                        let diff_rg: bool = hr != rgb[0] || hg != rgb[1];
8866                        if diff_rg || hb != rgb[2] {
8867                            #[cfg(target_arch = "aarch64")]
8868                            let (r_min, r_max, g_min, g_max, b_min, b_max): (
8869                                i32,
8870                                i32,
8871                                i32,
8872                                i32,
8873                                i32,
8874                                i32,
8875                            ) = {
8876                                // SAFETY: `x >= 1`, `x + 1 < w`, `y >= 1`, `y + 1 < h`, so every 4-byte pixel offset lies inside `src`.
8877                                unsafe {
8878                                    let c_word: u32 = u32::from_le_bytes([
8879                                        rgb[0] as u8,
8880                                        rgb[1] as u8,
8881                                        rgb[2] as u8,
8882                                        255,
8883                                    ]);
8884                                    let c_v: core::arch::aarch64::uint8x8_t =
8885                                        core::arch::aarch64::vreinterpret_u8_u32(
8886                                            core::arch::aarch64::vdup_n_u32(c_word),
8887                                        );
8888                                    let p0: core::arch::aarch64::uint8x8_t =
8889                                        Self::neon_load_px_u8(src, (row_up + coord_x - 1) * 4);
8890                                    let p1: core::arch::aarch64::uint8x8_t =
8891                                        Self::neon_load_px_u8(src, (row_up + coord_x) * 4);
8892                                    let p2: core::arch::aarch64::uint8x8_t =
8893                                        Self::neon_load_px_u8(src, (row_up + coord_x + 1) * 4);
8894                                    let p3: core::arch::aarch64::uint8x8_t =
8895                                        Self::neon_load_px_u8(src, (row + coord_x - 1) * 4);
8896                                    let p4: core::arch::aarch64::uint8x8_t =
8897                                        Self::neon_load_px_u8(src, (row + coord_x + 1) * 4);
8898                                    let p5: core::arch::aarch64::uint8x8_t =
8899                                        Self::neon_load_px_u8(src, (row_dn + coord_x - 1) * 4);
8900                                    let p6: core::arch::aarch64::uint8x8_t =
8901                                        Self::neon_load_px_u8(src, (row_dn + coord_x) * 4);
8902                                    let p7: core::arch::aarch64::uint8x8_t =
8903                                        Self::neon_load_px_u8(src, (row_dn + coord_x + 1) * 4);
8904                                    let lo_a: core::arch::aarch64::uint8x8_t =
8905                                        core::arch::aarch64::vmin_u8(
8906                                            core::arch::aarch64::vmin_u8(p0, p1),
8907                                            core::arch::aarch64::vmin_u8(p2, p3),
8908                                        );
8909                                    let lo_b: core::arch::aarch64::uint8x8_t =
8910                                        core::arch::aarch64::vmin_u8(
8911                                            core::arch::aarch64::vmin_u8(p4, p5),
8912                                            core::arch::aarch64::vmin_u8(p6, p7),
8913                                        );
8914                                    let v_min: core::arch::aarch64::uint8x8_t =
8915                                        core::arch::aarch64::vmin_u8(
8916                                            core::arch::aarch64::vmin_u8(lo_a, lo_b),
8917                                            c_v,
8918                                        );
8919                                    let hi_a: core::arch::aarch64::uint8x8_t =
8920                                        core::arch::aarch64::vmax_u8(
8921                                            core::arch::aarch64::vmax_u8(p0, p1),
8922                                            core::arch::aarch64::vmax_u8(p2, p3),
8923                                        );
8924                                    let hi_b: core::arch::aarch64::uint8x8_t =
8925                                        core::arch::aarch64::vmax_u8(
8926                                            core::arch::aarch64::vmax_u8(p4, p5),
8927                                            core::arch::aarch64::vmax_u8(p6, p7),
8928                                        );
8929                                    let v_max: core::arch::aarch64::uint8x8_t =
8930                                        core::arch::aarch64::vmax_u8(
8931                                            core::arch::aarch64::vmax_u8(hi_a, hi_b),
8932                                            c_v,
8933                                        );
8934                                    let min_u32: u32 = core::arch::aarch64::vget_lane_u32::<0>(
8935                                        core::arch::aarch64::vreinterpret_u32_u8(v_min),
8936                                    );
8937                                    let max_u32: u32 = core::arch::aarch64::vget_lane_u32::<0>(
8938                                        core::arch::aarch64::vreinterpret_u32_u8(v_max),
8939                                    );
8940                                    let min_b: [u8; 4] = min_u32.to_le_bytes();
8941                                    let max_b: [u8; 4] = max_u32.to_le_bytes();
8942                                    (
8943                                        min_b[0] as i32,
8944                                        max_b[0] as i32,
8945                                        min_b[1] as i32,
8946                                        max_b[1] as i32,
8947                                        min_b[2] as i32,
8948                                        max_b[2] as i32,
8949                                    )
8950                                }
8951                            };
8952                            #[cfg(not(target_arch = "aarch64"))]
8953                            let (r_min, r_max, g_min, g_max, b_min, b_max): (
8954                                i32,
8955                                i32,
8956                                i32,
8957                                i32,
8958                                i32,
8959                                i32,
8960                            ) = {
8961                                let offsets: [usize; 8] = [
8962                                    (row_up + coord_x - 1) * 4,
8963                                    (row_up + coord_x) * 4,
8964                                    (row_up + coord_x + 1) * 4,
8965                                    (row + coord_x - 1) * 4,
8966                                    (row + coord_x + 1) * 4,
8967                                    (row_dn + coord_x - 1) * 4,
8968                                    (row_dn + coord_x) * 4,
8969                                    (row_dn + coord_x + 1) * 4,
8970                                ];
8971                                let mut r_lo: i32 = rgb[0];
8972                                let mut r_hi: i32 = rgb[0];
8973                                let mut g_lo: i32 = rgb[1];
8974                                let mut g_hi: i32 = rgb[1];
8975                                let mut b_lo: i32 = rgb[2];
8976                                let mut b_hi: i32 = rgb[2];
8977                                for off in offsets.into_iter() {
8978                                    let vr: i32 = src[off] as i32;
8979                                    let vg: i32 = src[off + 1] as i32;
8980                                    let vb: i32 = src[off + 2] as i32;
8981                                    r_lo = r_lo.min(vr);
8982                                    r_hi = r_hi.max(vr);
8983                                    g_lo = g_lo.min(vg);
8984                                    g_hi = g_hi.max(vg);
8985                                    b_lo = b_lo.min(vb);
8986                                    b_hi = b_hi.max(vb);
8987                                }
8988                                (r_lo, r_hi, g_lo, g_hi, b_lo, b_hi)
8989                            };
8990                            let hr_c: i32 = hr.clamp(r_min, r_max);
8991                            let hg_c: i32 = hg.clamp(g_min, g_max);
8992                            let hb_c: i32 = hb.clamp(b_min, b_max);
8993                            rgb[0] = ((rgb[0] * 192 + hr_c * 64 + 128) >> 8).clamp(0, 255);
8994                            rgb[1] = ((rgb[1] * 192 + hg_c * 64 + 128) >> 8).clamp(0, 255);
8995                            rgb[2] = ((rgb[2] * 192 + hb_c * 64 + 128) >> 8).clamp(0, 255);
8996                        }
8997                    }
8998                }
8999                if !geom_edge && (4..=56).contains(&contrast) {
9000                    let off_u: usize = (row_up + coord_x) * 4;
9001                    let off_d: usize = (row_dn + coord_x) * 4;
9002                    let off_l: usize = (row + coord_x - 1) * 4;
9003                    let off_r: usize = (row + coord_x + 1) * 4;
9004                    for ch in 0..3usize {
9005                        let cu: i32 = src[off_u + ch] as i32;
9006                        let cd: i32 = src[off_d + ch] as i32;
9007                        let cl: i32 = src[off_l + ch] as i32;
9008                        let cr: i32 = src[off_r + ch] as i32;
9009                        let nbr_min: i32 = cu.min(cd).min(cl).min(cr).min(rgb[ch]);
9010                        let nbr_max: i32 = cu.max(cd).max(cl).max(cr).max(rgb[ch]);
9011                        let lap: i32 = rgb[ch] * 4 - (cu + cd + cl + cr);
9012                        rgb[ch] = (rgb[ch] + ((lap * 56) >> 10)).clamp(nbr_min, nbr_max);
9013                    }
9014                }
9015                if row_has_bloom {
9016                    let bx0: usize = (coord_x >> 2).min(bw_max);
9017                    if bloom_row_mask[bx0] != 0 {
9018                        let tx: f32 = ((coord_x & 3) as f32) * 0.25;
9019                        let bl: [f32; 3] = Self::sample_bloom_bilinear_row(
9020                            bloom,
9021                            (bloom_r0, bloom_r1, bw_max),
9022                            (bx0, tx, ty),
9023                        );
9024                        rgb[0] = (rgb[0] + (bl[0] * 78.0) as i32).min(255);
9025                        rgb[1] = (rgb[1] + (bl[1] * 78.0) as i32).min(255);
9026                        rgb[2] = (rgb[2] + (bl[2] * 78.0) as i32).min(255);
9027                    }
9028                }
9029                // SAFETY: `dc + 4 <= band_rows * row_bytes` and `[u8; 4]` has alignment 1.
9030                unsafe {
9031                    dst_ptr.add(dc).cast::<[u8; 4]>().write([
9032                        rgb[0] as u8,
9033                        rgb[1] as u8,
9034                        rgb[2] as u8,
9035                        255,
9036                    ]);
9037                }
9038                coord_x += 1;
9039            }
9040            if use_fxaa || has_bloom {
9041                let v_norm: f32 = (((coord_y as f32) + 0.5) / (height_val.max(1) as f32)) - 0.5;
9042                let v_sq: f32 = v_norm * v_norm;
9043                let inv_wf: f32 = 1.0 / (width_val.max(1) as f32);
9044                for vig_x in 0..width_val {
9045                    let u_norm: f32 = (((vig_x as f32) + 0.5) * inv_wf) - 0.5;
9046                    let r2: f32 = u_norm * u_norm + v_sq;
9047                    if r2 > 0.16 {
9048                        let vig_q8: u32 =
9049                            ((1.0 - (r2 - 0.16) * 0.44).clamp(0.82, 1.0) * 256.0) as u32;
9050                        let px_off: usize = dst_off + vig_x * 4;
9051                        // SAFETY: `px_off + 4 <= band_rows * row_bytes`.
9052                        unsafe {
9053                            let p_ptr: *mut u8 = dst_ptr.add(px_off);
9054                            *p_ptr = (((*p_ptr as u32) * vig_q8) >> 8) as u8;
9055                            *p_ptr.add(1) = (((*p_ptr.add(1) as u32) * vig_q8) >> 8) as u8;
9056                            *p_ptr.add(2) = (((*p_ptr.add(2) as u32) * vig_q8) >> 8) as u8;
9057                        }
9058                    }
9059                }
9060            }
9061        }
9062    }
9063
9064    /// Projects, culls, clips, and builds screen-space setup records for one frustum-visible object with smooth 3-vertex normal averaging.
9065    ///
9066    /// # Arguments
9067    ///
9068    /// - `&GeomPassContext<'_>` - Immutable per-frame frustum, Hi-Z, camera, and sky parameters.
9069    /// - `usize` - Index inside `visible_scratch` for Hi-Z pre-pass flag lookup.
9070    /// - `f32` - Squared distance from camera to object bounds center.
9071    /// - `usize` - Object index inside `ctx.objects`.
9072    /// - `&mut GeomPassOut<'_>` - Mutable per-chunk or sequential geometry output buffers and counters.
9073    fn process_visible_object_geom(
9074        ctx: &GeomPassContext<'_>,
9075        vis_slot: usize,
9076        dist_sq: f32,
9077        obj_idx: usize,
9078        out: &mut GeomPassOut<'_>,
9079    ) {
9080        let obj: &SceneObject3D = &ctx.objects[obj_idx];
9081        let skip_hiz_obj: bool = obj.get_is_dynamic()
9082            || obj.get_material().get_emissive().length_sq() > 0.05
9083            || obj.get_material().get_surface_detail() == SurfaceDetailMode::OceanWater;
9084        if ctx.hiz_active && ctx.hiz_occluder_flags[vis_slot] == 0 && !skip_hiz_obj {
9085            let obj_bounds: AxisAlignedBox3D = obj.get_world_bounds();
9086            let area_px: f32 = HiZPyramid::projected_screen_area_px(
9087                obj_bounds,
9088                &ctx.view_proj,
9089                ctx.w_f,
9090                ctx.h_f,
9091                ctx.near_plane,
9092            );
9093            if area_px < NANITE_MIN_SCREEN_AREA_PX
9094                || ctx
9095                    .hiz_pyramid
9096                    .is_bounds_occluded(obj_bounds, &ctx.view_proj, ctx.near_plane)
9097            {
9098                out.hiz_culled_objects += 1;
9099                return;
9100            }
9101        }
9102        let Some(chain) = ctx.mesh_lib.get(obj.get_mesh_id()) else {
9103            return;
9104        };
9105        out.visible_objects += 1;
9106        if let Some(unique_set) = out.unique_meshes.as_deref_mut() {
9107            let _: bool = unique_set.insert(obj.get_mesh_id());
9108        } else if let Some(mesh_ids) = out.mesh_ids.as_deref_mut() {
9109            mesh_ids.push(obj.get_mesh_id());
9110        }
9111        let dist: f32 = dist_sq.sqrt();
9112        let obj_radius: f32 = obj.get_world_bounds().radius();
9113        let deformed_mesh: Option<&Mesh3D> =
9114            ctx.deformed_meshes.get(obj_idx).and_then(Option::as_ref);
9115        let (mesh, lod_idx): (&Mesh3D, usize) = if let Some(deformed) = deformed_mesh {
9116            (deformed, 0)
9117        } else {
9118            chain.select_screen_error(dist, obj_radius, ctx.focal_px, ctx.lod_bias)
9119        };
9120        if lod_idx > 0 {
9121            out.lod_simplified_objects += 1;
9122        }
9123        let transform_val: Transform3D = obj.get_transform();
9124        let model_mat4: Mat4 = transform_val.to_mat4();
9125        let mvp_mat4: Mat4 = ctx.view_proj.mul(model_mat4);
9126        let normal_mat3: [Vec3; 3] = transform_val.normal_mat3();
9127        let tr_scale: Vec3 = transform_val.get_scale();
9128        let det_scale: f32 = tr_scale.get_x() * tr_scale.get_y() * tr_scale.get_z();
9129        let principled_id: Option<u32> = obj.try_get_principled_material_id();
9130        let double_sided: bool = principled_id
9131            .and_then(|mat_idx: u32| ctx.principled_materials.get(mat_idx as usize))
9132            .is_some_and(PrincipledMaterial3D::get_double_sided);
9133        let cull_backface: bool = mesh.get_is_closed() && det_scale > 0.0 && !double_sided;
9134        let obj_mat: PbrMaterial = obj.get_material();
9135        let has_sub_mats: bool = !mesh.get_tri_materials().is_empty();
9136        let base_mat_base: Vec3 = obj_mat.get_base_color();
9137        let base_mat_emissive: Vec3 = obj_mat.get_emissive();
9138        let base_mat_refl: f32 = obj_mat.get_reflectivity();
9139        let base_metallic: f32 = obj_mat.get_metallic();
9140        let base_rough: f32 = obj_mat.get_roughness();
9141        let base_alpha: f32 = (base_rough * base_rough).max(0.018);
9142        let base_alpha2: f32 = base_alpha * base_alpha;
9143        let base_f0: Vec3 = Vec3::splat(0.04).lerp(base_mat_base, base_metallic);
9144        let base_diffuse_scale: f32 = 1.0 - base_metallic;
9145        let base_do_refl: bool = ctx.use_rt_refl && base_mat_refl > 0.25;
9146        let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
9147        let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
9148        let meshlets: &[Meshlet3D] = mesh.get_meshlets().as_slice();
9149        out.cluster_ranges.clear();
9150        if deformed_mesh.is_none()
9151            && lod_idx == 0
9152            && ctx.frustum_on
9153            && let Some(nanite_dag) = ctx
9154                .nanite_dags
9155                .get(obj.get_mesh_id())
9156                .and_then(Option::as_ref)
9157        {
9158            let hiz_opt: Option<&HiZPyramid> =
9159                if ctx.hiz_active && ctx.hiz_occluder_flags[vis_slot] == 0 {
9160                    Some(ctx.hiz_pyramid)
9161                } else {
9162                    None
9163                };
9164            let cut_ctx: NaniteCutContext<'_> = NaniteCutContext {
9165                camera_position: ctx.cam_pos,
9166                model_matrix: model_mat4,
9167                view_projection: ctx.view_proj,
9168                normal_basis: normal_mat3,
9169                frustum: ctx.frustum,
9170                hiz_pyramid: hiz_opt,
9171                cull_backface,
9172                focal_px: ctx.focal_px,
9173                error_threshold_px: (1.5 * ctx.lod_bias.max(0.25)).clamp(0.5, 8.0),
9174                near_plane: ctx.near_plane,
9175                viewport_width: ctx.w_f,
9176                viewport_height: ctx.h_f,
9177                total_triangles: indices.len(),
9178            };
9179            let cut_stats: NaniteCutStats = nanite_dag.select_cut(&cut_ctx, out.cluster_ranges);
9180            out.meshlets_drawn += cut_stats.get_clusters_drawn();
9181            out.meshlets_culled += cut_stats.get_clusters_frustum_culled()
9182                + cut_stats.get_clusters_cone_culled()
9183                + cut_stats.get_clusters_micro_culled()
9184                + cut_stats.get_clusters_hiz_culled();
9185        } else if deformed_mesh.is_none() && meshlets.len() > 1 && ctx.frustum_on {
9186            for mlet in meshlets.iter() {
9187                let wb: AxisAlignedBox3D = model_mat4.transform_bounds(mlet.get_bounds());
9188                if !ctx.frustum.intersects_bounds(&wb) {
9189                    out.meshlets_culled += 1;
9190                    continue;
9191                }
9192                if ctx.hiz_active
9193                    && ctx.hiz_occluder_flags[vis_slot] == 0
9194                    && ctx
9195                        .hiz_pyramid
9196                        .is_bounds_occluded(wb, &ctx.view_proj, ctx.near_plane)
9197                {
9198                    out.meshlets_culled += 1;
9199                    continue;
9200                }
9201                let cutoff: f32 = mlet.get_cone_cutoff();
9202                if cull_backface && cutoff > 0.05 {
9203                    let world_axis: Vec3 =
9204                        Mat4::transform_normal_with_basis(mlet.get_cone_axis(), normal_mat3);
9205                    let v_cam: Vec3 = wb.center().sub(ctx.cam_pos);
9206                    let v_len: f32 = v_cam.length();
9207                    let sin_alpha: f32 = (1.0 - cutoff * cutoff).max(0.0).sqrt();
9208                    if v_cam.dot(world_axis) > v_len * sin_alpha + wb.radius() {
9209                        out.meshlets_culled += 1;
9210                        continue;
9211                    }
9212                }
9213                out.meshlets_drawn += 1;
9214                let s0: usize = mlet.get_first_tri() as usize;
9215                let s1: usize = (s0 + (mlet.get_tri_count() as usize)).min(indices.len());
9216                out.cluster_ranges.push((s0, s1));
9217            }
9218        } else {
9219            out.meshlets_drawn += meshlets.len().max(1);
9220            out.cluster_ranges.push((0, indices.len()));
9221        }
9222        if out.cluster_ranges.is_empty() {
9223            return;
9224        }
9225        out.projected_verts.clear();
9226        out.projected_verts.reserve(verts.len());
9227        for item_val in verts.iter() {
9228            let lp: Vec3 = item_val.get_position();
9229            let cp: [f32; 4] = mvp_mat4.mul_point4(lp);
9230            let wp: Vec3 = model_mat4.mul_point3(lp);
9231            out.projected_verts.push((cp, wp));
9232        }
9233        let vert_count: usize = out.projected_verts.len();
9234        for &(tri_start, tri_end) in out.cluster_ranges.iter() {
9235            for (local_offset, tri) in indices[tri_start..tri_end].iter().enumerate() {
9236                let global_tri_idx: usize = tri_start + local_offset;
9237                let (i0, i1, i2): (usize, usize, usize) =
9238                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
9239                let oob_01: bool = i0 >= vert_count || i1 >= vert_count;
9240                if oob_01 || i2 >= vert_count {
9241                    continue;
9242                }
9243                let (c0, wp0): ([f32; 4], Vec3) = out.projected_verts[i0];
9244                let (c1, wp1): ([f32; 4], Vec3) = out.projected_verts[i1];
9245                let (c2, wp2): ([f32; 4], Vec3) = out.projected_verts[i2];
9246                if c0[3] < ctx.near_plane && c1[3] < ctx.near_plane && c2[3] < ctx.near_plane {
9247                    continue;
9248                }
9249                let out_l: bool = c0[0] < -c0[3] && c1[0] < -c1[3] && c2[0] < -c2[3];
9250                let out_r: bool = c0[0] > c0[3] && c1[0] > c1[3] && c2[0] > c2[3];
9251                let out_b: bool = c0[1] < -c0[3] && c1[1] < -c1[3] && c2[1] < -c2[3];
9252                let out_t: bool = c0[1] > c0[3] && c1[1] > c1[3] && c2[1] > c2[3];
9253                let out_x: bool = out_l || out_r;
9254                let out_y: bool = out_b || out_t;
9255                if out_x || out_y {
9256                    continue;
9257                }
9258                let (clipped_tris, clipped_count): ([ClippedBaryVert; 6], usize) = if c0[3]
9259                    >= ctx.near_plane
9260                    && c1[3] >= ctx.near_plane
9261                    && c2[3] >= ctx.near_plane
9262                {
9263                    let zero_clip: ClippedBaryVert = ClippedBaryVert {
9264                        clip_pos: [0.0; 4],
9265                        world_pos: Vec3::zero(),
9266                        bary: [0.0; 3],
9267                    };
9268                    (
9269                        [
9270                            ClippedBaryVert {
9271                                clip_pos: c0,
9272                                world_pos: wp0,
9273                                bary: [1.0, 0.0, 0.0],
9274                            },
9275                            ClippedBaryVert {
9276                                clip_pos: c1,
9277                                world_pos: wp1,
9278                                bary: [0.0, 1.0, 0.0],
9279                            },
9280                            ClippedBaryVert {
9281                                clip_pos: c2,
9282                                world_pos: wp2,
9283                                bary: [0.0, 0.0, 1.0],
9284                            },
9285                            zero_clip,
9286                            zero_clip,
9287                            zero_clip,
9288                        ],
9289                        1,
9290                    )
9291                } else {
9292                    Self::clip_triangle_near_bary((c0, wp0), (c1, wp1), (c2, wp2), ctx.near_plane)
9293                };
9294                if clipped_count == 0 {
9295                    continue;
9296                }
9297                let vert0: Vertex3D = verts[i0];
9298                let vert1: Vertex3D = verts[i1];
9299                let vert2: Vertex3D = verts[i2];
9300                let local_n0: Vec3 = vert0.get_normal();
9301                let local_n1: Vec3 = vert1.get_normal();
9302                let local_n2: Vec3 = vert2.get_normal();
9303                let has_varied_normals: bool = local_n0.sub(local_n1).length_sq() > 1.0e-4
9304                    || local_n0.sub(local_n2).length_sq() > 1.0e-4;
9305                let has_extra_attrs: bool =
9306                    ((vert0.get_flags() | vert1.get_flags() | vert2.get_flags()) & 9) != 0;
9307                let mut cached_wn: Option<Vec3> = None;
9308                for ci in 0..clipped_count {
9309                    let base_ci: usize = ci * 3;
9310                    let cv0: ClippedBaryVert = clipped_tris[base_ci];
9311                    let cv1: ClippedBaryVert = clipped_tris[base_ci + 1];
9312                    let cv2: ClippedBaryVert = clipped_tris[base_ci + 2];
9313                    let (tc0, tw0, tb0): ([f32; 4], Vec3, [f32; 3]) =
9314                        (cv0.clip_pos, cv0.world_pos, cv0.bary);
9315                    let (tc1, tw1, tb1): ([f32; 4], Vec3, [f32; 3]) =
9316                        (cv1.clip_pos, cv1.world_pos, cv1.bary);
9317                    let (tc2, tw2, tb2): ([f32; 4], Vec3, [f32; 3]) =
9318                        (cv2.clip_pos, cv2.world_pos, cv2.bary);
9319                    let inv_w0: f32 = 1.0 / tc0[3];
9320                    let inv_w1: f32 = 1.0 / tc1[3];
9321                    let inv_w2: f32 = 1.0 / tc2[3];
9322                    let sx0: f32 = (tc0[0] * inv_w0 * 0.5 + 0.5) * ctx.w_f + ctx.jitter_x;
9323                    let sy0: f32 = (0.5 - tc0[1] * inv_w0 * 0.5) * ctx.h_f + ctx.jitter_y;
9324                    let sx1: f32 = (tc1[0] * inv_w1 * 0.5 + 0.5) * ctx.w_f + ctx.jitter_x;
9325                    let sy1: f32 = (0.5 - tc1[1] * inv_w1 * 0.5) * ctx.h_f + ctx.jitter_y;
9326                    let sx2: f32 = (tc2[0] * inv_w2 * 0.5 + 0.5) * ctx.w_f + ctx.jitter_x;
9327                    let sy2: f32 = (0.5 - tc2[1] * inv_w2 * 0.5) * ctx.h_f + ctx.jitter_y;
9328                    let area: f32 = (sx1 - sx0) * (sy2 - sy0) - (sy1 - sy0) * (sx2 - sx0);
9329                    if cull_backface {
9330                        if area >= -0.25 {
9331                            continue;
9332                        }
9333                    } else if area.abs() < 0.25 {
9334                        continue;
9335                    }
9336                    let min_x: i32 = (sx0.min(sx1).min(sx2).floor() as i32).max(0);
9337                    let max_x: i32 = (sx0.max(sx1).max(sx2).ceil() as i32).min(ctx.w_max_i);
9338                    let min_y: i32 = (sy0.min(sy1).min(sy2).floor() as i32).max(0);
9339                    let max_y: i32 = (sy0.max(sy1).max(sy2).ceil() as i32).min(ctx.h_max_i);
9340                    if min_x > max_x || min_y > max_y {
9341                        continue;
9342                    }
9343                    let wn: Vec3 = match cached_wn {
9344                        Some(item_count) => item_count,
9345                        None => {
9346                            let n_avg_local: Vec3 = local_n0.add(local_n1).add(local_n2);
9347                            let n_local: Vec3 = if n_avg_local.length_sq() > 1.0e-6 {
9348                                n_avg_local.normalize()
9349                            } else {
9350                                local_n0
9351                            };
9352                            let computed: Vec3 =
9353                                Mat4::transform_normal_with_basis(n_local, normal_mat3);
9354                            cached_wn = Some(computed);
9355                            computed
9356                        }
9357                    };
9358                    let tri_id: u32 = out.shaded_tris.len() as u32;
9359                    let shade_n: Vec3 = if cull_backface {
9360                        wn
9361                    } else {
9362                        let tri_center: Vec3 = tw0.add(tw1).add(tw2).scale(1.0 / 3.0);
9363                        let tri_view: Vec3 = ctx.cam_pos.sub(tri_center);
9364                        if wn.dot(tri_view) < 0.0 {
9365                            wn.scale(-1.0)
9366                        } else {
9367                            wn
9368                        }
9369                    };
9370                    let n_dot_l: f32 = shade_n.dot(ctx.sun_dir).max(0.0);
9371                    let ambient_sky: Vec3 = ctx.sky_horizon.lerp(
9372                        ctx.sky_zenith,
9373                        (shade_n.get_y() * 0.5 + 0.5).clamp(0.0, 1.0),
9374                    );
9375                    let (
9376                        tri_base,
9377                        tri_emissive,
9378                        tri_f0,
9379                        tri_alpha2,
9380                        tri_diffuse_scale,
9381                        tri_refl,
9382                        tri_metallic,
9383                        tri_do_refl,
9384                        tri_surface_detail,
9385                    ): (
9386                        Vec3,
9387                        Vec3,
9388                        Vec3,
9389                        f32,
9390                        f32,
9391                        f32,
9392                        f32,
9393                        bool,
9394                        SurfaceDetailMode,
9395                    ) = if !has_sub_mats {
9396                        (
9397                            base_mat_base,
9398                            base_mat_emissive,
9399                            base_f0,
9400                            base_alpha2,
9401                            base_diffuse_scale,
9402                            base_mat_refl,
9403                            base_metallic,
9404                            base_do_refl,
9405                            obj_mat.get_surface_detail(),
9406                        )
9407                    } else {
9408                        let (resolved, _): (PbrMaterial, u16) =
9409                            mesh.resolve_triangle_material(global_tri_idx, obj_mat);
9410                        let sub_base: Vec3 = resolved.get_base_color();
9411                        let sub_metal: f32 = resolved.get_metallic();
9412                        let sub_rough: f32 = resolved.get_roughness();
9413                        let sub_alpha: f32 = (sub_rough * sub_rough).max(0.018);
9414                        let sub_refl: f32 = resolved.get_reflectivity();
9415                        (
9416                            sub_base,
9417                            resolved.get_emissive(),
9418                            Vec3::splat(0.04).lerp(sub_base, sub_metal),
9419                            sub_alpha * sub_alpha,
9420                            1.0 - sub_metal,
9421                            sub_refl,
9422                            sub_metal,
9423                            ctx.use_rt_refl && sub_refl > 0.25,
9424                            resolved.get_surface_detail(),
9425                        )
9426                    };
9427                    let inv_area: f32 = 1.0 / area;
9428                    let smooth_attrs: bool = has_varied_normals || has_extra_attrs;
9429                    let smooth_legacy: bool = smooth_attrs || ctx.use_agx_tonemap;
9430                    let use_smooth: bool = principled_id.is_some()
9431                        || (tri_surface_detail == SurfaceDetailMode::None && smooth_legacy);
9432                    let smooth_idx: u32 = if use_smooth {
9433                        let world_n0: Vec3 =
9434                            Mat4::transform_normal_with_basis(local_n0, normal_mat3);
9435                        let world_n1: Vec3 =
9436                            Mat4::transform_normal_with_basis(local_n1, normal_mat3);
9437                        let world_n2: Vec3 =
9438                            Mat4::transform_normal_with_basis(local_n2, normal_mat3);
9439                        let tan_raw0: [f32; 4] = vert0.get_tangent();
9440                        let tan_raw1: [f32; 4] = vert1.get_tangent();
9441                        let tan_raw2: [f32; 4] = vert2.get_tangent();
9442                        let world_t0_v: Vec3 = Mat4::transform_normal_with_basis(
9443                            Vec3::new(tan_raw0[0], tan_raw0[1], tan_raw0[2]),
9444                            normal_mat3,
9445                        );
9446                        let world_t1_v: Vec3 = Mat4::transform_normal_with_basis(
9447                            Vec3::new(tan_raw1[0], tan_raw1[1], tan_raw1[2]),
9448                            normal_mat3,
9449                        );
9450                        let world_t2_v: Vec3 = Mat4::transform_normal_with_basis(
9451                            Vec3::new(tan_raw2[0], tan_raw2[1], tan_raw2[2]),
9452                            normal_mat3,
9453                        );
9454                        let uv0_orig: [[f32; 2]; 3] =
9455                            [vert0.get_uv0(), vert1.get_uv0(), vert2.get_uv0()];
9456                        let uv1_orig: [[f32; 2]; 3] =
9457                            [vert0.get_uv1(), vert1.get_uv1(), vert2.get_uv1()];
9458                        let unpack_col: fn([u8; 4]) -> [f32; 4] = |rgba_u8: [u8; 4]| -> [f32; 4] {
9459                            [
9460                                srgb_u8_to_linear(rgba_u8[0]),
9461                                srgb_u8_to_linear(rgba_u8[1]),
9462                                srgb_u8_to_linear(rgba_u8[2]),
9463                                f32::from(rgba_u8[3]) / 255.0,
9464                            ]
9465                        };
9466                        let col_orig: [[f32; 4]; 3] = [
9467                            unpack_col(vert0.get_color0()),
9468                            unpack_col(vert1.get_color0()),
9469                            unpack_col(vert2.get_color0()),
9470                        ];
9471                        let bary_list: [[f32; 3]; 3] = [tb0, tb1, tb2];
9472                        let mut interp_normals: [Vec3; 3] = [Vec3::zero(); 3];
9473                        let mut interp_tangents: [[f32; 4]; 3] = [[1.0, 0.0, 0.0, 1.0]; 3];
9474                        let mut interp_uv0: [[f32; 2]; 3] = [[0.0; 2]; 3];
9475                        let mut interp_uv1: [[f32; 2]; 3] = [[0.0; 2]; 3];
9476                        let mut interp_col: [[f32; 4]; 3] = [[1.0; 4]; 3];
9477                        for corner_idx in 0..3usize {
9478                            let b_w: [f32; 3] = bary_list[corner_idx];
9479                            let n_mix: Vec3 = world_n0
9480                                .scale(b_w[0])
9481                                .add(world_n1.scale(b_w[1]))
9482                                .add(world_n2.scale(b_w[2]));
9483                            interp_normals[corner_idx] = if n_mix.length_sq() > 1.0e-8 {
9484                                n_mix.normalize()
9485                            } else {
9486                                shade_n
9487                            };
9488                            let t_mix: Vec3 = world_t0_v
9489                                .scale(b_w[0])
9490                                .add(world_t1_v.scale(b_w[1]))
9491                                .add(world_t2_v.scale(b_w[2]));
9492                            let t_unit: Vec3 = if t_mix.length_sq() > 1.0e-8 {
9493                                t_mix.normalize()
9494                            } else {
9495                                Vec3::new(1.0, 0.0, 0.0)
9496                            };
9497                            let t_hand: f32 =
9498                                tan_raw0[3] * b_w[0] + tan_raw1[3] * b_w[1] + tan_raw2[3] * b_w[2];
9499                            interp_tangents[corner_idx] = [
9500                                t_unit.get_x(),
9501                                t_unit.get_y(),
9502                                t_unit.get_z(),
9503                                if t_hand < 0.0 { -1.0 } else { 1.0 },
9504                            ];
9505                            interp_uv0[corner_idx] = [
9506                                uv0_orig[0][0] * b_w[0]
9507                                    + uv0_orig[1][0] * b_w[1]
9508                                    + uv0_orig[2][0] * b_w[2],
9509                                uv0_orig[0][1] * b_w[0]
9510                                    + uv0_orig[1][1] * b_w[1]
9511                                    + uv0_orig[2][1] * b_w[2],
9512                            ];
9513                            interp_uv1[corner_idx] = [
9514                                uv1_orig[0][0] * b_w[0]
9515                                    + uv1_orig[1][0] * b_w[1]
9516                                    + uv1_orig[2][0] * b_w[2],
9517                                uv1_orig[0][1] * b_w[0]
9518                                    + uv1_orig[1][1] * b_w[1]
9519                                    + uv1_orig[2][1] * b_w[2],
9520                            ];
9521                            for ch_idx in 0..4usize {
9522                                interp_col[corner_idx][ch_idx] = col_orig[0][ch_idx] * b_w[0]
9523                                    + col_orig[1][ch_idx] * b_w[1]
9524                                    + col_orig[2][ch_idx] * b_w[2];
9525                            }
9526                        }
9527                        let new_smooth_id: u32 = out.smooth_tris.len() as u32;
9528                        out.smooth_tris.push(GSmoothTri {
9529                            screen_x: [sx0, sx1, sx2],
9530                            screen_y: [sy0, sy1, sy2],
9531                            inv_w: [inv_w0, inv_w1, inv_w2],
9532                            inv_area,
9533                            normals: interp_normals,
9534                            tangents: interp_tangents,
9535                            uv0: interp_uv0,
9536                            uv1: interp_uv1,
9537                            color0: interp_col,
9538                            principled_material_id: principled_id.unwrap_or(u32::MAX),
9539                            double_sided: !cull_backface,
9540                        });
9541                        new_smooth_id
9542                    } else {
9543                        u32::MAX
9544                    };
9545                    out.shaded_tris.push(GShadeTri {
9546                        shade_n,
9547                        mat_base: tri_base,
9548                        mat_emissive: tri_emissive,
9549                        ambient_sky,
9550                        f0: tri_f0,
9551                        n_dot_l,
9552                        alpha2: tri_alpha2,
9553                        diffuse_scale: tri_diffuse_scale,
9554                        mat_refl: tri_refl,
9555                        metallic: tri_metallic,
9556                        do_refl: tri_do_refl,
9557                        surface_detail: tri_surface_detail,
9558                        smooth_idx,
9559                    });
9560                    let dw0_dx: f32 = (sy1 - sy2) * inv_area;
9561                    let dw1_dx: f32 = (sy2 - sy0) * inv_area;
9562                    let dw2_dx: f32 = -(dw0_dx + dw1_dx);
9563                    let dw0_dy: f32 = (sx2 - sx1) * inv_area;
9564                    let dw1_dy: f32 = (sx0 - sx2) * inv_area;
9565                    let dw2_dy: f32 = -(dw0_dy + dw1_dy);
9566                    let d_inv_w_dx: f32 = dw0_dx * inv_w0 + dw1_dx * inv_w1 + dw2_dx * inv_w2;
9567                    let d_inv_w_dy: f32 = dw0_dy * inv_w0 + dw1_dy * inv_w1 + dw2_dy * inv_w2;
9568                    let neg_inv_slopes: [f32; 3] = [
9569                        if dw0_dx.abs() > 1e-9 {
9570                            -1.0 / dw0_dx
9571                        } else {
9572                            0.0
9573                        },
9574                        if dw1_dx.abs() > 1e-9 {
9575                            -1.0 / dw1_dx
9576                        } else {
9577                            0.0
9578                        },
9579                        if dw2_dx.abs() > 1e-9 {
9580                            -1.0 / dw2_dx
9581                        } else {
9582                            0.0
9583                        },
9584                    ];
9585                    let slopes: [f32; 3] = [dw0_dx, dw1_dx, dw2_dx];
9586                    let span_max: i32 = max_x - min_x;
9587                    let fx_start: f32 = (min_x as f32) + 0.5;
9588                    let fy_start: f32 = (min_y as f32) + 0.5;
9589                    let w0_row: f32 = ((sx1 - fx_start) * (sy2 - fy_start)
9590                        - (sy1 - fy_start) * (sx2 - fx_start))
9591                        * inv_area;
9592                    let w1_row: f32 = ((sx2 - fx_start) * (sy0 - fy_start)
9593                        - (sy2 - fy_start) * (sx0 - fx_start))
9594                        * inv_area;
9595                    let w2_row: f32 = 1.0 - w0_row - w1_row;
9596                    let inv_w_row: f32 = w0_row * inv_w0 + w1_row * inv_w1 + w2_row * inv_w2;
9597                    out.raster_tris.push(RasterTri2D {
9598                        min_y,
9599                        max_y,
9600                        min_x,
9601                        span_max,
9602                        tri_id,
9603                        slopes,
9604                        neg_inv_slopes,
9605                        dw_dy: [dw0_dy, dw1_dy, dw2_dy],
9606                        w_start: [w0_row, w1_row, w2_row],
9607                        inv_w_start: inv_w_row,
9608                        d_inv_w_dx,
9609                        d_inv_w_dy,
9610                    });
9611                }
9612            }
9613        }
9614    }
9615
9616    /// Renders `world` at runtime-configured `quality` directly into `out_pixels` without zero-filling, returning internal `(width, height)`.
9617    ///
9618    /// # Arguments
9619    ///
9620    /// - `&Self` - Mutable 3D renderer.
9621    /// - `&mut World3D` - Open-world 3D scene graph.
9622    /// - `u32` - Target viewport width in logical pixels.
9623    /// - `u32` - Target viewport height in logical pixels.
9624    /// - `&RenderQualityConfig` - Live runtime quality, resolution scale, LOD, and ray-tracing settings.
9625    /// - `&mut Vec<u8>` - Destination RGBA8 byte buffer resized without zero-fill and populated completely.
9626    ///
9627    /// # Returns
9628    ///
9629    /// - `(u32, u32)` - Internal rasterized framebuffer `(width, height)`.
9630    fn render_world_into_vec(
9631        &mut self,
9632        world: &mut World3D,
9633        viewport_w: u32,
9634        viewport_h: u32,
9635        quality: &RenderQualityConfig,
9636        out_pixels: &mut Vec<u8>,
9637    ) -> (u32, u32) {
9638        let scale: f32 = quality.get_resolution_scale().clamp(0.40, 4.0);
9639        let min_width: u32 = viewport_w.clamp(1, 240);
9640        let min_height: u32 = viewport_h.clamp(1, 144);
9641        let span_width: u32 = (((viewport_w as f32) * scale).round() as u32).max(min_width);
9642        let span_height: u32 = (((viewport_h as f32) * scale).round() as u32).max(min_height);
9643        let w_usize: usize = span_width as usize;
9644        let h_usize: usize = span_height as usize;
9645        let pixel_count: usize = w_usize * h_usize;
9646        let border_width: usize = w_usize.div_ceil(4);
9647        let bh: usize = h_usize.div_ceil(4);
9648        if self.get_width() != span_width || self.get_height() != span_height {
9649            self.set_width(span_width);
9650            self.set_height(span_height);
9651            let Self {
9652                color_buffer,
9653                aa_buffer,
9654                depth_buffer,
9655                g_tri_idx,
9656                luma_buffer,
9657                bloom_a,
9658                bloom_b,
9659                bloom_tile_active,
9660                hiz_pyramid,
9661                tsr_internal_scratch,
9662                has_taa_history,
9663                has_probe_history,
9664                ..
9665            } = self;
9666            let rgba_bytes: usize = pixel_count * 4;
9667            let bloom_cells: usize = border_width * bh;
9668            color_buffer.resize(rgba_bytes, 0);
9669            aa_buffer.resize(rgba_bytes, 0);
9670            depth_buffer.resize(pixel_count, 0.0);
9671            g_tri_idx.resize(pixel_count, u32::MAX);
9672            luma_buffer.resize(pixel_count, 0);
9673            bloom_a.resize(bloom_cells, [0.0; 4]);
9674            bloom_b.resize(bloom_cells, [0.0; 4]);
9675            bloom_tile_active.resize(bloom_cells, 0);
9676            hiz_pyramid.ensure_dimensions(w_usize, h_usize);
9677            tsr_internal_scratch.clear();
9678            if tsr_internal_scratch.capacity() < rgba_bytes {
9679                tsr_internal_scratch.reserve_exact(rgba_bytes);
9680            }
9681            *has_taa_history = false;
9682            *has_probe_history = false;
9683        }
9684        let rt_mode: RayTracingMode = quality.get_ray_tracing();
9685        if rt_mode != RayTracingMode::Off
9686            && (world.get_bvh_dirty()
9687                || world.get_dynamic_bvh_dirty()
9688                || (world.get_bvh().is_empty() && !world.get_objects().is_empty()))
9689        {
9690            world.ensure_bvh();
9691        }
9692        let sun: DirectionalLight3D = world.get_sun();
9693        self.ensure_sky_lut(&sun);
9694        let cam: Camera3D = world.get_camera();
9695        let aspect: f32 = (span_width as f32) / (span_height as f32).max(1.0);
9696        let matrix_value: Mat4 = world.active_view_projection(aspect);
9697        let frustum: Frustum3D = Frustum3D::from_view_proj(&matrix_value);
9698        let cam_fwd: Vec3 = cam.forward();
9699        let cam_right: Vec3 = cam.right();
9700        let cam_up: Vec3 = cam_right.cross(cam_fwd).normalize();
9701        let eff_fov_rad: f32 = Camera3D::effective_vertical_fov_rad(cam.get_fov_deg(), aspect);
9702        let half_h: f32 = (eff_fov_rad * 0.5).tan();
9703        let half_w: f32 = half_h * aspect;
9704        let focal_px: f32 = (span_height as f32) * 0.5 / half_h.max(0.05);
9705        let draw_dist_sq: f32 = quality.get_draw_distance() * quality.get_draw_distance();
9706        let frustum_on: bool = quality.get_frustum_culling();
9707        let chunk_on: bool = quality.get_chunk_streaming();
9708        let lod_bias: f32 = quality.get_lod_bias();
9709        let aa_mode: AntiAliasingMode = quality.get_anti_aliasing();
9710        let mut visible_objects: usize = 0;
9711        let mut culled_objects: usize = 0;
9712        let mut lod_simplified_objects: usize = 0;
9713        let mut meshlets_drawn: usize = 0;
9714        let mut meshlets_culled: usize = 0;
9715        let mut hiz_culled_objects: usize = 0;
9716        let use_vsm: bool = quality.get_virtual_shadow_maps()
9717            && (rt_mode == RayTracingMode::Off || !world.get_principled_materials().is_empty());
9718        if use_vsm {
9719            let Self {
9720                virtual_shadow_map, ..
9721            } = self;
9722            virtual_shadow_map.update_from_world(world);
9723        }
9724        let has_world_local_lights: bool = quality.get_clustered_lighting()
9725            && (!world.get_point_lights().is_empty() || !world.get_spot_lights().is_empty());
9726        let active_local_lights: usize = if has_world_local_lights {
9727            let Self { light_clusters, .. } = self;
9728            light_clusters.build_clusters(
9729                &cam,
9730                aspect,
9731                world.get_point_lights().as_slice(),
9732                world.get_spot_lights().as_slice(),
9733            );
9734            light_clusters.get_active_light_count()
9735        } else {
9736            0
9737        };
9738        let rt_stride_bias: usize = self.get_rt_stride_bias().min(2);
9739        let static_bvh: &Bvh3D = world.get_bvh();
9740        let dyn_instances: &[DynamicRayInstance] = world.dynamic_instances.as_slice();
9741        let local_bvhs: &[Option<Bvh3D>] = world.mesh_local_bvhs.as_slice();
9742        let total_bvh_nodes: usize = world.total_bvh_nodes();
9743        let world_rev: u64 = world.get_world_revision();
9744        let quality_fp: u64 = Self::quality_fingerprint(viewport_w, viewport_h, quality);
9745        {
9746            let Self {
9747                render_graph,
9748                cached_rdg_schedule,
9749                cached_rdg_key,
9750                last_executed_rdg_passes,
9751                ..
9752            } = self;
9753            if *cached_rdg_key != quality_fp || cached_rdg_schedule.get_ordered_passes().is_empty()
9754            {
9755                *render_graph =
9756                    RenderGraph3D::build_ue5_frame_graph(span_width, span_height, quality);
9757                *cached_rdg_schedule = render_graph.compile();
9758                *cached_rdg_key = quality_fp;
9759            }
9760            let executed_count: usize = render_graph.execute(
9761                cached_rdg_schedule,
9762                |_pass_kind: RenderPassKind3D, _pass_name: &str| -> u64 { 0 },
9763            );
9764            *last_executed_rdg_passes = executed_count;
9765        }
9766        let objects: &[SceneObject3D] = world.get_objects().as_slice();
9767        let mesh_lib: &[MeshLodChain] = world.get_mesh_library().as_slice();
9768        let deformed_meshes_slice: &[Option<Mesh3D>] = world.deformed_meshes.as_slice();
9769        let principled_mats_slice: &[PrincipledMaterial3D] =
9770            world.get_principled_materials().as_slice();
9771        let textures_slice: &[Texture2D3D] = world.get_textures().as_slice();
9772        let area_lights_slice: &[AreaLight3D] = world.get_area_lights().as_slice();
9773        let environment_ibl_ref: Option<&EnvironmentIbl3D> = world.environment_ibl();
9774        let use_agx_tonemap: bool = world.get_use_agx_tonemap();
9775        let cam_pos: Vec3 = cam.get_position();
9776        let sun_dir: Vec3 = sun.get_direction();
9777        let sky_horizon: Vec3 = sun.get_sky_horizon();
9778        let sky_zenith: Vec3 = sun.get_sky_zenith();
9779        let use_rt_refl: bool = matches!(
9780            rt_mode,
9781            RayTracingMode::ShadowsAndReflections | RayTracingMode::FullPathTracedGi
9782        );
9783        let base_rt_step: usize = if rt_mode == RayTracingMode::Off {
9784            0
9785        } else if cfg!(target_arch = "wasm32") {
9786            if w_usize >= 440 {
9787                7
9788            } else if w_usize >= 300 {
9789                6
9790            } else {
9791                4
9792            }
9793        } else if w_usize >= 1120 {
9794            7
9795        } else if w_usize >= 780 {
9796            6
9797        } else if w_usize >= 460 {
9798            5
9799        } else if w_usize >= 300 {
9800            4
9801        } else {
9802            2
9803        };
9804        let rt_step: usize = if base_rt_step > 0 {
9805            (base_rt_step + rt_stride_bias).min(8)
9806        } else {
9807            0
9808        };
9809        let gw: usize = if rt_step > 0 {
9810            w_usize.div_ceil(rt_step)
9811        } else {
9812            0
9813        };
9814        let gh: usize = if rt_step > 0 {
9815            h_usize.div_ceil(rt_step)
9816        } else {
9817            0
9818        };
9819        let tile_px: usize = ENGINE3D_TILE_MAX_PX
9820            .checked_div(rt_step)
9821            .map_or(ENGINE3D_TILE_MAX_PX, |entry_index: usize| {
9822                entry_index.max(1) * rt_step
9823            });
9824        let tiles_x: usize = w_usize.div_ceil(tile_px);
9825        let tiles_y: usize = h_usize.div_ceil(tile_px);
9826        let total_tiles: usize = tiles_x * tiles_y;
9827        let Self {
9828            color_buffer,
9829            aa_buffer,
9830            depth_buffer,
9831            g_tri_idx,
9832            luma_buffer,
9833            shaded_tris,
9834            smooth_tris,
9835            nanite_dags_cache,
9836            rt_probes,
9837            prev_rt_probes,
9838            has_probe_history,
9839            prev_probe_gw,
9840            prev_probe_gh,
9841            prev_probe_rt_mode,
9842            prev_sun_dir,
9843            rt_probes_wide_denoised,
9844            bloom_a,
9845            bloom_b,
9846            bloom_tile_active,
9847            visible_scratch,
9848            cluster_ranges_scratch,
9849            projected_verts_scratch,
9850            unique_meshes_scratch,
9851            raster_tris_scratch,
9852            tile_counts_scratch,
9853            tile_offsets_scratch,
9854            tile_cursors_scratch,
9855            tile_tri_indices_scratch,
9856            has_taa_history,
9857            prev_vp_m0,
9858            prev_view_proj,
9859            has_prev_vp,
9860            prev_render_dims,
9861            prev_rt_step,
9862            hiz_pyramid,
9863            hiz_occluder_flags_scratch,
9864            lumen_cache,
9865            light_clusters,
9866            virtual_shadow_map,
9867            tsr_upscaler,
9868            tsr_internal_scratch,
9869            geom_chunks_scratch,
9870            adapted_exposure,
9871            frame_index,
9872            sky_lut,
9873            aces_lut,
9874            saved_objs_scratch,
9875            reserved_object_cap,
9876            reserved_mesh_cap,
9877            ..
9878        } = self;
9879        if nanite_dags_cache.len() < mesh_lib.len() {
9880            let start_dag_idx: usize = nanite_dags_cache.len();
9881            for chain_item in mesh_lib[start_dag_idx..].iter() {
9882                let dag_entry: Option<NaniteClusterDag> = chain_item
9883                    .get_levels()
9884                    .first()
9885                    .filter(|lod0: &&Mesh3D| lod0.get_meshlets().len() > 1)
9886                    .map(NaniteClusterDag::from_mesh);
9887                nanite_dags_cache.push(dag_entry);
9888            }
9889        }
9890        let cur_frame_idx: usize = *frame_index as usize;
9891        let (jitter_x, jitter_y): (f32, f32) = if aa_mode == AntiAliasingMode::Tsr {
9892            HALTON_JITTER_8[cur_frame_idx & 7]
9893        } else {
9894            (0.0, 0.0)
9895        };
9896        *frame_index = frame_index.wrapping_add(1);
9897        if *reserved_object_cap < objects.len()
9898            || *reserved_mesh_cap < mesh_lib.len()
9899            || shaded_tris.capacity() == 0
9900        {
9901            let mut lod0_tris_sum: usize = 0;
9902            for scene_obj in objects.iter() {
9903                if let Some(chain) = mesh_lib.get(scene_obj.get_mesh_id())
9904                    && let Some(level0) = chain.get_levels().first()
9905                {
9906                    lod0_tris_sum = lod0_tris_sum.saturating_add(level0.get_indices().len());
9907                }
9908            }
9909            let mut max_mesh_verts: usize = 1_024;
9910            let mut max_mesh_clusters: usize = 128;
9911            for chain in mesh_lib.iter() {
9912                if let Some(level0) = chain.get_levels().first() {
9913                    max_mesh_verts = max_mesh_verts.max(level0.get_vertices().len());
9914                    max_mesh_clusters = max_mesh_clusters.max(level0.get_meshlets().len());
9915                }
9916            }
9917            let obj_cap: usize = objects.len().max(128);
9918            let mesh_cap: usize = mesh_lib.len().max(64);
9919            let max_scene_tris: usize = lod0_tris_sum.saturating_mul(2).max(8_192);
9920            let chunk_tri_cap: usize = (max_scene_tris / 2).max(2_048);
9921            if visible_scratch.capacity() < obj_cap {
9922                visible_scratch.reserve(obj_cap.saturating_sub(visible_scratch.len()));
9923            }
9924            if hiz_occluder_flags_scratch.capacity() < obj_cap {
9925                hiz_occluder_flags_scratch
9926                    .reserve(obj_cap.saturating_sub(hiz_occluder_flags_scratch.len()));
9927            }
9928            if saved_objs_scratch.capacity() < obj_cap {
9929                saved_objs_scratch.reserve(obj_cap.saturating_sub(saved_objs_scratch.len()));
9930            }
9931            if unique_meshes_scratch.capacity() < mesh_cap {
9932                unique_meshes_scratch.reserve(mesh_cap.saturating_sub(unique_meshes_scratch.len()));
9933            }
9934            if shaded_tris.capacity() < max_scene_tris {
9935                shaded_tris.reserve(max_scene_tris.saturating_sub(shaded_tris.len()));
9936            }
9937            if smooth_tris.capacity() < max_scene_tris {
9938                smooth_tris.reserve(max_scene_tris.saturating_sub(smooth_tris.len()));
9939            }
9940            if raster_tris_scratch.capacity() < max_scene_tris {
9941                raster_tris_scratch
9942                    .reserve(max_scene_tris.saturating_sub(raster_tris_scratch.len()));
9943            }
9944            if projected_verts_scratch.capacity() < max_mesh_verts {
9945                projected_verts_scratch
9946                    .reserve(max_mesh_verts.saturating_sub(projected_verts_scratch.len()));
9947            }
9948            if cluster_ranges_scratch.capacity() < max_mesh_clusters {
9949                cluster_ranges_scratch
9950                    .reserve(max_mesh_clusters.saturating_sub(cluster_ranges_scratch.len()));
9951            }
9952            if geom_chunks_scratch.len() != GEOM_PARALLEL_CHUNKS {
9953                geom_chunks_scratch.resize_with(GEOM_PARALLEL_CHUNKS, GeomChunkScratch::default);
9954            }
9955            for chunk_buf in geom_chunks_scratch.iter_mut() {
9956                if chunk_buf.shaded_tris.capacity() < chunk_tri_cap {
9957                    chunk_buf
9958                        .shaded_tris
9959                        .reserve(chunk_tri_cap.saturating_sub(chunk_buf.shaded_tris.len()));
9960                }
9961                if chunk_buf.smooth_tris.capacity() < chunk_tri_cap {
9962                    chunk_buf
9963                        .smooth_tris
9964                        .reserve(chunk_tri_cap.saturating_sub(chunk_buf.smooth_tris.len()));
9965                }
9966                if chunk_buf.raster_tris.capacity() < chunk_tri_cap {
9967                    chunk_buf
9968                        .raster_tris
9969                        .reserve(chunk_tri_cap.saturating_sub(chunk_buf.raster_tris.len()));
9970                }
9971                if chunk_buf.projected_verts.capacity() < max_mesh_verts {
9972                    chunk_buf
9973                        .projected_verts
9974                        .reserve(max_mesh_verts.saturating_sub(chunk_buf.projected_verts.len()));
9975                }
9976                if chunk_buf.cluster_ranges.capacity() < max_mesh_clusters {
9977                    chunk_buf
9978                        .cluster_ranges
9979                        .reserve(max_mesh_clusters.saturating_sub(chunk_buf.cluster_ranges.len()));
9980                }
9981                if chunk_buf.mesh_ids.capacity() < obj_cap {
9982                    chunk_buf
9983                        .mesh_ids
9984                        .reserve(obj_cap.saturating_sub(chunk_buf.mesh_ids.len()));
9985                }
9986            }
9987            *reserved_object_cap = obj_cap;
9988            *reserved_mesh_cap = mesh_cap;
9989        }
9990        visible_scratch.clear();
9991        unique_meshes_scratch.clear();
9992        if tile_counts_scratch.capacity() < total_tiles {
9993            tile_counts_scratch.reserve(total_tiles.saturating_sub(tile_counts_scratch.len()));
9994        }
9995        if tile_offsets_scratch.capacity() < total_tiles + 1 {
9996            tile_offsets_scratch
9997                .reserve((total_tiles + 1).saturating_sub(tile_offsets_scratch.len()));
9998        }
9999        if tile_cursors_scratch.capacity() < total_tiles {
10000            tile_cursors_scratch.reserve(total_tiles.saturating_sub(tile_cursors_scratch.len()));
10001        }
10002        let min_tile_indices: usize = total_tiles
10003            .saturating_mul(256)
10004            .max(shaded_tris.capacity().saturating_mul(8));
10005        if tile_tri_indices_scratch.capacity() < min_tile_indices {
10006            tile_tri_indices_scratch
10007                .reserve(min_tile_indices.saturating_sub(tile_tri_indices_scratch.len()));
10008        }
10009        for (obj_idx, obj) in objects.iter().enumerate() {
10010            if !world.is_object_visible(obj_idx) {
10011                culled_objects += 1;
10012                continue;
10013            }
10014            let bounds: AxisAlignedBox3D = obj.get_world_bounds();
10015            let dist_sq: f32 = bounds.center().sub(cam_pos).length_sq();
10016            if chunk_on {
10017                let bmin: Vec3 = bounds.get_min();
10018                let bmax: Vec3 = bounds.get_max();
10019                let cx: f32 = cam_pos.get_x().clamp(bmin.get_x(), bmax.get_x());
10020                let cy: f32 = cam_pos.get_y().clamp(bmin.get_y(), bmax.get_y());
10021                let cz: f32 = cam_pos.get_z().clamp(bmin.get_z(), bmax.get_z());
10022                let closest_dist_sq: f32 = Vec3::new(cx, cy, cz).sub(cam_pos).length_sq();
10023                if closest_dist_sq > draw_dist_sq {
10024                    culled_objects += 1;
10025                    continue;
10026                }
10027            }
10028            if frustum_on && !frustum.intersects_bounds(&bounds) {
10029                culled_objects += 1;
10030                continue;
10031            }
10032            visible_scratch.push((dist_sq, obj_idx));
10033        }
10034        visible_scratch.sort_unstable_by(|alpha_val: &(f32, usize), blue_val: &(f32, usize)| {
10035            alpha_val
10036                .0
10037                .total_cmp(&blue_val.0)
10038                .then_with(|| alpha_val.1.cmp(&blue_val.1))
10039        });
10040        shaded_tris.clear();
10041        smooth_tris.clear();
10042        raster_tris_scratch.clear();
10043        let near_plane: f32 = cam.get_near().max(0.15);
10044        let w_f: f32 = span_width as f32;
10045        let h_f: f32 = span_height as f32;
10046        let w_max_i: i32 = (span_width as i32) - 1;
10047        let h_max_i: i32 = (span_height as i32) - 1;
10048        let hiz_active: bool =
10049            quality.get_occlusion_culling() && objects.len() >= 220 && visible_scratch.len() >= 64;
10050        if hiz_active {
10051            hiz_pyramid.ensure_dimensions(w_usize, h_usize);
10052            hiz_pyramid.clear_for_prepass();
10053            hiz_occluder_flags_scratch.clear();
10054            hiz_occluder_flags_scratch.resize(visible_scratch.len(), 0);
10055            let mut stamped_occluders: usize = 0;
10056            let mut stamped_tris: usize = 0;
10057            for (vis_slot, &(dist_sq, obj_idx)) in visible_scratch.iter().enumerate() {
10058                if stamped_occluders >= HIZ_MAX_PREPASS_OCCLUDERS
10059                    || stamped_tris >= HIZ_MAX_OCCLUDER_TRIS
10060                {
10061                    break;
10062                }
10063                if dist_sq < 16.0 {
10064                    continue;
10065                }
10066                let obj: &SceneObject3D = &objects[obj_idx];
10067                if !obj.get_ray_trace_caster() || obj.get_world_bounds().radius() < 4.0 {
10068                    continue;
10069                }
10070                let Some(chain) = mesh_lib.get(obj.get_mesh_id()) else {
10071                    continue;
10072                };
10073                let Some(mesh) = chain.get_levels().first() else {
10074                    continue;
10075                };
10076                let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
10077                let invalid_occ: bool = !mesh.get_is_closed() || indices.is_empty();
10078                if invalid_occ || indices.len() > 24 {
10079                    continue;
10080                }
10081                let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
10082                let mvp_occ: Mat4 = matrix_value.mul(obj.get_transform().to_mat4());
10083                projected_verts_scratch.clear();
10084                projected_verts_scratch.reserve(verts.len());
10085                for item_val in verts.iter() {
10086                    let cp: [f32; 4] = mvp_occ.mul_point4(item_val.get_position());
10087                    projected_verts_scratch.push((cp, Vec3::zero()));
10088                }
10089                let vlen: usize = projected_verts_scratch.len();
10090                for tri in indices.iter() {
10091                    let (i0, i1, i2): (usize, usize, usize) =
10092                        (tri[0] as usize, tri[1] as usize, tri[2] as usize);
10093                    let out_01: bool = i0 >= vlen || i1 >= vlen;
10094                    if out_01 || i2 >= vlen {
10095                        continue;
10096                    }
10097                    let c0: [f32; 4] = projected_verts_scratch[i0].0;
10098                    let c1: [f32; 4] = projected_verts_scratch[i1].0;
10099                    let c2: [f32; 4] = projected_verts_scratch[i2].0;
10100                    let clipped_01: bool = c0[3] < near_plane || c1[3] < near_plane;
10101                    if clipped_01 || c2[3] < near_plane {
10102                        continue;
10103                    }
10104                    let iw0: f32 = 1.0 / c0[3];
10105                    let iw1: f32 = 1.0 / c1[3];
10106                    let iw2: f32 = 1.0 / c2[3];
10107                    let sx0: f32 = (c0[0] * iw0 * 0.5 + 0.5) * w_f;
10108                    let sy0: f32 = (0.5 - c0[1] * iw0 * 0.5) * h_f;
10109                    let sx1: f32 = (c1[0] * iw1 * 0.5 + 0.5) * w_f;
10110                    let sy1: f32 = (0.5 - c1[1] * iw1 * 0.5) * h_f;
10111                    let sx2: f32 = (c2[0] * iw2 * 0.5 + 0.5) * w_f;
10112                    let sy2: f32 = (0.5 - c2[1] * iw2 * 0.5) * h_f;
10113                    hiz_pyramid.stamp_occluder_triangle_conservative(
10114                        [sx0, sx1, sx2],
10115                        [sy0, sy1, sy2],
10116                        [iw0, iw1, iw2],
10117                    );
10118                    stamped_tris += 1;
10119                }
10120                hiz_occluder_flags_scratch[vis_slot] = 1;
10121                stamped_occluders += 1;
10122            }
10123            hiz_pyramid.rebuild_mips();
10124        }
10125        let geom_ctx: GeomPassContext<'_> = GeomPassContext {
10126            objects,
10127            mesh_lib,
10128            deformed_meshes: deformed_meshes_slice,
10129            principled_materials: principled_mats_slice,
10130            nanite_dags: nanite_dags_cache.as_slice(),
10131            hiz_pyramid: &*hiz_pyramid,
10132            hiz_occluder_flags: hiz_occluder_flags_scratch.as_slice(),
10133            frustum,
10134            view_proj: matrix_value,
10135            cam_pos,
10136            sun_dir,
10137            sky_horizon,
10138            sky_zenith,
10139            focal_px,
10140            lod_bias,
10141            near_plane,
10142            w_f,
10143            h_f,
10144            w_max_i,
10145            h_max_i,
10146            jitter_x,
10147            jitter_y,
10148            frustum_on,
10149            hiz_active,
10150            use_rt_refl,
10151            use_agx_tonemap,
10152        };
10153        let vis_len: usize = visible_scratch.len();
10154        if vis_len >= GEOM_PARALLEL_MIN_OBJECTS {
10155            if geom_chunks_scratch.len() != GEOM_PARALLEL_CHUNKS {
10156                geom_chunks_scratch.resize_with(GEOM_PARALLEL_CHUNKS, || GeomChunkScratch {
10157                    shaded_tris: Vec::with_capacity(512),
10158                    smooth_tris: Vec::with_capacity(512),
10159                    raster_tris: Vec::with_capacity(512),
10160                    mesh_ids: Vec::with_capacity(64),
10161                    projected_verts: Vec::with_capacity(512),
10162                    cluster_ranges: Vec::with_capacity(64),
10163                    visible_objects: 0,
10164                    hiz_culled_objects: 0,
10165                    lod_simplified_objects: 0,
10166                    meshlets_drawn: 0,
10167                    meshlets_culled: 0,
10168                });
10169            }
10170            let vis_slice: &[(f32, usize)] = visible_scratch.as_slice();
10171            let chunks_base: usize = geom_chunks_scratch.as_mut_ptr() as usize;
10172            parallel_for_ranges(GEOM_PARALLEL_CHUNKS, 1, |c0: usize, c1: usize| {
10173                for ci in c0..c1 {
10174                    // SAFETY: `parallel_for_ranges` partitions `0..GEOM_PARALLEL_CHUNKS` into strictly disjoint indices.
10175                    let chunk: &mut GeomChunkScratch =
10176                        unsafe { &mut *(chunks_base as *mut GeomChunkScratch).add(ci) };
10177                    chunk.shaded_tris.clear();
10178                    chunk.smooth_tris.clear();
10179                    chunk.raster_tris.clear();
10180                    chunk.mesh_ids.clear();
10181                    chunk.visible_objects = 0;
10182                    chunk.hiz_culled_objects = 0;
10183                    chunk.lod_simplified_objects = 0;
10184                    chunk.meshlets_drawn = 0;
10185                    chunk.meshlets_culled = 0;
10186                    let mut out_view: GeomPassOut<'_> = GeomPassOut {
10187                        shaded_tris: &mut chunk.shaded_tris,
10188                        smooth_tris: &mut chunk.smooth_tris,
10189                        raster_tris: &mut chunk.raster_tris,
10190                        projected_verts: &mut chunk.projected_verts,
10191                        cluster_ranges: &mut chunk.cluster_ranges,
10192                        mesh_ids: Some(&mut chunk.mesh_ids),
10193                        unique_meshes: None,
10194                        visible_objects: 0,
10195                        hiz_culled_objects: 0,
10196                        lod_simplified_objects: 0,
10197                        meshlets_drawn: 0,
10198                        meshlets_culled: 0,
10199                    };
10200                    let vis_start: usize = (ci * vis_len) / GEOM_PARALLEL_CHUNKS;
10201                    let vis_end: usize = ((ci + 1) * vis_len) / GEOM_PARALLEL_CHUNKS;
10202                    for (offset, &(dist_sq, obj_idx)) in
10203                        vis_slice[vis_start..vis_end].iter().enumerate()
10204                    {
10205                        let vis_slot: usize = vis_start + offset;
10206                        Self::process_visible_object_geom(
10207                            &geom_ctx,
10208                            vis_slot,
10209                            dist_sq,
10210                            obj_idx,
10211                            &mut out_view,
10212                        );
10213                    }
10214                    chunk.visible_objects = out_view.visible_objects;
10215                    chunk.hiz_culled_objects = out_view.hiz_culled_objects;
10216                    chunk.lod_simplified_objects = out_view.lod_simplified_objects;
10217                    chunk.meshlets_drawn = out_view.meshlets_drawn;
10218                    chunk.meshlets_culled = out_view.meshlets_culled;
10219                }
10220            });
10221            let mut total_chunk_tris: usize = 0;
10222            let mut total_chunk_smooth: usize = 0;
10223            for chunk in geom_chunks_scratch.iter() {
10224                total_chunk_tris += chunk.shaded_tris.len();
10225                total_chunk_smooth += chunk.smooth_tris.len();
10226            }
10227            if shaded_tris.capacity() < total_chunk_tris {
10228                shaded_tris.reserve(total_chunk_tris - shaded_tris.capacity());
10229            }
10230            if smooth_tris.capacity() < total_chunk_smooth {
10231                smooth_tris.reserve(total_chunk_smooth - smooth_tris.capacity());
10232            }
10233            if raster_tris_scratch.capacity() < total_chunk_tris {
10234                raster_tris_scratch.reserve(total_chunk_tris - raster_tris_scratch.capacity());
10235            }
10236            for chunk in geom_chunks_scratch.iter() {
10237                let base_tri_id: u32 = shaded_tris.len() as u32;
10238                let base_smooth_id: u32 = smooth_tris.len() as u32;
10239                smooth_tris.extend_from_slice(chunk.smooth_tris.as_slice());
10240                for &shaded_rec in chunk.shaded_tris.iter() {
10241                    let mut shifted_tri: GShadeTri = shaded_rec;
10242                    if shifted_tri.smooth_idx != u32::MAX {
10243                        shifted_tri.smooth_idx += base_smooth_id;
10244                    }
10245                    shaded_tris.push(shifted_tri);
10246                }
10247                for &rt in chunk.raster_tris.iter() {
10248                    let mut shifted: RasterTri2D = rt;
10249                    shifted.tri_id += base_tri_id;
10250                    raster_tris_scratch.push(shifted);
10251                }
10252                visible_objects += chunk.visible_objects;
10253                hiz_culled_objects += chunk.hiz_culled_objects;
10254                culled_objects += chunk.hiz_culled_objects;
10255                lod_simplified_objects += chunk.lod_simplified_objects;
10256                meshlets_drawn += chunk.meshlets_drawn;
10257                meshlets_culled += chunk.meshlets_culled;
10258                for &mesh_id in chunk.mesh_ids.iter() {
10259                    let _: bool = unique_meshes_scratch.insert(mesh_id);
10260                }
10261            }
10262        } else {
10263            let mut seq_out: GeomPassOut<'_> = GeomPassOut {
10264                shaded_tris,
10265                smooth_tris,
10266                raster_tris: raster_tris_scratch,
10267                projected_verts: projected_verts_scratch,
10268                cluster_ranges: cluster_ranges_scratch,
10269                mesh_ids: None,
10270                unique_meshes: Some(unique_meshes_scratch),
10271                visible_objects: 0,
10272                hiz_culled_objects: 0,
10273                lod_simplified_objects: 0,
10274                meshlets_drawn: 0,
10275                meshlets_culled: 0,
10276            };
10277            for (vis_slot, &(dist_sq, obj_idx)) in visible_scratch.iter().enumerate() {
10278                Self::process_visible_object_geom(
10279                    &geom_ctx,
10280                    vis_slot,
10281                    dist_sq,
10282                    obj_idx,
10283                    &mut seq_out,
10284                );
10285            }
10286            visible_objects += seq_out.visible_objects;
10287            hiz_culled_objects += seq_out.hiz_culled_objects;
10288            culled_objects += seq_out.hiz_culled_objects;
10289            lod_simplified_objects += seq_out.lod_simplified_objects;
10290            meshlets_drawn += seq_out.meshlets_drawn;
10291            meshlets_culled += seq_out.meshlets_culled;
10292        }
10293        let triangles_drawn: usize = shaded_tris.len();
10294        tile_counts_scratch.clear();
10295        tile_counts_scratch.resize(total_tiles, 0);
10296        let tile_px_i: i32 = tile_px as i32;
10297        let tiles_x_max: usize = tiles_x.saturating_sub(1);
10298        let tiles_y_max: usize = tiles_y.saturating_sub(1);
10299        for tri in raster_tris_scratch.iter() {
10300            let tx0: usize = (tri.min_x / tile_px_i) as usize;
10301            let tx1: usize = (((tri.min_x + tri.span_max) / tile_px_i) as usize).min(tiles_x_max);
10302            let ty0: usize = (tri.min_y / tile_px_i) as usize;
10303            let ty1: usize = ((tri.max_y / tile_px_i) as usize).min(tiles_y_max);
10304            for ty in ty0..=ty1 {
10305                let row_t: usize = ty * tiles_x;
10306                for tx in tx0..=tx1 {
10307                    tile_counts_scratch[row_t + tx] += 1;
10308                }
10309            }
10310        }
10311        tile_offsets_scratch.clear();
10312        tile_offsets_scratch.reserve(total_tiles + 1);
10313        let mut prefix_sum: u32 = 0;
10314        tile_offsets_scratch.push(0);
10315        for &cnt in tile_counts_scratch.iter() {
10316            prefix_sum += cnt;
10317            tile_offsets_scratch.push(prefix_sum);
10318        }
10319        tile_cursors_scratch.clear();
10320        tile_cursors_scratch.extend_from_slice(&tile_offsets_scratch[..total_tiles]);
10321        tile_tri_indices_scratch.resize(prefix_sum as usize, 0);
10322        for (slot, tri) in raster_tris_scratch.iter().enumerate() {
10323            let slot_u32: u32 = slot as u32;
10324            let tx0: usize = (tri.min_x / tile_px_i) as usize;
10325            let tx1: usize = (((tri.min_x + tri.span_max) / tile_px_i) as usize).min(tiles_x_max);
10326            let ty0: usize = (tri.min_y / tile_px_i) as usize;
10327            let ty1: usize = ((tri.max_y / tile_px_i) as usize).min(tiles_y_max);
10328            for ty in ty0..=ty1 {
10329                let row_t: usize = ty * tiles_x;
10330                for tx in tx0..=tx1 {
10331                    let t_idx: usize = row_t + tx;
10332                    let dst_pos: usize = tile_cursors_scratch[t_idx] as usize;
10333                    tile_cursors_scratch[t_idx] = (dst_pos as u32) + 1;
10334                    tile_tri_indices_scratch[dst_pos] = slot_u32;
10335                }
10336            }
10337        }
10338        let bloom_on: bool = matches!(
10339            quality.get_preset(),
10340            QualityPreset::High | QualityPreset::Ultra | QualityPreset::Cinematic
10341        );
10342        if bloom_on {
10343            let bloom_cells: usize = border_width * bh;
10344            if bloom_a.len() != bloom_cells {
10345                bloom_a.resize(bloom_cells, [0.0; 4]);
10346                bloom_b.resize(bloom_cells, [0.0; 4]);
10347                bloom_tile_active.resize(bloom_cells, 0);
10348            }
10349        }
10350        let sun_inv_dir: Vec3 = Ray3D::safe_inv_vec(sun_dir);
10351        let soft_shadow_rays: [(Vec3, Vec3); 16] = if rt_mode == RayTracingMode::FullPathTracedGi {
10352            let sun_t1: Vec3 = sun_dir.cross(Vec3::new(0.0, 1.0, 0.0)).normalize();
10353            let sun_t2: Vec3 = sun_dir.cross(sun_t1).normalize();
10354            let mut table: [(Vec3, Vec3); 16] = [(sun_dir, sun_inv_dir); 16];
10355            for (slot, &(ox, oy)) in table.iter_mut().zip(SOFT_SHADOW_RING_16.iter()) {
10356                let jittered: Vec3 = sun_dir
10357                    .add(sun_t1.scale(ox))
10358                    .add(sun_t2.scale(oy))
10359                    .normalize();
10360                *slot = (jittered, Ray3D::safe_inv_vec(jittered));
10361            }
10362            table
10363        } else {
10364            [(sun_dir, sun_inv_dir); 16]
10365        };
10366        let frame_context: DeferredFrameContext = DeferredFrameContext {
10367            width: w_usize,
10368            height: h_usize,
10369            grid_width: gw,
10370            grid_height: gh,
10371            bloom_width: border_width,
10372            raytrace_step: rt_step,
10373            inv_width: 1.0 / (span_width as f32).max(1.0),
10374            inv_height: 1.0 / (span_height as f32).max(1.0),
10375            camera_position: cam_pos,
10376            camera_forward: cam_fwd,
10377            camera_right_scaled: cam_right.scale(half_w),
10378            camera_up_scaled: cam_up.scale(half_h),
10379            sun,
10380            inv_sun_dir: sun_inv_dir,
10381            soft_shadow_rays,
10382            frame_index: cur_frame_idx,
10383            raytrace_mode: rt_mode,
10384            reflection_bounces: quality.get_reflection_bounces(),
10385            fog_on: quality.get_volumetric_fog(),
10386            inv_fog_distance: 0.92 / quality.get_draw_distance().max(40.0),
10387            exposure_scale: *adapted_exposure,
10388            bloom_on,
10389            has_clustered_lights: active_local_lights > 0,
10390            probe_frame_generation: PROBE_SCRATCH_FRAME_GEN.fetch_add(1, Ordering::Relaxed),
10391            world_time_secs: world.get_world_time_secs(),
10392        };
10393        let vp_m0: f32 = matrix_value.get_elements()[0]
10394            + matrix_value.get_elements()[12] * 0.01
10395            + matrix_value.get_elements()[14] * 0.01;
10396        let cam_stable: bool = (*prev_vp_m0 - vp_m0).abs() < 0.35;
10397        let sun_stable: bool = prev_sun_dir.dot(sun_dir) > 0.9999;
10398        let probe_hist_valid: bool = *has_probe_history
10399            && *has_prev_vp
10400            && rt_step > 0
10401            && *prev_probe_rt_mode == rt_mode
10402            && sun_stable;
10403        if rt_step > 0 {
10404            rt_probes.resize(gw * gh);
10405            prev_rt_probes.resize(gw * gh);
10406        }
10407        let use_lumen_cache: bool = quality.get_lumen_radiance_cache()
10408            && rt_step > 0
10409            && rt_mode == RayTracingMode::FullPathTracedGi;
10410        if use_lumen_cache && !sun_stable {
10411            lumen_cache.invalidate();
10412        }
10413        let rays_atom: AtomicUsize = AtomicUsize::new(0);
10414        let reproj_hits_atom: AtomicUsize = AtomicUsize::new(0);
10415        {
10416            let prev_probes_ref: Option<&RtProbeGridSoa> = if probe_hist_valid {
10417                Some(&*prev_rt_probes)
10418            } else {
10419                None
10420            };
10421            let lumen_ref: Option<&LumenRadianceCache> =
10422                if use_lumen_cache && lumen_cache.get_active_cells() > 0 {
10423                    Some(&*lumen_cache)
10424                } else {
10425                    None
10426                };
10427            let clusters_ref: Option<&LightClusterGrid3D> = if active_local_lights > 0 {
10428                Some(&*light_clusters)
10429            } else {
10430                None
10431            };
10432            let vsm_ref: Option<&VirtualShadowMap> = if use_vsm {
10433                Some(&*virtual_shadow_map)
10434            } else {
10435                None
10436            };
10437            let same_camera_pose: bool = probe_hist_valid
10438                && *prev_render_dims == (w_usize, h_usize)
10439                && *prev_rt_step == rt_step
10440                && *prev_probe_gw == gw
10441                && *prev_probe_gh == gh
10442                && prev_view_proj.get_elements() == matrix_value.get_elements();
10443            let tile_inputs: TileRasterProbeInputs<'_> = TileRasterProbeInputs {
10444                raster_tris: raster_tris_scratch.as_slice(),
10445                tile_offsets: tile_offsets_scratch.as_slice(),
10446                tile_tri_indices: tile_tri_indices_scratch.as_slice(),
10447                shaded_tris: shaded_tris.as_slice(),
10448                static_bvh,
10449                dyn_instances,
10450                local_bvhs,
10451                prev_probes: prev_probes_ref,
10452                prev_view_proj: *prev_view_proj,
10453                prev_render_dims: *prev_render_dims,
10454                prev_rt_step: *prev_rt_step,
10455                prev_gw: *prev_probe_gw,
10456                prev_gh: *prev_probe_gh,
10457                lumen_cache: lumen_ref,
10458                light_clusters: clusters_ref,
10459                vsm: vsm_ref,
10460                use_vsm_far_shadows: use_vsm,
10461                probe_checker_parity: cur_frame_idx & 1,
10462                same_camera_pose,
10463                tile_px,
10464                tiles_x,
10465                sky_lut: sky_lut.as_slice(),
10466            };
10467            let depth_base: usize = depth_buffer.as_mut_ptr() as usize;
10468            let gtri_base: usize = g_tri_idx.as_mut_ptr() as usize;
10469            let probe_ptrs: RtProbeGridMutPtrs = rt_probes.mut_ptrs();
10470            let tile_grain: usize = 1;
10471            parallel_for_ranges(total_tiles, tile_grain, |t0: usize, t1: usize| {
10472                // SAFETY: `parallel_for_ranges` partitions `0..total_tiles` into strictly disjoint screen tiles and probe blocks.
10473                let (red_val, hit_val): (usize, usize) = unsafe {
10474                    Self::raster_and_trace_tiles(
10475                        &frame_context,
10476                        &tile_inputs,
10477                        t0,
10478                        t1,
10479                        (depth_base, gtri_base, probe_ptrs),
10480                    )
10481                };
10482                if red_val > 0 {
10483                    let _: usize = rays_atom.fetch_add(red_val, Ordering::Relaxed);
10484                }
10485                if hit_val > 0 {
10486                    let _: usize = reproj_hits_atom.fetch_add(hit_val, Ordering::Relaxed);
10487                }
10488            });
10489        }
10490        if use_lumen_cache {
10491            lumen_cache.begin_frame(sun_dir);
10492            let total_probes: usize = gw * gh;
10493            let probe_stride: usize = (total_probes / 384).max(1).next_power_of_two();
10494            let mut p_cursor: usize = cur_frame_idx & (probe_stride - 1);
10495            while p_cursor < total_probes {
10496                if rt_probes.valid[p_cursor] != 0 {
10497                    lumen_cache.accumulate_sample(
10498                        Vec3::new(
10499                            rt_probes.world_x[p_cursor],
10500                            rt_probes.world_y[p_cursor],
10501                            rt_probes.world_z[p_cursor],
10502                        ),
10503                        Vec3::new(
10504                            rt_probes.nx[p_cursor],
10505                            rt_probes.ny[p_cursor],
10506                            rt_probes.nz[p_cursor],
10507                        ),
10508                        cam_pos,
10509                        Vec3::new(
10510                            rt_probes.gi_r[p_cursor],
10511                            rt_probes.gi_g[p_cursor],
10512                            rt_probes.gi_b[p_cursor],
10513                        ),
10514                        rt_probes.ao[p_cursor],
10515                        rt_probes.shadow[p_cursor],
10516                    );
10517                }
10518                p_cursor += probe_stride;
10519            }
10520        }
10521        let lumen_cache_cells: usize = lumen_cache.get_active_cells();
10522        let probe_reproj_hits: usize = reproj_hits_atom.load(Ordering::Relaxed);
10523        let denoise_probes: bool = rt_step > 0
10524            && matches!(
10525                rt_mode,
10526                RayTracingMode::ShadowsAndReflections | RayTracingMode::FullPathTracedGi
10527            );
10528        if denoise_probes && gw > PROBE_ROW_STACK_CAP {
10529            Self::denoise_wide_grid(rt_probes, gw, gh, rt_probes_wide_denoised);
10530        }
10531        let bloom_any_atom: AtomicUsize = AtomicUsize::new(0);
10532        let bloom_row_bits: [AtomicU64; 9] = [const { AtomicU64::new(0) }; 9];
10533        {
10534            let clusters_shade_ref: Option<&LightClusterGrid3D> = if active_local_lights > 0 {
10535                Some(&*light_clusters)
10536            } else {
10537                None
10538            };
10539            let vsm_shade_ref: Option<&VirtualShadowMap> = if use_vsm {
10540                Some(&*virtual_shadow_map)
10541            } else {
10542                None
10543            };
10544            let shade_inputs: ShadeBandInputs<'_> = ShadeBandInputs {
10545                depth_buf: depth_buffer.as_slice(),
10546                g_tri_idx: g_tri_idx.as_slice(),
10547                shaded_tris: shaded_tris.as_slice(),
10548                smooth_tris: smooth_tris.as_slice(),
10549                principled_materials: principled_mats_slice,
10550                textures: textures_slice,
10551                area_lights: area_lights_slice,
10552                light_clusters: clusters_shade_ref,
10553                vsm: vsm_shade_ref,
10554                environment_ibl: environment_ibl_ref,
10555                use_agx_tonemap,
10556                raw_probes: rt_probes,
10557                wide_denoised_probes: rt_probes_wide_denoised,
10558                denoise_probes,
10559                denoise_gi_channels: rt_mode == RayTracingMode::FullPathTracedGi,
10560                static_bvh,
10561                dyn_instances,
10562                local_bvhs,
10563                bloom_row_bits: &bloom_row_bits,
10564                sky_lut: sky_lut.as_slice(),
10565                aces_lut: aces_lut.as_slice(),
10566            };
10567            let color_base: usize = color_buffer.as_mut_ptr() as usize;
10568            let luma_base: usize = luma_buffer.as_mut_ptr() as usize;
10569            let bloom_base: usize = bloom_a.as_mut_ptr() as usize;
10570            let bloom_total_len: usize = bloom_a.len();
10571            let shade_grain: usize = 4;
10572            parallel_for_ranges(h_usize, shade_grain, |y0: usize, y1: usize| {
10573                let rows: usize = y1 - y0;
10574                // SAFETY: `shade_grain` is a multiple of 4 and `parallel_for_ranges` yields disjoint row bands.
10575                let c_band: &mut [u8] = unsafe {
10576                    from_raw_parts_mut(
10577                        (color_base as *mut u8).add(y0 * w_usize * 4),
10578                        rows * w_usize * 4,
10579                    )
10580                };
10581                // SAFETY: Disjoint luma row band for `[y0, y1)`.
10582                let l_band: &mut [u8] = unsafe {
10583                    from_raw_parts_mut((luma_base as *mut u8).add(y0 * w_usize), rows * w_usize)
10584                };
10585                let b_start: usize = (y0 / 4) * border_width;
10586                let b_end: usize = ((y1.div_ceil(4)) * border_width).min(bloom_total_len);
10587                let b_band: &mut [[f32; 4]] = if b_start < b_end {
10588                    // SAFETY: Since `y0` and non-final `y1` are multiples of 4, `[b_start, b_end)` ranges are disjoint.
10589                    unsafe {
10590                        from_raw_parts_mut(
10591                            (bloom_base as *mut [f32; 4]).add(b_start),
10592                            b_end - b_start,
10593                        )
10594                    }
10595                } else {
10596                    &mut []
10597                };
10598                let (radius_val, has_bloom_band): (usize, bool) = Self::shade_deferred_band(
10599                    &frame_context,
10600                    &shade_inputs,
10601                    (y0, c_band, l_band, b_band),
10602                );
10603                if radius_val > 0 {
10604                    let _: usize = rays_atom.fetch_add(radius_val, Ordering::Relaxed);
10605                }
10606                if has_bloom_band {
10607                    bloom_any_atom.store(1, Ordering::Relaxed);
10608                }
10609            });
10610        }
10611        let rays_traced: usize = rays_atom.load(Ordering::Relaxed);
10612        let luma_len: usize = luma_buffer.len();
10613        if luma_len >= 64 {
10614            let sample_stride: usize = (luma_len / 1024).max(1);
10615            let mut luma_sum: u32 = 0;
10616            let mut sample_cnt: u32 = 0;
10617            let mut sample_idx: usize = sample_stride >> 1;
10618            while sample_idx < luma_len {
10619                luma_sum += luma_buffer[sample_idx] as u32;
10620                sample_cnt += 1;
10621                sample_idx += sample_stride;
10622            }
10623            if sample_cnt > 0 {
10624                let avg_luma: f32 = ((luma_sum as f32) / ((sample_cnt as f32) * 255.0)).max(0.06);
10625                let desired_exp: f32 = ((*adapted_exposure)
10626                    * (AUTO_EXPOSURE_TARGET_LUMA / avg_luma))
10627                    .clamp(AUTO_EXPOSURE_MIN, AUTO_EXPOSURE_MAX);
10628                let exp_delta: f32 = desired_exp - *adapted_exposure;
10629                if exp_delta.abs() > 0.015 {
10630                    *adapted_exposure += exp_delta * AUTO_EXPOSURE_ADAPT_RATE;
10631                }
10632            }
10633        }
10634        let particles_drawn: usize = if world.get_niagara().get_active_count() > 0 {
10635            world.get_niagara().composite_depth_tested(
10636                &matrix_value,
10637                focal_px,
10638                (w_usize, h_usize),
10639                depth_buffer.as_slice(),
10640                color_buffer.as_mut_slice(),
10641            )
10642        } else {
10643            0
10644        };
10645        let bloom_effective: bool = if bloom_on && bloom_any_atom.load(Ordering::Relaxed) != 0 {
10646            let mut row_bits_snap: [u64; 9] = [0; 9];
10647            for (dst, src_atom) in row_bits_snap.iter_mut().zip(bloom_row_bits.iter()) {
10648                *dst = src_atom.load(Ordering::Relaxed);
10649            }
10650            Self::blur_bloom_and_mask(
10651                border_width,
10652                bh,
10653                bloom_a.as_mut_slice(),
10654                bloom_b.as_mut_slice(),
10655                bloom_tile_active.as_mut_slice(),
10656                &row_bits_snap,
10657            )
10658        } else {
10659            false
10660        };
10661        let byte_len: usize = pixel_count * 4;
10662        if aa_mode == AntiAliasingMode::Tsr {
10663            let tsr_params: TsrFrameParams = TsrFrameParams {
10664                src_width: w_usize,
10665                src_height: h_usize,
10666                dst_width: w_usize,
10667                dst_height: h_usize,
10668                camera_position: cam_pos,
10669                camera_forward: cam_fwd,
10670                camera_right_scaled: cam_right.scale(half_w),
10671                camera_up_scaled: cam_up.scale(half_h),
10672                view_projection: matrix_value,
10673                jitter_offset: (jitter_x, jitter_y),
10674                sharpness: TSR_DEFAULT_SHARPNESS,
10675            };
10676            if bloom_effective {
10677                tsr_internal_scratch.clear();
10678                if tsr_internal_scratch.capacity() < byte_len {
10679                    tsr_internal_scratch.reserve_exact(byte_len);
10680                }
10681                let post_inputs: PostProcessInputs<'_> = PostProcessInputs {
10682                    color_src: color_buffer.as_slice(),
10683                    luma: luma_buffer.as_slice(),
10684                    g_tri_idx: g_tri_idx.as_slice(),
10685                    bloom: bloom_a.as_slice(),
10686                    bloom_tile_active: bloom_tile_active.as_slice(),
10687                    taa_history: aa_buffer.as_slice(),
10688                };
10689                let tmp_base: usize = tsr_internal_scratch.as_mut_ptr() as usize;
10690                let post_grain: usize = 8;
10691                parallel_for_ranges(h_usize, post_grain, |y0: usize, y1: usize| {
10692                    // SAFETY: `tsr_internal_scratch` has capacity `>= byte_len` and row ranges are disjoint.
10693                    unsafe {
10694                        let band_ptr: *mut u8 = (tmp_base as *mut u8).add(y0 * w_usize * 4);
10695                        Self::post_process_band(
10696                            (w_usize, h_usize, border_width, bh),
10697                            &post_inputs,
10698                            (false, false, true),
10699                            (y0, band_ptr, y1 - y0),
10700                        );
10701                    }
10702                });
10703                // SAFETY: `parallel_for_ranges` initialized every byte in `0..byte_len`.
10704                unsafe {
10705                    tsr_internal_scratch.set_len(byte_len);
10706                }
10707                tsr_upscaler.upscale_rgba(
10708                    tsr_internal_scratch.as_slice(),
10709                    depth_buffer.as_slice(),
10710                    &tsr_params,
10711                    out_pixels,
10712                );
10713            } else {
10714                tsr_upscaler.upscale_rgba(
10715                    color_buffer.as_slice(),
10716                    depth_buffer.as_slice(),
10717                    &tsr_params,
10718                    out_pixels,
10719                );
10720            }
10721        } else {
10722            let use_fxaa: bool = aa_mode != AntiAliasingMode::Off;
10723            let use_taa: bool = aa_mode == AntiAliasingMode::Taa && *has_taa_history && cam_stable;
10724            out_pixels.clear();
10725            if out_pixels.capacity() < byte_len {
10726                out_pixels.reserve_exact(byte_len);
10727            }
10728            {
10729                let post_inputs: PostProcessInputs<'_> = PostProcessInputs {
10730                    color_src: color_buffer.as_slice(),
10731                    luma: luma_buffer.as_slice(),
10732                    g_tri_idx: g_tri_idx.as_slice(),
10733                    bloom: bloom_a.as_slice(),
10734                    bloom_tile_active: bloom_tile_active.as_slice(),
10735                    taa_history: aa_buffer.as_slice(),
10736                };
10737                let out_base: usize = out_pixels.as_mut_ptr() as usize;
10738                let post_grain: usize = 8;
10739                parallel_for_ranges(h_usize, post_grain, |y0: usize, y1: usize| {
10740                    // SAFETY: `out_pixels` has capacity `>= byte_len`, `parallel_for_ranges` partitions `0..h_usize`
10741                    // into disjoint row ranges, and `post_process_band` writes all `(y1 - y0) * w_usize * 4` bytes.
10742                    unsafe {
10743                        let band_ptr: *mut u8 = (out_base as *mut u8).add(y0 * w_usize * 4);
10744                        Self::post_process_band(
10745                            (w_usize, h_usize, border_width, bh),
10746                            &post_inputs,
10747                            (use_fxaa, use_taa, bloom_effective),
10748                            (y0, band_ptr, y1 - y0),
10749                        );
10750                    }
10751                });
10752            }
10753            // SAFETY: `parallel_for_ranges` has joined and initialized every byte in `0..byte_len`.
10754            unsafe {
10755                out_pixels.set_len(byte_len);
10756            }
10757        }
10758        if rt_step > 0 {
10759            swap(rt_probes, prev_rt_probes);
10760            *has_probe_history = true;
10761            *prev_probe_gw = gw;
10762            *prev_probe_gh = gh;
10763            *prev_probe_rt_mode = rt_mode;
10764            *prev_sun_dir = sun_dir;
10765        } else {
10766            *has_probe_history = false;
10767        }
10768        *prev_vp_m0 = vp_m0;
10769        *prev_view_proj = matrix_value;
10770        *has_prev_vp = true;
10771        *prev_render_dims = (w_usize, h_usize);
10772        *prev_rt_step = rt_step;
10773        if aa_mode == AntiAliasingMode::Taa {
10774            if aa_buffer.len() != byte_len {
10775                aa_buffer.resize(byte_len, 0);
10776            }
10777            swap(aa_buffer, color_buffer);
10778            *has_taa_history = true;
10779        } else {
10780            *has_taa_history = false;
10781        }
10782        let instanced_batches: usize = if quality.get_gpu_instancing() {
10783            unique_meshes_scratch.len()
10784        } else {
10785            visible_objects
10786        };
10787        let stats: RenderStats3D = RenderStats3D {
10788            render_width: span_width,
10789            render_height: span_height,
10790            visible_objects,
10791            culled_objects,
10792            instanced_batches,
10793            triangles_drawn,
10794            rays_traced,
10795            bvh_nodes: total_bvh_nodes,
10796            lod_simplified_objects,
10797            meshlets_drawn,
10798            meshlets_culled,
10799            hiz_culled_objects,
10800            lumen_cache_cells,
10801            active_local_lights,
10802            particles_drawn,
10803            probe_reproj_hits,
10804        };
10805        let same_world_and_cfg: bool = self.get_last_world_revision() == world_rev && {
10806            let Self {
10807                last_quality_fingerprint,
10808                ..
10809            } = self;
10810            *last_quality_fingerprint == quality_fp
10811        };
10812        let next_taa_count: u32 =
10813            if matches!(aa_mode, AntiAliasingMode::Taa | AntiAliasingMode::Tsr) {
10814                if same_world_and_cfg {
10815                    self.get_taa_accumulated_frames().saturating_add(1).min(8)
10816                } else {
10817                    1
10818                }
10819            } else {
10820                0
10821            };
10822        self.set_taa_accumulated_frames(next_taa_count);
10823        self.set_last_world_revision(world_rev);
10824        let Self {
10825            last_quality_fingerprint,
10826            ..
10827        } = self;
10828        *last_quality_fingerprint = quality_fp;
10829        self.set_last_stats(stats);
10830        (span_width, span_height)
10831    }
10832
10833    /// Computes a stable configuration fingerprint covering viewport dimensions and visual quality knobs.
10834    ///
10835    /// # Arguments
10836    ///
10837    /// - `u32` - Target viewport width.
10838    /// - `u32` - Target viewport height.
10839    /// - `&RenderQualityConfig` - Active quality settings.
10840    ///
10841    /// # Returns
10842    ///
10843    /// - `u64` - Combined configuration fingerprint.
10844    #[must_use]
10845    fn quality_fingerprint(viewport_w: u32, viewport_h: u32, quality: &RenderQualityConfig) -> u64 {
10846        let mut height_val: u64 = 0xCBF2_9CE4_8422_2325;
10847        let parts: [u64; 8] = [
10848            viewport_w as u64,
10849            viewport_h as u64,
10850            quality.get_resolution_scale().to_bits() as u64,
10851            quality.get_draw_distance().to_bits() as u64,
10852            quality.get_lod_bias().to_bits() as u64,
10853            quality.get_reflection_bounces() as u64,
10854            (quality.get_ray_tracing() as u64)
10855                | ((quality.get_anti_aliasing() as u64) << 8)
10856                | ((quality.get_preset() as u64) << 16)
10857                | ((quality.get_upscaler() as u64) << 24),
10858            u64::from(quality.get_volumetric_fog())
10859                | (u64::from(quality.get_frustum_culling()) << 1)
10860                | (u64::from(quality.get_chunk_streaming()) << 2)
10861                | (u64::from(quality.get_occlusion_culling()) << 3)
10862                | (u64::from(quality.get_virtual_shadow_maps()) << 4)
10863                | (u64::from(quality.get_clustered_lighting()) << 5)
10864                | (u64::from(quality.get_lumen_radiance_cache()) << 6),
10865        ];
10866        for point_val in parts.into_iter() {
10867            height_val ^= point_val;
10868            height_val = height_val.wrapping_mul(0x0100_0000_01B3);
10869        }
10870        height_val
10871    }
10872
10873    /// Attaches a shared-device GPU 3D render target texture handle for zero-readback single-pass UI+3D compositing.
10874    ///
10875    /// # Arguments
10876    ///
10877    /// - `&Self` - Mutable 3D renderer.
10878    /// - `GpuTextureHandle` - Shared-device GPU texture backing the 3D render target.
10879    /// - `Rect` - Viewport rectangle in logical UI pixels.
10880    pub fn attach_gpu_target(&mut self, handle: GpuTextureHandle, rect: Rect) {
10881        let Self { gpu_target, .. } = self;
10882        gpu_target.attach_handle(handle, rect);
10883    }
10884
10885    /// Prepares a `GpuCompositeDescriptor` referencing the attached shared-device GPU 3D render target for single-pass UI+3D compositing.
10886    ///
10887    /// # Arguments
10888    ///
10889    /// - `&Self` - Mutable 3D renderer.
10890    /// - `u64` - Monotonic compositor frame index.
10891    ///
10892    /// # Returns
10893    ///
10894    /// - `Option<GpuCompositeDescriptor>` - Single-pass composite descriptor when a GPU target is attached.
10895    #[must_use]
10896    pub fn prepare_gpu_composite_descriptor(
10897        &mut self,
10898        frame_index: u64,
10899    ) -> Option<GpuCompositeDescriptor> {
10900        let Self { gpu_target, .. } = self;
10901        gpu_target.record_composite_present(frame_index)
10902    }
10903
10904    /// Explicitly resets temporal anti-aliasing history on camera cuts or world teleports without touching unrelated HUD state.
10905    ///
10906    /// # Arguments
10907    ///
10908    /// - `&Self` - Mutable 3D renderer.
10909    pub fn invalidate_taa_history(&mut self) {
10910        let Self {
10911            has_taa_history,
10912            has_probe_history,
10913            has_prev_vp,
10914            tsr_upscaler,
10915            lumen_cache,
10916            adapted_exposure,
10917            ..
10918        } = self;
10919        *has_taa_history = false;
10920        *has_probe_history = false;
10921        *has_prev_vp = false;
10922        *adapted_exposure = 1.0;
10923        tsr_upscaler.invalidate_history();
10924        lumen_cache.invalidate();
10925        self.set_taa_accumulated_frames(0);
10926    }
10927
10928    /// Returns `true` when the cached 3D framebuffer can be reused across a HUD-only dirty frame without re-running 3D rasterization or starving TAA accumulation.
10929    ///
10930    /// # Arguments
10931    ///
10932    /// - `&Self` - 3D renderer reference.
10933    /// - `&World3D` - Active 3D world.
10934    /// - `u32` - Viewport width in pixels.
10935    /// - `u32` - Viewport height in pixels.
10936    /// - `&RenderQualityConfig` - Active quality settings.
10937    ///
10938    /// # Returns
10939    ///
10940    /// - `bool` - `true` when the cached 3D frame is valid and TAA accumulation does not require another sample.
10941    #[must_use]
10942    pub fn can_reuse_cached_world(
10943        &self,
10944        world: &World3D,
10945        viewport_w: u32,
10946        viewport_h: u32,
10947        quality: &RenderQualityConfig,
10948    ) -> bool {
10949        let Self {
10950            rgba_scratch,
10951            last_quality_fingerprint,
10952            ..
10953        } = self;
10954        if rgba_scratch.is_empty() {
10955            return false;
10956        }
10957        let fp: u64 = Self::quality_fingerprint(viewport_w, viewport_h, quality);
10958        if self.get_last_world_revision() != world.get_world_revision()
10959            || *last_quality_fingerprint != fp
10960        {
10961            return false;
10962        }
10963        if matches!(
10964            quality.get_anti_aliasing(),
10965            AntiAliasingMode::Taa | AntiAliasingMode::Tsr
10966        ) {
10967            self.get_taa_accumulated_frames() >= 8
10968        } else {
10969            true
10970        }
10971    }
10972
10973    /// Renders `world` into `rgba_scratch` only when 3D state changed or TAA needs another temporal sample, otherwise reusing the cached 3D buffer across HUD-only dirty updates.
10974    ///
10975    /// # Arguments
10976    ///
10977    /// - `&Self` - Mutable 3D renderer.
10978    /// - `&mut World3D` - Open-world 3D scene graph.
10979    /// - `u32` - Target viewport width in logical pixels.
10980    /// - `u32` - Target viewport height in logical pixels.
10981    /// - `&RenderQualityConfig` - Runtime quality settings.
10982    ///
10983    /// # Returns
10984    ///
10985    /// - `(&[u8], bool)` - Borrowed RGBA8 pixel slice and `true` if satisfied from cache without re-rasterization.
10986    #[must_use]
10987    pub fn render_world_or_reuse_cached(
10988        &mut self,
10989        world: &mut World3D,
10990        viewport_w: u32,
10991        viewport_h: u32,
10992        quality: &RenderQualityConfig,
10993    ) -> (&[u8], bool) {
10994        if self.can_reuse_cached_world(world, viewport_w, viewport_h, quality) {
10995            let next_reuses: u64 = self.get_cached_world_reuses().saturating_add(1);
10996            self.set_cached_world_reuses(next_reuses);
10997            let Self { rgba_scratch, .. } = self;
10998            return (rgba_scratch.as_slice(), true);
10999        }
11000        let pixels: &[u8] = self.render_world_rgba(world, viewport_w, viewport_h, quality);
11001        (pixels, false)
11002    }
11003
11004    /// Renders `world` directly into a bounded zero-allocation `RenderBufferPool` slot tagged with `fence_id`.
11005    ///
11006    /// # Arguments
11007    ///
11008    /// - `&Self` - Mutable 3D renderer.
11009    /// - `&mut World3D` - Open-world 3D scene graph.
11010    /// - `u32` - Target viewport width in logical pixels.
11011    /// - `u32` - Target viewport height in logical pixels.
11012    /// - `&RenderQualityConfig` - Runtime quality settings.
11013    /// - `&RenderBufferPool` - Bounded CPU output buffer pool.
11014    /// - `u64` - Submission fence value guarding reclamation.
11015    ///
11016    /// # Returns
11017    ///
11018    /// - `Option<PooledFrameLease>` - Populated pooled RGBA8 lease, or `None` if all bounded pool slots are in flight.
11019    #[must_use]
11020    pub fn render_world_into_pool(
11021        &mut self,
11022        world: &mut World3D,
11023        viewport_w: u32,
11024        viewport_h: u32,
11025        quality: &RenderQualityConfig,
11026        pool: &RenderBufferPool,
11027        fence_id: u64,
11028    ) -> Option<PooledFrameLease> {
11029        let scale: f32 = quality.get_resolution_scale().clamp(0.40, 4.0);
11030        let min_width: u32 = viewport_w.clamp(1, 240);
11031        let min_height: u32 = viewport_h.clamp(1, 144);
11032        let width_val: u32 = ((viewport_w as f32 * scale).round() as u32).max(min_width);
11033        let height_val: u32 = ((viewport_h as f32 * scale).round() as u32).max(min_height);
11034        let mut lease: PooledFrameLease = pool.acquire(width_val, height_val, fence_id)?;
11035        let (rw, rh): (u32, u32) = self.render_world_into_vec(
11036            world,
11037            viewport_w,
11038            viewport_h,
11039            quality,
11040            lease.get_mut_pixels(),
11041        );
11042        lease.set_dimensions(rw, rh);
11043        Some(lease)
11044    }
11045
11046    /// Renders `world` using a discontinuity-safe interpolated `World3DSnapshot` sampled at `alpha` with object-space inverse-interpolated dynamic RT (zero `dynamic_bvh` rebuilds per VSync).
11047    ///
11048    /// # Arguments
11049    ///
11050    /// - `&Self` - Mutable 3D renderer.
11051    /// - `&mut World3D` - 3D world holding shared mesh library, lighting, and BVH acceleration structures.
11052    /// - `&DoubleBufferedSnapshot<World3DSnapshot>` - Immutable `(prev_state, curr_state)` snapshot buffer.
11053    /// - `f32` - Normalized interpolation alpha in `[0.0, 1.0]`.
11054    /// - `(u32, u32)` - Target viewport `(width, height)` in logical pixels.
11055    /// - `&RenderQualityConfig` - Runtime quality settings.
11056    /// - `(&RenderBufferPool, u64)` - Bounded CPU output buffer pool and submission fence value.
11057    ///
11058    /// # Returns
11059    ///
11060    /// - `Option<PooledFrameLease>` - Rendered interpolated frame lease, or `None` under pool backpressure.
11061    #[must_use]
11062    pub fn render_world_interpolated_into_pool(
11063        &mut self,
11064        world: &mut World3D,
11065        snapshots: &DoubleBufferedSnapshot<World3DSnapshot>,
11066        alpha: f32,
11067        viewport: (u32, u32),
11068        quality: &RenderQualityConfig,
11069        target_pool: (&RenderBufferPool, u64),
11070    ) -> Option<PooledFrameLease> {
11071        let (viewport_w, viewport_h): (u32, u32) = viewport;
11072        let (pool, fence_id): (&RenderBufferPool, u64) = target_pool;
11073        if quality.get_ray_tracing() != RayTracingMode::Off
11074            && (world.get_bvh_dirty() || world.get_dynamic_bvh_dirty())
11075        {
11076            world.ensure_bvh();
11077        }
11078        let entry_index: f32 = alpha.clamp(0.0, 1.0);
11079        let prev_snap: &World3DSnapshot = snapshots.get_prev_state();
11080        let curr_snap: &World3DSnapshot = snapshots.get_curr_state();
11081        let cam_cut: bool = curr_snap.get_camera_cut();
11082        if cam_cut {
11083            self.invalidate_taa_history();
11084        }
11085        let interp_cam: Camera3D = if cam_cut {
11086            curr_snap.get_camera()
11087        } else {
11088            prev_snap
11089                .get_camera()
11090                .lerp(curr_snap.get_camera(), entry_index)
11091        };
11092        let saved_cam: Camera3D = world.get_camera();
11093        let mut saved_objs: Vec<(usize, Transform3D, AxisAlignedBox3D)> = {
11094            let Self {
11095                saved_objs_scratch, ..
11096            } = self;
11097            take(saved_objs_scratch)
11098        };
11099        saved_objs.clear();
11100        world.set_camera(interp_cam);
11101        let prev_objs: &[ObjectPose3D] = prev_snap.get_objects().as_slice();
11102        let next_objs: &[ObjectPose3D] = curr_snap.get_objects().as_slice();
11103        if saved_objs.capacity() < next_objs.len() {
11104            saved_objs.reserve(next_objs.len());
11105        }
11106        for (slot_idx, curr) in next_objs.iter().copied().enumerate() {
11107            let obj_idx: usize = curr.get_object_index();
11108            let mut blended_tr: Transform3D = curr.get_transform();
11109            if curr.get_visible()
11110                && let Some(prev) = prev_objs.get(slot_idx).copied()
11111            {
11112                let continuous: bool = prev.get_visible()
11113                    && prev.get_object_index() == obj_idx
11114                    && prev.get_teleport_epoch() == curr.get_teleport_epoch();
11115                if continuous {
11116                    blended_tr = prev
11117                        .get_transform()
11118                        .lerp_shortest_angle(curr.get_transform(), entry_index);
11119                }
11120            }
11121            let Some((orig_tr, orig_wb, mesh_id, is_dyn)) =
11122                world
11123                    .get_objects()
11124                    .get(obj_idx)
11125                    .map(|output_val: &SceneObject3D| {
11126                        (
11127                            output_val.get_transform(),
11128                            output_val.get_world_bounds(),
11129                            output_val.get_mesh_id(),
11130                            output_val.get_is_dynamic(),
11131                        )
11132                    })
11133            else {
11134                continue;
11135            };
11136            if orig_tr == blended_tr {
11137                continue;
11138            }
11139            saved_objs.push((obj_idx, orig_tr, orig_wb));
11140            let local_bounds: AxisAlignedBox3D = world
11141                .get_mesh_library()
11142                .get(mesh_id)
11143                .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
11144                .map(Mesh3D::get_bounds)
11145                .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
11146            let world_b: AxisAlignedBox3D = blended_tr.transform_bounds(local_bounds);
11147            if let Some(obj_mut) = world.get_mut_objects().get_mut(obj_idx) {
11148                obj_mut.set_transform(blended_tr);
11149                obj_mut.set_world_bounds(world_b);
11150            }
11151            if is_dyn {
11152                world.override_dynamic_instance_pose(obj_idx, blended_tr, world_b);
11153            }
11154        }
11155        let result: Option<PooledFrameLease> =
11156            self.render_world_into_pool(world, viewport_w, viewport_h, quality, pool, fence_id);
11157        world.set_camera(saved_cam);
11158        for &(idx, transform_val, wb) in saved_objs.iter() {
11159            let is_dyn: bool = world
11160                .get_objects()
11161                .get(idx)
11162                .is_some_and(SceneObject3D::get_is_dynamic);
11163            if let Some(obj_mut) = world.get_mut_objects().get_mut(idx) {
11164                obj_mut.set_transform(transform_val);
11165                obj_mut.set_world_bounds(wb);
11166            }
11167            if is_dyn {
11168                world.override_dynamic_instance_pose(idx, transform_val, wb);
11169            }
11170        }
11171        saved_objs.clear();
11172        let Self {
11173            saved_objs_scratch, ..
11174        } = self;
11175        *saved_objs_scratch = saved_objs;
11176        result
11177    }
11178
11179    /// Renders `world` at runtime-configured `quality` into an `ImageBuffer` without zero-filling output memory.
11180    ///
11181    /// # Arguments
11182    ///
11183    /// - `&Self` - Mutable 3D renderer.
11184    /// - `&mut World3D` - Open-world 3D scene graph.
11185    /// - `u32` - Target viewport width in logical pixels.
11186    /// - `u32` - Target viewport height in logical pixels.
11187    /// - `&RenderQualityConfig` - Live runtime quality, resolution scale, LOD, and ray-tracing settings.
11188    ///
11189    /// # Returns
11190    ///
11191    /// - `ImageBuffer` - Ready RGBA8 rendered 3D frame for immediate presentation.
11192    pub fn render_world(
11193        &mut self,
11194        world: &mut World3D,
11195        viewport_w: u32,
11196        viewport_h: u32,
11197        quality: &RenderQualityConfig,
11198    ) -> ImageBuffer {
11199        let mut out_pixels: Vec<u8> = Vec::new();
11200        let (width_val, height_val): (u32, u32) =
11201            self.render_world_into_vec(world, viewport_w, viewport_h, quality, &mut out_pixels);
11202        ImageBuffer::new(width_val, height_val, out_pixels)
11203    }
11204
11205    /// Renders `world` into the persistent internal `rgba_scratch` buffer, eliminating per-frame output heap allocations.
11206    ///
11207    /// # Arguments
11208    ///
11209    /// - `&Self` - Mutable 3D renderer.
11210    /// - `&mut World3D` - Open-world 3D scene graph.
11211    /// - `u32` - Target viewport width in logical pixels.
11212    /// - `u32` - Target viewport height in logical pixels.
11213    /// - `&RenderQualityConfig` - Live runtime quality, resolution scale, LOD, and ray-tracing settings.
11214    ///
11215    /// # Returns
11216    ///
11217    /// - `&[u8]` - Borrowed RGBA8 pixel slice of the rendered 3D frame.
11218    #[must_use]
11219    pub fn render_world_rgba(
11220        &mut self,
11221        world: &mut World3D,
11222        viewport_w: u32,
11223        viewport_h: u32,
11224        quality: &RenderQualityConfig,
11225    ) -> &[u8] {
11226        let mut scratch: Vec<u8> = {
11227            let Self { rgba_scratch, .. } = self;
11228            take(rgba_scratch)
11229        };
11230        let _: (u32, u32) =
11231            self.render_world_into_vec(world, viewport_w, viewport_h, quality, &mut scratch);
11232        let Self { rgba_scratch, .. } = self;
11233        *rgba_scratch = scratch;
11234        rgba_scratch.as_slice()
11235    }
11236
11237    /// Renders `world` at sub-native resolution and reconstructs a sharp native `(viewport_w, viewport_h)` frame via UE5 Temporal Super Resolution (TSR).
11238    ///
11239    /// # Arguments
11240    ///
11241    /// - `&mut World3D` - Open-world 3D scene graph.
11242    /// - `u32` - Target native output width in pixels.
11243    /// - `u32` - Target native output height in pixels.
11244    /// - `&RenderQualityConfig` - Runtime quality settings supplying internal `resolution_scale`.
11245    /// - `&mut Vec<u8>` - Reusable full-resolution destination RGBA8 buffer.
11246    ///
11247    /// # Returns
11248    ///
11249    /// - `(u32, u32)` - Actual reconstructed output dimensions `(dst_w, dst_h)`.
11250    pub fn render_world_tsr_into_vec(
11251        &mut self,
11252        world: &mut World3D,
11253        viewport_w: u32,
11254        viewport_h: u32,
11255        quality: &RenderQualityConfig,
11256        out_pixels: &mut Vec<u8>,
11257    ) -> (u32, u32) {
11258        let dst_w: u32 = viewport_w.max(1);
11259        let dst_h: u32 = viewport_h.max(1);
11260        let mut internal_quality: RenderQualityConfig = *quality;
11261        internal_quality.set_anti_aliasing(AntiAliasingMode::Off);
11262        let mut internal_buf: Vec<u8> = {
11263            let Self {
11264                tsr_internal_scratch,
11265                ..
11266            } = self;
11267            take(tsr_internal_scratch)
11268        };
11269        let (src_w, src_h): (u32, u32) =
11270            self.render_world_into_vec(world, dst_w, dst_h, &internal_quality, &mut internal_buf);
11271        let cam: Camera3D = world.get_camera();
11272        let aspect: f32 = (src_w as f32) / (src_h as f32).max(1.0);
11273        let view_proj: Mat4 = cam.view_projection(aspect);
11274        let cam_fwd: Vec3 = cam.forward();
11275        let cam_right: Vec3 = cam.right();
11276        let cam_up: Vec3 = cam_right.cross(cam_fwd).normalize();
11277        let eff_fov_rad: f32 = Camera3D::effective_vertical_fov_rad(cam.get_fov_deg(), aspect);
11278        let half_h: f32 = (eff_fov_rad * 0.5).tan();
11279        let half_w: f32 = half_h * aspect;
11280        let tsr_params: TsrFrameParams = TsrFrameParams {
11281            src_width: src_w as usize,
11282            src_height: src_h as usize,
11283            dst_width: dst_w as usize,
11284            dst_height: dst_h as usize,
11285            camera_position: cam.get_position(),
11286            camera_forward: cam_fwd,
11287            camera_right_scaled: cam_right.scale(half_w),
11288            camera_up_scaled: cam_up.scale(half_h),
11289            view_projection: view_proj,
11290            jitter_offset: (0.0, 0.0),
11291            sharpness: TSR_DEFAULT_SHARPNESS,
11292        };
11293        {
11294            let Self {
11295                depth_buffer,
11296                tsr_upscaler,
11297                ..
11298            } = self;
11299            tsr_upscaler.upscale_rgba(
11300                internal_buf.as_slice(),
11301                depth_buffer.as_slice(),
11302                &tsr_params,
11303                out_pixels,
11304            );
11305        }
11306        let Self {
11307            tsr_internal_scratch,
11308            ..
11309        } = self;
11310        *tsr_internal_scratch = internal_buf;
11311        (dst_w, dst_h)
11312    }
11313
11314    /// Renders `world` using UE5 Temporal Super Resolution (TSR) upscaling and returns a full-resolution `ImageBuffer`.
11315    ///
11316    /// # Arguments
11317    ///
11318    /// - `&mut World3D` - Open-world 3D scene graph.
11319    /// - `u32` - Target native output width in pixels.
11320    /// - `u32` - Target native output height in pixels.
11321    /// - `&RenderQualityConfig` - Runtime quality settings supplying internal scale and RT/Lumen toggles.
11322    ///
11323    /// # Returns
11324    ///
11325    /// - `ImageBuffer` - Reconstructed native-resolution RGBA8 frame.
11326    pub fn render_world_tsr(
11327        &mut self,
11328        world: &mut World3D,
11329        viewport_w: u32,
11330        viewport_h: u32,
11331        quality: &RenderQualityConfig,
11332    ) -> ImageBuffer {
11333        let mut out_pixels: Vec<u8> = Vec::new();
11334        let (dst_w, dst_h): (u32, u32) =
11335            self.render_world_tsr_into_vec(world, viewport_w, viewport_h, quality, &mut out_pixels);
11336        ImageBuffer::new(dst_w, dst_h, out_pixels)
11337    }
11338
11339    /// Renders `world` at sub-native resolution and writes the TSR-reconstructed native frame directly into a bounded zero-allocation `RenderBufferPool` slot.
11340    ///
11341    /// # Arguments
11342    ///
11343    /// - `&mut World3D` - Open-world 3D scene graph.
11344    /// - `(u32, u32)` - Target native output `(viewport_w, viewport_h)` in pixels.
11345    /// - `&RenderQualityConfig` - Runtime quality configuration controlling internal TSR scale.
11346    /// - `(&RenderBufferPool, u64)` - Bounded output frame pool and fence value.
11347    ///
11348    /// # Returns
11349    ///
11350    /// - `Option<PooledFrameLease>` - Populated native-resolution TSR frame lease, or `None` under pool backpressure.
11351    #[must_use]
11352    pub fn render_world_tsr_into_pool(
11353        &mut self,
11354        world: &mut World3D,
11355        viewport: (u32, u32),
11356        quality: &RenderQualityConfig,
11357        target_pool: (&RenderBufferPool, u64),
11358    ) -> Option<PooledFrameLease> {
11359        let (viewport_w, viewport_h): (u32, u32) = viewport;
11360        let (pool, fence_id): (&RenderBufferPool, u64) = target_pool;
11361        let dst_w: u32 = viewport_w.max(1);
11362        let dst_h: u32 = viewport_h.max(1);
11363        let mut lease: PooledFrameLease = pool.acquire(dst_w, dst_h, fence_id)?;
11364        let (rw, rh): (u32, u32) =
11365            self.render_world_tsr_into_vec(world, dst_w, dst_h, quality, lease.get_mut_pixels());
11366        lease.set_dimensions(rw, rh);
11367        Some(lease)
11368    }
11369
11370    /// Feeds measured `frame_ms` into the damped PI `AdaptiveFrameGovernor` and applies smooth DRS scale, LOD bias, and RT probe stride adjustments to `quality` without FPS oscillation.
11371    ///
11372    /// # Arguments
11373    ///
11374    /// - `f32` - Measured render duration of the most recent frame in milliseconds.
11375    /// - `&mut RenderQualityConfig` - Mutable runtime quality settings updated when `dynamic_resolution` is enabled.
11376    ///
11377    /// # Returns
11378    ///
11379    /// - `FramePacingTelemetry3D` - Updated smoothed frame-time and stability telemetry.
11380    pub fn apply_frame_pacing_feedback(
11381        &mut self,
11382        frame_ms: f32,
11383        quality: &mut RenderQualityConfig,
11384    ) -> FramePacingTelemetry3D {
11385        let target_hz: f32 = quality.get_target_fps().max(30.0);
11386        let governor: &mut AdaptiveFrameGovernor = self.get_mut_frame_governor();
11387        if (governor.get_target_hz() - target_hz).abs() > 0.5 {
11388            governor.set_target_hz(target_hz);
11389        }
11390        let telemetry: FramePacingTelemetry3D = governor.record_frame(frame_ms, quality);
11391        if quality.get_dynamic_resolution() {
11392            self.set_rt_stride_bias(telemetry.get_effective_rt_stride_bias());
11393        } else {
11394            self.set_rt_stride_bias(0);
11395        }
11396        telemetry
11397    }
11398
11399    /// Builds and compiles the UE5 Render Dependency Graph (RDG) for `(viewport_w, viewport_h)` and `quality`, reporting dead-pass culling and transient memory aliasing savings.
11400    ///
11401    /// # Arguments
11402    ///
11403    /// - `u32` - Target viewport width in pixels.
11404    /// - `u32` - Target viewport height in pixels.
11405    /// - `&RenderQualityConfig` - Active quality configuration controlling RT, Lumen, VSM, and TSR passes.
11406    ///
11407    /// # Returns
11408    ///
11409    /// - `RenderGraphSchedule3D` - Compiled pass schedule with transient memory aliasing telemetry.
11410    #[must_use]
11411    pub fn compile_frame_graph(
11412        &mut self,
11413        viewport_w: u32,
11414        viewport_h: u32,
11415        quality: &RenderQualityConfig,
11416    ) -> RenderGraphSchedule3D {
11417        let built: RenderGraph3D =
11418            RenderGraph3D::build_ue5_frame_graph(viewport_w, viewport_h, quality);
11419        let schedule: RenderGraphSchedule3D = built.compile();
11420        self.set_render_graph(built);
11421        schedule
11422    }
11423
11424    /// Clips a triangle against the camera near plane `w >= near_w` (Sutherland-Hodgman) while tracking original barycentric weights for exact attribute interpolation.
11425    ///
11426    /// # Arguments
11427    ///
11428    /// - `([f32; 4], Vec3)` - First clip-space and world-space vertex.
11429    /// - `([f32; 4], Vec3)` - Second clip-space and world-space vertex.
11430    /// - `([f32; 4], Vec3)` - Third clip-space and world-space vertex.
11431    /// - `f32` - Positive near-plane clip `w` threshold.
11432    ///
11433    /// # Returns
11434    ///
11435    /// - `([ClippedBaryVert; 6], usize)` - Packed output triangles with barycentric weights and valid triangle count (`0..=2`).
11436    #[must_use]
11437    fn clip_triangle_near_bary(
11438        vert0: ([f32; 4], Vec3),
11439        vert1: ([f32; 4], Vec3),
11440        vert2: ([f32; 4], Vec3),
11441        near_w: f32,
11442    ) -> ([ClippedBaryVert; 6], usize) {
11443        let zero_vert: ClippedBaryVert = ClippedBaryVert {
11444            clip_pos: [0.0; 4],
11445            world_pos: Vec3::zero(),
11446            bary: [0.0; 3],
11447        };
11448        let mut out_tris: [ClippedBaryVert; 6] = [zero_vert; 6];
11449        let input: [ClippedBaryVert; 3] = [
11450            ClippedBaryVert {
11451                clip_pos: vert0.0,
11452                world_pos: vert0.1,
11453                bary: [1.0, 0.0, 0.0],
11454            },
11455            ClippedBaryVert {
11456                clip_pos: vert1.0,
11457                world_pos: vert1.1,
11458                bary: [0.0, 1.0, 0.0],
11459            },
11460            ClippedBaryVert {
11461                clip_pos: vert2.0,
11462                world_pos: vert2.1,
11463                bary: [0.0, 0.0, 1.0],
11464            },
11465        ];
11466        let mut poly: [ClippedBaryVert; 4] = [zero_vert; 4];
11467        let mut count: usize = 0;
11468        for edge_idx in 0..3usize {
11469            let cur: ClippedBaryVert = input[edge_idx];
11470            let nxt: ClippedBaryVert = input[(edge_idx + 1) % 3];
11471            let cur_in: bool = cur.clip_pos[3] >= near_w;
11472            let nxt_in: bool = nxt.clip_pos[3] >= near_w;
11473            if cur_in && count < 4 {
11474                poly[count] = cur;
11475                count += 1;
11476            }
11477            if cur_in != nxt_in && count < 4 {
11478                let denom: f32 = nxt.clip_pos[3] - cur.clip_pos[3];
11479                let blend_factor: f32 = if denom.abs() > 1.0e-6 {
11480                    ((near_w - cur.clip_pos[3]) / denom).clamp(0.0, 1.0)
11481                } else {
11482                    0.5
11483                };
11484                let interp_clip: [f32; 4] = [
11485                    cur.clip_pos[0] + (nxt.clip_pos[0] - cur.clip_pos[0]) * blend_factor,
11486                    cur.clip_pos[1] + (nxt.clip_pos[1] - cur.clip_pos[1]) * blend_factor,
11487                    cur.clip_pos[2] + (nxt.clip_pos[2] - cur.clip_pos[2]) * blend_factor,
11488                    near_w,
11489                ];
11490                let interp_world: Vec3 = cur.world_pos.lerp(nxt.world_pos, blend_factor);
11491                let interp_bary: [f32; 3] = [
11492                    cur.bary[0] + (nxt.bary[0] - cur.bary[0]) * blend_factor,
11493                    cur.bary[1] + (nxt.bary[1] - cur.bary[1]) * blend_factor,
11494                    cur.bary[2] + (nxt.bary[2] - cur.bary[2]) * blend_factor,
11495                ];
11496                poly[count] = ClippedBaryVert {
11497                    clip_pos: interp_clip,
11498                    world_pos: interp_world,
11499                    bary: interp_bary,
11500                };
11501                count += 1;
11502            }
11503        }
11504        if count < 3 {
11505            return (out_tris, 0);
11506        }
11507        out_tris[0] = poly[0];
11508        out_tris[1] = poly[1];
11509        out_tris[2] = poly[2];
11510        if count == 4 {
11511            out_tris[3] = poly[0];
11512            out_tris[4] = poly[2];
11513            out_tris[5] = poly[3];
11514            (out_tris, 2)
11515        } else {
11516            (out_tris, 1)
11517        }
11518    }
11519
11520    /// Samples an optional `TextureSlot3D` with `KHR_texture_transform` and isotropic trilinear mip selection.
11521    ///
11522    /// # Arguments
11523    ///
11524    /// - `Option<TextureSlot3D>` - Optional texture binding slot.
11525    /// - `([f32; 2], [f32; 2])` - Interpolated `(uv0, uv1)` coordinates.
11526    /// - `(f32, f32, f32)` - `(uv0_area, uv1_area, screen_area_px)` for mip LOD estimation.
11527    /// - `&[Texture2D3D]` - Scene texture pool.
11528    ///
11529    /// # Returns
11530    ///
11531    /// - `Option<[f32; 4]>` - Linear RGBA sample when the slot references a valid texture.
11532    #[must_use]
11533    fn sample_principled_slot(
11534        slot_opt: Option<TextureSlot3D>,
11535        uv_pair: ([f32; 2], [f32; 2]),
11536        area_terms: (f32, f32, f32),
11537        textures: &[Texture2D3D],
11538    ) -> Option<[f32; 4]> {
11539        let slot: TextureSlot3D = slot_opt?;
11540        let texture: &Texture2D3D = textures.get(slot.get_texture_index() as usize)?;
11541        let (uv0_coord, uv1_coord): ([f32; 2], [f32; 2]) = uv_pair;
11542        let (uv0_area, uv1_area, screen_area): (f32, f32, f32) = area_terms;
11543        let (raw_uv, uv_area): ([f32; 2], f32) = if slot.get_tex_coord() == 1 {
11544            (uv1_coord, uv1_area)
11545        } else {
11546            (uv0_coord, uv0_area)
11547        };
11548        let transformed_uv: Vec2 = slot
11549            .get_transform()
11550            .apply_uv(Vec2::new(raw_uv[0], raw_uv[1]));
11551        let tex_scale: Vec2 = slot.get_transform().get_scale();
11552        let scale_area: f32 = (tex_scale.get_x() * tex_scale.get_y()).abs().max(1.0e-4);
11553        let tex_pixels: f32 =
11554            (texture.get_width().max(1) as f32) * (texture.get_height().max(1) as f32);
11555        let texels_per_px: f32 = (uv_area * scale_area * tex_pixels) / screen_area.max(1.0);
11556        let mip_lod: f32 = if texels_per_px > 1.0 {
11557            0.5 * texels_per_px.log2()
11558        } else {
11559            0.0
11560        };
11561        Some(texture.sample_trilinear(transformed_uv.get_x(), transformed_uv.get_y(), mip_lod))
11562    }
11563
11564    /// Evaluates the Estevez-Kulla Charlie sheen microfacet NDF and Ashikhmin visibility term.
11565    ///
11566    /// # Arguments
11567    ///
11568    /// - `f32` - Perceptual sheen roughness in `[0.07, 1.0]`.
11569    /// - `f32` - Clamped `N·H` cosine.
11570    /// - `f32` - Clamped `N·V` cosine.
11571    /// - `f32` - Clamped `N·L` cosine.
11572    ///
11573    /// # Returns
11574    ///
11575    /// - `f32` - Scalar Charlie sheen BRDF factor.
11576    #[cfg_attr(not(target_arch = "wasm32"), inline)]
11577    #[must_use]
11578    fn eval_charlie_sheen(sheen_rough: f32, n_dot_h: f32, n_dot_v: f32, n_dot_l: f32) -> f32 {
11579        let clamped_r: f32 = sheen_rough.clamp(0.07, 1.0);
11580        let alpha_g: f32 = clamped_r * clamped_r;
11581        let inv_r: f32 = 1.0 / alpha_g.max(1.0e-4);
11582        let sin2_h: f32 = (1.0 - n_dot_h * n_dot_h).max(1.0e-4);
11583        let ndf_charlie: f32 = (2.0 + inv_r) * sin2_h.powf(inv_r * 0.5) / (2.0 * PI);
11584        let vis_ashikhmin: f32 = 1.0 / (4.0 * (n_dot_l + n_dot_v - n_dot_l * n_dot_v)).max(1.0e-3);
11585        (ndf_charlie * vis_ashikhmin).min(8.0)
11586    }
11587
11588    /// Computes Snell refraction direction for unit incident vector `incident` and outward unit `normal` at IOR ratio `eta`.
11589    ///
11590    /// # Arguments
11591    ///
11592    /// - `Vec3` - Unit incident vector pointing toward surface (`-view_dir`).
11593    /// - `Vec3` - Unit outward surface normal.
11594    /// - `f32` - Refractive index ratio `eta_i / eta_t`.
11595    ///
11596    /// # Returns
11597    ///
11598    /// - `Vec3` - Unit refracted direction (falls back to reflection on total internal reflection).
11599    #[cfg_attr(not(target_arch = "wasm32"), inline)]
11600    #[must_use]
11601    fn refract_unit_ray(incident: Vec3, normal: Vec3, eta: f32) -> Vec3 {
11602        let cos_i: f32 = (-incident.dot(normal)).clamp(-1.0, 1.0);
11603        let sin2_t: f32 = eta * eta * (1.0 - cos_i * cos_i).max(0.0);
11604        if sin2_t >= 1.0 {
11605            return incident.reflect(normal).normalize();
11606        }
11607        let cos_t: f32 = (1.0 - sin2_t).sqrt();
11608        incident
11609            .scale(eta)
11610            .add(normal.scale(eta * cos_i - cos_t))
11611            .normalize()
11612    }
11613
11614    /// Encodes a display-referred linear RGB `[0..1]` color into exact sRGB `[u8; 4]` RGBA bytes.
11615    ///
11616    /// # Arguments
11617    ///
11618    /// - `Vec3` - Linear RGB color in `[0.0, 1.0]`.
11619    ///
11620    /// # Returns
11621    ///
11622    /// - `[u8; 4]` - Opaque sRGB RGBA8 pixel.
11623    #[cfg_attr(not(target_arch = "wasm32"), inline)]
11624    #[must_use]
11625    fn encode_srgb_rgba8(linear_rgb: Vec3) -> [u8; 4] {
11626        let to_srgb: fn(f32) -> u8 = |chan: f32| -> u8 {
11627            let clamped: f32 = chan.clamp(0.0, 1.0);
11628            let encoded: f32 = if clamped <= 0.003_130_8 {
11629                clamped * 12.92
11630            } else {
11631                1.055 * clamped.powf(1.0 / 2.4) - 0.055
11632            };
11633            (encoded * 255.0 + 0.5).clamp(0.0, 255.0) as u8
11634        };
11635        [
11636            to_srgb(linear_rgb.get_x()),
11637            to_srgb(linear_rgb.get_y()),
11638            to_srgb(linear_rgb.get_z()),
11639            255,
11640        ]
11641    }
11642
11643    /// Shades a single deferred pixel with perspective-correct barycentric attribute interpolation and full Blender Principled BSDF parity (IOR/specular, clearcoat, Charlie sheen, transmission+volume, normal maps, 4-cascade CSM, clustered/area lights, IBL, AgX/ACES).
11644    ///
11645    /// # Arguments
11646    ///
11647    /// - `&DeferredFrameContext` - Per-frame camera, sun, exposure, and ray-tracing settings.
11648    /// - `&ShadeBandInputs<'_>` - Read-only scene textures, Principled materials, lights, CSM, IBL, and BVH references.
11649    /// - `&GShadeTri` - Precomputed legacy fallback material record.
11650    /// - `&GSmoothTri` - Perspective-correct per-vertex normal, tangent, UV, and color record.
11651    /// - `(usize, usize)` - Pixel coordinates `(pixel_x, pixel_y)`.
11652    /// - `(Vec3, Vec3, f32)` - `(world_pos, raw_ray, linear_depth)` pixel geometry sample.
11653    ///
11654    /// # Returns
11655    ///
11656    /// - `[u8; 4]` - Tone-mapped sRGB RGBA8 output pixel.
11657    #[must_use]
11658    fn shade_pixel_principled_smooth(
11659        frame_context: &DeferredFrameContext,
11660        inputs: &ShadeBandInputs<'_>,
11661        tri: &GShadeTri,
11662        smooth_tri: &GSmoothTri,
11663        pixel_coords: (usize, usize),
11664        geom_sample: (Vec3, Vec3, f32),
11665    ) -> [u8; 4] {
11666        let (pixel_x, pixel_y): (usize, usize) = pixel_coords;
11667        let (world_pos, raw_ray, linear_depth): (Vec3, Vec3, f32) = geom_sample;
11668        let sample_x: f32 = (pixel_x as f32) + 0.5;
11669        let sample_y: f32 = (pixel_y as f32) + 0.5;
11670        let sx: [f32; 3] = smooth_tri.screen_x;
11671        let sy: [f32; 3] = smooth_tri.screen_y;
11672        let inv_area: f32 = smooth_tri.inv_area;
11673        let screen_w0: f32 = ((sx[1] - sample_x) * (sy[2] - sample_y)
11674            - (sy[1] - sample_y) * (sx[2] - sample_x))
11675            * inv_area;
11676        let screen_w1: f32 = ((sx[2] - sample_x) * (sy[0] - sample_y)
11677            - (sy[2] - sample_y) * (sx[0] - sample_x))
11678            * inv_area;
11679        let screen_w2: f32 = 1.0 - screen_w0 - screen_w1;
11680        let persp_0: f32 = screen_w0.max(0.0) * smooth_tri.inv_w[0];
11681        let persp_1: f32 = screen_w1.max(0.0) * smooth_tri.inv_w[1];
11682        let persp_2: f32 = screen_w2.max(0.0) * smooth_tri.inv_w[2];
11683        let inv_persp_sum: f32 = 1.0 / (persp_0 + persp_1 + persp_2).max(1.0e-9);
11684        let bary_0: f32 = persp_0 * inv_persp_sum;
11685        let bary_1: f32 = persp_1 * inv_persp_sum;
11686        let bary_2: f32 = persp_2 * inv_persp_sum;
11687        let view_dir: Vec3 = raw_ray.normalize().scale(-1.0);
11688        let raw_normal: Vec3 = smooth_tri.normals[0]
11689            .scale(bary_0)
11690            .add(smooth_tri.normals[1].scale(bary_1))
11691            .add(smooth_tri.normals[2].scale(bary_2));
11692        let mut geom_normal: Vec3 = if raw_normal.length_sq() > 1.0e-8 {
11693            raw_normal.normalize()
11694        } else {
11695            tri.shade_n
11696        };
11697        if smooth_tri.double_sided && geom_normal.dot(view_dir) < 0.0 {
11698            geom_normal = geom_normal.scale(-1.0);
11699        }
11700        let raw_tangent: Vec3 = Vec3::new(
11701            smooth_tri.tangents[0][0] * bary_0
11702                + smooth_tri.tangents[1][0] * bary_1
11703                + smooth_tri.tangents[2][0] * bary_2,
11704            smooth_tri.tangents[0][1] * bary_0
11705                + smooth_tri.tangents[1][1] * bary_1
11706                + smooth_tri.tangents[2][1] * bary_2,
11707            smooth_tri.tangents[0][2] * bary_0
11708                + smooth_tri.tangents[1][2] * bary_1
11709                + smooth_tri.tangents[2][2] * bary_2,
11710        );
11711        let ortho_tangent: Vec3 = raw_tangent.sub(geom_normal.scale(raw_tangent.dot(geom_normal)));
11712        let tangent_dir: Vec3 = if ortho_tangent.length_sq() > 1.0e-6 {
11713            ortho_tangent.normalize()
11714        } else {
11715            let helper_axis: Vec3 = if geom_normal.get_y().abs() < 0.9 {
11716                Vec3::new(0.0, 1.0, 0.0)
11717            } else {
11718                Vec3::new(1.0, 0.0, 0.0)
11719            };
11720            helper_axis.cross(geom_normal).normalize()
11721        };
11722        let tan_sign: f32 = if smooth_tri.tangents[0][3] < 0.0 {
11723            -1.0
11724        } else {
11725            1.0
11726        };
11727        let bitangent_dir: Vec3 = geom_normal.cross(tangent_dir).scale(tan_sign);
11728        let uv0_interp: [f32; 2] = [
11729            smooth_tri.uv0[0][0] * bary_0
11730                + smooth_tri.uv0[1][0] * bary_1
11731                + smooth_tri.uv0[2][0] * bary_2,
11732            smooth_tri.uv0[0][1] * bary_0
11733                + smooth_tri.uv0[1][1] * bary_1
11734                + smooth_tri.uv0[2][1] * bary_2,
11735        ];
11736        let uv1_interp: [f32; 2] = [
11737            smooth_tri.uv1[0][0] * bary_0
11738                + smooth_tri.uv1[1][0] * bary_1
11739                + smooth_tri.uv1[2][0] * bary_2,
11740            smooth_tri.uv1[0][1] * bary_0
11741                + smooth_tri.uv1[1][1] * bary_1
11742                + smooth_tri.uv1[2][1] * bary_2,
11743        ];
11744        let vcol_r: f32 = smooth_tri.color0[0][0] * bary_0
11745            + smooth_tri.color0[1][0] * bary_1
11746            + smooth_tri.color0[2][0] * bary_2;
11747        let vcol_g: f32 = smooth_tri.color0[0][1] * bary_0
11748            + smooth_tri.color0[1][1] * bary_1
11749            + smooth_tri.color0[2][1] * bary_2;
11750        let vcol_b: f32 = smooth_tri.color0[0][2] * bary_0
11751            + smooth_tri.color0[1][2] * bary_1
11752            + smooth_tri.color0[2][2] * bary_2;
11753        let vcol_a: f32 = smooth_tri.color0[0][3] * bary_0
11754            + smooth_tri.color0[1][3] * bary_1
11755            + smooth_tri.color0[2][3] * bary_2;
11756        let screen_area_px: f32 = 0.5 / inv_area.abs().max(1.0e-8);
11757        let uv0_area: f32 = ((smooth_tri.uv0[1][0] - smooth_tri.uv0[0][0])
11758            * (smooth_tri.uv0[2][1] - smooth_tri.uv0[0][1])
11759            - (smooth_tri.uv0[1][1] - smooth_tri.uv0[0][1])
11760                * (smooth_tri.uv0[2][0] - smooth_tri.uv0[0][0]))
11761            .abs()
11762            * 0.5;
11763        let uv1_area: f32 = ((smooth_tri.uv1[1][0] - smooth_tri.uv1[0][0])
11764            * (smooth_tri.uv1[2][1] - smooth_tri.uv1[0][1])
11765            - (smooth_tri.uv1[1][1] - smooth_tri.uv1[0][1])
11766                * (smooth_tri.uv1[2][0] - smooth_tri.uv1[0][0]))
11767            .abs()
11768            * 0.5;
11769        let area_terms: (f32, f32, f32) = (uv0_area, uv1_area, screen_area_px);
11770        let uv_pair: ([f32; 2], [f32; 2]) = (uv0_interp, uv1_interp);
11771        let mat_opt: Option<&PrincipledMaterial3D> =
11772            if smooth_tri.principled_material_id != u32::MAX {
11773                inputs
11774                    .principled_materials
11775                    .get(smooth_tri.principled_material_id as usize)
11776            } else {
11777                None
11778            };
11779        let mut albedo: Vec3 = Vec3::new(
11780            tri.mat_base.get_x() * vcol_r,
11781            tri.mat_base.get_y() * vcol_g,
11782            tri.mat_base.get_z() * vcol_b,
11783        );
11784        let mut alpha_val: f32 = vcol_a;
11785        let mut metallic: f32 = tri.metallic.clamp(0.0, 1.0);
11786        let mut roughness: f32 = tri.alpha2.sqrt().sqrt().clamp(0.04, 1.0);
11787        let mut shade_normal: Vec3 = geom_normal;
11788        let mut coat_normal: Vec3 = geom_normal;
11789        let mut ao_factor: f32 = 1.0;
11790        let mut emissive_rgb: Vec3 = tri.mat_emissive;
11791        let mut ior_val: f32 = 1.5;
11792        let mut spec_factor: f32 = 1.0;
11793        let mut spec_color: Vec3 = Vec3::splat(1.0);
11794        let mut coat_weight: f32 = 0.0;
11795        let mut coat_rough: f32 = 0.04;
11796        let mut sheen_color: Vec3 = Vec3::zero();
11797        let mut sheen_rough: f32 = 0.5;
11798        let mut transmission: f32 = 0.0;
11799        let mut thickness: f32 = 0.0;
11800        let mut atten_dist: f32 = f32::INFINITY;
11801        let mut atten_color: Vec3 = Vec3::splat(1.0);
11802        let mut is_unlit: bool = false;
11803        let mut alpha_masked: bool = false;
11804        if let Some(pmat) = mat_opt {
11805            let base_fac: [f32; 4] = pmat.get_base_color_factor();
11806            let base_tex: [f32; 4] = Self::sample_principled_slot(
11807                pmat.try_get_base_color_texture(),
11808                uv_pair,
11809                area_terms,
11810                inputs.textures,
11811            )
11812            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
11813            albedo = Vec3::new(
11814                base_fac[0] * base_tex[0] * vcol_r,
11815                base_fac[1] * base_tex[1] * vcol_g,
11816                base_fac[2] * base_tex[2] * vcol_b,
11817            );
11818            alpha_val = base_fac[3] * base_tex[3] * vcol_a;
11819            if pmat.get_alpha_mode() == AlphaMode3D::Mask && alpha_val < pmat.get_alpha_cutoff() {
11820                alpha_masked = true;
11821            }
11822            is_unlit = pmat.get_unlit();
11823            let mr_tex: [f32; 4] = Self::sample_principled_slot(
11824                pmat.try_get_metallic_roughness_texture(),
11825                uv_pair,
11826                area_terms,
11827                inputs.textures,
11828            )
11829            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
11830            metallic = (pmat.get_metallic_factor() * mr_tex[2]).clamp(0.0, 1.0);
11831            roughness = (pmat.get_roughness_factor() * mr_tex[1]).clamp(0.04, 1.0);
11832            if let Some(norm_tex) = Self::sample_principled_slot(
11833                pmat.try_get_normal_texture(),
11834                uv_pair,
11835                area_terms,
11836                inputs.textures,
11837            ) {
11838                let nscale: f32 = pmat.get_normal_scale();
11839                let ts_x: f32 = (norm_tex[0] * 2.0 - 1.0) * nscale;
11840                let ts_y: f32 = (norm_tex[1] * 2.0 - 1.0) * nscale;
11841                let ts_z: f32 = (norm_tex[2] * 2.0 - 1.0).max(0.05);
11842                let perturbed: Vec3 = tangent_dir
11843                    .scale(ts_x)
11844                    .add(bitangent_dir.scale(ts_y))
11845                    .add(geom_normal.scale(ts_z));
11846                if perturbed.length_sq() > 1.0e-8 {
11847                    shade_normal = perturbed.normalize();
11848                }
11849            }
11850            if let Some(occ_tex) = Self::sample_principled_slot(
11851                pmat.try_get_occlusion_texture(),
11852                uv_pair,
11853                area_terms,
11854                inputs.textures,
11855            ) {
11856                ao_factor =
11857                    (1.0 + pmat.get_occlusion_strength() * (occ_tex[0] - 1.0)).clamp(0.0, 1.0);
11858            }
11859            let em_fac: [f32; 3] = pmat.get_emissive_factor();
11860            let em_tex: [f32; 4] = Self::sample_principled_slot(
11861                pmat.try_get_emissive_texture(),
11862                uv_pair,
11863                area_terms,
11864                inputs.textures,
11865            )
11866            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
11867            let em_str: f32 = pmat.get_emissive_strength().max(0.0);
11868            emissive_rgb = Vec3::new(
11869                em_fac[0] * em_tex[0] * em_str,
11870                em_fac[1] * em_tex[1] * em_str,
11871                em_fac[2] * em_tex[2] * em_str,
11872            );
11873            ior_val = pmat.get_ior().max(1.0);
11874            let sp_tex: [f32; 4] = Self::sample_principled_slot(
11875                pmat.try_get_specular_texture(),
11876                uv_pair,
11877                area_terms,
11878                inputs.textures,
11879            )
11880            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
11881            spec_factor = (pmat.get_specular_factor() * sp_tex[3]).clamp(0.0, 1.0);
11882            let sp_col_fac: [f32; 3] = pmat.get_specular_color_factor();
11883            let sp_col_tex: [f32; 4] = Self::sample_principled_slot(
11884                pmat.try_get_specular_color_texture(),
11885                uv_pair,
11886                area_terms,
11887                inputs.textures,
11888            )
11889            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
11890            spec_color = Vec3::new(
11891                sp_col_fac[0] * sp_col_tex[0],
11892                sp_col_fac[1] * sp_col_tex[1],
11893                sp_col_fac[2] * sp_col_tex[2],
11894            );
11895            let cc_tex: [f32; 4] = Self::sample_principled_slot(
11896                pmat.try_get_clearcoat_texture(),
11897                uv_pair,
11898                area_terms,
11899                inputs.textures,
11900            )
11901            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
11902            coat_weight = (pmat.get_clearcoat_factor() * cc_tex[0]).clamp(0.0, 1.0);
11903            let cc_r_tex: [f32; 4] = Self::sample_principled_slot(
11904                pmat.try_get_clearcoat_roughness_texture(),
11905                uv_pair,
11906                area_terms,
11907                inputs.textures,
11908            )
11909            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
11910            coat_rough = (pmat.get_clearcoat_roughness_factor() * cc_r_tex[1]).clamp(0.04, 1.0);
11911            if let Some(cc_norm_tex) = Self::sample_principled_slot(
11912                pmat.try_get_clearcoat_normal_texture(),
11913                uv_pair,
11914                area_terms,
11915                inputs.textures,
11916            ) {
11917                let cc_x: f32 = cc_norm_tex[0] * 2.0 - 1.0;
11918                let cc_y: f32 = cc_norm_tex[1] * 2.0 - 1.0;
11919                let cc_z: f32 = (cc_norm_tex[2] * 2.0 - 1.0).max(0.05);
11920                let cc_pert: Vec3 = tangent_dir
11921                    .scale(cc_x)
11922                    .add(bitangent_dir.scale(cc_y))
11923                    .add(geom_normal.scale(cc_z));
11924                if cc_pert.length_sq() > 1.0e-8 {
11925                    coat_normal = cc_pert.normalize();
11926                }
11927            }
11928            let sh_col_fac: [f32; 3] = pmat.get_sheen_color_factor();
11929            let sh_col_tex: [f32; 4] = Self::sample_principled_slot(
11930                pmat.try_get_sheen_color_texture(),
11931                uv_pair,
11932                area_terms,
11933                inputs.textures,
11934            )
11935            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
11936            sheen_color = Vec3::new(
11937                sh_col_fac[0] * sh_col_tex[0],
11938                sh_col_fac[1] * sh_col_tex[1],
11939                sh_col_fac[2] * sh_col_tex[2],
11940            );
11941            let sh_r_tex: [f32; 4] = Self::sample_principled_slot(
11942                pmat.try_get_sheen_roughness_texture(),
11943                uv_pair,
11944                area_terms,
11945                inputs.textures,
11946            )
11947            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
11948            sheen_rough = (pmat.get_sheen_roughness_factor() * sh_r_tex[3]).clamp(0.07, 1.0);
11949            let tr_tex: [f32; 4] = Self::sample_principled_slot(
11950                pmat.try_get_transmission_texture(),
11951                uv_pair,
11952                area_terms,
11953                inputs.textures,
11954            )
11955            .unwrap_or([1.0, 1.0, 1.0, 1.0]);
11956            transmission =
11957                (pmat.get_transmission_factor() * tr_tex[0]).clamp(0.0, 1.0) * (1.0 - metallic);
11958            thickness = pmat.get_thickness_factor().max(0.0);
11959            atten_dist = pmat.get_attenuation_distance();
11960            atten_color = Vec3::from_array(pmat.get_attenuation_color());
11961        }
11962        if alpha_masked {
11963            let sky_hdr: Vec3 =
11964                Self::sample_sky_lut(inputs.sky_lut, raw_ray.normalize(), &frame_context.sun)
11965                    .scale(frame_context.exposure_scale);
11966            let sky_ldr: Vec3 = if inputs.use_agx_tonemap {
11967                agx_tonemap(sky_hdr)
11968            } else {
11969                aces_filmic_tonemap(sky_hdr)
11970            };
11971            return Self::encode_srgb_rgba8(sky_ldr);
11972        }
11973        if is_unlit {
11974            let unlit_hdr: Vec3 = albedo.scale(frame_context.exposure_scale);
11975            let unlit_ldr: Vec3 = if inputs.use_agx_tonemap {
11976                agx_tonemap(unlit_hdr)
11977            } else {
11978                aces_filmic_tonemap(unlit_hdr)
11979            };
11980            return Self::encode_srgb_rgba8(unlit_ldr);
11981        }
11982        let dielectric_f0_s: f32 = dielectric_f0_from_ior(ior_val);
11983        let dielectric_f0: Vec3 = Vec3::new(
11984            (dielectric_f0_s * spec_color.get_x()).min(1.0) * spec_factor,
11985            (dielectric_f0_s * spec_color.get_y()).min(1.0) * spec_factor,
11986            (dielectric_f0_s * spec_color.get_z()).min(1.0) * spec_factor,
11987        );
11988        let f0: Vec3 = dielectric_f0.lerp(albedo, metallic);
11989        let diffuse_albedo: Vec3 = albedo.scale((1.0 - metallic) * (1.0 - transmission));
11990        let alpha_rough: f32 = roughness * roughness;
11991        let alpha2: f32 = (alpha_rough * alpha_rough).max(1.0e-4);
11992        let n_dot_v: f32 = shade_normal.dot(view_dir).max(0.001);
11993        let sun_dir: Vec3 = frame_context.sun.get_direction();
11994        let sun_color: Vec3 = frame_context.sun.get_color();
11995        let sun_vis: f32 = if let Some(vsm) = inputs.vsm {
11996            vsm.sample_visibility(world_pos, shade_normal, sun_dir)
11997        } else if frame_context.raytrace_mode != RayTracingMode::Off {
11998            let shadow_origin: Vec3 = world_pos.add(shade_normal.scale(0.05));
11999            let mut static_hint: u32 = u32::MAX;
12000            let mut dyn_hint: u32 = u32::MAX;
12001            if World3D::trace_any_shadow_with_instances(
12002                inputs.static_bvh,
12003                inputs.dyn_instances,
12004                inputs.local_bvhs,
12005                (shadow_origin, sun_dir, frame_context.inv_sun_dir),
12006                (0.04, 140.0),
12007                (&mut static_hint, &mut dyn_hint),
12008            ) {
12009                0.15
12010            } else {
12011                1.0
12012            }
12013        } else {
12014            1.0
12015        };
12016        let brdf_lut_sample: [f32; 2] = inputs
12017            .environment_ibl
12018            .map_or([0.82, 0.08], |ibl: &EnvironmentIbl3D| {
12019                ibl.sample_brdf_lut(n_dot_v, roughness)
12020            });
12021        let multi_scatter: Vec3 =
12022            kulla_conty_multiscatter_factor(f0, brdf_lut_sample[0] + brdf_lut_sample[1]);
12023        let n_dot_l: f32 = shade_normal.dot(sun_dir).max(0.0);
12024        let mut direct_rgb: Vec3 = Vec3::zero();
12025        if n_dot_l > 0.0 && sun_vis > 0.0 {
12026            let half_vec: Vec3 = sun_dir.add(view_dir).normalize();
12027            let n_dot_h: f32 = shade_normal.dot(half_vec).max(0.0);
12028            let v_dot_h: f32 = view_dir.dot(half_vec).clamp(0.0, 1.0);
12029            let ggx_den: f32 = n_dot_h * n_dot_h * (alpha2 - 1.0) + 1.0;
12030            let ggx_d: f32 = alpha2 / (PI * ggx_den * ggx_den).max(1.0e-5);
12031            let vis_v: f32 = n_dot_l * (n_dot_v * (n_dot_v - n_dot_v * alpha2) + alpha2).sqrt();
12032            let vis_l: f32 = n_dot_v * (n_dot_l * (n_dot_l - n_dot_l * alpha2) + alpha2).sqrt();
12033            let smith_vis: f32 = 0.5 / (vis_v + vis_l).max(1.0e-4);
12034            let om_vh: f32 = 1.0 - v_dot_h;
12035            let pow5_vh: f32 = om_vh * om_vh * om_vh * om_vh * om_vh;
12036            let fresnel_base: Vec3 = f0.add(Vec3::splat(1.0).sub(f0).scale(pow5_vh));
12037            let base_spec: Vec3 = fresnel_base.mul(multi_scatter).scale(ggx_d * smith_vis);
12038            let base_diff: Vec3 = diffuse_albedo
12039                .mul(Vec3::splat(1.0).sub(fresnel_base))
12040                .scale(1.0 / PI);
12041            let mut layer_brdf: Vec3 = base_diff.add(base_spec);
12042            let max_sheen: f32 = sheen_color
12043                .get_x()
12044                .max(sheen_color.get_y())
12045                .max(sheen_color.get_z());
12046            if max_sheen > 1.0e-4 {
12047                let sheen_brdf: f32 =
12048                    Self::eval_charlie_sheen(sheen_rough, n_dot_h, n_dot_v, n_dot_l);
12049                let sheen_atten: f32 = (1.0 - max_sheen * 0.25).clamp(0.25, 1.0);
12050                layer_brdf = layer_brdf
12051                    .scale(sheen_atten)
12052                    .add(sheen_color.scale(sheen_brdf));
12053            }
12054            if coat_weight > 1.0e-4 {
12055                let cc_nl: f32 = coat_normal.dot(sun_dir).max(0.0);
12056                let cc_nh: f32 = coat_normal.dot(half_vec).max(0.0);
12057                let cc_a: f32 = coat_rough * coat_rough;
12058                let cc_a2: f32 = (cc_a * cc_a).max(1.0e-4);
12059                let cc_den: f32 = cc_nh * cc_nh * (cc_a2 - 1.0) + 1.0;
12060                let cc_d: f32 = cc_a2 / (PI * cc_den * cc_den).max(1.0e-5);
12061                let cc_vis: f32 = 0.25 / (v_dot_h * v_dot_h).max(0.04);
12062                let f_coat: f32 = 0.04 + 0.96 * pow5_vh;
12063                let coat_spec: f32 = (cc_d * cc_vis * f_coat * coat_weight).min(12.0);
12064                let coat_atten: f32 = (1.0 - coat_weight * f_coat).clamp(0.0, 1.0);
12065                layer_brdf = layer_brdf.scale(coat_atten).add(Vec3::splat(
12066                    coat_spec * (cc_nl / n_dot_l.max(1.0e-4)).min(1.5),
12067                ));
12068            }
12069            direct_rgb = layer_brdf.mul(sun_color).scale(n_dot_l * sun_vis);
12070        }
12071        let mut local_rgb: Vec3 = Vec3::zero();
12072        if let Some(clusters) = inputs.light_clusters {
12073            let screen_u: f32 = sample_x * frame_context.inv_width;
12074            let screen_v: f32 = sample_y * frame_context.inv_height;
12075            local_rgb = clusters.evaluate_pixel(
12076                world_pos,
12077                shade_normal,
12078                view_dir,
12079                (albedo, f0, alpha2, (1.0 - metallic) * (1.0 - transmission)),
12080                (screen_u, screen_v, linear_depth),
12081            );
12082        }
12083        for area_light in inputs.area_lights.iter() {
12084            local_rgb = local_rgb.add(area_light.evaluate_pbr(
12085                world_pos,
12086                shade_normal,
12087                view_dir,
12088                (
12089                    albedo,
12090                    f0,
12091                    roughness,
12092                    (1.0 - metallic) * (1.0 - transmission),
12093                ),
12094            ));
12095        }
12096        let refl_dir: Vec3 = view_dir.scale(-1.0).reflect(shade_normal).normalize();
12097        let om_nv: f32 = (1.0 - n_dot_v).clamp(0.0, 1.0);
12098        let pow5_nv: f32 = om_nv * om_nv * om_nv * om_nv * om_nv;
12099        let max_smooth_f0: Vec3 = Vec3::new(
12100            (1.0 - roughness).max(f0.get_x()),
12101            (1.0 - roughness).max(f0.get_y()),
12102            (1.0 - roughness).max(f0.get_z()),
12103        );
12104        let fresnel_ibl: Vec3 = f0.add(max_smooth_f0.sub(f0).scale(pow5_nv));
12105        let mut ibl_rgb: Vec3 = if let Some(ibl) = inputs.environment_ibl {
12106            let irradiance: Vec3 = ibl.evaluate_sh_diffuse(shade_normal);
12107            let prefiltered: Vec3 = ibl.sample_specular_octahedral(refl_dir, roughness);
12108            let ibl_diff: Vec3 = irradiance
12109                .mul(diffuse_albedo)
12110                .mul(Vec3::splat(1.0).sub(fresnel_ibl));
12111            let ibl_spec: Vec3 = prefiltered
12112                .mul(
12113                    f0.scale(brdf_lut_sample[0])
12114                        .add(Vec3::splat(brdf_lut_sample[1])),
12115                )
12116                .mul(multi_scatter);
12117            let mut combined_ibl: Vec3 = ibl_diff.add(ibl_spec);
12118            if coat_weight > 1.0e-4 {
12119                let cc_nv: f32 = coat_normal.dot(view_dir).max(0.001);
12120                let cc_om: f32 = (1.0 - cc_nv).clamp(0.0, 1.0);
12121                let f_coat_v: f32 = 0.04 + 0.96 * cc_om * cc_om * cc_om * cc_om * cc_om;
12122                let cc_refl: Vec3 = view_dir.scale(-1.0).reflect(coat_normal).normalize();
12123                let cc_pref: Vec3 = ibl.sample_specular_octahedral(cc_refl, coat_rough);
12124                combined_ibl = combined_ibl
12125                    .scale(1.0 - coat_weight * f_coat_v)
12126                    .add(cc_pref.scale(coat_weight * f_coat_v));
12127            }
12128            combined_ibl.scale(ao_factor)
12129        } else {
12130            let sky_hemi: Vec3 = frame_context.sun.get_sky_horizon().lerp(
12131                frame_context.sun.get_sky_zenith(),
12132                (shade_normal.get_y() * 0.5 + 0.5).clamp(0.0, 1.0),
12133            );
12134            let sky_spec: Vec3 = Self::sample_sky_lut(inputs.sky_lut, refl_dir, &frame_context.sun);
12135            let hemi_diff: Vec3 = sky_hemi
12136                .mul(diffuse_albedo)
12137                .mul(Vec3::splat(1.0).sub(fresnel_ibl))
12138                .scale(0.45);
12139            let hemi_spec: Vec3 = sky_spec
12140                .mul(fresnel_ibl)
12141                .mul(multi_scatter)
12142                .scale((1.0 - roughness * 0.65).clamp(0.15, 1.0));
12143            hemi_diff.add(hemi_spec).scale(ao_factor)
12144        };
12145        if sheen_color.length_sq() > 1.0e-6 {
12146            let sheen_grazing: f32 = pow5_nv * (0.35 + 0.65 * sheen_rough);
12147            ibl_rgb = ibl_rgb.add(sheen_color.scale(sheen_grazing * 0.45 * ao_factor));
12148        }
12149        let transmitted_rgb: Vec3 = if transmission > 1.0e-4 {
12150            let refr_dir: Vec3 =
12151                Self::refract_unit_ray(view_dir.scale(-1.0), shade_normal, 1.0 / ior_val);
12152            let bg_radiance: Vec3 = if let Some(ibl) = inputs.environment_ibl {
12153                ibl.sample_specular_octahedral(refr_dir, roughness)
12154            } else {
12155                Self::sample_sky_lut(inputs.sky_lut, refr_dir, &frame_context.sun)
12156            };
12157            let beer_atten: Vec3 =
12158                if thickness > 1.0e-4 && atten_dist.is_finite() && atten_dist > 1.0e-4 {
12159                    let sigma_r: f32 = -(atten_color.get_x().clamp(1.0e-4, 1.0)).ln() / atten_dist;
12160                    let sigma_g: f32 = -(atten_color.get_y().clamp(1.0e-4, 1.0)).ln() / atten_dist;
12161                    let sigma_b: f32 = -(atten_color.get_z().clamp(1.0e-4, 1.0)).ln() / atten_dist;
12162                    Vec3::new(
12163                        (-sigma_r * thickness).exp(),
12164                        (-sigma_g * thickness).exp(),
12165                        (-sigma_b * thickness).exp(),
12166                    )
12167                } else {
12168                    Vec3::splat(1.0)
12169                };
12170            bg_radiance
12171                .mul(albedo)
12172                .mul(beer_atten)
12173                .mul(Vec3::splat(1.0).sub(fresnel_ibl))
12174                .scale(transmission)
12175        } else {
12176            Vec3::zero()
12177        };
12178        let _alpha_blend_guard: f32 = alpha_val;
12179        let hdr_rgb: Vec3 = direct_rgb
12180            .add(local_rgb)
12181            .add(ibl_rgb)
12182            .add(transmitted_rgb)
12183            .add(emissive_rgb)
12184            .scale(frame_context.exposure_scale);
12185        let ldr_linear: Vec3 = if inputs.use_agx_tonemap {
12186            agx_tonemap(hdr_rgb)
12187        } else {
12188            aces_filmic_tonemap(hdr_rgb)
12189        };
12190        Self::encode_srgb_rgba8(ldr_linear)
12191    }
12192}