Skip to main content

re_core/
mesh.rs

1use crate::id::SkeletonId;
2use serde::{Deserialize, Serialize};
3
4/// Per-vertex skinning influences referencing joints of a skeleton asset.
5/// Joint indices point into `Skeleton::joints` of `skeleton`.
6#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
7pub struct Skin {
8    pub skeleton: SkeletonId,
9    /// Up to 4 joint indices per vertex (u16 to match glTF JOINTS_0).
10    pub joints: Vec<[u16; 4]>,
11    /// Corresponding weights per vertex, normalized to sum to 1.
12    pub weights: Vec<[f32; 4]>,
13}
14
15/// Globally unique stamp for GPU-mirror invalidation (see [`Mesh::stamp`]).
16pub fn new_mesh_stamp() -> u64 {
17    use std::sync::atomic::{AtomicU64, Ordering};
18    static NEXT: AtomicU64 = AtomicU64::new(1);
19    NEXT.fetch_add(1, Ordering::Relaxed)
20}
21
22/// A triangle-list mesh with optional vertex attributes and skin weights.
23/// 2D elements are meshes lying on the XY plane (normals +Z).
24#[derive(Clone, Debug, Serialize, Deserialize)]
25pub struct Mesh {
26    pub name: String,
27    pub positions: Vec<[f32; 3]>,
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub normals: Option<Vec<[f32; 3]>>,
30    #[serde(default, skip_serializing_if = "Option::is_none")]
31    pub uvs: Option<Vec<[f32; 2]>>,
32    /// Triangle indices; `None` means a flat, non-indexed triangle list.
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub indices: Option<Vec<u32>>,
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub skin: Option<Skin>,
37    /// CPU→GPU invalidation stamp: unique at creation, refreshed by
38    /// [`Mesh::touch`] on every in-place edit. GPU mirrors key their buffers
39    /// on it so edits and address reuse (ABA) force a re-upload. Never
40    /// serialized, never compared for equality.
41    #[serde(skip, default = "new_mesh_stamp")]
42    pub stamp: u64,
43}
44
45impl Default for Mesh {
46    fn default() -> Self {
47        Self {
48            name: String::new(),
49            positions: Vec::new(),
50            normals: None,
51            uvs: None,
52            indices: None,
53            skin: None,
54            stamp: new_mesh_stamp(),
55        }
56    }
57}
58
59impl PartialEq for Mesh {
60    fn eq(&self, other: &Self) -> bool {
61        self.name == other.name
62            && self.positions == other.positions
63            && self.normals == other.normals
64            && self.uvs == other.uvs
65            && self.indices == other.indices
66            && self.skin == other.skin
67    }
68}
69
70impl Mesh {
71    /// Mark the content as edited in place: every GPU mirror must
72    /// re-upload this mesh before drawing it again.
73    pub fn touch(&mut self) {
74        self.stamp = new_mesh_stamp();
75    }
76
77    pub fn vertex_count(&self) -> usize {
78        self.positions.len()
79    }
80
81    pub fn triangle_count(&self) -> usize {
82        match &self.indices {
83            Some(idx) => idx.len() / 3,
84            None => self.positions.len() / 3,
85        }
86    }
87
88    /// Axis-aligned bounding box: (min, max).
89    pub fn aabb(&self) -> ([f32; 3], [f32; 3]) {
90        let mut min = [f32::MAX; 3];
91        let mut max = [f32::MIN; 3];
92        for p in &self.positions {
93            for i in 0..3 {
94                min[i] = min[i].min(p[i]);
95                max[i] = max[i].max(p[i]);
96            }
97        }
98        if self.positions.is_empty() {
99            return ([0.0; 3], [0.0; 3]);
100        }
101        (min, max)
102    }
103
104    /// Recompute smooth vertex normals from triangle faces.
105    pub fn compute_normals(&mut self) {
106        let n = self.positions.len();
107        let mut acc = vec![glam::Vec3::ZERO; n];
108        let tri_count = self.triangle_count();
109        for t in 0..tri_count {
110            let [a, b, c] = self.triangle_indices(t);
111            let pa = glam::Vec3::from_array(self.positions[a as usize]);
112            let pb = glam::Vec3::from_array(self.positions[b as usize]);
113            let pc = glam::Vec3::from_array(self.positions[c as usize]);
114            let face = (pb - pa).cross(pc - pa);
115            for idx in [a, b, c] {
116                acc[idx as usize] += face;
117            }
118        }
119        self.normals = Some(
120            acc.iter()
121                .map(|v| {
122                    if v.length_squared() > 0.0 {
123                        v.normalize().to_array()
124                    } else {
125                        [0.0, 1.0, 0.0]
126                    }
127                })
128                .collect(),
129        );
130    }
131
132    pub fn iter_triangles(&self) -> impl Iterator<Item = [u32; 3]> + '_ {
133        (0..self.triangle_count()).map(move |t| self.triangle_indices(t))
134    }
135
136    fn triangle_indices(&self, t: usize) -> [u32; 3] {
137        match &self.indices {
138            Some(idx) => [idx[t * 3], idx[t * 3 + 1], idx[t * 3 + 2]],
139            None => [(t * 3) as u32, (t * 3 + 1) as u32, (t * 3 + 2) as u32],
140        }
141    }
142}