euv-core 0.47.1

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
use super::*;

/// Per-worker atomic wakeup epoch and condition variable slot eliminating shared-mutex contention and cache-line false sharing in `Engine3dWorkerPool`.
#[cfg(not(target_arch = "wasm32"))]
#[repr(align(128))]
#[derive(Debug, Default)]
pub(crate) struct Engine3dWorkerSlot {
    /// Monotonically incremented epoch signaling this worker to run the active job.
    pub(crate) epoch: AtomicUsize,
    /// Non-zero while this worker is parked on `wake` and requires condvar notification.
    pub(crate) parked: AtomicUsize,
    /// Private sleep mutex paired with `wake`.
    pub(crate) lock: Mutex<()>,
    /// Condition variable waking this worker when parked between frames.
    pub(crate) wake: Condvar,
}

/// Shared lock-free dispatch state coordinating caller and persistent 3D background workers.
#[cfg(not(target_arch = "wasm32"))]
#[repr(align(128))]
#[derive(Debug)]
pub(crate) struct Engine3dPoolShared {
    /// Raw pointer address of the caller-pinned `Engine3dJob` (`0` when idle).
    pub(crate) active_job: AtomicUsize,
    /// Number of background workers woken for the active dispatch.
    pub(crate) active_workers: AtomicUsize,
    /// Non-zero while the calling thread is parked waiting for workers to complete.
    pub(crate) caller_parked: AlignedAtomicUsize,
    /// Caller sleep mutex paired with `wake_caller`.
    pub(crate) caller_lock: Mutex<()>,
    /// Condition variable waking the calling thread once all active workers finish.
    pub(crate) wake_caller: Condvar,
    /// Per-worker wakeup slots (`len == worker_count`).
    pub(crate) slots: Vec<Engine3dWorkerSlot>,
}

/// Active work-stealing range job executed synchronously across caller and persistent 3D worker threads with 128-byte isolated atomics.
#[cfg(not(target_arch = "wasm32"))]
#[repr(align(128))]
#[derive(Debug)]
pub(crate) struct Engine3dJob {
    /// Type-erased chunk execution trampoline.
    pub(crate) trampoline: fn(usize, usize, usize),
    /// Caller-pinned closure reference encoded as `usize`.
    pub(crate) ctx_ptr: usize,
    /// Total logical items across all chunks.
    pub(crate) total_items: usize,
    /// Number of items per dynamic work-stealing chunk.
    pub(crate) chunk_size: usize,
    /// Total chunks to claim (`total_items.div_ceil(chunk_size)`).
    pub(crate) total_chunks: usize,
    /// Cache-line-isolated atomic cursor of the next unclaimed chunk index.
    pub(crate) next_chunk: AlignedAtomicUsize,
    /// Cache-line-isolated atomic count of background workers finished observing this epoch.
    pub(crate) workers_done: AlignedAtomicUsize,
}

/// Persistent warm thread pool eliminating per-frame OS thread spawns in `Renderer3D`.
#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug)]
pub(crate) struct Engine3dWorkerPool {
    /// Number of background worker threads (excluding the calling thread).
    pub(crate) worker_count: usize,
    /// Non-blocking re-entrancy guard serializing top-level dispatches cleanly.
    pub(crate) dispatch_lock: Mutex<()>,
    /// Shared lock-free atomic dispatch state and per-worker wakeup slots.
    pub(crate) shared: Arc<Engine3dPoolShared>,
}

