Skip to main content

brep_construction/construction/
polyhedron.rs

1//! A closed polyhedron from its corners and its planar polygon faces.
2//!
3//! Each face is a plane patch sized to the face itself (its polygon and a
4//! tenth of its extent around it), trimmed by the polygon's straight edges;
5//! the faces are sewn along their shared edges. A patch sized to its face
6//! keeps every quantity read through its parameters (area, moments) at the
7//! precision of the face, wherever the face stands.
8
9use crate::{face_from_surface_trimmed, make_line, solid_from_sheets, BrepSolid, KernelRefusal, KernelStage, NurbsSurface, OrRefuse, Vec3, Vec4};
10use std::collections::HashMap;
11
12/// The prefix of every refusal of this module.
13pub const POLYHEDRON_REFUSAL: &str = "polyhedron";
14
15fn input(what: &'static str, message: String) -> KernelRefusal {
16    KernelRefusal::input(KernelStage::Collect, what, format!("{POLYHEDRON_REFUSAL}: {message}"))
17}
18
19/// The closed polyhedron whose faces are the polygons `faces` over `points`:
20/// each face a loop of point indices running counter-clockwise seen from
21/// outside, flat (every corner within a billionth of the polyhedron's size
22/// of its plane), its consecutive corners distinct.
23///
24/// Refuses fewer than four faces, a face of fewer than three corners, an
25/// index past `points`, a face that is not flat or has no area, faces that
26/// do not close (every edge must be used once each way) and faces that form
27/// more than one closed part.
28pub fn make_polyhedron_brep(points: &[Vec3], faces: &[Vec<usize>]) -> Result<BrepSolid, KernelRefusal> {
29    if faces.len() < 4 {
30        return Err(input("polyhedron_faces", format!("{} faces bound no solid", faces.len())));
31    }
32    if let Some(f) = faces.iter().position(|face| face.len() < 3) {
33        return Err(input("polyhedron_face", format!("face {f} has fewer than three corners")));
34    }
35    if faces.iter().flatten().any(|&i| i >= points.len()) {
36        return Err(input("polyhedron_index", "a face names a corner past the points".into()));
37    }
38    let used: Vec<Vec3> = faces.iter().flatten().map(|&i| points[i]).collect();
39    let (mut low, mut high) = (used[0], used[0]);
40    for p in &used {
41        low = Vec3::new(low.x.min(p.x), low.y.min(p.y), low.z.min(p.z));
42        high = Vec3::new(high.x.max(p.x), high.y.max(p.y), high.z.max(p.z));
43    }
44    let size = high.sub(low).length();
45    if !(size.is_finite() && size > 0.0) {
46        return Err(input("polyhedron_extent", "the corners have no extent".into()));
47    }
48    // A billionth of the size, and the round-off of the coordinates themselves.
49    let reach = used.iter().fold(0.0f64, |m, p| m.max(p.x.abs()).max(p.y.abs()).max(p.z.abs()));
50    let flat = 1e-9 * size + 16.0 * f64::EPSILON * reach;
51    let mut sides: HashMap<(usize, usize), usize> = HashMap::new();
52    for (f, face) in faces.iter().enumerate() {
53        if face.len() < 3 {
54            return Err(input("polyhedron_face", format!("face {f} has fewer than three corners")));
55        }
56        for k in 0..face.len() {
57            let (a, b) = (face[k], face[(k + 1) % face.len()]);
58            if a == b || sides.insert((a, b), f).is_some() {
59                return Err(input("polyhedron_closure", format!("face {f} repeats a corner or an edge another face runs the same way")));
60            }
61        }
62    }
63    if sides.keys().any(|&(a, b)| !sides.contains_key(&(b, a))) {
64        return Err(input("polyhedron_closure", "the faces do not close: an edge has no face on its other side".into()));
65    }
66    // One polyhedron: every face reaches every other across edges (closed
67    // parts apart could lie one through another).
68    let mut reached = vec![false; faces.len()];
69    let mut stack = vec![0usize];
70    reached[0] = true;
71    while let Some(f) = stack.pop() {
72        let face = &faces[f];
73        for k in 0..face.len() {
74            let other = sides[&(face[(k + 1) % face.len()], face[k])];
75            if !reached[other] {
76                reached[other] = true;
77                stack.push(other);
78            }
79        }
80    }
81    if reached.iter().any(|&r| !r) {
82        return Err(input("polyhedron_parts", "the faces form more than one closed part".into()));
83    }
84    let line = |a: usize, b: usize| make_line(points[a], points[b]).or_refuse(KernelStage::Collect, "polyhedron.edge");
85    let mut sheets = Vec::with_capacity(faces.len());
86    for (f, face) in faces.iter().enumerate() {
87        // Newell's normal: the polygon's area vector, along its outward normal.
88        // Read about the face's own centre, so its size and not its place sets the round-off.
89        let centre = face.iter().fold(Vec3::new(0.0, 0.0, 0.0), |s, &i| s.add(points[i])).scale(1.0 / face.len() as f64);
90        let mut area = Vec3::new(0.0, 0.0, 0.0);
91        for k in 0..face.len() {
92            let (p, q) = (points[face[k]].sub(centre), points[face[(k + 1) % face.len()]].sub(centre));
93            area = area.add(Vec3::new((p.y - q.y) * (p.z + q.z), (p.z - q.z) * (p.x + q.x), (p.x - q.x) * (p.y + q.y)));
94        }
95        let length = area.length();
96        if !(length > flat * flat) {
97            return Err(input("polyhedron_face", format!("face {f} has no area")));
98        }
99        let n = area.scale(1.0 / length);
100        if face.iter().any(|&i| points[i].sub(centre).dot(n).abs() > flat) {
101            return Err(input("polyhedron_flat", format!("face {f} is not flat")));
102        }
103        // In-plane axes from the face's longest reach from its centre.
104        let far = face.iter().map(|&i| points[i].sub(centre)).fold(Vec3::new(0.0, 0.0, 0.0), |a, b| if b.length() > a.length() { b } else { a });
105        let e1 = far.sub(n.scale(far.dot(n))).scale(1.0 / far.length());
106        let e2 = n.cross(e1);
107        let (mut u0, mut u1, mut v0, mut v1) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY);
108        for &i in face {
109            let d = points[i].sub(centre);
110            (u0, u1, v0, v1) = (u0.min(d.dot(e1)), u1.max(d.dot(e1)), v0.min(d.dot(e2)), v1.max(d.dot(e2)));
111        }
112        let margin = 0.1 * (u1 - u0).max(v1 - v0);
113        let (u0, u1, v0, v1) = (u0 - margin, u1 + margin, v0 - margin, v1 + margin);
114        let corner = |u: f64, v: f64| Vec4::from_point(centre.add(e1.scale(u)).add(e2.scale(v)), 1.0);
115        let plane = NurbsSurface::new(1, 1, vec![0.0, 0.0, 1.0, 1.0], vec![0.0, 0.0, 1.0, 1.0], vec![vec![corner(u0, v0), corner(u0, v1)], vec![corner(u1, v0), corner(u1, v1)]])
116            .or_refuse(KernelStage::Collect, "polyhedron.face")?;
117        let edges = (0..face.len()).map(|k| line(face[k], face[(k + 1) % face.len()])).collect::<Result<Vec<_>, _>>()?;
118        sheets.push(face_from_surface_trimmed(&plane, &[edges])?);
119    }
120    solid_from_sheets(&sheets, flat)
121}
122