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"))]
5/// Inherent implementation of [`Engine3dWorkerPool`].
6impl Engine3dWorkerPool {
7    /// Creates a warm persistent worker pool sized to host CPU cores (`1..=16` total threads including caller) with lock-free spin-before-park dispatch.
8    ///
9    /// # Returns
10    ///
11    /// - `Self` - Initialized worker pool with zero per-frame thread spawn overhead.
12    #[must_use]
13    pub(crate) fn new() -> Self {
14        let total: usize = available_parallelism()
15            .map(usize::from)
16            .unwrap_or(4)
17            .clamp(1, ENGINE3D_WORKER_MAX_THREADS);
18        let requested_workers: usize = total.saturating_sub(1);
19        let mut slots: Vec<Engine3dWorkerSlot> = Vec::with_capacity(requested_workers);
20        for _ in 0..requested_workers {
21            slots.push(Engine3dWorkerSlot::default());
22        }
23        let shared: Arc<Engine3dPoolShared> = Arc::new(Engine3dPoolShared {
24            active_job: AtomicUsize::new(0),
25            active_workers: AtomicUsize::new(0),
26            caller_parked: AtomicUsize::new(0),
27            caller_lock: Mutex::new(()),
28            wake_caller: Condvar::new(),
29            slots,
30        });
31        let mut spawned_count: usize = 0;
32        for idx in 0..requested_workers {
33            let shared_clone: Arc<Engine3dPoolShared> = Arc::clone(&shared);
34            let name: String = format!("{ENGINE3D_WORKER_PREFIX}-{idx}");
35            let spawn_res: io::Result<JoinHandle<()>> =
36                Builder::new().name(name).spawn(move || {
37                    let slot: &Engine3dWorkerSlot = &shared_clone.slots[idx];
38                    let mut seen_epoch: usize = 0;
39                    loop {
40                        let mut spins: u32 = 0;
41                        let job_ptr: usize = loop {
42                            let cur_epoch: usize = slot.epoch.load(Ordering::Acquire);
43                            if cur_epoch != seen_epoch {
44                                let ptr: usize = shared_clone.active_job.load(Ordering::Acquire);
45                                if ptr != 0 {
46                                    seen_epoch = cur_epoch;
47                                    break ptr;
48                                }
49                            }
50                            if spins < ENGINE3D_WORKER_SPIN_LIMIT {
51                                spins += 1;
52                                spin_loop();
53                                continue;
54                            }
55                            let Ok(mut guard) = slot.lock.lock() else {
56                                return;
57                            };
58                            slot.parked.store(1, Ordering::SeqCst);
59                            let parked_ptr: Option<usize> = loop {
60                                let locked_epoch: usize = slot.epoch.load(Ordering::SeqCst);
61                                if locked_epoch != seen_epoch {
62                                    let ptr: usize =
63                                        shared_clone.active_job.load(Ordering::Acquire);
64                                    if ptr != 0 {
65                                        seen_epoch = locked_epoch;
66                                        break Some(ptr);
67                                    }
68                                }
69                                let Ok(next_guard) = slot.wake.wait(guard) else {
70                                    break None;
71                                };
72                                guard = next_guard;
73                            };
74                            slot.parked.store(0, Ordering::SeqCst);
75                            let Some(ptr) = parked_ptr else {
76                                return;
77                            };
78                            break ptr;
79                        };
80                        // SAFETY: Caller keeps `Engine3dJob` pinned on its stack until `workers_done >= active_workers`.
81                        let job: &Engine3dJob = unsafe { &*(job_ptr as *const Engine3dJob) };
82                        run_engine3d_job_loop(job);
83                        let expected: usize = shared_clone.active_workers.load(Ordering::Acquire);
84                        let finished: usize = job.workers_done.fetch_add(1, Ordering::SeqCst) + 1;
85                        if finished >= expected
86                            && shared_clone.caller_parked.load(Ordering::SeqCst) != 0
87                        {
88                            let _guard: Result<
89                                MutexGuard<'_, ()>,
90                                PoisonError<MutexGuard<'_, ()>>,
91                            > = shared_clone.caller_lock.lock();
92                            shared_clone.wake_caller.notify_one();
93                        }
94                    }
95                });
96            if spawn_res.is_ok() {
97                spawned_count += 1;
98            } else {
99                break;
100            }
101        }
102        Self {
103            worker_count: spawned_count,
104            dispatch_lock: Mutex::new(()),
105            shared,
106        }
107    }
108}
109
110/// High-FPS UE5-class Deferred GGX PBR + Persistent Multi-Core 32B SAH BVH + Lumen GI + Volumetric Fog + Bilinear Bloom + Geometry-Aware Morphological AA/TAA renderer.
111impl Renderer3D {
112    /// Evaluates physically inspired Rayleigh + Mie atmospheric sky and HDR solar disk radiance along `dir`.
113    ///
114    /// # Arguments
115    ///
116    /// - `Vec3` - Unit view or reflection direction.
117    /// - `&DirectionalLight3D` - Active sky & sun lighting parameters.
118    ///
119    /// # Returns
120    ///
121    /// - `Vec3` - Linear HDR sky radiance.
122    #[must_use]
123    pub fn sample_sky(dir: Vec3, sun: &DirectionalLight3D) -> Vec3 {
124        let up: f32 = dir.get_y().clamp(0.0, 1.0);
125        let t: f32 = up.sqrt();
126        let horizon_glow: f32 = (1.0 - up) * (1.0 - up);
127        let mut col: Vec3 = sun
128            .get_sky_horizon()
129            .lerp(sun.get_sky_zenith(), t)
130            .add(sun.get_sky_horizon().scale(horizon_glow * 0.14));
131        let sun_dot: f32 = dir.dot(sun.get_direction()).max(0.0);
132        if sun_dot > 0.992 {
133            let disk: f32 = ((sun_dot - 0.992) / 0.008).clamp(0.0, 1.0);
134            col = col.add(sun.get_color().scale(disk * 3.8 + 0.55));
135        } else if sun_dot > 0.72 {
136            let h1: f32 = ((sun_dot - 0.72) / 0.28).clamp(0.0, 1.0);
137            let h2: f32 = h1 * h1;
138            let mie: f32 = h2 * h2;
139            col = col.add(sun.get_color().scale(mie * 0.58 + h2 * 0.08));
140        }
141        col
142    }
143
144    /// Reconstructs exact world-space position for pixel `(px, py)` at camera depth `depth`.
145    ///
146    /// # Arguments
147    ///
148    /// - `&DeferredFrameCtx` - Shared per-frame camera basis.
149    /// - `usize` - Pixel X coordinate.
150    /// - `usize` - Pixel Y coordinate.
151    /// - `f32` - Linear camera-space depth (`1 / inv_w`).
152    ///
153    /// # Returns
154    ///
155    /// - `(Vec3, Vec3)` - `(world_pos, unnormalized_view_ray_dir)`.
156    #[must_use]
157    fn pixel_world_pos(fctx: &DeferredFrameCtx, px: usize, py: usize, depth: f32) -> (Vec3, Vec3) {
158        let ndc_x: f32 = 2.0 * (((px as f32) + 0.5) * fctx.inv_w_f) - 1.0;
159        let ndc_y: f32 = 1.0 - 2.0 * (((py as f32) + 0.5) * fctx.inv_h_f);
160        let ray_vec: Vec3 = fctx
161            .cam_fwd
162            .add(fctx.cam_right_scaled.scale(ndc_x))
163            .add(fctx.cam_up_scaled.scale(ndc_y));
164        (fctx.cam_pos.add(ray_vec.scale(depth)), ray_vec)
165    }
166
167    /// Shades a single BVH closest-hit surface with multi-bounce sky/emissive radiance for reflections and Lumen GI.
168    ///
169    /// # Arguments
170    ///
171    /// - `&Bvh3D` - Scene BVH holding triangle materials.
172    /// - `usize` - Winning triangle index.
173    /// - `&DirectionalLight3D` - Active directional sun light.
174    /// - `bool` - Enables secondary hemisphere sky energy conservation for multi-bounce Lumen GI.
175    ///
176    /// # Returns
177    ///
178    /// - `Vec3` - Linear HDR hit radiance.
179    #[must_use]
180    fn shade_bvh_hit(
181        bvh: &Bvh3D,
182        tri_idx: usize,
183        sun: &DirectionalLight3D,
184        multi_bounce: bool,
185    ) -> Vec3 {
186        let hit_tri: &BvhTriangle = &bvh.get_triangles()[tri_idx];
187        let hit_n: Vec3 = hit_tri.get_normal();
188        let h_nl: f32 = hit_n.dot(sun.get_direction()).abs().max(0.18);
189        let mat: PbrMaterial = hit_tri.get_material();
190        let mut col: Vec3 = mat
191            .get_base_color()
192            .mul(sun.get_color().scale(h_nl))
193            .add(mat.get_emissive());
194        if multi_bounce {
195            let sky_hemi: Vec3 = sun.get_sky_horizon().lerp(
196                sun.get_sky_zenith(),
197                (hit_n.get_y() * 0.5 + 0.5).clamp(0.0, 1.0),
198            );
199            col = col.add(mat.get_base_color().mul(sky_hemi.scale(0.32)));
200        }
201        col
202    }
203
204    /// Evaluates a band of coarse deferred RT probes `[gy_start..gy_end)` with precomputed soft-shadow and Lumen GI/AO ray tables.
205    ///
206    /// # Arguments
207    ///
208    /// - `&DeferredFrameCtx` - Shared per-frame camera and RT parameters.
209    /// - `ProbeTraceInputs<'_>` - Read-only depth, G-Buffer IDs, shading records, precomputed GI rays, and SAH BVH.
210    /// - `(usize, &mut [RtProbeSample])` - `(gy_start, mutable probe band slice)`.
211    ///
212    /// # Returns
213    ///
214    /// - `usize` - Total BVH rays traced within this band.
215    fn trace_probe_band(
216        fctx: &DeferredFrameCtx,
217        inputs: ProbeTraceInputs<'_>,
218        band: (usize, &mut [RtProbeSample]),
219    ) -> usize {
220        let (depth_buf, g_tri_idx, shaded_tris, gi_rays, static_bvh, dynamic_bvh): ProbeTraceInputs<
221            '_,
222        > = inputs;
223        let (gy_start, out_probes): (usize, &mut [RtProbeSample]) = band;
224        let gw: usize = fctx.gw;
225        let step: usize = fctx.rt_step;
226        let half_step: usize = step / 2;
227        let sun_dir: Vec3 = fctx.sun.get_direction();
228        let inv_sun: Vec3 = fctx.inv_sun_dir;
229        let soft_rays: [(Vec3, Vec3); 4] = fctx.soft_shadow_rays;
230        let use_soft_shadows: bool = fctx.rt_mode == RayTracingMode::FullPathTracedGi;
231        let multi_bounce_refl: bool = fctx.reflection_bounces >= 2;
232        let mut rays: usize = 0;
233        let mut static_shadow_cache: u32 = u32::MAX;
234        let mut dynamic_shadow_cache: u32 = u32::MAX;
235        let band_rows: usize = out_probes.len() / gw.max(1);
236        for local_gy in 0..band_rows {
237            let gy: usize = gy_start + local_gy;
238            let py: usize = (gy * step + half_step).min(fctx.h - 1);
239            let row_off: usize = py * fctx.w;
240            let probe_row: usize = local_gy * gw;
241            for gx in 0..gw {
242                let px: usize = (gx * step + half_step).min(fctx.w - 1);
243                let pix_idx: usize = row_off + px;
244                let tid: u32 = g_tri_idx[pix_idx];
245                if tid == u32::MAX {
246                    out_probes[probe_row + gx] = RtProbeSample::default();
247                    continue;
248                }
249                let inv_w: f32 = depth_buf[pix_idx];
250                let depth: f32 = 1.0 / inv_w.max(1e-6);
251                let tri_idx: usize = tid as usize;
252                let tri: &GShadeTri = &shaded_tris[tri_idx];
253                let (world_p, ray_vec): (Vec3, Vec3) = Self::pixel_world_pos(fctx, px, py, depth);
254                let origin: Vec3 = world_p.add(tri.shade_n.scale(0.08));
255                let pattern: usize = (gx & 1) | ((gy & 1) << 1);
256                let mut shadow: f32 = 1.0;
257                if tri.n_dot_l > 0.02 {
258                    rays += 1;
259                    let (s_dir, s_inv): (Vec3, Vec3) = if use_soft_shadows {
260                        soft_rays[pattern]
261                    } else {
262                        (sun_dir, inv_sun)
263                    };
264                    if World3D::trace_any_shadow_split(
265                        (static_bvh, dynamic_bvh),
266                        (origin, s_dir, s_inv),
267                        (0.05, 140.0),
268                        (&mut static_shadow_cache, &mut dynamic_shadow_cache),
269                    ) {
270                        shadow = 0.22;
271                    }
272                }
273                let mut refl: Vec3 = fctx.sun.get_sky_horizon();
274                if tri.do_refl {
275                    let view_in: Vec3 = ray_vec.normalize();
276                    let refl_dir: Vec3 = view_in.reflect(tri.shade_n).normalize();
277                    if depth > 64.0 {
278                        refl = Self::sample_sky(refl_dir, &fctx.sun);
279                    } else {
280                        let inv_refl: Vec3 = Ray3D::safe_inv_vec(refl_dir);
281                        rays += 1;
282                        refl = match World3D::trace_closest_split(
283                            (static_bvh, dynamic_bvh),
284                            (origin, refl_dir, inv_refl),
285                            (0.08, 100.0),
286                        ) {
287                            Some((hit_t, is_dyn, hit_idx)) => {
288                                let hit_bvh: &Bvh3D = if is_dyn { dynamic_bvh } else { static_bvh };
289                                let mut hit_rad: Vec3 = Self::shade_bvh_hit(
290                                    hit_bvh,
291                                    hit_idx,
292                                    &fctx.sun,
293                                    use_soft_shadows,
294                                );
295                                if multi_bounce_refl && hit_t < 30.0 && depth < 32.0 {
296                                    let hit_tri: &BvhTriangle = &hit_bvh.get_triangles()[hit_idx];
297                                    let hit_mat: PbrMaterial = hit_tri.get_material();
298                                    if hit_mat.get_reflectivity() > 0.55 {
299                                        let p2: Vec3 = origin
300                                            .add(refl_dir.scale(hit_t))
301                                            .add(hit_tri.get_normal().scale(0.08));
302                                        let r2: Vec3 =
303                                            refl_dir.reflect(hit_tri.get_normal()).normalize();
304                                        let inv_r2: Vec3 = Ray3D::safe_inv_vec(r2);
305                                        rays += 1;
306                                        let bounce2: Vec3 = match World3D::trace_closest_split(
307                                            (static_bvh, dynamic_bvh),
308                                            (p2, r2, inv_r2),
309                                            (0.08, 56.0),
310                                        ) {
311                                            Some((_, is_dyn2, idx2)) => {
312                                                let hit_bvh2: &Bvh3D =
313                                                    if is_dyn2 { dynamic_bvh } else { static_bvh };
314                                                Self::shade_bvh_hit(
315                                                    hit_bvh2, idx2, &fctx.sun, false,
316                                                )
317                                            }
318                                            None => Self::sample_sky(r2, &fctx.sun),
319                                        };
320                                        hit_rad = hit_rad.lerp(
321                                            bounce2,
322                                            (hit_mat.get_reflectivity() * 0.45).clamp(0.0, 0.5),
323                                        );
324                                    }
325                                }
326                                hit_rad
327                            }
328                            None => Self::sample_sky(refl_dir, &fctx.sun),
329                        };
330                    }
331                }
332                let mut gi_col: Vec3 = Vec3::zero();
333                let mut ao: f32 = 1.0;
334                if use_soft_shadows {
335                    if depth > 52.0 {
336                        gi_col = fctx.sun.get_sky_horizon().scale(0.18);
337                        ao = 0.88;
338                    } else {
339                        let (gi_dir, inv_gi): (Vec3, Vec3) = gi_rays[tri_idx][pattern];
340                        rays += 1;
341                        match World3D::trace_closest_split(
342                            (static_bvh, dynamic_bvh),
343                            (origin, gi_dir, inv_gi),
344                            (0.06, 20.0),
345                        ) {
346                            Some((dist, is_dyn, hit_idx)) => {
347                                let hit_bvh: &Bvh3D = if is_dyn { dynamic_bvh } else { static_bvh };
348                                let bounce: Vec3 =
349                                    Self::shade_bvh_hit(hit_bvh, hit_idx, &fctx.sun, true);
350                                let falloff: f32 = (1.0 - dist / 20.0).clamp(0.14, 1.0);
351                                gi_col = bounce.scale(0.36 * falloff);
352                                ao = 0.42 + 0.58 * (dist / 14.0).clamp(0.0, 1.0);
353                            }
354                            None => {
355                                gi_col = Self::sample_sky(gi_dir, &fctx.sun).scale(0.20);
356                                ao = 1.0;
357                            }
358                        }
359                    }
360                }
361                out_probes[probe_row + gx] = RtProbeSample {
362                    shadow,
363                    refl_r: refl.get_x(),
364                    refl_g: refl.get_y(),
365                    refl_b: refl.get_z(),
366                    gi_r: gi_col.get_x(),
367                    gi_g: gi_col.get_y(),
368                    gi_b: gi_col.get_z(),
369                    ao,
370                    depth,
371                    nx: tri.shade_n.get_x(),
372                    ny: tri.shade_n.get_y(),
373                    nz: tri.shade_n.get_z(),
374                    valid: 1,
375                };
376            }
377        }
378        rays
379    }
380
381    /// Runs a 3x3 depth- and normal-aware joint bilateral denoiser on a horizontal band of coarse Lumen GI probes.
382    ///
383    /// # Arguments
384    ///
385    /// - `usize` - Coarse probe grid width.
386    /// - `usize` - Coarse probe grid height.
387    /// - `&[RtProbeSample]` - Full noisy input probe grid.
388    /// - `usize` - Inclusive starting probe row `gy_start`.
389    /// - `&mut [RtProbeSample]` - Disjoint denoised output band slice.
390    fn denoise_gi_probes_band(
391        gw: usize,
392        gh: usize,
393        src: &[RtProbeSample],
394        gy_start: usize,
395        dst_band: &mut [RtProbeSample],
396    ) {
397        let band_rows: usize = dst_band.len() / gw.max(1);
398        for local_gy in 0..band_rows {
399            let gy: usize = gy_start + local_gy;
400            let y0: usize = gy.saturating_sub(1);
401            let y1: usize = (gy + 1).min(gh - 1);
402            let dst_row: usize = local_gy * gw;
403            for gx in 0..gw {
404                let idx: usize = gy * gw + gx;
405                let center: &RtProbeSample = &src[idx];
406                if center.valid == 0 {
407                    dst_band[dst_row + gx] = *center;
408                    continue;
409                }
410                let x0: usize = gx.saturating_sub(1);
411                let x1: usize = (gx + 1).min(gw - 1);
412                let depth_tol: f32 = center.depth * 0.22 + 0.75;
413                let inv_depth_tol: f32 = 1.0 / depth_tol;
414                let mut w_sum: f32 = 0.0;
415                let mut s_sum: f32 = 0.0;
416                let mut rr_sum: f32 = 0.0;
417                let mut rg_sum: f32 = 0.0;
418                let mut rb_sum: f32 = 0.0;
419                let mut gi_r: f32 = 0.0;
420                let mut gi_g: f32 = 0.0;
421                let mut gi_b: f32 = 0.0;
422                let mut ao_sum: f32 = 0.0;
423                for ny in y0..=y1 {
424                    let row_off: usize = ny * gw;
425                    for nx in x0..=x1 {
426                        let nb: &RtProbeSample = &src[row_off + nx];
427                        if nb.valid == 0 {
428                            continue;
429                        }
430                        let ndot: f32 = center
431                            .nx
432                            .mul_add(nb.nx, center.ny.mul_add(nb.ny, center.nz * nb.nz));
433                        if ndot < 0.75 {
434                            continue;
435                        }
436                        let d_diff: f32 = (center.depth - nb.depth).abs();
437                        if d_diff > depth_tol {
438                            continue;
439                        }
440                        let spatial: f32 = if nx == gx && ny == gy {
441                            1.8
442                        } else if nx == gx || ny == gy {
443                            1.0
444                        } else {
445                            0.6
446                        };
447                        let w: f32 = spatial * (1.0 - d_diff * inv_depth_tol);
448                        w_sum += w;
449                        s_sum = nb.shadow.mul_add(w, s_sum);
450                        rr_sum = nb.refl_r.mul_add(w, rr_sum);
451                        rg_sum = nb.refl_g.mul_add(w, rg_sum);
452                        rb_sum = nb.refl_b.mul_add(w, rb_sum);
453                        gi_r = nb.gi_r.mul_add(w, gi_r);
454                        gi_g = nb.gi_g.mul_add(w, gi_g);
455                        gi_b = nb.gi_b.mul_add(w, gi_b);
456                        ao_sum = nb.ao.mul_add(w, ao_sum);
457                    }
458                }
459                let mut out: RtProbeSample = *center;
460                if w_sum > 1e-4 {
461                    let inv_w: f32 = 1.0 / w_sum;
462                    out.shadow = s_sum * inv_w;
463                    out.refl_r = rr_sum * inv_w;
464                    out.refl_g = rg_sum * inv_w;
465                    out.refl_b = rb_sum * inv_w;
466                    out.gi_r = gi_r * inv_w;
467                    out.gi_g = gi_g * inv_w;
468                    out.gi_b = gi_b * inv_w;
469                    out.ao = ao_sum * inv_w;
470                }
471                dst_band[dst_row + gx] = out;
472            }
473        }
474    }
475
476    /// Evaluates a symmetric 5-tap Gaussian bloom kernel (`0.08, 0.22, 0.40, 0.22, 0.08`) using fused multiply-adds.
477    ///
478    /// # Arguments
479    ///
480    /// - `[f32; 3]` - Tap at offset `-2`.
481    /// - `[f32; 3]` - Tap at offset `-1`.
482    /// - `[f32; 3]` - Center tap `0`.
483    /// - `[f32; 3]` - Tap at offset `+1`.
484    /// - `[f32; 3]` - Tap at offset `+2`.
485    ///
486    /// # Returns
487    ///
488    /// - `[f32; 3]` - Filtered linear HDR bloom RGB triple.
489    #[inline(always)]
490    #[must_use]
491    fn blur_bloom_tap5(
492        c0: [f32; 3],
493        c1: [f32; 3],
494        c2: [f32; 3],
495        c3: [f32; 3],
496        c4: [f32; 3],
497    ) -> [f32; 3] {
498        [
499            (c0[0] + c4[0]).mul_add(0.08, (c1[0] + c3[0]).mul_add(0.22, c2[0] * 0.40)),
500            (c0[1] + c4[1]).mul_add(0.08, (c1[1] + c3[1]).mul_add(0.22, c2[1] * 0.40)),
501            (c0[2] + c4[2]).mul_add(0.08, (c1[2] + c3[2]).mul_add(0.22, c2[2] * 0.40)),
502        ]
503    }
504
505    /// Runs the horizontal 5-tap bloom blur pass over a band of rows with branchless interior taps.
506    ///
507    /// # Arguments
508    ///
509    /// - `usize` - Quarter-res bloom width `bw` (`>= 3`).
510    /// - `&[[f32; 3]]` - Full source bloom buffer.
511    /// - `usize` - Inclusive starting row `y_start`.
512    /// - `&mut [[f32; 3]]` - Disjoint mutable output row band.
513    fn blur_bloom_horiz_band(
514        bw: usize,
515        src: &[[f32; 3]],
516        y_start: usize,
517        dst_band: &mut [[f32; 3]],
518    ) {
519        let band_rows: usize = dst_band.len() / bw;
520        let max_x: usize = bw - 1;
521        for local_y in 0..band_rows {
522            let src_row_off: usize = (y_start + local_y) * bw;
523            let dst_row_off: usize = local_y * bw;
524            let src_row: &[[f32; 3]] = &src[src_row_off..(src_row_off + bw)];
525            let dst_row: &mut [[f32; 3]] = &mut dst_band[dst_row_off..(dst_row_off + bw)];
526            if bw >= 5 {
527                dst_row[0] = Self::blur_bloom_tap5(
528                    src_row[0], src_row[0], src_row[0], src_row[1], src_row[2],
529                );
530                dst_row[1] = Self::blur_bloom_tap5(
531                    src_row[0], src_row[0], src_row[1], src_row[2], src_row[3],
532                );
533                for (win, out) in src_row.windows(5).zip(dst_row[2..(bw - 2)].iter_mut()) {
534                    *out = Self::blur_bloom_tap5(win[0], win[1], win[2], win[3], win[4]);
535                }
536                dst_row[bw - 2] = Self::blur_bloom_tap5(
537                    src_row[bw - 4],
538                    src_row[bw - 3],
539                    src_row[bw - 2],
540                    src_row[max_x],
541                    src_row[max_x],
542                );
543                dst_row[max_x] = Self::blur_bloom_tap5(
544                    src_row[bw - 3],
545                    src_row[bw - 2],
546                    src_row[max_x],
547                    src_row[max_x],
548                    src_row[max_x],
549                );
550            } else {
551                for x in 0..bw {
552                    dst_row[x] = Self::blur_bloom_tap5(
553                        src_row[x.saturating_sub(2)],
554                        src_row[x.saturating_sub(1)],
555                        src_row[x],
556                        src_row[(x + 1).min(max_x)],
557                        src_row[(x + 2).min(max_x)],
558                    );
559                }
560            }
561        }
562    }
563
564    /// Runs the vertical 5-tap bloom blur pass over a band of rows with row-hoisted slices.
565    ///
566    /// # Arguments
567    ///
568    /// - `usize` - Quarter-res bloom width `bw`.
569    /// - `usize` - Quarter-res bloom height `bh`.
570    /// - `&[[f32; 3]]` - Full horizontally blurred bloom buffer.
571    /// - `usize` - Inclusive starting row `y_start`.
572    /// - `&mut [[f32; 3]]` - Disjoint mutable output row band.
573    fn blur_bloom_vert_band(
574        bw: usize,
575        bh: usize,
576        src: &[[f32; 3]],
577        y_start: usize,
578        dst_band: &mut [[f32; 3]],
579    ) {
580        let band_rows: usize = dst_band.len() / bw;
581        let max_y: usize = bh - 1;
582        for local_y in 0..band_rows {
583            let y: usize = y_start + local_y;
584            let o0: usize = y.saturating_sub(2) * bw;
585            let o1: usize = y.saturating_sub(1) * bw;
586            let o2: usize = y * bw;
587            let o3: usize = (y + 1).min(max_y) * bw;
588            let o4: usize = (y + 2).min(max_y) * bw;
589            let r0: &[[f32; 3]] = &src[o0..(o0 + bw)];
590            let r1: &[[f32; 3]] = &src[o1..(o1 + bw)];
591            let r2: &[[f32; 3]] = &src[o2..(o2 + bw)];
592            let r3: &[[f32; 3]] = &src[o3..(o3 + bw)];
593            let r4: &[[f32; 3]] = &src[o4..(o4 + bw)];
594            let dst_off: usize = local_y * bw;
595            let dst_row: &mut [[f32; 3]] = &mut dst_band[dst_off..(dst_off + bw)];
596            for x in 0..bw {
597                dst_row[x] = Self::blur_bloom_tap5(r0[x], r1[x], r2[x], r3[x], r4[x]);
598            }
599        }
600    }
601
602    /// Runs a parallel branchless 5-tap separable Gaussian blur over the quarter-resolution HDR bloom buffer.
603    ///
604    /// # Arguments
605    ///
606    /// - `usize` - Quarter-res bloom width.
607    /// - `usize` - Quarter-res bloom height.
608    /// - `&mut [[f32; 3]]` - Input bloom buffer (receives final blurred output).
609    /// - `&mut [[f32; 3]]` - Intermediate horizontal scratch buffer.
610    fn blur_bloom_separable(bw: usize, bh: usize, buf_a: &mut [[f32; 3]], buf_b: &mut [[f32; 3]]) {
611        if bw < 3 || bh < 3 {
612            return;
613        }
614        let min_len: usize = bw * bh;
615        if buf_a.len() < min_len || buf_b.len() < min_len {
616            return;
617        }
618        if min_len >= 8_192 && bh >= 16 {
619            let grain: usize = (bh / 16).clamp(8, 24);
620            let src_a: &[[f32; 3]] = &buf_a[..min_len];
621            let dst_b_base: usize = buf_b.as_mut_ptr() as usize;
622            parallel_for_ranges(bh, grain, |y0: usize, y1: usize| {
623                // SAFETY: `parallel_for_ranges` partitions `0..bh` into disjoint row bands within `buf_b[..min_len]`.
624                let out_band: &mut [[f32; 3]] = unsafe {
625                    from_raw_parts_mut((dst_b_base as *mut [f32; 3]).add(y0 * bw), (y1 - y0) * bw)
626                };
627                Self::blur_bloom_horiz_band(bw, src_a, y0, out_band);
628            });
629            let src_b: &[[f32; 3]] = &buf_b[..min_len];
630            let dst_a_base: usize = buf_a.as_mut_ptr() as usize;
631            parallel_for_ranges(bh, grain, |y0: usize, y1: usize| {
632                // SAFETY: `parallel_for_ranges` partitions `0..bh` into disjoint row bands within `buf_a[..min_len]`.
633                let out_band: &mut [[f32; 3]] = unsafe {
634                    from_raw_parts_mut((dst_a_base as *mut [f32; 3]).add(y0 * bw), (y1 - y0) * bw)
635                };
636                Self::blur_bloom_vert_band(bw, bh, src_b, y0, out_band);
637            });
638        } else {
639            Self::blur_bloom_horiz_band(bw, &buf_a[..min_len], 0, &mut buf_b[..min_len]);
640            Self::blur_bloom_vert_band(bw, bh, &buf_b[..min_len], 0, &mut buf_a[..min_len]);
641        }
642    }
643
644    /// Shades a horizontal pixel band with Cook-Torrance GGX PBR, borrowed probe bilateral upsampling, incremental grid stepping, fused specular math, and HDR bloom extraction.
645    ///
646    /// # Arguments
647    ///
648    /// - `&DeferredFrameCtx` - Shared per-frame camera, sun, and RT settings.
649    /// - `ShadeBandInputs<'_>` - Read-only scene, G-Buffer, probe, static BVH, and dynamic BVH slices.
650    /// - `(usize, &mut [u8], &mut [u8], &mut [[f32; 3]])` - `(py_start, color band, luma band, bloom band)`.
651    ///
652    /// # Returns
653    ///
654    /// - `(usize, bool)` - `(edge_rays_traced, band_emitted_nonzero_bloom)`.
655    fn shade_deferred_band(
656        fctx: &DeferredFrameCtx,
657        inputs: ShadeBandInputs<'_>,
658        outputs: (usize, &mut [u8], &mut [u8], &mut [[f32; 3]]),
659    ) -> (usize, bool) {
660        let (depth_buf, g_tri_idx, shaded_tris, probes, static_bvh, dynamic_bvh): ShadeBandInputs<
661            '_,
662        > = inputs;
663        let (py_start, color_band, luma_band, bloom_band): (
664            usize,
665            &mut [u8],
666            &mut [u8],
667            &mut [[f32; 3]],
668        ) = outputs;
669        let w: usize = fctx.w;
670        let gw: usize = fctx.gw;
671        let gh: usize = fctx.gh;
672        let gw_max: usize = gw.saturating_sub(1);
673        let gh_max: usize = gh.saturating_sub(1);
674        let bw: usize = fctx.bw;
675        let rt_step: usize = fctx.rt_step.max(1);
676        let step_f: f32 = rt_step as f32;
677        let inv_step: f32 = 1.0 / step_f;
678        let step2_i32: i32 = (rt_step * 2) as i32;
679        let init_sub_x: i32 = 1 - (rt_step as i32);
680        let inv_step2: f32 = 0.5 * inv_step;
681        let mut fx_lut: [f32; 16] = [0.0; 16];
682        let lut_len: usize = (rt_step * 2).min(16);
683        for (idx, slot) in fx_lut.iter_mut().take(lut_len).enumerate() {
684            *slot = (idx as f32) * inv_step2;
685        }
686        let sun_dir: Vec3 = fctx.sun.get_direction();
687        let inv_sun: Vec3 = fctx.inv_sun_dir;
688        let sun_col: Vec3 = fctx.sun.get_color();
689        let sky_horizon: Vec3 = fctx.sun.get_sky_horizon();
690        let sky_zenith: Vec3 = fctx.sun.get_sky_zenith();
691        let rt_active: bool = fctx.rt_mode != RayTracingMode::Off && !probes.is_empty();
692        let gi_active: bool = fctx.rt_mode == RayTracingMode::FullPathTracedGi && rt_active;
693        let band_rows: usize = luma_band.len() / w.max(1);
694        let ray_dx: Vec3 = fctx.cam_right_scaled.scale(2.0 * fctx.inv_w_f);
695        let ndc_x0: f32 = fctx.inv_w_f - 1.0;
696        let mut edge_rays: usize = 0;
697        let mut bloom_emitted: bool = false;
698        let mut static_shadow_cache: u32 = u32::MAX;
699        let mut dynamic_shadow_cache: u32 = u32::MAX;
700        for local_y in 0..band_rows {
701            let py: usize = py_start + local_y;
702            let row_off: usize = py * w;
703            let out_row_luma: usize = local_y * w;
704            let out_row_rgba: usize = out_row_luma * 4;
705            let write_bloom_row: bool = fctx.bloom_on && (py & 3) == 0 && bw > 0;
706            let bloom_row_off: usize = if write_bloom_row {
707                (local_y / 4) * bw
708            } else {
709                0
710            };
711            let ndc_y: f32 = 1.0 - 2.0 * (((py as f32) + 0.5) * fctx.inv_h_f);
712            let row_base_dir: Vec3 = fctx.cam_fwd.add(fctx.cam_up_scaled.scale(ndc_y));
713            let base_up: f32 = row_base_dir.get_y().clamp(0.0, 1.0);
714            let base_sky: Vec3 = sky_horizon
715                .lerp(sky_zenith, base_up.sqrt())
716                .add(sky_horizon.scale((1.0 - base_up) * (1.0 - base_up) * 0.14));
717            let base_sky_rgba: [u8; 4] = base_sky.scale(fctx.exposure_scale).to_aces_rgba8();
718            let base_sky_luma: u8 = (((base_sky_rgba[0] as u32) * 77
719                + (base_sky_rgba[1] as u32) * 150
720                + (base_sky_rgba[2] as u32) * 29)
721                >> 8) as u8;
722            let base_sky_bloom: [f32; 3] = [
723                (base_sky.get_x() - 1.15).max(0.0),
724                (base_sky.get_y() - 1.15).max(0.0),
725                (base_sky.get_z() - 1.15).max(0.0),
726            ];
727            let base_sky_bloom_rg: bool = base_sky_bloom[0] > 0.0 || base_sky_bloom[1] > 0.0;
728            let base_sky_bloom_on: bool = base_sky_bloom_rg || base_sky_bloom[2] > 0.0;
729            let row_has_sun: bool = row_base_dir.normalize().dot(sun_dir) >= 0.45;
730            let gy_f: f32 = (((py as f32) + 0.5) * inv_step - 0.5).clamp(0.0, gh_max as f32);
731            let gy0: usize = (gy_f as usize).min(gh_max);
732            let gy1: usize = (gy0 + 1).min(gh_max);
733            let fy: f32 = gy_f - (gy0 as f32);
734            let wy0: f32 = 1.0 - fy;
735            let wy1: f32 = fy;
736            let p_row0: usize = gy0 * gw;
737            let p_row1: usize = gy1 * gw;
738            let mut raw_ray: Vec3 = row_base_dir.add(fctx.cam_right_scaled.scale(ndc_x0));
739            let mut gx_cur: usize = 0;
740            let mut sub_x: i32 = init_sub_x;
741            for px in 0..w {
742                let pix_idx: usize = row_off + px;
743                let tid: u32 = g_tri_idx[pix_idx];
744                let cidx: usize = out_row_rgba + px * 4;
745                if tid == u32::MAX {
746                    let (rgba, luma, sky_bloom, has_sky_bloom): ([u8; 4], u8, [f32; 3], bool) =
747                        if row_has_sun {
748                            let dir: Vec3 = raw_ray.normalize();
749                            let sdot: f32 = dir.dot(sun_dir).max(0.0);
750                            if sdot > 0.72 {
751                                let mut col: Vec3 = base_sky;
752                                if sdot > 0.992 {
753                                    let disk: f32 = ((sdot - 0.992) / 0.008).clamp(0.0, 1.0);
754                                    col = col.add(sun_col.scale(disk * 3.8 + 0.55));
755                                } else {
756                                    let h1: f32 = ((sdot - 0.72) / 0.28).clamp(0.0, 1.0);
757                                    let h2: f32 = h1 * h1;
758                                    col = col.add(sun_col.scale(h2 * h2 * 0.58 + h2 * 0.08));
759                                }
760                                let exposed: Vec3 = col.scale(fctx.exposure_scale);
761                                let px_rgba: [u8; 4] = exposed.to_aces_rgba8();
762                                let px_luma: u8 = (((px_rgba[0] as u32) * 77
763                                    + (px_rgba[1] as u32) * 150
764                                    + (px_rgba[2] as u32) * 29)
765                                    >> 8) as u8;
766                                let er: f32 = (exposed.get_x() - 1.15).max(0.0);
767                                let eg: f32 = (exposed.get_y() - 1.15).max(0.0);
768                                let eb: f32 = (exposed.get_z() - 1.15).max(0.0);
769                                let rg_pos: bool = er > 0.0 || eg > 0.0;
770                                (px_rgba, px_luma, [er, eg, eb], rg_pos || eb > 0.0)
771                            } else {
772                                (
773                                    base_sky_rgba,
774                                    base_sky_luma,
775                                    base_sky_bloom,
776                                    base_sky_bloom_on,
777                                )
778                            }
779                        } else {
780                            (
781                                base_sky_rgba,
782                                base_sky_luma,
783                                base_sky_bloom,
784                                base_sky_bloom_on,
785                            )
786                        };
787                    if write_bloom_row && (px & 3) == 0 {
788                        let bidx: usize = bloom_row_off + (px >> 2);
789                        if bidx < bloom_band.len() {
790                            bloom_band[bidx] = sky_bloom;
791                            if has_sky_bloom {
792                                bloom_emitted = true;
793                            }
794                        }
795                    }
796                    color_band[cidx] = rgba[0];
797                    color_band[cidx + 1] = rgba[1];
798                    color_band[cidx + 2] = rgba[2];
799                    color_band[cidx + 3] = 255;
800                    luma_band[out_row_luma + px] = luma;
801                    raw_ray = raw_ray.add(ray_dx);
802                    sub_x += 2;
803                    if sub_x >= step2_i32 {
804                        sub_x -= step2_i32;
805                        gx_cur += 1;
806                    }
807                    continue;
808                }
809                let tri: &GShadeTri = &shaded_tris[tid as usize];
810                let depth: f32 = 1.0 / depth_buf[pix_idx].max(1e-6);
811                let world_p_px: Vec3 = fctx.cam_pos.add(raw_ray.scale(depth));
812                let mut shadow: f32 = 1.0;
813                let mut refl: Vec3 = sky_horizon;
814                let mut gi_col: Vec3 = Vec3::zero();
815                let mut ao: f32 = 1.0;
816                if rt_active {
817                    let (gx0, gx1, fx): (usize, usize, f32) = if sub_x <= 0 && gx_cur == 0 {
818                        (0, gw_max.min(1), 0.0)
819                    } else if gx_cur >= gw_max {
820                        (gw_max, gw_max, 0.0)
821                    } else {
822                        let lut_idx: usize = (sub_x as usize).min(15);
823                        (gx_cur, gx_cur + 1, fx_lut[lut_idx])
824                    };
825                    let wx0: f32 = 1.0 - fx;
826                    let wx1: f32 = fx;
827                    let taps: [(&RtProbeSample, f32); 4] = [
828                        (&probes[p_row0 + gx0], wx0 * wy0),
829                        (&probes[p_row0 + gx1], wx1 * wy0),
830                        (&probes[p_row1 + gx0], wx0 * wy1),
831                        (&probes[p_row1 + gx1], wx1 * wy1),
832                    ];
833                    let snx: f32 = tri.shade_n.get_x();
834                    let sny: f32 = tri.shade_n.get_y();
835                    let snz: f32 = tri.shade_n.get_z();
836                    let do_refl_tri: bool = tri.do_refl;
837                    let mut w_sum: f32 = 0.0;
838                    let mut s_sum: f32 = 0.0;
839                    let mut s_min: f32 = 2.0;
840                    let mut s_max: f32 = -1.0;
841                    let mut rr_sum: f32 = 0.0;
842                    let mut rg_sum: f32 = 0.0;
843                    let mut rb_sum: f32 = 0.0;
844                    let mut gr_sum: f32 = 0.0;
845                    let mut gg_sum: f32 = 0.0;
846                    let mut gb_sum: f32 = 0.0;
847                    let mut ao_sum: f32 = 0.0;
848                    let mut valid_matches: u32 = 0;
849                    for (pr, bw_tap) in taps.into_iter() {
850                        if pr.valid == 0 {
851                            continue;
852                        }
853                        let ndot: f32 = snx.mul_add(pr.nx, sny.mul_add(pr.ny, snz * pr.nz));
854                        if ndot < 0.78 {
855                            continue;
856                        }
857                        let depth_tol: f32 = if ndot > 0.95 {
858                            depth.mul_add(0.58, 2.4)
859                        } else {
860                            depth.mul_add(0.20, 0.75)
861                        };
862                        let d_diff: f32 = (depth - pr.depth).abs();
863                        if d_diff > depth_tol {
864                            continue;
865                        }
866                        let wt: f32 = bw_tap.mul_add(1.0 - d_diff / depth_tol, 1e-4);
867                        w_sum += wt;
868                        s_sum = pr.shadow.mul_add(wt, s_sum);
869                        s_min = s_min.min(pr.shadow);
870                        s_max = s_max.max(pr.shadow);
871                        if do_refl_tri {
872                            rr_sum = pr.refl_r.mul_add(wt, rr_sum);
873                            rg_sum = pr.refl_g.mul_add(wt, rg_sum);
874                            rb_sum = pr.refl_b.mul_add(wt, rb_sum);
875                        }
876                        if gi_active {
877                            gr_sum = pr.gi_r.mul_add(wt, gr_sum);
878                            gg_sum = pr.gi_g.mul_add(wt, gg_sum);
879                            gb_sum = pr.gi_b.mul_add(wt, gb_sum);
880                            ao_sum = pr.ao.mul_add(wt, ao_sum);
881                        }
882                        valid_matches += 1;
883                    }
884                    let inv_ws: f32 = if w_sum > 1e-5 { 1.0 / w_sum } else { 0.0 };
885                    let need_exact_shadow: bool = tri.n_dot_l > 0.02
886                        && depth < 42.0
887                        && (valid_matches == 0 || (!gi_active && (s_max - s_min) > 0.12));
888                    if need_exact_shadow {
889                        let origin: Vec3 = world_p_px.add(tri.shade_n.scale(0.08));
890                        edge_rays += 1;
891                        shadow = if World3D::trace_any_shadow_split(
892                            (static_bvh, dynamic_bvh),
893                            (origin, sun_dir, inv_sun),
894                            (0.05, 140.0),
895                            (&mut static_shadow_cache, &mut dynamic_shadow_cache),
896                        ) {
897                            0.22
898                        } else {
899                            1.0
900                        };
901                    } else if valid_matches > 0 {
902                        shadow = s_sum * inv_ws;
903                    }
904                    if do_refl_tri {
905                        if valid_matches > 0 {
906                            refl = Vec3::new(rr_sum * inv_ws, rg_sum * inv_ws, rb_sum * inv_ws);
907                        } else if depth < 32.0 {
908                            let origin: Vec3 = world_p_px.add(tri.shade_n.scale(0.08));
909                            let refl_dir: Vec3 =
910                                raw_ray.normalize().reflect(tri.shade_n).normalize();
911                            let inv_refl: Vec3 = Ray3D::safe_inv_vec(refl_dir);
912                            edge_rays += 1;
913                            refl = match World3D::trace_closest_split(
914                                (static_bvh, dynamic_bvh),
915                                (origin, refl_dir, inv_refl),
916                                (0.08, 96.0),
917                            ) {
918                                Some((_, is_dyn, hit_idx)) => {
919                                    let hit_bvh: &Bvh3D =
920                                        if is_dyn { dynamic_bvh } else { static_bvh };
921                                    Self::shade_bvh_hit(hit_bvh, hit_idx, &fctx.sun, gi_active)
922                                }
923                                None => Self::sample_sky(refl_dir, &fctx.sun),
924                            };
925                        } else {
926                            let refl_dir: Vec3 =
927                                raw_ray.normalize().reflect(tri.shade_n).normalize();
928                            refl = Self::sample_sky(refl_dir, &fctx.sun);
929                        }
930                    }
931                    if gi_active && valid_matches > 0 {
932                        gi_col = Vec3::new(gr_sum * inv_ws, gg_sum * inv_ws, gb_sum * inv_ws);
933                        ao = ao_sum * inv_ws;
934                    }
935                }
936                let view_in: Vec3 = raw_ray.normalize();
937                let view_to_cam: Vec3 = view_in.scale(-1.0);
938                let ndv_raw: f32 = tri.shade_n.dot(view_to_cam);
939                let ndv: f32 = ndv_raw.clamp(0.02, 1.0);
940                let f_om: f32 = 1.0 - ndv;
941                let f_om2: f32 = f_om * f_om;
942                let fresnel_t: f32 = f_om2 * f_om2 * f_om;
943                let v_dot_l: f32 = view_to_cam.dot(sun_dir);
944                let spec_col: Vec3 = if tri.n_dot_l > 0.0 {
945                    let ndh_unnorm: f32 = (tri.n_dot_l + ndv_raw).max(0.0);
946                    let h_len_sq: f32 = 2.0_f32.mul_add(v_dot_l, 2.0).max(1e-6);
947                    let ndh_sq: f32 = (ndh_unnorm * ndh_unnorm) / h_len_sq;
948                    let ggx_denom: f32 = ndh_sq.mul_add(tri.alpha2 - 1.0, 1.0);
949                    let spec_num: f32 = (0.25 * tri.alpha2 * tri.n_dot_l) * shadow;
950                    let ggx_term: f32 = (ggx_denom * ggx_denom).mul_add(PI, 1e-4);
951                    let vis_den: f32 = ndv.mul_add(tri.n_dot_l.max(0.06), 0.08);
952                    let spec_scalar: f32 = (spec_num / (ggx_term * vis_den)).min(4.5);
953                    let fresnel_rgb: Vec3 =
954                        tri.f0.add(Vec3::splat(1.0).sub(tri.f0).scale(fresnel_t));
955                    fresnel_rgb.mul(sun_col.scale(spec_scalar))
956                } else {
957                    Vec3::zero()
958                };
959                let mut surf_base: Vec3 = tri.mat_base;
960                let mut surf_emissive: Vec3 = tri.mat_emissive;
961                let mut surf_refl: f32 = tri.mat_refl;
962                let world_px_size: f32 = depth * fctx.inv_h_f * 1.85;
963                match tri.surface_detail {
964                    SurfaceDetailMode::ArchitecturalFacade
965                        if tri.shade_n.get_y().abs() < 0.25
966                            && world_p_px.get_y() > 2.4
967                            && surf_emissive.length_sq() < 0.02 =>
968                    {
969                        let u_coord: f32 = if tri.shade_n.get_x().abs() > 0.5 {
970                            world_p_px.get_z()
971                        } else {
972                            world_p_px.get_x()
973                        };
974                        let fx_win: f32 = (u_coord * 0.45).rem_euclid(1.0);
975                        let fy_win: f32 = (world_p_px.get_y() * 0.32).rem_euclid(1.0);
976                        let aa_u: f32 = (world_px_size * 0.45).clamp(0.02, 0.34);
977                        let aa_v: f32 = (world_px_size * 0.32).clamp(0.02, 0.34);
978                        let pane_u: f32 = smoothstep_f32(0.16 - aa_u, 0.16 + aa_u, fx_win)
979                            * (1.0 - smoothstep_f32(0.84 - aa_u, 0.84 + aa_u, fx_win));
980                        let pane_v: f32 = smoothstep_f32(0.20 - aa_v, 0.20 + aa_v, fy_win)
981                            * (1.0 - smoothstep_f32(0.82 - aa_v, 0.82 + aa_v, fy_win));
982                        let dist_fade: f32 = 1.0 - smoothstep_f32(48.0, 125.0, depth);
983                        let pane_w: f32 = (pane_u * pane_v * dist_fade).clamp(0.0, 1.0);
984                        let wall_base: Vec3 = surf_base.scale(0.84);
985                        if pane_w > 0.01 {
986                            let cell_x: i32 = (u_coord * 0.45).floor() as i32;
987                            let cell_y: i32 = (world_p_px.get_y() * 0.32).floor() as i32;
988                            let h_bits: u32 = ((cell_x.wrapping_mul(73856093))
989                                ^ (cell_y.wrapping_mul(19349663)))
990                                as u32;
991                            let lit_bucket: u32 = h_bits % 11;
992                            if lit_bucket == 0 {
993                                surf_base = wall_base.lerp(surf_base, pane_w);
994                                surf_emissive =
995                                    surf_emissive.add(Vec3::new(1.15, 0.92, 0.48).scale(pane_w));
996                            } else if lit_bucket == 1 {
997                                surf_base = wall_base.lerp(surf_base, pane_w);
998                                surf_emissive =
999                                    surf_emissive.add(Vec3::new(0.32, 0.85, 1.25).scale(pane_w));
1000                            } else {
1001                                surf_base = wall_base.lerp(surf_base.scale(0.62), pane_w);
1002                                surf_refl = (surf_refl + 0.22 * pane_w).min(0.95);
1003                            }
1004                        } else {
1005                            surf_base = wall_base;
1006                        }
1007                    }
1008                    SurfaceDetailMode::RoadSurface
1009                        if tri.shade_n.get_y() > 0.92 && world_p_px.get_y().abs() < 0.15 =>
1010                    {
1011                        let abs_x: f32 = world_p_px.get_x().abs();
1012                        let edge_aa: f32 = (world_px_size * 1.4).clamp(0.05, 0.42);
1013                        let curb_w: f32 = smoothstep_f32(9.9 - edge_aa, 9.9 + edge_aa, abs_x);
1014                        let walk_w: f32 = smoothstep_f32(10.6 - edge_aa, 10.6 + edge_aa, abs_x);
1015                        let micro_fade: f32 = 1.0 - smoothstep_f32(18.0, 58.0, depth);
1016                        let micro: f32 = (((world_p_px.get_x() * 3.1).floor() as i32
1017                            ^ (world_p_px.get_z() * 3.1).floor() as i32)
1018                            & 3) as f32;
1019                        let road_col: Vec3 =
1020                            surf_base.scale(1.0 + (micro * 0.03 - 0.045) * micro_fade);
1021                        let curb_col: Vec3 = Vec3::new(0.55, 0.57, 0.60);
1022                        let walk_col: Vec3 = Vec3::new(0.26, 0.28, 0.32);
1023                        surf_base = road_col.lerp(curb_col, curb_w).lerp(walk_col, walk_w);
1024                        surf_refl = surf_refl * (1.0 - curb_w)
1025                            + 0.18 * curb_w * (1.0 - walk_w)
1026                            + 0.12 * walk_w;
1027                    }
1028                    _ => {}
1029                }
1030                let kd_scale: f32 = (tri.diffuse_scale * (1.0 - fresnel_t * 0.55)).max(0.08);
1031                let direct: Vec3 = sun_col.scale(tri.n_dot_l * shadow * kd_scale);
1032                let indirect: Vec3 = tri.ambient_sky.scale(0.44 * ao).add(gi_col);
1033                let mut radiance: Vec3 = surf_base
1034                    .mul(direct.add(indirect))
1035                    .add(spec_col)
1036                    .add(surf_emissive);
1037                if tri.do_refl {
1038                    let refl_fresnel: f32 =
1039                        (0.18 + 0.82 * fresnel_t + tri.metallic * 0.25).clamp(0.18, 0.95);
1040                    let refl_blend: f32 = (surf_refl * refl_fresnel).clamp(0.0, 0.82);
1041                    radiance = radiance.lerp(refl, refl_blend);
1042                }
1043                if fctx.fog_on {
1044                    let height_atten: f32 =
1045                        (1.0 / (1.0 + world_p_px.get_y().max(0.0) * 0.045)).clamp(0.32, 1.0);
1046                    let fd: f32 = depth * fctx.inv_fog_dist * height_atten;
1047                    let fog_t: f32 = (fd / (1.0 + fd)).clamp(0.0, 0.85);
1048                    let sun_align: f32 = (-v_dot_l).max(0.0);
1049                    let sa2: f32 = sun_align * sun_align;
1050                    let shaft: f32 = sa2 * sa2 * fog_t * (0.35 + 0.65 * shadow);
1051                    let fog_col: Vec3 = sky_horizon.add(sun_col.scale(shaft * 0.55));
1052                    radiance = radiance.lerp(fog_col, fog_t);
1053                }
1054                let exposed: Vec3 = radiance.scale(fctx.exposure_scale);
1055                if write_bloom_row && (px & 3) == 0 {
1056                    let bidx: usize = bloom_row_off + (px >> 2);
1057                    if bidx < bloom_band.len() {
1058                        let er: f32 = (exposed.get_x() - 1.05).max(0.0);
1059                        let eg: f32 = (exposed.get_y() - 1.05).max(0.0);
1060                        let eb: f32 = (exposed.get_z() - 1.05).max(0.0);
1061                        bloom_band[bidx] = [er, eg, eb];
1062                        let rg_pos: bool = er > 0.0 || eg > 0.0;
1063                        if rg_pos || eb > 0.0 {
1064                            bloom_emitted = true;
1065                        }
1066                    }
1067                }
1068                let rgba: [u8; 4] = exposed.to_aces_rgba8();
1069                color_band[cidx] = rgba[0];
1070                color_band[cidx + 1] = rgba[1];
1071                color_band[cidx + 2] = rgba[2];
1072                color_band[cidx + 3] = 255;
1073                luma_band[out_row_luma + px] =
1074                    (((rgba[0] as u32) * 77 + (rgba[1] as u32) * 150 + (rgba[2] as u32) * 29) >> 8)
1075                        as u8;
1076                raw_ray = raw_ray.add(ray_dx);
1077                sub_x += 2;
1078                if sub_x >= step2_i32 {
1079                    sub_x -= step2_i32;
1080                    gx_cur += 1;
1081                }
1082            }
1083        }
1084        (edge_rays, bloom_emitted)
1085    }
1086
1087    /// Samples the quarter-resolution HDR bloom buffer using row-hoisted coordinates for active bloom tiles.
1088    ///
1089    /// # Arguments
1090    ///
1091    /// - `&[[f32; 3]]` - Blurred quarter-resolution HDR bloom slice.
1092    /// - `(usize, usize, usize)` - Row offsets and max X `(bloom_r0, bloom_r1, bw_max)`.
1093    /// - `(usize, f32, f32)` - Tile column and fractional weights `(bx0, tx, ty)`.
1094    ///
1095    /// # Returns
1096    ///
1097    /// - `[f32; 3]` - Bilinearly filtered bloom RGB radiance.
1098    #[inline(always)]
1099    #[must_use]
1100    fn sample_bloom_bilinear_row(
1101        bloom: &[[f32; 3]],
1102        row_info: (usize, usize, usize),
1103        tap: (usize, f32, f32),
1104    ) -> [f32; 3] {
1105        let (r0, r1, bw_max): (usize, usize, usize) = row_info;
1106        let (bx0, tx, ty): (usize, f32, f32) = tap;
1107        let bx1: usize = (bx0 + 1).min(bw_max);
1108        let c00: [f32; 3] = bloom[r0 + bx0];
1109        let c10: [f32; 3] = bloom[r0 + bx1];
1110        let c01: [f32; 3] = bloom[r1 + bx0];
1111        let c11: [f32; 3] = bloom[r1 + bx1];
1112        let omt_x: f32 = 1.0 - tx;
1113        let omt_y: f32 = 1.0 - ty;
1114        let w00: f32 = omt_x * omt_y;
1115        let w10: f32 = tx * omt_y;
1116        let w01: f32 = omt_x * ty;
1117        let w11: f32 = tx * ty;
1118        [
1119            c00[0].mul_add(w00, c10[0].mul_add(w10, c01[0].mul_add(w01, c11[0] * w11))),
1120            c00[1].mul_add(w00, c10[1].mul_add(w10, c01[1].mul_add(w01, c11[1] * w11))),
1121            c00[2].mul_add(w00, c10[2].mul_add(w10, c01[2].mul_add(w01, c11[2] * w11))),
1122        ]
1123    }
1124
1125    /// Populates `bloom_tile_active` (`1` where any bilinear corner contributes `>= 1` RGB LSB) and returns whether any tile is active.
1126    ///
1127    /// # Arguments
1128    ///
1129    /// - `usize` - Quarter-resolution bloom grid width.
1130    /// - `usize` - Quarter-resolution bloom grid height.
1131    /// - `&[[f32; 3]]` - Blurred quarter-resolution HDR bloom buffer.
1132    /// - `&mut [u8]` - Output tile-activity mask slice (`len >= bw * bh`).
1133    ///
1134    /// # Returns
1135    ///
1136    /// - `bool` - `true` when at least one bloom tile requires sampling in `post_process_band`.
1137    #[must_use]
1138    fn build_bloom_tile_mask(
1139        bw: usize,
1140        bh: usize,
1141        bloom: &[[f32; 3]],
1142        tile_active: &mut [u8],
1143    ) -> bool {
1144        let len: usize = bw * bh;
1145        if len == 0 || bloom.len() < len || tile_active.len() < len {
1146            return false;
1147        }
1148        let bw_max: usize = bw - 1;
1149        let bh_max: usize = bh - 1;
1150        let mut any_active: bool = false;
1151        for by in 0..bh {
1152            let r0: usize = by * bw;
1153            let r1: usize = (by + 1).min(bh_max) * bw;
1154            for bx in 0..bw {
1155                let bx1: usize = (bx + 1).min(bw_max);
1156                let c00: [f32; 3] = bloom[r0 + bx];
1157                let c10: [f32; 3] = bloom[r0 + bx1];
1158                let c01: [f32; 3] = bloom[r1 + bx];
1159                let c11: [f32; 3] = bloom[r1 + bx1];
1160                let max_r: f32 = c00[0].max(c10[0]).max(c01[0]).max(c11[0]);
1161                let max_g: f32 = c00[1].max(c10[1]).max(c01[1]).max(c11[1]);
1162                let max_b: f32 = c00[2].max(c10[2]).max(c01[2]).max(c11[2]);
1163                let active: bool = max_r.max(max_g).max(max_b) >= 0.015;
1164                tile_active[r0 + bx] = u8::from(active);
1165                if active {
1166                    any_active = true;
1167                }
1168            }
1169        }
1170        any_active
1171    }
1172
1173    /// Fused post-process pass applying Geometry-Aware FXAA 3.11 + 8-step Morphological Silhouette Edge-Walking AA, 9-tap variance-clamped TAA, and active-tile bilinear HDR Bloom directly into uninitialized output memory.
1174    ///
1175    /// # Arguments
1176    ///
1177    /// - `(usize, usize, usize, usize)` - Dimensions `(w, h, bloom_w, bloom_h)`.
1178    /// - `PostProcessInputs<'_>` - Read-only `(color_src, luma, g_tri_idx, bloom, bloom_tile_active, taa_history)`.
1179    /// - `(bool, bool, bool)` - Flags `(use_fxaa, use_taa, use_bloom)`.
1180    /// - `(usize, *mut u8, usize)` - `(y_start, writable band RGBA base pointer, band row count)`.
1181    unsafe fn post_process_band(
1182        dims: (usize, usize, usize, usize),
1183        inputs: PostProcessInputs<'_>,
1184        flags: (bool, bool, bool),
1185        band: (usize, *mut u8, usize),
1186    ) {
1187        let (w, h, bw, bh): (usize, usize, usize, usize) = dims;
1188        let (src, luma, g_tri_idx, bloom, bloom_active, history): PostProcessInputs<'_> = inputs;
1189        let (use_fxaa, use_taa, use_bloom): (bool, bool, bool) = flags;
1190        let (y_start, dst_ptr, band_rows): (usize, *mut u8, usize) = band;
1191        let row_bytes: usize = w * 4;
1192        let bloom_len: usize = bw * bh;
1193        let has_bloom: bool = use_bloom
1194            && bloom_len > 0
1195            && bloom.len() >= bloom_len
1196            && bloom_active.len() >= bloom_len;
1197        let bw_max: usize = bw.saturating_sub(1);
1198        let bh_max: usize = bh.saturating_sub(1);
1199        let has_taa: bool = use_taa && history.len() == src.len();
1200        let w_i32: i32 = w as i32;
1201        let h_i32: i32 = h as i32;
1202        for local_y in 0..band_rows {
1203            let y: usize = y_start + local_y;
1204            let src_off: usize = y * row_bytes;
1205            let dst_off: usize = local_y * row_bytes;
1206            if !use_fxaa && !has_bloom && !has_taa {
1207                // SAFETY: Caller guarantees `dst_ptr` covers `band_rows * row_bytes` disjoint writable bytes,
1208                // and `src_off + row_bytes <= src.len()` since `y < h`.
1209                unsafe {
1210                    dst_ptr
1211                        .add(dst_off)
1212                        .copy_from_nonoverlapping(src.as_ptr().add(src_off), row_bytes);
1213                }
1214                continue;
1215            }
1216            let by0: usize = (y >> 2).min(bh_max);
1217            let by1: usize = (by0 + 1).min(bh_max);
1218            let ty: f32 = ((y & 3) as f32) * 0.25;
1219            let bloom_r0: usize = by0 * bw;
1220            let bloom_r1: usize = by1 * bw;
1221            let edge_row: bool = y == 0 || y + 1 >= h;
1222            let simple_row: bool = !use_fxaa || edge_row;
1223            if simple_row || w < 3 {
1224                for x in 0..w {
1225                    let sc: usize = src_off + x * 4;
1226                    let dc: usize = dst_off + x * 4;
1227                    let mut r: i32 = src[sc] as i32;
1228                    let mut g: i32 = src[sc + 1] as i32;
1229                    let mut b: i32 = src[sc + 2] as i32;
1230                    if has_bloom {
1231                        let bx0: usize = (x >> 2).min(bw_max);
1232                        if bloom_active[bloom_r0 + bx0] != 0 {
1233                            let tx: f32 = ((x & 3) as f32) * 0.25;
1234                            let bl: [f32; 3] = Self::sample_bloom_bilinear_row(
1235                                bloom,
1236                                (bloom_r0, bloom_r1, bw_max),
1237                                (bx0, tx, ty),
1238                            );
1239                            r = (r + (bl[0] * 64.0) as i32).min(255);
1240                            g = (g + (bl[1] * 64.0) as i32).min(255);
1241                            b = (b + (bl[2] * 64.0) as i32).min(255);
1242                        }
1243                    }
1244                    // SAFETY: `dc + 4 <= band_rows * row_bytes` and `[u8; 4]` has alignment 1.
1245                    unsafe {
1246                        dst_ptr
1247                            .add(dc)
1248                            .cast::<[u8; 4]>()
1249                            .write([r as u8, g as u8, b as u8, 255]);
1250                    }
1251                }
1252                continue;
1253            }
1254            let last_px: usize = (w - 1) * 4;
1255            // SAFETY: `w >= 3`, so both first and last 4-byte pixels lie within `dst_off..dst_off + row_bytes`.
1256            unsafe {
1257                dst_ptr
1258                    .add(dst_off)
1259                    .copy_from_nonoverlapping(src.as_ptr().add(src_off), 4);
1260                dst_ptr
1261                    .add(dst_off + last_px)
1262                    .copy_from_nonoverlapping(src.as_ptr().add(src_off + last_px), 4);
1263            }
1264            let row: usize = y * w;
1265            let row_up: usize = (y - 1) * w;
1266            let row_dn: usize = (y + 1) * w;
1267            let y_i32: i32 = y as i32;
1268            for x in 1..(w - 1) {
1269                let lc: i32 = luma[row + x] as i32;
1270                let ln: i32 = luma[row_up + x] as i32;
1271                let ls: i32 = luma[row_dn + x] as i32;
1272                let le: i32 = luma[row + x + 1] as i32;
1273                let lw: i32 = luma[row + x - 1] as i32;
1274                let lmax: i32 = lc.max(ln).max(ls).max(le).max(lw);
1275                let lmin: i32 = lc.min(ln).min(ls).min(le).min(lw);
1276                let contrast: i32 = lmax - lmin;
1277                let (geom_edge, run_fxaa): (bool, bool) = if contrast >= 3 {
1278                    let tid_c: u32 = g_tri_idx[row + x];
1279                    let edge_v_id: bool =
1280                        tid_c != g_tri_idx[row_up + x] || tid_c != g_tri_idx[row_dn + x];
1281                    let edge_h_id: bool =
1282                        tid_c != g_tri_idx[row + x - 1] || tid_c != g_tri_idx[row + x + 1];
1283                    let ge: bool = edge_v_id || edge_h_id;
1284                    (ge, contrast >= 7 || ge)
1285                } else {
1286                    (false, false)
1287                };
1288                let sc: usize = (row + x) * 4;
1289                let dc: usize = dst_off + x * 4;
1290                let mut rgb: [i32; 3] = [src[sc] as i32, src[sc + 1] as i32, src[sc + 2] as i32];
1291                if run_fxaa {
1292                    let lnw: i32 = luma[row_up + x - 1] as i32;
1293                    let lne: i32 = luma[row_up + x + 1] as i32;
1294                    let lsw: i32 = luma[row_dn + x - 1] as i32;
1295                    let lse: i32 = luma[row_dn + x + 1] as i32;
1296                    let edge_h: i32 = (lnw + lne - 2 * ln).abs()
1297                        + 2 * (lw + le - 2 * lc).abs()
1298                        + (lsw + lse - 2 * ls).abs();
1299                    let edge_v: i32 = (lnw + lsw - 2 * lw).abs()
1300                        + 2 * (ln + ls - 2 * lc).abs()
1301                        + (lne + lse - 2 * le).abs();
1302                    let is_horiz: bool = edge_h >= edge_v;
1303                    let (l_neg, l_pos): (i32, i32) = if is_horiz { (ln, ls) } else { (lw, le) };
1304                    let grad_neg: i32 = (l_neg - lc).abs();
1305                    let grad_pos: i32 = (l_pos - lc).abs();
1306                    let step_sign: i32 = if grad_neg >= grad_pos { -1 } else { 1 };
1307                    let grad_steep: i32 = grad_neg.max(grad_pos);
1308                    let l_other: i32 = if step_sign < 0 { l_neg } else { l_pos };
1309                    let edge_avg_2: i32 = lc + l_other;
1310                    let grad_thresh_2: i32 = (grad_steep >> 1).max(3);
1311                    let (perp_dx, perp_dy, tan_dx, tan_dy): (i32, i32, i32, i32) = if is_horiz {
1312                        (0, step_sign, 1, 0)
1313                    } else {
1314                        (step_sign, 0, 0, 1)
1315                    };
1316                    let x_i32: i32 = x as i32;
1317                    let mut dist_neg: i32 = MLAA_MAX_WALK_STEPS as i32;
1318                    let mut end_neg_delta: i32 = 0;
1319                    for s in 1..=(MLAA_MAX_WALK_STEPS as i32) {
1320                        let sx: i32 = x_i32 - tan_dx * s;
1321                        let sy: i32 = y_i32 - tan_dy * s;
1322                        let ox: i32 = sx + perp_dx;
1323                        let oy: i32 = sy + perp_dy;
1324                        let oob_s: bool = sx < 0 || sx >= w_i32;
1325                        let oob_sy: bool = sy < 0 || sy >= h_i32;
1326                        let oob_o: bool = ox < 0 || ox >= w_i32;
1327                        let oob_oy: bool = oy < 0 || oy >= h_i32;
1328                        let oob_a: bool = oob_s || oob_sy;
1329                        let oob_b: bool = oob_o || oob_oy;
1330                        if oob_a || oob_b {
1331                            dist_neg = s;
1332                            break;
1333                        }
1334                        let pair_sum: i32 = (luma[(sy as usize) * w + (sx as usize)] as i32)
1335                            + (luma[(oy as usize) * w + (ox as usize)] as i32);
1336                        let delta: i32 = pair_sum - edge_avg_2;
1337                        if delta.abs() >= grad_thresh_2 {
1338                            dist_neg = s;
1339                            end_neg_delta = delta;
1340                            break;
1341                        }
1342                    }
1343                    let mut dist_pos: i32 = MLAA_MAX_WALK_STEPS as i32;
1344                    let mut end_pos_delta: i32 = 0;
1345                    for s in 1..=(MLAA_MAX_WALK_STEPS as i32) {
1346                        let sx: i32 = x_i32 + tan_dx * s;
1347                        let sy: i32 = y_i32 + tan_dy * s;
1348                        let ox: i32 = sx + perp_dx;
1349                        let oy: i32 = sy + perp_dy;
1350                        let oob_s: bool = sx < 0 || sx >= w_i32;
1351                        let oob_sy: bool = sy < 0 || sy >= h_i32;
1352                        let oob_o: bool = ox < 0 || ox >= w_i32;
1353                        let oob_oy: bool = oy < 0 || oy >= h_i32;
1354                        let oob_a: bool = oob_s || oob_sy;
1355                        let oob_b: bool = oob_o || oob_oy;
1356                        if oob_a || oob_b {
1357                            dist_pos = s;
1358                            break;
1359                        }
1360                        let pair_sum: i32 = (luma[(sy as usize) * w + (sx as usize)] as i32)
1361                            + (luma[(oy as usize) * w + (ox as usize)] as i32);
1362                        let delta: i32 = pair_sum - edge_avg_2;
1363                        if delta.abs() >= grad_thresh_2 {
1364                            dist_pos = s;
1365                            end_pos_delta = delta;
1366                            break;
1367                        }
1368                    }
1369                    let center_lt_avg: bool = (lc * 2) < edge_avg_2;
1370                    let (closer_dist, closer_delta): (i32, i32) = if dist_neg <= dist_pos {
1371                        (dist_neg, end_neg_delta)
1372                    } else {
1373                        (dist_pos, end_pos_delta)
1374                    };
1375                    let good_span: bool = (closer_delta < 0) != center_lt_avg;
1376                    let span_total: f32 = ((dist_neg + dist_pos).max(1)) as f32;
1377                    let morph_blend: f32 = if good_span {
1378                        (0.5 - ((closer_dist as f32) - 0.5).max(0.0) / span_total).clamp(0.0, 0.5)
1379                    } else {
1380                        0.0
1381                    };
1382                    let avg_8: i32 = ((ln + ls + le + lw) * 2 + lnw + lne + lsw + lse + 6) / 12;
1383                    let subpix_raw: f32 =
1384                        (((avg_8 - lc).abs() as f32) / (contrast.max(1) as f32)).clamp(0.0, 1.0);
1385                    let subpix_s: f32 = subpix_raw * subpix_raw * (3.0 - 2.0 * subpix_raw);
1386                    let subpix_blend: f32 =
1387                        subpix_s * subpix_s * if geom_edge { 0.78 } else { 0.52 };
1388                    let final_blend: f32 = morph_blend.max(subpix_blend).clamp(0.0, 0.78);
1389                    let blend_q8: i32 = (final_blend * 256.0).round() as i32;
1390                    if blend_q8 > 0 {
1391                        let nx: usize = (x_i32 + perp_dx).clamp(0, w_i32 - 1) as usize;
1392                        let ny: usize = (y_i32 + perp_dy).clamp(0, h_i32 - 1) as usize;
1393                        let n_sc: usize = (ny * w + nx) * 4;
1394                        let keep_q8: i32 = 256 - blend_q8;
1395                        for ch in 0..3 {
1396                            rgb[ch] =
1397                                ((rgb[ch] * keep_q8 + (src[n_sc + ch] as i32) * blend_q8 + 128)
1398                                    >> 8)
1399                                    .clamp(0, 255);
1400                        }
1401                    }
1402                }
1403                if has_taa {
1404                    let flat_3x3: bool = if contrast == 0 {
1405                        let lc_u8: u8 = lc as u8;
1406                        let diag_top: bool =
1407                            luma[row_up + x - 1] == lc_u8 && luma[row_up + x + 1] == lc_u8;
1408                        let diag_bot: bool =
1409                            luma[row_dn + x - 1] == lc_u8 && luma[row_dn + x + 1] == lc_u8;
1410                        diag_top && diag_bot
1411                    } else {
1412                        false
1413                    };
1414                    if !flat_3x3 {
1415                        let hr: i32 = history[sc] as i32;
1416                        let hg: i32 = history[sc + 1] as i32;
1417                        let hb: i32 = history[sc + 2] as i32;
1418                        let diff_rg: bool = hr != rgb[0] || hg != rgb[1];
1419                        if diff_rg || hb != rgb[2] {
1420                            let offsets: [usize; 8] = [
1421                                (row_up + x - 1) * 4,
1422                                (row_up + x) * 4,
1423                                (row_up + x + 1) * 4,
1424                                (row + x - 1) * 4,
1425                                (row + x + 1) * 4,
1426                                (row_dn + x - 1) * 4,
1427                                (row_dn + x) * 4,
1428                                (row_dn + x + 1) * 4,
1429                            ];
1430                            let mut r_min: i32 = rgb[0];
1431                            let mut r_max: i32 = rgb[0];
1432                            let mut g_min: i32 = rgb[1];
1433                            let mut g_max: i32 = rgb[1];
1434                            let mut b_min: i32 = rgb[2];
1435                            let mut b_max: i32 = rgb[2];
1436                            for off in offsets.into_iter() {
1437                                let vr: i32 = src[off] as i32;
1438                                let vg: i32 = src[off + 1] as i32;
1439                                let vb: i32 = src[off + 2] as i32;
1440                                r_min = r_min.min(vr);
1441                                r_max = r_max.max(vr);
1442                                g_min = g_min.min(vg);
1443                                g_max = g_max.max(vg);
1444                                b_min = b_min.min(vb);
1445                                b_max = b_max.max(vb);
1446                            }
1447                            let hr_c: i32 = hr.clamp(r_min, r_max);
1448                            let hg_c: i32 = hg.clamp(g_min, g_max);
1449                            let hb_c: i32 = hb.clamp(b_min, b_max);
1450                            rgb[0] = ((rgb[0] * 164 + hr_c * 92 + 128) >> 8).clamp(0, 255);
1451                            rgb[1] = ((rgb[1] * 164 + hg_c * 92 + 128) >> 8).clamp(0, 255);
1452                            rgb[2] = ((rgb[2] * 164 + hb_c * 92 + 128) >> 8).clamp(0, 255);
1453                        }
1454                    }
1455                }
1456                if has_bloom {
1457                    let bx0: usize = (x >> 2).min(bw_max);
1458                    if bloom_active[bloom_r0 + bx0] != 0 {
1459                        let tx: f32 = ((x & 3) as f32) * 0.25;
1460                        let bl: [f32; 3] = Self::sample_bloom_bilinear_row(
1461                            bloom,
1462                            (bloom_r0, bloom_r1, bw_max),
1463                            (bx0, tx, ty),
1464                        );
1465                        rgb[0] = (rgb[0] + (bl[0] * 64.0) as i32).min(255);
1466                        rgb[1] = (rgb[1] + (bl[1] * 64.0) as i32).min(255);
1467                        rgb[2] = (rgb[2] + (bl[2] * 64.0) as i32).min(255);
1468                    }
1469                }
1470                // SAFETY: `dc + 4 <= band_rows * row_bytes` and `[u8; 4]` has alignment 1.
1471                unsafe {
1472                    dst_ptr.add(dc).cast::<[u8; 4]>().write([
1473                        rgb[0] as u8,
1474                        rgb[1] as u8,
1475                        rgb[2] as u8,
1476                        255,
1477                    ]);
1478                }
1479            }
1480        }
1481    }
1482
1483    /// Renders `world` at runtime-configured `quality` directly into `out_pixels` without zero-filling, returning internal `(width, height)`.
1484    ///
1485    /// # Arguments
1486    ///
1487    /// - `&Self` - Mutable 3D renderer.
1488    /// - `&mut World3D` - Open-world 3D scene graph.
1489    /// - `u32` - Target viewport width in logical pixels.
1490    /// - `u32` - Target viewport height in logical pixels.
1491    /// - `&RenderQualityConfig` - Live runtime quality, resolution scale, LOD, and ray-tracing settings.
1492    /// - `&mut Vec<u8>` - Destination RGBA8 byte buffer resized without zero-fill and populated completely.
1493    ///
1494    /// # Returns
1495    ///
1496    /// - `(u32, u32)` - Internal rasterized framebuffer `(width, height)`.
1497    fn render_world_into_vec(
1498        &mut self,
1499        world: &mut World3D,
1500        viewport_w: u32,
1501        viewport_h: u32,
1502        quality: &RenderQualityConfig,
1503        out_pixels: &mut Vec<u8>,
1504    ) -> (u32, u32) {
1505        let scale: f32 = quality.get_resolution_scale().clamp(0.40, 4.0);
1506        let w: u32 = ((viewport_w as f32 * scale).round() as u32).clamp(240, 3840);
1507        let h: u32 = ((viewport_h as f32 * scale).round() as u32).clamp(144, 2160);
1508        let w_usize: usize = w as usize;
1509        let h_usize: usize = h as usize;
1510        let pixel_count: usize = w_usize * h_usize;
1511        let bw: usize = w_usize.div_ceil(4);
1512        let bh: usize = h_usize.div_ceil(4);
1513        if self.get_width() != w || self.get_height() != h {
1514            self.set_width(w);
1515            self.set_height(h);
1516            let Self {
1517                color_buffer,
1518                depth_buffer,
1519                g_tri_idx,
1520                luma_buffer,
1521                has_taa_history,
1522                ..
1523            } = self;
1524            color_buffer.resize(pixel_count * 4, 0);
1525            depth_buffer.resize(pixel_count, 0.0);
1526            g_tri_idx.resize(pixel_count, u32::MAX);
1527            luma_buffer.resize(pixel_count, 0);
1528            *has_taa_history = false;
1529        }
1530        let rt_mode: RayTracingMode = quality.get_ray_tracing();
1531        if rt_mode != RayTracingMode::Off {
1532            world.ensure_bvh();
1533        }
1534        let sun: DirectionalLight3D = world.get_sun();
1535        let cam: Camera3D = world.get_camera();
1536        let aspect: f32 = (w as f32) / (h as f32).max(1.0);
1537        let vp: Mat4 = cam.view_projection(aspect);
1538        let frustum: Frustum3D = Frustum3D::from_view_proj(&vp);
1539        let cam_fwd: Vec3 = cam.forward();
1540        let cam_right: Vec3 = cam.right();
1541        let cam_up: Vec3 = cam_right.cross(cam_fwd).normalize();
1542        let half_h: f32 = (cam.get_fov_deg().to_radians() * 0.5).tan();
1543        let half_w: f32 = half_h * aspect;
1544        let focal_px: f32 = (h as f32) * 0.5 / half_h.max(0.05);
1545        let draw_dist_sq: f32 = quality.get_draw_distance() * quality.get_draw_distance();
1546        let frustum_on: bool = quality.get_frustum_culling();
1547        let chunk_on: bool = quality.get_chunk_streaming();
1548        let lod_bias: f32 = quality.get_lod_bias();
1549        let aa_mode: AntiAliasingMode = quality.get_anti_aliasing();
1550        let mut visible_objects: usize = 0;
1551        let mut culled_objects: usize = 0;
1552        let mut triangles_drawn: usize = 0;
1553        let mut lod_simplified_objects: usize = 0;
1554        let mut meshlets_drawn: usize = 0;
1555        let mut meshlets_culled: usize = 0;
1556        let static_bvh: &Bvh3D = world.get_bvh();
1557        let dynamic_bvh: &Bvh3D = world.get_dynamic_bvh();
1558        let total_bvh_nodes: usize = world.total_bvh_nodes();
1559        let world_rev: u64 = world.get_world_revision();
1560        let quality_fp: u64 = Self::quality_fingerprint(viewport_w, viewport_h, quality);
1561        let objects: &[SceneObject3D] = world.get_objects().as_slice();
1562        let mesh_lib: &[MeshLodChain] = world.get_mesh_library().as_slice();
1563        let cam_pos: Vec3 = cam.get_position();
1564        let sun_dir: Vec3 = sun.get_direction();
1565        let sky_horizon: Vec3 = sun.get_sky_horizon();
1566        let sky_zenith: Vec3 = sun.get_sky_zenith();
1567        let use_rt_refl: bool = matches!(
1568            rt_mode,
1569            RayTracingMode::ShadowsAndReflections | RayTracingMode::FullPathTracedGi
1570        );
1571        let Self {
1572            color_buffer,
1573            aa_buffer,
1574            depth_buffer,
1575            g_tri_idx,
1576            luma_buffer,
1577            shaded_tris,
1578            gi_rays_scratch,
1579            rt_probes,
1580            rt_probes_denoised,
1581            bloom_a,
1582            bloom_b,
1583            bloom_tile_active,
1584            visible_scratch,
1585            cluster_ranges_scratch,
1586            projected_verts_scratch,
1587            unique_meshes_scratch,
1588            has_taa_history,
1589            prev_vp_m0,
1590            frame_index,
1591            ..
1592        } = self;
1593        let (jitter_x, jitter_y): (f32, f32) = if aa_mode == AntiAliasingMode::Taa {
1594            HALTON_JITTER_8[(*frame_index as usize) & 7]
1595        } else {
1596            (0.0, 0.0)
1597        };
1598        *frame_index = frame_index.wrapping_add(1);
1599        visible_scratch.clear();
1600        unique_meshes_scratch.clear();
1601        for (obj_idx, obj) in objects.iter().enumerate() {
1602            let bounds: Aabb3D = obj.get_world_bounds();
1603            let dist_sq: f32 = bounds.center().sub(cam_pos).length_sq();
1604            if chunk_on && dist_sq > draw_dist_sq {
1605                culled_objects += 1;
1606                continue;
1607            }
1608            if frustum_on && !frustum.intersects_aabb(&bounds) {
1609                culled_objects += 1;
1610                continue;
1611            }
1612            visible_scratch.push((dist_sq, obj_idx));
1613        }
1614        visible_scratch.sort_unstable_by(|a: &(f32, usize), b: &(f32, usize)| a.0.total_cmp(&b.0));
1615        depth_buffer.fill(0.0);
1616        g_tri_idx.fill(u32::MAX);
1617        shaded_tris.clear();
1618        for &(dist_sq, obj_idx) in visible_scratch.iter() {
1619            let obj: &SceneObject3D = &objects[obj_idx];
1620            let Some(chain) = mesh_lib.get(obj.get_mesh_id()) else {
1621                continue;
1622            };
1623            visible_objects += 1;
1624            let _: bool = unique_meshes_scratch.insert(obj.get_mesh_id());
1625            let dist: f32 = dist_sq.sqrt();
1626            let obj_radius: f32 = obj.get_world_bounds().radius();
1627            let (mesh, lod_idx): (&Mesh3D, usize) =
1628                chain.select_screen_error(dist, obj_radius, focal_px, lod_bias);
1629            if lod_idx > 0 {
1630                lod_simplified_objects += 1;
1631            }
1632            let tr: Transform3D = obj.get_transform();
1633            let mat: PbrMaterial = obj.get_material();
1634            let mat_base: Vec3 = mat.get_base_color();
1635            let mat_emissive: Vec3 = mat.get_emissive();
1636            let mat_refl: f32 = mat.get_reflectivity();
1637            let metallic: f32 = mat.get_metallic();
1638            let rough: f32 = mat.get_roughness();
1639            let alpha: f32 = (rough * rough).max(0.018);
1640            let alpha2: f32 = alpha * alpha;
1641            let f0: Vec3 = Vec3::splat(0.04).lerp(mat_base, metallic);
1642            let diffuse_scale: f32 = 1.0 - metallic;
1643            let do_refl: bool = use_rt_refl && mat_refl > 0.25;
1644            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
1645            let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
1646            let meshlets: &[Meshlet3D] = mesh.get_meshlets().as_slice();
1647            cluster_ranges_scratch.clear();
1648            if meshlets.len() > 1 && frustum_on {
1649                for mlet in meshlets.iter() {
1650                    let wb: Aabb3D = tr.transform_aabb(mlet.get_bounds());
1651                    if !frustum.intersects_aabb(&wb) {
1652                        meshlets_culled += 1;
1653                        continue;
1654                    }
1655                    meshlets_drawn += 1;
1656                    let s0: usize = mlet.get_first_tri() as usize;
1657                    let s1: usize = (s0 + (mlet.get_tri_count() as usize)).min(indices.len());
1658                    cluster_ranges_scratch.push((s0, s1));
1659                }
1660            } else {
1661                meshlets_drawn += meshlets.len().max(1);
1662                cluster_ranges_scratch.push((0, indices.len()));
1663            }
1664            if cluster_ranges_scratch.is_empty() {
1665                continue;
1666            }
1667            projected_verts_scratch.clear();
1668            projected_verts_scratch.reserve(verts.len());
1669            for v in verts.iter() {
1670                let wp: Vec3 = tr.transform_point(v.get_position());
1671                let cp: [f32; 4] = vp.mul_point4(wp);
1672                projected_verts_scratch.push((cp, wp));
1673            }
1674            let near_plane: f32 = cam.get_near().max(0.15);
1675            let w_f: f32 = w as f32;
1676            let h_f: f32 = h as f32;
1677            let w_max_i: i32 = (w as i32) - 1;
1678            let h_max_i: i32 = (h as i32) - 1;
1679            let vert_count: usize = projected_verts_scratch.len();
1680            for &(tri_start, tri_end) in cluster_ranges_scratch.iter() {
1681                for tri in indices[tri_start..tri_end].iter() {
1682                    let (i0, i1, i2): (usize, usize, usize) =
1683                        (tri[0] as usize, tri[1] as usize, tri[2] as usize);
1684                    let oob_01: bool = i0 >= vert_count || i1 >= vert_count;
1685                    if oob_01 || i2 >= vert_count {
1686                        continue;
1687                    }
1688                    let (c0, wp0): ([f32; 4], Vec3) = projected_verts_scratch[i0];
1689                    let (c1, wp1): ([f32; 4], Vec3) = projected_verts_scratch[i1];
1690                    let (c2, wp2): ([f32; 4], Vec3) = projected_verts_scratch[i2];
1691                    if c0[3] < near_plane && c1[3] < near_plane && c2[3] < near_plane {
1692                        continue;
1693                    }
1694                    let out_l: bool = c0[0] < -c0[3] && c1[0] < -c1[3] && c2[0] < -c2[3];
1695                    let out_r: bool = c0[0] > c0[3] && c1[0] > c1[3] && c2[0] > c2[3];
1696                    let out_b: bool = c0[1] < -c0[3] && c1[1] < -c1[3] && c2[1] < -c2[3];
1697                    let out_t: bool = c0[1] > c0[3] && c1[1] > c1[3] && c2[1] > c2[3];
1698                    let out_lr: bool = out_l || out_r;
1699                    let out_bt: bool = out_b || out_t;
1700                    if out_lr || out_bt {
1701                        continue;
1702                    }
1703                    let (clipped_tris, clipped_count): ([ClippedTriangle3D; 2], usize) =
1704                        Self::clip_triangle_near((c0, wp0), (c1, wp1), (c2, wp2), near_plane);
1705                    if clipped_count == 0 {
1706                        continue;
1707                    }
1708                    let mut cached_wn: Option<Vec3> = None;
1709                    for clipped in clipped_tris.iter().take(clipped_count) {
1710                        let [(tc0, tw0), (tc1, tw1), (tc2, tw2)]: ClippedTriangle3D = *clipped;
1711                        let inv_w0: f32 = 1.0 / tc0[3];
1712                        let inv_w1: f32 = 1.0 / tc1[3];
1713                        let inv_w2: f32 = 1.0 / tc2[3];
1714                        let sx0: f32 = (tc0[0] * inv_w0 * 0.5 + 0.5) * w_f + jitter_x;
1715                        let sy0: f32 = (0.5 - tc0[1] * inv_w0 * 0.5) * h_f + jitter_y;
1716                        let sx1: f32 = (tc1[0] * inv_w1 * 0.5 + 0.5) * w_f + jitter_x;
1717                        let sy1: f32 = (0.5 - tc1[1] * inv_w1 * 0.5) * h_f + jitter_y;
1718                        let sx2: f32 = (tc2[0] * inv_w2 * 0.5 + 0.5) * w_f + jitter_x;
1719                        let sy2: f32 = (0.5 - tc2[1] * inv_w2 * 0.5) * h_f + jitter_y;
1720                        let area: f32 = (sx1 - sx0) * (sy2 - sy0) - (sy1 - sy0) * (sx2 - sx0);
1721                        if area.abs() < 0.25 {
1722                            continue;
1723                        }
1724                        let min_x: i32 = (sx0.min(sx1).min(sx2).floor() as i32).max(0);
1725                        let max_x: i32 = (sx0.max(sx1).max(sx2).ceil() as i32).min(w_max_i);
1726                        let min_y: i32 = (sy0.min(sy1).min(sy2).floor() as i32).max(0);
1727                        let max_y: i32 = (sy0.max(sy1).max(sy2).ceil() as i32).min(h_max_i);
1728                        if min_x > max_x || min_y > max_y {
1729                            continue;
1730                        }
1731                        let wn: Vec3 = match cached_wn {
1732                            Some(n) => n,
1733                            None => {
1734                                let computed: Vec3 = tr.transform_normal(verts[i0].get_normal());
1735                                cached_wn = Some(computed);
1736                                computed
1737                            }
1738                        };
1739                        triangles_drawn += 1;
1740                        let tri_id: u32 = shaded_tris.len() as u32;
1741                        let tri_center: Vec3 = tw0.add(tw1).add(tw2).scale(1.0 / 3.0);
1742                        let tri_view: Vec3 = cam_pos.sub(tri_center).normalize();
1743                        let shade_n: Vec3 = if wn.dot(tri_view) < 0.0 {
1744                            wn.scale(-1.0)
1745                        } else {
1746                            wn
1747                        };
1748                        let n_dot_l: f32 = shade_n.dot(sun_dir).max(0.0);
1749                        let ambient_sky: Vec3 = sky_horizon
1750                            .lerp(sky_zenith, (shade_n.get_y() * 0.5 + 0.5).clamp(0.0, 1.0));
1751                        shaded_tris.push(GShadeTri {
1752                            shade_n,
1753                            mat_base,
1754                            mat_emissive,
1755                            ambient_sky,
1756                            f0,
1757                            n_dot_l,
1758                            alpha2,
1759                            diffuse_scale,
1760                            mat_refl,
1761                            metallic,
1762                            do_refl,
1763                            surface_detail: mat.get_surface_detail(),
1764                        });
1765                        let inv_area: f32 = 1.0 / area;
1766                        let dw0_dx: f32 = (sy1 - sy2) * inv_area;
1767                        let dw1_dx: f32 = (sy2 - sy0) * inv_area;
1768                        let dw2_dx: f32 = -(dw0_dx + dw1_dx);
1769                        let dw0_dy: f32 = (sx2 - sx1) * inv_area;
1770                        let dw1_dy: f32 = (sx0 - sx2) * inv_area;
1771                        let dw2_dy: f32 = -(dw0_dy + dw1_dy);
1772                        let d_inv_w_dx: f32 = dw0_dx * inv_w0 + dw1_dx * inv_w1 + dw2_dx * inv_w2;
1773                        let d_inv_w_dy: f32 = dw0_dy * inv_w0 + dw1_dy * inv_w1 + dw2_dy * inv_w2;
1774                        let neg_inv_slopes: [f32; 3] = [
1775                            if dw0_dx.abs() > 1e-9 {
1776                                -1.0 / dw0_dx
1777                            } else {
1778                                0.0
1779                            },
1780                            if dw1_dx.abs() > 1e-9 {
1781                                -1.0 / dw1_dx
1782                            } else {
1783                                0.0
1784                            },
1785                            if dw2_dx.abs() > 1e-9 {
1786                                -1.0 / dw2_dx
1787                            } else {
1788                                0.0
1789                            },
1790                        ];
1791                        let slopes: [f32; 3] = [dw0_dx, dw1_dx, dw2_dx];
1792                        let span_max: i32 = max_x - min_x;
1793                        let span_max_f: f32 = span_max as f32;
1794                        let fx_start: f32 = (min_x as f32) + 0.5;
1795                        let fy_start: f32 = (min_y as f32) + 0.5;
1796                        let mut w0_row: f32 = ((sx1 - fx_start) * (sy2 - fy_start)
1797                            - (sy1 - fy_start) * (sx2 - fx_start))
1798                            * inv_area;
1799                        let mut w1_row: f32 = ((sx2 - fx_start) * (sy0 - fy_start)
1800                            - (sy2 - fy_start) * (sx0 - fx_start))
1801                            * inv_area;
1802                        let mut w2_row: f32 = 1.0 - w0_row - w1_row;
1803                        let mut inv_w_row: f32 =
1804                            w0_row * inv_w0 + w1_row * inv_w1 + w2_row * inv_w2;
1805                        let mut row_off: usize = (min_y as usize) * w_usize;
1806                        for _py in min_y..=max_y {
1807                            let vals: [f32; 3] = [w0_row + 1e-5, w1_row + 1e-5, w2_row + 1e-5];
1808                            let mut k_lo: f32 = 0.0;
1809                            let mut k_hi: f32 = span_max_f;
1810                            let mut valid_span: bool = true;
1811                            for e in 0..3 {
1812                                let slope: f32 = slopes[e];
1813                                let val: f32 = vals[e];
1814                                if slope > 1e-9 {
1815                                    k_lo = k_lo.max((val * neg_inv_slopes[e]).ceil());
1816                                } else if slope < -1e-9 {
1817                                    k_hi = k_hi.min((val * neg_inv_slopes[e]).floor());
1818                                } else if val < 0.0 {
1819                                    valid_span = false;
1820                                    break;
1821                                }
1822                            }
1823                            if valid_span && k_lo <= k_hi {
1824                                let start_k: i32 = (k_lo as i32).max(0);
1825                                let end_k: i32 = (k_hi as i32).min(span_max);
1826                                if start_k <= end_k {
1827                                    let mut inv_w: f32 =
1828                                        d_inv_w_dx.mul_add(start_k as f32, inv_w_row);
1829                                    let px0: usize = row_off + ((min_x + start_k) as usize);
1830                                    let px1: usize = row_off + ((min_x + end_k) as usize);
1831                                    for (d_slot, g_slot) in depth_buffer[px0..=px1]
1832                                        .iter_mut()
1833                                        .zip(g_tri_idx[px0..=px1].iter_mut())
1834                                    {
1835                                        if inv_w > *d_slot {
1836                                            *d_slot = inv_w;
1837                                            *g_slot = tri_id;
1838                                        }
1839                                        inv_w += d_inv_w_dx;
1840                                    }
1841                                }
1842                            }
1843                            w0_row += dw0_dy;
1844                            w1_row += dw1_dy;
1845                            w2_row += dw2_dy;
1846                            inv_w_row += d_inv_w_dy;
1847                            row_off += w_usize;
1848                        }
1849                    }
1850                }
1851            }
1852        }
1853        let rt_step: usize = if rt_mode == RayTracingMode::Off {
1854            0
1855        } else if w_usize >= 780 {
1856            6
1857        } else if w_usize >= 460 {
1858            5
1859        } else if w_usize >= 300 {
1860            4
1861        } else {
1862            2
1863        };
1864        let gw: usize = if rt_step > 0 {
1865            w_usize.div_ceil(rt_step)
1866        } else {
1867            0
1868        };
1869        let gh: usize = if rt_step > 0 {
1870            h_usize.div_ceil(rt_step)
1871        } else {
1872            0
1873        };
1874        let bloom_on: bool = matches!(
1875            quality.get_preset(),
1876            QualityPreset::High | QualityPreset::Ultra | QualityPreset::Cinematic
1877        );
1878        if bloom_on {
1879            let bloom_cells: usize = bw * bh;
1880            if bloom_a.len() != bloom_cells {
1881                bloom_a.resize(bloom_cells, [0.0; 3]);
1882                bloom_b.resize(bloom_cells, [0.0; 3]);
1883                bloom_tile_active.resize(bloom_cells, 0);
1884            }
1885        }
1886        let sun_inv_dir: Vec3 = Ray3D::safe_inv_vec(sun_dir);
1887        let soft_shadow_rays: GiRayQuad = if rt_mode == RayTracingMode::FullPathTracedGi {
1888            let sun_t1: Vec3 = sun_dir.cross(Vec3::new(0.0, 1.0, 0.0)).normalize();
1889            let sun_t2: Vec3 = sun_dir.cross(sun_t1).normalize();
1890            let mut table: GiRayQuad = [(sun_dir, sun_inv_dir); 4];
1891            for (slot, &(ox, oy)) in table.iter_mut().zip(SOFT_SHADOW_OFFSETS_4.iter()) {
1892                let jittered: Vec3 = sun_dir
1893                    .add(sun_t1.scale(ox))
1894                    .add(sun_t2.scale(oy))
1895                    .normalize();
1896                *slot = (jittered, Ray3D::safe_inv_vec(jittered));
1897            }
1898            table
1899        } else {
1900            [(sun_dir, sun_inv_dir); 4]
1901        };
1902        let fctx: DeferredFrameCtx = DeferredFrameCtx {
1903            w: w_usize,
1904            h: h_usize,
1905            gw,
1906            gh,
1907            bw,
1908            rt_step,
1909            inv_w_f: 1.0 / (w as f32).max(1.0),
1910            inv_h_f: 1.0 / (h as f32).max(1.0),
1911            cam_pos,
1912            cam_fwd,
1913            cam_right_scaled: cam_right.scale(half_w),
1914            cam_up_scaled: cam_up.scale(half_h),
1915            sun,
1916            inv_sun_dir: sun_inv_dir,
1917            soft_shadow_rays,
1918            rt_mode,
1919            reflection_bounces: quality.get_reflection_bounces(),
1920            fog_on: quality.get_volumetric_fog(),
1921            inv_fog_dist: 1.45 / quality.get_draw_distance().max(40.0),
1922            exposure_scale: 1.0,
1923            bloom_on,
1924        };
1925        let rays_atom: AtomicUsize = AtomicUsize::new(0);
1926        if rt_step > 0 {
1927            let probe_count: usize = gw * gh;
1928            if rt_probes.len() != probe_count {
1929                rt_probes.resize(probe_count, RtProbeSample::default());
1930            }
1931            gi_rays_scratch.clear();
1932            if rt_mode == RayTracingMode::FullPathTracedGi {
1933                gi_rays_scratch.reserve(shaded_tris.len());
1934                let j0: Vec3 = Vec3::new(GI_JITTER_4[0][0], GI_JITTER_4[0][1], GI_JITTER_4[0][2]);
1935                let j1: Vec3 = Vec3::new(GI_JITTER_4[1][0], GI_JITTER_4[1][1], GI_JITTER_4[1][2]);
1936                let j2: Vec3 = Vec3::new(GI_JITTER_4[2][0], GI_JITTER_4[2][1], GI_JITTER_4[2][2]);
1937                let j3: Vec3 = Vec3::new(GI_JITTER_4[3][0], GI_JITTER_4[3][1], GI_JITTER_4[3][2]);
1938                let jits: [Vec3; 4] = [j0, j1, j2, j3];
1939                for tri in shaded_tris.iter() {
1940                    let n: Vec3 = tri.shade_n;
1941                    let mut dirs: [(Vec3, Vec3); 4] = [(n, n); 4];
1942                    for (slot, &base_jit) in dirs.iter_mut().zip(jits.iter()) {
1943                        let jit: Vec3 = if n.dot(base_jit) < -0.15 {
1944                            base_jit.scale(-1.0)
1945                        } else {
1946                            base_jit
1947                        };
1948                        let gi_dir: Vec3 = n.add(jit).normalize();
1949                        *slot = (gi_dir, Ray3D::safe_inv_vec(gi_dir));
1950                    }
1951                    gi_rays_scratch.push(dirs);
1952                }
1953            }
1954            let depth_ref: &[f32] = depth_buffer.as_slice();
1955            let gtri_ref: &[u32] = g_tri_idx.as_slice();
1956            let stri_ref: &[GShadeTri] = shaded_tris.as_slice();
1957            let gi_rays_ref: &[GiRayQuad] = gi_rays_scratch.as_slice();
1958            let probes_base: usize = rt_probes.as_mut_ptr() as usize;
1959            let probe_grain: usize = (gh / 32).clamp(2, 8);
1960            parallel_for_ranges(gh, probe_grain, |gy0: usize, gy1: usize| {
1961                // SAFETY: `parallel_for_ranges` partitions `0..gh` into disjoint row bands within `rt_probes`.
1962                let slice: &mut [RtProbeSample] = unsafe {
1963                    from_raw_parts_mut(
1964                        (probes_base as *mut RtProbeSample).add(gy0 * gw),
1965                        (gy1 - gy0) * gw,
1966                    )
1967                };
1968                let r: usize = Self::trace_probe_band(
1969                    &fctx,
1970                    (
1971                        depth_ref,
1972                        gtri_ref,
1973                        stri_ref,
1974                        gi_rays_ref,
1975                        static_bvh,
1976                        dynamic_bvh,
1977                    ),
1978                    (gy0, slice),
1979                );
1980                if r > 0 {
1981                    let _: usize = rays_atom.fetch_add(r, Ordering::Relaxed);
1982                }
1983            });
1984            let need_denoise: bool = matches!(
1985                rt_mode,
1986                RayTracingMode::ShadowsAndReflections | RayTracingMode::FullPathTracedGi
1987            );
1988            if need_denoise {
1989                if rt_probes_denoised.len() != probe_count {
1990                    rt_probes_denoised.resize(probe_count, RtProbeSample::default());
1991                }
1992                let src_probes: &[RtProbeSample] = rt_probes.as_slice();
1993                let dst_base: usize = rt_probes_denoised.as_mut_ptr() as usize;
1994                parallel_for_ranges(gh, probe_grain, |gy0: usize, gy1: usize| {
1995                    // SAFETY: Disjoint row bands within `rt_probes_denoised`.
1996                    let dst_slice: &mut [RtProbeSample] = unsafe {
1997                        from_raw_parts_mut(
1998                            (dst_base as *mut RtProbeSample).add(gy0 * gw),
1999                            (gy1 - gy0) * gw,
2000                        )
2001                    };
2002                    Self::denoise_gi_probes_band(gw, gh, src_probes, gy0, dst_slice);
2003                });
2004            }
2005        }
2006        let active_probes: &[RtProbeSample] = if rt_step == 0 {
2007            &[]
2008        } else if matches!(
2009            rt_mode,
2010            RayTracingMode::ShadowsAndReflections | RayTracingMode::FullPathTracedGi
2011        ) {
2012            rt_probes_denoised.as_slice()
2013        } else {
2014            rt_probes.as_slice()
2015        };
2016        let bloom_any_atom: AtomicUsize = AtomicUsize::new(0);
2017        {
2018            let depth_ref: &[f32] = depth_buffer.as_slice();
2019            let gtri_ref: &[u32] = g_tri_idx.as_slice();
2020            let stri_ref: &[GShadeTri] = shaded_tris.as_slice();
2021            let color_base: usize = color_buffer.as_mut_ptr() as usize;
2022            let luma_base: usize = luma_buffer.as_mut_ptr() as usize;
2023            let bloom_base: usize = bloom_a.as_mut_ptr() as usize;
2024            let bloom_total_len: usize = bloom_a.len();
2025            let shade_grain: usize = ((h_usize / 32).div_ceil(4) * 4).clamp(8, 24);
2026            parallel_for_ranges(h_usize, shade_grain, |y0: usize, y1: usize| {
2027                let rows: usize = y1 - y0;
2028                // SAFETY: `shade_grain` is a multiple of 4 and `parallel_for_ranges` yields disjoint row bands.
2029                let c_band: &mut [u8] = unsafe {
2030                    from_raw_parts_mut(
2031                        (color_base as *mut u8).add(y0 * w_usize * 4),
2032                        rows * w_usize * 4,
2033                    )
2034                };
2035                // SAFETY: Disjoint luma row band for `[y0, y1)`.
2036                let l_band: &mut [u8] = unsafe {
2037                    from_raw_parts_mut((luma_base as *mut u8).add(y0 * w_usize), rows * w_usize)
2038                };
2039                let b_start: usize = (y0 / 4) * bw;
2040                let b_end: usize = ((y1.div_ceil(4)) * bw).min(bloom_total_len);
2041                let b_band: &mut [[f32; 3]] = if b_start < b_end {
2042                    // SAFETY: Since `y0` and non-final `y1` are multiples of 4, `[b_start, b_end)` ranges are disjoint.
2043                    unsafe {
2044                        from_raw_parts_mut(
2045                            (bloom_base as *mut [f32; 3]).add(b_start),
2046                            b_end - b_start,
2047                        )
2048                    }
2049                } else {
2050                    &mut []
2051                };
2052                let (r, has_bloom_band): (usize, bool) = Self::shade_deferred_band(
2053                    &fctx,
2054                    (
2055                        depth_ref,
2056                        gtri_ref,
2057                        stri_ref,
2058                        active_probes,
2059                        static_bvh,
2060                        dynamic_bvh,
2061                    ),
2062                    (y0, c_band, l_band, b_band),
2063                );
2064                if r > 0 {
2065                    let _: usize = rays_atom.fetch_add(r, Ordering::Relaxed);
2066                }
2067                if has_bloom_band {
2068                    bloom_any_atom.store(1, Ordering::Relaxed);
2069                }
2070            });
2071        }
2072        let rays_traced: usize = rays_atom.load(Ordering::Relaxed);
2073        let bloom_effective: bool = if bloom_on && bloom_any_atom.load(Ordering::Relaxed) != 0 {
2074            Self::blur_bloom_separable(bw, bh, bloom_a.as_mut_slice(), bloom_b.as_mut_slice());
2075            Self::build_bloom_tile_mask(
2076                bw,
2077                bh,
2078                bloom_a.as_slice(),
2079                bloom_tile_active.as_mut_slice(),
2080            )
2081        } else {
2082            false
2083        };
2084        let use_fxaa: bool = aa_mode != AntiAliasingMode::Off;
2085        let vp_m0: f32 = vp.get_m()[0] + vp.get_m()[12] * 0.01 + vp.get_m()[14] * 0.01;
2086        let cam_stable: bool = (*prev_vp_m0 - vp_m0).abs() < 0.35;
2087        let use_taa: bool = aa_mode == AntiAliasingMode::Taa && *has_taa_history && cam_stable;
2088        let byte_len: usize = pixel_count * 4;
2089        out_pixels.clear();
2090        if out_pixels.capacity() < byte_len {
2091            out_pixels.reserve_exact(byte_len);
2092        }
2093        {
2094            let src_ref: &[u8] = color_buffer.as_slice();
2095            let luma_ref: &[u8] = luma_buffer.as_slice();
2096            let gtri_ref: &[u32] = g_tri_idx.as_slice();
2097            let bloom_ref: &[[f32; 3]] = bloom_a.as_slice();
2098            let bloom_mask_ref: &[u8] = bloom_tile_active.as_slice();
2099            let hist_ref: &[u8] = aa_buffer.as_slice();
2100            let out_base: usize = out_pixels.as_mut_ptr() as usize;
2101            let post_grain: usize = (h_usize / 32).clamp(8, 24);
2102            parallel_for_ranges(h_usize, post_grain, |y0: usize, y1: usize| {
2103                // SAFETY: `out_pixels` has capacity `>= byte_len`, `parallel_for_ranges` partitions `0..h_usize`
2104                // into disjoint row ranges, and `post_process_band` writes all `(y1 - y0) * w_usize * 4` bytes.
2105                unsafe {
2106                    let band_ptr: *mut u8 = (out_base as *mut u8).add(y0 * w_usize * 4);
2107                    Self::post_process_band(
2108                        (w_usize, h_usize, bw, bh),
2109                        (
2110                            src_ref,
2111                            luma_ref,
2112                            gtri_ref,
2113                            bloom_ref,
2114                            bloom_mask_ref,
2115                            hist_ref,
2116                        ),
2117                        (use_fxaa, use_taa, bloom_effective),
2118                        (y0, band_ptr, y1 - y0),
2119                    );
2120                }
2121            });
2122        }
2123        // SAFETY: `parallel_for_ranges` has joined and initialized every byte in `0..byte_len`.
2124        unsafe {
2125            out_pixels.set_len(byte_len);
2126        }
2127        if aa_mode == AntiAliasingMode::Taa {
2128            if aa_buffer.len() != byte_len {
2129                aa_buffer.resize(byte_len, 0);
2130            }
2131            swap(aa_buffer, color_buffer);
2132            *has_taa_history = true;
2133            *prev_vp_m0 = vp_m0;
2134        } else {
2135            *has_taa_history = false;
2136        }
2137        let instanced_batches: usize = if quality.get_gpu_instancing() {
2138            unique_meshes_scratch.len()
2139        } else {
2140            visible_objects
2141        };
2142        let stats: RenderStats3D = RenderStats3D {
2143            render_width: w,
2144            render_height: h,
2145            visible_objects,
2146            culled_objects,
2147            instanced_batches,
2148            triangles_drawn,
2149            rays_traced,
2150            bvh_nodes: total_bvh_nodes,
2151            lod_simplified_objects,
2152            meshlets_drawn,
2153            meshlets_culled,
2154        };
2155        let same_world_and_cfg: bool = self.get_last_world_revision() == world_rev && {
2156            let Self {
2157                last_quality_fingerprint,
2158                ..
2159            } = self;
2160            *last_quality_fingerprint == quality_fp
2161        };
2162        let next_taa_count: u32 = if aa_mode == AntiAliasingMode::Taa {
2163            if same_world_and_cfg {
2164                self.get_taa_accumulated_frames().saturating_add(1).min(8)
2165            } else {
2166                1
2167            }
2168        } else {
2169            0
2170        };
2171        self.set_taa_accumulated_frames(next_taa_count);
2172        self.set_last_world_revision(world_rev);
2173        let Self {
2174            last_quality_fingerprint,
2175            ..
2176        } = self;
2177        *last_quality_fingerprint = quality_fp;
2178        self.set_last_stats(stats);
2179        (w, h)
2180    }
2181
2182    /// Computes a stable configuration fingerprint covering viewport dimensions and visual quality knobs.
2183    ///
2184    /// # Arguments
2185    ///
2186    /// - `u32` - Target viewport width.
2187    /// - `u32` - Target viewport height.
2188    /// - `&RenderQualityConfig` - Active quality settings.
2189    ///
2190    /// # Returns
2191    ///
2192    /// - `u64` - Combined configuration fingerprint.
2193    #[must_use]
2194    fn quality_fingerprint(viewport_w: u32, viewport_h: u32, quality: &RenderQualityConfig) -> u64 {
2195        let mut h: u64 = 0xCBF2_9CE4_8422_2325;
2196        let parts: [u64; 8] = [
2197            viewport_w as u64,
2198            viewport_h as u64,
2199            quality.get_resolution_scale().to_bits() as u64,
2200            quality.get_draw_distance().to_bits() as u64,
2201            quality.get_lod_bias().to_bits() as u64,
2202            quality.get_reflection_bounces() as u64,
2203            (quality.get_ray_tracing() as u64)
2204                | ((quality.get_anti_aliasing() as u64) << 8)
2205                | ((quality.get_preset() as u64) << 16),
2206            u64::from(quality.get_volumetric_fog())
2207                | (u64::from(quality.get_frustum_culling()) << 1)
2208                | (u64::from(quality.get_chunk_streaming()) << 2),
2209        ];
2210        for p in parts.into_iter() {
2211            h ^= p;
2212            h = h.wrapping_mul(0x0100_0000_01B3);
2213        }
2214        h
2215    }
2216
2217    /// Explicitly resets temporal anti-aliasing history on camera cuts or world teleports without touching unrelated HUD state.
2218    ///
2219    /// # Arguments
2220    ///
2221    /// - `&Self` - Mutable 3D renderer.
2222    pub fn invalidate_taa_history(&mut self) {
2223        let Self {
2224            has_taa_history, ..
2225        } = self;
2226        *has_taa_history = false;
2227        self.set_taa_accumulated_frames(0);
2228    }
2229
2230    /// 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.
2231    ///
2232    /// # Arguments
2233    ///
2234    /// - `&Self` - 3D renderer reference.
2235    /// - `&World3D` - Active 3D world.
2236    /// - `u32` - Viewport width in pixels.
2237    /// - `u32` - Viewport height in pixels.
2238    /// - `&RenderQualityConfig` - Active quality settings.
2239    ///
2240    /// # Returns
2241    ///
2242    /// - `bool` - `true` when the cached 3D frame is valid and TAA accumulation does not require another sample.
2243    #[must_use]
2244    pub fn can_reuse_cached_world(
2245        &self,
2246        world: &World3D,
2247        viewport_w: u32,
2248        viewport_h: u32,
2249        quality: &RenderQualityConfig,
2250    ) -> bool {
2251        let Self {
2252            rgba_scratch,
2253            last_quality_fingerprint,
2254            ..
2255        } = self;
2256        if rgba_scratch.is_empty() {
2257            return false;
2258        }
2259        let fp: u64 = Self::quality_fingerprint(viewport_w, viewport_h, quality);
2260        if self.get_last_world_revision() != world.get_world_revision()
2261            || *last_quality_fingerprint != fp
2262        {
2263            return false;
2264        }
2265        if quality.get_anti_aliasing() == AntiAliasingMode::Taa {
2266            self.get_taa_accumulated_frames() >= 8
2267        } else {
2268            true
2269        }
2270    }
2271
2272    /// 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.
2273    ///
2274    /// # Arguments
2275    ///
2276    /// - `&Self` - Mutable 3D renderer.
2277    /// - `&mut World3D` - Open-world 3D scene graph.
2278    /// - `u32` - Target viewport width in logical pixels.
2279    /// - `u32` - Target viewport height in logical pixels.
2280    /// - `&RenderQualityConfig` - Runtime quality settings.
2281    ///
2282    /// # Returns
2283    ///
2284    /// - `(&[u8], bool)` - Borrowed RGBA8 pixel slice and `true` if satisfied from cache without re-rasterization.
2285    #[must_use]
2286    pub fn render_world_or_reuse_cached(
2287        &mut self,
2288        world: &mut World3D,
2289        viewport_w: u32,
2290        viewport_h: u32,
2291        quality: &RenderQualityConfig,
2292    ) -> (&[u8], bool) {
2293        if self.can_reuse_cached_world(world, viewport_w, viewport_h, quality) {
2294            let next_reuses: u64 = self.get_cached_world_reuses().saturating_add(1);
2295            self.set_cached_world_reuses(next_reuses);
2296            let Self { rgba_scratch, .. } = self;
2297            return (rgba_scratch.as_slice(), true);
2298        }
2299        let pixels: &[u8] = self.render_world_rgba(world, viewport_w, viewport_h, quality);
2300        (pixels, false)
2301    }
2302
2303    /// Renders `world` directly into a bounded zero-allocation `RenderBufferPool` slot tagged with `fence_id`.
2304    ///
2305    /// # Arguments
2306    ///
2307    /// - `&Self` - Mutable 3D renderer.
2308    /// - `&mut World3D` - Open-world 3D scene graph.
2309    /// - `u32` - Target viewport width in logical pixels.
2310    /// - `u32` - Target viewport height in logical pixels.
2311    /// - `&RenderQualityConfig` - Runtime quality settings.
2312    /// - `&RenderBufferPool` - Bounded CPU output buffer pool.
2313    /// - `u64` - Submission fence value guarding reclamation.
2314    ///
2315    /// # Returns
2316    ///
2317    /// - `Option<PooledFrameLease>` - Populated pooled RGBA8 lease, or `None` if all bounded pool slots are in flight.
2318    #[must_use]
2319    pub fn render_world_into_pool(
2320        &mut self,
2321        world: &mut World3D,
2322        viewport_w: u32,
2323        viewport_h: u32,
2324        quality: &RenderQualityConfig,
2325        pool: &RenderBufferPool,
2326        fence_id: u64,
2327    ) -> Option<PooledFrameLease> {
2328        let scale: f32 = quality.get_resolution_scale().clamp(0.40, 4.0);
2329        let w: u32 = ((viewport_w as f32 * scale).round() as u32).clamp(240, 3840);
2330        let h: u32 = ((viewport_h as f32 * scale).round() as u32).clamp(144, 2160);
2331        let mut lease: PooledFrameLease = pool.acquire(w, h, fence_id)?;
2332        let (rw, rh): (u32, u32) = self.render_world_into_vec(
2333            world,
2334            viewport_w,
2335            viewport_h,
2336            quality,
2337            lease.get_mut_pixels(),
2338        );
2339        lease.set_dimensions(rw, rh);
2340        Some(lease)
2341    }
2342
2343    /// Renders `world` using a discontinuity-safe interpolated `World3DSnapshot` sampled at `alpha` without mutating authoritative simulation transforms.
2344    ///
2345    /// # Arguments
2346    ///
2347    /// - `&Self` - Mutable 3D renderer.
2348    /// - `&mut World3D` - 3D world holding shared mesh library, lighting, and BVH acceleration structures.
2349    /// - `&DoubleBufferedSnapshot<World3DSnapshot>` - Immutable `(prev_state, curr_state)` snapshot buffer.
2350    /// - `f32` - Normalized interpolation alpha in `[0.0, 1.0]`.
2351    /// - `(u32, u32)` - Target viewport `(width, height)` in logical pixels.
2352    /// - `&RenderQualityConfig` - Runtime quality settings.
2353    /// - `(&RenderBufferPool, u64)` - Bounded CPU output buffer pool and submission fence value.
2354    ///
2355    /// # Returns
2356    ///
2357    /// - `Option<PooledFrameLease>` - Rendered interpolated frame lease, or `None` under pool backpressure.
2358    #[must_use]
2359    pub fn render_world_interpolated_into_pool(
2360        &mut self,
2361        world: &mut World3D,
2362        snapshots: &DoubleBufferedSnapshot<World3DSnapshot>,
2363        alpha: f32,
2364        viewport: (u32, u32),
2365        quality: &RenderQualityConfig,
2366        target_pool: (&RenderBufferPool, u64),
2367    ) -> Option<PooledFrameLease> {
2368        let (viewport_w, viewport_h): (u32, u32) = viewport;
2369        let (pool, fence_id): (&RenderBufferPool, u64) = target_pool;
2370        let interp: World3DSnapshot = snapshots.sample(alpha);
2371        if interp.get_camera_cut() {
2372            self.invalidate_taa_history();
2373        }
2374        let saved_cam: Camera3D = world.get_camera();
2375        let saved_objs: Vec<(usize, Transform3D, Aabb3D)> = interp
2376            .get_objects()
2377            .iter()
2378            .filter_map(|pose: &ObjectPose3D| {
2379                let idx: usize = pose.get_object_index();
2380                let obj: &SceneObject3D = world.get_objects().get(idx)?;
2381                Some((idx, obj.get_transform(), obj.get_world_bounds()))
2382            })
2383            .collect();
2384        world.set_camera(interp.get_camera());
2385        for pose in interp.get_objects().iter() {
2386            let idx: usize = pose.get_object_index();
2387            let Some(mesh_id) = world.get_objects().get(idx).map(SceneObject3D::get_mesh_id) else {
2388                continue;
2389            };
2390            let local_bounds: Aabb3D = world
2391                .get_mesh_library()
2392                .get(mesh_id)
2393                .and_then(|c: &MeshLodChain| c.get_levels().first())
2394                .map(Mesh3D::get_bounds)
2395                .unwrap_or_else(|| Aabb3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
2396            let world_b: Aabb3D = pose.get_transform().transform_aabb(local_bounds);
2397            if let Some(obj_mut) = world.get_mut_objects().get_mut(idx) {
2398                obj_mut.set_transform(pose.get_transform());
2399                obj_mut.set_world_bounds(world_b);
2400            }
2401        }
2402        let result: Option<PooledFrameLease> =
2403            self.render_world_into_pool(world, viewport_w, viewport_h, quality, pool, fence_id);
2404        world.set_camera(saved_cam);
2405        for (idx, tr, wb) in saved_objs.into_iter() {
2406            if let Some(obj_mut) = world.get_mut_objects().get_mut(idx) {
2407                obj_mut.set_transform(tr);
2408                obj_mut.set_world_bounds(wb);
2409            }
2410        }
2411        result
2412    }
2413
2414    /// Renders `world` at runtime-configured `quality` into an `ImageBuffer` without zero-filling output memory.
2415    ///
2416    /// # Arguments
2417    ///
2418    /// - `&Self` - Mutable 3D renderer.
2419    /// - `&mut World3D` - Open-world 3D scene graph.
2420    /// - `u32` - Target viewport width in logical pixels.
2421    /// - `u32` - Target viewport height in logical pixels.
2422    /// - `&RenderQualityConfig` - Live runtime quality, resolution scale, LOD, and ray-tracing settings.
2423    ///
2424    /// # Returns
2425    ///
2426    /// - `ImageBuffer` - Ready RGBA8 rendered 3D frame for immediate presentation.
2427    pub fn render_world(
2428        &mut self,
2429        world: &mut World3D,
2430        viewport_w: u32,
2431        viewport_h: u32,
2432        quality: &RenderQualityConfig,
2433    ) -> ImageBuffer {
2434        let mut out_pixels: Vec<u8> = Vec::new();
2435        let (w, h): (u32, u32) =
2436            self.render_world_into_vec(world, viewport_w, viewport_h, quality, &mut out_pixels);
2437        ImageBuffer::new(w, h, out_pixels)
2438    }
2439
2440    /// Renders `world` into the persistent internal `rgba_scratch` buffer, eliminating per-frame output heap allocations.
2441    ///
2442    /// # Arguments
2443    ///
2444    /// - `&Self` - Mutable 3D renderer.
2445    /// - `&mut World3D` - Open-world 3D scene graph.
2446    /// - `u32` - Target viewport width in logical pixels.
2447    /// - `u32` - Target viewport height in logical pixels.
2448    /// - `&RenderQualityConfig` - Live runtime quality, resolution scale, LOD, and ray-tracing settings.
2449    ///
2450    /// # Returns
2451    ///
2452    /// - `&[u8]` - Borrowed RGBA8 pixel slice of the rendered 3D frame.
2453    #[must_use]
2454    pub fn render_world_rgba(
2455        &mut self,
2456        world: &mut World3D,
2457        viewport_w: u32,
2458        viewport_h: u32,
2459        quality: &RenderQualityConfig,
2460    ) -> &[u8] {
2461        let mut scratch: Vec<u8> = {
2462            let Self { rgba_scratch, .. } = self;
2463            take(rgba_scratch)
2464        };
2465        let _: (u32, u32) =
2466            self.render_world_into_vec(world, viewport_w, viewport_h, quality, &mut scratch);
2467        let Self { rgba_scratch, .. } = self;
2468        *rgba_scratch = scratch;
2469        rgba_scratch.as_slice()
2470    }
2471
2472    /// Clips a triangle against the camera near plane `w >= near_w` (Sutherland-Hodgman), returning 0, 1, or 2 triangles.
2473    ///
2474    /// # Arguments
2475    ///
2476    /// - `ClipVertex3D` - First clip-space and world-space vertex.
2477    /// - `ClipVertex3D` - Second clip-space and world-space vertex.
2478    /// - `ClipVertex3D` - Third clip-space and world-space vertex.
2479    /// - `f32` - Positive near-plane clip `w` threshold.
2480    ///
2481    /// # Returns
2482    ///
2483    /// - `([ClippedTriangle3D; 2], usize)` - Output clipped triangles and valid count.
2484    #[must_use]
2485    fn clip_triangle_near(
2486        v0: ClipVertex3D,
2487        v1: ClipVertex3D,
2488        v2: ClipVertex3D,
2489        near_w: f32,
2490    ) -> ([ClippedTriangle3D; 2], usize) {
2491        let zero_v: ClipVertex3D = ([0.0; 4], Vec3::zero());
2492        let mut out_tris: [ClippedTriangle3D; 2] = [[zero_v; 3]; 2];
2493        let input: [ClipVertex3D; 3] = [v0, v1, v2];
2494        let mut poly: [ClipVertex3D; 4] = [zero_v; 4];
2495        let mut count: usize = 0;
2496        for i in 0..3 {
2497            let cur: ClipVertex3D = input[i];
2498            let nxt: ClipVertex3D = input[(i + 1) % 3];
2499            let cur_in: bool = cur.0[3] >= near_w;
2500            let nxt_in: bool = nxt.0[3] >= near_w;
2501            if cur_in && count < 4 {
2502                poly[count] = cur;
2503                count += 1;
2504            }
2505            if cur_in != nxt_in && count < 4 {
2506                let denom: f32 = nxt.0[3] - cur.0[3];
2507                let t: f32 = if denom.abs() > 1e-6 {
2508                    ((near_w - cur.0[3]) / denom).clamp(0.0, 1.0)
2509                } else {
2510                    0.5
2511                };
2512                let ic: [f32; 4] = [
2513                    cur.0[0] + (nxt.0[0] - cur.0[0]) * t,
2514                    cur.0[1] + (nxt.0[1] - cur.0[1]) * t,
2515                    cur.0[2] + (nxt.0[2] - cur.0[2]) * t,
2516                    near_w,
2517                ];
2518                let iw: Vec3 = cur.1.lerp(nxt.1, t);
2519                poly[count] = (ic, iw);
2520                count += 1;
2521            }
2522        }
2523        if count < 3 {
2524            return (out_tris, 0);
2525        }
2526        out_tris[0] = [poly[0], poly[1], poly[2]];
2527        if count == 4 {
2528            out_tris[1] = [poly[0], poly[2], poly[3]];
2529            (out_tris, 2)
2530        } else {
2531            (out_tris, 1)
2532        }
2533    }
2534}