/// Per-frame telemetry emitted by `Renderer3D` for live FPS/RT/LOD/Nanite/culling diagnostics.
#[derive(Clone, Copy, Data, Debug, Default, PartialEq)]
pub struct RenderStats3D {
    /// Internal rasterized framebuffer width in pixels.
    #[get(type(copy))]
    pub(crate) render_width: u32,
    /// Internal rasterized framebuffer height in pixels.
    #[get(type(copy))]
    pub(crate) render_height: u32,
    /// Active objects rendered inside frustum & chunk stream radius.
    #[get(type(copy))]
    pub(crate) visible_objects: usize,
    /// Objects rejected by 6-plane frustum culling or chunk draw distance.
    #[get(type(copy))]
    pub(crate) culled_objects: usize,
    /// Deduplicated GPU instancing draw batches.
    #[get(type(copy))]
    pub(crate) instanced_batches: usize,
    /// Triangles rasterized after backface culling.
    #[get(type(copy))]
    pub(crate) triangles_drawn: usize,
    /// BVH shadow/reflection/GI rays traced during this frame.
    #[get(type(copy))]
    pub(crate) rays_traced: usize,
    /// Total BVH nodes active in the acceleration structure.
    #[get(type(copy))]
    pub(crate) bvh_nodes: usize,
    /// Objects rendered at simplified distant LOD (`LOD1+`).
    #[get(type(copy))]
    pub(crate) lod_simplified_objects: usize,
    /// Nanite-style meshlet clusters drawn this frame.
    #[get(type(copy))]
    pub(crate) meshlets_drawn: usize,
    /// Nanite-style meshlet clusters culled by frustum or backface normal cones.
    #[get(type(copy))]
    pub(crate) meshlets_culled: usize,
}

/// Precomputed screen-space triangle rasterization setup record for parallel tiled G-Buffer rasterization.
#[derive(Clone, Copy, Debug)]
pub(crate) struct RasterTri2D {
    /// Inclusive clamped top scanline index.
    pub(crate) min_y: i32,
    /// Inclusive clamped bottom scanline index.
    pub(crate) max_y: i32,
    /// Inclusive clamped left pixel coordinate.
    pub(crate) min_x: i32,
    /// Horizontal bounding-box span width (`max_x - min_x`).
    pub(crate) span_max: i32,
    /// Index into `shaded_tris`.
    pub(crate) tri_id: u32,
    /// Edge slopes `(dw0_dx, dw1_dx, dw2_dx)`.
    pub(crate) slopes: [f32; 3],
    /// Precomputed negative reciprocal edge slopes for span clipping.
    pub(crate) neg_inv_slopes: [f32; 3],
    /// Vertical barycentric step `(dw0_dy, dw1_dy, dw2_dy)`.
    pub(crate) dw_dy: [f32; 3],
    /// Barycentric coordinates evaluated at `(min_x + 0.5, min_y + 0.5)`.
    pub(crate) w_start: [f32; 3],
    /// Reverse-Z `1/w` evaluated at `(min_x + 0.5, min_y + 0.5)`.
    pub(crate) inv_w_start: f32,
    /// Horizontal `1/w` derivative per pixel.
    pub(crate) d_inv_w_dx: f32,
    /// Vertical `1/w` derivative per scanline.
    pub(crate) d_inv_w_dy: f32,
}

/// Precomputed per-triangle Cook-Torrance GGX PBR shading record referenced by deferred G-Buffer indices.
#[derive(Clone, Copy, Debug)]
pub(crate) struct GShadeTri {
    /// Camera-facing unit shading normal.
    pub(crate) shade_n: Vec3,
    /// Material linear base albedo.
    pub(crate) mat_base: Vec3,
    /// Material linear emissive radiance.
    pub(crate) mat_emissive: Vec3,
    /// Precomputed hemisphere sky ambient tint.
    pub(crate) ambient_sky: Vec3,
    /// Precomputed Schlick base specular reflectance `F0 = lerp(0.04, albedo, metallic)`.
    pub(crate) f0: Vec3,
    /// Clamped directional sun Lambertian term `max(N·L, 0)`.
    pub(crate) n_dot_l: f32,
    /// GGX roughness squared (`alpha^2 = roughness^4`).
    pub(crate) alpha2: f32,
    /// Energy-conserving diffuse scale `(1.0 - metallic)`.
    pub(crate) diffuse_scale: f32,
    /// Surface base reflectivity weight `[0.0, 1.0]`.
    pub(crate) mat_refl: f32,
    /// Surface metallic scalar `[0.0, 1.0]`.
    pub(crate) metallic: f32,
    /// Whether this surface traces specular reflections.
    pub(crate) do_refl: bool,
    /// Procedural surface detail mode attached to the triangle's material.
    pub(crate) surface_detail: SurfaceDetailMode,
}

