Skip to main content

brep_offset/offset/
thicken_faces.rs

1//! THICKEN a sheet of several faces into one solid.
2//!
3//! Each face is thickened by itself ([`crate::thicken_trimmed_sheet`]: the
4//! face, its offset and the walls ruled between their edges), and the slabs are
5//! united. Where two faces meet along a crease the slabs either overlap (the
6//! crease closes toward the side thickened, and the union trims each moved face
7//! where it meets the other) or leave a gap (the crease opens toward that
8//! side). A gap is filled as the caller asks:
9//!
10//! - [`OffsetCorners::Sharp`]: the moved faces are extended until they meet,
11//!   a prism on the kite between the crease, its two moved images and the line
12//!   the two moved planes share; where three such creases meet in a corner,
13//!   the block out to the point the three moved planes share.
14//! - [`OffsetCorners::Rounded`]: the gap is closed by the cylinder of the
15//!   thickness about the crease, between the two moved faces; where three such
16//!   creases meet in a corner, by the piece of the ball about the corner
17//!   between the three.
18//!
19//! A whole patch of a round cylinder thickened toward its axis by its radius
20//! or more is the wedge between it and its axis, with the like wedge opposite
21//! for what is left over.
22//!
23//! A whole patch of a ring (an arc turned about an axis: a bend between a
24//! floor and a wall of revolution) thickened toward its tube's centre circle by
25//! the tube's radius or more is likewise the arc's sector turned about that
26//! axis, with the like sector opposite for what is left over.
27//!
28//! Faces that meet smoothly along a crease (a bend and the flat it leaves)
29//! need no fill; such a crease may be a closed circle. Where a crease closes toward the side thickened at a right
30//! angle or wider, the slabs end on each other or overlap; tighter than a
31//! right angle their square ends are cut off behind the other face. Fills are built where the crease is a straight line along
32//! which both faces keep their normals; any other open crease is refused by
33//! name, as is a corner where the open creases are not exactly three.
34use crate::topology::FaceRecord;
35use crate::{
36    boolean_operation, boolean_operation_nary, extrude_profile_brep, make_arc, make_line, make_sphere_brep_framed, project_point_to_surface,
37    solid_from_polygons, thicken_trimmed_sheet, BooleanOperation, BooleanOptions, BrepSolid, KernelRefusal, KernelStage, NurbsCurve, OffsetCorners,
38    OrRefuse, Vec3,
39};
40
41/// The prefix of every refusal of this operation.
42pub const THICKEN_FACES_REFUSAL: &str = "thickenFaces";
43
44fn input(what: &'static str, message: String) -> KernelRefusal {
45    KernelRefusal::input(KernelStage::Collect, what, format!("{THICKEN_FACES_REFUSAL}: {message}"))
46}
47
48fn refuse(what: &'static str, message: String) -> KernelRefusal {
49    KernelRefusal::unsupported(KernelStage::Classify, what, format!("{THICKEN_FACES_REFUSAL}: {message}"))
50}
51
52/// The sheet a chain of curves sweeps as it slides by `distance` along
53/// `direction`: one face per curve (the curve times the slide), each a sheet
54/// of its own, in the chain's order. Every face's normal is its curve's
55/// direction crossed with the slide's, so the faces of a chain run head to
56/// tail have their normals on one side of the sheet, as
57/// [`thicken_sheet_faces`] needs them; run the chain the other way for the
58/// other side.
59pub fn extrude_curves_to_sheet(curves: &[NurbsCurve], direction: Vec3, distance: f64) -> Result<Vec<BrepSolid>, KernelRefusal> {
60    if curves.is_empty() {
61        return Err(input("curves", "at least one curve is required".into()));
62    }
63    if !distance.is_finite() || distance.abs() <= 1e-12 {
64        return Err(input("distance", "distance must be a nonzero finite value".into()));
65    }
66    let slide = direction.normalized().map_err(|_| input("direction", "direction must be non-zero".into()))?.scale(distance);
67    curves
68        .iter()
69        .map(|curve| {
70            let net = curve
71                .control_points
72                .iter()
73                .map(|pole| vec![*pole, crate::Vec4 { x: pole.x + slide.x * pole.w, y: pole.y + slide.y * pole.w, z: pole.z + slide.z * pole.w, w: pole.w }])
74                .collect();
75            let surface = crate::NurbsSurface::new(curve.degree, 1, curve.knots.clone(), vec![0.0, 0.0, 1.0, 1.0], net).or_refuse(KernelStage::Collect, "thickenFaces.swept_face")?;
76            crate::face_from_surface(&surface)
77        })
78        .collect()
79}
80
81/// One use of an edge by a face: where it runs, and the face's normal there.
82struct Side {
83    face: usize,
84    start: Vec3,
85    middle: Vec3,
86    end: Vec3,
87    /// The face's normal at the start, the middle and the end.
88    normals: [Vec3; 3],
89    /// The way this use runs at its middle (a closed edge has no chord to say).
90    tangent: Vec3,
91}
92
93fn face_normal(face: &FaceRecord, point: Vec3) -> Result<Vec3, KernelRefusal> {
94    let surface = &face.surface;
95    let foot = project_point_to_surface(surface, point).or_refuse(KernelStage::Classify, "thickenFaces.project")?;
96    let normal = match surface.normal(foot.u, foot.v) {
97        Ok(normal) => normal,
98        // At a pole (a side of the patch collapsed to a point) the surface has no
99        // normal of its own: read it a little way in, where it has one.
100        Err(_) => {
101            let [u0, u1] = surface.domain_u().or_refuse(KernelStage::Classify, "thickenFaces.domain")?;
102            let [v0, v1] = surface.domain_v().or_refuse(KernelStage::Classify, "thickenFaces.domain")?;
103            let inward = |at: f64, low: f64, high: f64| at + (0.5 * (low + high) - at) * 1e-6;
104            surface.normal(inward(foot.u, u0, u1), inward(foot.v, v0, v1)).or_refuse(KernelStage::Classify, "thickenFaces.normal")?
105        }
106    };
107    Ok(if face.same_sense { normal } else { normal.scale(-1.0) })
108}
109
110/// The sheet `faces` thickened by `thickness` along the faces' normals
111/// (negative: against them), its open creases closed as `corners` says.
112///
113/// `faces` are sheets of one face or more ([`crate::face_from_surface`],
114/// [`crate::face_from_surface_trimmed`]) that meet along common edges, their
115/// normals all on one side of the sheet. The result is one solid.
116///
117/// Refuses faces whose normals disagree across a crease, a crease that is not
118/// a straight line with constant normals where it opens toward the thickened
119/// side or closes tighter than a right angle, a corner of other than three
120/// open creases, and whatever the single-face thicken or the union refuses.
121pub fn thicken_sheet_faces(faces: &[BrepSolid], thickness: f64, corners: OffsetCorners) -> Result<BrepSolid, KernelRefusal> {
122    if !thickness.is_finite() || thickness.abs() <= 1e-12 {
123        return Err(input("thickness", "thickness must be a nonzero finite value".into()));
124    }
125    let (t, sign) = (thickness.abs(), thickness.signum());
126    let mut records: Vec<(&BrepSolid, &FaceRecord)> = Vec::new();
127    for body in faces {
128        for face in body.shells.iter().flat_map(|shell| &shell.faces) {
129            records.push((body, face));
130        }
131    }
132    if records.is_empty() {
133        return Err(input("faces", "at least one face is required".into()));
134    }
135    let size = records
136        .iter()
137        .flat_map(|(body, _)| &body.vertices)
138        .map(|vertex| vertex.point.sub(records[0].0.vertices[0].point).length())
139        .fold(t, f64::max);
140    let tolerance = 1e-7 * size;
141    let near = |a: Vec3, b: Vec3| a.sub(b).length() <= tolerance;
142
143    // every use of an edge by a face, as that face's loop runs along it
144    let mut sides = Vec::new();
145    for (index, (body, face)) in records.iter().enumerate() {
146        for coedge in face.loops.iter().flat_map(|record| &record.coedges) {
147            let edge = body.edges.iter().find(|edge| edge.id == coedge.edge_id).ok_or_else(|| input("faces", "a face refers to a missing edge".into()))?;
148            if edge.degenerate {
149                continue;
150            }
151            let at = |fraction: f64| edge.curve.evaluate(edge.t0 + (edge.t1 - edge.t0) * fraction).or_refuse(KernelStage::Classify, "thickenFaces.edge");
152            let (mut start, middle, mut end) = (at(0.0)?, at(0.5)?, at(1.0)?);
153            if !coedge.forward {
154                std::mem::swap(&mut start, &mut end);
155            }
156            let normals = [face_normal(face, start)?, face_normal(face, middle)?, face_normal(face, end)?];
157            let along = edge.curve.derivatives(0.5 * (edge.t0 + edge.t1), 1).or_refuse(KernelStage::Classify, "thickenFaces.edge")?;
158            let tangent = along.get(1).copied().unwrap_or(end.sub(start)).scale(if coedge.forward { 1.0 } else { -1.0 });
159            sides.push(Side { face: index, start, middle, end, normals, tangent });
160        }
161    }
162
163    // the slabs, face by face
164    let mut parts = Vec::new();
165    for (_, face) in &records {
166        let loops: Vec<Vec<NurbsCurve>> = face.loops.iter().map(|record| record.coedges.iter().map(|coedge| coedge.pcurve.clone()).collect()).collect();
167        let along = if face.same_sense { thickness } else { -thickness };
168        let wedges = match past_its_axis(face, along, tolerance)? {
169            Some(wedges) => Some(wedges),
170            None => past_its_ring(face, along, tolerance)?,
171        };
172        match wedges {
173            Some(wedges) => parts.extend(wedges),
174            None => parts.extend(thicken_trimmed_sheet(&face.surface, &loops, along, false)?),
175        }
176    }
177
178    // the creases: two faces' uses of one edge, run opposite ways
179    struct Open {
180        faces: [usize; 2],
181        ends: [Vec3; 2],
182        moved: [Vec3; 2],
183    }
184    let mut open = Vec::new();
185    let mut cuts: Vec<BrepSolid> = Vec::new();
186    for (i, a) in sides.iter().enumerate() {
187        for b in sides.iter().skip(i + 1) {
188            if a.face == b.face || !near(a.middle, b.middle) {
189                continue;
190            }
191            // a closed crease starts where it ends: only the way it runs says how the two uses face
192            let closed = near(a.start, a.end);
193            let opposite = if closed { a.tangent.dot(b.tangent) < 0.0 } else { near(a.start, b.end) && near(a.end, b.start) };
194            if !opposite {
195                if closed || (near(a.start, b.start) && near(a.end, b.end)) {
196                    return Err(input("normals", format!("faces {} and {} have their normals on opposite sides of the sheet", a.face, b.face)));
197                }
198                continue;
199            }
200            let run = a.end.sub(a.start);
201            let tangent = if closed { a.tangent } else { run }.normalized().map_err(|_| refuse("crease", "a crease has no length".into()))?;
202            // toward face a's inside, across the crease, and how far face b's moved image leans that way
203            let inward = a.normals[1].cross(tangent);
204            let lean = b.normals[1].scale(sign).dot(inward);
205            let moved = [a.normals[1].scale(sign), b.normals[1].scale(sign)];
206            let straight = a.middle.sub(a.start).cross(tangent).length() <= tolerance;
207            let steady = |side: &Side| side.normals.iter().all(|normal| normal.sub(side.normals[1]).length() <= 1e-9);
208            if lean.abs() <= 1e-9 {
209                // the faces meet smoothly: the slabs' ends are one wall
210                continue;
211            }
212            if lean > 0.0 {
213                // the crease closes toward the thickened side. At a right angle, or wider, the
214                // slabs end on each other or overlap, and the union is the answer. Tighter than a
215                // right angle their square ends stand out behind the other face, and are cut off.
216                let cosine = moved[0].dot(moved[1]);
217                if cosine >= -1e-9 {
218                    continue;
219                }
220                if !straight || !steady(a) || !steady(b) {
221                    return Err(refuse("crease_closing", format!("the crease between faces {} and {} closes toward the thickened side tighter than a right angle and is not a straight line with constant normals", a.face, b.face)));
222                }
223                let inward_b = b.normals[1].cross(tangent.scale(-1.0));
224                for (own, other, into) in [(moved[0], moved[1], inward), (moved[1], moved[0], inward_b)] {
225                    let top = a.start.add(own.scale(t));
226                    let reach = top.add(into.scale(t * -cosine / into.dot(other)));
227                    let line = |from: Vec3, to: Vec3| make_line(from, to).or_refuse(KernelStage::Collect, "thickenFaces.cut_line");
228                    cuts.push(extrude_profile_brep(&[line(a.start, top)?, line(top, reach)?, line(reach, a.start)?], run, run.length())?);
229                }
230                continue;
231            }
232            // b runs the other way: its start is a's end
233            if !straight || !steady(a) || !steady(b) {
234                return Err(refuse("crease_curved", format!("the crease between faces {} and {} opens toward the thickened side and is not a straight line with constant normals", a.face, b.face)));
235            }
236            parts.push(crease_fill(a.start, run, moved, t, corners)?);
237            open.push(Open { faces: [a.face, b.face], ends: [a.start, a.end], moved });
238        }
239    }
240
241    // the corners: points where open creases end together
242    let mut points: Vec<Vec3> = Vec::new();
243    for crease in &open {
244        for end in crease.ends {
245            if !points.iter().any(|point| near(*point, end)) {
246                points.push(end);
247            }
248        }
249    }
250    for point in points {
251        let here: Vec<&Open> = open.iter().filter(|crease| crease.ends.iter().any(|end| near(*end, point))).collect();
252        if here.len() == 1 {
253            continue;
254        }
255        // three creases between three faces, each pair once
256        let mut around: Vec<(usize, Vec3)> = Vec::new();
257        for crease in &here {
258            for (face, moved) in crease.faces.iter().zip(crease.moved) {
259                if !around.iter().any(|(known, _)| known == face) {
260                    around.push((*face, moved));
261                }
262            }
263        }
264        if here.len() != 3 || around.len() != 3 {
265            return Err(refuse("corner", format!("{} open creases between {} faces meet in one corner; exactly three between three faces are built", here.len(), around.len())));
266        }
267        parts.push(corner_fill(point, [around[0].1, around[1].1, around[2].1], t, corners)?);
268    }
269
270    let united = if parts.len() == 1 { parts.remove(0) } else { boolean_operation_nary(&parts, BooleanOperation::Union)? };
271    if cuts.is_empty() {
272        return Ok(united);
273    }
274    let mut operands = vec![united];
275    operands.extend(cuts);
276    boolean_operation_nary(&operands, BooleanOperation::Subtract)
277}
278
279/// A whole patch of a round cylinder (an arc along u, slid straight along v)
280/// thickened toward its axis by its radius or more: every point `p + s·n`
281/// then runs from the patch to the axis and, past it, out the other side. So
282/// the body is the wedge between the patch and its axis and, opposite it, the
283/// like wedge of what the thickness has left over the radius. `None` for any
284/// other face or a thickness short of the axis, which the single-face thicken
285/// takes.
286fn past_its_axis(face: &FaceRecord, along: f64, tolerance: f64) -> Result<Option<Vec<BrepSolid>>, KernelRefusal> {
287    let surface = &face.surface;
288    let stage = KernelStage::Classify;
289    if surface.degree_v != 1 || surface.control_points.first().map(Vec::len) != Some(2) || !whole_domain(face)? {
290        return Ok(None);
291    }
292    let [u0, u1] = surface.domain_u().or_refuse(stage, "thickenFaces.domain")?;
293    let [v0, v1] = surface.domain_v().or_refuse(stage, "thickenFaces.domain")?;
294    let point = |u: f64, v: f64| surface.evaluate(u, v).or_refuse(stage, "thickenFaces.point");
295    let normal = |u: f64, v: f64| surface.normal(u, v).or_refuse(stage, "thickenFaces.normal");
296    let slide = point(u0, v1)?.sub(point(u0, v0)?);
297    // the centre the normals at the two ends of the arc pass through, toward the side thickened
298    let toward = along.signum();
299    let (p0, n0, p1, n1) = (point(u0, v0)?, normal(u0, v0)?.scale(toward), point(u1, v0)?, normal(u1, v0)?.scale(toward));
300    let chord = p1.sub(p0);
301    let spread = n0.sub(n1);
302    if spread.length() <= 1e-9 {
303        return Ok(None);
304    }
305    // p0 + R·n0 = p1 + R·n1
306    let radius = chord.dot(spread) / spread.dot(spread);
307    if !(radius > 0.0) || along.abs() < radius - tolerance {
308        return Ok(None);
309    }
310    let centre = p0.add(n0.scale(radius));
311    const SAMPLES: usize = 16;
312    for i in 0..=SAMPLES {
313        let u = u0 + (u1 - u0) * i as f64 / SAMPLES as f64;
314        for (v, shift) in [(v0, Vec3::new(0.0, 0.0, 0.0)), (v1, slide)] {
315            let focus = point(u, v)?.add(normal(u, v)?.scale(toward * radius));
316            if focus.sub(centre.add(shift)).length() > tolerance {
317                return Ok(None);
318            }
319        }
320    }
321    if slide.cross(n0).length() < (1.0 - 1e-9) * slide.length() {
322        return Ok(None);
323    }
324    // the wedge on the arc scaled about the centre by `factor`, slid along the axis
325    let arc = surface.iso_curve_v(v0).or_refuse(stage, "thickenFaces.arc")?;
326    let wedge = |factor: f64| -> Result<BrepSolid, KernelRefusal> {
327        let scaled = |q: Vec3| centre.add(q.sub(centre).scale(factor));
328        let poles = arc
329            .control_points
330            .iter()
331            .map(|pole| crate::Vec4::from_point(scaled(Vec3::new(pole.x / pole.w, pole.y / pole.w, pole.z / pole.w)), pole.w))
332            .collect();
333        let rim = NurbsCurve::new(arc.degree, arc.knots.clone(), poles).or_refuse(stage, "thickenFaces.wedge_arc")?;
334        let section = vec![
335            make_line(centre, scaled(p0)).or_refuse(stage, "thickenFaces.wedge_side")?,
336            rim,
337            make_line(scaled(p1), centre).or_refuse(stage, "thickenFaces.wedge_side")?,
338        ];
339        extrude_profile_brep(&section, slide, slide.length())
340    };
341    let mut wedges = vec![wedge(1.0)?];
342    let over = along.abs() - radius;
343    if over > tolerance {
344        wedges.push(wedge(-over / radius)?);
345    }
346    Ok(Some(wedges))
347}
348
349/// Is the face its surface's whole domain (its one loop's corners the domain's), regular at its corners?
350fn whole_domain(face: &FaceRecord) -> Result<bool, KernelRefusal> {
351    let surface = &face.surface;
352    let stage = KernelStage::Classify;
353    if face.loops.len() != 1 || face.loops[0].coedges.len() != 4 {
354        return Ok(false);
355    }
356    let [u0, u1] = surface.domain_u().or_refuse(stage, "thickenFaces.domain")?;
357    let [v0, v1] = surface.domain_v().or_refuse(stage, "thickenFaces.domain")?;
358    let corners = [[u0, v0], [u1, v0], [u1, v1], [u0, v1]];
359    let slack = 1e-9 * ((u1 - u0).abs() + (v1 - v0).abs());
360    for coedge in &face.loops[0].coedges {
361        let [t0, t1] = coedge.pcurve.domain().or_refuse(stage, "thickenFaces.pcurve")?;
362        for t in [t0, t1] {
363            let at = coedge.pcurve.evaluate(t).or_refuse(stage, "thickenFaces.pcurve")?;
364            if !corners.iter().any(|corner| (at.x - corner[0]).abs() + (at.y - corner[1]).abs() <= slack) {
365                return Ok(false);
366            }
367        }
368        // and runs along one side of the domain between them, not across the face
369        const SAMPLES: usize = 16;
370        let mut on_side = [true; 4];
371        for index in 1..SAMPLES {
372            let at = coedge.pcurve.evaluate(t0 + (t1 - t0) * index as f64 / SAMPLES as f64).or_refuse(stage, "thickenFaces.pcurve")?;
373            for (side, off) in [(at.x - u0).abs(), (at.x - u1).abs(), (at.y - v0).abs(), (at.y - v1).abs()].into_iter().enumerate() {
374                on_side[side] &= off <= slack;
375            }
376        }
377        if !on_side.iter().any(|on| *on) {
378            return Ok(false);
379        }
380    }
381    // a patch with a pole (a side collapsed to a point, where it has no normal) is no arc slid or turned
382    Ok(corners.iter().all(|corner| surface.normal(corner[0], corner[1]).is_ok()))
383}
384
385/// Places along one parameter of a surface that no span of it can hide
386/// between: twice the degree and one more in every knot span, ends included.
387/// A span is a rational piece of that degree, so the square of a distance
388/// along it, cleared of its weight, is a polynomial of twice the degree: one
389/// that vanishes at these vanishes along the span.
390fn span_places(knots: &[f64], degree: usize, low: f64, high: f64) -> Vec<f64> {
391    let mut breaks = vec![low];
392    breaks.extend(knots.iter().copied().filter(|knot| *knot > low && *knot < high));
393    breaks.push(high);
394    breaks.dedup();
395    let per_span = 2 * degree + 1;
396    let mut places = vec![low];
397    for span in breaks.windows(2) {
398        for index in 1..=per_span {
399            places.push(span[0] + (span[1] - span[0]) * index as f64 / per_span as f64);
400        }
401    }
402    *places.last_mut().expect("places") = high;
403    places
404}
405
406/// A whole patch of a ring (a circular arc along one parameter, turned about
407/// an axis along the other: a quarter of a torus round a cup's floor)
408/// thickened toward its tube's centre circle by the tube's radius or more.
409/// Every point `p + s·n` then runs from the patch to that circle and, past it,
410/// out the other side, each in its own half-plane through the axis. So the
411/// body is the arc's sector (the arc and its centre) turned about the axis
412/// and, opposite it, the like sector of what the thickness has left over the
413/// radius. `None` for any other face, a thickness short of the centre circle,
414/// or a leftover that would reach the axis, which the single-face thicken
415/// takes.
416fn past_its_ring(face: &FaceRecord, along: f64, tolerance: f64) -> Result<Option<Vec<BrepSolid>>, KernelRefusal> {
417    if !whole_domain(face)? {
418        return Ok(None);
419    }
420    for arc_along_u in [false, true] {
421        if let Some(sectors) = ring_sectors(face, along, tolerance, arc_along_u)? {
422            return Ok(Some(sectors));
423        }
424    }
425    Ok(None)
426}
427
428fn ring_sectors(face: &FaceRecord, along: f64, tolerance: f64, arc_along_u: bool) -> Result<Option<Vec<BrepSolid>>, KernelRefusal> {
429    let surface = &face.surface;
430    let stage = KernelStage::Classify;
431    let [u0, u1] = surface.domain_u().or_refuse(stage, "thickenFaces.domain")?;
432    let [v0, v1] = surface.domain_v().or_refuse(stage, "thickenFaces.domain")?;
433    // (a, b): along the arc, round the axis
434    let ([a0, a1], [b0, b1]) = if arc_along_u { ([u0, u1], [v0, v1]) } else { ([v0, v1], [u0, u1]) };
435    let at = |a: f64, b: f64| if arc_along_u { (a, b) } else { (b, a) };
436    let point = |a: f64, b: f64| surface.evaluate(at(a, b).0, at(a, b).1).or_refuse(stage, "thickenFaces.point");
437    let toward = along.signum();
438    let normal = |a: f64, b: f64| surface.normal(at(a, b).0, at(a, b).1).map(|normal| normal.scale(toward)).or_refuse(stage, "thickenFaces.normal");
439    // the centre the normals at the two ends of the first arc pass through
440    let (p0, n0, p1, n1) = (point(a0, b0)?, normal(a0, b0)?, point(a1, b0)?, normal(a1, b0)?);
441    let spread = n0.sub(n1);
442    if spread.length() <= 1e-9 {
443        return Ok(None);
444    }
445    let radius = p1.sub(p0).dot(spread) / spread.dot(spread);
446    if !(radius > 0.0) || along.abs() < radius - tolerance {
447        return Ok(None);
448    }
449    // read in every span of the surface both ways, so nothing between the readings is taken on trust
450    let (arc_places, turn_places) = if arc_along_u {
451        (span_places(&surface.knots_u, surface.degree_u, a0, a1), span_places(&surface.knots_v, surface.degree_v, b0, b1))
452    } else {
453        (span_places(&surface.knots_v, surface.degree_v, a0, a1), span_places(&surface.knots_u, surface.degree_u, b0, b1))
454    };
455    let (arcs, turns) = (arc_places.len() - 1, turn_places.len() - 1);
456    let arc_at = |i: usize| arc_places[i];
457    let turn_at = |j: usize| turn_places[j];
458    // each arc has one centre, the tube's centre line at that turn
459    let mut centres = Vec::with_capacity(turns + 1);
460    for j in 0..=turns {
461        let centre = point(a0, turn_at(j))?.add(normal(a0, turn_at(j))?.scale(radius));
462        for i in 1..=arcs {
463            if point(arc_at(i), turn_at(j))?.add(normal(arc_at(i), turn_at(j))?.scale(radius)).sub(centre).length() > tolerance {
464                return Ok(None);
465            }
466        }
467        centres.push(centre);
468    }
469    // the centres lie on a circle: its axis from three of them
470    let (f0, f1, f2) = (centres[0], centres[turns / 3], centres[2 * turns / 3]);
471    let (e1, e2) = (f1.sub(f0), f2.sub(f0));
472    let across = e1.cross(e2);
473    if across.length() <= 1e-9 * e1.length() * e2.length() || across.length() <= tolerance * tolerance {
474        return Ok(None);
475    }
476    let axis = across.normalized().or_refuse(stage, "thickenFaces.ring_axis")?;
477    // circumcentre of the three
478    let middle = f0.add(
479        e2.scale(e1.dot(e1)).sub(e1.scale(e2.dot(e2))).cross(across).scale(1.0 / (2.0 * across.dot(across))),
480    );
481    let ring = f0.sub(middle).length();
482    let over = along.abs() - radius;
483    if !(ring > over + tolerance) {
484        return Ok(None);
485    }
486    // every arc is the first turned about that axis, by a growing angle
487    let mut angle = 0.0;
488    for j in 1..=turns {
489        let (before, here) = (centres[j - 1].sub(middle), centres[j].sub(middle));
490        if (here.length() - ring).abs() > tolerance || here.dot(axis).abs() > tolerance {
491            return Ok(None);
492        }
493        let step = axis.dot(before.cross(here)).atan2(before.dot(here));
494        if !(step > 0.0) {
495            return Ok(None);
496        }
497        angle += step;
498        for i in 0..=arcs {
499            let first = point(arc_at(i), b0)?.sub(middle);
500            let turned = middle.add(first.rotate_about(axis, angle));
501            if point(arc_at(i), turn_at(j))?.sub(turned).length() > tolerance {
502                return Ok(None);
503            }
504        }
505    }
506    // the first arc lies in a half-plane through the axis, off the axis itself
507    let square = axis.cross(f0.sub(middle));
508    for i in 0..=arcs {
509        let from_axis = point(arc_at(i), b0)?.sub(middle);
510        if from_axis.dot(square).abs() > tolerance * ring.max(1.0) || from_axis.sub(axis.scale(from_axis.dot(axis))).length() <= tolerance {
511            return Ok(None);
512        }
513    }
514    let arc = if arc_along_u { surface.iso_curve_v(b0) } else { surface.iso_curve_u(b0) }.or_refuse(stage, "thickenFaces.arc")?;
515    let turn = angle.min(std::f64::consts::TAU);
516    // the sector on the arc scaled about its centre by `factor`, turned about the axis
517    let sector = |factor: f64| -> Result<BrepSolid, KernelRefusal> {
518        let scaled = |q: Vec3| f0.add(q.sub(f0).scale(factor));
519        let poles = arc
520            .control_points
521            .iter()
522            .map(|pole| crate::Vec4::from_point(scaled(Vec3::new(pole.x / pole.w, pole.y / pole.w, pole.z / pole.w)), pole.w))
523            .collect();
524        let rim = NurbsCurve::new(arc.degree, arc.knots.clone(), poles).or_refuse(stage, "thickenFaces.sector_arc")?;
525        let section = vec![
526            make_line(f0, scaled(p0)).or_refuse(stage, "thickenFaces.sector_side")?,
527            rim,
528            make_line(scaled(p1), f0).or_refuse(stage, "thickenFaces.sector_side")?,
529        ];
530        crate::revolve_profile_brep(&section, middle, axis, turn).or_refuse(KernelStage::Fragment, "thickenFaces.sector")
531    };
532    let mut sectors = vec![sector(1.0)?];
533    if over > tolerance {
534        sectors.push(sector(-over / radius)?);
535    }
536    Ok(Some(sectors))
537}
538
539/// The fill of an open straight crease from `start` along `run`, between the
540/// two faces' moved images `moved` (unit vectors square to the crease).
541fn crease_fill(start: Vec3, run: Vec3, moved: [Vec3; 2], t: f64, corners: OffsetCorners) -> Result<BrepSolid, KernelRefusal> {
542    let collect = KernelStage::Collect;
543    let (a, b) = (start.add(moved[0].scale(t)), start.add(moved[1].scale(t)));
544    let line = |from: Vec3, to: Vec3| make_line(from, to).or_refuse(collect, "thickenFaces.fill_line");
545    let section = match corners {
546        OffsetCorners::Sharp => {
547            // the point at the thickness from both faces, in the section's plane
548            let apex = start.add(moved[0].add(moved[1]).scale(t / (1.0 + moved[0].dot(moved[1]))));
549            vec![line(start, a)?, line(a, apex)?, line(apex, b)?, line(b, start)?]
550        }
551        OffsetCorners::Rounded => {
552            let across = moved[1].sub(moved[0].scale(moved[1].dot(moved[0]))).normalized().or_refuse(collect, "thickenFaces.fill_frame")?;
553            let angle = moved[0].dot(moved[1]).clamp(-1.0, 1.0).acos();
554            vec![line(start, a)?, make_arc(start, moved[0], across, t, 0.0, angle).or_refuse(collect, "thickenFaces.fill_arc")?, line(b, start)?]
555        }
556    };
557    extrude_profile_brep(&section, run, run.length())
558}
559
560/// The fill of a corner where three open creases meet, between the three
561/// faces' moved images `moved` (unit vectors).
562fn corner_fill(corner: Vec3, moved: [Vec3; 3], t: f64, corners: OffsetCorners) -> Result<BrepSolid, KernelRefusal> {
563    let at = |direction: Vec3, length: f64| corner.add(direction.scale(length));
564    match corners {
565        OffsetCorners::Sharp => {
566            // the point at the thickness from all three faces: moved[i] · x = 1
567            let [a, b, c] = moved;
568            let volume = a.dot(b.cross(c));
569            if volume.abs() <= 1e-9 {
570                return Err(refuse("corner", "the three faces at a corner do not span space".into()));
571            }
572            let far = b.cross(c).add(c.cross(a)).add(a.cross(b)).scale(1.0 / volume);
573            let pair = |i: usize, j: usize| at(moved[i].add(moved[j]), t / (1.0 + moved[i].dot(moved[j])));
574            let tip = |i: usize| at(moved[i], t);
575            let far = at(far, t);
576            let mut faces = Vec::new();
577            for (i, j) in [(0, 1), (1, 2), (2, 0)] {
578                faces.push(vec![corner, tip(i), pair(i, j), tip(j)]);
579            }
580            for (i, j, k) in [(0, 1, 2), (1, 2, 0), (2, 0, 1)] {
581                faces.push(vec![tip(i), pair(i, j), far, pair(i, k)]);
582            }
583            solid_from_polygons(&faces)
584        }
585        OffsetCorners::Rounded => {
586            // the ball about the corner, kept between the three directions: its poles and its
587            // seam turned away from the piece kept
588            let middle = moved[0].add(moved[1]).add(moved[2]).normalized().or_refuse(KernelStage::Collect, "thickenFaces.corner_frame")?;
589            let pole = middle.cross(moved[0]).normalized().or_refuse(KernelStage::Collect, "thickenFaces.corner_frame")?;
590            let ball = make_sphere_brep_framed(corner, t, pole, Some(middle.scale(-1.0))).or_refuse(KernelStage::Collect, "thickenFaces.corner_ball")?;
591            let reach = 4.0 * t;
592            let tips = [at(moved[0], reach), at(moved[1], reach), at(moved[2], reach)];
593            let base = tips[1].sub(tips[0]).cross(tips[2].sub(tips[0]));
594            if (tips[0].sub(corner).dot(base) / base.length()).abs() <= t {
595                return Err(refuse("corner", "the three faces at a corner are too nearly flat for a ball between them".into()));
596            }
597            let wedge = solid_from_polygons(&[
598                vec![corner, tips[0], tips[1]],
599                vec![corner, tips[1], tips[2]],
600                vec![corner, tips[2], tips[0]],
601                vec![tips[0], tips[1], tips[2]],
602            ])?;
603            boolean_operation(&ball, &wedge, BooleanOperation::Intersect, &BooleanOptions::default())
604        }
605    }
606}
607