Skip to main content

re_render/
billboard.rs

1//! Billboard-Bausteine: Quad-Geometrie, kamera-zugewandte Transform und
2//! UV-Rechtecke für Sheet-Texturen (SC1-Einheiten, Effekte, Icons).
3//!
4//! Ein Billboard ist hier bewusst kein eigener Draw-Typ, sondern ein
5//! normales [`DrawBatch`](crate::backend::DrawBatch) mit `sprite:
6//! Some(..)`: identischer Culling-/Sortier-/Backend-Pfad, nur eine
7//! andere Pipeline (unlit + alpha-blend) im Backend.
8
9use glam::{Mat4, Vec3};
10use re_core::mesh::Mesh;
11
12use crate::backend::Sprite;
13use crate::camera::Camera;
14
15/// Einheits-Quad (1×1) in der XY-Ebene, Front nach +Z, UV 0..1 mit
16/// (0,0) oben links — wie die Pixelzeilen einer Sheet-Textur.
17/// Alle Billboards einer Art teilen sich dieses Mesh (Backend-Cache).
18pub fn unit_quad() -> Mesh {
19    Mesh {
20        name: "billboard".into(),
21        positions: vec![
22            [-0.5, 0.5, 0.0],
23            [0.5, 0.5, 0.0],
24            [0.5, -0.5, 0.0],
25            [-0.5, -0.5, 0.0],
26        ],
27        normals: Some(vec![[0.0, 0.0, 1.0]; 4]),
28        uvs: Some(vec![[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]),
29        indices: Some(vec![0, 1, 2, 0, 2, 3]),
30        ..Default::default()
31    }
32}
33
34/// Matrix, die das Einheits-Quad an `center` kamera-zugewandt aufstellt.
35///
36/// `yaw_only` hält das Quad senkrecht (nur um die Hochachse zur Kamera,
37/// wie im Original und in VR üblich); sonst kippt es exakt mit ihr.
38pub fn billboard_matrix(
39    camera: &Camera,
40    center: Vec3,
41    width: f32,
42    height: f32,
43    yaw_only: bool,
44) -> Mat4 {
45    let c2w = camera.view.inverse();
46    let (right, up, forward) = if yaw_only {
47        // Horizontale Kamerarechte; Welt-Up; Front = rechtwinklig dazwischen.
48        let mut flat = Vec3::new(c2w.x_axis.x, 0.0, c2w.x_axis.z);
49        if flat.length_squared() < 1e-12 {
50            flat = Vec3::X; // Kamera senkrecht nach unten: Rechte beliebig
51        }
52        let right = flat.normalize();
53        (right, Vec3::Y, right.cross(Vec3::Y))
54    } else {
55        (
56            c2w.x_axis.truncate(),
57            c2w.y_axis.truncate(),
58            c2w.z_axis.truncate(),
59        )
60    };
61    Mat4::from_cols(
62        (right * width).extend(0.0),
63        (up * height).extend(0.0),
64        forward.extend(0.0),
65        center.extend(1.0),
66    )
67}
68
69/// Pixelrechteck eines [`Sprite`] → normalisierter UV-Offset
70/// `[u0, v0, du, dv]` (Textur-UVs: (0,0) = oben links).
71pub fn uv_rect(sprite: &Sprite, tex_w: u32, tex_h: u32) -> [f32; 4] {
72    let [x, y, w, h] = sprite.rect;
73    [
74        x as f32 / tex_w as f32,
75        y as f32 / tex_h as f32,
76        w as f32 / tex_w as f32,
77        h as f32 / tex_h as f32,
78    ]
79}
80
81#[cfg(test)]
82mod tests {
83    use super::*;
84
85    fn camera() -> Camera {
86        // MoBA-typisch: erhöht, schräg auf den Ursprung.
87        Camera::perspective(Vec3::new(20.0, 30.0, 20.0), Vec3::ZERO, Vec3::Y, 0.9, 1.6)
88    }
89
90    #[test]
91    fn quad_ist_einheitlich_und_uv_vollstaendig() {
92        let q = unit_quad();
93        assert_eq!(q.triangle_count(), 2);
94        let (mn, mx) = q.aabb();
95        assert_eq!((mn, mx), ([-0.5, -0.5, 0.0], [0.5, 0.5, 0.0]));
96        let uvs = q.uvs.unwrap();
97        assert_eq!(uvs[0], [0.0, 0.0]); // oben links (y>0)
98        assert_eq!(uvs[2], [1.0, 1.0]);
99    }
100
101    #[test]
102    fn billboard_zeigt_zur_kamera() {
103        let cam = camera();
104        let m = billboard_matrix(&cam, Vec3::new(4.0, 2.0, -6.0), 3.0, 6.0, true);
105        // Mittelpunkt landet exakt auf center.
106        let c = m.transform_point3(Vec3::new(0.0, 0.0, 0.0));
107        assert!((c - Vec3::new(4.0, 2.0, -6.0)).length() < 1e-5);
108        // yaw-only: Die Normale zeigt HORIZONTAL zur Kamera (Kamerahöhe
109        // darf sie nicht kippen) — darum Vergleich in der XZ-Ebene.
110        let n = m.transform_vector3(Vec3::Z);
111        assert!(n.y.abs() < 1e-6, "yaw-only-Normale muss waagerecht sein");
112        let eye = cam.view.inverse().w_axis.truncate();
113        let to_cam = Vec3::new(eye.x - c.x, 0.0, eye.z - c.z).normalize();
114        assert!(n.normalize().dot(to_cam) > 0.95);
115        // Breite wirkt horizontal, Höhe vertikal (yaw-only: Up = Welt-Y).
116        let w = m.transform_vector3(Vec3::X);
117        let h = m.transform_vector3(Vec3::Y);
118        assert!((h.length() - 6.0).abs() < 1e-5);
119        assert!((h.y.abs() / h.length() - 1.0).abs() < 1e-5);
120        assert!((w.length() - 3.0).abs() < 1e-5);
121        assert!(w.y.abs() < 1e-5);
122    }
123
124    #[test]
125    fn volle_kameraausrichtung_ohne_yaw_only() {
126        let cam = camera();
127        let m = billboard_matrix(&cam, Vec3::ZERO, 1.0, 1.0, false);
128        let c2w = cam.view.inverse();
129        // Ohne yaw_only sind die Spalten die Kamera-Achsen (skaliert).
130        let d = m
131            .transform_vector3(Vec3::Y)
132            .dot(c2w.y_axis.truncate())
133            .abs();
134        assert!((d - 1.0).abs() < 1e-6);
135    }
136
137    #[test]
138    fn uv_rechteck_rechnet_prozentual() {
139        let s = Sprite {
140            texture: 0,
141            rect: [64, 128, 32, 64],
142        };
143        let uv = uv_rect(&s, 2048, 640);
144        let close = |a: f32, b: f32| (a - b).abs() < 1e-6;
145        assert!(close(uv[0], 64.0 / 2048.0));
146        assert!(close(uv[1], 128.0 / 640.0));
147        assert!(close(uv[2], 32.0 / 2048.0));
148        assert!(close(uv[3], 64.0 / 640.0));
149    }
150}