Skip to main content

brep_construction/construction/sweep_topology/
stations.rs

1//! Error-driven station placement, and the MEASURED bound a station sweep
2//! reports (kinematic-sweep plan, item 2).
3//!
4//! A station sweep places rigid copies of the section at sampled stations and
5//! lofts through them; between stations the loft's cubic v-interpolant stands
6//! in for the path, and everything it gets wrong is a function of where the
7//! stations are. Two instruments here read that:
8//!
9//! - [`spine_deviations`]: the loft's own interpolant of the STATION POINTS
10//!   (the same fit, the same chord parameters) against the true path between
11//!   the stations, one number per span. The chain sampler refines the spans
12//!   that read over the requested tolerance ([`refine_parameters`]).
13//! - [`station_report`]: after the sections are placed, the same interpolants
14//!   of the section's centre track and frame axes — which, because the loft's
15//!   fit is linear in the data and every column shares one parameter vector,
16//!   ARE the built wall between stations — against the true path and the true
17//!   transported frame: the worst wall deviation, and the built solid's volume
18//!   by quadrature against the kinematic sweep's own volume. The built volume
19//!   is the loft's to quadrature precision (`the_station_report_reads_the_
20//!   built_volume` pins it against `solid_mass_properties` at 1e-10), so the
21//!   reported residual is the Pappus residual itself, not a bound on it.
22use crate::mass_properties::{GAUSS_W, GAUSS_X};
23use crate::{interpolate_curve, interpolate_curve_closed, NurbsCurve, Vec3};
24use crate::{Approximation, KernelRefusal, KernelStage, OrRefuse};
25
26/// The centre-track deviation a station sweep is refined to when its caller
27/// names none: 1e-4 mm. Read off the tolerance ladder in the record: the
28/// loosest value at which both closed rings the plan named sit under 1e-6
29/// relative on their closed forms (the rounded rectangle 4.8e-4 → 1.9e-7 at
30/// 211 stations from 81, the filleted skew quad 8.3e-4 → 7.4e-8 at 248 from
31/// 92), while the `R = 10` ring keeps its 64 stations and every single-curve
32/// fixture the landed geometry pins (a quarter arc at 32 stations reads
33/// 1.4e-7, a 350° arc 3.9e-5) stays under it and so bit-identical. One
34/// decade tighter costs half again as many stations for a residual already
35/// under 1e-7.
36pub const SWEEP_DEFAULT_TOLERANCE: f64 = 1e-4;
37
38/// The loft's station cap: its interpolation solve is per control column and
39/// a run past this looks like a hang. Refinement stops here and says so.
40pub const SWEEP_MAX_STATIONS: usize = 1024;
41
42/// How many refinement rounds the sampler runs before it stops and reports
43/// what it reached (`StationBudget::rounds_exhausted`). A round splits an
44/// offending span by up to 8, so six rounds cover a span 2.6e5× over under
45/// the `h²` law a G1 joint's span obeys.
46pub const SWEEP_REFINEMENT_ROUNDS: usize = 6;
47
48/// Where a station sits on the chain: the segment its NEXT span runs on, and
49/// its parameter there. A joint station belongs to the segment it departs
50/// into; the last station of an open run keeps the segment it arrived on.
51#[derive(Clone, Copy, Debug, PartialEq)]
52pub struct StationParam {
53    pub segment: usize,
54    pub t: f64,
55}
56
57/// What the sampler did to reach its stations.
58#[derive(Clone, Copy, Debug, PartialEq)]
59pub struct StationBudget {
60    /// The stations the floors gave before any refinement.
61    pub initial: usize,
62    /// The stations lofted through.
63    pub stations: usize,
64    /// Refinement rounds that inserted at least one station.
65    pub rounds: usize,
66    /// True when refinement wanted more stations than the cap allows.
67    pub at_cap: bool,
68    /// True when [`SWEEP_REFINEMENT_ROUNDS`] rounds ran and the last
69    /// measurement was still over the tolerance.
70    pub rounds_exhausted: bool,
71}
72
73/// The measured bound a station sweep carries.
74#[derive(Clone, Debug, PartialEq)]
75pub struct SweepStationReport {
76    pub budget: StationBudget,
77    /// The centre-track deviation the run was refined to, mm.
78    pub tolerance: f64,
79    /// The worst distance from the true path to the loft's centre track, mm —
80    /// the number read against `tolerance`, and the one refinement drives:
81    /// the cubic's error falls as `h⁴` inside a segment and as `h²` at a G1
82    /// joint's curvature jump.
83    pub spine_deviation: f64,
84    /// The worst deviation of the loft's frame axes from the transported
85    /// frame ACROSS the path's tangent, per unit of section reach: the part
86    /// that can stand the wall off the kinematic sweep. Reported, not driven.
87    pub frame_deviation: f64,
88    /// The worst deviation of the frame axes ALONG the path's tangent, per
89    /// unit reach: the section SLIDING along the wall it lies in. At a G1
90    /// joint the frame's rate of turn jumps and one cubic through the frames
91    /// overshoots along the tangent by a term first order in the spacing
92    /// (2.3e-3 on the rounded-rectangle ring at 1e-4, where the across part
93    /// reads 3.5e-5); a slide `δ` moves the wall off itself only at second
94    /// order, `δ²κ / (2(1 − reach·κ))`, which is what `wall_deviation` adds.
95    pub frame_slide: f64,
96    /// `spine + reach × frame + (reach × slide)²·κ / (2(1 − reach·κ))`: the
97    /// worst distance any wall point stands off the kinematic sweep's wall, mm
98    /// — for a section square to the path, untwisted, unscaled and unrolled,
99    /// whose wall contains the path's tangent; otherwise, or where
100    /// `reach·κ ≥ 1`, `spine + reach × (frame + slide)`.
101    pub wall_deviation: f64,
102    /// The section's reach from its anchor, mm (a control-hull bound).
103    pub reach: f64,
104    /// The built solid's volume, by quadrature over the loft's own interpolants.
105    pub built_volume: f64,
106    /// The kinematic sweep's volume: `A·L` for a section centred on the path,
107    /// with the section's first-moment terms and the carried anchor's own
108    /// motion otherwise (Simpson over each span's quarter points).
109    pub ideal_volume: f64,
110    /// `|built − ideal|`, mm³: the Pappus residual, measured.
111    pub volume_residual: f64,
112    /// True when `volume_residual` is the crude `lateral area × wall
113    /// deviation` bound instead of the quadrature (a seam-shifted ring).
114    pub crude_bound: bool,
115}
116
117impl SweepStationReport {
118    /// The report as the typed approximation a feature result carries
119    /// (`sweep.stations`).
120    pub fn approximation(&self, body: impl Into<String>) -> Approximation {
121        let cap = if self.budget.at_cap {
122            format!(
123                "; refinement stopped at the {SWEEP_MAX_STATIONS}-station cap, so the run does \
124                 not meet the requested tolerance"
125            )
126        } else if self.budget.rounds_exhausted {
127            format!(
128                "; refinement stopped after its {SWEEP_REFINEMENT_ROUNDS} rounds still over the \
129                 requested tolerance"
130            )
131        } else {
132            String::new()
133        };
134        let volume = if self.crude_bound {
135            format!(
136                "the volume is within {:.3e} mm³ of the kinematic sweep's (lateral area × wall \
137                 deviation)",
138                self.volume_residual
139            )
140        } else {
141            format!(
142                "the volume by quadrature is {:.9} against the kinematic sweep's {:.9} \
143                 (residual {:.3e} mm³)",
144                self.built_volume, self.ideal_volume, self.volume_residual
145            )
146        };
147        Approximation {
148            code: "sweep.stations".to_string(),
149            body: body.into(),
150            measured: self.spine_deviation,
151            bar: self.tolerance,
152            volume_bound: Some(self.volume_residual),
153            edges: Vec::new(),
154            budget: None,
155            message: format!(
156                "the swept wall is lofted through {} stations ({} from the floors, {} refinement \
157                 round(s)); the loft's centre track stands within {:.3e} mm of the path against \
158                 the requested {:.1e}{cap}; its frame stands within {:.3e} per unit reach of the \
159                 transported frame across the path and slides up to {:.3e} along it (a reach of \
160                 {:.3}), so the wall is within {:.3e} mm of the kinematic sweep's; {volume}",
161                self.budget.stations,
162                self.budget.initial,
163                self.budget.rounds,
164                self.spine_deviation,
165                self.tolerance,
166                self.frame_deviation,
167                self.frame_slide,
168                self.reach,
169                self.wall_deviation,
170            ),
171        }
172    }
173}
174
175/// Whether refinement is switched off — by the environment
176/// (`BREP_SWEEP_STATION_REFINEMENT=0`, mirroring `BREP_SWEEP_BEND_GUARD`, the
177/// switch a probe or a whole-module run pulls) or by this thread's stub.
178pub(super) fn refinement_enabled() -> bool {
179    switch!(live "BREP_SWEEP_STATION_REFINEMENT", true)
180}
181
182/// Whether the station lane BREAKS its wall columns at the joints where the
183/// path's curvature jumps (`BREP_SWEEP_JOINT_BREAKS`, default on; `=0`
184/// restores one interpolant per column): each run
185/// of stations between two such joints is interpolated on its own and the
186/// runs meet C0 there ([`crate::loft_topology::interpolate_column_broken`]),
187/// so the refinement no longer has to cluster stations at every joint.
188pub(super) fn joint_breaks_enabled() -> bool {
189    switch!(live "BREP_SWEEP_JOINT_BREAKS", true)
190}
191
192/// The loft's v-interpolant, broken at `breaks` when the run is broken
193/// (`Some`, the seam included on a ring) — exactly the columns
194/// [`crate::loft_topology::loft_profile_brep_broken`] and its closed twin
195/// build, so the instruments read the wall that is built.
196pub(super) fn interpolant_broken(
197    points: &[Vec3],
198    parameters: &[f64],
199    closed: bool,
200    breaks: Option<&[usize]>,
201) -> Result<NurbsCurve, String> {
202    match breaks {
203        None => interpolant(points, parameters, closed),
204        Some(breaks) if closed => {
205            let mut unrolled = points.to_vec();
206            unrolled.push(points[0]);
207            crate::loft_topology::interpolate_column_broken(&unrolled, parameters, breaks)
208        }
209        Some(breaks) => crate::loft_topology::interpolate_column_broken(points, parameters, breaks),
210    }
211}
212
213
214/// Cumulative chord parameters over `points`, normalized to `[0, 1]`; a
215/// CLOSED run has one more entry for the wrap chord back to point 0.
216pub(super) fn chord_parameters(points: &[Vec3], closed: bool) -> Vec<f64> {
217    let count = points.len();
218    let mut parameters = Vec::with_capacity(count + usize::from(closed));
219    let mut total = 0.0;
220    parameters.push(0.0);
221    for index in 1..count {
222        total += points[index].sub(points[index - 1]).length();
223        parameters.push(total);
224    }
225    if closed {
226        total += points[0].sub(points[count - 1]).length();
227        parameters.push(total);
228    }
229    if total > 0.0 {
230        for parameter in parameters.iter_mut() {
231            *parameter /= total;
232        }
233    }
234    parameters
235}
236
237/// The loft's own v-parameters for a run of placed sections: the average over
238/// every control-point column of that column's cumulative chord fraction, the
239/// wrap chord included on a ring — `loft_topology/basic.rs` and `closed.rs`,
240/// formula for formula, so the interpolants built on them are the loft's.
241pub(super) fn loft_parameters(sections: &[Vec<NurbsCurve>], closed: bool) -> Result<Vec<f64>, KernelRefusal> {
242    let count = sections.len();
243    let spans = count - 1 + usize::from(closed);
244    let mut accumulated = vec![0.0; spans + 1];
245    let mut columns = 0usize;
246    for curve_index in 0..sections[0].len() {
247        for control_index in 0..sections[0][curve_index].control_points.len() {
248            let mut chords = vec![0.0; spans + 1];
249            let mut total = 0.0;
250            for station in 1..=spans {
251                let previous = sections[station - 1][curve_index].control_points[control_index]
252                    .point()
253                    .or_refuse(KernelStage::Refine, "control_point")?;
254                let current = sections[station % count][curve_index].control_points[control_index]
255                    .point()
256                    .or_refuse(KernelStage::Refine, "control_point")?;
257                total += current.sub(previous).length();
258                chords[station] = total;
259            }
260            if total <= 1e-6 {
261                continue;
262            }
263            for station in 0..=spans {
264                accumulated[station] += chords[station] / total;
265            }
266            columns += 1;
267        }
268    }
269    if columns == 0 {
270        return Err(KernelRefusal::input(
271            KernelStage::Classify,
272            "coincident_sections",
273            "sweepSolid: the placed sections coincide",
274        ));
275    }
276    let mut parameters: Vec<f64> = accumulated.iter().map(|sum| sum / columns as f64).collect();
277    parameters[0] = 0.0;
278    parameters[spans] = 1.0;
279    Ok(parameters)
280}
281
282/// The loft's v-interpolant through `points` at `parameters`: the open fit at
283/// the loft's degree (cubic, or fewer points minus one), or the periodic
284/// cubic on a ring (`parameters` then carries the wrap entry).
285pub(super) fn interpolant(points: &[Vec3], parameters: &[f64], closed: bool) -> Result<NurbsCurve, String> {
286    if closed {
287        interpolate_curve_closed(points, parameters)
288    } else {
289        interpolate_curve(points, 3usize.min(points.len() - 1), parameters)
290    }
291}
292
293/// The parameter on `curve` nearest `point`, from `guess`: Newton on the
294/// distance's derivative, held inside the curve's domain. The spans are
295/// short and the guess is the chord fraction, so a few steps converge; a step
296/// that does not improve is discarded.
297fn nearest_parameter(curve: &NurbsCurve, point: Vec3, guess: f64) -> Result<(f64, f64), String> {
298    let [lo, hi] = curve.domain()?;
299    let (u, _) = crate::projection::curve_foot_newton(curve, point, guess, [lo, hi],
300        crate::projection::CurveFootPolicy {
301            domain: crate::projection::FootDomain::Clamp,
302            iterations: 6,
303            slope_guard: 1e-300,
304            step_limit: f64::INFINITY,
305            parameter_tolerance: 1e-15 * hi.abs().max(1.0),
306            mode: crate::projection::FootMode::Monotone,
307        })?;
308    Ok((u, curve.evaluate(u)?.sub(point).length()))
309}
310
311/// The true path piece under span `k`: its segment and parameter interval.
312/// A span runs from station `k` to station `k + 1` on station `k`'s departing
313/// segment — to that segment's end when the next station is the joint (or
314/// station 0 of a ring).
315fn span_piece(chain: &[NurbsCurve], params: &[StationParam], k: usize, closed: bool) -> Result<(usize, f64, f64), String> {
316    let count = params.len();
317    let from = params[k];
318    let next = (k + 1) % count;
319    let end = if !closed && k + 1 == count {
320        return Err("no span past the last station of an open run".into());
321    } else if next != 0 && params[next].segment == from.segment {
322        params[next].t
323    } else {
324        chain[from.segment].domain()?[1]
325    };
326    Ok((from.segment, from.t, end))
327}
328
329/// The fractions of a span the instruments sample the true path at.
330const SPAN_FRACTIONS: [f64; 3] = [0.25, 0.5, 0.75];
331
332/// Per span, the worst distance from the true path to the loft's interpolant
333/// of the station points (at the centre-chord parameters the sampler has
334/// before any section is placed). An open run of `n` stations has `n − 1`
335/// spans, a ring `n`.
336pub(super) fn spine_deviations(
337    chain: &[NurbsCurve],
338    params: &[StationParam],
339    points: &[Vec3],
340    closed: bool,
341    breaks: Option<&[usize]>,
342) -> Result<Vec<f64>, String> {
343    let parameters = chord_parameters(points, closed);
344    let spine = interpolant_broken(points, &parameters, closed, breaks)?;
345    let spans = points.len() - 1 + usize::from(closed);
346    let mut deviations = Vec::with_capacity(spans);
347    for k in 0..spans {
348        let (segment, t_a, t_b) = span_piece(chain, params, k, closed)?;
349        let (u_a, u_b) = (parameters[k], parameters[k + 1]);
350        let mut worst: f64 = 0.0;
351        for fraction in SPAN_FRACTIONS {
352            let truth = chain[segment].evaluate(t_a + (t_b - t_a) * fraction)?;
353            let (_, distance) = nearest_parameter(&spine, truth, u_a + (u_b - u_a) * fraction)?;
354            worst = worst.max(distance);
355        }
356        deviations.push(worst);
357    }
358    Ok(deviations)
359}
360
361/// One refinement round: for every span whose deviation is over `tolerance`,
362/// split it into `ceil((deviation / tolerance)^(1/4))` equal parameter steps
363/// — the cubic interpolant's `h⁴` law — or `^(1/2)` for a span that starts or
364/// ends at a segment joint, where a curvature jump drops the cubic to `h²`
365/// (at least 2, at most 8 pieces), and insert the new parameters into that
366/// segment's list. Returns how many stations were inserted and whether the
367/// round wanted more than the cap allows, in which case the spans are refined
368/// worst-first until it is reached and the caller records `at_cap`.
369pub(super) fn refine_parameters(
370    chain: &[NurbsCurve],
371    per_segment: &mut [Vec<f64>],
372    params: &[StationParam],
373    deviations: &[f64],
374    tolerance: f64,
375    closed: bool,
376    emitted: usize,
377    breaks: Option<&[usize]>,
378) -> Result<(usize, bool), String> {
379    let count = params.len();
380    // A broken station (and a broken ring's seam) ends a run the cubic fits
381    // on its own: the span beside it keeps the `h⁴` law.
382    let broken_at = |station: usize| match breaks {
383        Some(breaks) => (closed && station == 0) || breaks.contains(&station),
384        None => false,
385    };
386    let mut wanted: Vec<(usize, usize)> = Vec::new();
387    for (k, &deviation) in deviations.iter().enumerate() {
388        if deviation > tolerance {
389            let (segment, t_a, t_b) = span_piece(chain, params, k, closed)?;
390            let [t0, t1] = chain[segment].domain()?;
391            let next = (k + 1) % count;
392            let at_joint = (t_a == t0 && (k > 0 || closed))
393                || t_b == t1 && (next != 0 || closed) && (next == 0 || params[next].segment != segment);
394            let broken = (t_a == t0 && broken_at(k)) || (t_b == t1 && broken_at(next));
395            let exponent = if at_joint && !broken { 0.5 } else { 0.25 };
396            let pieces = ((deviation / tolerance).powf(exponent).ceil() as usize).clamp(2, 8);
397            wanted.push((k, pieces));
398        }
399    }
400    if wanted.is_empty() {
401        return Ok((0, false));
402    }
403    let asked: usize = wanted.iter().map(|(_, pieces)| pieces - 1).sum();
404    let room = SWEEP_MAX_STATIONS.saturating_sub(emitted);
405    let at_cap = asked > room;
406    if at_cap {
407        // Worst first, as many as fit; a span that does not fit whole is
408        // bisected if one station fits.
409        wanted.sort_by(|a, b| deviations[b.0].total_cmp(&deviations[a.0]));
410    }
411    let mut inserted = 0usize;
412    for (k, pieces) in wanted {
413        let mut pieces = pieces;
414        while pieces > 1 && inserted + pieces - 1 > room {
415            pieces -= 1;
416        }
417        if pieces < 2 {
418            continue;
419        }
420        let (segment, t_a, t_b) = span_piece(chain, params, k, closed)?;
421        for step in 1..pieces {
422            per_segment[segment].push(t_a + (t_b - t_a) * step as f64 / pieces as f64);
423        }
424        inserted += pieces - 1;
425    }
426    for list in per_segment.iter_mut() {
427        list.sort_by(|a, b| a.total_cmp(b));
428        list.dedup();
429    }
430    Ok((inserted, at_cap))
431}
432
433/// The section's signed area and first moments about its anchor, in the
434/// anchor's own `(a, b) = ((x − origin)·pu, (x − origin)·pv)` coordinates, by
435/// Gauss quadrature on every knot span of every curve (Green's theorem:
436/// `A = ½∮(a·b' − b·a')`, `∫a dA = ½∮a²·b'`, `∫b dA = −½∮b²·a'`). Exact on
437/// polynomial curves; a rational arc reads to round-off at eight points a
438/// span.
439pub(super) fn section_moments(profile: &[NurbsCurve], origin: Vec3, pu: Vec3, pv: Vec3) -> Result<(f64, f64, f64), String> {
440    let (mut area, mut moment_a, mut moment_b) = (0.0, 0.0, 0.0);
441    for curve in profile {
442        for pair in curve.knots.windows(2) {
443            if pair[1] <= pair[0] {
444                continue;
445            }
446            let half = 0.5 * (pair[1] - pair[0]);
447            let middle = 0.5 * (pair[1] + pair[0]);
448            for index in 0..GAUSS_X.len() {
449                let derivatives = curve.derivatives_small(middle + half * GAUSS_X[index], 1)?;
450                let local = derivatives[0].sub(origin);
451                let (a, b) = (local.dot(pu), local.dot(pv));
452                let (da, db) = (derivatives[1].dot(pu), derivatives[1].dot(pv));
453                let weight = GAUSS_W[index] * half;
454                area += weight * 0.5 * (a * db - b * da);
455                moment_a += weight * 0.5 * a * a * db;
456                moment_b -= weight * 0.5 * b * b * da;
457            }
458        }
459    }
460    Ok((area, moment_a, moment_b))
461}
462
463/// How far the section reaches from its anchor: the farthest control point
464/// (the curves lie in their hulls, so this bounds every section point).
465pub(super) fn section_reach(profile: &[NurbsCurve], origin: Vec3) -> f64 {
466    profile
467        .iter()
468        .flat_map(|curve| curve.control_points.iter())
469        .filter_map(|point| point.point().ok())
470        .map(|point| point.sub(origin).length())
471        .fold(0.0, f64::max)
472}
473
474/// Rodrigues about a unit axis.
475fn rotated(x: Vec3, axis: Vec3, angle: f64) -> Vec3 {
476    x.rotate_about(axis, angle)
477}
478
479/// The inputs [`station_report`] reads off a placed run.
480pub(super) struct PlacedRun<'a> {
481    pub chain: &'a [NurbsCurve],
482    pub params: &'a [StationParam],
483    pub points: &'a [Vec3],
484    pub tangents: &'a [Vec3],
485    /// The axes the sections were placed on, twist included.
486    pub axes: &'a [(Vec3, Vec3)],
487    /// The image of the anchor origin at every station (the centre track).
488    pub centres: &'a [Vec3],
489    /// The images of `pu` and `pv` — the section's affine axes — per station.
490    pub e1: &'a [Vec3],
491    pub e2: &'a [Vec3],
492    /// `(pu, pv)` in the placement basis `(t, r, s)`: the same coefficients
493    /// at every station, which is what makes the carry rigid.
494    pub pu_in_frame: [f64; 3],
495    pub pv_in_frame: [f64; 3],
496    pub closed: bool,
497    pub sections: &'a [Vec<NurbsCurve>],
498    /// Signed area and first moments of the section about its anchor.
499    pub moments: (f64, f64, f64),
500    pub reach: f64,
501    /// The seam shift of a twisted ring; the quadrature is over one lap only.
502    pub shift: usize,
503    pub budget: StationBudget,
504    pub tolerance: f64,
505    /// The stations the loft broke its columns at (`None`: one interpolant).
506    pub breaks: Option<&'a [usize]>,
507    /// True when the path's tangent lies in the wall at every point, so a
508    /// slide of the section along it stands the wall off only at second
509    /// order: a section held square to the path (`Transplant`), untwisted,
510    /// unscaled and not rolled by a spatial ring's counter-twist. Otherwise
511    /// the slide is counted at first order.
512    pub slide_in_wall: bool,
513}
514
515/// One RMF step (Wang et al. 2008), as `sweep.rs::rmf_step` takes it, for the
516/// sub-station transport below.
517fn rmf_step(r: Vec3, t: Vec3, t_next: Vec3, step: Vec3) -> Option<Vec3> {
518    let c1 = step.dot(step);
519    let candidate = if c1 <= 1e-18 {
520        r
521    } else {
522        let reflected_r = r.sub(step.scale(2.0 / c1 * step.dot(r)));
523        let reflected_t = t.sub(step.scale(2.0 / c1 * step.dot(t)));
524        let v2 = t_next.sub(reflected_t);
525        let c2 = v2.dot(v2);
526        if c2 <= 1e-18 {
527            reflected_r
528        } else {
529            reflected_r.sub(v2.scale(2.0 / c2 * v2.dot(reflected_r)))
530        }
531    };
532    candidate.sub(t_next.scale(candidate.dot(t_next))).normalized().ok()
533}
534
535/// Sub-station fractions the report transports the frame through: the span's
536/// quarter points, then its end (where the residual roll is read).
537const SUB_FRACTIONS: [f64; 4] = [0.25, 0.5, 0.75, 1.0];
538
539/// The measured bound of a placed run — see the module header.
540pub(super) fn station_report(run: &PlacedRun<'_>) -> Result<SweepStationReport, KernelRefusal> {
541    let refuse = |what: &str, error: String| {
542        KernelRefusal::internal(KernelStage::Refine, "station_report", format!("sweepSolid: station report ({what}): {error}"))
543    };
544    let count = run.points.len();
545    let closed = run.closed;
546    let spans = count - 1 + usize::from(closed);
547    let (area, moment_a, moment_b) = run.moments;
548    // The section's anchor rides the path under `Transplant`; under `Rigid` it
549    // rides where it was drawn, `offset` from the path in the station-0 frame
550    // and carried rigidly — so the centre track is the path plus that offset
551    // turned with the frame, and the track's own motion enters the volume.
552    let t0 = run.tangents[0];
553    let (r0, s0) = run.axes[0];
554    let drawn = run.centres[0].sub(run.points[0]);
555    let offset = [drawn.dot(t0), drawn.dot(r0), drawn.dot(s0)];
556    let carried = offset.iter().any(|component| component.abs() > 1e-12 * run.reach.max(1e-9));
557    let centred = moment_a.abs().max(moment_b.abs()) <= 1e-9 * area.abs() * run.reach.max(1e-9);
558    let corrections = !centred || carried;
559
560    // --- The loft's interpolants of the centre track and the affine axes, on
561    //     the loft's own parameters.
562    let parameters = loft_parameters(run.sections, closed)?;
563    let centre = interpolant_broken(run.centres, &parameters, closed, run.breaks).map_err(|e| refuse("centre", e))?;
564    let axis_1 = interpolant_broken(run.e1, &parameters, closed, run.breaks).map_err(|e| refuse("axis 1", e))?;
565    let axis_2 = interpolant_broken(run.e2, &parameters, closed, run.breaks).map_err(|e| refuse("axis 2", e))?;
566
567    // --- The built volume: ∫ det[X_v, X_a, X_b] over the section and one lap,
568    //     with X = C(v) + a·E1(v) + b·E2(v), by Gauss on every knot span of the
569    //     interpolants (the integrand is a polynomial of degree 8 there).
570    let mut built = 0.0;
571    let mut lateral_length = 0.0;
572    for pair in centre.knots.windows(2) {
573        if pair[1] <= pair[0] {
574            continue;
575        }
576        let half = 0.5 * (pair[1] - pair[0]);
577        let middle = 0.5 * (pair[1] + pair[0]);
578        for index in 0..GAUSS_X.len() {
579            let v = middle + half * GAUSS_X[index];
580            let c = centre.derivatives_small(v, 1).map_err(|e| refuse("centre", e))?;
581            let e1 = axis_1.derivatives_small(v, 1).map_err(|e| refuse("axis 1", e))?;
582            let e2 = axis_2.derivatives_small(v, 1).map_err(|e| refuse("axis 2", e))?;
583            let normal = e1[0].cross(e2[0]);
584            let weight = GAUSS_W[index] * half;
585            built += weight * (area * c[1].dot(normal) + moment_a * e1[1].dot(normal) + moment_b * e2[1].dot(normal));
586            lateral_length += weight * c[1].length();
587        }
588    }
589
590    // --- The true path and the transported frame between stations: the
591    //     deviations, the path length, and the kinematic sweep's own moment
592    //     terms (Simpson over each span's quarter points).
593    let [pu_t, pu_r, pu_s] = run.pu_in_frame;
594    let [pv_t, pv_r, pv_s] = run.pv_in_frame;
595    let axes_of = |t: Vec3, r: Vec3, s: Vec3| -> (Vec3, Vec3) {
596        (
597            t.scale(pu_t).add(r.scale(pu_r)).add(s.scale(pu_s)),
598            t.scale(pv_t).add(r.scale(pv_r)).add(s.scale(pv_s)),
599        )
600    };
601    let mut spine_deviation: f64 = 0.0;
602    let mut frame_deviation: f64 = 0.0;
603    let mut frame_slide: f64 = 0.0;
604    let mut kappa_max: f64 = 0.0;
605    let mut length = 0.0;
606    let mut moment_integral = 0.0;
607    for k in 0..spans {
608        let (segment, t_a, t_b) = span_piece(run.chain, run.params, k, closed).map_err(|e| refuse("span", e))?;
609        let curve = &run.chain[segment];
610        let next = (k + 1) % count;
611        let (u_a, u_b) = (parameters[k], parameters[k + 1]);
612        // Path length over the span, by Gauss in the path parameter.
613        let (half, middle) = (0.5 * (t_b - t_a), 0.5 * (t_b + t_a));
614        for index in 0..GAUSS_X.len() {
615            let derivatives = curve.derivatives_small(middle + half * GAUSS_X[index], 1).map_err(|e| refuse("path", e))?;
616            length += GAUSS_W[index] * half * derivatives[1].length();
617        }
618        // Transport station k's placed frame through the quarter points to
619        // station k + 1, read the roll it arrives short of the placed frame
620        // there, and lay that roll down linearly in chord over the span.
621        let (r_k, s_k) = run.axes[k];
622        let mut r = r_k;
623        let mut t_prev = run.tangents[k];
624        let mut p_prev = run.points[k];
625        let mut transported: Vec<(Vec3, Vec3, Vec3, Vec3)> = Vec::with_capacity(SUB_FRACTIONS.len());
626        let [d0, d1] = curve.domain().map_err(|e| refuse("domain", e))?;
627        for fraction in SUB_FRACTIONS {
628            let t = t_a + (t_b - t_a) * fraction;
629            let derivatives = curve.derivatives_small(t, 2).map_err(|e| refuse("path", e))?;
630            let point = derivatives[0];
631            // A stationary parameter (a cusp in the parameterization) still has
632            // a direction of travel: the one-sided limit `unit_tangent` reads.
633            let tangent = curve.unit_tangent(t, d0, d1).map_err(|e| refuse("tangent", e))?;
634            let kappa_n = super::sweep::curvature_vector(derivatives[1], derivatives[2]);
635            r = rmf_step(r, t_prev, tangent, point.sub(p_prev)).ok_or_else(|| refuse("transport", "the frame degenerated".into()))?;
636            transported.push((point, tangent, kappa_n, r));
637            t_prev = tangent;
638            p_prev = point;
639        }
640        let (r_end, _) = run.axes[next];
641        let t_end = run.tangents[next];
642        let r_arrived = transported[SUB_FRACTIONS.len() - 1].3;
643        let roll = r_arrived.cross(r_end).dot(t_end).atan2(r_arrived.dot(r_end));
644        let chord: f64 = {
645            let mut sum = 0.0;
646            let mut prev = run.points[k];
647            for entry in &transported {
648                sum += entry.0.sub(prev).length();
649                prev = entry.0;
650            }
651            sum
652        };
653        let _ = s_k;
654        // Simpson over the five points of the span (station k, the quarter
655        // points, station k + 1) for the moment terms.
656        let mut integrand: Vec<(f64, f64)> = Vec::with_capacity(5);
657        let mut chord_so_far = 0.0;
658        let mut prev = run.points[k];
659        for (which, fraction) in std::iter::once(0.0).chain(SUB_FRACTIONS).enumerate() {
660            let (point, tangent, kappa_n, r_raw) = if which == 0 {
661                let derivatives = curve.derivatives_small(t_a, 2).map_err(|e| refuse("path", e))?;
662                (run.points[k], run.tangents[k], super::sweep::curvature_vector(derivatives[1], derivatives[2]), r_k)
663            } else {
664                transported[which - 1]
665            };
666            chord_so_far += point.sub(prev).length();
667            prev = point;
668            let phi = if chord > 0.0 { roll * chord_so_far / chord } else { 0.0 };
669            let r_true = if which == 0 { r_k } else { rotated(r_raw, tangent, phi) };
670            let s_true = tangent.cross(r_true);
671            let (e1_true, e2_true) = axes_of(tangent, r_true, s_true);
672            let centre_true = point
673                .add(tangent.scale(offset[0]))
674                .add(r_true.scale(offset[1]))
675                .add(s_true.scale(offset[2]));
676            let speed = curve.derivatives_small(t_a + (t_b - t_a) * fraction, 1).map_err(|e| refuse("path", e))?[1].length();
677            if corrections {
678                // d/ds of the carried axes: T' = κN, and the RMF's r' = −κ(r·N)T
679                // plus the roll laid down, ω = roll / chord, about T. The
680                // centre's own motion beyond T is the offset turned with them.
681                let omega = if chord > 0.0 { roll / chord } else { 0.0 };
682                let t_dot = kappa_n;
683                let r_dot = tangent.scale(-kappa_n.dot(r_true)).add(s_true.scale(omega));
684                let s_dot = tangent.scale(-kappa_n.dot(s_true)).sub(r_true.scale(omega));
685                let e1_dot = t_dot.scale(pu_t).add(r_dot.scale(pu_r)).add(s_dot.scale(pu_s));
686                let e2_dot = t_dot.scale(pv_t).add(r_dot.scale(pv_r)).add(s_dot.scale(pv_s));
687                let c_dot = t_dot.scale(offset[0]).add(r_dot.scale(offset[1])).add(s_dot.scale(offset[2]));
688                let normal = e1_true.cross(e2_true);
689                integrand.push((
690                    fraction,
691                    (area * c_dot.dot(normal) + moment_a * e1_dot.dot(normal) + moment_b * e2_dot.dot(normal)) * speed,
692                ));
693            }
694            if which == 0 || which == SUB_FRACTIONS.len() {
695                continue;
696            }
697            // The deviations, at the interior quarter points.
698            let guess = u_a + (u_b - u_a) * fraction;
699            let (u, distance) = nearest_parameter(&centre, centre_true, guess).map_err(|e| refuse("projection", e))?;
700            spine_deviation = spine_deviation.max(distance);
701            let e1_built = axis_1.evaluate(u).map_err(|e| refuse("axis 1", e))?;
702            let e2_built = axis_2.evaluate(u).map_err(|e| refuse("axis 2", e))?;
703            // Split along the path's tangent (a slide within the wall) and
704            // across it (a standoff).
705            let (d1, d2) = (e1_built.sub(e1_true), e2_built.sub(e2_true));
706            let (a1, a2) = (d1.dot(tangent), d2.dot(tangent));
707            let across = (d1.sub(tangent.scale(a1)).length_squared() + d2.sub(tangent.scale(a2)).length_squared()).sqrt();
708            frame_deviation = frame_deviation.max(across);
709            frame_slide = frame_slide.max((a1 * a1 + a2 * a2).sqrt());
710            kappa_max = kappa_max.max(kappa_n.length());
711        }
712        if corrections {
713            // Composite Simpson on four equal steps of the path parameter.
714            let h = (t_b - t_a) / 4.0;
715            let weights = [1.0, 4.0, 2.0, 4.0, 1.0];
716            moment_integral += integrand.iter().zip(weights).map(|((_, g), w)| g * w).sum::<f64>() * h / 3.0;
717        }
718    }
719    let (e1_0, e2_0) = (run.e1[0], run.e2[0]);
720    let advance = run.tangents[0].dot(e1_0.cross(e2_0));
721    let ideal = area * length * advance + moment_integral;
722    // Curvature at the stations too: a joint's jump lands there.
723    for k in 0..spans {
724        let (segment, t_a, t_b) = span_piece(run.chain, run.params, k, closed).map_err(|e| refuse("span", e))?;
725        for t in [t_a, t_b] {
726            let derivatives = run.chain[segment].derivatives_small(t, 2).map_err(|e| refuse("path", e))?;
727            kappa_max = kappa_max.max(super::sweep::curvature_vector(derivatives[1], derivatives[2]).length());
728        }
729    }
730    let slide = run.reach * frame_slide;
731    let wall_deviation = if run.slide_in_wall && run.reach * kappa_max < 1.0 {
732        spine_deviation + run.reach * frame_deviation + slide * slide * kappa_max / (2.0 * (1.0 - run.reach * kappa_max))
733    } else {
734        spine_deviation + run.reach * (frame_deviation + frame_slide)
735    };
736    let (built_volume, ideal_volume, residual, crude) = if run.shift == 0 {
737        (built.abs(), ideal.abs(), (built.abs() - ideal.abs()).abs(), false)
738    } else {
739        // A seam-shifted ring's columns run several laps; the one-lap
740        // quadrature does not describe it. Bound it instead.
741        let perimeter = section_perimeter(run.sections.first().map(|s| s.as_slice()).unwrap_or(&[]))?;
742        (f64::NAN, ideal.abs(), perimeter * lateral_length * wall_deviation, true)
743    };
744    Ok(SweepStationReport {
745        budget: run.budget,
746        tolerance: run.tolerance,
747        spine_deviation,
748        frame_deviation,
749        frame_slide,
750        wall_deviation,
751        reach: run.reach,
752        built_volume,
753        ideal_volume,
754        volume_residual: residual,
755        crude_bound: crude,
756    })
757}
758
759/// A section's perimeter by chord sums (64 per curve) — only the crude bound
760/// reads it.
761fn section_perimeter(section: &[NurbsCurve]) -> Result<f64, KernelRefusal> {
762    let mut total = 0.0;
763    for curve in section {
764        let [start, end] = curve.domain().or_refuse(KernelStage::Refine, "domain")?;
765        let mut previous = curve.evaluate(start).or_refuse(KernelStage::Refine, "evaluate")?;
766        for index in 1..=64 {
767            let point = curve.evaluate(start + (end - start) * index as f64 / 64.0).or_refuse(KernelStage::Refine, "evaluate")?;
768            total += point.sub(previous).length();
769            previous = point;
770        }
771    }
772    Ok(total)
773}