1use crate::{face_area, shell_vector_areas, solid_piece_by_plane, BrepSolid, FaceRecord, KernelRefusal, KernelStage, NurbsCurve, Vec3};
13
14fn sub_band_area_enabled() -> bool {
18 crate::switch!("BREP_SECTION_SUB_BAND_AREA", true)
19}
20
21enum Cut {
23 Miss,
25 Caps(BrepSolid, Vec<usize>),
27 SubBand(f64),
31}
32
33const COVERS: [f64; 4] = [1.2, 1.5, 2.0, 3.0];
36
37fn caps(solid: &BrepSolid, origin: Vec3, normal: Vec3) -> Result<Cut, KernelRefusal> {
50 let unit = normal
51 .normalized()
52 .map_err(|_| KernelRefusal::input(KernelStage::Collect, "section_normal", "section: the plane normal has no direction"))?;
53 let refuse = |message: String| KernelRefusal::internal(KernelStage::Fragment, "section_split", format!("section: {message}"));
54 let surfaces = solid.shells.iter().flat_map(|shell| &shell.faces).flat_map(|face| face.surface.control_points.iter().flatten());
55 let curves = solid.edges.iter().flat_map(|edge| edge.curve.control_points.iter());
56 let (mut low, mut high) = (f64::INFINITY, f64::NEG_INFINITY);
57 for control in surfaces.chain(curves) {
58 let height = control.point().map_err(|message| refuse(message))?.sub(origin).dot(unit);
59 low = low.min(height);
60 high = high.max(height);
61 }
62 if !(low < 0.0 && high > 0.0) {
63 return Ok(Cut::Miss);
64 }
65 let mut declined = Vec::new();
66 let mut found = None;
67 'covers: for cover in COVERS {
68 for above in [false, true] {
69 match solid_piece_by_plane(solid, origin, unit, above, cover) {
70 Ok(piece) => {
71 found = Some((piece, above));
72 break 'covers;
73 }
74 Err(message) => declined.push(message),
75 }
76 }
77 }
78 let Some((piece, piece_above)) = found else {
79 return Err(refuse(declined.join("; ")));
80 };
81 let Some(piece) = piece else {
83 return Ok(Cut::Miss);
84 };
85 let extent = piece.vertices.iter().fold(0.0f64, |extent, vertex| {
86 extent.max(vertex.point.x.abs()).max(vertex.point.y.abs()).max(vertex.point.z.abs())
87 });
88 let scale = 1.0 + extent;
89 let tolerance = 1e-9 * scale;
90 let on_plane = |face: &FaceRecord| -> bool {
91 if !face.surface.is_affine().unwrap_or(false) {
92 return false;
93 }
94 face.surface.control_points.iter().flatten().all(|control| {
95 control.point().is_ok_and(|point| point.sub(origin).dot(unit).abs() <= tolerance)
96 })
97 };
98 let faces: Vec<usize> = piece.shells.iter().flat_map(|shell| &shell.faces).enumerate().filter(|(_, face)| on_plane(face)).map(|(index, _)| index).collect();
99 if faces.is_empty() {
100 let other = !piece_above;
107 let mut other_declined = Vec::new();
108 for cover in COVERS {
109 match solid_piece_by_plane(solid, origin, unit, other, cover) {
110 Ok(None) => return Ok(Cut::Miss),
111 Ok(Some(other_piece)) => {
112 if lumps_part(solid, &piece, &other_piece, origin, unit, other, tolerance) {
113 return Ok(Cut::Miss);
114 }
115 if sub_band_area_enabled() {
116 if let Some(area) = sub_band_area(solid, &piece, &other_piece, unit, piece_above) {
117 return Ok(Cut::SubBand(area));
118 }
119 }
120 return Err(refuse("the solid lies on both sides of the plane but the cut left no face on it".into()));
121 }
122 Err(message) => other_declined.push(message),
123 }
124 }
125 return Err(refuse(format!(
126 "the cut left no face on the plane, and the other side declined: {}",
127 other_declined.join("; ")
128 )));
129 }
130 Ok(Cut::Caps(piece, faces))
131}
132
133fn sub_band_area(solid: &BrepSolid, piece: &BrepSolid, other: &BrepSolid, unit: Vec3, piece_above: bool) -> Option<f64> {
147 let residual = |body: &BrepSolid| -> Option<(Vec3, f64)> {
150 let report = shell_vector_areas(body);
151 if !report.unreadable.is_empty() || report.shells.is_empty() {
152 return None;
153 }
154 let mut sum = Vec3::new(0.0, 0.0, 0.0);
155 let mut error = 0.0;
156 for shell in &report.shells {
157 if !shell.closed || shell.gave_up || !shell.trim_residual.length().is_finite() {
158 return None;
159 }
160 sum = sum.add(shell.trim_residual);
161 error += shell.quadrature_error;
162 }
163 Some((sum, error))
164 };
165 let (whole, whole_error) = residual(solid)?;
166 let (first, first_error) = residual(piece)?;
167 let (second, second_error) = residual(other)?;
168 let (above, below) = if piece_above { (first, second) } else { (second, first) };
170 let (area_above, area_below) = (above.dot(unit), -below.dot(unit));
171 if !(area_above > 0.0 && area_below > 0.0) {
172 return None;
173 }
174 let off = |vector: Vec3, along: f64| vector.sub(unit.scale(along)).length();
175 let noise = whole.length()
176 + off(above, area_above)
177 + off(below, -area_below)
178 + (area_above - area_below).abs()
179 + 10.0 * (whole_error + first_error + second_error);
180 let area = 0.5 * (area_above + area_below);
181 (area > 10.0 * noise).then_some(area)
182}
183
184fn lumps_part(solid: &BrepSolid, first: &BrepSolid, second: &BrepSolid, origin: Vec3, unit: Vec3, second_above: bool, tolerance: f64) -> bool {
191 let faces = |body: &BrepSolid| body.shells.iter().map(|shell| shell.faces.len()).sum::<usize>();
192 if faces(first) + faces(second) != faces(solid) {
193 return false;
194 }
195 let side = |body: &BrepSolid, above: bool| {
196 body.vertices.iter().all(|vertex| {
197 let height = vertex.point.sub(origin).dot(unit);
198 if above { height > tolerance } else { height < -tolerance }
199 })
200 };
201 if !(side(first, !second_above) && side(second, second_above)) {
202 return false;
203 }
204 match (crate::solid_mass_properties(solid), crate::solid_mass_properties(first), crate::solid_mass_properties(second)) {
205 (Ok(whole), Ok(a), Ok(b)) => (a.volume + b.volume - whole.volume).abs() <= 1e-6 * whole.volume.abs().max(f64::MIN_POSITIVE),
208 _ => false,
209 }
210}
211
212fn sample_edge(curve: &NurbsCurve, t0: f64, t1: f64, tolerance: f64) -> Result<Vec<Vec3>, String> {
216 let (low, high) = (t0.min(t1), t0.max(t1));
217 let mut breaks: Vec<f64> = vec![low];
218 breaks.extend(curve.knots.iter().copied().filter(|&knot| knot > low && knot < high));
219 breaks.push(high);
220 breaks.dedup();
221 let chord_error = |a: f64, b: f64| -> Result<f64, String> {
222 let (p, q) = (curve.evaluate(a)?, curve.evaluate(b)?);
223 let chord = q.sub(p);
224 let length = chord.length();
225 let mut worst = 0.0f64;
226 for fraction in [0.25, 0.5, 0.75] {
227 let point = curve.evaluate(a + (b - a) * fraction)?;
228 let offset = point.sub(p);
229 let along = if length > 0.0 { offset.dot(chord) / (length * length) } else { 0.0 };
230 worst = worst.max(offset.sub(chord.scale(along.clamp(0.0, 1.0))).length());
231 }
232 Ok(worst)
233 };
234 let mut parameters = vec![low];
235 for pair in breaks.windows(2) {
236 let mut start = pair[0];
238 let mut pending = vec![(pair[1], 0u32)];
239 while let Some((end, depth)) = pending.pop() {
240 if depth < 24 && chord_error(start, end)? > tolerance {
241 let middle = 0.5 * (start + end);
242 pending.push((end, depth + 1));
243 pending.push((middle, depth + 1));
244 continue;
245 }
246 parameters.push(end);
247 start = end;
248 }
249 }
250 let mut points = parameters.iter().map(|&t| curve.evaluate(t)).collect::<Result<Vec<_>, _>>()?;
251 if t1 < t0 {
252 points.reverse();
253 }
254 Ok(points)
255}
256
257pub fn solid_section(
264 solid: &BrepSolid,
265 origin: Vec3,
266 normal: Vec3,
267 chord_tolerance: f64,
268) -> Result<Vec<Vec<Vec3>>, KernelRefusal> {
269 if !(chord_tolerance > 0.0 && chord_tolerance.is_finite()) {
270 return Err(KernelRefusal::input(KernelStage::Collect, "section_tolerance", "section: the chord tolerance must be positive"));
271 }
272 let (below, faces) = match caps(solid, origin, normal)? {
273 Cut::Miss => return Ok(Vec::new()),
274 Cut::Caps(below, faces) => (below, faces),
275 Cut::SubBand(area) => {
276 return Err(KernelRefusal::internal(
277 KernelStage::Fragment,
278 "section_split",
279 format!(
280 "section: every region of the cut is thinner than the boolean's weld band (area {area:.3e}), \
281 so no face on the plane holds its curves"
282 ),
283 ))
284 }
285 };
286 let all: Vec<&FaceRecord> = below.shells.iter().flat_map(|shell| &shell.faces).collect();
287 let mut pieces = Vec::new();
288 for index in faces {
289 for coedge in all[index].loops.iter().flat_map(|loop_record| &loop_record.coedges) {
290 let edge = below.edges.iter().find(|edge| edge.id == coedge.edge_id).ok_or_else(|| {
291 KernelRefusal::internal(KernelStage::Collect, "section_edge", format!("section: edge {} is missing", coedge.edge_id))
292 })?;
293 if edge.degenerate {
294 continue;
295 }
296 let points = sample_edge(&edge.curve, edge.t0, edge.t1, chord_tolerance)
297 .map_err(|message| KernelRefusal::internal(KernelStage::Collect, "section_sample", format!("section: {message}")))?;
298 pieces.push(points);
299 }
300 }
301 Ok(pieces)
302}
303
304pub fn solid_section_area(solid: &BrepSolid, origin: Vec3, normal: Vec3) -> Result<f64, KernelRefusal> {
308 let (below, faces) = match caps(solid, origin, normal)? {
309 Cut::Miss => return Ok(0.0),
310 Cut::Caps(below, faces) => (below, faces),
311 Cut::SubBand(area) => return Ok(area),
312 };
313 let all: Vec<&FaceRecord> = below.shells.iter().flat_map(|shell| &shell.faces).collect();
314 let mut area = 0.0;
315 for index in faces {
316 area += face_area(all[index])
317 .map_err(|message| KernelRefusal::internal(KernelStage::Collect, "section_area", format!("section area: {message}")))?;
318 }
319 Ok(area)
320}
321