Skip to main content

euv_core/game/engine3d/renderer/
struct.rs

1use super::*;
2
3/// Per-worker atomic wakeup epoch and condition variable slot eliminating shared-mutex contention and cache-line false sharing in `Engine3dWorkerPool`.
4#[cfg(not(target_arch = "wasm32"))]
5#[repr(align(128))]
6#[derive(Debug, Default)]
7pub(crate) struct Engine3dWorkerSlot {
8    /// Monotonically incremented epoch signaling this worker to run the active job.
9    pub(crate) epoch: AtomicUsize,
10    /// Non-zero while this worker is parked on `wake` and requires condvar notification.
11    pub(crate) parked: AtomicUsize,
12    /// Private sleep mutex paired with `wake`.
13    pub(crate) lock: Mutex<()>,
14    /// Condition variable waking this worker when parked between frames.
15    pub(crate) wake: Condvar,
16}
17
18/// Shared lock-free dispatch state coordinating caller and persistent 3D background workers.
19#[cfg(not(target_arch = "wasm32"))]
20#[repr(align(128))]
21#[derive(Debug)]
22pub(crate) struct Engine3dPoolShared {
23    /// Raw pointer address of the caller-pinned `Engine3dJob` (`0` when idle).
24    pub(crate) active_job: AtomicUsize,
25    /// Number of background workers woken for the active dispatch.
26    pub(crate) active_workers: AtomicUsize,
27    /// Non-zero while the calling thread is parked waiting for workers to complete.
28    pub(crate) caller_parked: AlignedAtomicUsize,
29    /// Caller sleep mutex paired with `wake_caller`.
30    pub(crate) caller_lock: Mutex<()>,
31    /// Condition variable waking the calling thread once all active workers finish.
32    pub(crate) wake_caller: Condvar,
33    /// Per-worker wakeup slots (`len == worker_count`).
34    pub(crate) slots: Vec<Engine3dWorkerSlot>,
35}
36
37/// Active work-stealing range job executed synchronously across caller and persistent 3D worker threads with 128-byte isolated atomics.
38#[cfg(not(target_arch = "wasm32"))]
39#[repr(align(128))]
40#[derive(Debug)]
41pub(crate) struct Engine3dJob {
42    /// Type-erased chunk execution trampoline.
43    pub(crate) trampoline: fn(usize, usize, usize),
44    /// Caller-pinned closure reference encoded as `usize`.
45    pub(crate) ctx_ptr: usize,
46    /// Total logical items across all chunks.
47    pub(crate) total_items: usize,
48    /// Number of items per dynamic work-stealing chunk.
49    pub(crate) chunk_size: usize,
50    /// Total chunks to claim (`total_items.div_ceil(chunk_size)`).
51    pub(crate) total_chunks: usize,
52    /// Cache-line-isolated atomic cursor of the next unclaimed chunk index.
53    pub(crate) next_chunk: AlignedAtomicUsize,
54    /// Cache-line-isolated atomic count of background workers finished observing this epoch.
55    pub(crate) workers_done: AlignedAtomicUsize,
56}
57
58/// Persistent warm thread pool eliminating per-frame OS thread spawns in `Renderer3D`.
59#[cfg(not(target_arch = "wasm32"))]
60#[derive(Debug)]
61pub(crate) struct Engine3dWorkerPool {
62    /// Number of background worker threads (excluding the calling thread).
63    pub(crate) worker_count: usize,
64    /// Non-blocking re-entrancy guard serializing top-level dispatches cleanly.
65    pub(crate) dispatch_lock: Mutex<()>,
66    /// Shared lock-free atomic dispatch state and per-worker wakeup slots.
67    pub(crate) shared: Arc<Engine3dPoolShared>,
68}
69
70/// Per-frame telemetry emitted by `Renderer3D` for live FPS/RT/LOD/Nanite/culling diagnostics.
71#[derive(Clone, Copy, Data, Debug, Default, PartialEq)]
72pub struct RenderStats3D {
73    /// Internal rasterized framebuffer width in pixels.
74    #[get(type(copy))]
75    pub(crate) render_width: u32,
76    /// Internal rasterized framebuffer height in pixels.
77    #[get(type(copy))]
78    pub(crate) render_height: u32,
79    /// Active objects rendered inside frustum & chunk stream radius.
80    #[get(type(copy))]
81    pub(crate) visible_objects: usize,
82    /// Objects rejected by 6-plane frustum culling or chunk draw distance.
83    #[get(type(copy))]
84    pub(crate) culled_objects: usize,
85    /// Deduplicated GPU instancing draw batches.
86    #[get(type(copy))]
87    pub(crate) instanced_batches: usize,
88    /// Triangles rasterized after backface culling.
89    #[get(type(copy))]
90    pub(crate) triangles_drawn: usize,
91    /// BVH shadow/reflection/GI rays traced during this frame.
92    #[get(type(copy))]
93    pub(crate) rays_traced: usize,
94    /// Total BVH nodes active in the acceleration structure.
95    #[get(type(copy))]
96    pub(crate) bvh_nodes: usize,
97    /// Objects rendered at simplified distant LOD (`LOD1+`).
98    #[get(type(copy))]
99    pub(crate) lod_simplified_objects: usize,
100    /// Nanite-style meshlet clusters drawn this frame.
101    #[get(type(copy))]
102    pub(crate) meshlets_drawn: usize,
103    /// Nanite-style meshlet clusters culled by frustum or backface normal cones.
104    #[get(type(copy))]
105    pub(crate) meshlets_culled: usize,
106    /// Objects occluded by the conservative Hi-Z occlusion pyramid pre-pass.
107    #[get(type(copy))]
108    pub(crate) hiz_culled_objects: usize,
109    /// Active occupied cells inside the world-space Lumen Radiance Cache.
110    #[get(type(copy))]
111    pub(crate) lumen_cache_cells: usize,
112    /// Active point and spot lights binned into the 16x9x16 clustered froxel grid.
113    #[get(type(copy))]
114    pub(crate) active_local_lights: usize,
115    /// Depth-tested 3D Niagara particles composited this frame.
116    #[get(type(copy))]
117    pub(crate) particles_drawn: usize,
118    /// Coarse RT probes reused via analytical motion-vector temporal reprojection.
119    #[get(type(copy))]
120    pub(crate) probe_reproj_hits: usize,
121}
122
123/// Precomputed screen-space triangle rasterization setup record for parallel tiled G-Buffer rasterization.
124#[derive(Clone, Copy, Debug)]
125pub(crate) struct RasterTri2D {
126    /// Inclusive clamped top scanline index.
127    pub(crate) min_y: i32,
128    /// Inclusive clamped bottom scanline index.
129    pub(crate) max_y: i32,
130    /// Inclusive clamped left pixel coordinate.
131    pub(crate) min_x: i32,
132    /// Horizontal bounding-box span width (`max_x - min_x`).
133    pub(crate) span_max: i32,
134    /// Index into `shaded_tris`.
135    pub(crate) tri_id: u32,
136    /// Edge slopes `(dw0_dx, dw1_dx, dw2_dx)`.
137    pub(crate) slopes: [f32; 3],
138    /// Precomputed negative reciprocal edge slopes for span clipping.
139    pub(crate) neg_inv_slopes: [f32; 3],
140    /// Vertical barycentric step `(dw0_dy, dw1_dy, dw2_dy)`.
141    pub(crate) dw_dy: [f32; 3],
142    /// Barycentric coordinates evaluated at `(min_x + 0.5, min_y + 0.5)`.
143    pub(crate) w_start: [f32; 3],
144    /// Reverse-Z `1/w` evaluated at `(min_x + 0.5, min_y + 0.5)`.
145    pub(crate) inv_w_start: f32,
146    /// Horizontal `1/w` derivative per pixel.
147    pub(crate) d_inv_w_dx: f32,
148    /// Vertical `1/w` derivative per scanline.
149    pub(crate) d_inv_w_dy: f32,
150}
151
152/// Precomputed per-triangle Cook-Torrance GGX PBR shading record referenced by deferred G-Buffer indices.
153#[derive(Clone, Copy, Debug)]
154pub(crate) struct GShadeTri {
155    /// Camera-facing unit shading normal.
156    pub(crate) shade_n: Vec3,
157    /// Material linear base albedo.
158    pub(crate) mat_base: Vec3,
159    /// Material linear emissive radiance.
160    pub(crate) mat_emissive: Vec3,
161    /// Precomputed hemisphere sky ambient tint.
162    pub(crate) ambient_sky: Vec3,
163    /// Precomputed Schlick base specular reflectance `F0 = lerp(0.04, albedo, metallic)`.
164    pub(crate) f0: Vec3,
165    /// Clamped directional sun Lambertian term `max(N·L, 0)`.
166    pub(crate) n_dot_l: f32,
167    /// GGX roughness squared (`alpha^2 = roughness^4`).
168    pub(crate) alpha2: f32,
169    /// Energy-conserving diffuse scale `(1.0 - metallic)`.
170    pub(crate) diffuse_scale: f32,
171    /// Surface base reflectivity weight `[0.0, 1.0]`.
172    pub(crate) mat_refl: f32,
173    /// Surface metallic scalar `[0.0, 1.0]`.
174    pub(crate) metallic: f32,
175    /// Whether this surface traces specular reflections.
176    pub(crate) do_refl: bool,
177    /// Procedural surface detail mode attached to the triangle's material.
178    pub(crate) surface_detail: SurfaceDetailMode,
179}
180
181/// Structure-of-Arrays coarse deferred ray-tracing probe grid enabling contiguous SIMD bilateral denoise and upsampling.
182#[derive(Clone, Debug, Default)]
183pub(crate) struct RtProbeGridSoa {
184    /// Sun visibility factor per probe (`1.0` lit, `0.22` shadowed).
185    pub(crate) shadow: Vec<f32>,
186    /// Traced reflection linear red radiance.
187    pub(crate) refl_r: Vec<f32>,
188    /// Traced reflection linear green radiance.
189    pub(crate) refl_g: Vec<f32>,
190    /// Traced reflection linear blue radiance.
191    pub(crate) refl_b: Vec<f32>,
192    /// Colored indirect Lumen GI bounce red radiance.
193    pub(crate) gi_r: Vec<f32>,
194    /// Colored indirect Lumen GI bounce green radiance.
195    pub(crate) gi_g: Vec<f32>,
196    /// Colored indirect Lumen GI bounce blue radiance.
197    pub(crate) gi_b: Vec<f32>,
198    /// Ambient occlusion factor in `[0.42, 1.0]`.
199    pub(crate) ao: Vec<f32>,
200    /// Camera-space linear depth at probe center.
201    pub(crate) depth: Vec<f32>,
202    /// Surface normal X for bilateral edge stopping.
203    pub(crate) nx: Vec<f32>,
204    /// Surface normal Y for bilateral edge stopping.
205    pub(crate) ny: Vec<f32>,
206    /// Surface normal Z for bilateral edge stopping.
207    pub(crate) nz: Vec<f32>,
208    /// World-space surface X coordinate for temporal probe reprojection validation.
209    pub(crate) world_x: Vec<f32>,
210    /// World-space surface Y coordinate for temporal probe reprojection validation.
211    pub(crate) world_y: Vec<f32>,
212    /// World-space surface Z coordinate for temporal probe reprojection validation.
213    pub(crate) world_z: Vec<f32>,
214    /// Non-zero when this probe sits on valid scene geometry.
215    pub(crate) valid: Vec<u8>,
216}
217
218/// Fixed-capacity L1-stack single-row SoA probe buffer (`gw <= PROBE_ROW_STACK_CAP`) enabling zero-allocation streaming bilateral denoising inside `shade_deferred_band`.
219#[derive(Clone, Debug)]
220pub(crate) struct RtProbeRowStack {
221    /// Sun visibility factor across one probe row.
222    pub(crate) shadow: [f32; PROBE_ROW_STACK_CAP],
223    /// Reflection linear red radiance across one probe row.
224    pub(crate) refl_r: [f32; PROBE_ROW_STACK_CAP],
225    /// Reflection linear green radiance across one probe row.
226    pub(crate) refl_g: [f32; PROBE_ROW_STACK_CAP],
227    /// Reflection linear blue radiance across one probe row.
228    pub(crate) refl_b: [f32; PROBE_ROW_STACK_CAP],
229    /// Colored Lumen GI red radiance across one probe row.
230    pub(crate) gi_r: [f32; PROBE_ROW_STACK_CAP],
231    /// Colored Lumen GI green radiance across one probe row.
232    pub(crate) gi_g: [f32; PROBE_ROW_STACK_CAP],
233    /// Colored Lumen GI blue radiance across one probe row.
234    pub(crate) gi_b: [f32; PROBE_ROW_STACK_CAP],
235    /// Ambient occlusion factor across one probe row.
236    pub(crate) ao: [f32; PROBE_ROW_STACK_CAP],
237    /// Linear probe depth across one probe row.
238    pub(crate) depth: [f32; PROBE_ROW_STACK_CAP],
239    /// Surface normal X across one probe row.
240    pub(crate) nx: [f32; PROBE_ROW_STACK_CAP],
241    /// Surface normal Y across one probe row.
242    pub(crate) ny: [f32; PROBE_ROW_STACK_CAP],
243    /// Surface normal Z across one probe row.
244    pub(crate) nz: [f32; PROBE_ROW_STACK_CAP],
245    /// Validity flags (`0` sky, `1` geometry) across one probe row.
246    pub(crate) valid: [u8; PROBE_ROW_STACK_CAP],
247}
248
249/// Per-thread persistent L1-hot 2-row probe denoise scratch avoiding 25 KB per-band stack zero-initialization and reusing denoised boundary rows across contiguous chunks.
250#[derive(Clone, Debug)]
251pub(crate) struct RtProbeRowScratch {
252    /// Monotonic frame generation tag invalidating cached rows across frames.
253    pub(crate) frame_gen: u64,
254    /// Probe row index cached in `buf_a` (`usize::MAX` if invalid).
255    pub(crate) cached_gy_a: usize,
256    /// Probe row index cached in `buf_b` (`usize::MAX` if invalid).
257    pub(crate) cached_gy_b: usize,
258    /// First L1-hot denoised probe row buffer.
259    pub(crate) buf_a: RtProbeRowStack,
260    /// Second L1-hot denoised probe row buffer.
261    pub(crate) buf_b: RtProbeRowStack,
262}
263
264/// Zero-copy borrowed view over one contiguous row of SoA RT probes (stack-denoised or wide pre-denoised).
265#[derive(Clone, Copy)]
266pub(crate) struct RtProbeRowView<'a> {
267    /// Sun visibility slice for this row.
268    pub(crate) shadow: &'a [f32],
269    /// Reflection red slice.
270    pub(crate) refl_r: &'a [f32],
271    /// Reflection green slice.
272    pub(crate) refl_g: &'a [f32],
273    /// Reflection blue slice.
274    pub(crate) refl_b: &'a [f32],
275    /// Lumen GI red slice.
276    pub(crate) gi_r: &'a [f32],
277    /// Lumen GI green slice.
278    pub(crate) gi_g: &'a [f32],
279    /// Lumen GI blue slice.
280    pub(crate) gi_b: &'a [f32],
281    /// Ambient occlusion slice.
282    pub(crate) ao: &'a [f32],
283    /// Linear depth slice.
284    pub(crate) depth: &'a [f32],
285    /// Normal X slice.
286    pub(crate) nx: &'a [f32],
287    /// Normal Y slice.
288    pub(crate) ny: &'a [f32],
289    /// Normal Z slice.
290    pub(crate) nz: &'a [f32],
291    /// Validity flags slice.
292    pub(crate) valid: &'a [u8],
293}
294
295/// 16-byte-aligned 2x2 bilinear probe cell packed into 4-lane SIMD arrays and cached across consecutive horizontal pixels sharing `(gx0, gx1, tid)`.
296#[repr(C, align(16))]
297#[derive(Clone, Copy)]
298pub(crate) struct CachedProbeCell {
299    /// Four corner linear depths `[p00, p10, p01, p11]`.
300    pub(crate) depth: [f32; 4],
301    /// Four corner sun visibility factors.
302    pub(crate) shadow: [f32; 4],
303    /// Four corner reflection linear red samples.
304    pub(crate) refl_r: [f32; 4],
305    /// Four corner reflection linear green samples.
306    pub(crate) refl_g: [f32; 4],
307    /// Four corner reflection linear blue samples.
308    pub(crate) refl_b: [f32; 4],
309    /// Four corner GI linear red samples.
310    pub(crate) gi_r: [f32; 4],
311    /// Four corner GI linear green samples.
312    pub(crate) gi_g: [f32; 4],
313    /// Four corner GI linear blue samples.
314    pub(crate) gi_b: [f32; 4],
315    /// Four corner ambient occlusion samples.
316    pub(crate) ao: [f32; 4],
317    /// Four corner bilateral depth tolerance scale (`0.58` high-agreement, `0.20` low-agreement).
318    pub(crate) tol_scale: [f32; 4],
319    /// Four corner bilateral depth tolerance bias (`2.4` high-agreement, `0.75` low-agreement).
320    pub(crate) tol_bias: [f32; 4],
321    /// Four corner SIMD validity bitmasks (`0xFFFF_FFFF` when corner passes normal test, else `0`).
322    pub(crate) valid_u32: [u32; 4],
323    /// Compact 4-bit corner validity mask (`0` triggers immediate edge fallback).
324    pub(crate) vmask: u8,
325}
326
327/// 16-byte-aligned 32-pixel L1-hot Structure-of-Arrays run scratch decoupling probe bilateral upsampling from zero-spill specialized PBR shading kernels.
328#[repr(C, align(16))]
329#[derive(Clone, Copy)]
330pub(crate) struct RunScratch32 {
331    /// Linear camera depth for up to 32 contiguous pixels of one triangle.
332    pub(crate) depths: [f32; 32],
333    /// Interpolated sun shadow factor for up to 32 pixels.
334    pub(crate) shadow: [f32; 32],
335    /// Interpolated reflection linear red for up to 32 pixels.
336    pub(crate) refl_r: [f32; 32],
337    /// Interpolated reflection linear green for up to 32 pixels.
338    pub(crate) refl_g: [f32; 32],
339    /// Interpolated reflection linear blue for up to 32 pixels.
340    pub(crate) refl_b: [f32; 32],
341    /// Interpolated Lumen GI linear red for up to 32 pixels.
342    pub(crate) gi_r: [f32; 32],
343    /// Interpolated Lumen GI linear green for up to 32 pixels.
344    pub(crate) gi_g: [f32; 32],
345    /// Interpolated Lumen GI linear blue for up to 32 pixels.
346    pub(crate) gi_b: [f32; 32],
347    /// Interpolated ambient occlusion for up to 32 pixels.
348    pub(crate) ao: [f32; 32],
349}
350
351/// Writable 4-pixel scanline slice targets and optional quarter-res HDR bloom slot for `shade_span_4x_specialized`.
352pub(crate) struct SpanShadeOut<'a> {
353    /// 16-byte RGBA8 destination span.
354    pub(crate) rgba: &'a mut [u8],
355    /// 4-byte Rec.601 luma destination span.
356    pub(crate) luma: &'a mut [u8],
357    /// Optional `(lane_index, bloom_cell)` HDR excess radiance slot.
358    pub(crate) bloom: Option<(usize, &'a mut [f32; 4])>,
359}
360
361/// Writable full-scanline color, luma, and quarter-res bloom buffers passed to 32-pixel run shaders.
362pub(crate) struct RunRowOut<'a> {
363    /// Full scanline RGBA8 output slice.
364    pub(crate) color: &'a mut [u8],
365    /// Full scanline Rec.601 luma output slice.
366    pub(crate) luma: &'a mut [u8],
367    /// Whether bloom extraction is active on this scanline (`(py & 3) == 0`).
368    pub(crate) write_bloom: bool,
369    /// Starting index of this scanline's bloom row inside `bloom_band`.
370    pub(crate) bloom_off: usize,
371    /// Writable quarter-resolution HDR bloom band slice.
372    pub(crate) bloom_band: &'a mut [[f32; 4]],
373}
374
375/// Shared read-only probe rows and horizontal bilinear stepping context for `upsample_run_probes_32` and `shade_tri_run_4x`.
376#[derive(Clone, Copy)]
377pub(crate) struct ProbeBandContext<'a> {
378    /// Top denoised probe row view `gy0`.
379    pub(crate) top_row: &'a RtProbeRowView<'a>,
380    /// Bottom denoised probe row view `gy1`.
381    pub(crate) bottom_row: &'a RtProbeRowView<'a>,
382    /// Vertical bilinear weight for `r0`.
383    pub(crate) wy0: f32,
384    /// Vertical bilinear weight for `r1`.
385    pub(crate) wy1: f32,
386    /// Maximum valid coarse probe column index `gw - 1`.
387    pub(crate) gw_max: usize,
388    /// Doubled integer probe stride `rt_step * 2`.
389    pub(crate) step2_i32: i32,
390    /// Precomputed fractional horizontal lookup table indexed by `sub_x`.
391    pub(crate) fx_lut: &'a [f32; 16],
392}
393
394/// Raw writable base addresses for lock-free disjoint-tile writes into `RtProbeGridSoa`.
395#[derive(Clone, Copy, Debug)]
396pub(crate) struct RtProbeGridMutPtrs {
397    /// Base pointer for `shadow`.
398    pub(crate) shadow: usize,
399    /// Base pointer for `refl_r`.
400    pub(crate) refl_r: usize,
401    /// Base pointer for `refl_g`.
402    pub(crate) refl_g: usize,
403    /// Base pointer for `refl_b`.
404    pub(crate) refl_b: usize,
405    /// Base pointer for `gi_r`.
406    pub(crate) gi_r: usize,
407    /// Base pointer for `gi_g`.
408    pub(crate) gi_g: usize,
409    /// Base pointer for `gi_b`.
410    pub(crate) gi_b: usize,
411    /// Base pointer for `ao`.
412    pub(crate) ao: usize,
413    /// Base pointer for `depth`.
414    pub(crate) depth: usize,
415    /// Base pointer for `nx`.
416    pub(crate) nx: usize,
417    /// Base pointer for `ny`.
418    pub(crate) ny: usize,
419    /// Base pointer for `nz`.
420    pub(crate) nz: usize,
421    /// Base pointer for `world_x`.
422    pub(crate) world_x: usize,
423    /// Base pointer for `world_y`.
424    pub(crate) world_y: usize,
425    /// Base pointer for `world_z`.
426    pub(crate) world_z: usize,
427    /// Base pointer for `valid`.
428    pub(crate) valid: usize,
429}
430
431/// Shared read-only inputs for fused Barrier 1 tiled rasterization and L1-hot coherent 2x2 probe packet tracing.
432pub(crate) struct TileRasterProbeInputs<'a> {
433    /// Screen-space triangle setup records.
434    pub(crate) raster_tris: &'a [RasterTri2D],
435    /// Flat CSR prefix offsets per tile (`len == total_tiles + 1`).
436    pub(crate) tile_offsets: &'a [u32],
437    /// Binned triangle indices into `raster_tris`.
438    pub(crate) tile_tri_indices: &'a [u32],
439    /// Precomputed GGX triangle shading records.
440    pub(crate) shaded_tris: &'a [GShadeTri],
441    /// Static world BVH4/BVH8 acceleration structure.
442    pub(crate) static_bvh: &'a Bvh3D,
443    /// Active object-space dynamic raytracing instances.
444    pub(crate) dyn_instances: &'a [DynamicRayInstance],
445    /// Local-space BVH4/BVH8 cache indexed by `mesh_id`.
446    pub(crate) local_bvhs: &'a [Option<Bvh3D>],
447    /// Previous frame coarse RT probe grid for world-space-validated temporal checkerboard reuse.
448    pub(crate) prev_probes: Option<&'a RtProbeGridSoa>,
449    /// Previous frame view-projection matrix for analytical motion-vector probe reprojection.
450    pub(crate) prev_view_proj: Mat4,
451    /// Previous frame internal framebuffer `(width, height)` for motion-vector reprojection.
452    pub(crate) prev_render_dims: (usize, usize),
453    /// Previous frame coarse RT probe stride.
454    pub(crate) prev_rt_step: usize,
455    /// Previous frame coarse RT probe grid width.
456    pub(crate) prev_gw: usize,
457    /// Previous frame coarse RT probe grid height.
458    pub(crate) prev_gh: usize,
459    /// Optional read-only world-space Lumen Radiance Cache for O(1) multi-bounce indirect GI lookups.
460    pub(crate) lumen_cache: Option<&'a LumenRadianceCache>,
461    /// Optional read-only Clustered Deferred local light grid evaluated per coarse probe.
462    pub(crate) light_clusters: Option<&'a LightClusterGrid3D>,
463    /// Optional read-only Virtual Shadow Map for zero-BVH-ray distant shadow sampling.
464    pub(crate) vsm: Option<&'a VirtualShadowMap>,
465    /// Enables O(1) VSM lookup for distant probes (`depth > 42m`) instead of long-range BVH shadow rays.
466    pub(crate) use_vsm_far_shadows: bool,
467    /// Alternating checkerboard parity (`0` or `1`) selecting which 2x2 probe blocks refresh vs reuse.
468    pub(crate) probe_checker_parity: usize,
469    /// Tile edge dimension in pixels (`<= 64`, multiple of `rt_step` when RT active).
470    pub(crate) tile_px: usize,
471    /// Number of tiles horizontally.
472    pub(crate) tiles_x: usize,
473}
474
475/// Shared read-only inputs for fused Barrier 2 streaming bilateral denoise and vectorized deferred PBR shading.
476pub(crate) struct ShadeBandInputs<'a> {
477    /// Reverse-Z `1/w` depth buffer.
478    pub(crate) depth_buf: &'a [f32],
479    /// Deferred G-Buffer triangle IDs.
480    pub(crate) g_tri_idx: &'a [u32],
481    /// Precomputed GGX triangle shading records.
482    pub(crate) shaded_tris: &'a [GShadeTri],
483    /// Raw coarse RT probe SoA grid written by Barrier 1.
484    pub(crate) raw_probes: &'a RtProbeGridSoa,
485    /// Optional pre-denoised full probe grid used only when `gw > 256` (e.g. 4K viewports).
486    pub(crate) wide_denoised_probes: &'a RtProbeGridSoa,
487    /// Whether bilateral 3x3 probe denoising is active during row streaming (`gw <= 256`).
488    pub(crate) denoise_probes: bool,
489    /// Whether GI/AO channels require 3x3 bilateral denoising (`true` for `FullPathTracedGi`, `false` for analytic clustered local lights).
490    pub(crate) denoise_gi_channels: bool,
491    /// Static world BVH4/BVH8 acceleration structure.
492    pub(crate) static_bvh: &'a Bvh3D,
493    /// Active object-space dynamic raytracing instances.
494    pub(crate) dyn_instances: &'a [DynamicRayInstance],
495    /// Local-space BVH4/BVH8 cache indexed by `mesh_id`.
496    pub(crate) local_bvhs: &'a [Option<Bvh3D>],
497    /// Atomic bitset marking quarter-resolution bloom rows that received non-zero HDR radiance (`576` bits -> `bh <= 576`).
498    pub(crate) bloom_row_bits: &'a [AtomicU64; 9],
499}
500
501/// Shared read-only inputs for Barrier 3 vectorized FXAA/MLAA/TAA and bilinear HDR bloom compositing.
502pub(crate) struct PostProcessInputs<'a> {
503    /// Tone-mapped RGBA8 intermediate framebuffer.
504    pub(crate) color_src: &'a [u8],
505    /// Rec.601 luma buffer populated during deferred shading.
506    pub(crate) luma: &'a [u8],
507    /// Deferred G-Buffer triangle IDs for geometry-aware AA edge detection.
508    pub(crate) g_tri_idx: &'a [u32],
509    /// Blurred quarter-resolution HDR bloom buffer (`[r, g, b, 0]`).
510    pub(crate) bloom: &'a [[f32; 4]],
511    /// Active bloom tile mask (`1` where bloom contributes `>= 1` RGB LSB).
512    pub(crate) bloom_tile_active: &'a [u8],
513    /// Previous frame RGBA8 TAA temporal history buffer.
514    pub(crate) taa_history: &'a [u8],
515}
516
517/// Immutable per-frame camera, lighting, volumetric, and ray-tracing configuration shared across worker threads.
518#[derive(Clone, Copy, Debug)]
519pub(crate) struct DeferredFrameContext {
520    /// Framebuffer width in pixels.
521    pub(crate) width: usize,
522    /// Framebuffer height in pixels.
523    pub(crate) height: usize,
524    /// Coarse RT grid width in probes.
525    pub(crate) grid_width: usize,
526    /// Coarse RT grid height in probes.
527    pub(crate) grid_height: usize,
528    /// Quarter-res HDR bloom width.
529    pub(crate) bloom_width: usize,
530    /// Pixel stride per coarse RT probe.
531    pub(crate) raytrace_step: usize,
532    /// Reciprocal framebuffer width.
533    pub(crate) inv_width: f32,
534    /// Reciprocal framebuffer height.
535    pub(crate) inv_height: f32,
536    /// Camera world position.
537    pub(crate) camera_position: Vec3,
538    /// Camera unit forward basis.
539    pub(crate) camera_forward: Vec3,
540    /// Camera right basis scaled by `half_w`.
541    pub(crate) camera_right_scaled: Vec3,
542    /// Camera up basis scaled by `half_h`.
543    pub(crate) camera_up_scaled: Vec3,
544    /// Active directional sun & sky parameters.
545    pub(crate) sun: DirectionalLight3D,
546    /// Precomputed safe reciprocal sun direction for fast shadow BVH traversal.
547    pub(crate) inv_sun_dir: Vec3,
548    /// Precomputed 16-tap Vogel-disk blue-noise soft-shadow `(dir, inv_dir)` ray table hoisted once per frame.
549    pub(crate) soft_shadow_rays: [(Vec3, Vec3); 16],
550    /// Monotonic frame index driving deterministic blue-noise temporal rotation across TSR/TAA frames.
551    pub(crate) frame_index: usize,
552    /// Active ray-tracing quality tier.
553    pub(crate) raytrace_mode: RayTracingMode,
554    /// Maximum reflection/GI bounce depth (`0..=3`).
555    pub(crate) reflection_bounces: u8,
556    /// Whether volumetric height/distance fog and crepuscular sun-shafts are enabled.
557    pub(crate) fog_on: bool,
558    /// Precomputed inverse fog attenuation distance.
559    pub(crate) inv_fog_distance: f32,
560    /// Exposure scale derived from physically based camera EV100.
561    pub(crate) exposure_scale: f32,
562    /// Whether quarter-res emissive/specular bloom extraction is active.
563    pub(crate) bloom_on: bool,
564    /// Whether dynamic local point/spot lights are active in `LightClusterGrid3D` and injected into the GI probe channels.
565    pub(crate) has_clustered_lights: bool,
566    /// Monotonic frame generation tag for per-thread probe denoise scratch cache invalidation.
567    pub(crate) probe_frame_generation: u64,
568}
569
570/// Per-chunk reusable scratch buffers eliminating heap allocations in the 8-way parallel geometry front-end.
571#[derive(Clone, Debug, Default)]
572pub(crate) struct GeomChunkScratch {
573    /// Per-chunk precomputed GGX shading triangle records.
574    pub(crate) shaded_tris: Vec<GShadeTri>,
575    /// Per-chunk precomputed screen-space rasterization setup records.
576    pub(crate) raster_tris: Vec<RasterTri2D>,
577    /// Per-chunk transformed vertex scratch `(clip_pos, world_pos)`.
578    pub(crate) projected_verts: Vec<([f32; 4], Vec3)>,
579    /// Per-chunk visible meshlet triangle ranges.
580    pub(crate) cluster_ranges: Vec<(usize, usize)>,
581    /// Per-chunk visible object count.
582    pub(crate) visible_objects: usize,
583    /// Per-chunk Hi-Z occluded object count.
584    pub(crate) hiz_culled_objects: usize,
585    /// Per-chunk simplified LOD object count.
586    pub(crate) lod_simplified_objects: usize,
587    /// Per-chunk drawn meshlet count.
588    pub(crate) meshlets_drawn: usize,
589    /// Per-chunk culled meshlet count.
590    pub(crate) meshlets_culled: usize,
591    /// Per-chunk unique mesh IDs for instanced batch telemetry.
592    pub(crate) mesh_ids: Vec<usize>,
593}
594
595/// Shared read-only scene, frustum, Hi-Z, and lighting state passed to per-object geometry front-end projection.
596pub(crate) struct GeomPassContext<'a> {
597    /// All scene objects in the world.
598    pub(crate) objects: &'a [SceneObject3D],
599    /// Mesh LOD chain library indexed by `mesh_id`.
600    pub(crate) mesh_lib: &'a [MeshLodChain],
601    /// Conservative Hi-Z depth pyramid for occlusion queries.
602    pub(crate) hiz_pyramid: &'a HiZPyramid,
603    /// Flags marking near pre-pass occluders (`1` = stamped occluder).
604    pub(crate) hiz_occluder_flags: &'a [u8],
605    /// Active view frustum planes.
606    pub(crate) frustum: Frustum3D,
607    /// Current frame view-projection matrix.
608    pub(crate) view_proj: Mat4,
609    /// Camera world-space position.
610    pub(crate) cam_pos: Vec3,
611    /// Normalized directional sun vector.
612    pub(crate) sun_dir: Vec3,
613    /// Linear HDR horizon sky color.
614    pub(crate) sky_horizon: Vec3,
615    /// Linear HDR zenith sky color.
616    pub(crate) sky_zenith: Vec3,
617    /// Vertical projection focal length in pixels.
618    pub(crate) focal_px: f32,
619    /// LOD distance bias multiplier.
620    pub(crate) lod_bias: f32,
621    /// Clamped near clip plane distance.
622    pub(crate) near_plane: f32,
623    /// Render viewport width in pixels as `f32`.
624    pub(crate) w_f: f32,
625    /// Render viewport height in pixels as `f32`.
626    pub(crate) h_f: f32,
627    /// Maximum valid pixel X coordinate (`width - 1`).
628    pub(crate) w_max_i: i32,
629    /// Maximum valid pixel Y coordinate (`height - 1`).
630    pub(crate) h_max_i: i32,
631    /// Subpixel temporal jitter X in pixels.
632    pub(crate) jitter_x: f32,
633    /// Subpixel temporal jitter Y in pixels.
634    pub(crate) jitter_y: f32,
635    /// Whether frustum and meshlet culling are active.
636    pub(crate) frustum_on: bool,
637    /// Whether Hi-Z occlusion culling is active.
638    pub(crate) hiz_active: bool,
639    /// Whether ray-traced reflections are enabled.
640    pub(crate) use_rt_refl: bool,
641}
642
643/// Writable per-pass or per-chunk geometry buffers and counters updated by `process_visible_object_geom`.
644pub(crate) struct GeomPassOut<'a> {
645    /// Destination precomputed GGX triangle shading list.
646    pub(crate) shaded_tris: &'a mut Vec<GShadeTri>,
647    /// Destination 2D screen-space raster setup list.
648    pub(crate) raster_tris: &'a mut Vec<RasterTri2D>,
649    /// Reusable per-object transformed vertex buffer.
650    pub(crate) projected_verts: &'a mut Vec<([f32; 4], Vec3)>,
651    /// Reusable per-object visible meshlet triangle ranges.
652    pub(crate) cluster_ranges: &'a mut Vec<(usize, usize)>,
653    /// Optional mesh ID accumulator for parallel chunks (`None` when writing directly to `unique_meshes`).
654    pub(crate) mesh_ids: Option<&'a mut Vec<usize>>,
655    /// Optional direct unique mesh set for sequential processing.
656    pub(crate) unique_meshes: Option<&'a mut HashSet<usize>>,
657    /// Visible object count accumulator.
658    pub(crate) visible_objects: usize,
659    /// Hi-Z occluded object count accumulator.
660    pub(crate) hiz_culled_objects: usize,
661    /// Simplified LOD object count accumulator.
662    pub(crate) lod_simplified_objects: usize,
663    /// Drawn meshlet count accumulator.
664    pub(crate) meshlets_drawn: usize,
665    /// Culled meshlet count accumulator.
666    pub(crate) meshlets_culled: usize,
667}
668
669/// Zero-allocation UE5-class Deferred GGX PBR + Persistent Multi-Core SIMD BVH4/BVH8 + Nanite Hi-Z + Lumen GI + VSM + Clustered Lighting + TSR 3D renderer.
670#[derive(Clone, Data, Debug)]
671pub struct Renderer3D {
672    /// Pre-allocated RGBA8 tone-mapped intermediate pixel buffer.
673    pub(crate) color_buffer: Vec<u8>,
674    /// Pre-allocated RGBA8 temporal history buffer for variance-clamped TAA.
675    pub(crate) aa_buffer: Vec<u8>,
676    /// Pre-allocated floating-point linear `1/w` reverse-Z depth buffer (`0.0` = sky).
677    pub(crate) depth_buffer: Vec<f32>,
678    /// Deferred G-Buffer triangle index per pixel (`u32::MAX` = sky).
679    #[get(skip)]
680    #[get_mut(skip)]
681    #[set(skip)]
682    pub(crate) g_tri_idx: Vec<u32>,
683    /// Single-byte per-pixel Rec.601 luma buffer populated during deferred shading for fast morphological AA.
684    #[get(skip)]
685    #[get_mut(skip)]
686    #[set(skip)]
687    pub(crate) luma_buffer: Vec<u8>,
688    /// Per-frame precomputed GGX triangle shading records.
689    #[get(skip)]
690    #[get_mut(skip)]
691    #[set(skip)]
692    pub(crate) shaded_tris: Vec<GShadeTri>,
693    /// Persistent reusable RGBA8 final output buffer eliminating per-frame allocations in `render_world_rgba`.
694    #[get(skip)]
695    #[get_mut(skip)]
696    #[set(skip)]
697    pub(crate) rgba_scratch: Vec<u8>,
698    /// Structure-of-Arrays coarse coherent ray-tracing probe grid.
699    #[get(skip)]
700    #[get_mut(skip)]
701    #[set(skip)]
702    pub(crate) rt_probes: RtProbeGridSoa,
703    /// Previous frame coarse RT probe grid swapped in O(1) for temporal checkerboard probe reuse.
704    #[get(skip)]
705    #[get_mut(skip)]
706    #[set(skip)]
707    pub(crate) prev_rt_probes: RtProbeGridSoa,
708    /// Whether `prev_rt_probes` holds valid history matching `(prev_probe_gw, prev_probe_gh, prev_probe_rt_mode)`.
709    #[get(skip)]
710    #[get_mut(skip)]
711    #[set(skip)]
712    pub(crate) has_probe_history: bool,
713    /// Coarse probe width stored in `prev_rt_probes`.
714    #[get(skip)]
715    #[get_mut(skip)]
716    #[set(skip)]
717    pub(crate) prev_probe_gw: usize,
718    /// Coarse probe height stored in `prev_rt_probes`.
719    #[get(skip)]
720    #[get_mut(skip)]
721    #[set(skip)]
722    pub(crate) prev_probe_gh: usize,
723    /// Ray-tracing mode stored in `prev_rt_probes`.
724    #[get(skip)]
725    #[get_mut(skip)]
726    #[set(skip)]
727    pub(crate) prev_probe_rt_mode: RayTracingMode,
728    /// Previous frame directional sun vector for invalidating temporal probes on lighting changes.
729    #[get(skip)]
730    #[get_mut(skip)]
731    #[set(skip)]
732    pub(crate) prev_sun_dir: Vec3,
733    /// Fallback full-grid denoised SoA probe buffer used only when `gw > 256` (4K+).
734    #[get(skip)]
735    #[get_mut(skip)]
736    #[set(skip)]
737    pub(crate) rt_probes_wide_denoised: RtProbeGridSoa,
738    /// Quarter-res 16-byte-aligned HDR bloom extraction and vertical blur buffer.
739    #[get(skip)]
740    #[get_mut(skip)]
741    #[set(skip)]
742    pub(crate) bloom_a: Vec<[f32; 4]>,
743    /// Quarter-res 16-byte-aligned HDR bloom horizontal blur scratch buffer.
744    #[get(skip)]
745    #[get_mut(skip)]
746    #[set(skip)]
747    pub(crate) bloom_b: Vec<[f32; 4]>,
748    /// Quarter-res active-bloom tile mask (`1` when any bilinear corner contributes `>= 1` RGB LSB) skipping dark tiles in post-processing.
749    #[get(skip)]
750    #[get_mut(skip)]
751    #[set(skip)]
752    pub(crate) bloom_tile_active: Vec<u8>,
753    /// Reusable front-to-back object sorting scratch buffer.
754    #[get(skip)]
755    #[get_mut(skip)]
756    #[set(skip)]
757    pub(crate) visible_scratch: Vec<(f32, usize)>,
758    /// Reusable meshlet triangle-range scratch buffer eliminating per-object heap allocations.
759    #[get(skip)]
760    #[get_mut(skip)]
761    #[set(skip)]
762    pub(crate) cluster_ranges_scratch: Vec<(usize, usize)>,
763    /// Reusable per-object transformed vertex cache `(clip_pos, world_pos)` avoiding redundant vertex transforms.
764    #[get(skip)]
765    #[get_mut(skip)]
766    #[set(skip)]
767    pub(crate) projected_verts_scratch: Vec<([f32; 4], Vec3)>,
768    /// Reusable unique mesh-id set for instancing telemetry.
769    #[get(skip)]
770    #[get_mut(skip)]
771    #[set(skip)]
772    pub(crate) unique_meshes_scratch: HashSet<usize>,
773    /// Reusable saved dynamic-object transforms for zero-allocation interpolated rendering.
774    #[get(skip)]
775    #[get_mut(skip)]
776    #[set(skip)]
777    pub(crate) saved_objs_scratch: Vec<(usize, Transform3D, AxisAlignedBox3D)>,
778    /// Reusable screen-space triangle setup list for parallel tiled rasterization.
779    #[get(skip)]
780    #[get_mut(skip)]
781    #[set(skip)]
782    pub(crate) raster_tris_scratch: Vec<RasterTri2D>,
783    /// Reusable per-tile triangle count array for flat CSR binning.
784    #[get(skip)]
785    #[get_mut(skip)]
786    #[set(skip)]
787    pub(crate) tile_counts_scratch: Vec<u32>,
788    /// Reusable flat CSR prefix-sum offset array (`total_tiles + 1`).
789    #[get(skip)]
790    #[get_mut(skip)]
791    #[set(skip)]
792    pub(crate) tile_offsets_scratch: Vec<u32>,
793    /// Reusable per-tile insertion cursor array for flat CSR binning.
794    #[get(skip)]
795    #[get_mut(skip)]
796    #[set(skip)]
797    pub(crate) tile_cursors_scratch: Vec<u32>,
798    /// Reusable flat array of binned triangle indices across all screen tiles.
799    #[get(skip)]
800    #[get_mut(skip)]
801    #[set(skip)]
802    pub(crate) tile_tri_indices_scratch: Vec<u32>,
803    /// Optional shared-device GPU composite target for zero-readback single-pass UI+3D compositing.
804    #[get(skip)]
805    #[get_mut(skip)]
806    #[set(skip)]
807    pub(crate) gpu_target: GpuCompositeTarget,
808    /// Whether `aa_buffer` holds a valid previous frame compatible with temporal anti-aliasing.
809    #[get(skip)]
810    #[get_mut(skip)]
811    #[set(skip)]
812    pub(crate) has_taa_history: bool,
813    /// Previous frame view-projection fingerprint used to detect camera cuts for TAA.
814    #[get(skip)]
815    #[get_mut(skip)]
816    #[set(skip)]
817    pub(crate) prev_vp_m0: f32,
818    /// Full previous frame view-projection matrix driving analytical motion-vector probe reprojection and TSR.
819    #[get(skip)]
820    #[get_mut(skip)]
821    #[set(skip)]
822    pub(crate) prev_view_proj: Mat4,
823    /// Whether `prev_view_proj` contains a valid previous frame transform.
824    #[get(skip)]
825    #[get_mut(skip)]
826    #[set(skip)]
827    pub(crate) has_prev_vp: bool,
828    /// Previous frame internal render dimensions `(width, height)`.
829    #[get(skip)]
830    #[get_mut(skip)]
831    #[set(skip)]
832    pub(crate) prev_render_dims: (usize, usize),
833    /// Previous frame coarse RT probe stride.
834    #[get(skip)]
835    #[get_mut(skip)]
836    #[set(skip)]
837    pub(crate) prev_rt_step: usize,
838    /// Conservative reverse-Z hierarchical depth pyramid for Nanite-style occlusion culling.
839    #[get(skip)]
840    #[get_mut(skip)]
841    #[set(skip)]
842    pub(crate) hiz_pyramid: HiZPyramid,
843    /// Reusable occluder pre-pass flags marking stamped near occluders (`len == visible_scratch.len()`).
844    #[get(skip)]
845    #[get_mut(skip)]
846    #[set(skip)]
847    pub(crate) hiz_occluder_flags_scratch: Vec<u8>,
848    /// Persistent 2-cascade world-space Lumen Radiance Cache enabling O(1) multi-bounce indirect GI.
849    #[get(skip)]
850    #[get_mut(skip)]
851    #[set(skip)]
852    pub(crate) lumen_cache: LumenRadianceCache,
853    /// Pre-allocated 16x9x16 logarithmic-Z froxel grid for UE5 Clustered Deferred local lighting.
854    #[get(skip)]
855    #[get_mut(skip)]
856    #[set(skip)]
857    pub(crate) light_clusters: LightClusterGrid3D,
858    /// Two-cascade texel-snapped Virtual Shadow Map with static page caching and 4-tap PCF.
859    #[get(skip)]
860    #[get_mut(skip)]
861    #[set(skip)]
862    pub(crate) virtual_shadow_map: VirtualShadowMap,
863    /// UE5 Temporal Super Resolution upscaler reconstructing sub-native frames with motion vectors and RCAS.
864    #[get(skip)]
865    #[get_mut(skip)]
866    #[set(skip)]
867    pub(crate) tsr_upscaler: TsrUpscaler,
868    /// Reusable intermediate RGBA8 scratch buffer for sub-native TSR upscaling and bloom-to-TSR handoff.
869    #[get(skip)]
870    #[get_mut(skip)]
871    #[set(skip)]
872    pub(crate) tsr_internal_scratch: Vec<u8>,
873    /// Damped PI frame-pacing governor preventing FPS oscillation across variable GPU/CPU workloads.
874    pub(crate) frame_governor: AdaptiveFrameGovernor,
875    /// Compile-once UE5 Render Dependency Graph describing frame pass order and transient memory aliasing.
876    pub(crate) render_graph: RenderGraph3D,
877    /// Optional additive RT probe stride bias (`0..=2`) modulated by `AdaptiveFrameGovernor` under heavy load.
878    #[get(type(copy))]
879    pub(crate) rt_stride_bias: usize,
880    /// Persistent reusable per-chunk buffers for deterministic 8-way parallel geometry front-end processing in dense worlds.
881    #[get(skip)]
882    #[get_mut(skip)]
883    #[set(skip)]
884    pub(crate) geom_chunks_scratch: Vec<GeomChunkScratch>,
885    /// Smoothly adapted UE5-style eye-adaptation exposure multiplier (`1.0` on frame 0).
886    #[get(type(copy))]
887    pub(crate) adapted_exposure: f32,
888    /// Monotonic frame counter driving Halton(2, 3) temporal subpixel jitter.
889    #[get(skip)]
890    #[get_mut(skip)]
891    #[set(skip)]
892    pub(crate) frame_index: u32,
893    /// Last rendered `World3D::world_revision` enabling HUD-only dirty frames to reuse the cached 3D frame.
894    #[get(type(copy))]
895    pub(crate) last_world_revision: u64,
896    /// Quality and viewport configuration fingerprint paired with `last_world_revision`.
897    #[get(skip)]
898    #[get_mut(skip)]
899    #[set(skip)]
900    pub(crate) last_quality_fingerprint: u64,
901    /// Number of consecutive static-world TAA accumulation frames completed since the last world change.
902    #[get(type(copy))]
903    pub(crate) taa_accumulated_frames: u32,
904    /// Total HUD-only dirty frames satisfied from the cached 3D framebuffer without re-rasterizing.
905    #[get(type(copy))]
906    pub(crate) cached_world_reuses: u64,
907    /// Last rendered internal width.
908    #[get(type(copy))]
909    pub(crate) width: u32,
910    /// Last rendered internal height.
911    #[get(type(copy))]
912    pub(crate) height: u32,
913    /// Telemetry from the most recent frame.
914    #[get(type(copy))]
915    pub(crate) last_stats: RenderStats3D,
916}