1use super::*;
136use crate::offset_retrim::plane_of_surface;
137use crate::topology::ShellRecord;
138use crate::{
139 boolean_operation, make_plane, BooleanOperation, BooleanOptions,
140
141};
142use crate::curve::parameter_line;
143use crate::{KernelRefusal, KernelStage, OrRefuse};
144
145const OP: &str = "move_faces(re-cut)";
146
147#[derive(Clone, Copy, Debug)]
149struct HalfSpace {
150 normal: Vec3,
151 offset: f64,
152}
153
154
155pub fn recut_moved_planes(
162 solid: &BrepSolid,
163 moved: &[u64],
164 translation: Vec3,
165) -> Result<BrepSolid, KernelRefusal> {
166 recut_moved_planes_rigid(solid, moved, None, translation)
167}
168
169struct Motion {
173 rotation: Option<AffineTransform>,
174 translation: Vec3,
175}
176
177impl Motion {
178 fn point(&self, point: Vec3) -> Vec3 {
179 match &self.rotation {
180 None => point.add(self.translation),
181 Some(rotation) => rotation.point(point).add(self.translation),
182 }
183 }
184
185 fn plane(&self, normal: Vec3, offset: f64) -> (Vec3, f64) {
189 match &self.rotation {
190 None => (normal, offset + self.translation.dot(normal)),
191 Some(rotation) => {
192 let turned = super::face_rotate::rotate_direction(rotation, normal);
193 (turned, turned.dot(self.point(normal.scale(offset))))
194 }
195 }
196 }
197}
198
199pub fn recut_moved_planes_rigid(
223 solid: &BrepSolid,
224 moved: &[u64],
225 rotation: Option<(Vec3, Vec3, f64)>,
226 translation: Vec3,
227) -> Result<BrepSolid, KernelRefusal> {
228 let scale = solid_model_scale(solid);
229 let tolerance = (scale * 1e-7).max(1e-9);
230 let moved_set: HashSet<u64> = moved.iter().copied().collect();
231 if moved_set.is_empty() {
232 return Err(KernelRefusal::input(
233 KernelStage::Collect,
234 "selection",
235 format!("{OP}: no face was selected"),
236 ));
237 }
238 let motion = Motion {
239 rotation: match rotation {
240 None => None,
241 Some((point, axis, angle)) => {
242 let axis = axis.normalized().map_err(|_| {
243 KernelRefusal::input(
244 KernelStage::Collect,
245 "rotation_axis",
246 format!("{OP}: the rotation axis has zero length"),
247 )
248 })?;
249 Some(
250 super::face_rotate::rotation_about(point, axis, angle)
251 .or_input(KernelStage::Collect, "rotation")?,
252 )
253 }
254 },
255 translation,
256 };
257
258 let mut carriers: Vec<(u64, Vec3, f64)> = Vec::new();
262 for &id in &moved_set {
263 let face = face_by_id(solid, id)?;
264 let plane = plane_of_surface(&face.surface, tolerance.max(1e-9) * 10.0, OP).map_err(
265 |error| {
266 KernelRefusal::unsupported(
267 KernelStage::Classify,
268 "curved_carrier",
269 format!(
270 "{error} — this road sweeps a PLANE's slab, so face {id}{} cannot take it",
271 named(face)
272 ),
273 )
274 },
275 )?;
276 let normal = if face.same_sense {
277 plane.normal
278 } else {
279 plane.normal.scale(-1.0)
280 };
281 carriers.push((id, normal, normal.dot(plane.origin)));
282 }
283 carriers.sort_by_key(|entry| entry.0);
285
286 let bounds = solid_bounds(solid)?;
291 let bounds = if motion.rotation.is_none() {
292 bounds
293 } else {
294 solid.vertices.iter().fold(bounds, |(low, high), vertex| {
295 let point = motion.point(vertex.point);
296 (
297 Vec3::new(low.x.min(point.x), low.y.min(point.y), low.z.min(point.z)),
298 Vec3::new(high.x.max(point.x), high.y.max(point.y), high.z.max(point.z)),
299 )
300 })
301 };
302 let margin = translation.length() + scale.max(1.0);
303 let clip = box_half_spaces(bounds, margin);
304
305 let motion_floor = (scale * 1e-9).max(1e-12);
306 let edge_band = (scale * 1e-7).max(1e-9);
307 let mut removing: Vec<BrepSolid> = Vec::new();
308 let mut adding: Vec<BrepSolid> = Vec::new();
309
310 for &(id, normal, offset) in &carriers {
311 let face = face_by_id(solid, id)?;
312 let (moved_normal, moved_offset) = motion.plane(normal, offset);
313 let facing = moved_normal.dot(normal);
314 if motion.rotation.is_some() && facing <= 1e-6 {
315 return Err(KernelRefusal::ill_posed(
316 KernelStage::Classify,
317 "turned_past_right_angle",
318 format!(
319 "{OP}: the motion turns face {id}{} through a right angle or more, so its \
320 new carrier does not face the way the old one did and there is no wedge \
321 between them for a tool to fill; refusing",
322 named(face)
323 ),
324 ));
325 }
326 let unturned = moved_normal.sub(normal).length() <= 1e-12;
327 let translation_delta = translation.dot(normal);
330 if motion.rotation.is_none() && translation_delta.abs() <= motion_floor {
331 continue;
333 }
334
335 let mut neighbour_planes: HashMap<u64, ((Vec3, f64), (Vec3, f64))> = HashMap::default();
338 let mut tangent_bands: HashSet<u64> = HashSet::default();
340 let polygon = trim_polygon(solid, face, normal, edge_band)?;
341 for source in &polygon.sources {
342 let &EdgeSource::Neighbour(neighbour) = source else { continue };
343 if neighbour_planes.contains_key(&neighbour) || tangent_bands.contains(&neighbour) {
344 continue;
345 }
346 let other = face_by_id(solid, neighbour)?;
347 if motion.rotation.is_some()
348 && !moved_set.contains(&neighbour)
349 && plane_of_surface(&other.surface, tolerance.max(1e-9) * 10.0, OP).is_err()
350 && band_is_tangent_along_shared_edges(face, other, normal)
351 {
352 tangent_bands.insert(neighbour);
353 continue;
354 }
355 let plane = plane_of_surface(&other.surface, tolerance.max(1e-9) * 10.0, OP)
356 .map_err(|error| {
357 KernelRefusal::unsupported(
358 KernelStage::Classify,
359 "curved_neighbour",
360 format!(
361 "{error} — face {id}{} is bounded by face {neighbour}{}, and this road \
362 needs every bounding carrier as a half-space",
363 named(face),
364 named(other)
365 ),
366 )
367 })?;
368 let outward = if other.same_sense {
369 plane.normal
370 } else {
371 plane.normal.scale(-1.0)
372 };
373 let home = (outward, outward.dot(plane.origin));
374 let left = if moved_set.contains(&neighbour) {
375 motion.plane(home.0, home.1)
376 } else {
377 home
378 };
379 neighbour_planes.insert(neighbour, (home, left));
380 }
381
382 let hinge = if unturned {
385 None
386 } else {
387 polygon.frame.hinge(normal, offset, moved_normal, moved_offset)
388 };
389 let cells = convex_cells(&polygon, hinge, edge_band, scale).map_err(|error| {
390 KernelRefusal::internal(
391 KernelStage::Classify,
392 "cell_split",
393 format!("{OP}: face {id}{}'s trim could not be cut into convex cells — {error}", named(face)),
394 )
395 })?;
396
397 let surround = if tangent_bands.is_empty() {
398 None
399 } else {
400 Some(tangent_surround(solid, face, normal, offset, &tangent_bands, &moved_set, tolerance)?)
401 };
402
403 for cell in &cells {
404 let seat = polygon.frame.lift(cell.centroid());
405 let delta = if motion.rotation.is_none() {
410 translation_delta
411 } else {
412 (moved_offset - moved_normal.dot(seat)) / facing
413 };
414 if delta.abs() <= motion_floor {
415 if unturned {
416 continue;
417 }
418 return Err(KernelRefusal::ill_posed(
419 KernelStage::Classify,
420 "turned_through_trim",
421 format!(
422 "{OP}: the motion turns face {id}{} about a line through its own trim, and a \
423 cell of the trim still sits on that line after the hinge split, so which way \
424 it moves is not decided by the geometry; refusing rather than choosing",
425 named(face)
426 ),
427 ));
428 }
429 let adds = delta > 0.0;
430
431 let (inner, outer) = if adds {
436 ((moved_normal, moved_offset), (normal, offset))
437 } else {
438 ((normal, offset), (moved_normal, moved_offset))
439 };
440 let wedge = |inner: (Vec3, f64), outer: (Vec3, f64)| {
441 [
442 HalfSpace { normal: inner.0, offset: inner.1 },
443 HalfSpace { normal: outer.0.scale(-1.0), offset: -outer.1 },
444 ]
445 };
446 let touches_band = cell.sources.iter().any(|source| {
449 matches!(source, EdgeSource::Neighbour(neighbour) if tangent_bands.contains(neighbour))
450 });
451 let (inner, outer) = match (&surround, adds && touches_band) {
452 (Some(surround), true) => (inner, (outer.0, outer.1 - surround.inner_wall_depth)),
453 _ => (inner, outer),
454 };
455 let mut spaces = clip.clone();
456 if let (Some(surround), true) = (&surround, touches_band) {
457 for plane in &surround.planes {
458 push_unique(
459 &mut spaces,
460 HalfSpace { normal: plane.0, offset: plane.1 },
461 tolerance,
462 );
463 }
464 }
465 if motion.rotation.is_none() {
466 spaces.push(HalfSpace {
469 normal,
470 offset: offset.max(offset + delta),
471 });
472 spaces.push(HalfSpace {
473 normal: normal.scale(-1.0),
474 offset: -offset.min(offset + delta),
475 });
476 } else {
477 spaces.extend(wedge(inner, outer));
478 }
479
480 let probe = seat.add(normal.scale(delta * 0.5));
484
485 let mut at_home: Vec<HalfSpace> = Vec::new();
488 let mut sides: Vec<HalfSpace> = Vec::new();
490
491 for (edge, source) in cell.sources.iter().enumerate() {
492 if matches!(source, EdgeSource::Neighbour(neighbour) if tangent_bands.contains(neighbour)) {
496 let plane = polygon.frame.edge_plane(cell, edge);
497 let home_sign = if plane.0.dot(seat) - plane.1 > 0.0 { -1.0 } else { 1.0 };
498 push_unique(
499 &mut at_home,
500 HalfSpace { normal: plane.0.scale(home_sign), offset: plane.1 * home_sign },
501 tolerance,
502 );
503 continue;
504 }
505 let (home, bound) = match source {
506 EdgeSource::Neighbour(neighbour) => {
507 let &(home, left) = neighbour_planes
508 .get(neighbour)
509 .expect("every neighbour's plane was read above");
510 let material_side = home.0.dot(seat) - home.1 < 0.0;
524 let bound = if material_side == adds { left } else { home };
525 (home, bound)
526 }
527 EdgeSource::Hinge => {
528 let plane = polygon.frame.edge_plane(cell, edge);
529 (plane, plane)
530 }
531 };
532 let reach = bound.0.dot(probe) - bound.1;
533 if reach.abs() <= tolerance {
534 return Err(KernelRefusal::ill_posed(
535 KernelStage::Classify,
536 "probe_on_carrier",
537 format!(
538 "{OP}: the probe point for face {id} lies ON the carrier of one of its \
539 bounds ({reach:.3e} from it), so which side of that carrier the tool \
540 is on is not decided by the geometry; refusing rather than choosing"
541 ),
542 ));
543 }
544 let sign = if reach > 0.0 { -1.0 } else { 1.0 };
545 let bound = HalfSpace {
546 normal: bound.0.scale(sign),
547 offset: bound.1 * sign,
548 };
549 let home_sign = if home.0.dot(seat) - home.1 > 0.0 { -1.0 } else { 1.0 };
552 push_unique(&mut spaces, bound, tolerance);
553 push_unique(&mut sides, bound, tolerance);
554 push_unique(
555 &mut at_home,
556 HalfSpace {
557 normal: home.0.scale(home_sign),
558 offset: home.1 * home_sign,
559 },
560 tolerance,
561 );
562 }
563 cell_is_its_bounds(face, cell, &polygon.frame, &at_home, scale)?;
564 if motion.rotation.is_some() {
565 let (home_inner, home_outer) = if adds {
566 ((moved_normal, moved_offset), (normal, offset))
567 } else {
568 ((normal, offset), (moved_normal, moved_offset))
569 };
570 one_way_only(id, &clip, &sides, wedge(home_outer, home_inner), tolerance, || named(face))?;
571 }
572
573 let tool = convex_solid(&spaces, probe, tolerance).map_err(|error| {
574 KernelRefusal::internal(
575 KernelStage::Fragment,
576 "tool_polytope",
577 format!("{OP}: the tool for face {id} could not be built — {error}"),
578 )
579 })?;
580 if adds {
581 adding.push(tool);
582 } else {
583 removing.push(tool);
584 }
585 }
586 }
587 if removing.is_empty() && adding.is_empty() {
588 return Err(KernelRefusal::input(
589 KernelStage::Classify,
590 "in_plane_motion",
591 format!(
592 "{OP}: every selected face slides inside its own carrier (the motion has no \
593 component along any of their normals), so there is no material for a re-cut to \
594 move"
595 ),
596 ));
597 }
598
599 let unite = |mut tools: Vec<BrepSolid>| -> Result<Option<BrepSolid>, KernelRefusal> {
607 if tools.is_empty() {
608 return Ok(None);
609 }
610 let mut tool = tools.remove(0);
611 for next in tools {
612 tool = boolean_operation(&tool, &next, BooleanOperation::Union, &BooleanOptions::default())
615 .map_err(|error| {
616 error.with_message(|message| {
617 format!("{OP}: the tools could not be unioned into one — {message}")
618 })
619 })?;
620 }
621 Ok(Some(tool))
622 };
623 let mut cut = solid.clone();
624 if let Some(tool) = unite(removing)? {
625 cut = boolean_operation(&cut, &tool, BooleanOperation::Subtract, &BooleanOptions::default())
626 .map_err(|error| {
627 error.with_message(|message| format!("{OP}: the re-cut's subtract refused — {message}"))
628 })?;
629 }
630 if let Some(tool) = unite(adding)? {
631 cut = boolean_operation(&cut, &tool, BooleanOperation::Union, &BooleanOptions::default())
632 .map_err(|error| {
633 error.with_message(|message| format!("{OP}: the re-cut's union refused — {message}"))
634 })?;
635 }
636 Ok(restamp(cut, solid, &moved_set, &motion, tolerance))
637}
638
639pub fn reblend_lost_fillets(original: &BrepSolid, moved: &[u64], mut body: BrepSolid) -> (BrepSolid, Vec<String>) {
647 let tolerance = (solid_model_scale(original) * 1e-6).max(1e-9);
648 let moved_set: HashSet<u64> = moved.iter().copied().collect();
649 let faces: HashMap<u64, &FaceRecord> =
650 original.shells.iter().flat_map(|shell| &shell.faces).map(|face| (face.id, face)).collect();
651 let mut owners: HashMap<u64, Vec<u64>> = HashMap::default();
652 for face in faces.values() {
653 for coedge in face.loops.iter().flat_map(|wire| &wire.coedges) {
654 owners.entry(coedge.edge_id).or_default().push(face.id);
655 }
656 }
657 let across = |face: &FaceRecord| -> Vec<u64> {
658 let mut found: Vec<u64> = face
659 .loops
660 .iter()
661 .flat_map(|wire| &wire.coedges)
662 .flat_map(|coedge| owners.get(&coedge.edge_id).into_iter().flatten().copied())
663 .filter(|id| *id != face.id)
664 .collect();
665 found.sort_unstable();
666 found.dedup();
667 found
668 };
669 let mut notes = Vec::new();
670 let mut ordered = moved.to_vec();
671 ordered.sort_unstable();
672 for id in ordered {
673 let Some(&face) = faces.get(&id) else { continue };
674 let Ok(plane) = plane_of_surface(&face.surface, tolerance * 10.0, OP) else { continue };
675 for band_id in across(face) {
676 let band = faces[&band_id];
677 let Some(band_name) = band.name.clone() else { continue };
678 if moved_set.contains(&band_id)
679 || plane_of_surface(&band.surface, tolerance * 10.0, OP).is_ok()
680 || !band_is_tangent_along_shared_edges(face, band, plane.normal)
681 || body.shells.iter().flat_map(|shell| &shell.faces).any(|f| f.name.as_deref() == Some(&band_name))
682 {
683 continue;
684 }
685 let radius = super::face_move::ruled_revolution_carrier(&band.surface)
690 .filter(|(_, rho0, rho1, _)| (rho0 - rho1).abs() <= tolerance)
691 .map(|(_, rho0, _, _)| rho0);
692 let (remade, radius_label) = match radius {
693 Some(rho0) => (
694 across(band)
695 .into_iter()
696 .filter(|wall| *wall != id)
697 .find_map(|wall| {
698 let wall = faces[&wall];
699 let wall_plane = plane_of_surface(&wall.surface, tolerance * 10.0, OP).ok()?;
700 band_is_tangent_along_shared_edges(wall, band, wall_plane.normal).then_some(wall)
701 })
702 .ok_or_else(|| "the wall beyond it could not be read".to_string())
703 .and_then(|wall| sharp_edge_between(&body, face, wall))
704 .and_then(|edge| {
705 let rebuilt =
706 crate::fillet_edge(&body, edge, rho0, Some(&band_name)).map_err(|e| e.to_string())?;
707 let issues = rebuilt.validate();
708 if !issues.is_empty() {
709 return Err(format!("the new fillet is invalid: {issues:?}"));
710 }
711 crate::accept_sound(rebuilt, "transformFace").map_err(|e| e.to_string())
714 }),
715 format!(" (radius {rho0})"),
716 ),
717 None => (
718 super::blend_rebuild::read_band_law(original, band_id)
719 .map_err(|reason| {
720 format!(
721 "it is neither a constant-radius fillet nor a rolling-ball fillet under a \
722 radius law: {reason}"
723 )
724 })
725 .and_then(|law| super::blend_rebuild::remake_band(&body, &law, false, "transformFace")),
726 String::new(),
727 ),
728 };
729 match remade {
730 Ok(rebuilt) => {
731 body = rebuilt;
732 for beside in across(band) {
735 let beside = faces[&beside];
736 let Some(beside_name) = beside.name.as_deref() else { continue };
737 if !moved_set.contains(&beside.id)
738 && plane_of_surface(&beside.surface, tolerance * 10.0, OP).is_err()
739 && !body.shells.iter().flat_map(|shell| &shell.faces).any(|f| f.name.as_deref() == Some(beside_name))
740 {
741 notes.push(format!(
742 "transformFace: blend `{beside_name}`, which ran round fillet \
743 `{band_name}`, was not re-made: the fillet was rebuilt at its radius \
744 and the faces either side of that blend now meet over it"
745 ));
746 }
747 }
748 }
749 Err(reason) => notes.push(format!(
750 "transformFace: fillet `{band_name}`{radius_label} was lost: the moved face no \
751 longer reaches it, so it was filled in, and it could not be re-made ({reason})"
752 )),
753 }
754 }
755 }
756 (body, notes)
757}
758
759fn sharp_edge_between(body: &BrepSolid, first: &FaceRecord, second: &FaceRecord) -> Result<u64, String> {
761 let edges_of = |face: &FaceRecord| -> Result<HashSet<u64>, String> {
762 let name = face.name.as_deref().ok_or_else(|| format!("face {} has no name to find it by", face.id))?;
763 Ok(body
764 .shells
765 .iter()
766 .flat_map(|shell| &shell.faces)
767 .filter(|f| f.name.as_deref() == Some(name))
768 .flat_map(|f| f.loops.iter().flat_map(|wire| &wire.coedges).map(|coedge| coedge.edge_id))
769 .collect())
770 };
771 let (a, b) = (edges_of(first)?, edges_of(second)?);
772 let mut shared = a.intersection(&b).copied();
773 match (shared.next(), shared.next()) {
774 (Some(edge), None) => Ok(edge),
775 _ => Err("no single sharp edge joins the turned face to the wall beyond it".to_string()),
776 }
777}
778
779struct TangentSurround {
781 planes: Vec<(Vec3, f64)>,
783 inner_wall_depth: f64,
785}
786
787fn band_is_tangent_along_shared_edges(
789 face: &FaceRecord,
790 band: &FaceRecord,
791 normal: Vec3,
792) -> bool {
793 let own: HashSet<u64> =
794 face.loops.iter().flat_map(|wire| &wire.coedges).map(|coedge| coedge.edge_id).collect();
795 let mut shared = 0usize;
796 for coedge in band.loops.iter().flat_map(|wire| &wire.coedges) {
797 if !own.contains(&coedge.edge_id) {
798 continue;
799 }
800 let Ok([q0, q1]) = coedge.pcurve.domain() else {
801 return false;
802 };
803 let Ok(uv) = coedge.pcurve.evaluate(0.5 * (q0 + q1)) else {
804 return false;
805 };
806 let Ok(band_normal) = band.surface.normal(uv.x, uv.y) else {
807 return false;
808 };
809 if band_normal.cross(normal).length() > 1e-4 {
810 return false;
811 }
812 shared += 1;
813 }
814 shared > 0
815}
816
817fn tangent_surround(
826 solid: &BrepSolid,
827 face: &FaceRecord,
828 normal: Vec3,
829 offset: f64,
830 bands: &HashSet<u64>,
831 moved: &HashSet<u64>,
832 tolerance: f64,
833) -> Result<TangentSurround, KernelRefusal> {
834 let mut owners: HashMap<u64, Vec<u64>> = HashMap::default();
835 for other in solid.shells.iter().flat_map(|shell| &shell.faces) {
836 for coedge in other.loops.iter().flat_map(|wire| &wire.coedges) {
837 owners.entry(coedge.edge_id).or_default().push(other.id);
838 }
839 }
840 let edges: HashMap<u64, &EdgeRecord> = solid.edges.iter().map(|edge| (edge.id, edge)).collect();
841 let points: HashMap<u64, Vec3> =
842 solid.vertices.iter().map(|vertex| (vertex.id, vertex.point)).collect();
843 let plane_band = tolerance.max(1e-9) * 10.0;
844
845 let mut curved: HashSet<u64> = bands.clone();
846 let mut planar: HashSet<u64> = HashSet::default();
847 let mut stack: Vec<u64> = bands.iter().copied().collect();
848 while let Some(id) = stack.pop() {
849 let current = face_by_id(solid, id)?;
850 for coedge in current.loops.iter().flat_map(|wire| &wire.coedges) {
851 for &next in owners.get(&coedge.edge_id).into_iter().flatten() {
852 if next == id || next == face.id || curved.contains(&next) || planar.contains(&next) {
853 continue;
854 }
855 if moved.contains(&next) {
856 return Err(KernelRefusal::unsupported(
857 KernelStage::Classify,
858 "curved_neighbour",
859 format!(
860 "{OP}: face {next} is also selected and borders the fillet beside face \
861 {}, so what bounds the tool past that fillet is itself moving; refusing",
862 face.id
863 ),
864 ));
865 }
866 let other = face_by_id(solid, next)?;
867 if plane_of_surface(&other.surface, plane_band, OP).is_ok() {
868 planar.insert(next);
869 } else {
870 curved.insert(next);
871 stack.push(next);
872 }
873 }
874 }
875 }
876
877 let vertices_of = |id: u64| -> Result<Vec<Vec3>, KernelRefusal> {
878 let mut found = Vec::new();
879 for coedge in face_by_id(solid, id)?.loops.iter().flat_map(|wire| &wire.coedges) {
880 if let Some(edge) = edges.get(&coedge.edge_id) {
881 found.extend(points.get(&edge.start_vertex_id).copied());
882 found.extend(points.get(&edge.end_vertex_id).copied());
883 }
884 }
885 Ok(found)
886 };
887 let mut region: Vec<Vec3> = Vec::new();
888 let mut depth = 0.0f64;
889 for &id in &curved {
890 for point in vertices_of(id)? {
891 depth = depth.max(offset - normal.dot(point));
892 region.push(point);
893 }
894 }
895 let mut ordered: Vec<u64> = planar.iter().copied().collect();
896 ordered.sort_unstable();
897 for &id in &ordered {
898 region.extend(vertices_of(id)?);
899 }
900
901 let mut planes = Vec::new();
902 for &id in &ordered {
903 let other = face_by_id(solid, id)?;
904 let plane = plane_of_surface(&other.surface, plane_band, OP)
905 .map_err(|error| KernelRefusal::unsupported(KernelStage::Classify, "curved_neighbour", error.to_string()))?;
906 let outward = if other.same_sense { plane.normal } else { plane.normal.scale(-1.0) };
907 let outward_offset = outward.dot(plane.origin);
908 if let Some(point) = region.iter().find(|point| outward.dot(**point) - outward_offset > plane_band) {
909 return Err(KernelRefusal::unsupported(
910 KernelStage::Classify,
911 "curved_neighbour",
912 format!(
913 "{OP}: the part is not convex around the fillet beside face {} (face {id}{} has \
914 material on both sides, at {point:?}), so the wedge a turn adds there has no \
915 bound that keeps it out of the part's other features; refusing",
916 face.id,
917 named(other)
918 ),
919 ));
920 }
921 planes.push((outward, outward_offset));
922 }
923 Ok(TangentSurround { planes, inner_wall_depth: depth * 1.5 + tolerance })
924}
925
926fn push_unique(spaces: &mut Vec<HalfSpace>, space: HalfSpace, tolerance: f64) {
931 let band = tolerance.max(1e-9) * 10.0;
932 if spaces.iter().any(|other| {
933 other.normal.sub(space.normal).length() <= 1e-9 && (other.offset - space.offset).abs() <= band
934 }) {
935 return;
936 }
937 spaces.push(space);
938}
939
940#[derive(Clone, Copy, Debug, PartialEq)]
944enum EdgeSource {
945 Neighbour(u64),
946 Hinge,
947}
948
949#[derive(Clone, Copy, Debug)]
953struct Frame {
954 origin: Vec3,
955 u: Vec3,
956 v: Vec3,
957}
958
959impl Frame {
960 fn new(origin: Vec3, normal: Vec3) -> Result<Self, String> {
961 let u = normal.perpendicular()?.normalized()?;
962 let v = normal.cross(u).normalized()?;
963 Ok(Self { origin, u, v })
964 }
965
966 fn drop(&self, point: Vec3) -> [f64; 2] {
967 let delta = point.sub(self.origin);
968 [delta.dot(self.u), delta.dot(self.v)]
969 }
970
971 fn lift(&self, point: [f64; 2]) -> Vec3 {
972 self.origin.add(self.u.scale(point[0])).add(self.v.scale(point[1]))
973 }
974
975 fn hinge(&self, normal: Vec3, offset: f64, moved: Vec3, moved_offset: f64) -> Option<Line2> {
978 let direction = normal.cross(moved);
979 if direction.length() <= 1e-12 {
980 return None;
981 }
982 let direction = direction.normalized().ok()?;
983 let across = direction.cross(normal).normalized().ok()?;
986 let rate = moved.dot(across);
987 if rate.abs() <= 1e-12 {
988 return None;
989 }
990 let _ = offset;
991 let point = self.origin.add(across.scale((moved_offset - moved.dot(self.origin)) / rate));
992 let [px, py] = self.drop(point);
993 let [qx, qy] = self.drop(point.add(direction));
994 Some(Line2 {
995 point: [px, py],
996 direction: [qx - px, qy - py],
997 })
998 }
999
1000 fn edge_plane(&self, cell: &Cell, edge: usize) -> (Vec3, f64) {
1004 let a = cell.points[edge];
1005 let b = cell.points[(edge + 1) % cell.points.len()];
1006 let d = [b[0] - a[0], b[1] - a[1]];
1009 let length = (d[0] * d[0] + d[1] * d[1]).sqrt().max(1e-300);
1010 let out = [d[1] / length, -d[0] / length];
1011 let normal = self.u.scale(out[0]).add(self.v.scale(out[1]));
1012 let normal = normal.normalized().unwrap_or(normal);
1013 (normal, normal.dot(self.lift(a)))
1014 }
1015}
1016
1017#[derive(Clone, Copy, Debug)]
1019struct Line2 {
1020 point: [f64; 2],
1021 direction: [f64; 2],
1022}
1023
1024impl Line2 {
1025 fn side(&self, p: [f64; 2]) -> f64 {
1028 let d = self.direction;
1029 let length = (d[0] * d[0] + d[1] * d[1]).sqrt().max(1e-300);
1030 (d[0] * (p[1] - self.point[1]) - d[1] * (p[0] - self.point[0])) / length
1031 }
1032}
1033
1034#[derive(Clone, Debug)]
1038struct Cell {
1039 points: Vec<[f64; 2]>,
1040 sources: Vec<EdgeSource>,
1041}
1042
1043impl Cell {
1044 fn signed_area(&self) -> f64 {
1045 let n = self.points.len();
1046 (0..n)
1047 .map(|i| {
1048 let a = self.points[i];
1049 let b = self.points[(i + 1) % n];
1050 crate::polygon::area_term(a, b)
1051 })
1052 .sum::<f64>()
1053 * 0.5
1054 }
1055
1056 fn centroid(&self) -> [f64; 2] {
1058 let n = self.points.len();
1059 let area = self.signed_area();
1060 if area.abs() <= 1e-300 {
1061 let mean = self.points.iter().fold([0.0, 0.0], |s, p| [s[0] + p[0], s[1] + p[1]]);
1062 return [mean[0] / n as f64, mean[1] / n as f64];
1063 }
1064 let mut cx = 0.0;
1065 let mut cy = 0.0;
1066 for i in 0..n {
1067 let a = self.points[i];
1068 let b = self.points[(i + 1) % n];
1069 let w = crate::polygon::area_term(a, b);
1070 cx += (a[0] + b[0]) * w;
1071 cy += (a[1] + b[1]) * w;
1072 }
1073 [cx / (6.0 * area), cy / (6.0 * area)]
1074 }
1075
1076 fn reflex_vertex(&self, band: f64) -> Option<usize> {
1080 let n = self.points.len();
1081 (0..n).find(|&i| {
1082 let p = self.points[(i + n - 1) % n];
1083 let q = self.points[i];
1084 let r = self.points[(i + 1) % n];
1085 let a = [q[0] - p[0], q[1] - p[1]];
1086 let b = [r[0] - q[0], r[1] - q[1]];
1087 let la = (a[0] * a[0] + a[1] * a[1]).sqrt();
1088 let lb = (b[0] * b[0] + b[1] * b[1]).sqrt();
1089 if la <= band || lb <= band {
1090 return false;
1091 }
1092 (a[0] * b[1] - a[1] * b[0]) / la.max(lb) < -band
1095 })
1096 }
1097}
1098
1099struct TrimPolygon {
1101 frame: Frame,
1102 points: Vec<[f64; 2]>,
1103 sources: Vec<EdgeSource>,
1104}
1105
1106fn trim_polygon(
1113 solid: &BrepSolid,
1114 face: &FaceRecord,
1115 normal: Vec3,
1116 band: f64,
1117) -> Result<TrimPolygon, KernelRefusal> {
1118 let id = face.id;
1119 if face.loops.len() != 1 {
1120 return Err(KernelRefusal::unsupported(
1121 KernelStage::Classify,
1122 "island_trim",
1123 format!(
1124 "{OP}: face {id}{} has {} loops, so its trim has an island whose walls bound no cell \
1125 of the outer trim, and this road cuts one convex cell at a time; refusing rather \
1126 than filling the island",
1127 named(face),
1128 face.loops.len()
1129 ),
1130 ));
1131 }
1132 let edges: HashMap<u64, &EdgeRecord> = solid.edges.iter().map(|edge| (edge.id, edge)).collect();
1133 let vertices: HashMap<u64, Vec3> =
1134 solid.vertices.iter().map(|vertex| (vertex.id, vertex.point)).collect();
1135 let mut across: HashMap<u64, u64> = HashMap::default();
1137 for other in solid.shells.iter().flat_map(|shell| &shell.faces) {
1138 if other.id == id {
1139 continue;
1140 }
1141 for coedge in other.loops.iter().flat_map(|wire| &wire.coedges) {
1142 across.entry(coedge.edge_id).or_insert(other.id);
1143 }
1144 }
1145 let mut points3: Vec<Vec3> = Vec::new();
1146 let mut sources: Vec<EdgeSource> = Vec::new();
1147 for coedge in &face.loops[0].coedges {
1148 let edge = edges.get(&coedge.edge_id).ok_or_else(|| {
1149 KernelRefusal::input(
1150 KernelStage::Collect,
1151 "missing_edge",
1152 format!("{OP}: face {id} uses edge {} which the solid does not hold", coedge.edge_id),
1153 )
1154 })?;
1155 if edge.degenerate {
1156 continue;
1157 }
1158 let (start_id, end_id) = if coedge.forward {
1159 (edge.start_vertex_id, edge.end_vertex_id)
1160 } else {
1161 (edge.end_vertex_id, edge.start_vertex_id)
1162 };
1163 let start = *vertices.get(&start_id).ok_or_else(|| {
1164 KernelRefusal::input(
1165 KernelStage::Collect,
1166 "missing_vertex",
1167 format!("{OP}: edge {} starts at vertex {start_id}, which the solid does not hold", edge.id),
1168 )
1169 })?;
1170 let end = *vertices.get(&end_id).ok_or_else(|| {
1171 KernelRefusal::input(
1172 KernelStage::Collect,
1173 "missing_vertex",
1174 format!("{OP}: edge {} ends at vertex {end_id}, which the solid does not hold", edge.id),
1175 )
1176 })?;
1177 let middle = edge
1179 .curve
1180 .evaluate(0.5 * (edge.t0 + edge.t1))
1181 .or_refuse(KernelStage::Classify, "evaluate")?;
1182 let chord_middle = start.add(end).scale(0.5);
1183 if middle.sub(chord_middle).length() > band.max(1e-9) * 100.0 {
1184 return Err(KernelRefusal::unsupported(
1185 KernelStage::Classify,
1186 "curved_edge",
1187 format!(
1188 "{OP}: edge {} of face {id}{} is not straight (its midpoint is {:.3e} off its \
1189 chord), so the trim is not a polygon this road can cut into cells",
1190 edge.id,
1191 named(face),
1192 middle.sub(chord_middle).length()
1193 ),
1194 ));
1195 }
1196 let neighbour = *across.get(&edge.id).ok_or_else(|| {
1197 KernelRefusal::unsupported(
1198 KernelStage::Classify,
1199 "open_edge",
1200 format!(
1201 "{OP}: edge {} of face {id}{} is held by no other face, so nothing bounds the \
1202 tool there",
1203 edge.id,
1204 named(face)
1205 ),
1206 )
1207 })?;
1208 points3.push(start);
1209 sources.push(EdgeSource::Neighbour(neighbour));
1210 }
1211 if points3.len() < 3 {
1212 return Err(KernelRefusal::unsupported(
1213 KernelStage::Classify,
1214 "thin_trim",
1215 format!("{OP}: face {id}{} has fewer than three corners", named(face)),
1216 ));
1217 }
1218 let frame = Frame::new(points3[0], normal).map_err(|error| {
1219 KernelRefusal::internal(KernelStage::Classify, "frame", format!("{OP}: {error}"))
1220 })?;
1221 let mut points: Vec<[f64; 2]> = points3.iter().map(|point| frame.drop(*point)).collect();
1222 let probe = Cell { points: points.clone(), sources: sources.clone() };
1223 if probe.signed_area() < 0.0 {
1224 points.reverse();
1227 sources.reverse();
1228 sources.rotate_left(1);
1229 let _ = &mut points;
1230 }
1231 Ok(TrimPolygon { frame, points, sources })
1232}
1233
1234fn convex_cells(
1240 polygon: &TrimPolygon,
1241 hinge: Option<Line2>,
1242 band: f64,
1243 scale: f64,
1244) -> Result<Vec<Cell>, String> {
1245 let area_floor = (band * scale).max(1e-18);
1246 let mut pending = vec![Cell {
1247 points: polygon.points.clone(),
1248 sources: polygon.sources.clone(),
1249 }];
1250 let mut convex: Vec<Cell> = Vec::new();
1251 let mut rounds = 0usize;
1252 while let Some(cell) = pending.pop() {
1253 rounds += 1;
1254 if rounds > 256 {
1255 return Err("the reflex cut did not converge in 256 rounds".into());
1256 }
1257 let cell = dedupe(cell, band);
1258 if cell.points.len() < 3 || cell.signed_area().abs() <= area_floor {
1259 continue;
1260 }
1261 match cell.reflex_vertex(band) {
1262 None => convex.push(cell),
1263 Some(vertex) => {
1264 let (first, second) = split_at_reflex(&cell, vertex, band)?;
1265 pending.push(first);
1266 pending.push(second);
1267 }
1268 }
1269 }
1270 let Some(hinge) = hinge else { return Ok(convex) };
1271 let mut cells: Vec<Cell> = Vec::new();
1272 for cell in convex {
1273 let sides: Vec<f64> = cell.points.iter().map(|point| hinge.side(*point)).collect();
1274 let high = sides.iter().copied().fold(f64::MIN, f64::max);
1275 let low = sides.iter().copied().fold(f64::MAX, f64::min);
1276 if high > band && low < -band {
1277 for half in split_by_line(&cell, &sides, band) {
1278 let half = dedupe(half, band);
1279 if half.points.len() >= 3 && half.signed_area().abs() > area_floor {
1280 cells.push(half);
1281 }
1282 }
1283 } else {
1284 cells.push(cell);
1285 }
1286 }
1287 Ok(cells)
1288}
1289
1290fn dedupe(cell: Cell, band: f64) -> Cell {
1293 let mut points: Vec<[f64; 2]> = Vec::new();
1294 let mut sources: Vec<EdgeSource> = Vec::new();
1295 for (point, source) in cell.points.iter().zip(&cell.sources) {
1296 if let Some(last) = points.last() {
1297 if (last[0] - point[0]).hypot(last[1] - point[1]) <= band {
1298 *sources.last_mut().expect("as many sources as points") = *source;
1300 continue;
1301 }
1302 }
1303 points.push(*point);
1304 sources.push(*source);
1305 }
1306 while points.len() >= 2 {
1307 let first = points[0];
1308 let last = points[points.len() - 1];
1309 if (last[0] - first[0]).hypot(last[1] - first[1]) <= band {
1310 points.pop();
1311 let source = sources.pop().expect("as many sources as points");
1312 let _ = source;
1313 } else {
1314 break;
1315 }
1316 }
1317 Cell { points, sources }
1318}
1319
1320fn split_at_reflex(cell: &Cell, vertex: usize, band: f64) -> Result<(Cell, Cell), String> {
1325 let n = cell.points.len();
1326 let points: Vec<[f64; 2]> = (0..n).map(|i| cell.points[(vertex + i) % n]).collect();
1328 let sources: Vec<EdgeSource> = (0..n).map(|i| cell.sources[(vertex + i) % n]).collect();
1329 let p0 = points[0];
1330 let prev = points[n - 1];
1331 let d = [p0[0] - prev[0], p0[1] - prev[1]];
1332 let length = (d[0] * d[0] + d[1] * d[1]).sqrt();
1333 if length <= band {
1334 return Err("a reflex corner with a zero-length arriving edge".into());
1335 }
1336 let d = [d[0] / length, d[1] / length];
1337 let mut best: Option<(usize, f64, f64)> = None;
1339 for j in 1..(n - 1) {
1340 let a = points[j];
1341 let b = points[(j + 1) % n];
1342 let e = [b[0] - a[0], b[1] - a[1]];
1343 let denominator = d[0] * e[1] - d[1] * e[0];
1344 if denominator.abs() <= 1e-15 {
1345 continue;
1346 }
1347 let w = [a[0] - p0[0], a[1] - p0[1]];
1348 let t = (w[0] * e[1] - w[1] * e[0]) / denominator;
1349 let s = (w[0] * d[1] - w[1] * d[0]) / denominator;
1350 let e_length = (e[0] * e[0] + e[1] * e[1]).sqrt().max(1e-300);
1351 let s_band = band / e_length;
1352 if t <= band || s < -s_band || s > 1.0 + s_band {
1353 continue;
1354 }
1355 if best.map_or(true, |(_, best_t, _)| t < best_t) {
1356 best = Some((j, t, s.clamp(0.0, 1.0)));
1357 }
1358 }
1359 let Some((j, t, s)) = best else {
1360 return Err(format!("the extension of the edge arriving at corner {vertex} meets no boundary edge"));
1361 };
1362 let hit = [p0[0] + d[0] * t, p0[1] + d[1] * t];
1363 let a = points[j];
1364 let b = points[(j + 1) % n];
1365 let e_length = ((b[0] - a[0]).powi(2) + (b[1] - a[1]).powi(2)).sqrt().max(1e-300);
1366 let at_a = s * e_length <= band;
1367 let at_b = (1.0 - s) * e_length <= band;
1368 let arriving = sources[n - 1];
1369 let mut first_points: Vec<[f64; 2]> = points[0..=j].to_vec();
1371 let mut first_sources: Vec<EdgeSource> = sources[0..j].to_vec();
1372 if at_b {
1373 first_points.push(b);
1374 first_sources.push(sources[j]);
1375 } else if !at_a {
1376 first_points.push(hit);
1377 first_sources.push(sources[j]);
1378 }
1379 first_sources.push(arriving);
1380 let mut second_points: Vec<[f64; 2]> = Vec::new();
1383 let mut second_sources: Vec<EdgeSource> = Vec::new();
1384 if at_a {
1385 second_points.push(a);
1386 second_sources.push(sources[j]);
1387 } else if !at_b {
1388 second_points.push(hit);
1389 second_sources.push(sources[j]);
1390 }
1391 for k in (j + 1)..n {
1392 second_points.push(points[k]);
1393 second_sources.push(sources[k]);
1394 }
1395 *second_sources.last_mut().expect("the second piece has an edge") = arriving;
1397 Ok((
1398 Cell { points: first_points, sources: first_sources },
1399 Cell { points: second_points, sources: second_sources },
1400 ))
1401}
1402
1403fn split_by_line(cell: &Cell, sides: &[f64], band: f64) -> [Cell; 2] {
1406 let n = cell.points.len();
1407 let mut positive = Cell { points: Vec::new(), sources: Vec::new() };
1408 let mut negative = Cell { points: Vec::new(), sources: Vec::new() };
1409 for j in 0..n {
1410 let p = cell.points[j];
1411 let q = cell.points[(j + 1) % n];
1412 let (fp, fq) = (sides[j], sides[(j + 1) % n]);
1413 let source = cell.sources[j];
1414 let p_on = fp.abs() <= band;
1415 let q_on = fq.abs() <= band;
1416 if fp > band || p_on {
1421 positive.points.push(p);
1422 positive.sources.push(if !p_on || fq > band || q_on { source } else { EdgeSource::Hinge });
1423 }
1424 if fp < -band || p_on {
1425 negative.points.push(p);
1426 negative.sources.push(if !p_on || fq < -band || q_on { source } else { EdgeSource::Hinge });
1427 }
1428 if (fp > band && fq < -band) || (fp < -band && fq > band) {
1430 let t = fp / (fp - fq);
1431 let x = [p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t];
1432 if fp > band {
1433 positive.points.push(x);
1434 positive.sources.push(EdgeSource::Hinge);
1435 negative.points.push(x);
1436 negative.sources.push(source);
1437 } else {
1438 negative.points.push(x);
1439 negative.sources.push(EdgeSource::Hinge);
1440 positive.points.push(x);
1441 positive.sources.push(source);
1442 }
1443 }
1444 }
1445 [positive, negative]
1446}
1447
1448fn one_way_only(
1456 id: u64,
1457 clip: &[HalfSpace],
1458 sides: &[HalfSpace],
1459 other: [HalfSpace; 2],
1460 tolerance: f64,
1461 name: impl Fn() -> String,
1462) -> Result<(), KernelRefusal> {
1463 let band = tolerance.max(1e-9) * 10.0;
1464 let spaces: Vec<HalfSpace> = clip.iter().chain(sides).chain(&other).copied().collect();
1465 let mut depth = 0.0f64;
1466 for a in 0..spaces.len() {
1467 for b in (a + 1)..spaces.len() {
1468 for c in (b + 1)..spaces.len() {
1469 let Some(point) = three_plane_point(&spaces[a], &spaces[b], &spaces[c]) else {
1470 continue;
1471 };
1472 if spaces
1473 .iter()
1474 .any(|space| space.normal.dot(point) - space.offset > band)
1475 {
1476 continue;
1477 }
1478 let inside = other
1480 .iter()
1481 .map(|space| space.offset - space.normal.dot(point))
1482 .fold(0.0f64, f64::max);
1483 depth = depth.max(inside);
1484 }
1485 }
1486 }
1487 if depth > band * 1e3 {
1488 return Err(KernelRefusal::ill_posed(
1489 KernelStage::Classify,
1490 "one_way_only",
1491 format!(
1492 "{OP}: the motion turns face {id}{} so that the line its old and new carriers meet \
1493 in crosses its own bounds — part of the face moves into the body and part out of it \
1494 (the other wedge reaches {depth:.3e} past them), so one tool would add material \
1495 where the other takes it away; refusing rather than choosing",
1496 name()
1497 ),
1498 ));
1499 }
1500 Ok(())
1501}
1502
1503fn cell_is_its_bounds(
1518 face: &FaceRecord,
1519 cell: &Cell,
1520 frame: &Frame,
1521 at_home: &[HalfSpace],
1522 scale: f64,
1523) -> Result<(), KernelRefusal> {
1524 let band = (scale * 1e-4).max(1e-6);
1529 let n = cell.points.len();
1530 let mut worst = 0.0f64;
1531 for i in 0..n {
1532 let a = cell.points[i];
1533 let b = cell.points[(i + 1) % n];
1534 for point in [a, [(a[0] + b[0]) * 0.5, (a[1] + b[1]) * 0.5]] {
1535 let point = frame.lift(point);
1536 for space in at_home {
1537 worst = worst.max(space.normal.dot(point) - space.offset);
1538 }
1539 }
1540 }
1541 if worst > band {
1542 return Err(KernelRefusal::unsupported(
1543 KernelStage::Classify,
1544 "reflex_trim",
1545 format!(
1546 "{OP}: face {}{} has a boundary point {worst:.3e} outside one of its own \
1547 bounding carriers, so its trim is not the region its bounding carriers \
1548 enclose — their intersection is the trim's CONVEX CORE, and the tool this \
1549 road would build is that core rather than all the material the motion \
1550 moves. Refusing rather than cutting some of it",
1551 face.id,
1552 named(face)
1553 ),
1554 ));
1555 }
1556 Ok(())
1557}
1558
1559
1560fn face_by_id(solid: &BrepSolid, id: u64) -> Result<&FaceRecord, KernelRefusal> {
1561 solid
1562 .shells
1563 .iter()
1564 .flat_map(|shell| &shell.faces)
1565 .find(|face| face.id == id)
1566 .ok_or_else(|| {
1567 KernelRefusal::input(
1568 KernelStage::Collect,
1569 "face_id",
1570 format!("{OP}: no face with id {id} on this solid"),
1571 )
1572 })
1573}
1574
1575fn named(face: &FaceRecord) -> String {
1576 face.name
1577 .as_ref()
1578 .map(|name| format!(" '{name}'"))
1579 .unwrap_or_default()
1580}
1581
1582fn solid_bounds(solid: &BrepSolid) -> Result<(Vec3, Vec3), KernelRefusal> {
1586 if solid.vertices.is_empty() {
1587 return Err(KernelRefusal::input(
1588 KernelStage::Collect,
1589 "empty_solid",
1590 format!("{OP}: the solid has no vertices to bound"),
1591 ));
1592 }
1593 let mut low = Vec3::new(f64::MAX, f64::MAX, f64::MAX);
1594 let mut high = Vec3::new(f64::MIN, f64::MIN, f64::MIN);
1595 for vertex in &solid.vertices {
1596 low = Vec3::new(
1597 low.x.min(vertex.point.x),
1598 low.y.min(vertex.point.y),
1599 low.z.min(vertex.point.z),
1600 );
1601 high = Vec3::new(
1602 high.x.max(vertex.point.x),
1603 high.y.max(vertex.point.y),
1604 high.z.max(vertex.point.z),
1605 );
1606 }
1607 Ok((low, high))
1608}
1609
1610fn box_half_spaces((low, high): (Vec3, Vec3), margin: f64) -> Vec<HalfSpace> {
1612 let low = Vec3::new(low.x - margin, low.y - margin, low.z - margin);
1613 let high = Vec3::new(high.x + margin, high.y + margin, high.z + margin);
1614 vec![
1615 HalfSpace { normal: Vec3::new(1.0, 0.0, 0.0), offset: high.x },
1616 HalfSpace { normal: Vec3::new(-1.0, 0.0, 0.0), offset: -low.x },
1617 HalfSpace { normal: Vec3::new(0.0, 1.0, 0.0), offset: high.y },
1618 HalfSpace { normal: Vec3::new(0.0, -1.0, 0.0), offset: -low.y },
1619 HalfSpace { normal: Vec3::new(0.0, 0.0, 1.0), offset: high.z },
1620 HalfSpace { normal: Vec3::new(0.0, 0.0, -1.0), offset: -low.z },
1621 ]
1622}
1623
1624fn convex_solid(
1635 spaces: &[HalfSpace],
1636 inside: Vec3,
1637 tolerance: f64,
1638) -> Result<BrepSolid, String> {
1639 let band = tolerance.max(1e-9) * 10.0;
1640 for space in spaces {
1641 if space.normal.dot(inside) - space.offset > -band {
1642 return Err(format!(
1643 "the seat point is not strictly inside the half-space set (it is {:.3e} past one \
1644 of them), so the slab and its bounds enclose nothing",
1645 space.normal.dot(inside) - space.offset
1646 ));
1647 }
1648 }
1649 let mut corners: Vec<Vec3> = Vec::new();
1651 for a in 0..spaces.len() {
1652 for b in (a + 1)..spaces.len() {
1653 for c in (b + 1)..spaces.len() {
1654 let Some(point) = three_plane_point(&spaces[a], &spaces[b], &spaces[c]) else {
1655 continue;
1656 };
1657 if spaces
1658 .iter()
1659 .any(|space| space.normal.dot(point) - space.offset > band)
1660 {
1661 continue;
1662 }
1663 if corners
1664 .iter()
1665 .any(|other| other.sub(point).length() <= band)
1666 {
1667 continue;
1668 }
1669 corners.push(point);
1670 }
1671 }
1672 }
1673 if corners.len() < 4 {
1674 return Err(format!(
1675 "the half-space set has {} corner(s), which is not a bounded volume",
1676 corners.len()
1677 ));
1678 }
1679
1680 let vertices: Vec<VertexRecord> = corners
1681 .iter()
1682 .enumerate()
1683 .map(|(index, point)| VertexRecord { id: index as u64 + 1, point: *point })
1684 .collect();
1685 let mut edges: Vec<EdgeRecord> = Vec::new();
1686 let mut edge_index: HashMap<(usize, usize), u64> = HashMap::default();
1687 let mut faces: Vec<FaceRecord> = Vec::new();
1688 let mut next_id = 1000u64;
1689
1690 for space in spaces {
1691 let mut on: Vec<usize> = (0..corners.len())
1692 .filter(|&index| (space.normal.dot(corners[index]) - space.offset).abs() <= band)
1693 .collect();
1694 if on.len() < 3 {
1695 continue;
1696 }
1697 let centroid = on
1701 .iter()
1702 .fold(Vec3::new(0.0, 0.0, 0.0), |sum, &index| sum.add(corners[index]))
1703 .scale(1.0 / on.len() as f64);
1704 let u_dir = corners[on[0]].sub(centroid).normalized()?;
1705 let v_dir = space.normal.cross(u_dir).normalized()?;
1706 on.sort_by(|&a, &b| {
1707 let angle = |index: usize| {
1708 let delta = corners[index].sub(centroid);
1709 delta.dot(v_dir).atan2(delta.dot(u_dir))
1710 };
1711 angle(a).total_cmp(&angle(b))
1712 });
1713 faces.push(polygon_face(
1714 &vertices,
1715 &on,
1716 space.normal,
1717 &mut edges,
1718 &mut edge_index,
1719 &mut next_id,
1720 )?);
1721 }
1722 if faces.len() < 4 {
1723 return Err(format!(
1724 "the half-space set produced {} face(s), which does not close a volume",
1725 faces.len()
1726 ));
1727 }
1728
1729 let shell_id = next_id + 1;
1730 let solid_id = next_id + 2;
1731 let solid = BrepSolid {
1732 mass_properties_cache: Default::default(),
1733 cells: Default::default(),
1734 id: solid_id,
1735 vertices,
1736 edges,
1737 shells: vec![ShellRecord { id: shell_id, faces }],
1738 genus: 0,
1739 kind: crate::BodyKind::Solid,
1740 };
1741 let issues = solid.validate();
1742 if !issues.is_empty() {
1743 return Err(format!("the tool polytope did not validate: {issues:?}"));
1744 }
1745 Ok(solid)
1746}
1747
1748fn three_plane_point(a: &HalfSpace, b: &HalfSpace, c: &HalfSpace) -> Option<Vec3> {
1751 let cross = b.normal.cross(c.normal);
1752 let determinant = a.normal.dot(cross);
1753 if determinant.abs() <= 1e-9 {
1754 return None;
1755 }
1756 let point = cross
1757 .scale(a.offset)
1758 .add(c.normal.cross(a.normal).scale(b.offset))
1759 .add(a.normal.cross(b.normal).scale(c.offset))
1760 .scale(1.0 / determinant);
1761 Some(point)
1762}
1763
1764fn polygon_face(
1767 vertices: &[VertexRecord],
1768 corners: &[usize],
1769 normal: Vec3,
1770 edges: &mut Vec<EdgeRecord>,
1771 edge_index: &mut HashMap<(usize, usize), u64>,
1772 next_id: &mut u64,
1773) -> Result<FaceRecord, String> {
1774 let origin_point = vertices[corners[0]].point;
1775 let u_dir = vertices[corners[1]]
1776 .point
1777 .sub(origin_point)
1778 .normalized()?;
1779 let v_dir = normal.cross(u_dir).normalized()?;
1780 let mut low_u = f64::MAX;
1781 let mut low_v = f64::MAX;
1782 let mut high_u = f64::MIN;
1783 let mut high_v = f64::MIN;
1784 let projected: Vec<(f64, f64)> = corners
1785 .iter()
1786 .map(|&index| {
1787 let delta = vertices[index].point.sub(origin_point);
1788 let (u, v) = (delta.dot(u_dir), delta.dot(v_dir));
1789 low_u = low_u.min(u);
1790 low_v = low_v.min(v);
1791 high_u = high_u.max(u);
1792 high_v = high_v.max(v);
1793 (u, v)
1794 })
1795 .collect();
1796 let plane_origin = origin_point.add(u_dir.scale(low_u)).add(v_dir.scale(low_v));
1797 let surface = make_plane(
1798 plane_origin,
1799 u_dir,
1800 v_dir,
1801 high_u - low_u,
1802 high_v - low_v,
1803 )?;
1804
1805 let mut coedges: Vec<CoedgeRecord> = Vec::with_capacity(corners.len());
1806 for index in 0..corners.len() {
1807 let start = corners[index];
1808 let end = corners[(index + 1) % corners.len()];
1809 let key = if start < end { (start, end) } else { (end, start) };
1810 let edge_id = match edge_index.get(&key) {
1811 Some(id) => *id,
1812 None => {
1813 let id = *next_id;
1814 *next_id += 1;
1815 edges.push(EdgeRecord {
1816 id,
1817 curve: make_line(vertices[key.0].point, vertices[key.1].point)?,
1818 t0: 0.0,
1819 t1: 1.0,
1820 start_vertex_id: vertices[key.0].id,
1821 end_vertex_id: vertices[key.1].id,
1822 degenerate: false,
1823 name: None,
1824 });
1825 edge_index.insert(key, id);
1826 id
1827 }
1828 };
1829 let start_uv = projected[index];
1830 let end_uv = projected[(index + 1) % corners.len()];
1831 coedges.push(CoedgeRecord {
1832 id: *next_id,
1833 edge_id,
1834 forward: vertices[start].id
1835 == edges
1836 .iter()
1837 .find(|edge| edge.id == edge_id)
1838 .expect("the edge was just minted")
1839 .start_vertex_id,
1840 pcurve: parameter_line(
1841 start_uv.0 - low_u,
1842 start_uv.1 - low_v,
1843 end_uv.0 - low_u,
1844 end_uv.1 - low_v,
1845 )?,
1846 });
1847 *next_id += 1;
1848 }
1849 let loop_id = *next_id;
1850 *next_id += 1;
1851 let face_id = *next_id;
1852 *next_id += 1;
1853 Ok(FaceRecord {
1854 id: face_id,
1855 surface,
1856 same_sense: true,
1857 loops: vec![LoopRecord { id: loop_id, coedges }],
1858 name: None,
1859 })
1860}
1861
1862fn restamp(
1872 mut cut: BrepSolid,
1873 original: &BrepSolid,
1874 moved: &HashSet<u64>,
1875 motion: &Motion,
1876 tolerance: f64,
1877) -> BrepSolid {
1878 let band = tolerance.max(1e-9) * 1e3;
1879 let mut wanted: Vec<(String, Vec3, f64)> = Vec::new();
1881 for face in original.shells.iter().flat_map(|shell| &shell.faces) {
1882 let Some(name) = face.name.clone() else { continue };
1883 let Ok(plane) = plane_of_surface(&face.surface, band, OP) else {
1884 continue;
1885 };
1886 let normal = if face.same_sense {
1887 plane.normal
1888 } else {
1889 plane.normal.scale(-1.0)
1890 };
1891 let (normal, offset) = if moved.contains(&face.id) {
1892 motion.plane(normal, normal.dot(plane.origin))
1893 } else {
1894 (normal, normal.dot(plane.origin))
1895 };
1896 wanted.push((name, normal, offset));
1897 }
1898 let taken: HashSet<String> = cut
1899 .shells
1900 .iter()
1901 .flat_map(|shell| &shell.faces)
1902 .filter_map(|face| face.name.clone())
1903 .collect();
1904 let mut used: HashMap<String, usize> = HashMap::default();
1905 for name in &taken {
1906 used.insert(name.clone(), 1);
1907 }
1908 for shell in &mut cut.shells {
1909 for face in &mut shell.faces {
1910 if face.name.is_some() {
1911 continue;
1912 }
1913 let Ok(plane) = plane_of_surface(&face.surface, band, OP) else {
1914 continue;
1915 };
1916 let normal = if face.same_sense {
1917 plane.normal
1918 } else {
1919 plane.normal.scale(-1.0)
1920 };
1921 let offset = normal.dot(plane.origin);
1922 let Some((name, _, _)) = wanted.iter().find(|(_, other, other_offset)| {
1923 other.sub(normal).length() <= 1e-9 && (other_offset - offset).abs() <= band
1924 }) else {
1925 continue;
1926 };
1927 let count = used.entry(name.clone()).or_insert(0);
1928 *count += 1;
1929 face.name = Some(if *count == 1 {
1930 name.clone()
1931 } else {
1932 format!("{name}_{}", *count - 1)
1933 });
1934 }
1935 }
1936 cut
1937}