1use crate::cull::{Frustum, HiZPyramid};
19use glam::{Mat4, Vec3};
20
21#[derive(Clone, Copy, Debug, PartialEq)]
29pub struct GdrInstance {
30 pub world: Mat4,
31 pub center: Vec3,
32 pub half: Vec3,
33 pub albedo: [f32; 4],
34 pub params: [f32; 4],
35 pub mesh: u32,
36}
37
38#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
43pub struct GdrArgs {
44 pub index_count: u32,
45 pub instance_count: u32,
46 pub first_index: u32,
47 pub base_vertex: i32,
48 pub first_instance: u32,
49}
50
51pub type GdrArgsRow = (u32, u32, u32, i32, u32);
56
57#[derive(Clone, Copy, Debug, PartialEq)]
61pub struct ScreenWindow {
62 pub x0: u32,
63 pub y0: u32,
64 pub w: u32,
65 pub h: u32,
66 pub near: f32,
67}
68
69impl ScreenWindow {
70 pub fn from_aabb(
76 view_proj: &Mat4,
77 center: Vec3,
78 half: Vec3,
79 width: u32,
80 height: u32,
81 ) -> Option<Self> {
82 let (mut mnx, mut mny) = (f32::MAX, f32::MAX);
83 let (mut mxx, mut mxy) = (f32::MIN, f32::MIN);
84 let mut near = f32::MAX;
85 for i in 0..8 {
86 let corner = center
87 + Vec3::new(
88 if i & 1 == 0 { -half.x } else { half.x },
89 if i & 2 == 0 { -half.y } else { half.y },
90 if i & 4 == 0 { -half.z } else { half.z },
91 );
92 let clip = view_proj * corner.extend(1.0);
93 if clip.w <= 0.0 {
94 return None; }
96 let ndc = clip.truncate() / clip.w;
97 mnx = mnx.min(ndc.x);
98 mxx = mxx.max(ndc.x);
99 mny = mny.min(ndc.y);
100 mxy = mxy.max(ndc.y);
101 near = near.min(ndc.z);
102 }
103 let fx0 = (mnx * 0.5 + 0.5) * width as f32;
106 let fx1 = (mxx * 0.5 + 0.5) * width as f32;
107 let fy0 = (0.5 - mxy * 0.5) * height as f32;
108 let fy1 = (0.5 - mny * 0.5) * height as f32;
109 if fx0 < 0.0 || fy0 < 0.0 || fx1 > width as f32 || fy1 > height as f32 {
110 return None; }
112 let (x0, x1) = (
113 fx0.floor().max(0.0) as u32,
114 fx1.ceil().min(width as f32) as u32,
115 );
116 let (y0, y1) = (
117 fy0.floor().max(0.0) as u32,
118 fy1.ceil().min(height as f32) as u32,
119 );
120 Some(Self {
121 x0,
122 y0,
123 w: (x1.saturating_sub(x0)).max(1),
124 h: (y1.saturating_sub(y0)).max(1),
125 near,
126 })
127 }
128
129 pub fn occluded_by(&self, hiz: &HiZPyramid, epsilon: f32) -> bool {
139 let limit = self.near + epsilon;
140 let max_level = (hiz.level_count() - 1).min(13);
141 let mut m = HiZPyramid::level_for_size(self.w, self.h).min(max_level);
142 let mut occl = true;
143 while occl && m >= 1 {
144 let tx0 = self.x0 >> m;
145 let ty0 = self.y0 >> m;
146 let tx1 = (self.x0 + self.w - 1) >> m;
147 let ty1 = (self.y0 + self.h - 1) >> m;
148 let mut all = true;
149 for ty in ty0..=ty1 {
150 for tx in tx0..=tx1 {
151 if hiz.min_depth_in(m, tx, ty, tx + 1, ty + 1) > limit {
152 all = false;
153 }
154 }
155 }
156 occl = all;
157 m -= 1;
158 }
159 if occl {
160 if u64::from(self.w) * u64::from(self.h) > 4096 {
161 occl = false;
162 } else {
163 let mut all0 = true;
164 for dy in 0..self.h {
165 for dx in 0..self.w {
166 let px = self.x0 + dx;
167 let py = self.y0 + dy;
168 if hiz.min_depth_in(0, px, py, px + 1, py + 1) > limit {
169 all0 = false;
170 }
171 }
172 }
173 occl = all0;
174 }
175 }
176 occl
177 }
178}
179
180pub fn mesh_bounds(world: &Mat4, local_min: Vec3, local_max: Vec3) -> (Vec3, Vec3) {
185 let mut mn = Vec3::splat(f32::MAX);
186 let mut mx = Vec3::splat(f32::MIN);
187 for i in 0..8 {
188 let corner = world
189 * Vec3::new(
190 if i & 1 == 0 { local_min.x } else { local_max.x },
191 if i & 2 == 0 { local_min.y } else { local_max.y },
192 if i & 4 == 0 { local_min.z } else { local_max.z },
193 )
194 .extend(1.0);
195 mn = mn.min(corner.truncate());
198 mx = mx.max(corner.truncate());
199 }
200 ((mn + mx) * 0.5, (mx - mn) * 0.5)
201}
202
203#[derive(Clone, Debug, Default, PartialEq)]
207pub struct GdrCullResult {
208 pub list: Vec<u32>,
211 pub bases: Vec<u32>,
213 pub capacity: Vec<u32>,
215 pub args: Vec<GdrArgs>,
218}
219
220pub fn initial_args(index_counts: &[u32], bases: &[u32]) -> Vec<GdrArgs> {
228 index_counts
229 .iter()
230 .zip(bases)
231 .map(|(&n, &b)| GdrArgs {
232 index_count: n,
233 instance_count: 0,
234 first_index: 0,
235 base_vertex: 0,
236 first_instance: b,
237 })
238 .collect()
239}
240
241pub fn cull(
247 instances: &[GdrInstance],
248 index_counts: &[u32],
249 view_proj: &Mat4,
250 screen: Option<(u32, u32)>,
251 hiz: Option<(&HiZPyramid, f32)>,
252) -> GdrCullResult {
253 let n_mesh = index_counts.len();
254 let frustum = Frustum::from_view_proj(view_proj);
255 let mut capacity = vec![0u32; n_mesh];
256 for inst in instances {
257 let m = inst.mesh as usize;
258 debug_assert!(m < n_mesh, "Mesh-Schublade ausserhalb der Tabelle");
259 capacity[m] += 1;
260 }
261 let mut bases = vec![0u32; n_mesh];
262 let mut total = 0u32;
263 for m in 0..n_mesh {
264 bases[m] = total;
265 total += capacity[m];
266 }
267 let mut result = GdrCullResult {
268 list: vec![u32::MAX; total as usize],
269 bases: bases.clone(),
270 capacity,
271 args: initial_args(index_counts, &bases),
272 };
273 let mut filled = vec![0u32; n_mesh];
274 for (id, inst) in instances.iter().enumerate() {
275 let m = inst.mesh as usize;
276 if !frustum.intersects_aabb(inst.center, inst.half) {
277 continue;
278 }
279 if let (Some((pyramid, eps)), Some((sw, sh))) = (hiz, screen) {
280 if let Some(win) = ScreenWindow::from_aabb(view_proj, inst.center, inst.half, sw, sh) {
281 if win.occluded_by(pyramid, eps) {
282 continue;
283 }
284 }
285 }
286 result.list[(bases[m] + filled[m]) as usize] = id as u32;
287 filled[m] += 1;
288 }
289 for (m, &count) in filled.iter().enumerate() {
290 result.args[m].instance_count = count;
291 }
292 result
293}
294
295#[cfg(test)]
296mod tests {
297 use super::*;
298
299 fn persp(aspect: f32) -> Mat4 {
300 Mat4::perspective_rh(std::f32::consts::FRAC_PI_2, aspect, 0.1, 100.0)
301 }
302
303 fn inst(mesh: u32, x: f32) -> GdrInstance {
304 GdrInstance {
305 world: Mat4::from_translation(Vec3::new(x, 0.0, -5.0)),
306 center: Vec3::new(x, 0.0, -5.0),
307 half: Vec3::splat(0.5),
308 albedo: [0.6, 0.6, 0.6, 0.0],
309 params: [0.4, 0.0, 0.0, 0.0],
310 mesh,
311 }
312 }
313
314 #[test]
315 fn frustum_cull_haelt_sichtbare_verwirft_draussen() {
316 let vp = persp(1.0);
317 let list = [inst(0, 0.0), inst(0, 50.0), inst(1, -0.5), inst(0, 0.0)];
318 let r = cull(&list, &[36, 12], &vp, None, None);
319 assert_eq!(r.args[0].instance_count, 2, "zwei von Mesh 0 sichtbar");
320 assert_eq!(r.args[1].instance_count, 1);
321 assert_eq!(r.args[0].index_count, 36);
322 assert_eq!(&r.list[0..2], &[0, 3]);
325 assert_eq!(r.list[2], u32::MAX, "Mesh 0 lasst eine Stelle leer");
326 assert_eq!(r.list[3], 2, "Mesh 1 fuellt nur eine Stelle");
327 assert_eq!(r.bases, vec![0, 3]);
328 assert_eq!(r.capacity, vec![3, 1]);
329 }
330
331 #[test]
332 fn cull_is_deterministisch_ueber_wiederholungen() {
333 let vp = persp(1.6);
334 let list: Vec<_> = (0..64)
335 .map(|i| inst(i % 3, ((i as f32) * 0.37).rem_euclid(12.0) - 6.0))
336 .collect();
337 let a = cull(&list, &[10, 20, 30], &vp, Some((64, 40)), None);
338 let b = cull(&list, &[10, 20, 30], &vp, Some((64, 40)), None);
339 assert_eq!(a, b);
340 }
341
342 #[test]
343 fn bounds_umschliessen_rotierte_box_konservativ() {
344 let world = Mat4::from_rotation_z(std::f32::consts::FRAC_PI_6)
346 * Mat4::from_translation(Vec3::X * 3.0);
347 let mn = Vec3::new(-0.5, -1.0, -2.0);
348 let mx = Vec3::new(0.5, 1.0, 2.0);
349 let (c, h) = mesh_bounds(&world, mn, mx);
350 for i in 0..8 {
351 let corner = (world
352 * Vec3::new(
353 if i & 1 == 0 { mn.x } else { mx.x },
354 if i & 2 == 0 { mn.y } else { mx.y },
355 if i & 4 == 0 { mn.z } else { mx.z },
356 )
357 .extend(1.0))
358 .truncate();
359 for k in 0..3 {
360 assert!(
361 (corner[k] - c[k]).abs() <= h[k] + 1e-5,
362 "Ecke {corner:?} ausserhalb der Huelle {c:?}±{h:?}"
363 );
364 }
365 }
366 }
367
368 #[test]
369 fn okklusion_verdeckt_hinter_wand_und_laesst_freies_durch() {
370 let vp = persp(1.0);
371 let (sw, sh) = (64u32, 64u32);
372 let mut p = HiZPyramid::new(sw, sh);
374 let mut depth = vec![1.0; (sw * sh) as usize];
375 for y in 0..sh {
376 for x in 0..sw / 2 {
377 depth[(y * sw + x) as usize] = 0.5;
378 }
379 }
380 p.build_from_depth(&depth);
381 let win_left =
383 ScreenWindow::from_aabb(&vp, Vec3::new(-1.6, 0.0, -5.0), Vec3::splat(0.2), sw, sh)
384 .expect("ganz im Bild");
385 let win_right =
386 ScreenWindow::from_aabb(&vp, Vec3::new(1.6, 0.0, -5.0), Vec3::splat(0.2), sw, sh)
387 .expect("ganz im Bild");
388 assert!(
389 win_left.near > 0.5,
390 "Hinter der Wand: {:+.3} > 0.5",
391 win_left.near
392 );
393 assert!(win_left.occluded_by(&p, 1e-4), "hinter Wand verdeckt");
394 assert!(!win_right.occluded_by(&p, 1e-4), "neben der Wand frei");
395 let mut hidden = inst(0, -1.6);
397 hidden.half = Vec3::splat(0.2);
398 let mut open = inst(0, 1.6);
399 open.half = Vec3::splat(0.2);
400 let r = cull(
401 &[hidden, open],
402 &[12],
403 &vp,
404 Some((sw, sh)),
405 Some((&p, 1e-4)),
406 );
407 assert_eq!(r.args[0].instance_count, 1);
408 assert_eq!(r.list[r.bases[0] as usize], 1, "nur das freie Objekt");
409 let r2 = cull(&[hidden, open], &[12], &vp, Some((sw, sh)), None);
411 assert_eq!(r2.args[0].instance_count, 2);
412 }
413
414 #[test]
415 fn fenster_am_rand_und_hinter_kamera_bleiben_sichtbar() {
416 let vp = persp(1.0);
417 let edge =
419 ScreenWindow::from_aabb(&vp, Vec3::new(3.6, 0.0, -1.2), Vec3::splat(0.5), 64, 64);
420 assert!(edge.is_none(), "ueber den Rand: kein Okklusions-Beweis");
421 let cross =
423 ScreenWindow::from_aabb(&vp, Vec3::new(0.0, 0.0, -0.05), Vec3::splat(0.2), 64, 64);
424 assert!(cross.is_none(), "Kameraebene: kein Okklusions-Beweis");
425 }
426
427 #[test]
428 fn leere_tabellen_sind_sauber() {
429 let vp = persp(1.0);
430 let r = cull(&[], &[], &vp, None, None);
431 assert!(r.list.is_empty() && r.args.is_empty() && r.bases.is_empty());
432 let i0 = initial_args(&[6, 3], &[0, 6]);
433 assert_eq!(i0[0].index_count, 6);
434 assert_eq!(i0[0].first_instance, 0);
435 assert_eq!(i0[1].instance_count, 0);
436 assert_eq!(i0[1].first_instance, 6);
437 }
438}