/// Structure-of-Arrays coarse deferred ray-tracing probe grid enabling contiguous SIMD bilateral denoise and upsampling.
#[derive(Clone, Debug, Default)]
pub(crate) struct RtProbeGridSoa {
    /// Sun visibility factor per probe (`1.0` lit, `0.22` shadowed).
    pub(crate) shadow: Vec<f32>,
    /// Traced reflection linear red radiance.
    pub(crate) refl_r: Vec<f32>,
    /// Traced reflection linear green radiance.
    pub(crate) refl_g: Vec<f32>,
    /// Traced reflection linear blue radiance.
    pub(crate) refl_b: Vec<f32>,
    /// Colored indirect Lumen GI bounce red radiance.
    pub(crate) gi_r: Vec<f32>,
    /// Colored indirect Lumen GI bounce green radiance.
    pub(crate) gi_g: Vec<f32>,
    /// Colored indirect Lumen GI bounce blue radiance.
    pub(crate) gi_b: Vec<f32>,
    /// Ambient occlusion factor in `[0.42, 1.0]`.
    pub(crate) ao: Vec<f32>,
    /// Camera-space linear depth at probe center.
    pub(crate) depth: Vec<f32>,
    /// Surface normal X for bilateral edge stopping.
    pub(crate) nx: Vec<f32>,
    /// Surface normal Y for bilateral edge stopping.
    pub(crate) ny: Vec<f32>,
    /// Surface normal Z for bilateral edge stopping.
    pub(crate) nz: Vec<f32>,
    /// World-space surface X coordinate for temporal probe reprojection validation.
    pub(crate) world_x: Vec<f32>,
    /// World-space surface Y coordinate for temporal probe reprojection validation.
    pub(crate) world_y: Vec<f32>,
    /// World-space surface Z coordinate for temporal probe reprojection validation.
    pub(crate) world_z: Vec<f32>,
    /// Non-zero when this probe sits on valid scene geometry.
    pub(crate) valid: Vec<u8>,
}

/// Fixed-capacity L1-stack single-row SoA probe buffer (`gw <= PROBE_ROW_STACK_CAP`) enabling zero-allocation streaming bilateral denoising inside `shade_deferred_band`.
#[derive(Clone, Debug)]
pub(crate) struct RtProbeRowStack {
    /// Sun visibility factor across one probe row.
    pub(crate) shadow: [f32; PROBE_ROW_STACK_CAP],
    /// Reflection linear red radiance across one probe row.
    pub(crate) refl_r: [f32; PROBE_ROW_STACK_CAP],
    /// Reflection linear green radiance across one probe row.
    pub(crate) refl_g: [f32; PROBE_ROW_STACK_CAP],
    /// Reflection linear blue radiance across one probe row.
    pub(crate) refl_b: [f32; PROBE_ROW_STACK_CAP],
    /// Colored Lumen GI red radiance across one probe row.
    pub(crate) gi_r: [f32; PROBE_ROW_STACK_CAP],
    /// Colored Lumen GI green radiance across one probe row.
    pub(crate) gi_g: [f32; PROBE_ROW_STACK_CAP],
    /// Colored Lumen GI blue radiance across one probe row.
    pub(crate) gi_b: [f32; PROBE_ROW_STACK_CAP],
    /// Ambient occlusion factor across one probe row.
    pub(crate) ao: [f32; PROBE_ROW_STACK_CAP],
    /// Linear probe depth across one probe row.
    pub(crate) depth: [f32; PROBE_ROW_STACK_CAP],
    /// Surface normal X across one probe row.
    pub(crate) nx: [f32; PROBE_ROW_STACK_CAP],
    /// Surface normal Y across one probe row.
    pub(crate) ny: [f32; PROBE_ROW_STACK_CAP],
    /// Surface normal Z across one probe row.
    pub(crate) nz: [f32; PROBE_ROW_STACK_CAP],
    /// Validity flags (`0` sky, `1` geometry) across one probe row.
    pub(crate) valid: [u8; PROBE_ROW_STACK_CAP],
}

