1use crate::{KernelRefusal, KernelStage};
31
32#[derive(Clone, Debug)]
34pub enum LawSegment {
35 Constant { length: f64, radius: f64 },
37 Linear {
40 length: f64,
41 start_radius: f64,
42 end_radius: f64,
43 },
44 Interpolated { points: Vec<(f64, f64)> },
51}
52
53#[derive(Clone, Debug)]
56struct Piece {
57 s0: f64,
58 s1: f64,
59 coeffs: [f64; 6],
61}
62
63impl Piece {
64 fn width(&self) -> f64 {
65 self.s1 - self.s0
66 }
67
68 fn evaluate(&self, s: f64) -> f64 {
69 let u = ((s - self.s0) / self.width()).clamp(0.0, 1.0);
70 poly_eval(&self.coeffs, u)
71 }
72}
73
74#[derive(Clone, Debug)]
80pub struct RadiusLaw {
81 pieces: Vec<Piece>,
82 total: f64,
83}
84
85impl RadiusLaw {
86 pub fn constant(length: f64, radius: f64) -> Result<Self, KernelRefusal> {
88 Self::from_segments(&[LawSegment::Constant { length, radius }])
89 }
90
91 pub fn from_vertex_radii(edge_lengths: &[f64], vertex_radii: &[f64]) -> Result<Self, KernelRefusal> {
99 if edge_lengths.is_empty() {
100 return Err(KernelRefusal::input(
101 KernelStage::Collect,
102 "chain_edges",
103 "radius_law: at least one chain edge length is required",
104 ));
105 }
106 if vertex_radii.len() != edge_lengths.len() + 1 {
107 return Err(KernelRefusal::input(
108 KernelStage::Collect,
109 "vertex_radii_count",
110 format!(
111 "radius_law: need exactly one radius per chain vertex (edges + 1): \
112 {} edges need {} radii, got {}",
113 edge_lengths.len(),
114 edge_lengths.len() + 1,
115 vertex_radii.len()
116 ),
117 ));
118 }
119 for length in edge_lengths {
120 if !(length.is_finite() && *length > 0.0) {
121 return Err(segment_length_refusal());
122 }
123 }
124 let mut points = Vec::with_capacity(vertex_radii.len());
125 let mut abscissa = 0.0;
126 points.push((0.0, vertex_radii[0]));
127 for (length, radius) in edge_lengths.iter().zip(vertex_radii[1..].iter()) {
128 abscissa += length;
129 points.push((abscissa, *radius));
130 }
131 Self::from_segments(&[LawSegment::Interpolated { points }])
132 }
133
134 pub fn from_segments(segments: &[LawSegment]) -> Result<Self, KernelRefusal> {
137 if segments.is_empty() {
138 return Err(KernelRefusal::input(
139 KernelStage::Collect,
140 "segments",
141 "radius_law: at least one segment is required",
142 ));
143 }
144 let mut evals: Vec<SegmentEval> = Vec::with_capacity(segments.len());
147 let mut cursor = 0.0_f64;
148 for segment in segments {
149 let eval = SegmentEval::build(segment, cursor)?;
150 cursor = eval.s_end();
151 evals.push(eval);
152 }
153 let total = cursor;
154 for (index, eval) in evals.iter().enumerate() {
157 if let SegmentEval::Linear { r0, r1, .. } = eval {
158 if (*r0 == 0.0 && index != 0) || (*r1 == 0.0 && index + 1 != evals.len()) {
159 return Err(KernelRefusal::input(
160 KernelStage::Collect,
161 "radius",
162 "radius_law: a radius may be nought only at the law's start or end",
163 ));
164 }
165 }
166 }
167
168 let mut needs_transition = vec![false; evals.len().saturating_sub(1)];
172 for i in 0..needs_transition.len() {
173 let s_j = evals[i].s_end();
174 let (vl, dl) = evals[i].value_slope(s_j);
175 let (vr, dr) = evals[i + 1].value_slope(s_j);
176 needs_transition[i] = vl != vr || dl != dr;
177 }
178
179 let mut pieces: Vec<Piece> = Vec::new();
186 for i in 0..evals.len() {
187 let left_trim = i > 0 && needs_transition[i - 1];
188 let right_trim = i < needs_transition.len() && needs_transition[i];
189 let mid = evals[i].s_start() + evals[i].length() * 0.5;
190 let keep_from = if left_trim { mid } else { evals[i].s_start() };
191 let keep_to = if right_trim { mid } else { evals[i].s_end() };
192 if keep_to > keep_from {
193 evals[i].emit_pieces(keep_from, keep_to, &mut pieces);
194 }
195 if right_trim {
196 let a_s = evals[i].s_start() + evals[i].length() * 0.5;
197 let b_s = evals[i + 1].s_start() + evals[i + 1].length() * 0.5;
198 let (a, da) = evals[i].value_slope(a_s);
199 let (b, db) = evals[i + 1].value_slope(b_s);
200 pieces.push(quintic_bridge(a_s, b_s, a, da, b, db));
201 }
202 }
203 debug_assert!(pieces
204 .windows(2)
205 .all(|pair| (pair[0].s1 - pair[1].s0).abs() == 0.0));
206 Ok(Self { pieces, total })
207 }
208
209 pub fn linear_ends(&self) -> Option<(f64, f64)> {
214 let (r0, r1) = (self.radius_at(0.0), self.radius_at(self.total));
215 let scale = r0.abs().max(r1.abs());
216 let chord = |s: f64| r0 + (r1 - r0) * (s / self.total);
217 let straight = self.pieces.iter().all(|piece| {
218 piece.coeffs[2..].iter().all(|c| *c == 0.0)
219 && (self.radius_at(piece.s0) - chord(piece.s0)).abs() <= 1e-12 * scale
220 && (self.radius_at(piece.s1) - chord(piece.s1)).abs() <= 1e-12 * scale
221 });
222 (self.total > 0.0 && straight).then_some((r0, r1))
223 }
224
225 pub fn total_length(&self) -> f64 {
227 self.total
228 }
229
230 pub fn radius_at(&self, s: f64) -> f64 {
232 debug_assert!(s.is_finite(), "radius_law: abscissa must be finite");
233 let s = s.clamp(0.0, self.total);
234 let index = self
236 .pieces
237 .partition_point(|piece| piece.s1 < s)
238 .min(self.pieces.len() - 1);
239 self.pieces[index].evaluate(s)
240 }
241
242 pub fn radius_at_fraction(&self, fraction: f64) -> f64 {
244 self.radius_at(fraction * self.total)
245 }
246
247 pub fn max_second_derivative(&self, s_a: f64, s_b: f64) -> f64 {
256 let lo = s_a.min(s_b).clamp(0.0, self.total);
257 let hi = s_a.max(s_b).clamp(0.0, self.total);
258 let mut bound = 0.0_f64;
259 for piece in &self.pieces {
260 if piece.s1 < lo || piece.s0 > hi {
261 continue;
262 }
263 let c = &piece.coeffs;
265 let dd = [2.0 * c[2], 6.0 * c[3], 12.0 * c[4], 20.0 * c[5]];
266 let b0 = dd[0];
268 let b1 = dd[0] + dd[1] / 3.0;
269 let b2 = dd[0] + 2.0 * dd[1] / 3.0 + dd[2] / 3.0;
270 let b3 = dd[0] + dd[1] + dd[2] + dd[3];
271 let max_u = b0.abs().max(b1.abs()).max(b2.abs()).max(b3.abs());
272 let width = piece.width();
273 if width > 0.0 {
274 bound = bound.max(max_u / (width * width));
275 }
276 }
277 bound
278 }
279}
280
281enum SegmentEval {
283 Constant {
284 s0: f64,
285 length: f64,
286 radius: f64,
287 },
288 Linear {
289 s0: f64,
290 length: f64,
291 r0: f64,
292 r1: f64,
293 },
294 Interpolated {
295 s0: f64,
296 xs: Vec<f64>,
298 ys: Vec<f64>,
299 ds: Vec<f64>,
301 },
302}
303
304fn check_radius(radius: f64) -> Result<(), KernelRefusal> {
305 if !(radius.is_finite() && radius > 0.0) {
306 return Err(KernelRefusal::input(
307 KernelStage::Collect,
308 "radius",
309 "radius_law: every radius must be positive and finite",
310 ));
311 }
312 Ok(())
313}
314
315fn segment_length_refusal() -> KernelRefusal {
318 KernelRefusal::input(
319 KernelStage::Collect,
320 "segment_length",
321 "radius_law: segment length must be positive and finite",
322 )
323}
324
325impl SegmentEval {
326 fn build(segment: &LawSegment, s0: f64) -> Result<Self, KernelRefusal> {
327 match segment {
328 LawSegment::Constant { length, radius } => {
329 if !(length.is_finite() && *length > 0.0) {
330 return Err(segment_length_refusal());
331 }
332 check_radius(*radius)?;
333 Ok(Self::Constant {
334 s0,
335 length: *length,
336 radius: *radius,
337 })
338 }
339 LawSegment::Linear {
340 length,
341 start_radius,
342 end_radius,
343 } => {
344 if !(length.is_finite() && *length > 0.0) {
345 return Err(segment_length_refusal());
346 }
347 if *start_radius == 0.0 || *end_radius == 0.0 {
350 check_radius(start_radius.max(*end_radius))?;
351 } else {
352 check_radius(*start_radius)?;
353 check_radius(*end_radius)?;
354 }
355 Ok(Self::Linear {
356 s0,
357 length: *length,
358 r0: *start_radius,
359 r1: *end_radius,
360 })
361 }
362 LawSegment::Interpolated { points } => {
363 if points.len() < 2 {
364 return Err(KernelRefusal::input(
365 KernelStage::Collect,
366 "interpolation_points",
367 "radius_law: an interpolated segment needs at least two points",
368 ));
369 }
370 if points[0].0 != 0.0 {
371 return Err(KernelRefusal::input(
372 KernelStage::Collect,
373 "interpolation_start",
374 "radius_law: interpolation abscissas must start at exactly 0",
375 ));
376 }
377 for pair in points.windows(2) {
378 if !(pair[1].0.is_finite() && pair[1].0 > pair[0].0) {
379 return Err(KernelRefusal::input(
380 KernelStage::Collect,
381 "interpolation_monotone",
382 "radius_law: interpolation abscissas must be strictly increasing",
383 ));
384 }
385 }
386 for (_, radius) in points {
387 check_radius(*radius)?;
388 }
389 let xs: Vec<f64> = points.iter().map(|(x, _)| s0 + x).collect();
390 let ys: Vec<f64> = points.iter().map(|(_, y)| *y).collect();
391 let ds = pchip_slopes(&xs, &ys);
392 Ok(Self::Interpolated { s0, xs, ys, ds })
393 }
394 }
395 }
396
397 fn s_start(&self) -> f64 {
398 match self {
399 Self::Constant { s0, .. } | Self::Linear { s0, .. } | Self::Interpolated { s0, .. } => {
400 *s0
401 }
402 }
403 }
404
405 fn length(&self) -> f64 {
406 match self {
407 Self::Constant { length, .. } | Self::Linear { length, .. } => *length,
408 Self::Interpolated { s0, xs, .. } => xs[xs.len() - 1] - s0,
409 }
410 }
411
412 fn s_end(&self) -> f64 {
413 match self {
414 Self::Constant { s0, length, .. } | Self::Linear { s0, length, .. } => s0 + length,
415 Self::Interpolated { xs, .. } => xs[xs.len() - 1],
416 }
417 }
418
419 fn value_slope(&self, s: f64) -> (f64, f64) {
424 match self {
425 Self::Constant { radius, .. } => (*radius, 0.0),
426 Self::Linear {
427 s0,
428 length,
429 r0,
430 r1,
431 } => {
432 let slope = (r1 - r0) / length;
433 (r0 + slope * (s - s0), slope)
434 }
435 Self::Interpolated { xs, ys, ds, .. } => {
436 let i = interval_index(xs, s);
437 let h = xs[i + 1] - xs[i];
438 let coeffs = hermite_cubic(ys[i], ds[i] * h, ys[i + 1], ds[i + 1] * h);
439 let u = ((s - xs[i]) / h).clamp(0.0, 1.0);
440 let deriv = poly_eval(&poly_derivative(&coeffs), u) / h;
441 (poly_eval(&coeffs, u), deriv)
442 }
443 }
444 }
445
446 fn emit_pieces(&self, from: f64, to: f64, out: &mut Vec<Piece>) {
448 match self {
449 Self::Constant { radius, .. } => out.push(Piece {
450 s0: from,
451 s1: to,
452 coeffs: [*radius, 0.0, 0.0, 0.0, 0.0, 0.0],
453 }),
454 Self::Linear { .. } => {
455 let (va, slope) = self.value_slope(from);
456 out.push(Piece {
457 s0: from,
458 s1: to,
459 coeffs: [va, slope * (to - from), 0.0, 0.0, 0.0, 0.0],
460 });
461 }
462 Self::Interpolated { xs, ys, ds, .. } => {
463 for i in 0..xs.len() - 1 {
464 let (x0, x1) = (xs[i], xs[i + 1]);
465 let (a, b) = (x0.max(from), x1.min(to));
466 if b <= a {
467 continue;
468 }
469 let h = x1 - x0;
470 let cubic = hermite_cubic(ys[i], ds[i] * h, ys[i + 1], ds[i + 1] * h);
471 let coeffs = poly_restrict(&cubic, (a - x0) / h, (b - x0) / h);
472 out.push(Piece {
473 s0: a,
474 s1: b,
475 coeffs,
476 });
477 }
478 }
479 }
480 }
481}
482
483fn quintic_bridge(a_s: f64, b_s: f64, a: f64, da: f64, b: f64, db: f64) -> Piece {
490 let w = b_s - a_s;
491 let a1 = da * w;
494 let b1 = db * w;
495 let d = b - a - a1;
496 let e = b1 - a1;
497 Piece {
500 s0: a_s,
501 s1: b_s,
502 coeffs: [
503 a,
504 a1,
505 0.0,
506 10.0 * d - 4.0 * e,
507 7.0 * e - 15.0 * d,
508 6.0 * d - 3.0 * e,
509 ],
510 }
511}
512
513fn poly_eval(coeffs: &[f64; 6], u: f64) -> f64 {
515 let mut value = coeffs[5];
516 for k in (0..5).rev() {
517 value = value * u + coeffs[k];
518 }
519 value
520}
521
522fn poly_derivative(coeffs: &[f64; 6]) -> [f64; 6] {
524 let mut out = [0.0; 6];
525 for k in 1..6 {
526 out[k - 1] = coeffs[k] * k as f64;
527 }
528 out
529}
530
531fn poly_restrict(coeffs: &[f64; 6], x0: f64, x1: f64) -> [f64; 6] {
534 let h = x1 - x0;
535 let mut result = [0.0; 6];
536 let mut power = [0.0; 6];
538 power[0] = 1.0;
539 for k in 0..6 {
540 for j in 0..6 {
541 result[j] += coeffs[k] * power[j];
542 }
543 if k < 5 {
544 let mut next = [0.0; 6];
546 for j in 0..6 {
547 next[j] += power[j] * x0;
548 if j + 1 < 6 {
549 next[j + 1] += power[j] * h;
550 }
551 }
552 power = next;
553 }
554 }
555 result
556}
557
558fn hermite_cubic(y0: f64, d0: f64, y1: f64, d1: f64) -> [f64; 6] {
561 let delta = y1 - y0;
562 [
563 y0,
564 d0,
565 3.0 * delta - 2.0 * d0 - d1,
566 -2.0 * delta + d0 + d1,
567 0.0,
568 0.0,
569 ]
570}
571
572fn interval_index(xs: &[f64], s: f64) -> usize {
574 let mut i = xs.partition_point(|x| *x <= s);
575 i = i.clamp(1, xs.len() - 1);
576 i - 1
577}
578
579fn pchip_slopes(xs: &[f64], ys: &[f64]) -> Vec<f64> {
582 let n = xs.len();
583 debug_assert!(n >= 2);
584 let m = n - 1;
585 let h: Vec<f64> = (0..m).map(|i| xs[i + 1] - xs[i]).collect();
586 let secant: Vec<f64> = (0..m).map(|i| (ys[i + 1] - ys[i]) / h[i]).collect();
587 let mut d = vec![0.0_f64; n];
588 if n == 2 {
589 d[0] = secant[0];
590 d[1] = secant[0];
591 return d;
592 }
593 for i in 1..m {
597 let (s0, s1) = (secant[i - 1], secant[i]);
598 if s0 * s1 > 0.0 {
599 let w1 = 2.0 * h[i] + h[i - 1];
600 let w2 = h[i] + 2.0 * h[i - 1];
601 d[i] = (w1 + w2) / (w1 / s0 + w2 / s1);
602 }
603 }
604 d[0] = end_slope(h[0], h[1], secant[0], secant[1]);
607 d[n - 1] = end_slope(h[m - 1], h[m - 2], secant[m - 1], secant[m - 2]);
608 d
609}
610
611fn end_slope(h0: f64, h1: f64, s0: f64, s1: f64) -> f64 {
614 let mut d = ((2.0 * h0 + h1) * s0 - h0 * s1) / (h0 + h1);
615 if d * s0 <= 0.0 {
616 d = 0.0;
617 } else if s0 * s1 < 0.0 && d.abs() > 3.0 * s0.abs() {
618 d = 3.0 * s0;
619 }
620 d
621}
622