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/// An external spur gear generated by a standard rack cutter. Lengths in model
28/// units, angles in radians; coefficients are multiples of the module.
29#[derive(Clone, Debug)]
30pub struct SpurGear {
31    pub module: f64,
32    pub teeth: usize,
33    pub pressure_angle: f64,
34    /// Profile shift coefficient x (the cutter moved out by x · module).
35    pub profile_shift: f64,
36    /// Addendum coefficient ha* (tip radius = r + (ha* + x) m).
37    pub addendum: f64,
38    /// Dedendum coefficient hf* (root radius = r - (hf* - x) m).
39    pub dedendum: f64,
40    /// Cutter tip radius coefficient rho_f*.
41    pub root_fillet: f64,
42    /// Circumferential backlash taken off the tooth thickness on the reference circle.
43    pub backlash: f64,
44    pub face_width: f64,
45}
46
47impl Default for SpurGear {
48    fn default() -> Self {
49        Self {
50            module: 2.0,
51            teeth: 20,
52            pressure_angle: 20f64.to_radians(),
53            profile_shift: 0.0,
54            addendum: 1.0,
55            dedendum: 1.25,
56            root_fillet: 0.38,
57            backlash: 0.0,
58            face_width: 10.0,
59        }
60    }
61}
62
63/// Derived data of a generated gear (diameters in model units).
64#[derive(Clone, Debug, Default)]
65pub struct GearData {
66    pub pitch_diameter: f64,
67    pub base_diameter: f64,
68    pub tip_diameter: f64,
69    pub root_diameter: f64,
70    /// Diameter where the involute flank meets the root fillet.
71    pub form_diameter: f64,
72    /// Tooth thickness on the reference (pitch) circle, arc length.
73    pub tooth_thickness: f64,
74    /// Tooth thickness on the tip circle, arc length.
75    pub tip_thickness: f64,
76    /// Whether the root fillet cuts into the involute (generated undercut).
77    pub undercut: bool,
78    /// The smallest profile shift at which this gear has no undercut.
79    pub min_shift_without_undercut: f64,
80}
81
82/// One curve of a gear section with the face role it gives the solid.
83#[derive(Clone, Debug)]
84pub struct SectionCurve {
85    pub curve: NurbsCurve,
86    /// Face role: `V`/`W` root fillets, `R`/`L` flanks, `K` tip land, `G` root land.
87    pub role: &'static str,
88    pub tooth: usize,
89}
90
91impl SectionCurve {
92    /// The face-name suffix this curve's face carries (`R3`, `K0`, …).
93    pub fn suffix(&self) -> String {
94        format!("{}{}", self.role, self.tooth)
95    }
96}
97
98/// A closed gear section in the z = 0 plane, counter-clockwise about +z.
99#[derive(Clone, Debug)]
100pub struct GearSection {
101    pub curves: Vec<SectionCurve>,
102    pub data: GearData,
103}
104
105fn refuse(code: &str, message: String) -> KernelRefusal {
106    KernelRefusal::input(KernelStage::Collect, code, message)
107}
108
109fn rotate(point: [f64; 2], angle: f64) -> [f64; 2] {
110    let (s, c) = angle.sin_cos();
111    [c * point[0] - s * point[1], s * point[0] + c * point[1]]
112}
113
114fn polar_angle(point: [f64; 2]) -> f64 {
115    point[1].atan2(point[0])
116}
117
118fn radius_of(point: [f64; 2]) -> f64 {
119    point[0].hypot(point[1])
120}
121
122/// The rack cutter of a spur gear in the generating frame, and its envelope.
123struct RackCutter {
124    r: f64,
125    alpha: f64,
126    /// Reference line of the cutter (x).
127    x_ref: f64,
128    /// The cutter flank's y on the reference line.
129    y0: f64,
130    /// Root radius = the cutter tip line (x).
131    r_f: f64,
132    rho: f64,
133    /// Tip fillet centre.
134    centre: [f64; 2],
135}
136
137impl RackCutter {
138    fn new(gear: &SpurGear) -> Self {
139        let m = gear.module;
140        let r = m * gear.teeth as f64 / 2.0;
141        let p = PI * m;
142        let alpha = gear.pressure_angle;
143        let x_ref = r + gear.profile_shift * m;
144        let y0 = p / 4.0 - gear.backlash / 2.0;
145        let r_f = x_ref - gear.dedendum * m;
146        let rho = gear.root_fillet * m;
147        let x_c = r_f + rho;
148        let y_c = y0 + (rho + (x_ref - x_c) * alpha.sin()) / alpha.cos();
149        Self { r, alpha, x_ref, y0, r_f, rho, centre: [x_c, y_c] }
150    }
151
152    /// The gear point generated by the rack point `q` with outward normal `n`.
153    fn envelope(&self, q: [f64; 2], n: [f64; 2]) -> [f64; 2] {
154        let s = (q[0] - self.r) * n[1] / n[0] - q[1];
155        rotate([q[0], q[1] + s], -s / self.r)
156    }
157
158    /// The involute flank (left side of tooth 0) generated by the flank point at `x`.
159    fn flank(&self, x: f64) -> [f64; 2] {
160        let a = self.alpha;
161        let q = [x, self.y0 + (self.x_ref - x) * a.tan()];
162        self.envelope(q, [-a.sin(), -a.cos()])
163    }
164
165    /// The root fillet (left side of tooth 0) generated by the cutter tip fillet
166    /// at normal angle `psi` (0 = the tip line, pi/2 - alpha = the flank).
167    fn fillet(&self, psi: f64) -> [f64; 2] {
168        let n = [-psi.cos(), -psi.sin()];
169        if self.rho == 0.0 {
170            // A sharp cutter corner: the point is fixed, its normal still sweeps.
171            return self.envelope(self.centre, n);
172        }
173        let q = [self.centre[0] + self.rho * n[0], self.centre[1] + self.rho * n[1]];
174        self.envelope(q, n)
175    }
176
177    /// The flank point x whose generated point lies at radius `radius` (the involute branch).
178    fn flank_x_at_radius(&self, radius: f64) -> f64 {
179        let c = 1.0 / self.alpha.tan();
180        let c2 = c * c;
181        let disc = (self.r * self.r * c2 * c2 - (1.0 + c2) * (self.r * self.r * c2 - radius * radius)).max(0.0);
182        (self.r * c2 + disc.sqrt()) / (1.0 + c2)
183    }
184}
185
186/// A cubic B-spline (C1 Hermite spans) through `f` on `[a, b]`, refined until each
187/// span is within `tolerance` of `f` at its sample parameters.
188fn fit_planar(f: &dyn Fn(f64) -> [f64; 2], a: f64, b: f64, tolerance: f64) -> Result<NurbsCurve, KernelRefusal> {
189    let derivative = |t: f64| {
190        let h = 1e-6 * (b - a).abs().max(1e-12);
191        let p = f(t + h);
192        let q = f(t - h);
193        [(p[0] - q[0]) / (2.0 * h), (p[1] - q[1]) / (2.0 * h)]
194    };
195    let span_points = |t0: f64, t1: f64| {
196        let (p0, p1) = (f(t0), f(t1));
197        let (d0, d1) = (derivative(t0), derivative(t1));
198        let k = (t1 - t0) / 3.0;
199        [p0, [p0[0] + d0[0] * k, p0[1] + d0[1] * k], [p1[0] - d1[0] * k, p1[1] - d1[1] * k], p1]
200    };
201    let bezier = |c: &[[f64; 2]; 4], u: f64| {
202        let v = 1.0 - u;
203        let w = [v * v * v, 3.0 * v * v * u, 3.0 * v * u * u, u * u * u];
204        [
205            w[0] * c[0][0] + w[1] * c[1][0] + w[2] * c[2][0] + w[3] * c[3][0],
206            w[0] * c[0][1] + w[1] * c[1][1] + w[2] * c[2][1] + w[3] * c[3][1],
207        ]
208    };
209    let mut pending: Vec<(f64, f64, usize)> = (0..4).rev().map(|i| {
210        let t0 = a + (b - a) * i as f64 / 4.0;
211        let t1 = a + (b - a) * (i + 1) as f64 / 4.0;
212        (t0, t1, 0)
213    }).collect();
214    let mut spans: Vec<(f64, f64, [[f64; 2]; 4])> = Vec::new();
215    while let Some((t0, t1, depth)) = pending.pop() {
216        let c = span_points(t0, t1);
217        let worst = [0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
218            .iter()
219            .map(|&u| {
220                let exact = f(t0 + (t1 - t0) * u);
221                let fitted = bezier(&c, u);
222                (exact[0] - fitted[0]).hypot(exact[1] - fitted[1])
223            })
224            .fold(0.0, f64::max);
225        if worst > tolerance && depth < 16 {
226            let mid = 0.5 * (t0 + t1);
227            pending.push((mid, t1, depth + 1));
228            pending.push((t0, mid, depth + 1));
229        } else if worst > tolerance {
230            return Err(refuse("gear_fit", format!("gear curve fit did not converge ({worst:.3e} > {tolerance:.3e})")));
231        } else {
232            spans.push((t0, t1, c));
233        }
234    }
235    // Knots in [0, 1] (normalised). The Hermite spans join with C1 continuity,
236    // so each interior knot is doubled and the shared span end, which lies on
237    // the segment between its two neighbours, is implied rather than stored.
238    let scale = 1.0 / (b - a);
239    let to_point = |p: [f64; 2]| Vec4::from_point(Vec3::new(p[0], p[1], 0.0), 1.0);
240    let mut knots = vec![0.0; 4];
241    let mut points = vec![to_point(spans[0].2[0])];
242    for (index, (_, t1, c)) in spans.iter().enumerate() {
243        points.push(to_point(c[1]));
244        points.push(to_point(c[2]));
245        if index + 1 < spans.len() {
246            let k = (t1 - a) * scale;
247            knots.extend([k, k]);
248        } else {
249            points.push(to_point(c[3]));
250        }
251    }
252    knots.extend([1.0; 4]);
253    NurbsCurve::new(3, knots, points).map_err(|error| refuse("gear_fit", error))
254}
255
256fn mirrored(curve: &NurbsCurve) -> NurbsCurve {
257    let mut copy = curve.clone();
258    for point in &mut copy.control_points {
259        point.y = -point.y;
260    }
261    NurbsCurve::new(copy.degree, copy.knots, copy.control_points).expect("a mirrored curve is a valid curve")
262}
263
264fn rotated(curve: &NurbsCurve, angle: f64) -> NurbsCurve {
265    let (s, c) = angle.sin_cos();
266    let points = curve
267        .control_points
268        .iter()
269        .map(|p| Vec4 { x: c * p.x - s * p.y, y: s * p.x + c * p.y, z: p.z, w: p.w })
270        .collect();
271    NurbsCurve::new(curve.degree, curve.knots.clone(), points).expect("a rotated curve is a valid curve")
272}
273
274fn arc(radius: f64, from: f64, to: f64) -> Result<NurbsCurve, KernelRefusal> {
275    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)
276        .map_err(|error| refuse("gear_arc", error))
277}
278
279fn check_spur(gear: &SpurGear, max_pressure_degrees: f64) -> Result<(), KernelRefusal> {
280    let positive = |value: f64, what: &str| {
281        if value.is_finite() && value > 0.0 {
282            Ok(())
283        } else {
284            Err(refuse("gear_input", format!("The {what} must be greater than zero (it is {value}).")))
285        }
286    };
287    positive(gear.module, "module")?;
288    positive(gear.face_width, "face width")?;
289    positive(gear.addendum, "addendum coefficient")?;
290    positive(gear.dedendum, "dedendum coefficient")?;
291    if gear.teeth < 3 {
292        return Err(refuse("gear_input", format!("A gear needs at least 3 teeth (it has {}).", gear.teeth)));
293    }
294    let degrees = gear.pressure_angle.to_degrees();
295    if !(10.0 - 1e-9..=max_pressure_degrees + 1e-9).contains(&degrees) {
296        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and {max_pressure_degrees}° (it is {degrees}°).")));
297    }
298    if !(gear.root_fillet >= 0.0) || !(gear.backlash >= 0.0) || !gear.profile_shift.is_finite() {
299        return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
300    }
301    Ok(())
302}
303
304/// The section of an external spur gear, generated by its rack cutter.
305pub fn spur_section(gear: &SpurGear) -> Result<GearSection, KernelRefusal> {
306    check_spur(gear, 35.0)?;
307    generated_section(gear)
308}
309
310/// [`spur_section`] for a helical gear's transverse section, whose pressure
311/// angle (already checked in the normal section) may exceed 35°.
312fn transverse_section(gear: &SpurGear) -> Result<GearSection, KernelRefusal> {
313    check_spur(gear, 60.0)?;
314    generated_section(gear)
315}
316
317fn generated_section(gear: &SpurGear) -> Result<GearSection, KernelRefusal> {
318    let m = gear.module;
319    let z = gear.teeth as f64;
320    let rack = RackCutter::new(gear);
321    let alpha = rack.alpha;
322    let r = rack.r;
323    let r_b = r * alpha.cos();
324    let r_a = r + (gear.addendum + gear.profile_shift) * m;
325    let r_f = rack.r_f;
326    let half_pitch = PI / z;
327    let tolerance = GEAR_FIT_TOLERANCE * m;
328
329    if r_f <= 1e-9 * m {
330        return Err(refuse(
331            "root_below_centre",
332            format!("The root circle diameter is zero or negative (d = {:.4}): too few teeth for this dedendum.", 2.0 * r_f),
333        ));
334    }
335    // The cutter's tip land must stay; with too large a tip radius the two fillets cross.
336    let rho_max = ((PI * m / 2.0 - rack.y0) * alpha.cos() - (rack.x_ref - r_f) * alpha.sin()) / (1.0 - alpha.sin());
337    if rack.rho > rho_max + 1e-9 * m {
338        return Err(refuse(
339            "root_fillet_too_large",
340            format!(
341                "The root fillet coefficient {:.4} is larger than the {:.4} that fits this tooth space; lower it.",
342                gear.root_fillet,
343                rho_max / m
344            ),
345        ));
346    }
347    let psi_end = PI / 2.0 - alpha;
348    let x_flank_tangent = rack.centre[0] - rack.rho * alpha.sin();
349    let x_interference = r * alpha.cos().powi(2);
350    let min_shift = gear.dedendum - gear.root_fillet * (1.0 - alpha.sin()) - z / 2.0 * alpha.sin().powi(2);
351    let undercut = x_flank_tangent < x_interference - 1e-12 * m;
352
353    // The junction J of the left flank and its root fillet.
354    let (x_join, psi_join) = if !undercut {
355        (x_flank_tangent, psi_end)
356    } else {
357        // The fillet cuts the involute. Above the base circle the fillet lies
358        // outside the involute at the flank tangency (psi_end) and inside it
359        // just above the base circle, so the crossing is in [psi_base, psi_end],
360        // where psi_base is the fillet's base-circle crossing (its radius rises
361        // from the root, which is below the base circle here). Search that
362        // interval at a resolution relative to its own width, so a gear just
363        // past the undercut limit (a very short interval) is found too.
364        let difference = |psi: f64| -> Option<f64> {
365            let point = rack.fillet(psi);
366            let radius = radius_of(point);
367            if radius <= r_b {
368                return None;
369            }
370            Some(polar_angle(point) - polar_angle(rack.flank(rack.flank_x_at_radius(radius))))
371        };
372        let (mut below, mut above) = (0.0, psi_end);
373        for _ in 0..200 {
374            let mid = 0.5 * (below + above);
375            if radius_of(rack.fillet(mid)) <= r_b { below = mid } else { above = mid }
376        }
377        let psi_base = above;
378        let steps = 4000;
379        let mut found = None;
380        let mut previous: Option<(f64, f64)> = None;
381        for step in 0..=steps {
382            let psi = psi_end - (psi_end - psi_base) * step as f64 / steps as f64;
383            if let Some(value) = difference(psi) {
384                if let Some((last_psi, last_value)) = previous {
385                    if (value <= 0.0) != (last_value <= 0.0) {
386                        found = Some((psi, last_psi));
387                        break;
388                    }
389                }
390                previous = Some((psi, value));
391            }
392        }
393        // No crossing resolvable above the base circle: the fillet meets the
394        // flank at the base circle itself (the undercut limit).
395        let (mut lo, mut hi) = found.unwrap_or((psi_base, psi_base));
396        let sign_lo = difference(lo).unwrap_or(-1.0) <= 0.0;
397        for _ in 0..200 {
398            let mid = 0.5 * (lo + hi);
399            match difference(mid) {
400                Some(value) if (value <= 0.0) == sign_lo => lo = mid,
401                Some(_) => hi = mid,
402                None => lo = mid,
403            }
404        }
405        let psi = 0.5 * (lo + hi);
406        (rack.flank_x_at_radius(radius_of(rack.fillet(psi))), psi)
407    };
408    let join = rack.fillet(psi_join);
409    let form_radius = radius_of(join);
410    if r_a <= form_radius + 1e-9 * m {
411        return Err(refuse(
412            "tip_below_form",
413            format!(
414                "The tip circle (d = {:.4}) does not reach above the form circle (d = {:.4}); raise the addendum or lower the dedendum.",
415                2.0 * r_a,
416                2.0 * form_radius
417            ),
418        ));
419    }
420    let x_tip = rack.flank_x_at_radius(r_a);
421    let tip = rack.flank(x_tip);
422    // Half the tooth thickness angle at a radius (the textbook involute form,
423    // unwrapped: a polar angle read off a crossed flank wraps round and would
424    // pass a tooth whose flanks crossed below the tip).
425    let thickness = PI * m / 2.0 + 2.0 * gear.profile_shift * m * alpha.tan() - gear.backlash;
426    let involute = |angle: f64| angle.tan() - angle;
427    let half_angle = |radius: f64| thickness / (2.0 * r) + involute(alpha) - involute((r_b / radius).min(1.0).acos());
428    let tip_angle = half_angle(r_a);
429    let tip_offset = polar_angle(tip) - tip_angle;
430    if tip_angle * r_a <= 1e-6 * m || tip_offset.abs() > 1e-9 {
431        // Where the flanks meet: half_angle falls as the radius grows.
432        let (mut lo, mut hi) = (form_radius.max(r_b), r_a);
433        for _ in 0..200 {
434            let mid = 0.5 * (lo + hi);
435            if half_angle(mid) > 0.0 { lo = mid } else { hi = mid }
436        }
437        return Err(refuse(
438            "pointed_tip",
439            format!(
440                "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.",
441                2.0 * lo,
442                2.0 * r_a
443            ),
444        ));
445    }
446    if tip_angle >= half_pitch {
447        return Err(refuse("teeth_overlap", "The tooth tips overlap their neighbours.".into()));
448    }
449    // Fillet samples must stay inside the half space (else neighbouring gaps cross).
450    for step in 0..=64 {
451        let point = rack.fillet(psi_join * step as f64 / 64.0);
452        let angle = polar_angle(point);
453        if angle <= 0.0 || angle > half_pitch + 1e-12 {
454            return Err(refuse("teeth_overlap", "The tooth gaps cross: the root form of one gap cuts the next tooth.".into()));
455        }
456    }
457
458    let flank_fit = fit_planar(&|x| rack.flank(x), x_join, x_tip, tolerance)?; // J -> tip
459    let fillet_fit = fit_planar(&|psi| rack.fillet(psi), 0.0, psi_join, tolerance)?; // root -> J
460    let root_angle = rack.centre[1] / r;
461    let land = 2.0 * half_pitch - 2.0 * root_angle;
462
463    // Tooth 0, counter-clockwise: V (root -> J_R), R (J_R -> tip), K, L (tip -> J), W (J -> root), G.
464    let mut tooth: Vec<(&'static str, NurbsCurve)> = vec![
465        ("V", mirrored(&fillet_fit)),
466        ("R", mirrored(&flank_fit)),
467        ("K", arc(r_a, -tip_angle, tip_angle)?),
468        ("L", flank_fit.reversed().map_err(|e| refuse("gear_fit", e))?),
469        ("W", fillet_fit.reversed().map_err(|e| refuse("gear_fit", e))?),
470    ];
471    if land > 1e-9 {
472        tooth.push(("G", arc(r_f, root_angle, 2.0 * half_pitch - root_angle)?));
473    }
474
475    let mut curves = Vec::with_capacity(tooth.len() * gear.teeth);
476    for index in 0..gear.teeth {
477        let angle = TAU * index as f64 / z;
478        for (role, curve) in &tooth {
479            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
480        }
481    }
482    // Share every junction exactly: each curve ends on the next one's first point.
483    snap_junctions(&mut curves);
484
485    let thickness_angle = |radius: f64| polar_angle(rack.flank(rack.flank_x_at_radius(radius)));
486    let data = GearData {
487        pitch_diameter: 2.0 * r,
488        base_diameter: 2.0 * r_b,
489        tip_diameter: 2.0 * r_a,
490        root_diameter: 2.0 * r_f,
491        form_diameter: 2.0 * form_radius,
492        tooth_thickness: 2.0 * r * thickness_angle(r.max(r_b)),
493        tip_thickness: 2.0 * r_a * tip_angle,
494        undercut,
495        min_shift_without_undercut: min_shift,
496    };
497    Ok(GearSection { curves, data })
498}
499
500/// A spur gear solid: the section extruded along +z by the face width. The face
501/// names (suffixes, in the solid's face order) are the section curves' roles,
502/// then `F` (the z = 0 face) and `B` (the z = width face).
503pub fn spur_solid(gear: &SpurGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
504    let section = spur_section(gear)?;
505    let solid = extrude_section(&section, gear.face_width)?;
506    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
507    names.push("F".into());
508    names.push("B".into());
509    Ok((solid, names, section.data))
510}
511
512/// Extrude a counter-clockwise gear section along +z.
513pub fn extrude_section(section: &GearSection, width: f64) -> Result<BrepSolid, KernelRefusal> {
514    let curves: Vec<NurbsCurve> = section.curves.iter().map(|piece| piece.curve.clone()).collect();
515    extrude_profile_brep(&curves, Vec3::new(0.0, 0.0, 1.0), width)
516}
517
518/// A straight-toothed rack: the basic rack profile of `teeth` teeth along +x
519/// from x = 0, the pitch line on y = 0, teeth pointing +y, extruded along +z.
520/// Each end stops in the middle of a tooth space.
521#[derive(Clone, Debug)]
522pub struct Rack {
523    pub module: f64,
524    pub teeth: usize,
525    pub pressure_angle: f64,
526    pub addendum: f64,
527    pub dedendum: f64,
528    /// Root fillet radius coefficient (× module).
529    pub root_fillet: f64,
530    /// Circumferential backlash taken off the tooth thickness on the pitch line.
531    pub backlash: f64,
532    pub face_width: f64,
533    /// Distance from the pitch line down to the rack's back face.
534    pub height: f64,
535    /// Helix angle of a helical rack (0: straight teeth); the module, pressure
536    /// angle and coefficients are then those of the normal section. Positive
537    /// leans the teeth one way (right hand), negative the other.
538    pub helix_angle: f64,
539}
540
541impl Default for Rack {
542    fn default() -> Self {
543        Self {
544            module: 2.0,
545            teeth: 10,
546            pressure_angle: 20f64.to_radians(),
547            addendum: 1.0,
548            dedendum: 1.25,
549            root_fillet: 0.38,
550            backlash: 0.0,
551            face_width: 10.0,
552            height: 6.0,
553            helix_angle: 0.0,
554        }
555    }
556}
557
558fn line(a: [f64; 2], b: [f64; 2]) -> Result<NurbsCurve, KernelRefusal> {
559    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))
560}
561
562fn centred_arc(centre: [f64; 2], radius: f64, from: f64, to: f64) -> Result<NurbsCurve, KernelRefusal> {
563    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)
564        .map_err(|error| refuse("gear_arc", error))
565}
566
567/// The section of a straight rack (exact: lines and arcs), counter-clockwise.
568/// Roles: `G<k>` the root land before tooth k (`G<teeth>` the last one),
569/// `W<k>`/`V<k>` the root fillets left/right of tooth k, `L<k>`/`R<k>` its
570/// left (low x) and right flanks, `K<k>` its tip, `BASE` the back face, `E0`
571/// and `E1` the ends at x = 0 and x = length.
572pub fn rack_section(rack: &Rack) -> Result<GearSection, KernelRefusal> {
573    rack_section_checked(rack, 35.0)
574}
575
576fn rack_section_checked(rack: &Rack, max_pressure_degrees: f64) -> Result<GearSection, KernelRefusal> {
577    let m = rack.module;
578    let positive = |value: f64, what: &str| {
579        if value.is_finite() && value > 0.0 {
580            Ok(())
581        } else {
582            Err(refuse("gear_input", format!("The {what} must be greater than zero (it is {value}).")))
583        }
584    };
585    positive(m, "module")?;
586    positive(rack.face_width, "face width")?;
587    positive(rack.addendum, "addendum coefficient")?;
588    positive(rack.dedendum, "dedendum coefficient")?;
589    if rack.teeth < 1 {
590        return Err(refuse("gear_input", "A rack needs at least one tooth.".into()));
591    }
592    let degrees = rack.pressure_angle.to_degrees();
593    if !(10.0 - 1e-9..=max_pressure_degrees + 1e-9).contains(&degrees) {
594        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and {max_pressure_degrees}° (it is {degrees}°).")));
595    }
596    if !(rack.root_fillet >= 0.0) || !(rack.backlash >= 0.0) {
597        return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
598    }
599    let alpha = rack.pressure_angle;
600    let (ha, hf) = (rack.addendum * m, rack.dedendum * m);
601    if rack.height <= hf + 1e-9 * m {
602        return Err(refuse(
603            "rack_too_thin",
604            format!("The rack height below the pitch line ({:.4}) must exceed the dedendum ({:.4}).", rack.height, hf),
605        ));
606    }
607    let p = PI * m;
608    let w = p / 4.0 - rack.backlash / 2.0; // half the tooth thickness on the pitch line
609    let tip_half = w - ha * alpha.tan();
610    if tip_half <= 1e-6 * m {
611        return Err(refuse(
612            "pointed_tip",
613            "The rack teeth come to a point below their tip line; reduce the addendum, the pressure angle or the backlash.".into(),
614        ));
615    }
616    let rho = rack.root_fillet * m;
617    // Right-hand fillet of the tooth centred on x = 0: centre, flank tangent point, root tangent x.
618    let y_p = -hf + rho - rho * alpha.sin();
619    let flank_x = |y: f64| w - y * alpha.tan();
620    let centre = [flank_x(y_p) + rho * alpha.cos(), -hf + rho];
621    let root_half = centre[0]; // the root tangent point's x (right of the tooth centre)
622    if y_p >= ha - 1e-9 * m {
623        return Err(refuse(
624            "root_fillet_too_large",
625            format!(
626                "The root fillet (coefficient {:.4}) reaches above the tooth tip; lower it or raise the addendum.",
627                rack.root_fillet
628            ),
629        ));
630    }
631    if root_half > p / 2.0 + 1e-9 * m {
632        let max = (p / 2.0 - w - hf * alpha.tan()) * alpha.cos() / (1.0 - alpha.sin());
633        return Err(refuse(
634            "root_fillet_too_large",
635            format!("The root fillet coefficient {:.4} is larger than the {:.4} that fits this tooth space; lower it.", rack.root_fillet, max / m),
636        ));
637    }
638    let length = p * rack.teeth as f64;
639    let mut curves: Vec<SectionCurve> = Vec::new();
640    let mut push = |curve: NurbsCurve, role: &'static str, tooth: usize| curves.push(SectionCurve { curve, role, tooth });
641    let base = -rack.height;
642    push(line([0.0, base], [length, base])?, "BASE", 0);
643    push(line([length, base], [length, -hf])?, "E1", 0);
644    // Teeth from the right end leftwards (counter-clockwise along the top).
645    let mut x_prev_root = length; // where the current root land starts (right end)
646    for k in (0..rack.teeth).rev() {
647        let c = (k as f64 + 0.5) * p;
648        let right_root = [c + root_half, -hf];
649        if x_prev_root - right_root[0] > 1e-9 * m {
650            push(line([x_prev_root, -hf], right_root)?, "G", k + 1);
651        }
652        // Right fillet: from the root tangent (angle 270°) back to the flank tangent (180° + alpha).
653        let right_centre = [c + centre[0], centre[1]];
654        let right_flank_low = [c + flank_x(y_p), y_p];
655        if rho > 0.0 {
656            push(centred_arc(right_centre, rho, PI + alpha, 1.5 * PI)?.reversed().map_err(|e| refuse("gear_arc", e))?, "V", k);
657        }
658        let right_tip = [c + tip_half, ha];
659        let left_tip = [c - tip_half, ha];
660        let left_flank_low = [c - flank_x(y_p), y_p];
661        push(line(if rho > 0.0 { right_flank_low } else { right_root }, right_tip)?, "R", k);
662        push(line(right_tip, left_tip)?, "K", k);
663        let left_root = [c - root_half, -hf];
664        push(line(left_tip, if rho > 0.0 { left_flank_low } else { left_root })?, "L", k);
665        if rho > 0.0 {
666            let left_centre = [c - centre[0], centre[1]];
667            push(centred_arc(left_centre, rho, 1.5 * PI, 2.0 * PI - alpha)?.reversed().map_err(|e| refuse("gear_arc", e))?, "W", k);
668        }
669        x_prev_root = left_root[0];
670    }
671    if x_prev_root > 1e-9 * m {
672        push(line([x_prev_root, -hf], [0.0, -hf])?, "G", 0);
673    }
674    push(line([0.0, -hf], [0.0, base])?, "E0", 0);
675    // Share every junction exactly.
676    snap_junctions(&mut curves);
677    let data = GearData {
678        pitch_diameter: f64::INFINITY,
679        tooth_thickness: 2.0 * w,
680        tip_thickness: 2.0 * tip_half,
681        ..GearData::default()
682    };
683    Ok(GearSection { curves, data })
684}
685
686/// A rack solid: the section extruded along +z by the face width; names as
687/// [`rack_section`], then `F` (z = 0) and `B` (z = width).
688pub fn rack_solid(rack: &Rack) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
689    let beta = rack.helix_angle;
690    if !(beta.abs().to_degrees() <= 45.0 + 1e-9) {
691        return Err(refuse("bad_helix", format!("The rack's helix angle must be between −45° and 45° (it is {:.4}°).", beta.to_degrees())));
692    }
693    // A helical rack's transverse section (the plane z = const) is the rack of
694    // the transverse module and pressure angle; the teeth run along (tan beta, 0, 1).
695    let degrees = rack.pressure_angle.to_degrees();
696    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&degrees) {
697        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and 35° (it is {degrees}°).")));
698    }
699    if beta == 0.0 {
700        // Straight teeth: the rack exactly as given (no transverse conversion).
701        let section = rack_section(rack)?;
702        let solid = extrude_section(&section, rack.face_width)?;
703        let mut names: Vec<String> = section.curves.iter().map(rack_suffix).collect();
704        names.push("F".into());
705        names.push("B".into());
706        return Ok((solid, names, section.data));
707    }
708    // A helical rack's teeth are straight prisms along (tan beta, 0, 1). Its
709    // normal section (across the teeth) is the basic rack; the transverse
710    // section (z = const) is that section stretched along the rack by
711    // 1 / cos beta, exactly: lines stay lines, the root rounds become ellipses
712    // (still rational quadratic arcs).
713    let c = beta.cos();
714    let mut section = rack_section(rack)?;
715    for piece in &mut section.curves {
716        for point in &mut piece.curve.control_points {
717            point.x /= c;
718        }
719    }
720    // The recorded thicknesses are read along the rack (transverse), as the section is.
721    section.data.tooth_thickness /= c;
722    section.data.tip_thickness /= c;
723    let curves: Vec<NurbsCurve> = section.curves.iter().map(|piece| piece.curve.clone()).collect();
724    let direction = Vec3::new(beta.tan(), 0.0, 1.0);
725    let solid = extrude_profile_brep(&curves, direction, rack.face_width / c)?;
726    let mut names: Vec<String> = section.curves.iter().map(rack_suffix).collect();
727    names.push("F".into());
728    names.push("B".into());
729    Ok((solid, names, section.data))
730}
731
732fn rack_suffix(piece: &SectionCurve) -> String {
733    match piece.role {
734        "BASE" | "E0" | "E1" => piece.role.to_string(),
735        _ => piece.suffix(),
736    }
737}
738
739/// Share every junction of a closed loop exactly: each curve ends on the next one's first point.
740fn snap_junctions(curves: &mut [SectionCurve]) {
741    let count = curves.len();
742    for index in 0..count {
743        let start = curves[(index + 1) % count].curve.control_points[0];
744        let curve = &mut curves[index].curve;
745        let last = curve.control_points.len() - 1;
746        let w = curve.control_points[last].w;
747        curve.control_points[last] = Vec4 { x: start.x / start.w * w, y: start.y / start.w * w, z: start.z / start.w * w, w };
748    }
749}
750
751/// An internal (ring) gear: involute tooth spaces cut into the inside of a
752/// ring. Lengths in model units, angles in radians, coefficients × module.
753#[derive(Clone, Debug)]
754pub struct RingGear {
755    pub module: f64,
756    pub teeth: usize,
757    pub pressure_angle: f64,
758    /// Profile shift: the cutter moved outward by x · module (tip and root
759    /// circles grow by x · module, the spaces widen by 2 x m tan alpha).
760    pub profile_shift: f64,
761    pub addendum: f64,
762    pub dedendum: f64,
763    /// Radius of the root fillet (× module): an exact arc tangent to the
764    /// flank and the root circle.
765    pub root_fillet: f64,
766    /// Circumferential backlash added to each tooth space on the reference circle.
767    pub backlash: f64,
768    pub face_width: f64,
769    /// Radial wall beyond the root circle.
770    pub rim: f64,
771}
772
773impl Default for RingGear {
774    fn default() -> Self {
775        Self {
776            module: 2.0,
777            teeth: 60,
778            pressure_angle: 20f64.to_radians(),
779            profile_shift: 0.0,
780            addendum: 1.0,
781            dedendum: 1.25,
782            root_fillet: 0.38,
783            backlash: 0.0,
784            face_width: 10.0,
785            rim: 6.0,
786        }
787    }
788}
789
790/// The inner (toothed) loop of a ring gear, counter-clockwise about +z, and its data.
791/// Roles per tooth space k: `R<k>` flank on its clockwise side, `V<k>` its
792/// fillet, `G<k>` the root land, `W<k>`, `L<k>`, then `K<k>` the tip land of
793/// the ring tooth after the space.
794pub fn ring_section(gear: &RingGear) -> Result<GearSection, KernelRefusal> {
795    ring_section_checked(gear, 35.0)
796}
797
798fn ring_section_checked(gear: &RingGear, max_pressure_degrees: f64) -> Result<GearSection, KernelRefusal> {
799    let m = gear.module;
800    let positive = |value: f64, what: &str| {
801        if value.is_finite() && value > 0.0 {
802            Ok(())
803        } else {
804            Err(refuse("gear_input", format!("The {what} must be greater than zero (it is {value}).")))
805        }
806    };
807    positive(m, "module")?;
808    positive(gear.face_width, "face width")?;
809    positive(gear.addendum, "addendum coefficient")?;
810    positive(gear.dedendum, "dedendum coefficient")?;
811    positive(gear.rim, "rim thickness")?;
812    if gear.teeth < 6 {
813        return Err(refuse("gear_input", format!("An internal gear needs at least 6 teeth (it has {}).", gear.teeth)));
814    }
815    let degrees = gear.pressure_angle.to_degrees();
816    if !(10.0 - 1e-9..=max_pressure_degrees + 1e-9).contains(&degrees) {
817        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and {max_pressure_degrees}° (it is {degrees}°).")));
818    }
819    if !(gear.root_fillet >= 0.0) || !(gear.backlash >= 0.0) || !gear.profile_shift.is_finite() {
820        return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
821    }
822    let z = gear.teeth as f64;
823    let alpha = gear.pressure_angle;
824    let r = m * z / 2.0;
825    let r_b = r * alpha.cos();
826    let r_a = r - (gear.addendum - gear.profile_shift) * m; // inner (tip) circle
827    let r_f = r + (gear.dedendum + gear.profile_shift) * m; // outer (root) circle
828    let rho = gear.root_fillet * m;
829    let half_pitch = PI / z;
830    let tolerance = GEAR_FIT_TOLERANCE * m;
831    if r_a <= r_b + 1e-9 * m {
832        return Err(refuse(
833            "tip_inside_base",
834            format!(
835                "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.",
836                2.0 * r_a,
837                2.0 * r_b
838            ),
839        ));
840    }
841    // Half the SPACE angle at a radius: the space is shaped as an external tooth.
842    let space = PI * m / 2.0 + 2.0 * gear.profile_shift * m * alpha.tan() + gear.backlash;
843    let involute = |angle: f64| angle.tan() - angle;
844    let half_space = |radius: f64| space / (2.0 * r) + involute(alpha) - involute((r_b / radius).min(1.0).acos());
845    let flank = |radius: f64| {
846        let angle = half_space(radius);
847        [radius * angle.cos(), radius * angle.sin()]
848    };
849    if half_space(r_a) >= half_pitch - 1e-6 * m / r_a {
850        return Err(refuse(
851            "pointed_tip",
852            "The ring teeth come to a point at the tip circle: reduce the profile shift, the backlash or the addendum.".into(),
853        ));
854    }
855    // The spaces narrow outward: one that closes before the root circle has
856    // crossed flanks (read unwrapped, from the closed form).
857    if half_space(r_f) <= 1e-6 * m / r_f {
858        let (mut lo, mut hi) = (r_a, r_f);
859        for _ in 0..200 {
860            let mid = 0.5 * (lo + hi);
861            if half_space(mid) > 0.0 { lo = mid } else { hi = mid }
862        }
863        return Err(refuse(
864            "teeth_overlap",
865            format!(
866                "The tooth spaces close at d = {:.4}, inside the root circle (d = {:.4}); reduce the dedendum or the profile shift.",
867                2.0 * lo,
868                2.0 * r_f
869            ),
870        ));
871    }
872    // The fillet: a circle of radius rho tangent to the flank (left side of
873    // space 0, at T) and inside the root circle. Its centre is T moved by rho
874    // along the flank's normal into the space; solve |centre| = r_f - rho for T.
875    let normal_into_space = |radius: f64| {
876        let h = 1e-6 * m;
877        let (a, b) = (flank(radius - h), flank(radius + h));
878        let (tx, ty) = (b[0] - a[0], b[1] - a[1]);
879        let length = tx.hypot(ty);
880        // The space lies at smaller angles than its left flank: the normal turned clockwise from the outward tangent.
881        [ty / length, -tx / length]
882    };
883    let centre_at = |radius: f64| {
884        let point = flank(radius);
885        let n = normal_into_space(radius);
886        [point[0] + rho * n[0], point[1] + rho * n[1]]
887    };
888    let (join_radius, centre) = if rho == 0.0 {
889        (r_f, flank(r_f))
890    } else {
891        let target = r_f - rho;
892        let (mut lo, mut hi) = (r_a, r_f);
893        if radius_of(centre_at(lo)) > target {
894            return Err(refuse("root_fillet_too_large", "The root fillet is too large for the tooth depth; lower it.".into()));
895        }
896        for _ in 0..200 {
897            let mid = 0.5 * (lo + hi);
898            if radius_of(centre_at(mid)) < target { lo = mid } else { hi = mid }
899        }
900        let radius = 0.5 * (lo + hi);
901        (radius, centre_at(radius))
902    };
903    let root_angle = polar_angle(centre);
904    if rho > 0.0 && root_angle <= 1e-9 {
905        return Err(refuse(
906            "root_fillet_too_large",
907            "The root fillet is larger than fits the tooth space; lower it.".into(),
908        ));
909    }
910    let tip_angle = half_space(r_a);
911    // Left flank of space 0 from its root end (join) in to the tip circle.
912    let flank_fit = fit_planar(&|radius| flank(radius), r_a, join_radius, tolerance)?; // tip -> join
913    let mut space: Vec<(&'static str, NurbsCurve)> = Vec::new();
914    // Clockwise side (negative angles), outward: mirrored left flank (tip -> join), fillet, land, fillet, flank.
915    space.push(("R", mirrored(&flank_fit)));
916    if rho > 0.0 {
917        // The left fillet runs counter-clockwise about its centre from the root
918        // tangent point (straight out from the centre) round to the flank join.
919        let join = flank(join_radius);
920        let from = root_angle;
921        let mut to = (join[1] - centre[1]).atan2(join[0] - centre[0]);
922        while to <= from {
923            to += TAU;
924        }
925        let left = centred_arc(centre, rho, from, to)?; // root -> join
926        space.push(("V", mirrored(&left).reversed().map_err(|e| refuse("gear_arc", e))?));
927        space.push(("G", arc(r_f, -root_angle, root_angle)?));
928        space.push(("W", left));
929    } else {
930        space.push(("G", arc(r_f, -root_angle, root_angle)?));
931    }
932    space.push(("L", flank_fit.reversed().map_err(|e| refuse("gear_fit", e))?));
933    space.push(("K", arc(r_a, tip_angle, 2.0 * half_pitch - tip_angle)?));
934    let mut curves = Vec::with_capacity(space.len() * gear.teeth);
935    for index in 0..gear.teeth {
936        let angle = TAU * index as f64 / z;
937        for (role, curve) in &space {
938            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
939        }
940    }
941    snap_junctions(&mut curves);
942    let data = GearData {
943        pitch_diameter: 2.0 * r,
944        base_diameter: 2.0 * r_b,
945        tip_diameter: 2.0 * r_a,
946        root_diameter: 2.0 * r_f,
947        form_diameter: 2.0 * join_radius,
948        tooth_thickness: 2.0 * r * (half_pitch - half_space(r)),
949        tip_thickness: 2.0 * r_a * (half_pitch - tip_angle),
950        undercut: false,
951        min_shift_without_undercut: 0.0,
952    };
953    Ok(GearSection { curves, data })
954}
955
956/// A ring gear solid: a cylinder of radius root + rim with the toothed loop
957/// cut through it. Its faces carry their role names (`R3`, `K0`, …, `OD` the
958/// outside, `F` at z = 0, `B` at z = width) in `face.name`.
959pub fn ring_solid(gear: &RingGear) -> Result<(BrepSolid, GearData), KernelRefusal> {
960    let section = ring_section(gear)?;
961    let outer = section.data.root_diameter / 2.0 + gear.rim;
962    let axis = Vec3::new(0.0, 0.0, 1.0);
963    let mut blank = crate::make_cylinder_brep(Vec3::new(0.0, 0.0, 0.0), axis, outer, gear.face_width)
964        .map_err(|error| refuse("gear_blank", error))?;
965    for (face, name) in blank.shells[0].faces.iter_mut().zip(["OD", "F", "B"]) {
966        face.name = Some(name.into());
967    }
968    // The tool runs past both faces so no face of it lies on the blank's.
969    let reach = gear.face_width * 0.1 + gear.module;
970    let shifted: Vec<SectionCurve> = section
971        .curves
972        .iter()
973        .map(|piece| SectionCurve { curve: translated(&piece.curve, -reach), role: piece.role, tooth: piece.tooth })
974        .collect();
975    let mut tool = extrude_section(&GearSection { curves: shifted.clone(), data: section.data.clone() }, gear.face_width + 2.0 * reach)?;
976    for (face, piece) in tool.shells[0].faces.iter_mut().zip(&shifted) {
977        face.name = Some(piece.suffix());
978    }
979    let ring = crate::boolean_operation_nary(&[blank, tool], crate::BooleanOperation::Subtract)?;
980    Ok((ring, section.data))
981}
982
983/// A helical (or double helical) ring gear: `gear` in the normal section,
984/// its transverse section screwed through the blank. Names as [`ring_solid`].
985pub fn ring_solid_helical(gear: &RingGear, helix_angle: f64, hand: Hand, herringbone: bool) -> Result<(BrepSolid, GearData), KernelRefusal> {
986    let beta = helix_angle;
987    if !(beta.to_degrees() >= 0.5 - 1e-9 && beta.to_degrees() <= 45.0 + 1e-9) {
988        return Err(refuse("bad_helix", format!("The helix angle must be between 0.5° and 45° (it is {:.4}°).", beta.to_degrees())));
989    }
990    let normal = gear.pressure_angle.to_degrees();
991    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&normal) {
992        return Err(refuse("gear_input", format!("The normal pressure angle must be between 10° and 35° (it is {normal}°).")));
993    }
994    let c = beta.cos();
995    let transverse = RingGear {
996        module: gear.module / c,
997        pressure_angle: (gear.pressure_angle.tan() / c).atan(),
998        profile_shift: gear.profile_shift * c,
999        addendum: gear.addendum * c,
1000        dedendum: gear.dedendum * c,
1001        root_fillet: gear.root_fillet * c,
1002        ..gear.clone()
1003    };
1004    let section = ring_section_checked(&transverse, 60.0)?;
1005    let r = transverse.module * transverse.teeth as f64 / 2.0;
1006    let sign = if hand == Hand::Right { 1.0 } else { -1.0 };
1007    let rate = sign * beta.tan() / r; // turn per unit height
1008    let outer = section.data.root_diameter / 2.0 + gear.rim;
1009    let mut blank = crate::make_cylinder_brep(Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), outer, gear.face_width)
1010        .map_err(|error| refuse("gear_blank", error))?;
1011    for (face, name) in blank.shells[0].faces.iter_mut().zip(["OD", "F", "B"]) {
1012        face.name = Some(name.into());
1013    }
1014    // The tool runs past both faces, turned so that it reads the nominal section at z = 0.
1015    let reach = gear.face_width * 0.1 + transverse.module;
1016    let height = gear.face_width + 2.0 * reach;
1017    let start: Vec<SectionCurve> = section
1018        .curves
1019        .iter()
1020        .map(|piece| SectionCurve { curve: rotated(&piece.curve, -rate * reach), role: piece.role, tooth: piece.tooth })
1021        .collect();
1022    let twist = if herringbone { Twist::Herringbone { turn: rate * height } } else { Twist::Helical { turn: rate * height } };
1023    let tool = twisted_prism(&GearSection { curves: start.clone(), data: section.data.clone() }, height, twist, GEAR_FIT_TOLERANCE * transverse.module)?;
1024    let shift = crate::AffineTransform::new([1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, -reach, 0.0, 0.0, 0.0, 1.0])
1025        .map_err(|e| refuse("gear_transform", e))?;
1026    let mut tool = crate::transform_brep(&tool, shift, false).map_err(|e| refuse("gear_transform", e))?;
1027    for (face, piece) in tool.shells[0].faces.iter_mut().zip(&start) {
1028        face.name = Some(piece.suffix());
1029    }
1030    let ring = crate::boolean_operation_nary(&[blank, tool], crate::BooleanOperation::Subtract)?;
1031    Ok((ring, section.data))
1032}
1033
1034fn translated(curve: &NurbsCurve, dz: f64) -> NurbsCurve {
1035    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();
1036    NurbsCurve::new(curve.degree, curve.knots.clone(), points).expect("a translated curve is a valid curve")
1037}
1038
1039/// Which ISO 606 tooth form a sprocket is cut to.
1040#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1041pub enum SprocketForm {
1042    /// Smallest seating radius, largest flank radius, largest seating angle.
1043    Minimum,
1044    /// Largest seating radius, smallest flank radius, smallest seating angle.
1045    Maximum,
1046    /// The mean of the two.
1047    Mean,
1048}
1049
1050/// A roller-chain sprocket (ISO 606 tooth form; ANSI chains are its A series).
1051#[derive(Clone, Debug)]
1052pub struct Sprocket {
1053    pub pitch: f64,
1054    pub roller_diameter: f64,
1055    pub teeth: usize,
1056    pub form: SprocketForm,
1057    /// Tooth width across the sprocket (the extrusion).
1058    pub width: f64,
1059}
1060
1061/// The section of a roller-chain sprocket, counter-clockwise; every curve is a
1062/// circular arc. Tooth k is centred on angle 2 pi k / z (tooth 0 on +x); gap k
1063/// follows it. Roles: `A<k>` the flank into gap k, `S<k>` its roller seating,
1064/// `C<k>` the flank out of it, `K<k>` the tip land of the tooth after gap k
1065/// (absent when the flanks meet below the tip circle).
1066pub fn sprocket_section(sprocket: &Sprocket) -> Result<GearSection, KernelRefusal> {
1067    let p = sprocket.pitch;
1068    let d1 = sprocket.roller_diameter;
1069    if !(p > 0.0 && d1 > 0.0 && d1 < p && sprocket.width > 0.0) {
1070        return Err(refuse(
1071            "gear_input",
1072            format!("The chain pitch ({p}), the roller diameter ({d1}, less than the pitch) and the width must be positive."),
1073        ));
1074    }
1075    if sprocket.teeth < 6 || sprocket.teeth > 300 {
1076        return Err(refuse("gear_input", format!("A sprocket needs from 6 to 300 teeth (it has {}).", sprocket.teeth)));
1077    }
1078    let z = sprocket.teeth as f64;
1079    let tau = TAU / z;
1080    let d = p / (PI / z).sin();
1081    // ISO 606 tooth form limits.
1082    let ri_min = 0.505 * d1;
1083    let ri_max = 0.505 * d1 + 0.069 * d1.cbrt();
1084    let re_min = 0.008 * d1 * (z * z + 180.0);
1085    let re_max = 0.12 * d1 * (z + 2.0);
1086    let a_min = (120.0 - 90.0 / z).to_radians();
1087    let a_max = (140.0 - 90.0 / z).to_radians();
1088    let da_min = d + p * (1.0 - 1.6 / z) - d1;
1089    let da_max = d + 1.25 * p - d1;
1090    let (ri, re, alpha, da) = match sprocket.form {
1091        SprocketForm::Minimum => (ri_min, re_max, a_max, da_min),
1092        SprocketForm::Maximum => (ri_max, re_min, a_min, da_max),
1093        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)),
1094    };
1095    let ra = da / 2.0;
1096    // Gap 0 centred on angle tau / 2 is built centred on +x, then turned.
1097    let c = [d / 2.0, 0.0];
1098    let u = [-(alpha / 2.0).cos(), (alpha / 2.0).sin()]; // roller centre -> upper seating end
1099    let t_up = [c[0] + ri * u[0], c[1] + ri * u[1]];
1100    let f = [c[0] + (ri + re) * u[0], c[1] + (ri + re) * u[1]]; // the upper flank's centre
1101    // The upper flank: circle (f, re) from t_up outward. The tooth after the gap
1102    // is centred on the line at angle tau / 2 (built frame).
1103    let half = tau / 2.0;
1104    let a_t = (t_up[1] - f[1]).atan2(t_up[0] - f[0]);
1105    // Walk the flank circle from t_up in the sense that moves away from the axis.
1106    let on_flank = |angle: f64| [f[0] + re * angle.cos(), f[1] + re * angle.sin()];
1107    let step = 1e-4;
1108    let sense = if radius_of(on_flank(a_t + step)) > radius_of(on_flank(a_t - step)) { 1.0 } else { -1.0 };
1109    // Find where the flank reaches the tip circle or the tooth centre line, whichever first.
1110    let reach = |angle: f64| {
1111        let q = on_flank(angle);
1112        (radius_of(q) >= ra, polar_angle(q) >= half)
1113    };
1114    let (mut lo, mut hi) = (0.0, PI / 2.0);
1115    if !(reach(a_t + sense * hi).0 || reach(a_t + sense * hi).1) {
1116        return Err(refuse("gear_input", "The sprocket flank does not reach the tip circle.".into()));
1117    }
1118    for _ in 0..200 {
1119        let mid = 0.5 * (lo + hi);
1120        let (tip, centre) = reach(a_t + sense * mid);
1121        if tip || centre { hi = mid } else { lo = mid }
1122    }
1123    let a_end = a_t + sense * hi;
1124    let end = on_flank(a_end);
1125    let pointed = polar_angle(end) >= half - 1e-12 || radius_of(end) < ra - 1e-9 * p;
1126    let (a_end, end) = if pointed {
1127        // Land exactly on the tooth centre line.
1128        let (mut lo, mut hi) = (0.0, hi);
1129        for _ in 0..200 {
1130            let mid = 0.5 * (lo + hi);
1131            if polar_angle(on_flank(a_t + sense * mid)) >= half { hi = mid } else { lo = mid }
1132        }
1133        let a = a_t + sense * hi;
1134        (a, on_flank(a))
1135    } else {
1136        (a_end, end)
1137    };
1138    let flank_arc = |from: f64, to: f64| -> Result<NurbsCurve, KernelRefusal> {
1139        if to > from { centred_arc(f, re, from, to) } else { centred_arc(f, re, to, from)?.reversed().map_err(|e| refuse("gear_arc", e)) }
1140    };
1141    let upper = flank_arc(a_t, a_end)?; // t_up -> end
1142    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
1143    let lower = mirrored(&upper).reversed().map_err(|e| refuse("gear_arc", e))?; // end' -> t_down
1144    let mut gap: Vec<(&'static str, NurbsCurve)> = vec![("A", lower), ("S", seat), ("C", upper)];
1145    let tip_angle = polar_angle(end);
1146    if !pointed {
1147        gap.push(("K", arc(ra, tip_angle, tau - tip_angle)?));
1148    }
1149    let mut curves = Vec::with_capacity(gap.len() * sprocket.teeth);
1150    for index in 0..sprocket.teeth {
1151        let angle = tau * index as f64 + half;
1152        for (role, curve) in &gap {
1153            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
1154        }
1155    }
1156    snap_junctions(&mut curves);
1157    let data = GearData {
1158        pitch_diameter: d,
1159        tip_diameter: if pointed { 2.0 * radius_of(end) } else { da },
1160        root_diameter: d - 2.0 * ri,
1161        ..GearData::default()
1162    };
1163    Ok(GearSection { curves, data })
1164}
1165
1166/// A sprocket solid: the section extruded along +z by the width; names as
1167/// [`sprocket_section`], then `F` and `B`.
1168pub fn sprocket_solid(sprocket: &Sprocket) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
1169    let section = sprocket_section(sprocket)?;
1170    let solid = extrude_section(&section, sprocket.width)?;
1171    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
1172    names.push("F".into());
1173    names.push("B".into());
1174    Ok((solid, names, section.data))
1175}
1176
1177/// The turn of a twisted prism's section along its height: `theta(t)` at
1178/// `t = z / width` in [0, 1], with an optional crease at `t = 1/2` (a
1179/// herringbone's apex).
1180#[derive(Clone, Copy, Debug)]
1181pub enum Twist {
1182    /// theta = turn · t (a helical gear: a screw motion).
1183    Helical { turn: f64 },
1184    /// theta = turn · (1/2 − |t − 1/2|): out by `turn / 2` to the middle and back.
1185    Herringbone { turn: f64 },
1186}
1187
1188impl Twist {
1189    fn angle(&self, t: f64) -> f64 {
1190        match *self {
1191            Twist::Helical { turn } => turn * t,
1192            Twist::Herringbone { turn } => turn * (0.5 - (t - 0.5).abs()),
1193        }
1194    }
1195
1196    fn rate(&self, t: f64, after_crease: bool) -> f64 {
1197        match *self {
1198            Twist::Helical { turn } => turn,
1199            Twist::Herringbone { turn } => {
1200                if t < 0.5 || (t == 0.5 && !after_crease) { turn } else { -turn }
1201            }
1202        }
1203    }
1204
1205    fn total_turn(&self) -> f64 {
1206        match *self {
1207            Twist::Helical { turn } => turn.abs(),
1208            Twist::Herringbone { turn } => turn.abs(),
1209        }
1210    }
1211}
1212
1213/// The axial basis of a twisted prism: cubic Hermite spans in t carrying
1214/// (cos theta, sin theta, t), with doubled interior knots (C1) and a tripled
1215/// knot at a crease. Returns (knots, per control point (cos, sin, t)).
1216fn twist_basis(twist: Twist, reach: f64, tolerance: f64) -> Result<(Vec<f64>, Vec<[f64; 3]>), KernelRefusal> {
1217    let crease = matches!(twist, Twist::Herringbone { .. });
1218    // Hermite cubic error of cos/sin over a span of turn d: about reach · d^4 / 384.
1219    let per = (384.0 * tolerance / reach.max(1e-12)).powf(0.25);
1220    let needed = twist.total_turn() / per;
1221    if !(needed <= 4096.0) {
1222        return Err(refuse(
1223            "twist_too_long",
1224            format!(
1225                "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).",
1226                twist.total_turn() / TAU,
1227                4096.0 * per / TAU
1228            ),
1229        ));
1230    }
1231    let mut spans = (needed.ceil() as usize).max(1);
1232    if crease && spans % 2 == 1 {
1233        spans += 1;
1234    }
1235    let value = |t: f64| {
1236        let a = twist.angle(t);
1237        [a.cos(), a.sin(), t]
1238    };
1239    let slope = |t: f64, after: bool| {
1240        let a = twist.angle(t);
1241        let r = twist.rate(t, after);
1242        [-a.sin() * r, a.cos() * r, 1.0]
1243    };
1244    let mut knots = vec![0.0; 4];
1245    let mut points = vec![value(0.0)];
1246    for index in 0..spans {
1247        let (t0, t1) = (index as f64 / spans as f64, (index + 1) as f64 / spans as f64);
1248        let h = (t1 - t0) / 3.0;
1249        let (p0, p1) = (value(t0), value(t1));
1250        let (d0, d1) = (slope(t0, true), slope(t1, false));
1251        points.push([p0[0] + d0[0] * h, p0[1] + d0[1] * h, p0[2] + d0[2] * h]);
1252        points.push([p1[0] - d1[0] * h, p1[1] - d1[1] * h, p1[2] - d1[2] * h]);
1253        let last = index + 1 == spans;
1254        let at_crease = crease && 2 * (index + 1) == spans;
1255        if last {
1256            points.push(p1);
1257        } else if at_crease {
1258            points.push(p1);
1259            knots.extend([t1, t1, t1]);
1260        } else {
1261            knots.extend([t1, t1]);
1262        }
1263    }
1264    knots.extend([1.0; 4]);
1265    Ok((knots, points))
1266}
1267
1268/// Carry a section curve along the twist: the curve turned by theta and lifted
1269
1270
1271/// A counter-clockwise section (z = 0) carried up to z = width while turning
1272/// by `twist`: side faces in section order, then the face at z = 0, then the
1273/// face at z = width (exactly the section turned by the end angle).
1274pub fn twisted_prism(section: &GearSection, width: f64, twist: Twist, tolerance: f64) -> Result<BrepSolid, KernelRefusal> {
1275    if !(width > 0.0) {
1276        return Err(refuse("gear_input", format!("The face width must be greater than zero (it is {width}).")));
1277    }
1278    let reach = section
1279        .curves
1280        .iter()
1281        .flat_map(|c| c.curve.control_points.iter())
1282        .map(|p| (p.x / p.w).hypot(p.y / p.w))
1283        .fold(0.0, f64::max);
1284    let (knots_v, basis) = twist_basis(twist, reach, tolerance)?;
1285    let rows = |p: Vec4| -> Vec<Vec4> {
1286        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()
1287    };
1288    prism_by_rows(section, 3, &knots_v, &rows)
1289}
1290
1291/// A planar counter-clockwise section (in a plane z = const) carried along
1292/// v in [0, 1] by `rows`, which maps each homogeneous control point to the
1293/// control points of its v-curve (degree `degree_v` on `knots_v`); the last
1294/// row must again be planar at a constant z (the top cap). Side faces in
1295/// section order, then the face at v = 0, then the face at v = 1.
1296pub fn prism_by_rows(section: &GearSection, degree_v: usize, knots_v: &[f64], rows: &dyn Fn(Vec4) -> Vec<Vec4>) -> Result<BrepSolid, KernelRefusal> {
1297    use crate::sweep_topology::{curve_to_plane_parameters, make_plane, parameter_line, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, ShellRecord, VertexRecord};
1298    let curves: Vec<NurbsCurve> = section.curves.iter().map(|piece| piece.curve.clone()).collect();
1299    let count = curves.len();
1300    let top_of = |curve: &NurbsCurve| -> Result<NurbsCurve, KernelRefusal> {
1301        let points = curve.control_points.iter().map(|p| *rows(*p).last().expect("a row")).collect();
1302        NurbsCurve::new(curve.degree, curve.knots.clone(), points).map_err(|e| refuse("gear_curve", e))
1303    };
1304    let point_of = |p: Vec4| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w);
1305    let unit = |p: Vec4| Vec4 { x: p.x / p.w, y: p.y / p.w, z: p.z / p.w, w: 1.0 };
1306    let starts: Vec<Vec4> = curves.iter().map(|c| c.control_points[0]).collect();
1307    let mut vertices = Vec::with_capacity(2 * count);
1308    for (index, start) in starts.iter().enumerate() {
1309        vertices.push(VertexRecord { id: index as u64 + 1, point: point_of(*start) });
1310    }
1311    for (index, start) in starts.iter().enumerate() {
1312        vertices.push(VertexRecord { id: (count + index) as u64 + 1, point: point_of(*rows(unit(*start)).last().expect("a row")) });
1313    }
1314    let edge_id = |kind: usize, index: usize| 10 + (kind * count + index) as u64;
1315    let mut edges = Vec::with_capacity(3 * count);
1316    let mut tops = Vec::with_capacity(count);
1317    for (index, curve) in curves.iter().enumerate() {
1318        let [start, end] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
1319        let next = (index + 1) % count;
1320        let top = top_of(curve)?;
1321        let axial = NurbsCurve::new(degree_v, knots_v.to_vec(), rows(unit(starts[index]))).map_err(|e| refuse("gear_edge", e))?;
1322        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 });
1323        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 });
1324        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 });
1325        tops.push(top);
1326    }
1327    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));
1328    let mut next_id = 10 + 3 * count as u64 + 1000;
1329    let mut faces = Vec::with_capacity(count + 2);
1330    for (index, curve) in curves.iter().enumerate() {
1331        let [start, end] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
1332        let next = (index + 1) % count;
1333        let coedges = vec![
1334            CoedgeRecord { id: next_id, edge_id: edge_id(0, index), forward: true, pcurve: line([start, 0.0], [end, 0.0])? },
1335            CoedgeRecord { id: next_id + 1, edge_id: edge_id(2, next), forward: true, pcurve: line([end, 0.0], [end, 1.0])? },
1336            CoedgeRecord { id: next_id + 2, edge_id: edge_id(1, index), forward: false, pcurve: line([end, 1.0], [start, 1.0])? },
1337            CoedgeRecord { id: next_id + 3, edge_id: edge_id(2, index), forward: false, pcurve: line([start, 1.0], [start, 0.0])? },
1338        ];
1339        next_id += 4;
1340        let surface_rows: Vec<Vec<Vec4>> = curve.control_points.iter().map(|p| rows(*p)).collect();
1341        let surface = NurbsSurface::new(curve.degree, degree_v, curve.knots.clone(), knots_v.to_vec(), surface_rows).map_err(|e| refuse("gear_surface", e))?;
1342        faces.push(FaceRecord { id: next_id + 1, surface, same_sense: true, loops: vec![LoopRecord { id: next_id, coedges }], name: None });
1343        next_id += 2;
1344    }
1345    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);
1346    let pad = reach * 1.1 + 1.0;
1347    let x_axis = Vec3::new(1.0, 0.0, 0.0);
1348    let y_axis = Vec3::new(0.0, 1.0, 0.0);
1349    let z0 = vertices[0].point.z;
1350    let z1 = vertices[count].point.z;
1351    let bottom_origin = Vec3::new(-pad, -pad, z0);
1352    let mut bottom = Vec::with_capacity(count);
1353    for index in (0..count).rev() {
1354        bottom.push(CoedgeRecord {
1355            id: next_id,
1356            edge_id: edge_id(0, index),
1357            forward: false,
1358            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))?,
1359        });
1360        next_id += 1;
1361    }
1362    faces.push(FaceRecord {
1363        id: next_id + 1,
1364        surface: make_plane(bottom_origin, x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e))?,
1365        same_sense: false,
1366        loops: vec![LoopRecord { id: next_id, coedges: bottom }],
1367        name: None,
1368    });
1369    next_id += 2;
1370    let top_origin = Vec3::new(-pad, -pad, z1);
1371    let mut top = Vec::with_capacity(count);
1372    for (index, curve) in tops.iter().enumerate() {
1373        top.push(CoedgeRecord {
1374            id: next_id,
1375            edge_id: edge_id(1, index),
1376            forward: true,
1377            pcurve: curve_to_plane_parameters(curve, top_origin, x_axis, y_axis).map_err(|e| refuse("gear_pcurve", e))?,
1378        });
1379        next_id += 1;
1380    }
1381    faces.push(FaceRecord {
1382        id: next_id + 1,
1383        surface: make_plane(top_origin, x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e))?,
1384        same_sense: true,
1385        loops: vec![LoopRecord { id: next_id, coedges: top }],
1386        name: None,
1387    });
1388    next_id += 2;
1389    let solid = BrepSolid {
1390        mass_properties_cache: Default::default(),
1391        cells: Default::default(),
1392        id: next_id + 1,
1393        vertices,
1394        edges,
1395        shells: vec![ShellRecord { id: next_id, faces }],
1396        genus: 0,
1397        kind: crate::BodyKind::Solid,
1398    };
1399    let issues = solid.validate();
1400    if issues.is_empty() {
1401        Ok(solid)
1402    } else {
1403        Err(KernelRefusal::internal(KernelStage::Validate, "validate", format!("gear prism is not valid: {issues:?}")))
1404    }
1405}
1406
1407/// Hand of a helical gear's teeth.
1408#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1409pub enum Hand {
1410    Right,
1411    Left,
1412}
1413
1414/// A helical (or, with `herringbone`, double helical) external gear given by
1415/// its normal-section values; `spur` carries them (module = normal module,
1416/// pressure angle = normal pressure angle, coefficients × normal module).
1417#[derive(Clone, Debug)]
1418pub struct HelicalGear {
1419    pub spur: SpurGear,
1420    pub helix_angle: f64,
1421    pub hand: Hand,
1422    pub herringbone: bool,
1423}
1424
1425/// The transverse spur gear a helical gear's every section is (turned).
1426pub fn helical_transverse(gear: &HelicalGear) -> Result<SpurGear, KernelRefusal> {
1427    let beta = gear.helix_angle;
1428    // The pressure angle limits apply to the normal section (the cutter's).
1429    let normal = gear.spur.pressure_angle.to_degrees();
1430    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&normal) {
1431        return Err(refuse("gear_input", format!("The normal pressure angle must be between 10° and 35° (it is {normal}°).")));
1432    }
1433    if !(beta.to_degrees() >= 0.5 - 1e-9 && beta.to_degrees() <= 45.0 + 1e-9) {
1434        return Err(refuse("bad_helix", format!("The helix angle must be between 0.5° and 45° (it is {:.4}°).", beta.to_degrees())));
1435    }
1436    let n = &gear.spur;
1437    let c = beta.cos();
1438    Ok(SpurGear {
1439        module: n.module / c,
1440        teeth: n.teeth,
1441        pressure_angle: (n.pressure_angle.tan() / c).atan(),
1442        profile_shift: n.profile_shift * c,
1443        addendum: n.addendum * c,
1444        dedendum: n.dedendum * c,
1445        // The cutter's tip radius in the transverse section is taken as the
1446        // normal one (the true section of the round is a slightly longer ellipse).
1447        root_fillet: n.root_fillet * c,
1448        backlash: n.backlash,
1449        face_width: n.face_width,
1450    })
1451}
1452
1453/// A helical or herringbone gear solid; names as [`spur_solid`].
1454pub fn helical_solid(gear: &HelicalGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
1455    let transverse = helical_transverse(gear)?;
1456    let section = transverse_section(&transverse)?;
1457    let r = transverse.module * transverse.teeth as f64 / 2.0;
1458    let width = transverse.face_width;
1459    let sign = if gear.hand == Hand::Right { 1.0 } else { -1.0 };
1460    let twist = if gear.herringbone {
1461        // Each half advances by its own half width.
1462        Twist::Herringbone { turn: sign * width * gear.helix_angle.tan() / r }
1463    } else {
1464        Twist::Helical { turn: sign * width * gear.helix_angle.tan() / r }
1465    };
1466    let solid = twisted_prism(&section, width, twist, 0.1 * GEAR_FIT_TOLERANCE * transverse.module)?;
1467    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
1468    names.push("F".into());
1469    names.push("B".into());
1470    Ok((solid, names, section.data))
1471}
1472
1473/// A straight-sided spline (ISO 14 form: `teeth` keys of width `key_width`
1474/// between the minor diameter `minor` and the major diameter `major`).
1475#[derive(Clone, Debug)]
1476pub struct StraightSpline {
1477    pub teeth: usize,
1478    pub minor: f64,
1479    pub major: f64,
1480    pub key_width: f64,
1481    pub length: f64,
1482}
1483
1484fn check_straight_spline(spline: &StraightSpline) -> Result<(), KernelRefusal> {
1485    let StraightSpline { teeth, minor, major, key_width, length } = *spline;
1486    if !(minor > 0.0 && major > minor && key_width > 0.0 && length > 0.0) {
1487        return Err(refuse(
1488            "gear_input",
1489            format!("A spline needs 0 < minor diameter ({minor}) < major diameter ({major}), a positive key width ({key_width}) and length ({length})."),
1490        ));
1491    }
1492    if teeth < 2 || teeth > 100 {
1493        return Err(refuse("gear_input", format!("A spline needs from 2 to 100 keys (it has {teeth}).")));
1494    }
1495    // The keys must not meet on the minor circle.
1496    let half_root = (key_width / minor).asin();
1497    if !(key_width < minor) || 2.0 * half_root >= TAU / teeth as f64 - 1e-9 {
1498        return Err(refuse("keys_overlap", format!("{teeth} keys {key_width} wide do not fit round a {minor} minor diameter.")));
1499    }
1500    Ok(())
1501}
1502
1503/// The section of a straight-sided spline shaft, counter-clockwise; exact
1504/// lines and arcs. Key k is centred on angle 2 pi k / N. Roles: `R<k>`/`L<k>`
1505/// its flanks, `K<k>` its top on the major circle, `G<k>` the root land after it.
1506pub fn straight_spline_section(spline: &StraightSpline) -> Result<GearSection, KernelRefusal> {
1507    check_straight_spline(spline)?;
1508    let (rr, ra, h) = (spline.minor / 2.0, spline.major / 2.0, spline.key_width / 2.0);
1509    let n = spline.teeth as f64;
1510    let foot = [(rr * rr - h * h).sqrt(), h];
1511    let top = [(ra * ra - h * h).sqrt(), h];
1512    let top_angle = (h / ra).asin();
1513    let foot_angle = (h / rr).asin();
1514    let key: Vec<(&'static str, NurbsCurve)> = vec![
1515        ("R", line([foot[0], -h], [top[0], -h])?),
1516        ("K", arc(ra, -top_angle, top_angle)?),
1517        ("L", line(top, foot)?),
1518        ("G", arc(rr, foot_angle, TAU / n - foot_angle)?),
1519    ];
1520    let mut curves = Vec::with_capacity(4 * spline.teeth);
1521    for index in 0..spline.teeth {
1522        let angle = TAU * index as f64 / n;
1523        for (role, curve) in &key {
1524            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
1525        }
1526    }
1527    snap_junctions(&mut curves);
1528    Ok(GearSection { curves, data: GearData { tip_diameter: spline.major, root_diameter: spline.minor, ..GearData::default() } })
1529}
1530
1531/// A spline shaft: the section extruded along +z by the length; names as the
1532/// section's roles, then `F` and `B`.
1533pub fn straight_spline_shaft(spline: &StraightSpline) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
1534    let section = straight_spline_section(spline)?;
1535    let solid = extrude_section(&section, spline.length)?;
1536    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
1537    names.push("F".into());
1538    names.push("B".into());
1539    Ok((solid, names, section.data))
1540}
1541
1542/// Cut a counter-clockwise section through a cylinder of `outside` diameter
1543/// and `length`: a hub. The section's faces keep their role names, the
1544/// cylinder's are `OD`, `F` and `B` (all in `face.name`).
1545pub fn hub_from_section(section: &GearSection, outside: f64, length: f64) -> Result<BrepSolid, KernelRefusal> {
1546    // The section's true outer radius, read off the curves (a rational arc's
1547    // middle control point lies outside the arc).
1548    let mut reach: f64 = 0.0;
1549    for piece in &section.curves {
1550        let [t0, t1] = piece.curve.domain().map_err(|e| refuse("gear_domain", e))?;
1551        for i in 0..=32 {
1552            let p = piece.curve.evaluate(t0 + (t1 - t0) * i as f64 / 32.0).map_err(|e| refuse("gear_eval", e))?;
1553            reach = reach.max(p.x.hypot(p.y));
1554        }
1555    }
1556    if !(outside / 2.0 > reach + 1e-9) {
1557        return Err(refuse(
1558            "hub_too_small",
1559            format!("The hub's outside diameter ({outside}) must be larger than its spline's major diameter ({:.4}).", 2.0 * reach),
1560        ));
1561    }
1562    let mut blank = crate::make_cylinder_brep(Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), outside / 2.0, length)
1563        .map_err(|error| refuse("gear_blank", error))?;
1564    for (face, name) in blank.shells[0].faces.iter_mut().zip(["OD", "F", "B"]) {
1565        face.name = Some(name.into());
1566    }
1567    let extra = 0.1 * length + 0.1 * reach;
1568    let shifted: Vec<SectionCurve> = section
1569        .curves
1570        .iter()
1571        .map(|piece| SectionCurve { curve: translated(&piece.curve, -extra), role: piece.role, tooth: piece.tooth })
1572        .collect();
1573    let mut tool = extrude_section(&GearSection { curves: shifted.clone(), data: section.data.clone() }, length + 2.0 * extra)?;
1574    for (face, piece) in tool.shells[0].faces.iter_mut().zip(&shifted) {
1575        face.name = Some(piece.suffix());
1576    }
1577    crate::boolean_operation_nary(&[blank, tool], crate::BooleanOperation::Subtract)
1578}
1579
1580/// A spline hub: the shaft's section (nominal size) cut through a cylinder.
1581pub fn straight_spline_hub(spline: &StraightSpline, outside: f64) -> Result<(BrepSolid, GearData), KernelRefusal> {
1582    let section = straight_spline_section(spline)?;
1583    let hub = hub_from_section(&section, outside, spline.length)?;
1584    Ok((hub, section.data))
1585}
1586
1587/// A timing-belt pulley with straight-sided grooves (ISO 5294 Table 2 form;
1588/// the metric trapezoidal profiles the same way): every curve a line or an arc.
1589#[derive(Clone, Debug)]
1590pub struct TimingPulley {
1591    /// Belt pitch.
1592    pub pitch: f64,
1593    pub teeth: usize,
1594    /// Pitch line differential 2a: outside diameter = pitch z / pi - 2a.
1595    pub pld: f64,
1596    /// Groove bottom width bw.
1597    pub bottom_width: f64,
1598    /// Groove depth hg (from the outside diameter).
1599    pub depth: f64,
1600    /// Groove side angle to the radial direction, each side (half of 2 beta).
1601    pub side_angle: f64,
1602    /// Bottom (root) corner radius rb.
1603    pub bottom_radius: f64,
1604    /// Top (tip) corner radius rt.
1605    pub top_radius: f64,
1606    pub width: f64,
1607}
1608
1609/// An arc about `centre` from `from` to `to` (both on it), counter-clockwise
1610/// when `ccw`, else clockwise.
1611fn arc_through(centre: [f64; 2], from: [f64; 2], to: [f64; 2], ccw: bool) -> Result<NurbsCurve, KernelRefusal> {
1612    let radius = (from[0] - centre[0]).hypot(from[1] - centre[1]);
1613    let a0 = (from[1] - centre[1]).atan2(from[0] - centre[0]);
1614    let a1 = (to[1] - centre[1]).atan2(to[0] - centre[0]);
1615    if ccw {
1616        let mut end = a1;
1617        while end <= a0 {
1618            end += TAU;
1619        }
1620        centred_arc(centre, radius, a0, end)
1621    } else {
1622        let mut start = a1;
1623        while start <= a0 - TAU {
1624            start += TAU;
1625        }
1626        while start >= a0 {
1627            start -= TAU;
1628        }
1629        centred_arc(centre, radius, start, a0)?.reversed().map_err(|e| refuse("gear_arc", e))
1630    }
1631}
1632
1633/// The pulley section, counter-clockwise. Groove k is centred on angle
1634/// 2 pi (k + 1/2) / z (tooth k on angle 2 pi k / z). Roles per groove k, in
1635/// order: `Q<k>` the top corner arc into it, `A<k>` its first side, `U<k>`
1636/// the bottom corner arc, `S<k>` the bottom, `D<k>` the other bottom corner
1637/// arc, `C<k>` the other side, `P<k>` the top corner arc out of it, `K<k>`
1638/// the land of the next tooth on the outside diameter.
1639pub fn timing_pulley_section(pulley: &TimingPulley) -> Result<GearSection, KernelRefusal> {
1640    let TimingPulley { pitch, teeth, pld, bottom_width, depth, side_angle, bottom_radius, top_radius, width } = pulley.clone();
1641    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) {
1642        return Err(refuse("gear_input", "The pulley's pitch, groove sizes and width must be positive.".into()));
1643    }
1644    if !(0.0..60f64.to_radians()).contains(&side_angle) {
1645        return Err(refuse("gear_input", "The groove side angle must be between 0° and 60°.".into()));
1646    }
1647    if teeth < 6 || teeth > 400 {
1648        return Err(refuse("gear_input", format!("A pulley needs from 6 to 400 teeth (it has {teeth}).")));
1649    }
1650    let z = teeth as f64;
1651    let ro = pitch * z / PI / 2.0 - pld / 2.0;
1652    let x_bottom = ro - depth;
1653    if !(x_bottom > 0.0) {
1654        return Err(refuse("gear_input", "The groove is deeper than the pulley's radius.".into()));
1655    }
1656    let tau = TAU / z;
1657    let (s, c) = side_angle.sin_cos();
1658    let side = [c, s]; // outward along the upper side
1659    let normal = [-s, c]; // from the upper side into the material
1660    let corner = [x_bottom, bottom_width / 2.0];
1661    // The upper side meets the outside circle at |corner + t side| = ro.
1662    let b = corner[0] * side[0] + corner[1] * side[1];
1663    let t_top = -b + (b * b - (corner[0] * corner[0] + corner[1] * corner[1] - ro * ro)).sqrt();
1664    let top = [corner[0] + t_top * side[0], corner[1] + t_top * side[1]];
1665    // Bottom corner fillet: between the bottom (direction +y) and the side; the
1666    // path turns right there (clockwise arc). Interior turn angle phi = 90° - beta.
1667    let turn = PI / 2.0 - side_angle;
1668    let reach_b = bottom_radius * (turn / 2.0).tan();
1669    let t1 = [corner[0], corner[1] - reach_b];
1670    let t2 = [corner[0] + reach_b * side[0], corner[1] + reach_b * side[1]];
1671    let centre_b = [t1[0] + bottom_radius, t1[1]];
1672    // Top corner fillet: tangent to the side (offset into the material) and
1673    // inside the outside circle (centre at ro - rt).
1674    let rt = top_radius;
1675    let base = [corner[0] + rt * normal[0], corner[1] + rt * normal[1]];
1676    let bb = base[0] * side[0] + base[1] * side[1];
1677    let disc = bb * bb - (base[0] * base[0] + base[1] * base[1] - (ro - rt) * (ro - rt));
1678    if disc < 0.0 {
1679        return Err(refuse("gear_input", "The groove's top radius does not fit.".into()));
1680    }
1681    let t_c = -bb + disc.sqrt();
1682    let centre_t = [base[0] + t_c * side[0], base[1] + t_c * side[1]];
1683    let t3 = [corner[0] + t_c * side[0], corner[1] + t_c * side[1]];
1684    let scale = ro / (centre_t[0].hypot(centre_t[1]));
1685    let t4 = [centre_t[0] * scale, centre_t[1] * scale];
1686    let land_start = polar_angle(t4);
1687    if land_start >= tau / 2.0 - 1e-9 || reach_b > t_c + 1e-12 || t1[1] < 0.0 {
1688        return Err(refuse(
1689            "groove_too_wide",
1690            format!("The grooves and their corner radii do not fit the pitch at {teeth} teeth; add teeth or reduce the radii."),
1691        ));
1692    }
1693    let _ = top;
1694    // The upper half of groove 0, outward: bottom half line, D, C, P.
1695    let mut upper: Vec<(&'static str, NurbsCurve)> = Vec::new();
1696    if bottom_radius > 0.0 {
1697        upper.push(("D", arc_through(centre_b, t1, t2, false)?));
1698    }
1699    upper.push(("C", line(t2, t3)?));
1700    if rt > 0.0 {
1701        upper.push(("P", arc_through(centre_t, t3, t4, true)?));
1702    }
1703    let mut groove: Vec<(&'static str, NurbsCurve)> = Vec::new();
1704    let lower_roles = |role: &'static str| match role {
1705        "D" => "U",
1706        "C" => "A",
1707        _ => "Q",
1708    };
1709    for (role, curve) in upper.iter().rev() {
1710        groove.push((lower_roles(role), mirrored(curve).reversed().map_err(|e| refuse("gear_arc", e))?));
1711    }
1712    groove.push(("S", line([t1[0], -t1[1]], t1)?));
1713    groove.extend(upper.into_iter());
1714    groove.push(("K", arc(ro, land_start, tau - land_start)?));
1715    let mut curves = Vec::with_capacity(groove.len() * teeth);
1716    for index in 0..teeth {
1717        let angle = tau * index as f64 + tau / 2.0;
1718        for (role, curve) in &groove {
1719            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
1720        }
1721    }
1722    snap_junctions(&mut curves);
1723    let data = GearData { pitch_diameter: pitch * z / PI, tip_diameter: 2.0 * ro, root_diameter: 2.0 * x_bottom, ..GearData::default() };
1724    Ok(GearSection { curves, data })
1725}
1726
1727/// A pulley solid: the section extruded along +z by the width; names as the
1728/// section's roles, then `F` and `B`.
1729pub fn timing_pulley_solid(pulley: &TimingPulley) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
1730    let section = timing_pulley_section(pulley)?;
1731    let solid = extrude_section(&section, pulley.width)?;
1732    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
1733    names.push("F".into());
1734    names.push("B".into());
1735    Ok((solid, names, section.data))
1736}
1737
1738/// A ratchet wheel: `teeth` teeth on `outside` diameter, `depth` deep. A saw
1739/// tooth has a locking face (leaning `lean` back from radial, so a pawl is drawn
1740/// in under load) and a straight back; a symmetric tooth leans both faces
1741/// equally (for a reversible pawl). Teeth lock against counter-clockwise turning
1742/// when `clockwise_locks` is false.
1743#[derive(Clone, Debug)]
1744pub struct Ratchet {
1745    pub teeth: usize,
1746    pub outside: f64,
1747    pub depth: f64,
1748    pub lean: f64,
1749    pub symmetric: bool,
1750    pub clockwise_locks: bool,
1751    pub width: f64,
1752}
1753
1754/// The ratchet section, counter-clockwise; straight lines only. Roles per
1755/// tooth k (tip k on angle 2 pi k / z): `LK<k>` the locking face below its
1756/// tip, `BK<k>` the back running up to it.
1757pub fn ratchet_section(ratchet: &Ratchet) -> Result<GearSection, KernelRefusal> {
1758    let Ratchet { teeth, outside, depth, lean, symmetric, clockwise_locks, width } = ratchet.clone();
1759    if !(outside > 0.0 && depth > 0.0 && depth < outside / 2.0 && width > 0.0) {
1760        return Err(refuse("gear_input", format!("A ratchet needs a positive outside diameter ({outside}), a depth ({depth}) under its radius and a positive width.")));
1761    }
1762    if teeth < 3 || teeth > 360 {
1763        return Err(refuse("gear_input", format!("A ratchet needs from 3 to 360 teeth (it has {teeth}).")));
1764    }
1765    if !(lean >= 0.0 && lean.to_degrees() <= 30.0) {
1766        return Err(refuse("gear_input", "The locking face lean must be between 0° and 30°.".into()));
1767    }
1768    let z = teeth as f64;
1769    let tau = TAU / z;
1770    let ra = outside / 2.0;
1771    let rf = ra - depth;
1772    // Tooth 0's tip on +x. The locking face runs from the tip down to the root
1773    // at a polar angle `foot` ahead of the tip (counter-clockwise), leaning back.
1774    // A radial face has foot = 0; leaning back by `lean` moves the root point
1775    // forward along the face's direction: solve |tip + t d| = rf.
1776    let tip = [ra, 0.0];
1777    let face_angle = PI + lean; // pointing inward, tilted to +y by `lean`
1778    let d = [face_angle.cos(), face_angle.sin()];
1779    let b = tip[0] * d[0] + tip[1] * d[1];
1780    let t = -b - (b * b - (ra * ra - rf * rf)).sqrt();
1781    let root = [tip[0] + t * d[0], tip[1] + t * d[1]];
1782    let foot = polar_angle(root);
1783    let (lock, back) = if symmetric {
1784        // Both faces meet at the root halfway between tips, each leaning equally.
1785        let mid = [rf * (tau / 2.0).cos(), rf * (tau / 2.0).sin()];
1786        let lock = line(tip, mid)?;
1787        let next = [ra * tau.cos(), ra * tau.sin()];
1788        (lock, line(mid, next)?)
1789    } else {
1790        if foot >= tau - 1e-9 {
1791            return Err(refuse("gear_input", "The locking faces overlap: fewer teeth, less depth or less lean.".into()));
1792        }
1793        let next = [ra * tau.cos(), ra * tau.sin()];
1794        (line(tip, root)?, line(root, next)?)
1795    };
1796    // Counter-clockwise traversal from tip k: locking face down, back up to tip k + 1.
1797    let mut curves = Vec::with_capacity(2 * teeth);
1798    for index in 0..teeth {
1799        let angle = tau * index as f64;
1800        curves.push(SectionCurve { curve: rotated(&lock, angle), role: "LK", tooth: index });
1801        curves.push(SectionCurve { curve: rotated(&back, angle), role: "BK", tooth: index });
1802    }
1803    if clockwise_locks {
1804        // The mirror image locks the other way; mirror, then restore the
1805        // counter-clockwise order.
1806        let mut mirrored_curves: Vec<SectionCurve> = curves
1807            .iter()
1808            .map(|piece| SectionCurve { curve: mirrored(&piece.curve).reversed().expect("a line reverses"), role: piece.role, tooth: piece.tooth })
1809            .collect();
1810        mirrored_curves.reverse();
1811        curves = mirrored_curves;
1812    }
1813    snap_junctions(&mut curves);
1814    Ok(GearSection { curves, data: GearData { tip_diameter: outside, root_diameter: 2.0 * rf, ..GearData::default() } })
1815}
1816
1817/// A ratchet solid: the section extruded along +z; names as the section's roles, then `F` and `B`.
1818pub fn ratchet_solid(ratchet: &Ratchet) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
1819    let section = ratchet_section(ratchet)?;
1820    let solid = extrude_section(&section, ratchet.width)?;
1821    let mut names: Vec<String> = section.curves.iter().map(|c| c.suffix()).collect();
1822    names.push("F".into());
1823    names.push("B".into());
1824    Ok((solid, names, section.data))
1825}
1826
1827/// An external Geneva wheel of `slots` slots for a driver at `centre_distance`
1828/// whose pin of `pin_diameter` runs on the crank radius a sin(pi / n); the
1829/// wheel's radius is a cos(pi / n) (the pin enters the slot tangentially). The
1830/// rim between slots is cut by the concave locking arc of radius
1831/// `lock_radius + clearance / 2` about the driver's centre.
1832#[derive(Clone, Debug)]
1833pub struct GenevaWheel {
1834    pub slots: usize,
1835    pub centre_distance: f64,
1836    pub pin_diameter: f64,
1837    pub clearance: f64,
1838    /// The driver's locking disc radius; 0 = crank radius − pin diameter.
1839    pub lock_radius: f64,
1840    pub width: f64,
1841}
1842
1843/// Derived Geneva sizes: (crank radius, wheel radius, slot inner centre radius, locking disc radius).
1844pub fn geneva_sizes(wheel: &GenevaWheel) -> (f64, f64, f64, f64) {
1845    let n = wheel.slots as f64;
1846    let a = wheel.centre_distance;
1847    let crank = a * (PI / n).sin();
1848    let radius = a * (PI / n).cos();
1849    let lock = if wheel.lock_radius > 0.0 { wheel.lock_radius } else { crank - wheel.pin_diameter };
1850    (crank, radius, a - crank, lock)
1851}
1852
1853/// The Geneva wheel section, counter-clockwise; lines and arcs. Slot k on
1854/// angle 2 pi k / n. Roles: `SL<k>`/`SU<k>` its sides, `SE<k>` its end arc,
1855/// `RA<k>`/`RB<k>` the rim arcs either side of the locking arc `LA<k>` that
1856/// follows slot k.
1857pub fn geneva_section(wheel: &GenevaWheel) -> Result<GearSection, KernelRefusal> {
1858    let GenevaWheel { slots, centre_distance: a, pin_diameter: dp, clearance: c, width, .. } = wheel.clone();
1859    if !(3..=12).contains(&slots) {
1860        return Err(refuse("gear_input", format!("A Geneva wheel has from 3 to 12 slots (it has {slots}).")));
1861    }
1862    if !(a > 0.0 && dp > 0.0 && c >= 0.0 && width > 0.0) {
1863        return Err(refuse("gear_input", "The centre distance, pin diameter and width must be positive (the clearance not negative).".into()));
1864    }
1865    let n = slots as f64;
1866    let (crank, rw, end_centre, lock) = geneva_sizes(wheel);
1867    let half = (dp + c) / 2.0; // half the slot width
1868    let rl = lock + c / 2.0;
1869    if !(lock > 0.0 && lock < a - rw + 1e-9 + rw) || !(half < end_centre) || !(half < rw * (PI / n).sin()) {
1870        return Err(refuse("gear_input", format!("The pin ({dp}) is too large for {slots} slots at centre distance {a}.")));
1871    }
1872    // Adjacent slots must not meet: their ends (and sides) stay apart only
1873    // while the end centres are more than a slot width apart.
1874    if end_centre * (PI / n).sin() <= half * (1.0 + 1e-9) {
1875        return Err(refuse(
1876            "gear_input",
1877            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),
1878        ));
1879    }
1880    let x_top = (rw * rw - half * half).sqrt();
1881    let p1 = [x_top, half];
1882    let beta = PI / n;
1883    let centre = [a * beta.cos(), a * beta.sin()];
1884    // Rim circle (O, rw) meets the locking circle (centre, rl).
1885    let along = (rw * rw - rl * rl + a * a) / (2.0 * a);
1886    let h2 = rw * rw - along * along;
1887    if h2 <= 0.0 {
1888        return Err(refuse("gear_input", "The locking arc does not reach the wheel's rim: increase the locking disc radius.".into()));
1889    }
1890    let h = h2.sqrt();
1891    let e = [beta.cos(), beta.sin()];
1892    let perp = [-beta.sin(), beta.cos()];
1893    let q1 = [along * e[0] - h * perp[0], along * e[1] - h * perp[1]];
1894    let q2 = [along * e[0] + h * perp[0], along * e[1] + h * perp[1]];
1895    let a1 = polar_angle(p1);
1896    if polar_angle(q1) <= a1 + 1e-9 {
1897        return Err(refuse("gear_input", "The locking arc cuts into the slots: reduce the locking disc radius or the pin.".into()));
1898    }
1899    let tau = TAU / n;
1900    let slot: Vec<(&'static str, NurbsCurve)> = vec![
1901        ("SL", line([x_top, -half], [end_centre, -half])?),
1902        ("SE", arc_through([end_centre, 0.0], [end_centre, -half], [end_centre, half], false)?),
1903        ("SU", line([end_centre, half], p1)?),
1904        ("RA", arc(rw, a1, polar_angle(q1))?),
1905        ("LA", arc_through(centre, q1, q2, false)?),
1906        ("RB", arc(rw, polar_angle(q2), tau - a1)?),
1907    ];
1908    let mut curves = Vec::with_capacity(6 * slots);
1909    for index in 0..slots {
1910        let angle = tau * index as f64;
1911        for (role, curve) in &slot {
1912            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
1913        }
1914    }
1915    snap_junctions(&mut curves);
1916    let _ = crank;
1917    Ok(GearSection { curves, data: GearData { tip_diameter: 2.0 * rw, ..GearData::default() } })
1918}
1919
1920/// A Geneva wheel solid: the section extruded along +z; names as the
1921/// section's roles, then `F` and `B`.
1922pub fn geneva_solid(wheel: &GenevaWheel) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
1923    let section = geneva_section(wheel)?;
1924    let solid = extrude_section(&section, wheel.width)?;
1925    let mut names: Vec<String> = section.curves.iter().map(|c| c.suffix()).collect();
1926    names.push("F".into());
1927    names.push("B".into());
1928    Ok((solid, names, section.data))
1929}
1930
1931/// A cylindrical worm with an Archimedean (ZA) thread: straight flanks in the
1932/// axial section at the axial pressure angle. Lengths in model units.
1933#[derive(Clone, Debug)]
1934pub struct Worm {
1935    pub axial_module: f64,
1936    pub starts: usize,
1937    /// Reference (pitch) diameter d1 = q × axial module.
1938    pub reference_diameter: f64,
1939    pub pressure_angle: f64,
1940    pub addendum: f64,
1941    pub dedendum: f64,
1942    pub length: f64,
1943    pub hand: Hand,
1944}
1945
1946impl Worm {
1947    /// The lead: starts × axial pitch.
1948    pub fn lead(&self) -> f64 {
1949        self.starts as f64 * PI * self.axial_module
1950    }
1951
1952    /// The axial thread thickness at a radius (ZA: straight axial flanks).
1953    pub fn axial_thickness(&self, radius: f64) -> f64 {
1954        PI * self.axial_module / 2.0 - 2.0 * (radius - self.reference_diameter / 2.0) * self.pressure_angle.tan()
1955    }
1956}
1957
1958/// The worm's transverse section (z = 0), counter-clockwise: per start j (its
1959/// thread centred on angle 2 pi j / n) `R<j>` the flank on its clockwise side,
1960/// `K<j>` the thread's tip, `L<j>` the other flank, `G<j>` the root after it.
1961/// The flanks are Archimedean spirals (fitted), tip and root exact arcs.
1962pub fn worm_section(worm: &Worm) -> Result<GearSection, KernelRefusal> {
1963    let m = worm.axial_module;
1964    if !(m > 0.0 && worm.reference_diameter > 0.0 && worm.length > 0.0 && worm.addendum > 0.0 && worm.dedendum > 0.0) {
1965        return Err(refuse("gear_input", "The worm's module, diameter, length, addendum and dedendum must be positive.".into()));
1966    }
1967    if worm.starts < 1 || worm.starts > 8 {
1968        return Err(refuse("gear_input", format!("A worm has from 1 to 8 starts (it has {}).", worm.starts)));
1969    }
1970    let degrees = worm.pressure_angle.to_degrees();
1971    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&degrees) {
1972        return Err(refuse("gear_input", format!("The axial pressure angle must be between 10° and 35° (it is {degrees}°).")));
1973    }
1974    let r1 = worm.reference_diameter / 2.0;
1975    let ra = r1 + worm.addendum * m;
1976    let rf = r1 - worm.dedendum * m;
1977    if !(rf > 0.0) {
1978        return Err(refuse("gear_input", format!("The worm's root diameter is not positive ({:.4}): raise the diameter quotient.", 2.0 * rf)));
1979    }
1980    let lead = worm.lead();
1981    let gamma = (lead / (PI * worm.reference_diameter)).atan();
1982    if gamma.to_degrees() > 45.0 {
1983        return Err(refuse("bad_lead", format!("The lead angle {:.3}° is over 45°: fewer starts or a larger diameter.", gamma.to_degrees())));
1984    }
1985    if worm.axial_thickness(ra) <= 1e-6 * m {
1986        return Err(refuse("pointed_tip", "The worm thread comes to a point below its tip: lower the addendum or the pressure angle.".into()));
1987    }
1988    let n = worm.starts as f64;
1989    let pitch = PI * m;
1990    if worm.axial_thickness(rf) >= pitch - 1e-6 * m {
1991        return Err(refuse("teeth_overlap", "The worm's threads meet at the root: lower the dedendum or the pressure angle.".into()));
1992    }
1993    // Half the angular width of a thread at radius r in the transverse plane.
1994    let half = |r: f64| PI * worm.axial_thickness(r) / lead;
1995    let flank = |r: f64| {
1996        let t = half(r);
1997        [r * t.cos(), r * t.sin()]
1998    };
1999    let tolerance = GEAR_FIT_TOLERANCE * m;
2000    let upper = fit_planar(&|r| flank(r), rf, ra, tolerance)?; // root -> tip on the +angle side
2001    let tau = TAU / n;
2002    let thread: Vec<(&'static str, NurbsCurve)> = vec![
2003        ("R", mirrored(&upper)),
2004        ("K", arc(ra, -half(ra), half(ra))?),
2005        ("L", upper.reversed().map_err(|e| refuse("gear_fit", e))?),
2006        ("G", arc(rf, half(rf), tau - half(rf))?),
2007    ];
2008    let mut curves = Vec::with_capacity(4 * worm.starts);
2009    for index in 0..worm.starts {
2010        let angle = tau * index as f64;
2011        for (role, curve) in &thread {
2012            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
2013        }
2014    }
2015    snap_junctions(&mut curves);
2016    let data = GearData { pitch_diameter: worm.reference_diameter, tip_diameter: 2.0 * ra, root_diameter: 2.0 * rf, ..GearData::default() };
2017    Ok(GearSection { curves, data })
2018}
2019
2020/// A worm solid: the transverse section screwed along +z by the length (one
2021/// lead per turn); names as the section's roles, then `F` and `B`.
2022pub fn worm_solid(worm: &Worm) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
2023    let section = worm_section(worm)?;
2024    let sign = if worm.hand == Hand::Right { 1.0 } else { -1.0 };
2025    let turn = sign * TAU * worm.length / worm.lead();
2026    let solid = twisted_prism(&section, worm.length, Twist::Helical { turn }, GEAR_FIT_TOLERANCE * worm.axial_module)?;
2027    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
2028    names.push("F".into());
2029    names.push("B".into());
2030    Ok((solid, names, section.data))
2031}
2032
2033/// A cycloidal-drive disc: `pins` housing pins of diameter `pin_diameter` on a
2034/// circle of `pin_circle_diameter`, the disc running at `eccentricity`; the disc
2035/// has pins − 1 lobes. Its profile is the equidistant (by the pin radius plus
2036/// half the clearance) of the epitrochoid the pin centres trace relative to it.
2037#[derive(Clone, Debug)]
2038pub struct CycloidalDisc {
2039    pub pins: usize,
2040    pub pin_circle_diameter: f64,
2041    pub pin_diameter: f64,
2042    pub eccentricity: f64,
2043    /// Running clearance (diametral): the profile stands clearance / 2 further off the pins.
2044    pub clearance: f64,
2045    pub width: f64,
2046}
2047
2048impl CycloidalDisc {
2049    /// The epitrochoid of the pin centres relative to the disc, and its derivative.
2050    fn trochoid(&self, t: f64) -> ([f64; 2], [f64; 2]) {
2051        let r = self.pin_circle_diameter / 2.0;
2052        let e = self.eccentricity;
2053        let n = self.pins as f64;
2054        (
2055            [r * t.cos() - e * (n * t).cos(), -r * t.sin() + e * (n * t).sin()],
2056            [-r * t.sin() + e * n * (n * t).sin(), -r * t.cos() + e * n * (n * t).cos()],
2057        )
2058    }
2059
2060    /// The disc profile point at parameter t: the trochoid moved by the offset
2061    /// along its normal towards the disc's centre.
2062    pub fn profile(&self, t: f64) -> [f64; 2] {
2063        let (q, d) = self.trochoid(t);
2064        let length = d[0].hypot(d[1]);
2065        let offset = self.pin_diameter / 2.0 + self.clearance / 2.0;
2066        // The trochoid runs clockwise (y = -r sin t ...); its right-hand normal points inward.
2067        let n = [d[1] / length, -d[0] / length];
2068        [q[0] + offset * n[0], q[1] + offset * n[1]]
2069    }
2070}
2071
2072/// The disc's section, counter-clockwise: one fitted piece per lobe, `LB<k>`.
2073pub fn cycloidal_disc_section(disc: &CycloidalDisc) -> Result<GearSection, KernelRefusal> {
2074    let CycloidalDisc { pins, pin_circle_diameter: dc, pin_diameter: dp, eccentricity: e, clearance, width } = disc.clone();
2075    if !(4..=200).contains(&pins) {
2076        return Err(refuse("gear_input", format!("A cycloidal drive has from 4 to 200 pins (it has {pins}).")));
2077    }
2078    if !(dc > 0.0 && dp > 0.0 && e > 0.0 && clearance >= 0.0 && width > 0.0) {
2079        return Err(refuse("gear_input", "The pin circle, pin diameter, eccentricity and width must be positive.".into()));
2080    }
2081    let n = pins as f64;
2082    let r = dc / 2.0;
2083    // The trochoid loops back on itself once e >= r / n.
2084    if e >= r / n * (1.0 - 1e-9) {
2085        return Err(refuse(
2086            "gear_input",
2087            format!("The eccentricity must be under the pin circle radius / pins = {:.4} (it is {e}).", r / n),
2088        ));
2089    }
2090    // The offset must stay under the trochoid's smallest radius of curvature (else the lobes cusp).
2091    let offset = dp / 2.0 + clearance / 2.0;
2092    // An inward offset can cusp only where the (clockwise) curve turns
2093    // clockwise, its centre of curvature inside. Radius of curvature there,
2094    // from the closed-form first and second derivatives.
2095    let (rr, ee) = (dc / 2.0, e);
2096    let radius = |t: f64| -> f64 {
2097        let d = [-rr * t.sin() + ee * n * (n * t).sin(), -rr * t.cos() + ee * n * (n * t).cos()];
2098        let dd = [-rr * t.cos() + ee * n * n * (n * t).cos(), rr * t.sin() - ee * n * n * (n * t).sin()];
2099        let cross = d[0] * dd[1] - d[1] * dd[0];
2100        let speed = d[0].hypot(d[1]);
2101        if cross < 0.0 { speed * speed * speed / -cross } else { f64::INFINITY }
2102    };
2103    // The curve repeats every 2 pi / (n - 1): sample one period densely, then
2104    // refine every local minimum by golden-section search.
2105    let period = TAU / (n - 1.0);
2106    let samples = 2000;
2107    let values: Vec<f64> = (0..=samples).map(|i| radius(period * i as f64 / samples as f64)).collect();
2108    let mut least = f64::INFINITY;
2109    for i in 0..=samples {
2110        let previous = values[if i == 0 { samples - 1 } else { i - 1 }];
2111        let next = values[if i == samples { 1 } else { i + 1 }];
2112        if values[i] <= previous && values[i] <= next && values[i].is_finite() {
2113            let (mut lo, mut hi) = (period * (i as f64 - 1.0) / samples as f64, period * (i as f64 + 1.0) / samples as f64);
2114            for _ in 0..100 {
2115                let a = lo + (hi - lo) * 0.381966;
2116                let b = hi - (hi - lo) * 0.381966;
2117                if radius(a) < radius(b) { hi = b } else { lo = a }
2118            }
2119            least = least.min(radius(0.5 * (lo + hi)));
2120        }
2121    }
2122    if offset >= least * (1.0 - 1e-6) {
2123        return Err(refuse(
2124            "undercut",
2125            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})."),
2126        ));
2127    }
2128    let lobes = pins - 1;
2129    let step = TAU / lobes as f64;
2130    let tolerance = GEAR_FIT_TOLERANCE * dp.min(e * 4.0);
2131    // The trochoid runs clockwise in t: walk t downwards for a counter-clockwise section.
2132    let mut curves = Vec::with_capacity(lobes);
2133    for k in 0..lobes {
2134        let (a, b) = (step * k as f64, step * (k + 1) as f64);
2135        let piece = fit_planar(&|u| disc.profile(-u), a, b, tolerance)?;
2136        curves.push(SectionCurve { curve: piece, role: "LB", tooth: k });
2137    }
2138    snap_junctions(&mut curves);
2139    Ok(GearSection { curves, data: GearData { pitch_diameter: dc, ..GearData::default() } })
2140}
2141
2142/// A cycloidal disc solid: the section extruded along +z; names `LB<k>`, `F`, `B`.
2143pub fn cycloidal_disc_solid(disc: &CycloidalDisc) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
2144    let section = cycloidal_disc_section(disc)?;
2145    let solid = extrude_section(&section, disc.width)?;
2146    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
2147    names.push("F".into());
2148    names.push("B".into());
2149    Ok((solid, names, section.data))
2150}
2151
2152/// The pin ring of a cycloidal drive: a ring of `outside` diameter whose bore
2153/// is the pin circle, with `pins` pins of `pin_diameter` centred on it (half
2154/// standing into the bore). Exact arcs. Faces: `P<k>` the pins' exposed halves,
2155/// `G<k>` the bore between pins, `OD`, `F`, `B`.
2156pub fn cycloidal_pin_ring(pins: usize, pin_circle_diameter: f64, pin_diameter: f64, outside: f64, width: f64) -> Result<(BrepSolid, GearData), KernelRefusal> {
2157    if !(4..=200).contains(&pins) || !(pin_diameter > 0.0 && pin_circle_diameter > pin_diameter && width > 0.0) {
2158        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()));
2159    }
2160    let r = pin_circle_diameter / 2.0;
2161    let rp = pin_diameter / 2.0;
2162    let n = pins as f64;
2163    let tau = TAU / n;
2164    // Where a pin's circle crosses the bore circle (radius r): half-angle delta about the origin.
2165    let delta = 2.0 * (rp / (2.0 * r)).asin();
2166    if 2.0 * delta >= tau - 1e-9 || 2.0 * r * (PI / n).sin() <= pin_diameter * (1.0 + 1e-9) {
2167        return Err(refuse("gear_input", format!("{pins} pins of diameter {pin_diameter} overlap on a {pin_circle_diameter} pin circle.")));
2168    }
2169    let centre = [r, 0.0];
2170    let a = [r * (-delta).cos(), r * (-delta).sin()];
2171    let b = [r * delta.cos(), r * delta.sin()];
2172    // The pin bulges into the bore: its arc from a to b passes through (r - rp, 0).
2173    let cw = arc_through(centre, a, b, false)?;
2174    let pin_arc = {
2175        let [t0, t1] = cw.domain().map_err(|e| refuse("gear_domain", e))?;
2176        let mid = cw.evaluate(0.5 * (t0 + t1)).map_err(|e| refuse("gear_eval", e))?;
2177        if mid.x < r { cw } else { arc_through(centre, a, b, true)? }
2178    };
2179    let space: Vec<(&'static str, NurbsCurve)> = vec![("P", pin_arc), ("G", arc(r, delta, tau - delta)?)];
2180    let mut curves = Vec::with_capacity(2 * pins);
2181    for k in 0..pins {
2182        for (role, curve) in &space {
2183            curves.push(SectionCurve { curve: rotated(curve, tau * k as f64), role, tooth: k });
2184        }
2185    }
2186    snap_junctions(&mut curves);
2187    let section = GearSection { curves, data: GearData { pitch_diameter: pin_circle_diameter, ..GearData::default() } };
2188    let ring = hub_from_section(&section, outside, width)?;
2189    Ok((ring, section.data))
2190}
2191
2192/// A cycloidal (clock-style) gear: teeth whose addenda are epicycloids rolled
2193/// by a circle of `generating_radius` on the pitch circle and whose dedenda are
2194/// radial lines (the hypocycloid of a circle of half the mate's pitch radius).
2195#[derive(Clone, Debug)]
2196pub struct CycloidalGear {
2197    pub module: f64,
2198    pub teeth: usize,
2199    /// Radius of the rolling circle (usually half the mating gear's pitch radius).
2200    pub generating_radius: f64,
2201    /// Tooth thickness on the pitch circle as a fraction of the circular pitch.
2202    pub tooth_fraction: f64,
2203    /// Addendum limit × module (the tip is pointed if the flanks meet first).
2204    pub addendum: f64,
2205    /// Dedendum × module.
2206    pub dedendum: f64,
2207    pub width: f64,
2208}
2209
2210/// The cycloidal gear's section, counter-clockwise. Per tooth k: `R<k>`/`L<k>`
2211/// the radial dedendum flanks, `ER<k>`/`EL<k>` the epicycloidal addenda, `K<k>`
2212/// the tip land (absent when pointed), `G<k>` the root land.
2213pub fn cycloidal_gear_section(gear: &CycloidalGear) -> Result<GearSection, KernelRefusal> {
2214    let m = gear.module;
2215    if !(m > 0.0 && gear.generating_radius > 0.0 && gear.addendum > 0.0 && gear.dedendum > 0.0 && gear.width > 0.0) {
2216        return Err(refuse("gear_input", "The module, rolling circle, addendum, dedendum and width must be positive.".into()));
2217    }
2218    if !(gear.tooth_fraction > 0.1 && gear.tooth_fraction < 0.9) {
2219        return Err(refuse("gear_input", "The tooth thickness must be between 0.1 and 0.9 of the pitch.".into()));
2220    }
2221    if gear.teeth < 6 || gear.teeth > 1000 {
2222        return Err(refuse("gear_input", format!("A cycloidal gear needs from 6 to 1000 teeth (it has {}).", gear.teeth)));
2223    }
2224    let z = gear.teeth as f64;
2225    let r = m * z / 2.0;
2226    let rho = gear.generating_radius;
2227    let rf = r - gear.dedendum * m;
2228    if !(rf > 0.0) {
2229        return Err(refuse("root_below_centre", "The root circle is not positive: fewer dedendum or more teeth.".into()));
2230    }
2231    let tau = TAU / z;
2232    let psi = PI * gear.tooth_fraction / z; // half the tooth angle on the pitch circle
2233    // The right flank's epicycloid, from the pitch circle at angle -psi.
2234    let k = (r + rho) / rho;
2235    let epi = |phi: f64| {
2236        let p = [(r + rho) * phi.cos() - rho * (k * phi).cos(), (r + rho) * phi.sin() - rho * (k * phi).sin()];
2237        rotate(p, -psi)
2238    };
2239    let ra = r + gear.addendum * m;
2240    // Run phi up until the curve reaches the tip circle or the tooth centre line (angle 0).
2241    let reach = |phi: f64| radius_of(epi(phi)) >= ra || polar_angle(epi(phi)) >= 0.0;
2242    let mut hi = 1e-3;
2243    while !reach(hi) {
2244        hi *= 1.5;
2245        if hi > PI {
2246            return Err(refuse("gear_input", "The addendum curve does not close.".into()));
2247        }
2248    }
2249    let mut lo = 0.0;
2250    for _ in 0..200 {
2251        let mid = 0.5 * (lo + hi);
2252        if reach(mid) { hi = mid } else { lo = mid }
2253    }
2254    let end = epi(hi);
2255    // Pointed when the flank reaches the tooth centre line no later than the
2256    // tip circle (a tip land narrower than 1e-9 counts as pointed).
2257    let pointed = polar_angle(end) >= -1e-9;
2258    let phi_end = if pointed {
2259        let (mut lo, mut hi) = (0.0, hi);
2260        for _ in 0..200 {
2261            let mid = 0.5 * (lo + hi);
2262            if polar_angle(epi(mid)) >= 0.0 { hi = mid } else { lo = mid }
2263        }
2264        hi
2265    } else {
2266        hi
2267    };
2268    let tolerance = GEAR_FIT_TOLERANCE * m;
2269    let right_add = fit_planar(&|phi| epi(phi), 0.0, phi_end, tolerance)?; // pitch -> tip, right side
2270    let foot = [rf * (-psi).cos(), rf * (-psi).sin()];
2271    let pitch_point = [r * (-psi).cos(), r * (-psi).sin()];
2272    let mut tooth: Vec<(&'static str, NurbsCurve)> = vec![("R", line(foot, pitch_point)?), ("ER", right_add.clone())];
2273    let tip_angle = -polar_angle(epi(phi_end));
2274    if !pointed {
2275        tooth.push(("K", arc(ra, -tip_angle, tip_angle)?));
2276    }
2277    tooth.push(("EL", mirrored(&right_add).reversed().map_err(|e| refuse("gear_fit", e))?));
2278    tooth.push(("L", line([pitch_point[0], -pitch_point[1]], [foot[0], -foot[1]])?));
2279    tooth.push(("G", arc(rf, psi, tau - psi)?));
2280    let mut curves = Vec::with_capacity(tooth.len() * gear.teeth);
2281    for index in 0..gear.teeth {
2282        let angle = tau * index as f64;
2283        for (role, curve) in &tooth {
2284            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
2285        }
2286    }
2287    snap_junctions(&mut curves);
2288    let data = GearData {
2289        pitch_diameter: 2.0 * r,
2290        tip_diameter: 2.0 * radius_of(epi(phi_end)),
2291        root_diameter: 2.0 * rf,
2292        tooth_thickness: 2.0 * psi * r,
2293        ..GearData::default()
2294    };
2295    Ok(GearSection { curves, data })
2296}
2297
2298/// A cycloidal gear solid; names as the section's roles, then `F` and `B`.
2299pub fn cycloidal_gear_solid(gear: &CycloidalGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
2300    let section = cycloidal_gear_section(gear)?;
2301    let solid = extrude_section(&section, gear.width)?;
2302    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
2303    names.push("F".into());
2304    names.push("B".into());
2305    Ok((solid, names, section.data))
2306}
2307
2308/// A straight bevel gear with spherical-involute teeth (the true conjugate
2309/// form; not Tredgold's back-cone approximation). Module at the heel, shaft
2310/// angle 90°, pitch cone angle atan(z / z_mate). Apex at the origin, axis +z,
2311/// the teeth between cone distances R − face width and R; back and front
2312/// faces are the back and front cones (perpendicular to the pitch cone).
2313#[derive(Clone, Debug)]
2314pub struct BevelGear {
2315    pub module: f64,
2316    pub teeth: usize,
2317    pub mate_teeth: usize,
2318    pub pressure_angle: f64,
2319    pub addendum: f64,
2320    pub dedendum: f64,
2321    pub face_width: f64,
2322    pub backlash: f64,
2323}
2324
2325/// Derived bevel sizes: (pitch cone angle, cone distance, base cone angle).
2326pub fn bevel_cones(gear: &BevelGear) -> (f64, f64, f64) {
2327    let delta = (gear.teeth as f64).atan2(gear.mate_teeth as f64);
2328    let cone = gear.module * gear.teeth as f64 / (2.0 * delta.sin());
2329    let base = (delta.sin() * gear.pressure_angle.cos()).asin();
2330    (delta, cone, base)
2331}
2332
2333/// A point of the spherical involute of the base cone (half angle `base`) on
2334/// the sphere of radius `r`, unwrapped by `phi` from the base circle at azimuth 0.
2335fn spherical_involute(r: f64, base: f64, phi: f64) -> [f64; 3] {
2336    let (s, c) = base.sin_cos();
2337    let t = phi * s;
2338    [
2339        r * (t.cos() * s * phi.cos() + t.sin() * phi.sin()),
2340        r * (t.cos() * s * phi.sin() - t.sin() * phi.cos()),
2341        r * t.cos() * c,
2342    ]
2343}
2344
2345/// The polar angle from the axis (the cone angle) of a point.
2346fn cone_angle(p: [f64; 3]) -> f64 {
2347    p[0].hypot(p[1]).atan2(p[2])
2348}
2349
2350/// Central projection from the apex onto the plane z = h.
2351fn project(p: [f64; 3], h: f64) -> [f64; 2] {
2352    [p[0] * h / p[2], p[1] * h / p[2]]
2353}
2354
2355/// The bevel gear section: the spherical tooth outline on the sphere through
2356/// the heel, centrally projected onto the plane z = h (so every surface the
2357/// apex sees edge-on — tooth flanks, root and tip cones — becomes a planar
2358/// curve; the cones' circles project to exact arcs). Counter-clockwise; roles
2359/// as the spur gear's: `V/R/K/L/W/G` with `V/W` the radial (meridian) root
2360/// extension below the base cone when the root lies under it.
2361pub fn bevel_section(gear: &BevelGear, h: f64) -> Result<GearSection, KernelRefusal> {
2362    let m = gear.module;
2363    if !(m > 0.0 && gear.face_width > 0.0 && gear.addendum > 0.0 && gear.dedendum > 0.0 && gear.backlash >= 0.0) {
2364        return Err(refuse("gear_input", "The module, face width, addendum and dedendum must be positive.".into()));
2365    }
2366    if gear.teeth < 6 || gear.mate_teeth < 6 {
2367        return Err(refuse("gear_input", "A bevel pair needs at least 6 teeth on each gear.".into()));
2368    }
2369    let degrees = gear.pressure_angle.to_degrees();
2370    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&degrees) {
2371        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and 35° (it is {degrees}°).")));
2372    }
2373    let (delta, r, base) = bevel_cones(gear);
2374    if gear.face_width > r / 3.0 + 1e-9 {
2375        return Err(refuse(
2376            "face_too_wide",
2377            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),
2378        ));
2379    }
2380    let z = gear.teeth as f64;
2381    let tip = delta + gear.addendum * m / r;
2382    let root = delta - gear.dedendum * m / r;
2383    if !(root > 0.0) {
2384        return Err(refuse("root_below_centre", "The root cone passes the axis: fewer dedendum or more teeth.".into()));
2385    }
2386    // The unwrap angle where the involute reaches a cone angle theta: cos(phi sin b) cos b = cos theta.
2387    let phi_at = |theta: f64| ((theta.cos() / base.cos()).clamp(-1.0, 1.0)).acos() / base.sin();
2388    let azimuth = |p: [f64; 3]| p[1].atan2(p[0]);
2389    // Position the left flank: half the tooth thickness (arc on the pitch circle of radius r sin delta) at the pitch cone.
2390    let half = (PI * m / 2.0 - gear.backlash) / (2.0 * r * delta.sin());
2391    let p_pitch = spherical_involute(r, base, phi_at(delta));
2392    // The involute (unwrapping counter-clockwise) leans to positive azimuth as it rises: the left flank
2393    // is it mirrored, turned so its pitch point sits at +half.
2394    let shift = half + azimuth(p_pitch);
2395    let left = |phi: f64| {
2396        let p = spherical_involute(r, base, phi);
2397        let q = [p[0], -p[1], p[2]];
2398        let (s, c) = shift.sin_cos();
2399        [c * q[0] - s * q[1], s * q[0] + c * q[1], q[2]]
2400    };
2401    let tip_phi = phi_at(tip);
2402    if azimuth(left(tip_phi)) <= 1e-6 * m / r {
2403        return Err(refuse("pointed_tip", "The teeth come to a point below the tip cone: reduce the addendum.".into()));
2404    }
2405    // At the base cone the involute leaves with zero speed (a cusp in phi):
2406    // when the root lies under it, the flank starts a little above (2% of the
2407    // unwrap) and the radial root extension runs up to that point.
2408    let extend = !(root > base); // the root lies on or under the base cone: a radial extension
2409    let start_phi = if extend { 0.02 * tip_phi } else { phi_at(root) };
2410    let tolerance = GEAR_FIT_TOLERANCE * m;
2411    let flank = fit_planar(&|phi| project(left(phi), h), start_phi, tip_phi, tolerance)?; // root side -> tip
2412    let tau = TAU / z;
2413    let base_point = project(left(start_phi), h);
2414    let root_r = h * root.tan();
2415    let tip_r = h * tip.tan();
2416    let foot_angle = base_point[1].atan2(base_point[0]);
2417    let mut tooth: Vec<(&'static str, NurbsCurve)> = Vec::new();
2418    let tip_angle = {
2419        let p = project(left(tip_phi), h);
2420        p[1].atan2(p[0])
2421    };
2422    // Right side (mirror), going up: [V radial] + R; tip K; then L down + [W radial]; G root land.
2423    let radial_foot = [root_r * foot_angle.cos(), root_r * foot_angle.sin()];
2424    if extend {
2425        tooth.push(("V", line([radial_foot[0], -radial_foot[1]], [base_point[0], -base_point[1]])?));
2426    }
2427    tooth.push(("R", mirrored(&flank)));
2428    tooth.push(("K", arc(tip_r, -tip_angle, tip_angle)?));
2429    tooth.push(("L", flank.reversed().map_err(|e| refuse("gear_fit", e))?));
2430    if extend {
2431        tooth.push(("W", line(base_point, radial_foot)?));
2432    }
2433    if foot_angle >= tau / 2.0 - 1e-9 {
2434        return Err(refuse("teeth_overlap", "The tooth roots meet: fewer teeth or a smaller pressure angle.".into()));
2435    }
2436    tooth.push(("G", arc(root_r, foot_angle, tau - foot_angle)?));
2437    let mut curves = Vec::with_capacity(tooth.len() * gear.teeth);
2438    for index in 0..gear.teeth {
2439        let angle = tau * index as f64;
2440        for (role, curve) in &tooth {
2441            curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
2442        }
2443    }
2444    // Lift the section into the plane z = h.
2445    for piece in &mut curves {
2446        for p in &mut piece.curve.control_points {
2447            p.z = p.w * h;
2448        }
2449    }
2450    snap_junctions(&mut curves);
2451    // Diameters at the heel: where each cone meets the back cone (perpendicular
2452    // to the pitch cone at cone distance r).
2453    let heel = |angle: f64| 2.0 * r * angle.sin() / (angle - delta).cos();
2454    let data = GearData {
2455        pitch_diameter: 2.0 * r * delta.sin(),
2456        tip_diameter: heel(tip),
2457        root_diameter: heel(root),
2458        ..GearData::default()
2459    };
2460    Ok(GearSection { curves, data })
2461}
2462
2463/// A straight bevel gear solid: the section's cone (every curve carried to
2464/// and from the apex by scaling, so the flanks are exactly the cones over the
2465/// spherical involutes) cut to the back and front cones. Faces carry their
2466/// roles in `face.name` (`R3`, `K0`, …, `BACK`, `FRONT`).
2467pub fn bevel_solid(gear: &BevelGear) -> Result<(BrepSolid, GearData), KernelRefusal> {
2468    let (delta, r, _) = bevel_cones(gear);
2469    let rho = r - gear.face_width;
2470    let m = gear.module;
2471    let tip = delta + gear.addendum * m / r;
2472    let h = r * delta.cos();
2473    let mut section = bevel_section(gear, h)?;
2474    // The cone of the section, from below the lowest blank point inside it to above the back cone's apex.
2475    let z_lo = 0.5 * rho * tip.cos() / (tip - delta).cos();
2476    let z_hi = 1.05 * r / delta.cos();
2477    let (s_lo, s_hi) = (z_lo / h, z_hi / h);
2478    for piece in &mut section.curves {
2479        for p in &mut piece.curve.control_points {
2480            p.x *= s_lo;
2481            p.y *= s_lo;
2482            p.z *= s_lo;
2483        }
2484    }
2485    let grow = s_hi / s_lo;
2486    let rows = |p: Vec4| vec![p, Vec4 { x: p.x * grow, y: p.y * grow, z: p.z * grow, w: p.w }];
2487    let mut cone = prism_by_rows(&section, 1, &[0.0, 0.0, 1.0, 1.0], &rows)?;
2488    let count = section.curves.len();
2489    for (index, face) in cone.shells[0].faces.iter_mut().enumerate() {
2490        face.name = Some(if index < count { section.curves[index].suffix() } else { "CAP".into() });
2491    }
2492    // The blank: between the front and back cones, out past the tip.
2493    let r_out = r * tip.sin() * 1.2 + m;
2494    let (sd, cd) = delta.sin_cos();
2495    let back_apex = [0.0, r / cd];
2496    let front_apex = [0.0, rho / cd];
2497    let out = |along: f64| {
2498        // From the pitch point at cone distance `along`, outwards on the line perpendicular to the pitch cone.
2499        let t = (r_out - along * sd) / cd;
2500        [along * sd + t * cd, along * cd - t * sd]
2501    };
2502    let (f2, b2) = (out(rho), out(r));
2503    let at = |q: [f64; 2]| Vec3::new(q[0], 0.0, q[1]);
2504    let line3 = |a: [f64; 2], b: [f64; 2]| crate::make_line(at(a), at(b)).map_err(|e| refuse("gear_blank", e));
2505    let revolve = |profile: Vec<NurbsCurve>, names: &[&str]| -> Result<BrepSolid, KernelRefusal> {
2506        let names: Vec<Option<String>> = names.iter().map(|n| Some(n.to_string())).collect();
2507        crate::revolve_profile_brep_named(&profile, Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), TAU, &names, &[])
2508            .map_err(|e| refuse("gear_blank", e))
2509    };
2510    // Below the back cone: a cone of material under it, out past the tip and down below the cone's foot.
2511    // Below everything the back cone bounds: under the cone prism's foot and the back cone's outer point.
2512    let low = (z_lo * 0.5).min(b2[1]) - m;
2513    let back = revolve(
2514        vec![line3(back_apex, b2)?, line3(b2, [b2[0], low])?, line3([b2[0], low], [0.0, low])?, line3([0.0, low], back_apex)?],
2515        &["BACK", "BX1", "BX2", "BX3"],
2516    )?;
2517    // Above the front cone.
2518    let high = z_hi * 1.1;
2519    let front = revolve(
2520        vec![line3(front_apex, [0.0, high])?, line3([0.0, high], [f2[0], high])?, line3([f2[0], high], f2)?, line3(f2, front_apex)?],
2521        &["FX1", "FX2", "FX3", "FRONT"],
2522    )?;
2523    let cut = crate::boolean_operation_nary(&[cone, back], crate::BooleanOperation::Intersect)?;
2524    let gear_solid = crate::boolean_operation_nary(&[cut, front], crate::BooleanOperation::Intersect)?;
2525    Ok((gear_solid, section.data))
2526}
2527
2528/// An elliptical gear: the pitch curve is an ellipse turning about one of its
2529/// foci, and the teeth are generated by rolling the standard basic rack round
2530/// it without slip (the rack's pitch line tangent to the ellipse, the contact
2531/// normal through the touching point), as a spur gear is generated round its
2532/// pitch circle. Two identical elliptical gears with an odd tooth count mesh
2533/// at a centre distance of the major axis (see [`elliptical_sizes`]).
2534///
2535/// The ellipse is sized so its perimeter is exactly `teeth` circular pitches
2536/// (π · module), so the teeth close. Tooth 0 is centred on the near vertex
2537/// (on +x, closest to the pivot).
2538#[derive(Clone, Debug)]
2539pub struct EllipticalGear {
2540    pub module: f64,
2541    pub teeth: usize,
2542    /// Eccentricity of the pitch ellipse (0 is a spur gear turning about its centre).
2543    pub eccentricity: f64,
2544    pub pressure_angle: f64,
2545    /// Addendum coefficient × module, measured normal to the pitch curve.
2546    pub addendum: f64,
2547    /// Dedendum coefficient × module, normal to the pitch curve.
2548    pub dedendum: f64,
2549    /// Tip radius of the generating rack × module.
2550    pub root_fillet: f64,
2551    /// Arc length added to each tooth space along the pitch curve.
2552    pub backlash: f64,
2553    pub face_width: f64,
2554}
2555
2556/// The pitch ellipse about its focus, by arc length.
2557struct PitchEllipse {
2558    /// Semi-latus rectum: r(θ) = p / (1 + e cos θ) about the focus.
2559    latus: f64,
2560    e: f64,
2561    /// Cumulative arc length at θ = 2π i / SEGMENTS.
2562    table: Vec<f64>,
2563}
2564
2565impl PitchEllipse {
2566    const SEGMENTS: usize = 1024;
2567
2568    fn new(latus: f64, e: f64) -> Self {
2569        let mut curve = Self { latus, e, table: Vec::with_capacity(Self::SEGMENTS + 1) };
2570        // Five-point Gauss-Legendre per segment.
2571        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];
2572        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];
2573        let step = TAU / Self::SEGMENTS as f64;
2574        let mut total = 0.0;
2575        curve.table.push(0.0);
2576        for i in 0..Self::SEGMENTS {
2577            let mid = (i as f64 + 0.5) * step;
2578            let sum: f64 = nodes.iter().zip(&weights).map(|(x, w)| w * curve.speed(mid + 0.5 * step * x)).sum();
2579            total += 0.5 * step * sum;
2580            curve.table.push(total);
2581        }
2582        curve
2583    }
2584
2585    fn length(&self) -> f64 {
2586        self.table[Self::SEGMENTS]
2587    }
2588
2589    /// Point, first and second derivatives in θ.
2590    fn derivatives(&self, theta: f64) -> ([f64; 2], [f64; 2], [f64; 2]) {
2591        let (s, c) = theta.sin_cos();
2592        let d = 1.0 + self.e * c;
2593        let d1 = -self.e * s;
2594        let d2 = -self.e * c;
2595        let r = self.latus / d;
2596        let r1 = -self.latus * d1 / (d * d);
2597        let r2 = -self.latus * (d2 * d - 2.0 * d1 * d1) / (d * d * d);
2598        (
2599            [r * c, r * s],
2600            [r1 * c - r * s, r1 * s + r * c],
2601            [r2 * c - 2.0 * r1 * s - r * c, r2 * s + 2.0 * r1 * c - r * s],
2602        )
2603    }
2604
2605    fn speed(&self, theta: f64) -> f64 {
2606        let (_, d1, _) = self.derivatives(theta);
2607        d1[0].hypot(d1[1])
2608    }
2609
2610    /// The polar angle at arc length `s` (any real; the curve is periodic).
2611    fn theta_at(&self, s: f64) -> f64 {
2612        let length = self.length();
2613        let turns = (s / length).floor();
2614        let local = s - turns * length;
2615        let index = self.table.partition_point(|&value| value <= local).clamp(1, Self::SEGMENTS) - 1;
2616        let step = TAU / Self::SEGMENTS as f64;
2617        let (lo, hi) = (index as f64 * step, (index + 1) as f64 * step);
2618        let span = self.table[index + 1] - self.table[index];
2619        let mut theta = lo + step * (local - self.table[index]) / span;
2620        // Newton on the segment's arc length, measured from its start by Gauss-Legendre.
2621        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];
2622        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];
2623        for _ in 0..8 {
2624            let half = 0.5 * (theta - lo);
2625            let arc: f64 = half * nodes.iter().zip(&weights).map(|(x, w)| w * self.speed(lo + half * (1.0 + x))).sum::<f64>();
2626            let error = self.table[index] + arc - local;
2627            theta = (theta - error / self.speed(theta)).clamp(lo, hi);
2628            if error.abs() < 1e-15 * length {
2629                break;
2630            }
2631        }
2632        theta + turns * TAU
2633    }
2634
2635    /// Point, unit tangent (counter-clockwise), outward unit normal and signed curvature at arc length `s`.
2636    fn frame(&self, s: f64) -> ([f64; 2], [f64; 2], [f64; 2], f64) {
2637        let (p, d1, d2) = self.derivatives(self.theta_at(s));
2638        let speed = d1[0].hypot(d1[1]);
2639        let t = [d1[0] / speed, d1[1] / speed];
2640        let curvature = (d1[0] * d2[1] - d1[1] * d2[0]) / speed.powi(3);
2641        (p, t, [t[1], -t[0]], curvature)
2642    }
2643}
2644
2645/// The derived sizes of an elliptical gear: (semi-major axis, eccentricity,
2646/// perimeter, centre distance to an identical mate = 2 × semi-major axis).
2647pub fn elliptical_sizes(gear: &EllipticalGear) -> (f64, f64, f64, f64) {
2648    let e = gear.eccentricity;
2649    let unit = PitchEllipse::new(1.0 - e * e, e); // semi-major axis 1
2650    let a = PI * gear.module * gear.teeth as f64 / unit.length();
2651    (a, e, PI * gear.module * gear.teeth as f64, 2.0 * a)
2652}
2653
2654/// The rack, pitch line on y = 0 with +y away from the gear, rolled to arc
2655/// length `s`: rack point (x, y) lies at P(s) + (x − s) T(s) + y N(s).
2656struct RollingRack<'a> {
2657    pitch: &'a PitchEllipse,
2658}
2659
2660impl RollingRack<'_> {
2661    /// The gear point generated by the rack point `q` with normal direction `n`
2662    /// (either sense): the normal through q meets the pitch line at the rolling position.
2663    fn envelope(&self, q: [f64; 2], n: [f64; 2]) -> [f64; 2] {
2664        let s = q[0] - q[1] * n[0] / n[1];
2665        self.place(q, s)
2666    }
2667
2668    fn place(&self, q: [f64; 2], s: f64) -> [f64; 2] {
2669        let (p, t, n, _) = self.pitch.frame(s);
2670        let u = q[0] - s;
2671        [p[0] + u * t[0] + q[1] * n[0], p[1] + u * t[1] + q[1] * n[1]]
2672    }
2673
2674    /// The arc length of the foot of the normal from `g` to the pitch curve
2675    /// (starting near `guess`) and the signed distance along the outward normal.
2676    fn foot(&self, g: [f64; 2], guess: f64) -> (f64, f64) {
2677        let mut sigma = guess;
2678        for _ in 0..40 {
2679            let (p, t, n, curvature) = self.pitch.frame(sigma);
2680            let v = [g[0] - p[0], g[1] - p[1]];
2681            let along = v[0] * t[0] + v[1] * t[1];
2682            let distance = v[0] * n[0] + v[1] * n[1];
2683            let step = along / (1.0 + curvature * distance);
2684            sigma += step;
2685            if step.abs() < 1e-15 * self.pitch.length() {
2686                break;
2687            }
2688        }
2689        let (p, _, n, _) = self.pitch.frame(sigma);
2690        (sigma, (g[0] - p[0]) * n[0] + (g[1] - p[1]) * n[1])
2691    }
2692}
2693
2694/// The elliptical gear section, counter-clockwise about the pivot (the focus,
2695/// at the origin). Roles per tooth k, as the spur gear's: `V<k>` root fillet,
2696/// `R<k>` flank rising to `K<k>` the tip land (normal offset of the pitch
2697/// curve), `L<k>` the falling flank, `W<k>` root fillet, `G<k>` the root land
2698/// (inward offset) of the space after tooth k.
2699pub fn elliptical_section(gear: &EllipticalGear) -> Result<GearSection, KernelRefusal> {
2700    let m = gear.module;
2701    if !(m > 0.0 && gear.face_width > 0.0 && gear.addendum > 0.0 && gear.dedendum > 0.0) {
2702        return Err(refuse("gear_input", "The module, face width, addendum and dedendum must be positive.".into()));
2703    }
2704    if !(gear.root_fillet >= 0.0 && gear.backlash >= 0.0) {
2705        return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
2706    }
2707    if !(0.0..=0.8).contains(&gear.eccentricity) {
2708        return Err(refuse("gear_input", format!("The eccentricity must be from 0 to 0.8 (it is {}).", gear.eccentricity)));
2709    }
2710    if gear.teeth < 8 || gear.teeth > 1000 {
2711        return Err(refuse("gear_input", format!("An elliptical gear needs from 8 to 1000 teeth (it has {}).", gear.teeth)));
2712    }
2713    let degrees = gear.pressure_angle.to_degrees();
2714    if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&degrees) {
2715        return Err(refuse("gear_input", format!("The pressure angle must be between 10° and 35° (it is {degrees}°).")));
2716    }
2717    let (a, e, perimeter, _) = elliptical_sizes(gear);
2718    let pitch_curve = PitchEllipse::new(a * (1.0 - e * e), e);
2719    let rack = RollingRack { pitch: &pitch_curve };
2720    let z = gear.teeth as f64;
2721    let p = perimeter / z;
2722    let alpha = gear.pressure_angle;
2723    let (sin_a, cos_a, tan_a) = (alpha.sin(), alpha.cos(), alpha.tan());
2724    let h_a = gear.addendum * m;
2725    let h_f = gear.dedendum * m;
2726    let rho = gear.root_fillet * m;
2727    let tolerance = GEAR_FIT_TOLERANCE * m;
2728    // The sharpest point of the ellipse is its major vertex: radius b²/a.
2729    let min_radius = a * (1.0 - e * e);
2730    if h_f >= min_radius {
2731        return Err(refuse(
2732            "undercut",
2733            format!("The root would fold at the ellipse's ends (radius of curvature {min_radius:.4} there): add teeth or lower the eccentricity."),
2734        ));
2735    }
2736    // Cutter tooth centred on x = 0 (it cuts the space there): half width at height y is w0 + y tan α.
2737    let w0 = p / 4.0 + gear.backlash / 2.0;
2738    let centre_y = -h_f + rho;
2739    let centre_x = -w0 - (centre_y - rho * sin_a) * tan_a + rho * cos_a; // low-side fillet centre
2740    if centre_x >= 0.0 {
2741        return Err(refuse("root_fillet_too_large", "The root fillet is larger than fits the tooth space; lower it.".into()));
2742    }
2743    let y_join = centre_y - rho * sin_a;
2744    let low_flank = |c: f64, y: f64| rack.envelope([c - w0 - y * tan_a, y], [cos_a, sin_a]);
2745    let high_flank = |c: f64, y: f64| rack.envelope([c + w0 + y * tan_a, y], [-cos_a, sin_a]);
2746    // ψ ∈ [0, 1]: from the flank tangency (0) to the tip line (1).
2747    let fillet_normal = |t: f64| {
2748        let psi = -PI + alpha + t * (PI / 2.0 - alpha);
2749        [psi.cos(), psi.sin()]
2750    };
2751    let low_fillet = |c: f64, t: f64| {
2752        let n = fillet_normal(t);
2753        if rho == 0.0 {
2754            return rack.envelope([c + centre_x, centre_y], n);
2755        }
2756        rack.envelope([c + centre_x + rho * n[0], centre_y + rho * n[1]], n)
2757    };
2758    let high_fillet = |c: f64, t: f64| {
2759        let n = fillet_normal(t);
2760        if rho == 0.0 {
2761            return rack.envelope([c - centre_x, centre_y], [-n[0], n[1]]);
2762        }
2763        rack.envelope([c - centre_x - rho * n[0], centre_y + rho * n[1]], [-n[0], n[1]])
2764    };
2765    let root = |x: f64| rack.place([x, -h_f], x);
2766    let tip = |sigma: f64| {
2767        let (q, _, n, _) = pitch_curve.frame(sigma);
2768        [q[0] + h_a * n[0], q[1] + h_a * n[1]]
2769    };
2770    // The generated flank is regular while sin²α + y κ > 0 down to its foot (it cusps
2771    // where the rack flank passes the point of interference); κ is largest, 1 / min_radius,
2772    // at the major vertices.
2773    if sin_a * sin_a + y_join / min_radius <= 1e-9 {
2774        return Err(refuse(
2775            "undercut",
2776            format!(
2777                "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."
2778            ),
2779        ));
2780    }
2781    // The flank height where a generated flank reaches the tip offset (offset distance h_a).
2782    let top_of = |flank: &dyn Fn(f64) -> [f64; 2], guess: f64| -> Result<(f64, f64), KernelRefusal> {
2783        let offset = |y: f64| rack.foot(flank(y), guess).1 - h_a;
2784        let (mut lo, mut hi) = (y_join, h_a + 2.0 * m);
2785        if !(offset(lo) < 0.0 && offset(hi) > 0.0) {
2786            return Err(refuse("gear_fit", "The generated flank does not reach the tip curve.".into()));
2787        }
2788        for _ in 0..200 {
2789            let mid = 0.5 * (lo + hi);
2790            if offset(mid) < 0.0 { lo = mid } else { hi = mid }
2791        }
2792        let y = 0.5 * (lo + hi);
2793        Ok((y, rack.foot(flank(y), guess).0))
2794    };
2795    let mut curves = Vec::with_capacity(6 * gear.teeth);
2796    let reversed = |curve: NurbsCurve| curve.reversed().map_err(|error| refuse("gear_fit", error));
2797    for k in 0..gear.teeth {
2798        let before = (k as f64 - 0.5) * p; // the space before tooth k
2799        let after = (k as f64 + 0.5) * p;
2800        let rising = |y: f64| high_flank(before, y);
2801        let falling = |y: f64| low_flank(after, y);
2802        let (y_rise, sigma_rise) = top_of(&rising, k as f64 * p - w0)?;
2803        let (y_fall, sigma_fall) = top_of(&falling, k as f64 * p + w0)?;
2804        if sigma_fall - sigma_rise <= 1e-6 * m {
2805            return Err(refuse("pointed_tip", "The teeth come to a point below the tip curve: reduce the addendum or the backlash.".into()));
2806        }
2807        curves.push(SectionCurve { curve: reversed(fit_planar(&|t| high_fillet(before, t), 0.0, 1.0, tolerance)?)?, role: "V", tooth: k });
2808        curves.push(SectionCurve { curve: fit_planar(&rising, y_join, y_rise, tolerance)?, role: "R", tooth: k });
2809        curves.push(SectionCurve { curve: fit_planar(&tip, sigma_rise, sigma_fall, tolerance)?, role: "K", tooth: k });
2810        curves.push(SectionCurve { curve: reversed(fit_planar(&falling, y_join, y_fall, tolerance)?)?, role: "L", tooth: k });
2811        curves.push(SectionCurve { curve: fit_planar(&|t| low_fillet(after, t), 0.0, 1.0, tolerance)?, role: "W", tooth: k });
2812        if centre_x < -1e-9 * m {
2813            curves.push(SectionCurve { curve: fit_planar(&root, after + centre_x, after - centre_x, tolerance)?, role: "G", tooth: k });
2814        }
2815    }
2816    snap_junctions(&mut curves);
2817    let samples = 4096;
2818    let (mut tip_max, mut root_min) = (0.0_f64, f64::INFINITY);
2819    for i in 0..samples {
2820        let s = perimeter * i as f64 / samples as f64;
2821        tip_max = tip_max.max(radius_of(tip(s)));
2822        root_min = root_min.min(radius_of(rack.place([s, -h_f], s)));
2823    }
2824    let data = GearData {
2825        pitch_diameter: perimeter / PI,
2826        tip_diameter: 2.0 * tip_max,
2827        root_diameter: 2.0 * root_min,
2828        tooth_thickness: p / 2.0 - gear.backlash,
2829        ..GearData::default()
2830    };
2831    Ok(GearSection { curves, data })
2832}
2833
2834/// An elliptical gear solid: the section extruded along +z by the face width;
2835/// names as the section's roles, then `F` and `B`.
2836pub fn elliptical_solid(gear: &EllipticalGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
2837    let section = elliptical_section(gear)?;
2838    let solid = extrude_section(&section, gear.face_width)?;
2839    let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
2840    names.push("F".into());
2841    names.push("B".into());
2842    Ok((solid, names, section.data))
2843}
2844
2845/// The parameter breaks (normalised to [0, 1]) at which [`fit_planar`] would
2846/// split `f` on `[a, b]` to fit it within `tolerance`.
2847fn adaptive_breaks(f: &dyn Fn(f64) -> [f64; 2], tolerance: f64) -> Result<Vec<f64>, KernelRefusal> {
2848    let mut breaks = vec![0.0];
2849    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();
2850    while let Some((t0, t1, depth)) = pending.pop() {
2851        if hermite_span_error(f, t0, t1) > tolerance {
2852            if depth >= 16 {
2853                return Err(refuse("gear_fit", format!("gear curve fit did not converge on [{t0}, {t1}]")));
2854            }
2855            let mid = 0.5 * (t0 + t1);
2856            pending.push((mid, t1, depth + 1));
2857            pending.push((t0, mid, depth + 1));
2858        } else {
2859            breaks.push(t1);
2860        }
2861    }
2862    Ok(breaks)
2863}
2864
2865/// The cubic Hermite span of `f` on `[t0, t1]` (numeric end derivatives) as Bézier points.
2866fn hermite_span(f: &dyn Fn(f64) -> [f64; 2], t0: f64, t1: f64) -> [[f64; 2]; 4] {
2867    let derivative = |t: f64| {
2868        let h = 1e-6;
2869        let (p, q) = (f(t + h), f(t - h));
2870        [(p[0] - q[0]) / (2.0 * h), (p[1] - q[1]) / (2.0 * h)]
2871    };
2872    let (p0, p1) = (f(t0), f(t1));
2873    let (d0, d1) = (derivative(t0), derivative(t1));
2874    let k = (t1 - t0) / 3.0;
2875    [p0, [p0[0] + d0[0] * k, p0[1] + d0[1] * k], [p1[0] - d1[0] * k, p1[1] - d1[1] * k], p1]
2876}
2877
2878fn hermite_span_error(f: &dyn Fn(f64) -> [f64; 2], t0: f64, t1: f64) -> f64 {
2879    let c = hermite_span(f, t0, t1);
2880    [0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
2881        .iter()
2882        .map(|&u| {
2883            let exact = f(t0 + (t1 - t0) * u);
2884            let v = 1.0 - u;
2885            let w = [v * v * v, 3.0 * v * v * u, 3.0 * v * u * u, u * u * u];
2886            let x = w[0] * c[0][0] + w[1] * c[1][0] + w[2] * c[2][0] + w[3] * c[3][0];
2887            let y = w[0] * c[0][1] + w[1] * c[1][1] + w[2] * c[2][1] + w[3] * c[3][1];
2888            (exact[0] - x).hypot(exact[1] - y)
2889        })
2890        .fold(0.0, f64::max)
2891}
2892
2893/// `f` on [0, 1] as C1 cubic Hermite spans at the given breaks (as
2894/// [`fit_planar`] lays them out), and its worst error over the spans.
2895fn fit_on_breaks(f: &dyn Fn(f64) -> [f64; 2], breaks: &[f64]) -> Result<(NurbsCurve, f64), KernelRefusal> {
2896    let to_point = |p: [f64; 2]| Vec4::from_point(Vec3::new(p[0], p[1], 0.0), 1.0);
2897    let mut knots = vec![0.0; 4];
2898    let mut points = Vec::with_capacity(2 * breaks.len() + 2);
2899    let mut worst = 0.0_f64;
2900    let spans = breaks.len() - 1;
2901    for index in 0..spans {
2902        let (t0, t1) = (breaks[index], breaks[index + 1]);
2903        let c = hermite_span(f, t0, t1);
2904        worst = worst.max(hermite_span_error(f, t0, t1));
2905        if index == 0 {
2906            points.push(to_point(c[0]));
2907        }
2908        points.push(to_point(c[1]));
2909        points.push(to_point(c[2]));
2910        if index + 1 < spans {
2911            knots.extend([t1, t1]);
2912        } else {
2913            points.push(to_point(c[3]));
2914        }
2915    }
2916    knots.extend([1.0; 4]);
2917    Ok((NurbsCurve::new(3, knots, points).map_err(|error| refuse("gear_fit", error))?, worst))
2918}
2919
2920/// A throated (single-enveloping) worm wheel: the teeth are cut as a hob of
2921/// the mating ZA worm cuts them, the worm's thread swept by the generating
2922/// motion (the worm turning, the wheel turning with it at the gear ratio).
2923/// In every plane across the face width the worm's thread section moves as a
2924/// rack and the wheel section is its envelope; the flanks, tips (the throat,
2925/// a torus about the worm's axis) and roots are skinned through those
2926/// sections. Front face on z = 0, back face on z = face width; the worm's
2927/// axis runs along +y at x = centre distance, z = face width / 2.
2928#[derive(Clone, Debug)]
2929pub struct WormWheel {
2930    /// The mating worm (its length is not used).
2931    pub worm: Worm,
2932    pub teeth: usize,
2933    /// Wheel addendum × module, in the mid-plane (the throat).
2934    pub addendum: f64,
2935    /// Wheel dedendum × module, in the mid-plane: the hob's tip (the worm's tip plus the clearance).
2936    pub dedendum: f64,
2937    pub face_width: f64,
2938    /// Axial backlash: the hob's thread is that much thicker than the worm's.
2939    pub backlash: f64,
2940}
2941
2942/// The worm wheel's sizes: (pitch radius, centre distance, throat radius in the mid-plane, outside radius at the faces).
2943pub fn worm_wheel_sizes(wheel: &WormWheel) -> (f64, f64, f64, f64) {
2944    let m = wheel.worm.axial_module;
2945    let r2 = m * wheel.teeth as f64 / 2.0;
2946    let a = r2 + wheel.worm.reference_diameter / 2.0;
2947    let throat = r2 + wheel.addendum * m;
2948    let tube = a - throat;
2949    let half = wheel.face_width / 2.0;
2950    (r2, a, throat, a - (tube * tube - half * half).max(0.0).sqrt())
2951}
2952
2953/// One plane z = c (from the mid-plane) of the wheel: the hob section as a rack.
2954struct WheelPlane<'a> {
2955    wheel: &'a WormWheel,
2956    c: f64,
2957    r2: f64,
2958    a: f64,
2959    /// The hob's tip radius about the worm axis.
2960    rho_tip: f64,
2961    /// The wheel's tip (throat) radius in this plane.
2962    r_tip: f64,
2963    /// Flank parameters (radius about the worm axis) where each flank reaches the tip: [- side, + side].
2964    rho_clip: [f64; 2],
2965}
2966
2967impl<'a> WheelPlane<'a> {
2968    fn new(wheel: &'a WormWheel, c: f64) -> Result<Self, KernelRefusal> {
2969        let m = wheel.worm.axial_module;
2970        let (r2, a, throat, _) = worm_wheel_sizes(wheel);
2971        let rho_tip = a - (r2 - wheel.dedendum * m);
2972        let tube = a - throat;
2973        let r_tip = a - (tube * tube - c * c).sqrt();
2974        let mut plane = Self { wheel, c, r2, a, rho_tip, r_tip, rho_clip: [0.0; 2] };
2975        for (index, side) in [-1.0, 1.0].into_iter().enumerate() {
2976            // The generated flank falls from above the tip to the root. A hob point with rho under the throat's
2977            // tube radius sits beyond the throat (x = a - sqrt(rho^2 - c^2) > r_tip), and so does its envelope.
2978            let (mut lo, mut hi) = (0.5 * (c.abs() + tube), rho_tip);
2979            if !(radius_of(plane.flank(side, lo)) > r_tip && radius_of(plane.flank(side, hi)) < r_tip) {
2980                return Err(refuse("gear_fit", "A worm wheel flank does not reach its throat.".into()));
2981            }
2982            for _ in 0..200 {
2983                let mid = 0.5 * (lo + hi);
2984                if radius_of(plane.flank(side, mid)) > r_tip { lo = mid } else { hi = mid }
2985            }
2986            plane.rho_clip[index] = 0.5 * (lo + hi);
2987        }
2988        Ok(plane)
2989    }
2990
2991    /// The hob flank point (radial x from the wheel axis, y along the worm axis) at radius `rho`
2992    /// about the worm axis, on the `side` (±1) of the thread centred on y = 0.
2993    fn hob(&self, side: f64, rho: f64) -> [f64; 2] {
2994        let worm = &self.wheel.worm;
2995        let hand = if worm.hand == Hand::Right { 1.0 } else { -1.0 };
2996        let thickness = worm.axial_thickness(rho) + self.wheel.backlash;
2997        let angle = (self.c / rho).clamp(-1.0, 1.0).asin();
2998        [self.a - (rho * rho - self.c * self.c).max(0.0).sqrt(), side * thickness / 2.0 + hand * worm.lead() * angle / TAU]
2999    }
3000
3001    fn hob_normal(&self, side: f64, rho: f64) -> [f64; 2] {
3002        // d/drho of hob(): x = a - sqrt(rho^2 - c^2), y = side t(rho) / 2 + hand L asin(c / rho) / 2 pi (exact:
3003        // a difference quotient's rounding noise is magnified by the fits' own derivative steps).
3004        let worm = &self.wheel.worm;
3005        let hand = if worm.hand == Hand::Right { 1.0 } else { -1.0 };
3006        let root = (rho * rho - self.c * self.c).max(1e-300).sqrt();
3007        let t = [-rho / root, -side * worm.pressure_angle.tan() - hand * worm.lead() * self.c / (TAU * rho * root)];
3008        let length = t[0].hypot(t[1]);
3009        // Outward of the thread: +y on the + side.
3010        let n = [-t[1] / length, t[0] / length];
3011        if n[1] * side >= 0.0 { n } else { [-n[0], -n[1]] }
3012    }
3013
3014    /// The wheel point generated by the hob point `q` with normal `n` (rolling at the pitch radius).
3015    fn envelope(&self, q: [f64; 2], n: [f64; 2]) -> [f64; 2] {
3016        let s = (q[0] - self.r2) * n[1] / n[0] - q[1];
3017        rotate([q[0], q[1] + s], -s / self.r2)
3018    }
3019
3020    fn flank(&self, side: f64, rho: f64) -> [f64; 2] {
3021        self.envelope(self.hob(side, rho), self.hob_normal(side, rho))
3022    }
3023
3024    /// The root fillet the hob's sharp tip corner traces, `t` from the flank (0) to the tip land (1).
3025    fn fillet(&self, side: f64, t: f64) -> [f64; 2] {
3026        let n = self.hob_normal(side, self.rho_tip);
3027        let from = n[1].atan2(n[0]);
3028        let psi = from + t * (side * PI - from);
3029        self.envelope(self.hob(side, self.rho_tip), [psi.cos(), psi.sin()])
3030    }
3031
3032    /// The six pieces of tooth 0 on normalised parameters, in section order V, R, K, L, W, G.
3033    fn piece(&self, role: usize, t: f64) -> [f64; 2] {
3034        let tau = TAU / self.wheel.teeth as f64;
3035        let half = tau / 2.0;
3036        let turn = |p: [f64; 2], angle: f64| rotate(p, angle);
3037        let root_r = self.a - (self.rho_tip * self.rho_tip - self.c * self.c).sqrt();
3038        match role {
3039            0 => turn(self.fillet(1.0, 1.0 - t), -half),
3040            1 => turn(self.flank(1.0, self.rho_tip + t * (self.rho_clip[1] - self.rho_tip)), -half),
3041            2 => {
3042                let from = polar_angle(self.flank(1.0, self.rho_clip[1]));
3043                let to = tau + polar_angle(self.flank(-1.0, self.rho_clip[0]));
3044                let angle = from + t * (to - from) - half;
3045                [self.r_tip * angle.cos(), self.r_tip * angle.sin()]
3046            }
3047            3 => turn(self.flank(-1.0, self.rho_clip[0] + t * (self.rho_tip - self.rho_clip[0])), half),
3048            4 => turn(self.fillet(-1.0, t), half),
3049            _ => {
3050                // The root land of the space after the tooth (the base space turned by tau, then by -half).
3051                let from = polar_angle(self.fillet(-1.0, 1.0));
3052                let to = polar_angle(self.fillet(1.0, 1.0));
3053                let angle = from + t * (to - from) + half;
3054                [root_r * angle.cos(), root_r * angle.sin()]
3055            }
3056        }
3057    }
3058
3059    /// Refuse a plane whose teeth are pointed, whose roots meet, or whose flanks are undercut.
3060    fn check(&self) -> Result<(), KernelRefusal> {
3061        let m = self.wheel.worm.axial_module;
3062        let tau = TAU / self.wheel.teeth as f64;
3063        let tip_span = tau + polar_angle(self.flank(-1.0, self.rho_clip[0])) - polar_angle(self.flank(1.0, self.rho_clip[1]));
3064        if tip_span * self.r_tip <= 1e-6 * m {
3065            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)));
3066        }
3067        let root_span = polar_angle(self.fillet(1.0, 1.0)) - polar_angle(self.fillet(-1.0, 1.0));
3068        if root_span <= 1e-9 {
3069            return Err(refuse("teeth_overlap", "The worm thread is wider than the wheel's tooth space at the root: lower the dedendum.".into()));
3070        }
3071        // Each flank must fall steadily from its tip to its root, and the corner's trace must not cross it.
3072        for side in [-1.0, 1.0] {
3073            let index = if side < 0.0 { 0 } else { 1 };
3074            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();
3075            let fillet: Vec<[f64; 2]> = (0..=48).map(|i| self.fillet(side, i as f64 / 48.0)).collect();
3076            let falling = flank.windows(2).all(|pair| radius_of(pair[1]) < radius_of(pair[0]));
3077            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])));
3078            if !falling || crosses {
3079                return Err(refuse(
3080                    "undercut",
3081                    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),
3082                ));
3083            }
3084        }
3085        Ok(())
3086    }
3087}
3088
3089fn segments_cross(a: [f64; 2], b: [f64; 2], c: [f64; 2], d: [f64; 2]) -> bool {
3090    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]);
3091    let (d1, d2) = (cross(c, d, a), cross(c, d, b));
3092    let (d3, d4) = (cross(a, b, c), cross(a, b, d));
3093    d1 * d2 < 0.0 && d3 * d4 < 0.0
3094}
3095
3096const WHEEL_ROLES: [&str; 6] = ["V", "R", "K", "L", "W", "G"];
3097
3098/// Tooth 0's six curves in the plane `c`, fitted on the shared breaks, at height z.
3099fn wheel_tooth(plane: &WheelPlane, breaks: &[Vec<f64>], z: f64) -> Result<(Vec<NurbsCurve>, f64), KernelRefusal> {
3100    let mut curves = Vec::with_capacity(6);
3101    let mut worst = 0.0_f64;
3102    for (role, role_breaks) in breaks.iter().enumerate() {
3103        let (mut curve, error) = fit_on_breaks(&|t| plane.piece(role, t), role_breaks)?;
3104        worst = worst.max(error);
3105        for p in &mut curve.control_points {
3106            p.z = z * p.w;
3107        }
3108        curves.push(curve);
3109    }
3110    Ok((curves, worst))
3111}
3112
3113/// The full section (every tooth) from tooth 0's curves, junctions shared.
3114fn wheel_section(tooth: &[NurbsCurve], teeth: usize) -> Vec<SectionCurve> {
3115    let tau = TAU / teeth as f64;
3116    let mut curves = Vec::with_capacity(6 * teeth);
3117    for index in 0..teeth {
3118        for (role, curve) in tooth.iter().enumerate() {
3119            curves.push(SectionCurve { curve: rotated(curve, tau * index as f64), role: WHEEL_ROLES[role], tooth: index });
3120        }
3121    }
3122    snap_junctions(&mut curves);
3123    curves
3124}
3125
3126/// A throated worm wheel solid and its data; face names as the spur gear's
3127/// per tooth (`V/R/K/L/W/G<n>`, the `K` faces making the throat), then `F` (z = 0) and `B`.
3128pub fn worm_wheel_solid(wheel: &WormWheel) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
3129    let worm = &wheel.worm;
3130    let m = worm.axial_module;
3131    worm_section(worm)?; // the worm's own checks
3132    if wheel.teeth < 12 || wheel.teeth > 400 {
3133        return Err(refuse("gear_input", format!("A worm wheel needs from 12 to 400 teeth (it has {}).", wheel.teeth)));
3134    }
3135    if !(wheel.addendum > 0.0 && wheel.dedendum > 0.0 && wheel.face_width > 0.0 && wheel.backlash >= 0.0) {
3136        return Err(refuse("gear_input", "The wheel's addendum, dedendum and face width must be positive, the backlash not negative.".into()));
3137    }
3138    let (r2, a, throat, _) = worm_wheel_sizes(wheel);
3139    let tube = a - throat;
3140    let limit = 0.9 * tube;
3141    if wheel.face_width / 2.0 > limit {
3142        return Err(refuse(
3143            "face_too_wide",
3144            format!("The face width ({}) must stay inside the throat: at most {:.4} for this worm.", wheel.face_width, 2.0 * limit),
3145        ));
3146    }
3147    // The hob's thread at the wheel's tip (in the mid-plane) must leave a tooth in the axial pitch. Checked
3148    // here, before any polar angle: a thread a whole pitch wider wraps round to the same teeth.
3149    if worm.axial_thickness(tube) + wheel.backlash >= PI * m - 1e-6 * m {
3150        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)));
3151    }
3152    if worm.axial_thickness(a - (r2 - wheel.dedendum * m)) + wheel.backlash <= 1e-6 * m {
3153        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()));
3154    }
3155    let half = wheel.face_width / 2.0;
3156    let tolerance = GEAR_FIT_TOLERANCE * m;
3157    let skin_tolerance = 1e-5 * m;
3158    // Shared breaks per role from the mid-plane and both faces.
3159    let probe: Vec<WheelPlane> = [-half, 0.0, half].iter().map(|&c| WheelPlane::new(wheel, c)).collect::<Result<_, _>>()?;
3160    for plane in &probe {
3161        plane.check()?;
3162    }
3163    let mut breaks: Vec<Vec<f64>> = Vec::with_capacity(6);
3164    for role in 0..6 {
3165        let mut all: Vec<f64> = Vec::new();
3166        for plane in &probe {
3167            all.extend(adaptive_breaks(&|t| plane.piece(role, t), tolerance)?);
3168        }
3169        all.sort_by(f64::total_cmp);
3170        all.dedup_by(|x, y| (*x - *y).abs() < 1e-12);
3171        breaks.push(all);
3172    }
3173    // Planes across the face; each plane's control points carried along v by
3174    // cubic Hermite spans (derivatives from planes a step either side).
3175    let mut planes = 8usize;
3176    loop {
3177        let step = wheel.face_width / planes as f64;
3178        let delta = 1e-3 * step;
3179        let mut rows: Vec<Vec<NurbsCurve>> = Vec::with_capacity(planes + 1); // tooth 0 per plane
3180        let mut slopes: Vec<Vec<Vec<[f64; 2]>>> = Vec::with_capacity(planes + 1);
3181        let mut refit = false;
3182        for j in 0..=planes {
3183            let c = -half + step * j as f64;
3184            let plane = WheelPlane::new(wheel, c)?;
3185            plane.check()?;
3186            let (tooth, worst) = wheel_tooth(&plane, &breaks, c + half)?;
3187            if worst > tolerance {
3188                refit = true;
3189                break;
3190            }
3191            let lo = wheel_tooth(&WheelPlane::new(wheel, c - delta)?, &breaks, 0.0)?.0;
3192            let hi = wheel_tooth(&WheelPlane::new(wheel, c + delta)?, &breaks, 0.0)?.0;
3193            let slope: Vec<Vec<[f64; 2]>> = lo
3194                .iter()
3195                .zip(&hi)
3196                .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())
3197                .collect();
3198            rows.push(tooth);
3199            slopes.push(slope);
3200        }
3201        if refit {
3202            // A plane the shared breaks fit too loosely: halve every span and start over.
3203            for role_breaks in &mut breaks {
3204                let mut finer = Vec::with_capacity(2 * role_breaks.len());
3205                for pair in role_breaks.windows(2) {
3206                    finer.push(pair[0]);
3207                    finer.push(0.5 * (pair[0] + pair[1]));
3208                }
3209                finer.push(1.0);
3210                *role_breaks = finer;
3211            }
3212            continue;
3213        }
3214        // Check the skin halfway between planes against the exact plane there.
3215        let mut worst = 0.0_f64;
3216        for j in 0..planes {
3217            let c = -half + step * (j as f64 + 0.5);
3218            let exact = wheel_tooth(&WheelPlane::new(wheel, c)?, &breaks, 0.0)?.0;
3219            for role in 0..6 {
3220                for (k, p) in exact[role].control_points.iter().enumerate() {
3221                    let (p0, p1) = (rows[j][role].control_points[k], rows[j + 1][role].control_points[k]);
3222                    let (d0, d1) = (slopes[j][role][k], slopes[j + 1][role][k]);
3223                    let x = 0.5 * (p0.x + p1.x) + step * (d0[0] - d1[0]) / 8.0;
3224                    let y = 0.5 * (p0.y + p1.y) + step * (d0[1] - d1[1]) / 8.0;
3225                    worst = worst.max((x - p.x).hypot(y - p.y));
3226                }
3227            }
3228        }
3229        if worst > skin_tolerance {
3230            if planes >= 256 {
3231                return Err(refuse("gear_fit", format!("The worm wheel's flanks could not be skinned within {skin_tolerance:.2e} ({worst:.2e}).")));
3232            }
3233            planes *= 2;
3234            continue;
3235        }
3236        // Rows along v for every control point of the full bottom section, keyed by its bits.
3237        let sections: Vec<Vec<SectionCurve>> = rows.iter().map(|tooth| wheel_section(tooth, wheel.teeth)).collect();
3238        let tau = TAU / wheel.teeth as f64;
3239        let mut table: std::collections::HashMap<[u64; 4], Vec<Vec4>> = std::collections::HashMap::new();
3240        let h = 1.0 / planes as f64;
3241        for (index, piece) in sections[0].iter().enumerate() {
3242            let (role, tooth) = (index % 6, index / 6);
3243            let (s, cs) = (tau * tooth as f64).sin_cos();
3244            for (k, p) in piece.curve.control_points.iter().enumerate() {
3245                let mut row = Vec::with_capacity(3 * planes + 1);
3246                for j in 0..=planes {
3247                    let q = sections[j][index].curve.control_points[k];
3248                    let d = slopes[j][role][k];
3249                    // The slope in v (per unit v: face width per unit c), turned with the tooth.
3250                    let dv = [wheel.face_width * (cs * d[0] - s * d[1]), wheel.face_width * (s * d[0] + cs * d[1]), wheel.face_width];
3251                    let point = Vec3::new(q.x, q.y, q.z);
3252                    if j > 0 {
3253                        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));
3254                    }
3255                    if j == 0 || j == planes {
3256                        row.push(Vec4::from_point(point, 1.0));
3257                    }
3258                    if j < planes {
3259                        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));
3260                    }
3261                }
3262                table.insert([p.x.to_bits(), p.y.to_bits(), p.z.to_bits(), p.w.to_bits()], row);
3263            }
3264        }
3265        let mut knots_v = vec![0.0; 4];
3266        for j in 1..planes {
3267            let v = j as f64 * h;
3268            knots_v.extend([v, v]);
3269        }
3270        knots_v.extend([1.0; 4]);
3271        let section = GearSection { curves: sections[0].clone(), data: GearData::default() };
3272        let solid = prism_by_rows(&section, 3, &knots_v, &|p: Vec4| {
3273            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")
3274        })?;
3275        let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
3276        names.push("F".into());
3277        names.push("B".into());
3278        let data = GearData {
3279            pitch_diameter: 2.0 * r2,
3280            tip_diameter: 2.0 * throat,
3281            root_diameter: 2.0 * (r2 - wheel.dedendum * m),
3282            tip_thickness: 0.0,
3283            ..GearData::default()
3284        };
3285        return Ok((solid, names, data));
3286    }
3287}
3288