Skip to main content

brep_construction/construction/
gears.rs

1//! Gear sections and gear solids.
2//!
3//! An involute gear is built the way it is cut: its section is the envelope of a
4//! rack cutter rolled round the pitch circle. A rack point `q` with outward normal
5//! `n` touches the gear when its normal passes through the pitch point; with the
6//! gear's tooth 0 centred on +x, the rack's rolling line on `x = r` and the rack
7//! displaced by `s` along +y, that is
8//!
9//! ```text
10//!   s = (q.x - r) n.y / n.x - q.y,      gear point = Rot(-s / r) (q.x, q.y + s).
11//! ```
12//!
13//! The cutter's straight flank generates the involute; its tip fillet (radius
14//! `rho`) generates the root fillet, the equidistant of the trochoid traced by
15//! the fillet's centre, and so the real undercut when the tooth count is small.
16//! Neither curve is rational: each is fitted by a cubic B-spline (C1 Hermite
17//! spans, refined until every span is within the fit bound of the closed form at
18//! its sample parameters), while the tip and root lands are exact circular arcs.
19use crate::{extrude_profile_brep, make_arc, BrepSolid, KernelRefusal, KernelStage, NurbsCurve, NurbsSurface, Vec3, Vec4};
20use std::f64::consts::{PI, TAU};
21
22/// The fit bound of every fitted gear curve, as a fraction of the module: the
23/// largest distance, at the span sample parameters, between a fitted curve and
24/// its closed form.
25pub const GEAR_FIT_TOLERANCE: f64 = 5e-7;
26
27/// The bound of a generated (envelope) gear surface against the meshing equation's points, as a fraction of
28/// the module (the build spec's 1e-5 x module). A skinned surface is within the sum of its section fit's error
29/// and its skin's (a B-spline surface stays within its control points' largest deviation), so the bound is
30/// split: a quarter to the section fit in each plane, three quarters to the skin between planes.
31pub const GEAR_GENERATED_TOLERANCE: f64 = 1e-5;
32const GENERATED_SECTION_SHARE: f64 = 0.25;
33const CROWN_SECTION_SHARE: f64 = 0.1;
34
35/// An external spur gear generated by a standard rack cutter. Lengths in model
36/// units, angles in radians; coefficients are multiples of the module.
37#[derive(Clone, Debug)]
38pub struct SpurGear {
39    pub module: f64,
40    pub teeth: usize,
41    pub pressure_angle: f64,
42    /// Profile shift coefficient x (the cutter moved out by x · module).
43    pub profile_shift: f64,
44    /// Addendum coefficient ha* (tip radius = r + (ha* + x) m).
45    pub addendum: f64,
46    /// Dedendum coefficient hf* (root radius = r - (hf* - x) m).
47    pub dedendum: f64,
48    /// Cutter tip radius coefficient rho_f*.
49    pub root_fillet: f64,
50    /// Circumferential backlash taken off the tooth thickness on the reference circle.
51    pub backlash: f64,
52    pub face_width: f64,
53}
54
55impl Default for SpurGear {
56    fn default() -> Self {
57        Self {
58            module: 2.0,
59            teeth: 20,
60            pressure_angle: 20f64.to_radians(),
61            profile_shift: 0.0,
62            addendum: 1.0,
63            dedendum: 1.25,
64            root_fillet: 0.38,
65            backlash: 0.0,
66            face_width: 10.0,
67        }
68    }
69}
70
71/// Derived data of a generated gear (diameters in model units).
72#[derive(Clone, Debug, Default)]
73pub struct GearData {
74    pub pitch_diameter: f64,
75    pub base_diameter: f64,
76    pub tip_diameter: f64,
77    pub root_diameter: f64,
78    /// Diameter where the involute flank meets the root fillet.
79    pub form_diameter: f64,
80    /// Tooth thickness on the reference (pitch) circle, arc length.
81    pub tooth_thickness: f64,
82    /// Tooth thickness on the tip circle, arc length.
83    pub tip_thickness: f64,
84    /// Whether the root fillet cuts into the involute (generated undercut).
85    pub undercut: bool,
86    /// The smallest profile shift at which this gear has no undercut.
87    pub min_shift_without_undercut: f64,
88}
89
90/// One curve of a gear section with the face role it gives the solid.
91#[derive(Clone, Debug)]
92pub struct SectionCurve {
93    pub curve: NurbsCurve,
94    /// Face role: `V`/`W` root fillets, `R`/`L` flanks, `K` tip land, `G` root land.
95    pub role: &'static str,
96    pub tooth: usize,
97}
98
99impl SectionCurve {
100    /// The face-name suffix this curve's face carries (`R3`, `K0`, …).
101    pub fn suffix(&self) -> String {
102        format!("{}{}", self.role, self.tooth)
103    }
104}
105
106/// A closed gear section in the z = 0 plane, counter-clockwise about +z.
107#[derive(Clone, Debug)]
108pub struct GearSection {
109    pub curves: Vec<SectionCurve>,
110    pub data: GearData,
111}
112
113fn refuse(code: &str, message: String) -> KernelRefusal {
114    KernelRefusal::input(KernelStage::Collect, code, message)
115}
116
117fn rotate(point: [f64; 2], angle: f64) -> [f64; 2] {
118    let (s, c) = angle.sin_cos();
119    [c * point[0] - s * point[1], s * point[0] + c * point[1]]
120}
121
122fn polar_angle(point: [f64; 2]) -> f64 {
123    point[1].atan2(point[0])
124}
125
126fn radius_of(point: [f64; 2]) -> f64 {
127    point[0].hypot(point[1])
128}
129
130/// The rack cutter of a spur gear in the generating frame, and its envelope.
131struct RackCutter {
132    r: f64,
133    alpha: f64,
134    /// Reference line of the cutter (x).
135    x_ref: f64,
136    /// The cutter flank's y on the reference line.
137    y0: f64,
138    /// Root radius = the cutter tip line (x).
139    r_f: f64,
140    rho: f64,
141    /// Tip fillet centre.
142    centre: [f64; 2],
143}
144
145impl RackCutter {
146    fn new(gear: &SpurGear) -> Self {
147        let m = gear.module;
148        let r = m * gear.teeth as f64 / 2.0;
149        let p = PI * m;
150        let alpha = gear.pressure_angle;
151        let x_ref = r + gear.profile_shift * m;
152        let y0 = p / 4.0 - gear.backlash / 2.0;
153        let r_f = x_ref - gear.dedendum * m;
154        let rho = gear.root_fillet * m;
155        let x_c = r_f + rho;
156        let y_c = y0 + (rho + (x_ref - x_c) * alpha.sin()) / alpha.cos();
157        Self { r, alpha, x_ref, y0, r_f, rho, centre: [x_c, y_c] }
158    }
159
160    /// The gear point generated by the rack point `q` with outward normal `n`.
161    fn envelope(&self, q: [f64; 2], n: [f64; 2]) -> [f64; 2] {
162        let s = (q[0] - self.r) * n[1] / n[0] - q[1];
163        rotate([q[0], q[1] + s], -s / self.r)
164    }
165
166    /// The involute flank (left side of tooth 0) generated by the flank point at `x`.
167    fn flank(&self, x: f64) -> [f64; 2] {
168        let a = self.alpha;
169        let q = [x, self.y0 + (self.x_ref - x) * a.tan()];
170        self.envelope(q, [-a.sin(), -a.cos()])
171    }
172
173    /// The root fillet (left side of tooth 0) generated by the cutter tip fillet
174    /// at normal angle `psi` (0 = the tip line, pi/2 - alpha = the flank).
175    fn fillet(&self, psi: f64) -> [f64; 2] {
176        let n = [-psi.cos(), -psi.sin()];
177        if self.rho == 0.0 {
178            // A sharp cutter corner: the point is fixed, its normal still sweeps.
179            return self.envelope(self.centre, n);
180        }
181        let q = [self.centre[0] + self.rho * n[0], self.centre[1] + self.rho * n[1]];
182        self.envelope(q, n)
183    }
184
185    /// The flank point x whose generated point lies at radius `radius` (the involute branch).
186    fn flank_x_at_radius(&self, radius: f64) -> f64 {
187        let c = 1.0 / self.alpha.tan();
188        let c2 = c * c;
189        let disc = (self.r * self.r * c2 * c2 - (1.0 + c2) * (self.r * self.r * c2 - radius * radius)).max(0.0);
190        (self.r * c2 + disc.sqrt()) / (1.0 + c2)
191    }
192}
193
194/// A cubic B-spline (C1 Hermite spans) through `f` on `[a, b]`, refined until each
195/// span is within `tolerance` of `f` at its sample parameters.
196fn fit_planar(f: &dyn Fn(f64) -> [f64; 2], a: f64, b: f64, tolerance: f64) -> Result<NurbsCurve, KernelRefusal> {
197    let derivative = |t: f64| {
198        let h = 1e-6 * (b - a).abs().max(1e-12);
199        let p = f(t + h);
200        let q = f(t - h);
201        [(p[0] - q[0]) / (2.0 * h), (p[1] - q[1]) / (2.0 * h)]
202    };
203    let span_points = |t0: f64, t1: f64| {
204        let (p0, p1) = (f(t0), f(t1));
205        let (d0, d1) = (derivative(t0), derivative(t1));
206        let k = (t1 - t0) / 3.0;
207        [p0, [p0[0] + d0[0] * k, p0[1] + d0[1] * k], [p1[0] - d1[0] * k, p1[1] - d1[1] * k], p1]
208    };
209    let bezier = |c: &[[f64; 2]; 4], u: f64| {
210        let v = 1.0 - u;
211        let w = [v * v * v, 3.0 * v * v * u, 3.0 * v * u * u, u * u * u];
212        [
213            w[0] * c[0][0] + w[1] * c[1][0] + w[2] * c[2][0] + w[3] * c[3][0],
214            w[0] * c[0][1] + w[1] * c[1][1] + w[2] * c[2][1] + w[3] * c[3][1],
215        ]
216    };
217    let mut pending: Vec<(f64, f64, usize)> = (0..4).rev().map(|i| {
218        let t0 = a + (b - a) * i as f64 / 4.0;
219        let t1 = a + (b - a) * (i + 1) as f64 / 4.0;
220        (t0, t1, 0)
221    }).collect();
222    let mut spans: Vec<(f64, f64, [[f64; 2]; 4])> = Vec::new();
223    while let Some((t0, t1, depth)) = pending.pop() {
224        let c = span_points(t0, t1);
225        let worst = [0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
226            .iter()
227            .map(|&u| {
228                let exact = f(t0 + (t1 - t0) * u);
229                let fitted = bezier(&c, u);
230                (exact[0] - fitted[0]).hypot(exact[1] - fitted[1])
231            })
232            .fold(0.0, f64::max);
233        if worst > tolerance && depth < 16 {
234            let mid = 0.5 * (t0 + t1);
235            pending.push((mid, t1, depth + 1));
236            pending.push((t0, mid, depth + 1));
237        } else if worst > tolerance {
238            return Err(refuse("gear_fit", format!("gear curve fit did not converge ({worst:.3e} > {tolerance:.3e})")));
239        } else {
240            spans.push((t0, t1, c));
241        }
242    }
243    // Knots in [0, 1] (normalised). The Hermite spans join with C1 continuity,
244    // so each interior knot is doubled and the shared span end, which lies on
245    // the segment between its two neighbours, is implied rather than stored.
246    let scale = 1.0 / (b - a);
247    let to_point = |p: [f64; 2]| Vec4::from_point(Vec3::new(p[0], p[1], 0.0), 1.0);
248    let mut knots = vec![0.0; 4];
249    let mut points = vec![to_point(spans[0].2[0])];
250    for (index, (_, t1, c)) in spans.iter().enumerate() {
251        points.push(to_point(c[1]));
252        points.push(to_point(c[2]));
253        if index + 1 < spans.len() {
254            let k = (t1 - a) * scale;
255            knots.extend([k, k]);
256        } else {
257            points.push(to_point(c[3]));
258        }
259    }
260    knots.extend([1.0; 4]);
261    NurbsCurve::new(3, knots, points).map_err(|error| refuse("gear_fit", error))
262}
263
264fn mirrored(curve: &NurbsCurve) -> NurbsCurve {
265    let mut copy = curve.clone();
266    for point in &mut copy.control_points {
267        point.y = -point.y;
268    }
269    NurbsCurve::new(copy.degree, copy.knots, copy.control_points).expect("a mirrored curve is a valid curve")
270}
271
272fn rotated(curve: &NurbsCurve, angle: f64) -> NurbsCurve {
273    let (s, c) = angle.sin_cos();
274    let points = curve
275        .control_points
276        .iter()
277        .map(|p| Vec4 { x: c * p.x - s * p.y, y: s * p.x + c * p.y, z: p.z, w: p.w })
278        .collect();
279    NurbsCurve::new(curve.degree, curve.knots.clone(), points).expect("a rotated curve is a valid curve")
280}
281
282fn arc(radius: f64, from: f64, to: f64) -> Result<NurbsCurve, KernelRefusal> {
283    make_arc(Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), radius, from, to)
284        .map_err(|error| refuse("gear_arc", error))
285}
286
287fn check_spur(gear: &SpurGear, max_pressure_degrees: f64) -> Result<(), KernelRefusal> {
288    let positive = |value: f64, what: &str| {
289        if value.is_finite() && value > 0.0 {
290            Ok(())
291        } else {
292            Err(refuse("gear_input", format!("The {what} must be greater than zero (it is {value}).")))
293        }
294    };
295    positive(gear.module, "module")?;
296    positive(gear.face_width, "face width")?;
297    positive(gear.addendum, "addendum coefficient")?;
298    positive(gear.dedendum, "dedendum coefficient")?;
299    if gear.teeth < 3 {
300        return Err(refuse("gear_input", format!("A gear needs at least 3 teeth (it has {}).", gear.teeth)));
301    }
302    let degrees = gear.pressure_angle.to_degrees();
303    if !(10.0 - 1e-9..=max_pressure_degrees + 1e-9).contains(&degrees) {
304        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and {max_pressure_degrees}° (it is {degrees}°).")));
305    }
306    if !(gear.root_fillet >= 0.0) || !(gear.backlash >= 0.0) || !gear.profile_shift.is_finite() {
307        return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
308    }
309    Ok(())
310}
311
312/// The section of an external spur gear, generated by its rack cutter.
313pub fn spur_section(gear: &SpurGear) -> Result<GearSection, KernelRefusal> {
314    check_spur(gear, 35.0)?;
315    generated_section(gear)
316}
317
318/// [`spur_section`] for a helical gear's transverse section, whose pressure
319/// angle (already checked in the normal section) may exceed 35°.
320fn transverse_section(gear: &SpurGear) -> Result<GearSection, KernelRefusal> {
321    check_spur(gear, 60.0)?;
322    generated_section(gear)
323}
324
325fn generated_section(gear: &SpurGear) -> Result<GearSection, KernelRefusal> {
326    let m = gear.module;
327    let z = gear.teeth as f64;
328    let rack = RackCutter::new(gear);
329    let alpha = rack.alpha;
330    let r = rack.r;
331    let r_b = r * alpha.cos();
332    let r_a = r + (gear.addendum + gear.profile_shift) * m;
333    let r_f = rack.r_f;
334    let half_pitch = PI / z;
335    let tolerance = GEAR_FIT_TOLERANCE * m;
336
337    if r_f <= 1e-9 * m {
338        return Err(refuse(
339            "root_below_centre",
340            format!("The root circle diameter is zero or negative (d = {:.4}): too few teeth for this dedendum.", 2.0 * r_f),
341        ));
342    }
343    // The cutter's tip land must stay; with too large a tip radius the two fillets cross.
344    let rho_max = ((PI * m / 2.0 - rack.y0) * alpha.cos() - (rack.x_ref - r_f) * alpha.sin()) / (1.0 - alpha.sin());
345    if rack.rho > rho_max + 1e-9 * m {
346        return Err(refuse(
347            "root_fillet_too_large",
348            format!(
349                "The root fillet coefficient {:.4} is larger than the {:.4} that fits this tooth space; lower it.",
350                gear.root_fillet,
351                rho_max / m
352            ),
353        ));
354    }
355    let psi_end = PI / 2.0 - alpha;
356    let x_flank_tangent = rack.centre[0] - rack.rho * alpha.sin();
357    let x_interference = r * alpha.cos().powi(2);
358    let min_shift = gear.dedendum - gear.root_fillet * (1.0 - alpha.sin()) - z / 2.0 * alpha.sin().powi(2);
359    let undercut = x_flank_tangent < x_interference - 1e-12 * m;
360
361    // The junction J of the left flank and its root fillet.
362    let (x_join, psi_join) = if !undercut {
363        (x_flank_tangent, psi_end)
364    } else {
365        // The fillet cuts the involute. Above the base circle the fillet lies
366        // outside the involute at the flank tangency (psi_end) and inside it
367        // just above the base circle, so the crossing is in [psi_base, psi_end],
368        // where psi_base is the fillet's base-circle crossing (its radius rises
369        // from the root, which is below the base circle here). Search that
370        // interval at a resolution relative to its own width, so a gear just
371        // past the undercut limit (a very short interval) is found too.
372        let difference = |psi: f64| -> Option<f64> {
373            let point = rack.fillet(psi);
374            let radius = radius_of(point);
375            if radius <= r_b {
376                return None;
377            }
378            Some(polar_angle(point) - polar_angle(rack.flank(rack.flank_x_at_radius(radius))))
379        };
380        let (mut below, mut above) = (0.0, psi_end);
381        for _ in 0..200 {
382            let mid = 0.5 * (below + above);
383            if radius_of(rack.fillet(mid)) <= r_b { below = mid } else { above = mid }
384        }
385        let psi_base = above;
386        let steps = 4000;
387        let mut found = None;
388        let mut previous: Option<(f64, f64)> = None;
389        for step in 0..=steps {
390            let psi = psi_end - (psi_end - psi_base) * step as f64 / steps as f64;
391            if let Some(value) = difference(psi) {
392                if let Some((last_psi, last_value)) = previous {
393                    if (value <= 0.0) != (last_value <= 0.0) {
394                        found = Some((psi, last_psi));
395                        break;
396                    }
397                }
398                previous = Some((psi, value));
399            }
400        }
401        // No crossing resolvable above the base circle: the fillet meets the
402        // flank at the base circle itself (the undercut limit).
403        let (mut lo, mut hi) = found.unwrap_or((psi_base, psi_base));
404        let sign_lo = difference(lo).unwrap_or(-1.0) <= 0.0;
405        for _ in 0..200 {
406            let mid = 0.5 * (lo + hi);
407            match difference(mid) {
408                Some(value) if (value <= 0.0) == sign_lo => lo = mid,
409                Some(_) => hi = mid,
410                None => lo = mid,
411            }
412        }
413        let psi = 0.5 * (lo + hi);
414        (rack.flank_x_at_radius(radius_of(rack.fillet(psi))), psi)
415    };
416    let join = rack.fillet(psi_join);
417    let form_radius = radius_of(join);
418    if r_a <= form_radius + 1e-9 * m {
419        return Err(refuse(
420            "tip_below_form",
421            format!(
422                "The tip circle (d = {:.4}) does not reach above the form circle (d = {:.4}); raise the addendum or lower the dedendum.",
423                2.0 * r_a,
424                2.0 * form_radius
425            ),
426        ));
427    }
428    let x_tip = rack.flank_x_at_radius(r_a);
429    let tip = rack.flank(x_tip);
430    // Half the tooth thickness angle at a radius (the textbook involute form,
431    // unwrapped: a polar angle read off a crossed flank wraps round and would
432    // pass a tooth whose flanks crossed below the tip).
433    let thickness = PI * m / 2.0 + 2.0 * gear.profile_shift * m * alpha.tan() - gear.backlash;
434    let involute = |angle: f64| angle.tan() - angle;
435    let half_angle = |radius: f64| thickness / (2.0 * r) + involute(alpha) - involute((r_b / radius).min(1.0).acos());
436    let tip_angle = half_angle(r_a);
437    let tip_offset = polar_angle(tip) - tip_angle;
438    if tip_angle * r_a <= 1e-6 * m || tip_offset.abs() > 1e-9 {
439        // Where the flanks meet: half_angle falls as the radius grows.
440        let (mut lo, mut hi) = (form_radius.max(r_b), r_a);
441        for _ in 0..200 {
442            let mid = 0.5 * (lo + hi);
443            if half_angle(mid) > 0.0 { lo = mid } else { hi = mid }
444        }
445        return Err(refuse(
446            "pointed_tip",
447            format!(
448                "The teeth come to a point at d = {:.4}, inside the tip circle (d = {:.4}); reduce the addendum or the profile shift, or add teeth.",
449                2.0 * lo,
450                2.0 * r_a
451            ),
452        ));
453    }
454    if tip_angle >= half_pitch {
455        return Err(refuse("teeth_overlap", "The tooth tips overlap their neighbours.".into()));
456    }
457    // Fillet samples must stay inside the half space (else neighbouring gaps cross).
458    for step in 0..=64 {
459        let point = rack.fillet(psi_join * step as f64 / 64.0);
460        let angle = polar_angle(point);
461        if angle <= 0.0 || angle > half_pitch + 1e-12 {
462            return Err(refuse("teeth_overlap", "The tooth gaps cross: the root form of one gap cuts the next tooth.".into()));
463        }
464    }
465
466    let flank_fit = fit_planar(&|x| rack.flank(x), x_join, x_tip, tolerance)?; // J -> tip
467    let fillet_fit = fit_planar(&|psi| rack.fillet(psi), 0.0, psi_join, tolerance)?; // root -> J
468    let root_angle = rack.centre[1] / r;
469    let land = 2.0 * half_pitch - 2.0 * root_angle;
470
471    // Tooth 0, counter-clockwise: V (root -> J_R), R (J_R -> tip), K, L (tip -> J), W (J -> root), G.
472    let mut tooth: Vec<(&'static str, NurbsCurve)> = vec![
473        ("V", mirrored(&fillet_fit)),
474        ("R", mirrored(&flank_fit)),
475        ("K", arc(r_a, -tip_angle, tip_angle)?),
476        ("L", flank_fit.reversed().map_err(|e| refuse("gear_fit", e))?),
477        ("W", fillet_fit.reversed().map_err(|e| refuse("gear_fit", e))?),
478    ];
479    if land > 1e-9 {
480        tooth.push(("G", arc(r_f, root_angle, 2.0 * half_pitch - root_angle)?));
481    }
482
483    let mut curves = Vec::with_capacity(tooth.len() * gear.teeth);
484    for index in 0..gear.teeth {
485        let angle = TAU * index as f64 / z;
486        for (role, curve) in &tooth {
487            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
488        }
489    }
490    // Share every junction exactly: each curve ends on the next one's first point.
491    snap_junctions(&mut curves);
492
493    let thickness_angle = |radius: f64| polar_angle(rack.flank(rack.flank_x_at_radius(radius)));
494    let data = GearData {
495        pitch_diameter: 2.0 * r,
496        base_diameter: 2.0 * r_b,
497        tip_diameter: 2.0 * r_a,
498        root_diameter: 2.0 * r_f,
499        form_diameter: 2.0 * form_radius,
500        tooth_thickness: 2.0 * r * thickness_angle(r.max(r_b)),
501        tip_thickness: 2.0 * r_a * tip_angle,
502        undercut,
503        min_shift_without_undercut: min_shift,
504    };
505    Ok(GearSection { curves, data })
506}
507
508/// A spur gear solid: the section extruded along +z by the face width. The face
509/// names (suffixes, in the solid's face order) are the section curves' roles,
510/// then `F` (the z = 0 face) and `B` (the z = width face).
511pub fn spur_solid(gear: &SpurGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
512    let section = spur_section(gear)?;
513    let solid = extrude_section(&section, gear.face_width)?;
514    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
515    names.push("F".into());
516    names.push("B".into());
517    Ok((solid, names, section.data))
518}
519
520/// An intermittent (mutilated) spur gear: only teeth 0 .. `kept` of the full gear, the rest of the rim an exact
521/// arc. Without `locking` the gap is the root circle; with it, past one root land after the last tooth and before
522/// the first (room for the driven gear's tooth to leave and enter), the rim rises radially to an arc on the tip
523/// circle that locks the driven gear between steps. Names: the kept teeth as the spur gear's, `S` the gap's arc,
524/// `E0`/`E1` the locking arc's radial ends, then `F`, `B`.
525pub fn spur_sector_solid(gear: &SpurGear, kept: usize, locking: bool) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
526    let full = spur_section(gear)?;
527    let z = gear.teeth;
528    if !(1..z).contains(&kept) {
529        return Err(refuse("gear_input", format!("A sector keeps from 1 to {} of the {z} teeth (not {kept}).", z - 1)));
530    }
531    if locking && kept + 2 > z {
532        return Err(refuse("gear_input", "A locking arc needs at least two teeth left out (a root land each side).".into()));
533    }
534    let point = |curve: &NurbsCurve, end: bool| -> Result<[f64; 2], KernelRefusal> {
535        let [a, b] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
536        let p = curve.evaluate(if end { b } else { a }).map_err(|e| refuse("gear_eval", e))?;
537        Ok([p.x, p.y])
538    };
539    let unwrap_ccw = |from: f64, to: f64| from + (to - from).rem_euclid(TAU);
540    let mut curves: Vec<SectionCurve> = full.curves.iter().filter(|c| c.tooth < kept).cloned().collect();
541    let first = full.curves.iter().find(|c| c.tooth == 0).expect("tooth 0").curve.clone();
542    let start = point(&first, false)?; // tooth 0's first piece: where the rim comes back
543    let root_r = radius_of(start);
544    if locking {
545        // Keep the root land after the last tooth and the one before tooth 0; between them the locking arc.
546        let after = full.curves.iter().filter(|c| c.tooth == kept).next().expect("the next tooth").curve.clone();
547        let rise = point(&after, false)?; // where tooth `kept` would start
548        let before_land = full.curves.iter().filter(|c| c.tooth == z - 1 && c.role == "G").last().map(|c| c.curve.clone());
549        let Some(before_land) = before_land else {
550            return Err(refuse("gear_input", "This gear has no root land for a locking arc.".into()));
551        };
552        let fall = point(&before_land, false)?; // where the land before tooth 0 starts
553        let tip_r = full.data.tip_diameter / 2.0;
554        let (a0, a1) = (polar_angle(rise), polar_angle(fall));
555        let a1 = unwrap_ccw(a0, a1);
556        let up = [tip_r * a0.cos(), tip_r * a0.sin()];
557        let down = [tip_r * a1.cos(), tip_r * a1.sin()];
558        curves.push(SectionCurve { curve: line(rise, up)?, role: "E", tooth: 0 });
559        curves.push(SectionCurve { curve: arc(tip_r, a0, a1)?, role: "S", tooth: 0 });
560        curves.push(SectionCurve { curve: line(down, fall)?, role: "E", tooth: 1 });
561        curves.push(SectionCurve { curve: before_land, role: "G", tooth: z - 1 });
562    } else {
563        // Drop the last kept tooth's root land: the root circle runs on to tooth 0.
564        if curves.last().is_some_and(|c| c.role == "G") {
565            curves.pop();
566        }
567        let end = point(&curves.last().expect("a kept tooth").curve, true)?;
568        let (a0, a1) = (polar_angle(end), polar_angle(start));
569        curves.push(SectionCurve { curve: arc(root_r, a0, unwrap_ccw(a0, a1))?, role: "S", tooth: 0 });
570    }
571    snap_junctions(&mut curves);
572    let section = GearSection { curves, data: full.data };
573    let solid = extrude_section(&section, gear.face_width)?;
574    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
575    names.push("F".into());
576    names.push("B".into());
577    Ok((solid, names, section.data))
578}
579
580/// Extrude a counter-clockwise gear section along +z.
581pub fn extrude_section(section: &GearSection, width: f64) -> Result<BrepSolid, KernelRefusal> {
582    let curves: Vec<NurbsCurve> = section.curves.iter().map(|piece| piece.curve.clone()).collect();
583    extrude_profile_brep(&curves, Vec3::new(0.0, 0.0, 1.0), width)
584}
585
586/// A straight-toothed rack: the basic rack profile of `teeth` teeth along +x
587/// from x = 0, the pitch line on y = 0, teeth pointing +y, extruded along +z.
588/// Each end stops in the middle of a tooth space.
589#[derive(Clone, Debug)]
590pub struct Rack {
591    pub module: f64,
592    pub teeth: usize,
593    pub pressure_angle: f64,
594    pub addendum: f64,
595    pub dedendum: f64,
596    /// Root fillet radius coefficient (× module).
597    pub root_fillet: f64,
598    /// Circumferential backlash taken off the tooth thickness on the pitch line.
599    pub backlash: f64,
600    pub face_width: f64,
601    /// Distance from the pitch line down to the rack's back face.
602    pub height: f64,
603    /// Helix angle of a helical rack (0: straight teeth); the module, pressure
604    /// angle and coefficients are then those of the normal section. Positive
605    /// leans the teeth one way (right hand), negative the other.
606    pub helix_angle: f64,
607}
608
609impl Default for Rack {
610    fn default() -> Self {
611        Self {
612            module: 2.0,
613            teeth: 10,
614            pressure_angle: 20f64.to_radians(),
615            addendum: 1.0,
616            dedendum: 1.25,
617            root_fillet: 0.38,
618            backlash: 0.0,
619            face_width: 10.0,
620            height: 6.0,
621            helix_angle: 0.0,
622        }
623    }
624}
625
626fn line(a: [f64; 2], b: [f64; 2]) -> Result<NurbsCurve, KernelRefusal> {
627    crate::make_line(Vec3::new(a[0], a[1], 0.0), Vec3::new(b[0], b[1], 0.0)).map_err(|error| refuse("gear_line", error))
628}
629
630fn centred_arc(centre: [f64; 2], radius: f64, from: f64, to: f64) -> Result<NurbsCurve, KernelRefusal> {
631    make_arc(Vec3::new(centre[0], centre[1], 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), radius, from, to)
632        .map_err(|error| refuse("gear_arc", error))
633}
634
635/// The section of a straight rack (exact: lines and arcs), counter-clockwise.
636/// Roles: `G<k>` the root land before tooth k (`G<teeth>` the last one),
637/// `W<k>`/`V<k>` the root fillets left/right of tooth k, `L<k>`/`R<k>` its
638/// left (low x) and right flanks, `K<k>` its tip, `BASE` the back face, `E0`
639/// and `E1` the ends at x = 0 and x = length.
640pub fn rack_section(rack: &Rack) -> Result<GearSection, KernelRefusal> {
641    rack_section_checked(rack, 35.0)
642}
643
644fn rack_section_checked(rack: &Rack, max_pressure_degrees: f64) -> Result<GearSection, KernelRefusal> {
645    let m = rack.module;
646    let positive = |value: f64, what: &str| {
647        if value.is_finite() && value > 0.0 {
648            Ok(())
649        } else {
650            Err(refuse("gear_input", format!("The {what} must be greater than zero (it is {value}).")))
651        }
652    };
653    positive(m, "module")?;
654    positive(rack.face_width, "face width")?;
655    positive(rack.addendum, "addendum coefficient")?;
656    positive(rack.dedendum, "dedendum coefficient")?;
657    if rack.teeth < 1 {
658        return Err(refuse("gear_input", "A rack needs at least one tooth.".into()));
659    }
660    let degrees = rack.pressure_angle.to_degrees();
661    if !(10.0 - 1e-9..=max_pressure_degrees + 1e-9).contains(&degrees) {
662        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and {max_pressure_degrees}° (it is {degrees}°).")));
663    }
664    if !(rack.root_fillet >= 0.0) || !(rack.backlash >= 0.0) {
665        return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
666    }
667    let alpha = rack.pressure_angle;
668    let (ha, hf) = (rack.addendum * m, rack.dedendum * m);
669    if rack.height <= hf + 1e-9 * m {
670        return Err(refuse(
671            "rack_too_thin",
672            format!("The rack height below the pitch line ({:.4}) must exceed the dedendum ({:.4}).", rack.height, hf),
673        ));
674    }
675    let p = PI * m;
676    let w = p / 4.0 - rack.backlash / 2.0; // half the tooth thickness on the pitch line
677    let tip_half = w - ha * alpha.tan();
678    if tip_half <= 1e-6 * m {
679        return Err(refuse(
680            "pointed_tip",
681            "The rack teeth come to a point below their tip line; reduce the addendum, the pressure angle or the backlash.".into(),
682        ));
683    }
684    let rho = rack.root_fillet * m;
685    // Right-hand fillet of the tooth centred on x = 0: centre, flank tangent point, root tangent x.
686    let y_p = -hf + rho - rho * alpha.sin();
687    let flank_x = |y: f64| w - y * alpha.tan();
688    let centre = [flank_x(y_p) + rho * alpha.cos(), -hf + rho];
689    let root_half = centre[0]; // the root tangent point's x (right of the tooth centre)
690    if y_p >= ha - 1e-9 * m {
691        return Err(refuse(
692            "root_fillet_too_large",
693            format!(
694                "The root fillet (coefficient {:.4}) reaches above the tooth tip; lower it or raise the addendum.",
695                rack.root_fillet
696            ),
697        ));
698    }
699    if root_half > p / 2.0 + 1e-9 * m {
700        let max = (p / 2.0 - w - hf * alpha.tan()) * alpha.cos() / (1.0 - alpha.sin());
701        return Err(refuse(
702            "root_fillet_too_large",
703            format!("The root fillet coefficient {:.4} is larger than the {:.4} that fits this tooth space; lower it.", rack.root_fillet, max / m),
704        ));
705    }
706    let length = p * rack.teeth as f64;
707    let mut curves: Vec<SectionCurve> = Vec::new();
708    let mut push = |curve: NurbsCurve, role: &'static str, tooth: usize| curves.push(SectionCurve { curve, role, tooth });
709    let base = -rack.height;
710    push(line([0.0, base], [length, base])?, "BASE", 0);
711    push(line([length, base], [length, -hf])?, "E1", 0);
712    // Teeth from the right end leftwards (counter-clockwise along the top).
713    let mut x_prev_root = length; // where the current root land starts (right end)
714    for k in (0..rack.teeth).rev() {
715        let c = (k as f64 + 0.5) * p;
716        let right_root = [c + root_half, -hf];
717        if x_prev_root - right_root[0] > 1e-9 * m {
718            push(line([x_prev_root, -hf], right_root)?, "G", k + 1);
719        }
720        // Right fillet: from the root tangent (angle 270°) back to the flank tangent (180° + alpha).
721        let right_centre = [c + centre[0], centre[1]];
722        let right_flank_low = [c + flank_x(y_p), y_p];
723        if rho > 0.0 {
724            push(centred_arc(right_centre, rho, PI + alpha, 1.5 * PI)?.reversed().map_err(|e| refuse("gear_arc", e))?, "V", k);
725        }
726        let right_tip = [c + tip_half, ha];
727        let left_tip = [c - tip_half, ha];
728        let left_flank_low = [c - flank_x(y_p), y_p];
729        push(line(if rho > 0.0 { right_flank_low } else { right_root }, right_tip)?, "R", k);
730        push(line(right_tip, left_tip)?, "K", k);
731        let left_root = [c - root_half, -hf];
732        push(line(left_tip, if rho > 0.0 { left_flank_low } else { left_root })?, "L", k);
733        if rho > 0.0 {
734            let left_centre = [c - centre[0], centre[1]];
735            push(centred_arc(left_centre, rho, 1.5 * PI, 2.0 * PI - alpha)?.reversed().map_err(|e| refuse("gear_arc", e))?, "W", k);
736        }
737        x_prev_root = left_root[0];
738    }
739    if x_prev_root > 1e-9 * m {
740        push(line([x_prev_root, -hf], [0.0, -hf])?, "G", 0);
741    }
742    push(line([0.0, -hf], [0.0, base])?, "E0", 0);
743    // Share every junction exactly.
744    snap_junctions(&mut curves);
745    let data = GearData {
746        pitch_diameter: f64::INFINITY,
747        tooth_thickness: 2.0 * w,
748        tip_thickness: 2.0 * tip_half,
749        ..GearData::default()
750    };
751    Ok(GearSection { curves, data })
752}
753
754/// A rack solid: the section extruded along +z by the face width; names as
755/// [`rack_section`], then `F` (z = 0) and `B` (z = width).
756pub fn rack_solid(rack: &Rack) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
757    let beta = rack.helix_angle;
758    if !(beta.abs().to_degrees() <= 45.0 + 1e-9) {
759        return Err(refuse("bad_helix", format!("The rack's helix angle must be between −45° and 45° (it is {:.4}°).", beta.to_degrees())));
760    }
761    // A helical rack's transverse section (the plane z = const) is the rack of
762    // the transverse module and pressure angle; the teeth run along (tan beta, 0, 1).
763    let degrees = rack.pressure_angle.to_degrees();
764    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&degrees) {
765        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and 35° (it is {degrees}°).")));
766    }
767    if beta == 0.0 {
768        // Straight teeth: the rack exactly as given (no transverse conversion).
769        let section = rack_section(rack)?;
770        let solid = extrude_section(&section, rack.face_width)?;
771        let mut names: Vec<String> = section.curves.iter().map(rack_suffix).collect();
772        names.push("F".into());
773        names.push("B".into());
774        return Ok((solid, names, section.data));
775    }
776    // A helical rack's teeth are straight prisms along (tan beta, 0, 1). Its
777    // normal section (across the teeth) is the basic rack; the transverse
778    // section (z = const) is that section stretched along the rack by
779    // 1 / cos beta, exactly: lines stay lines, the root rounds become ellipses
780    // (still rational quadratic arcs).
781    let c = beta.cos();
782    let mut section = rack_section(rack)?;
783    for piece in &mut section.curves {
784        for point in &mut piece.curve.control_points {
785            point.x /= c;
786        }
787    }
788    // The recorded thicknesses are read along the rack (transverse), as the section is.
789    section.data.tooth_thickness /= c;
790    section.data.tip_thickness /= c;
791    let curves: Vec<NurbsCurve> = section.curves.iter().map(|piece| piece.curve.clone()).collect();
792    let direction = Vec3::new(beta.tan(), 0.0, 1.0);
793    let solid = extrude_profile_brep(&curves, direction, rack.face_width / c)?;
794    let mut names: Vec<String> = section.curves.iter().map(rack_suffix).collect();
795    names.push("F".into());
796    names.push("B".into());
797    Ok((solid, names, section.data))
798}
799
800fn rack_suffix(piece: &SectionCurve) -> String {
801    match piece.role {
802        "BASE" | "E0" | "E1" => piece.role.to_string(),
803        _ => piece.suffix(),
804    }
805}
806
807/// Share every junction of a closed loop exactly: each curve ends on the next one's first point.
808fn snap_junctions(curves: &mut [SectionCurve]) {
809    let count = curves.len();
810    for index in 0..count {
811        let start = curves[(index + 1) % count].curve.control_points[0];
812        let curve = &mut curves[index].curve;
813        let last = curve.control_points.len() - 1;
814        let w = curve.control_points[last].w;
815        curve.control_points[last] = Vec4 { x: start.x / start.w * w, y: start.y / start.w * w, z: start.z / start.w * w, w };
816    }
817}
818
819/// An internal (ring) gear: involute tooth spaces cut into the inside of a
820/// ring. Lengths in model units, angles in radians, coefficients × module.
821#[derive(Clone, Debug)]
822pub struct RingGear {
823    pub module: f64,
824    pub teeth: usize,
825    pub pressure_angle: f64,
826    /// Profile shift: the cutter moved outward by x · module (tip and root
827    /// circles grow by x · module, the spaces widen by 2 x m tan alpha).
828    pub profile_shift: f64,
829    pub addendum: f64,
830    pub dedendum: f64,
831    /// Radius of the root fillet (× module): an exact arc tangent to the
832    /// flank and the root circle.
833    pub root_fillet: f64,
834    /// Circumferential backlash added to each tooth space on the reference circle.
835    pub backlash: f64,
836    pub face_width: f64,
837    /// Radial wall beyond the root circle.
838    pub rim: f64,
839}
840
841impl Default for RingGear {
842    fn default() -> Self {
843        Self {
844            module: 2.0,
845            teeth: 60,
846            pressure_angle: 20f64.to_radians(),
847            profile_shift: 0.0,
848            addendum: 1.0,
849            dedendum: 1.25,
850            root_fillet: 0.38,
851            backlash: 0.0,
852            face_width: 10.0,
853            rim: 6.0,
854        }
855    }
856}
857
858/// The inner (toothed) loop of a ring gear, counter-clockwise about +z, and its data.
859/// Roles per tooth space k: `R<k>` flank on its clockwise side, `V<k>` its
860/// fillet, `G<k>` the root land, `W<k>`, `L<k>`, then `K<k>` the tip land of
861/// the ring tooth after the space.
862pub fn ring_section(gear: &RingGear) -> Result<GearSection, KernelRefusal> {
863    ring_section_checked(gear, 35.0)
864}
865
866fn ring_section_checked(gear: &RingGear, max_pressure_degrees: f64) -> Result<GearSection, KernelRefusal> {
867    let m = gear.module;
868    let positive = |value: f64, what: &str| {
869        if value.is_finite() && value > 0.0 {
870            Ok(())
871        } else {
872            Err(refuse("gear_input", format!("The {what} must be greater than zero (it is {value}).")))
873        }
874    };
875    positive(m, "module")?;
876    positive(gear.face_width, "face width")?;
877    positive(gear.addendum, "addendum coefficient")?;
878    positive(gear.dedendum, "dedendum coefficient")?;
879    positive(gear.rim, "rim thickness")?;
880    if gear.teeth < 6 {
881        return Err(refuse("gear_input", format!("An internal gear needs at least 6 teeth (it has {}).", gear.teeth)));
882    }
883    let degrees = gear.pressure_angle.to_degrees();
884    if !(10.0 - 1e-9..=max_pressure_degrees + 1e-9).contains(&degrees) {
885        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and {max_pressure_degrees}° (it is {degrees}°).")));
886    }
887    if !(gear.root_fillet >= 0.0) || !(gear.backlash >= 0.0) || !gear.profile_shift.is_finite() {
888        return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
889    }
890    let z = gear.teeth as f64;
891    let alpha = gear.pressure_angle;
892    let r = m * z / 2.0;
893    let r_b = r * alpha.cos();
894    let r_a = r - (gear.addendum - gear.profile_shift) * m; // inner (tip) circle
895    let r_f = r + (gear.dedendum + gear.profile_shift) * m; // outer (root) circle
896    let rho = gear.root_fillet * m;
897    let half_pitch = PI / z;
898    let tolerance = GEAR_FIT_TOLERANCE * m;
899    if r_a <= r_b + 1e-9 * m {
900        return Err(refuse(
901            "tip_inside_base",
902            format!(
903                "An internal gear's tip circle (d = {:.4}) must lie outside its base circle (d = {:.4}); raise the tooth count, lower the pressure angle or the addendum.",
904                2.0 * r_a,
905                2.0 * r_b
906            ),
907        ));
908    }
909    // Half the SPACE angle at a radius: the space is shaped as an external tooth.
910    let space = PI * m / 2.0 + 2.0 * gear.profile_shift * m * alpha.tan() + gear.backlash;
911    let involute = |angle: f64| angle.tan() - angle;
912    let half_space = |radius: f64| space / (2.0 * r) + involute(alpha) - involute((r_b / radius).min(1.0).acos());
913    let flank = |radius: f64| {
914        let angle = half_space(radius);
915        [radius * angle.cos(), radius * angle.sin()]
916    };
917    if half_space(r_a) >= half_pitch - 1e-6 * m / r_a {
918        return Err(refuse(
919            "pointed_tip",
920            "The ring teeth come to a point at the tip circle: reduce the profile shift, the backlash or the addendum.".into(),
921        ));
922    }
923    // The spaces narrow outward: one that closes before the root circle has
924    // crossed flanks (read unwrapped, from the closed form).
925    if half_space(r_f) <= 1e-6 * m / r_f {
926        let (mut lo, mut hi) = (r_a, r_f);
927        for _ in 0..200 {
928            let mid = 0.5 * (lo + hi);
929            if half_space(mid) > 0.0 { lo = mid } else { hi = mid }
930        }
931        return Err(refuse(
932            "teeth_overlap",
933            format!(
934                "The tooth spaces close at d = {:.4}, inside the root circle (d = {:.4}); reduce the dedendum or the profile shift.",
935                2.0 * lo,
936                2.0 * r_f
937            ),
938        ));
939    }
940    // The fillet: a circle of radius rho tangent to the flank (left side of
941    // space 0, at T) and inside the root circle. Its centre is T moved by rho
942    // along the flank's normal into the space; solve |centre| = r_f - rho for T.
943    let normal_into_space = |radius: f64| {
944        let h = 1e-6 * m;
945        let (a, b) = (flank(radius - h), flank(radius + h));
946        let (tx, ty) = (b[0] - a[0], b[1] - a[1]);
947        let length = tx.hypot(ty);
948        // The space lies at smaller angles than its left flank: the normal turned clockwise from the outward tangent.
949        [ty / length, -tx / length]
950    };
951    let centre_at = |radius: f64| {
952        let point = flank(radius);
953        let n = normal_into_space(radius);
954        [point[0] + rho * n[0], point[1] + rho * n[1]]
955    };
956    let (join_radius, centre) = if rho == 0.0 {
957        (r_f, flank(r_f))
958    } else {
959        let target = r_f - rho;
960        let (mut lo, mut hi) = (r_a, r_f);
961        if radius_of(centre_at(lo)) > target {
962            return Err(refuse("root_fillet_too_large", "The root fillet is too large for the tooth depth; lower it.".into()));
963        }
964        for _ in 0..200 {
965            let mid = 0.5 * (lo + hi);
966            if radius_of(centre_at(mid)) < target { lo = mid } else { hi = mid }
967        }
968        let radius = 0.5 * (lo + hi);
969        (radius, centre_at(radius))
970    };
971    let root_angle = polar_angle(centre);
972    if rho > 0.0 && root_angle <= 1e-9 {
973        return Err(refuse(
974            "root_fillet_too_large",
975            "The root fillet is larger than fits the tooth space; lower it.".into(),
976        ));
977    }
978    let tip_angle = half_space(r_a);
979    // Left flank of space 0 from its root end (join) in to the tip circle.
980    let flank_fit = fit_planar(&|radius| flank(radius), r_a, join_radius, tolerance)?; // tip -> join
981    let mut space: Vec<(&'static str, NurbsCurve)> = Vec::new();
982    // Clockwise side (negative angles), outward: mirrored left flank (tip -> join), fillet, land, fillet, flank.
983    space.push(("R", mirrored(&flank_fit)));
984    if rho > 0.0 {
985        // The left fillet runs counter-clockwise about its centre from the root
986        // tangent point (straight out from the centre) round to the flank join.
987        let join = flank(join_radius);
988        let from = root_angle;
989        let mut to = (join[1] - centre[1]).atan2(join[0] - centre[0]);
990        while to <= from {
991            to += TAU;
992        }
993        let left = centred_arc(centre, rho, from, to)?; // root -> join
994        space.push(("V", mirrored(&left).reversed().map_err(|e| refuse("gear_arc", e))?));
995        space.push(("G", arc(r_f, -root_angle, root_angle)?));
996        space.push(("W", left));
997    } else {
998        space.push(("G", arc(r_f, -root_angle, root_angle)?));
999    }
1000    space.push(("L", flank_fit.reversed().map_err(|e| refuse("gear_fit", e))?));
1001    space.push(("K", arc(r_a, tip_angle, 2.0 * half_pitch - tip_angle)?));
1002    let mut curves = Vec::with_capacity(space.len() * gear.teeth);
1003    for index in 0..gear.teeth {
1004        let angle = TAU * index as f64 / z;
1005        for (role, curve) in &space {
1006            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
1007        }
1008    }
1009    snap_junctions(&mut curves);
1010    let data = GearData {
1011        pitch_diameter: 2.0 * r,
1012        base_diameter: 2.0 * r_b,
1013        tip_diameter: 2.0 * r_a,
1014        root_diameter: 2.0 * r_f,
1015        form_diameter: 2.0 * join_radius,
1016        tooth_thickness: 2.0 * r * (half_pitch - half_space(r)),
1017        tip_thickness: 2.0 * r_a * (half_pitch - tip_angle),
1018        undercut: false,
1019        min_shift_without_undercut: 0.0,
1020    };
1021    Ok(GearSection { curves, data })
1022}
1023
1024/// A ring gear solid: a cylinder of radius root + rim with the toothed loop
1025/// cut through it. Its faces carry their role names (`R3`, `K0`, …, `OD` the
1026/// outside, `F` at z = 0, `B` at z = width) in `face.name`.
1027pub fn ring_solid(gear: &RingGear) -> Result<(BrepSolid, GearData), KernelRefusal> {
1028    let section = ring_section(gear)?;
1029    let outer = section.data.root_diameter / 2.0 + gear.rim;
1030    let width = gear.face_width;
1031    let rows = |p: Vec4| vec![p, Vec4 { x: p.x, y: p.y, z: p.z + p.w * width, w: p.w }];
1032    let ring = hollow_prism(&section, outer, width, 1, &[0.0, 0.0, 1.0, 1.0], &rows)?;
1033    Ok((ring, section.data))
1034}
1035
1036/// A helical (or double helical) ring gear: `gear` in the normal section,
1037/// its transverse section screwed through the blank. Names as [`ring_solid`].
1038pub fn ring_solid_helical(gear: &RingGear, helix_angle: f64, hand: Hand, herringbone: bool) -> Result<(BrepSolid, GearData), KernelRefusal> {
1039    let beta = helix_angle;
1040    if !(beta.to_degrees() >= 0.5 - 1e-9 && beta.to_degrees() <= 45.0 + 1e-9) {
1041        return Err(refuse("bad_helix", format!("The helix angle must be between 0.5° and 45° (it is {:.4}°).", beta.to_degrees())));
1042    }
1043    let normal = gear.pressure_angle.to_degrees();
1044    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&normal) {
1045        return Err(refuse("gear_input", format!("The normal pressure angle must be between 10° and 35° (it is {normal}°).")));
1046    }
1047    let c = beta.cos();
1048    let transverse = RingGear {
1049        module: gear.module / c,
1050        pressure_angle: (gear.pressure_angle.tan() / c).atan(),
1051        profile_shift: gear.profile_shift * c,
1052        addendum: gear.addendum * c,
1053        dedendum: gear.dedendum * c,
1054        root_fillet: gear.root_fillet * c,
1055        ..gear.clone()
1056    };
1057    let section = ring_section_checked(&transverse, 60.0)?;
1058    let r = transverse.module * transverse.teeth as f64 / 2.0;
1059    let sign = if hand == Hand::Right { 1.0 } else { -1.0 };
1060    let rate = sign * beta.tan() / r; // turn per unit height
1061    let outer = section.data.root_diameter / 2.0 + gear.rim;
1062    // The section carried up the face width turning at the helix's rate (out and back for double helical).
1063    let width = gear.face_width;
1064    let turn = rate * width;
1065    let twist = if herringbone { Twist::Herringbone { turn } } else { Twist::Helical { turn } };
1066    let reach = section.curves.iter().flat_map(|c| c.curve.control_points.iter()).map(|p| (p.x / p.w).hypot(p.y / p.w)).fold(0.0, f64::max);
1067    let (knots_v, basis) = twist_basis(twist, reach, GEAR_FIT_TOLERANCE * transverse.module)?;
1068    let rows = |p: Vec4| -> Vec<Vec4> { basis.iter().map(|[c, s, t]| Vec4 { x: c * p.x - s * p.y, y: s * p.x + c * p.y, z: p.z + p.w * t * width, w: p.w }).collect() };
1069    let ring = hollow_prism(&section, outer, width, 3, &knots_v, &rows)?;
1070    Ok((ring, section.data))
1071}
1072
1073fn translated(curve: &NurbsCurve, dz: f64) -> NurbsCurve {
1074    let points = curve.control_points.iter().map(|p| Vec4 { x: p.x, y: p.y, z: p.z + p.w * dz, w: p.w }).collect();
1075    NurbsCurve::new(curve.degree, curve.knots.clone(), points).expect("a translated curve is a valid curve")
1076}
1077
1078/// Which ISO 606 tooth form a sprocket is cut to.
1079#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1080pub enum SprocketForm {
1081    /// Smallest seating radius, largest flank radius, largest seating angle.
1082    Minimum,
1083    /// Largest seating radius, smallest flank radius, smallest seating angle.
1084    Maximum,
1085    /// The mean of the two.
1086    Mean,
1087}
1088
1089/// A roller-chain sprocket (ISO 606 tooth form; ANSI chains are its A series).
1090#[derive(Clone, Debug)]
1091pub struct Sprocket {
1092    pub pitch: f64,
1093    pub roller_diameter: f64,
1094    pub teeth: usize,
1095    pub form: SprocketForm,
1096    /// Tooth width across the sprocket (the extrusion).
1097    pub width: f64,
1098}
1099
1100/// The section of a roller-chain sprocket, counter-clockwise; every curve is a
1101/// circular arc. Tooth k is centred on angle 2 pi k / z (tooth 0 on +x); gap k
1102/// follows it. Roles: `A<k>` the flank into gap k, `S<k>` its roller seating,
1103/// `C<k>` the flank out of it, `K<k>` the tip land of the tooth after gap k
1104/// (absent when the flanks meet below the tip circle).
1105pub fn sprocket_section(sprocket: &Sprocket) -> Result<GearSection, KernelRefusal> {
1106    let p = sprocket.pitch;
1107    let d1 = sprocket.roller_diameter;
1108    if !(p > 0.0 && d1 > 0.0 && d1 < p && sprocket.width > 0.0) {
1109        return Err(refuse(
1110            "gear_input",
1111            format!("The chain pitch ({p}), the roller diameter ({d1}, less than the pitch) and the width must be positive."),
1112        ));
1113    }
1114    if sprocket.teeth < 6 || sprocket.teeth > 300 {
1115        return Err(refuse("gear_input", format!("A sprocket needs from 6 to 300 teeth (it has {}).", sprocket.teeth)));
1116    }
1117    let z = sprocket.teeth as f64;
1118    let tau = TAU / z;
1119    let d = p / (PI / z).sin();
1120    // ISO 606 tooth form limits.
1121    let ri_min = 0.505 * d1;
1122    let ri_max = 0.505 * d1 + 0.069 * d1.cbrt();
1123    let re_min = 0.008 * d1 * (z * z + 180.0);
1124    let re_max = 0.12 * d1 * (z + 2.0);
1125    let a_min = (120.0 - 90.0 / z).to_radians();
1126    let a_max = (140.0 - 90.0 / z).to_radians();
1127    let da_min = d + p * (1.0 - 1.6 / z) - d1;
1128    let da_max = d + 1.25 * p - d1;
1129    let (ri, re, alpha, da) = match sprocket.form {
1130        SprocketForm::Minimum => (ri_min, re_max, a_max, da_min),
1131        SprocketForm::Maximum => (ri_max, re_min, a_min, da_max),
1132        SprocketForm::Mean => (0.5 * (ri_min + ri_max), 0.5 * (re_min + re_max), 0.5 * (a_min + a_max), 0.5 * (da_min + da_max)),
1133    };
1134    let ra = da / 2.0;
1135    // Gap 0 centred on angle tau / 2 is built centred on +x, then turned.
1136    let c = [d / 2.0, 0.0];
1137    let u = [-(alpha / 2.0).cos(), (alpha / 2.0).sin()]; // roller centre -> upper seating end
1138    let t_up = [c[0] + ri * u[0], c[1] + ri * u[1]];
1139    let f = [c[0] + (ri + re) * u[0], c[1] + (ri + re) * u[1]]; // the upper flank's centre
1140    // The upper flank: circle (f, re) from t_up outward. The tooth after the gap
1141    // is centred on the line at angle tau / 2 (built frame).
1142    let half = tau / 2.0;
1143    let a_t = (t_up[1] - f[1]).atan2(t_up[0] - f[0]);
1144    // Walk the flank circle from t_up in the sense that moves away from the axis.
1145    let on_flank = |angle: f64| [f[0] + re * angle.cos(), f[1] + re * angle.sin()];
1146    let step = 1e-4;
1147    let sense = if radius_of(on_flank(a_t + step)) > radius_of(on_flank(a_t - step)) { 1.0 } else { -1.0 };
1148    // Find where the flank reaches the tip circle or the tooth centre line, whichever first.
1149    let reach = |angle: f64| {
1150        let q = on_flank(angle);
1151        (radius_of(q) >= ra, polar_angle(q) >= half)
1152    };
1153    let (mut lo, mut hi) = (0.0, PI / 2.0);
1154    if !(reach(a_t + sense * hi).0 || reach(a_t + sense * hi).1) {
1155        return Err(refuse("gear_input", "The sprocket flank does not reach the tip circle.".into()));
1156    }
1157    for _ in 0..200 {
1158        let mid = 0.5 * (lo + hi);
1159        let (tip, centre) = reach(a_t + sense * mid);
1160        if tip || centre { hi = mid } else { lo = mid }
1161    }
1162    let a_end = a_t + sense * hi;
1163    let end = on_flank(a_end);
1164    let pointed = polar_angle(end) >= half - 1e-12 || radius_of(end) < ra - 1e-9 * p;
1165    let (a_end, end) = if pointed {
1166        // Land exactly on the tooth centre line.
1167        let (mut lo, mut hi) = (0.0, hi);
1168        for _ in 0..200 {
1169            let mid = 0.5 * (lo + hi);
1170            if polar_angle(on_flank(a_t + sense * mid)) >= half { hi = mid } else { lo = mid }
1171        }
1172        let a = a_t + sense * hi;
1173        (a, on_flank(a))
1174    } else {
1175        (a_end, end)
1176    };
1177    let flank_arc = |from: f64, to: f64| -> Result<NurbsCurve, KernelRefusal> {
1178        if to > from { centred_arc(f, re, from, to) } else { centred_arc(f, re, to, from)?.reversed().map_err(|e| refuse("gear_arc", e)) }
1179    };
1180    let upper = flank_arc(a_t, a_end)?; // t_up -> end
1181    let seat = centred_arc(c, ri, PI - alpha / 2.0, PI + alpha / 2.0)?.reversed().map_err(|e| refuse("gear_arc", e))?; // t_down -> t_up
1182    let lower = mirrored(&upper).reversed().map_err(|e| refuse("gear_arc", e))?; // end' -> t_down
1183    let mut gap: Vec<(&'static str, NurbsCurve)> = vec![("A", lower), ("S", seat), ("C", upper)];
1184    let tip_angle = polar_angle(end);
1185    if !pointed {
1186        gap.push(("K", arc(ra, tip_angle, tau - tip_angle)?));
1187    }
1188    let mut curves = Vec::with_capacity(gap.len() * sprocket.teeth);
1189    for index in 0..sprocket.teeth {
1190        let angle = tau * index as f64 + half;
1191        for (role, curve) in &gap {
1192            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
1193        }
1194    }
1195    snap_junctions(&mut curves);
1196    let data = GearData {
1197        pitch_diameter: d,
1198        tip_diameter: if pointed { 2.0 * radius_of(end) } else { da },
1199        root_diameter: d - 2.0 * ri,
1200        ..GearData::default()
1201    };
1202    Ok(GearSection { curves, data })
1203}
1204
1205/// A sprocket solid: the section extruded along +z by the width; names as
1206/// [`sprocket_section`], then `F` and `B`.
1207pub fn sprocket_solid(sprocket: &Sprocket) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
1208    let section = sprocket_section(sprocket)?;
1209    let solid = extrude_section(&section, sprocket.width)?;
1210    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
1211    names.push("F".into());
1212    names.push("B".into());
1213    Ok((solid, names, section.data))
1214}
1215
1216/// The turn of a twisted prism's section along its height: `theta(t)` at
1217/// `t = z / width` in [0, 1], with an optional crease at `t = 1/2` (a
1218/// herringbone's apex).
1219#[derive(Clone, Copy, Debug)]
1220pub enum Twist {
1221    /// theta = turn · t (a helical gear: a screw motion).
1222    Helical { turn: f64 },
1223    /// theta = turn · (1/2 − |t − 1/2|): out by `turn / 2` to the middle and back.
1224    Herringbone { turn: f64 },
1225}
1226
1227impl Twist {
1228    fn angle(&self, t: f64) -> f64 {
1229        match *self {
1230            Twist::Helical { turn } => turn * t,
1231            Twist::Herringbone { turn } => turn * (0.5 - (t - 0.5).abs()),
1232        }
1233    }
1234
1235    fn rate(&self, t: f64, after_crease: bool) -> f64 {
1236        match *self {
1237            Twist::Helical { turn } => turn,
1238            Twist::Herringbone { turn } => {
1239                if t < 0.5 || (t == 0.5 && !after_crease) { turn } else { -turn }
1240            }
1241        }
1242    }
1243
1244    fn total_turn(&self) -> f64 {
1245        match *self {
1246            Twist::Helical { turn } => turn.abs(),
1247            Twist::Herringbone { turn } => turn.abs(),
1248        }
1249    }
1250}
1251
1252/// The axial basis of a twisted prism: cubic Hermite spans in t carrying
1253/// (cos theta, sin theta, t), with doubled interior knots (C1) and a tripled
1254/// knot at a crease. Returns (knots, per control point (cos, sin, t)).
1255fn twist_basis(twist: Twist, reach: f64, tolerance: f64) -> Result<(Vec<f64>, Vec<[f64; 3]>), KernelRefusal> {
1256    let crease = matches!(twist, Twist::Herringbone { .. });
1257    // Hermite cubic error of cos/sin over a span of turn d: about reach · d^4 / 384.
1258    let per = (384.0 * tolerance / reach.max(1e-12)).powf(0.25);
1259    let needed = twist.total_turn() / per;
1260    if !(needed <= 4096.0) {
1261        return Err(refuse(
1262            "twist_too_long",
1263            format!(
1264                "The teeth turn {:.3} times round the axis over the face width; shorten the face width or lower the helix angle (at most {:.1} turns at this size).",
1265                twist.total_turn() / TAU,
1266                4096.0 * per / TAU
1267            ),
1268        ));
1269    }
1270    let mut spans = (needed.ceil() as usize).max(1);
1271    if crease && spans % 2 == 1 {
1272        spans += 1;
1273    }
1274    let value = |t: f64| {
1275        let a = twist.angle(t);
1276        [a.cos(), a.sin(), t]
1277    };
1278    let slope = |t: f64, after: bool| {
1279        let a = twist.angle(t);
1280        let r = twist.rate(t, after);
1281        [-a.sin() * r, a.cos() * r, 1.0]
1282    };
1283    let mut knots = vec![0.0; 4];
1284    let mut points = vec![value(0.0)];
1285    for index in 0..spans {
1286        let (t0, t1) = (index as f64 / spans as f64, (index + 1) as f64 / spans as f64);
1287        let h = (t1 - t0) / 3.0;
1288        let (p0, p1) = (value(t0), value(t1));
1289        let (d0, d1) = (slope(t0, true), slope(t1, false));
1290        points.push([p0[0] + d0[0] * h, p0[1] + d0[1] * h, p0[2] + d0[2] * h]);
1291        points.push([p1[0] - d1[0] * h, p1[1] - d1[1] * h, p1[2] - d1[2] * h]);
1292        let last = index + 1 == spans;
1293        let at_crease = crease && 2 * (index + 1) == spans;
1294        if last {
1295            points.push(p1);
1296        } else if at_crease {
1297            points.push(p1);
1298            knots.extend([t1, t1, t1]);
1299        } else {
1300            knots.extend([t1, t1]);
1301        }
1302    }
1303    knots.extend([1.0; 4]);
1304    Ok((knots, points))
1305}
1306
1307/// Carry a section curve along the twist: the curve turned by theta and lifted
1308
1309
1310/// A counter-clockwise section (z = 0) carried up to z = width while turning
1311/// by `twist`: side faces in section order, then the face at z = 0, then the
1312/// face at z = width (exactly the section turned by the end angle).
1313pub fn twisted_prism(section: &GearSection, width: f64, twist: Twist, tolerance: f64) -> Result<BrepSolid, KernelRefusal> {
1314    if !(width > 0.0) {
1315        return Err(refuse("gear_input", format!("The face width must be greater than zero (it is {width}).")));
1316    }
1317    let reach = section
1318        .curves
1319        .iter()
1320        .flat_map(|c| c.curve.control_points.iter())
1321        .map(|p| (p.x / p.w).hypot(p.y / p.w))
1322        .fold(0.0, f64::max);
1323    let (knots_v, basis) = twist_basis(twist, reach, tolerance)?;
1324    let rows = |p: Vec4| -> Vec<Vec4> {
1325        basis.iter().map(|[c, s, t]| Vec4 { x: c * p.x - s * p.y, y: s * p.x + c * p.y, z: p.z + p.w * t * width, w: p.w }).collect()
1326    };
1327    prism_by_rows(section, 3, &knots_v, &rows)
1328}
1329
1330/// The section's largest distance from the z axis, read off the curves (a rational arc's middle control
1331/// point lies outside the arc).
1332fn section_reach(section: &GearSection) -> Result<f64, KernelRefusal> {
1333    let mut reach: f64 = 0.0;
1334    for piece in &section.curves {
1335        let [t0, t1] = piece.curve.domain().map_err(|e| refuse("gear_domain", e))?;
1336        for i in 0..=32 {
1337            let p = piece.curve.evaluate(t0 + (t1 - t0) * i as f64 / 32.0).map_err(|e| refuse("gear_eval", e))?;
1338            reach = reach.max(p.x.hypot(p.y));
1339        }
1340    }
1341    Ok(reach)
1342}
1343
1344/// A cylinder of `radius` and `height` with the counter-clockwise planar section (in z = z0, read off the
1345/// section) carried through it by `rows` (as [`prism_by_rows`] carries it; the last row planar at z0 + `height`)
1346/// taken out:
1347/// a ring gear or a spline hub, built directly rather than as a boolean. The section's faces are named by
1348/// their role (`R3`, `G0`, …), the cylinder `OD`, the face at z = 0 `F` and the face at z = `height` `B`.
1349pub fn hollow_prism(section: &GearSection, radius: f64, height: f64, degree_v: usize, knots_v: &[f64], rows: &dyn Fn(Vec4) -> Vec<Vec4>) -> Result<BrepSolid, KernelRefusal> {
1350    use crate::sweep_topology::{curve_to_plane_parameters, make_plane, parameter_line};
1351    let line = |a: [f64; 2], b: [f64; 2]| parameter_line(a[0], a[1], b[0], b[1]).map_err(|e| refuse("gear_pcurve", e));
1352    let point_of = |p: Vec4| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w);
1353    if !(height > 0.0 && radius.is_finite() && radius > section_reach(section)? * (1.0 + 1e-9)) {
1354        return Err(refuse("gear_input", format!("The ring's outside radius ({radius}) must clear its section and its height ({height}) be positive.")));
1355    }
1356    let count = section.curves.len();
1357    let z0 = section.curves.first().map(|c| c.curve.control_points[0]).map(|p| p.z / p.w).unwrap_or(0.0);
1358    let mut shell = ShellBuilder { vertices: Vec::new(), edges: Vec::new(), faces: Vec::new(), next: 0 };
1359    // The walls: junction j starts curve j at the bottom and the top, joined by its v-curve.
1360    let mut bottom_v = Vec::with_capacity(count);
1361    let mut top_v = Vec::with_capacity(count);
1362    let mut axial = Vec::with_capacity(count);
1363    for piece in &section.curves {
1364        let start = piece.curve.control_points[0];
1365        let unit = Vec4 { x: start.x / start.w, y: start.y / start.w, z: start.z / start.w, w: 1.0 };
1366        let row = rows(unit);
1367        let (b, t) = (shell.vertex(point_of(start)), shell.vertex(point_of(*row.last().expect("a row"))));
1368        let curve = NurbsCurve::new(degree_v, knots_v.to_vec(), row).map_err(|e| refuse("gear_edge", e))?;
1369        axial.push(shell.edge(curve, b, t)?);
1370        bottom_v.push(b);
1371        top_v.push(t);
1372    }
1373    let mut bottom_e = Vec::with_capacity(count);
1374    let mut top_e = Vec::with_capacity(count);
1375    for (index, piece) in section.curves.iter().enumerate() {
1376        let next = (index + 1) % count;
1377        let top = NurbsCurve::new(piece.curve.degree, piece.curve.knots.clone(), piece.curve.control_points.iter().map(|p| *rows(*p).last().expect("a row")).collect()).map_err(|e| refuse("gear_curve", e))?;
1378        bottom_e.push(shell.edge(piece.curve.clone(), bottom_v[index], bottom_v[next])?);
1379        top_e.push(shell.edge(top, top_v[index], top_v[next])?);
1380    }
1381    for (index, piece) in section.curves.iter().enumerate() {
1382        let next = (index + 1) % count;
1383        let [u0, u1] = piece.curve.domain().map_err(|e| refuse("gear_domain", e))?;
1384        let grid: Vec<Vec<Vec4>> = piece.curve.control_points.iter().map(|p| rows(*p)).collect();
1385        let surface = NurbsSurface::new(piece.curve.degree, degree_v, piece.curve.knots.clone(), knots_v.to_vec(), grid).map_err(|e| refuse("gear_surface", e))?;
1386        let loops = vec![vec![
1387            (bottom_e[index], true, line([u0, 0.0], [u1, 0.0])?),
1388            (axial[next], true, line([u1, 0.0], [u1, 1.0])?),
1389            (top_e[index], false, line([u0, 1.0], [u1, 1.0])?),
1390            (axial[index], false, line([u0, 0.0], [u0, 1.0])?),
1391        ]];
1392        // The section's outward normal points into the hole: the solid lies outside it.
1393        shell.face(surface, false, loops, piece.suffix())?;
1394    }
1395    // The outside cylinder, one face with a seam at angle 0.
1396    let circle = crate::make_arc(Vec3::new(0.0, 0.0, z0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), radius, 0.0, TAU).map_err(|e| refuse("gear_arc", e))?;
1397    let lifted = translated(&circle, height);
1398    let (b0, t0) = (shell.vertex(Vec3::new(radius, 0.0, z0)), shell.vertex(Vec3::new(radius, 0.0, z0 + height)));
1399    let bottom_circle = shell.edge(circle.clone(), b0, b0)?;
1400    let top_circle = shell.edge(lifted.clone(), t0, t0)?;
1401    let seam = shell.edge(crate::make_line(Vec3::new(radius, 0.0, z0), Vec3::new(radius, 0.0, z0 + height)).map_err(|e| refuse("gear_edge", e))?, b0, t0)?;
1402    let side = crate::make_extrusion(&circle, Vec3::new(0.0, 0.0, height)).map_err(|e| refuse("gear_surface", e))?;
1403    let [c0, c1] = circle.domain().map_err(|e| refuse("gear_domain", e))?;
1404    let loops = vec![vec![
1405        (bottom_circle, true, line([c0, 0.0], [c1, 0.0])?),
1406        (seam, true, line([c1, 0.0], [c1, 1.0])?),
1407        (top_circle, false, line([c0, 1.0], [c1, 1.0])?),
1408        (seam, false, line([c0, 0.0], [c0, 1.0])?),
1409    ]];
1410    shell.face(side, true, loops, "OD".into())?;
1411    // The two ends: the outer circle round the section's hole.
1412    let pad = radius * 1.1 + 1.0;
1413    let x_axis = Vec3::new(1.0, 0.0, 0.0);
1414    let y_axis = Vec3::new(0.0, 1.0, 0.0);
1415    for (z, name, ring_edge, hole) in [(z0, "F", bottom_circle, &bottom_e), (z0 + height, "B", top_circle, &top_e)] {
1416        let origin = Vec3::new(-pad, -pad, z);
1417        let on_plane = |curve: &NurbsCurve| curve_to_plane_parameters(curve, origin, x_axis, y_axis).map_err(|e| refuse("gear_pcurve", e));
1418        let outer = vec![(ring_edge, true, on_plane(shell.curve(ring_edge))?)];
1419        let mut inner = Vec::with_capacity(count);
1420        for &edge in hole.iter() {
1421            inner.push((edge, true, on_plane(shell.curve(edge))?));
1422        }
1423        let plane = make_plane(origin, x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e))?;
1424        shell.face(plane, name == "B", vec![outer, inner], name.into())?;
1425    }
1426    let id = shell.id();
1427    let shell_id = shell.id();
1428    let solid = BrepSolid {
1429        mass_properties_cache: Default::default(),
1430        cells: Default::default(),
1431        id,
1432        vertices: shell.vertices,
1433        edges: shell.edges,
1434        shells: vec![crate::sweep_topology::ShellRecord { id: shell_id, faces: shell.faces }],
1435        genus: 1,
1436        kind: crate::BodyKind::Solid,
1437    };
1438    let issues = solid.validate();
1439    if !issues.is_empty() {
1440        return Err(KernelRefusal::internal(KernelStage::Validate, "validate", format!("hollow gear prism is not valid: {issues:?}")));
1441    }
1442    Ok(solid)
1443}
1444
1445/// A planar counter-clockwise section (in a plane z = const) carried along
1446/// v in [0, 1] by `rows`, which maps each homogeneous control point to the
1447/// control points of its v-curve (degree `degree_v` on `knots_v`); the last
1448/// row must again be planar at a constant z (the top cap). Side faces in
1449/// section order, then the face at v = 0, then the face at v = 1.
1450pub fn prism_by_rows(section: &GearSection, degree_v: usize, knots_v: &[f64], rows: &dyn Fn(Vec4) -> Vec<Vec4>) -> Result<BrepSolid, KernelRefusal> {
1451    use crate::sweep_topology::{curve_to_plane_parameters, make_plane, parameter_line, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, ShellRecord, VertexRecord};
1452    let curves: Vec<NurbsCurve> = section.curves.iter().map(|piece| piece.curve.clone()).collect();
1453    let count = curves.len();
1454    let top_of = |curve: &NurbsCurve| -> Result<NurbsCurve, KernelRefusal> {
1455        let points = curve.control_points.iter().map(|p| *rows(*p).last().expect("a row")).collect();
1456        NurbsCurve::new(curve.degree, curve.knots.clone(), points).map_err(|e| refuse("gear_curve", e))
1457    };
1458    let point_of = |p: Vec4| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w);
1459    let unit = |p: Vec4| Vec4 { x: p.x / p.w, y: p.y / p.w, z: p.z / p.w, w: 1.0 };
1460    let starts: Vec<Vec4> = curves.iter().map(|c| c.control_points[0]).collect();
1461    let mut vertices = Vec::with_capacity(2 * count);
1462    for (index, start) in starts.iter().enumerate() {
1463        vertices.push(VertexRecord { id: index as u64 + 1, point: point_of(*start) });
1464    }
1465    for (index, start) in starts.iter().enumerate() {
1466        vertices.push(VertexRecord { id: (count + index) as u64 + 1, point: point_of(*rows(unit(*start)).last().expect("a row")) });
1467    }
1468    let edge_id = |kind: usize, index: usize| 10 + (kind * count + index) as u64;
1469    let mut edges = Vec::with_capacity(3 * count);
1470    let mut tops = Vec::with_capacity(count);
1471    for (index, curve) in curves.iter().enumerate() {
1472        let [start, end] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
1473        let next = (index + 1) % count;
1474        let top = top_of(curve)?;
1475        let axial = NurbsCurve::new(degree_v, knots_v.to_vec(), rows(unit(starts[index]))).map_err(|e| refuse("gear_edge", e))?;
1476        edges.push(EdgeRecord { id: edge_id(0, index), curve: curve.clone(), t0: start, t1: end, start_vertex_id: index as u64 + 1, end_vertex_id: next as u64 + 1, degenerate: false, name: None });
1477        edges.push(EdgeRecord { id: edge_id(1, index), curve: top.clone(), t0: start, t1: end, start_vertex_id: (count + index) as u64 + 1, end_vertex_id: (count + next) as u64 + 1, degenerate: false, name: None });
1478        edges.push(EdgeRecord { id: edge_id(2, index), curve: axial, t0: 0.0, t1: 1.0, start_vertex_id: index as u64 + 1, end_vertex_id: (count + index) as u64 + 1, degenerate: false, name: None });
1479        tops.push(top);
1480    }
1481    let line = |a: [f64; 2], b: [f64; 2]| parameter_line(a[0], a[1], b[0], b[1]).map_err(|e| refuse("gear_pcurve", e));
1482    let mut next_id = 10 + 3 * count as u64 + 1000;
1483    let mut faces = Vec::with_capacity(count + 2);
1484    for (index, curve) in curves.iter().enumerate() {
1485        let [start, end] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
1486        let next = (index + 1) % count;
1487        let coedges = vec![
1488            CoedgeRecord { id: next_id, edge_id: edge_id(0, index), forward: true, pcurve: line([start, 0.0], [end, 0.0])? },
1489            CoedgeRecord { id: next_id + 1, edge_id: edge_id(2, next), forward: true, pcurve: line([end, 0.0], [end, 1.0])? },
1490            CoedgeRecord { id: next_id + 2, edge_id: edge_id(1, index), forward: false, pcurve: line([end, 1.0], [start, 1.0])? },
1491            CoedgeRecord { id: next_id + 3, edge_id: edge_id(2, index), forward: false, pcurve: line([start, 1.0], [start, 0.0])? },
1492        ];
1493        next_id += 4;
1494        let surface_rows: Vec<Vec<Vec4>> = curve.control_points.iter().map(|p| rows(*p)).collect();
1495        let surface = NurbsSurface::new(curve.degree, degree_v, curve.knots.clone(), knots_v.to_vec(), surface_rows).map_err(|e| refuse("gear_surface", e))?;
1496        faces.push(FaceRecord { id: next_id + 1, surface, same_sense: true, loops: vec![LoopRecord { id: next_id, coedges }], name: None });
1497        next_id += 2;
1498    }
1499    let reach = curves.iter().chain(tops.iter()).flat_map(|c| c.control_points.iter()).map(|p| (p.x / p.w).hypot(p.y / p.w)).fold(0.0, f64::max);
1500    let pad = reach * 1.1 + 1.0;
1501    let x_axis = Vec3::new(1.0, 0.0, 0.0);
1502    let y_axis = Vec3::new(0.0, 1.0, 0.0);
1503    let z0 = vertices[0].point.z;
1504    let z1 = vertices[count].point.z;
1505    let bottom_origin = Vec3::new(-pad, -pad, z0);
1506    let mut bottom = Vec::with_capacity(count);
1507    for index in (0..count).rev() {
1508        bottom.push(CoedgeRecord {
1509            id: next_id,
1510            edge_id: edge_id(0, index),
1511            forward: false,
1512            pcurve: curve_to_plane_parameters(&curves[index], bottom_origin, x_axis, y_axis).and_then(|c| c.reversed()).map_err(|e| refuse("gear_pcurve", e))?,
1513        });
1514        next_id += 1;
1515    }
1516    faces.push(FaceRecord {
1517        id: next_id + 1,
1518        surface: make_plane(bottom_origin, x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e))?,
1519        same_sense: false,
1520        loops: vec![LoopRecord { id: next_id, coedges: bottom }],
1521        name: None,
1522    });
1523    next_id += 2;
1524    let top_origin = Vec3::new(-pad, -pad, z1);
1525    let mut top = Vec::with_capacity(count);
1526    for (index, curve) in tops.iter().enumerate() {
1527        top.push(CoedgeRecord {
1528            id: next_id,
1529            edge_id: edge_id(1, index),
1530            forward: true,
1531            pcurve: curve_to_plane_parameters(curve, top_origin, x_axis, y_axis).map_err(|e| refuse("gear_pcurve", e))?,
1532        });
1533        next_id += 1;
1534    }
1535    faces.push(FaceRecord {
1536        id: next_id + 1,
1537        surface: make_plane(top_origin, x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e))?,
1538        same_sense: true,
1539        loops: vec![LoopRecord { id: next_id, coedges: top }],
1540        name: None,
1541    });
1542    next_id += 2;
1543    let solid = BrepSolid {
1544        mass_properties_cache: Default::default(),
1545        cells: Default::default(),
1546        id: next_id + 1,
1547        vertices,
1548        edges,
1549        shells: vec![ShellRecord { id: next_id, faces }],
1550        genus: 0,
1551        kind: crate::BodyKind::Solid,
1552    };
1553    let issues = solid.validate();
1554    if issues.is_empty() {
1555        Ok(solid)
1556    } else {
1557        Err(KernelRefusal::internal(KernelStage::Validate, "validate", format!("gear prism is not valid: {issues:?}")))
1558    }
1559}
1560
1561/// Hand of a helical gear's teeth.
1562#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1563pub enum Hand {
1564    Right,
1565    Left,
1566}
1567
1568/// A helical (or, with `herringbone`, double helical) external gear given by
1569/// its normal-section values; `spur` carries them (module = normal module,
1570/// pressure angle = normal pressure angle, coefficients × normal module).
1571#[derive(Clone, Debug)]
1572pub struct HelicalGear {
1573    pub spur: SpurGear,
1574    pub helix_angle: f64,
1575    pub hand: Hand,
1576    pub herringbone: bool,
1577}
1578
1579/// The transverse spur gear a helical gear's every section is (turned).
1580pub fn helical_transverse(gear: &HelicalGear) -> Result<SpurGear, KernelRefusal> {
1581    let beta = gear.helix_angle;
1582    // The pressure angle limits apply to the normal section (the cutter's).
1583    let normal = gear.spur.pressure_angle.to_degrees();
1584    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&normal) {
1585        return Err(refuse("gear_input", format!("The normal pressure angle must be between 10° and 35° (it is {normal}°).")));
1586    }
1587    if !(beta.to_degrees() >= 0.5 - 1e-9 && beta.to_degrees() <= 45.0 + 1e-9) {
1588        return Err(refuse("bad_helix", format!("The helix angle must be between 0.5° and 45° (it is {:.4}°).", beta.to_degrees())));
1589    }
1590    let n = &gear.spur;
1591    let c = beta.cos();
1592    Ok(SpurGear {
1593        module: n.module / c,
1594        teeth: n.teeth,
1595        pressure_angle: (n.pressure_angle.tan() / c).atan(),
1596        profile_shift: n.profile_shift * c,
1597        addendum: n.addendum * c,
1598        dedendum: n.dedendum * c,
1599        // The cutter's tip radius in the transverse section is taken as the
1600        // normal one (the true section of the round is a slightly longer ellipse).
1601        root_fillet: n.root_fillet * c,
1602        backlash: n.backlash,
1603        face_width: n.face_width,
1604    })
1605}
1606
1607/// A helical or herringbone gear solid; names as [`spur_solid`].
1608pub fn helical_solid(gear: &HelicalGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
1609    let transverse = helical_transverse(gear)?;
1610    let section = transverse_section(&transverse)?;
1611    let r = transverse.module * transverse.teeth as f64 / 2.0;
1612    let width = transverse.face_width;
1613    let sign = if gear.hand == Hand::Right { 1.0 } else { -1.0 };
1614    let twist = if gear.herringbone {
1615        // Each half advances by its own half width.
1616        Twist::Herringbone { turn: sign * width * gear.helix_angle.tan() / r }
1617    } else {
1618        Twist::Helical { turn: sign * width * gear.helix_angle.tan() / r }
1619    };
1620    let solid = twisted_prism(&section, width, twist, 0.1 * GEAR_FIT_TOLERANCE * transverse.module)?;
1621    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
1622    names.push("F".into());
1623    names.push("B".into());
1624    Ok((solid, names, section.data))
1625}
1626
1627/// A straight-sided spline (ISO 14 form: `teeth` keys of width `key_width`
1628/// between the minor diameter `minor` and the major diameter `major`).
1629#[derive(Clone, Debug)]
1630pub struct StraightSpline {
1631    pub teeth: usize,
1632    pub minor: f64,
1633    pub major: f64,
1634    pub key_width: f64,
1635    pub length: f64,
1636}
1637
1638fn check_straight_spline(spline: &StraightSpline) -> Result<(), KernelRefusal> {
1639    let StraightSpline { teeth, minor, major, key_width, length } = *spline;
1640    if !(minor > 0.0 && major > minor && key_width > 0.0 && length > 0.0) {
1641        return Err(refuse(
1642            "gear_input",
1643            format!("A spline needs 0 < minor diameter ({minor}) < major diameter ({major}), a positive key width ({key_width}) and length ({length})."),
1644        ));
1645    }
1646    if teeth < 2 || teeth > 100 {
1647        return Err(refuse("gear_input", format!("A spline needs from 2 to 100 keys (it has {teeth}).")));
1648    }
1649    // The keys must not meet on the minor circle.
1650    let half_root = (key_width / minor).asin();
1651    if !(key_width < minor) || 2.0 * half_root >= TAU / teeth as f64 - 1e-9 {
1652        return Err(refuse("keys_overlap", format!("{teeth} keys {key_width} wide do not fit round a {minor} minor diameter.")));
1653    }
1654    Ok(())
1655}
1656
1657/// The section of a straight-sided spline shaft, counter-clockwise; exact
1658/// lines and arcs. Key k is centred on angle 2 pi k / N. Roles: `R<k>`/`L<k>`
1659/// its flanks, `K<k>` its top on the major circle, `G<k>` the root land after it.
1660pub fn straight_spline_section(spline: &StraightSpline) -> Result<GearSection, KernelRefusal> {
1661    check_straight_spline(spline)?;
1662    let (rr, ra, h) = (spline.minor / 2.0, spline.major / 2.0, spline.key_width / 2.0);
1663    let n = spline.teeth as f64;
1664    let foot = [(rr * rr - h * h).sqrt(), h];
1665    let top = [(ra * ra - h * h).sqrt(), h];
1666    let top_angle = (h / ra).asin();
1667    let foot_angle = (h / rr).asin();
1668    let key: Vec<(&'static str, NurbsCurve)> = vec![
1669        ("R", line([foot[0], -h], [top[0], -h])?),
1670        ("K", arc(ra, -top_angle, top_angle)?),
1671        ("L", line(top, foot)?),
1672        ("G", arc(rr, foot_angle, TAU / n - foot_angle)?),
1673    ];
1674    let mut curves = Vec::with_capacity(4 * spline.teeth);
1675    for index in 0..spline.teeth {
1676        let angle = TAU * index as f64 / n;
1677        for (role, curve) in &key {
1678            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
1679        }
1680    }
1681    snap_junctions(&mut curves);
1682    Ok(GearSection { curves, data: GearData { tip_diameter: spline.major, root_diameter: spline.minor, ..GearData::default() } })
1683}
1684
1685/// A spline shaft: the section extruded along +z by the length; names as the
1686/// section's roles, then `F` and `B`.
1687pub fn straight_spline_shaft(spline: &StraightSpline) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
1688    let section = straight_spline_section(spline)?;
1689    let solid = extrude_section(&section, spline.length)?;
1690    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
1691    names.push("F".into());
1692    names.push("B".into());
1693    Ok((solid, names, section.data))
1694}
1695
1696/// Cut a counter-clockwise section through a cylinder of `outside` diameter
1697/// and `length`: a hub. The section's faces keep their role names, the
1698/// cylinder's are `OD`, `F` and `B` (all in `face.name`).
1699pub fn hub_from_section(section: &GearSection, outside: f64, length: f64) -> Result<BrepSolid, KernelRefusal> {
1700    // The section's true outer radius, read off the curves (a rational arc's
1701    // middle control point lies outside the arc).
1702    let mut reach: f64 = 0.0;
1703    for piece in &section.curves {
1704        let [t0, t1] = piece.curve.domain().map_err(|e| refuse("gear_domain", e))?;
1705        for i in 0..=32 {
1706            let p = piece.curve.evaluate(t0 + (t1 - t0) * i as f64 / 32.0).map_err(|e| refuse("gear_eval", e))?;
1707            reach = reach.max(p.x.hypot(p.y));
1708        }
1709    }
1710    if !(outside / 2.0 > reach + 1e-9) {
1711        return Err(refuse(
1712            "hub_too_small",
1713            format!("The hub's outside diameter ({outside}) must be larger than its spline's major diameter ({:.4}).", 2.0 * reach),
1714        ));
1715    }
1716    let rows = |p: Vec4| vec![p, Vec4 { x: p.x, y: p.y, z: p.z + p.w * length, w: p.w }];
1717    hollow_prism(section, outside / 2.0, length, 1, &[0.0, 0.0, 1.0, 1.0], &rows)
1718}
1719
1720/// A spline hub: the shaft's section (nominal size) cut through a cylinder.
1721pub fn straight_spline_hub(spline: &StraightSpline, outside: f64) -> Result<(BrepSolid, GearData), KernelRefusal> {
1722    let section = straight_spline_section(spline)?;
1723    let hub = hub_from_section(&section, outside, spline.length)?;
1724    Ok((hub, section.data))
1725}
1726
1727/// A timing-belt pulley with straight-sided grooves (ISO 5294 Table 2 form;
1728/// the metric trapezoidal profiles the same way): every curve a line or an arc.
1729#[derive(Clone, Debug)]
1730pub struct TimingPulley {
1731    /// Belt pitch.
1732    pub pitch: f64,
1733    pub teeth: usize,
1734    /// Pitch line differential 2a: outside diameter = pitch z / pi - 2a.
1735    pub pld: f64,
1736    /// Groove bottom width bw.
1737    pub bottom_width: f64,
1738    /// Groove depth hg (from the outside diameter).
1739    pub depth: f64,
1740    /// Groove side angle to the radial direction, each side (half of 2 beta).
1741    pub side_angle: f64,
1742    /// Bottom (root) corner radius rb.
1743    pub bottom_radius: f64,
1744    /// Top (tip) corner radius rt.
1745    pub top_radius: f64,
1746    pub width: f64,
1747}
1748
1749/// An arc about `centre` from `from` to `to` (both on it), counter-clockwise
1750/// when `ccw`, else clockwise.
1751fn arc_through(centre: [f64; 2], from: [f64; 2], to: [f64; 2], ccw: bool) -> Result<NurbsCurve, KernelRefusal> {
1752    let radius = (from[0] - centre[0]).hypot(from[1] - centre[1]);
1753    let a0 = (from[1] - centre[1]).atan2(from[0] - centre[0]);
1754    let a1 = (to[1] - centre[1]).atan2(to[0] - centre[0]);
1755    if ccw {
1756        let mut end = a1;
1757        while end <= a0 {
1758            end += TAU;
1759        }
1760        centred_arc(centre, radius, a0, end)
1761    } else {
1762        let mut start = a1;
1763        while start <= a0 - TAU {
1764            start += TAU;
1765        }
1766        while start >= a0 {
1767            start -= TAU;
1768        }
1769        centred_arc(centre, radius, start, a0)?.reversed().map_err(|e| refuse("gear_arc", e))
1770    }
1771}
1772
1773/// The pulley section, counter-clockwise. Groove k is centred on angle
1774/// 2 pi (k + 1/2) / z (tooth k on angle 2 pi k / z). Roles per groove k, in
1775/// order: `Q<k>` the top corner arc into it, `A<k>` its first side, `U<k>`
1776/// the bottom corner arc, `S<k>` the bottom, `D<k>` the other bottom corner
1777/// arc, `C<k>` the other side, `P<k>` the top corner arc out of it, `K<k>`
1778/// the land of the next tooth on the outside diameter.
1779pub fn timing_pulley_section(pulley: &TimingPulley) -> Result<GearSection, KernelRefusal> {
1780    let TimingPulley { pitch, teeth, pld, bottom_width, depth, side_angle, bottom_radius, top_radius, width } = pulley.clone();
1781    if !(pitch > 0.0 && pld >= 0.0 && bottom_width > 0.0 && depth > 0.0 && width > 0.0 && bottom_radius >= 0.0 && top_radius >= 0.0) {
1782        return Err(refuse("gear_input", "The pulley's pitch, groove sizes and width must be positive.".into()));
1783    }
1784    if !(0.0..60f64.to_radians()).contains(&side_angle) {
1785        return Err(refuse("gear_input", "The groove side angle must be between 0° and 60°.".into()));
1786    }
1787    if teeth < 6 || teeth > 400 {
1788        return Err(refuse("gear_input", format!("A pulley needs from 6 to 400 teeth (it has {teeth}).")));
1789    }
1790    let z = teeth as f64;
1791    let ro = pitch * z / PI / 2.0 - pld / 2.0;
1792    let x_bottom = ro - depth;
1793    if !(x_bottom > 0.0) {
1794        return Err(refuse("gear_input", "The groove is deeper than the pulley's radius.".into()));
1795    }
1796    let tau = TAU / z;
1797    let (s, c) = side_angle.sin_cos();
1798    let side = [c, s]; // outward along the upper side
1799    let normal = [-s, c]; // from the upper side into the material
1800    let corner = [x_bottom, bottom_width / 2.0];
1801    // The upper side meets the outside circle at |corner + t side| = ro.
1802    let b = corner[0] * side[0] + corner[1] * side[1];
1803    let t_top = -b + (b * b - (corner[0] * corner[0] + corner[1] * corner[1] - ro * ro)).sqrt();
1804    let top = [corner[0] + t_top * side[0], corner[1] + t_top * side[1]];
1805    // Bottom corner fillet: between the bottom (direction +y) and the side; the
1806    // path turns right there (clockwise arc). Interior turn angle phi = 90° - beta.
1807    let turn = PI / 2.0 - side_angle;
1808    let reach_b = bottom_radius * (turn / 2.0).tan();
1809    let t1 = [corner[0], corner[1] - reach_b];
1810    let t2 = [corner[0] + reach_b * side[0], corner[1] + reach_b * side[1]];
1811    let centre_b = [t1[0] + bottom_radius, t1[1]];
1812    // Top corner fillet: tangent to the side (offset into the material) and
1813    // inside the outside circle (centre at ro - rt).
1814    let rt = top_radius;
1815    let base = [corner[0] + rt * normal[0], corner[1] + rt * normal[1]];
1816    let bb = base[0] * side[0] + base[1] * side[1];
1817    let disc = bb * bb - (base[0] * base[0] + base[1] * base[1] - (ro - rt) * (ro - rt));
1818    if disc < 0.0 {
1819        return Err(refuse("gear_input", "The groove's top radius does not fit.".into()));
1820    }
1821    let t_c = -bb + disc.sqrt();
1822    let centre_t = [base[0] + t_c * side[0], base[1] + t_c * side[1]];
1823    let t3 = [corner[0] + t_c * side[0], corner[1] + t_c * side[1]];
1824    let scale = ro / (centre_t[0].hypot(centre_t[1]));
1825    let t4 = [centre_t[0] * scale, centre_t[1] * scale];
1826    let land_start = polar_angle(t4);
1827    if land_start >= tau / 2.0 - 1e-9 || reach_b > t_c + 1e-12 || t1[1] < 0.0 {
1828        return Err(refuse(
1829            "groove_too_wide",
1830            format!("The grooves and their corner radii do not fit the pitch at {teeth} teeth; add teeth or reduce the radii."),
1831        ));
1832    }
1833    let _ = top;
1834    // The upper half of groove 0, outward: bottom half line, D, C, P.
1835    let mut upper: Vec<(&'static str, NurbsCurve)> = Vec::new();
1836    if bottom_radius > 0.0 {
1837        upper.push(("D", arc_through(centre_b, t1, t2, false)?));
1838    }
1839    upper.push(("C", line(t2, t3)?));
1840    if rt > 0.0 {
1841        upper.push(("P", arc_through(centre_t, t3, t4, true)?));
1842    }
1843    let mut groove: Vec<(&'static str, NurbsCurve)> = Vec::new();
1844    let lower_roles = |role: &'static str| match role {
1845        "D" => "U",
1846        "C" => "A",
1847        _ => "Q",
1848    };
1849    for (role, curve) in upper.iter().rev() {
1850        groove.push((lower_roles(role), mirrored(curve).reversed().map_err(|e| refuse("gear_arc", e))?));
1851    }
1852    groove.push(("S", line([t1[0], -t1[1]], t1)?));
1853    groove.extend(upper.into_iter());
1854    groove.push(("K", arc(ro, land_start, tau - land_start)?));
1855    let mut curves = Vec::with_capacity(groove.len() * teeth);
1856    for index in 0..teeth {
1857        let angle = tau * index as f64 + tau / 2.0;
1858        for (role, curve) in &groove {
1859            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
1860        }
1861    }
1862    snap_junctions(&mut curves);
1863    let data = GearData { pitch_diameter: pitch * z / PI, tip_diameter: 2.0 * ro, root_diameter: 2.0 * x_bottom, ..GearData::default() };
1864    Ok(GearSection { curves, data })
1865}
1866
1867/// A straight beveloid (conical involute) gear: a spur gear whose profile shift grows linearly across the
1868/// face, `cone_angle` the angle its tip and root cones make with the axis. Every plane square to the axis is the
1869/// spur gear the standard rack generates at that plane's shift, so the flanks are involute helicoids (turning
1870/// opposite ways on the two sides) and the tip and root are cones; it meshes with spur, helical or beveloid
1871/// gears on parallel, crossed or skew axes and takes up backlash by sliding along its axis. `spur` is the gear
1872/// at z = 0 (its profile shift there) and its face width.
1873#[derive(Clone, Debug)]
1874pub struct BeveloidGear {
1875    pub spur: SpurGear,
1876    pub cone_angle: f64,
1877}
1878
1879/// A beveloid gear solid: plane sections skinned (planes added until the skin holds 1e-5 × module halfway
1880/// between them). Names as the spur gear's per tooth, then `F` (z = 0) and `B`.
1881pub fn beveloid_solid(gear: &BeveloidGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
1882    let base = &gear.spur;
1883    let m = base.module;
1884    let width = base.face_width;
1885    let degrees = gear.cone_angle.to_degrees();
1886    if !(degrees > 0.0 && degrees <= 20.0 + 1e-9) {
1887        return Err(refuse("gear_input", format!("The cone angle must be over 0° and at most 20° (it is {degrees}°).")));
1888    }
1889    if !(width > 0.0) {
1890        return Err(refuse("gear_input", "The face width must be positive.".into()));
1891    }
1892    let slope = gear.cone_angle.tan() / m;
1893    let at = |z: f64| -> Result<GearSection, KernelRefusal> { spur_section(&SpurGear { profile_shift: base.profile_shift + slope * z, ..base.clone() }) };
1894    let first = at(0.0)?;
1895    let roles: Vec<&'static str> = first.curves.iter().filter(|c| c.tooth == 0).map(|c| c.role).collect();
1896    let count = roles.len();
1897    // Tooth 0's pieces in a plane, each as a function of its normalised parameter.
1898    let pieces = |section: &GearSection| -> Result<Vec<NurbsCurve>, KernelRefusal> {
1899        let tooth: Vec<NurbsCurve> = section.curves.iter().filter(|c| c.tooth == 0).map(|c| c.curve.clone()).collect();
1900        let same: Vec<&'static str> = section.curves.iter().filter(|c| c.tooth == 0).map(|c| c.role).collect();
1901        if same != roles {
1902            return Err(refuse(
1903                "section_changes",
1904                "The tooth's form changes across the face (undercut or a pointed tip appears partway): lower the cone angle or narrow the face.".into(),
1905            ));
1906        }
1907        Ok(tooth)
1908    };
1909    let evaluate = |curve: &NurbsCurve, t: f64| -> [f64; 2] {
1910        let [a, b] = curve.domain().unwrap_or([0.0, 1.0]);
1911        let p = curve.evaluate_extended(a + (b - a) * t).unwrap_or(Vec3::new(f64::NAN, f64::NAN, 0.0));
1912        [p.x, p.y]
1913    };
1914    let tolerance = GEAR_FIT_TOLERANCE * m;
1915    let skin_tolerance = 1e-5 * m;
1916    let probes: Vec<Vec<NurbsCurve>> = [0.0, 0.5 * width, width].iter().map(|&z| at(z).and_then(|s| pieces(&s))).collect::<Result<_, _>>()?;
1917    let mut breaks: Vec<Vec<f64>> = Vec::with_capacity(count);
1918    for role in 0..count {
1919        let mut all: Vec<f64> = Vec::new();
1920        for probe in &probes {
1921            all.extend(adaptive_breaks(&|t| evaluate(&probe[role], t), tolerance)?);
1922        }
1923        all.sort_by(f64::total_cmp);
1924        all.dedup_by(|x, y| (*x - *y).abs() < 1e-12);
1925        breaks.push(all);
1926    }
1927    // Tooth 0's curves in the plane at height z, refitted on the shared breaks (so every plane's control points pair up).
1928    let refit = |z: f64| -> Result<(Vec<NurbsCurve>, f64), KernelRefusal> {
1929        let tooth = pieces(&at(z)?)?;
1930        let mut curves = Vec::with_capacity(count);
1931        let mut worst = 0.0_f64;
1932        for (role, role_breaks) in breaks.iter().enumerate() {
1933            let (mut curve, error) = fit_on_breaks(&|t| evaluate(&tooth[role], t), role_breaks)?;
1934            worst = worst.max(error);
1935            for p in &mut curve.control_points {
1936                p.z = z * p.w;
1937            }
1938            curves.push(curve);
1939        }
1940        Ok((curves, worst))
1941    };
1942    let teeth = base.teeth;
1943    let tau = TAU / teeth as f64;
1944    let mut planes = 4usize;
1945    loop {
1946        let step = width / planes as f64;
1947        let delta = 1e-3 * step.min(m);
1948        let mut rows: Vec<Vec<NurbsCurve>> = Vec::with_capacity(planes + 1);
1949        let mut slopes: Vec<Vec<Vec<[f64; 2]>>> = Vec::with_capacity(planes + 1);
1950        for j in 0..=planes {
1951            let z = step * j as f64;
1952            let (tooth, worst) = refit(z)?;
1953            if worst > 2.0 * tolerance {
1954                return Err(refuse("gear_fit", format!("The beveloid's sections could not be fitted on shared breaks ({worst:.2e}).")));
1955            }
1956            let lo = refit(z - delta)?.0;
1957            let hi = refit(z + delta)?.0;
1958            let slope: Vec<Vec<[f64; 2]>> = lo
1959                .iter()
1960                .zip(&hi)
1961                .map(|(l, h)| l.control_points.iter().zip(&h.control_points).map(|(p, q)| [(q.x - p.x) / (2.0 * delta), (q.y - p.y) / (2.0 * delta)]).collect())
1962                .collect();
1963            rows.push(tooth);
1964            slopes.push(slope);
1965        }
1966        let mut worst = 0.0_f64;
1967        for j in 0..planes {
1968            let exact = refit(step * (j as f64 + 0.5))?.0;
1969            for role in 0..count {
1970                for (k, p) in exact[role].control_points.iter().enumerate() {
1971                    let (p0, p1) = (rows[j][role].control_points[k], rows[j + 1][role].control_points[k]);
1972                    let (d0, d1) = (slopes[j][role][k], slopes[j + 1][role][k]);
1973                    let x = 0.5 * (p0.x + p1.x) + step * (d0[0] - d1[0]) / 8.0;
1974                    let y = 0.5 * (p0.y + p1.y) + step * (d0[1] - d1[1]) / 8.0;
1975                    worst = worst.max((x - p.x).hypot(y - p.y));
1976                }
1977            }
1978        }
1979        if worst > skin_tolerance {
1980            if planes >= 256 {
1981                return Err(refuse("gear_fit", format!("The beveloid's flanks could not be skinned within {skin_tolerance:.2e} ({worst:.2e}).")));
1982            }
1983            let factor = (1.15 * (worst / skin_tolerance).powf(0.25)).max(2.0);
1984            planes = (planes as f64 * factor).ceil().min(256.0) as usize;
1985            continue;
1986        }
1987        // The full section from tooth 0's curves at z = 0, junctions shared; every tooth's rows tooth 0's turned.
1988        let mut section_curves: Vec<SectionCurve> = Vec::with_capacity(count * teeth);
1989        for index in 0..teeth {
1990            for (role, curve) in rows[0].iter().enumerate() {
1991                section_curves.push(SectionCurve { curve: rotated(curve, tau * index as f64), role: roles[role], tooth: index });
1992            }
1993        }
1994        snap_junctions(&mut section_curves);
1995        let mut table: std::collections::HashMap<[u64; 4], Vec<Vec4>> = std::collections::HashMap::new();
1996        let h = 1.0 / planes as f64;
1997        for (index, piece) in section_curves.iter().enumerate() {
1998            let (role, tooth) = (index % count, index / count);
1999            let (s, cs) = (tau * tooth as f64).sin_cos();
2000            for (k, p) in piece.curve.control_points.iter().enumerate() {
2001                let mut row = Vec::with_capacity(2 * planes + 2);
2002                for j in 0..=planes {
2003                    let q = if j == 0 { *p } else { let r = rows[j][role].control_points[k]; Vec4 { x: cs * r.x - s * r.y, y: s * r.x + cs * r.y, z: r.z, w: r.w } };
2004                    let d = slopes[j][role][k];
2005                    let dv = [width * (cs * d[0] - s * d[1]), width * (s * d[0] + cs * d[1]), width];
2006                    let point = Vec3::new(q.x, q.y, q.z);
2007                    if j > 0 {
2008                        row.push(Vec4::from_point(Vec3::new(point.x - dv[0] * h / 3.0, point.y - dv[1] * h / 3.0, point.z - dv[2] * h / 3.0), 1.0));
2009                    }
2010                    if j == 0 || j == planes {
2011                        row.push(Vec4::from_point(point, 1.0));
2012                    }
2013                    if j < planes {
2014                        row.push(Vec4::from_point(Vec3::new(point.x + dv[0] * h / 3.0, point.y + dv[1] * h / 3.0, point.z + dv[2] * h / 3.0), 1.0));
2015                    }
2016                }
2017                table.insert([p.x.to_bits(), p.y.to_bits(), p.z.to_bits(), p.w.to_bits()], row);
2018            }
2019        }
2020        let mut knots_v = vec![0.0; 4];
2021        for j in 1..planes {
2022            let v = j as f64 * h;
2023            knots_v.extend([v, v]);
2024        }
2025        knots_v.extend([1.0; 4]);
2026        let section = GearSection { curves: section_curves, data: GearData::default() };
2027        let solid = prism_by_rows(&section, 3, &knots_v, &|p: Vec4| {
2028            table.get(&[p.x.to_bits(), p.y.to_bits(), p.z.to_bits(), p.w.to_bits()]).cloned().expect("a row for every section control point")
2029        })?;
2030        let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
2031        names.push("F".into());
2032        names.push("B".into());
2033        return Ok((solid, names, first.data));
2034    }
2035}
2036
2037/// A star (pin) wheel: the wheel that drives a lantern pinion, as in clocks and mills. Its teeth are cut
2038/// for the pinion's round pins: above the pitch circle each flank is the curve parallel, at the pin radius, to
2039/// the epicycloid the pin's centre traces relative to the wheel (the pinion's pitch circle rolling on the
2040/// wheel's), so the pins roll on the flanks; below it the tooth space has straight walls the pin's width apart
2041/// and a round root clear of the pins. Module m: wheel pitch radius m × teeth / 2, the pinion's m × pins / 2.
2042/// Tooth space 0 is centred on +x.
2043#[derive(Clone, Debug)]
2044pub struct StarWheel {
2045    pub module: f64,
2046    pub teeth: usize,
2047    /// Pins of the mating lantern pinion.
2048    pub pinion_pins: usize,
2049    pub pin_diameter: f64,
2050    /// Tip height above the pitch circle × module; 0 takes 92% of the height where the flanks meet.
2051    pub addendum: f64,
2052    /// Root clearance below the pins, × module.
2053    pub clearance: f64,
2054    pub backlash: f64,
2055    pub face_width: f64,
2056}
2057
2058/// The star wheel's section (counter-clockwise; per tooth `V` the +θ space wall, `R` its flank, `K` the tip,
2059/// `L`/`W` the next space's flank and wall, `G` that space's root).
2060pub fn star_wheel_section(wheel: &StarWheel) -> Result<GearSection, KernelRefusal> {
2061    let m = wheel.module;
2062    if !(m > 0.0 && wheel.pin_diameter > 0.0 && wheel.face_width > 0.0 && wheel.addendum >= 0.0 && wheel.clearance >= 0.0 && wheel.backlash >= 0.0) {
2063        return Err(refuse("gear_input", "The module, pin diameter and face width must be positive; the addendum, clearance and backlash not negative.".into()));
2064    }
2065    if !(6..=1000).contains(&wheel.teeth) || !(3..=200).contains(&wheel.pinion_pins) {
2066        return Err(refuse("gear_input", format!("A star wheel needs 6 to 1000 teeth and a pinion of 3 to 200 pins (it has {} and {}).", wheel.teeth, wheel.pinion_pins)));
2067    }
2068    let r2 = m * wheel.teeth as f64 / 2.0;
2069    let r1 = m * wheel.pinion_pins as f64 / 2.0;
2070    let rho = wheel.pin_diameter / 2.0;
2071    let half = rho + wheel.backlash / 2.0; // the space's half width
2072    let tau = TAU / wheel.teeth as f64;
2073    if !(2.0 * half < PI * m * 0.9) {
2074        return Err(refuse("pins_too_thick", format!("The pins ({}) fill the pitch ({:.4}): a star wheel needs pins under 0.9 of the pitch.", wheel.pin_diameter, PI * m)));
2075    }
2076    // The pin centre's path in the wheel's frame: the epicycloid with its cusp at (r2, 0), and its normal.
2077    let k = (r1 + r2) / r1;
2078    let path = |a: f64| {
2079        let t = PI + a * k;
2080        [(r2 + r1) * a.cos() + r1 * t.cos(), (r2 + r1) * a.sin() + r1 * t.sin()]
2081    };
2082    let path_tangent = |a: f64| {
2083        let t = PI + a * k;
2084        let d = [-(r2 + r1) * a.sin() - r1 * k * t.sin(), (r2 + r1) * a.cos() + r1 * k * t.cos()];
2085        let l = d[0].hypot(d[1]);
2086        [d[0] / l, d[1] / l]
2087    };
2088    // The flank: the path offset by the space's half width to the tooth's side (left of the outgoing branch).
2089    let flank = |a: f64| {
2090        let (p, t) = (path(a), path_tangent(a));
2091        [p[0] - half * t[1], p[1] + half * t[0]]
2092    };
2093    // Near the cusp the offset curve first runs back below the pitch circle (a swallowtail: the pin's centre
2094    // leaves the cusp sideways before it rises), so the space's boundary there is the offset curve only from its
2095    // own cusp (where its x stops falling) out; below that point the wall is straight at that point's height.
2096    let slope_x = |a: f64| {
2097        let h = 1e-7 * a.max(1e-9);
2098        flank(a + h)[0] - flank(a - h)[0]
2099    };
2100    let mut hi = 1e-6;
2101    while slope_x(hi) < 0.0 {
2102        hi *= 1.5;
2103        if hi > 1.0 {
2104            return Err(refuse("gear_fit", "The star wheel's flank never turns outward.".into()));
2105        }
2106    }
2107    let (mut lo, mut top) = (hi / 1.5, hi);
2108    for _ in 0..200 {
2109        let mid = 0.5 * (lo + top);
2110        if !(mid > lo && mid < top) {
2111            break;
2112        }
2113        if slope_x(mid) < 0.0 { lo = mid } else { top = mid }
2114    }
2115    let cusp = 0.5 * (lo + top);
2116    // Below that the swept pins (the cusp's disc and the swallowtail inside it) stay under the line at the half
2117    // width, so the space's wall is straight at the half width up to where the outer branch rises to it.
2118    let outside = |a: f64| flank(a)[1] - half;
2119    let mut hi = cusp * 1.5;
2120    while outside(hi) < 0.0 {
2121        hi *= 1.5;
2122        if hi > PI {
2123            return Err(refuse("gear_fit", "The star wheel's flank never rises past the pin's width.".into()));
2124        }
2125    }
2126    let (mut lo, mut top) = (cusp, hi);
2127    for _ in 0..200 {
2128        let mid = 0.5 * (lo + top);
2129        if !(mid > lo && mid < top) {
2130            break;
2131        }
2132        if outside(mid) < 0.0 { lo = mid } else { top = mid }
2133    }
2134    let start = 0.5 * (lo + top);
2135    // Where the flank reaches the tooth's middle (the flanks of neighbouring spaces meet): the pointed tip.
2136    let reach = |a: f64| polar_angle(flank(a)) - tau / 2.0;
2137    let mut hi = 1e-3;
2138    while reach(hi) < 0.0 {
2139        hi *= 1.5;
2140        if hi > PI {
2141            return Err(refuse("gear_fit", "The star wheel's flanks never meet.".into()));
2142        }
2143    }
2144    let (mut lo, mut top) = (start, hi);
2145    for _ in 0..200 {
2146        let mid = 0.5 * (lo + top);
2147        if !(mid > lo && mid < top) {
2148            break;
2149        }
2150        if reach(mid) < 0.0 { lo = mid } else { top = mid }
2151    }
2152    let pointed = radius_of(flank(0.5 * (lo + top)));
2153    let base = radius_of(flank(start));
2154    let tip_r = if wheel.addendum > 0.0 { r2 + wheel.addendum * m } else { base + 0.92 * (pointed - base) };
2155    if !(tip_r < pointed - 1e-6 * m) {
2156        return Err(refuse("pointed_tip", format!("The teeth come to a point at radius {pointed:.4}, below the tip ({tip_r:.4}): lower the addendum.")));
2157    }
2158    if !(tip_r > base) {
2159        return Err(refuse("gear_input", "The tip must lie above the pitch circle.".into()));
2160    }
2161    // The flank's parameter at the tip circle.
2162    let (mut lo, mut top) = (start, 0.5 * (lo + top));
2163    for _ in 0..200 {
2164        let mid = 0.5 * (lo + top);
2165        if !(mid > lo && mid < top) {
2166            break;
2167        }
2168        if radius_of(flank(mid)) < tip_r { lo = mid } else { top = mid }
2169    }
2170    let end = 0.5 * (lo + top);
2171    let root_r = r2 - half - wheel.clearance * m;
2172    if !(root_r > half * 1.01) {
2173        return Err(refuse("root_below_centre", "The root circle falls inside the space's width: more teeth or thinner pins.".into()));
2174    }
2175    let wall_foot = [(root_r * root_r - half * half).sqrt(), half];
2176    let wall_top = flank(start);
2177    let tolerance = GEAR_FIT_TOLERANCE * m;
2178    let right_flank = fit_planar(&flank, start, end, tolerance)?;
2179    let tip_from = polar_angle(flank(end));
2180    let mirror_into_next = |curve: &NurbsCurve| -> Result<NurbsCurve, KernelRefusal> {
2181        // Space 1's -θ side: space 0's +θ side mirrored about the x axis, turned by tau, run backwards.
2182        rotated(&mirrored(curve), tau).reversed().map_err(|e| refuse("gear_fit", e))
2183    };
2184    let wall = line(wall_foot, wall_top)?;
2185    let beta = (half / root_r).asin();
2186    let tooth: Vec<(&'static str, NurbsCurve)> = vec![
2187        ("V", wall.clone()),
2188        ("R", right_flank.clone()),
2189        ("K", arc(tip_r, tip_from, tau - tip_from)?),
2190        ("L", mirror_into_next(&right_flank)?),
2191        ("W", mirror_into_next(&wall)?),
2192        ("G", arc(root_r, tau - beta, tau + beta)?),
2193    ];
2194    let mut curves = Vec::with_capacity(6 * wheel.teeth);
2195    for index in 0..wheel.teeth {
2196        for (role, curve) in &tooth {
2197            curves.push(SectionCurve { curve: rotated(curve, tau * index as f64), role, tooth: index });
2198        }
2199    }
2200    snap_junctions(&mut curves);
2201    let data = GearData {
2202        pitch_diameter: 2.0 * r2,
2203        tip_diameter: 2.0 * tip_r,
2204        root_diameter: 2.0 * root_r,
2205        ..GearData::default()
2206    };
2207    Ok(GearSection { curves, data })
2208}
2209
2210/// A star wheel solid (the section extruded by the face width) with its face names and data.
2211pub fn star_wheel_solid(wheel: &StarWheel) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
2212    let section = star_wheel_section(wheel)?;
2213    let solid = extrude_section(&section, wheel.face_width)?;
2214    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
2215    names.push("F".into());
2216    names.push("B".into());
2217    Ok((solid, names, section.data))
2218}
2219
2220/// A lantern pinion: two discs joined by `pins` round pins on a circle, as a clock's or a mill's pinion,
2221/// driven by a star wheel's cycloidal teeth. Exact: pins and disc rims are cylinders, the disc faces planes.
2222/// The first disc spans z = -thickness..0, the pins z = 0..length, the second disc length..length + thickness;
2223/// pin 0 is centred on +x.
2224#[derive(Clone, Debug)]
2225pub struct LanternPinion {
2226    pub pins: usize,
2227    pub pin_circle_diameter: f64,
2228    pub pin_diameter: f64,
2229    pub disc_diameter: f64,
2230    pub disc_thickness: f64,
2231    /// The pins' length between the discs.
2232    pub length: f64,
2233}
2234
2235/// A lantern pinion solid and its data. Faces are named `P<k>` (pin walls), `FL1_OD`, `FL1_F` (the first
2236/// disc's outer face), `FL1_B` (its inner face round the pins), `FL2_F` (the second disc's inner face),
2237/// `FL2_OD` and `FL2_B`.
2238pub fn lantern_solid(lantern: &LanternPinion) -> Result<(BrepSolid, GearData), KernelRefusal> {
2239    use crate::sweep_topology::{curve_to_plane_parameters, make_plane, parameter_line};
2240    let n = lantern.pins;
2241    let (r, d, t, length) = (lantern.pin_circle_diameter / 2.0, lantern.pin_diameter, lantern.disc_thickness, lantern.length);
2242    let radius = lantern.disc_diameter / 2.0;
2243    if !(3..=200).contains(&n) {
2244        return Err(refuse("gear_input", format!("A lantern pinion needs from 3 to 200 pins (it has {n}).")));
2245    }
2246    if !(r > 0.0 && d > 0.0 && t > 0.0 && length > 0.0 && [r, d, t, length, radius].iter().all(|v| v.is_finite())) {
2247        return Err(refuse("gear_input", "The pin circle, pin diameter, disc thickness and length must be positive.".into()));
2248    }
2249    if !(2.0 * r * (PI / n as f64).sin() > d * (1.0 + 1e-9)) {
2250        return Err(refuse("pins_overlap", format!("The {n} pins of diameter {d} overlap on a pin circle of diameter {}: enlarge the circle or thin the pins.", 2.0 * r)));
2251    }
2252    if !(radius > r + d / 2.0) {
2253        return Err(refuse("disc_too_small", format!("The discs (diameter {}) must reach past the pins (to {:.4}).", 2.0 * radius, 2.0 * r + d)));
2254    }
2255    let line = |a: [f64; 2], b: [f64; 2]| parameter_line(a[0], a[1], b[0], b[1]).map_err(|e| refuse("gear_pcurve", e));
2256    let x_axis = Vec3::new(1.0, 0.0, 0.0);
2257    let y_axis = Vec3::new(0.0, 1.0, 0.0);
2258    let circle = |cx: f64, cy: f64, z: f64, rad: f64| crate::make_arc(Vec3::new(cx, cy, z), x_axis, y_axis, rad, 0.0, TAU).map_err(|e| refuse("gear_arc", e));
2259    let mut shell = ShellBuilder { vertices: Vec::new(), edges: Vec::new(), faces: Vec::new(), next: 0 };
2260    // A cylinder from z = `low` up by `height` round (cx, cy): its circles, its seam and its face; returns the circles.
2261    let cylinder = |shell: &mut ShellBuilder, cx: f64, cy: f64, rad: f64, low: f64, height: f64, name: String| -> Result<(u64, u64), KernelRefusal> {
2262        let base = circle(cx, cy, low, rad)?;
2263        let (a, b) = (shell.vertex(Vec3::new(cx + rad, cy, low)), shell.vertex(Vec3::new(cx + rad, cy, low + height)));
2264        let lower = shell.edge(base.clone(), a, a)?;
2265        let upper = shell.edge(translated(&base, height), b, b)?;
2266        let seam = shell.edge(crate::make_line(Vec3::new(cx + rad, cy, low), Vec3::new(cx + rad, cy, low + height)).map_err(|e| refuse("gear_edge", e))?, a, b)?;
2267        let side = crate::make_extrusion(&base, Vec3::new(0.0, 0.0, height)).map_err(|e| refuse("gear_surface", e))?;
2268        let [c0, c1] = base.domain().map_err(|e| refuse("gear_domain", e))?;
2269        let loops = vec![vec![
2270            (lower, true, line([c0, 0.0], [c1, 0.0])?),
2271            (seam, true, line([c1, 0.0], [c1, 1.0])?),
2272            (upper, false, line([c0, 1.0], [c1, 1.0])?),
2273            (seam, false, line([c0, 0.0], [c0, 1.0])?),
2274        ]];
2275        shell.face(side, true, loops, name)?;
2276        Ok((lower, upper))
2277    };
2278    let mut pin_bottoms = Vec::with_capacity(n);
2279    let mut pin_tops = Vec::with_capacity(n);
2280    for k in 0..n {
2281        let (s, c) = (TAU * k as f64 / n as f64).sin_cos();
2282        let (lower, upper) = cylinder(&mut shell, r * c, r * s, d / 2.0, 0.0, length, format!("P{k}"))?;
2283        pin_bottoms.push(lower);
2284        pin_tops.push(upper);
2285    }
2286    let (outer1, inner1) = cylinder(&mut shell, 0.0, 0.0, radius, -t, t, "FL1_OD".into())?;
2287    let (inner2, outer2) = cylinder(&mut shell, 0.0, 0.0, radius, length, t, "FL2_OD".into())?;
2288    let pad = radius * 1.1 + 1.0;
2289    let plane_at = |z: f64| make_plane(Vec3::new(-pad, -pad, z), x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e));
2290    let on_plane = |curve: &NurbsCurve, z: f64| curve_to_plane_parameters(curve, Vec3::new(-pad, -pad, z), x_axis, y_axis).map_err(|e| refuse("gear_pcurve", e));
2291    // The discs' outer faces, then their inner faces round the pins.
2292    let face = vec![vec![(outer1, true, on_plane(shell.curve(outer1), -t)?)]];
2293    shell.face(plane_at(-t)?, false, face, "FL1_F".into())?;
2294    let face = vec![vec![(outer2, true, on_plane(shell.curve(outer2), length + t)?)]];
2295    shell.face(plane_at(length + t)?, true, face, "FL2_B".into())?;
2296    for (z, rim, pins, same_sense, name) in [(0.0, inner1, &pin_bottoms, true, "FL1_B"), (length, inner2, &pin_tops, false, "FL2_F")] {
2297        let mut loops = vec![vec![(rim, true, on_plane(shell.curve(rim), z)?)]];
2298        for &pin in pins.iter() {
2299            loops.push(vec![(pin, true, on_plane(shell.curve(pin), z)?)]);
2300        }
2301        shell.face(plane_at(z)?, same_sense, loops, name.into())?;
2302    }
2303    let id = shell.id();
2304    let shell_id = shell.id();
2305    let solid = BrepSolid {
2306        mass_properties_cache: Default::default(),
2307        cells: Default::default(),
2308        id,
2309        vertices: shell.vertices,
2310        edges: shell.edges,
2311        shells: vec![crate::sweep_topology::ShellRecord { id: shell_id, faces: shell.faces }],
2312        genus: (n - 1) as _,
2313        kind: crate::BodyKind::Solid,
2314    };
2315    let issues = solid.validate();
2316    if !issues.is_empty() {
2317        return Err(KernelRefusal::internal(KernelStage::Validate, "validate", format!("lantern pinion is not valid: {issues:?}")));
2318    }
2319    let data = GearData { pitch_diameter: 2.0 * r, tip_diameter: 2.0 * r + d, root_diameter: 2.0 * r - d, ..GearData::default() };
2320    Ok((solid, data))
2321}
2322
2323/// A pulley solid: the section extruded along +z by the width; names as the
2324/// section's roles, then `F` and `B`.
2325/// The counter-clockwise section (z = 0) extruded to z = `width` with a flange disc of `radius` and
2326/// `thickness` under it (and, with `both`, another over it), built directly rather than as a union. Faces
2327/// are named: the section's walls by role, the flanges `FL1_OD`/`FL1_F` (its outer face)/`FL1_B` (the
2328/// annulus round the section) and `FL2_F` (the annulus)/`FL2_OD`/`FL2_B`, and without a second flange the
2329/// section's own end `B`.
2330pub fn flanged_prism(section: &GearSection, width: f64, radius: f64, thickness: f64, both: bool) -> Result<BrepSolid, KernelRefusal> {
2331    use crate::sweep_topology::{curve_to_plane_parameters, make_plane, parameter_line};
2332    let line = |a: [f64; 2], b: [f64; 2]| parameter_line(a[0], a[1], b[0], b[1]).map_err(|e| refuse("gear_pcurve", e));
2333    let point_of = |p: Vec4| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w);
2334    if !(width > 0.0 && thickness > 0.0 && radius.is_finite() && radius > section_reach(section)? * (1.0 + 1e-9)) {
2335        return Err(refuse(
2336            "gear_input",
2337            format!("The flange radius ({radius}) must clear the section, and the width ({width}) and flange thickness ({thickness}) be positive."),
2338        ));
2339    }
2340    let up = Vec3::new(0.0, 0.0, width);
2341    let count = section.curves.len();
2342    let mut shell = ShellBuilder { vertices: Vec::new(), edges: Vec::new(), faces: Vec::new(), next: 0 };
2343    let mut bottom_v = Vec::with_capacity(count);
2344    let mut top_v = Vec::with_capacity(count);
2345    let mut axial = Vec::with_capacity(count);
2346    for piece in &section.curves {
2347        let p = point_of(piece.curve.control_points[0]);
2348        let (b, t) = (shell.vertex(p), shell.vertex(p.add(up)));
2349        axial.push(shell.edge(crate::make_line(p, p.add(up)).map_err(|e| refuse("gear_edge", e))?, b, t)?);
2350        bottom_v.push(b);
2351        top_v.push(t);
2352    }
2353    let mut bottom_e = Vec::with_capacity(count);
2354    let mut top_e = Vec::with_capacity(count);
2355    for (index, piece) in section.curves.iter().enumerate() {
2356        let next = (index + 1) % count;
2357        bottom_e.push(shell.edge(piece.curve.clone(), bottom_v[index], bottom_v[next])?);
2358        top_e.push(shell.edge(translated(&piece.curve, width), top_v[index], top_v[next])?);
2359    }
2360    for (index, piece) in section.curves.iter().enumerate() {
2361        let next = (index + 1) % count;
2362        let [u0, u1] = piece.curve.domain().map_err(|e| refuse("gear_domain", e))?;
2363        let surface = crate::make_extrusion(&piece.curve, up).map_err(|e| refuse("gear_surface", e))?;
2364        let loops = vec![vec![
2365            (bottom_e[index], true, line([u0, 0.0], [u1, 0.0])?),
2366            (axial[next], true, line([u1, 0.0], [u1, 1.0])?),
2367            (top_e[index], false, line([u0, 1.0], [u1, 1.0])?),
2368            (axial[index], false, line([u0, 0.0], [u0, 1.0])?),
2369        ]];
2370        shell.face(surface, true, loops, piece.suffix())?;
2371    }
2372    let pad = radius * 1.1 + 1.0;
2373    let x_axis = Vec3::new(1.0, 0.0, 0.0);
2374    let y_axis = Vec3::new(0.0, 1.0, 0.0);
2375    let plane_at = |z: f64| make_plane(Vec3::new(-pad, -pad, z), x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e));
2376    let on_plane = |curve: &NurbsCurve, z: f64| curve_to_plane_parameters(curve, Vec3::new(-pad, -pad, z), x_axis, y_axis).map_err(|e| refuse("gear_pcurve", e));
2377    // A flange from z = `low` to `low` + thickness: its circles, seam and outside cylinder; returns the circles.
2378    let flange = |shell: &mut ShellBuilder, low: f64, name: &str| -> Result<(u64, u64), KernelRefusal> {
2379        let circle = crate::make_arc(Vec3::new(0.0, 0.0, low), x_axis, y_axis, radius, 0.0, TAU).map_err(|e| refuse("gear_arc", e))?;
2380        let lifted = translated(&circle, thickness);
2381        let (a, b) = (shell.vertex(Vec3::new(radius, 0.0, low)), shell.vertex(Vec3::new(radius, 0.0, low + thickness)));
2382        let lower = shell.edge(circle.clone(), a, a)?;
2383        let upper = shell.edge(lifted, b, b)?;
2384        let seam = shell.edge(crate::make_line(Vec3::new(radius, 0.0, low), Vec3::new(radius, 0.0, low + thickness)).map_err(|e| refuse("gear_edge", e))?, a, b)?;
2385        let side = crate::make_extrusion(&circle, Vec3::new(0.0, 0.0, thickness)).map_err(|e| refuse("gear_surface", e))?;
2386        let [c0, c1] = circle.domain().map_err(|e| refuse("gear_domain", e))?;
2387        let loops = vec![vec![
2388            (lower, true, line([c0, 0.0], [c1, 0.0])?),
2389            (seam, true, line([c1, 0.0], [c1, 1.0])?),
2390            (upper, false, line([c0, 1.0], [c1, 1.0])?),
2391            (seam, false, line([c0, 0.0], [c0, 1.0])?),
2392        ]];
2393        shell.face(side, true, loops, format!("{name}OD"))?;
2394        Ok((lower, upper))
2395    };
2396    // Flange 1 under the section: its outer face at z = -thickness, the annulus at z = 0 round the section.
2397    let (outer1, inner1) = flange(&mut shell, -thickness, "FL1_")?;
2398    let face = vec![(outer1, true, on_plane(shell.curve(outer1), -thickness)?)];
2399    shell.face(plane_at(-thickness)?, false, vec![face], "FL1_F".into())?;
2400    let mut annulus = vec![vec![(inner1, true, on_plane(shell.curve(inner1), 0.0)?)], Vec::with_capacity(count)];
2401    for &edge in &bottom_e {
2402        annulus[1].push((edge, true, on_plane(shell.curve(edge), 0.0)?));
2403    }
2404    shell.face(plane_at(0.0)?, true, annulus, "FL1_B".into())?;
2405    if both {
2406        let (inner2, outer2) = flange(&mut shell, width, "FL2_")?;
2407        let mut annulus = vec![vec![(inner2, true, on_plane(shell.curve(inner2), width)?)], Vec::with_capacity(count)];
2408        for &edge in &top_e {
2409            annulus[1].push((edge, true, on_plane(shell.curve(edge), width)?));
2410        }
2411        shell.face(plane_at(width)?, false, annulus, "FL2_F".into())?;
2412        let face = vec![(outer2, true, on_plane(shell.curve(outer2), width + thickness)?)];
2413        shell.face(plane_at(width + thickness)?, true, vec![face], "FL2_B".into())?;
2414    } else {
2415        let mut end = Vec::with_capacity(count);
2416        for &edge in &top_e {
2417            end.push((edge, true, on_plane(shell.curve(edge), width)?));
2418        }
2419        shell.face(plane_at(width)?, true, vec![end], "B".into())?;
2420    }
2421    let id = shell.id();
2422    let shell_id = shell.id();
2423    let solid = BrepSolid {
2424        mass_properties_cache: Default::default(),
2425        cells: Default::default(),
2426        id,
2427        vertices: shell.vertices,
2428        edges: shell.edges,
2429        shells: vec![crate::sweep_topology::ShellRecord { id: shell_id, faces: shell.faces }],
2430        genus: 0,
2431        kind: crate::BodyKind::Solid,
2432    };
2433    let issues = solid.validate();
2434    if !issues.is_empty() {
2435        return Err(KernelRefusal::internal(KernelStage::Validate, "validate", format!("flanged prism is not valid: {issues:?}")));
2436    }
2437    Ok(solid)
2438}
2439
2440pub fn timing_pulley_solid(pulley: &TimingPulley) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
2441    let section = timing_pulley_section(pulley)?;
2442    let solid = extrude_section(&section, pulley.width)?;
2443    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
2444    names.push("F".into());
2445    names.push("B".into());
2446    Ok((solid, names, section.data))
2447}
2448
2449/// A ratchet wheel: `teeth` teeth on `outside` diameter, `depth` deep. A saw
2450/// tooth has a locking face (leaning `lean` back from radial, so a pawl is drawn
2451/// in under load) and a straight back; a symmetric tooth leans both faces
2452/// equally (for a reversible pawl). Teeth lock against counter-clockwise turning
2453/// when `clockwise_locks` is false.
2454#[derive(Clone, Debug)]
2455pub struct Ratchet {
2456    pub teeth: usize,
2457    pub outside: f64,
2458    pub depth: f64,
2459    pub lean: f64,
2460    pub symmetric: bool,
2461    pub clockwise_locks: bool,
2462    pub width: f64,
2463}
2464
2465/// The ratchet section, counter-clockwise; straight lines only. Roles per
2466/// tooth k (tip k on angle 2 pi k / z): `LK<k>` the locking face below its
2467/// tip, `BK<k>` the back running up to it.
2468pub fn ratchet_section(ratchet: &Ratchet) -> Result<GearSection, KernelRefusal> {
2469    let Ratchet { teeth, outside, depth, lean, symmetric, clockwise_locks, width } = ratchet.clone();
2470    if !(outside > 0.0 && depth > 0.0 && depth < outside / 2.0 && width > 0.0) {
2471        return Err(refuse("gear_input", format!("A ratchet needs a positive outside diameter ({outside}), a depth ({depth}) under its radius and a positive width.")));
2472    }
2473    if teeth < 3 || teeth > 360 {
2474        return Err(refuse("gear_input", format!("A ratchet needs from 3 to 360 teeth (it has {teeth}).")));
2475    }
2476    if !(lean >= 0.0 && lean.to_degrees() <= 30.0) {
2477        return Err(refuse("gear_input", "The locking face lean must be between 0° and 30°.".into()));
2478    }
2479    let z = teeth as f64;
2480    let tau = TAU / z;
2481    let ra = outside / 2.0;
2482    let rf = ra - depth;
2483    // Tooth 0's tip on +x. The locking face runs from the tip down to the root
2484    // at a polar angle `foot` ahead of the tip (counter-clockwise), leaning back.
2485    // A radial face has foot = 0; leaning back by `lean` moves the root point
2486    // forward along the face's direction: solve |tip + t d| = rf.
2487    let tip = [ra, 0.0];
2488    let face_angle = PI + lean; // pointing inward, tilted to +y by `lean`
2489    let d = [face_angle.cos(), face_angle.sin()];
2490    let b = tip[0] * d[0] + tip[1] * d[1];
2491    let t = -b - (b * b - (ra * ra - rf * rf)).sqrt();
2492    let root = [tip[0] + t * d[0], tip[1] + t * d[1]];
2493    let foot = polar_angle(root);
2494    let (lock, back) = if symmetric {
2495        // Both faces meet at the root halfway between tips, each leaning equally.
2496        let mid = [rf * (tau / 2.0).cos(), rf * (tau / 2.0).sin()];
2497        let lock = line(tip, mid)?;
2498        let next = [ra * tau.cos(), ra * tau.sin()];
2499        (lock, line(mid, next)?)
2500    } else {
2501        if foot >= tau - 1e-9 {
2502            return Err(refuse("gear_input", "The locking faces overlap: fewer teeth, less depth or less lean.".into()));
2503        }
2504        let next = [ra * tau.cos(), ra * tau.sin()];
2505        (line(tip, root)?, line(root, next)?)
2506    };
2507    // Counter-clockwise traversal from tip k: locking face down, back up to tip k + 1.
2508    let mut curves = Vec::with_capacity(2 * teeth);
2509    for index in 0..teeth {
2510        let angle = tau * index as f64;
2511        curves.push(SectionCurve { curve: rotated(&lock, angle), role: "LK", tooth: index });
2512        curves.push(SectionCurve { curve: rotated(&back, angle), role: "BK", tooth: index });
2513    }
2514    if clockwise_locks {
2515        // The mirror image locks the other way; mirror, then restore the
2516        // counter-clockwise order.
2517        let mut mirrored_curves: Vec<SectionCurve> = curves
2518            .iter()
2519            .map(|piece| SectionCurve { curve: mirrored(&piece.curve).reversed().expect("a line reverses"), role: piece.role, tooth: piece.tooth })
2520            .collect();
2521        mirrored_curves.reverse();
2522        curves = mirrored_curves;
2523    }
2524    snap_junctions(&mut curves);
2525    Ok(GearSection { curves, data: GearData { tip_diameter: outside, root_diameter: 2.0 * rf, ..GearData::default() } })
2526}
2527
2528/// A ratchet solid: the section extruded along +z; names as the section's roles, then `F` and `B`.
2529pub fn ratchet_solid(ratchet: &Ratchet) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
2530    let section = ratchet_section(ratchet)?;
2531    let solid = extrude_section(&section, ratchet.width)?;
2532    let mut names: Vec<String> = section.curves.iter().map(|c| c.suffix()).collect();
2533    names.push("F".into());
2534    names.push("B".into());
2535    Ok((solid, names, section.data))
2536}
2537
2538/// An external Geneva wheel of `slots` slots for a driver at `centre_distance`
2539/// whose pin of `pin_diameter` runs on the crank radius a sin(pi / n); the
2540/// wheel's radius is a cos(pi / n) (the pin enters the slot tangentially). The
2541/// rim between slots is cut by the concave locking arc of radius
2542/// `lock_radius + clearance / 2` about the driver's centre.
2543#[derive(Clone, Debug)]
2544pub struct GenevaWheel {
2545    pub slots: usize,
2546    pub centre_distance: f64,
2547    pub pin_diameter: f64,
2548    pub clearance: f64,
2549    /// The driver's locking disc radius; 0 = crank radius − pin diameter.
2550    pub lock_radius: f64,
2551    pub width: f64,
2552}
2553
2554/// Derived Geneva sizes: (crank radius, wheel radius, slot inner centre radius, locking disc radius).
2555pub fn geneva_sizes(wheel: &GenevaWheel) -> (f64, f64, f64, f64) {
2556    let n = wheel.slots as f64;
2557    let a = wheel.centre_distance;
2558    let crank = a * (PI / n).sin();
2559    let radius = a * (PI / n).cos();
2560    let lock = if wheel.lock_radius > 0.0 { wheel.lock_radius } else { crank - wheel.pin_diameter };
2561    (crank, radius, a - crank, lock)
2562}
2563
2564/// The Geneva wheel section, counter-clockwise; lines and arcs. Slot k on
2565/// angle 2 pi k / n. Roles: `SL<k>`/`SU<k>` its sides, `SE<k>` its end arc,
2566/// `RA<k>`/`RB<k>` the rim arcs either side of the locking arc `LA<k>` that
2567/// follows slot k.
2568pub fn geneva_section(wheel: &GenevaWheel) -> Result<GearSection, KernelRefusal> {
2569    let GenevaWheel { slots, centre_distance: a, pin_diameter: dp, clearance: c, width, .. } = wheel.clone();
2570    if !(3..=12).contains(&slots) {
2571        return Err(refuse("gear_input", format!("A Geneva wheel has from 3 to 12 slots (it has {slots}).")));
2572    }
2573    if !(a > 0.0 && dp > 0.0 && c >= 0.0 && width > 0.0) {
2574        return Err(refuse("gear_input", "The centre distance, pin diameter and width must be positive (the clearance not negative).".into()));
2575    }
2576    let n = slots as f64;
2577    let (crank, rw, end_centre, lock) = geneva_sizes(wheel);
2578    let half = (dp + c) / 2.0; // half the slot width
2579    let rl = lock + c / 2.0;
2580    if !(lock > 0.0 && lock < a - rw + 1e-9 + rw) || !(half < end_centre) || !(half < rw * (PI / n).sin()) {
2581        return Err(refuse("gear_input", format!("The pin ({dp}) is too large for {slots} slots at centre distance {a}.")));
2582    }
2583    // Adjacent slots must not meet: their ends (and sides) stay apart only
2584    // while the end centres are more than a slot width apart.
2585    if end_centre * (PI / n).sin() <= half * (1.0 + 1e-9) {
2586        return Err(refuse(
2587            "gear_input",
2588            format!("Adjacent slots meet near the hub: {slots} slots {:.4} wide need a larger centre distance than {a}, or a smaller pin.", 2.0 * half),
2589        ));
2590    }
2591    let x_top = (rw * rw - half * half).sqrt();
2592    let p1 = [x_top, half];
2593    let beta = PI / n;
2594    let centre = [a * beta.cos(), a * beta.sin()];
2595    // Rim circle (O, rw) meets the locking circle (centre, rl).
2596    let along = (rw * rw - rl * rl + a * a) / (2.0 * a);
2597    let h2 = rw * rw - along * along;
2598    if h2 <= 0.0 {
2599        return Err(refuse("gear_input", "The locking arc does not reach the wheel's rim: increase the locking disc radius.".into()));
2600    }
2601    let h = h2.sqrt();
2602    let e = [beta.cos(), beta.sin()];
2603    let perp = [-beta.sin(), beta.cos()];
2604    let q1 = [along * e[0] - h * perp[0], along * e[1] - h * perp[1]];
2605    let q2 = [along * e[0] + h * perp[0], along * e[1] + h * perp[1]];
2606    let a1 = polar_angle(p1);
2607    if polar_angle(q1) <= a1 + 1e-9 {
2608        return Err(refuse("gear_input", "The locking arc cuts into the slots: reduce the locking disc radius or the pin.".into()));
2609    }
2610    let tau = TAU / n;
2611    let slot: Vec<(&'static str, NurbsCurve)> = vec![
2612        ("SL", line([x_top, -half], [end_centre, -half])?),
2613        ("SE", arc_through([end_centre, 0.0], [end_centre, -half], [end_centre, half], false)?),
2614        ("SU", line([end_centre, half], p1)?),
2615        ("RA", arc(rw, a1, polar_angle(q1))?),
2616        ("LA", arc_through(centre, q1, q2, false)?),
2617        ("RB", arc(rw, polar_angle(q2), tau - a1)?),
2618    ];
2619    let mut curves = Vec::with_capacity(6 * slots);
2620    for index in 0..slots {
2621        let angle = tau * index as f64;
2622        for (role, curve) in &slot {
2623            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
2624        }
2625    }
2626    snap_junctions(&mut curves);
2627    let _ = crank;
2628    Ok(GearSection { curves, data: GearData { tip_diameter: 2.0 * rw, ..GearData::default() } })
2629}
2630
2631/// A Geneva wheel solid: the section extruded along +z; names as the
2632/// section's roles, then `F` and `B`.
2633pub fn geneva_solid(wheel: &GenevaWheel) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
2634    let section = geneva_section(wheel)?;
2635    let solid = extrude_section(&section, wheel.width)?;
2636    let mut names: Vec<String> = section.curves.iter().map(|c| c.suffix()).collect();
2637    names.push("F".into());
2638    names.push("B".into());
2639    Ok((solid, names, section.data))
2640}
2641
2642/// A cylindrical worm with an Archimedean (ZA) thread: straight flanks in the
2643/// axial section at the axial pressure angle. Lengths in model units.
2644#[derive(Clone, Debug)]
2645pub struct Worm {
2646    pub axial_module: f64,
2647    pub starts: usize,
2648    /// Reference (pitch) diameter d1 = q × axial module.
2649    pub reference_diameter: f64,
2650    pub pressure_angle: f64,
2651    pub addendum: f64,
2652    pub dedendum: f64,
2653    pub length: f64,
2654    pub hand: Hand,
2655}
2656
2657impl Worm {
2658    /// The lead: starts × axial pitch.
2659    pub fn lead(&self) -> f64 {
2660        self.starts as f64 * PI * self.axial_module
2661    }
2662
2663    /// The axial thread thickness at a radius (ZA: straight axial flanks).
2664    pub fn axial_thickness(&self, radius: f64) -> f64 {
2665        PI * self.axial_module / 2.0 - 2.0 * (radius - self.reference_diameter / 2.0) * self.pressure_angle.tan()
2666    }
2667}
2668
2669/// The worm's transverse section (z = 0), counter-clockwise: per start j (its
2670/// thread centred on angle 2 pi j / n) `R<j>` the flank on its clockwise side,
2671/// `K<j>` the thread's tip, `L<j>` the other flank, `G<j>` the root after it.
2672/// The flanks are Archimedean spirals (fitted), tip and root exact arcs.
2673pub fn worm_section(worm: &Worm) -> Result<GearSection, KernelRefusal> {
2674    let m = worm.axial_module;
2675    if !(m > 0.0 && worm.reference_diameter > 0.0 && worm.length > 0.0 && worm.addendum > 0.0 && worm.dedendum > 0.0) {
2676        return Err(refuse("gear_input", "The worm's module, diameter, length, addendum and dedendum must be positive.".into()));
2677    }
2678    if worm.starts < 1 || worm.starts > 8 {
2679        return Err(refuse("gear_input", format!("A worm has from 1 to 8 starts (it has {}).", worm.starts)));
2680    }
2681    let degrees = worm.pressure_angle.to_degrees();
2682    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&degrees) {
2683        return Err(refuse("gear_input", format!("The axial pressure angle must be between 10° and 35° (it is {degrees}°).")));
2684    }
2685    let r1 = worm.reference_diameter / 2.0;
2686    let ra = r1 + worm.addendum * m;
2687    let rf = r1 - worm.dedendum * m;
2688    if !(rf > 0.0) {
2689        return Err(refuse("gear_input", format!("The worm's root diameter is not positive ({:.4}): raise the diameter quotient.", 2.0 * rf)));
2690    }
2691    let lead = worm.lead();
2692    let gamma = (lead / (PI * worm.reference_diameter)).atan();
2693    if gamma.to_degrees() > 45.0 {
2694        return Err(refuse("bad_lead", format!("The lead angle {:.3}° is over 45°: fewer starts or a larger diameter.", gamma.to_degrees())));
2695    }
2696    if worm.axial_thickness(ra) <= 1e-6 * m {
2697        return Err(refuse("pointed_tip", "The worm thread comes to a point below its tip: lower the addendum or the pressure angle.".into()));
2698    }
2699    let n = worm.starts as f64;
2700    let pitch = PI * m;
2701    if worm.axial_thickness(rf) >= pitch - 1e-6 * m {
2702        return Err(refuse("teeth_overlap", "The worm's threads meet at the root: lower the dedendum or the pressure angle.".into()));
2703    }
2704    // Half the angular width of a thread at radius r in the transverse plane.
2705    let half = |r: f64| PI * worm.axial_thickness(r) / lead;
2706    let flank = |r: f64| {
2707        let t = half(r);
2708        [r * t.cos(), r * t.sin()]
2709    };
2710    let tolerance = GEAR_FIT_TOLERANCE * m;
2711    let upper = fit_planar(&|r| flank(r), rf, ra, tolerance)?; // root -> tip on the +angle side
2712    let tau = TAU / n;
2713    let thread: Vec<(&'static str, NurbsCurve)> = vec![
2714        ("R", mirrored(&upper)),
2715        ("K", arc(ra, -half(ra), half(ra))?),
2716        ("L", upper.reversed().map_err(|e| refuse("gear_fit", e))?),
2717        ("G", arc(rf, half(rf), tau - half(rf))?),
2718    ];
2719    let mut curves = Vec::with_capacity(4 * worm.starts);
2720    for index in 0..worm.starts {
2721        let angle = tau * index as f64;
2722        for (role, curve) in &thread {
2723            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
2724        }
2725    }
2726    snap_junctions(&mut curves);
2727    let data = GearData { pitch_diameter: worm.reference_diameter, tip_diameter: 2.0 * ra, root_diameter: 2.0 * rf, ..GearData::default() };
2728    Ok(GearSection { curves, data })
2729}
2730
2731/// A worm solid: the transverse section screwed along +z by the length (one
2732/// lead per turn); names as the section's roles, then `F` and `B`.
2733pub fn worm_solid(worm: &Worm) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
2734    let section = worm_section(worm)?;
2735    let sign = if worm.hand == Hand::Right { 1.0 } else { -1.0 };
2736    let turn = sign * TAU * worm.length / worm.lead();
2737    let solid = twisted_prism(&section, worm.length, Twist::Helical { turn }, GEAR_FIT_TOLERANCE * worm.axial_module)?;
2738    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
2739    names.push("F".into());
2740    names.push("B".into());
2741    Ok((solid, names, section.data))
2742}
2743
2744/// A cycloidal-drive disc: `pins` housing pins of diameter `pin_diameter` on a
2745/// circle of `pin_circle_diameter`, the disc running at `eccentricity`; the disc
2746/// has pins − 1 lobes. Its profile is the equidistant (by the pin radius plus
2747/// half the clearance) of the epitrochoid the pin centres trace relative to it.
2748#[derive(Clone, Debug)]
2749pub struct CycloidalDisc {
2750    pub pins: usize,
2751    pub pin_circle_diameter: f64,
2752    pub pin_diameter: f64,
2753    pub eccentricity: f64,
2754    /// Running clearance (diametral): the profile stands clearance / 2 further off the pins.
2755    pub clearance: f64,
2756    pub width: f64,
2757}
2758
2759impl CycloidalDisc {
2760    /// The epitrochoid of the pin centres relative to the disc, and its derivative.
2761    fn trochoid(&self, t: f64) -> ([f64; 2], [f64; 2]) {
2762        let r = self.pin_circle_diameter / 2.0;
2763        let e = self.eccentricity;
2764        let n = self.pins as f64;
2765        (
2766            [r * t.cos() - e * (n * t).cos(), -r * t.sin() + e * (n * t).sin()],
2767            [-r * t.sin() + e * n * (n * t).sin(), -r * t.cos() + e * n * (n * t).cos()],
2768        )
2769    }
2770
2771    /// The disc profile point at parameter t: the trochoid moved by the offset
2772    /// along its normal towards the disc's centre.
2773    pub fn profile(&self, t: f64) -> [f64; 2] {
2774        let (q, d) = self.trochoid(t);
2775        let length = d[0].hypot(d[1]);
2776        let offset = self.pin_diameter / 2.0 + self.clearance / 2.0;
2777        // The trochoid runs clockwise (y = -r sin t ...); its right-hand normal points inward.
2778        let n = [d[1] / length, -d[0] / length];
2779        [q[0] + offset * n[0], q[1] + offset * n[1]]
2780    }
2781}
2782
2783/// The disc's section, counter-clockwise: one fitted piece per lobe, `LB<k>`.
2784pub fn cycloidal_disc_section(disc: &CycloidalDisc) -> Result<GearSection, KernelRefusal> {
2785    let CycloidalDisc { pins, pin_circle_diameter: dc, pin_diameter: dp, eccentricity: e, clearance, width } = disc.clone();
2786    if !(4..=200).contains(&pins) {
2787        return Err(refuse("gear_input", format!("A cycloidal drive has from 4 to 200 pins (it has {pins}).")));
2788    }
2789    if !(dc > 0.0 && dp > 0.0 && e > 0.0 && clearance >= 0.0 && width > 0.0) {
2790        return Err(refuse("gear_input", "The pin circle, pin diameter, eccentricity and width must be positive.".into()));
2791    }
2792    let n = pins as f64;
2793    let r = dc / 2.0;
2794    // The trochoid loops back on itself once e >= r / n.
2795    if e >= r / n * (1.0 - 1e-9) {
2796        return Err(refuse(
2797            "gear_input",
2798            format!("The eccentricity must be under the pin circle radius / pins = {:.4} (it is {e}).", r / n),
2799        ));
2800    }
2801    // The offset must stay under the trochoid's smallest radius of curvature (else the lobes cusp).
2802    let offset = dp / 2.0 + clearance / 2.0;
2803    // An inward offset can cusp only where the (clockwise) curve turns
2804    // clockwise, its centre of curvature inside. Radius of curvature there,
2805    // from the closed-form first and second derivatives.
2806    let (rr, ee) = (dc / 2.0, e);
2807    let radius = |t: f64| -> f64 {
2808        let d = [-rr * t.sin() + ee * n * (n * t).sin(), -rr * t.cos() + ee * n * (n * t).cos()];
2809        let dd = [-rr * t.cos() + ee * n * n * (n * t).cos(), rr * t.sin() - ee * n * n * (n * t).sin()];
2810        let cross = d[0] * dd[1] - d[1] * dd[0];
2811        let speed = d[0].hypot(d[1]);
2812        if cross < 0.0 { speed * speed * speed / -cross } else { f64::INFINITY }
2813    };
2814    // The curve repeats every 2 pi / (n - 1): sample one period densely, then
2815    // refine every local minimum by golden-section search.
2816    let period = TAU / (n - 1.0);
2817    let samples = 2000;
2818    let values: Vec<f64> = (0..=samples).map(|i| radius(period * i as f64 / samples as f64)).collect();
2819    let mut least = f64::INFINITY;
2820    for i in 0..=samples {
2821        let previous = values[if i == 0 { samples - 1 } else { i - 1 }];
2822        let next = values[if i == samples { 1 } else { i + 1 }];
2823        if values[i] <= previous && values[i] <= next && values[i].is_finite() {
2824            let (mut lo, mut hi) = (period * (i as f64 - 1.0) / samples as f64, period * (i as f64 + 1.0) / samples as f64);
2825            for _ in 0..100 {
2826                let a = lo + (hi - lo) * 0.381966;
2827                let b = hi - (hi - lo) * 0.381966;
2828                if radius(a) < radius(b) { hi = b } else { lo = a }
2829            }
2830            least = least.min(radius(0.5 * (lo + hi)));
2831        }
2832    }
2833    if offset >= least * (1.0 - 1e-6) {
2834        return Err(refuse(
2835            "undercut",
2836            format!("The pins ({dp}) are too large for this eccentricity and pin circle: the lobes would cusp (the pin radius plus half the clearance must be under {least:.4})."),
2837        ));
2838    }
2839    let lobes = pins - 1;
2840    let step = TAU / lobes as f64;
2841    let tolerance = GEAR_FIT_TOLERANCE * dp.min(e * 4.0);
2842    // The trochoid runs clockwise in t: walk t downwards for a counter-clockwise section.
2843    let mut curves = Vec::with_capacity(lobes);
2844    for k in 0..lobes {
2845        let (a, b) = (step * k as f64, step * (k + 1) as f64);
2846        let piece = fit_planar(&|u| disc.profile(-u), a, b, tolerance)?;
2847        curves.push(SectionCurve { curve: piece, role: "LB", tooth: k });
2848    }
2849    snap_junctions(&mut curves);
2850    Ok(GearSection { curves, data: GearData { pitch_diameter: dc, ..GearData::default() } })
2851}
2852
2853/// A cycloidal disc solid: the section extruded along +z; names `LB<k>`, `F`, `B`.
2854pub fn cycloidal_disc_solid(disc: &CycloidalDisc) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
2855    let section = cycloidal_disc_section(disc)?;
2856    let solid = extrude_section(&section, disc.width)?;
2857    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
2858    names.push("F".into());
2859    names.push("B".into());
2860    Ok((solid, names, section.data))
2861}
2862
2863/// The pin ring of a cycloidal drive: a ring of `outside` diameter whose bore
2864/// is the pin circle, with `pins` pins of `pin_diameter` centred on it (half
2865/// standing into the bore). Exact arcs. Faces: `P<k>` the pins' exposed halves,
2866/// `G<k>` the bore between pins, `OD`, `F`, `B`.
2867pub fn cycloidal_pin_ring(pins: usize, pin_circle_diameter: f64, pin_diameter: f64, outside: f64, width: f64) -> Result<(BrepSolid, GearData), KernelRefusal> {
2868    if !(4..=200).contains(&pins) || !(pin_diameter > 0.0 && pin_circle_diameter > pin_diameter && width > 0.0) {
2869        return Err(refuse("gear_input", "The pin ring needs 4 to 200 pins, a pin circle larger than the pins and a positive width.".into()));
2870    }
2871    let r = pin_circle_diameter / 2.0;
2872    let rp = pin_diameter / 2.0;
2873    let n = pins as f64;
2874    let tau = TAU / n;
2875    // Where a pin's circle crosses the bore circle (radius r): half-angle delta about the origin.
2876    let delta = 2.0 * (rp / (2.0 * r)).asin();
2877    if 2.0 * delta >= tau - 1e-9 || 2.0 * r * (PI / n).sin() <= pin_diameter * (1.0 + 1e-9) {
2878        return Err(refuse("gear_input", format!("{pins} pins of diameter {pin_diameter} overlap on a {pin_circle_diameter} pin circle.")));
2879    }
2880    let centre = [r, 0.0];
2881    let a = [r * (-delta).cos(), r * (-delta).sin()];
2882    let b = [r * delta.cos(), r * delta.sin()];
2883    // The pin bulges into the bore: its arc from a to b passes through (r - rp, 0).
2884    let cw = arc_through(centre, a, b, false)?;
2885    let pin_arc = {
2886        let [t0, t1] = cw.domain().map_err(|e| refuse("gear_domain", e))?;
2887        let mid = cw.evaluate(0.5 * (t0 + t1)).map_err(|e| refuse("gear_eval", e))?;
2888        if mid.x < r { cw } else { arc_through(centre, a, b, true)? }
2889    };
2890    let space: Vec<(&'static str, NurbsCurve)> = vec![("P", pin_arc), ("G", arc(r, delta, tau - delta)?)];
2891    let mut curves = Vec::with_capacity(2 * pins);
2892    for k in 0..pins {
2893        for (role, curve) in &space {
2894            curves.push(SectionCurve { curve: rotated(curve, tau * k as f64), role, tooth: k });
2895        }
2896    }
2897    snap_junctions(&mut curves);
2898    let section = GearSection { curves, data: GearData { pitch_diameter: pin_circle_diameter, ..GearData::default() } };
2899    let ring = hub_from_section(&section, outside, width)?;
2900    Ok((ring, section.data))
2901}
2902
2903/// A cycloidal (clock-style) gear: teeth whose addenda are epicycloids rolled
2904/// by a circle of `generating_radius` on the pitch circle and whose dedenda are
2905/// radial lines (the hypocycloid of a circle of half the mate's pitch radius).
2906#[derive(Clone, Debug)]
2907pub struct CycloidalGear {
2908    pub module: f64,
2909    pub teeth: usize,
2910    /// Radius of the rolling circle (usually half the mating gear's pitch radius).
2911    pub generating_radius: f64,
2912    /// Tooth thickness on the pitch circle as a fraction of the circular pitch.
2913    pub tooth_fraction: f64,
2914    /// Addendum limit × module (the tip is pointed if the flanks meet first).
2915    pub addendum: f64,
2916    /// Dedendum × module.
2917    pub dedendum: f64,
2918    pub width: f64,
2919}
2920
2921/// The cycloidal gear's section, counter-clockwise. Per tooth k: `R<k>`/`L<k>`
2922/// the radial dedendum flanks, `ER<k>`/`EL<k>` the epicycloidal addenda, `K<k>`
2923/// the tip land (absent when pointed), `G<k>` the root land.
2924pub fn cycloidal_gear_section(gear: &CycloidalGear) -> Result<GearSection, KernelRefusal> {
2925    let m = gear.module;
2926    if !(m > 0.0 && gear.generating_radius > 0.0 && gear.addendum > 0.0 && gear.dedendum > 0.0 && gear.width > 0.0) {
2927        return Err(refuse("gear_input", "The module, rolling circle, addendum, dedendum and width must be positive.".into()));
2928    }
2929    if !(gear.tooth_fraction > 0.1 && gear.tooth_fraction < 0.9) {
2930        return Err(refuse("gear_input", "The tooth thickness must be between 0.1 and 0.9 of the pitch.".into()));
2931    }
2932    if gear.teeth < 6 || gear.teeth > 1000 {
2933        return Err(refuse("gear_input", format!("A cycloidal gear needs from 6 to 1000 teeth (it has {}).", gear.teeth)));
2934    }
2935    let z = gear.teeth as f64;
2936    let r = m * z / 2.0;
2937    let rho = gear.generating_radius;
2938    let rf = r - gear.dedendum * m;
2939    if !(rf > 0.0) {
2940        return Err(refuse("root_below_centre", "The root circle is not positive: fewer dedendum or more teeth.".into()));
2941    }
2942    let tau = TAU / z;
2943    let psi = PI * gear.tooth_fraction / z; // half the tooth angle on the pitch circle
2944    // The right flank's epicycloid, from the pitch circle at angle -psi.
2945    let k = (r + rho) / rho;
2946    let epi = |phi: f64| {
2947        let p = [(r + rho) * phi.cos() - rho * (k * phi).cos(), (r + rho) * phi.sin() - rho * (k * phi).sin()];
2948        rotate(p, -psi)
2949    };
2950    let ra = r + gear.addendum * m;
2951    // Run phi up until the curve reaches the tip circle or the tooth centre line (angle 0).
2952    let reach = |phi: f64| radius_of(epi(phi)) >= ra || polar_angle(epi(phi)) >= 0.0;
2953    let mut hi = 1e-3;
2954    while !reach(hi) {
2955        hi *= 1.5;
2956        if hi > PI {
2957            return Err(refuse("gear_input", "The addendum curve does not close.".into()));
2958        }
2959    }
2960    let mut lo = 0.0;
2961    for _ in 0..200 {
2962        let mid = 0.5 * (lo + hi);
2963        if reach(mid) { hi = mid } else { lo = mid }
2964    }
2965    let end = epi(hi);
2966    // Pointed when the flank reaches the tooth centre line no later than the
2967    // tip circle (a tip land narrower than 1e-9 counts as pointed).
2968    let pointed = polar_angle(end) >= -1e-9;
2969    let phi_end = if pointed {
2970        let (mut lo, mut hi) = (0.0, hi);
2971        for _ in 0..200 {
2972            let mid = 0.5 * (lo + hi);
2973            if polar_angle(epi(mid)) >= 0.0 { hi = mid } else { lo = mid }
2974        }
2975        hi
2976    } else {
2977        hi
2978    };
2979    let tolerance = GEAR_FIT_TOLERANCE * m;
2980    let right_add = fit_planar(&|phi| epi(phi), 0.0, phi_end, tolerance)?; // pitch -> tip, right side
2981    let foot = [rf * (-psi).cos(), rf * (-psi).sin()];
2982    let pitch_point = [r * (-psi).cos(), r * (-psi).sin()];
2983    let mut tooth: Vec<(&'static str, NurbsCurve)> = vec![("R", line(foot, pitch_point)?), ("ER", right_add.clone())];
2984    let tip_angle = -polar_angle(epi(phi_end));
2985    if !pointed {
2986        tooth.push(("K", arc(ra, -tip_angle, tip_angle)?));
2987    }
2988    tooth.push(("EL", mirrored(&right_add).reversed().map_err(|e| refuse("gear_fit", e))?));
2989    tooth.push(("L", line([pitch_point[0], -pitch_point[1]], [foot[0], -foot[1]])?));
2990    tooth.push(("G", arc(rf, psi, tau - psi)?));
2991    let mut curves = Vec::with_capacity(tooth.len() * gear.teeth);
2992    for index in 0..gear.teeth {
2993        let angle = tau * index as f64;
2994        for (role, curve) in &tooth {
2995            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
2996        }
2997    }
2998    snap_junctions(&mut curves);
2999    let data = GearData {
3000        pitch_diameter: 2.0 * r,
3001        tip_diameter: 2.0 * radius_of(epi(phi_end)),
3002        root_diameter: 2.0 * rf,
3003        tooth_thickness: 2.0 * psi * r,
3004        ..GearData::default()
3005    };
3006    Ok(GearSection { curves, data })
3007}
3008
3009/// A cycloidal gear solid; names as the section's roles, then `F` and `B`.
3010pub fn cycloidal_gear_solid(gear: &CycloidalGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
3011    let section = cycloidal_gear_section(gear)?;
3012    let solid = extrude_section(&section, gear.width)?;
3013    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
3014    names.push("F".into());
3015    names.push("B".into());
3016    Ok((solid, names, section.data))
3017}
3018
3019/// A straight bevel gear with spherical-involute teeth (the true conjugate
3020/// form; not Tredgold's back-cone approximation). Module at the heel, shaft
3021/// angle 90°, pitch cone angle atan(z / z_mate). Apex at the origin, axis +z,
3022/// the teeth between cone distances R − face width and R; back and front
3023/// faces are the back and front cones (perpendicular to the pitch cone).
3024#[derive(Clone, Debug)]
3025pub struct BevelGear {
3026    pub module: f64,
3027    pub teeth: usize,
3028    pub mate_teeth: usize,
3029    pub pressure_angle: f64,
3030    pub addendum: f64,
3031    pub dedendum: f64,
3032    pub face_width: f64,
3033    pub backlash: f64,
3034}
3035
3036/// Derived bevel sizes: (pitch cone angle, cone distance, base cone angle).
3037pub fn bevel_cones(gear: &BevelGear) -> (f64, f64, f64) {
3038    let delta = (gear.teeth as f64).atan2(gear.mate_teeth as f64);
3039    let cone = gear.module * gear.teeth as f64 / (2.0 * delta.sin());
3040    let base = (delta.sin() * gear.pressure_angle.cos()).asin();
3041    (delta, cone, base)
3042}
3043
3044/// A point of the spherical involute of the base cone (half angle `base`) on
3045/// the sphere of radius `r`, unwrapped by `phi` from the base circle at azimuth 0.
3046fn spherical_involute(r: f64, base: f64, phi: f64) -> [f64; 3] {
3047    let (s, c) = base.sin_cos();
3048    let t = phi * s;
3049    [
3050        r * (t.cos() * s * phi.cos() + t.sin() * phi.sin()),
3051        r * (t.cos() * s * phi.sin() - t.sin() * phi.cos()),
3052        r * t.cos() * c,
3053    ]
3054}
3055
3056/// The polar angle from the axis (the cone angle) of a point.
3057fn cone_angle(p: [f64; 3]) -> f64 {
3058    p[0].hypot(p[1]).atan2(p[2])
3059}
3060
3061/// Central projection from the apex onto the plane z = h.
3062fn project(p: [f64; 3], h: f64) -> [f64; 2] {
3063    [p[0] * h / p[2], p[1] * h / p[2]]
3064}
3065
3066/// The bevel gear section: the spherical tooth outline on the sphere through
3067/// the heel, centrally projected onto the plane z = h (so every surface the
3068/// apex sees edge-on — tooth flanks, root and tip cones — becomes a planar
3069/// curve; the cones' circles project to exact arcs). Counter-clockwise; roles
3070/// as the spur gear's: `V/R/K/L/W/G` with `V/W` the radial (meridian) root
3071/// extension below the base cone when the root lies under it.
3072pub fn bevel_section(gear: &BevelGear, h: f64) -> Result<GearSection, KernelRefusal> {
3073    let m = gear.module;
3074    if !(m > 0.0 && gear.face_width > 0.0 && gear.addendum > 0.0 && gear.dedendum > 0.0 && gear.backlash >= 0.0) {
3075        return Err(refuse("gear_input", "The module, face width, addendum and dedendum must be positive.".into()));
3076    }
3077    if gear.teeth < 6 || gear.mate_teeth < 6 {
3078        return Err(refuse("gear_input", "A bevel pair needs at least 6 teeth on each gear.".into()));
3079    }
3080    let degrees = gear.pressure_angle.to_degrees();
3081    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&degrees) {
3082        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and 35° (it is {degrees}°).")));
3083    }
3084    let (delta, r, base) = bevel_cones(gear);
3085    if gear.face_width > r / 3.0 + 1e-9 {
3086        return Err(refuse(
3087            "face_too_wide",
3088            format!("The face width ({}) is over a third of the cone distance ({:.4}): the teeth would be too small at the toe.", gear.face_width, r),
3089        ));
3090    }
3091    let z = gear.teeth as f64;
3092    let tip = delta + gear.addendum * m / r;
3093    let root = delta - gear.dedendum * m / r;
3094    if !(root > 0.0) {
3095        return Err(refuse("root_below_centre", "The root cone passes the axis: fewer dedendum or more teeth.".into()));
3096    }
3097    // The unwrap angle where the involute reaches a cone angle theta: cos(phi sin b) cos b = cos theta.
3098    let phi_at = |theta: f64| ((theta.cos() / base.cos()).clamp(-1.0, 1.0)).acos() / base.sin();
3099    let azimuth = |p: [f64; 3]| p[1].atan2(p[0]);
3100    // Position the left flank: half the tooth thickness (arc on the pitch circle of radius r sin delta) at the pitch cone.
3101    let half = (PI * m / 2.0 - gear.backlash) / (2.0 * r * delta.sin());
3102    let p_pitch = spherical_involute(r, base, phi_at(delta));
3103    // The involute (unwrapping counter-clockwise) leans to positive azimuth as it rises: the left flank
3104    // is it mirrored, turned so its pitch point sits at +half.
3105    let shift = half + azimuth(p_pitch);
3106    let left = |phi: f64| {
3107        let p = spherical_involute(r, base, phi);
3108        let q = [p[0], -p[1], p[2]];
3109        let (s, c) = shift.sin_cos();
3110        [c * q[0] - s * q[1], s * q[0] + c * q[1], q[2]]
3111    };
3112    let tip_phi = phi_at(tip);
3113    if azimuth(left(tip_phi)) <= 1e-6 * m / r {
3114        return Err(refuse("pointed_tip", "The teeth come to a point below the tip cone: reduce the addendum.".into()));
3115    }
3116    // At the base cone the involute leaves with zero speed (a cusp in phi):
3117    // when the root lies under it, the flank starts a little above (2% of the
3118    // unwrap) and the radial root extension runs up to that point.
3119    let extend = !(root > base); // the root lies on or under the base cone: a radial extension
3120    let start_phi = if extend { 0.02 * tip_phi } else { phi_at(root) };
3121    let tolerance = GEAR_FIT_TOLERANCE * m;
3122    let flank = fit_planar(&|phi| project(left(phi), h), start_phi, tip_phi, tolerance)?; // root side -> tip
3123    let tau = TAU / z;
3124    let base_point = project(left(start_phi), h);
3125    let root_r = h * root.tan();
3126    let tip_r = h * tip.tan();
3127    let foot_angle = base_point[1].atan2(base_point[0]);
3128    let mut tooth: Vec<(&'static str, NurbsCurve)> = Vec::new();
3129    let tip_angle = {
3130        let p = project(left(tip_phi), h);
3131        p[1].atan2(p[0])
3132    };
3133    // Right side (mirror), going up: [V radial] + R; tip K; then L down + [W radial]; G root land.
3134    let radial_foot = [root_r * foot_angle.cos(), root_r * foot_angle.sin()];
3135    if extend {
3136        tooth.push(("V", line([radial_foot[0], -radial_foot[1]], [base_point[0], -base_point[1]])?));
3137    }
3138    tooth.push(("R", mirrored(&flank)));
3139    tooth.push(("K", arc(tip_r, -tip_angle, tip_angle)?));
3140    tooth.push(("L", flank.reversed().map_err(|e| refuse("gear_fit", e))?));
3141    if extend {
3142        tooth.push(("W", line(base_point, radial_foot)?));
3143    }
3144    if foot_angle >= tau / 2.0 - 1e-9 {
3145        return Err(refuse("teeth_overlap", "The tooth roots meet: fewer teeth or a smaller pressure angle.".into()));
3146    }
3147    tooth.push(("G", arc(root_r, foot_angle, tau - foot_angle)?));
3148    let mut curves = Vec::with_capacity(tooth.len() * gear.teeth);
3149    for index in 0..gear.teeth {
3150        let angle = tau * index as f64;
3151        for (role, curve) in &tooth {
3152            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
3153        }
3154    }
3155    // Lift the section into the plane z = h.
3156    for piece in &mut curves {
3157        for p in &mut piece.curve.control_points {
3158            p.z = p.w * h;
3159        }
3160    }
3161    snap_junctions(&mut curves);
3162    // Diameters at the heel: where each cone meets the back cone (perpendicular
3163    // to the pitch cone at cone distance r).
3164    let heel = |angle: f64| 2.0 * r * angle.sin() / (angle - delta).cos();
3165    let data = GearData {
3166        pitch_diameter: 2.0 * r * delta.sin(),
3167        tip_diameter: heel(tip),
3168        root_diameter: heel(root),
3169        ..GearData::default()
3170    };
3171    Ok(GearSection { curves, data })
3172}
3173
3174/// A straight bevel gear solid: the section's cone (every flank exactly the cone from the apex over the
3175/// spherical involute) between the front and back cones. Built directly, without booleans: the back cone
3176/// cuts every generator at the cone distance r, so each face of the tooth outline is its back curve (the
3177/// outline's trace on the back cone) scaled towards the apex down to the front cone, a ruled face whose
3178/// edges are all iso-lines. Faces carry their roles in `face.name` (`R3`, `K0`, …, `BACK`, `FRONT`).
3179pub fn bevel_solid(gear: &BevelGear) -> Result<(BrepSolid, GearData), KernelRefusal> {
3180    use crate::sweep_topology::parameter_line;
3181    let (delta, r, base) = bevel_cones(gear);
3182    // The section's own checks and data (diameters at the heel).
3183    let data = bevel_section(gear, r * delta.cos())?.data;
3184    let m = gear.module;
3185    let teeth = gear.teeth;
3186    let tau = TAU / teeth as f64;
3187    let tip = delta + gear.addendum * m / r;
3188    let root = delta - gear.dedendum * m / r;
3189    // The left flank on the sphere of radius r, as `bevel_section` positions it.
3190    let phi_at = |theta: f64| ((theta.cos() / base.cos()).clamp(-1.0, 1.0)).acos() / base.sin();
3191    let azimuth = |p: [f64; 3]| p[1].atan2(p[0]);
3192    let half = (PI * m / 2.0 - gear.backlash) / (2.0 * r * delta.sin());
3193    let shift = half + azimuth(spherical_involute(r, base, phi_at(delta)));
3194    let left = |phi: f64| {
3195        let p = spherical_involute(r, base, phi);
3196        let q = [p[0], -p[1], p[2]];
3197        let (s, c) = shift.sin_cos();
3198        [c * q[0] - s * q[1], s * q[0] + c * q[1], q[2]]
3199    };
3200    let tip_phi = phi_at(tip);
3201    let extend = !(root > base);
3202    let start_phi = if extend { 0.02 * tip_phi } else { phi_at(root) };
3203    let foot_angle = azimuth(left(start_phi));
3204    let tip_angle = azimuth(left(tip_phi));
3205    // Along the ray through p, the point on the back cone (rho sin delta + z cos delta = r).
3206    let (sd, cd) = delta.sin_cos();
3207    let back = |p: [f64; 3]| {
3208        let s = r / (p[0].hypot(p[1]) * sd + p[2] * cd);
3209        [p[0] * s, p[1] * s, p[2] * s]
3210    };
3211    // The back cone's circle at cone angle theta: (radius, height).
3212    let circle_at = |theta: f64| {
3213        let k = r / (theta - delta).cos();
3214        (k * theta.sin(), k * theta.cos())
3215    };
3216    let at = |theta: f64, angle: f64| {
3217        let (rho, z) = circle_at(theta);
3218        Vec3::new(rho * angle.cos(), rho * angle.sin(), z)
3219    };
3220    let v3 = |p: [f64; 3]| Vec3::new(p[0], p[1], p[2]);
3221    let mirror = |curve: &NurbsCurve| -> Result<NurbsCurve, KernelRefusal> {
3222        NurbsCurve::new(curve.degree, curve.knots.clone(), curve.control_points.iter().map(|p| Vec4 { x: p.x, y: -p.y, z: p.z, w: p.w }).collect()).map_err(|e| refuse("gear_fit", e))
3223    };
3224    let arc_on = |theta: f64, from: f64, to: f64| -> Result<NurbsCurve, KernelRefusal> {
3225        let (rho, z) = circle_at(theta);
3226        crate::make_arc(Vec3::new(0.0, 0.0, z), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), rho, from, to).map_err(|e| refuse("gear_arc", e))
3227    };
3228    let segment = |a: Vec3, b: Vec3| crate::make_line(a, b).map_err(|e| refuse("gear_edge", e));
3229    // The left flank's back curve, fitted from the exact involute (tip -> foot); the right flank mirrors it.
3230    let tolerance = 0.2 * GEAR_FIT_TOLERANCE * m;
3231    let flank = |t: f64| back(left(tip_phi - t * (tip_phi - start_phi)));
3232    let (left_back, _) = fit_on_breaks3(&flank, &adaptive_breaks3(&flank, tolerance)?)?;
3233    let right_back = mirror(&left_back)?.reversed().map_err(|e| refuse("gear_fit", e))?;
3234    let foot = v3(back(left(start_phi)));
3235    let mirrored = |p: Vec3| Vec3::new(p.x, -p.y, p.z);
3236    // Tooth 0's back curves in section order (counter-clockwise about +z).
3237    let mut tooth: Vec<(&'static str, NurbsCurve)> = Vec::new();
3238    if extend {
3239        tooth.push(("V", segment(at(root, -foot_angle), mirrored(foot))?));
3240    }
3241    tooth.push(("R", right_back));
3242    tooth.push(("K", arc_on(tip, -tip_angle, tip_angle)?));
3243    tooth.push(("L", left_back));
3244    if extend {
3245        tooth.push(("W", segment(foot, at(root, foot_angle))?));
3246    }
3247    tooth.push(("G", arc_on(root, foot_angle, tau - foot_angle)?));
3248    let mut curves: Vec<SectionCurve> = Vec::with_capacity(tooth.len() * teeth);
3249    for index in 0..teeth {
3250        for (role, curve) in &tooth {
3251            curves.push(SectionCurve { curve: rotated(curve, tau * index as f64), role, tooth: index });
3252        }
3253    }
3254    snap_junctions(&mut curves);
3255    let count = curves.len();
3256    let lambda = (r - gear.face_width) / r;
3257    let scaled = |curve: &NurbsCurve| -> Result<NurbsCurve, KernelRefusal> {
3258        NurbsCurve::new(curve.degree, curve.knots.clone(), curve.control_points.iter().map(|p| Vec4 { x: p.x * lambda, y: p.y * lambda, z: p.z * lambda, w: p.w }).collect()).map_err(|e| refuse("gear_fit", e))
3259    };
3260    let point_of = |p: Vec4| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w);
3261    let mut shell = ShellBuilder { vertices: Vec::new(), edges: Vec::new(), faces: Vec::new(), next: 0 };
3262    // Junction j starts curve j: its back and front vertices and the generator between them.
3263    let mut back_v = Vec::with_capacity(count);
3264    let mut front_v = Vec::with_capacity(count);
3265    let mut generators = Vec::with_capacity(count);
3266    for piece in &curves {
3267        let b = point_of(piece.curve.control_points[0]);
3268        let f = b.scale(lambda);
3269        let (vb, vf) = (shell.vertex(b), shell.vertex(f));
3270        generators.push(shell.edge(segment(f, b)?, vf, vb)?);
3271        back_v.push(vb);
3272        front_v.push(vf);
3273    }
3274    let mut back_e = Vec::with_capacity(count);
3275    let mut front_e = Vec::with_capacity(count);
3276    for (index, piece) in curves.iter().enumerate() {
3277        let next = (index + 1) % count;
3278        back_e.push(shell.edge(piece.curve.clone(), back_v[index], back_v[next])?);
3279        front_e.push(shell.edge(scaled(&piece.curve)?, front_v[index], front_v[next])?);
3280    }
3281    let line = |a: [f64; 2], b: [f64; 2]| parameter_line(a[0], a[1], b[0], b[1]).map_err(|e| refuse("gear_pcurve", e));
3282    for (index, piece) in curves.iter().enumerate() {
3283        let next = (index + 1) % count;
3284        let rows: Vec<Vec<Vec4>> = piece.curve.control_points.iter().map(|p| vec![Vec4 { x: p.x * lambda, y: p.y * lambda, z: p.z * lambda, w: p.w }, *p]).collect();
3285        let surface = NurbsSurface::new(piece.curve.degree, 1, piece.curve.knots.clone(), vec![0.0, 0.0, 1.0, 1.0], rows).map_err(|e| refuse("gear_surface", e))?;
3286        let [u0, u1] = piece.curve.domain().map_err(|e| refuse("gear_domain", e))?;
3287        let loops = vec![vec![
3288            (front_e[index], true, line([u0, 0.0], [u1, 0.0])?),
3289            (generators[next], true, line([u1, 0.0], [u1, 1.0])?),
3290            (back_e[index], false, line([u0, 1.0], [u1, 1.0])?),
3291            (generators[index], false, line([u0, 0.0], [u0, 1.0])?),
3292        ]];
3293        shell.face(surface, true, loops, piece.suffix())?;
3294    }
3295    // The back and front cones, each one face round its apex (a pole edge there) with a seam through
3296    // junction 0. u follows the rational circle from junction 0's azimuth, v runs out from the apex.
3297    let seam = {
3298        let p = point_of(curves[0].curve.control_points[0]);
3299        p.y.atan2(p.x)
3300    };
3301    let reach = curves.iter().flat_map(|c| c.curve.control_points.iter()).map(|p| (p.x / p.w).hypot(p.y / p.w)).fold(0.0, f64::max) * 1.1 + m;
3302    let circle = crate::make_arc(Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), 1.0, seam, seam + TAU).map_err(|e| refuse("gear_arc", e))?;
3303    let segments = (circle.knots.len() - 6) / 2 + 1;
3304    let quarter = TAU / segments as f64;
3305    let cone = |scale: f64| -> Result<NurbsSurface, KernelRefusal> {
3306        let (apex, rim) = (scale * r / cd, scale * (r - reach * sd) / cd);
3307        let rows = circle.control_points.iter().map(|c| vec![Vec4 { x: 0.0, y: 0.0, z: apex * c.w, w: c.w }, Vec4 { x: scale * reach * c.x, y: scale * reach * c.y, z: rim * c.w, w: c.w }]).collect();
3308        NurbsSurface::new(circle.degree, 1, circle.knots.clone(), vec![0.0, 0.0, 1.0, 1.0], rows).map_err(|e| refuse("gear_surface", e))
3309    };
3310    // The circle's parameter at an angle from the seam: each span a rational quadratic arc of `quarter`, on
3311    // which tan(beta / 2) = (2 s - 1) tan(quarter / 4) about the span's middle.
3312    let parameter = |angle: f64| {
3313        let k = ((angle / quarter).floor().max(0.0) as usize).min(segments - 1);
3314        let beta = angle - (k as f64 + 0.5) * quarter;
3315        let s = ((beta / 2.0).tan() / (quarter / 4.0).tan() + 1.0) / 2.0;
3316        (k as f64 + s) / segments as f64
3317    };
3318    // Back-cone pcurves of the back curves (the front cone is the back scaled to the apex: the same pcurves).
3319    let mut cone_pcurves = Vec::with_capacity(count);
3320    for piece in &curves {
3321        let curve = &piece.curve;
3322        let [t0, t1] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
3323        let mid = curve.evaluate(0.5 * (t0 + t1)).map_err(|e| refuse("gear_curve", e))?;
3324        let middle = (mid.y.atan2(mid.x) - seam).rem_euclid(TAU);
3325        // (Extended past the ends: the fit's end slopes look a step outside the edge.)
3326        let uv = |t: f64| {
3327            let p = curve.evaluate_extended(t0 + (t1 - t0) * t).unwrap_or(mid);
3328            let angle = middle + ((p.y.atan2(p.x) - seam - middle + PI).rem_euclid(TAU) - PI);
3329            [parameter(angle), p.x.hypot(p.y) / reach]
3330        };
3331        let breaks = adaptive_breaks(&uv, 1e-11)?;
3332        let (mut pcurve, _) = fit_on_breaks(&uv, &breaks)?;
3333        // On the edge's own parameter range.
3334        pcurve.knots.iter_mut().for_each(|k| *k = t0 + (t1 - t0) * *k);
3335        cone_pcurves.push(NurbsCurve::new(pcurve.degree, pcurve.knots.clone(), pcurve.control_points.clone()).map_err(|e| refuse("gear_pcurve", e))?);
3336    }
3337    let seam_v = point_of(curves[0].curve.control_points[0]).x.hypot(point_of(curves[0].curve.control_points[0]).y) / reach;
3338    for (scale, name, outline, junction) in [(1.0, "BACK", &back_e, &back_v), (lambda, "FRONT", &front_e, &front_v)] {
3339        let surface = cone(scale)?;
3340        let apex_point = Vec3::new(0.0, 0.0, scale * r / cd);
3341        let apex = shell.vertex(apex_point);
3342        let pole_curve = NurbsCurve::new(surface.degree_u, surface.knots_u.clone(), surface.control_points.iter().map(|row| row[0]).collect()).map_err(|e| refuse("gear_edge", e))?;
3343        let pole = shell.degenerate_edge(pole_curve, apex)?;
3344        let seam_point = shell.vertices.iter().find(|v| v.id == junction[0]).expect("junction 0").point;
3345        let seam_edge = shell.edge(segment(apex_point, seam_point)?, apex, junction[0])?;
3346        let mut coedges = vec![(pole, true, line([0.0, 0.0], [1.0, 0.0])?), (seam_edge, true, line([1.0, 0.0], [1.0, seam_v])?)];
3347        for index in (0..count).rev() {
3348            coedges.push((outline[index], false, cone_pcurves[index].clone()));
3349        }
3350        coedges.push((seam_edge, false, line([0.0, 0.0], [0.0, seam_v])?));
3351        // The surface's normal points to the apex side: outward for the front, inward for the back.
3352        shell.face(surface, name == "FRONT", vec![coedges], name.into())?;
3353    }
3354    let id = shell.id();
3355    let shell_id = shell.id();
3356    let solid = BrepSolid {
3357        mass_properties_cache: Default::default(),
3358        cells: Default::default(),
3359        id,
3360        vertices: shell.vertices,
3361        edges: shell.edges,
3362        shells: vec![crate::sweep_topology::ShellRecord { id: shell_id, faces: shell.faces }],
3363        genus: 0,
3364        kind: crate::BodyKind::Solid,
3365    };
3366    let issues = solid.validate();
3367    if !issues.is_empty() {
3368        return Err(KernelRefusal::internal(KernelStage::Validate, "validate", format!("bevel gear is not valid: {issues:?}")));
3369    }
3370    Ok((solid, data))
3371}
3372
3373/// The cubic Hermite span of a space curve (numeric end derivatives) as Bézier points.
3374fn hermite_span3(f: &dyn Fn(f64) -> [f64; 3], t0: f64, t1: f64) -> [[f64; 3]; 4] {
3375    let derivative = |t: f64| {
3376        let h = 1e-6;
3377        let (p, q) = (f(t + h), f(t - h));
3378        [(p[0] - q[0]) / (2.0 * h), (p[1] - q[1]) / (2.0 * h), (p[2] - q[2]) / (2.0 * h)]
3379    };
3380    let (p0, p1) = (f(t0), f(t1));
3381    let (d0, d1) = (derivative(t0), derivative(t1));
3382    let k = (t1 - t0) / 3.0;
3383    let ahead = |p: [f64; 3], d: [f64; 3], s: f64| [p[0] + s * d[0], p[1] + s * d[1], p[2] + s * d[2]];
3384    [p0, ahead(p0, d0, k), ahead(p1, d1, -k), p1]
3385}
3386
3387fn hermite_span3_error(f: &dyn Fn(f64) -> [f64; 3], t0: f64, t1: f64) -> f64 {
3388    let c = hermite_span3(f, t0, t1);
3389    [0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
3390        .iter()
3391        .map(|&u| {
3392            let exact = f(t0 + (t1 - t0) * u);
3393            let v = 1.0 - u;
3394            let w = [v * v * v, 3.0 * v * v * u, 3.0 * v * u * u, u * u * u];
3395            let mut d = 0.0;
3396            for axis in 0..3 {
3397                let x = w[0] * c[0][axis] + w[1] * c[1][axis] + w[2] * c[2][axis] + w[3] * c[3][axis];
3398                d += (exact[axis] - x).powi(2);
3399            }
3400            d.sqrt()
3401        })
3402        .fold(0.0, f64::max)
3403}
3404
3405fn adaptive_breaks3(f: &dyn Fn(f64) -> [f64; 3], tolerance: f64) -> Result<Vec<f64>, KernelRefusal> {
3406    let mut breaks = vec![0.0];
3407    let mut pending: Vec<(f64, f64, usize)> = (0..4).rev().map(|i| (i as f64 / 4.0, (i + 1) as f64 / 4.0, 0)).collect();
3408    while let Some((t0, t1, depth)) = pending.pop() {
3409        if hermite_span3_error(f, t0, t1) > tolerance {
3410            if depth >= 16 {
3411                return Err(refuse("gear_fit", format!("gear curve fit did not converge on [{t0}, {t1}]")));
3412            }
3413            let mid = 0.5 * (t0 + t1);
3414            pending.push((mid, t1, depth + 1));
3415            pending.push((t0, mid, depth + 1));
3416        } else {
3417            breaks.push(t1);
3418        }
3419    }
3420    Ok(breaks)
3421}
3422
3423/// A space curve on [0, 1] as C1 cubic Hermite spans at the given breaks, and its worst error.
3424fn fit_on_breaks3(f: &dyn Fn(f64) -> [f64; 3], breaks: &[f64]) -> Result<(NurbsCurve, f64), KernelRefusal> {
3425    let to_point = |p: [f64; 3]| Vec4::from_point(Vec3::new(p[0], p[1], p[2]), 1.0);
3426    let mut knots = vec![0.0; 4];
3427    let mut points = Vec::with_capacity(2 * breaks.len() + 2);
3428    let mut worst = 0.0_f64;
3429    let spans = breaks.len() - 1;
3430    for index in 0..spans {
3431        let (t0, t1) = (breaks[index], breaks[index + 1]);
3432        let c = hermite_span3(f, t0, t1);
3433        worst = worst.max(hermite_span3_error(f, t0, t1));
3434        if index == 0 {
3435            points.push(to_point(c[0]));
3436        }
3437        points.push(to_point(c[1]));
3438        points.push(to_point(c[2]));
3439        if index + 1 < spans {
3440            knots.extend([t1, t1]);
3441        } else {
3442            points.push(to_point(c[3]));
3443        }
3444    }
3445    knots.extend([1.0; 4]);
3446    Ok((NurbsCurve::new(3, knots, points).map_err(|error| refuse("gear_fit", error))?, worst))
3447}
3448
3449/// Builds a closed shell from faces whose loops are given in any direction: each loop is turned to run
3450/// counter-clockwise about the outward normal (its pcurves' area sign against `same_sense`). A face's first
3451/// loop is its outer loop.
3452pub(crate) struct ShellBuilder {
3453    pub(crate) vertices: Vec<crate::sweep_topology::VertexRecord>,
3454    pub(crate) edges: Vec<crate::sweep_topology::EdgeRecord>,
3455    pub(crate) faces: Vec<crate::sweep_topology::FaceRecord>,
3456    pub(crate) next: u64,
3457}
3458
3459impl ShellBuilder {
3460    pub(crate) fn id(&mut self) -> u64 {
3461        self.next += 1;
3462        self.next
3463    }
3464
3465    pub(crate) fn vertex(&mut self, p: Vec3) -> u64 {
3466        let id = self.id();
3467        self.vertices.push(crate::sweep_topology::VertexRecord { id, point: p });
3468        id
3469    }
3470
3471    pub(crate) fn edge(&mut self, curve: NurbsCurve, start: u64, end: u64) -> Result<u64, KernelRefusal> {
3472        let [t0, t1] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
3473        let id = self.id();
3474        self.edges.push(crate::sweep_topology::EdgeRecord { id, curve, t0, t1, start_vertex_id: start, end_vertex_id: end, degenerate: false, name: None });
3475        Ok(id)
3476    }
3477
3478    /// A pole: an edge collapsed to the vertex `at` (its curve the surface's iso-curve there).
3479    pub(crate) fn degenerate_edge(&mut self, curve: NurbsCurve, at: u64) -> Result<u64, KernelRefusal> {
3480        let [t0, t1] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
3481        let id = self.id();
3482        self.edges.push(crate::sweep_topology::EdgeRecord { id, curve, t0, t1, start_vertex_id: at, end_vertex_id: at, degenerate: true, name: None });
3483        Ok(id)
3484    }
3485
3486    #[allow(dead_code)]
3487    pub(crate) fn curve(&self, edge: u64) -> &NurbsCurve {
3488        &self.edges.iter().find(|e| e.id == edge).expect("a known edge").curve
3489    }
3490
3491    /// `loops`: (edge, forward, pcurve along the edge's own direction).
3492    pub(crate) fn face(&mut self, surface: NurbsSurface, same_sense: bool, loops: Vec<Vec<(u64, bool, NurbsCurve)>>, name: String) -> Result<(), KernelRefusal> {
3493        use crate::sweep_topology::{CoedgeRecord, FaceRecord, LoopRecord};
3494        let area = |coedges: &[(u64, bool, NurbsCurve)]| -> Result<f64, KernelRefusal> {
3495            let mut points = Vec::new();
3496            for (_, forward, pcurve) in coedges {
3497                let [a, b] = pcurve.domain().map_err(|e| refuse("gear_pcurve", e))?;
3498                for i in 0..16 {
3499                    let f = i as f64 / 16.0;
3500                    let t = if *forward { a + (b - a) * f } else { b - (b - a) * f };
3501                    points.push(pcurve.evaluate(t).map_err(|e| refuse("gear_pcurve", e))?);
3502                }
3503            }
3504            Ok((0..points.len()).map(|i| {
3505                let (p, q) = (points[i], points[(i + 1) % points.len()]);
3506                p.x * q.y - q.x * p.y
3507            }).sum::<f64>() / 2.0)
3508        };
3509        // The first loop is the outer one (a sampled area cannot tell: a hole of many short edges can out-measure
3510        // an outer circle of one).
3511        let areas: Vec<f64> = loops.iter().map(|l| area(l)).collect::<Result<_, _>>()?;
3512        let outer = 0;
3513        let mut records = Vec::with_capacity(loops.len());
3514        for (index, coedges) in loops.into_iter().enumerate() {
3515            let want = (index == outer) == same_sense;
3516            let mut coedges = coedges;
3517            if (areas[index] > 0.0) != want {
3518                coedges.reverse();
3519                for coedge in &mut coedges {
3520                    coedge.1 = !coedge.1;
3521                }
3522            }
3523            let mut out = Vec::with_capacity(coedges.len());
3524            for (edge, forward, pcurve) in coedges {
3525                let pcurve = if forward { pcurve } else { pcurve.reversed().map_err(|e| refuse("gear_pcurve", e))? };
3526                out.push(CoedgeRecord { id: self.id(), edge_id: edge, forward, pcurve });
3527            }
3528            records.push(LoopRecord { id: self.id(), coedges: out });
3529        }
3530        let id = self.id();
3531        self.faces.push(FaceRecord { id, surface, same_sense, loops: records, name: Some(name) });
3532        Ok(())
3533    }
3534}
3535
3536/// An elliptical gear: the pitch curve is an ellipse turning about one of its
3537/// foci, and the teeth are generated by rolling the standard basic rack round
3538/// it without slip (the rack's pitch line tangent to the ellipse, the contact
3539/// normal through the touching point), as a spur gear is generated round its
3540/// pitch circle. Two identical elliptical gears with an odd tooth count mesh
3541/// at a centre distance of the major axis (see [`elliptical_sizes`]).
3542///
3543/// The ellipse is sized so its perimeter is exactly `teeth` circular pitches
3544/// (π · module), so the teeth close. Tooth 0 is centred on the near vertex
3545/// (on +x, closest to the pivot).
3546#[derive(Clone, Debug)]
3547pub struct EllipticalGear {
3548    pub module: f64,
3549    pub teeth: usize,
3550    /// Eccentricity of the pitch ellipse (0 is a spur gear turning about its centre).
3551    pub eccentricity: f64,
3552    pub pressure_angle: f64,
3553    /// Addendum coefficient × module, measured normal to the pitch curve.
3554    pub addendum: f64,
3555    /// Dedendum coefficient × module, normal to the pitch curve.
3556    pub dedendum: f64,
3557    /// Tip radius of the generating rack × module.
3558    pub root_fillet: f64,
3559    /// Arc length added to each tooth space along the pitch curve.
3560    pub backlash: f64,
3561    pub face_width: f64,
3562}
3563
3564/// The pitch ellipse about its focus, by arc length.
3565struct PitchEllipse {
3566    /// Semi-latus rectum: r(θ) = p / (1 + e cos nθ) about the focus (n = 1, an ellipse) or the centre (n lobes).
3567    latus: f64,
3568    e: f64,
3569    lobes: f64,
3570    segments: usize,
3571    /// Cumulative arc length at θ = 2π i / SEGMENTS.
3572    table: Vec<f64>,
3573}
3574
3575impl PitchEllipse {
3576    const SEGMENTS: usize = 1024;
3577
3578    fn new(latus: f64, e: f64) -> Self {
3579        Self::lobed(latus, e, 1)
3580    }
3581
3582    fn lobed(latus: f64, e: f64, lobes: usize) -> Self {
3583        let segments = Self::SEGMENTS * lobes.max(1);
3584        let mut curve = Self { latus, e, lobes: lobes.max(1) as f64, segments, table: Vec::with_capacity(segments + 1) };
3585        // Five-point Gauss-Legendre per segment.
3586        let nodes = [0.0, -0.538_469_310_105_683_1, 0.538_469_310_105_683_1, -0.906_179_845_938_664, 0.906_179_845_938_664];
3587        let weights = [0.568_888_888_888_888_9, 0.478_628_670_499_366_5, 0.478_628_670_499_366_5, 0.236_926_885_056_189_1, 0.236_926_885_056_189_1];
3588        let step = TAU / segments as f64;
3589        let mut total = 0.0;
3590        curve.table.push(0.0);
3591        for i in 0..segments {
3592            let mid = (i as f64 + 0.5) * step;
3593            let sum: f64 = nodes.iter().zip(&weights).map(|(x, w)| w * curve.speed(mid + 0.5 * step * x)).sum();
3594            total += 0.5 * step * sum;
3595            curve.table.push(total);
3596        }
3597        curve
3598    }
3599
3600    fn length(&self) -> f64 {
3601        self.table[self.segments]
3602    }
3603
3604    /// Point, first and second derivatives in θ.
3605    fn derivatives(&self, theta: f64) -> ([f64; 2], [f64; 2], [f64; 2]) {
3606        let n = self.lobes;
3607        let (s, c) = theta.sin_cos();
3608        let (sn, cn) = (n * theta).sin_cos();
3609        let d = 1.0 + self.e * cn;
3610        let d1 = -self.e * n * sn;
3611        let d2 = -self.e * n * n * cn;
3612        let r = self.latus / d;
3613        let r1 = -self.latus * d1 / (d * d);
3614        let r2 = -self.latus * (d2 * d - 2.0 * d1 * d1) / (d * d * d);
3615        (
3616            [r * c, r * s],
3617            [r1 * c - r * s, r1 * s + r * c],
3618            [r2 * c - 2.0 * r1 * s - r * c, r2 * s + 2.0 * r1 * c - r * s],
3619        )
3620    }
3621
3622    fn speed(&self, theta: f64) -> f64 {
3623        let (_, d1, _) = self.derivatives(theta);
3624        d1[0].hypot(d1[1])
3625    }
3626
3627    /// The polar angle at arc length `s` (any real; the curve is periodic).
3628    fn theta_at(&self, s: f64) -> f64 {
3629        let length = self.length();
3630        let turns = (s / length).floor();
3631        let local = s - turns * length;
3632        let index = self.table.partition_point(|&value| value <= local).clamp(1, self.segments) - 1;
3633        let step = TAU / self.segments as f64;
3634        let (lo, hi) = (index as f64 * step, (index + 1) as f64 * step);
3635        let span = self.table[index + 1] - self.table[index];
3636        let mut theta = lo + step * (local - self.table[index]) / span;
3637        // Newton on the segment's arc length, measured from its start by Gauss-Legendre.
3638        let nodes = [0.0, -0.538_469_310_105_683_1, 0.538_469_310_105_683_1, -0.906_179_845_938_664, 0.906_179_845_938_664];
3639        let weights = [0.568_888_888_888_888_9, 0.478_628_670_499_366_5, 0.478_628_670_499_366_5, 0.236_926_885_056_189_1, 0.236_926_885_056_189_1];
3640        for _ in 0..8 {
3641            let half = 0.5 * (theta - lo);
3642            let arc: f64 = half * nodes.iter().zip(&weights).map(|(x, w)| w * self.speed(lo + half * (1.0 + x))).sum::<f64>();
3643            let error = self.table[index] + arc - local;
3644            theta = (theta - error / self.speed(theta)).clamp(lo, hi);
3645            if error.abs() < 1e-15 * length {
3646                break;
3647            }
3648        }
3649        theta + turns * TAU
3650    }
3651
3652    /// Point, unit tangent (counter-clockwise), outward unit normal and signed curvature at arc length `s`.
3653    fn frame(&self, s: f64) -> ([f64; 2], [f64; 2], [f64; 2], f64) {
3654        let (p, d1, d2) = self.derivatives(self.theta_at(s));
3655        let speed = d1[0].hypot(d1[1]);
3656        let t = [d1[0] / speed, d1[1] / speed];
3657        let curvature = (d1[0] * d2[1] - d1[1] * d2[0]) / speed.powi(3);
3658        (p, t, [t[1], -t[0]], curvature)
3659    }
3660}
3661
3662/// The derived sizes of an elliptical gear: (semi-major axis, eccentricity,
3663/// perimeter, centre distance to an identical mate = 2 × semi-major axis).
3664pub fn elliptical_sizes(gear: &EllipticalGear) -> (f64, f64, f64, f64) {
3665    lobed_sizes(gear, 1)
3666}
3667
3668/// [`elliptical_sizes`] for a pitch curve of `lobes` lobes, r(θ) = a (1 − e²) / (1 + e cos(lobes · θ)) about its
3669/// centre (one lobe: the ellipse about its focus). Two equal gears roll on it at the same centre distance 2a.
3670pub fn lobed_sizes(gear: &EllipticalGear, lobes: usize) -> (f64, f64, f64, f64) {
3671    let e = gear.eccentricity;
3672    let unit = PitchEllipse::lobed(1.0 - e * e, e, lobes); // a = 1
3673    let a = PI * gear.module * gear.teeth as f64 / unit.length();
3674    (a, e, PI * gear.module * gear.teeth as f64, 2.0 * a)
3675}
3676
3677/// The rack, pitch line on y = 0 with +y away from the gear, rolled to arc
3678/// length `s`: rack point (x, y) lies at P(s) + (x − s) T(s) + y N(s).
3679struct RollingRack<'a> {
3680    pitch: &'a PitchEllipse,
3681}
3682
3683impl RollingRack<'_> {
3684    /// The gear point generated by the rack point `q` with normal direction `n`
3685    /// (either sense): the normal through q meets the pitch line at the rolling position.
3686    fn envelope(&self, q: [f64; 2], n: [f64; 2]) -> [f64; 2] {
3687        let s = q[0] - q[1] * n[0] / n[1];
3688        self.place(q, s)
3689    }
3690
3691    fn place(&self, q: [f64; 2], s: f64) -> [f64; 2] {
3692        let (p, t, n, _) = self.pitch.frame(s);
3693        let u = q[0] - s;
3694        [p[0] + u * t[0] + q[1] * n[0], p[1] + u * t[1] + q[1] * n[1]]
3695    }
3696
3697    /// The arc length of the foot of the normal from `g` to the pitch curve
3698    /// (starting near `guess`) and the signed distance along the outward normal.
3699    fn foot(&self, g: [f64; 2], guess: f64) -> (f64, f64) {
3700        let mut sigma = guess;
3701        for _ in 0..40 {
3702            let (p, t, n, curvature) = self.pitch.frame(sigma);
3703            let v = [g[0] - p[0], g[1] - p[1]];
3704            let along = v[0] * t[0] + v[1] * t[1];
3705            let distance = v[0] * n[0] + v[1] * n[1];
3706            let step = along / (1.0 + curvature * distance);
3707            sigma += step;
3708            if step.abs() < 1e-15 * self.pitch.length() {
3709                break;
3710            }
3711        }
3712        let (p, _, n, _) = self.pitch.frame(sigma);
3713        (sigma, (g[0] - p[0]) * n[0] + (g[1] - p[1]) * n[1])
3714    }
3715}
3716
3717/// The elliptical gear section, counter-clockwise about the pivot (the focus,
3718/// at the origin). Roles per tooth k, as the spur gear's: `V<k>` root fillet,
3719/// `R<k>` flank rising to `K<k>` the tip land (normal offset of the pitch
3720/// curve), `L<k>` the falling flank, `W<k>` root fillet, `G<k>` the root land
3721/// (inward offset) of the space after tooth k.
3722pub fn elliptical_section(gear: &EllipticalGear) -> Result<GearSection, KernelRefusal> {
3723    lobed_section(gear, 1)
3724}
3725
3726/// [`elliptical_section`] on a pitch curve of `lobes` lobes about its centre ([`lobed_sizes`]); tooth 0 is
3727/// centred on +x, where the curve is nearest its axis.
3728pub fn lobed_section(gear: &EllipticalGear, lobes: usize) -> Result<GearSection, KernelRefusal> {
3729    if !(1..=8).contains(&lobes) {
3730        return Err(refuse("gear_input", format!("A lobed pitch curve has 1 to 8 lobes (not {lobes}).")));
3731    }
3732    let m = gear.module;
3733    if !(m > 0.0 && gear.face_width > 0.0 && gear.addendum > 0.0 && gear.dedendum > 0.0) {
3734        return Err(refuse("gear_input", "The module, face width, addendum and dedendum must be positive.".into()));
3735    }
3736    if !(gear.root_fillet >= 0.0 && gear.backlash >= 0.0) {
3737        return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
3738    }
3739    if !(0.0..=0.8).contains(&gear.eccentricity) {
3740        return Err(refuse("gear_input", format!("The eccentricity must be from 0 to 0.8 (it is {}).", gear.eccentricity)));
3741    }
3742    if gear.teeth < 8 || gear.teeth > 1000 {
3743        return Err(refuse("gear_input", format!("An elliptical gear needs from 8 to 1000 teeth (it has {}).", gear.teeth)));
3744    }
3745    let degrees = gear.pressure_angle.to_degrees();
3746    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&degrees) {
3747        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and 35° (it is {degrees}°).")));
3748    }
3749    let (a, e, perimeter, _) = lobed_sizes(gear, lobes);
3750    let pitch_curve = PitchEllipse::lobed(a * (1.0 - e * e), e, lobes);
3751    let rack = RollingRack { pitch: &pitch_curve };
3752    let z = gear.teeth as f64;
3753    let p = perimeter / z;
3754    let alpha = gear.pressure_angle;
3755    let (sin_a, cos_a, tan_a) = (alpha.sin(), alpha.cos(), alpha.tan());
3756    let h_a = gear.addendum * m;
3757    let h_f = gear.dedendum * m;
3758    let rho = gear.root_fillet * m;
3759    let tolerance = GEAR_FIT_TOLERANCE * m;
3760    // The sharpest point of the ellipse is its major vertex: radius b²/a.
3761    // The sharpest point's radius of curvature: the ellipse's major vertex b²/a; with lobes, read off the curve
3762    // (which must be convex for a rack to roll round it).
3763    let min_radius = if lobes == 1 {
3764        a * (1.0 - e * e)
3765    } else {
3766        let mut least = f64::INFINITY;
3767        for i in 0..4096 {
3768            let (_, d1, d2) = pitch_curve.derivatives(TAU * i as f64 / 4096.0);
3769            let cross = d1[0] * d2[1] - d1[1] * d2[0];
3770            if !(cross > 0.0) {
3771                return Err(refuse("not_convex", format!("The {lobes}-lobe pitch curve is not convex at this eccentricity ({e}): a rack cannot roll round it; lower the eccentricity.")));
3772            }
3773            least = least.min(d1[0].hypot(d1[1]).powi(3) / cross);
3774        }
3775        least
3776    };
3777    if h_f >= min_radius {
3778        return Err(refuse(
3779            "undercut",
3780            format!("The root would fold at the ellipse's ends (radius of curvature {min_radius:.4} there): add teeth or lower the eccentricity."),
3781        ));
3782    }
3783    // Cutter tooth centred on x = 0 (it cuts the space there): half width at height y is w0 + y tan α.
3784    let w0 = p / 4.0 + gear.backlash / 2.0;
3785    let centre_y = -h_f + rho;
3786    let centre_x = -w0 - (centre_y - rho * sin_a) * tan_a + rho * cos_a; // low-side fillet centre
3787    if centre_x >= 0.0 {
3788        return Err(refuse("root_fillet_too_large", "The root fillet is larger than fits the tooth space; lower it.".into()));
3789    }
3790    let y_join = centre_y - rho * sin_a;
3791    let low_flank = |c: f64, y: f64| rack.envelope([c - w0 - y * tan_a, y], [cos_a, sin_a]);
3792    let high_flank = |c: f64, y: f64| rack.envelope([c + w0 + y * tan_a, y], [-cos_a, sin_a]);
3793    // ψ ∈ [0, 1]: from the flank tangency (0) to the tip line (1).
3794    let fillet_normal = |t: f64| {
3795        let psi = -PI + alpha + t * (PI / 2.0 - alpha);
3796        [psi.cos(), psi.sin()]
3797    };
3798    let low_fillet = |c: f64, t: f64| {
3799        let n = fillet_normal(t);
3800        if rho == 0.0 {
3801            return rack.envelope([c + centre_x, centre_y], n);
3802        }
3803        rack.envelope([c + centre_x + rho * n[0], centre_y + rho * n[1]], n)
3804    };
3805    let high_fillet = |c: f64, t: f64| {
3806        let n = fillet_normal(t);
3807        if rho == 0.0 {
3808            return rack.envelope([c - centre_x, centre_y], [-n[0], n[1]]);
3809        }
3810        rack.envelope([c - centre_x - rho * n[0], centre_y + rho * n[1]], [-n[0], n[1]])
3811    };
3812    let root = |x: f64| rack.place([x, -h_f], x);
3813    let tip = |sigma: f64| {
3814        let (q, _, n, _) = pitch_curve.frame(sigma);
3815        [q[0] + h_a * n[0], q[1] + h_a * n[1]]
3816    };
3817    // The generated flank is regular while sin²α + y κ > 0 down to its foot (it cusps
3818    // where the rack flank passes the point of interference); κ is largest, 1 / min_radius,
3819    // at the major vertices.
3820    if sin_a * sin_a + y_join / min_radius <= 1e-9 {
3821        return Err(refuse(
3822            "undercut",
3823            format!(
3824                "The teeth would be undercut where the ellipse is sharpest (radius of curvature {min_radius:.4}): add teeth, lower the eccentricity or raise the pressure angle."
3825            ),
3826        ));
3827    }
3828    // The flank height where a generated flank reaches the tip offset (offset distance h_a).
3829    let top_of = |flank: &dyn Fn(f64) -> [f64; 2], guess: f64| -> Result<(f64, f64), KernelRefusal> {
3830        let offset = |y: f64| rack.foot(flank(y), guess).1 - h_a;
3831        let (mut lo, mut hi) = (y_join, h_a + 2.0 * m);
3832        if !(offset(lo) < 0.0 && offset(hi) > 0.0) {
3833            return Err(refuse("gear_fit", "The generated flank does not reach the tip curve.".into()));
3834        }
3835        // Until the interval stops shrinking (about 55 halvings), not a fixed 200 evaluations.
3836        for _ in 0..200 {
3837            let mid = 0.5 * (lo + hi);
3838            if !(mid > lo && mid < hi) {
3839                break;
3840            }
3841            if offset(mid) < 0.0 { lo = mid } else { hi = mid }
3842        }
3843        let y = 0.5 * (lo + hi);
3844        Ok((y, rack.foot(flank(y), guess).0))
3845    };
3846    let mut curves = Vec::with_capacity(6 * gear.teeth);
3847    let reversed = |curve: NurbsCurve| curve.reversed().map_err(|error| refuse("gear_fit", error));
3848    for k in 0..gear.teeth {
3849        let before = (k as f64 - 0.5) * p; // the space before tooth k
3850        let after = (k as f64 + 0.5) * p;
3851        let rising = |y: f64| high_flank(before, y);
3852        let falling = |y: f64| low_flank(after, y);
3853        let (y_rise, sigma_rise) = top_of(&rising, k as f64 * p - w0)?;
3854        let (y_fall, sigma_fall) = top_of(&falling, k as f64 * p + w0)?;
3855        if sigma_fall - sigma_rise <= 1e-6 * m {
3856            return Err(refuse("pointed_tip", "The teeth come to a point below the tip curve: reduce the addendum or the backlash.".into()));
3857        }
3858        curves.push(SectionCurve { curve: reversed(fit_planar(&|t| high_fillet(before, t), 0.0, 1.0, tolerance)?)?, role: "V", tooth: k });
3859        curves.push(SectionCurve { curve: fit_planar(&rising, y_join, y_rise, tolerance)?, role: "R", tooth: k });
3860        curves.push(SectionCurve { curve: fit_planar(&tip, sigma_rise, sigma_fall, tolerance)?, role: "K", tooth: k });
3861        curves.push(SectionCurve { curve: reversed(fit_planar(&falling, y_join, y_fall, tolerance)?)?, role: "L", tooth: k });
3862        curves.push(SectionCurve { curve: fit_planar(&|t| low_fillet(after, t), 0.0, 1.0, tolerance)?, role: "W", tooth: k });
3863        if centre_x < -1e-9 * m {
3864            curves.push(SectionCurve { curve: fit_planar(&root, after + centre_x, after - centre_x, tolerance)?, role: "G", tooth: k });
3865        }
3866    }
3867    snap_junctions(&mut curves);
3868    let samples = 4096;
3869    let (mut tip_max, mut root_min) = (0.0_f64, f64::INFINITY);
3870    for i in 0..samples {
3871        let s = perimeter * i as f64 / samples as f64;
3872        tip_max = tip_max.max(radius_of(tip(s)));
3873        root_min = root_min.min(radius_of(rack.place([s, -h_f], s)));
3874    }
3875    let data = GearData {
3876        pitch_diameter: perimeter / PI,
3877        tip_diameter: 2.0 * tip_max,
3878        root_diameter: 2.0 * root_min,
3879        tooth_thickness: p / 2.0 - gear.backlash,
3880        ..GearData::default()
3881    };
3882    Ok(GearSection { curves, data })
3883}
3884
3885/// An elliptical gear solid: the section extruded along +z by the face width;
3886/// names as the section's roles, then `F` and `B`.
3887pub fn elliptical_solid(gear: &EllipticalGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
3888    lobed_solid(gear, 1)
3889}
3890
3891/// A lobed non-circular gear solid ([`lobed_section`] extruded by the face width), names as the elliptical gear's.
3892pub fn lobed_solid(gear: &EllipticalGear, lobes: usize) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
3893    let section = lobed_section(gear, lobes)?;
3894    let solid = extrude_section(&section, gear.face_width)?;
3895    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
3896    names.push("F".into());
3897    names.push("B".into());
3898    Ok((solid, names, section.data))
3899}
3900
3901/// The parameter breaks (normalised to [0, 1]) at which [`fit_planar`] would
3902/// split `f` on `[a, b]` to fit it within `tolerance`.
3903fn adaptive_breaks(f: &dyn Fn(f64) -> [f64; 2], tolerance: f64) -> Result<Vec<f64>, KernelRefusal> {
3904    let mut breaks = vec![0.0];
3905    let mut pending: Vec<(f64, f64, usize)> = (0..4).rev().map(|i| (i as f64 / 4.0, (i + 1) as f64 / 4.0, 0)).collect();
3906    while let Some((t0, t1, depth)) = pending.pop() {
3907        if hermite_span_error(f, t0, t1) > tolerance {
3908            if depth >= 16 {
3909                return Err(refuse("gear_fit", format!("gear curve fit did not converge on [{t0}, {t1}]")));
3910            }
3911            let mid = 0.5 * (t0 + t1);
3912            pending.push((mid, t1, depth + 1));
3913            pending.push((t0, mid, depth + 1));
3914        } else {
3915            breaks.push(t1);
3916        }
3917    }
3918    Ok(breaks)
3919}
3920
3921/// Merge `fresh` breaks into `breaks` role by role (both are dyadic, so the union refines each
3922/// shared set only where the fresh one is finer). Returns whether any break was added.
3923fn merge_breaks(breaks: &mut [Vec<f64>], fresh: Vec<Vec<f64>>) -> bool {
3924    let mut added = false;
3925    for (role_breaks, more) in breaks.iter_mut().zip(fresh) {
3926        let before = role_breaks.len();
3927        role_breaks.extend(more);
3928        role_breaks.sort_by(f64::total_cmp);
3929        role_breaks.dedup_by(|x, y| (*x - *y).abs() < 1e-12);
3930        added |= role_breaks.len() > before;
3931    }
3932    added
3933}
3934
3935/// Halve every span of every role (the fallback when a plane's own breaks add nothing).
3936fn halve_breaks(breaks: &mut [Vec<f64>]) {
3937    for role_breaks in breaks.iter_mut() {
3938        let mut finer = Vec::with_capacity(2 * role_breaks.len());
3939        for pair in role_breaks.windows(2) {
3940            finer.push(pair[0]);
3941            finer.push(0.5 * (pair[0] + pair[1]));
3942        }
3943        finer.push(1.0);
3944        *role_breaks = finer;
3945    }
3946}
3947
3948/// The cubic Hermite span of `f` on `[t0, t1]` (numeric end derivatives) as Bézier points.
3949fn hermite_span(f: &dyn Fn(f64) -> [f64; 2], t0: f64, t1: f64) -> [[f64; 2]; 4] {
3950    let derivative = |t: f64| {
3951        let h = 1e-6;
3952        let (p, q) = (f(t + h), f(t - h));
3953        [(p[0] - q[0]) / (2.0 * h), (p[1] - q[1]) / (2.0 * h)]
3954    };
3955    let (p0, p1) = (f(t0), f(t1));
3956    let (d0, d1) = (derivative(t0), derivative(t1));
3957    let k = (t1 - t0) / 3.0;
3958    [p0, [p0[0] + d0[0] * k, p0[1] + d0[1] * k], [p1[0] - d1[0] * k, p1[1] - d1[1] * k], p1]
3959}
3960
3961fn hermite_span_error(f: &dyn Fn(f64) -> [f64; 2], t0: f64, t1: f64) -> f64 {
3962    let c = hermite_span(f, t0, t1);
3963    [0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
3964        .iter()
3965        .map(|&u| {
3966            let exact = f(t0 + (t1 - t0) * u);
3967            let v = 1.0 - u;
3968            let w = [v * v * v, 3.0 * v * v * u, 3.0 * v * u * u, u * u * u];
3969            let x = w[0] * c[0][0] + w[1] * c[1][0] + w[2] * c[2][0] + w[3] * c[3][0];
3970            let y = w[0] * c[0][1] + w[1] * c[1][1] + w[2] * c[2][1] + w[3] * c[3][1];
3971            (exact[0] - x).hypot(exact[1] - y)
3972        })
3973        .fold(0.0, f64::max)
3974}
3975
3976/// `f` on [0, 1] as C1 cubic Hermite spans at the given breaks (as
3977/// [`fit_planar`] lays them out), and its worst error over the spans.
3978fn fit_on_breaks(f: &dyn Fn(f64) -> [f64; 2], breaks: &[f64]) -> Result<(NurbsCurve, f64), KernelRefusal> {
3979    let to_point = |p: [f64; 2]| Vec4::from_point(Vec3::new(p[0], p[1], 0.0), 1.0);
3980    let mut knots = vec![0.0; 4];
3981    let mut points = Vec::with_capacity(2 * breaks.len() + 2);
3982    let mut worst = 0.0_f64;
3983    let spans = breaks.len() - 1;
3984    for index in 0..spans {
3985        let (t0, t1) = (breaks[index], breaks[index + 1]);
3986        let c = hermite_span(f, t0, t1);
3987        worst = worst.max(hermite_span_error(f, t0, t1));
3988        if index == 0 {
3989            points.push(to_point(c[0]));
3990        }
3991        points.push(to_point(c[1]));
3992        points.push(to_point(c[2]));
3993        if index + 1 < spans {
3994            knots.extend([t1, t1]);
3995        } else {
3996            points.push(to_point(c[3]));
3997        }
3998    }
3999    knots.extend([1.0; 4]);
4000    Ok((NurbsCurve::new(3, knots, points).map_err(|error| refuse("gear_fit", error))?, worst))
4001}
4002
4003/// A throated (single-enveloping) worm wheel: the teeth are cut as a hob of
4004/// the mating ZA worm cuts them, the worm's thread swept by the generating
4005/// motion (the worm turning, the wheel turning with it at the gear ratio).
4006/// In every plane across the face width the worm's thread section moves as a
4007/// rack and the wheel section is its envelope; the flanks, tips (the throat,
4008/// a torus about the worm's axis) and roots are skinned through those
4009/// sections. Front face on z = 0, back face on z = face width; the worm's
4010/// axis runs along +y at x = centre distance, z = face width / 2.
4011#[derive(Clone, Debug)]
4012pub struct WormWheel {
4013    /// The mating worm (its length is not used).
4014    pub worm: Worm,
4015    pub teeth: usize,
4016    /// Wheel addendum × module, in the mid-plane (the throat).
4017    pub addendum: f64,
4018    /// Wheel dedendum × module, in the mid-plane: the hob's tip (the worm's tip plus the clearance).
4019    pub dedendum: f64,
4020    pub face_width: f64,
4021    /// Axial backlash: the hob's thread is that much thicker than the worm's.
4022    pub backlash: f64,
4023}
4024
4025/// The worm wheel's sizes: (pitch radius, centre distance, throat radius in the mid-plane, outside radius at the faces).
4026pub fn worm_wheel_sizes(wheel: &WormWheel) -> (f64, f64, f64, f64) {
4027    let m = wheel.worm.axial_module;
4028    let r2 = m * wheel.teeth as f64 / 2.0;
4029    let a = r2 + wheel.worm.reference_diameter / 2.0;
4030    let throat = r2 + wheel.addendum * m;
4031    let tube = a - throat;
4032    let half = wheel.face_width / 2.0;
4033    (r2, a, throat, a - (tube * tube - half * half).max(0.0).sqrt())
4034}
4035
4036/// One plane z = c (from the mid-plane) of the wheel: the hob section as a rack.
4037struct WheelPlane<'a> {
4038    wheel: &'a WormWheel,
4039    c: f64,
4040    r2: f64,
4041    a: f64,
4042    /// The hob's tip radius about the worm axis.
4043    rho_tip: f64,
4044    /// The wheel's tip (throat) radius in this plane.
4045    r_tip: f64,
4046    /// Flank parameters (radius about the worm axis) where each flank reaches the tip: [- side, + side].
4047    rho_clip: [f64; 2],
4048}
4049
4050impl<'a> WheelPlane<'a> {
4051    fn new(wheel: &'a WormWheel, c: f64) -> Result<Self, KernelRefusal> {
4052        let m = wheel.worm.axial_module;
4053        let (r2, a, throat, _) = worm_wheel_sizes(wheel);
4054        let rho_tip = a - (r2 - wheel.dedendum * m);
4055        let tube = a - throat;
4056        let r_tip = a - (tube * tube - c * c).sqrt();
4057        let mut plane = Self { wheel, c, r2, a, rho_tip, r_tip, rho_clip: [0.0; 2] };
4058        for (index, side) in [-1.0, 1.0].into_iter().enumerate() {
4059            // The generated flank falls from above the tip to the root. A hob point with rho under the throat's
4060            // tube radius sits beyond the throat (x = a - sqrt(rho^2 - c^2) > r_tip), and so does its envelope.
4061            let (mut lo, mut hi) = (0.5 * (c.abs() + tube), rho_tip);
4062            if !(radius_of(plane.flank(side, lo)) > r_tip && radius_of(plane.flank(side, hi)) < r_tip) {
4063                return Err(refuse("gear_fit", "A worm wheel flank does not reach its throat.".into()));
4064            }
4065            for _ in 0..200 {
4066                let mid = 0.5 * (lo + hi);
4067                if !(mid > lo && mid < hi) {
4068                    break;
4069                }
4070                if radius_of(plane.flank(side, mid)) > r_tip { lo = mid } else { hi = mid }
4071            }
4072            plane.rho_clip[index] = 0.5 * (lo + hi);
4073        }
4074        Ok(plane)
4075    }
4076
4077    /// The hob flank point (radial x from the wheel axis, y along the worm axis) at radius `rho`
4078    /// about the worm axis, on the `side` (±1) of the thread centred on y = 0.
4079    fn hob(&self, side: f64, rho: f64) -> [f64; 2] {
4080        let worm = &self.wheel.worm;
4081        let hand = if worm.hand == Hand::Right { 1.0 } else { -1.0 };
4082        let thickness = worm.axial_thickness(rho) + self.wheel.backlash;
4083        let angle = (self.c / rho).clamp(-1.0, 1.0).asin();
4084        [self.a - (rho * rho - self.c * self.c).max(0.0).sqrt(), side * thickness / 2.0 + hand * worm.lead() * angle / TAU]
4085    }
4086
4087    fn hob_normal(&self, side: f64, rho: f64) -> [f64; 2] {
4088        // d/drho of hob(): x = a - sqrt(rho^2 - c^2), y = side t(rho) / 2 + hand L asin(c / rho) / 2 pi (exact:
4089        // a difference quotient's rounding noise is magnified by the fits' own derivative steps).
4090        let worm = &self.wheel.worm;
4091        let hand = if worm.hand == Hand::Right { 1.0 } else { -1.0 };
4092        let root = (rho * rho - self.c * self.c).max(1e-300).sqrt();
4093        let t = [-rho / root, -side * worm.pressure_angle.tan() - hand * worm.lead() * self.c / (TAU * rho * root)];
4094        let length = t[0].hypot(t[1]);
4095        // Outward of the thread: +y on the + side.
4096        let n = [-t[1] / length, t[0] / length];
4097        if n[1] * side >= 0.0 { n } else { [-n[0], -n[1]] }
4098    }
4099
4100    /// The wheel point generated by the hob point `q` with normal `n` (rolling at the pitch radius).
4101    fn envelope(&self, q: [f64; 2], n: [f64; 2]) -> [f64; 2] {
4102        let s = (q[0] - self.r2) * n[1] / n[0] - q[1];
4103        rotate([q[0], q[1] + s], -s / self.r2)
4104    }
4105
4106    fn flank(&self, side: f64, rho: f64) -> [f64; 2] {
4107        self.envelope(self.hob(side, rho), self.hob_normal(side, rho))
4108    }
4109
4110    /// The root fillet the hob's sharp tip corner traces, `t` from the flank (0) to the tip land (1).
4111    fn fillet(&self, side: f64, t: f64) -> [f64; 2] {
4112        let n = self.hob_normal(side, self.rho_tip);
4113        let from = n[1].atan2(n[0]);
4114        let psi = from + t * (side * PI - from);
4115        self.envelope(self.hob(side, self.rho_tip), [psi.cos(), psi.sin()])
4116    }
4117
4118    /// The six pieces of tooth 0 on normalised parameters, in section order V, R, K, L, W, G.
4119    fn piece(&self, role: usize, t: f64) -> [f64; 2] {
4120        let tau = TAU / self.wheel.teeth as f64;
4121        let half = tau / 2.0;
4122        let turn = |p: [f64; 2], angle: f64| rotate(p, angle);
4123        let root_r = self.a - (self.rho_tip * self.rho_tip - self.c * self.c).sqrt();
4124        match role {
4125            0 => turn(self.fillet(1.0, 1.0 - t), -half),
4126            1 => turn(self.flank(1.0, self.rho_tip + t * (self.rho_clip[1] - self.rho_tip)), -half),
4127            2 => {
4128                let from = polar_angle(self.flank(1.0, self.rho_clip[1]));
4129                let to = tau + polar_angle(self.flank(-1.0, self.rho_clip[0]));
4130                let angle = from + t * (to - from) - half;
4131                [self.r_tip * angle.cos(), self.r_tip * angle.sin()]
4132            }
4133            3 => turn(self.flank(-1.0, self.rho_clip[0] + t * (self.rho_tip - self.rho_clip[0])), half),
4134            4 => turn(self.fillet(-1.0, t), half),
4135            _ => {
4136                // The root land of the space after the tooth (the base space turned by tau, then by -half).
4137                let from = polar_angle(self.fillet(-1.0, 1.0));
4138                let to = polar_angle(self.fillet(1.0, 1.0));
4139                let angle = from + t * (to - from) + half;
4140                [root_r * angle.cos(), root_r * angle.sin()]
4141            }
4142        }
4143    }
4144
4145    /// Refuse a plane whose teeth are pointed, whose roots meet, or whose flanks are undercut.
4146    fn check(&self) -> Result<(), KernelRefusal> {
4147        let m = self.wheel.worm.axial_module;
4148        let tau = TAU / self.wheel.teeth as f64;
4149        let tip_span = tau + polar_angle(self.flank(-1.0, self.rho_clip[0])) - polar_angle(self.flank(1.0, self.rho_clip[1]));
4150        if tip_span * self.r_tip <= 1e-6 * m {
4151            return Err(refuse("pointed_tip", format!("The wheel teeth come to a point below the throat {:.4} from the mid-plane: lower the addendum or the face width.", self.c)));
4152        }
4153        let root_span = polar_angle(self.fillet(1.0, 1.0)) - polar_angle(self.fillet(-1.0, 1.0));
4154        if root_span <= 1e-9 {
4155            return Err(refuse("teeth_overlap", "The worm thread is wider than the wheel's tooth space at the root: lower the dedendum.".into()));
4156        }
4157        // Each flank must fall steadily from its tip to its root, and the corner's trace must not cross it.
4158        for side in [-1.0, 1.0] {
4159            let index = if side < 0.0 { 0 } else { 1 };
4160            let flank: Vec<[f64; 2]> = (0..=96).map(|i| self.flank(side, self.rho_clip[index] + (self.rho_tip - self.rho_clip[index]) * i as f64 / 96.0)).collect();
4161            let fillet: Vec<[f64; 2]> = (0..=48).map(|i| self.fillet(side, i as f64 / 48.0)).collect();
4162            let falling = flank.windows(2).all(|pair| radius_of(pair[1]) < radius_of(pair[0]));
4163            let crosses = flank[..flank.len() - 2].windows(2).any(|f| fillet[1..].windows(2).any(|g| segments_cross(f[0], f[1], g[0], g[1])));
4164            if !falling || crosses {
4165                return Err(refuse(
4166                    "undercut",
4167                    format!("The worm undercuts the wheel teeth {:.4} from the mid-plane: add wheel teeth, narrow the face width or raise the pressure angle.", self.c),
4168                ));
4169            }
4170        }
4171        Ok(())
4172    }
4173}
4174
4175fn segments_cross(a: [f64; 2], b: [f64; 2], c: [f64; 2], d: [f64; 2]) -> bool {
4176    let cross = |o: [f64; 2], p: [f64; 2], q: [f64; 2]| (p[0] - o[0]) * (q[1] - o[1]) - (p[1] - o[1]) * (q[0] - o[0]);
4177    let (d1, d2) = (cross(c, d, a), cross(c, d, b));
4178    let (d3, d4) = (cross(a, b, c), cross(a, b, d));
4179    d1 * d2 < 0.0 && d3 * d4 < 0.0
4180}
4181
4182const WHEEL_ROLES: [&str; 6] = ["V", "R", "K", "L", "W", "G"];
4183
4184/// Tooth 0's six curves in the plane `c`, fitted on the shared breaks, at height z.
4185fn wheel_tooth(plane: &WheelPlane, breaks: &[Vec<f64>], z: f64) -> Result<(Vec<NurbsCurve>, f64), KernelRefusal> {
4186    let mut curves = Vec::with_capacity(6);
4187    let mut worst = 0.0_f64;
4188    for (role, role_breaks) in breaks.iter().enumerate() {
4189        let (mut curve, error) = fit_on_breaks(&|t| plane.piece(role, t), role_breaks)?;
4190        worst = worst.max(error);
4191        for p in &mut curve.control_points {
4192            p.z = z * p.w;
4193        }
4194        curves.push(curve);
4195    }
4196    Ok((curves, worst))
4197}
4198
4199/// The full section (every tooth) from tooth 0's curves, junctions shared.
4200fn wheel_section(tooth: &[NurbsCurve], teeth: usize) -> Vec<SectionCurve> {
4201    let tau = TAU / teeth as f64;
4202    let mut curves = Vec::with_capacity(6 * teeth);
4203    for index in 0..teeth {
4204        for (role, curve) in tooth.iter().enumerate() {
4205            curves.push(SectionCurve { curve: rotated(curve, tau * index as f64), role: WHEEL_ROLES[role], tooth: index });
4206        }
4207    }
4208    snap_junctions(&mut curves);
4209    curves
4210}
4211
4212/// A throated worm wheel solid and its data; face names as the spur gear's
4213/// per tooth (`V/R/K/L/W/G<n>`, the `K` faces making the throat), then `F` (z = 0) and `B`.
4214pub fn worm_wheel_solid(wheel: &WormWheel) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
4215    let worm = &wheel.worm;
4216    let m = worm.axial_module;
4217    worm_section(worm)?; // the worm's own checks
4218    if wheel.teeth < 12 || wheel.teeth > 400 {
4219        return Err(refuse("gear_input", format!("A worm wheel needs from 12 to 400 teeth (it has {}).", wheel.teeth)));
4220    }
4221    if !(wheel.addendum > 0.0 && wheel.dedendum > 0.0 && wheel.face_width > 0.0 && wheel.backlash >= 0.0) {
4222        return Err(refuse("gear_input", "The wheel's addendum, dedendum and face width must be positive, the backlash not negative.".into()));
4223    }
4224    let (r2, a, throat, _) = worm_wheel_sizes(wheel);
4225    let tube = a - throat;
4226    let limit = 0.9 * tube;
4227    if wheel.face_width / 2.0 > limit {
4228        return Err(refuse(
4229            "face_too_wide",
4230            format!("The face width ({}) must stay inside the throat: at most {:.4} for this worm.", wheel.face_width, 2.0 * limit),
4231        ));
4232    }
4233    // The hob's thread at the wheel's tip (in the mid-plane) must leave a tooth in the axial pitch. Checked
4234    // here, before any polar angle: a thread a whole pitch wider wraps round to the same teeth.
4235    if worm.axial_thickness(tube) + wheel.backlash >= PI * m - 1e-6 * m {
4236        return Err(refuse("pointed_tip", format!("The backlash ({}) leaves no wheel tooth: the hob's thread fills the whole axial pitch at the throat.", wheel.backlash)));
4237    }
4238    if worm.axial_thickness(a - (r2 - wheel.dedendum * m)) + wheel.backlash <= 1e-6 * m {
4239        return Err(refuse("pointed_tip", "The hob's thread (the worm's, grown to the wheel's root) comes to a point: lower the wheel dedendum.".into()));
4240    }
4241    let half = wheel.face_width / 2.0;
4242    let tolerance = GEAR_GENERATED_TOLERANCE * GENERATED_SECTION_SHARE * m;
4243    let skin_tolerance = GEAR_GENERATED_TOLERANCE * (1.0 - GENERATED_SECTION_SHARE) * m;
4244    // Shared breaks per role from the mid-plane and both faces.
4245    let probe: Vec<WheelPlane> = [-half, 0.0, half].iter().map(|&c| WheelPlane::new(wheel, c)).collect::<Result<_, _>>()?;
4246    for plane in &probe {
4247        plane.check()?;
4248    }
4249    let mut breaks: Vec<Vec<f64>> = Vec::with_capacity(6);
4250    for role in 0..6 {
4251        let mut all: Vec<f64> = Vec::new();
4252        for plane in &probe {
4253            all.extend(adaptive_breaks(&|t| plane.piece(role, t), tolerance)?);
4254        }
4255        all.sort_by(f64::total_cmp);
4256        all.dedup_by(|x, y| (*x - *y).abs() < 1e-12);
4257        breaks.push(all);
4258    }
4259    // Planes across the face; each plane's control points carried along v by
4260    // cubic Hermite spans (derivatives from planes a step either side).
4261    let mut planes = 8usize;
4262    loop {
4263        let step = wheel.face_width / planes as f64;
4264        let delta = 1e-3 * step;
4265        let mut rows: Vec<Vec<NurbsCurve>> = Vec::with_capacity(planes + 1); // tooth 0 per plane
4266        let mut slopes: Vec<Vec<Vec<[f64; 2]>>> = Vec::with_capacity(planes + 1);
4267        let mut refit: Option<WheelPlane> = None;
4268        for j in 0..=planes {
4269            let c = -half + step * j as f64;
4270            let plane = WheelPlane::new(wheel, c)?;
4271            plane.check()?;
4272            let (tooth, worst) = wheel_tooth(&plane, &breaks, c + half)?;
4273            if worst > tolerance {
4274                refit = Some(plane);
4275                break;
4276            }
4277            let lo = wheel_tooth(&WheelPlane::new(wheel, c - delta)?, &breaks, 0.0)?.0;
4278            let hi = wheel_tooth(&WheelPlane::new(wheel, c + delta)?, &breaks, 0.0)?.0;
4279            let slope: Vec<Vec<[f64; 2]>> = lo
4280                .iter()
4281                .zip(&hi)
4282                .map(|(l, h)| l.control_points.iter().zip(&h.control_points).map(|(p, q)| [(q.x - p.x) / (2.0 * delta), (q.y - p.y) / (2.0 * delta)]).collect())
4283                .collect();
4284            rows.push(tooth);
4285            slopes.push(slope);
4286        }
4287        if let Some(plane) = refit {
4288            // A plane the shared breaks fit too loosely: add that plane's own breaks (refining only the spans
4289            // it needs), else halve every span, and start over.
4290            let fresh = (0..6).map(|role| adaptive_breaks(&|t| plane.piece(role, t), tolerance)).collect::<Result<Vec<_>, _>>()?;
4291            if !merge_breaks(&mut breaks, fresh) {
4292                halve_breaks(&mut breaks);
4293            }
4294            continue;
4295        }
4296        // Check the skin halfway between planes against the exact plane there.
4297        let mut worst = 0.0_f64;
4298        for j in 0..planes {
4299            let c = -half + step * (j as f64 + 0.5);
4300            let exact = wheel_tooth(&WheelPlane::new(wheel, c)?, &breaks, 0.0)?.0;
4301            for role in 0..6 {
4302                for (k, p) in exact[role].control_points.iter().enumerate() {
4303                    let (p0, p1) = (rows[j][role].control_points[k], rows[j + 1][role].control_points[k]);
4304                    let (d0, d1) = (slopes[j][role][k], slopes[j + 1][role][k]);
4305                    let x = 0.5 * (p0.x + p1.x) + step * (d0[0] - d1[0]) / 8.0;
4306                    let y = 0.5 * (p0.y + p1.y) + step * (d0[1] - d1[1]) / 8.0;
4307                    worst = worst.max((x - p.x).hypot(y - p.y));
4308                }
4309            }
4310        }
4311        if worst > skin_tolerance {
4312            if planes >= 256 {
4313                return Err(refuse("gear_fit", format!("The worm wheel's flanks could not be skinned within {skin_tolerance:.2e} ({worst:.2e}).")));
4314            }
4315            // The skin's error falls as the fourth power of the plane spacing: go straight to the count that
4316            // reading predicts (with a margin), not plane-count doubling by doubling.
4317            let factor = (1.15 * (worst / skin_tolerance).powf(0.25)).max(2.0);
4318            planes = (planes as f64 * factor).ceil().min(256.0) as usize;
4319            continue;
4320        }
4321        // Rows along v for every control point of the full bottom section, keyed by its bits.
4322        // Tooth 0's section with its junctions shared; every tooth's rows are tooth 0's turned.
4323        let first = wheel_section(&rows[0], wheel.teeth);
4324        let tau = TAU / wheel.teeth as f64;
4325        let mut table: std::collections::HashMap<[u64; 4], Vec<Vec4>> = std::collections::HashMap::new();
4326        let h = 1.0 / planes as f64;
4327        for (index, piece) in first.iter().enumerate() {
4328            let (role, tooth) = (index % 6, index / 6);
4329            let (s, cs) = (tau * tooth as f64).sin_cos();
4330            for (k, p) in piece.curve.control_points.iter().enumerate() {
4331                let mut row = Vec::with_capacity(3 * planes + 1);
4332                for j in 0..=planes {
4333                    let q = if j == 0 { piece.curve.control_points[k] } else { let p = rows[j][role].control_points[k]; Vec4 { x: cs * p.x - s * p.y, y: s * p.x + cs * p.y, z: p.z, w: p.w } };
4334                    let d = slopes[j][role][k];
4335                    // The slope in v (per unit v: face width per unit c), turned with the tooth.
4336                    let dv = [wheel.face_width * (cs * d[0] - s * d[1]), wheel.face_width * (s * d[0] + cs * d[1]), wheel.face_width];
4337                    let point = Vec3::new(q.x, q.y, q.z);
4338                    if j > 0 {
4339                        row.push(Vec4::from_point(Vec3::new(point.x - dv[0] * h / 3.0, point.y - dv[1] * h / 3.0, point.z - dv[2] * h / 3.0), 1.0));
4340                    }
4341                    if j == 0 || j == planes {
4342                        row.push(Vec4::from_point(point, 1.0));
4343                    }
4344                    if j < planes {
4345                        row.push(Vec4::from_point(Vec3::new(point.x + dv[0] * h / 3.0, point.y + dv[1] * h / 3.0, point.z + dv[2] * h / 3.0), 1.0));
4346                    }
4347                }
4348                table.insert([p.x.to_bits(), p.y.to_bits(), p.z.to_bits(), p.w.to_bits()], row);
4349            }
4350        }
4351        let mut knots_v = vec![0.0; 4];
4352        for j in 1..planes {
4353            let v = j as f64 * h;
4354            knots_v.extend([v, v]);
4355        }
4356        knots_v.extend([1.0; 4]);
4357        let section = GearSection { curves: first.clone(), data: GearData::default() };
4358        let solid = prism_by_rows(&section, 3, &knots_v, &|p: Vec4| {
4359            table.get(&[p.x.to_bits(), p.y.to_bits(), p.z.to_bits(), p.w.to_bits()]).cloned().expect("a row for every section control point")
4360        })?;
4361        let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
4362        names.push("F".into());
4363        names.push("B".into());
4364        let data = GearData {
4365            pitch_diameter: 2.0 * r2,
4366            tip_diameter: 2.0 * throat,
4367            root_diameter: 2.0 * (r2 - wheel.dedendum * m),
4368            tip_thickness: 0.0,
4369            ..GearData::default()
4370        };
4371        return Ok((solid, names, data));
4372    }
4373}
4374
4375/// A crown (face) gear: teeth on the flat face of a disc, for a spur pinion
4376/// whose axis lies parallel to that face and meets the crown's axis (90°
4377/// shaft angle). The teeth are cut as a shaper cuts them: a spur shaper with
4378/// `shaper_extra` more teeth than the pinion turns about the pinion's axis
4379/// while the crown turns with it at the tooth ratio, and the tooth spaces are
4380/// the volume its teeth sweep. The shaper's flanks are involutes and its tips
4381/// are rounded (0.2 × module, less on a thin tooth) and flat between the rounds, so every
4382/// face of a tooth space (root land, fillets, flanks) is the envelope of one
4383/// smooth piece of the shaper's outline. A shaper with more teeth than the
4384/// pinion touches it at a point rather than along a line, which keeps the
4385/// pair's contact clear of the tooth ends.
4386///
4387/// The crown's axis is +z; its back face is z = 0, the root plane z = `rim`,
4388/// the pitch plane z = `rim` + dedendum × module and the tips the plane
4389/// above by the addendum. The pinion's axis runs along +x (through the crown
4390/// axis, so radially) at the pitch plane + the pinion's pitch radius; tooth
4391/// space 0 is centred on +x.
4392#[derive(Clone, Debug)]
4393pub struct CrownGear {
4394    pub module: f64,
4395    pub teeth: usize,
4396    /// Teeth of the mating spur pinion.
4397    pub pinion_teeth: usize,
4398    /// The shaper's teeth over the pinion's (1 to 3).
4399    pub shaper_extra: usize,
4400    pub pressure_angle: f64,
4401    /// Crown addendum × module above the pitch plane (the pinion's dedendum less the clearance).
4402    pub addendum: f64,
4403    /// Crown dedendum × module below the pitch plane: the shaper's addendum (the pinion's plus the clearance).
4404    pub dedendum: f64,
4405    /// Inner radius of the toothed ring; 0 takes the undercut limit ([`crown_limits`]).
4406    pub inner_radius: f64,
4407    /// Outer radius of the toothed ring; 0 takes the pointed-tooth limit.
4408    pub outer_radius: f64,
4409    /// Blank thickness under the root plane.
4410    pub rim: f64,
4411}
4412
4413/// The shaper's tip round, × module.
4414const CROWN_TIP_ROUND: f64 = 0.2;
4415/// The narrowest tip land the outer radius may leave, × module.
4416const CROWN_TIP_LAND: f64 = 0.05;
4417
4418/// The generating shaper in its transverse plane: (Y, H), H up from the
4419/// shaper's axis, tooth 0 pointing down (to the crown), polar angle from −H
4420/// towards +Y. Its +Y side generates the +Y wall of tooth space 0.
4421struct CrownShaper {
4422    /// Pitch, base and tip radii.
4423    rs: f64,
4424    rb: f64,
4425    ra: f64,
4426    /// Crown turn per shaper turn (shaper teeth / crown teeth).
4427    k: f64,
4428    /// Half the tooth's angle at the pitch circle plus inv(α): the flank at roll u sits at c0 − inv(α(u)).
4429    c0: f64,
4430    /// Tip round radius, its centre and the roll where it meets the involute.
4431    rr: f64,
4432    centre: [f64; 2],
4433    uj: f64,
4434    /// Polar angle of the round's centre (half the tip land's angle).
4435    bc: f64,
4436    /// Normal angles (CCW from +Y) of the round where it meets the land and the involute.
4437    psi_land: f64,
4438    psi_flank: f64,
4439}
4440
4441/// A point of the shaper's outline with its outward unit normal and its
4442/// moment about the shaper's axis (point × normal), which the generating
4443/// motion leaves unchanged.
4444#[derive(Clone, Copy)]
4445struct OutlinePoint {
4446    q: [f64; 2],
4447    n: [f64; 2],
4448    moment: f64,
4449}
4450
4451impl CrownShaper {
4452    fn new(gear: &CrownGear) -> Result<Self, KernelRefusal> {
4453        let m = gear.module;
4454        let ns = (gear.pinion_teeth + gear.shaper_extra) as f64;
4455        let alpha = gear.pressure_angle;
4456        let rs = m * ns / 2.0;
4457        let rb = rs * alpha.cos();
4458        let ra = rs + gear.dedendum * m;
4459        let c0 = PI / (2.0 * ns) + alpha.tan() - alpha;
4460        // The tip round: 0.2 × module, smaller on a thin tooth so a tip land of at least 0.02 × module stays.
4461        let mut rr = CROWN_TIP_ROUND * m;
4462        for _ in 0..12 {
4463            let shaper = Self::rounded(rs, rb, ra, ns / gear.teeth as f64, c0, rr)?;
4464            if shaper.bc * ra >= 0.01 * m {
4465                return Ok(shaper);
4466            }
4467            rr *= 0.7;
4468        }
4469        Err(refuse("shaper_tip", "The shaper's teeth come to a point before its tip: lower the dedendum or raise the shaper's teeth.".into()))
4470    }
4471
4472    fn rounded(rs: f64, rb: f64, ra: f64, k: f64, c0: f64, rr: f64) -> Result<Self, KernelRefusal> {
4473        let mut shaper = Self { rs, rb, ra, k, c0, rr, centre: [0.0; 2], uj: 0.0, bc: 0.0, psi_land: 0.0, psi_flank: 0.0 };
4474        // The round touches the tip circle (its centre on ra − rr) and the involute.
4475        let reach = |u: f64| {
4476            let p = shaper.involute(u);
4477            radius_of([p.q[0] - rr * p.n[0], p.q[1] - rr * p.n[1]])
4478        };
4479        let u_tip = ((ra / rb).powi(2) - 1.0).sqrt();
4480        let (mut lo, mut hi) = (0.0, u_tip);
4481        if !(reach(lo) < ra - rr && reach(hi) > ra - rr) {
4482            return Err(refuse("shaper_tip", "The shaper's tip round does not fit its tooth: lower the dedendum or the pressure angle.".into()));
4483        }
4484        for _ in 0..200 {
4485            let mid = 0.5 * (lo + hi);
4486            if reach(mid) < ra - rr { lo = mid } else { hi = mid }
4487        }
4488        shaper.uj = 0.5 * (lo + hi);
4489        let p = shaper.involute(shaper.uj);
4490        shaper.centre = [p.q[0] - rr * p.n[0], p.q[1] - rr * p.n[1]];
4491        shaper.bc = shaper.centre[0].atan2(-shaper.centre[1]);
4492        shaper.psi_land = shaper.centre[1].atan2(shaper.centre[0]);
4493        shaper.psi_flank = p.n[1].atan2(p.n[0]);
4494        Ok(shaper)
4495    }
4496
4497    /// The +Y flank (an involute of the base circle) at roll `u`.
4498    fn involute(&self, u: f64) -> OutlinePoint {
4499        let s = (1.0 + u * u).sqrt();
4500        let rho = self.rb * s;
4501        let beta = self.c0 - u + u.atan();
4502        let (sb, cb) = beta.sin_cos();
4503        let (e, de) = ([sb, -cb], [cb, sb]);
4504        OutlinePoint { q: [rho * e[0], rho * e[1]], n: [(u * e[0] + de[0]) / s, (u * e[1] + de[1]) / s], moment: self.rb }
4505    }
4506
4507    /// The +Y tip round at normal angle `psi`.
4508    fn round(&self, psi: f64) -> OutlinePoint {
4509        let n = [psi.cos(), psi.sin()];
4510        let c = self.centre;
4511        OutlinePoint { q: [c[0] + self.rr * n[0], c[1] + self.rr * n[1]], n, moment: c[0] * n[1] - c[1] * n[0] }
4512    }
4513
4514    /// The crown point (crown frame: X along tooth space 0, Y, height h above the pitch plane) that
4515    /// the outline point generates where the shaper's line of it crosses x (from the crown axis).
4516    fn generate(&self, p: OutlinePoint, x: f64) -> Option<[f64; 3]> {
4517        // Contact where the normal is square to the relative velocity: n·v = 0 with
4518        // v = (k y, rs − h − k x, y) gives (n rotated by φ)_Y · k x = moment.
4519        let c = p.moment / (self.k * x);
4520        if !(c.abs() <= 1.0) {
4521            return None;
4522        }
4523        let mut phi = -c.acos() - p.n[1].atan2(p.n[0]);
4524        phi = (phi + PI).rem_euclid(TAU) - PI;
4525        let q = rotate(p.q, phi);
4526        let (s, co) = (self.k * phi).sin_cos();
4527        Some([x * co + q[0] * s, -x * s + q[0] * co, self.rs + q[1]])
4528    }
4529
4530    /// The point `p` generates on the cylinder of `radius` about the crown axis: (polar angle, h).
4531    fn on_cylinder(&self, p: OutlinePoint, radius: f64) -> Option<[f64; 2]> {
4532        // The crown's turn keeps the radius: it is hypot(x, y) of the shaper's contact point.
4533        let radius_at = |x: f64| self.generate(p, x).map(|g| (g[0].hypot(g[1]), g));
4534        let mut x = radius;
4535        for _ in 0..60 {
4536            let (r, g) = radius_at(x)?;
4537            let error = r - radius;
4538            if error.abs() <= 1e-13 * radius {
4539                return Some([g[1].atan2(g[0]), g[2]]);
4540            }
4541            let dx = 1e-7 * radius;
4542            let slope = (radius_at(x + dx)?.0 - r) / dx;
4543            // Damped: a full step may leave the range where the contact exists (x < moment / k).
4544            let mut step = error / slope;
4545            let mut halvings = 0;
4546            while !(step.is_finite() && radius_at(x - step).is_some()) {
4547                step *= 0.5;
4548                halvings += 1;
4549                if !step.is_finite() || halvings > 60 {
4550                    return None;
4551                }
4552            }
4553            x -= step;
4554        }
4555        None
4556    }
4557}
4558
4559fn check_crown_input(gear: &CrownGear) -> Result<(), KernelRefusal> {
4560    let m = gear.module;
4561    if !(m > 0.0 && gear.addendum > 0.0 && gear.dedendum > 0.0 && gear.rim > 0.0) {
4562        return Err(refuse("gear_input", "The module, addendum, dedendum and rim must be positive.".into()));
4563    }
4564    // The limits search out to 4 × the pitch radius: keep every size well inside the floating-point range.
4565    let sizes = [m, gear.addendum * m, gear.dedendum * m, gear.rim, gear.inner_radius, gear.outer_radius, 4.0 * m * gear.teeth as f64];
4566    if sizes.iter().any(|v| !(v.is_finite() && v.abs() < 1e12)) {
4567        return Err(refuse("gear_input", "The crown gear's sizes must be finite and under 1e12.".into()));
4568    }
4569    if !(gear.inner_radius >= 0.0 && gear.outer_radius >= 0.0) {
4570        return Err(refuse("gear_input", "The inner and outer radii must not be negative (0 takes the limits).".into()));
4571    }
4572    if gear.pinion_teeth < 10 || gear.pinion_teeth > 100 {
4573        return Err(refuse("gear_input", format!("The pinion needs from 10 to 100 teeth (it has {}).", gear.pinion_teeth)));
4574    }
4575    if !(1..=3).contains(&gear.shaper_extra) {
4576        return Err(refuse("gear_input", format!("The shaper has 1 to 3 teeth more than the pinion (not {}).", gear.shaper_extra)));
4577    }
4578    let shaper = gear.pinion_teeth + gear.shaper_extra;
4579    if gear.teeth < 2 * shaper || gear.teeth > 600 {
4580        return Err(refuse("gear_input", format!("A crown gear needs from twice the shaper's teeth ({}) to 600 teeth (it has {}).", 2 * shaper, gear.teeth)));
4581    }
4582    let degrees = gear.pressure_angle.to_degrees();
4583    if !(14.5 - 1e-9..=30.0 + 1e-9).contains(&degrees) {
4584        return Err(refuse("gear_input", format!("The pressure angle must be from 14.5° to 30° (it is {degrees}°).")));
4585    }
4586    Ok(())
4587}
4588
4589/// One cylinder about the crown axis: tooth space 0's walls where they cross it.
4590struct CrownRing<'a> {
4591    shaper: &'a CrownShaper,
4592    radius: f64,
4593    /// The roll where the flank reaches the tips.
4594    u_tip: f64,
4595    /// Heights above the pitch plane of the tips and the root, and of the pitch plane above z = 0.
4596    tip: f64,
4597    root: f64,
4598    lift: f64,
4599}
4600
4601impl<'a> CrownRing<'a> {
4602    fn new(gear: &CrownGear, shaper: &'a CrownShaper, radius: f64, lift: f64) -> Result<Self, KernelRefusal> {
4603        let tip = gear.addendum * gear.module;
4604        let undercut = || refuse("undercut", format!("The crown's teeth are undercut at radius {radius:.4}: raise the inner radius."));
4605        let height = |u: f64| shaper.on_cylinder(shaper.involute(u), radius).map(|p| p[1]);
4606        let (Some(h0), Some(h1)) = (height(0.0), height(shaper.uj)) else {
4607            return Err(undercut());
4608        };
4609        // The flank falls from the base circle (u = 0) to the round (u = uj); the tips need it from above them.
4610        if !(h0 >= tip && h1 < tip) {
4611            return Err(undercut());
4612        }
4613        let (mut lo, mut hi) = (0.0, shaper.uj);
4614        for _ in 0..200 {
4615            let mid = 0.5 * (lo + hi);
4616            match height(mid) {
4617                Some(h) if h >= tip => lo = mid,
4618                Some(_) => hi = mid,
4619                None => return Err(undercut()),
4620            }
4621        }
4622        Ok(Self { shaper, radius, u_tip: 0.5 * (lo + hi), tip, root: shaper.rs - shaper.ra, lift })
4623    }
4624
4625    /// The five walls of tooth space 0 as (polar angle, h), in order across the space from the −θ tip to the +θ
4626    /// tip: L the −θ flank (down), W its fillet, G the root land, V the +θ fillet, R the +θ flank (up).
4627    fn polar(&self, role: usize, t: f64) -> [f64; 2] {
4628        let s = self.shaper;
4629        let at = |p: OutlinePoint| s.on_cylinder(p, self.radius).unwrap_or([f64::NAN, f64::NAN]);
4630        let fillet = |t: f64| at(s.round(s.psi_land + t * (s.psi_flank - s.psi_land)));
4631        let flank = |t: f64| at(s.involute(s.uj + t * (self.u_tip - s.uj)));
4632        let mirror = |p: [f64; 2]| [-p[0], p[1]];
4633        match role {
4634            0 => mirror(flank(1.0 - t)),
4635            1 => mirror(fillet(1.0 - t)),
4636            // The land, turned about the crown axis by k × its angle: the root land between two radial lines.
4637            2 => [s.k * s.bc * (2.0 * t - 1.0), self.root],
4638            3 => fillet(t),
4639            _ => flank(t),
4640        }
4641    }
4642
4643    fn piece(&self, role: usize, t: f64) -> [f64; 3] {
4644        let [angle, h] = self.polar(role, t);
4645        [self.radius * angle.cos(), self.radius * angle.sin(), h + self.lift]
4646    }
4647
4648    /// Refuse a ring whose walls do not rise steadily from the root to the tips.
4649    fn check(&self) -> Result<(), KernelRefusal> {
4650        for role in [3, 4] {
4651            let points: Vec<[f64; 2]> = (0..=64).map(|i| self.polar(role, i as f64 / 64.0)).collect();
4652            if points.iter().any(|p| !p[0].is_finite()) || !points.windows(2).all(|w| w[1][1] > w[0][1]) {
4653                return Err(refuse("undercut", format!("The crown's tooth space does not rise steadily at radius {:.4}: raise the inner radius.", self.radius)));
4654            }
4655        }
4656        Ok(())
4657    }
4658}
4659
4660/// The crown gear's limits: (undercut limit, pointed-tooth limit). The first is the smallest inner radius at
4661/// which the shaper's flank reaches the tips from above its base circle and every wall of the tooth space
4662/// reaches the cylinder (the flank's foot, by the round, the last); the second is the largest outer radius
4663/// that leaves a tip land of 0.05 × module.
4664pub fn crown_limits(gear: &CrownGear) -> Result<(f64, f64), KernelRefusal> {
4665    check_crown_input(gear)?;
4666    let shaper = CrownShaper::new(gear)?;
4667    let m = gear.module;
4668    let tip = gear.addendum * m;
4669    let r2 = m * gear.teeth as f64 / 2.0;
4670    let base_free = |r: f64| shaper.on_cylinder(shaper.involute(0.0), r).is_some_and(|p| p[1] >= tip);
4671    let (mut lo, mut hi) = (shaper.rb / shaper.k * (1.0 + 1e-9), 4.0 * r2);
4672    if !base_free(hi) {
4673        return Err(refuse("undercut", "The crown's tips would need the shaper's flank below its base circle at every radius: lower the addendum.".into()));
4674    }
4675    for _ in 0..200 {
4676        let mid = 0.5 * (lo + hi);
4677        if base_free(mid) { hi = mid } else { lo = mid }
4678    }
4679    // Then every wall must reach the cylinder: the flank's foot, by the round, is the last to.
4680    let walls_reach = |r: f64| base_free(r) && CrownRing::new(gear, &shaper, r, 0.0).and_then(|ring| ring.check()).is_ok();
4681    if !walls_reach(hi) {
4682        let step = 0.02 * m;
4683        let mut found = None;
4684        let mut r = hi;
4685        while r < 2.0 * r2 {
4686            r += step;
4687            if walls_reach(r) {
4688                found = Some(r);
4689                break;
4690            }
4691        }
4692        let Some(good) = found else {
4693            return Err(refuse("undercut", "The crown's tooth spaces do not reach from the root to the tips at any radius: lower the addendum or raise the pressure angle.".into()));
4694        };
4695        let (mut lo, mut top) = (good - step, good);
4696        for _ in 0..100 {
4697            let mid = 0.5 * (lo + top);
4698            if walls_reach(mid) { top = mid } else { lo = mid }
4699        }
4700        hi = top;
4701    }
4702    // A little inside, so the skin's slopes may look a step past the ring's ends.
4703    let inner = hi + 2e-3 * m;
4704    let tau = TAU / gear.teeth as f64;
4705    let land = |r: f64| -> Result<bool, KernelRefusal> {
4706        let ring = CrownRing::new(gear, &shaper, r, 0.0)?;
4707        Ok((tau - 2.0 * ring.polar(4, 1.0)[0]) * r >= CROWN_TIP_LAND * m)
4708    };
4709    let (mut lo, mut hi) = (inner, 4.0 * r2);
4710    if !land(lo)? {
4711        return Err(refuse("pointed_tip", "The crown's teeth come to a point at the undercut limit: add crown teeth or lower the addendum.".into()));
4712    }
4713    if land(hi).unwrap_or(false) {
4714        return Err(refuse("gear_input", "The crown's teeth never come to a point: check the module and tooth counts.".into()));
4715    }
4716    for _ in 0..100 {
4717        let mid = 0.5 * (lo + hi);
4718        if land(mid).unwrap_or(false) { lo = mid } else { hi = mid }
4719    }
4720    Ok((inner, lo - 2e-3 * m))
4721}
4722
4723/// The crown gear's sizes: [pitch radius, inner radius, outer radius, z of the pitch plane, z of the tips,
4724/// z of the pinion's axis], the radii resolved from the limits where 0.
4725pub fn crown_sizes(gear: &CrownGear) -> Result<[f64; 6], KernelRefusal> {
4726    let m = gear.module;
4727    let (limit_in, limit_out) = crown_limits(gear)?;
4728    let inner = if gear.inner_radius > 0.0 { gear.inner_radius } else { limit_in };
4729    let outer = if gear.outer_radius > 0.0 { gear.outer_radius } else { limit_out };
4730    if inner < limit_in - 1e-9 * m {
4731        return Err(refuse("undercut", format!("The inner radius ({inner}) is inside the undercut limit {limit_in:.4}: raise it.")));
4732    }
4733    if outer > limit_out + 1e-9 * m {
4734        return Err(refuse("pointed_tip", format!("The outer radius ({outer}) is past the pointed-tooth limit {limit_out:.4}: lower it.")));
4735    }
4736    if !(outer > inner + 0.1 * m) {
4737        return Err(refuse("gear_input", format!("The outer radius ({outer:.4}) must be beyond the inner radius ({inner:.4}).")));
4738    }
4739    let pitch = gear.rim + gear.dedendum * m;
4740    Ok([m * gear.teeth as f64 / 2.0, inner, outer, pitch, pitch + gear.addendum * m, pitch + m * gear.pinion_teeth as f64 / 2.0])
4741}
4742
4743const CROWN_ROLES: [&str; 5] = ["L", "W", "G", "V", "R"];
4744
4745/// Tooth space 0's five walls on one ring, fitted on the shared breaks, junctions shared.
4746fn crown_walls(ring: &CrownRing, breaks: &[Vec<f64>]) -> Result<(Vec<NurbsCurve>, f64), KernelRefusal> {
4747    let mut curves: Vec<NurbsCurve> = Vec::with_capacity(5);
4748    let mut worst = 0.0_f64;
4749    for (role, role_breaks) in breaks.iter().enumerate() {
4750        let (curve, error) = fit_on_breaks3(&|t| ring.piece(role, t), role_breaks)?;
4751        worst = worst.max(error);
4752        curves.push(curve);
4753    }
4754    for index in 0..4 {
4755        let start = curves[index + 1].control_points[0];
4756        let last = curves[index].control_points.len() - 1;
4757        curves[index].control_points[last] = start;
4758    }
4759    Ok((curves, worst))
4760}
4761
4762/// Tooth space 0's five wall surfaces (u across the wall in role order, v from the inner radius out), skinned
4763/// through rings until the skin holds its share of [`GEAR_GENERATED_TOLERANCE`] halfway between them.
4764fn crown_wall_surfaces(gear: &CrownGear, shaper: &CrownShaper, inner: f64, outer: f64, lift: f64) -> Result<Vec<NurbsSurface>, KernelRefusal> {
4765    let m = gear.module;
4766    // A tenth of the bound to the section fit, not a quarter: the crown's root and land walls run nearly flat,
4767    // and a fit error normal to them is what a pinion tooth sweeping by (or a check along the circle) meets
4768    // magnified many times.
4769    let tolerance = GEAR_GENERATED_TOLERANCE * CROWN_SECTION_SHARE * m;
4770    let skin_tolerance = GEAR_GENERATED_TOLERANCE * (1.0 - CROWN_SECTION_SHARE) * m;
4771    let probe: Vec<CrownRing> = [inner, 0.5 * (inner + outer), outer].iter().map(|&r| CrownRing::new(gear, shaper, r, lift)).collect::<Result<_, _>>()?;
4772    for ring in &probe {
4773        ring.check()?;
4774    }
4775    let mut breaks: Vec<Vec<f64>> = Vec::with_capacity(5);
4776    for role in 0..5 {
4777        let mut all: Vec<f64> = Vec::new();
4778        for ring in &probe {
4779            all.extend(adaptive_breaks3(&|t| ring.piece(role, t), tolerance)?);
4780        }
4781        all.sort_by(f64::total_cmp);
4782        all.dedup_by(|x, y| (*x - *y).abs() < 1e-12);
4783        breaks.push(all);
4784    }
4785    let length = outer - inner;
4786    let mut rings = 4usize;
4787    loop {
4788        let step = length / rings as f64;
4789        let delta = 1e-3 * step.min(m);
4790        let mut rows: Vec<Vec<NurbsCurve>> = Vec::with_capacity(rings + 1);
4791        let mut slopes: Vec<Vec<Vec<[f64; 3]>>> = Vec::with_capacity(rings + 1);
4792        let mut refit: Option<CrownRing> = None;
4793        for j in 0..=rings {
4794            let r = inner + step * j as f64;
4795            let ring = CrownRing::new(gear, shaper, r, lift)?;
4796            ring.check()?;
4797            let (walls, worst) = crown_walls(&ring, &breaks)?;
4798            if worst > tolerance {
4799                refit = Some(ring);
4800                break;
4801            }
4802            let lo = crown_walls(&CrownRing::new(gear, shaper, r - delta, lift)?, &breaks)?.0;
4803            let hi = crown_walls(&CrownRing::new(gear, shaper, r + delta, lift)?, &breaks)?.0;
4804            let slope: Vec<Vec<[f64; 3]>> = lo
4805                .iter()
4806                .zip(&hi)
4807                .map(|(l, h)| l.control_points.iter().zip(&h.control_points).map(|(p, q)| [(q.x - p.x) / (2.0 * delta), (q.y - p.y) / (2.0 * delta), (q.z - p.z) / (2.0 * delta)]).collect())
4808                .collect();
4809            rows.push(walls);
4810            slopes.push(slope);
4811        }
4812        if let Some(ring) = refit {
4813            // As the worm wheel: that ring's own breaks where it needs them, else every span halved.
4814            let fresh = (0..5).map(|role| adaptive_breaks3(&|t| ring.piece(role, t), tolerance)).collect::<Result<Vec<_>, _>>()?;
4815            if !merge_breaks(&mut breaks, fresh) {
4816                halve_breaks(&mut breaks);
4817            }
4818            continue;
4819        }
4820        let mut worst = 0.0_f64;
4821        for j in 0..rings {
4822            let r = inner + step * (j as f64 + 0.5);
4823            let exact = crown_walls(&CrownRing::new(gear, shaper, r, lift)?, &breaks)?.0;
4824            for role in 0..5 {
4825                for (k, p) in exact[role].control_points.iter().enumerate() {
4826                    let (p0, p1) = (rows[j][role].control_points[k], rows[j + 1][role].control_points[k]);
4827                    let (d0, d1) = (slopes[j][role][k], slopes[j + 1][role][k]);
4828                    let x = 0.5 * (p0.x + p1.x) + step * (d0[0] - d1[0]) / 8.0;
4829                    let y = 0.5 * (p0.y + p1.y) + step * (d0[1] - d1[1]) / 8.0;
4830                    let z = 0.5 * (p0.z + p1.z) + step * (d0[2] - d1[2]) / 8.0;
4831                    worst = worst.max(((x - p.x).powi(2) + (y - p.y).powi(2) + (z - p.z).powi(2)).sqrt());
4832                }
4833            }
4834        }
4835        if worst > skin_tolerance {
4836            if rings >= 256 {
4837                return Err(refuse("gear_fit", format!("The crown gear's tooth spaces could not be skinned within {skin_tolerance:.2e} ({worst:.2e}).")));
4838            }
4839            rings *= 2;
4840            continue;
4841        }
4842        let h = 1.0 / rings as f64;
4843        let mut knots_v = vec![0.0; 4];
4844        for j in 1..rings {
4845            let v = j as f64 * h;
4846            knots_v.extend([v, v]);
4847        }
4848        knots_v.extend([1.0; 4]);
4849        let mut surfaces = Vec::with_capacity(5);
4850        for role in 0..5 {
4851            let grid: Vec<Vec<Vec4>> = (0..rows[0][role].control_points.len())
4852                .map(|k| {
4853                    let mut row = Vec::with_capacity(2 * rings + 2);
4854                    for j in 0..=rings {
4855                        let q = rows[j][role].control_points[k];
4856                        let d = slopes[j][role][k];
4857                        let along = |s: f64| Vec4::from_point(Vec3::new(q.x + s * length * d[0], q.y + s * length * d[1], q.z + s * length * d[2]), 1.0);
4858                        if j > 0 {
4859                            row.push(along(-h / 3.0));
4860                        }
4861                        if j == 0 || j == rings {
4862                            row.push(along(0.0));
4863                        }
4864                        if j < rings {
4865                            row.push(along(h / 3.0));
4866                        }
4867                    }
4868                    row
4869                })
4870                .collect();
4871            surfaces.push(NurbsSurface::new(3, 3, rows[0][role].knots.clone(), knots_v.clone(), grid).map_err(|e| refuse("gear_surface", e))?);
4872        }
4873        return Ok(surfaces);
4874    }
4875}
4876
4877fn iso_u(surface: &NurbsSurface, last: bool) -> Result<NurbsCurve, KernelRefusal> {
4878    let row = if last { surface.control_points.len() - 1 } else { 0 };
4879    NurbsCurve::new(surface.degree_v, surface.knots_v.clone(), surface.control_points[row].clone()).map_err(|e| refuse("gear_edge", e))
4880}
4881
4882fn iso_v(surface: &NurbsSurface, last: bool) -> Result<NurbsCurve, KernelRefusal> {
4883    let column = if last { surface.control_points[0].len() - 1 } else { 0 };
4884    NurbsCurve::new(surface.degree_u, surface.knots_u.clone(), surface.control_points.iter().map(|row| row[column]).collect()).map_err(|e| refuse("gear_edge", e))
4885}
4886
4887fn turned_surface(surface: &NurbsSurface, angle: f64) -> Result<NurbsSurface, KernelRefusal> {
4888    let (s, c) = angle.sin_cos();
4889    let grid = surface.control_points.iter().map(|row| row.iter().map(|p| Vec4 { x: c * p.x - s * p.y, y: s * p.x + c * p.y, z: p.z, w: p.w }).collect()).collect();
4890    NurbsSurface::new(surface.degree_u, surface.degree_v, surface.knots_u.clone(), surface.knots_v.clone(), grid).map_err(|e| refuse("gear_surface", e))
4891}
4892
4893/// Arcs of `radius` about the z axis at height `z` through the given angles, as one curve whose span i (on
4894/// [i, i + 1]) is the arc from angle i to angle i + 1, and each span alone.
4895fn joined_arcs(radius: f64, z: f64, angles: &[f64]) -> Result<(NurbsCurve, Vec<NurbsCurve>), KernelRefusal> {
4896    let mut pieces = Vec::with_capacity(angles.len() - 1);
4897    for pair in angles.windows(2) {
4898        pieces.push(crate::make_arc(Vec3::new(0.0, 0.0, z), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), radius, pair[0], pair[1]).map_err(|e| refuse("gear_arc", e))?);
4899    }
4900    let degree = pieces[0].degree;
4901    let mut knots: Vec<f64> = Vec::new();
4902    let mut points: Vec<Vec4> = Vec::new();
4903    for (index, piece) in pieces.iter().enumerate() {
4904        let shift = index as f64;
4905        if index == 0 {
4906            knots.extend(piece.knots[..piece.knots.len() - 1].iter().map(|k| k + shift));
4907            points.extend(piece.control_points.iter().copied());
4908        } else {
4909            knots.extend(piece.knots[degree + 1..piece.knots.len() - 1].iter().map(|k| k + shift));
4910            points.extend(piece.control_points[1..].iter().copied());
4911        }
4912    }
4913    knots.push(pieces.len() as f64);
4914    Ok((NurbsCurve::new(degree, knots, points).map_err(|e| refuse("gear_arc", e))?, pieces))
4915}
4916
4917/// A crown gear solid and its data. Faces carry their names: per tooth space n `G<n>` (root land), `V<n>` /
4918/// `W<n>` (the +θ and −θ fillets), `R<n>` / `L<n>` (the +θ and −θ flanks), `I<n>` and `O<n>` (the inner and
4919/// outer cylinder from the middle of tooth n − 1 to the middle of tooth n); per tooth n (between spaces n and
4920/// n + 1) `K<n>` (tip land); and `B` (the back).
4921pub fn crown_solid(gear: &CrownGear) -> Result<(BrepSolid, GearData), KernelRefusal> {
4922    use crate::sweep_topology::{curve_to_plane_parameters, make_plane, parameter_line};
4923    let [r2, inner, outer, pitch, tip, _] = crown_sizes(gear)?;
4924    let shaper = CrownShaper::new(gear)?;
4925    let walls = crown_wall_surfaces(gear, &shaper, inner, outer, pitch)?;
4926    let teeth = gear.teeth;
4927    let tau = TAU / teeth as f64;
4928    let line = |a: [f64; 2], b: [f64; 2]| parameter_line(a[0], a[1], b[0], b[1]).map_err(|e| refuse("gear_pcurve", e));
4929    let mut shell = ShellBuilder { vertices: Vec::new(), edges: Vec::new(), faces: Vec::new(), next: 0 };
4930    // Per space j: its walls turned by j tau, their corner vertices and edges.
4931    struct Space {
4932        walls: Vec<NurbsSurface>,
4933        inner: [u64; 6],
4934        outer: [u64; 6],
4935        /// Edges between walls (and the two tip edges), at u = 0 of wall 0 then u = 1 of each wall.
4936        across: [u64; 6],
4937        inner_edges: [u64; 5],
4938        outer_edges: [u64; 5],
4939    }
4940    let point_of = |p: Vec4| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w);
4941    let mut spaces: Vec<Space> = Vec::with_capacity(teeth);
4942    for j in 0..teeth {
4943        let turned: Vec<NurbsSurface> = walls.iter().map(|w| turned_surface(w, tau * j as f64)).collect::<Result<_, _>>()?;
4944        let mut inner_v = [0u64; 6];
4945        let mut outer_v = [0u64; 6];
4946        for k in 0..6 {
4947            let (wall, row) = if k < 5 { (&turned[k], 0) } else { (&turned[4], turned[4].control_points.len() - 1) };
4948            let column = &wall.control_points[row];
4949            inner_v[k] = shell.vertex(point_of(column[0]));
4950            outer_v[k] = shell.vertex(point_of(*column.last().expect("a row")));
4951        }
4952        let mut across = [0u64; 6];
4953        across[0] = shell.edge(iso_u(&turned[0], false)?, inner_v[0], outer_v[0])?;
4954        for k in 0..5 {
4955            across[k + 1] = shell.edge(iso_u(&turned[k], true)?, inner_v[k + 1], outer_v[k + 1])?;
4956        }
4957        let mut inner_edges = [0u64; 5];
4958        let mut outer_edges = [0u64; 5];
4959        for k in 0..5 {
4960            inner_edges[k] = shell.edge(iso_v(&turned[k], false)?, inner_v[k], inner_v[k + 1])?;
4961            outer_edges[k] = shell.edge(iso_v(&turned[k], true)?, outer_v[k], outer_v[k + 1])?;
4962        }
4963        spaces.push(Space { walls: turned, inner: inner_v, outer: outer_v, across, inner_edges, outer_edges });
4964    }
4965    // The walls' faces: u along the wall, v outwards; the outward side faces into the space (or up from the land).
4966    for (j, space) in spaces.iter().enumerate() {
4967        for k in 0..5 {
4968            let surface = space.walls[k].clone();
4969            let at = |u: f64, v: f64| surface.evaluate(u, v).map_err(|e| refuse("gear_surface", e));
4970            let p = at(0.5, 0.5)?;
4971            let du = at(0.5 + 1e-6, 0.5)?.sub(at(0.5 - 1e-6, 0.5)?);
4972            let dv = at(0.5, 0.5 + 1e-6)?.sub(at(0.5, 0.5 - 1e-6)?);
4973            let normal = du.cross(dv);
4974            let centre = tau * j as f64;
4975            let off = (p.y.atan2(p.x) - centre + PI).rem_euclid(TAU) - PI;
4976            let tangential = Vec3::new(-p.y, p.x, 0.0).scale(1.0 / p.x.hypot(p.y));
4977            let outward = Vec3::new(0.0, 0.0, 1.0).sub(tangential.scale(off.signum()));
4978            let same_sense = normal.dot(outward) > 0.0;
4979            let loops = vec![vec![
4980                (space.inner_edges[k], true, line([0.0, 0.0], [1.0, 0.0])?),
4981                (space.across[k + 1], true, line([1.0, 0.0], [1.0, 1.0])?),
4982                (space.outer_edges[k], false, line([0.0, 1.0], [1.0, 1.0])?),
4983                (space.across[k], false, line([0.0, 0.0], [0.0, 1.0])?),
4984            ]];
4985            shell.face(surface, same_sense, loops, format!("{}{j}", CROWN_ROLES[k]))?;
4986        }
4987    }
4988    // Side lines at the middle of every tooth, inner and outer, and the cylinders between them.
4989    let mut sides = Vec::with_capacity(teeth); // per tooth j: [(bottom, top) inner, (bottom, top) outer] vertices and edges
4990    for j in 0..teeth {
4991        let angle = tau * j as f64 + tau / 2.0;
4992        let mut side = Vec::with_capacity(2);
4993        for radius in [inner, outer] {
4994            let (s, c) = angle.sin_cos();
4995            let bottom = shell.vertex(Vec3::new(radius * c, radius * s, 0.0));
4996            let top = shell.vertex(Vec3::new(radius * c, radius * s, tip));
4997            let edge = shell.edge(crate::make_line(Vec3::new(radius * c, radius * s, 0.0), Vec3::new(radius * c, radius * s, tip)).map_err(|e| refuse("gear_edge", e))?, bottom, top)?;
4998            side.push((bottom, top, edge));
4999        }
5000        sides.push(side);
5001    }
5002    // Per space j and per radius: the bottom arc edge and the two tip arcs (the tooth before, the tooth after).
5003    let mut bottoms: [Vec<u64>; 2] = [Vec::new(), Vec::new()];
5004    let mut tip_arcs: [Vec<(u64, u64)>; 2] = [Vec::new(), Vec::new()];
5005    for j in 0..teeth {
5006        let space = &spaces[j];
5007        let before = &sides[(j + teeth - 1) % teeth];
5008        let after = &sides[j];
5009        let base_angle = tau * j as f64 - tau / 2.0;
5010        for (side, radius) in [inner, outer].into_iter().enumerate() {
5011            let corners = if side == 0 { space.inner } else { space.outer };
5012            let point = |id: u64| shell.vertices.iter().find(|v| v.id == id).expect("a vertex").point;
5013            let unwrap = |p: Vec3| base_angle + (p.y.atan2(p.x) - base_angle).rem_euclid(TAU);
5014            let angles = [base_angle, unwrap(point(corners[0])), unwrap(point(corners[5])), base_angle + tau];
5015            let (base, _) = joined_arcs(radius, 0.0, &angles)?;
5016            let (_, lifted) = joined_arcs(radius, tip, &angles)?;
5017            let bottom = shell.edge(base.clone(), before[side].0, after[side].0)?;
5018            let first = shell.edge(lifted[0].clone(), before[side].1, corners[0])?;
5019            let last = shell.edge(lifted[2].clone(), corners[5], after[side].1)?;
5020            bottoms[side].push(bottom);
5021            tip_arcs[side].push((first, last));
5022            let surface = crate::make_extrusion(&base, Vec3::new(0.0, 0.0, tip)).map_err(|e| refuse("gear_surface", e))?;
5023            let wall_edges = if side == 0 { space.inner_edges } else { space.outer_edges };
5024            let mut coedges = vec![
5025                (bottom, true, line([0.0, 0.0], [3.0, 0.0])?),
5026                (after[side].2, true, line([3.0, 0.0], [3.0, 1.0])?),
5027                (last, false, line([2.0, 1.0], [3.0, 1.0])?),
5028            ];
5029            for k in (0..5).rev() {
5030                let curve = shell.curve(wall_edges[k]).clone();
5031                let pcurve = crate::build_pcurve_on_surface(&surface, &curve).map_err(|e| refuse("gear_pcurve", e))?;
5032                coedges.push((wall_edges[k], false, pcurve));
5033            }
5034            coedges.push((first, false, line([0.0, 1.0], [1.0, 1.0])?));
5035            coedges.push((before[side].2, false, line([0.0, 0.0], [0.0, 1.0])?));
5036            // The extrusion's normal points out from the axis: outward for the outer cylinder, inward for the inner.
5037            shell.face(surface, side == 1, vec![coedges], format!("{}{j}", if side == 0 { "I" } else { "O" }))?;
5038        }
5039    }
5040    // Tip lands: tooth j between space j (its R tip edge) and space j + 1 (its L tip edge).
5041    let pad = outer * 1.1 + 1.0;
5042    let x_axis = Vec3::new(1.0, 0.0, 0.0);
5043    let y_axis = Vec3::new(0.0, 1.0, 0.0);
5044    let on_plane = |curve: &NurbsCurve, z: f64| curve_to_plane_parameters(curve, Vec3::new(-pad, -pad, z), x_axis, y_axis).map_err(|e| refuse("gear_pcurve", e));
5045    for j in 0..teeth {
5046        let next = (j + 1) % teeth;
5047        let mut coedges = Vec::with_capacity(6);
5048        for (edge, forward) in [
5049            (spaces[j].across[5], true),
5050            (tip_arcs[1][j].1, true),
5051            (tip_arcs[1][next].0, true),
5052            (spaces[next].across[0], false),
5053            (tip_arcs[0][next].0, false),
5054            (tip_arcs[0][j].1, false),
5055        ] {
5056            let pcurve = on_plane(shell.curve(edge), tip)?;
5057            coedges.push((edge, forward, pcurve));
5058        }
5059        let plane = make_plane(Vec3::new(-pad, -pad, tip), x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e))?;
5060        shell.face(plane, true, vec![coedges], format!("K{j}"))?;
5061    }
5062    // The back: the outer and inner bottom arcs.
5063    let mut loops = Vec::with_capacity(2);
5064    for side in [1, 0] {
5065        let mut coedges = Vec::with_capacity(teeth);
5066        for &edge in &bottoms[side] {
5067            coedges.push((edge, true, on_plane(shell.curve(edge), 0.0)?));
5068        }
5069        loops.push(coedges);
5070    }
5071    let plane = make_plane(Vec3::new(-pad, -pad, 0.0), x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e))?;
5072    shell.face(plane, false, loops, "B".into())?;
5073    let id = shell.id();
5074    let shell_id = shell.id();
5075    let solid = BrepSolid {
5076        mass_properties_cache: Default::default(),
5077        cells: Default::default(),
5078        id,
5079        vertices: shell.vertices,
5080        edges: shell.edges,
5081        shells: vec![crate::sweep_topology::ShellRecord { id: shell_id, faces: shell.faces }],
5082        genus: 1,
5083        kind: crate::BodyKind::Solid,
5084    };
5085    let issues = solid.validate();
5086    if !issues.is_empty() {
5087        return Err(KernelRefusal::internal(KernelStage::Validate, "validate", format!("crown gear is not valid: {issues:?}")));
5088    }
5089    let data = GearData {
5090        pitch_diameter: 2.0 * r2,
5091        base_diameter: 2.0 * r2 * gear.pressure_angle.cos(),
5092        tip_diameter: 2.0 * outer,
5093        root_diameter: 2.0 * inner,
5094        ..GearData::default()
5095    };
5096    Ok((solid, data))
5097}
5098