1use serde::{Deserialize, Serialize};
62
63use super::{SceneMap, SelectionGeometry, Vec3};
64
65const EDGE_SAMPLES: usize = 16;
69const SPHERE_SAMPLES: usize = 16;
72const PARALLEL: f64 = 1e-6;
74const TERMINAL_TOLERANCE: f64 = 1e-4;
77const DISTINCT_ENDS: f64 = 0.85;
80const RELATIVE_TOLERANCE: f64 = 1e-6;
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub enum ContactRule {
86 Axis,
88 Caps,
90 Direction,
92 Strip,
95}
96
97impl ContactRule {
98 pub fn as_str(self) -> &'static str {
100 match self {
101 ContactRule::Axis => "axis",
102 ContactRule::Caps => "caps",
103 ContactRule::Direction => "direction",
104 ContactRule::Strip => "strip",
105 }
106 }
107}
108
109#[derive(Debug, Clone, Copy)]
112pub struct ContactAxis {
113 pub axis: Vec3,
117 pub plus_end: Vec3,
119 pub minus_end: Vec3,
121 pub plus_outward: Vec3,
123 pub minus_outward: Vec3,
125 pub wire_at_plus: bool,
127 pub rule: ContactRule,
129}
130
131impl ContactAxis {
132 pub fn wire_end(&self) -> Vec3 {
134 if self.wire_at_plus {
135 self.plus_end
136 } else {
137 self.minus_end
138 }
139 }
140
141 pub fn other_end(&self) -> Vec3 {
143 if self.wire_at_plus {
144 self.minus_end
145 } else {
146 self.plus_end
147 }
148 }
149
150 pub fn outward(&self) -> Vec3 {
152 if self.wire_at_plus {
153 self.plus_outward
154 } else {
155 self.minus_outward
156 }
157 }
158}
159
160#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
163#[serde(rename_all = "camelCase")]
164pub struct PortContactRow {
165 pub body: String,
167 pub end: String,
170 pub axis: [f64; 3],
172 pub wire_end: [f64; 3],
174 pub other_end: [f64; 3],
176 pub seats_origin: bool,
179 #[serde(default)]
182 pub rule: String,
183}
184
185pub fn contact_body_solid(scene: &SceneMap, name: &str) -> Option<u32> {
189 let name = name.trim();
190 if name.is_empty() {
191 return None;
192 }
193 scene.resolve_solid(name)
194}
195
196pub fn contact_body_axis(scene: &SceneMap, name: &str, reverse: bool) -> Result<ContactAxis, String> {
201 contact_body_end(scene, name, reverse, None)
202}
203
204pub fn contact_body_end(
211 scene: &SceneMap,
212 name: &str,
213 reverse: bool,
214 direction: Option<Vec3>,
215) -> Result<ContactAxis, String> {
216 let name = name.trim();
217 let handle = contact_body_solid(scene, name)
218 .ok_or_else(|| format!("contact body '{name}' is not a solid of this part"))?;
219 let (ends, scale) = crate::with_registered_solid_str(handle, |solid| body_ends(solid, name, direction))?;
220 let mut wire_at_plus = match ends.toward {
221 Some(toward) => toward,
223 None => {
225 let mut plus_side = ends.plus_by_default;
226 if let Some(centre) = rest_of_part_centre(scene, handle) {
227 let plus = ends.plus_end.sub(centre).length();
228 let minus = ends.minus_end.sub(centre).length();
229 if (plus - minus).abs() > RELATIVE_TOLERANCE * scale {
230 plus_side = plus > minus;
231 }
232 }
233 plus_side
234 }
235 };
236 if reverse {
237 wire_at_plus = !wire_at_plus;
238 }
239 Ok(ContactAxis {
240 axis: ends.axis,
241 plus_end: ends.plus_end,
242 minus_end: ends.minus_end,
243 plus_outward: ends.plus_outward,
244 minus_outward: ends.minus_outward,
245 wire_at_plus,
246 rule: ends.rule,
247 })
248}
249
250struct Ends {
252 axis: Vec3,
253 plus_end: Vec3,
254 minus_end: Vec3,
255 plus_outward: Vec3,
256 minus_outward: Vec3,
257 rule: ContactRule,
258 toward: Option<bool>,
261 plus_by_default: bool,
265}
266
267fn body_ends(solid: &crate::BrepSolid, name: &str, direction: Option<Vec3>) -> Result<(Ends, f64), String> {
269 let scale = solid_scale(solid);
270 let points = body_points(solid);
271 if points.is_empty() {
272 return Err(format!("contact body '{name}' has no geometry to measure"));
273 }
274 let tolerance = RELATIVE_TOLERANCE * scale;
275
276 let mut groups: Vec<(Vec3, Vec3)> = Vec::new();
279 let mut spheres: Vec<(&crate::FaceRecord, Vec3, f64)> = Vec::new();
280 let mut planes: Vec<(&crate::FaceRecord, Vec3)> = Vec::new();
281 let mut round_tips: Vec<(&crate::FaceRecord, Vec3, Vec3)> = Vec::new();
284 for shell in &solid.shells {
285 for face in &shell.faces {
286 match crate::resolve_face_selection(solid, face.id) {
287 Ok(SelectionGeometry::Axis { origin, direction, radius }) => {
288 let Ok(direction) = direction.normalized() else { continue };
289 let direction = canonical(direction);
290 if radius.is_none() {
291 round_tips.push((face, origin, direction));
292 }
293 let known = groups
294 .iter()
295 .any(|(o, d)| collinear(*o, *d, origin, direction, tolerance));
296 if !known {
297 groups.push((origin, direction));
298 }
299 }
300 Ok(SelectionGeometry::Sphere { center, radius }) => spheres.push((face, center, radius)),
301 Ok(SelectionGeometry::Plane { normal, .. }) => {
302 if let Ok(normal) = normal.normalized() {
303 planes.push((face, normal));
304 }
305 }
306 _ => {}
307 }
308 }
309 }
310
311 if let [(origin, axis)] = groups.as_slice() {
312 let (origin, axis) = (*origin, *axis);
313 let (low, high) = axial_extent(&points, &spheres, origin, axis, tolerance);
314 if high - low <= RELATIVE_TOLERANCE * scale {
315 return Err(format!("contact body '{name}' has no length along its axis"));
316 }
317 let reach = points.iter().map(|p| off_axis(origin, axis, *p)).fold(0.0, f64::max);
321 if direction.is_none() && reach > high - low && strip_axis_enabled() {
322 if let Some(ends) = strip_body_ends(solid, &points, scale) {
323 return Ok((ends, scale));
324 }
325 }
326 let ends = Ends {
327 axis,
328 plus_end: origin.add(axis.scale(high)),
329 minus_end: origin.add(axis.scale(low)),
330 plus_outward: axis,
331 minus_outward: axis.scale(-1.0),
332 rule: ContactRule::Axis,
333 toward: None,
334 plus_by_default: true,
335 };
336 return Ok((ends, scale));
337 }
338
339 let slack = TERMINAL_TOLERANCE * scale;
343 let behind = |centre: Vec3, outward: Vec3| points.iter().all(|p| p.sub(centre).dot(outward) <= slack);
344 let body_centre = bbox_centre(&points);
345 let mut caps: Vec<Cap> = Vec::new();
346 for (face, normal) in &planes {
347 if let Some(centre) = boundary_centroid(solid, face) {
348 if behind(centre, *normal) {
349 caps.push(Cap { point: centre, outward: *normal, line: None });
350 }
351 }
352 }
353 for (face, center, _) in &spheres {
354 if let Some(pole) = sphere_tip(face, body_centre) {
355 if let Ok(outward) = pole.sub(*center).normalized() {
356 if behind(pole, outward) {
357 caps.push(Cap { point: pole, outward, line: Some((*center, outward)) });
358 }
359 }
360 }
361 }
362 for (face, origin, axis) in &round_tips {
363 if let Some(tip) = axial_tip(face, *origin, *axis, body_centre) {
364 if behind(tip.point, tip.outward) {
365 caps.push(tip);
366 }
367 }
368 }
369 let mut ends: Vec<Cap> = Vec::new();
372 for cap in caps {
373 match ends.iter_mut().find(|end| end.point.sub(cap.point).length() <= slack) {
374 Some(end) => {
375 if end.line.is_none() {
376 end.line = cap.line;
377 }
378 }
379 None => ends.push(cap),
380 }
381 }
382 if ends.len() < 2 && planes.len() == 2 {
383 let two: Vec<Cap> = planes
387 .iter()
388 .filter_map(|(face, normal)| {
389 boundary_centroid(solid, face).map(|centre| Cap { point: centre, outward: *normal, line: None })
390 })
391 .collect();
392 if two.len() == 2 && !same_end(&two[0], &two[1]) {
393 ends = two;
394 }
395 }
396 if let Some((a, b)) = distinct_ends(&ends, tolerance) {
397 let (mut a, mut b) = (ends[a], ends[b]);
398 a.point = on_line_of(a, &b);
401 b.point = on_line_of(b, &a);
402 if let Ok(chord) = a.point.sub(b.point).normalized() {
403 let axis = canonical(chord);
404 let (plus, minus) = if a.point.dot(axis) >= b.point.dot(axis) { (a, b) } else { (b, a) };
405 let ends = Ends {
406 axis,
407 plus_end: plus.point,
408 minus_end: minus.point,
409 plus_outward: plus.outward,
410 minus_outward: minus.outward,
411 rule: ContactRule::Caps,
412 toward: None,
413 plus_by_default: true,
414 };
415 return Ok((ends, scale));
416 }
417 }
418
419 if direction.is_none() && strip_ends_enabled() {
422 if let Some(ends) = strip_body_ends(solid, &points, scale) {
423 return Ok((ends, scale));
424 }
425 }
426
427 let Some(direction) = direction.and_then(|d| d.normalized().ok()) else {
429 return Err(format!(
430 "contact body '{name}' has no distinct ends to take a wire end from; pick a Direction (a face, an edge or an axis) to say which way the wire leaves"
431 ));
432 };
433 let axis = canonical(direction);
434 let extreme = |toward: Vec3| -> Vec3 {
435 for (face, normal) in &planes {
437 if normal.dot(toward) >= 1.0 - PARALLEL {
438 if let Some(centre) = boundary_centroid(solid, face) {
439 if behind(centre, *normal) {
440 return centre;
441 }
442 }
443 }
444 }
445 let top = points.iter().map(|p| p.dot(toward)).fold(f64::NEG_INFINITY, f64::max);
447 let at_top: Vec<Vec3> = points.iter().copied().filter(|p| top - p.dot(toward) <= slack).collect();
448 bbox_centre(&at_top)
449 };
450 let plus_end = extreme(axis);
451 let minus_end = extreme(axis.scale(-1.0));
452 if plus_end.sub(minus_end).dot(axis) <= RELATIVE_TOLERANCE * scale {
453 return Err(format!("contact body '{name}' has no length along its Direction"));
454 }
455 let ends = Ends {
456 axis,
457 plus_end,
458 minus_end,
459 plus_outward: axis,
460 minus_outward: axis.scale(-1.0),
461 rule: ContactRule::Direction,
462 toward: Some(direction.dot(axis) > 0.0),
463 plus_by_default: true,
464 };
465 Ok((ends, scale))
466}
467
468fn strip_ends_enabled() -> bool {
472 crate::switch!("BREP_CONTACT_STRIP_ENDS", true)
473}
474
475fn strip_axis_enabled() -> bool {
480 strip_ends_enabled() && crate::switch!("BREP_CONTACT_STRIP_AXIS", false)
481}
482
483fn strip_ends(
517 solid: &crate::BrepSolid,
518 planes: &[(&crate::FaceRecord, Vec3)],
519 behind: &dyn Fn(Vec3, Vec3) -> bool,
520 slack: f64,
521) -> Option<((Cap, f64), (Cap, f64))> {
522 let graph = WireGraph::of(solid);
523 if graph.points.len() < 2 {
524 return None;
525 }
526 let from_start = graph.distances(0);
527 if from_start.iter().any(|d| !d.is_finite()) {
530 return None;
531 }
532 let p = farthest(&from_start)?;
533 let from_p = graph.distances(p);
534
535 let faces: Vec<(&crate::FaceRecord, Vec3, Vec3, Vec<usize>)> = planes
537 .iter()
538 .filter_map(|(face, normal)| {
539 let centre = boundary_centroid(solid, face)?;
540 if !behind(centre, *normal) {
541 return None;
542 }
543 let nodes = graph.face_nodes(face);
544 (!nodes.is_empty()).then(|| (*face, *normal, centre, nodes))
545 })
546 .collect();
547 let cap_at = |from_other: &[f64]| -> Option<usize> {
549 let mut scored: Vec<(f64, usize)> = faces
550 .iter()
551 .enumerate()
552 .map(|(i, (_, _, _, nodes))| {
553 (nodes.iter().map(|n| from_other[*n]).fold(f64::INFINITY, f64::min), i)
554 })
555 .filter(|(score, _)| score.is_finite())
556 .collect();
557 scored.sort_by(|a, b| b.0.total_cmp(&a.0));
558 let &(best, i) = scored.first()?;
559 let size = graph.spread(&faces[i].3);
560 let distinct = scored.get(1).map_or(true, |&(second, _)| best - second >= 0.5 * size);
561 (distinct && size > slack).then_some(i)
562 };
563 let at_q = cap_at(&from_p)?;
567 let at_p = cap_at(&graph.distances_from(&faces[at_q].3))?;
568 if at_p == at_q || cap_at(&graph.distances_from(&faces[at_p].3))? != at_q {
569 return None;
570 }
571 let cap = |i: usize| Cap { point: faces[i].2, outward: faces[i].1, line: None };
572 let (a, b) = (cap(at_p), cap(at_q));
573 if same_end(&a, &b) || a.point.sub(b.point).length() <= slack {
574 return None;
575 }
576 let soled = |end: usize, other: Vec3| -> (Cap, f64) {
579 let (cap_face, normal, centre, _) = &faces[end];
580 let Ok(away) = other.sub(*centre).normalized() else { return (cap(end), 0.0) };
581 let cap_edges: Vec<u64> = face_edges(cap_face);
582 faces
583 .iter()
584 .enumerate()
585 .filter(|(i, (face, n, _, _))| {
586 *i != end
587 && n.dot(*normal).abs() <= SQUARE
588 && n.dot(away) <= -SOLE_AWAY
589 && face_edges(face).iter().any(|e| cap_edges.contains(e))
590 })
591 .min_by(|x, y| x.1 .1.dot(away).total_cmp(&y.1 .1.dot(away)))
592 .map(|(_, (_, n, c, nodes))| (Cap { point: *c, outward: *n, line: None }, graph.spread(nodes)))
593 .unwrap_or_else(|| (cap(end), 0.0))
594 };
595 Some((soled(at_p, b.point), soled(at_q, a.point)))
596}
597
598fn strip_body_ends(solid: &crate::BrepSolid, points: &[Vec3], scale: f64) -> Option<Ends> {
601 let slack = TERMINAL_TOLERANCE * scale;
602 let behind = |centre: Vec3, outward: Vec3| points.iter().all(|p| p.sub(centre).dot(outward) <= slack);
603 let planes: Vec<(&crate::FaceRecord, Vec3)> = solid
604 .shells
605 .iter()
606 .flat_map(|shell| &shell.faces)
607 .filter_map(|face| match crate::resolve_face_selection(solid, face.id) {
608 Ok(SelectionGeometry::Plane { normal, .. }) => normal.normalized().ok().map(|normal| (face, normal)),
609 _ => None,
610 })
611 .collect();
612 let ((a, a_sole), (b, b_sole)) = strip_ends(solid, &planes, &behind, slack)?;
613 let axis = canonical(a.point.sub(b.point).normalized().ok()?);
614 let ((plus, plus_sole), (minus, minus_sole)) =
615 if a.point.dot(axis) >= b.point.dot(axis) { ((a, a_sole), (b, b_sole)) } else { ((b, b_sole), (a, a_sole)) };
616 Some(Ends {
617 axis,
618 plus_end: plus.point,
619 minus_end: minus.point,
620 plus_outward: plus.outward,
621 minus_outward: minus.outward,
622 rule: ContactRule::Strip,
623 toward: None,
624 plus_by_default: plus_sole >= minus_sole,
625 })
626}
627
628const SQUARE: f64 = 1e-3;
630const SOLE_AWAY: f64 = 0.25;
633
634fn face_edges(face: &crate::FaceRecord) -> Vec<u64> {
636 face.loops.iter().flat_map(|l| l.coedges.iter().map(|c| c.edge_id)).collect()
637}
638
639fn farthest(distances: &[f64]) -> Option<usize> {
641 distances
642 .iter()
643 .enumerate()
644 .filter(|(_, d)| d.is_finite())
645 .max_by(|a, b| a.1.total_cmp(b.1))
646 .map(|(i, _)| i)
647}
648
649struct WireGraph {
652 points: Vec<Vec3>,
653 links: Vec<Vec<(usize, f64)>>,
654 chains: std::collections::HashMap<u64, Vec<usize>>,
656}
657
658impl WireGraph {
659 fn of(solid: &crate::BrepSolid) -> Self {
660 let mut graph = WireGraph { points: Vec::new(), links: Vec::new(), chains: Default::default() };
661 let mut vertex_node: std::collections::HashMap<u64, usize> = Default::default();
662 for vertex in &solid.vertices {
663 vertex_node.insert(vertex.id, graph.node(vertex.point));
664 }
665 for edge in &solid.edges {
666 if edge.degenerate {
667 continue;
668 }
669 let (Some(&start), Some(&end)) = (vertex_node.get(&edge.start_vertex_id), vertex_node.get(&edge.end_vertex_id))
670 else {
671 continue;
672 };
673 let mut chain = vec![start];
674 for i in 1..EDGE_SAMPLES {
675 let t = edge.t0 + (edge.t1 - edge.t0) * (i as f64 / EDGE_SAMPLES as f64);
676 if let Ok(point) = edge.curve.evaluate(t) {
677 chain.push(graph.node(point));
678 }
679 }
680 chain.push(end);
681 for pair in chain.windows(2) {
682 let length = graph.points[pair[0]].sub(graph.points[pair[1]]).length();
683 graph.links[pair[0]].push((pair[1], length));
684 graph.links[pair[1]].push((pair[0], length));
685 }
686 graph.chains.insert(edge.id, chain);
687 }
688 graph
689 }
690
691 fn node(&mut self, point: Vec3) -> usize {
692 self.points.push(point);
693 self.links.push(Vec::new());
694 self.points.len() - 1
695 }
696
697 fn face_nodes(&self, face: &crate::FaceRecord) -> Vec<usize> {
699 let mut nodes: Vec<usize> = face_edges(face)
700 .iter()
701 .filter_map(|e| self.chains.get(e))
702 .flatten()
703 .copied()
704 .collect();
705 nodes.sort_unstable();
706 nodes.dedup();
707 nodes
708 }
709
710 fn spread(&self, nodes: &[usize]) -> f64 {
712 let mut largest = 0.0_f64;
713 for (k, a) in nodes.iter().enumerate() {
714 for b in &nodes[k + 1..] {
715 largest = largest.max(self.points[*a].sub(self.points[*b]).length());
716 }
717 }
718 largest
719 }
720
721 fn distances(&self, source: usize) -> Vec<f64> {
723 self.distances_from(&[source])
724 }
725
726 fn distances_from(&self, sources: &[usize]) -> Vec<f64> {
729 use std::cmp::Reverse;
730 let mut best = vec![f64::INFINITY; self.points.len()];
731 let mut heap = std::collections::BinaryHeap::new();
732 for &source in sources {
733 best[source] = 0.0;
734 heap.push(Reverse((Ordered(0.0), source)));
735 }
736 while let Some(Reverse((Ordered(d), node))) = heap.pop() {
737 if d > best[node] {
738 continue;
739 }
740 for &(next, length) in &self.links[node] {
741 let through = d + length;
742 if through < best[next] {
743 best[next] = through;
744 heap.push(Reverse((Ordered(through), next)));
745 }
746 }
747 }
748 best
749 }
750}
751
752#[derive(Clone, Copy, PartialEq)]
754struct Ordered(f64);
755impl Eq for Ordered {}
756impl PartialOrd for Ordered {
757 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
758 Some(self.cmp(other))
759 }
760}
761impl Ord for Ordered {
762 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
763 self.0.total_cmp(&other.0)
764 }
765}
766
767fn axial_extent(
771 points: &[Vec3],
772 spheres: &[(&crate::FaceRecord, Vec3, f64)],
773 origin: Vec3,
774 axis: Vec3,
775 tolerance: f64,
776) -> (f64, f64) {
777 let mut low = f64::INFINITY;
778 let mut high = f64::NEG_INFINITY;
779 let mut include = |point: Vec3| {
780 let t = point.sub(origin).dot(axis);
781 low = low.min(t);
782 high = high.max(t);
783 };
784 for point in points {
785 include(*point);
786 }
787 for (face, center, _) in spheres {
788 if off_axis(origin, axis, *center) > tolerance {
789 continue;
790 }
791 for point in sphere_samples(face) {
792 include(point);
793 }
794 }
795 (low, high)
796}
797
798fn body_points(solid: &crate::BrepSolid) -> Vec<Vec3> {
801 let mut points: Vec<Vec3> = solid.vertices.iter().map(|vertex| vertex.point).collect();
802 for edge in &solid.edges {
803 if edge.degenerate {
804 continue;
805 }
806 for i in 0..=EDGE_SAMPLES {
807 let t = edge.t0 + (edge.t1 - edge.t0) * (i as f64 / EDGE_SAMPLES as f64);
808 if let Ok(point) = edge.curve.evaluate(t) {
809 points.push(point);
810 }
811 }
812 }
813 points
814}
815
816fn sphere_samples(face: &crate::FaceRecord) -> Vec<Vec3> {
819 let (Ok(u), Ok(v)) = (face.surface.domain_u(), face.surface.domain_v()) else { return Vec::new() };
820 let mut out = Vec::new();
821 for i in 0..=SPHERE_SAMPLES {
822 for j in 0..=SPHERE_SAMPLES {
823 let s = u[0] + (u[1] - u[0]) * (i as f64 / SPHERE_SAMPLES as f64);
824 let t = v[0] + (v[1] - v[0]) * (j as f64 / SPHERE_SAMPLES as f64);
825 if let Ok(point) = face.surface.evaluate(s, t) {
826 out.push(point);
827 }
828 }
829 }
830 out
831}
832
833fn sphere_tip(face: &crate::FaceRecord, body_centre: Vec3) -> Option<Vec3> {
836 sphere_samples(face)
837 .into_iter()
838 .max_by(|a, b| a.sub(body_centre).length().total_cmp(&b.sub(body_centre).length()))
839}
840
841fn boundary_centroid(solid: &crate::BrepSolid, face: &crate::FaceRecord) -> Option<Vec3> {
844 let mut sum = Vec3::new(0.0, 0.0, 0.0);
845 let mut length = 0.0;
846 for edge_id in face.loops.iter().flat_map(|l| l.coedges.iter().map(|c| c.edge_id)) {
847 let Some(edge) = solid.edges.iter().find(|edge| edge.id == edge_id) else { continue };
848 if edge.degenerate {
849 continue;
850 }
851 let samples: Vec<Vec3> = (0..=EDGE_SAMPLES)
852 .filter_map(|i| edge.curve.evaluate(edge.t0 + (edge.t1 - edge.t0) * (i as f64 / EDGE_SAMPLES as f64)).ok())
853 .collect();
854 for pair in samples.windows(2) {
855 let piece = pair[1].sub(pair[0]).length();
856 sum = sum.add(pair[0].add(pair[1]).scale(0.5 * piece));
857 length += piece;
858 }
859 }
860 (length > 0.0).then(|| sum.scale(1.0 / length))
861}
862
863fn distinct_ends(caps: &[Cap], tolerance: f64) -> Option<(usize, usize)> {
866 let mut pairs: Vec<(f64, usize, usize)> = Vec::new();
867 for i in 0..caps.len() {
868 for j in i + 1..caps.len() {
869 pairs.push((caps[i].point.sub(caps[j].point).length(), i, j));
870 }
871 }
872 pairs.sort_by(|a, b| b.0.total_cmp(&a.0));
873 let &(best, i, j) = pairs.first()?;
874 if best <= tolerance {
875 return None;
876 }
877 let rival = pairs.iter().skip(1).any(|&(d, k, l)| (k, l) != (i, j) && d >= DISTINCT_ENDS * best);
878 (!rival).then_some((i, j))
879}
880
881#[derive(Debug, Clone, Copy)]
884pub(super) struct Cap {
885 pub(super) point: Vec3,
886 pub(super) outward: Vec3,
887 pub(super) line: Option<(Vec3, Vec3)>,
888}
889
890fn axial_tip(face: &crate::FaceRecord, origin: Vec3, axis: Vec3, body_centre: Vec3) -> Option<Cap> {
894 let samples = sphere_samples(face);
895 if samples.is_empty() {
896 return None;
897 }
898 let along: Vec<f64> = samples.iter().map(|p| p.sub(origin).dot(axis)).collect();
899 let mean = along.iter().sum::<f64>() / along.len() as f64;
900 let centre = body_centre.sub(origin).dot(axis);
901 let (t, outward) = if mean >= centre {
902 (along.iter().copied().fold(f64::NEG_INFINITY, f64::max), axis)
903 } else {
904 (along.iter().copied().fold(f64::INFINITY, f64::min), axis.scale(-1.0))
905 };
906 Some(Cap { point: origin.add(axis.scale(t)), outward, line: Some((origin, axis)) })
907}
908
909fn on_line_of(end: Cap, other: &Cap) -> Vec3 {
912 let (Some((origin, direction)), None) = (other.line, end.line) else { return end.point };
913 let Ok(direction) = direction.normalized() else { return end.point };
914 if end.outward.dot(direction).abs() < 1.0 - PARALLEL {
915 return end.point;
916 }
917 origin.add(direction.scale(end.point.sub(origin).dot(direction)))
918}
919
920pub(super) fn same_end(a: &Cap, b: &Cap) -> bool {
924 let apart = a.point.sub(b.point);
925 let length = apart.length();
926 a.outward.dot(b.outward) > 0.9 && (length == 0.0 || apart.dot(a.outward).abs() >= 0.9 * length)
927}
928
929fn bbox_centre(points: &[Vec3]) -> Vec3 {
931 let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
932 let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
933 for p in points {
934 low = Vec3::new(low.x.min(p.x), low.y.min(p.y), low.z.min(p.z));
935 high = Vec3::new(high.x.max(p.x), high.y.max(p.y), high.z.max(p.z));
936 }
937 low.add(high).scale(0.5)
938}
939
940fn rest_of_part_centre(scene: &SceneMap, body: u32) -> Option<Vec3> {
944 let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
945 let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
946 let mut any = false;
947 let mut handles: Vec<u32> = scene.solids.values().copied().filter(|h| *h != body).collect();
948 handles.sort_unstable();
949 handles.dedup();
950 for handle in handles {
951 let Ok((a, b)) = crate::feature_pipeline::pmi::resolve::solid_bbox(handle) else { continue };
952 low = Vec3::new(low.x.min(a.x), low.y.min(a.y), low.z.min(a.z));
953 high = Vec3::new(high.x.max(b.x), high.y.max(b.y), high.z.max(b.z));
954 any = true;
955 }
956 any.then(|| low.add(high).scale(0.5))
957}
958
959fn canonical(direction: Vec3) -> Vec3 {
962 let [x, y, z] = [direction.x, direction.y, direction.z];
963 let largest = if x.abs() >= y.abs() && x.abs() >= z.abs() {
964 x
965 } else if y.abs() >= z.abs() {
966 y
967 } else {
968 z
969 };
970 if largest < 0.0 {
971 direction.scale(-1.0)
972 } else {
973 direction
974 }
975}
976
977fn collinear(o1: Vec3, d1: Vec3, o2: Vec3, d2: Vec3, tolerance: f64) -> bool {
979 d1.cross(d2).length() <= PARALLEL && off_axis(o1, d1, o2) <= tolerance.max(1e-9)
980}
981
982fn off_axis(origin: Vec3, axis: Vec3, point: Vec3) -> f64 {
984 let offset = point.sub(origin);
985 offset.sub(axis.scale(offset.dot(axis))).length()
986}
987
988fn solid_scale(solid: &crate::BrepSolid) -> f64 {
990 let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
991 let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
992 for vertex in &solid.vertices {
993 let p = vertex.point;
994 low = Vec3::new(low.x.min(p.x), low.y.min(p.y), low.z.min(p.z));
995 high = Vec3::new(high.x.max(p.x), high.y.max(p.y), high.z.max(p.z));
996 }
997 if solid.vertices.is_empty() {
998 return 1.0;
999 }
1000 high.sub(low).length().max(1.0)
1001}