/// 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.
#[derive(Clone, Debug)]
pub(crate) struct RtProbeRowScratch {
    /// Monotonic frame generation tag invalidating cached rows across frames.
    pub(crate) frame_gen: u64,
    /// Probe row index cached in `buf_a` (`usize::MAX` if invalid).
    pub(crate) cached_gy_a: usize,
    /// Probe row index cached in `buf_b` (`usize::MAX` if invalid).
    pub(crate) cached_gy_b: usize,
    /// First L1-hot denoised probe row buffer.
    pub(crate) buf_a: RtProbeRowStack,
    /// Second L1-hot denoised probe row buffer.
    pub(crate) buf_b: RtProbeRowStack,
}

/// Zero-copy borrowed view over one contiguous row of SoA RT probes (stack-denoised or wide pre-denoised).
#[derive(Clone, Copy)]
pub(crate) struct RtProbeRowView<'a> {
    /// Sun visibility slice for this row.
    pub(crate) shadow: &'a [f32],
    /// Reflection red slice.
    pub(crate) refl_r: &'a [f32],
    /// Reflection green slice.
    pub(crate) refl_g: &'a [f32],
    /// Reflection blue slice.
    pub(crate) refl_b: &'a [f32],
    /// Lumen GI red slice.
    pub(crate) gi_r: &'a [f32],
    /// Lumen GI green slice.
    pub(crate) gi_g: &'a [f32],
    /// Lumen GI blue slice.
    pub(crate) gi_b: &'a [f32],
    /// Ambient occlusion slice.
    pub(crate) ao: &'a [f32],
    /// Linear depth slice.
    pub(crate) depth: &'a [f32],
    /// Normal X slice.
    pub(crate) nx: &'a [f32],
    /// Normal Y slice.
    pub(crate) ny: &'a [f32],
    /// Normal Z slice.
    pub(crate) nz: &'a [f32],
    /// Validity flags slice.
    pub(crate) valid: &'a [u8],
}

/// 16-byte-aligned 2x2 bilinear probe cell packed into 4-lane SIMD arrays and cached across consecutive horizontal pixels sharing `(gx0, gx1, tid)`.
#[repr(C, align(16))]
#[derive(Clone, Copy)]
pub(crate) struct CachedProbeCell {
    /// Four corner linear depths `[p00, p10, p01, p11]`.
    pub(crate) depth: [f32; 4],
    /// Four corner sun visibility factors.
    pub(crate) shadow: [f32; 4],
    /// Four corner reflection linear red samples.
    pub(crate) refl_r: [f32; 4],
    /// Four corner reflection linear green samples.
    pub(crate) refl_g: [f32; 4],
    /// Four corner reflection linear blue samples.
    pub(crate) refl_b: [f32; 4],
    /// Four corner GI linear red samples.
    pub(crate) gi_r: [f32; 4],
    /// Four corner GI linear green samples.
    pub(crate) gi_g: [f32; 4],
    /// Four corner GI linear blue samples.
    pub(crate) gi_b: [f32; 4],
    /// Four corner ambient occlusion samples.
    pub(crate) ao: [f32; 4],
    /// Four corner bilateral depth tolerance scale (`0.58` high-agreement, `0.20` low-agreement).
    pub(crate) tol_scale: [f32; 4],
    /// Four corner bilateral depth tolerance bias (`2.4` high-agreement, `0.75` low-agreement).
    pub(crate) tol_bias: [f32; 4],
    /// Four corner SIMD validity bitmasks (`0xFFFF_FFFF` when corner passes normal test, else `0`).
    pub(crate) valid_u32: [u32; 4],
    /// Compact 4-bit corner validity mask (`0` triggers immediate edge fallback).
    pub(crate) vmask: u8,
}

/// 16-byte-aligned 32-pixel L1-hot Structure-of-Arrays run scratch decoupling probe bilateral upsampling from zero-spill specialized PBR shading kernels.
#[repr(C, align(16))]
#[derive(Clone, Copy)]
pub(crate) struct RunScratch32 {
    /// Linear camera depth for up to 32 contiguous pixels of one triangle.
    pub(crate) depths: [f32; 32],
    /// Interpolated sun shadow factor for up to 32 pixels.
    pub(crate) shadow: [f32; 32],
    /// Interpolated reflection linear red for up to 32 pixels.
    pub(crate) refl_r: [f32; 32],
    /// Interpolated reflection linear green for up to 32 pixels.
    pub(crate) refl_g: [f32; 32],
    /// Interpolated reflection linear blue for up to 32 pixels.
    pub(crate) refl_b: [f32; 32],
    /// Interpolated Lumen GI linear red for up to 32 pixels.
    pub(crate) gi_r: [f32; 32],
    /// Interpolated Lumen GI linear green for up to 32 pixels.
    pub(crate) gi_g: [f32; 32],
    /// Interpolated Lumen GI linear blue for up to 32 pixels.
    pub(crate) gi_b: [f32; 32],
    /// Interpolated ambient occlusion for up to 32 pixels.
    pub(crate) ao: [f32; 32],
}

