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 in `Engine3dWorkerPool`.
4#[cfg(not(target_arch = "wasm32"))]
5#[derive(Debug, Default)]
6pub(crate) struct Engine3dWorkerSlot {
7    /// Monotonically incremented epoch signaling this worker to run the active job.
8    pub(crate) epoch: AtomicUsize,
9    /// Non-zero while this worker is parked on `wake` and requires condvar notification.
10    pub(crate) parked: AtomicUsize,
11    /// Private sleep mutex paired with `wake`.
12    pub(crate) lock: Mutex<()>,
13    /// Condition variable waking this worker when parked between frames.
14    pub(crate) wake: Condvar,
15}
16
17/// Shared lock-free dispatch state coordinating caller and persistent 3D background workers.
18#[cfg(not(target_arch = "wasm32"))]
19#[derive(Debug)]
20pub(crate) struct Engine3dPoolShared {
21    /// Raw pointer address of the caller-pinned `Engine3dJob` (`0` when idle).
22    pub(crate) active_job: AtomicUsize,
23    /// Number of background workers woken for the active dispatch.
24    pub(crate) active_workers: AtomicUsize,
25    /// Non-zero while the calling thread is parked waiting for workers to complete.
26    pub(crate) caller_parked: AtomicUsize,
27    /// Caller sleep mutex paired with `wake_caller`.
28    pub(crate) caller_lock: Mutex<()>,
29    /// Condition variable waking the calling thread once all active workers finish.
30    pub(crate) wake_caller: Condvar,
31    /// Per-worker wakeup slots (`len == worker_count`).
32    pub(crate) slots: Vec<Engine3dWorkerSlot>,
33}
34
35/// Active work-stealing range job executed synchronously across caller and persistent 3D worker threads.
36#[cfg(not(target_arch = "wasm32"))]
37#[derive(Debug)]
38pub(crate) struct Engine3dJob {
39    /// Type-erased chunk execution trampoline.
40    pub(crate) trampoline: Engine3dChunkFn,
41    /// Caller-pinned closure reference encoded as `usize`.
42    pub(crate) ctx_ptr: usize,
43    /// Total logical items across all chunks.
44    pub(crate) total_items: usize,
45    /// Number of items per dynamic work-stealing chunk.
46    pub(crate) chunk_size: usize,
47    /// Total chunks to claim (`total_items.div_ceil(chunk_size)`).
48    pub(crate) total_chunks: usize,
49    /// Atomic cursor of the next unclaimed chunk index.
50    pub(crate) next_chunk: AtomicUsize,
51    /// Atomic count of background workers finished observing this epoch.
52    pub(crate) workers_done: AtomicUsize,
53}
54
55/// Persistent warm thread pool eliminating per-frame OS thread spawns in `Renderer3D`.
56#[cfg(not(target_arch = "wasm32"))]
57#[derive(Debug)]
58pub(crate) struct Engine3dWorkerPool {
59    /// Number of background worker threads (excluding the calling thread).
60    pub(crate) worker_count: usize,
61    /// Non-blocking re-entrancy guard serializing top-level dispatches cleanly.
62    pub(crate) dispatch_lock: Mutex<()>,
63    /// Shared lock-free atomic dispatch state and per-worker wakeup slots.
64    pub(crate) shared: Arc<Engine3dPoolShared>,
65}
66
67/// Per-frame telemetry emitted by `Renderer3D` for live FPS/RT/LOD/Nanite/culling diagnostics.
68#[derive(Clone, Copy, Data, Debug, Default, PartialEq)]
69pub struct RenderStats3D {
70    /// Internal rasterized framebuffer width in pixels.
71    #[get(type(copy))]
72    pub(crate) render_width: u32,
73    /// Internal rasterized framebuffer height in pixels.
74    #[get(type(copy))]
75    pub(crate) render_height: u32,
76    /// Active objects rendered inside frustum & chunk stream radius.
77    #[get(type(copy))]
78    pub(crate) visible_objects: usize,
79    /// Objects rejected by 6-plane frustum culling or chunk draw distance.
80    #[get(type(copy))]
81    pub(crate) culled_objects: usize,
82    /// Deduplicated GPU instancing draw batches.
83    #[get(type(copy))]
84    pub(crate) instanced_batches: usize,
85    /// Triangles rasterized after backface culling.
86    #[get(type(copy))]
87    pub(crate) triangles_drawn: usize,
88    /// BVH shadow/reflection/GI rays traced during this frame.
89    #[get(type(copy))]
90    pub(crate) rays_traced: usize,
91    /// Total BVH nodes active in the acceleration structure.
92    #[get(type(copy))]
93    pub(crate) bvh_nodes: usize,
94    /// Objects rendered at simplified distant LOD (`LOD1+`).
95    #[get(type(copy))]
96    pub(crate) lod_simplified_objects: usize,
97    /// Nanite-style meshlet clusters drawn this frame.
98    #[get(type(copy))]
99    pub(crate) meshlets_drawn: usize,
100    /// Nanite-style meshlet clusters culled by frustum or backface normal cones.
101    #[get(type(copy))]
102    pub(crate) meshlets_culled: usize,
103}
104
105/// Precomputed per-triangle Cook-Torrance GGX PBR shading record referenced by deferred G-Buffer indices.
106#[derive(Clone, Copy, Debug)]
107pub(crate) struct GShadeTri {
108    /// Camera-facing unit shading normal.
109    pub(crate) shade_n: Vec3,
110    /// Material linear base albedo.
111    pub(crate) mat_base: Vec3,
112    /// Material linear emissive radiance.
113    pub(crate) mat_emissive: Vec3,
114    /// Precomputed hemisphere sky ambient tint.
115    pub(crate) ambient_sky: Vec3,
116    /// Precomputed Schlick base specular reflectance `F0 = lerp(0.04, albedo, metallic)`.
117    pub(crate) f0: Vec3,
118    /// Clamped directional sun Lambertian term `max(N·L, 0)`.
119    pub(crate) n_dot_l: f32,
120    /// GGX roughness squared (`alpha^2 = roughness^4`).
121    pub(crate) alpha2: f32,
122    /// Energy-conserving diffuse scale `(1.0 - metallic)`.
123    pub(crate) diffuse_scale: f32,
124    /// Surface base reflectivity weight `[0.0, 1.0]`.
125    pub(crate) mat_refl: f32,
126    /// Surface metallic scalar `[0.0, 1.0]`.
127    pub(crate) metallic: f32,
128    /// Whether this surface traces specular reflections.
129    pub(crate) do_refl: bool,
130    /// Procedural surface detail mode attached to the triangle's material.
131    pub(crate) surface_detail: SurfaceDetailMode,
132}
133
134/// Coarse deferred ray-tracing probe storing soft shadow, multi-bounce reflection, colored Lumen GI, and bilateral edge metadata.
135#[derive(Clone, Copy, Debug, Default)]
136pub(crate) struct RtProbeSample {
137    /// Sun visibility factor (`1.0` lit, `0.22` shadowed).
138    pub(crate) shadow: f32,
139    /// Traced reflection linear red radiance.
140    pub(crate) refl_r: f32,
141    /// Traced reflection linear green radiance.
142    pub(crate) refl_g: f32,
143    /// Traced reflection linear blue radiance.
144    pub(crate) refl_b: f32,
145    /// Colored indirect Lumen GI bounce linear radiance (red).
146    pub(crate) gi_r: f32,
147    /// Colored indirect Lumen GI bounce linear radiance (green).
148    pub(crate) gi_g: f32,
149    /// Colored indirect Lumen GI bounce linear radiance (blue).
150    pub(crate) gi_b: f32,
151    /// Ambient occlusion factor in `[0.42, 1.0]`.
152    pub(crate) ao: f32,
153    /// Camera-space linear depth at probe center.
154    pub(crate) depth: f32,
155    /// Surface normal X for bilateral edge stopping.
156    pub(crate) nx: f32,
157    /// Surface normal Y for bilateral edge stopping.
158    pub(crate) ny: f32,
159    /// Surface normal Z for bilateral edge stopping.
160    pub(crate) nz: f32,
161    /// Non-zero when this probe sits on valid scene geometry.
162    pub(crate) valid: u8,
163}
164
165/// Immutable per-frame camera, lighting, volumetric, and ray-tracing configuration shared across worker threads.
166#[derive(Clone, Copy, Debug)]
167pub(crate) struct DeferredFrameCtx {
168    /// Framebuffer width in pixels.
169    pub(crate) w: usize,
170    /// Framebuffer height in pixels.
171    pub(crate) h: usize,
172    /// Coarse RT grid width in probes.
173    pub(crate) gw: usize,
174    /// Coarse RT grid height in probes.
175    pub(crate) gh: usize,
176    /// Quarter-res HDR bloom width.
177    pub(crate) bw: usize,
178    /// Pixel stride per coarse RT probe.
179    pub(crate) rt_step: usize,
180    /// Reciprocal framebuffer width.
181    pub(crate) inv_w_f: f32,
182    /// Reciprocal framebuffer height.
183    pub(crate) inv_h_f: f32,
184    /// Camera world position.
185    pub(crate) cam_pos: Vec3,
186    /// Camera unit forward basis.
187    pub(crate) cam_fwd: Vec3,
188    /// Camera right basis scaled by `half_w`.
189    pub(crate) cam_right_scaled: Vec3,
190    /// Camera up basis scaled by `half_h`.
191    pub(crate) cam_up_scaled: Vec3,
192    /// Active directional sun & sky parameters.
193    pub(crate) sun: DirectionalLight3D,
194    /// Precomputed safe reciprocal sun direction for fast shadow BVH traversal.
195    pub(crate) inv_sun_dir: Vec3,
196    /// Precomputed 2x2 soft-shadow jittered `(dir, inv_dir)` ray table hoisted once per frame.
197    pub(crate) soft_shadow_rays: GiRayQuad,
198    /// Active ray-tracing quality tier.
199    pub(crate) rt_mode: RayTracingMode,
200    /// Maximum reflection/GI bounce depth (`0..=3`).
201    pub(crate) reflection_bounces: u8,
202    /// Whether volumetric height/distance fog and crepuscular sun-shafts are enabled.
203    pub(crate) fog_on: bool,
204    /// Precomputed inverse fog attenuation distance.
205    pub(crate) inv_fog_dist: f32,
206    /// Exposure scale derived from physically based camera EV100.
207    pub(crate) exposure_scale: f32,
208    /// Whether quarter-res emissive/specular bloom extraction is active.
209    pub(crate) bloom_on: bool,
210}
211
212/// Zero-allocation UE5-class Deferred GGX PBR + Persistent Multi-Core SAH BVH + Lumen GI + Bloom + Morphological AA/TAA 3D renderer.
213#[derive(Clone, Data, Debug, Default)]
214pub struct Renderer3D {
215    /// Pre-allocated RGBA8 tone-mapped intermediate pixel buffer.
216    pub(crate) color_buffer: Vec<u8>,
217    /// Pre-allocated RGBA8 temporal history buffer for variance-clamped TAA.
218    pub(crate) aa_buffer: Vec<u8>,
219    /// Pre-allocated floating-point linear `1/w` reverse-Z depth buffer (`0.0` = sky).
220    pub(crate) depth_buffer: Vec<f32>,
221    /// Deferred G-Buffer triangle index per pixel (`u32::MAX` = sky).
222    #[get(skip)]
223    #[get_mut(skip)]
224    #[set(skip)]
225    pub(crate) g_tri_idx: Vec<u32>,
226    /// Single-byte per-pixel Rec.601 luma buffer populated during deferred shading for fast morphological AA.
227    #[get(skip)]
228    #[get_mut(skip)]
229    #[set(skip)]
230    pub(crate) luma_buffer: Vec<u8>,
231    /// Per-frame precomputed GGX triangle shading records.
232    #[get(skip)]
233    #[get_mut(skip)]
234    #[set(skip)]
235    pub(crate) shaded_tris: Vec<GShadeTri>,
236    /// Per-triangle precomputed 2x2 Lumen GI/AO `(dir, inv_dir)` ray table hoisted once per frame.
237    #[get(skip)]
238    #[get_mut(skip)]
239    #[set(skip)]
240    pub(crate) gi_rays_scratch: Vec<GiRayQuad>,
241    /// Persistent reusable RGBA8 final output buffer eliminating per-frame allocations in `render_world_rgba`.
242    #[get(skip)]
243    #[get_mut(skip)]
244    #[set(skip)]
245    pub(crate) rgba_scratch: Vec<u8>,
246    /// Coarse coherent ray-tracing probe grid.
247    #[get(skip)]
248    #[get_mut(skip)]
249    #[set(skip)]
250    pub(crate) rt_probes: Vec<RtProbeSample>,
251    /// Bilaterally denoised coarse Lumen GI and soft-shadow probe grid.
252    #[get(skip)]
253    #[get_mut(skip)]
254    #[set(skip)]
255    pub(crate) rt_probes_denoised: Vec<RtProbeSample>,
256    /// Quarter-res HDR bloom extraction and vertical blur buffer.
257    #[get(skip)]
258    #[get_mut(skip)]
259    #[set(skip)]
260    pub(crate) bloom_a: Vec<[f32; 3]>,
261    /// Quarter-res HDR bloom horizontal blur scratch buffer.
262    #[get(skip)]
263    #[get_mut(skip)]
264    #[set(skip)]
265    pub(crate) bloom_b: Vec<[f32; 3]>,
266    /// Quarter-res active-bloom tile mask (`1` when any bilinear corner contributes `>= 1` RGB LSB) skipping dark tiles in post-processing.
267    #[get(skip)]
268    #[get_mut(skip)]
269    #[set(skip)]
270    pub(crate) bloom_tile_active: Vec<u8>,
271    /// Reusable front-to-back object sorting scratch buffer.
272    #[get(skip)]
273    #[get_mut(skip)]
274    #[set(skip)]
275    pub(crate) visible_scratch: Vec<(f32, usize)>,
276    /// Reusable meshlet triangle-range scratch buffer eliminating per-object heap allocations.
277    #[get(skip)]
278    #[get_mut(skip)]
279    #[set(skip)]
280    pub(crate) cluster_ranges_scratch: Vec<(usize, usize)>,
281    /// Reusable per-object transformed vertex cache `(clip_pos, world_pos)` avoiding redundant vertex transforms.
282    #[get(skip)]
283    #[get_mut(skip)]
284    #[set(skip)]
285    pub(crate) projected_verts_scratch: Vec<([f32; 4], Vec3)>,
286    /// Reusable unique mesh-id set for instancing telemetry.
287    #[get(skip)]
288    #[get_mut(skip)]
289    #[set(skip)]
290    pub(crate) unique_meshes_scratch: HashSet<usize>,
291    /// Whether `aa_buffer` holds a valid previous frame compatible with temporal anti-aliasing.
292    #[get(skip)]
293    #[get_mut(skip)]
294    #[set(skip)]
295    pub(crate) has_taa_history: bool,
296    /// Previous frame view-projection fingerprint used to detect camera cuts for TAA.
297    #[get(skip)]
298    #[get_mut(skip)]
299    #[set(skip)]
300    pub(crate) prev_vp_m0: f32,
301    /// Monotonic frame counter driving Halton(2, 3) temporal subpixel jitter.
302    #[get(skip)]
303    #[get_mut(skip)]
304    #[set(skip)]
305    pub(crate) frame_index: u32,
306    /// Last rendered `World3D::world_revision` enabling HUD-only dirty frames to reuse the cached 3D frame.
307    #[get(type(copy))]
308    pub(crate) last_world_revision: u64,
309    /// Quality and viewport configuration fingerprint paired with `last_world_revision`.
310    #[get(skip)]
311    #[get_mut(skip)]
312    #[set(skip)]
313    pub(crate) last_quality_fingerprint: u64,
314    /// Number of consecutive static-world TAA accumulation frames completed since the last world change.
315    #[get(type(copy))]
316    pub(crate) taa_accumulated_frames: u32,
317    /// Total HUD-only dirty frames satisfied from the cached 3D framebuffer without re-rasterizing.
318    #[get(type(copy))]
319    pub(crate) cached_world_reuses: u64,
320    /// Last rendered internal width.
321    #[get(type(copy))]
322    pub(crate) width: u32,
323    /// Last rendered internal height.
324    #[get(type(copy))]
325    pub(crate) height: u32,
326    /// Telemetry from the most recent frame.
327    #[get(type(copy))]
328    pub(crate) last_stats: RenderStats3D,
329}