Skip to main content

Mesh

Struct Mesh 

Source
pub struct Mesh {
    pub positions: Vec<[f32; 3]>,
    pub normals: Vec<[f32; 3]>,
    pub uvs: Vec<[f32; 2]>,
    pub colors: Vec<[f32; 3]>,
    pub indices: Vec<[u32; 3]>,
}
Expand description

A triangle mesh, indexed.

normals, uvs and colors are either empty or as long as positions. The geometry here needs none of them; they are carried so a reader and a writer round-trip, and colors is what the vertex-colour stand-in for texture is trained on and written from.

Fields§

§positions: Vec<[f32; 3]>§normals: Vec<[f32; 3]>§uvs: Vec<[f32; 2]>§colors: Vec<[f32; 3]>

Linear RGB per vertex, 0 to 1.

§indices: Vec<[u32; 3]>

Implementations§

Source§

impl Mesh

Source

pub fn read_glb<P: AsRef<Path>>(path: P) -> Result<Self, NetworkError>

Reads the whole scene of a .glb file as one mesh.

Examples found in repository?
examples/mesh_samples.rs (line 247)
245fn read(path: &std::path::Path) -> Result<Mesh, rusting_brain::NetworkError> {
246    match path.extension().and_then(|e| e.to_str()) {
247        Some("glb") => Mesh::read_glb(path),
248        _ => Mesh::read_obj(path),
249    }
250}
Source§

impl Mesh

Source

pub fn write_glb<P: AsRef<Path>>(&self, path: P) -> Result<(), NetworkError>

Writes the mesh as a .glb.

One node, one mesh, one triangle primitive, one buffer view per attribute, and one material — an untextured PBR white, because nothing in this pipeline produces a texture or the UVs that would place one. Normals, UVs and vertex colours are written when the mesh carries them; a viewer multiplies COLOR_0 by the material’s base colour, which is why that base colour is white.

Source

pub fn to_glb(&self) -> Result<Glb, NetworkError>

The same, kept in memory.

Source§

impl Mesh

Source

pub fn triangle(&self, face: usize) -> [[f32; 3]; 3]

The three corners of a face.

Source

pub fn bounds(&self) -> ([f32; 3], [f32; 3])

The smallest axis-aligned box holding every vertex.

Source

pub fn normalize(&mut self) -> Transform

Centres the mesh on its bounding box and scales it to fill [-1, 1], returning the transform that was applied.

The longest axis reaches the faces of the cube and the others fall short of them, because scaling the axes separately would change the shape.

Examples found in repository?
examples/mesh_samples.rs (line 130)
57fn main() -> Result<(), Box<dyn std::error::Error>> {
58    let args = parse()?;
59    std::fs::create_dir_all(&args.out)?;
60
61    let mut paths: Vec<PathBuf> = std::fs::read_dir(&args.meshes)?
62        .filter_map(|entry| entry.ok().map(|entry| entry.path()))
63        .filter(|path| {
64            path.extension().is_some_and(|extension| {
65                matches!(extension.to_ascii_lowercase().to_str(), Some("obj" | "glb"))
66            })
67        })
68        .collect();
69    paths.sort();
70    if paths.is_empty() {
71        return Err(format!("no .obj or .glb files in {}", args.meshes.display()).into());
72    }
73    println!(
74        "{} meshes, {} per shard, {} surface and {} query points each",
75        paths.len(),
76        args.shard,
77        args.surface,
78        args.queries
79    );
80
81    let sampling = QuerySampling {
82        count: args.queries,
83        near_surface: args.near_surface,
84        jitter: args.jitter,
85        extent: args.extent,
86    };
87
88    let mut index: BTreeMap<String, String> = BTreeMap::new();
89    let mut skipped = 0;
90    let mut colored = 0;
91    let started = Instant::now();
92    let shards = paths.len().div_ceil(args.shard);
93    for (number, chunk) in paths.chunks(args.shard).enumerate() {
94        let shard = format!("samples-{number:05}.safetensors");
95
96        // Already done by an earlier run: take its names and move on.
97        let done = completed(&args.out.join(&shard));
98        if !done.is_empty() {
99            for stem in &done {
100                index.insert(stem.clone(), shard.clone());
101            }
102            write_index(&args.out, &index)?;
103            println!("{shard}: {} meshes, already written", done.len());
104            continue;
105        }
106        // One shard at a time in memory. A 200K-query mesh is 3 MB here and
107        // half that on disk, so the shard size is the knob that bounds this.
108        let mut sampled: Vec<(String, [usize; 2], Vec<f32>)> = Vec::new();
109        let mut meshes = 0;
110        for path in chunk {
111            let stem = path
112                .file_stem()
113                .and_then(|stem| stem.to_str())
114                .ok_or_else(|| format!("{} has no usable name", path.display()))?
115                .to_string();
116
117            // One bad asset in a scraped dataset should not cost the whole run.
118            let mesh = match read(path) {
119                Ok(mesh) => mesh,
120                Err(error) => {
121                    eprintln!("skipping {}: {error}", path.display());
122                    skipped += 1;
123                    continue;
124                }
125            };
126            // The seed is per mesh, so a rerun of one shard reproduces exactly
127            // the samples the first run wrote.
128            let mut rng = StdRng::seed_from_u64(args.seed ^ hash(&stem));
129            let mut mesh = mesh;
130            let placement = mesh.normalize();
131            let bvh = Bvh::build(&mesh);
132
133            let (points, normals, colors) = bvh.sample_surface_colored(args.surface, &mut rng);
134            let mut surface = Vec::with_capacity(args.surface * 6);
135            for (point, normal) in points.iter().zip(&normals) {
136                surface.extend(point);
137                surface.extend(normal);
138            }
139
140            let queries = bvh.sample_queries(&sampling, &mut rng);
141            let distances = bvh.signed_distance(&queries);
142            let mut samples = Vec::with_capacity(queries.len() * 4);
143            for (query, distance) in queries.iter().zip(&distances) {
144                samples.extend(query);
145                samples.push(*distance);
146            }
147
148            index.insert(stem.clone(), shard.clone());
149            meshes += 1;
150            sampled.push((format!("{stem}.surface"), [points.len(), 6], surface));
151            // Only the meshes that carry colour get a colour tensor; the loader
152            // treats a missing one as "this mesh trains shape only".
153            if !colors.is_empty() {
154                colored += 1;
155                sampled.push((format!("{stem}.colors"), [colors.len(), 3], colors.concat()));
156            }
157            sampled.push((format!("{stem}.queries"), [queries.len(), 4], samples));
158            sampled.push((
159                format!("{stem}.transform"),
160                [1, 4],
161                vec![
162                    placement.center[0],
163                    placement.center[1],
164                    placement.center[2],
165                    placement.scale,
166                ],
167            ));
168        }
169        if sampled.is_empty() {
170            continue;
171        }
172
173        let borrowed: Vec<(&str, &[usize], &[f32])> = sampled
174            .iter()
175            .map(|(name, shape, data)| (name.as_str(), &shape[..], &data[..]))
176            .collect();
177        safetensors::write_as(
178            args.out.join(&shard),
179            &borrowed,
180            &BTreeMap::from([
181                ("source".to_string(), "mesh_samples".to_string()),
182                ("surface".to_string(), args.surface.to_string()),
183                ("queries".to_string(), args.queries.to_string()),
184            ]),
185            Dtype::Bf16,
186        )?;
187        write_index(&args.out, &index)?;
188        println!(
189            "{shard}: {meshes} meshes, {}",
190            progress(started, number + 1, shards)
191        );
192    }
193
194    write_index(&args.out, &index)?;
195    println!(
196        "wrote {} entries to index.json, {colored} with colour, skipped {skipped}",
197        index.len()
198    );
199    Ok(())
200}
Source

