brep_kernel/construction/loft_topology/
guided.rs1use super::*;
2
3fn guided_section_centroid(curves: &[NurbsCurve]) -> Result<Vec3, String> {
6 let mut sum = Vec3::default();
7 let mut count = 0usize;
8 for curve in curves {
9 let [start, end] = curve.domain()?;
10 for index in 0..16 {
11 sum = sum.add(curve.evaluate(start + (end - start) * index as f64 / 16.0)?);
12 count += 1;
13 }
14 }
15 if count == 0 {
16 return Err("guidedLoft: a section has no sampleable curves".into());
17 }
18 Ok(sum.scale(1.0 / count as f64))
19}
20
21pub fn loft_profile_brep_guided(
37 sections: &[Vec<NurbsCurve>],
38 guide: &NurbsCurve,
39 name: Option<&str>,
40) -> Result<BrepSolid, String> {
41 loft_profile_brep_guided_core(sections, guide, name, false)
42}
43
44pub fn loft_profile_brep_guided_frame(
58 sections: &[Vec<NurbsCurve>],
59 guide: &NurbsCurve,
60 name: Option<&str>,
61) -> Result<BrepSolid, String> {
62 loft_profile_brep_guided_core(sections, guide, name, true)
63}
64
65struct GuidedFrames {
68 params: Vec<f64>,
69 points: Vec<Vec3>,
70 tangents: Vec<Vec3>,
71 r_axes: Vec<Vec3>,
72 s_axes: Vec<Vec3>,
73}
74
75impl GuidedFrames {
76 fn index_of(&self, t: f64) -> Result<usize, String> {
79 let lower = self.params.partition_point(|p| *p < t - 1e-9);
80 if lower < self.params.len() && (self.params[lower] - t).abs() <= 1e-9 {
81 Ok(lower)
82 } else {
83 Err(format!("guidedLoft: no frame marched at parameter {t}"))
84 }
85 }
86}
87
88fn guided_frames(
94 guide: &NurbsCurve,
95 g0: f64,
96 g1: f64,
97 station_params: &[f64],
98 section_params: &[f64],
99) -> Result<GuidedFrames, String> {
100 let mut params: Vec<f64> = station_params
101 .iter()
102 .chain(section_params.iter())
103 .copied()
104 .collect();
105 params.sort_by(|a, b| a.partial_cmp(b).expect("guide params are finite"));
106 params.dedup_by(|a, b| (*a - *b).abs() <= 1e-12);
107
108 let count = params.len();
109 let mut points = Vec::with_capacity(count);
110 let mut tangents = Vec::with_capacity(count);
111 for (index, t) in params.iter().enumerate() {
112 let derivatives = guide.derivatives(g0 + (g1 - g0) * t, 1)?;
113 let tangent = derivatives[1]
114 .normalized()
115 .map_err(|_| format!("guidedLoft: guide tangent is degenerate at station {index}"))?;
116 points.push(derivatives[0]);
117 tangents.push(tangent);
118 }
119
120 let mut r_axes = Vec::with_capacity(count);
121 let mut s_axes = Vec::with_capacity(count);
122 let r0 = tangents[0].perpendicular()?; s_axes.push(tangents[0].cross(r0).normalized()?);
124 r_axes.push(r0);
125 for index in 0..count - 1 {
126 let t_next = tangents[index + 1];
127 let v1 = points[index + 1].sub(points[index]);
128 let c1 = v1.dot(v1);
129 let r_candidate = if c1 <= 1e-18 {
130 r_axes[index]
131 } else {
132 let reflected_r = r_axes[index].sub(v1.scale(2.0 / c1 * v1.dot(r_axes[index])));
133 let reflected_t = tangents[index].sub(v1.scale(2.0 / c1 * v1.dot(tangents[index])));
134 let v2 = t_next.sub(reflected_t);
135 let c2 = v2.dot(v2);
136 if c2 <= 1e-18 {
137 reflected_r
138 } else {
139 reflected_r.sub(v2.scale(2.0 / c2 * v2.dot(reflected_r)))
140 }
141 };
142 let r_next = r_candidate
143 .sub(t_next.scale(r_candidate.dot(t_next)))
144 .normalized()
145 .map_err(|_| format!("guidedLoft: frame degenerated at station {index}"))?;
146 s_axes.push(t_next.cross(r_next).normalized()?);
147 r_axes.push(r_next);
148 }
149 Ok(GuidedFrames {
150 params,
151 points,
152 tangents,
153 r_axes,
154 s_axes,
155 })
156}
157
158fn loft_profile_brep_guided_core(
159 sections: &[Vec<NurbsCurve>],
160 guide: &NurbsCurve,
161 name: Option<&str>,
162 rotate_to_frame: bool,
163) -> Result<BrepSolid, String> {
164 let _ = name;
167 let tolerance = 1e-6;
168 let section_count = sections.len();
169 if section_count < 2 {
170 return Err("guidedLoft: need at least 2 sections".into());
171 }
172
173 let curve_count = validate_sections(sections, tolerance, "guidedLoft", true)?;
174
175 let [g0, g1] = guide.domain()?;
177 if (g1 - g0).abs() <= tolerance {
178 return Err("guidedLoft: guide domain is degenerate".into());
179 }
180 let guide_start = guide.evaluate(g0)?;
181 let mut guide_extent = 0.0_f64;
182 for index in 1..=8 {
183 let point = guide.evaluate(g0 + (g1 - g0) * index as f64 / 8.0)?;
184 guide_extent = guide_extent.max(point.sub(guide_start).length());
185 }
186 if guide_extent <= tolerance {
187 return Err("guidedLoft: guide curve is degenerate (no spatial extent)".into());
188 }
189 let mut u_list = Vec::with_capacity(section_count);
190 for section in sections {
191 let centroid = guided_section_centroid(section)?;
192 let projection = crate::project_point_to_curve(guide, centroid)?;
193 let u = ((projection.u - g0) / (g1 - g0)).clamp(0.0, 1.0);
194 u_list.push(u);
195 }
196
197 let increasing = u_list.windows(2).all(|pair| pair[1] > pair[0] + tolerance);
202 let decreasing = u_list.windows(2).all(|pair| pair[1] < pair[0] - tolerance);
203 if !increasing && !decreasing {
204 return Err("guidedLoft: sections do not project monotonically onto the guide".into());
205 }
206 let mut ordered_sections: Vec<Vec<NurbsCurve>> = sections.to_vec();
207 let mut ordered_u = u_list;
208 if decreasing {
209 ordered_sections.reverse();
210 ordered_u.reverse();
211 }
212 let u_first = ordered_u[0];
213 let u_last = ordered_u[section_count - 1];
214 if u_last - u_first <= tolerance {
215 return Err("guidedLoft: sections project to coincident guide stations".into());
216 }
217
218 let station_count = 24usize.max(6 * section_count);
225 let station_params: Vec<f64> = (0..station_count)
226 .map(|station| {
227 let frac = station as f64 / (station_count - 1) as f64;
228 u_first + (u_last - u_first) * frac
229 })
230 .collect();
231
232 let frames = if rotate_to_frame {
237 Some(guided_frames(guide, g0, g1, &station_params, &ordered_u)?)
238 } else {
239 None
240 };
241 let blend_sources: Vec<Vec<NurbsCurve>> = if let Some(frames) = &frames {
242 let mut localized = Vec::with_capacity(section_count);
243 for (section_index, section) in ordered_sections.iter().enumerate() {
244 let frame = frames.index_of(ordered_u[section_index])?;
245 let origin = frames.points[frame];
246 let (r, s, t_axis) = (
247 frames.r_axes[frame],
248 frames.s_axes[frame],
249 frames.tangents[frame],
250 );
251 let mut local_section = Vec::with_capacity(curve_count);
252 for curve in section {
253 let control_points = curve
254 .control_points
255 .iter()
256 .map(|point| {
257 let weight = point.w;
258 let local = Vec3::new(point.x / weight, point.y / weight, point.z / weight)
259 .sub(origin);
260 Vec4 {
261 x: local.dot(r) * weight,
262 y: local.dot(s) * weight,
263 z: local.dot(t_axis) * weight,
264 w: weight,
265 }
266 })
267 .collect();
268 local_section.push(NurbsCurve::new(
269 curve.degree,
270 curve.knots.clone(),
271 control_points,
272 )?);
273 }
274 localized.push(local_section);
275 }
276 localized
277 } else {
278 ordered_sections.clone()
279 };
280
281 let mut blended_sections: Vec<Vec<NurbsCurve>> = Vec::with_capacity(station_count);
282 for &t in &station_params {
283 let mut interval = 0usize;
285 while interval + 1 < section_count - 1 && ordered_u[interval + 1] <= t {
286 interval += 1;
287 }
288 let u_lo = ordered_u[interval];
289 let u_hi = ordered_u[interval + 1];
290 let span = u_hi - u_lo;
291 if span <= tolerance {
292 return Err("guidedLoft: sections project to coincident guide stations".into());
293 }
294 let f = ((t - u_lo) / span).clamp(0.0, 1.0);
295 let section_lo = &blend_sources[interval];
296 let section_hi = &blend_sources[interval + 1];
297 let mut blended: Vec<NurbsCurve> = Vec::with_capacity(curve_count);
302 for curve_index in 0..curve_count {
303 let curve_lo = §ion_lo[curve_index];
304 let curve_hi = §ion_hi[curve_index];
305 let control_points = curve_lo
306 .control_points
307 .iter()
308 .zip(&curve_hi.control_points)
309 .map(|(a, b)| Vec4 {
310 x: a.x * (1.0 - f) + b.x * f,
311 y: a.y * (1.0 - f) + b.y * f,
312 z: a.z * (1.0 - f) + b.z * f,
313 w: a.w * (1.0 - f) + b.w * f,
314 })
315 .collect();
316 blended.push(NurbsCurve::new(
317 curve_lo.degree,
318 curve_lo.knots.clone(),
319 control_points,
320 )?);
321 }
322 let placed: Vec<NurbsCurve> = if let Some(frames) = &frames {
323 let frame = frames.index_of(t)?;
325 let origin = frames.points[frame];
326 let (r, s, t_axis) = (
327 frames.r_axes[frame],
328 frames.s_axes[frame],
329 frames.tangents[frame],
330 );
331 let mut placed = Vec::with_capacity(curve_count);
332 for curve in &blended {
333 let control_points = curve
334 .control_points
335 .iter()
336 .map(|point| {
337 let weight = point.w;
338 let world = origin
339 .add(r.scale(point.x / weight))
340 .add(s.scale(point.y / weight))
341 .add(t_axis.scale(point.z / weight));
342 Vec4 {
343 x: world.x * weight,
344 y: world.y * weight,
345 z: world.z * weight,
346 w: weight,
347 }
348 })
349 .collect();
350 placed.push(NurbsCurve::new(
351 curve.degree,
352 curve.knots.clone(),
353 control_points,
354 )?);
355 }
356 placed
357 } else {
358 let blended_centroid = guided_section_centroid(&blended)?;
360 let guide_point = guide.evaluate(g0 + (g1 - g0) * t)?;
361 let delta = guide_point.sub(blended_centroid);
362 let mut placed = Vec::with_capacity(curve_count);
363 for curve in &blended {
364 let control_points = curve
365 .control_points
366 .iter()
367 .map(|point| Vec4 {
368 x: point.x + point.w * delta.x,
369 y: point.y + point.w * delta.y,
370 z: point.z + point.w * delta.z,
371 w: point.w,
372 })
373 .collect();
374 placed.push(NurbsCurve::new(
375 curve.degree,
376 curve.knots.clone(),
377 control_points,
378 )?);
379 }
380 placed
381 };
382 blended_sections.push(placed);
383 }
384
385 loft_profile_brep(&blended_sections)
387 .map_err(|error| format!("guidedLoft: loft through guided sections failed: {error}"))
388}