Skip to main content

re_render/
cluster.rs

1//! Cluster-Grid für Licht-Culling und Clustered Shadows (M5, Box 2).
2//!
3//! „Shadow 2.0 = cascaded + clustered“: CSM deckt die gerichtete Sonne ab,
4//! für Punkt- und Spot-Lichter schneidet man den Sichtraum zusätzlich in
5//! ein 3D-Raster — Bildschirm-Kacheln (x·y) mal logarithmische
6//! Tiefenscheiben. Jede Zelle (ein *Cluster*) trägt die Lichter, die sie
7//! schneiden; der Shader indiziert nur noch seinen eigenen Cluster.
8//!
9//! Dieser Kern liefert die Aufteilung, die Index-Mathematik und die
10//! CPU-Referenz des Licht-Cullings ([`cull_lights`]) — backend-neutral
11//! und headless testbar. Der GPU-Pass spiegelt [`cluster_view_aabb`] und
12//! die Kugel-AABB-Prüfung Kanal-für-Kanal.
13
14use glam::{Mat4, Vec3};
15
16/// Logarithmische Tiefen-Grenzen von `near` bis `far` (Länge `count + 1`).
17///
18/// Log-Scheiben haben konstante *relative* Auflösung: nahe Cluster sind
19/// dünn, ferne dick — passend zur perspektivischen Tiefenverteilung.
20/// `count = 0` ergibt nur die beiden Anker.
21pub fn log_z_bounds(near: f32, far: f32, count: usize) -> Vec<f32> {
22    let near = near.max(1e-4);
23    let far = far.max(near * 1.001);
24    let n = count;
25    let ratio = far / near;
26    (0..=n)
27        .map(|i| {
28            if i == n {
29                far
30            } else {
31                near * ratio.powf(i as f32 / n.max(1) as f32)
32            }
33        })
34        .collect()
35}
36
37/// Bildschirm-Kachelraster × logarithmische Tiefenscheiben.
38#[derive(Clone, Debug, PartialEq)]
39pub struct ClusterGrid {
40    /// Kacheln waagerecht.
41    pub tiles_x: u32,
42    /// Kacheln senkrecht.
43    pub tiles_y: u32,
44    /// Tiefen-Grenzen, Länge `slices + 1`, monoton `near..far`.
45    z_bounds: Vec<f32>,
46}
47
48impl ClusterGrid {
49    /// Raster mit `tiles_x·tiles_y` Kacheln und `slices` Scheiben über
50    /// `near..far`. Alle Achsen mindestens 1; `far <= near` wird
51    /// auf `near · 1.001` gehoben.
52    pub fn new(tiles_x: u32, tiles_y: u32, slices: u32, near: f32, far: f32) -> Self {
53        Self {
54            tiles_x: tiles_x.max(1),
55            tiles_y: tiles_y.max(1),
56            z_bounds: log_z_bounds(near, far, slices.max(1) as usize),
57        }
58    }
59
60    /// Kachelraster für eine Rendergröße: `tiles = ceil(size / tile_size)`,
61    /// mindestens 1 je Achse.
62    pub fn for_render_size(
63        render_size: [u32; 2],
64        tile_size: u32,
65        slices: u32,
66        near: f32,
67        far: f32,
68    ) -> Self {
69        let ts = tile_size.max(1);
70        Self::new(
71            render_size[0].max(1).div_ceil(ts),
72            render_size[1].max(1).div_ceil(ts),
73            slices,
74            near,
75            far,
76        )
77    }
78
79    /// Anzahl Tiefenscheiben.
80    pub fn slice_count(&self) -> u32 {
81        (self.z_bounds.len() - 1) as u32
82    }
83
84    /// Gesamtzahl Cluster.
85    pub fn cluster_count(&self) -> u32 {
86        self.tiles_x * self.tiles_y * self.slice_count()
87    }
88
89    /// Grenzen der Scheibe `slice` als `(near, far)` dieser Scheibe.
90    pub fn slice_bounds(&self, slice: u32) -> Option<(f32, f32)> {
91        let i = slice as usize;
92        if i + 1 < self.z_bounds.len() {
93            Some((self.z_bounds[i], self.z_bounds[i + 1]))
94        } else {
95            None
96        }
97    }
98
99    /// Linearer Cluster-Index: x am schnellsten, dann y, dann Scheibe —
100    /// benachbarte Kacheln liegen also beieinander (gutmütig für
101    /// Speicherzugriff-Muster auf der GPU).
102    pub fn index(&self, tile_x: u32, tile_y: u32, slice: u32) -> u32 {
103        (slice * self.tiles_y + tile_y) * self.tiles_x + tile_x
104    }
105
106    /// Umkehrung von [`Self::index`]. `None` außerhalb des Rasters.
107    pub fn coords(&self, index: u32) -> Option<(u32, u32, u32)> {
108        if index >= self.cluster_count() {
109            return None;
110        }
111        let x = index % self.tiles_x;
112        let y = (index / self.tiles_x) % self.tiles_y;
113        let z = index / (self.tiles_x * self.tiles_y);
114        Some((x, y, z))
115    }
116
117    /// Scheibe einer Sichttiefe. `None` außerhalb `near..far`.
118    /// Scheibengrenzen gehören zur *unteren* Scheibe (nur `near` selbst
119    /// startet Scheibe 0) — so ist die Zuordnung eindeutig.
120    pub fn slice_of(&self, view_depth: f32) -> Option<u32> {
121        let last = self.z_bounds.len() - 1;
122        if view_depth < self.z_bounds[0] || view_depth > self.z_bounds[last] {
123            return None;
124        }
125        let pp = self.z_bounds.partition_point(|&b| b < view_depth);
126        Some((pp.saturating_sub(1) as u32).min(self.slice_count() - 1))
127    }
128
129    /// Cluster für einen Pixel (`pixel_x`, `pixel_y`) bei gegebener
130    /// Kachelgröße und Sichttiefe. Pixel außerhalb des Rasters werden auf
131    /// die Randkachel geklemmt (Raster deckt die Rendergröße vollständig).
132    pub fn locate(
133        &self,
134        pixel_x: u32,
135        pixel_y: u32,
136        tile_size: u32,
137        view_depth: f32,
138    ) -> Option<u32> {
139        let ts = tile_size.max(1);
140        let tx = (pixel_x / ts).min(self.tiles_x - 1);
141        let ty = (pixel_y / ts).min(self.tiles_y - 1);
142        self.slice_of(view_depth).map(|z| self.index(tx, ty, z))
143    }
144}
145
146// ── Licht-Culling (CPU-Referenz des Compute-Passes) ───────────────────
147//
148// Der GPU-Compute-Pass tut genau zwei Dinge: pro Cluster sein View-Raum-
149// AABB aufbauen (cluster_view_aabb) und jede Licht-Kugel dagegen testen
150// (sphere_intersects_aabb). Diese Funktionen sind 1:1 die CPU-Referenz —
151// der Compute-Shader muss dieselben Listen liefern (Index-für-Index).
152
153/// Ein Licht als Culling-Kugel (Punktlicht: Radius = Reichweite; Spot:
154/// Hüllkugel des Kegels).
155#[derive(Clone, Copy, Debug, PartialEq)]
156pub struct SphereLight {
157    pub position: Vec3,
158    pub radius: f32,
159}
160
161impl SphereLight {
162    pub fn new(position: Vec3, radius: f32) -> Self {
163        Self {
164            position,
165            radius: radius.max(0.0),
166        }
167    }
168}
169
170/// Das View-Raum-AABB des Clusters `(tile_x, tile_y, slice)`.
171///
172/// Der Cluster ist ein Sichtkörper-Zellfach: die Kachel spannt ihren NDC-
173/// x/y-Bereich (Kachel 0 = oben-links), die Scheibe die lineare Sichttiefe
174/// `near..far` (Kamera blickt die −Z entlang). Da die x/y-Ausdehnung mit
175/// der Tiefe wächst, wird das AABB über beide Scheiben-Tiefen genommen —
176/// konservativ, nie ein False Negative gegen die echte Zelle.
177///
178/// `proj` muss eine Standard-Perspektivmatrix sein (x_axis.x = cot(fov_x/2),
179/// y_axis.y = cot(fov_y/2)); entartete Werte → `None`.
180pub fn cluster_view_aabb(
181    grid: &ClusterGrid,
182    tile_x: u32,
183    tile_y: u32,
184    slice: u32,
185    proj: &Mat4,
186) -> Option<(Vec3, Vec3)> {
187    let a = proj.x_axis.x;
188    let b = proj.y_axis.y;
189    if a == 0.0 || b == 0.0 || !a.is_finite() || !b.is_finite() {
190        return None;
191    }
192    if tile_x >= grid.tiles_x || tile_y >= grid.tiles_y {
193        return None;
194    }
195    let (zn, zf) = grid.slice_bounds(slice)?;
196    // NDC-Spannweite der Kachel; y von oben (Kachel 0) nach unten.
197    let nx0 = 2.0 * tile_x as f32 / grid.tiles_x as f32 - 1.0;
198    let nx1 = 2.0 * (tile_x + 1) as f32 / grid.tiles_x as f32 - 1.0;
199    let ny1 = 1.0 - 2.0 * tile_y as f32 / grid.tiles_y as f32;
200    let ny0 = 1.0 - 2.0 * (tile_y + 1) as f32 / grid.tiles_y as f32;
201    // ndc_x = a·x/d ⇒ x = ndc_x·d/a (analog y); Sichttiefe d ⇒ z = −d.
202    let corner = |ndc_x: f32, ndc_y: f32, d: f32| Vec3::new(ndc_x * d / a, ndc_y * d / b, -d);
203    let mut mn = Vec3::splat(f32::MAX);
204    let mut mx = Vec3::splat(f32::MIN);
205    for (ex, ey) in [(nx0, ny0), (nx0, ny1), (nx1, ny0), (nx1, ny1)] {
206        for d in [zn, zf] {
207            let c = corner(ex, ey, d);
208            mn = mn.min(c);
209            mx = mx.max(c);
210        }
211    }
212    Some((mn, mx))
213}
214
215/// Konservative Kugel-AABB-Prüfung (Distanz zum nächstgelegenen Punkt).
216pub fn sphere_intersects_aabb(center: Vec3, radius: f32, min: Vec3, max: Vec3) -> bool {
217    let closest = center.clamp(min, max);
218    (closest - center).length_squared() <= radius * radius
219}
220
221/// CPU-Referenz des Licht-Culling-Passes: je Cluster die Indizes der
222/// erreichenden Lichter, aufsteigend — deterministisch.
223///
224/// Die Licht-Kugeln werden in den View-Raum transformiert (View ist
225/// starr ⇒ Radius bleibt) gegen [`cluster_view_aabb`] getestet — genau
226/// die Reihenfolge des Compute-Shaders. Ergebnis-Länge:
227/// `grid.cluster_count()`.
228pub fn cull_lights(
229    grid: &ClusterGrid,
230    view: &Mat4,
231    proj: &Mat4,
232    lights: &[SphereLight],
233) -> Vec<Vec<u32>> {
234    let view_lights: Vec<(Vec3, f32)> = lights
235        .iter()
236        .map(|l| (view.transform_point3(l.position), l.radius))
237        .collect();
238    let mut out = vec![Vec::new(); grid.cluster_count() as usize];
239    for z in 0..grid.slice_count() {
240        for y in 0..grid.tiles_y {
241            for x in 0..grid.tiles_x {
242                let Some((mn, mx)) = cluster_view_aabb(grid, x, y, z, proj) else {
243                    continue;
244                };
245                let cell = &mut out[grid.index(x, y, z) as usize];
246                for (li, (c, r)) in view_lights.iter().enumerate() {
247                    if sphere_intersects_aabb(*c, *r, mn, mx) {
248                        cell.push(li as u32);
249                    }
250                }
251            }
252        }
253    }
254    out
255}
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260
261    fn approx(a: f32, b: f32, eps: f32) -> bool {
262        (a - b).abs() < eps
263    }
264
265    #[test]
266    fn z_grenzen_verankert_monoton_und_log() {
267        let b = log_z_bounds(0.5, 200.0, 4);
268        assert_eq!(b.len(), 5);
269        assert!(approx(b[0], 0.5, 1e-5) && approx(*b.last().unwrap(), 200.0, 1e-5));
270        for w in b.windows(2) {
271            assert!(w[1] > w[0], "monoton: {w:?}");
272        }
273        // Log: konstantes Verhältnis je Scheibe.
274        let r0 = b[1] / b[0];
275        let r1 = b[2] / b[1];
276        let r3 = b[4] / b[3];
277        assert!(
278            approx(r0, r1, 1e-3) && approx(r1, r3, 1e-3),
279            "log-Verhältnis {r0},{r1},{r3}"
280        );
281        // Absolute Abstände wachsen nach hinten.
282        assert!(b[1] - b[0] < b[4] - b[3]);
283    }
284
285    #[test]
286    fn grid_baut_und_klemmt() {
287        let g = ClusterGrid::new(8, 6, 4, 0.1, 100.0);
288        assert_eq!(g.slice_count(), 4);
289        assert_eq!(g.cluster_count(), 8 * 6 * 4);
290        // Unsinnige Achsen -> mindestens 1.
291        let e = ClusterGrid::new(0, 0, 0, 10.0, 5.0);
292        assert_eq!((e.tiles_x, e.tiles_y, e.slice_count()), (1, 1, 1));
293        // for_render_size deckt die Größe vollständig ab.
294        let r = ClusterGrid::for_render_size([1920, 1080], 16, 4, 0.1, 400.0);
295        assert_eq!((r.tiles_x, r.tiles_y), (120, 68)); // ceil(1920/16), ceil(1080/16)
296    }
297
298    #[test]
299    fn index_und_coords_sind_invers() {
300        let g = ClusterGrid::new(4, 3, 5, 0.1, 100.0);
301        for z in 0..g.slice_count() {
302            for y in 0..g.tiles_y {
303                for x in 0..g.tiles_x {
304                    let i = g.index(x, y, z);
305                    assert!(i < g.cluster_count());
306                    assert_eq!(g.coords(i), Some((x, y, z)), "Roundtrip {x},{y},{z}");
307                }
308            }
309        }
310        assert_eq!(g.coords(g.cluster_count()), None);
311    }
312
313    #[test]
314    fn scheibenzuordnung_eindeutig() {
315        let g = ClusterGrid::new(1, 1, 4, 1.0, 1000.0);
316        // Anker: near -> Scheibe 0, far -> letzte Scheibe.
317        assert_eq!(g.slice_of(1.0), Some(0));
318        assert_eq!(g.slice_of(1000.0), Some(3));
319        // Außerhalb: None.
320        assert_eq!(g.slice_of(0.99), None);
321        assert_eq!(g.slice_of(1000.1), None);
322        // Jede Tiefe zwischen near und far trifft genau eine Scheibe,
323        // und die Scheibengrenzen gehören nach unten.
324        let b = log_z_bounds(1.0, 1000.0, 4);
325        for k in 0..4 {
326            let innen = (b[k] + b[k + 1]) * 0.5;
327            assert_eq!(g.slice_of(innen), Some(k as u32), "Mitte Scheibe {k}");
328            if k > 0 {
329                assert_eq!(
330                    g.slice_of(b[k]),
331                    Some((k - 1) as u32),
332                    "Grenze {k} -> unten"
333                );
334            }
335        }
336        // slice_bounds passt zu slice_of: Mitte der Scheibe liegt in ihr.
337        let (n, f) = g.slice_bounds(2).unwrap();
338        assert!(n < f && f <= 1000.0);
339        assert_eq!(g.slice_of((n + f) * 0.5), Some(2));
340        assert_eq!(g.slice_bounds(4), None);
341    }
342
343    #[test]
344    fn locate_nutzt_raster_richtig() {
345        let g = ClusterGrid::for_render_size([100, 50], 10, 4, 1.0, 1000.0);
346        assert_eq!((g.tiles_x, g.tiles_y), (10, 5));
347        let tiefe = 1.0; // Scheibe 0
348        assert_eq!(g.locate(0, 0, 10, tiefe), Some(g.index(0, 0, 0)));
349        assert_eq!(g.locate(10, 0, 10, tiefe), Some(g.index(1, 0, 0)));
350        assert_eq!(g.locate(0, 10, 10, tiefe), Some(g.index(0, 1, 0)));
351        // Rand-Pixel (99,49) und darüber hinaus -> letzte Kachel.
352        assert_eq!(g.locate(99, 49, 10, tiefe), Some(g.index(9, 4, 0)));
353        assert_eq!(g.locate(500, 500, 10, tiefe), Some(g.index(9, 4, 0)));
354        // Tiefe außerhalb -> None.
355        assert_eq!(g.locate(5, 5, 10, 2000.0), None);
356    }
357
358    #[test]
359    fn tiefe_und_index_haengen_konsistent_zusammen() {
360        let g = ClusterGrid::new(2, 2, 4, 1.0, 1000.0);
361        let b = log_z_bounds(1.0, 1000.0, 4);
362        for k in 0..4 {
363            let d = (b[k] + b[k + 1]) * 0.5;
364            let idx = g.locate(15, 15, 10, d).unwrap();
365            let (x, y, z) = g.coords(idx).unwrap();
366            assert_eq!((x, y), (1, 1), "Pixel (15,15) bei tile 10");
367            assert_eq!(z, k as u32, "Scheibe bei Tiefe {d}");
368        }
369    }
370
371    // ── Licht-Culling ──────────────────────────────────────────────────
372
373    /// Kamera: Identitäts-View, 90° fovy, Aspect 1, near 1, far 100.
374    fn test_camera() -> (Mat4, Mat4) {
375        (
376            Mat4::IDENTITY,
377            Mat4::perspective_rh(std::f32::consts::FRAC_PI_2, 1.0, 1.0, 100.0),
378        )
379    }
380
381    #[test]
382    fn cluster_aabb_waechst_mit_der_tiefe() {
383        let (view, proj) = test_camera();
384        let _ = view;
385        let g = ClusterGrid::new(1, 1, 4, 1.0, 100.0);
386        let (mn0, mx0) = cluster_view_aabb(&g, 0, 0, 0, &proj).unwrap();
387        let (mn3, mx3) = cluster_view_aabb(&g, 0, 0, 3, &proj).unwrap();
388        // Volle NDC-Breite: bei 90° fovy gilt x = ±d.
389        assert!(approx(mx0.x, g.slice_bounds(0).unwrap().1, 1e-3));
390        assert!(mn0.z < mx0.z && approx(mn0.z, -g.slice_bounds(0).unwrap().1, 1e-5));
391        assert!(mn3.x < mn0.x, "ferne Zelle auch nach links breiter");
392        assert!(mx3.x > mx0.x * 3.0, "ferne Zelle deutlich breiter");
393        // Z-Achse = Scheiben-Tiefen (negativ, Blick −Z).
394        let (zn, zf) = g.slice_bounds(2).unwrap();
395        let (mn, mx) = cluster_view_aabb(&g, 0, 0, 2, &proj).unwrap();
396        assert!(approx(mn.z, -zf, 1e-4) && approx(mx.z, -zn, 1e-4));
397    }
398
399    #[test]
400    fn kugel_aabb_grundfaelle() {
401        let (mn, mx) = (Vec3::splat(-1.0), Vec3::splat(1.0));
402        assert!(sphere_intersects_aabb(Vec3::ZERO, 0.1, mn, mx), "Innen");
403        assert!(
404            sphere_intersects_aabb(Vec3::new(1.5, 0.0, 0.0), 0.5, mn, mx),
405            "Berührt"
406        );
407        assert!(
408            !sphere_intersects_aabb(Vec3::new(1.6, 0.0, 0.0), 0.5, mn, mx),
409            "Außerhalb"
410        );
411        assert!(
412            sphere_intersects_aabb(Vec3::new(3.0, 3.0, 0.0), 3.0, mn, mx),
413            "Ecke aus der Ferne"
414        );
415    }
416
417    #[test]
418    fn zentrales_licht_nur_in_seiner_scheibe() {
419        let (view, proj) = test_camera();
420        let g = ClusterGrid::new(2, 2, 4, 1.0, 100.0);
421        // Tiefe 5: Scheiben [1, 3.16, 10, 31.6, 100] -> Scheibe 1.
422        let lights = [SphereLight::new(Vec3::new(0.0, 0.0, -5.0), 0.1)];
423        let lists = cull_lights(&g, &view, &proj, &lights);
424        for z in 0..4 {
425            for t in 0..4 {
426                let cell = &lists[g.index(t % 2, t / 2, z) as usize];
427                if z == 1 {
428                    // x=0/y=0 liegt auf der Kachelgrenze -> alle 4 Kacheln.
429                    assert!(cell.contains(&0), "Scheibe 1, Kachel {t} muss treffen");
430                } else {
431                    assert!(cell.is_empty(), "Scheibe {z}, Kachel {t} muss leer sein");
432                }
433            }
434        }
435    }
436
437    #[test]
438    fn licht_hinter_oder_neben_der_kamera_faellt_weg() {
439        let (view, proj) = test_camera();
440        let g = ClusterGrid::new(2, 2, 4, 1.0, 100.0);
441        let lights = [
442            SphereLight::new(Vec3::new(0.0, 0.0, 5.0), 0.5), // dahinter
443            SphereLight::new(Vec3::new(50.0, 0.0, -5.0), 0.5), // weit rechts vorbei
444        ];
445        let lists = cull_lights(&g, &view, &proj, &lights);
446        assert!(
447            lists.iter().all(|l| l.is_empty()),
448            "beide müssen komplett weg sein"
449        );
450    }
451
452    #[test]
453    fn riesiges_licht_trifft_alle_cluster() {
454        let (view, proj) = test_camera();
455        let g = ClusterGrid::new(3, 3, 4, 1.0, 100.0);
456        let lights = [SphereLight::new(Vec3::new(0.0, 0.0, -30.0), 500.0)];
457        let lists = cull_lights(&g, &view, &proj, &lights);
458        assert_eq!(lists.len(), g.cluster_count() as usize);
459        assert!(
460            lists.iter().all(|l| l == &vec![0]),
461            "riesige Kugel schneidet alles"
462        );
463    }
464
465    #[test]
466    fn keine_false_negatives_konservativ_wie_die_gpu() {
467        let (view, proj) = test_camera();
468        let g = ClusterGrid::new(4, 4, 4, 1.0, 100.0);
469        // Tiefe 6 (Scheibe 1), NDC (-0.4, 0.4) -> Kachel x=1, y=1 (y von oben).
470        let d = 6.0;
471        let pos = Vec3::new(-0.4 * d, 0.4 * d, -d);
472        let lights = [SphereLight::new(pos, 0.05)];
473        let lists = cull_lights(&g, &view, &proj, &lights);
474        let hits: Vec<u32> = (0..g.cluster_count())
475            .filter(|&i| !lists[i as usize].is_empty())
476            .collect();
477        // Muss den Ziel-Cluster enthalten (kein False Negative)…
478        let target = g.index(1, 1, 1);
479        assert!(hits.contains(&target), "Ziel-Cluster fehlt: {hits:?}");
480        // …und darf wegen des konservativen AABBs (spannt beide Scheiben-
481        // Tiefen) Nachbar-Kacheln derselben Scheibe streifen — niemals
482        // aber eine andere Scheibe oder einen anderen Kachelblock.
483        for h in &hits {
484            let (x, y, z) = g.coords(*h).unwrap();
485            assert_eq!(z, 1, "Treffer in falscher Scheibe: {h}");
486            assert!(
487                (x as i32 - 1).abs() <= 1 && (y as i32 - 1).abs() <= 1,
488                "Treffer zu weit weg: {h}"
489            );
490        }
491    }
492
493    #[test]
494    fn culling_ist_deterministisch_und_sortiert() {
495        let (view, proj) = test_camera();
496        let g = ClusterGrid::new(2, 2, 2, 1.0, 50.0);
497        let lights = [
498            SphereLight::new(Vec3::new(0.0, 0.0, -5.0), 2.0),
499            SphereLight::new(Vec3::new(0.2, 0.0, -5.2), 1.0),
500            SphereLight::new(Vec3::new(0.0, 0.0, -20.0), 3.0),
501        ];
502        let a = cull_lights(&g, &view, &proj, &lights);
503        let b = cull_lights(&g, &view, &proj, &lights);
504        assert_eq!(a, b, "zwei Läufe müssen identisch sein");
505        for l in &a {
506            let mut s = l.clone();
507            s.sort();
508            assert_eq!(l, &s, "Listen müssen aufsteigend sortiert sein");
509        }
510        // Licht 0 und 1 überschneiden sich -> gemeinsame Cluster mit [0,1].
511        assert!(
512            a.iter().any(|l| l == &vec![0u32, 1]),
513            "Überschneidung muss Liste [0,1] erzeugen"
514        );
515    }
516}