1use crate::{face_area, solid_piece_by_plane, BrepSolid, FaceRecord, KernelRefusal, KernelStage, NurbsCurve, Vec3};
13
14const COVERS: [f64; 4] = [1.2, 1.5, 2.0, 3.0];
17
18fn caps(solid: &BrepSolid, origin: Vec3, normal: Vec3) -> Result<Option<(BrepSolid, Vec<usize>)>, KernelRefusal> {
31 let unit = normal
32 .normalized()
33 .map_err(|_| KernelRefusal::input(KernelStage::Collect, "section_normal", "section: the plane normal has no direction"))?;
34 let refuse = |message: String| KernelRefusal::internal(KernelStage::Fragment, "section_split", format!("section: {message}"));
35 let surfaces = solid.shells.iter().flat_map(|shell| &shell.faces).flat_map(|face| face.surface.control_points.iter().flatten());
36 let curves = solid.edges.iter().flat_map(|edge| edge.curve.control_points.iter());
37 let (mut low, mut high) = (f64::INFINITY, f64::NEG_INFINITY);
38 for control in surfaces.chain(curves) {
39 let height = control.point().map_err(|message| refuse(message))?.sub(origin).dot(unit);
40 low = low.min(height);
41 high = high.max(height);
42 }
43 if !(low < 0.0 && high > 0.0) {
44 return Ok(None);
45 }
46 let mut declined = Vec::new();
47 let mut found = None;
48 'covers: for cover in COVERS {
49 for above in [false, true] {
50 match solid_piece_by_plane(solid, origin, unit, above, cover) {
51 Ok(piece) => {
52 found = Some(piece);
53 break 'covers;
54 }
55 Err(message) => declined.push(message),
56 }
57 }
58 }
59 let Some(piece) = found else {
60 return Err(refuse(declined.join("; ")));
61 };
62 let Some(piece) = piece else {
64 return Ok(None);
65 };
66 let extent = piece.vertices.iter().fold(0.0f64, |extent, vertex| {
67 extent.max(vertex.point.x.abs()).max(vertex.point.y.abs()).max(vertex.point.z.abs())
68 });
69 let scale = 1.0 + extent;
70 let tolerance = 1e-9 * scale;
71 let on_plane = |face: &FaceRecord| -> bool {
72 if !face.surface.is_affine().unwrap_or(false) {
73 return false;
74 }
75 face.surface.control_points.iter().flatten().all(|control| {
76 control.point().is_ok_and(|point| point.sub(origin).dot(unit).abs() <= tolerance)
77 })
78 };
79 let faces: Vec<usize> = piece.shells.iter().flat_map(|shell| &shell.faces).enumerate().filter(|(_, face)| on_plane(face)).map(|(index, _)| index).collect();
80 if faces.is_empty() {
81 let other = declined.len() % 2 == 0;
88 let mut other_declined = Vec::new();
89 for cover in COVERS {
90 match solid_piece_by_plane(solid, origin, unit, other, cover) {
91 Ok(None) => return Ok(None),
92 Ok(Some(other_piece)) => {
93 if lumps_part(solid, &piece, &other_piece, origin, unit, other, tolerance) {
94 return Ok(None);
95 }
96 return Err(refuse("the solid lies on both sides of the plane but the cut left no face on it".into()));
97 }
98 Err(message) => other_declined.push(message),
99 }
100 }
101 return Err(refuse(format!(
102 "the cut left no face on the plane, and the other side declined: {}",
103 other_declined.join("; ")
104 )));
105 }
106 Ok(Some((piece, faces)))
107}
108
109fn lumps_part(solid: &BrepSolid, first: &BrepSolid, second: &BrepSolid, origin: Vec3, unit: Vec3, second_above: bool, tolerance: f64) -> bool {
116 let faces = |body: &BrepSolid| body.shells.iter().map(|shell| shell.faces.len()).sum::<usize>();
117 if faces(first) + faces(second) != faces(solid) {
118 return false;
119 }
120 let side = |body: &BrepSolid, above: bool| {
121 body.vertices.iter().all(|vertex| {
122 let height = vertex.point.sub(origin).dot(unit);
123 if above { height > tolerance } else { height < -tolerance }
124 })
125 };
126 if !(side(first, !second_above) && side(second, second_above)) {
127 return false;
128 }
129 match (crate::solid_mass_properties(solid), crate::solid_mass_properties(first), crate::solid_mass_properties(second)) {
130 (Ok(whole), Ok(a), Ok(b)) => (a.volume + b.volume - whole.volume).abs() <= 1e-6 * whole.volume.abs().max(f64::MIN_POSITIVE),
133 _ => false,
134 }
135}
136
137fn sample_edge(curve: &NurbsCurve, t0: f64, t1: f64, tolerance: f64) -> Result<Vec<Vec3>, String> {
141 let (low, high) = (t0.min(t1), t0.max(t1));
142 let mut breaks: Vec<f64> = vec![low];
143 breaks.extend(curve.knots.iter().copied().filter(|&knot| knot > low && knot < high));
144 breaks.push(high);
145 breaks.dedup();
146 let chord_error = |a: f64, b: f64| -> Result<f64, String> {
147 let (p, q) = (curve.evaluate(a)?, curve.evaluate(b)?);
148 let chord = q.sub(p);
149 let length = chord.length();
150 let mut worst = 0.0f64;
151 for fraction in [0.25, 0.5, 0.75] {
152 let point = curve.evaluate(a + (b - a) * fraction)?;
153 let offset = point.sub(p);
154 let along = if length > 0.0 { offset.dot(chord) / (length * length) } else { 0.0 };
155 worst = worst.max(offset.sub(chord.scale(along.clamp(0.0, 1.0))).length());
156 }
157 Ok(worst)
158 };
159 let mut parameters = vec![low];
160 for pair in breaks.windows(2) {
161 let mut start = pair[0];
163 let mut pending = vec![(pair[1], 0u32)];
164 while let Some((end, depth)) = pending.pop() {
165 if depth < 24 && chord_error(start, end)? > tolerance {
166 let middle = 0.5 * (start + end);
167 pending.push((end, depth + 1));
168 pending.push((middle, depth + 1));
169 continue;
170 }
171 parameters.push(end);
172 start = end;
173 }
174 }
175 let mut points = parameters.iter().map(|&t| curve.evaluate(t)).collect::<Result<Vec<_>, _>>()?;
176 if t1 < t0 {
177 points.reverse();
178 }
179 Ok(points)
180}
181
182pub fn solid_section(
189 solid: &BrepSolid,
190 origin: Vec3,
191 normal: Vec3,
192 chord_tolerance: f64,
193) -> Result<Vec<Vec<Vec3>>, KernelRefusal> {
194 if !(chord_tolerance > 0.0 && chord_tolerance.is_finite()) {
195 return Err(KernelRefusal::input(KernelStage::Collect, "section_tolerance", "section: the chord tolerance must be positive"));
196 }
197 let Some((below, faces)) = caps(solid, origin, normal)? else {
198 return Ok(Vec::new());
199 };
200 let all: Vec<&FaceRecord> = below.shells.iter().flat_map(|shell| &shell.faces).collect();
201 let mut pieces = Vec::new();
202 for index in faces {
203 for coedge in all[index].loops.iter().flat_map(|loop_record| &loop_record.coedges) {
204 let edge = below.edges.iter().find(|edge| edge.id == coedge.edge_id).ok_or_else(|| {
205 KernelRefusal::internal(KernelStage::Collect, "section_edge", format!("section: edge {} is missing", coedge.edge_id))
206 })?;
207 if edge.degenerate {
208 continue;
209 }
210 let points = sample_edge(&edge.curve, edge.t0, edge.t1, chord_tolerance)
211 .map_err(|message| KernelRefusal::internal(KernelStage::Collect, "section_sample", format!("section: {message}")))?;
212 pieces.push(points);
213 }
214 }
215 Ok(pieces)
216}
217
218pub fn solid_section_area(solid: &BrepSolid, origin: Vec3, normal: Vec3) -> Result<f64, KernelRefusal> {
222 let Some((below, faces)) = caps(solid, origin, normal)? else {
223 return Ok(0.0);
224 };
225 let all: Vec<&FaceRecord> = below.shells.iter().flat_map(|shell| &shell.faces).collect();
226 let mut area = 0.0;
227 for index in faces {
228 area += face_area(all[index])
229 .map_err(|message| KernelRefusal::internal(KernelStage::Collect, "section_area", format!("section area: {message}")))?;
230 }
231 Ok(area)
232}
233