use crate::{extrude_profile_brep, make_arc, BrepSolid, KernelRefusal, KernelStage, NurbsCurve, NurbsSurface, Vec3, Vec4};
use std::f64::consts::{PI, TAU};
pub const GEAR_FIT_TOLERANCE: f64 = 5e-7;
#[derive(Clone, Debug)]
pub struct SpurGear {
pub module: f64,
pub teeth: usize,
pub pressure_angle: f64,
pub profile_shift: f64,
pub addendum: f64,
pub dedendum: f64,
pub root_fillet: f64,
pub backlash: f64,
pub face_width: f64,
}
impl Default for SpurGear {
fn default() -> Self {
Self {
module: 2.0,
teeth: 20,
pressure_angle: 20f64.to_radians(),
profile_shift: 0.0,
addendum: 1.0,
dedendum: 1.25,
root_fillet: 0.38,
backlash: 0.0,
face_width: 10.0,
}
}
}
#[derive(Clone, Debug, Default)]
pub struct GearData {
pub pitch_diameter: f64,
pub base_diameter: f64,
pub tip_diameter: f64,
pub root_diameter: f64,
pub form_diameter: f64,
pub tooth_thickness: f64,
pub tip_thickness: f64,
pub undercut: bool,
pub min_shift_without_undercut: f64,
}
#[derive(Clone, Debug)]
pub struct SectionCurve {
pub curve: NurbsCurve,
pub role: &'static str,
pub tooth: usize,
}
impl SectionCurve {
pub fn suffix(&self) -> String {
format!("{}{}", self.role, self.tooth)
}
}
#[derive(Clone, Debug)]
pub struct GearSection {
pub curves: Vec<SectionCurve>,
pub data: GearData,
}
fn refuse(code: &str, message: String) -> KernelRefusal {
KernelRefusal::input(KernelStage::Collect, code, message)
}
fn rotate(point: [f64; 2], angle: f64) -> [f64; 2] {
let (s, c) = angle.sin_cos();
[c * point[0] - s * point[1], s * point[0] + c * point[1]]
}
fn polar_angle(point: [f64; 2]) -> f64 {
point[1].atan2(point[0])
}
fn radius_of(point: [f64; 2]) -> f64 {
point[0].hypot(point[1])
}
struct RackCutter {
r: f64,
alpha: f64,
x_ref: f64,
y0: f64,
r_f: f64,
rho: f64,
centre: [f64; 2],
}
impl RackCutter {
fn new(gear: &SpurGear) -> Self {
let m = gear.module;
let r = m * gear.teeth as f64 / 2.0;
let p = PI * m;
let alpha = gear.pressure_angle;
let x_ref = r + gear.profile_shift * m;
let y0 = p / 4.0 - gear.backlash / 2.0;
let r_f = x_ref - gear.dedendum * m;
let rho = gear.root_fillet * m;
let x_c = r_f + rho;
let y_c = y0 + (rho + (x_ref - x_c) * alpha.sin()) / alpha.cos();
Self { r, alpha, x_ref, y0, r_f, rho, centre: [x_c, y_c] }
}
fn envelope(&self, q: [f64; 2], n: [f64; 2]) -> [f64; 2] {
let s = (q[0] - self.r) * n[1] / n[0] - q[1];
rotate([q[0], q[1] + s], -s / self.r)
}
fn flank(&self, x: f64) -> [f64; 2] {
let a = self.alpha;
let q = [x, self.y0 + (self.x_ref - x) * a.tan()];
self.envelope(q, [-a.sin(), -a.cos()])
}
fn fillet(&self, psi: f64) -> [f64; 2] {
let n = [-psi.cos(), -psi.sin()];
if self.rho == 0.0 {
return self.envelope(self.centre, n);
}
let q = [self.centre[0] + self.rho * n[0], self.centre[1] + self.rho * n[1]];
self.envelope(q, n)
}
fn flank_x_at_radius(&self, radius: f64) -> f64 {
let c = 1.0 / self.alpha.tan();
let c2 = c * c;
let disc = (self.r * self.r * c2 * c2 - (1.0 + c2) * (self.r * self.r * c2 - radius * radius)).max(0.0);
(self.r * c2 + disc.sqrt()) / (1.0 + c2)
}
}
fn fit_planar(f: &dyn Fn(f64) -> [f64; 2], a: f64, b: f64, tolerance: f64) -> Result<NurbsCurve, KernelRefusal> {
let derivative = |t: f64| {
let h = 1e-6 * (b - a).abs().max(1e-12);
let p = f(t + h);
let q = f(t - h);
[(p[0] - q[0]) / (2.0 * h), (p[1] - q[1]) / (2.0 * h)]
};
let span_points = |t0: f64, t1: f64| {
let (p0, p1) = (f(t0), f(t1));
let (d0, d1) = (derivative(t0), derivative(t1));
let k = (t1 - t0) / 3.0;
[p0, [p0[0] + d0[0] * k, p0[1] + d0[1] * k], [p1[0] - d1[0] * k, p1[1] - d1[1] * k], p1]
};
let bezier = |c: &[[f64; 2]; 4], u: f64| {
let v = 1.0 - u;
let w = [v * v * v, 3.0 * v * v * u, 3.0 * v * u * u, u * u * u];
[
w[0] * c[0][0] + w[1] * c[1][0] + w[2] * c[2][0] + w[3] * c[3][0],
w[0] * c[0][1] + w[1] * c[1][1] + w[2] * c[2][1] + w[3] * c[3][1],
]
};
let mut pending: Vec<(f64, f64, usize)> = (0..4).rev().map(|i| {
let t0 = a + (b - a) * i as f64 / 4.0;
let t1 = a + (b - a) * (i + 1) as f64 / 4.0;
(t0, t1, 0)
}).collect();
let mut spans: Vec<(f64, f64, [[f64; 2]; 4])> = Vec::new();
while let Some((t0, t1, depth)) = pending.pop() {
let c = span_points(t0, t1);
let worst = [0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
.iter()
.map(|&u| {
let exact = f(t0 + (t1 - t0) * u);
let fitted = bezier(&c, u);
(exact[0] - fitted[0]).hypot(exact[1] - fitted[1])
})
.fold(0.0, f64::max);
if worst > tolerance && depth < 16 {
let mid = 0.5 * (t0 + t1);
pending.push((mid, t1, depth + 1));
pending.push((t0, mid, depth + 1));
} else if worst > tolerance {
return Err(refuse("gear_fit", format!("gear curve fit did not converge ({worst:.3e} > {tolerance:.3e})")));
} else {
spans.push((t0, t1, c));
}
}
let scale = 1.0 / (b - a);
let to_point = |p: [f64; 2]| Vec4::from_point(Vec3::new(p[0], p[1], 0.0), 1.0);
let mut knots = vec![0.0; 4];
let mut points = vec![to_point(spans[0].2[0])];
for (index, (_, t1, c)) in spans.iter().enumerate() {
points.push(to_point(c[1]));
points.push(to_point(c[2]));
if index + 1 < spans.len() {
let k = (t1 - a) * scale;
knots.extend([k, k]);
} else {
points.push(to_point(c[3]));
}
}
knots.extend([1.0; 4]);
NurbsCurve::new(3, knots, points).map_err(|error| refuse("gear_fit", error))
}
fn mirrored(curve: &NurbsCurve) -> NurbsCurve {
let mut copy = curve.clone();
for point in &mut copy.control_points {
point.y = -point.y;
}
NurbsCurve::new(copy.degree, copy.knots, copy.control_points).expect("a mirrored curve is a valid curve")
}
fn rotated(curve: &NurbsCurve, angle: f64) -> NurbsCurve {
let (s, c) = angle.sin_cos();
let points = curve
.control_points
.iter()
.map(|p| Vec4 { x: c * p.x - s * p.y, y: s * p.x + c * p.y, z: p.z, w: p.w })
.collect();
NurbsCurve::new(curve.degree, curve.knots.clone(), points).expect("a rotated curve is a valid curve")
}
fn arc(radius: f64, from: f64, to: f64) -> Result<NurbsCurve, KernelRefusal> {
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)
.map_err(|error| refuse("gear_arc", error))
}
fn check_spur(gear: &SpurGear, max_pressure_degrees: f64) -> Result<(), KernelRefusal> {
let positive = |value: f64, what: &str| {
if value.is_finite() && value > 0.0 {
Ok(())
} else {
Err(refuse("gear_input", format!("The {what} must be greater than zero (it is {value}).")))
}
};
positive(gear.module, "module")?;
positive(gear.face_width, "face width")?;
positive(gear.addendum, "addendum coefficient")?;
positive(gear.dedendum, "dedendum coefficient")?;
if gear.teeth < 3 {
return Err(refuse("gear_input", format!("A gear needs at least 3 teeth (it has {}).", gear.teeth)));
}
let degrees = gear.pressure_angle.to_degrees();
if !(10.0 - 1e-9..=max_pressure_degrees + 1e-9).contains(°rees) {
return Err(refuse("gear_input", format!("The pressure angle must be between 10° and {max_pressure_degrees}° (it is {degrees}°).")));
}
if !(gear.root_fillet >= 0.0) || !(gear.backlash >= 0.0) || !gear.profile_shift.is_finite() {
return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
}
Ok(())
}
pub fn spur_section(gear: &SpurGear) -> Result<GearSection, KernelRefusal> {
check_spur(gear, 35.0)?;
generated_section(gear)
}
fn transverse_section(gear: &SpurGear) -> Result<GearSection, KernelRefusal> {
check_spur(gear, 60.0)?;
generated_section(gear)
}
fn generated_section(gear: &SpurGear) -> Result<GearSection, KernelRefusal> {
let m = gear.module;
let z = gear.teeth as f64;
let rack = RackCutter::new(gear);
let alpha = rack.alpha;
let r = rack.r;
let r_b = r * alpha.cos();
let r_a = r + (gear.addendum + gear.profile_shift) * m;
let r_f = rack.r_f;
let half_pitch = PI / z;
let tolerance = GEAR_FIT_TOLERANCE * m;
if r_f <= 1e-9 * m {
return Err(refuse(
"root_below_centre",
format!("The root circle diameter is zero or negative (d = {:.4}): too few teeth for this dedendum.", 2.0 * r_f),
));
}
let rho_max = ((PI * m / 2.0 - rack.y0) * alpha.cos() - (rack.x_ref - r_f) * alpha.sin()) / (1.0 - alpha.sin());
if rack.rho > rho_max + 1e-9 * m {
return Err(refuse(
"root_fillet_too_large",
format!(
"The root fillet coefficient {:.4} is larger than the {:.4} that fits this tooth space; lower it.",
gear.root_fillet,
rho_max / m
),
));
}
let psi_end = PI / 2.0 - alpha;
let x_flank_tangent = rack.centre[0] - rack.rho * alpha.sin();
let x_interference = r * alpha.cos().powi(2);
let min_shift = gear.dedendum - gear.root_fillet * (1.0 - alpha.sin()) - z / 2.0 * alpha.sin().powi(2);
let undercut = x_flank_tangent < x_interference - 1e-12 * m;
let (x_join, psi_join) = if !undercut {
(x_flank_tangent, psi_end)
} else {
let difference = |psi: f64| -> Option<f64> {
let point = rack.fillet(psi);
let radius = radius_of(point);
if radius <= r_b {
return None;
}
Some(polar_angle(point) - polar_angle(rack.flank(rack.flank_x_at_radius(radius))))
};
let (mut below, mut above) = (0.0, psi_end);
for _ in 0..200 {
let mid = 0.5 * (below + above);
if radius_of(rack.fillet(mid)) <= r_b { below = mid } else { above = mid }
}
let psi_base = above;
let steps = 4000;
let mut found = None;
let mut previous: Option<(f64, f64)> = None;
for step in 0..=steps {
let psi = psi_end - (psi_end - psi_base) * step as f64 / steps as f64;
if let Some(value) = difference(psi) {
if let Some((last_psi, last_value)) = previous {
if (value <= 0.0) != (last_value <= 0.0) {
found = Some((psi, last_psi));
break;
}
}
previous = Some((psi, value));
}
}
let (mut lo, mut hi) = found.unwrap_or((psi_base, psi_base));
let sign_lo = difference(lo).unwrap_or(-1.0) <= 0.0;
for _ in 0..200 {
let mid = 0.5 * (lo + hi);
match difference(mid) {
Some(value) if (value <= 0.0) == sign_lo => lo = mid,
Some(_) => hi = mid,
None => lo = mid,
}
}
let psi = 0.5 * (lo + hi);
(rack.flank_x_at_radius(radius_of(rack.fillet(psi))), psi)
};
let join = rack.fillet(psi_join);
let form_radius = radius_of(join);
if r_a <= form_radius + 1e-9 * m {
return Err(refuse(
"tip_below_form",
format!(
"The tip circle (d = {:.4}) does not reach above the form circle (d = {:.4}); raise the addendum or lower the dedendum.",
2.0 * r_a,
2.0 * form_radius
),
));
}
let x_tip = rack.flank_x_at_radius(r_a);
let tip = rack.flank(x_tip);
let thickness = PI * m / 2.0 + 2.0 * gear.profile_shift * m * alpha.tan() - gear.backlash;
let involute = |angle: f64| angle.tan() - angle;
let half_angle = |radius: f64| thickness / (2.0 * r) + involute(alpha) - involute((r_b / radius).min(1.0).acos());
let tip_angle = half_angle(r_a);
let tip_offset = polar_angle(tip) - tip_angle;
if tip_angle * r_a <= 1e-6 * m || tip_offset.abs() > 1e-9 {
let (mut lo, mut hi) = (form_radius.max(r_b), r_a);
for _ in 0..200 {
let mid = 0.5 * (lo + hi);
if half_angle(mid) > 0.0 { lo = mid } else { hi = mid }
}
return Err(refuse(
"pointed_tip",
format!(
"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.",
2.0 * lo,
2.0 * r_a
),
));
}
if tip_angle >= half_pitch {
return Err(refuse("teeth_overlap", "The tooth tips overlap their neighbours.".into()));
}
for step in 0..=64 {
let point = rack.fillet(psi_join * step as f64 / 64.0);
let angle = polar_angle(point);
if angle <= 0.0 || angle > half_pitch + 1e-12 {
return Err(refuse("teeth_overlap", "The tooth gaps cross: the root form of one gap cuts the next tooth.".into()));
}
}
let flank_fit = fit_planar(&|x| rack.flank(x), x_join, x_tip, tolerance)?; let fillet_fit = fit_planar(&|psi| rack.fillet(psi), 0.0, psi_join, tolerance)?; let root_angle = rack.centre[1] / r;
let land = 2.0 * half_pitch - 2.0 * root_angle;
let mut tooth: Vec<(&'static str, NurbsCurve)> = vec![
("V", mirrored(&fillet_fit)),
("R", mirrored(&flank_fit)),
("K", arc(r_a, -tip_angle, tip_angle)?),
("L", flank_fit.reversed().map_err(|e| refuse("gear_fit", e))?),
("W", fillet_fit.reversed().map_err(|e| refuse("gear_fit", e))?),
];
if land > 1e-9 {
tooth.push(("G", arc(r_f, root_angle, 2.0 * half_pitch - root_angle)?));
}
let mut curves = Vec::with_capacity(tooth.len() * gear.teeth);
for index in 0..gear.teeth {
let angle = TAU * index as f64 / z;
for (role, curve) in &tooth {
curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
}
}
snap_junctions(&mut curves);
let thickness_angle = |radius: f64| polar_angle(rack.flank(rack.flank_x_at_radius(radius)));
let data = GearData {
pitch_diameter: 2.0 * r,
base_diameter: 2.0 * r_b,
tip_diameter: 2.0 * r_a,
root_diameter: 2.0 * r_f,
form_diameter: 2.0 * form_radius,
tooth_thickness: 2.0 * r * thickness_angle(r.max(r_b)),
tip_thickness: 2.0 * r_a * tip_angle,
undercut,
min_shift_without_undercut: min_shift,
};
Ok(GearSection { curves, data })
}
pub fn spur_solid(gear: &SpurGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
let section = spur_section(gear)?;
let solid = extrude_section(§ion, gear.face_width)?;
let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
names.push("F".into());
names.push("B".into());
Ok((solid, names, section.data))
}
pub fn extrude_section(section: &GearSection, width: f64) -> Result<BrepSolid, KernelRefusal> {
let curves: Vec<NurbsCurve> = section.curves.iter().map(|piece| piece.curve.clone()).collect();
extrude_profile_brep(&curves, Vec3::new(0.0, 0.0, 1.0), width)
}
#[derive(Clone, Debug)]
pub struct Rack {
pub module: f64,
pub teeth: usize,
pub pressure_angle: f64,
pub addendum: f64,
pub dedendum: f64,
pub root_fillet: f64,
pub backlash: f64,
pub face_width: f64,
pub height: f64,
pub helix_angle: f64,
}
impl Default for Rack {
fn default() -> Self {
Self {
module: 2.0,
teeth: 10,
pressure_angle: 20f64.to_radians(),
addendum: 1.0,
dedendum: 1.25,
root_fillet: 0.38,
backlash: 0.0,
face_width: 10.0,
height: 6.0,
helix_angle: 0.0,
}
}
}
fn line(a: [f64; 2], b: [f64; 2]) -> Result<NurbsCurve, KernelRefusal> {
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))
}
fn centred_arc(centre: [f64; 2], radius: f64, from: f64, to: f64) -> Result<NurbsCurve, KernelRefusal> {
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)
.map_err(|error| refuse("gear_arc", error))
}
pub fn rack_section(rack: &Rack) -> Result<GearSection, KernelRefusal> {
rack_section_checked(rack, 35.0)
}
fn rack_section_checked(rack: &Rack, max_pressure_degrees: f64) -> Result<GearSection, KernelRefusal> {
let m = rack.module;
let positive = |value: f64, what: &str| {
if value.is_finite() && value > 0.0 {
Ok(())
} else {
Err(refuse("gear_input", format!("The {what} must be greater than zero (it is {value}).")))
}
};
positive(m, "module")?;
positive(rack.face_width, "face width")?;
positive(rack.addendum, "addendum coefficient")?;
positive(rack.dedendum, "dedendum coefficient")?;
if rack.teeth < 1 {
return Err(refuse("gear_input", "A rack needs at least one tooth.".into()));
}
let degrees = rack.pressure_angle.to_degrees();
if !(10.0 - 1e-9..=max_pressure_degrees + 1e-9).contains(°rees) {
return Err(refuse("gear_input", format!("The pressure angle must be between 10° and {max_pressure_degrees}° (it is {degrees}°).")));
}
if !(rack.root_fillet >= 0.0) || !(rack.backlash >= 0.0) {
return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
}
let alpha = rack.pressure_angle;
let (ha, hf) = (rack.addendum * m, rack.dedendum * m);
if rack.height <= hf + 1e-9 * m {
return Err(refuse(
"rack_too_thin",
format!("The rack height below the pitch line ({:.4}) must exceed the dedendum ({:.4}).", rack.height, hf),
));
}
let p = PI * m;
let w = p / 4.0 - rack.backlash / 2.0; let tip_half = w - ha * alpha.tan();
if tip_half <= 1e-6 * m {
return Err(refuse(
"pointed_tip",
"The rack teeth come to a point below their tip line; reduce the addendum, the pressure angle or the backlash.".into(),
));
}
let rho = rack.root_fillet * m;
let y_p = -hf + rho - rho * alpha.sin();
let flank_x = |y: f64| w - y * alpha.tan();
let centre = [flank_x(y_p) + rho * alpha.cos(), -hf + rho];
let root_half = centre[0]; if y_p >= ha - 1e-9 * m {
return Err(refuse(
"root_fillet_too_large",
format!(
"The root fillet (coefficient {:.4}) reaches above the tooth tip; lower it or raise the addendum.",
rack.root_fillet
),
));
}
if root_half > p / 2.0 + 1e-9 * m {
let max = (p / 2.0 - w - hf * alpha.tan()) * alpha.cos() / (1.0 - alpha.sin());
return Err(refuse(
"root_fillet_too_large",
format!("The root fillet coefficient {:.4} is larger than the {:.4} that fits this tooth space; lower it.", rack.root_fillet, max / m),
));
}
let length = p * rack.teeth as f64;
let mut curves: Vec<SectionCurve> = Vec::new();
let mut push = |curve: NurbsCurve, role: &'static str, tooth: usize| curves.push(SectionCurve { curve, role, tooth });
let base = -rack.height;
push(line([0.0, base], [length, base])?, "BASE", 0);
push(line([length, base], [length, -hf])?, "E1", 0);
let mut x_prev_root = length; for k in (0..rack.teeth).rev() {
let c = (k as f64 + 0.5) * p;
let right_root = [c + root_half, -hf];
if x_prev_root - right_root[0] > 1e-9 * m {
push(line([x_prev_root, -hf], right_root)?, "G", k + 1);
}
let right_centre = [c + centre[0], centre[1]];
let right_flank_low = [c + flank_x(y_p), y_p];
if rho > 0.0 {
push(centred_arc(right_centre, rho, PI + alpha, 1.5 * PI)?.reversed().map_err(|e| refuse("gear_arc", e))?, "V", k);
}
let right_tip = [c + tip_half, ha];
let left_tip = [c - tip_half, ha];
let left_flank_low = [c - flank_x(y_p), y_p];
push(line(if rho > 0.0 { right_flank_low } else { right_root }, right_tip)?, "R", k);
push(line(right_tip, left_tip)?, "K", k);
let left_root = [c - root_half, -hf];
push(line(left_tip, if rho > 0.0 { left_flank_low } else { left_root })?, "L", k);
if rho > 0.0 {
let left_centre = [c - centre[0], centre[1]];
push(centred_arc(left_centre, rho, 1.5 * PI, 2.0 * PI - alpha)?.reversed().map_err(|e| refuse("gear_arc", e))?, "W", k);
}
x_prev_root = left_root[0];
}
if x_prev_root > 1e-9 * m {
push(line([x_prev_root, -hf], [0.0, -hf])?, "G", 0);
}
push(line([0.0, -hf], [0.0, base])?, "E0", 0);
snap_junctions(&mut curves);
let data = GearData {
pitch_diameter: f64::INFINITY,
tooth_thickness: 2.0 * w,
tip_thickness: 2.0 * tip_half,
..GearData::default()
};
Ok(GearSection { curves, data })
}
pub fn rack_solid(rack: &Rack) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
let beta = rack.helix_angle;
if !(beta.abs().to_degrees() <= 45.0 + 1e-9) {
return Err(refuse("bad_helix", format!("The rack's helix angle must be between −45° and 45° (it is {:.4}°).", beta.to_degrees())));
}
let degrees = rack.pressure_angle.to_degrees();
if !(10.0 - 1e-9..=35.0 + 1e-9).contains(°rees) {
return Err(refuse("gear_input", format!("The pressure angle must be between 10° and 35° (it is {degrees}°).")));
}
if beta == 0.0 {
let section = rack_section(rack)?;
let solid = extrude_section(§ion, rack.face_width)?;
let mut names: Vec<String> = section.curves.iter().map(rack_suffix).collect();
names.push("F".into());
names.push("B".into());
return Ok((solid, names, section.data));
}
let c = beta.cos();
let mut section = rack_section(rack)?;
for piece in &mut section.curves {
for point in &mut piece.curve.control_points {
point.x /= c;
}
}
section.data.tooth_thickness /= c;
section.data.tip_thickness /= c;
let curves: Vec<NurbsCurve> = section.curves.iter().map(|piece| piece.curve.clone()).collect();
let direction = Vec3::new(beta.tan(), 0.0, 1.0);
let solid = extrude_profile_brep(&curves, direction, rack.face_width / c)?;
let mut names: Vec<String> = section.curves.iter().map(rack_suffix).collect();
names.push("F".into());
names.push("B".into());
Ok((solid, names, section.data))
}
fn rack_suffix(piece: &SectionCurve) -> String {
match piece.role {
"BASE" | "E0" | "E1" => piece.role.to_string(),
_ => piece.suffix(),
}
}
fn snap_junctions(curves: &mut [SectionCurve]) {
let count = curves.len();
for index in 0..count {
let start = curves[(index + 1) % count].curve.control_points[0];
let curve = &mut curves[index].curve;
let last = curve.control_points.len() - 1;
let w = curve.control_points[last].w;
curve.control_points[last] = Vec4 { x: start.x / start.w * w, y: start.y / start.w * w, z: 0.0, w };
}
}
#[derive(Clone, Debug)]
pub struct RingGear {
pub module: f64,
pub teeth: usize,
pub pressure_angle: f64,
pub profile_shift: f64,
pub addendum: f64,
pub dedendum: f64,
pub root_fillet: f64,
pub backlash: f64,
pub face_width: f64,
pub rim: f64,
}
impl Default for RingGear {
fn default() -> Self {
Self {
module: 2.0,
teeth: 60,
pressure_angle: 20f64.to_radians(),
profile_shift: 0.0,
addendum: 1.0,
dedendum: 1.25,
root_fillet: 0.38,
backlash: 0.0,
face_width: 10.0,
rim: 6.0,
}
}
}
pub fn ring_section(gear: &RingGear) -> Result<GearSection, KernelRefusal> {
ring_section_checked(gear, 35.0)
}
fn ring_section_checked(gear: &RingGear, max_pressure_degrees: f64) -> Result<GearSection, KernelRefusal> {
let m = gear.module;
let positive = |value: f64, what: &str| {
if value.is_finite() && value > 0.0 {
Ok(())
} else {
Err(refuse("gear_input", format!("The {what} must be greater than zero (it is {value}).")))
}
};
positive(m, "module")?;
positive(gear.face_width, "face width")?;
positive(gear.addendum, "addendum coefficient")?;
positive(gear.dedendum, "dedendum coefficient")?;
positive(gear.rim, "rim thickness")?;
if gear.teeth < 6 {
return Err(refuse("gear_input", format!("An internal gear needs at least 6 teeth (it has {}).", gear.teeth)));
}
let degrees = gear.pressure_angle.to_degrees();
if !(10.0 - 1e-9..=max_pressure_degrees + 1e-9).contains(°rees) {
return Err(refuse("gear_input", format!("The pressure angle must be between 10° and {max_pressure_degrees}° (it is {degrees}°).")));
}
if !(gear.root_fillet >= 0.0) || !(gear.backlash >= 0.0) || !gear.profile_shift.is_finite() {
return Err(refuse("gear_input", "The root fillet and the backlash cannot be negative.".into()));
}
let z = gear.teeth as f64;
let alpha = gear.pressure_angle;
let r = m * z / 2.0;
let r_b = r * alpha.cos();
let r_a = r - (gear.addendum - gear.profile_shift) * m; let r_f = r + (gear.dedendum + gear.profile_shift) * m; let rho = gear.root_fillet * m;
let half_pitch = PI / z;
let tolerance = GEAR_FIT_TOLERANCE * m;
if r_a <= r_b + 1e-9 * m {
return Err(refuse(
"tip_inside_base",
format!(
"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.",
2.0 * r_a,
2.0 * r_b
),
));
}
let space = PI * m / 2.0 + 2.0 * gear.profile_shift * m * alpha.tan() + gear.backlash;
let involute = |angle: f64| angle.tan() - angle;
let half_space = |radius: f64| space / (2.0 * r) + involute(alpha) - involute((r_b / radius).min(1.0).acos());
let flank = |radius: f64| {
let angle = half_space(radius);
[radius * angle.cos(), radius * angle.sin()]
};
if half_space(r_a) >= half_pitch - 1e-6 * m / r_a {
return Err(refuse(
"pointed_tip",
"The ring teeth come to a point at the tip circle: reduce the profile shift, the backlash or the addendum.".into(),
));
}
if half_space(r_f) <= 1e-6 * m / r_f {
let (mut lo, mut hi) = (r_a, r_f);
for _ in 0..200 {
let mid = 0.5 * (lo + hi);
if half_space(mid) > 0.0 { lo = mid } else { hi = mid }
}
return Err(refuse(
"teeth_overlap",
format!(
"The tooth spaces close at d = {:.4}, inside the root circle (d = {:.4}); reduce the dedendum or the profile shift.",
2.0 * lo,
2.0 * r_f
),
));
}
let normal_into_space = |radius: f64| {
let h = 1e-6 * m;
let (a, b) = (flank(radius - h), flank(radius + h));
let (tx, ty) = (b[0] - a[0], b[1] - a[1]);
let length = tx.hypot(ty);
[ty / length, -tx / length]
};
let centre_at = |radius: f64| {
let point = flank(radius);
let n = normal_into_space(radius);
[point[0] + rho * n[0], point[1] + rho * n[1]]
};
let (join_radius, centre) = if rho == 0.0 {
(r_f, flank(r_f))
} else {
let target = r_f - rho;
let (mut lo, mut hi) = (r_a, r_f);
if radius_of(centre_at(lo)) > target {
return Err(refuse("root_fillet_too_large", "The root fillet is too large for the tooth depth; lower it.".into()));
}
for _ in 0..200 {
let mid = 0.5 * (lo + hi);
if radius_of(centre_at(mid)) < target { lo = mid } else { hi = mid }
}
let radius = 0.5 * (lo + hi);
(radius, centre_at(radius))
};
let root_angle = polar_angle(centre);
if rho > 0.0 && root_angle <= 1e-9 {
return Err(refuse(
"root_fillet_too_large",
"The root fillet is larger than fits the tooth space; lower it.".into(),
));
}
let tip_angle = half_space(r_a);
let flank_fit = fit_planar(&|radius| flank(radius), r_a, join_radius, tolerance)?; let mut space: Vec<(&'static str, NurbsCurve)> = Vec::new();
space.push(("R", mirrored(&flank_fit)));
if rho > 0.0 {
let join = flank(join_radius);
let from = root_angle;
let mut to = (join[1] - centre[1]).atan2(join[0] - centre[0]);
while to <= from {
to += TAU;
}
let left = centred_arc(centre, rho, from, to)?; space.push(("V", mirrored(&left).reversed().map_err(|e| refuse("gear_arc", e))?));
space.push(("G", arc(r_f, -root_angle, root_angle)?));
space.push(("W", left));
} else {
space.push(("G", arc(r_f, -root_angle, root_angle)?));
}
space.push(("L", flank_fit.reversed().map_err(|e| refuse("gear_fit", e))?));
space.push(("K", arc(r_a, tip_angle, 2.0 * half_pitch - tip_angle)?));
let mut curves = Vec::with_capacity(space.len() * gear.teeth);
for index in 0..gear.teeth {
let angle = TAU * index as f64 / z;
for (role, curve) in &space {
curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
}
}
snap_junctions(&mut curves);
let data = GearData {
pitch_diameter: 2.0 * r,
base_diameter: 2.0 * r_b,
tip_diameter: 2.0 * r_a,
root_diameter: 2.0 * r_f,
form_diameter: 2.0 * join_radius,
tooth_thickness: 2.0 * r * (half_pitch - half_space(r)),
tip_thickness: 2.0 * r_a * (half_pitch - tip_angle),
undercut: false,
min_shift_without_undercut: 0.0,
};
Ok(GearSection { curves, data })
}
pub fn ring_solid(gear: &RingGear) -> Result<(BrepSolid, GearData), KernelRefusal> {
let section = ring_section(gear)?;
let outer = section.data.root_diameter / 2.0 + gear.rim;
let axis = Vec3::new(0.0, 0.0, 1.0);
let mut blank = crate::make_cylinder_brep(Vec3::new(0.0, 0.0, 0.0), axis, outer, gear.face_width)
.map_err(|error| refuse("gear_blank", error))?;
for (face, name) in blank.shells[0].faces.iter_mut().zip(["OD", "F", "B"]) {
face.name = Some(name.into());
}
let reach = gear.face_width * 0.1 + gear.module;
let shifted: Vec<SectionCurve> = section
.curves
.iter()
.map(|piece| SectionCurve { curve: translated(&piece.curve, -reach), role: piece.role, tooth: piece.tooth })
.collect();
let mut tool = extrude_section(&GearSection { curves: shifted.clone(), data: section.data.clone() }, gear.face_width + 2.0 * reach)?;
for (face, piece) in tool.shells[0].faces.iter_mut().zip(&shifted) {
face.name = Some(piece.suffix());
}
let ring = crate::boolean_operation_nary(&[blank, tool], crate::BooleanOperation::Subtract)?;
Ok((ring, section.data))
}
pub fn ring_solid_helical(gear: &RingGear, helix_angle: f64, hand: Hand, herringbone: bool) -> Result<(BrepSolid, GearData), KernelRefusal> {
let beta = helix_angle;
if !(beta.to_degrees() >= 0.5 - 1e-9 && beta.to_degrees() <= 45.0 + 1e-9) {
return Err(refuse("bad_helix", format!("The helix angle must be between 0.5° and 45° (it is {:.4}°).", beta.to_degrees())));
}
let normal = gear.pressure_angle.to_degrees();
if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&normal) {
return Err(refuse("gear_input", format!("The normal pressure angle must be between 10° and 35° (it is {normal}°).")));
}
let c = beta.cos();
let transverse = RingGear {
module: gear.module / c,
pressure_angle: (gear.pressure_angle.tan() / c).atan(),
profile_shift: gear.profile_shift * c,
addendum: gear.addendum * c,
dedendum: gear.dedendum * c,
root_fillet: gear.root_fillet * c,
..gear.clone()
};
let section = ring_section_checked(&transverse, 60.0)?;
let r = transverse.module * transverse.teeth as f64 / 2.0;
let sign = if hand == Hand::Right { 1.0 } else { -1.0 };
let rate = sign * beta.tan() / r; let outer = section.data.root_diameter / 2.0 + gear.rim;
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)
.map_err(|error| refuse("gear_blank", error))?;
for (face, name) in blank.shells[0].faces.iter_mut().zip(["OD", "F", "B"]) {
face.name = Some(name.into());
}
let reach = gear.face_width * 0.1 + transverse.module;
let height = gear.face_width + 2.0 * reach;
let start: Vec<SectionCurve> = section
.curves
.iter()
.map(|piece| SectionCurve { curve: rotated(&piece.curve, -rate * reach), role: piece.role, tooth: piece.tooth })
.collect();
let twist = if herringbone { Twist::Herringbone { turn: rate * height } } else { Twist::Helical { turn: rate * height } };
let tool = twisted_prism(&GearSection { curves: start.clone(), data: section.data.clone() }, height, twist, GEAR_FIT_TOLERANCE * transverse.module)?;
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])
.map_err(|e| refuse("gear_transform", e))?;
let mut tool = crate::transform_brep(&tool, shift, false).map_err(|e| refuse("gear_transform", e))?;
for (face, piece) in tool.shells[0].faces.iter_mut().zip(&start) {
face.name = Some(piece.suffix());
}
let ring = crate::boolean_operation_nary(&[blank, tool], crate::BooleanOperation::Subtract)?;
Ok((ring, section.data))
}
fn translated(curve: &NurbsCurve, dz: f64) -> NurbsCurve {
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();
NurbsCurve::new(curve.degree, curve.knots.clone(), points).expect("a translated curve is a valid curve")
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SprocketForm {
Minimum,
Maximum,
Mean,
}
#[derive(Clone, Debug)]
pub struct Sprocket {
pub pitch: f64,
pub roller_diameter: f64,
pub teeth: usize,
pub form: SprocketForm,
pub width: f64,
}
pub fn sprocket_section(sprocket: &Sprocket) -> Result<GearSection, KernelRefusal> {
let p = sprocket.pitch;
let d1 = sprocket.roller_diameter;
if !(p > 0.0 && d1 > 0.0 && d1 < p && sprocket.width > 0.0) {
return Err(refuse(
"gear_input",
format!("The chain pitch ({p}), the roller diameter ({d1}, less than the pitch) and the width must be positive."),
));
}
if sprocket.teeth < 6 || sprocket.teeth > 300 {
return Err(refuse("gear_input", format!("A sprocket needs from 6 to 300 teeth (it has {}).", sprocket.teeth)));
}
let z = sprocket.teeth as f64;
let tau = TAU / z;
let d = p / (PI / z).sin();
let ri_min = 0.505 * d1;
let ri_max = 0.505 * d1 + 0.069 * d1.cbrt();
let re_min = 0.008 * d1 * (z * z + 180.0);
let re_max = 0.12 * d1 * (z + 2.0);
let a_min = (120.0 - 90.0 / z).to_radians();
let a_max = (140.0 - 90.0 / z).to_radians();
let da_min = d + p * (1.0 - 1.6 / z) - d1;
let da_max = d + 1.25 * p - d1;
let (ri, re, alpha, da) = match sprocket.form {
SprocketForm::Minimum => (ri_min, re_max, a_max, da_min),
SprocketForm::Maximum => (ri_max, re_min, a_min, da_max),
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)),
};
let ra = da / 2.0;
let c = [d / 2.0, 0.0];
let u = [-(alpha / 2.0).cos(), (alpha / 2.0).sin()]; let t_up = [c[0] + ri * u[0], c[1] + ri * u[1]];
let f = [c[0] + (ri + re) * u[0], c[1] + (ri + re) * u[1]]; let half = tau / 2.0;
let a_t = (t_up[1] - f[1]).atan2(t_up[0] - f[0]);
let on_flank = |angle: f64| [f[0] + re * angle.cos(), f[1] + re * angle.sin()];
let step = 1e-4;
let sense = if radius_of(on_flank(a_t + step)) > radius_of(on_flank(a_t - step)) { 1.0 } else { -1.0 };
let reach = |angle: f64| {
let q = on_flank(angle);
(radius_of(q) >= ra, polar_angle(q) >= half)
};
let (mut lo, mut hi) = (0.0, PI / 2.0);
if !(reach(a_t + sense * hi).0 || reach(a_t + sense * hi).1) {
return Err(refuse("gear_input", "The sprocket flank does not reach the tip circle.".into()));
}
for _ in 0..200 {
let mid = 0.5 * (lo + hi);
let (tip, centre) = reach(a_t + sense * mid);
if tip || centre { hi = mid } else { lo = mid }
}
let a_end = a_t + sense * hi;
let end = on_flank(a_end);
let pointed = polar_angle(end) >= half - 1e-12 || radius_of(end) < ra - 1e-9 * p;
let (a_end, end) = if pointed {
let (mut lo, mut hi) = (0.0, hi);
for _ in 0..200 {
let mid = 0.5 * (lo + hi);
if polar_angle(on_flank(a_t + sense * mid)) >= half { hi = mid } else { lo = mid }
}
let a = a_t + sense * hi;
(a, on_flank(a))
} else {
(a_end, end)
};
let flank_arc = |from: f64, to: f64| -> Result<NurbsCurve, KernelRefusal> {
if to > from { centred_arc(f, re, from, to) } else { centred_arc(f, re, to, from)?.reversed().map_err(|e| refuse("gear_arc", e)) }
};
let upper = flank_arc(a_t, a_end)?; let seat = centred_arc(c, ri, PI - alpha / 2.0, PI + alpha / 2.0)?.reversed().map_err(|e| refuse("gear_arc", e))?; let lower = mirrored(&upper).reversed().map_err(|e| refuse("gear_arc", e))?; let mut gap: Vec<(&'static str, NurbsCurve)> = vec![("A", lower), ("S", seat), ("C", upper)];
let tip_angle = polar_angle(end);
if !pointed {
gap.push(("K", arc(ra, tip_angle, tau - tip_angle)?));
}
let mut curves = Vec::with_capacity(gap.len() * sprocket.teeth);
for index in 0..sprocket.teeth {
let angle = tau * index as f64 + half;
for (role, curve) in &gap {
curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
}
}
snap_junctions(&mut curves);
let data = GearData {
pitch_diameter: d,
tip_diameter: if pointed { 2.0 * radius_of(end) } else { da },
root_diameter: d - 2.0 * ri,
..GearData::default()
};
Ok(GearSection { curves, data })
}
pub fn sprocket_solid(sprocket: &Sprocket) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
let section = sprocket_section(sprocket)?;
let solid = extrude_section(§ion, sprocket.width)?;
let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
names.push("F".into());
names.push("B".into());
Ok((solid, names, section.data))
}
#[derive(Clone, Copy, Debug)]
pub enum Twist {
Helical { turn: f64 },
Herringbone { turn: f64 },
}
impl Twist {
fn angle(&self, t: f64) -> f64 {
match *self {
Twist::Helical { turn } => turn * t,
Twist::Herringbone { turn } => turn * (0.5 - (t - 0.5).abs()),
}
}
fn rate(&self, t: f64, after_crease: bool) -> f64 {
match *self {
Twist::Helical { turn } => turn,
Twist::Herringbone { turn } => {
if t < 0.5 || (t == 0.5 && !after_crease) { turn } else { -turn }
}
}
}
fn total_turn(&self) -> f64 {
match *self {
Twist::Helical { turn } => turn.abs(),
Twist::Herringbone { turn } => turn.abs(),
}
}
}
fn twist_basis(twist: Twist, reach: f64, tolerance: f64) -> Result<(Vec<f64>, Vec<[f64; 3]>), KernelRefusal> {
let crease = matches!(twist, Twist::Herringbone { .. });
let per = (384.0 * tolerance / reach.max(1e-12)).powf(0.25);
let needed = twist.total_turn() / per;
if !(needed <= 4096.0) {
return Err(refuse(
"twist_too_long",
format!(
"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).",
twist.total_turn() / TAU,
4096.0 * per / TAU
),
));
}
let mut spans = (needed.ceil() as usize).max(1);
if crease && spans % 2 == 1 {
spans += 1;
}
let value = |t: f64| {
let a = twist.angle(t);
[a.cos(), a.sin(), t]
};
let slope = |t: f64, after: bool| {
let a = twist.angle(t);
let r = twist.rate(t, after);
[-a.sin() * r, a.cos() * r, 1.0]
};
let mut knots = vec![0.0; 4];
let mut points = vec![value(0.0)];
for index in 0..spans {
let (t0, t1) = (index as f64 / spans as f64, (index + 1) as f64 / spans as f64);
let h = (t1 - t0) / 3.0;
let (p0, p1) = (value(t0), value(t1));
let (d0, d1) = (slope(t0, true), slope(t1, false));
points.push([p0[0] + d0[0] * h, p0[1] + d0[1] * h, p0[2] + d0[2] * h]);
points.push([p1[0] - d1[0] * h, p1[1] - d1[1] * h, p1[2] - d1[2] * h]);
let last = index + 1 == spans;
let at_crease = crease && 2 * (index + 1) == spans;
if last {
points.push(p1);
} else if at_crease {
points.push(p1);
knots.extend([t1, t1, t1]);
} else {
knots.extend([t1, t1]);
}
}
knots.extend([1.0; 4]);
Ok((knots, points))
}
fn twisted_surface(curve: &NurbsCurve, width: f64, knots_v: &[f64], basis: &[[f64; 3]]) -> Result<NurbsSurface, KernelRefusal> {
let rows = curve
.control_points
.iter()
.map(|p| {
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()
})
.collect();
NurbsSurface::new(curve.degree, 3, curve.knots.clone(), knots_v.to_vec(), rows).map_err(|e| refuse("gear_surface", e))
}
fn twisted_edge(point: Vec4, width: f64, knots_v: &[f64], basis: &[[f64; 3]]) -> Result<NurbsCurve, KernelRefusal> {
let (x, y) = (point.x / point.w, point.y / point.w);
let points = basis
.iter()
.map(|[c, s, t]| Vec4 { x: c * x - s * y, y: s * x + c * y, z: t * width, w: 1.0 })
.collect();
NurbsCurve::new(3, knots_v.to_vec(), points).map_err(|e| refuse("gear_edge", e))
}
pub fn twisted_prism(section: &GearSection, width: f64, twist: Twist, tolerance: f64) -> Result<BrepSolid, KernelRefusal> {
use crate::sweep_topology::{curve_to_plane_parameters, make_plane, parameter_line, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, ShellRecord, VertexRecord};
if !(width > 0.0) {
return Err(refuse("gear_input", format!("The face width must be greater than zero (it is {width}).")));
}
let curves: Vec<NurbsCurve> = section.curves.iter().map(|piece| piece.curve.clone()).collect();
let count = curves.len();
let reach = curves
.iter()
.flat_map(|c| c.control_points.iter())
.map(|p| (p.x / p.w).hypot(p.y / p.w))
.fold(0.0, f64::max);
let (knots_v, basis) = twist_basis(twist, reach, tolerance)?;
let end_angle = twist.angle(1.0);
let lift = |curve: &NurbsCurve| -> NurbsCurve {
let mut top = rotated(curve, end_angle);
for point in &mut top.control_points {
point.z += point.w * width;
}
top
};
let starts: Vec<Vec4> = curves.iter().map(|c| c.control_points[0]).collect();
let point_of = |p: Vec4| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w);
let mut vertices = Vec::with_capacity(2 * count);
for (index, start) in starts.iter().enumerate() {
vertices.push(VertexRecord { id: index as u64 + 1, point: point_of(*start) });
}
let (se, ce) = end_angle.sin_cos();
for (index, start) in starts.iter().enumerate() {
let p = point_of(*start);
vertices.push(VertexRecord {
id: (count + index) as u64 + 1,
point: Vec3::new(ce * p.x - se * p.y, se * p.x + ce * p.y, width),
});
}
let edge_id = |kind: usize, index: usize| 10 + (kind * count + index) as u64;
let mut edges = Vec::with_capacity(3 * count);
for (index, curve) in curves.iter().enumerate() {
let [start, end] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
let next = (index + 1) % count;
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 });
edges.push(EdgeRecord { id: edge_id(1, index), curve: lift(curve), t0: start, t1: end, start_vertex_id: (count + index) as u64 + 1, end_vertex_id: (count + next) as u64 + 1, degenerate: false, name: None });
edges.push(EdgeRecord { id: edge_id(2, index), curve: twisted_edge(starts[index], width, &knots_v, &basis)?, 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 });
}
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));
let mut next_id = 10 + 3 * count as u64 + 1000;
let mut faces = Vec::with_capacity(count + 2);
for (index, curve) in curves.iter().enumerate() {
let [start, end] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
let next = (index + 1) % count;
let coedges = vec![
CoedgeRecord { id: next_id, edge_id: edge_id(0, index), forward: true, pcurve: line([start, 0.0], [end, 0.0])? },
CoedgeRecord { id: next_id + 1, edge_id: edge_id(2, next), forward: true, pcurve: line([end, 0.0], [end, 1.0])? },
CoedgeRecord { id: next_id + 2, edge_id: edge_id(1, index), forward: false, pcurve: line([end, 1.0], [start, 1.0])? },
CoedgeRecord { id: next_id + 3, edge_id: edge_id(2, index), forward: false, pcurve: line([start, 1.0], [start, 0.0])? },
];
next_id += 4;
faces.push(FaceRecord {
id: next_id + 1,
surface: twisted_surface(curve, width, &knots_v, &basis)?,
same_sense: true,
loops: vec![LoopRecord { id: next_id, coedges }],
name: None,
});
next_id += 2;
}
let pad = reach * 1.1 + 1.0;
let x_axis = Vec3::new(1.0, 0.0, 0.0);
let y_axis = Vec3::new(0.0, 1.0, 0.0);
let bottom_origin = Vec3::new(-pad, -pad, 0.0);
let mut bottom = Vec::with_capacity(count);
for index in (0..count).rev() {
bottom.push(CoedgeRecord {
id: next_id,
edge_id: edge_id(0, index),
forward: false,
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))?,
});
next_id += 1;
}
faces.push(FaceRecord {
id: next_id + 1,
surface: make_plane(bottom_origin, x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e))?,
same_sense: false,
loops: vec![LoopRecord { id: next_id, coedges: bottom }],
name: None,
});
next_id += 2;
let top_origin = Vec3::new(-pad, -pad, width);
let mut top = Vec::with_capacity(count);
for (index, curve) in curves.iter().enumerate() {
top.push(CoedgeRecord {
id: next_id,
edge_id: edge_id(1, index),
forward: true,
pcurve: curve_to_plane_parameters(&lift(curve), top_origin, x_axis, y_axis).map_err(|e| refuse("gear_pcurve", e))?,
});
next_id += 1;
}
faces.push(FaceRecord {
id: next_id + 1,
surface: make_plane(top_origin, x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e))?,
same_sense: true,
loops: vec![LoopRecord { id: next_id, coedges: top }],
name: None,
});
next_id += 2;
let solid = BrepSolid {
mass_properties_cache: Default::default(),
cells: Default::default(),
id: next_id + 1,
vertices,
edges,
shells: vec![ShellRecord { id: next_id, faces }],
genus: 0,
kind: crate::BodyKind::Solid,
};
let issues = solid.validate();
if issues.is_empty() {
Ok(solid)
} else {
Err(KernelRefusal::internal(KernelStage::Validate, "validate", format!("twisted gear prism is not valid: {issues:?}")))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Hand {
Right,
Left,
}
#[derive(Clone, Debug)]
pub struct HelicalGear {
pub spur: SpurGear,
pub helix_angle: f64,
pub hand: Hand,
pub herringbone: bool,
}
pub fn helical_transverse(gear: &HelicalGear) -> Result<SpurGear, KernelRefusal> {
let beta = gear.helix_angle;
let normal = gear.spur.pressure_angle.to_degrees();
if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&normal) {
return Err(refuse("gear_input", format!("The normal pressure angle must be between 10° and 35° (it is {normal}°).")));
}
if !(beta.to_degrees() >= 0.5 - 1e-9 && beta.to_degrees() <= 45.0 + 1e-9) {
return Err(refuse("bad_helix", format!("The helix angle must be between 0.5° and 45° (it is {:.4}°).", beta.to_degrees())));
}
let n = &gear.spur;
let c = beta.cos();
Ok(SpurGear {
module: n.module / c,
teeth: n.teeth,
pressure_angle: (n.pressure_angle.tan() / c).atan(),
profile_shift: n.profile_shift * c,
addendum: n.addendum * c,
dedendum: n.dedendum * c,
root_fillet: n.root_fillet * c,
backlash: n.backlash,
face_width: n.face_width,
})
}
pub fn helical_solid(gear: &HelicalGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
let transverse = helical_transverse(gear)?;
let section = transverse_section(&transverse)?;
let r = transverse.module * transverse.teeth as f64 / 2.0;
let width = transverse.face_width;
let sign = if gear.hand == Hand::Right { 1.0 } else { -1.0 };
let twist = if gear.herringbone {
Twist::Herringbone { turn: sign * width * gear.helix_angle.tan() / r }
} else {
Twist::Helical { turn: sign * width * gear.helix_angle.tan() / r }
};
let solid = twisted_prism(§ion, width, twist, 0.1 * GEAR_FIT_TOLERANCE * transverse.module)?;
let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
names.push("F".into());
names.push("B".into());
Ok((solid, names, section.data))
}
#[derive(Clone, Debug)]
pub struct StraightSpline {
pub teeth: usize,
pub minor: f64,
pub major: f64,
pub key_width: f64,
pub length: f64,
}
fn check_straight_spline(spline: &StraightSpline) -> Result<(), KernelRefusal> {
let StraightSpline { teeth, minor, major, key_width, length } = *spline;
if !(minor > 0.0 && major > minor && key_width > 0.0 && length > 0.0) {
return Err(refuse(
"gear_input",
format!("A spline needs 0 < minor diameter ({minor}) < major diameter ({major}), a positive key width ({key_width}) and length ({length})."),
));
}
if teeth < 2 || teeth > 100 {
return Err(refuse("gear_input", format!("A spline needs from 2 to 100 keys (it has {teeth}).")));
}
let half_root = (key_width / minor).asin();
if !(key_width < minor) || 2.0 * half_root >= TAU / teeth as f64 - 1e-9 {
return Err(refuse("keys_overlap", format!("{teeth} keys {key_width} wide do not fit round a {minor} minor diameter.")));
}
Ok(())
}
pub fn straight_spline_section(spline: &StraightSpline) -> Result<GearSection, KernelRefusal> {
check_straight_spline(spline)?;
let (rr, ra, h) = (spline.minor / 2.0, spline.major / 2.0, spline.key_width / 2.0);
let n = spline.teeth as f64;
let foot = [(rr * rr - h * h).sqrt(), h];
let top = [(ra * ra - h * h).sqrt(), h];
let top_angle = (h / ra).asin();
let foot_angle = (h / rr).asin();
let key: Vec<(&'static str, NurbsCurve)> = vec![
("R", line([foot[0], -h], [top[0], -h])?),
("K", arc(ra, -top_angle, top_angle)?),
("L", line(top, foot)?),
("G", arc(rr, foot_angle, TAU / n - foot_angle)?),
];
let mut curves = Vec::with_capacity(4 * spline.teeth);
for index in 0..spline.teeth {
let angle = TAU * index as f64 / n;
for (role, curve) in &key {
curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
}
}
snap_junctions(&mut curves);
Ok(GearSection { curves, data: GearData { tip_diameter: spline.major, root_diameter: spline.minor, ..GearData::default() } })
}
pub fn straight_spline_shaft(spline: &StraightSpline) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
let section = straight_spline_section(spline)?;
let solid = extrude_section(§ion, spline.length)?;
let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
names.push("F".into());
names.push("B".into());
Ok((solid, names, section.data))
}
pub fn hub_from_section(section: &GearSection, outside: f64, length: f64) -> Result<BrepSolid, KernelRefusal> {
let mut reach: f64 = 0.0;
for piece in §ion.curves {
let [t0, t1] = piece.curve.domain().map_err(|e| refuse("gear_domain", e))?;
for i in 0..=32 {
let p = piece.curve.evaluate(t0 + (t1 - t0) * i as f64 / 32.0).map_err(|e| refuse("gear_eval", e))?;
reach = reach.max(p.x.hypot(p.y));
}
}
if !(outside / 2.0 > reach + 1e-9) {
return Err(refuse(
"hub_too_small",
format!("The hub's outside diameter ({outside}) must be larger than its spline's major diameter ({:.4}).", 2.0 * reach),
));
}
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)
.map_err(|error| refuse("gear_blank", error))?;
for (face, name) in blank.shells[0].faces.iter_mut().zip(["OD", "F", "B"]) {
face.name = Some(name.into());
}
let extra = 0.1 * length + 0.1 * reach;
let shifted: Vec<SectionCurve> = section
.curves
.iter()
.map(|piece| SectionCurve { curve: translated(&piece.curve, -extra), role: piece.role, tooth: piece.tooth })
.collect();
let mut tool = extrude_section(&GearSection { curves: shifted.clone(), data: section.data.clone() }, length + 2.0 * extra)?;
for (face, piece) in tool.shells[0].faces.iter_mut().zip(&shifted) {
face.name = Some(piece.suffix());
}
crate::boolean_operation_nary(&[blank, tool], crate::BooleanOperation::Subtract)
}
pub fn straight_spline_hub(spline: &StraightSpline, outside: f64) -> Result<(BrepSolid, GearData), KernelRefusal> {
let section = straight_spline_section(spline)?;
let hub = hub_from_section(§ion, outside, spline.length)?;
Ok((hub, section.data))
}
#[derive(Clone, Debug)]
pub struct TimingPulley {
pub pitch: f64,
pub teeth: usize,
pub pld: f64,
pub bottom_width: f64,
pub depth: f64,
pub side_angle: f64,
pub bottom_radius: f64,
pub top_radius: f64,
pub width: f64,
}
fn arc_through(centre: [f64; 2], from: [f64; 2], to: [f64; 2], ccw: bool) -> Result<NurbsCurve, KernelRefusal> {
let radius = (from[0] - centre[0]).hypot(from[1] - centre[1]);
let a0 = (from[1] - centre[1]).atan2(from[0] - centre[0]);
let a1 = (to[1] - centre[1]).atan2(to[0] - centre[0]);
if ccw {
let mut end = a1;
while end <= a0 {
end += TAU;
}
centred_arc(centre, radius, a0, end)
} else {
let mut start = a1;
while start <= a0 - TAU {
start += TAU;
}
while start >= a0 {
start -= TAU;
}
centred_arc(centre, radius, start, a0)?.reversed().map_err(|e| refuse("gear_arc", e))
}
}
pub fn timing_pulley_section(pulley: &TimingPulley) -> Result<GearSection, KernelRefusal> {
let TimingPulley { pitch, teeth, pld, bottom_width, depth, side_angle, bottom_radius, top_radius, width } = pulley.clone();
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) {
return Err(refuse("gear_input", "The pulley's pitch, groove sizes and width must be positive.".into()));
}
if !(0.0..60f64.to_radians()).contains(&side_angle) {
return Err(refuse("gear_input", "The groove side angle must be between 0° and 60°.".into()));
}
if teeth < 6 || teeth > 400 {
return Err(refuse("gear_input", format!("A pulley needs from 6 to 400 teeth (it has {teeth}).")));
}
let z = teeth as f64;
let ro = pitch * z / PI / 2.0 - pld / 2.0;
let x_bottom = ro - depth;
if !(x_bottom > 0.0) {
return Err(refuse("gear_input", "The groove is deeper than the pulley's radius.".into()));
}
let tau = TAU / z;
let (s, c) = side_angle.sin_cos();
let side = [c, s]; let normal = [-s, c]; let corner = [x_bottom, bottom_width / 2.0];
let b = corner[0] * side[0] + corner[1] * side[1];
let t_top = -b + (b * b - (corner[0] * corner[0] + corner[1] * corner[1] - ro * ro)).sqrt();
let top = [corner[0] + t_top * side[0], corner[1] + t_top * side[1]];
let turn = PI / 2.0 - side_angle;
let reach_b = bottom_radius * (turn / 2.0).tan();
let t1 = [corner[0], corner[1] - reach_b];
let t2 = [corner[0] + reach_b * side[0], corner[1] + reach_b * side[1]];
let centre_b = [t1[0] + bottom_radius, t1[1]];
let rt = top_radius;
let base = [corner[0] + rt * normal[0], corner[1] + rt * normal[1]];
let bb = base[0] * side[0] + base[1] * side[1];
let disc = bb * bb - (base[0] * base[0] + base[1] * base[1] - (ro - rt) * (ro - rt));
if disc < 0.0 {
return Err(refuse("gear_input", "The groove's top radius does not fit.".into()));
}
let t_c = -bb + disc.sqrt();
let centre_t = [base[0] + t_c * side[0], base[1] + t_c * side[1]];
let t3 = [corner[0] + t_c * side[0], corner[1] + t_c * side[1]];
let scale = ro / (centre_t[0].hypot(centre_t[1]));
let t4 = [centre_t[0] * scale, centre_t[1] * scale];
let land_start = polar_angle(t4);
if land_start >= tau / 2.0 - 1e-9 || reach_b > t_c + 1e-12 || t1[1] < 0.0 {
return Err(refuse(
"groove_too_wide",
format!("The grooves and their corner radii do not fit the pitch at {teeth} teeth; add teeth or reduce the radii."),
));
}
let _ = top;
let mut upper: Vec<(&'static str, NurbsCurve)> = Vec::new();
if bottom_radius > 0.0 {
upper.push(("D", arc_through(centre_b, t1, t2, false)?));
}
upper.push(("C", line(t2, t3)?));
if rt > 0.0 {
upper.push(("P", arc_through(centre_t, t3, t4, true)?));
}
let mut groove: Vec<(&'static str, NurbsCurve)> = Vec::new();
let lower_roles = |role: &'static str| match role {
"D" => "U",
"C" => "A",
_ => "Q",
};
for (role, curve) in upper.iter().rev() {
groove.push((lower_roles(role), mirrored(curve).reversed().map_err(|e| refuse("gear_arc", e))?));
}
groove.push(("S", line([t1[0], -t1[1]], t1)?));
groove.extend(upper.into_iter());
groove.push(("K", arc(ro, land_start, tau - land_start)?));
let mut curves = Vec::with_capacity(groove.len() * teeth);
for index in 0..teeth {
let angle = tau * index as f64 + tau / 2.0;
for (role, curve) in &groove {
curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
}
}
snap_junctions(&mut curves);
let data = GearData { pitch_diameter: pitch * z / PI, tip_diameter: 2.0 * ro, root_diameter: 2.0 * x_bottom, ..GearData::default() };
Ok(GearSection { curves, data })
}
pub fn timing_pulley_solid(pulley: &TimingPulley) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
let section = timing_pulley_section(pulley)?;
let solid = extrude_section(§ion, pulley.width)?;
let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
names.push("F".into());
names.push("B".into());
Ok((solid, names, section.data))
}
#[derive(Clone, Debug)]
pub struct Ratchet {
pub teeth: usize,
pub outside: f64,
pub depth: f64,
pub lean: f64,
pub symmetric: bool,
pub clockwise_locks: bool,
pub width: f64,
}
pub fn ratchet_section(ratchet: &Ratchet) -> Result<GearSection, KernelRefusal> {
let Ratchet { teeth, outside, depth, lean, symmetric, clockwise_locks, width } = ratchet.clone();
if !(outside > 0.0 && depth > 0.0 && depth < outside / 2.0 && width > 0.0) {
return Err(refuse("gear_input", format!("A ratchet needs a positive outside diameter ({outside}), a depth ({depth}) under its radius and a positive width.")));
}
if teeth < 3 || teeth > 360 {
return Err(refuse("gear_input", format!("A ratchet needs from 3 to 360 teeth (it has {teeth}).")));
}
if !(lean >= 0.0 && lean.to_degrees() <= 30.0) {
return Err(refuse("gear_input", "The locking face lean must be between 0° and 30°.".into()));
}
let z = teeth as f64;
let tau = TAU / z;
let ra = outside / 2.0;
let rf = ra - depth;
let tip = [ra, 0.0];
let face_angle = PI + lean; let d = [face_angle.cos(), face_angle.sin()];
let b = tip[0] * d[0] + tip[1] * d[1];
let t = -b - (b * b - (ra * ra - rf * rf)).sqrt();
let root = [tip[0] + t * d[0], tip[1] + t * d[1]];
let foot = polar_angle(root);
let (lock, back) = if symmetric {
let mid = [rf * (tau / 2.0).cos(), rf * (tau / 2.0).sin()];
let lock = line(tip, mid)?;
let next = [ra * tau.cos(), ra * tau.sin()];
(lock, line(mid, next)?)
} else {
if foot >= tau - 1e-9 {
return Err(refuse("gear_input", "The locking faces overlap: fewer teeth, less depth or less lean.".into()));
}
let next = [ra * tau.cos(), ra * tau.sin()];
(line(tip, root)?, line(root, next)?)
};
let mut curves = Vec::with_capacity(2 * teeth);
for index in 0..teeth {
let angle = tau * index as f64;
curves.push(SectionCurve { curve: rotated(&lock, angle), role: "LK", tooth: index });
curves.push(SectionCurve { curve: rotated(&back, angle), role: "BK", tooth: index });
}
if clockwise_locks {
let mut mirrored_curves: Vec<SectionCurve> = curves
.iter()
.map(|piece| SectionCurve { curve: mirrored(&piece.curve).reversed().expect("a line reverses"), role: piece.role, tooth: piece.tooth })
.collect();
mirrored_curves.reverse();
curves = mirrored_curves;
}
snap_junctions(&mut curves);
Ok(GearSection { curves, data: GearData { tip_diameter: outside, root_diameter: 2.0 * rf, ..GearData::default() } })
}
pub fn ratchet_solid(ratchet: &Ratchet) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
let section = ratchet_section(ratchet)?;
let solid = extrude_section(§ion, ratchet.width)?;
let mut names: Vec<String> = section.curves.iter().map(|c| c.suffix()).collect();
names.push("F".into());
names.push("B".into());
Ok((solid, names, section.data))
}
#[derive(Clone, Debug)]
pub struct GenevaWheel {
pub slots: usize,
pub centre_distance: f64,
pub pin_diameter: f64,
pub clearance: f64,
pub lock_radius: f64,
pub width: f64,
}
pub fn geneva_sizes(wheel: &GenevaWheel) -> (f64, f64, f64, f64) {
let n = wheel.slots as f64;
let a = wheel.centre_distance;
let crank = a * (PI / n).sin();
let radius = a * (PI / n).cos();
let lock = if wheel.lock_radius > 0.0 { wheel.lock_radius } else { crank - wheel.pin_diameter };
(crank, radius, a - crank, lock)
}
pub fn geneva_section(wheel: &GenevaWheel) -> Result<GearSection, KernelRefusal> {
let GenevaWheel { slots, centre_distance: a, pin_diameter: dp, clearance: c, width, .. } = wheel.clone();
if !(3..=12).contains(&slots) {
return Err(refuse("gear_input", format!("A Geneva wheel has from 3 to 12 slots (it has {slots}).")));
}
if !(a > 0.0 && dp > 0.0 && c >= 0.0 && width > 0.0) {
return Err(refuse("gear_input", "The centre distance, pin diameter and width must be positive (the clearance not negative).".into()));
}
let n = slots as f64;
let (crank, rw, end_centre, lock) = geneva_sizes(wheel);
let half = (dp + c) / 2.0; let rl = lock + c / 2.0;
if !(lock > 0.0 && lock < a - rw + 1e-9 + rw) || !(half < end_centre) || !(half < rw * (PI / n).sin()) {
return Err(refuse("gear_input", format!("The pin ({dp}) is too large for {slots} slots at centre distance {a}.")));
}
if end_centre * (PI / n).sin() <= half * (1.0 + 1e-9) {
return Err(refuse(
"gear_input",
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),
));
}
let x_top = (rw * rw - half * half).sqrt();
let p1 = [x_top, half];
let beta = PI / n;
let centre = [a * beta.cos(), a * beta.sin()];
let along = (rw * rw - rl * rl + a * a) / (2.0 * a);
let h2 = rw * rw - along * along;
if h2 <= 0.0 {
return Err(refuse("gear_input", "The locking arc does not reach the wheel's rim: increase the locking disc radius.".into()));
}
let h = h2.sqrt();
let e = [beta.cos(), beta.sin()];
let perp = [-beta.sin(), beta.cos()];
let q1 = [along * e[0] - h * perp[0], along * e[1] - h * perp[1]];
let q2 = [along * e[0] + h * perp[0], along * e[1] + h * perp[1]];
let a1 = polar_angle(p1);
if polar_angle(q1) <= a1 + 1e-9 {
return Err(refuse("gear_input", "The locking arc cuts into the slots: reduce the locking disc radius or the pin.".into()));
}
let tau = TAU / n;
let slot: Vec<(&'static str, NurbsCurve)> = vec![
("SL", line([x_top, -half], [end_centre, -half])?),
("SE", arc_through([end_centre, 0.0], [end_centre, -half], [end_centre, half], false)?),
("SU", line([end_centre, half], p1)?),
("RA", arc(rw, a1, polar_angle(q1))?),
("LA", arc_through(centre, q1, q2, false)?),
("RB", arc(rw, polar_angle(q2), tau - a1)?),
];
let mut curves = Vec::with_capacity(6 * slots);
for index in 0..slots {
let angle = tau * index as f64;
for (role, curve) in &slot {
curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
}
}
snap_junctions(&mut curves);
let _ = crank;
Ok(GearSection { curves, data: GearData { tip_diameter: 2.0 * rw, ..GearData::default() } })
}
pub fn geneva_solid(wheel: &GenevaWheel) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
let section = geneva_section(wheel)?;
let solid = extrude_section(§ion, wheel.width)?;
let mut names: Vec<String> = section.curves.iter().map(|c| c.suffix()).collect();
names.push("F".into());
names.push("B".into());
Ok((solid, names, section.data))
}
#[derive(Clone, Debug)]
pub struct Worm {
pub axial_module: f64,
pub starts: usize,
pub reference_diameter: f64,
pub pressure_angle: f64,
pub addendum: f64,
pub dedendum: f64,
pub length: f64,
pub hand: Hand,
}
impl Worm {
pub fn lead(&self) -> f64 {
self.starts as f64 * PI * self.axial_module
}
pub fn axial_thickness(&self, radius: f64) -> f64 {
PI * self.axial_module / 2.0 - 2.0 * (radius - self.reference_diameter / 2.0) * self.pressure_angle.tan()
}
}
pub fn worm_section(worm: &Worm) -> Result<GearSection, KernelRefusal> {
let m = worm.axial_module;
if !(m > 0.0 && worm.reference_diameter > 0.0 && worm.length > 0.0 && worm.addendum > 0.0 && worm.dedendum > 0.0) {
return Err(refuse("gear_input", "The worm's module, diameter, length, addendum and dedendum must be positive.".into()));
}
if worm.starts < 1 || worm.starts > 8 {
return Err(refuse("gear_input", format!("A worm has from 1 to 8 starts (it has {}).", worm.starts)));
}
let degrees = worm.pressure_angle.to_degrees();
if !(10.0 - 1e-9..=35.0 + 1e-9).contains(°rees) {
return Err(refuse("gear_input", format!("The axial pressure angle must be between 10° and 35° (it is {degrees}°).")));
}
let r1 = worm.reference_diameter / 2.0;
let ra = r1 + worm.addendum * m;
let rf = r1 - worm.dedendum * m;
if !(rf > 0.0) {
return Err(refuse("gear_input", format!("The worm's root diameter is not positive ({:.4}): raise the diameter quotient.", 2.0 * rf)));
}
let lead = worm.lead();
let gamma = (lead / (PI * worm.reference_diameter)).atan();
if gamma.to_degrees() > 45.0 {
return Err(refuse("bad_lead", format!("The lead angle {:.3}° is over 45°: fewer starts or a larger diameter.", gamma.to_degrees())));
}
if worm.axial_thickness(ra) <= 1e-6 * m {
return Err(refuse("pointed_tip", "The worm thread comes to a point below its tip: lower the addendum or the pressure angle.".into()));
}
let n = worm.starts as f64;
let pitch = PI * m;
if worm.axial_thickness(rf) >= pitch - 1e-6 * m {
return Err(refuse("teeth_overlap", "The worm's threads meet at the root: lower the dedendum or the pressure angle.".into()));
}
let half = |r: f64| PI * worm.axial_thickness(r) / lead;
let flank = |r: f64| {
let t = half(r);
[r * t.cos(), r * t.sin()]
};
let tolerance = GEAR_FIT_TOLERANCE * m;
let upper = fit_planar(&|r| flank(r), rf, ra, tolerance)?; let tau = TAU / n;
let thread: Vec<(&'static str, NurbsCurve)> = vec![
("R", mirrored(&upper)),
("K", arc(ra, -half(ra), half(ra))?),
("L", upper.reversed().map_err(|e| refuse("gear_fit", e))?),
("G", arc(rf, half(rf), tau - half(rf))?),
];
let mut curves = Vec::with_capacity(4 * worm.starts);
for index in 0..worm.starts {
let angle = tau * index as f64;
for (role, curve) in &thread {
curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
}
}
snap_junctions(&mut curves);
let data = GearData { pitch_diameter: worm.reference_diameter, tip_diameter: 2.0 * ra, root_diameter: 2.0 * rf, ..GearData::default() };
Ok(GearSection { curves, data })
}
pub fn worm_solid(worm: &Worm) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
let section = worm_section(worm)?;
let sign = if worm.hand == Hand::Right { 1.0 } else { -1.0 };
let turn = sign * TAU * worm.length / worm.lead();
let solid = twisted_prism(§ion, worm.length, Twist::Helical { turn }, GEAR_FIT_TOLERANCE * worm.axial_module)?;
let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
names.push("F".into());
names.push("B".into());
Ok((solid, names, section.data))
}
#[derive(Clone, Debug)]
pub struct CycloidalDisc {
pub pins: usize,
pub pin_circle_diameter: f64,
pub pin_diameter: f64,
pub eccentricity: f64,
pub clearance: f64,
pub width: f64,
}
impl CycloidalDisc {
fn trochoid(&self, t: f64) -> ([f64; 2], [f64; 2]) {
let r = self.pin_circle_diameter / 2.0;
let e = self.eccentricity;
let n = self.pins as f64;
(
[r * t.cos() - e * (n * t).cos(), -r * t.sin() + e * (n * t).sin()],
[-r * t.sin() + e * n * (n * t).sin(), -r * t.cos() + e * n * (n * t).cos()],
)
}
pub fn profile(&self, t: f64) -> [f64; 2] {
let (q, d) = self.trochoid(t);
let length = d[0].hypot(d[1]);
let offset = self.pin_diameter / 2.0 + self.clearance / 2.0;
let n = [d[1] / length, -d[0] / length];
[q[0] + offset * n[0], q[1] + offset * n[1]]
}
}
pub fn cycloidal_disc_section(disc: &CycloidalDisc) -> Result<GearSection, KernelRefusal> {
let CycloidalDisc { pins, pin_circle_diameter: dc, pin_diameter: dp, eccentricity: e, clearance, width } = disc.clone();
if !(4..=200).contains(&pins) {
return Err(refuse("gear_input", format!("A cycloidal drive has from 4 to 200 pins (it has {pins}).")));
}
if !(dc > 0.0 && dp > 0.0 && e > 0.0 && clearance >= 0.0 && width > 0.0) {
return Err(refuse("gear_input", "The pin circle, pin diameter, eccentricity and width must be positive.".into()));
}
let n = pins as f64;
let r = dc / 2.0;
if e >= r / n * (1.0 - 1e-9) {
return Err(refuse(
"gear_input",
format!("The eccentricity must be under the pin circle radius / pins = {:.4} (it is {e}).", r / n),
));
}
let offset = dp / 2.0 + clearance / 2.0;
let (rr, ee) = (dc / 2.0, e);
let radius = |t: f64| -> f64 {
let d = [-rr * t.sin() + ee * n * (n * t).sin(), -rr * t.cos() + ee * n * (n * t).cos()];
let dd = [-rr * t.cos() + ee * n * n * (n * t).cos(), rr * t.sin() - ee * n * n * (n * t).sin()];
let cross = d[0] * dd[1] - d[1] * dd[0];
let speed = d[0].hypot(d[1]);
if cross < 0.0 { speed * speed * speed / -cross } else { f64::INFINITY }
};
let period = TAU / (n - 1.0);
let samples = 2000;
let values: Vec<f64> = (0..=samples).map(|i| radius(period * i as f64 / samples as f64)).collect();
let mut least = f64::INFINITY;
for i in 0..=samples {
let previous = values[if i == 0 { samples - 1 } else { i - 1 }];
let next = values[if i == samples { 1 } else { i + 1 }];
if values[i] <= previous && values[i] <= next && values[i].is_finite() {
let (mut lo, mut hi) = (period * (i as f64 - 1.0) / samples as f64, period * (i as f64 + 1.0) / samples as f64);
for _ in 0..100 {
let a = lo + (hi - lo) * 0.381966;
let b = hi - (hi - lo) * 0.381966;
if radius(a) < radius(b) { hi = b } else { lo = a }
}
least = least.min(radius(0.5 * (lo + hi)));
}
}
if offset >= least * (1.0 - 1e-6) {
return Err(refuse(
"undercut",
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})."),
));
}
let lobes = pins - 1;
let step = TAU / lobes as f64;
let tolerance = GEAR_FIT_TOLERANCE * dp.min(e * 4.0);
let mut curves = Vec::with_capacity(lobes);
for k in 0..lobes {
let (a, b) = (step * k as f64, step * (k + 1) as f64);
let piece = fit_planar(&|u| disc.profile(-u), a, b, tolerance)?;
curves.push(SectionCurve { curve: piece, role: "LB", tooth: k });
}
snap_junctions(&mut curves);
Ok(GearSection { curves, data: GearData { pitch_diameter: dc, ..GearData::default() } })
}
pub fn cycloidal_disc_solid(disc: &CycloidalDisc) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
let section = cycloidal_disc_section(disc)?;
let solid = extrude_section(§ion, disc.width)?;
let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
names.push("F".into());
names.push("B".into());
Ok((solid, names, section.data))
}
pub fn cycloidal_pin_ring(pins: usize, pin_circle_diameter: f64, pin_diameter: f64, outside: f64, width: f64) -> Result<(BrepSolid, GearData), KernelRefusal> {
if !(4..=200).contains(&pins) || !(pin_diameter > 0.0 && pin_circle_diameter > pin_diameter && width > 0.0) {
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()));
}
let r = pin_circle_diameter / 2.0;
let rp = pin_diameter / 2.0;
let n = pins as f64;
let tau = TAU / n;
let delta = 2.0 * (rp / (2.0 * r)).asin();
if 2.0 * delta >= tau - 1e-9 || 2.0 * r * (PI / n).sin() <= pin_diameter * (1.0 + 1e-9) {
return Err(refuse("gear_input", format!("{pins} pins of diameter {pin_diameter} overlap on a {pin_circle_diameter} pin circle.")));
}
let centre = [r, 0.0];
let a = [r * (-delta).cos(), r * (-delta).sin()];
let b = [r * delta.cos(), r * delta.sin()];
let cw = arc_through(centre, a, b, false)?;
let pin_arc = {
let [t0, t1] = cw.domain().map_err(|e| refuse("gear_domain", e))?;
let mid = cw.evaluate(0.5 * (t0 + t1)).map_err(|e| refuse("gear_eval", e))?;
if mid.x < r { cw } else { arc_through(centre, a, b, true)? }
};
let space: Vec<(&'static str, NurbsCurve)> = vec![("P", pin_arc), ("G", arc(r, delta, tau - delta)?)];
let mut curves = Vec::with_capacity(2 * pins);
for k in 0..pins {
for (role, curve) in &space {
curves.push(SectionCurve { curve: rotated(curve, tau * k as f64), role, tooth: k });
}
}
snap_junctions(&mut curves);
let section = GearSection { curves, data: GearData { pitch_diameter: pin_circle_diameter, ..GearData::default() } };
let ring = hub_from_section(§ion, outside, width)?;
Ok((ring, section.data))
}
#[derive(Clone, Debug)]
pub struct CycloidalGear {
pub module: f64,
pub teeth: usize,
pub generating_radius: f64,
pub tooth_fraction: f64,
pub addendum: f64,
pub dedendum: f64,
pub width: f64,
}
pub fn cycloidal_gear_section(gear: &CycloidalGear) -> Result<GearSection, KernelRefusal> {
let m = gear.module;
if !(m > 0.0 && gear.generating_radius > 0.0 && gear.addendum > 0.0 && gear.dedendum > 0.0 && gear.width > 0.0) {
return Err(refuse("gear_input", "The module, rolling circle, addendum, dedendum and width must be positive.".into()));
}
if !(gear.tooth_fraction > 0.1 && gear.tooth_fraction < 0.9) {
return Err(refuse("gear_input", "The tooth thickness must be between 0.1 and 0.9 of the pitch.".into()));
}
if gear.teeth < 6 || gear.teeth > 1000 {
return Err(refuse("gear_input", format!("A cycloidal gear needs from 6 to 1000 teeth (it has {}).", gear.teeth)));
}
let z = gear.teeth as f64;
let r = m * z / 2.0;
let rho = gear.generating_radius;
let rf = r - gear.dedendum * m;
if !(rf > 0.0) {
return Err(refuse("root_below_centre", "The root circle is not positive: fewer dedendum or more teeth.".into()));
}
let tau = TAU / z;
let psi = PI * gear.tooth_fraction / z; let k = (r + rho) / rho;
let epi = |phi: f64| {
let p = [(r + rho) * phi.cos() - rho * (k * phi).cos(), (r + rho) * phi.sin() - rho * (k * phi).sin()];
rotate(p, -psi)
};
let ra = r + gear.addendum * m;
let reach = |phi: f64| radius_of(epi(phi)) >= ra || polar_angle(epi(phi)) >= 0.0;
let mut hi = 1e-3;
while !reach(hi) {
hi *= 1.5;
if hi > PI {
return Err(refuse("gear_input", "The addendum curve does not close.".into()));
}
}
let mut lo = 0.0;
for _ in 0..200 {
let mid = 0.5 * (lo + hi);
if reach(mid) { hi = mid } else { lo = mid }
}
let end = epi(hi);
let pointed = polar_angle(end) >= -1e-9;
let phi_end = if pointed {
let (mut lo, mut hi) = (0.0, hi);
for _ in 0..200 {
let mid = 0.5 * (lo + hi);
if polar_angle(epi(mid)) >= 0.0 { hi = mid } else { lo = mid }
}
hi
} else {
hi
};
let tolerance = GEAR_FIT_TOLERANCE * m;
let right_add = fit_planar(&|phi| epi(phi), 0.0, phi_end, tolerance)?; let foot = [rf * (-psi).cos(), rf * (-psi).sin()];
let pitch_point = [r * (-psi).cos(), r * (-psi).sin()];
let mut tooth: Vec<(&'static str, NurbsCurve)> = vec![("R", line(foot, pitch_point)?), ("ER", right_add.clone())];
let tip_angle = -polar_angle(epi(phi_end));
if !pointed {
tooth.push(("K", arc(ra, -tip_angle, tip_angle)?));
}
tooth.push(("EL", mirrored(&right_add).reversed().map_err(|e| refuse("gear_fit", e))?));
tooth.push(("L", line([pitch_point[0], -pitch_point[1]], [foot[0], -foot[1]])?));
tooth.push(("G", arc(rf, psi, tau - psi)?));
let mut curves = Vec::with_capacity(tooth.len() * gear.teeth);
for index in 0..gear.teeth {
let angle = tau * index as f64;
for (role, curve) in &tooth {
curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
}
}
snap_junctions(&mut curves);
let data = GearData {
pitch_diameter: 2.0 * r,
tip_diameter: 2.0 * radius_of(epi(phi_end)),
root_diameter: 2.0 * rf,
tooth_thickness: 2.0 * psi * r,
..GearData::default()
};
Ok(GearSection { curves, data })
}
pub fn cycloidal_gear_solid(gear: &CycloidalGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
let section = cycloidal_gear_section(gear)?;
let solid = extrude_section(§ion, gear.width)?;
let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
names.push("F".into());
names.push("B".into());
Ok((solid, names, section.data))
}