/// Writable 4-pixel scanline slice targets and optional quarter-res HDR bloom slot for `shade_span_4x_specialized`.
pub(crate) struct SpanShadeOut<'a> {
    /// 16-byte RGBA8 destination span.
    pub(crate) rgba: &'a mut [u8],
    /// 4-byte Rec.601 luma destination span.
    pub(crate) luma: &'a mut [u8],
    /// Optional `(lane_index, bloom_cell)` HDR excess radiance slot.
    pub(crate) bloom: Option<(usize, &'a mut [f32; 4])>,
}

/// Writable full-scanline color, luma, and quarter-res bloom buffers passed to 32-pixel run shaders.
pub(crate) struct RunRowOut<'a> {
    /// Full scanline RGBA8 output slice.
    pub(crate) color: &'a mut [u8],
    /// Full scanline Rec.601 luma output slice.
    pub(crate) luma: &'a mut [u8],
    /// Whether bloom extraction is active on this scanline (`(py & 3) == 0`).
    pub(crate) write_bloom: bool,
    /// Starting index of this scanline's bloom row inside `bloom_band`.
    pub(crate) bloom_off: usize,
    /// Writable quarter-resolution HDR bloom band slice.
    pub(crate) bloom_band: &'a mut [[f32; 4]],
}

/// Shared read-only probe rows and horizontal bilinear stepping context for `upsample_run_probes_32` and `shade_tri_run_4x`.
#[derive(Clone, Copy)]
pub(crate) struct ProbeBandCtx<'a> {
    /// Top denoised probe row view `gy0`.
    pub(crate) r0: &'a RtProbeRowView<'a>,
    /// Bottom denoised probe row view `gy1`.
    pub(crate) r1: &'a RtProbeRowView<'a>,
    /// Vertical bilinear weight for `r0`.
    pub(crate) wy0: f32,
    /// Vertical bilinear weight for `r1`.
    pub(crate) wy1: f32,
    /// Maximum valid coarse probe column index `gw - 1`.
    pub(crate) gw_max: usize,
    /// Doubled integer probe stride `rt_step * 2`.
    pub(crate) step2_i32: i32,
    /// Precomputed fractional horizontal lookup table indexed by `sub_x`.
    pub(crate) fx_lut: &'a [f32; 16],
}

/// Raw writable base addresses for lock-free disjoint-tile writes into `RtProbeGridSoa`.
#[derive(Clone, Copy, Debug)]
pub(crate) struct RtProbeGridMutPtrs {
    /// Base pointer for `shadow`.
    pub(crate) shadow: usize,
    /// Base pointer for `refl_r`.
    pub(crate) refl_r: usize,
    /// Base pointer for `refl_g`.
    pub(crate) refl_g: usize,
    /// Base pointer for `refl_b`.
    pub(crate) refl_b: usize,
    /// Base pointer for `gi_r`.
    pub(crate) gi_r: usize,
    /// Base pointer for `gi_g`.
    pub(crate) gi_g: usize,
    /// Base pointer for `gi_b`.
    pub(crate) gi_b: usize,
    /// Base pointer for `ao`.
    pub(crate) ao: usize,
    /// Base pointer for `depth`.
    pub(crate) depth: usize,
    /// Base pointer for `nx`.
    pub(crate) nx: usize,
    /// Base pointer for `ny`.
    pub(crate) ny: usize,
    /// Base pointer for `nz`.
    pub(crate) nz: usize,
    /// Base pointer for `world_x`.
    pub(crate) world_x: usize,
    /// Base pointer for `world_y`.
    pub(crate) world_y: usize,
    /// Base pointer for `world_z`.
    pub(crate) world_z: usize,
    /// Base pointer for `valid`.
    pub(crate) valid: usize,
}