pub fn recompute_normals(&mut self)

Replaces the per-vertex normals with area-weighted face normals.

Weighting by area rather than averaging the unit face normals is what keeps a vertex where one huge triangle meets several slivers from being dominated by the slivers.

Source

pub fn area(&self) -> f32

Total surface area.

Source

pub fn read_obj<P: AsRef<Path>>(path: P) -> Result<Self, NetworkError>

Reads a Wavefront OBJ file.

Positions, normals, texture coordinates and faces. Faces with more than three corners are fanned into triangles, which is right for the convex quads an exporter emits. Materials, groups and smoothing are skipped: the geometry is what a distance field is built from.

Examples found in repository?
examples/mesh_samples.rs (line 248)
245fn read(path: &std::path::Path) -> Result<Mesh, rusting_brain::NetworkError> {
246    match path.extension().and_then(|e| e.to_str()) {
247        Some("glb") => Mesh::read_glb(path),
248        _ => Mesh::read_obj(path),
249    }
250}
Source

pub fn write_obj<P: AsRef<Path>>(&self, path: P) -> Result<(), NetworkError>

Writes a Wavefront OBJ file: positions, normals if there are any, and faces.

Source§

impl Mesh

Source

pub fn simplify(&mut self, target_faces: usize) -> usize

Collapses edges until the mesh is down to target_faces, cheapest first.

This is Garland and Heckbert’s quadric error metric: every vertex carries the sum of the squared-distance quadrics of the faces around it, an edge costs whatever that sum evaluates to at the point it would collapse onto, and the point itself is the one that minimizes it. A boundary edge gets an extra plane at right angles to its face, weighted heavily, so an open edge is held in place rather than eaten away.

Returns the face count it finished on, which can be above the target if there was nothing left that could be collapsed safely.

Normals are recomputed if the mesh had them. UVs are dropped: a collapse merges two vertices that generally sit in different places in a texture atlas, and inventing a coordinate for the merged one would be worse than admitting there isn’t one.

Source

pub fn simplify_within(&mut self, max_error: f32) -> (usize, f32)

Collapses edges for as long as the quadric error stays under max_error, and returns the face count it finished on together with the largest error it accepted.

This is Mesh::simplify asking the other question. A face target says how big the mesh may be and lets the error land where it lands, which is the wrong way round for a pipeline that extracted the mesh from a field and wants it as small as it can be without visibly moving the surface. Given a bound, this collapses the cheap edges — a flat region, a redundant row of vertices along a plane — and stops at the first edge that would cost more than the bound.

The units are the metric’s, not the world’s: an error is a sum of squared distances to the planes around the edge, each weighted by the area of the face it came from. So it scales with the mesh, and the way to pick a bound is to simplify one representative mesh to a face count that looks right and use the largest error that run reports. The second return value is there for exactly that.

Everything else matches Mesh::simplify: the same metric, the same refusal to fold a face over, normals recomputed, UVs dropped.

Trait Implementations§

Source§

impl Clone for Mesh

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Mesh

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Mesh

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl Forget for Mesh

§

impl Freeze for Mesh

§

impl Move for Mesh

§

impl RefUnwindSafe for Mesh

§

impl Send for Mesh

§

impl Sync for Mesh

§

impl Unpin for Mesh

§

impl UnsafeUnpin for Mesh

§

impl UnwindSafe for Mesh

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V