diff --git a/crates/mesh/README.md b/crates/mesh/README.md index 8c0cdec00..df32e7a59 100644 --- a/crates/mesh/README.md +++ b/crates/mesh/README.md @@ -24,8 +24,9 @@ USD, Alembic and COLLADA are not here yet. - `Part`: the faces of a mesh that share a group name, a material and a smoothing group. A face is a polygon of three or more `Corner`s; each corner indexes a position and optionally a normal and a UV. Formats with separate indices (OBJ) are kept exactly, and polygons stay whole. - `Part::triangles()` fans them; `Mesh::unified()` gives one vertex per distinct corner as a - triangle list, which is what a renderer wants. + `Part::triangles_in(&mesh.positions)` triangulates them (a fan for a convex face, ear clipping + in the face's plane for a concave one; `Part::triangles()` only fans); `Mesh::unified()` gives + one vertex per distinct corner as a triangle list, which is what a renderer wants. - `Material`: metallic-roughness factors, alpha mode, double-sided, unlit, and five texture slots. A `TextureRef` names an `Image`, a UV set and wrap modes. An `Image` is a URI the caller resolves or the encoded bytes the file embedded; nothing here decodes images. diff --git a/crates/mesh/src/lib.rs b/crates/mesh/src/lib.rs index 6017c8dd2..4808834fa 100644 --- a/crates/mesh/src/lib.rs +++ b/crates/mesh/src/lib.rs @@ -47,6 +47,7 @@ pub mod ply; pub mod stl; #[cfg(feature = "threemf")] pub mod threemf; +mod triangulate; use std::collections::HashMap; use std::fmt; @@ -193,7 +194,8 @@ impl Part { }) } - /// The faces as triangles: a polygon becomes a fan from its first corner. + /// The faces as triangles: a polygon becomes a fan from its first corner, which is right + /// only for a convex face. [`Part::triangles_in`] triangulates concave faces too. pub fn triangles(&self) -> impl Iterator + '_ { self.faces().flat_map(|f| { let first = f.first().copied(); @@ -204,7 +206,19 @@ impl Part { }) } - /// Triangles the faces fan into. + /// The faces as triangles, with `positions` (the mesh's [`Mesh::positions`]) to see their + /// shape. A convex face becomes a fan from its first corner, as in [`Part::triangles`]; a + /// concave one is triangulated by ear clipping in its own plane, so no triangle covers a + /// notch. Each triangle keeps the face's winding. A face with a corner that has no position, + /// or with no area, keeps the fan. What is left of a face when no ear can be found (it + /// crosses itself) or the part's work budget (256 steps per corner) is spent is + /// fanned. Every face gives `corners − 2` triangles, as [`Part::triangle_count`] counts. + pub fn triangles_in<'a>(&'a self, positions: &'a [[f64; 3]]) -> impl Iterator + 'a { + let mut budget = triangulate::WORK_PER_CORNER.saturating_mul(self.corners.len()); + self.faces().flat_map(move |f| triangulate::face(f, positions, &mut budget)) + } + + /// Triangles the faces give: `corners − 2` each. pub fn triangle_count(&self) -> usize { if self.face_sizes.is_empty() { self.corners.len() / 3 } else { self.face_sizes.iter().map(|n| (*n as usize).saturating_sub(2)).sum() } } @@ -291,8 +305,8 @@ impl Mesh { Ok(()) } - /// The mesh as triangles with one vertex per distinct corner. Corners whose indices are out - /// of range are dropped with their triangle. + /// The mesh as triangles ([`Part::triangles_in`]) with one vertex per distinct corner. + /// Corners whose indices are out of range are dropped with their triangle. pub fn unified(&self) -> Unified { let mut out = Unified::default(); let all = |f: &dyn Fn(&Corner) -> bool| self.parts.iter().all(|p| p.corners.iter().all(f)); @@ -302,7 +316,7 @@ impl Mesh { let mut ids: HashMap = HashMap::new(); for part in &self.parts { let mut tris = Vec::with_capacity(part.triangle_count()); - 'tri: for t in part.triangles() { + 'tri: for t in part.triangles_in(&self.positions) { let mut tri = [0u32; 3]; for (slot, c) in tri.iter_mut().zip(t) { let key = Corner { diff --git a/crates/mesh/src/stl.rs b/crates/mesh/src/stl.rs index e60911a7a..444db5f67 100644 --- a/crates/mesh/src/stl.rs +++ b/crates/mesh/src/stl.rs @@ -238,7 +238,7 @@ fn ascii(bytes: &[u8], limits: &Limits) -> Result { fn triangles(scene: &Scene, limits: &Limits, mut each: impl FnMut([f64; 3], [[f64; 3]; 3])) -> Result<()> { for (index, world) in scene.instances(limits)? { let Some(mesh) = scene.meshes.get(index) else { continue }; - for t in mesh.parts.iter().flat_map(Part::triangles) { + for t in mesh.parts.iter().flat_map(|p| p.triangles_in(&mesh.positions)) { let p = t.map(|c| mesh.positions.get(c.position as usize).copied()); let [Some(a), Some(b), Some(c)] = p else { return Err(malformed(KIND, "a corner index is out of range")) }; // A mirrored placement turns the winding; turn it back so the facet faces out. diff --git a/crates/mesh/src/tests.rs b/crates/mesh/src/tests.rs index 160b5b3dc..423732de8 100644 --- a/crates/mesh/src/tests.rs +++ b/crates/mesh/src/tests.rs @@ -14,6 +14,7 @@ mod ply; mod stl; #[cfg(feature = "threemf")] mod threemf; +mod triangulate; /// Every truncation of `good` and two mutations of every byte go through `read`: it may refuse /// them, it must not panic, and what it accepts must be a valid scene. diff --git a/crates/mesh/src/tests/triangulate.rs b/crates/mesh/src/tests/triangulate.rs new file mode 100644 index 000000000..2bb0c3f6c --- /dev/null +++ b/crates/mesh/src/tests/triangulate.rs @@ -0,0 +1,147 @@ +//! Triangulating concave faces ([`Part::triangles_in`]). + +use super::*; + +/// A one-face part over corners `0..n`. +fn polygon(n: usize) -> Part { + Part { face_sizes: vec![n as u32], corners: (0..n as u32).map(Corner::at).collect(), ..Part::default() } +} + +/// Twice the signed area of a 2D triangle or of a closed 2D polygon. +fn area2(p: &[[f64; 2]]) -> f64 { + (0..p.len()).map(|i| p[i][0] * p[(i + 1) % p.len()][1] - p[(i + 1) % p.len()][0] * p[i][1]).sum() +} + +/// Whether `q` is strictly inside the 2D polygon `p`, by the even-odd rule. +fn inside(p: &[[f64; 2]], q: [f64; 2]) -> bool { + let mut odd = false; + for i in 0..p.len() { + let (a, b) = (p[i], p[(i + 1) % p.len()]); + if (a[1] > q[1]) != (b[1] > q[1]) && q[0] < a[0] + (q[1] - a[1]) / (b[1] - a[1]) * (b[0] - a[0]) { + odd = !odd; + } + } + odd +} + +/// Places the 2D outline on a tilted plane in 3D, so the triangulation has to find the plane. +fn lift(outline: &[[f64; 2]]) -> Vec<[f64; 3]> { + // An orthonormal basis of the plane through (1, 2, 3), its normal leaning on every axis. + let (u, v) = ([2.0 / 3.0, 2.0 / 3.0, -1.0 / 3.0], [-1.0 / 3.0, 2.0 / 3.0, 2.0 / 3.0]); + outline.iter().map(|p| [0, 1, 2].map(|k| [1.0, 2.0, 3.0][k] + p[0] * u[k] + p[1] * v[k])).collect() +} + +/// Triangulates `outline` as one face lifted into 3D, and checks the triangles tile it: one +/// fewer than two per corner, each wound as the outline is and lying inside it (three points +/// inside every triangle are inside the outline), and their areas adding up to the outline's. +fn assert_tiles(outline: &[[f64; 2]]) -> Vec<[u32; 3]> { + let positions = lift(outline); + let tris: Vec<[u32; 3]> = polygon(outline.len()).triangles_in(&positions).map(|t| t.map(|c| c.position)).collect(); + assert_eq!(tris.len(), outline.len() - 2, "{tris:?}"); + let whole = area2(outline); + let mut sum = 0.0; + for t in &tris { + let p = t.map(|i| outline[i as usize]); + let a = area2(&p); + assert!(a * whole.signum() > 0.0, "{t:?} is wound against the outline or has no area"); + sum += a.abs(); + for w in [[1.0, 1.0, 1.0], [4.0, 1.0, 1.0], [1.0, 4.0, 1.0], [1.0, 1.0, 4.0]] { + let n: f64 = w.iter().sum(); + let q = [0, 1].map(|k| (0..3).map(|j| p[j][k] * w[j]).sum::() / n); + assert!(inside(outline, q), "{t:?} leaves the outline at {q:?}"); + } + } + assert!((sum - whole.abs()).abs() < 1e-9 * whole.abs(), "areas {sum} and {whole}"); + tris +} + +#[test] +fn concave_faces_are_not_fanned_across_their_notch() { + // The issue's face: a fan from (0, 0) covers the notch between (2, 2), (1, 0.5) and (0, 2). + let notch = [[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [1.0, 0.5], [0.0, 2.0]]; + let fan: Vec<[u32; 3]> = polygon(5).triangles().map(|t| t.map(|c| c.position)).collect(); + assert_eq!(fan, [[0, 1, 2], [0, 2, 3], [0, 3, 4]]); + let tris = assert_tiles(¬ch); + assert_ne!(tris, fan); + // The same face wound the other way. + let mut cw = notch; + cw.reverse(); + assert_tiles(&cw); + // An L, a comb with nine teeth, a ten-pointed star and an arrow with straight corners. + assert_tiles(&[[0.0, 0.0], [3.0, 0.0], [3.0, 1.0], [1.0, 1.0], [1.0, 3.0], [0.0, 3.0]]); + let mut comb = vec![[0.0, 0.0], [18.0, 0.0]]; + for k in (0..9).rev() { + let x = 2.0 * k as f64; + comb.extend([[x + 2.0, 5.0], [x + 1.0, 5.0], [x + 1.0, 1.0]]); + } + comb.pop(); + assert_tiles(&comb); + let star: Vec<[f64; 2]> = (0..20) + .map(|k| { + let (r, a) = (if k % 2 == 0 { 3.0 } else { 1.0 }, k as f64 * std::f64::consts::PI / 10.0); + [r * a.cos(), r * a.sin()] + }) + .collect(); + assert_tiles(&star); + assert_tiles(&[[0.0, 1.0], [2.0, 1.0], [4.0, 1.0], [4.0, 0.0], [6.0, 2.0], [4.0, 4.0], [4.0, 3.0], [2.0, 3.0], [0.0, 3.0]]); +} + +#[test] +fn convex_faces_keep_their_fan() { + let hexagon: Vec<[f64; 2]> = (0..6).map(|k| [(k as f64).cos(), (k as f64).sin()]).collect(); + let positions = lift(&hexagon); + let part = polygon(6); + assert_eq!(part.triangles_in(&positions).collect::>(), part.triangles().collect::>()); + // A square with a straight corner on one side is still convex. + let square = lift(&[[0.0, 0.0], [1.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0]]); + assert_eq!(polygon(5).triangles_in(&square).collect::>(), polygon(5).triangles().collect::>()); +} + +#[test] +fn faces_that_cannot_be_clipped_keep_their_triangle_count() { + // No positions, a face with no area, and a bow tie that crosses itself. + let bow = lift(&[[0.0, 0.0], [2.0, 2.0], [2.0, 0.0], [0.0, 2.0]]); + let flat = lift(&[[0.0, 0.0], [1.0, 0.0], [2.0, 0.0], [3.0, 0.0]]); + for positions in [&[][..], &flat, &bow] { + assert_eq!(polygon(4).triangles_in(positions).count(), 2); + } + // A comb of 4000 teeth: the work stays bounded and every triangle is still given. + let mut comb = vec![[0.0, 0.0], [8000.0, 0.0]]; + for k in (0..4000).rev() { + let x = 2.0 * k as f64; + comb.extend([[x + 2.0, 5.0], [x + 1.0, 5.0], [x + 1.0, 1.0]]); + } + let positions = lift(&comb); + let part = polygon(comb.len()); + assert_eq!(part.triangles_in(&positions).count(), part.triangle_count()); +} + +#[test] +fn unified_and_stl_use_the_clipped_triangles() { + let notch = [[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [1.0, 0.5], [0.0, 2.0]]; + let mesh = Mesh { name: "Notch".into(), positions: lift(¬ch), parts: vec![polygon(5)], ..Mesh::default() }; + let expected: Vec<[u32; 3]> = mesh.parts[0].triangles_in(&mesh.positions).map(|t| t.map(|c| c.position)).collect(); + let u = mesh.unified(); + let got: Vec<[u32; 3]> = u.parts[0].iter().map(|t| t.map(|i| u.corners[i as usize].position)).collect(); + assert_eq!(got, expected); + #[cfg(feature = "stl")] + { + let scene = Scene::from_meshes(vec![mesh.clone()], vec![]); + let text = crate::stl::write_ascii(&scene, "n", &Limits::default()).unwrap(); + let back = crate::stl::read(text.as_bytes(), &Limits::default()).unwrap(); + // The facets' area is the face's, 2.5, not the fan's 3.5. + let m = &back.meshes[0]; + let area: f64 = m + .parts + .iter() + .flat_map(Part::triangles) + .map(|t| { + let p = t.map(|c| m.positions[c.position as usize]); + let (a, b) = ([0, 1, 2].map(|k| p[1][k] - p[0][k]), [0, 1, 2].map(|k| p[2][k] - p[0][k])); + let n = [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; + (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt() / 2.0 + }) + .sum(); + assert!((area - 2.5).abs() < 1e-6, "{area}"); + } +} diff --git a/crates/mesh/src/triangulate.rs b/crates/mesh/src/triangulate.rs new file mode 100644 index 000000000..84e3dd34a --- /dev/null +++ b/crates/mesh/src/triangulate.rs @@ -0,0 +1,226 @@ +//! Triangulating one polygon face: a fan for a convex face, ear clipping for a concave one. +//! +//! The face is projected onto the plane of its two minor axes (dropping the largest component +//! of its Newell normal) and clipped there. Work is charged to a budget the caller shares +//! between the faces of a part, so a crafted face cannot make it quadratic in the file's size; +//! when the budget runs out, or no ear can be found (a self-intersecting face), what is left of +//! the face is fanned. A face always gives `corners − 2` triangles, wound as the face is. + +use crate::Corner; + +/// Steps (ear checks, containment tests, looks for a straight corner) allowed per corner of a +/// part, shared by its faces. +pub(crate) const WORK_PER_CORNER: usize = 256; + +/// Relative tolerance under which a turn counts as straight. +const STRAIGHT: f64 = 1e-12; + +/// The triangles of one face. +pub(crate) enum FaceTriangles<'a> { + /// A fan from the first corner; `next` is the corner the next triangle starts its edge at. + Fan { face: &'a [Corner], next: usize }, + /// Triangles clipped from a concave face. + Ears(std::vec::IntoIter<[Corner; 3]>), +} + +impl Iterator for FaceTriangles<'_> { + type Item = [Corner; 3]; + + fn next(&mut self) -> Option<[Corner; 3]> { + match self { + FaceTriangles::Fan { face, next } => { + let t = [*face.first()?, *face.get(*next)?, *face.get(*next + 1)?]; + *next += 1; + Some(t) + } + FaceTriangles::Ears(it) => it.next(), + } + } +} + +/// Triangulates `face`, whose corners index `positions`, charging its work to `budget`. +pub(crate) fn face<'a>(face: &'a [Corner], positions: &[[f64; 3]], budget: &mut usize) -> FaceTriangles<'a> { + let fan = FaceTriangles::Fan { face, next: 1 }; + if face.len() <= 3 { + return fan; + } + let Some(pts) = project(face, positions) else { return fan }; + let area: f64 = (0..pts.len()).map(|i| cross(pts[i], pts[(i + 1) % pts.len()])).sum(); + if !area.is_finite() || area == 0.0 { + return fan; + } + let ring = Ring::new(pts, area.signum()); + if ring.is_convex() { + return fan; + } + FaceTriangles::Ears(ring.clip(face, budget).into_iter()) +} + +/// The face's corners in 2D, on the plane of the two axes its Newell normal leans on least; +/// `None` when a corner has no position or the face has no finite normal. +fn project(face: &[Corner], positions: &[[f64; 3]]) -> Option> { + let p: Vec<[f64; 3]> = face.iter().map(|c| positions.get(c.position as usize).copied()).collect::>()?; + let mut n = [0.0f64; 3]; + for (i, a) in p.iter().enumerate() { + let b = p[(i + 1) % p.len()]; + n[0] += (a[1] - b[1]) * (a[2] + b[2]); + n[1] += (a[2] - b[2]) * (a[0] + b[0]); + n[2] += (a[0] - b[0]) * (a[1] + b[1]); + } + let n = n.map(f64::abs); + if !n.iter().all(|x| x.is_finite()) { + return None; + } + // Drop the dominant axis, keeping the other two in cyclic order so the winding seen from the + // normal's side is kept; the sign of the projected area decides orientation anyway. + let (u, v) = if n[0] >= n[1] && n[0] >= n[2] { + (1, 2) + } else if n[1] >= n[2] { + (2, 0) + } else { + (0, 1) + }; + Some(p.iter().map(|q| [q[u], q[v]]).collect()) +} + +/// The z component of `a × b`. +fn cross(a: [f64; 2], b: [f64; 2]) -> f64 { + a[0] * b[1] - a[1] * b[0] +} + +/// Twice the signed area of triangle `a b c`. +fn orient(a: [f64; 2], b: [f64; 2], c: [f64; 2]) -> f64 { + (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) +} + +/// A face's projected corners as a doubly linked ring that ears are clipped from. +struct Ring { + pts: Vec<[f64; 2]>, + /// The sign of the face's projected area: turns of this sign are convex. + sign: f64, + prev: Vec, + next: Vec, +} + +impl Ring { + fn new(pts: Vec<[f64; 2]>, sign: f64) -> Ring { + let n = pts.len(); + Ring { pts, sign, prev: (0..n).map(|i| (i + n - 1) % n).collect(), next: (0..n).map(|i| (i + 1) % n).collect() } + } + + /// The turn at corner `i`, positive when convex; and the tolerance under which it is straight. + fn turn(&self, i: usize) -> (f64, f64) { + let (a, b, c) = (self.pts[self.prev[i]], self.pts[i], self.pts[self.next[i]]); + let (e, f) = ([b[0] - a[0], b[1] - a[1]], [c[0] - b[0], c[1] - b[1]]); + (cross(e, f) * self.sign, STRAIGHT * e[0].hypot(e[1]) * f[0].hypot(f[1])) + } + + /// No corner turns the other way. A face that winds round more than once (a pentagram) + /// counts as convex too and keeps its fan. + fn is_convex(&self) -> bool { + (0..self.pts.len()).all(|i| { + let (t, tol) = self.turn(i); + t >= -tol + }) + } + + /// Whether the triangle at corner `i` is an ear: convex, and no corner that is not convex + /// lies in it or on its edges (corners at the same place as one of its own excepted). + /// `None` when `budget` runs out. + fn is_ear(&self, i: usize, reflex: &[usize], budget: &mut usize) -> Option { + *budget = budget.checked_sub(1)?; + let (t, tol) = self.turn(i); + if t <= tol { + return Some(false); + } + let (a, b, c) = (self.pts[self.prev[i]], self.pts[i], self.pts[self.next[i]]); + for &r in reflex { + *budget = budget.checked_sub(1)?; + let p = self.pts[r]; + let (turn, tol) = self.turn(r); + if p == a || p == b || p == c || turn > tol { + continue; + } + if self.left_of(a, b, p) && self.left_of(b, c, p) && self.left_of(c, a, p) { + return Some(false); + } + } + Some(true) + } + + /// Whether `p` lies on the inner side of edge `a b`, or on it within rounding (a corner on an + /// ear's edge, after the face is projected, may land a hair outside). + fn left_of(&self, a: [f64; 2], b: [f64; 2], p: [f64; 2]) -> bool { + let l1 = |u: [f64; 2], v: [f64; 2]| (v[0] - u[0]).abs() + (v[1] - u[1]).abs(); + orient(a, b, p) * self.sign >= -STRAIGHT * l1(a, b) * l1(a, p) + } + + /// The first straight corner of the `left` corners from `from` on, charging each look to + /// `budget`. + fn straight(&self, from: usize, left: usize, budget: &mut usize) -> Option { + let mut j = from; + for _ in 0..left { + *budget = budget.checked_sub(1)?; + let (t, tol) = self.turn(j); + if t.abs() <= tol { + return Some(j); + } + j = self.next[j]; + } + None + } + + /// Unlinks corner `i`, returning its triangle. + fn cut(&mut self, i: usize, face: &[Corner]) -> [Corner; 3] { + let (a, c) = (self.prev[i], self.next[i]); + self.next[a] = c; + self.prev[c] = a; + [face[a], face[i], face[c]] + } + + /// Clips ears until a triangle is left. When a whole lap finds no ear, a straight corner is + /// cut instead (its triangle has no area); failing that, or when the budget runs out, the + /// rest is fanned. + fn clip(mut self, face: &[Corner], budget: &mut usize) -> Vec<[Corner; 3]> { + let mut out = Vec::with_capacity(face.len() - 2); + let mut removed = vec![false; face.len()]; + let mut reflex: Vec = (0..face.len()).filter(|&i| self.turn(i).0 <= self.turn(i).1).collect(); + let (mut left, mut i, mut stop) = (face.len(), 0, 0); + while left > 3 { + let ear = match self.is_ear(i, &reflex, budget) { + Some(true) => true, + Some(false) => { + i = self.next[i]; + if i != stop { + continue; + } + match self.straight(i, left, budget) { + Some(j) => { + i = j; + true + } + None => false, + } + } + None => false, + }; + if !ear { + break; + } + let c = self.next[i]; + out.push(self.cut(i, face)); + removed[i] = true; + reflex.retain(|&r| !removed[r]); + left -= 1; + (i, stop) = (c, c); + } + // Fan whatever is left from corner `i`. + let first = i; + let mut b = self.next[first]; + while self.next[b] != first { + out.push([face[first], face[b], face[self.next[b]]]); + b = self.next[b]; + } + out + } +}