/// Shared read-only inputs for fused Barrier 1 tiled rasterization and L1-hot coherent 2x2 probe packet tracing.
pub(crate) struct TileRasterProbeInputs<'a> {
    /// Screen-space triangle setup records.
    pub(crate) raster_tris: &'a [RasterTri2D],
    /// Flat CSR prefix offsets per tile (`len == total_tiles + 1`).
    pub(crate) tile_offsets: &'a [u32],
    /// Binned triangle indices into `raster_tris`.
    pub(crate) tile_tri_indices: &'a [u32],
    /// Precomputed GGX triangle shading records.
    pub(crate) shaded_tris: &'a [GShadeTri],
    /// Static world BVH4/BVH8 acceleration structure.
    pub(crate) static_bvh: &'a Bvh3D,
    /// Active object-space dynamic raytracing instances.
    pub(crate) dyn_instances: &'a [DynamicRayInstance],
    /// Local-space BVH4/BVH8 cache indexed by `mesh_id`.
    pub(crate) local_bvhs: &'a [Option<Bvh3D>],
    /// Previous frame coarse RT probe grid for world-space-validated temporal checkerboard reuse.
    pub(crate) prev_probes: Option<&'a RtProbeGridSoa>,
    /// Alternating checkerboard parity (`0` or `1`) selecting which 2x2 probe blocks refresh vs reuse.
    pub(crate) probe_checker_parity: usize,
    /// Tile edge dimension in pixels (`<= 64`, multiple of `rt_step` when RT active).
    pub(crate) tile_px: usize,
    /// Number of tiles horizontally.
    pub(crate) tiles_x: usize,
}

/// Shared read-only inputs for fused Barrier 2 streaming bilateral denoise and vectorized deferred PBR shading.
pub(crate) struct ShadeBandInputs<'a> {
    /// Reverse-Z `1/w` depth buffer.
    pub(crate) depth_buf: &'a [f32],
    /// Deferred G-Buffer triangle IDs.
    pub(crate) g_tri_idx: &'a [u32],
    /// Precomputed GGX triangle shading records.
    pub(crate) shaded_tris: &'a [GShadeTri],
    /// Raw coarse RT probe SoA grid written by Barrier 1.
    pub(crate) raw_probes: &'a RtProbeGridSoa,
    /// Optional pre-denoised full probe grid used only when `gw > 256` (e.g. 4K viewports).
    pub(crate) wide_denoised_probes: &'a RtProbeGridSoa,
    /// Whether bilateral 3x3 probe denoising is active during row streaming (`gw <= 256`).
    pub(crate) denoise_probes: bool,
    /// Static world BVH4/BVH8 acceleration structure.
    pub(crate) static_bvh: &'a Bvh3D,
    /// Active object-space dynamic raytracing instances.
    pub(crate) dyn_instances: &'a [DynamicRayInstance],
    /// Local-space BVH4/BVH8 cache indexed by `mesh_id`.
    pub(crate) local_bvhs: &'a [Option<Bvh3D>],
    /// Atomic bitset marking quarter-resolution bloom rows that received non-zero HDR radiance (`576` bits -> `bh <= 576`).
    pub(crate) bloom_row_bits: &'a [AtomicU64; 9],
}

/// Shared read-only inputs for Barrier 3 vectorized FXAA/MLAA/TAA and bilinear HDR bloom compositing.
pub(crate) struct PostProcessInputs<'a> {
    /// Tone-mapped RGBA8 intermediate framebuffer.
    pub(crate) color_src: &'a [u8],
    /// Rec.601 luma buffer populated during deferred shading.
    pub(crate) luma: &'a [u8],
    /// Deferred G-Buffer triangle IDs for geometry-aware AA edge detection.
    pub(crate) g_tri_idx: &'a [u32],
    /// Blurred quarter-resolution HDR bloom buffer (`[r, g, b, 0]`).
    pub(crate) bloom: &'a [[f32; 4]],
    /// Active bloom tile mask (`1` where bloom contributes `>= 1` RGB LSB).
    pub(crate) bloom_tile_active: &'a [u8],
    /// Previous frame RGBA8 TAA temporal history buffer.
    pub(crate) taa_history: &'a [u8],
}

