Skip to main content

euv_core/game/engine3d/occlusion/
impl.rs

1use super::*;
2
3/// Conservative reverse-Z Hierarchical Z-Buffer construction, occluder pre-pass stamping, and O(1) occlusion queries for `HiZPyramid`.
4impl HiZPyramid {
5    /// Creates an empty `HiZPyramid` sized for `(viewport_width, viewport_height)` using `8x8` base cells.
6    ///
7    /// # Arguments
8    ///
9    /// - `usize` - Target viewport width in pixels.
10    /// - `usize` - Target viewport height in pixels.
11    ///
12    /// # Returns
13    ///
14    /// - `Self` - Pre-allocated reverse-Z Hi-Z pyramid marked invalid until populated.
15    #[must_use]
16    pub fn new(viewport_width: usize, viewport_height: usize) -> Self {
17        let mut pyramid: Self = Self {
18            viewport_width: 0,
19            viewport_height: 0,
20            cell_size_px: HIZ_BASE_CELL_PX,
21            valid: false,
22            levels: Vec::new(),
23            level_dims: Vec::new(),
24        };
25        pyramid.ensure_dimensions(viewport_width, viewport_height);
26        pyramid
27    }
28
29    /// Ensures internal mip buffers match `(viewport_width, viewport_height)` without reallocating when dimensions are unchanged.
30    ///
31    /// # Arguments
32    ///
33    /// - `usize` - Target viewport width in pixels.
34    /// - `usize` - Target viewport height in pixels.
35    pub fn ensure_dimensions(&mut self, viewport_width: usize, viewport_height: usize) {
36        let safe_w: usize = viewport_width.max(1);
37        let safe_h: usize = viewport_height.max(1);
38        let cell_px: usize = self.get_cell_size_px().max(1);
39        if self.get_viewport_width() == safe_w
40            && self.get_viewport_height() == safe_h
41            && !self.levels_slice().is_empty()
42        {
43            return;
44        }
45        self.set_viewport_width(safe_w);
46        self.set_viewport_height(safe_h);
47        self.set_cell_size_px(cell_px);
48        self.set_valid(false);
49        let Self {
50            levels, level_dims, ..
51        } = self;
52        levels.clear();
53        level_dims.clear();
54        let mut cur_w: usize = safe_w.div_ceil(cell_px).max(1);
55        let mut cur_h: usize = safe_h.div_ceil(cell_px).max(1);
56        loop {
57            level_dims.push((cur_w, cur_h));
58            levels.push(vec![0.0; cur_w * cur_h]);
59            if cur_w == 1 && cur_h == 1 {
60                break;
61            }
62            cur_w = cur_w.div_ceil(2).max(1);
63            cur_h = cur_h.div_ceil(2).max(1);
64        }
65    }
66
67    /// Clears base level cells to reverse-Z far (`0.0`) and invalidates the pyramid prior to same-frame occluder stamping.
68    pub fn clear_for_prepass(&mut self) {
69        self.set_valid(false);
70        let Self { levels, .. } = self;
71        if let Some(base_level) = levels.first_mut() {
72            base_level.fill(0.0);
73        }
74    }
75
76    /// Returns the number of mip levels currently allocated in this Hi-Z pyramid.
77    ///
78    /// # Returns
79    ///
80    /// - `usize` - Mip level count (`0` when uninitialized).
81    #[must_use]
82    pub fn mip_count(&self) -> usize {
83        self.levels_slice().len()
84    }
85
86    /// Returns an immutable slice of all mip buffers.
87    ///
88    /// # Returns
89    ///
90    /// - `&[Vec<f32>]` - Mip level depth arrays.
91    #[must_use]
92    fn levels_slice(&self) -> &[Vec<f32>] {
93        let Self { levels, .. } = self;
94        levels.as_slice()
95    }
96
97    /// Builds the full conservative reverse-Z Hi-Z mip pyramid directly from a rendered reverse-Z `depth_buffer`.
98    ///
99    /// # Arguments
100    ///
101    /// - `&[f32]` - Full-resolution reverse-Z `1/w` depth buffer (`0.0` = sky/far).
102    /// - `usize` - Viewport width in pixels.
103    /// - `usize` - Viewport height in pixels.
104    pub fn build_from_depth_buffer(
105        &mut self,
106        depth_buffer: &[f32],
107        viewport_width: usize,
108        viewport_height: usize,
109    ) {
110        if viewport_width == 0
111            || viewport_height == 0
112            || depth_buffer.len() < viewport_width.saturating_mul(viewport_height)
113        {
114            self.set_valid(false);
115            return;
116        }
117        self.ensure_dimensions(viewport_width, viewport_height);
118        let cell_px: usize = self.get_cell_size_px().max(1);
119        let (base_w, base_h): (usize, usize) = {
120            let Self { level_dims, .. } = self;
121            level_dims.first().copied().unwrap_or((1, 1))
122        };
123        {
124            let Self { levels, .. } = self;
125            if let Some(level0) = levels.first_mut() {
126                for cell_y in 0..base_h {
127                    let py_start: usize = cell_y * cell_px;
128                    let py_end: usize = (py_start + cell_px).min(viewport_height);
129                    let cell_row_off: usize = cell_y * base_w;
130                    for cell_x in 0..base_w {
131                        let px_start: usize = cell_x * cell_px;
132                        let px_end: usize = (px_start + cell_px).min(viewport_width);
133                        let mut min_inv_w: f32 = f32::INFINITY;
134                        for pixel_y in py_start..py_end {
135                            let row_off: usize = pixel_y * viewport_width;
136                            let span: &[f32] =
137                                &depth_buffer[(row_off + px_start)..(row_off + px_end)];
138                            for &depth_val in span.iter() {
139                                if depth_val < min_inv_w {
140                                    min_inv_w = depth_val;
141                                }
142                            }
143                            if min_inv_w <= 0.0 {
144                                min_inv_w = 0.0;
145                                break;
146                            }
147                        }
148                        level0[cell_row_off + cell_x] = if min_inv_w.is_finite() {
149                            min_inv_w
150                        } else {
151                            0.0
152                        };
153                    }
154                }
155            }
156        }
157        self.rebuild_mips();
158    }
159
160    /// Conservatively stamps a closed solid occluder triangle into Level 0 Hi-Z cells that lie 100% inside the triangle footprint.
161    ///
162    /// # Arguments
163    ///
164    /// - `[f32; 3]` - Triangle vertex screen X coordinates `(sx0, sx1, sx2)`.
165    /// - `[f32; 3]` - Triangle vertex screen Y coordinates `(sy0, sy1, sy2)`.
166    /// - `[f32; 3]` - Triangle vertex reverse-Z `1/w` values `(inv_w0, inv_w1, inv_w2)`.
167    #[cfg_attr(not(target_arch = "wasm32"), inline)]
168    pub fn stamp_occluder_triangle_conservative(
169        &mut self,
170        screen_x: [f32; 3],
171        screen_y: [f32; 3],
172        inv_w: [f32; 3],
173    ) {
174        let area: f32 = (screen_x[1] - screen_x[0]) * (screen_y[2] - screen_y[0])
175            - (screen_y[1] - screen_y[0]) * (screen_x[2] - screen_x[0]);
176        if area >= -1.0 {
177            return;
178        }
179        let cell_px: usize = self.get_cell_size_px().max(1);
180        let cell_f: f32 = cell_px as f32;
181        let (base_w, base_h): (usize, usize) = {
182            let Self { level_dims, .. } = self;
183            match level_dims.first().copied() {
184                Some(dims) => dims,
185                None => return,
186            }
187        };
188        let min_px: f32 = screen_x[0].min(screen_x[1]).min(screen_x[2]);
189        let max_px: f32 = screen_x[0].max(screen_x[1]).max(screen_x[2]);
190        let min_py: f32 = screen_y[0].min(screen_y[1]).min(screen_y[2]);
191        let max_py: f32 = screen_y[0].max(screen_y[1]).max(screen_y[2]);
192        let cell_x0: usize = ((min_px / cell_f).floor().max(0.0) as usize).min(base_w);
193        let cell_x1: usize =
194            ((max_px / cell_f).floor().max(0.0) as usize).min(base_w.saturating_sub(1));
195        let cell_y0: usize = ((min_py / cell_f).floor().max(0.0) as usize).min(base_h);
196        let cell_y1: usize =
197            ((max_py / cell_f).floor().max(0.0) as usize).min(base_h.saturating_sub(1));
198        let out_of_x_bounds: bool = cell_x0 > cell_x1 || cell_x0 >= base_w;
199        let out_of_y_bounds: bool = cell_y0 > cell_y1 || cell_y0 >= base_h;
200        if out_of_x_bounds || out_of_y_bounds {
201            return;
202        }
203        let inv_area: f32 = 1.0 / area;
204        let dw0_dx: f32 = (screen_y[1] - screen_y[2]) * inv_area;
205        let dw1_dx: f32 = (screen_y[2] - screen_y[0]) * inv_area;
206        let dw2_dx: f32 = -(dw0_dx + dw1_dx);
207        let dw0_dy: f32 = (screen_x[2] - screen_x[1]) * inv_area;
208        let dw1_dy: f32 = (screen_x[0] - screen_x[2]) * inv_area;
209        let dw2_dy: f32 = -(dw0_dy + dw1_dy);
210        let d_inv_w_dx: f32 = dw0_dx * inv_w[0] + dw1_dx * inv_w[1] + dw2_dx * inv_w[2];
211        let d_inv_w_dy: f32 = dw0_dy * inv_w[0] + dw1_dy * inv_w[1] + dw2_dy * inv_w[2];
212        let tri_min_inv_w: f32 = inv_w[0].min(inv_w[1]).min(inv_w[2]).max(0.0);
213        let Self { levels, .. } = self;
214        let Some(level0) = levels.first_mut() else {
215            return;
216        };
217        let dx_step_w0: f32 = dw0_dx * cell_f;
218        let dx_step_w1: f32 = dw1_dx * cell_f;
219        let dx_step_w2: f32 = dw2_dx * cell_f;
220        let dx_step_iw: f32 = d_inv_w_dx * cell_f;
221        let bias_w0: f32 = dw0_dx.min(0.0) * cell_f + dw0_dy.min(0.0) * cell_f;
222        let bias_w1: f32 = dw1_dx.min(0.0) * cell_f + dw1_dy.min(0.0) * cell_f;
223        let bias_w2: f32 = dw2_dx.min(0.0) * cell_f + dw2_dy.min(0.0) * cell_f;
224        let bias_iw: f32 = d_inv_w_dx.min(0.0) * cell_f + d_inv_w_dy.min(0.0) * cell_f;
225        let px_start: f32 = (cell_x0 * cell_px) as f32;
226        for cell_y in cell_y0..=cell_y1 {
227            let py0: f32 = (cell_y * cell_px) as f32;
228            let row_off: usize = cell_y * base_w;
229            let mut w0_tl: f32 = ((screen_x[1] - px_start) * (screen_y[2] - py0)
230                - (screen_y[1] - py0) * (screen_x[2] - px_start))
231                * inv_area;
232            let mut w1_tl: f32 = ((screen_x[2] - px_start) * (screen_y[0] - py0)
233                - (screen_y[2] - py0) * (screen_x[0] - px_start))
234                * inv_area;
235            let mut w2_tl: f32 = 1.0 - w0_tl - w1_tl;
236            let mut inv_w_tl: f32 = w0_tl * inv_w[0] + w1_tl * inv_w[1] + w2_tl * inv_w[2];
237            for cell_x in cell_x0..=cell_x1 {
238                if w0_tl + bias_w0 >= 0.0 && w1_tl + bias_w1 >= 0.0 && w2_tl + bias_w2 >= 0.0 {
239                    let inv_w_cell_min: f32 = (inv_w_tl + bias_iw).max(tri_min_inv_w);
240                    let cell_slot: &mut f32 = &mut level0[row_off + cell_x];
241                    if inv_w_cell_min > *cell_slot {
242                        *cell_slot = inv_w_cell_min;
243                    }
244                }
245                w0_tl += dx_step_w0;
246                w1_tl += dx_step_w1;
247                w2_tl += dx_step_w2;
248                inv_w_tl += dx_step_iw;
249            }
250        }
251    }
252
253    /// Rebuilds all coarser mip levels (`1..mip_count`) from Level 0 using conservative 2x2 minimum reduction and marks the pyramid valid.
254    pub fn rebuild_mips(&mut self) {
255        let mip_len: usize = self.mip_count();
256        if mip_len == 0 {
257            self.set_valid(false);
258            return;
259        }
260        {
261            let Self {
262                levels, level_dims, ..
263            } = self;
264            for mip_idx in 1..mip_len {
265                let (src_w, src_h): (usize, usize) = level_dims[mip_idx - 1];
266                let (dst_w, dst_h): (usize, usize) = level_dims[mip_idx];
267                let (left_slice, right_slice): (&mut [Vec<f32>], &mut [Vec<f32>]) =
268                    levels.split_at_mut(mip_idx);
269                let src_level: &[f32] = left_slice[mip_idx - 1].as_slice();
270                let dst_level: &mut [f32] = right_slice[0].as_mut_slice();
271                for dst_y in 0..dst_h {
272                    let sy0: usize = (dst_y * 2).min(src_h.saturating_sub(1));
273                    let sy1: usize = (sy0 + 1).min(src_h.saturating_sub(1));
274                    let row0: usize = sy0 * src_w;
275                    let row1: usize = sy1 * src_w;
276                    let dst_row: usize = dst_y * dst_w;
277                    for dst_x in 0..dst_w {
278                        let sx0: usize = (dst_x * 2).min(src_w.saturating_sub(1));
279                        let sx1: usize = (sx0 + 1).min(src_w.saturating_sub(1));
280                        let min_top: f32 = src_level[row0 + sx0].min(src_level[row0 + sx1]);
281                        let min_bot: f32 = src_level[row1 + sx0].min(src_level[row1 + sx1]);
282                        dst_level[dst_row + dst_x] = min_top.min(min_bot);
283                    }
284                }
285            }
286        }
287        self.set_valid(true);
288    }
289
290    /// Tests whether `world_bounds` is 100% occluded by closer geometry already recorded in this conservative reverse-Z Hi-Z pyramid.
291    ///
292    /// # Arguments
293    ///
294    /// - `AxisAlignedBox3D` - Candidate world-space bounding box.
295    /// - `&Mat4` - Active frame view-projection matrix.
296    /// - `f32` - Camera near clip distance in meters.
297    ///
298    /// # Returns
299    ///
300    /// - `bool` - `true` when guaranteed completely hidden behind closer occluders.
301    #[cfg_attr(not(target_arch = "wasm32"), inline)]
302    #[must_use]
303    pub fn is_bounds_occluded(
304        &self,
305        world_bounds: AxisAlignedBox3D,
306        view_proj: &Mat4,
307        near_plane: f32,
308    ) -> bool {
309        if !self.get_valid() || self.mip_count() == 0 {
310            return false;
311        }
312        let min_pt: Vec3 = world_bounds.get_min();
313        let max_pt: Vec3 = world_bounds.get_max();
314        let corners: [Vec3; 8] = [
315            Vec3::new(min_pt.get_x(), min_pt.get_y(), min_pt.get_z()),
316            Vec3::new(max_pt.get_x(), min_pt.get_y(), min_pt.get_z()),
317            Vec3::new(min_pt.get_x(), max_pt.get_y(), min_pt.get_z()),
318            Vec3::new(max_pt.get_x(), max_pt.get_y(), min_pt.get_z()),
319            Vec3::new(min_pt.get_x(), min_pt.get_y(), max_pt.get_z()),
320            Vec3::new(max_pt.get_x(), min_pt.get_y(), max_pt.get_z()),
321            Vec3::new(min_pt.get_x(), max_pt.get_y(), max_pt.get_z()),
322            Vec3::new(max_pt.get_x(), max_pt.get_y(), max_pt.get_z()),
323        ];
324        let safe_near: f32 = near_plane.max(0.15);
325        let vp_w: f32 = self.get_viewport_width() as f32;
326        let vp_h: f32 = self.get_viewport_height() as f32;
327        let mut min_sx: f32 = f32::INFINITY;
328        let mut max_sx: f32 = f32::NEG_INFINITY;
329        let mut min_sy: f32 = f32::INFINITY;
330        let mut max_sy: f32 = f32::NEG_INFINITY;
331        let mut nearest_inv_w: f32 = 0.0;
332        for corner in corners.iter().copied() {
333            let clip: [f32; 4] = view_proj.mul_point4(corner);
334            if clip[3] <= safe_near {
335                return false;
336            }
337            let inv_w: f32 = 1.0 / clip[3];
338            if inv_w > nearest_inv_w {
339                nearest_inv_w = inv_w;
340            }
341            let sx: f32 = (clip[0] * inv_w * 0.5 + 0.5) * vp_w;
342            let sy: f32 = (0.5 - clip[1] * inv_w * 0.5) * vp_h;
343            min_sx = min_sx.min(sx);
344            max_sx = max_sx.max(sx);
345            min_sy = min_sy.min(sy);
346            max_sy = max_sy.max(sy);
347        }
348        let outside_horizontal: bool = max_sx < 0.0 || min_sx >= vp_w;
349        let outside_vertical: bool = max_sy < 0.0 || min_sy >= vp_h;
350        if outside_horizontal || outside_vertical {
351            return false;
352        }
353        let clamped_x0: f32 = min_sx.clamp(0.0, (vp_w - 1.0).max(0.0));
354        let clamped_x1: f32 = max_sx.clamp(0.0, (vp_w - 1.0).max(0.0));
355        let clamped_y0: f32 = min_sy.clamp(0.0, (vp_h - 1.0).max(0.0));
356        let clamped_y1: f32 = max_sy.clamp(0.0, (vp_h - 1.0).max(0.0));
357        let cell_px: usize = self.get_cell_size_px().max(1);
358        let mut cx0: usize = (clamped_x0 as usize) / cell_px;
359        let mut cx1: usize = (clamped_x1 as usize) / cell_px;
360        let mut cy0: usize = (clamped_y0 as usize) / cell_px;
361        let mut cy1: usize = (clamped_y1 as usize) / cell_px;
362        let Self {
363            levels, level_dims, ..
364        } = self;
365        let max_mip: usize = levels.len().saturating_sub(1);
366        let mut mip_idx: usize = 0;
367        while mip_idx < max_mip && ((cx1 - cx0) > 1 || (cy1 - cy0) > 1) {
368            cx0 >>= 1;
369            cx1 >>= 1;
370            cy0 >>= 1;
371            cy1 >>= 1;
372            mip_idx += 1;
373        }
374        let (mip_w, mip_h): (usize, usize) = level_dims[mip_idx];
375        let level_data: &[f32] = levels[mip_idx].as_slice();
376        let safe_x0: usize = cx0.min(mip_w.saturating_sub(1));
377        let safe_x1: usize = cx1.min(mip_w.saturating_sub(1));
378        let safe_y0: usize = cy0.min(mip_h.saturating_sub(1));
379        let safe_y1: usize = cy1.min(mip_h.saturating_sub(1));
380        let mut hiz_min_inv_w: f32 = f32::INFINITY;
381        for cell_y in safe_y0..=safe_y1 {
382            let row_off: usize = cell_y * mip_w;
383            for cell_x in safe_x0..=safe_x1 {
384                let sample: f32 = level_data[row_off + cell_x];
385                if sample < hiz_min_inv_w {
386                    hiz_min_inv_w = sample;
387                }
388            }
389        }
390        let test_inv_w: f32 =
391            nearest_inv_w * HIZ_CONSERVATIVE_INV_W_SCALE + HIZ_CONSERVATIVE_INV_W_EPS;
392        hiz_min_inv_w.is_finite() && test_inv_w < hiz_min_inv_w
393    }
394
395    /// Estimates the projected screen-space bounding area in square pixels of `world_bounds` for micro-cluster culling.
396    ///
397    /// # Arguments
398    ///
399    /// - `AxisAlignedBox3D` - Candidate world-space bounding box.
400    /// - `&Mat4` - Active frame view-projection matrix.
401    /// - `f32` - Viewport width in pixels.
402    /// - `f32` - Viewport height in pixels.
403    /// - `f32` - Camera near clip distance in meters.
404    ///
405    /// # Returns
406    ///
407    /// - `f32` - Projected screen area in square pixels (`f32::INFINITY` if intersecting near plane).
408    #[cfg_attr(not(target_arch = "wasm32"), inline)]
409    #[must_use]
410    pub fn projected_screen_area_px(
411        world_bounds: AxisAlignedBox3D,
412        view_proj: &Mat4,
413        viewport_w: f32,
414        viewport_h: f32,
415        near_plane: f32,
416    ) -> f32 {
417        let min_pt: Vec3 = world_bounds.get_min();
418        let max_pt: Vec3 = world_bounds.get_max();
419        let corners: [Vec3; 8] = [
420            Vec3::new(min_pt.get_x(), min_pt.get_y(), min_pt.get_z()),
421            Vec3::new(max_pt.get_x(), min_pt.get_y(), min_pt.get_z()),
422            Vec3::new(min_pt.get_x(), max_pt.get_y(), min_pt.get_z()),
423            Vec3::new(max_pt.get_x(), max_pt.get_y(), min_pt.get_z()),
424            Vec3::new(min_pt.get_x(), min_pt.get_y(), max_pt.get_z()),
425            Vec3::new(max_pt.get_x(), min_pt.get_y(), max_pt.get_z()),
426            Vec3::new(min_pt.get_x(), max_pt.get_y(), max_pt.get_z()),
427            Vec3::new(max_pt.get_x(), max_pt.get_y(), max_pt.get_z()),
428        ];
429        let safe_near: f32 = near_plane.max(0.15);
430        let mut min_sx: f32 = f32::INFINITY;
431        let mut max_sx: f32 = f32::NEG_INFINITY;
432        let mut min_sy: f32 = f32::INFINITY;
433        let mut max_sy: f32 = f32::NEG_INFINITY;
434        for corner in corners.iter().copied() {
435            let clip: [f32; 4] = view_proj.mul_point4(corner);
436            if clip[3] <= safe_near {
437                return f32::INFINITY;
438            }
439            let inv_w: f32 = 1.0 / clip[3];
440            let sx: f32 = (clip[0] * inv_w * 0.5 + 0.5) * viewport_w;
441            let sy: f32 = (0.5 - clip[1] * inv_w * 0.5) * viewport_h;
442            min_sx = min_sx.min(sx);
443            max_sx = max_sx.max(sx);
444            min_sy = min_sy.min(sy);
445            max_sy = max_sy.max(sy);
446        }
447        (max_sx - min_sx).max(0.0) * (max_sy - min_sy).max(0.0)
448    }
449
450    /// Samples the conservative minimum reverse-Z `1/w` stored at mip `mip_level` cell `(cell_x, cell_y)`.
451    ///
452    /// # Arguments
453    ///
454    /// - `usize` - Target mip level index.
455    /// - `usize` - Cell X coordinate.
456    /// - `usize` - Cell Y coordinate.
457    ///
458    /// # Returns
459    ///
460    /// - `f32` - Stored reverse-Z depth (`0.0` when out of bounds or invalid).
461    #[must_use]
462    pub fn sample_mip_cell(&self, mip_level: usize, cell_x: usize, cell_y: usize) -> f32 {
463        let Self {
464            levels, level_dims, ..
465        } = self;
466        let Some(&(mip_w, mip_h)) = level_dims.get(mip_level) else {
467            return 0.0;
468        };
469        if cell_x >= mip_w || cell_y >= mip_h {
470            return 0.0;
471        }
472        levels[mip_level][cell_y * mip_w + cell_x]
473    }
474}
475
476/// Hierarchical cluster DAG construction and continuous UE5 Nanite screen-error cuts for `NaniteClusterDag`.
477impl NaniteClusterDag {
478    /// Builds a bottom-up hierarchical `NaniteClusterDag` over the meshlets of `mesh`.
479    ///
480    /// # Arguments
481    ///
482    /// - `&Mesh3D` - Source mesh containing partitioned `Meshlet3D` clusters.
483    ///
484    /// # Returns
485    ///
486    /// - `Self` - Ready Nanite cluster DAG for continuous LOD cuts and culling.
487    #[must_use]
488    pub fn from_mesh(mesh: &Mesh3D) -> Self {
489        let meshlets: &[Meshlet3D] = mesh.get_meshlets().as_slice();
490        if meshlets.is_empty() {
491            return Self::default();
492        }
493        let mut nodes: Vec<NaniteClusterNode> = Vec::with_capacity(meshlets.len() * 2);
494        for meshlet in meshlets.iter() {
495            nodes.push(NaniteClusterNode {
496                first_tri: meshlet.get_first_tri(),
497                tri_count: meshlet.get_tri_count(),
498                bounds: meshlet.get_bounds(),
499                cone_axis: meshlet.get_cone_axis(),
500                cone_cutoff: meshlet.get_cone_cutoff(),
501                cluster_error: 0.0,
502                parent_error: f32::INFINITY,
503                lod_level: 0,
504                child_start: 0,
505                child_count: 0,
506            });
507        }
508        let mut level_start: usize = 0;
509        let mut level_end: usize = nodes.len();
510        let mut level_count: usize = 1;
511        let mut cur_lod: u8 = 0;
512        while level_end - level_start > 1 {
513            let next_start: usize = nodes.len();
514            let next_lod: u8 = cur_lod.saturating_add(1);
515            let mut cursor: usize = level_start;
516            while cursor < level_end {
517                let group_end: usize = (cursor + NANITE_DAG_BRANCH_FACTOR).min(level_end);
518                let first_child: NaniteClusterNode = nodes[cursor];
519                let mut merged_bounds: AxisAlignedBox3D = first_child.get_bounds();
520                let mut axis_sum: Vec3 = Vec3::zero();
521                let mut min_tri: u32 = first_child.get_first_tri();
522                let mut max_tri_end: u32 = min_tri.saturating_add(first_child.get_tri_count());
523                let mut max_child_err: f32 = 0.0;
524                for child in nodes[cursor..group_end].iter() {
525                    merged_bounds.expand_box(child.get_bounds());
526                    axis_sum = axis_sum.add(child.get_cone_axis());
527                    let c_start: u32 = child.get_first_tri();
528                    let c_end: u32 = c_start.saturating_add(child.get_tri_count());
529                    min_tri = min_tri.min(c_start);
530                    max_tri_end = max_tri_end.max(c_end);
531                    max_child_err = max_child_err.max(child.get_cluster_error());
532                }
533                let cone_axis: Vec3 = if axis_sum.length_sq() > 1.0e-6 {
534                    axis_sum.normalize()
535                } else {
536                    Vec3::new(0.0, 1.0, 0.0)
537                };
538                let mut cone_cutoff: f32 = 1.0;
539                for child in nodes[cursor..group_end].iter() {
540                    let dot_axis: f32 = child.get_cone_axis().dot(cone_axis);
541                    cone_cutoff = cone_cutoff.min(dot_axis * child.get_cone_cutoff().max(0.0));
542                }
543                let group_error: f32 =
544                    max_child_err.max(merged_bounds.radius() * 0.04 * (next_lod as f32));
545                for child in nodes[cursor..group_end].iter_mut() {
546                    child.set_parent_error(group_error);
547                }
548                nodes.push(NaniteClusterNode {
549                    first_tri: min_tri,
550                    tri_count: max_tri_end.saturating_sub(min_tri),
551                    bounds: merged_bounds,
552                    cone_axis,
553                    cone_cutoff: cone_cutoff.clamp(-1.0, 1.0),
554                    cluster_error: group_error,
555                    parent_error: f32::INFINITY,
556                    lod_level: next_lod,
557                    child_start: cursor as u32,
558                    child_count: (group_end - cursor) as u16,
559                });
560                cursor = group_end;
561            }
562            level_start = next_start;
563            level_end = nodes.len();
564            level_count += 1;
565            cur_lod = next_lod;
566        }
567        Self {
568            nodes,
569            root_start: level_start,
570            level_count,
571        }
572    }
573
574    /// Evaluates a continuous Nanite screen-error cut across this DAG with frustum, normal-cone, micro-area, and Hi-Z occlusion culling.
575    ///
576    /// # Arguments
577    ///
578    /// - `&NaniteCutContext<'_>` - Per-object camera, transform, frustum, Hi-Z, and screen-error parameters.
579    /// - `&mut Vec<(usize, usize)>` - Reusable output triangle-range buffer cleared and populated in place.
580    ///
581    /// # Returns
582    ///
583    /// - `NaniteCutStats` - Drawn and per-stage culled cluster counts.
584    pub fn select_cut(
585        &self,
586        context: &NaniteCutContext<'_>,
587        out_ranges: &mut Vec<(usize, usize)>,
588    ) -> NaniteCutStats {
589        out_ranges.clear();
590        let nodes: &[NaniteClusterNode] = self.get_nodes().as_slice();
591        if nodes.is_empty() {
592            return NaniteCutStats::default();
593        }
594        let mut stats: NaniteCutStats = NaniteCutStats::default();
595        let mut stack: [usize; 128] = [0; 128];
596        let mut sp: usize = 0;
597        let root_start: usize = self.get_root_start().min(nodes.len());
598        for root_idx in root_start..nodes.len() {
599            if sp < stack.len() {
600                stack[sp] = root_idx;
601                sp += 1;
602            }
603        }
604        let cam_pos: Vec3 = context.get_camera_position();
605        let model_mat: Mat4 = context.get_model_matrix();
606        let view_proj: Mat4 = context.get_view_projection();
607        let normal_basis: [Vec3; 3] = context.get_normal_basis();
608        let frustum: Frustum3D = context.get_frustum();
609        let hiz_opt: Option<&HiZPyramid> = context.hiz_pyramid_ref();
610        let cull_backface: bool = context.get_cull_backface();
611        let focal_px: f32 = context.get_focal_px().max(1.0);
612        let err_thresh: f32 = context.get_error_threshold_px().max(0.25);
613        let near_plane: f32 = context.get_near_plane();
614        let vp_w: f32 = context.get_viewport_width();
615        let vp_h: f32 = context.get_viewport_height();
616        let max_tris: usize = context.get_total_triangles();
617        while sp > 0 {
618            sp -= 1;
619            let node_idx: usize = stack[sp];
620            let node: NaniteClusterNode = nodes[node_idx];
621            let world_bounds: AxisAlignedBox3D = model_mat.transform_bounds(node.get_bounds());
622            if !frustum.intersects_bounds(&world_bounds) {
623                stats.set_clusters_frustum_culled(stats.get_clusters_frustum_culled() + 1);
624                continue;
625            }
626            let cutoff: f32 = node.get_cone_cutoff();
627            if cull_backface && cutoff > 0.05 {
628                let world_axis: Vec3 =
629                    Mat4::transform_normal_with_basis(node.get_cone_axis(), normal_basis);
630                let to_cluster: Vec3 = world_bounds.center().sub(cam_pos);
631                let dist_len: f32 = to_cluster.length();
632                let sin_alpha: f32 = (1.0 - cutoff * cutoff).max(0.0).sqrt();
633                if to_cluster.dot(world_axis) > dist_len * sin_alpha + world_bounds.radius() {
634                    stats.set_clusters_cone_culled(stats.get_clusters_cone_culled() + 1);
635                    continue;
636                }
637            }
638            let screen_area: f32 = HiZPyramid::projected_screen_area_px(
639                world_bounds,
640                &view_proj,
641                vp_w,
642                vp_h,
643                near_plane,
644            );
645            if screen_area < NANITE_MIN_SCREEN_AREA_PX {
646                stats.set_clusters_micro_culled(stats.get_clusters_micro_culled() + 1);
647                continue;
648            }
649            if let Some(hiz) = hiz_opt
650                && hiz.is_bounds_occluded(world_bounds, &view_proj, near_plane)
651            {
652                stats.set_clusters_hiz_culled(stats.get_clusters_hiz_culled() + 1);
653                continue;
654            }
655            let dist: f32 = world_bounds.center().sub(cam_pos).length().max(0.5);
656            let proj_error: f32 = (node.get_cluster_error() * focal_px) / dist;
657            let child_count: usize = node.get_child_count() as usize;
658            if child_count > 0 && proj_error > err_thresh {
659                let child_start: usize = node.get_child_start() as usize;
660                let child_end: usize = child_start.saturating_add(child_count).min(nodes.len());
661                for child_idx in child_start..child_end {
662                    if sp < stack.len() {
663                        stack[sp] = child_idx;
664                        sp += 1;
665                    }
666                }
667            } else {
668                let start_tri: usize = node.get_first_tri() as usize;
669                let end_tri: usize = start_tri
670                    .saturating_add(node.get_tri_count() as usize)
671                    .min(max_tris);
672                if start_tri < end_tri {
673                    out_ranges.push((start_tri, end_tri));
674                    stats.set_clusters_drawn(stats.get_clusters_drawn() + 1);
675                }
676            }
677        }
678        stats
679    }
680}
681
682/// Accessors and builder helpers for `NaniteCutContext`.
683impl<'a> NaniteCutContext<'a> {
684    /// Returns the optional borrowed `HiZPyramid` reference attached to this cut context.
685    ///
686    /// # Returns
687    ///
688    /// - `Option<&'a HiZPyramid>` - Optional active Hi-Z pyramid.
689    #[must_use]
690    pub fn hiz_pyramid_ref(&self) -> Option<&'a HiZPyramid> {
691        let Self { hiz_pyramid, .. } = self;
692        *hiz_pyramid
693    }
694
695    /// Attaches an optional conservative reverse-Z `HiZPyramid` to this cut context.
696    ///
697    /// # Arguments
698    ///
699    /// - `Option<&'a HiZPyramid>` - Optional Hi-Z pyramid for cluster occlusion culling.
700    ///
701    /// # Returns
702    ///
703    /// - `Self` - Updated cut context.
704    #[must_use]
705    pub fn with_hiz(mut self, pyramid: Option<&'a HiZPyramid>) -> Self {
706        let Self { hiz_pyramid, .. } = &mut self;
707        *hiz_pyramid = pyramid;
708        self
709    }
710
711    /// Creates a `NaniteCutContext` configured for an object transform, camera frustum, and viewport projection.
712    ///
713    /// # Arguments
714    ///
715    /// - `(Vec3, Frustum3D)` - `(camera_position, frustum)` active view camera state.
716    /// - `(Mat4, Mat4, [Vec3; 3])` - `(model_matrix, view_projection, normal_basis)` transform matrices.
717    /// - `bool` - Whether closed-mesh normal-cone backface culling is enabled.
718    /// - `(f32, f32, f32, f32)` - `(focal_px, near_plane, viewport_width, viewport_height)`.
719    /// - `usize` - Total triangles in the mesh.
720    ///
721    /// # Returns
722    ///
723    /// - `Self` - Ready Nanite cut context with default error threshold.
724    #[must_use]
725    pub fn for_object(
726        camera_state: (Vec3, Frustum3D),
727        transforms: (Mat4, Mat4, [Vec3; 3]),
728        cull_backface: bool,
729        projection: (f32, f32, f32, f32),
730        total_triangles: usize,
731    ) -> Self {
732        let (camera_position, frustum): (Vec3, Frustum3D) = camera_state;
733        let (model_matrix, view_projection, normal_basis): (Mat4, Mat4, [Vec3; 3]) = transforms;
734        let (focal_px, near_plane, viewport_width, viewport_height): (f32, f32, f32, f32) =
735            projection;
736        Self {
737            camera_position,
738            model_matrix,
739            view_projection,
740            normal_basis,
741            frustum,
742            hiz_pyramid: None,
743            cull_backface,
744            focal_px,
745            error_threshold_px: NANITE_DEFAULT_ERROR_THRESHOLD_PX,
746            near_plane,
747            viewport_width,
748            viewport_height,
749            total_triangles,
750        }
751    }
752}