Skip to main content

re_core/
primitives.rs

1use crate::mesh::Mesh;
2use glam::Vec3;
3
4/// Available generated shapes. 2D shapes lie on the XY plane facing +Z.
5#[derive(Copy, Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
6pub enum PrimitiveKind {
7    Box,
8    Sphere,
9    Cylinder,
10    Cone,
11    Capsule,
12    Torus,
13    Plane,
14    Rect,
15    Circle,
16}
17
18impl PrimitiveKind {
19    pub fn parse(s: &str) -> Option<Self> {
20        Some(match s.to_ascii_lowercase().as_str() {
21            "box" | "cube" => Self::Box,
22            "sphere" => Self::Sphere,
23            "cylinder" => Self::Cylinder,
24            "cone" => Self::Cone,
25            "capsule" => Self::Capsule,
26            "torus" => Self::Torus,
27            "plane" => Self::Plane,
28            "rect" | "rectangle" => Self::Rect,
29            "circle" | "disc" => Self::Circle,
30            _ => return None,
31        })
32    }
33
34    pub fn name(&self) -> &'static str {
35        match self {
36            Self::Box => "box",
37            Self::Sphere => "sphere",
38            Self::Cylinder => "cylinder",
39            Self::Cone => "cone",
40            Self::Capsule => "capsule",
41            Self::Torus => "torus",
42            Self::Plane => "plane",
43            Self::Rect => "rect",
44            Self::Circle => "circle",
45        }
46    }
47}
48
49/// Build a primitive mesh. `a`/`b` are size parameters (radius, width, height…),
50/// `segments` controls tessellation.
51pub fn generate(kind: PrimitiveKind, a: f32, b: f32, segments: u32) -> Mesh {
52    let seg = segments.max(3);
53    match kind {
54        PrimitiveKind::Box => cube(a, b.max(0.001), a), // a=w, b=h; depth=w
55        PrimitiveKind::Sphere => uv_sphere(a.max(0.001), seg, seg / 2),
56        PrimitiveKind::Cylinder => cylinder(a.max(0.001), b.max(0.001), seg),
57        PrimitiveKind::Cone => cone(a.max(0.001), b.max(0.001), seg),
58        PrimitiveKind::Capsule => capsule(a.max(0.001), b.max(0.001), seg),
59        PrimitiveKind::Torus => torus(a.max(0.001), (b * 0.25).max(0.001), seg, seg),
60        PrimitiveKind::Plane => cube(1.0_f32.max(a), 1e-4, 1.0_f32.max(b)),
61        PrimitiveKind::Rect => rect_xy(a.max(0.001), b.max(0.001)),
62        PrimitiveKind::Circle => circle_xy(a.max(0.001), seg),
63    }
64}
65
66/// Axis-aligned box centered at origin.
67pub fn cube(w: f32, h: f32, d: f32) -> Mesh {
68    let (hx, hy, hz) = (w / 2.0, h / 2.0, d / 2.0);
69    let mut mesh = Mesh::default();
70    // +X
71    quad(
72        &mut mesh,
73        [[hx, -hy, -hz], [hx, hy, -hz], [hx, hy, hz], [hx, -hy, hz]],
74        [1.0, 0.0, 0.0],
75    );
76    // -X
77    quad(
78        &mut mesh,
79        [
80            [-hx, -hy, hz],
81            [-hx, hy, hz],
82            [-hx, hy, -hz],
83            [-hx, -hy, -hz],
84        ],
85        [-1.0, 0.0, 0.0],
86    );
87    // +Y
88    quad(
89        &mut mesh,
90        [[-hx, hy, -hz], [-hx, hy, hz], [hx, hy, hz], [hx, hy, -hz]],
91        [0.0, 1.0, 0.0],
92    );
93    // -Y
94    quad(
95        &mut mesh,
96        [
97            [-hx, -hy, hz],
98            [-hx, -hy, -hz],
99            [hx, -hy, -hz],
100            [hx, -hy, hz],
101        ],
102        [0.0, -1.0, 0.0],
103    );
104    // +Z
105    quad(
106        &mut mesh,
107        [[-hx, -hy, hz], [hx, -hy, hz], [hx, hy, hz], [-hx, hy, hz]],
108        [0.0, 0.0, 1.0],
109    );
110    // -Z
111    quad(
112        &mut mesh,
113        [
114            [hx, -hy, -hz],
115            [-hx, -hy, -hz],
116            [-hx, hy, -hz],
117            [hx, hy, -hz],
118        ],
119        [0.0, 0.0, -1.0],
120    );
121    mesh
122}
123
124fn quad(mesh: &mut Mesh, corners: [[f32; 3]; 4], normal: [f32; 3]) {
125    let base = mesh.positions.len() as u32;
126    let uvs = [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]];
127    for i in 0..4 {
128        mesh.positions.push(corners[i]);
129        mesh.normals.get_or_insert_with(Vec::new).push(normal);
130        mesh.uvs.get_or_insert_with(Vec::new).push(uvs[i]);
131    }
132    mesh.indices
133        .get_or_insert_with(Vec::new)
134        .extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
135}
136
137/// UV sphere, poles on +Y/-Y.
138pub fn uv_sphere(radius: f32, segments: u32, rings: u32) -> Mesh {
139    let segments = segments.max(3) as usize;
140    let rings = rings.max(2) as usize;
141    let mut mesh = Mesh::default();
142    for r in 0..=rings {
143        let phi = std::f32::consts::PI * r as f32 / rings as f32; // 0..PI
144        for s in 0..=segments {
145            let theta = 2.0 * std::f32::consts::PI * s as f32 / segments as f32;
146            let n = Vec3::new(phi.sin() * theta.cos(), phi.cos(), phi.sin() * theta.sin());
147            mesh.push_v(
148                (n * radius).to_array(),
149                n.to_array(),
150                [s as f32 / segments as f32, r as f32 / rings as f32],
151            );
152        }
153    }
154    let stride = segments + 1;
155    for r in 0..rings {
156        for s in 0..segments {
157            let a = (r * stride + s) as u32;
158            let b = a + stride as u32;
159            mesh.indices
160                .as_mut()
161                .unwrap()
162                .extend_from_slice(&[a, b, a + 1, a + 1, b, b + 1]);
163        }
164    }
165    mesh
166}
167
168/// Cylinder along Y, centered.
169pub fn cylinder(radius: f32, height: f32, segments: u32) -> Mesh {
170    let seg = segments.max(3) as usize;
171    let hy = height / 2.0;
172    let mut mesh = Mesh::default();
173    // side
174    for s in 0..=seg {
175        let t = 2.0 * std::f32::consts::PI * s as f32 / seg as f32;
176        let (x, z) = (t.cos(), t.sin());
177        let bottom = mesh.positions.len() as u32;
178        mesh.push_v(
179            [x * radius, -hy, z * radius],
180            [x, 0.0, z],
181            [s as f32 / seg as f32, 0.0],
182        );
183        mesh.push_v(
184            [x * radius, hy, z * radius],
185            [x, 0.0, z],
186            [s as f32 / seg as f32, 1.0],
187        );
188        if s > 0 {
189            let i = mesh.indices.as_mut().unwrap();
190            i.extend_from_slice(&[
191                bottom - 2,
192                bottom - 1,
193                bottom,
194                bottom,
195                bottom - 1,
196                bottom + 1,
197            ]);
198        }
199    }
200    // caps
201    for (y, ny, flip) in [(hy, 1.0, false), (-hy, -1.0, true)] {
202        let center = mesh.positions.len() as u32;
203        mesh.push_v([0.0, y, 0.0], [0.0, ny, 0.0], [0.5, 0.5]);
204        for s in 0..=seg {
205            let t = 2.0 * std::f32::consts::PI * s as f32 / seg as f32;
206            let ring = mesh.positions.len() as u32;
207            mesh.push_v(
208                [t.cos() * radius, y, t.sin() * radius],
209                [0.0, ny, 0.0],
210                [t.cos() * 0.5 + 0.5, t.sin() * 0.5 + 0.5],
211            );
212            if s > 0 {
213                let i = mesh.indices.as_mut().unwrap();
214                if flip {
215                    i.extend_from_slice(&[center, ring, ring - 1]);
216                } else {
217                    i.extend_from_slice(&[center, ring - 1, ring]);
218                }
219            }
220        }
221    }
222    mesh
223}
224
225/// Cone along Y, base at -height/2.
226pub fn cone(radius: f32, height: f32, segments: u32) -> Mesh {
227    let seg = segments.max(3) as usize;
228    let hy = height / 2.0;
229    let mut mesh = Mesh::default();
230    for s in 0..=seg {
231        let t = 2.0 * std::f32::consts::PI * s as f32 / seg as f32;
232        let (x, z) = (t.cos(), t.sin());
233        let bottom = mesh.positions.len() as u32;
234        // side normal for a cone with apex at +Y
235        let n = Vec3::new(x * height, radius, z * height).normalize_or_zero();
236        let n = if n.length_squared() > 0.0 { n } else { Vec3::Y };
237        mesh.push_v(
238            [x * radius, -hy, z * radius],
239            n.to_array(),
240            [s as f32 / seg as f32, 0.0],
241        );
242        mesh.push_v([0.0, hy, 0.0], n.to_array(), [s as f32 / seg as f32, 1.0]);
243        if s > 0 {
244            let i = mesh.indices.as_mut().unwrap();
245            i.extend_from_slice(&[
246                bottom - 2,
247                bottom - 1,
248                bottom,
249                bottom,
250                bottom - 1,
251                bottom + 1,
252            ]);
253        }
254    }
255    // base cap
256    let center = mesh.positions.len() as u32;
257    mesh.push_v([0.0, -hy, 0.0], [0.0, -1.0, 0.0], [0.5, 0.5]);
258    for s in 0..=seg {
259        let t = 2.0 * std::f32::consts::PI * s as f32 / seg as f32;
260        let ring = mesh.positions.len() as u32;
261        mesh.push_v(
262            [t.cos() * radius, -hy, t.sin() * radius],
263            [0.0, -1.0, 0.0],
264            [0.0, 0.0],
265        );
266        if s > 0 {
267            mesh.indices
268                .as_mut()
269                .unwrap()
270                .extend_from_slice(&[center, ring, ring - 1]);
271        }
272    }
273    mesh
274}
275
276/// Capsule along Y: `height` = total height, radius `radius`.
277pub fn capsule(radius: f32, height: f32, segments: u32) -> Mesh {
278    let height = height.max(radius * 2.0);
279    let cyl_h = height - radius * 2.0;
280    let mut mesh = uv_sphere(radius, segments, segments / 2 + 1);
281    // shift top hemisphere up, bottom down
282    for p in &mut mesh.positions {
283        if p[1] > 0.0 {
284            p[1] += cyl_h / 2.0;
285        } else {
286            p[1] -= cyl_h / 2.0;
287        }
288    }
289    // insert a cylinder band between the hemispheres
290    let seg = segments.max(3) as usize;
291    let mut band = Mesh::default();
292    for s in 0..=seg {
293        let t = 2.0 * std::f32::consts::PI * s as f32 / seg as f32;
294        band.push_v(
295            [t.cos() * radius, cyl_h / 2.0, t.sin() * radius],
296            [t.cos(), 0.0, t.sin()],
297            [0.0, 0.0],
298        );
299        band.push_v(
300            [t.cos() * radius, -cyl_h / 2.0, t.sin() * radius],
301            [t.cos(), 0.0, t.sin()],
302            [0.0, 0.0],
303        );
304    }
305    // quad strip around the band: ring s = (2s top, 2s+1 bottom)
306    {
307        let idx = band.indices.as_mut().unwrap();
308        for s in 0..seg {
309            let (t0, b0) = (2 * s as u32, 2 * s as u32 + 1);
310            let (t1, b1) = (t0 + 2, b0 + 2);
311            idx.extend_from_slice(&[t0, b0, t1, t1, b0, b1]);
312        }
313    }
314    merge(&mut mesh, band);
315    mesh
316}
317
318/// Torus in the XZ plane.
319pub fn torus(radius: f32, tube: f32, segments: u32, sides: u32) -> Mesh {
320    let seg = segments.max(3) as usize;
321    let side = sides.max(3) as usize;
322    let mut mesh = Mesh::default();
323    for i in 0..=seg {
324        let u = 2.0 * std::f32::consts::PI * i as f32 / seg as f32;
325        for j in 0..=side {
326            let v = 2.0 * std::f32::consts::PI * j as f32 / side as f32;
327            let cx = radius * u.cos();
328            let cz = radius * u.sin();
329            let nx = u.cos() * v.cos();
330            let ny = v.sin();
331            let nz = u.sin() * v.cos();
332            mesh.push_v(
333                [cx + tube * nx, tube * ny, cz + tube * nz],
334                [nx, ny, nz],
335                [i as f32 / seg as f32, j as f32 / side as f32],
336            );
337        }
338    }
339    let stride = side + 1;
340    for i in 0..seg {
341        for j in 0..side {
342            let a = (i * stride + j) as u32;
343            let b = a + stride as u32;
344            mesh.indices
345                .as_mut()
346                .unwrap()
347                .extend_from_slice(&[a, b, a + 1, a + 1, b, b + 1]);
348        }
349    }
350    mesh
351}
352
353/// 2D rectangle on the XY plane, normal +Z.
354pub fn rect_xy(w: f32, h: f32) -> Mesh {
355    let (hx, hy) = (w / 2.0, h / 2.0);
356    let mut mesh = Mesh::default();
357    quad(
358        &mut mesh,
359        [
360            [-hx, -hy, 0.0],
361            [hx, -hy, 0.0],
362            [hx, hy, 0.0],
363            [-hx, hy, 0.0],
364        ],
365        [0.0, 0.0, 1.0],
366    );
367    mesh
368}
369
370/// 2D filled circle on the XY plane, normal +Z.
371pub fn circle_xy(radius: f32, segments: u32) -> Mesh {
372    let seg = segments.max(3) as usize;
373    let mut mesh = Mesh::default();
374    let center = mesh.positions.len() as u32;
375    mesh.push_v([0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.5, 0.5]);
376    for s in 0..=seg {
377        let t = 2.0 * std::f32::consts::PI * s as f32 / seg as f32;
378        let ring = mesh.positions.len() as u32;
379        mesh.push_v(
380            [t.cos() * radius, t.sin() * radius, 0.0],
381            [0.0, 0.0, 1.0],
382            [t.cos() * 0.5 + 0.5, t.sin() * 0.5 + 0.5],
383        );
384        if s > 0 {
385            mesh.indices
386                .as_mut()
387                .unwrap()
388                .extend_from_slice(&[center, ring - 1, ring]);
389        }
390    }
391    mesh
392}
393
394impl Mesh {
395    fn push_v(&mut self, p: [f32; 3], n: [f32; 3], uv: [f32; 2]) {
396        self.positions.push(p);
397        self.normals.get_or_insert_with(Vec::new).push(n);
398        self.uvs.get_or_insert_with(Vec::new).push(uv);
399        self.indices.get_or_insert_with(Vec::new);
400    }
401}
402
403/// Append `other` to `base` (reindexing). Used for capsule band.
404fn merge(base: &mut Mesh, other: Mesh) {
405    let off = base.positions.len() as u32;
406    base.positions.extend(other.positions);
407    if let Some(n) = other.normals {
408        base.normals.get_or_insert_with(Vec::new).extend(n);
409    }
410    if let Some(u) = other.uvs {
411        base.uvs.get_or_insert_with(Vec::new).extend(u);
412    }
413    if let Some(i) = other.indices {
414        let bi = base.indices.get_or_insert_with(Vec::new);
415        bi.reserve(i.len());
416        bi.extend(i.into_iter().map(|v| v + off));
417    }
418}
419
420#[cfg(test)]
421mod tests {
422    use super::*;
423    use std::collections::BTreeSet;
424
425    #[test]
426    fn capsule_band_is_triangulated() {
427        let m = capsule(0.5, 3.0, 8);
428        let idx = m.indices.clone().unwrap();
429        assert_eq!(idx.len() % 3, 0);
430        assert!(
431            idx.iter().all(|&i| (i as usize) < m.positions.len()),
432            "Index außerhalb"
433        );
434        // Die Band-Vertizes (letztes 2*(seg+1)) müssen von Dreiecken
435        // referenziert werden — sonst rendert die Kapsel mit Loch.
436        let first_band = m.positions.len() - 2 * (8 + 1);
437        let referenced: BTreeSet<u32> = idx.iter().copied().collect();
438        for v in first_band..m.positions.len() {
439            assert!(
440                referenced.contains(&(v as u32)),
441                "Band-Vertiz {v} ohne Dreieck"
442            );
443        }
444        let (min, max) = m.aabb();
445        assert!(
446            (max[1] - min[1] - 3.0).abs() < 1e-3,
447            "Kapsel überspannt nicht die Höhe"
448        );
449    }
450}