/// Immutable per-frame camera, lighting, volumetric, and ray-tracing configuration shared across worker threads.
#[derive(Clone, Copy, Debug)]
pub(crate) struct DeferredFrameCtx {
    /// Framebuffer width in pixels.
    pub(crate) w: usize,
    /// Framebuffer height in pixels.
    pub(crate) h: usize,
    /// Coarse RT grid width in probes.
    pub(crate) gw: usize,
    /// Coarse RT grid height in probes.
    pub(crate) gh: usize,
    /// Quarter-res HDR bloom width.
    pub(crate) bw: usize,
    /// Pixel stride per coarse RT probe.
    pub(crate) rt_step: usize,
    /// Reciprocal framebuffer width.
    pub(crate) inv_w_f: f32,
    /// Reciprocal framebuffer height.
    pub(crate) inv_h_f: f32,
    /// Camera world position.
    pub(crate) cam_pos: Vec3,
    /// Camera unit forward basis.
    pub(crate) cam_fwd: Vec3,
    /// Camera right basis scaled by `half_w`.
    pub(crate) cam_right_scaled: Vec3,
    /// Camera up basis scaled by `half_h`.
    pub(crate) cam_up_scaled: Vec3,
    /// Active directional sun & sky parameters.
    pub(crate) sun: DirectionalLight3D,
    /// Precomputed safe reciprocal sun direction for fast shadow BVH traversal.
    pub(crate) inv_sun_dir: Vec3,
    /// Precomputed 2x2 soft-shadow jittered `(dir, inv_dir)` ray table hoisted once per frame.
    pub(crate) soft_shadow_rays: [(Vec3, Vec3); 4],
    /// Active ray-tracing quality tier.
    pub(crate) rt_mode: RayTracingMode,
    /// Maximum reflection/GI bounce depth (`0..=3`).
    pub(crate) reflection_bounces: u8,
    /// Whether volumetric height/distance fog and crepuscular sun-shafts are enabled.
    pub(crate) fog_on: bool,
    /// Precomputed inverse fog attenuation distance.
    pub(crate) inv_fog_dist: f32,
    /// Exposure scale derived from physically based camera EV100.
    pub(crate) exposure_scale: f32,
    /// Whether quarter-res emissive/specular bloom extraction is active.
    pub(crate) bloom_on: bool,
    /// Monotonic frame generation tag for per-thread probe denoise scratch cache invalidation.
    pub(crate) probe_frame_gen: u64,
}

