1use super::*;
12
13const ENTRY: &str = "full_round";
14
15fn unsupported(what: &'static str, message: String) -> KernelRefusal {
16 KernelRefusal::unsupported(KernelStage::Classify, what, format!("{ENTRY}: {message}"))
17}
18
19fn plane_of(face: &FaceRecord) -> Option<(Vec3, Vec3)> {
21 let s = &face.surface;
22 if s.degree_u != 1 || s.degree_v != 1 {
23 return None;
24 }
25 let pts: Vec<Vec3> = s.control_points.iter().flatten().filter_map(|c| c.point().ok()).collect();
26 if pts.len() < 3 {
27 return None;
28 }
29 let mut n = pts[1].sub(pts[0]).cross(pts[pts.len() - 1].sub(pts[0])).normalized().ok()?;
30 let scale = pts.iter().map(|p| p.sub(pts[0]).length()).fold(0.0, f64::max).max(1.0);
31 if pts.iter().any(|p| n.dot(p.sub(pts[0])).abs() > 1e-10 * scale) {
32 return None;
33 }
34 let [u0, u1] = s.domain_u().ok()?;
35 let [v0, v1] = s.domain_v().ok()?;
36 if s.normal(0.5 * (u0 + u1), 0.5 * (v0 + v1)).ok()?.dot(n) < 0.0 {
37 n = n.scale(-1.0);
38 }
39 Some((if face.same_sense { n } else { n.scale(-1.0) }, pts[0]))
40}
41
42fn face_at(solid: &BrepSolid, point: Vec3) -> Result<u64, KernelRefusal> {
43 let size = solid.vertices.iter().map(|v| v.point.sub(solid.vertices[0].point).length()).fold(0.0, f64::max);
44 let near = if size > 0.0 { 1e-6 * size } else { 1e-9 };
45 let mut best: Option<(f64, u64)> = None;
46 for face in solid.shells.iter().flat_map(|s| s.faces.iter()) {
47 let Ok(q) = crate::project_point_to_surface(&face.surface, point) else { continue };
48 if q.distance > near {
49 continue;
50 }
51 let inside = crate::classification::parameter_point_in_face(face, crate::Vec2 { x: q.u, y: q.v }, 1e-9).map(|c| c != crate::classification::PolygonClass::Outside).unwrap_or(false);
52 if inside && best.map_or(true, |b| q.distance < b.0) {
53 best = Some((q.distance, face.id));
54 }
55 }
56 best.map(|b| b.1).ok_or_else(|| KernelRefusal::input(KernelStage::Collect, "face_point", format!("{ENTRY}: no face of the solid holds the point {point:?}")))
57}
58
59pub fn full_round(solid: &BrepSolid, side_a: Vec3, middle: Vec3, side_b: Vec3, name: Option<&str>) -> Result<BrepSolid, KernelRefusal> {
62 let _operation = crate::blend::BlendOperation::enter();
63 if solid.shells.len() != 1 {
64 return Err(unsupported("full_round_shells", "the solid has more than one shell".into()));
65 }
66 let faces = &solid.shells[0].faces;
67 let ids = [face_at(solid, side_a)?, face_at(solid, middle)?, face_at(solid, side_b)?];
68 if ids[0] == ids[1] || ids[1] == ids[2] || ids[0] == ids[2] {
69 return Err(KernelRefusal::input(KernelStage::Collect, "full_round_faces", format!("{ENTRY}: the three points must lie on three faces")));
70 }
71 let by_id = |id: u64| faces.iter().find(|f| f.id == id).expect("face");
72 let planes: Vec<(Vec3, Vec3)> = ids.iter().map(|&id| plane_of(by_id(id))).collect::<Option<_>>().ok_or_else(|| unsupported("full_round_planes", "the three faces must be planes".into()))?;
73 let e = planes[0].0.cross(planes[1].0).normalized().map_err(|_| unsupported("full_round_parallel", "the side and middle faces are parallel".into()))?;
74 if planes[2].0.dot(e).abs() > 1e-9 {
75 return Err(unsupported("full_round_prism", "the three faces do not run along one direction".into()));
76 }
77 let mut ends: Vec<(usize, Vec3, Vec3)> = Vec::new();
79 for (index, face) in faces.iter().enumerate() {
80 let (n, on) = plane_of(face).ok_or_else(|| unsupported("full_round_prism", "the solid is not a prism: a face is not a plane".into()))?;
81 if face.loops.len() != 1 {
82 return Err(unsupported("full_round_prism", "the solid is not a prism: a face has a hole".into()));
83 }
84 if (n.dot(e).abs() - 1.0).abs() <= 1e-9 {
85 ends.push((index, n, on));
86 } else if n.dot(e).abs() > 1e-9 {
87 return Err(unsupported("full_round_prism", "the solid is not a prism: a face is neither along the direction nor square to it".into()));
88 }
89 }
90 if ends.len() != 2 || ends[0].1.dot(ends[1].1) > 0.0 {
91 return Err(unsupported("full_round_prism", "the solid is not a prism: it has no two opposite end faces".into()));
92 }
93 let size = solid.vertices.iter().map(|v| v.point.sub(solid.vertices[0].point).length()).fold(0.0, f64::max).max(1.0);
96 for &(index, _, on) in &ends {
97 let heights: Vec<f64> = faces[index]
98 .loops
99 .iter()
100 .flat_map(|l| l.coedges.iter())
101 .filter_map(|c| solid.edges.iter().find(|x| x.id == c.edge_id))
102 .flat_map(|x| [x.start_vertex_id, x.end_vertex_id])
103 .filter_map(|id| solid.vertices.iter().find(|v| v.id == id))
104 .map(|v| v.point)
105 .collect::<Vec<Vec3>>()
106 .iter()
107 .map(|p| e.dot(p.sub(on)))
108 .collect();
109 let width = faces[index]
111 .loops
112 .iter()
113 .flat_map(|l| l.coedges.iter())
114 .filter_map(|c| solid.edges.iter().find(|x| x.id == c.edge_id))
115 .filter_map(|x| Some(x.curve.evaluate(x.t0).ok()?.sub(x.curve.evaluate(x.t1).ok()?).length()))
116 .fold(0.0, f64::max)
117 .max(1e-300);
118 if heights.iter().any(|h| h.abs() > 1e-12 * width) {
119 return Err(unsupported("full_round_prism", "the solid is not a prism: an end face is not square to the direction".into()));
120 }
121 }
122 let (start, finish) = if ends[0].1.dot(e) < 0.0 { (ends[0], ends[1]) } else { (ends[1], ends[0]) };
124 let length = e.dot(finish.2.sub(start.2));
125 if !(length > 0.0) {
126 return Err(unsupported("full_round_prism", "the end faces stand the wrong way".into()));
127 }
128 let face = &faces[start.0];
130 let mut points: Vec<Vec3> = Vec::new();
131 let mut owners: Vec<u64> = Vec::new(); for coedge in &face.loops[0].coedges {
133 let edge = solid.edges.iter().find(|x| x.id == coedge.edge_id).ok_or_else(|| unsupported("full_round_prism", "a loop edge is missing".into()))?;
134 if edge.curve.degree != 1 || edge.curve.control_points.len() != 2 {
135 return Err(unsupported("full_round_prism", "the solid is not a prism on a polygon".into()));
136 }
137 let a = edge.curve.evaluate(if coedge.forward { edge.t0 } else { edge.t1 }).or_refuse(KernelStage::Classify, "evaluate")?;
138 points.push(a);
139 let other = faces.iter().find(|f| f.id != face.id && f.loops.iter().flat_map(|l| l.coedges.iter()).any(|c| c.edge_id == edge.id)).map(|f| f.id).unwrap_or(0);
140 owners.push(other);
141 }
142 let n = points.len();
143 let Some(mi) = owners.iter().position(|&o| o == ids[1]) else { return Err(unsupported("full_round_faces", "the middle face does not meet the end face".into())) };
144 let (prev, next) = ((mi + n - 1) % n, (mi + 1) % n);
145 let (ia, ib) = if owners[prev] == ids[0] && owners[next] == ids[2] {
146 (prev, next)
147 } else if owners[prev] == ids[2] && owners[next] == ids[0] {
148 (prev, next)
149 } else {
150 return Err(unsupported("full_round_faces", "the side faces do not both border the middle face".into()));
151 };
152 let inward = |k: usize| -> Vec3 {
155 let id = owners[k];
156 let (n, _) = plane_of(faces.iter().find(|f| f.id == id).expect("face")).expect("planar");
157 n.scale(-1.0)
158 };
159 let on_line = |k: usize| points[k];
160 let rows: Vec<(Vec3, Vec3)> = [ia, mi, ib].iter().map(|&k| (inward(k), on_line(k))).collect();
161 let x_axis = rows[1].0.cross(e).normalized().or_refuse(KernelStage::Classify, "normalized")?;
163 let y_axis = e.cross(x_axis);
164 let origin = points[mi];
165 let to2 = |v: Vec3| [v.dot(x_axis), v.dot(y_axis)];
166 let m: Vec<[f64; 4]> = rows.iter().map(|(nv, p)| { let n2 = to2(*nv); [n2[0], n2[1], -1.0, n2[0] * to2(p.sub(origin))[0] + n2[1] * to2(p.sub(origin))[1]] }).collect();
167 let det3 = |a: [[f64; 3]; 3]| a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1]) - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0]) + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0]);
168 let a = [[m[0][0], m[0][1], m[0][2]], [m[1][0], m[1][1], m[1][2]], [m[2][0], m[2][1], m[2][2]]];
169 let d = det3(a);
170 if d.abs() < 1e-12 {
171 return Err(unsupported("full_round_circle", "no circle touches the three faces".into()));
172 }
173 let column = |c: usize| { let mut b = a; for r in 0..3 { b[r][c] = m[r][3]; } det3(b) / d };
174 let (cx, cy, rho) = (column(0), column(1), column(2));
175 if !(rho > 0.0) {
176 return Err(unsupported("full_round_circle", "the circle touching the three faces lies outside the solid".into()));
177 }
178 let centre = origin.add(x_axis.scale(cx)).add(y_axis.scale(cy));
179 let touch = |k: usize| { let (nv, _) = rows[k]; centre.sub(nv.scale(rho)) };
180 let (ta, tm, tb) = (touch(0), touch(1), touch(2));
181 let within = |p: Vec3, a: Vec3, b: Vec3| { let ab = b.sub(a); let f = p.sub(a).dot(ab) / ab.dot(ab); f >= -1e-9 && f <= 1.0 + 1e-9 };
183 if !(within(ta, points[ia], points[(ia + 1) % n]) && within(tm, points[mi], points[(mi + 1) % n]) && within(tb, points[ib], points[(ib + 1) % n])) {
184 return Err(unsupported("full_round_contacts", "the round's contacts do not all lie on their faces".into()));
185 }
186 let (arc_u, arc_w, arc_sweep) = {
190 let (ra, rm, rb) = (ta.sub(centre), tm.sub(centre), tb.sub(centre));
191 let u = ra.normalized().or_refuse(KernelStage::Fragment, "normalized")?;
192 let mut w = e.cross(u);
193 let angle = |r: Vec3, w: Vec3| { let a = r.dot(w).atan2(r.dot(u)); if a < 0.0 { a + std::f64::consts::TAU } else { a } };
194 if angle(rm, w) > angle(rb, w) {
195 w = w.scale(-1.0);
196 }
197 let sweep = angle(rb, w);
198 (u, w, sweep)
199 };
200 for k in 0..n {
201 if k == ia || k == mi || k == ib {
202 continue;
203 }
204 let (a, b) = (points[k], points[(k + 1) % n]);
205 for j in 0..=512 {
206 let p = a.add(b.sub(a).scale(j as f64 / 512.0));
207 let r = p.sub(centre);
208 if r.length() >= rho * (1.0 - 1e-9) {
209 continue;
210 }
211 let at = r.dot(arc_w).atan2(r.dot(arc_u));
212 let at = if at < 0.0 { at + std::f64::consts::TAU } else { at };
213 if at > 1e-9 && at < arc_sweep - 1e-9 {
214 return Err(unsupported("full_round_clearance", format!("the round of radius {rho:.6} would cross another face of the section")));
215 }
216 }
217 }
218 let mut curves: Vec<NurbsCurve> = Vec::new();
220 let line = |p: Vec3, q: Vec3| make_line(p, q).or_refuse(KernelStage::Fragment, "make_line");
221 let mut k = (ib + 1) % n;
222 while k != ia {
224 let next_k = (k + 1) % n;
225 curves.push(line(points[k], points[next_k])?);
226 k = next_k;
227 }
228 if points[ia].sub(ta).length() > 1e-12 {
229 curves.push(line(points[ia], ta)?);
230 }
231 let (ra, rm, rb) = (ta.sub(centre), tm.sub(centre), tb.sub(centre));
233 let u = ra.normalized().or_refuse(KernelStage::Fragment, "normalized")?;
234 let mut w = e.cross(u);
235 let angle = |r: Vec3, w: Vec3| { let a = r.dot(w).atan2(r.dot(u)); if a < 0.0 { a + std::f64::consts::TAU } else { a } };
236 if angle(rm, w) > angle(rb, w) {
237 w = w.scale(-1.0);
238 }
239 let sweep = angle(rb, w);
240 curves.push(crate::make_arc(centre, u, w, rho, 0.0, sweep).or_refuse(KernelStage::Fragment, "make_arc")?);
241 let after = (ib + 1) % n;
242 if tb.sub(points[after]).length() > 1e-12 {
243 curves.push(line(tb, points[after])?);
244 }
245 let mut result = extrude_profile_brep(&curves, e, length)?;
246 let old: Vec<(Vec3, Vec3, Option<String>)> = faces.iter().filter_map(|f| plane_of(f).map(|(n, on)| (n, on, f.name.clone()))).collect();
249 for face in &mut result.shells[0].faces {
250 match plane_of(face) {
251 Some((n, on)) => {
252 if let Some((_, _, old_name)) = old.iter().find(|(m, at, _)| m.dot(n) > 1.0 - 1e-9 && m.dot(on.sub(*at)).abs() <= 1e-9 * size) {
253 face.name = old_name.clone();
254 }
255 }
256 None => {
257 if let Some(name) = name {
258 face.name = Some(name.to_string());
259 }
260 }
261 }
262 }
263 if result.validate().iter().any(|i| i.severity == "error") {
264 return Err(KernelRefusal::internal(KernelStage::Validate, "full_round_result", format!("{ENTRY}: the rebuilt prism does not validate")));
265 }
266 Ok(result)
267}