1use crate::{extrude_profile_brep, make_arc, BrepSolid, KernelRefusal, KernelStage, NurbsCurve, NurbsSurface, Vec3, Vec4};
20use std::f64::consts::{PI, TAU};
21
22pub const GEAR_FIT_TOLERANCE: f64 = 5e-7;
26
27#[derive(Clone, Debug)]
30pub struct SpurGear {
31 pub module: f64,
32 pub teeth: usize,
33 pub pressure_angle: f64,
34 pub profile_shift: f64,
36 pub addendum: f64,
38 pub dedendum: f64,
40 pub root_fillet: f64,
42 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#[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 pub form_diameter: f64,
72 pub tooth_thickness: f64,
74 pub tip_thickness: f64,
76 pub undercut: bool,
78 pub min_shift_without_undercut: f64,
80}
81
82#[derive(Clone, Debug)]
84pub struct SectionCurve {
85 pub curve: NurbsCurve,
86 pub role: &'static str,
88 pub tooth: usize,
89}
90
91impl SectionCurve {
92 pub fn suffix(&self) -> String {
94 format!("{}{}", self.role, self.tooth)
95 }
96}
97
98#[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
122struct RackCutter {
124 r: f64,
125 alpha: f64,
126 x_ref: f64,
128 y0: f64,
130 r_f: f64,
132 rho: f64,
133 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 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 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 fn fillet(&self, psi: f64) -> [f64; 2] {
168 let n = [-psi.cos(), -psi.sin()];
169 if self.rho == 0.0 {
170 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 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
186fn 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 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(°rees) {
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
304pub fn spur_section(gear: &SpurGear) -> Result<GearSection, KernelRefusal> {
306 check_spur(gear, 35.0)?;
307 generated_section(gear)
308}
309
310fn 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 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 let (x_join, psi_join) = if !undercut {
355 (x_flank_tangent, psi_end)
356 } else {
357 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 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 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 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 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)?; let fillet_fit = fit_planar(&|psi| rack.fillet(psi), 0.0, psi_join, tolerance)?; let root_angle = rack.centre[1] / r;
461 let land = 2.0 * half_pitch - 2.0 * root_angle;
462
463 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 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
500pub fn spur_solid(gear: &SpurGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
504 let section = spur_section(gear)?;
505 let solid = extrude_section(§ion, 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
512pub 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#[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 pub root_fillet: f64,
530 pub backlash: f64,
532 pub face_width: f64,
533 pub height: f64,
535 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
567pub 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(°rees) {
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; 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 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]; 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 let mut x_prev_root = length; 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 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 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
686pub 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 let degrees = rack.pressure_angle.to_degrees();
696 if !(10.0 - 1e-9..=35.0 + 1e-9).contains(°rees) {
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 let section = rack_section(rack)?;
702 let solid = extrude_section(§ion, 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 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 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
739fn 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: 0.0, w };
748 }
749}
750
751#[derive(Clone, Debug)]
754pub struct RingGear {
755 pub module: f64,
756 pub teeth: usize,
757 pub pressure_angle: f64,
758 pub profile_shift: f64,
761 pub addendum: f64,
762 pub dedendum: f64,
763 pub root_fillet: f64,
766 pub backlash: f64,
768 pub face_width: f64,
769 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
790pub 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(°rees) {
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; let r_f = r + (gear.dedendum + gear.profile_shift) * m; 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 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 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 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 [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 let flank_fit = fit_planar(&|radius| flank(radius), r_a, join_radius, tolerance)?; let mut space: Vec<(&'static str, NurbsCurve)> = Vec::new();
914 space.push(("R", mirrored(&flank_fit)));
916 if rho > 0.0 {
917 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)?; 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
956pub 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 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
983pub 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; 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1041pub enum SprocketForm {
1042 Minimum,
1044 Maximum,
1046 Mean,
1048}
1049
1050#[derive(Clone, Debug)]
1052pub struct Sprocket {
1053 pub pitch: f64,
1054 pub roller_diameter: f64,
1055 pub teeth: usize,
1056 pub form: SprocketForm,
1057 pub width: f64,
1059}
1060
1061pub 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 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 let c = [d / 2.0, 0.0];
1098 let u = [-(alpha / 2.0).cos(), (alpha / 2.0).sin()]; 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]]; let half = tau / 2.0;
1104 let a_t = (t_up[1] - f[1]).atan2(t_up[0] - f[0]);
1105 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 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 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)?; 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)];
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
1166pub fn sprocket_solid(sprocket: &Sprocket) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
1169 let section = sprocket_section(sprocket)?;
1170 let solid = extrude_section(§ion, 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#[derive(Clone, Copy, Debug)]
1181pub enum Twist {
1182 Helical { turn: f64 },
1184 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
1213fn twist_basis(twist: Twist, reach: f64, tolerance: f64) -> Result<(Vec<f64>, Vec<[f64; 3]>), KernelRefusal> {
1217 let crease = matches!(twist, Twist::Herringbone { .. });
1218 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
1268fn twisted_surface(curve: &NurbsCurve, width: f64, knots_v: &[f64], basis: &[[f64; 3]]) -> Result<NurbsSurface, KernelRefusal> {
1271 let rows = curve
1272 .control_points
1273 .iter()
1274 .map(|p| {
1275 basis
1276 .iter()
1277 .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 })
1278 .collect()
1279 })
1280 .collect();
1281 NurbsSurface::new(curve.degree, 3, curve.knots.clone(), knots_v.to_vec(), rows).map_err(|e| refuse("gear_surface", e))
1282}
1283
1284fn twisted_edge(point: Vec4, width: f64, knots_v: &[f64], basis: &[[f64; 3]]) -> Result<NurbsCurve, KernelRefusal> {
1286 let (x, y) = (point.x / point.w, point.y / point.w);
1287 let points = basis
1288 .iter()
1289 .map(|[c, s, t]| Vec4 { x: c * x - s * y, y: s * x + c * y, z: t * width, w: 1.0 })
1290 .collect();
1291 NurbsCurve::new(3, knots_v.to_vec(), points).map_err(|e| refuse("gear_edge", e))
1292}
1293
1294pub fn twisted_prism(section: &GearSection, width: f64, twist: Twist, tolerance: f64) -> Result<BrepSolid, KernelRefusal> {
1298 use crate::sweep_topology::{curve_to_plane_parameters, make_plane, parameter_line, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, ShellRecord, VertexRecord};
1299 if !(width > 0.0) {
1300 return Err(refuse("gear_input", format!("The face width must be greater than zero (it is {width}).")));
1301 }
1302 let curves: Vec<NurbsCurve> = section.curves.iter().map(|piece| piece.curve.clone()).collect();
1303 let count = curves.len();
1304 let reach = curves
1305 .iter()
1306 .flat_map(|c| c.control_points.iter())
1307 .map(|p| (p.x / p.w).hypot(p.y / p.w))
1308 .fold(0.0, f64::max);
1309 let (knots_v, basis) = twist_basis(twist, reach, tolerance)?;
1310 let end_angle = twist.angle(1.0);
1311 let lift = |curve: &NurbsCurve| -> NurbsCurve {
1312 let mut top = rotated(curve, end_angle);
1313 for point in &mut top.control_points {
1314 point.z += point.w * width;
1315 }
1316 top
1317 };
1318 let starts: Vec<Vec4> = curves.iter().map(|c| c.control_points[0]).collect();
1319 let point_of = |p: Vec4| Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w);
1320 let mut vertices = Vec::with_capacity(2 * count);
1321 for (index, start) in starts.iter().enumerate() {
1322 vertices.push(VertexRecord { id: index as u64 + 1, point: point_of(*start) });
1323 }
1324 let (se, ce) = end_angle.sin_cos();
1325 for (index, start) in starts.iter().enumerate() {
1326 let p = point_of(*start);
1327 vertices.push(VertexRecord {
1328 id: (count + index) as u64 + 1,
1329 point: Vec3::new(ce * p.x - se * p.y, se * p.x + ce * p.y, width),
1330 });
1331 }
1332 let edge_id = |kind: usize, index: usize| 10 + (kind * count + index) as u64;
1334 let mut edges = Vec::with_capacity(3 * count);
1335 for (index, curve) in curves.iter().enumerate() {
1336 let [start, end] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
1337 let next = (index + 1) % count;
1338 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 });
1339 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 });
1340 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 });
1341 }
1342 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));
1343 let mut next_id = 10 + 3 * count as u64 + 1000;
1344 let mut faces = Vec::with_capacity(count + 2);
1345 for (index, curve) in curves.iter().enumerate() {
1346 let [start, end] = curve.domain().map_err(|e| refuse("gear_domain", e))?;
1347 let next = (index + 1) % count;
1348 let coedges = vec![
1349 CoedgeRecord { id: next_id, edge_id: edge_id(0, index), forward: true, pcurve: line([start, 0.0], [end, 0.0])? },
1350 CoedgeRecord { id: next_id + 1, edge_id: edge_id(2, next), forward: true, pcurve: line([end, 0.0], [end, 1.0])? },
1351 CoedgeRecord { id: next_id + 2, edge_id: edge_id(1, index), forward: false, pcurve: line([end, 1.0], [start, 1.0])? },
1352 CoedgeRecord { id: next_id + 3, edge_id: edge_id(2, index), forward: false, pcurve: line([start, 1.0], [start, 0.0])? },
1353 ];
1354 next_id += 4;
1355 faces.push(FaceRecord {
1356 id: next_id + 1,
1357 surface: twisted_surface(curve, width, &knots_v, &basis)?,
1358 same_sense: true,
1359 loops: vec![LoopRecord { id: next_id, coedges }],
1360 name: None,
1361 });
1362 next_id += 2;
1363 }
1364 let pad = reach * 1.1 + 1.0;
1365 let x_axis = Vec3::new(1.0, 0.0, 0.0);
1366 let y_axis = Vec3::new(0.0, 1.0, 0.0);
1367 let bottom_origin = Vec3::new(-pad, -pad, 0.0);
1368 let mut bottom = Vec::with_capacity(count);
1369 for index in (0..count).rev() {
1370 bottom.push(CoedgeRecord {
1371 id: next_id,
1372 edge_id: edge_id(0, index),
1373 forward: false,
1374 pcurve: curve_to_plane_parameters(&curves[index], bottom_origin, x_axis, y_axis)
1375 .and_then(|c| c.reversed())
1376 .map_err(|e| refuse("gear_pcurve", e))?,
1377 });
1378 next_id += 1;
1379 }
1380 faces.push(FaceRecord {
1381 id: next_id + 1,
1382 surface: make_plane(bottom_origin, x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e))?,
1383 same_sense: false,
1384 loops: vec![LoopRecord { id: next_id, coedges: bottom }],
1385 name: None,
1386 });
1387 next_id += 2;
1388 let top_origin = Vec3::new(-pad, -pad, width);
1389 let mut top = Vec::with_capacity(count);
1390 for (index, curve) in curves.iter().enumerate() {
1391 top.push(CoedgeRecord {
1392 id: next_id,
1393 edge_id: edge_id(1, index),
1394 forward: true,
1395 pcurve: curve_to_plane_parameters(&lift(curve), top_origin, x_axis, y_axis).map_err(|e| refuse("gear_pcurve", e))?,
1396 });
1397 next_id += 1;
1398 }
1399 faces.push(FaceRecord {
1400 id: next_id + 1,
1401 surface: make_plane(top_origin, x_axis, y_axis, 2.0 * pad, 2.0 * pad).map_err(|e| refuse("gear_plane", e))?,
1402 same_sense: true,
1403 loops: vec![LoopRecord { id: next_id, coedges: top }],
1404 name: None,
1405 });
1406 next_id += 2;
1407 let solid = BrepSolid {
1408 mass_properties_cache: Default::default(),
1409 cells: Default::default(),
1410 id: next_id + 1,
1411 vertices,
1412 edges,
1413 shells: vec![ShellRecord { id: next_id, faces }],
1414 genus: 0,
1415 kind: crate::BodyKind::Solid,
1416 };
1417 let issues = solid.validate();
1418 if issues.is_empty() {
1419 Ok(solid)
1420 } else {
1421 Err(KernelRefusal::internal(KernelStage::Validate, "validate", format!("twisted gear prism is not valid: {issues:?}")))
1422 }
1423}
1424
1425#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1427pub enum Hand {
1428 Right,
1429 Left,
1430}
1431
1432#[derive(Clone, Debug)]
1436pub struct HelicalGear {
1437 pub spur: SpurGear,
1438 pub helix_angle: f64,
1439 pub hand: Hand,
1440 pub herringbone: bool,
1441}
1442
1443pub fn helical_transverse(gear: &HelicalGear) -> Result<SpurGear, KernelRefusal> {
1445 let beta = gear.helix_angle;
1446 let normal = gear.spur.pressure_angle.to_degrees();
1448 if !(10.0 - 1e-9..=35.0 + 1e-9).contains(&normal) {
1449 return Err(refuse("gear_input", format!("The normal pressure angle must be between 10° and 35° (it is {normal}°).")));
1450 }
1451 if !(beta.to_degrees() >= 0.5 - 1e-9 && beta.to_degrees() <= 45.0 + 1e-9) {
1452 return Err(refuse("bad_helix", format!("The helix angle must be between 0.5° and 45° (it is {:.4}°).", beta.to_degrees())));
1453 }
1454 let n = &gear.spur;
1455 let c = beta.cos();
1456 Ok(SpurGear {
1457 module: n.module / c,
1458 teeth: n.teeth,
1459 pressure_angle: (n.pressure_angle.tan() / c).atan(),
1460 profile_shift: n.profile_shift * c,
1461 addendum: n.addendum * c,
1462 dedendum: n.dedendum * c,
1463 root_fillet: n.root_fillet * c,
1466 backlash: n.backlash,
1467 face_width: n.face_width,
1468 })
1469}
1470
1471pub fn helical_solid(gear: &HelicalGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
1473 let transverse = helical_transverse(gear)?;
1474 let section = transverse_section(&transverse)?;
1475 let r = transverse.module * transverse.teeth as f64 / 2.0;
1476 let width = transverse.face_width;
1477 let sign = if gear.hand == Hand::Right { 1.0 } else { -1.0 };
1478 let twist = if gear.herringbone {
1479 Twist::Herringbone { turn: sign * width * gear.helix_angle.tan() / r }
1481 } else {
1482 Twist::Helical { turn: sign * width * gear.helix_angle.tan() / r }
1483 };
1484 let solid = twisted_prism(§ion, width, twist, 0.1 * GEAR_FIT_TOLERANCE * transverse.module)?;
1485 let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
1486 names.push("F".into());
1487 names.push("B".into());
1488 Ok((solid, names, section.data))
1489}
1490
1491#[derive(Clone, Debug)]
1494pub struct StraightSpline {
1495 pub teeth: usize,
1496 pub minor: f64,
1497 pub major: f64,
1498 pub key_width: f64,
1499 pub length: f64,
1500}
1501
1502fn check_straight_spline(spline: &StraightSpline) -> Result<(), KernelRefusal> {
1503 let StraightSpline { teeth, minor, major, key_width, length } = *spline;
1504 if !(minor > 0.0 && major > minor && key_width > 0.0 && length > 0.0) {
1505 return Err(refuse(
1506 "gear_input",
1507 format!("A spline needs 0 < minor diameter ({minor}) < major diameter ({major}), a positive key width ({key_width}) and length ({length})."),
1508 ));
1509 }
1510 if teeth < 2 || teeth > 100 {
1511 return Err(refuse("gear_input", format!("A spline needs from 2 to 100 keys (it has {teeth}).")));
1512 }
1513 let half_root = (key_width / minor).asin();
1515 if !(key_width < minor) || 2.0 * half_root >= TAU / teeth as f64 - 1e-9 {
1516 return Err(refuse("keys_overlap", format!("{teeth} keys {key_width} wide do not fit round a {minor} minor diameter.")));
1517 }
1518 Ok(())
1519}
1520
1521pub fn straight_spline_section(spline: &StraightSpline) -> Result<GearSection, KernelRefusal> {
1525 check_straight_spline(spline)?;
1526 let (rr, ra, h) = (spline.minor / 2.0, spline.major / 2.0, spline.key_width / 2.0);
1527 let n = spline.teeth as f64;
1528 let foot = [(rr * rr - h * h).sqrt(), h];
1529 let top = [(ra * ra - h * h).sqrt(), h];
1530 let top_angle = (h / ra).asin();
1531 let foot_angle = (h / rr).asin();
1532 let key: Vec<(&'static str, NurbsCurve)> = vec![
1533 ("R", line([foot[0], -h], [top[0], -h])?),
1534 ("K", arc(ra, -top_angle, top_angle)?),
1535 ("L", line(top, foot)?),
1536 ("G", arc(rr, foot_angle, TAU / n - foot_angle)?),
1537 ];
1538 let mut curves = Vec::with_capacity(4 * spline.teeth);
1539 for index in 0..spline.teeth {
1540 let angle = TAU * index as f64 / n;
1541 for (role, curve) in &key {
1542 curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
1543 }
1544 }
1545 snap_junctions(&mut curves);
1546 Ok(GearSection { curves, data: GearData { tip_diameter: spline.major, root_diameter: spline.minor, ..GearData::default() } })
1547}
1548
1549pub fn straight_spline_shaft(spline: &StraightSpline) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
1552 let section = straight_spline_section(spline)?;
1553 let solid = extrude_section(§ion, spline.length)?;
1554 let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
1555 names.push("F".into());
1556 names.push("B".into());
1557 Ok((solid, names, section.data))
1558}
1559
1560pub fn hub_from_section(section: &GearSection, outside: f64, length: f64) -> Result<BrepSolid, KernelRefusal> {
1564 let mut reach: f64 = 0.0;
1567 for piece in §ion.curves {
1568 let [t0, t1] = piece.curve.domain().map_err(|e| refuse("gear_domain", e))?;
1569 for i in 0..=32 {
1570 let p = piece.curve.evaluate(t0 + (t1 - t0) * i as f64 / 32.0).map_err(|e| refuse("gear_eval", e))?;
1571 reach = reach.max(p.x.hypot(p.y));
1572 }
1573 }
1574 if !(outside / 2.0 > reach + 1e-9) {
1575 return Err(refuse(
1576 "hub_too_small",
1577 format!("The hub's outside diameter ({outside}) must be larger than its spline's major diameter ({:.4}).", 2.0 * reach),
1578 ));
1579 }
1580 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)
1581 .map_err(|error| refuse("gear_blank", error))?;
1582 for (face, name) in blank.shells[0].faces.iter_mut().zip(["OD", "F", "B"]) {
1583 face.name = Some(name.into());
1584 }
1585 let extra = 0.1 * length + 0.1 * reach;
1586 let shifted: Vec<SectionCurve> = section
1587 .curves
1588 .iter()
1589 .map(|piece| SectionCurve { curve: translated(&piece.curve, -extra), role: piece.role, tooth: piece.tooth })
1590 .collect();
1591 let mut tool = extrude_section(&GearSection { curves: shifted.clone(), data: section.data.clone() }, length + 2.0 * extra)?;
1592 for (face, piece) in tool.shells[0].faces.iter_mut().zip(&shifted) {
1593 face.name = Some(piece.suffix());
1594 }
1595 crate::boolean_operation_nary(&[blank, tool], crate::BooleanOperation::Subtract)
1596}
1597
1598pub fn straight_spline_hub(spline: &StraightSpline, outside: f64) -> Result<(BrepSolid, GearData), KernelRefusal> {
1600 let section = straight_spline_section(spline)?;
1601 let hub = hub_from_section(§ion, outside, spline.length)?;
1602 Ok((hub, section.data))
1603}
1604
1605#[derive(Clone, Debug)]
1608pub struct TimingPulley {
1609 pub pitch: f64,
1611 pub teeth: usize,
1612 pub pld: f64,
1614 pub bottom_width: f64,
1616 pub depth: f64,
1618 pub side_angle: f64,
1620 pub bottom_radius: f64,
1622 pub top_radius: f64,
1624 pub width: f64,
1625}
1626
1627fn arc_through(centre: [f64; 2], from: [f64; 2], to: [f64; 2], ccw: bool) -> Result<NurbsCurve, KernelRefusal> {
1630 let radius = (from[0] - centre[0]).hypot(from[1] - centre[1]);
1631 let a0 = (from[1] - centre[1]).atan2(from[0] - centre[0]);
1632 let a1 = (to[1] - centre[1]).atan2(to[0] - centre[0]);
1633 if ccw {
1634 let mut end = a1;
1635 while end <= a0 {
1636 end += TAU;
1637 }
1638 centred_arc(centre, radius, a0, end)
1639 } else {
1640 let mut start = a1;
1641 while start <= a0 - TAU {
1642 start += TAU;
1643 }
1644 while start >= a0 {
1645 start -= TAU;
1646 }
1647 centred_arc(centre, radius, start, a0)?.reversed().map_err(|e| refuse("gear_arc", e))
1648 }
1649}
1650
1651pub fn timing_pulley_section(pulley: &TimingPulley) -> Result<GearSection, KernelRefusal> {
1658 let TimingPulley { pitch, teeth, pld, bottom_width, depth, side_angle, bottom_radius, top_radius, width } = pulley.clone();
1659 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) {
1660 return Err(refuse("gear_input", "The pulley's pitch, groove sizes and width must be positive.".into()));
1661 }
1662 if !(0.0..60f64.to_radians()).contains(&side_angle) {
1663 return Err(refuse("gear_input", "The groove side angle must be between 0° and 60°.".into()));
1664 }
1665 if teeth < 6 || teeth > 400 {
1666 return Err(refuse("gear_input", format!("A pulley needs from 6 to 400 teeth (it has {teeth}).")));
1667 }
1668 let z = teeth as f64;
1669 let ro = pitch * z / PI / 2.0 - pld / 2.0;
1670 let x_bottom = ro - depth;
1671 if !(x_bottom > 0.0) {
1672 return Err(refuse("gear_input", "The groove is deeper than the pulley's radius.".into()));
1673 }
1674 let tau = TAU / z;
1675 let (s, c) = side_angle.sin_cos();
1676 let side = [c, s]; let normal = [-s, c]; let corner = [x_bottom, bottom_width / 2.0];
1679 let b = corner[0] * side[0] + corner[1] * side[1];
1681 let t_top = -b + (b * b - (corner[0] * corner[0] + corner[1] * corner[1] - ro * ro)).sqrt();
1682 let top = [corner[0] + t_top * side[0], corner[1] + t_top * side[1]];
1683 let turn = PI / 2.0 - side_angle;
1686 let reach_b = bottom_radius * (turn / 2.0).tan();
1687 let t1 = [corner[0], corner[1] - reach_b];
1688 let t2 = [corner[0] + reach_b * side[0], corner[1] + reach_b * side[1]];
1689 let centre_b = [t1[0] + bottom_radius, t1[1]];
1690 let rt = top_radius;
1693 let base = [corner[0] + rt * normal[0], corner[1] + rt * normal[1]];
1694 let bb = base[0] * side[0] + base[1] * side[1];
1695 let disc = bb * bb - (base[0] * base[0] + base[1] * base[1] - (ro - rt) * (ro - rt));
1696 if disc < 0.0 {
1697 return Err(refuse("gear_input", "The groove's top radius does not fit.".into()));
1698 }
1699 let t_c = -bb + disc.sqrt();
1700 let centre_t = [base[0] + t_c * side[0], base[1] + t_c * side[1]];
1701 let t3 = [corner[0] + t_c * side[0], corner[1] + t_c * side[1]];
1702 let scale = ro / (centre_t[0].hypot(centre_t[1]));
1703 let t4 = [centre_t[0] * scale, centre_t[1] * scale];
1704 let land_start = polar_angle(t4);
1705 if land_start >= tau / 2.0 - 1e-9 || reach_b > t_c + 1e-12 || t1[1] < 0.0 {
1706 return Err(refuse(
1707 "groove_too_wide",
1708 format!("The grooves and their corner radii do not fit the pitch at {teeth} teeth; add teeth or reduce the radii."),
1709 ));
1710 }
1711 let _ = top;
1712 let mut upper: Vec<(&'static str, NurbsCurve)> = Vec::new();
1714 if bottom_radius > 0.0 {
1715 upper.push(("D", arc_through(centre_b, t1, t2, false)?));
1716 }
1717 upper.push(("C", line(t2, t3)?));
1718 if rt > 0.0 {
1719 upper.push(("P", arc_through(centre_t, t3, t4, true)?));
1720 }
1721 let mut groove: Vec<(&'static str, NurbsCurve)> = Vec::new();
1722 let lower_roles = |role: &'static str| match role {
1723 "D" => "U",
1724 "C" => "A",
1725 _ => "Q",
1726 };
1727 for (role, curve) in upper.iter().rev() {
1728 groove.push((lower_roles(role), mirrored(curve).reversed().map_err(|e| refuse("gear_arc", e))?));
1729 }
1730 groove.push(("S", line([t1[0], -t1[1]], t1)?));
1731 groove.extend(upper.into_iter());
1732 groove.push(("K", arc(ro, land_start, tau - land_start)?));
1733 let mut curves = Vec::with_capacity(groove.len() * teeth);
1734 for index in 0..teeth {
1735 let angle = tau * index as f64 + tau / 2.0;
1736 for (role, curve) in &groove {
1737 curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
1738 }
1739 }
1740 snap_junctions(&mut curves);
1741 let data = GearData { pitch_diameter: pitch * z / PI, tip_diameter: 2.0 * ro, root_diameter: 2.0 * x_bottom, ..GearData::default() };
1742 Ok(GearSection { curves, data })
1743}
1744
1745pub fn timing_pulley_solid(pulley: &TimingPulley) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
1748 let section = timing_pulley_section(pulley)?;
1749 let solid = extrude_section(§ion, pulley.width)?;
1750 let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
1751 names.push("F".into());
1752 names.push("B".into());
1753 Ok((solid, names, section.data))
1754}
1755
1756#[derive(Clone, Debug)]
1762pub struct Ratchet {
1763 pub teeth: usize,
1764 pub outside: f64,
1765 pub depth: f64,
1766 pub lean: f64,
1767 pub symmetric: bool,
1768 pub clockwise_locks: bool,
1769 pub width: f64,
1770}
1771
1772pub fn ratchet_section(ratchet: &Ratchet) -> Result<GearSection, KernelRefusal> {
1776 let Ratchet { teeth, outside, depth, lean, symmetric, clockwise_locks, width } = ratchet.clone();
1777 if !(outside > 0.0 && depth > 0.0 && depth < outside / 2.0 && width > 0.0) {
1778 return Err(refuse("gear_input", format!("A ratchet needs a positive outside diameter ({outside}), a depth ({depth}) under its radius and a positive width.")));
1779 }
1780 if teeth < 3 || teeth > 360 {
1781 return Err(refuse("gear_input", format!("A ratchet needs from 3 to 360 teeth (it has {teeth}).")));
1782 }
1783 if !(lean >= 0.0 && lean.to_degrees() <= 30.0) {
1784 return Err(refuse("gear_input", "The locking face lean must be between 0° and 30°.".into()));
1785 }
1786 let z = teeth as f64;
1787 let tau = TAU / z;
1788 let ra = outside / 2.0;
1789 let rf = ra - depth;
1790 let tip = [ra, 0.0];
1795 let face_angle = PI + lean; let d = [face_angle.cos(), face_angle.sin()];
1797 let b = tip[0] * d[0] + tip[1] * d[1];
1798 let t = -b - (b * b - (ra * ra - rf * rf)).sqrt();
1799 let root = [tip[0] + t * d[0], tip[1] + t * d[1]];
1800 let foot = polar_angle(root);
1801 let (lock, back) = if symmetric {
1802 let mid = [rf * (tau / 2.0).cos(), rf * (tau / 2.0).sin()];
1804 let lock = line(tip, mid)?;
1805 let next = [ra * tau.cos(), ra * tau.sin()];
1806 (lock, line(mid, next)?)
1807 } else {
1808 if foot >= tau - 1e-9 {
1809 return Err(refuse("gear_input", "The locking faces overlap: fewer teeth, less depth or less lean.".into()));
1810 }
1811 let next = [ra * tau.cos(), ra * tau.sin()];
1812 (line(tip, root)?, line(root, next)?)
1813 };
1814 let mut curves = Vec::with_capacity(2 * teeth);
1816 for index in 0..teeth {
1817 let angle = tau * index as f64;
1818 curves.push(SectionCurve { curve: rotated(&lock, angle), role: "LK", tooth: index });
1819 curves.push(SectionCurve { curve: rotated(&back, angle), role: "BK", tooth: index });
1820 }
1821 if clockwise_locks {
1822 let mut mirrored_curves: Vec<SectionCurve> = curves
1825 .iter()
1826 .map(|piece| SectionCurve { curve: mirrored(&piece.curve).reversed().expect("a line reverses"), role: piece.role, tooth: piece.tooth })
1827 .collect();
1828 mirrored_curves.reverse();
1829 curves = mirrored_curves;
1830 }
1831 snap_junctions(&mut curves);
1832 Ok(GearSection { curves, data: GearData { tip_diameter: outside, root_diameter: 2.0 * rf, ..GearData::default() } })
1833}
1834
1835pub fn ratchet_solid(ratchet: &Ratchet) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
1837 let section = ratchet_section(ratchet)?;
1838 let solid = extrude_section(§ion, ratchet.width)?;
1839 let mut names: Vec<String> = section.curves.iter().map(|c| c.suffix()).collect();
1840 names.push("F".into());
1841 names.push("B".into());
1842 Ok((solid, names, section.data))
1843}
1844
1845#[derive(Clone, Debug)]
1851pub struct GenevaWheel {
1852 pub slots: usize,
1853 pub centre_distance: f64,
1854 pub pin_diameter: f64,
1855 pub clearance: f64,
1856 pub lock_radius: f64,
1858 pub width: f64,
1859}
1860
1861pub fn geneva_sizes(wheel: &GenevaWheel) -> (f64, f64, f64, f64) {
1863 let n = wheel.slots as f64;
1864 let a = wheel.centre_distance;
1865 let crank = a * (PI / n).sin();
1866 let radius = a * (PI / n).cos();
1867 let lock = if wheel.lock_radius > 0.0 { wheel.lock_radius } else { crank - wheel.pin_diameter };
1868 (crank, radius, a - crank, lock)
1869}
1870
1871pub fn geneva_section(wheel: &GenevaWheel) -> Result<GearSection, KernelRefusal> {
1876 let GenevaWheel { slots, centre_distance: a, pin_diameter: dp, clearance: c, width, .. } = wheel.clone();
1877 if !(3..=12).contains(&slots) {
1878 return Err(refuse("gear_input", format!("A Geneva wheel has from 3 to 12 slots (it has {slots}).")));
1879 }
1880 if !(a > 0.0 && dp > 0.0 && c >= 0.0 && width > 0.0) {
1881 return Err(refuse("gear_input", "The centre distance, pin diameter and width must be positive (the clearance not negative).".into()));
1882 }
1883 let n = slots as f64;
1884 let (crank, rw, end_centre, lock) = geneva_sizes(wheel);
1885 let half = (dp + c) / 2.0; let rl = lock + c / 2.0;
1887 if !(lock > 0.0 && lock < a - rw + 1e-9 + rw) || !(half < end_centre) || !(half < rw * (PI / n).sin()) {
1888 return Err(refuse("gear_input", format!("The pin ({dp}) is too large for {slots} slots at centre distance {a}.")));
1889 }
1890 if end_centre * (PI / n).sin() <= half * (1.0 + 1e-9) {
1893 return Err(refuse(
1894 "gear_input",
1895 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),
1896 ));
1897 }
1898 let x_top = (rw * rw - half * half).sqrt();
1899 let p1 = [x_top, half];
1900 let beta = PI / n;
1901 let centre = [a * beta.cos(), a * beta.sin()];
1902 let along = (rw * rw - rl * rl + a * a) / (2.0 * a);
1904 let h2 = rw * rw - along * along;
1905 if h2 <= 0.0 {
1906 return Err(refuse("gear_input", "The locking arc does not reach the wheel's rim: increase the locking disc radius.".into()));
1907 }
1908 let h = h2.sqrt();
1909 let e = [beta.cos(), beta.sin()];
1910 let perp = [-beta.sin(), beta.cos()];
1911 let q1 = [along * e[0] - h * perp[0], along * e[1] - h * perp[1]];
1912 let q2 = [along * e[0] + h * perp[0], along * e[1] + h * perp[1]];
1913 let a1 = polar_angle(p1);
1914 if polar_angle(q1) <= a1 + 1e-9 {
1915 return Err(refuse("gear_input", "The locking arc cuts into the slots: reduce the locking disc radius or the pin.".into()));
1916 }
1917 let tau = TAU / n;
1918 let slot: Vec<(&'static str, NurbsCurve)> = vec![
1919 ("SL", line([x_top, -half], [end_centre, -half])?),
1920 ("SE", arc_through([end_centre, 0.0], [end_centre, -half], [end_centre, half], false)?),
1921 ("SU", line([end_centre, half], p1)?),
1922 ("RA", arc(rw, a1, polar_angle(q1))?),
1923 ("LA", arc_through(centre, q1, q2, false)?),
1924 ("RB", arc(rw, polar_angle(q2), tau - a1)?),
1925 ];
1926 let mut curves = Vec::with_capacity(6 * slots);
1927 for index in 0..slots {
1928 let angle = tau * index as f64;
1929 for (role, curve) in &slot {
1930 curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
1931 }
1932 }
1933 snap_junctions(&mut curves);
1934 let _ = crank;
1935 Ok(GearSection { curves, data: GearData { tip_diameter: 2.0 * rw, ..GearData::default() } })
1936}
1937
1938pub fn geneva_solid(wheel: &GenevaWheel) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
1941 let section = geneva_section(wheel)?;
1942 let solid = extrude_section(§ion, wheel.width)?;
1943 let mut names: Vec<String> = section.curves.iter().map(|c| c.suffix()).collect();
1944 names.push("F".into());
1945 names.push("B".into());
1946 Ok((solid, names, section.data))
1947}
1948
1949#[derive(Clone, Debug)]
1952pub struct Worm {
1953 pub axial_module: f64,
1954 pub starts: usize,
1955 pub reference_diameter: f64,
1957 pub pressure_angle: f64,
1958 pub addendum: f64,
1959 pub dedendum: f64,
1960 pub length: f64,
1961 pub hand: Hand,
1962}
1963
1964impl Worm {
1965 pub fn lead(&self) -> f64 {
1967 self.starts as f64 * PI * self.axial_module
1968 }
1969
1970 pub fn axial_thickness(&self, radius: f64) -> f64 {
1972 PI * self.axial_module / 2.0 - 2.0 * (radius - self.reference_diameter / 2.0) * self.pressure_angle.tan()
1973 }
1974}
1975
1976pub fn worm_section(worm: &Worm) -> Result<GearSection, KernelRefusal> {
1981 let m = worm.axial_module;
1982 if !(m > 0.0 && worm.reference_diameter > 0.0 && worm.length > 0.0 && worm.addendum > 0.0 && worm.dedendum > 0.0) {
1983 return Err(refuse("gear_input", "The worm's module, diameter, length, addendum and dedendum must be positive.".into()));
1984 }
1985 if worm.starts < 1 || worm.starts > 8 {
1986 return Err(refuse("gear_input", format!("A worm has from 1 to 8 starts (it has {}).", worm.starts)));
1987 }
1988 let degrees = worm.pressure_angle.to_degrees();
1989 if !(10.0 - 1e-9..=35.0 + 1e-9).contains(°rees) {
1990 return Err(refuse("gear_input", format!("The axial pressure angle must be between 10° and 35° (it is {degrees}°).")));
1991 }
1992 let r1 = worm.reference_diameter / 2.0;
1993 let ra = r1 + worm.addendum * m;
1994 let rf = r1 - worm.dedendum * m;
1995 if !(rf > 0.0) {
1996 return Err(refuse("gear_input", format!("The worm's root diameter is not positive ({:.4}): raise the diameter quotient.", 2.0 * rf)));
1997 }
1998 let lead = worm.lead();
1999 let gamma = (lead / (PI * worm.reference_diameter)).atan();
2000 if gamma.to_degrees() > 45.0 {
2001 return Err(refuse("bad_lead", format!("The lead angle {:.3}° is over 45°: fewer starts or a larger diameter.", gamma.to_degrees())));
2002 }
2003 if worm.axial_thickness(ra) <= 1e-6 * m {
2004 return Err(refuse("pointed_tip", "The worm thread comes to a point below its tip: lower the addendum or the pressure angle.".into()));
2005 }
2006 let n = worm.starts as f64;
2007 let pitch = PI * m;
2008 if worm.axial_thickness(rf) >= pitch - 1e-6 * m {
2009 return Err(refuse("teeth_overlap", "The worm's threads meet at the root: lower the dedendum or the pressure angle.".into()));
2010 }
2011 let half = |r: f64| PI * worm.axial_thickness(r) / lead;
2013 let flank = |r: f64| {
2014 let t = half(r);
2015 [r * t.cos(), r * t.sin()]
2016 };
2017 let tolerance = GEAR_FIT_TOLERANCE * m;
2018 let upper = fit_planar(&|r| flank(r), rf, ra, tolerance)?; let tau = TAU / n;
2020 let thread: Vec<(&'static str, NurbsCurve)> = vec![
2021 ("R", mirrored(&upper)),
2022 ("K", arc(ra, -half(ra), half(ra))?),
2023 ("L", upper.reversed().map_err(|e| refuse("gear_fit", e))?),
2024 ("G", arc(rf, half(rf), tau - half(rf))?),
2025 ];
2026 let mut curves = Vec::with_capacity(4 * worm.starts);
2027 for index in 0..worm.starts {
2028 let angle = tau * index as f64;
2029 for (role, curve) in &thread {
2030 curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
2031 }
2032 }
2033 snap_junctions(&mut curves);
2034 let data = GearData { pitch_diameter: worm.reference_diameter, tip_diameter: 2.0 * ra, root_diameter: 2.0 * rf, ..GearData::default() };
2035 Ok(GearSection { curves, data })
2036}
2037
2038pub fn worm_solid(worm: &Worm) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
2041 let section = worm_section(worm)?;
2042 let sign = if worm.hand == Hand::Right { 1.0 } else { -1.0 };
2043 let turn = sign * TAU * worm.length / worm.lead();
2044 let solid = twisted_prism(§ion, worm.length, Twist::Helical { turn }, GEAR_FIT_TOLERANCE * worm.axial_module)?;
2045 let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
2046 names.push("F".into());
2047 names.push("B".into());
2048 Ok((solid, names, section.data))
2049}
2050
2051#[derive(Clone, Debug)]
2056pub struct CycloidalDisc {
2057 pub pins: usize,
2058 pub pin_circle_diameter: f64,
2059 pub pin_diameter: f64,
2060 pub eccentricity: f64,
2061 pub clearance: f64,
2063 pub width: f64,
2064}
2065
2066impl CycloidalDisc {
2067 fn trochoid(&self, t: f64) -> ([f64; 2], [f64; 2]) {
2069 let r = self.pin_circle_diameter / 2.0;
2070 let e = self.eccentricity;
2071 let n = self.pins as f64;
2072 (
2073 [r * t.cos() - e * (n * t).cos(), -r * t.sin() + e * (n * t).sin()],
2074 [-r * t.sin() + e * n * (n * t).sin(), -r * t.cos() + e * n * (n * t).cos()],
2075 )
2076 }
2077
2078 pub fn profile(&self, t: f64) -> [f64; 2] {
2081 let (q, d) = self.trochoid(t);
2082 let length = d[0].hypot(d[1]);
2083 let offset = self.pin_diameter / 2.0 + self.clearance / 2.0;
2084 let n = [d[1] / length, -d[0] / length];
2086 [q[0] + offset * n[0], q[1] + offset * n[1]]
2087 }
2088}
2089
2090pub fn cycloidal_disc_section(disc: &CycloidalDisc) -> Result<GearSection, KernelRefusal> {
2092 let CycloidalDisc { pins, pin_circle_diameter: dc, pin_diameter: dp, eccentricity: e, clearance, width } = disc.clone();
2093 if !(4..=200).contains(&pins) {
2094 return Err(refuse("gear_input", format!("A cycloidal drive has from 4 to 200 pins (it has {pins}).")));
2095 }
2096 if !(dc > 0.0 && dp > 0.0 && e > 0.0 && clearance >= 0.0 && width > 0.0) {
2097 return Err(refuse("gear_input", "The pin circle, pin diameter, eccentricity and width must be positive.".into()));
2098 }
2099 let n = pins as f64;
2100 let r = dc / 2.0;
2101 if e >= r / n * (1.0 - 1e-9) {
2103 return Err(refuse(
2104 "gear_input",
2105 format!("The eccentricity must be under the pin circle radius / pins = {:.4} (it is {e}).", r / n),
2106 ));
2107 }
2108 let offset = dp / 2.0 + clearance / 2.0;
2110 let (rr, ee) = (dc / 2.0, e);
2114 let radius = |t: f64| -> f64 {
2115 let d = [-rr * t.sin() + ee * n * (n * t).sin(), -rr * t.cos() + ee * n * (n * t).cos()];
2116 let dd = [-rr * t.cos() + ee * n * n * (n * t).cos(), rr * t.sin() - ee * n * n * (n * t).sin()];
2117 let cross = d[0] * dd[1] - d[1] * dd[0];
2118 let speed = d[0].hypot(d[1]);
2119 if cross < 0.0 { speed * speed * speed / -cross } else { f64::INFINITY }
2120 };
2121 let period = TAU / (n - 1.0);
2124 let samples = 2000;
2125 let values: Vec<f64> = (0..=samples).map(|i| radius(period * i as f64 / samples as f64)).collect();
2126 let mut least = f64::INFINITY;
2127 for i in 0..=samples {
2128 let previous = values[if i == 0 { samples - 1 } else { i - 1 }];
2129 let next = values[if i == samples { 1 } else { i + 1 }];
2130 if values[i] <= previous && values[i] <= next && values[i].is_finite() {
2131 let (mut lo, mut hi) = (period * (i as f64 - 1.0) / samples as f64, period * (i as f64 + 1.0) / samples as f64);
2132 for _ in 0..100 {
2133 let a = lo + (hi - lo) * 0.381966;
2134 let b = hi - (hi - lo) * 0.381966;
2135 if radius(a) < radius(b) { hi = b } else { lo = a }
2136 }
2137 least = least.min(radius(0.5 * (lo + hi)));
2138 }
2139 }
2140 if offset >= least * (1.0 - 1e-6) {
2141 return Err(refuse(
2142 "undercut",
2143 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})."),
2144 ));
2145 }
2146 let lobes = pins - 1;
2147 let step = TAU / lobes as f64;
2148 let tolerance = GEAR_FIT_TOLERANCE * dp.min(e * 4.0);
2149 let mut curves = Vec::with_capacity(lobes);
2151 for k in 0..lobes {
2152 let (a, b) = (step * k as f64, step * (k + 1) as f64);
2153 let piece = fit_planar(&|u| disc.profile(-u), a, b, tolerance)?;
2154 curves.push(SectionCurve { curve: piece, role: "LB", tooth: k });
2155 }
2156 snap_junctions(&mut curves);
2157 Ok(GearSection { curves, data: GearData { pitch_diameter: dc, ..GearData::default() } })
2158}
2159
2160pub fn cycloidal_disc_solid(disc: &CycloidalDisc) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
2162 let section = cycloidal_disc_section(disc)?;
2163 let solid = extrude_section(§ion, disc.width)?;
2164 let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
2165 names.push("F".into());
2166 names.push("B".into());
2167 Ok((solid, names, section.data))
2168}
2169
2170pub fn cycloidal_pin_ring(pins: usize, pin_circle_diameter: f64, pin_diameter: f64, outside: f64, width: f64) -> Result<(BrepSolid, GearData), KernelRefusal> {
2175 if !(4..=200).contains(&pins) || !(pin_diameter > 0.0 && pin_circle_diameter > pin_diameter && width > 0.0) {
2176 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()));
2177 }
2178 let r = pin_circle_diameter / 2.0;
2179 let rp = pin_diameter / 2.0;
2180 let n = pins as f64;
2181 let tau = TAU / n;
2182 let delta = 2.0 * (rp / (2.0 * r)).asin();
2184 if 2.0 * delta >= tau - 1e-9 || 2.0 * r * (PI / n).sin() <= pin_diameter * (1.0 + 1e-9) {
2185 return Err(refuse("gear_input", format!("{pins} pins of diameter {pin_diameter} overlap on a {pin_circle_diameter} pin circle.")));
2186 }
2187 let centre = [r, 0.0];
2188 let a = [r * (-delta).cos(), r * (-delta).sin()];
2189 let b = [r * delta.cos(), r * delta.sin()];
2190 let cw = arc_through(centre, a, b, false)?;
2192 let pin_arc = {
2193 let [t0, t1] = cw.domain().map_err(|e| refuse("gear_domain", e))?;
2194 let mid = cw.evaluate(0.5 * (t0 + t1)).map_err(|e| refuse("gear_eval", e))?;
2195 if mid.x < r { cw } else { arc_through(centre, a, b, true)? }
2196 };
2197 let space: Vec<(&'static str, NurbsCurve)> = vec![("P", pin_arc), ("G", arc(r, delta, tau - delta)?)];
2198 let mut curves = Vec::with_capacity(2 * pins);
2199 for k in 0..pins {
2200 for (role, curve) in &space {
2201 curves.push(SectionCurve { curve: rotated(curve, tau * k as f64), role, tooth: k });
2202 }
2203 }
2204 snap_junctions(&mut curves);
2205 let section = GearSection { curves, data: GearData { pitch_diameter: pin_circle_diameter, ..GearData::default() } };
2206 let ring = hub_from_section(§ion, outside, width)?;
2207 Ok((ring, section.data))
2208}
2209
2210#[derive(Clone, Debug)]
2214pub struct CycloidalGear {
2215 pub module: f64,
2216 pub teeth: usize,
2217 pub generating_radius: f64,
2219 pub tooth_fraction: f64,
2221 pub addendum: f64,
2223 pub dedendum: f64,
2225 pub width: f64,
2226}
2227
2228pub fn cycloidal_gear_section(gear: &CycloidalGear) -> Result<GearSection, KernelRefusal> {
2232 let m = gear.module;
2233 if !(m > 0.0 && gear.generating_radius > 0.0 && gear.addendum > 0.0 && gear.dedendum > 0.0 && gear.width > 0.0) {
2234 return Err(refuse("gear_input", "The module, rolling circle, addendum, dedendum and width must be positive.".into()));
2235 }
2236 if !(gear.tooth_fraction > 0.1 && gear.tooth_fraction < 0.9) {
2237 return Err(refuse("gear_input", "The tooth thickness must be between 0.1 and 0.9 of the pitch.".into()));
2238 }
2239 if gear.teeth < 6 || gear.teeth > 1000 {
2240 return Err(refuse("gear_input", format!("A cycloidal gear needs from 6 to 1000 teeth (it has {}).", gear.teeth)));
2241 }
2242 let z = gear.teeth as f64;
2243 let r = m * z / 2.0;
2244 let rho = gear.generating_radius;
2245 let rf = r - gear.dedendum * m;
2246 if !(rf > 0.0) {
2247 return Err(refuse("root_below_centre", "The root circle is not positive: fewer dedendum or more teeth.".into()));
2248 }
2249 let tau = TAU / z;
2250 let psi = PI * gear.tooth_fraction / z; let k = (r + rho) / rho;
2253 let epi = |phi: f64| {
2254 let p = [(r + rho) * phi.cos() - rho * (k * phi).cos(), (r + rho) * phi.sin() - rho * (k * phi).sin()];
2255 rotate(p, -psi)
2256 };
2257 let ra = r + gear.addendum * m;
2258 let reach = |phi: f64| radius_of(epi(phi)) >= ra || polar_angle(epi(phi)) >= 0.0;
2260 let mut hi = 1e-3;
2261 while !reach(hi) {
2262 hi *= 1.5;
2263 if hi > PI {
2264 return Err(refuse("gear_input", "The addendum curve does not close.".into()));
2265 }
2266 }
2267 let mut lo = 0.0;
2268 for _ in 0..200 {
2269 let mid = 0.5 * (lo + hi);
2270 if reach(mid) { hi = mid } else { lo = mid }
2271 }
2272 let end = epi(hi);
2273 let pointed = polar_angle(end) >= -1e-9;
2276 let phi_end = if pointed {
2277 let (mut lo, mut hi) = (0.0, hi);
2278 for _ in 0..200 {
2279 let mid = 0.5 * (lo + hi);
2280 if polar_angle(epi(mid)) >= 0.0 { hi = mid } else { lo = mid }
2281 }
2282 hi
2283 } else {
2284 hi
2285 };
2286 let tolerance = GEAR_FIT_TOLERANCE * m;
2287 let right_add = fit_planar(&|phi| epi(phi), 0.0, phi_end, tolerance)?; let foot = [rf * (-psi).cos(), rf * (-psi).sin()];
2289 let pitch_point = [r * (-psi).cos(), r * (-psi).sin()];
2290 let mut tooth: Vec<(&'static str, NurbsCurve)> = vec![("R", line(foot, pitch_point)?), ("ER", right_add.clone())];
2291 let tip_angle = -polar_angle(epi(phi_end));
2292 if !pointed {
2293 tooth.push(("K", arc(ra, -tip_angle, tip_angle)?));
2294 }
2295 tooth.push(("EL", mirrored(&right_add).reversed().map_err(|e| refuse("gear_fit", e))?));
2296 tooth.push(("L", line([pitch_point[0], -pitch_point[1]], [foot[0], -foot[1]])?));
2297 tooth.push(("G", arc(rf, psi, tau - psi)?));
2298 let mut curves = Vec::with_capacity(tooth.len() * gear.teeth);
2299 for index in 0..gear.teeth {
2300 let angle = tau * index as f64;
2301 for (role, curve) in &tooth {
2302 curves.push(SectionCurve { curve: rotated(curve, angle), role, tooth: index });
2303 }
2304 }
2305 snap_junctions(&mut curves);
2306 let data = GearData {
2307 pitch_diameter: 2.0 * r,
2308 tip_diameter: 2.0 * radius_of(epi(phi_end)),
2309 root_diameter: 2.0 * rf,
2310 tooth_thickness: 2.0 * psi * r,
2311 ..GearData::default()
2312 };
2313 Ok(GearSection { curves, data })
2314}
2315
2316pub fn cycloidal_gear_solid(gear: &CycloidalGear) -> Result<(BrepSolid, Vec<String>, GearData), KernelRefusal> {
2318 let section = cycloidal_gear_section(gear)?;
2319 let solid = extrude_section(§ion, gear.width)?;
2320 let mut names: Vec<String> = section.curves.iter().map(SectionCurve::suffix).collect();
2321 names.push("F".into());
2322 names.push("B".into());
2323 Ok((solid, names, section.data))
2324}
2325