Skip to main content

euv_core/game/engine3d/renderer/
struct.rs

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