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