1use super::*;
2
3#[derive(Clone)]
4struct SectionFrame {
5 normal: Vec3,
6 centroid: Vec3,
7 samples: Vec<Vec3>,
8 planar: bool,
9}
10
11pub(super) fn closed_points(
12 curves: &[NurbsCurve],
13 tolerance: f64,
14) -> Result<Vec<Vec3>, KernelRefusal> {
15 if curves.len() < 2 {
16 return Err(KernelRefusal::input(
17 KernelStage::Collect,
18 "section_curve_count",
19 "loftSolid: a section needs at least 2 curves",
20 ));
21 }
22 let mut points = Vec::with_capacity(curves.len());
23 for (index, curve) in curves.iter().enumerate() {
24 let [start, end] = curve.domain().or_refuse(KernelStage::Collect, "domain")?;
25 let next = &curves[(index + 1) % curves.len()];
26 let next_start = next.domain().or_refuse(KernelStage::Collect, "domain")?[0];
27 if curve
28 .evaluate(end)
29 .or_refuse(KernelStage::Collect, "evaluate")?
30 .sub(
31 next.evaluate(next_start)
32 .or_refuse(KernelStage::Collect, "evaluate")?,
33 )
34 .length()
35 > tolerance
36 {
37 return Err(KernelRefusal::input(
38 KernelStage::Collect,
39 "open_section",
40 format!("loftSolid: section is open at curve {index}"),
41 ));
42 }
43 points.push(
44 curve
45 .evaluate(start)
46 .or_refuse(KernelStage::Collect, "evaluate")?,
47 );
48 }
49 Ok(points)
50}
51
52fn section_frame(curves: &[NurbsCurve], tolerance: f64) -> Result<SectionFrame, KernelRefusal> {
53 let mut samples = Vec::new();
54 for curve in curves {
55 let [start, end] = curve.domain().or_refuse(KernelStage::Classify, "domain")?;
56 for index in 0..16 {
57 samples.push(
58 curve
59 .evaluate(start + (end - start) * index as f64 / 16.0)
60 .or_refuse(KernelStage::Classify, "evaluate")?,
61 );
62 }
63 }
64 let mut normal = crate::polygon::newell_normal(&samples);
65 let mut centroid = samples.iter().fold(Vec3::default(), |sum, &point| sum.add(point));
66 normal = normal
69 .normalized()
70 .or_input(KernelStage::Classify, "section_normal")?;
71 centroid = centroid.scale(1.0 / samples.len() as f64);
72 let planar = samples
73 .iter()
74 .all(|point| point.sub(samples[0]).dot(normal).abs() <= tolerance * 100.0);
75 Ok(SectionFrame {
76 normal,
77 centroid,
78 samples,
79 planar,
80 })
81}
82
83const CAP_ADVANCE_MIN: f64 = 0.1;
88
89fn advance_from(
95 sections: &[Vec<NurbsCurve>],
96 anchor: Vec3,
97 normal: Vec3,
98 order: impl Iterator<Item = usize>,
99 tolerance: f64,
100) -> Result<Option<Vec3>, KernelRefusal> {
101 for index in order {
102 let step = section_frame(§ions[index], tolerance)?
103 .centroid
104 .sub(anchor);
105 let length = step.length();
106 if length > tolerance && (step.dot(normal) / length).abs() >= CAP_ADVANCE_MIN {
107 return Ok(Some(step.scale(1.0 / length)));
108 }
109 }
110 Ok(None)
111}
112
113fn reverse_section(curves: &[NurbsCurve]) -> Result<Vec<NurbsCurve>, KernelRefusal> {
114 curves
115 .iter()
116 .rev()
117 .map(NurbsCurve::reversed)
118 .collect::<Result<Vec<_>, String>>()
119 .or_refuse(KernelStage::Classify, "reverse_section")
120}
121
122fn cap_face(
127 curves: &[NurbsCurve],
128 edge_ids: &[u64],
129 frame: &SectionFrame,
130 advance: Vec3,
131 outward: bool,
132 next_id: &mut u64,
133) -> Result<FaceRecord, KernelRefusal> {
134 let normal = if frame.normal.dot(advance) >= 0.0 {
135 frame.normal
136 } else {
137 frame.normal.scale(-1.0)
138 };
139 let x_axis = normal
140 .perpendicular()
141 .or_refuse(KernelStage::Fragment, "cap_frame")?;
142 let y_axis = normal
143 .cross(x_axis)
144 .normalized()
145 .or_refuse(KernelStage::Fragment, "cap_frame")?;
146 let (mut min_x, mut min_y) = (f64::INFINITY, f64::INFINITY);
147 let (mut max_x, mut max_y) = (f64::NEG_INFINITY, f64::NEG_INFINITY);
148 for point in &frame.samples {
149 let delta = point.sub(frame.centroid);
150 min_x = min_x.min(delta.dot(x_axis));
151 max_x = max_x.max(delta.dot(x_axis));
152 min_y = min_y.min(delta.dot(y_axis));
153 max_y = max_y.max(delta.dot(y_axis));
154 }
155 let padding = (max_x - min_x).max(max_y - min_y) * 0.05 + 1e-6;
156 let origin = frame
157 .centroid
158 .add(x_axis.scale(min_x - padding))
159 .add(y_axis.scale(min_y - padding));
160 let surface = make_plane(
161 origin,
162 x_axis,
163 y_axis,
164 max_x - min_x + 2.0 * padding,
165 max_y - min_y + 2.0 * padding,
166 )
167 .or_refuse(KernelStage::Fragment, "cap_plane")?;
168 let mut coedges = Vec::with_capacity(curves.len());
169 if outward {
170 for (index, curve) in curves.iter().enumerate() {
171 coedges.push(CoedgeRecord {
172 id: *next_id,
173 edge_id: edge_ids[index],
174 forward: true,
175 pcurve: curve_to_plane_parameters(curve, origin, x_axis, y_axis)
176 .or_refuse(KernelStage::Fragment, "cap_pcurve")?,
177 });
178 *next_id += 1;
179 }
180 } else {
181 for index in (0..curves.len()).rev() {
182 coedges.push(CoedgeRecord {
183 id: *next_id,
184 edge_id: edge_ids[index],
185 forward: false,
186 pcurve: curve_to_plane_parameters(&curves[index], origin, x_axis, y_axis)
187 .or_refuse(KernelStage::Fragment, "cap_pcurve")?
188 .reversed()
189 .or_refuse(KernelStage::Fragment, "cap_pcurve")?,
190 });
191 *next_id += 1;
192 }
193 }
194 let loop_id = *next_id;
195 *next_id += 1;
196 let face_id = *next_id;
197 *next_id += 1;
198 Ok(FaceRecord {
199 id: face_id,
200 surface,
201 same_sense: outward,
202 loops: vec![LoopRecord {
203 id: loop_id,
204 coedges,
205 }],
206 name: None,
207 })
208}
209
210pub fn loft_profile_brep(input_sections: &[Vec<NurbsCurve>]) -> Result<BrepSolid, KernelRefusal> {
215 loft_profile_brep_core(input_sections, None, &[], true)
216}
217
218pub(crate) fn loft_profile_brep_unscanned(input_sections: &[Vec<NurbsCurve>]) -> Result<BrepSolid, KernelRefusal> {
222 loft_profile_brep_core(input_sections, None, &[], false)
223}
224
225pub fn loft_profile_brep_broken(
231 input_sections: &[Vec<NurbsCurve>],
232 breaks: &[usize],
233) -> Result<BrepSolid, KernelRefusal> {
234 loft_profile_brep_core(input_sections, None, breaks, true)
235}
236
237pub fn loft_profile_brep_tangent(
244 input_sections: &[Vec<NurbsCurve>],
245 start_direction: Vec3,
246 end_direction: Vec3,
247) -> Result<BrepSolid, KernelRefusal> {
248 let start = start_direction.normalized().map_err(|_| {
249 KernelRefusal::input(
250 KernelStage::Collect,
251 "start_tangent",
252 "loftSolid: start tangent must be a nonzero direction",
253 )
254 })?;
255 let end = end_direction.normalized().map_err(|_| {
256 KernelRefusal::input(
257 KernelStage::Collect,
258 "end_tangent",
259 "loftSolid: end tangent must be a nonzero direction",
260 )
261 })?;
262 loft_profile_brep_core(input_sections, Some((start, end)), &[], true)
263}
264
265fn loft_profile_brep_core(
266 input_sections: &[Vec<NurbsCurve>],
267 end_tangents: Option<(Vec3, Vec3)>,
268 breaks: &[usize],
269 scan: bool,
270) -> Result<BrepSolid, KernelRefusal> {
271 let mut profile = super::ConstructionProfile::new("loft");
272 let tolerance = 1e-6;
273 let section_count = input_sections.len();
274 if section_count < 2 {
275 return Err(KernelRefusal::input(
276 KernelStage::Collect,
277 "section_count",
278 "loftSolid: need at least 2 sections",
279 ));
280 }
281 let mut sections = input_sections.to_vec();
282 let ruled = section_count == 2 && end_tangents.is_none();
285 if !breaks.is_empty() && (end_tangents.is_some() || breaks.iter().any(|&b| b == 0 || b >= section_count - 1)) {
286 return Err(KernelRefusal::internal(
287 KernelStage::Collect,
288 "loft_breaks",
289 format!("loftSolid: column breaks {breaks:?} must be interior to {section_count} sections and need no end tangents"),
290 ));
291 }
292 let curve_count = if ruled {
293 super::validation::validate_section_loops(§ions, tolerance, "loftSolid")?
294 } else {
295 super::validation::align_section_starts(&mut sections);
297 validate_sections(§ions, tolerance, "loftSolid", true)?
298 };
299
300 let first_frame = section_frame(§ions[0], tolerance)?;
301 let last_frame = section_frame(§ions[section_count - 1], tolerance)?;
302 if !first_frame.planar || !last_frame.planar {
303 return Err(KernelRefusal::unsupported(
304 KernelStage::Classify,
305 "planar_end_sections",
306 "loftSolid: end sections must be planar",
307 ));
308 }
309 last_frame
312 .centroid
313 .sub(first_frame.centroid)
314 .normalized()
315 .map_err(|_| {
316 KernelRefusal::input(
317 KernelStage::Classify,
318 "coincident_ends",
319 "loftSolid: end sections coincide",
320 )
321 })?;
322 let start_advance = advance_from(
325 §ions,
326 first_frame.centroid,
327 first_frame.normal,
328 1..section_count,
329 tolerance,
330 )?
331 .ok_or_else(|| {
332 KernelRefusal::input(
333 KernelStage::Classify,
334 "start_in_plane",
335 "loftSolid: the loft runs inside its START section's plane — every later section \
336 lies in it, so the start cap would be a sliver rather than a face",
337 )
338 })?;
339 let finish_advance = advance_from(
342 §ions,
343 last_frame.centroid,
344 last_frame.normal,
345 (0..section_count - 1).rev(),
346 tolerance,
347 )?
348 .map(|step| step.scale(-1.0))
349 .ok_or_else(|| {
350 KernelRefusal::input(
351 KernelStage::Classify,
352 "end_in_plane",
353 "loftSolid: the loft runs inside its END section's plane — every earlier section \
354 lies in it, so the end cap would be a sliver rather than a face",
355 )
356 })?;
357 let frames = sections
367 .iter()
368 .map(|section| section_frame(section, tolerance))
369 .collect::<Result<Vec<_>, _>>()?;
370 let parallel = frames
371 .iter()
372 .all(|frame| frame.planar && frame.normal.cross(first_frame.normal).length() <= 1e-9);
373 if parallel {
374 let offsets: Vec<f64> = frames
375 .iter()
376 .map(|frame| frame.centroid.sub(first_frame.centroid).dot(first_frame.normal))
377 .collect();
378 let scale = frames.iter().fold(1.0f64, |m, frame| {
382 m.max(frame.centroid.x.abs()).max(frame.centroid.y.abs()).max(frame.centroid.z.abs())
383 });
384 let noise = 1e-12 * scale;
385 let rise = (offsets[section_count - 1] - offsets[0]).signum();
386 let ruled_end = |k: usize| k == 0 || k == section_count - 1 || breaks.contains(&k);
387 if let Some(k) = (1..section_count).find(|&k| {
388 let step = (offsets[k] - offsets[k - 1]) * rise;
389 if step.abs() <= noise {
390 !(ruled_end(k - 1) && ruled_end(k))
391 } else {
392 step < 0.0
393 }
394 }) {
395 return Err(KernelRefusal::input(
396 KernelStage::Classify,
397 "section_order",
398 format!(
399 "loftSolid: section {k} does not advance past section {} along their common normal \
400 (offsets {:.6} then {:.6}); the loft would turn back through itself",
401 k - 1,
402 offsets[k - 1],
403 offsets[k],
404 ),
405 ));
406 }
407 }
408 let first_normal = if first_frame.normal.dot(start_advance) >= 0.0 {
409 first_frame.normal
410 } else {
411 first_frame.normal.scale(-1.0)
412 };
413 let x_axis = first_normal
414 .perpendicular()
415 .or_refuse(KernelStage::Classify, "section_frame")?;
416 let y_axis = first_normal
417 .cross(x_axis)
418 .normalized()
419 .or_refuse(KernelStage::Classify, "section_frame")?;
420 let mut section_reversed = Vec::with_capacity(section_count);
456 section_reversed.push(
457 profile_area(§ions[0], first_frame.centroid, x_axis, y_axis)
458 .or_refuse(KernelStage::Classify, "profile_area")?
459 < 0.0,
460 );
461 let mut previous_normal = if section_reversed[0] {
462 first_frame.normal.scale(-1.0)
463 } else {
464 first_frame.normal
465 };
466 for section in sections.iter().skip(1) {
467 let normal = section_frame(section, tolerance)?.normal;
468 let flip = normal.dot(previous_normal) < 0.0;
469 section_reversed.push(flip);
470 previous_normal = if flip { normal.scale(-1.0) } else { normal };
471 }
472 let reversed_winding = section_reversed[0];
475 for (index, flip) in section_reversed.into_iter().enumerate() {
476 if flip {
477 sections[index] = reverse_section(§ions[index])?;
478 }
479 }
480
481 if ruled {
482 for curve_index in 0..curve_count {
486 let family = [
487 sections[0][curve_index].clone(),
488 sections[1][curve_index].clone(),
489 ];
490 if family[0].degree == family[1].degree
492 && family[0].knots == family[1].knots
493 && family[0].control_points.len() == family[1].control_points.len()
494 {
495 continue;
496 }
497 let (compatible, _) = crate::coons::compat::make_family_compatible(&family, 1)
498 .or_refuse(KernelStage::Refine, "section_compatibility")?;
499 for (section, curve) in sections.iter_mut().zip(compatible) {
500 section[curve_index] = curve;
501 }
502 }
503 }
504
505 profile.lap("profile");
506 let mut parameters = vec![0.0; section_count];
507 let mut accumulated = vec![0.0; section_count];
508 let mut columns = 0usize;
509 for curve_index in 0..curve_count {
510 for control_index in 0..sections[0][curve_index].control_points.len() {
511 let mut total = 0.0;
512 let mut chords = vec![0.0; section_count];
513 for section_index in 1..section_count {
514 let previous = sections[section_index - 1][curve_index].control_points
515 [control_index]
516 .point()
517 .or_refuse(KernelStage::Refine, "control_point")?;
518 let current = sections[section_index][curve_index].control_points[control_index]
519 .point()
520 .or_refuse(KernelStage::Refine, "control_point")?;
521 total += current.sub(previous).length();
522 chords[section_index] = total;
523 }
524 if total <= tolerance {
525 continue;
526 }
527 for section_index in 0..section_count {
528 accumulated[section_index] += chords[section_index] / total;
529 }
530 columns += 1;
531 }
532 }
533 if columns == 0 {
534 return Err(KernelRefusal::input(
535 KernelStage::Classify,
536 "coincident_sections",
537 "loftSolid: sections coincide",
538 ));
539 }
540 for index in 0..section_count {
541 parameters[index] = accumulated[index] / columns as f64;
542 }
543 parameters[0] = 0.0;
544 parameters[section_count - 1] = 1.0;
545 if parameters.windows(2).any(|pair| pair[1] <= pair[0] + 1e-9) {
546 return Err(KernelRefusal::input(
547 KernelStage::Classify,
548 "section_order",
549 "loftSolid: sections are not strictly ordered",
550 ));
551 }
552 let degree_v = if end_tangents.is_some() || !breaks.is_empty() {
555 3
556 } else {
557 3usize.min(section_count - 1)
558 };
559 let mut skins = Vec::with_capacity(curve_count);
560 for curve_index in 0..curve_count {
561 let reference = §ions[0][curve_index];
562 if ruled {
563 let grid = reference
567 .control_points
568 .iter()
569 .zip(§ions[1][curve_index].control_points)
570 .map(|(&start, &end)| vec![start, end])
571 .collect();
572 skins.push(
573 NurbsSurface::new(
574 reference.degree,
575 1,
576 reference.knots.clone(),
577 vec![0.0, 0.0, 1.0, 1.0],
578 grid,
579 )
580 .or_refuse(KernelStage::Fragment, "skin")?,
581 );
582 continue;
583 }
584 let mut grid = Vec::with_capacity(reference.control_points.len());
585 let mut knots_v = Vec::new();
586 for control_index in 0..reference.control_points.len() {
587 let points = sections
588 .iter()
589 .map(|section| section[curve_index].control_points[control_index].point())
590 .collect::<Result<Vec<_>, String>>()
591 .or_refuse(KernelStage::Refine, "control_point")?;
592 let interpolated = match end_tangents {
593 None if !breaks.is_empty() => super::broken::interpolate_column_broken(&points, ¶meters, breaks)
594 .or_refuse(KernelStage::Refine, "interpolate_broken")?,
595 None => interpolate_curve(&points, degree_v, ¶meters)
596 .or_refuse(KernelStage::Refine, "interpolate")?,
597 Some((start_direction, end_direction)) => {
598 let chord: f64 = points
599 .windows(2)
600 .map(|pair| pair[1].sub(pair[0]).length())
601 .sum();
602 let magnitude = if chord > tolerance { chord } else { 1.0 };
605 crate::interpolate_curve_with_end_tangents(
606 &points,
607 ¶meters,
608 start_direction.scale(magnitude),
609 end_direction.scale(magnitude),
610 )
611 .or_refuse(KernelStage::Refine, "interpolate_tangent")?
612 }
613 };
614 knots_v = interpolated.knots.clone();
615 let weight = reference.control_points[control_index].w;
616 grid.push(
617 interpolated
618 .control_points
619 .iter()
620 .map(|point| Vec4::from_point(point.point().unwrap(), weight))
621 .collect(),
622 );
623 }
624 skins.push(NurbsSurface::new(
625 reference.degree,
626 degree_v,
627 reference.knots.clone(),
628 knots_v,
629 grid,
630 )
631 .or_refuse(KernelStage::Fragment, "skin")?);
632 }
633
634 profile.lap("surface");
635 let bottom = §ions[0];
636 let top = §ions[section_count - 1];
637 let bottom_points = closed_points(bottom, tolerance)?;
638 let top_points = closed_points(top, tolerance)?;
639 let mut vertices = Vec::with_capacity(2 * curve_count);
640 for (index, point) in bottom_points.iter().chain(&top_points).enumerate() {
641 vertices.push(VertexRecord {
642 id: index as u64 + 1,
643 point: *point,
644 });
645 }
646 let mut edges = Vec::with_capacity(3 * curve_count);
647 let mut bottom_edge_ids = Vec::new();
648 let mut top_edge_ids = Vec::new();
649 let mut vertical_edge_ids = Vec::new();
650 for index in 0..curve_count {
651 let [start, end] = bottom[index]
652 .domain()
653 .or_refuse(KernelStage::Fragment, "domain")?;
654 let [top_start, top_end] = top[index]
663 .domain()
664 .or_refuse(KernelStage::Fragment, "domain")?;
665 let bottom_id = 10 + index as u64;
666 let top_id = 10 + curve_count as u64 + index as u64;
667 let vertical_id = 10 + 2 * curve_count as u64 + index as u64;
668 bottom_edge_ids.push(bottom_id);
669 top_edge_ids.push(top_id);
670 vertical_edge_ids.push(vertical_id);
671 edges.push(EdgeRecord {
672 id: bottom_id,
673 curve: bottom[index].clone(),
674 t0: start,
675 t1: end,
676 start_vertex_id: index as u64 + 1,
677 end_vertex_id: ((index + 1) % curve_count) as u64 + 1,
678 degenerate: false,
679 name: None,
680 });
681 edges.push(EdgeRecord {
682 id: top_id,
683 curve: top[index].clone(),
684 t0: top_start,
685 t1: top_end,
686 start_vertex_id: (curve_count + index) as u64 + 1,
687 end_vertex_id: (curve_count + (index + 1) % curve_count) as u64 + 1,
688 degenerate: false,
689 name: None,
690 });
691 let vertical = skins[index]
692 .iso_curve_u(start)
693 .or_refuse(KernelStage::Fragment, "iso_curve")?;
694 let [v_start, v_end] = vertical
695 .domain()
696 .or_refuse(KernelStage::Fragment, "domain")?;
697 edges.push(EdgeRecord {
698 id: vertical_id,
699 curve: vertical,
700 t0: v_start,
701 t1: v_end,
702 start_vertex_id: index as u64 + 1,
703 end_vertex_id: (curve_count + index) as u64 + 1,
704 degenerate: false,
705 name: None,
706 });
707 }
708
709 profile.lap("edges");
710 let mut next_id = 1000u64;
711 let mut faces = Vec::with_capacity(curve_count + 2);
712 for index in 0..curve_count {
713 let [start, end] = bottom[index]
714 .domain()
715 .or_refuse(KernelStage::Fragment, "domain")?;
716 let coedges = vec![
717 CoedgeRecord {
718 id: next_id,
719 edge_id: bottom_edge_ids[index],
720 forward: true,
721 pcurve: parameter_line(start, 0.0, end, 0.0)
722 .or_refuse(KernelStage::Fragment, "pcurve")?,
723 },
724 CoedgeRecord {
725 id: next_id + 1,
726 edge_id: vertical_edge_ids[(index + 1) % curve_count],
727 forward: true,
728 pcurve: parameter_line(end, 0.0, end, 1.0)
729 .or_refuse(KernelStage::Fragment, "pcurve")?,
730 },
731 CoedgeRecord {
732 id: next_id + 2,
733 edge_id: top_edge_ids[index],
734 forward: false,
735 pcurve: parameter_line(end, 1.0, start, 1.0)
736 .or_refuse(KernelStage::Fragment, "pcurve")?,
737 },
738 CoedgeRecord {
739 id: next_id + 3,
740 edge_id: vertical_edge_ids[index],
741 forward: false,
742 pcurve: parameter_line(start, 1.0, start, 0.0)
743 .or_refuse(KernelStage::Fragment, "pcurve")?,
744 },
745 ];
746 next_id += 4;
747 let loop_id = next_id;
748 next_id += 1;
749 let face_id = next_id;
750 next_id += 1;
751 faces.push(FaceRecord {
752 id: face_id,
753 surface: skins[index].clone(),
754 same_sense: true,
755 loops: vec![LoopRecord {
756 id: loop_id,
757 coedges,
758 }],
759 name: None,
760 });
761 }
762 if reversed_winding {
763 faces.reverse();
768 }
769 faces.push(cap_face(
770 bottom,
771 &bottom_edge_ids,
772 &first_frame,
773 start_advance,
774 false,
775 &mut next_id,
776 )?);
777 faces.push(cap_face(
778 top,
779 &top_edge_ids,
780 &last_frame,
781 finish_advance,
782 true,
783 &mut next_id,
784 )?);
785 let solid = BrepSolid {
786 mass_properties_cache: Default::default(),
787 cells: Default::default(),
788 id: next_id + 1,
789 vertices,
790 edges,
791 shells: vec![ShellRecord { id: next_id, faces }],
792 genus: 0,
793 kind: crate::BodyKind::Solid,
794 };
795 profile.lap("topology_pcurves");
796 let issues = solid.validate();
797 profile.lap("validation");
798 if !issues.is_empty() {
799 return Err(KernelRefusal::internal(
800 KernelStage::Validate,
801 "validate",
802 format!(
803 "Rust loft builder produced invalid topology: {issues:?}"
804 ),
805 ));
806 }
807 if !scan {
813 return Ok(solid);
814 }
815 let accepted = crate::accept_sound(solid, "loftSolid");
816 profile.lap("acceptance");
817 accepted
818}