1use crate::gears::ShellBuilder;
6use crate::{BrepSolid, KernelRefusal, KernelStage, NurbsCurve, Vec3, Vec4};
7
8fn refuse(code: &str, message: String) -> KernelRefusal {
9 KernelRefusal::input(KernelStage::Collect, code, message)
10}
11
12#[derive(Clone, Copy)]
14struct Plane {
15 origin: Vec3,
16 x: Vec3,
17 y: Vec3,
18 n: Vec3,
19}
20
21impl Plane {
22 fn coords(&self, p: Vec3) -> [f64; 2] {
23 let d = p.sub(self.origin);
24 [d.dot(self.x), d.dot(self.y)]
25 }
26
27 fn flipped(self) -> Plane {
28 let n = self.n.scale(-1.0);
29 Plane { origin: self.origin, x: self.x, y: n.cross(self.x), n }
30 }
31}
32
33fn loop_samples(curves: &[NurbsCurve]) -> Result<Vec<Vec3>, KernelRefusal> {
35 let mut points = Vec::with_capacity(32 * curves.len());
36 for curve in curves {
37 let [t0, t1] = curve.domain().map_err(|e| refuse("profile_curve", e))?;
38 for i in 0..32 {
39 points.push(curve.evaluate(t0 + (t1 - t0) * i as f64 / 32.0).map_err(|e| refuse("profile_curve", e))?);
40 }
41 }
42 Ok(points)
43}
44
45fn signed_area(points: &[[f64; 2]]) -> f64 {
46 (0..points.len()).map(|i| {
47 let (p, q) = (points[i], points[(i + 1) % points.len()]);
48 p[0] * q[1] - q[0] * p[1]
49 }).sum::<f64>() / 2.0
50}
51
52fn inside(point: [f64; 2], polygon: &[[f64; 2]]) -> bool {
53 let mut crossings = 0;
54 for i in 0..polygon.len() {
55 let (a, b) = (polygon[i], polygon[(i + 1) % polygon.len()]);
56 if (a[1] > point[1]) != (b[1] > point[1]) {
57 let x = a[0] + (point[1] - a[1]) / (b[1] - a[1]) * (b[0] - a[0]);
58 if x > point[0] {
59 crossings += 1;
60 }
61 }
62 }
63 crossings % 2 == 1
64}
65
66fn profile_plane(outer: &[NurbsCurve], holes: &[Vec<NurbsCurve>]) -> Result<(Plane, Vec<f64>), KernelRefusal> {
70 if outer.is_empty() || holes.iter().any(|h| h.is_empty()) {
71 return Err(refuse("profile_empty", "A profile loop needs at least one curve.".into()));
72 }
73 let loops: Vec<&[NurbsCurve]> = std::iter::once(outer).chain(holes.iter().map(|h| h.as_slice())).collect();
74 let samples: Vec<Vec<Vec3>> = loops.iter().map(|l| loop_samples(l)).collect::<Result<_, _>>()?;
75 let scale = samples.iter().flatten().map(|p| p.x.abs().max(p.y.abs()).max(p.z.abs())).fold(1.0_f64, f64::max);
76 let tolerance = 1e-7 * scale;
77 for (index, curves) in loops.iter().enumerate() {
78 for (i, curve) in curves.iter().enumerate() {
79 let next = &curves[(i + 1) % curves.len()];
80 let [_, t1] = curve.domain().map_err(|e| refuse("profile_curve", e))?;
81 let [s0, _] = next.domain().map_err(|e| refuse("profile_curve", e))?;
82 let (end, start) = (curve.evaluate(t1).map_err(|e| refuse("profile_curve", e))?, next.evaluate(s0).map_err(|e| refuse("profile_curve", e))?);
83 if end.sub(start).length() > tolerance.max(1e-9) * 10.0 {
84 return Err(refuse("profile_open", format!("Profile loop {index} is not closed: curve {i} ends {:.3e} from the next curve's start.", end.sub(start).length())));
85 }
86 }
87 }
88 let outer_points = &samples[0];
89 let mut normal = Vec3::new(0.0, 0.0, 0.0);
90 for i in 0..outer_points.len() {
91 let (p, q) = (outer_points[i], outer_points[(i + 1) % outer_points.len()]);
92 normal = normal.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)));
93 }
94 let n = normal.normalized().map_err(|_| refuse("profile_degenerate", "The outer loop encloses no area.".into()))?;
95 let origin = outer_points[0];
96 let x = n.perpendicular().map_err(|e| refuse("profile_degenerate", e))?;
97 let plane = Plane { origin, x, y: n.cross(x), n };
98 for points in &samples {
99 for p in points {
100 let off = p.sub(origin).dot(n).abs();
101 if off > 1e-6 * scale {
102 return Err(refuse("profile_not_planar", format!("The profile is not planar: a point lies {off:.3e} off its plane.")));
103 }
104 }
105 }
106 let flat: Vec<Vec<[f64; 2]>> = samples.iter().map(|points| points.iter().map(|p| plane.coords(*p)).collect()).collect();
107 let areas: Vec<f64> = flat.iter().map(|points| signed_area(points)).collect();
108 for (index, points) in flat.iter().enumerate().skip(1) {
109 if !points.iter().all(|p| inside(*p, &flat[0])) {
110 return Err(refuse("hole_outside", format!("Hole {} is not inside the outer loop.", index - 1)));
111 }
112 }
113 Ok((plane, areas))
114}
115
116fn translated(curve: &NurbsCurve, by: Vec3) -> Result<NurbsCurve, KernelRefusal> {
117 NurbsCurve::new(
118 curve.degree,
119 curve.knots.clone(),
120 curve.control_points.iter().map(|p| Vec4 { x: p.x + p.w * by.x, y: p.y + p.w * by.y, z: p.z + p.w * by.z, w: p.w }).collect(),
121 )
122 .map_err(|e| refuse("profile_curve", e))
123}
124
125fn finish(shell: ShellBuilder, genus: usize, what: &str) -> Result<BrepSolid, KernelRefusal> {
126 let mut shell = shell;
127 let id = shell.id();
128 let shell_id = shell.id();
129 let solid = BrepSolid {
130 mass_properties_cache: Default::default(),
131 cells: Default::default(),
132 id,
133 vertices: shell.vertices,
134 edges: shell.edges,
135 shells: vec![crate::sweep_topology::ShellRecord { id: shell_id, faces: shell.faces }],
136 genus: genus as _,
137 kind: crate::BodyKind::Solid,
138 };
139 let issues = solid.validate();
140 if !issues.is_empty() {
141 return Err(KernelRefusal::internal(KernelStage::Validate, "validate", format!("{what} is not valid: {issues:?}")));
142 }
143 Ok(solid)
144}
145
146pub fn extrude_profile_with_holes(outer: &[NurbsCurve], holes: &[Vec<NurbsCurve>], direction: Vec3, distance: f64) -> Result<BrepSolid, KernelRefusal> {
152 use crate::sweep_topology::{curve_to_plane_parameters, make_plane, parameter_line};
153 let travel = direction.normalized().map_err(|_| refuse("direction", "The extrusion direction must be nonzero.".into()))?.scale(distance);
154 let (mut plane, mut areas) = profile_plane(outer, holes)?;
155 let along = travel.dot(plane.n);
156 if !(distance.is_finite() && along.abs() > 1e-9 * travel.length().max(1e-300)) {
157 return Err(refuse("direction", "The extrusion must leave the profile's plane (a nonzero distance, not along the plane).".into()));
158 }
159 if along < 0.0 {
160 plane = plane.flipped();
161 areas.iter_mut().for_each(|a| *a = -*a);
162 }
163 let line = |a: [f64; 2], b: [f64; 2]| parameter_line(a[0], a[1], b[0], b[1]).map_err(|e| refuse("profile_pcurve", e));
164 let point_of = |p: Vec4| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w);
165 let mut shell = ShellBuilder { vertices: Vec::new(), edges: Vec::new(), faces: Vec::new(), next: 0 };
166 let loops: Vec<&[NurbsCurve]> = std::iter::once(outer).chain(holes.iter().map(|h| h.as_slice())).collect();
167 let mut bottoms: Vec<Vec<u64>> = Vec::with_capacity(loops.len());
168 let mut tops: Vec<Vec<u64>> = Vec::with_capacity(loops.len());
169 for (index, curves) in loops.iter().enumerate() {
170 let count = curves.len();
171 let (mut b, mut t, mut axial) = (Vec::with_capacity(count), Vec::with_capacity(count), Vec::with_capacity(count));
172 for curve in curves.iter() {
173 let p = point_of(curve.control_points[0]);
174 let (vb, vt) = (shell.vertex(p), shell.vertex(p.add(travel)));
175 axial.push(shell.edge(crate::make_line(p, p.add(travel)).map_err(|e| refuse("profile_edge", e))?, vb, vt)?);
176 b.push(vb);
177 t.push(vt);
178 }
179 let (mut bottom_e, mut top_e) = (Vec::with_capacity(count), Vec::with_capacity(count));
180 for (i, curve) in curves.iter().enumerate() {
181 let next = (i + 1) % count;
182 bottom_e.push(shell.edge(curve.clone(), b[i], b[next])?);
183 top_e.push(shell.edge(translated(curve, travel)?, t[i], t[next])?);
184 }
185 let counter_clockwise = areas[index] > 0.0;
188 let same_sense = counter_clockwise == (index == 0);
189 for (i, curve) in curves.iter().enumerate() {
190 let next = (i + 1) % count;
191 let [u0, u1] = curve.domain().map_err(|e| refuse("profile_curve", e))?;
192 let surface = crate::make_extrusion(curve, travel).map_err(|e| refuse("profile_surface", e))?;
193 let loops = vec![vec![
194 (bottom_e[i], true, line([u0, 0.0], [u1, 0.0])?),
195 (axial[next], true, line([u1, 0.0], [u1, 1.0])?),
196 (top_e[i], false, line([u0, 1.0], [u1, 1.0])?),
197 (axial[i], false, line([u0, 0.0], [u0, 1.0])?),
198 ]];
199 let name = if index == 0 { format!("W{i}") } else { format!("H{}_{i}", index - 1) };
200 shell.face(surface, same_sense, loops, name)?;
201 }
202 bottoms.push(bottom_e);
203 tops.push(top_e);
204 }
205 let flat: Vec<[f64; 2]> = loop_samples(outer)?.iter().map(|p| plane.coords(*p)).collect();
207 let (lo, hi) = flat.iter().fold(([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]), |(lo, hi), p| ([lo[0].min(p[0]), lo[1].min(p[1])], [hi[0].max(p[0]), hi[1].max(p[1])]));
208 let pad = 0.1 * (hi[0] - lo[0]).max(hi[1] - lo[1]) + 1e-6;
209 let corner = plane.origin.add(plane.x.scale(lo[0] - pad)).add(plane.y.scale(lo[1] - pad));
210 let (size_x, size_y) = (hi[0] - lo[0] + 2.0 * pad, hi[1] - lo[1] + 2.0 * pad);
211 for (shift, edges, name, same_sense) in [(Vec3::new(0.0, 0.0, 0.0), &bottoms, "B", false), (travel, &tops, "T", true)] {
212 let origin = corner.add(shift);
213 let mut face_loops = Vec::with_capacity(edges.len());
214 for loop_edges in edges.iter() {
215 let mut coedges = Vec::with_capacity(loop_edges.len());
216 for &edge in loop_edges {
217 let pcurve = curve_to_plane_parameters(shell.curve(edge), origin, plane.x, plane.y).map_err(|e| refuse("profile_pcurve", e))?;
218 coedges.push((edge, true, pcurve));
219 }
220 face_loops.push(coedges);
221 }
222 let surface = make_plane(origin, plane.x, plane.y, size_x, size_y).map_err(|e| refuse("profile_plane", e))?;
223 shell.face(surface, same_sense, face_loops, name.into())?;
224 }
225 finish(shell, holes.len(), "extruded profile")
226}
227
228pub fn revolve_profile_with_holes(outer: &[NurbsCurve], holes: &[Vec<NurbsCurve>], axis_point: Vec3, axis_direction: Vec3, angle: f64) -> Result<BrepSolid, KernelRefusal> {
234 let (plane, _) = profile_plane(outer, holes)?;
235 let axis = axis_direction.normalized().map_err(|_| refuse("axis", "The revolve axis must be nonzero.".into()))?;
236 if axis.dot(plane.n).abs() > 1e-9 || axis_point.sub(plane.origin).dot(plane.n).abs() > 1e-6 * (1.0 + axis_point.length()) {
237 return Err(refuse("axis", "The revolve axis must lie in the profile's plane.".into()));
238 }
239 let revolve = |curves: &[NurbsCurve]| crate::revolve_profile_brep(curves, axis_point, axis, angle).map_err(|e| refuse("revolve", e));
240 let mut solid = revolve(outer)?;
241 if holes.is_empty() {
242 return Ok(solid);
243 }
244 for (index, hole) in holes.iter().enumerate() {
245 let near = loop_samples(hole)?.iter().map(|p| { let d = p.sub(axis_point); d.sub(axis.scale(d.dot(axis))).length() }).fold(f64::INFINITY, f64::min);
247 if !(near > 1e-9 * (1.0 + axis_point.length())) {
248 return Err(refuse("hole_on_axis", format!("Hole {index} touches the revolve axis.")));
249 }
250 let cutter = revolve(hole)?;
251 solid = crate::boolean_operation_nary(&[solid, cutter], crate::BooleanOperation::Subtract)?;
252 }
253 Ok(solid)
254}
255