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 first_normal = if first_frame.normal.dot(start_advance) >= 0.0 {
358 first_frame.normal
359 } else {
360 first_frame.normal.scale(-1.0)
361 };
362 let x_axis = first_normal
363 .perpendicular()
364 .or_refuse(KernelStage::Classify, "section_frame")?;
365 let y_axis = first_normal
366 .cross(x_axis)
367 .normalized()
368 .or_refuse(KernelStage::Classify, "section_frame")?;
369 let mut section_reversed = Vec::with_capacity(section_count);
405 section_reversed.push(
406 profile_area(§ions[0], first_frame.centroid, x_axis, y_axis)
407 .or_refuse(KernelStage::Classify, "profile_area")?
408 < 0.0,
409 );
410 let mut previous_normal = if section_reversed[0] {
411 first_frame.normal.scale(-1.0)
412 } else {
413 first_frame.normal
414 };
415 for section in sections.iter().skip(1) {
416 let normal = section_frame(section, tolerance)?.normal;
417 let flip = normal.dot(previous_normal) < 0.0;
418 section_reversed.push(flip);
419 previous_normal = if flip { normal.scale(-1.0) } else { normal };
420 }
421 let reversed_winding = section_reversed[0];
424 for (index, flip) in section_reversed.into_iter().enumerate() {
425 if flip {
426 sections[index] = reverse_section(§ions[index])?;
427 }
428 }
429
430 if ruled {
431 for curve_index in 0..curve_count {
435 let family = [
436 sections[0][curve_index].clone(),
437 sections[1][curve_index].clone(),
438 ];
439 if family[0].degree == family[1].degree
441 && family[0].knots == family[1].knots
442 && family[0].control_points.len() == family[1].control_points.len()
443 {
444 continue;
445 }
446 let (compatible, _) = crate::coons::compat::make_family_compatible(&family, 1)
447 .or_refuse(KernelStage::Refine, "section_compatibility")?;
448 for (section, curve) in sections.iter_mut().zip(compatible) {
449 section[curve_index] = curve;
450 }
451 }
452 }
453
454 profile.lap("profile");
455 let mut parameters = vec![0.0; section_count];
456 let mut accumulated = vec![0.0; section_count];
457 let mut columns = 0usize;
458 for curve_index in 0..curve_count {
459 for control_index in 0..sections[0][curve_index].control_points.len() {
460 let mut total = 0.0;
461 let mut chords = vec![0.0; section_count];
462 for section_index in 1..section_count {
463 let previous = sections[section_index - 1][curve_index].control_points
464 [control_index]
465 .point()
466 .or_refuse(KernelStage::Refine, "control_point")?;
467 let current = sections[section_index][curve_index].control_points[control_index]
468 .point()
469 .or_refuse(KernelStage::Refine, "control_point")?;
470 total += current.sub(previous).length();
471 chords[section_index] = total;
472 }
473 if total <= tolerance {
474 continue;
475 }
476 for section_index in 0..section_count {
477 accumulated[section_index] += chords[section_index] / total;
478 }
479 columns += 1;
480 }
481 }
482 if columns == 0 {
483 return Err(KernelRefusal::input(
484 KernelStage::Classify,
485 "coincident_sections",
486 "loftSolid: sections coincide",
487 ));
488 }
489 for index in 0..section_count {
490 parameters[index] = accumulated[index] / columns as f64;
491 }
492 parameters[0] = 0.0;
493 parameters[section_count - 1] = 1.0;
494 if parameters.windows(2).any(|pair| pair[1] <= pair[0] + 1e-9) {
495 return Err(KernelRefusal::input(
496 KernelStage::Classify,
497 "section_order",
498 "loftSolid: sections are not strictly ordered",
499 ));
500 }
501 let degree_v = if end_tangents.is_some() || !breaks.is_empty() {
504 3
505 } else {
506 3usize.min(section_count - 1)
507 };
508 let mut skins = Vec::with_capacity(curve_count);
509 for curve_index in 0..curve_count {
510 let reference = §ions[0][curve_index];
511 if ruled {
512 let grid = reference
516 .control_points
517 .iter()
518 .zip(§ions[1][curve_index].control_points)
519 .map(|(&start, &end)| vec![start, end])
520 .collect();
521 skins.push(
522 NurbsSurface::new(
523 reference.degree,
524 1,
525 reference.knots.clone(),
526 vec![0.0, 0.0, 1.0, 1.0],
527 grid,
528 )
529 .or_refuse(KernelStage::Fragment, "skin")?,
530 );
531 continue;
532 }
533 let mut grid = Vec::with_capacity(reference.control_points.len());
534 let mut knots_v = Vec::new();
535 for control_index in 0..reference.control_points.len() {
536 let points = sections
537 .iter()
538 .map(|section| section[curve_index].control_points[control_index].point())
539 .collect::<Result<Vec<_>, String>>()
540 .or_refuse(KernelStage::Refine, "control_point")?;
541 let interpolated = match end_tangents {
542 None if !breaks.is_empty() => super::broken::interpolate_column_broken(&points, ¶meters, breaks)
543 .or_refuse(KernelStage::Refine, "interpolate_broken")?,
544 None => interpolate_curve(&points, degree_v, ¶meters)
545 .or_refuse(KernelStage::Refine, "interpolate")?,
546 Some((start_direction, end_direction)) => {
547 let chord: f64 = points
548 .windows(2)
549 .map(|pair| pair[1].sub(pair[0]).length())
550 .sum();
551 let magnitude = if chord > tolerance { chord } else { 1.0 };
554 crate::interpolate_curve_with_end_tangents(
555 &points,
556 ¶meters,
557 start_direction.scale(magnitude),
558 end_direction.scale(magnitude),
559 )
560 .or_refuse(KernelStage::Refine, "interpolate_tangent")?
561 }
562 };
563 knots_v = interpolated.knots.clone();
564 let weight = reference.control_points[control_index].w;
565 grid.push(
566 interpolated
567 .control_points
568 .iter()
569 .map(|point| Vec4::from_point(point.point().unwrap(), weight))
570 .collect(),
571 );
572 }
573 skins.push(NurbsSurface::new(
574 reference.degree,
575 degree_v,
576 reference.knots.clone(),
577 knots_v,
578 grid,
579 )
580 .or_refuse(KernelStage::Fragment, "skin")?);
581 }
582
583 profile.lap("surface");
584 let bottom = §ions[0];
585 let top = §ions[section_count - 1];
586 let bottom_points = closed_points(bottom, tolerance)?;
587 let top_points = closed_points(top, tolerance)?;
588 let mut vertices = Vec::with_capacity(2 * curve_count);
589 for (index, point) in bottom_points.iter().chain(&top_points).enumerate() {
590 vertices.push(VertexRecord {
591 id: index as u64 + 1,
592 point: *point,
593 });
594 }
595 let mut edges = Vec::with_capacity(3 * curve_count);
596 let mut bottom_edge_ids = Vec::new();
597 let mut top_edge_ids = Vec::new();
598 let mut vertical_edge_ids = Vec::new();
599 for index in 0..curve_count {
600 let [start, end] = bottom[index]
601 .domain()
602 .or_refuse(KernelStage::Fragment, "domain")?;
603 let [top_start, top_end] = top[index]
612 .domain()
613 .or_refuse(KernelStage::Fragment, "domain")?;
614 let bottom_id = 10 + index as u64;
615 let top_id = 10 + curve_count as u64 + index as u64;
616 let vertical_id = 10 + 2 * curve_count as u64 + index as u64;
617 bottom_edge_ids.push(bottom_id);
618 top_edge_ids.push(top_id);
619 vertical_edge_ids.push(vertical_id);
620 edges.push(EdgeRecord {
621 id: bottom_id,
622 curve: bottom[index].clone(),
623 t0: start,
624 t1: end,
625 start_vertex_id: index as u64 + 1,
626 end_vertex_id: ((index + 1) % curve_count) as u64 + 1,
627 degenerate: false,
628 name: None,
629 });
630 edges.push(EdgeRecord {
631 id: top_id,
632 curve: top[index].clone(),
633 t0: top_start,
634 t1: top_end,
635 start_vertex_id: (curve_count + index) as u64 + 1,
636 end_vertex_id: (curve_count + (index + 1) % curve_count) as u64 + 1,
637 degenerate: false,
638 name: None,
639 });
640 let vertical = skins[index]
641 .iso_curve_u(start)
642 .or_refuse(KernelStage::Fragment, "iso_curve")?;
643 let [v_start, v_end] = vertical
644 .domain()
645 .or_refuse(KernelStage::Fragment, "domain")?;
646 edges.push(EdgeRecord {
647 id: vertical_id,
648 curve: vertical,
649 t0: v_start,
650 t1: v_end,
651 start_vertex_id: index as u64 + 1,
652 end_vertex_id: (curve_count + index) as u64 + 1,
653 degenerate: false,
654 name: None,
655 });
656 }
657
658 profile.lap("edges");
659 let mut next_id = 1000u64;
660 let mut faces = Vec::with_capacity(curve_count + 2);
661 for index in 0..curve_count {
662 let [start, end] = bottom[index]
663 .domain()
664 .or_refuse(KernelStage::Fragment, "domain")?;
665 let coedges = vec![
666 CoedgeRecord {
667 id: next_id,
668 edge_id: bottom_edge_ids[index],
669 forward: true,
670 pcurve: parameter_line(start, 0.0, end, 0.0)
671 .or_refuse(KernelStage::Fragment, "pcurve")?,
672 },
673 CoedgeRecord {
674 id: next_id + 1,
675 edge_id: vertical_edge_ids[(index + 1) % curve_count],
676 forward: true,
677 pcurve: parameter_line(end, 0.0, end, 1.0)
678 .or_refuse(KernelStage::Fragment, "pcurve")?,
679 },
680 CoedgeRecord {
681 id: next_id + 2,
682 edge_id: top_edge_ids[index],
683 forward: false,
684 pcurve: parameter_line(end, 1.0, start, 1.0)
685 .or_refuse(KernelStage::Fragment, "pcurve")?,
686 },
687 CoedgeRecord {
688 id: next_id + 3,
689 edge_id: vertical_edge_ids[index],
690 forward: false,
691 pcurve: parameter_line(start, 1.0, start, 0.0)
692 .or_refuse(KernelStage::Fragment, "pcurve")?,
693 },
694 ];
695 next_id += 4;
696 let loop_id = next_id;
697 next_id += 1;
698 let face_id = next_id;
699 next_id += 1;
700 faces.push(FaceRecord {
701 id: face_id,
702 surface: skins[index].clone(),
703 same_sense: true,
704 loops: vec![LoopRecord {
705 id: loop_id,
706 coedges,
707 }],
708 name: None,
709 });
710 }
711 if reversed_winding {
712 faces.reverse();
717 }
718 faces.push(cap_face(
719 bottom,
720 &bottom_edge_ids,
721 &first_frame,
722 start_advance,
723 false,
724 &mut next_id,
725 )?);
726 faces.push(cap_face(
727 top,
728 &top_edge_ids,
729 &last_frame,
730 finish_advance,
731 true,
732 &mut next_id,
733 )?);
734 let solid = BrepSolid {
735 mass_properties_cache: Default::default(),
736 cells: Default::default(),
737 id: next_id + 1,
738 vertices,
739 edges,
740 shells: vec![ShellRecord { id: next_id, faces }],
741 genus: 0,
742 kind: crate::BodyKind::Solid,
743 };
744 profile.lap("topology_pcurves");
745 let issues = solid.validate();
746 profile.lap("validation");
747 if !issues.is_empty() {
748 return Err(KernelRefusal::internal(
749 KernelStage::Validate,
750 "validate",
751 format!(
752 "Rust loft builder produced invalid topology: {issues:?}"
753 ),
754 ));
755 }
756 if !scan {
762 return Ok(solid);
763 }
764 let accepted = crate::accept_sound(solid, "loftSolid");
765 profile.lap("acceptance");
766 accepted
767}