/// Zero-allocation UE5-class Deferred GGX PBR + Persistent Multi-Core SIMD BVH4/BVH8 + Lumen GI + Bloom + Morphological AA/TAA 3D renderer.
#[derive(Clone, Data, Debug, Default)]
pub struct Renderer3D {
    /// Pre-allocated RGBA8 tone-mapped intermediate pixel buffer.
    pub(crate) color_buffer: Vec<u8>,
    /// Pre-allocated RGBA8 temporal history buffer for variance-clamped TAA.
    pub(crate) aa_buffer: Vec<u8>,
    /// Pre-allocated floating-point linear `1/w` reverse-Z depth buffer (`0.0` = sky).
    pub(crate) depth_buffer: Vec<f32>,
    /// Deferred G-Buffer triangle index per pixel (`u32::MAX` = sky).
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) g_tri_idx: Vec<u32>,
    /// Single-byte per-pixel Rec.601 luma buffer populated during deferred shading for fast morphological AA.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) luma_buffer: Vec<u8>,
    /// Per-frame precomputed GGX triangle shading records.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) shaded_tris: Vec<GShadeTri>,
    /// Persistent reusable RGBA8 final output buffer eliminating per-frame allocations in `render_world_rgba`.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) rgba_scratch: Vec<u8>,
    /// Structure-of-Arrays coarse coherent ray-tracing probe grid.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) rt_probes: RtProbeGridSoa,
    /// Previous frame coarse RT probe grid swapped in O(1) for temporal checkerboard probe reuse.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) prev_rt_probes: RtProbeGridSoa,
    /// Whether `prev_rt_probes` holds valid history matching `(prev_probe_gw, prev_probe_gh, prev_probe_rt_mode)`.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) has_probe_history: bool,
    /// Coarse probe width stored in `prev_rt_probes`.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) prev_probe_gw: usize,
    /// Coarse probe height stored in `prev_rt_probes`.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) prev_probe_gh: usize,
    /// Ray-tracing mode stored in `prev_rt_probes`.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) prev_probe_rt_mode: RayTracingMode,
    /// Previous frame directional sun vector for invalidating temporal probes on lighting changes.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) prev_sun_dir: Vec3,
    /// Fallback full-grid denoised SoA probe buffer used only when `gw > 256` (4K+).
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) rt_probes_wide_denoised: RtProbeGridSoa,
    /// Quarter-res 16-byte-aligned HDR bloom extraction and vertical blur buffer.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) bloom_a: Vec<[f32; 4]>,
    /// Quarter-res 16-byte-aligned HDR bloom horizontal blur scratch buffer.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) bloom_b: Vec<[f32; 4]>,
    /// Quarter-res active-bloom tile mask (`1` when any bilinear corner contributes `>= 1` RGB LSB) skipping dark tiles in post-processing.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) bloom_tile_active: Vec<u8>,
    /// Reusable front-to-back object sorting scratch buffer.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) visible_scratch: Vec<(f32, usize)>,
    /// Reusable meshlet triangle-range scratch buffer eliminating per-object heap allocations.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) cluster_ranges_scratch: Vec<(usize, usize)>,
    /// Reusable per-object transformed vertex cache `(clip_pos, world_pos)` avoiding redundant vertex transforms.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) projected_verts_scratch: Vec<([f32; 4], Vec3)>,
    /// Reusable unique mesh-id set for instancing telemetry.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) unique_meshes_scratch: HashSet<usize>,
    /// Reusable saved dynamic-object transforms for zero-allocation interpolated rendering.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) saved_objs_scratch: Vec<(usize, Transform3D, Aabb3D)>,
    /// Reusable screen-space triangle setup list for parallel tiled rasterization.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) raster_tris_scratch: Vec<RasterTri2D>,
    /// Reusable per-tile triangle count array for flat CSR binning.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) tile_counts_scratch: Vec<u32>,
    /// Reusable flat CSR prefix-sum offset array (`total_tiles + 1`).
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) tile_offsets_scratch: Vec<u32>,
    /// Reusable per-tile insertion cursor array for flat CSR binning.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) tile_cursors_scratch: Vec<u32>,
    /// Reusable flat array of binned triangle indices across all screen tiles.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) tile_tri_indices_scratch: Vec<u32>,
    /// Optional shared-device GPU composite target for zero-readback single-pass UI+3D compositing.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) gpu_target: GpuCompositeTarget,
    /// Whether `aa_buffer` holds a valid previous frame compatible with temporal anti-aliasing.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) has_taa_history: bool,
    /// Previous frame view-projection fingerprint used to detect camera cuts for TAA.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) prev_vp_m0: f32,
    /// Monotonic frame counter driving Halton(2, 3) temporal subpixel jitter.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) frame_index: u32,
    /// Last rendered `World3D::world_revision` enabling HUD-only dirty frames to reuse the cached 3D frame.
    #[get(type(copy))]
    pub(crate) last_world_revision: u64,
    /// Quality and viewport configuration fingerprint paired with `last_world_revision`.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) last_quality_fingerprint: u64,
    /// Number of consecutive static-world TAA accumulation frames completed since the last world change.
    #[get(type(copy))]
    pub(crate) taa_accumulated_frames: u32,
    /// Total HUD-only dirty frames satisfied from the cached 3D framebuffer without re-rasterizing.
    #[get(type(copy))]
    pub(crate) cached_world_reuses: u64,
    /// Last rendered internal width.
    #[get(type(copy))]
    pub(crate) width: u32,
    /// Last rendered internal height.
    #[get(type(copy))]
    pub(crate) height: u32,
    /// Telemetry from the most recent frame.
    #[get(type(copy))]
    pub(crate) last_stats: RenderStats3D,
}