@rulecad/gears 0.3.4 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/core.mjs CHANGED
@@ -24,17 +24,72 @@ const TAU = 2 * Math.PI;
24
24
  * @type {Record<string, { value: number, unit: string, rule: string, kind: string }>}
25
25
  */
26
26
  export const DEFAULTS = {
27
- pressureAngle: { value: 20, unit: 'deg', rule: 'The standard pressure angle (ISO 53): stronger teeth than 14.5°, and the one tables and cutters use', kind: 'spec' },
28
- addendum: { value: 1, unit: '× module', rule: 'Tooth height above the pitch circle (ISO 53 basic rack)', kind: 'spec' },
29
- dedendum: { value: 1.25, unit: '× module', rule: 'Depth below the pitch circle: the addendum and 0.25 module of clearance under the mate\'s tip (ISO 53)', kind: 'spec' },
30
- rootFillet: { value: 0.38, unit: '× module', rule: 'The root fillet of the ISO 53 profile A rack: a rounded root is where a tooth stops cracking', kind: 'spec' },
31
- tipRound: { value: 0.1, unit: '× module', rule: 'A tip a printer can draw: rounded about a quarter line at module 1, so no corner is left to the slicer', kind: 'estimate' },
32
- backlash: { value: 0.15, unit: 'mm', rule: 'Play between mating teeth, split between the two: FDM gear guides give 0.1 to 0.2 mm; measure it with the sampler plate', kind: 'estimate' },
33
- chamfer: { value: 0.3, unit: 'mm', rule: 'A chamfer round the bed face, so the first layer\'s squish (elephant\'s foot) doesn\'t widen the teeth there', kind: 'estimate' },
34
- efficiency: { value: 0.95, unit: 'per mesh', rule: 'Power a printed mesh passes on, dry: metal spur gears pass 98 to 99%, and dry plastic teeth rub more. Measure yours', kind: 'estimate' },
35
- module: { value: 0.8, unit: 'mm at a 0.4 mm nozzle', rule: 'The smallest module worth printing: twice the nozzle, so a tooth is three lines at the pitch circle', kind: 'estimate' },
36
- printGap: { value: 0.3, unit: 'mm', rule: 'The gap each side between gears printed in place, in mesh, that still prints apart: the X1C\'s print_gap. An estimate until the fit test plate measures it; the sampler plate\'s gears bound on pegs printed 0.105 mm clear each side, so it is no smaller than that', kind: 'estimate' },
37
- helix: { value: 30, unit: 'deg', rule: 'The helix angle of a herringbone printed in place: steep enough that the rings cannot walk off the planets, and each half prints at 30° from the layers', kind: 'default' },
27
+ pressureAngle: {
28
+ value: 20,
29
+ unit: 'deg',
30
+ rule: 'The standard pressure angle (ISO 53): stronger teeth than 14.5°, and the one tables and cutters use',
31
+ kind: 'spec',
32
+ },
33
+ addendum: {
34
+ value: 1,
35
+ unit: '× module',
36
+ rule: 'Tooth height above the pitch circle (ISO 53 basic rack)',
37
+ kind: 'spec',
38
+ },
39
+ dedendum: {
40
+ value: 1.25,
41
+ unit: '× module',
42
+ rule: "Depth below the pitch circle: the addendum and 0.25 module of clearance under the mate's tip (ISO 53)",
43
+ kind: 'spec',
44
+ },
45
+ rootFillet: {
46
+ value: 0.38,
47
+ unit: '× module',
48
+ rule: 'The root fillet of the ISO 53 profile A rack: a rounded root is where a tooth stops cracking',
49
+ kind: 'spec',
50
+ },
51
+ tipRound: {
52
+ value: 0.1,
53
+ unit: '× module',
54
+ rule: 'A tip a printer can draw: rounded about a quarter line at module 1, so no corner is left to the slicer',
55
+ kind: 'estimate',
56
+ },
57
+ backlash: {
58
+ value: 0.15,
59
+ unit: 'mm',
60
+ rule: 'Play between mating teeth, split between the two: FDM gear guides give 0.1 to 0.2 mm; measure it with the sampler plate',
61
+ kind: 'estimate',
62
+ },
63
+ chamfer: {
64
+ value: 0.3,
65
+ unit: 'mm',
66
+ rule: "A chamfer round the bed face, so the first layer's squish (elephant's foot) doesn't widen the teeth there",
67
+ kind: 'estimate',
68
+ },
69
+ efficiency: {
70
+ value: 0.95,
71
+ unit: 'per mesh',
72
+ rule: 'Power a printed mesh passes on, dry: metal spur gears pass 98 to 99%, and dry plastic teeth rub more. Measure yours',
73
+ kind: 'estimate',
74
+ },
75
+ module: {
76
+ value: 0.8,
77
+ unit: 'mm at a 0.4 mm nozzle',
78
+ rule: 'The smallest module worth printing: twice the nozzle, so a tooth is three lines at the pitch circle',
79
+ kind: 'estimate',
80
+ },
81
+ printGap: {
82
+ value: 0.3,
83
+ unit: 'mm',
84
+ rule: "The gap each side between gears printed in place, in mesh, that still prints apart: the X1C's print_gap. An estimate until the fit test plate measures it; the sampler plate's gears bound on pegs printed 0.105 mm clear each side, so it is no smaller than that",
85
+ kind: 'estimate',
86
+ },
87
+ helix: {
88
+ value: 30,
89
+ unit: 'deg',
90
+ rule: 'The helix angle of a herringbone printed in place: steep enough that the rings cannot walk off the planets, and each half prints at 30° from the layers',
91
+ kind: 'default',
92
+ },
38
93
  };
39
94
  const D = (k) => DEFAULTS[k].value;
40
95
 
@@ -43,29 +98,65 @@ const D = (k) => DEFAULTS[k].value;
43
98
  const isNum = (x) => typeof x === 'number' && Number.isFinite(x);
44
99
  const shown = (v) => (v === undefined ? 'nothing' : JSON.stringify(v));
45
100
  /** A size above 0, by name. */
46
- function size(what, k, v) { if (!(isNum(v) && v > 0)) throw new Error(`${what}: ${k} is a size above 0 (got ${shown(v)})`); return v; }
47
- function whole(what, k, v, least) { if (!(Number.isInteger(v) && v >= least)) throw new Error(`${what}: ${k} is a whole number of ${least} or more (got ${shown(v)})`); return v; }
48
- function between(what, k, v, lo, hi, unit = '') { if (!(isNum(v) && v >= lo && v <= hi)) throw new Error(`${what}: ${k} is a number from ${lo} to ${hi}${unit} (got ${shown(v)})`); return v; }
49
- function atLeast0(what, k, v) { if (!(isNum(v) && v >= 0)) throw new Error(`${what}: ${k} is 0 or more (got ${shown(v)})`); return v; }
101
+ function size(what, k, v) {
102
+ if (!(isNum(v) && v > 0)) throw new Error(`${what}: ${k} is a size above 0 (got ${shown(v)})`);
103
+ return v;
104
+ }
105
+ function whole(what, k, v, least) {
106
+ if (!(Number.isInteger(v) && v >= least))
107
+ throw new Error(`${what}: ${k} is a whole number of ${least} or more (got ${shown(v)})`);
108
+ return v;
109
+ }
110
+ function between(what, k, v, lo, hi, unit = '') {
111
+ if (!(isNum(v) && v >= lo && v <= hi))
112
+ throw new Error(`${what}: ${k} is a number from ${lo} to ${hi}${unit} (got ${shown(v)})`);
113
+ return v;
114
+ }
115
+ function atLeast0(what, k, v) {
116
+ if (!(isNum(v) && v >= 0)) throw new Error(`${what}: ${k} is 0 or more (got ${shown(v)})`);
117
+ return v;
118
+ }
50
119
 
51
120
  // The parameters every gear shares, checked and with their defaults
52
121
  function common(what, p) {
53
- if (!p || typeof p !== 'object') throw new Error(`${what}: give the gear's parameters as an object ({ module, teeth, … }), not ${shown(p)}`);
122
+ if (!p || typeof p !== 'object')
123
+ throw new Error(`${what}: give the gear's parameters as an object ({ module, teeth, … }), not ${shown(p)}`);
54
124
  const module = size(what, 'module', p.module);
55
125
  const pressureAngle = between(what, 'pressureAngle', p.pressureAngle ?? D('pressureAngle'), 10, 35, '°');
56
126
  const shift = between(what, 'shift', p.shift ?? 0, -1, 1.5, ' (times the module)');
57
127
  const backlash = atLeast0(what, 'backlash', p.backlash ?? D('backlash'));
58
128
  const addendum = between(what, 'addendum', p.addendum ?? D('addendum'), 0.5, 1.5, ' (times the module)');
59
- const dedendum = between(what, 'dedendum', p.dedendum ?? D('dedendum'), addendum, 2, ' (times the module, at least the addendum)');
129
+ const dedendum = between(
130
+ what,
131
+ 'dedendum',
132
+ p.dedendum ?? D('dedendum'),
133
+ addendum,
134
+ 2,
135
+ ' (times the module, at least the addendum)',
136
+ );
60
137
  const rootFillet = between(what, 'rootFillet', p.rootFillet ?? D('rootFillet'), 0, 0.6, ' (times the module)');
61
138
  const tipRound = between(what, 'tipRound', p.tipRound ?? D('tipRound'), 0, 0.4, ' (times the module)');
62
139
  // Helical teeth: the spur profile turned along the width by the helix angle (the module and pressure angle are the
63
140
  // transverse ones, in the gear's own plane, so a helical gear's centre distance is a spur gear's)
64
141
  const helix = between(what, 'helix', p.helix ?? 0, 0, 45, '°');
65
- if (p.hand != null && p.hand !== 'right' && p.hand !== 'left') throw new Error(`${what}: hand is "right" or "left" (got ${shown(p.hand)})`);
66
- if (p.herringbone != null && typeof p.herringbone !== 'boolean') throw new Error(`${what}: herringbone is true or false (got ${shown(p.herringbone)})`);
142
+ if (p.hand != null && p.hand !== 'right' && p.hand !== 'left')
143
+ throw new Error(`${what}: hand is "right" or "left" (got ${shown(p.hand)})`);
144
+ if (p.herringbone != null && typeof p.herringbone !== 'boolean')
145
+ throw new Error(`${what}: herringbone is true or false (got ${shown(p.herringbone)})`);
67
146
  if (p.herringbone && !helix) throw new Error(`${what}: a herringbone needs a helix angle (say helix: 30)`);
68
- return { module, pressureAngle, shift, backlash, addendum, dedendum, rootFillet, tipRound, helix, hand: p.hand ?? 'right', herringbone: !!p.herringbone };
147
+ return {
148
+ module,
149
+ pressureAngle,
150
+ shift,
151
+ backlash,
152
+ addendum,
153
+ dedendum,
154
+ rootFillet,
155
+ tipRound,
156
+ helix,
157
+ hand: p.hand ?? 'right',
158
+ herringbone: !!p.herringbone,
159
+ };
69
160
  }
70
161
 
71
162
  // ---------- the numbers ----------
@@ -94,26 +185,54 @@ const halfAt = (s, r, rb, rho) => s / (2 * r) + inv(Math.acos(rb / r)) - inv(Mat
94
185
  * @returns {GearModel}
95
186
  */
96
187
  export function gearModel(p) {
97
- const what = 'gearModel', c = common(what, p), teeth = whole(what, 'teeth', p?.teeth, 6);
98
- const { module: m, pressureAngle, shift: x, backlash } = c, a = pressureAngle * DEG;
188
+ const what = 'gearModel',
189
+ c = common(what, p),
190
+ teeth = whole(what, 'teeth', p?.teeth, 6);
191
+ const { module: m, pressureAngle, shift: x, backlash } = c,
192
+ a = pressureAngle * DEG;
99
193
  // Undercut: the basic rack's tip line reaches under the base circle when z sin²α / 2 < addendum − x (a whisker of
100
194
  // slack, so 17 teeth at 20° pass, as tables have it)
101
195
  const need = c.addendum - (teeth * Math.sin(a) ** 2) / 2;
102
196
  if (x < need - 0.01) {
103
- throw new Error(`${what}: ${teeth} teeth at ${pressureAngle}° are undercut (the mate's tip would cut under the base circle, or the tooth be cut away there): give a profile shift of at least ${(Math.ceil(need * 100) / 100).toFixed(2)} (shift: ${(Math.ceil(need * 100) / 100).toFixed(2)}), or ${Math.ceil((2 * (c.addendum - x)) / Math.sin(a) ** 2 - 0.1)} teeth or more`);
197
+ throw new Error(
198
+ `${what}: ${teeth} teeth at ${pressureAngle}° are undercut (the mate's tip would cut under the base circle, or the tooth be cut away there): give a profile shift of at least ${(Math.ceil(need * 100) / 100).toFixed(2)} (shift: ${(Math.ceil(need * 100) / 100).toFixed(2)}), or ${Math.ceil((2 * (c.addendum - x)) / Math.sin(a) ** 2 - 0.1)} teeth or more`,
199
+ );
104
200
  }
105
- const r = (m * teeth) / 2, rb = r * Math.cos(a), ra = r + m * (c.addendum + x), rf = r - m * (c.dedendum - x);
201
+ const r = (m * teeth) / 2,
202
+ rb = r * Math.cos(a),
203
+ ra = r + m * (c.addendum + x),
204
+ rf = r - m * (c.dedendum - x);
106
205
  const s = m * (Math.PI / 2 + 2 * x * Math.tan(a)) - backlash / 2;
107
- if (!(s > 0)) throw new Error(`${what}: a backlash of ${backlash} mm leaves no tooth (at most ${(2 * m * (Math.PI / 2 + 2 * x * Math.tan(a))).toFixed(2)} mm)`);
206
+ if (!(s > 0))
207
+ throw new Error(
208
+ `${what}: a backlash of ${backlash} mm leaves no tooth (at most ${(2 * m * (Math.PI / 2 + 2 * x * Math.tan(a))).toFixed(2)} mm)`,
209
+ );
108
210
  const tipHalf = halfAt(s, r, rb, ra);
109
- if (!(tipHalf > 0)) throw new Error(`${what}: the teeth come to a point before the tip circle: less profile shift (${x} now), or a smaller addendum`);
211
+ if (!(tipHalf > 0))
212
+ throw new Error(
213
+ `${what}: the teeth come to a point before the tip circle: less profile shift (${x} now), or a smaller addendum`,
214
+ );
110
215
  const rootHalf = halfAt(s, r, rb, Math.max(rf, rb));
111
216
  return {
112
- kind: 'external', module: m, teeth, pressureAngle, shift: x, backlash,
113
- helix: c.helix, hand: c.hand, herringbone: c.herringbone, thrust: c.herringbone ? 0 : Math.tan(c.helix * DEG),
114
- pitch: 2 * r, base: 2 * rb, tip: 2 * ra, root: 2 * rf, thickness: s,
115
- circularPitch: Math.PI * m, basePitch: Math.PI * m * Math.cos(a),
116
- topLand: 2 * ra * Math.sin(tipHalf), rootThickness: 2 * Math.max(rf, rb) * Math.sin(rootHalf),
217
+ kind: 'external',
218
+ module: m,
219
+ teeth,
220
+ pressureAngle,
221
+ shift: x,
222
+ backlash,
223
+ helix: c.helix,
224
+ hand: c.hand,
225
+ herringbone: c.herringbone,
226
+ thrust: c.herringbone ? 0 : Math.tan(c.helix * DEG),
227
+ pitch: 2 * r,
228
+ base: 2 * rb,
229
+ tip: 2 * ra,
230
+ root: 2 * rf,
231
+ thickness: s,
232
+ circularPitch: Math.PI * m,
233
+ basePitch: Math.PI * m * Math.cos(a),
234
+ topLand: 2 * ra * Math.sin(tipHalf),
235
+ rootThickness: 2 * Math.max(rf, rb) * Math.sin(rootHalf),
117
236
  rack: { pressureAngle, addendum: c.addendum, dedendum: c.dedendum, rootFillet: c.rootFillet, tipRound: c.tipRound },
118
237
  };
119
238
  }
@@ -125,23 +244,49 @@ export function gearModel(p) {
125
244
  * @returns {GearModel & { rim: number, space: number }}
126
245
  */
127
246
  export function internalModel(p) {
128
- const what = 'internalModel', c = common(what, p), teeth = whole(what, 'teeth', p?.teeth, 12);
129
- const { module: m, pressureAngle, shift: x, backlash } = c, a = pressureAngle * DEG;
130
- const r = (m * teeth) / 2, rb = r * Math.cos(a), ra = r - m * (c.addendum - x), rf = r + m * (c.dedendum + x);
247
+ const what = 'internalModel',
248
+ c = common(what, p),
249
+ teeth = whole(what, 'teeth', p?.teeth, 12);
250
+ const { module: m, pressureAngle, shift: x, backlash } = c,
251
+ a = pressureAngle * DEG;
252
+ const r = (m * teeth) / 2,
253
+ rb = r * Math.cos(a),
254
+ ra = r - m * (c.addendum - x),
255
+ rf = r + m * (c.dedendum + x);
131
256
  // the space on the pitch circle: π m minus the tooth (m (π/2 − 2x tan α)), widened by this gear's half of the backlash
132
- const e = m * (Math.PI / 2 + 2 * x * Math.tan(a)) + backlash / 2, s = Math.PI * m - e;
257
+ const e = m * (Math.PI / 2 + 2 * x * Math.tan(a)) + backlash / 2,
258
+ s = Math.PI * m - e;
133
259
  if (!(s > 0)) throw new Error(`${what}: a backlash of ${backlash} mm leaves no tooth`);
134
260
  const rim = p.rim ?? 2 * rf + 6 * m;
135
- if (!(isNum(rim) && rim > 2 * rf + 2 * m)) throw new Error(`${what}: rim is the ring's outer diameter, more than the root diameter and two modules (${(2 * rf + 2 * m).toFixed(2)} mm; got ${shown(p.rim)})`);
261
+ if (!(isNum(rim) && rim > 2 * rf + 2 * m))
262
+ throw new Error(
263
+ `${what}: rim is the ring's outer diameter, more than the root diameter and two modules (${(2 * rf + 2 * m).toFixed(2)} mm; got ${shown(p.rim)})`,
264
+ );
136
265
  // An internal tooth's width at a radius is the pitch angle less the space's
137
266
  const toothHalf = (rho) => Math.PI / teeth - halfAt(e, r, rb, rho);
138
267
  if (!(toothHalf(ra) > 0)) throw new Error(`${what}: the teeth come to a point at the tip circle: less profile shift`);
139
268
  return {
140
- kind: 'internal', module: m, teeth, pressureAngle, shift: x, backlash,
141
- helix: c.helix, hand: c.hand, herringbone: c.herringbone, thrust: c.herringbone ? 0 : Math.tan(c.helix * DEG),
142
- pitch: 2 * r, base: 2 * rb, tip: 2 * ra, root: 2 * rf, thickness: s, space: e, rim,
143
- circularPitch: Math.PI * m, basePitch: Math.PI * m * Math.cos(a),
144
- topLand: 2 * Math.max(ra, rb) * Math.sin(toothHalf(Math.max(ra, rb))), rootThickness: 2 * rf * Math.sin(toothHalf(rf)),
269
+ kind: 'internal',
270
+ module: m,
271
+ teeth,
272
+ pressureAngle,
273
+ shift: x,
274
+ backlash,
275
+ helix: c.helix,
276
+ hand: c.hand,
277
+ herringbone: c.herringbone,
278
+ thrust: c.herringbone ? 0 : Math.tan(c.helix * DEG),
279
+ pitch: 2 * r,
280
+ base: 2 * rb,
281
+ tip: 2 * ra,
282
+ root: 2 * rf,
283
+ thickness: s,
284
+ space: e,
285
+ rim,
286
+ circularPitch: Math.PI * m,
287
+ basePitch: Math.PI * m * Math.cos(a),
288
+ topLand: 2 * Math.max(ra, rb) * Math.sin(toothHalf(Math.max(ra, rb))),
289
+ rootThickness: 2 * rf * Math.sin(toothHalf(rf)),
145
290
  rack: { pressureAngle, addendum: c.addendum, dedendum: c.dedendum, rootFillet: c.rootFillet, tipRound: c.tipRound },
146
291
  };
147
292
  }
@@ -152,20 +297,38 @@ export function internalModel(p) {
152
297
  * @param {GearSpec & { height?: number }} p
153
298
  */
154
299
  export function rackModel(p) {
155
- const what = 'rackModel', c = common(what, p), teeth = whole(what, 'teeth', p?.teeth, 1);
156
- const { module: m, pressureAngle, backlash } = c, a = pressureAngle * DEG;
157
- if (p.shift) throw new Error(`${what}: a rack has no profile shift (shift the pinion instead; got ${shown(p.shift)})`);
300
+ const what = 'rackModel',
301
+ c = common(what, p),
302
+ teeth = whole(what, 'teeth', p?.teeth, 1);
303
+ const { module: m, pressureAngle, backlash } = c,
304
+ a = pressureAngle * DEG;
305
+ if (p.shift)
306
+ throw new Error(`${what}: a rack has no profile shift (shift the pinion instead; got ${shown(p.shift)})`);
158
307
  const height = p.height === undefined ? 3 * m : size(what, 'height', p.height);
159
308
  const s = (Math.PI * m) / 2 - backlash / 2;
160
309
  if (!(s > 0)) throw new Error(`${what}: a backlash of ${backlash} mm leaves no tooth`);
161
310
  const tipHalf = s / 2 - m * c.addendum * Math.tan(a);
162
311
  if (!(tipHalf > 0)) throw new Error(`${what}: the teeth come to a point: a smaller addendum or pressure angle`);
163
312
  return {
164
- kind: 'rack', module: m, teeth, pressureAngle, shift: 0, backlash, height, thickness: s,
165
- helix: c.helix, hand: c.hand, herringbone: c.herringbone, thrust: c.herringbone ? 0 : Math.tan(c.helix * DEG),
166
- length: teeth * Math.PI * m, tipLine: m * c.addendum, rootLine: -m * c.dedendum,
167
- circularPitch: Math.PI * m, basePitch: Math.PI * m * Math.cos(a),
168
- topLand: 2 * tipHalf, rootThickness: s + 2 * m * c.dedendum * Math.tan(a),
313
+ kind: 'rack',
314
+ module: m,
315
+ teeth,
316
+ pressureAngle,
317
+ shift: 0,
318
+ backlash,
319
+ height,
320
+ thickness: s,
321
+ helix: c.helix,
322
+ hand: c.hand,
323
+ herringbone: c.herringbone,
324
+ thrust: c.herringbone ? 0 : Math.tan(c.helix * DEG),
325
+ length: teeth * Math.PI * m,
326
+ tipLine: m * c.addendum,
327
+ rootLine: -m * c.dedendum,
328
+ circularPitch: Math.PI * m,
329
+ basePitch: Math.PI * m * Math.cos(a),
330
+ topLand: 2 * tipHalf,
331
+ rootThickness: s + 2 * m * c.dedendum * Math.tan(a),
169
332
  rack: { pressureAngle, addendum: c.addendum, dedendum: c.dedendum, rootFillet: c.rootFillet, tipRound: c.tipRound },
170
333
  };
171
334
  }
@@ -179,30 +342,47 @@ const N = { root: 3, fillet: 6, flank: 14, round: 4, tip: 3 };
179
342
  const dist = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1]);
180
343
  // The nearest point of the flank to c: a scan, then a golden-section search round the best
181
344
  function nearest(flank, q0, q1, c) {
182
- let best = q0, bd = Infinity;
183
- for (let i = 0; i <= 48; i++) { const q = q0 + ((q1 - q0) * i) / 48, d = dist(flank(q), c); if (d < bd) { bd = d; best = q; } }
184
- let lo = Math.max(q0, best - (q1 - q0) / 48), hi = Math.min(q1, best + (q1 - q0) / 48);
345
+ let best = q0,
346
+ bd = Infinity;
347
+ for (let i = 0; i <= 48; i++) {
348
+ const q = q0 + ((q1 - q0) * i) / 48,
349
+ d = dist(flank(q), c);
350
+ if (d < bd) {
351
+ bd = d;
352
+ best = q;
353
+ }
354
+ }
355
+ let lo = Math.max(q0, best - (q1 - q0) / 48),
356
+ hi = Math.min(q1, best + (q1 - q0) / 48);
185
357
  const g = (Math.sqrt(5) - 1) / 2;
186
358
  for (let i = 0; i < 40; i++) {
187
- const a = hi - g * (hi - lo), b = lo + g * (hi - lo);
188
- if (dist(flank(a), c) < dist(flank(b), c)) hi = b; else lo = a;
359
+ const a = hi - g * (hi - lo),
360
+ b = lo + g * (hi - lo);
361
+ if (dist(flank(a), c) < dist(flank(b), c)) hi = b;
362
+ else lo = a;
189
363
  }
190
364
  const q = (lo + hi) / 2;
191
365
  return { q, d: dist(flank(q), c) };
192
366
  }
193
367
  // Points on an arc about c from a to b (the short way), n of them, a included and b not
194
368
  function arc(c, a, b, n) {
195
- const r = dist(a, c), a0 = Math.atan2(a[1] - c[1], a[0] - c[0]);
369
+ const r = dist(a, c),
370
+ a0 = Math.atan2(a[1] - c[1], a[0] - c[0]);
196
371
  let d = Math.atan2(b[1] - c[1], b[0] - c[0]) - a0;
197
372
  while (d > Math.PI) d -= TAU;
198
373
  while (d < -Math.PI) d += TAU;
199
- return Array.from({ length: n }, (_, i) => { const t = a0 + (d * i) / n; return [c[0] + r * Math.cos(t), c[1] + r * Math.sin(t)]; });
374
+ return Array.from({ length: n }, (_, i) => {
375
+ const t = a0 + (d * i) / n;
376
+ return [c[0] + r * Math.cos(t), c[1] + r * Math.sin(t)];
377
+ });
200
378
  }
201
379
  // n points along a curve from q0 to q1, evenly spaced along its length, q0 included and q1 not
202
380
  function along(curve, q0, q1, n) {
203
- const fine = Array.from({ length: 121 }, (_, i) => curve(q0 + ((q1 - q0) * i) / 120)), at = [0];
381
+ const fine = Array.from({ length: 121 }, (_, i) => curve(q0 + ((q1 - q0) * i) / 120)),
382
+ at = [0];
204
383
  for (let i = 1; i < fine.length; i++) at.push(at[i - 1] + dist(fine[i], fine[i - 1]));
205
- const total = at.at(-1), out = [];
384
+ const total = at.at(-1),
385
+ out = [];
206
386
  for (let k = 0, j = 0; k < n; k++) {
207
387
  const want = (total * k) / n;
208
388
  while (j < fine.length - 2 && at[j + 1] < want) j++;
@@ -223,26 +403,41 @@ function half(g) {
223
403
  const level = base + sign * rho;
224
404
  if (rho < 1e-4 || tries > 40) return null;
225
405
  if (level <= g.rootLevel || level >= g.tipLevel) continue;
226
- const tFlank = g.flankT(level), lim = tooth ? tFlank + (tMid - tFlank) * 0.85 : tMid + (tFlank - tMid) * 0.05;
406
+ const tFlank = g.flankT(level),
407
+ lim = tooth ? tFlank + (tMid - tFlank) * 0.85 : tMid + (tFlank - tMid) * 0.05;
227
408
  const d = (t) => nearest(g.flank, g.q0, g.q1, g.point(t, level)).d;
228
409
  if (d(lim) < rho) continue; // no room: smaller
229
- let lo = tFlank, hi = lim; // d(lo) ≈ 0, d(hi) ≥ rho
230
- for (let i = 0; i < 60; i++) { const mid = (lo + hi) / 2; if (d(mid) < rho) lo = mid; else hi = mid; }
231
- const c = g.point(hi, level), n = nearest(g.flank, g.q0, g.q1, c);
410
+ let lo = tFlank,
411
+ hi = lim; // d(lo) ≈ 0, d(hi) ≥ rho
412
+ for (let i = 0; i < 60; i++) {
413
+ const mid = (lo + hi) / 2;
414
+ if (d(mid) < rho) lo = mid;
415
+ else hi = mid;
416
+ }
417
+ const c = g.point(hi, level),
418
+ n = nearest(g.flank, g.q0, g.q1, c);
232
419
  return { rho, c, q: n.q, touch: g.flank(n.q), foot: g.point(hi, base), t: hi };
233
420
  }
234
421
  };
235
422
  const root = g.fillet > 0 ? fit(g.fillet, g.rootLevel, 1, g.t0, false) : null;
236
423
  const tip = g.round > 0 ? fit(g.round, g.tipLevel, -1, 0, true) : null;
237
424
  // without a fillet (or a round), the corner itself
238
- const rootQ = root ? root.q : g.q0, tipQ = tip ? tip.q : g.q1;
239
- const rootFoot = root ? root.foot : g.flank(g.q0), tipFoot = tip ? tip.foot : g.flank(g.q1);
240
- const rootT = root ? root.t : g.flankT(g.rootLevel), tipT = tip ? tip.t : g.flankT(g.tipLevel);
425
+ const rootQ = root ? root.q : g.q0,
426
+ tipQ = tip ? tip.q : g.q1;
427
+ const rootFoot = root ? root.foot : g.flank(g.q0);
428
+ const rootT = root ? root.t : g.flankT(g.rootLevel),
429
+ tipT = tip ? tip.t : g.flankT(g.tipLevel);
241
430
  const pts = [
242
431
  ...Array.from({ length: N.root }, (_, i) => g.point(g.t0 + ((rootT - g.t0) * i) / N.root, g.rootLevel)),
243
- ...(root ? arc(root.c, root.foot, root.touch, N.fillet) : Array(N.fillet).fill(rootFoot).map((p, i) => g.flank(g.q0 + ((rootQ - g.q0) * i) / N.fillet))),
432
+ ...(root
433
+ ? arc(root.c, root.foot, root.touch, N.fillet)
434
+ : Array(N.fillet)
435
+ .fill(rootFoot)
436
+ .map((p, i) => g.flank(g.q0 + ((rootQ - g.q0) * i) / N.fillet))),
244
437
  ...along(g.flank, rootQ, tipQ, N.flank),
245
- ...(tip ? arc(tip.c, tip.touch, tip.foot, N.round) : Array.from({ length: N.round }, (_, i) => g.flank(tipQ + ((g.q1 - tipQ) * i) / N.round))),
438
+ ...(tip
439
+ ? arc(tip.c, tip.touch, tip.foot, N.round)
440
+ : Array.from({ length: N.round }, (_, i) => g.flank(tipQ + ((g.q1 - tipQ) * i) / N.round))),
246
441
  ...Array.from({ length: N.tip }, (_, i) => g.point(tipT + ((0 - tipT) * i) / N.tip, g.tipLevel)),
247
442
  ];
248
443
  return { pts, fillet: root ? root.rho : 0, round: tip ? tip.rho : 0, wantFillet: g.fillet, wantRound: g.round };
@@ -251,25 +446,53 @@ function half(g) {
251
446
  // A gear's (or an internal gear's spaces') outline: one loop, counter-clockwise, tooth 0 on +x. grow moves it outwards
252
447
  // by that much along its normal (an involute's offset is the same involute, thinner by grow / rb each side).
253
448
  function loop({ teeth: z, thickness: s, r, rb, ra, rf, fillet, round, grow = 0 }) {
254
- s += (2 * grow * r) / rb; ra += grow; rf += grow;
255
- fillet = Math.max(1e-3, fillet - grow); round = Math.max(1e-3, round + grow);
256
- const hAt = (rho) => halfAt(s, r, rb, rho), rLow = rf, rHigh = ra;
257
- const flank = (rho) => { const h = hAt(rho); return [rho * Math.cos(h), -rho * Math.sin(h)]; };
449
+ s += (2 * grow * r) / rb;
450
+ ra += grow;
451
+ rf += grow;
452
+ fillet = Math.max(1e-3, fillet - grow);
453
+ round = Math.max(1e-3, round + grow);
454
+ const hAt = (rho) => halfAt(s, r, rb, rho),
455
+ rLow = rf,
456
+ rHigh = ra;
457
+ const flank = (rho) => {
458
+ const h = hAt(rho);
459
+ return [rho * Math.cos(h), -rho * Math.sin(h)];
460
+ };
258
461
  const h = half({
259
- t0: -Math.PI / z, rootLevel: rf, tipLevel: ra, q0: rLow, q1: rHigh, flank, fillet, round,
260
- flankT: (rho) => -hAt(rho), point: (t, rho) => [rho * Math.cos(t), rho * Math.sin(t)],
462
+ t0: -Math.PI / z,
463
+ rootLevel: rf,
464
+ tipLevel: ra,
465
+ q0: rLow,
466
+ q1: rHigh,
467
+ flank,
468
+ fillet,
469
+ round,
470
+ flankT: (rho) => -hAt(rho),
471
+ point: (t, rho) => [rho * Math.cos(t), rho * Math.sin(t)],
261
472
  });
262
- const tooth = [...h.pts, [ra, 0], ...h.pts.slice(1).reverse().map(([x, y]) => [x, -y])];
473
+ const tooth = [
474
+ ...h.pts,
475
+ [ra, 0],
476
+ ...h.pts
477
+ .slice(1)
478
+ .reverse()
479
+ .map(([x, y]) => [x, -y]),
480
+ ];
263
481
  if (!Number.isInteger(z)) return { tooth, fillet: h.fillet, round: h.round };
264
482
  const out = [];
265
483
  for (let k = 0; k < z; k++) {
266
- const c = Math.cos((TAU * k) / z), sn = Math.sin((TAU * k) / z);
484
+ const c = Math.cos((TAU * k) / z),
485
+ sn = Math.sin((TAU * k) / z);
267
486
  for (const [x, y] of tooth) out.push([x * c - y * sn, x * sn + y * c]);
268
487
  }
269
488
  return { points: out, fillet: h.fillet, round: h.round };
270
489
  }
271
490
 
272
- const circle = (d, n, grow = 0) => Array.from({ length: n }, (_, i) => [((d / 2 + grow) * Math.cos((TAU * i) / n)), ((d / 2 + grow) * Math.sin((TAU * i) / n))]);
491
+ const circle = (d, n, grow = 0) =>
492
+ Array.from({ length: n }, (_, i) => [
493
+ (d / 2 + grow) * Math.cos((TAU * i) / n),
494
+ (d / 2 + grow) * Math.sin((TAU * i) / n),
495
+ ]);
273
496
  // A bore: a circle, or with a flat (a D shape) the points past the flat brought onto it. grow: outwards, into the hole.
274
497
  function bore(d, flat, grow = 0) {
275
498
  const pts = circle(d, 48, grow);
@@ -286,13 +509,29 @@ const reversed = (pts) => [...pts].reverse();
286
509
  * @param {number} [grow] outwards along the outline's normal, mm (negative: inwards)
287
510
  */
288
511
  export function spurProfile(p, grow = 0) {
289
- const g = gearModel(p), r = g.pitch / 2, m = g.module;
290
- const l = loop({ teeth: g.teeth, thickness: g.thickness, r, rb: g.base / 2, ra: g.tip / 2, rf: g.root / 2, fillet: g.rack.rootFillet * m, round: g.rack.tipRound * m, grow });
512
+ const g = gearModel(p),
513
+ r = g.pitch / 2,
514
+ m = g.module;
515
+ const l = loop({
516
+ teeth: g.teeth,
517
+ thickness: g.thickness,
518
+ r,
519
+ rb: g.base / 2,
520
+ ra: g.tip / 2,
521
+ rf: g.root / 2,
522
+ fillet: g.rack.rootFillet * m,
523
+ round: g.rack.tipRound * m,
524
+ grow,
525
+ });
291
526
  const loops = [l.points];
292
527
  if (p.bore != null) {
293
528
  size('spur', 'bore', p.bore);
294
- if (p.bore > g.root - 4 * m) throw new Error(`spur: a bore of ${p.bore} mm leaves under two modules of web under the teeth (at most ${(g.root - 4 * m).toFixed(2)} mm)`);
295
- if (p.flat != null && !(size('spur', 'flat', p.flat) < p.bore / 2)) throw new Error(`spur: flat is how deep the bore's flat cuts, under half the bore (got ${p.flat})`);
529
+ if (p.bore > g.root - 4 * m)
530
+ throw new Error(
531
+ `spur: a bore of ${p.bore} mm leaves under two modules of web under the teeth (at most ${(g.root - 4 * m).toFixed(2)} mm)`,
532
+ );
533
+ if (p.flat != null && !(size('spur', 'flat', p.flat) < p.bore / 2))
534
+ throw new Error(`spur: flat is how deep the bore's flat cuts, under half the bore (got ${p.flat})`);
296
535
  loops.push(reversed(bore(p.bore, p.flat, -grow)));
297
536
  }
298
537
  return { loops, fillet: l.fillet, round: l.round, model: g };
@@ -300,27 +539,60 @@ export function spurProfile(p, grow = 0) {
300
539
 
301
540
  /** An internal gear's outline: the rim (counter-clockwise), then the teeth's inner outline (clockwise). */
302
541
  export function internalProfile(p, grow = 0) {
303
- const g = internalModel(p), r = g.pitch / 2, m = g.module;
542
+ const g = internalModel(p),
543
+ r = g.pitch / 2,
544
+ m = g.module;
304
545
  // the spaces, drawn as an outer gear's teeth: their "tips" are the ring's roots (the ring's root fillet there), their
305
546
  // "roots" the ring's tips (its round there). Growing the ring is shrinking the spaces.
306
- const l = loop({ teeth: g.teeth, thickness: g.space, r, rb: g.base / 2, ra: g.root / 2, rf: g.tip / 2, fillet: g.rack.tipRound * m, round: g.rack.rootFillet * m, grow: -grow });
547
+ const l = loop({
548
+ teeth: g.teeth,
549
+ thickness: g.space,
550
+ r,
551
+ rb: g.base / 2,
552
+ ra: g.root / 2,
553
+ rf: g.tip / 2,
554
+ fillet: g.rack.tipRound * m,
555
+ round: g.rack.rootFillet * m,
556
+ grow: -grow,
557
+ });
307
558
  // the ring's tooth 0 on +x: the spaces' loop has a space on +x, so turn it half a pitch
308
- const c = Math.cos(Math.PI / g.teeth), s = Math.sin(Math.PI / g.teeth), turned = l.points.map(([x, y]) => [x * c - y * s, x * s + y * c]);
559
+ const c = Math.cos(Math.PI / g.teeth),
560
+ s = Math.sin(Math.PI / g.teeth),
561
+ turned = l.points.map(([x, y]) => [x * c - y * s, x * s + y * c]);
309
562
  return { loops: [circle(g.rim, 96, grow), reversed(turned)], fillet: l.round, round: l.fillet, model: g };
310
563
  }
311
564
 
312
565
  /** A rack's outline: one loop, counter-clockwise, its pitch line on y = 0, teeth up +y from x = 0. */
313
566
  export function rackProfile(p, grow = 0) {
314
- const g = rackModel(p), m = g.module, a = g.pressureAngle * DEG, pitch = Math.PI * m;
315
- const s = g.thickness + (2 * grow) / Math.cos(a), yt = g.tipLine + grow, yr = g.rootLine + grow;
567
+ const g = rackModel(p),
568
+ m = g.module,
569
+ a = g.pressureAngle * DEG,
570
+ pitch = Math.PI * m;
571
+ const s = g.thickness + (2 * grow) / Math.cos(a),
572
+ yt = g.tipLine + grow,
573
+ yr = g.rootLine + grow;
316
574
  const w = (y) => s / 2 - y * Math.tan(a); // half the tooth's width at height y
317
575
  const flank = (y) => [-w(y), y];
318
576
  const h = half({
319
- t0: -pitch / 2, rootLevel: yr, tipLevel: yt, q0: yr, q1: yt, flank,
320
- fillet: Math.max(1e-3, g.rack.rootFillet * m - grow), round: Math.max(1e-3, g.rack.tipRound * m + grow),
321
- flankT: (y) => -w(y), point: (t, y) => [t, y],
577
+ t0: -pitch / 2,
578
+ rootLevel: yr,
579
+ tipLevel: yt,
580
+ q0: yr,
581
+ q1: yt,
582
+ flank,
583
+ fillet: Math.max(1e-3, g.rack.rootFillet * m - grow),
584
+ round: Math.max(1e-3, g.rack.tipRound * m + grow),
585
+ flankT: (y) => -w(y),
586
+ point: (t, y) => [t, y],
322
587
  });
323
- const tooth = [...h.pts, [0, yt], ...h.pts.slice(1).reverse().map(([x, y]) => [-x, y])];
588
+ const tooth = [
589
+ ...h.pts,
590
+ [0, yt],
591
+ ...h.pts
592
+ .slice(1)
593
+ .reverse()
594
+ .map(([x, y]) => [-x, y]),
595
+ ];
324
596
  const top = [];
325
597
  for (let k = 0; k < g.teeth; k++) for (const [x, y] of tooth) top.push([x + (k + 0.5) * pitch, y]);
326
598
  top.push([g.length, yr]);
@@ -334,20 +606,31 @@ export function rackProfile(p, grow = 0) {
334
606
  // (a helix), all with the same points, so the walls join point to point. Caps are triangulated with their holes.
335
607
  function loft(profile, width, { chamfer, twist, slide, scale }) {
336
608
  const [bottom, top] = Array.isArray(chamfer) ? chamfer : [chamfer, 0];
337
- if (bottom + top >= width) throw new Error(`the chamfers (${bottom} and ${top} mm) are as tall as the gear (${width} mm)`);
609
+ if (bottom + top >= width)
610
+ throw new Error(`the chamfers (${bottom} and ${top} mm) are as tall as the gear (${width} mm)`);
338
611
  // heights: the chamfers' ends, and for a twist enough between that no slice turns more than a degree or so
339
612
  const zs = [0, ...(bottom > 0 ? [bottom] : []), ...(top > 0 ? [width - top] : []), width];
340
613
  if (twist) {
341
- const most = Math.max(...[0, 0.25, 0.5, 0.75, 1].map((f) => Math.abs(twist(width * f)))), n = Math.ceil(most / (1.5 * DEG));
614
+ const most = Math.max(...[0, 0.25, 0.5, 0.75, 1].map((f) => Math.abs(twist(width * f)))),
615
+ n = Math.ceil(most / (1.5 * DEG));
342
616
  for (let i = 1; i < n; i++) zs.push((width * i) / n);
343
617
  zs.push(width / 2); // (a herringbone's apex)
344
618
  }
345
- if (slide) { const n = Math.ceil(width / 0.5); for (let i = 1; i < n; i++) zs.push((width * i) / n); zs.push(width / 2); }
619
+ if (slide) {
620
+ const n = Math.ceil(width / 0.5);
621
+ for (let i = 1; i < n; i++) zs.push((width * i) / n);
622
+ zs.push(width / 2);
623
+ }
346
624
  if (scale) for (let i = 1; i < 8; i++) zs.push((width * i) / 8); // (straight lines toward the apex: a few slices keep the caps' triangles sound)
347
625
  const heights = [...new Set(zs.map((z) => +z.toFixed(9)))].sort((x, y) => x - y);
348
626
  const slices = heights.map((z) => {
349
627
  const grow = z < bottom ? -(bottom - z) : z > width - top ? -(z - (width - top)) : 0;
350
- const loops = profile(grow, z), turn = twist ? twist(z) : 0, k = scale ? scale(z) : 1, c = Math.cos(turn) * k, s = Math.sin(turn) * k, dx = slide ? slide(z) : 0;
628
+ const loops = profile(grow, z),
629
+ turn = twist ? twist(z) : 0,
630
+ k = scale ? scale(z) : 1,
631
+ c = Math.cos(turn) * k,
632
+ s = Math.sin(turn) * k,
633
+ dx = slide ? slide(z) : 0;
351
634
  const at = (p) => [p[0] * c - p[1] * s + dx, p[0] * s + p[1] * c];
352
635
  const sides = loops.flatMap((pts) => pts.map((p, i) => [at(p), at(pts[(i + 1) % pts.length])]));
353
636
  return slice.transform(mat4.fromTranslation(mat4.create(), [0, 0, z]), slice.fromSides(sides));
@@ -363,7 +646,8 @@ function loft(profile, width, { chamfer, twist, slide, scale }) {
363
646
  * @returns {object} a JSCAD geom3
364
647
  */
365
648
  export function spur(p) {
366
- const width = size('spur', 'width', p?.width), chamfer = chamfers('spur', p, width);
649
+ const width = size('spur', 'width', p?.width),
650
+ chamfer = chamfers('spur', p, width);
367
651
  const { model: g } = spurProfile(p); // (refuses here, before any slicing)
368
652
  return loft((grow) => spurProfile(p, grow).loops, width, { chamfer, twist: twistOf(g, width) });
369
653
  }
@@ -373,40 +657,53 @@ export function spur(p) {
373
657
  // ring, or its rack, of the same hand.
374
658
  function twistOf(g, width) {
375
659
  if (!g.helix) return null;
376
- const k = (g.hand === 'left' ? -1 : 1) * Math.tan(g.helix * DEG) / (g.pitch / 2);
660
+ const k = ((g.hand === 'left' ? -1 : 1) * Math.tan(g.helix * DEG)) / (g.pitch / 2);
377
661
  return g.herringbone ? (z) => k * Math.min(z, width - z) : (z) => k * z;
378
662
  }
379
663
 
380
664
  /** A helical gear: a spur gear's profile turned along its width by the helix angle. Meshes with one of the opposite hand. @param {GearSpec & Solid & { helix: number, hand?: 'right' | 'left' }} p */
381
665
  export function helical(p) {
382
- if (!(p?.helix > 0)) throw new Error(`helical: give a helix angle above 0° (got ${shown(p?.helix)}); 15° to 30° print well`);
666
+ if (!(p?.helix > 0))
667
+ throw new Error(`helical: give a helix angle above 0° (got ${shown(p?.helix)}); 15° to 30° print well`);
383
668
  return spur({ ...p, herringbone: false });
384
669
  }
385
670
 
386
671
  /** A herringbone gear: helical one way to the middle of its width and back, so it pushes no thrust along its axis and stays on its shaft. Prints with no supports. @param {GearSpec & Solid & { helix?: number }} p */
387
- export function herringbone(p) { return spur({ ...p, helix: p?.helix ?? 30, herringbone: true }); }
672
+ export function herringbone(p) {
673
+ return spur({ ...p, helix: p?.helix ?? 30, herringbone: true });
674
+ }
388
675
 
389
676
  /** An internal (ring) gear, its rim round it. @param {GearSpec & Solid & { rim?: number }} p */
390
677
  export function internal(p) {
391
- const width = size('internal', 'width', p?.width), chamfer = chamfers('internal', p, width);
678
+ const width = size('internal', 'width', p?.width),
679
+ chamfer = chamfers('internal', p, width);
392
680
  const { model: g } = internalProfile(p);
393
681
  return loft((grow) => internalProfile(p, grow).loops, width, { chamfer, twist: twistOf(g, width) });
394
682
  }
395
683
 
396
684
  /** A rack along x, its teeth up +y, its width up z. @param {GearSpec & Solid & { height?: number }} p */
397
685
  export function rack(p) {
398
- const width = size('rack', 'width', p?.width), chamfer = chamfers('rack', p, width);
686
+ const width = size('rack', 'width', p?.width),
687
+ chamfer = chamfers('rack', p, width);
399
688
  const { model: g } = rackProfile(p);
400
689
  // a helical rack's teeth slide along it with height as its pinion's turn: z tan β, the same hand as the pinion
401
690
  const k = g.helix ? (g.hand === 'left' ? -1 : 1) * Math.tan(g.helix * DEG) : 0;
402
- return loft((grow) => rackProfile(p, grow).loops, width, { chamfer, ...(k ? { slide: g.herringbone ? (z) => k * Math.min(z, width - z) : (z) => k * z } : {}) });
691
+ return loft((grow) => rackProfile(p, grow).loops, width, {
692
+ chamfer,
693
+ ...(k ? { slide: g.herringbone ? (z) => k * Math.min(z, width - z) : (z) => k * z } : {}),
694
+ });
403
695
  }
404
696
 
405
697
  function chamfers(what, p, width) {
406
- const most = 0.25 * p.module, c = p.chamfer ?? Math.min(D('chamfer'), most), pair = Array.isArray(c) ? c : [c, 0]; // (the default: no more than the teeth can lose)
407
- if (pair.length !== 2 || !pair.every((x) => isNum(x) && x >= 0)) throw new Error(`${what}: chamfer is a size in mm (0 or more), or [bed face, top face] (got ${shown(c)})`);
408
- if (pair.some((x) => x > most)) throw new Error(`${what}: a chamfer over a quarter module (${most.toFixed(2)} mm) eats the tips: at most that`);
409
- if (pair[0] + pair[1] >= width) throw new Error(`${what}: the chamfers (${pair.join(' and ')} mm) are as tall as the gear (${width} mm)`);
698
+ const most = 0.25 * p.module,
699
+ c = p.chamfer ?? Math.min(D('chamfer'), most),
700
+ pair = Array.isArray(c) ? c : [c, 0]; // (the default: no more than the teeth can lose)
701
+ if (pair.length !== 2 || !pair.every((x) => isNum(x) && x >= 0))
702
+ throw new Error(`${what}: chamfer is a size in mm (0 or more), or [bed face, top face] (got ${shown(c)})`);
703
+ if (pair.some((x) => x > most))
704
+ throw new Error(`${what}: a chamfer over a quarter module (${most.toFixed(2)} mm) eats the tips: at most that`);
705
+ if (pair[0] + pair[1] >= width)
706
+ throw new Error(`${what}: the chamfers (${pair.join(' and ')} mm) are as tall as the gear (${width} mm)`);
410
707
  return pair;
411
708
  }
412
709
 
@@ -428,70 +725,294 @@ function working(a, sum, zs) {
428
725
  * @param {GearModel} a @param {GearModel} b @param {{ centre?: number }} [o]
429
726
  */
430
727
  export function mesh(a, b, { centre, width } = {}) {
431
- const out = [], f = (level, text, code, values) => out.push({ level, text, code, ...(values ? { values } : {}) });
432
- for (const [k, g] of [['a', a], ['b', b]]) if (!g || !['external', 'internal', 'rack'].includes(g.kind)) throw new Error(`mesh: ${k} is a gear's model (gearModel, internalModel or rackModel), not ${shown(g)}`);
433
- if (a.kind !== 'external' && b.kind !== 'external') throw new Error(`mesh: a ${a.kind} and a ${b.kind} don't mesh: one of them is an outer gear`);
728
+ const out = [],
729
+ f = (level, text, code, values) => out.push({ level, text, code, ...(values ? { values } : {}) });
730
+ for (const [k, g] of [
731
+ ['a', a],
732
+ ['b', b],
733
+ ])
734
+ if (!g || !['external', 'internal', 'rack'].includes(g.kind))
735
+ throw new Error(`mesh: ${k} is a gear's model (gearModel, internalModel or rackModel), not ${shown(g)}`);
736
+ if (a.kind !== 'external' && b.kind !== 'external')
737
+ throw new Error(`mesh: a ${a.kind} and a ${b.kind} don't mesh: one of them is an outer gear`);
434
738
  if (b.kind === 'external' && a.kind !== 'external') return flip(mesh(b, a, { centre, width }));
435
- if (Math.abs(a.module - b.module) > 1e-9) f('fail', `modules differ (${a.module} and ${b.module} mm): teeth of different sizes don't mesh`, 'mesh.module');
436
- if (Math.abs(a.pressureAngle - b.pressureAngle) > 1e-9) f('fail', `pressure angles differ (${a.pressureAngle}° and ${b.pressureAngle}°): the flanks don't roll on each other`, 'mesh.pressure');
437
- const m = a.module, al = a.pressureAngle * DEG, pb = Math.PI * m * Math.cos(al);
739
+ if (Math.abs(a.module - b.module) > 1e-9)
740
+ f('fail', `modules differ (${a.module} and ${b.module} mm): teeth of different sizes don't mesh`, 'mesh.module');
741
+ if (Math.abs(a.pressureAngle - b.pressureAngle) > 1e-9)
742
+ f(
743
+ 'fail',
744
+ `pressure angles differ (${a.pressureAngle}° and ${b.pressureAngle}°): the flanks don't roll on each other`,
745
+ 'mesh.pressure',
746
+ );
747
+ const m = a.module,
748
+ al = a.pressureAngle * DEG,
749
+ pb = Math.PI * m * Math.cos(al);
438
750
  // Helical teeth: the same angle, opposite hands outside each other, the same hand on a ring or a rack
439
- const ha = a.helix ?? 0, hb = b.helix ?? 0;
440
- if (Math.abs(ha - hb) > 1e-9) f('fail', `helix angles differ (${ha}° and ${hb}°): the teeth cross each other`, 'mesh.helix');
751
+ const ha = a.helix ?? 0,
752
+ hb = b.helix ?? 0;
753
+ if (Math.abs(ha - hb) > 1e-9)
754
+ f('fail', `helix angles differ (${ha}° and ${hb}°): the teeth cross each other`, 'mesh.helix');
441
755
  else if (ha > 0) {
442
756
  const same = b.kind !== 'external';
443
- if ((a.hand === b.hand) !== same) f('fail', `both are ${a.hand}-handed: ${same ? `a pinion and its ${b.kind === 'rack' ? 'rack' : 'ring'} are of the same hand` : 'outer gears that mesh are of opposite hands'}`, 'mesh.helix');
757
+ if ((a.hand === b.hand) !== same)
758
+ f(
759
+ 'fail',
760
+ `both are ${a.hand}-handed: ${same ? `a pinion and its ${b.kind === 'rack' ? 'rack' : 'ring'} are of the same hand` : 'outer gears that mesh are of opposite hands'}`,
761
+ 'mesh.helix',
762
+ );
444
763
  if (!!a.herringbone !== !!b.herringbone) f('fail', 'a herringbone meshes only with a herringbone', 'mesh.helix');
445
764
  }
446
- const ra1 = a.tip / 2, rb1 = a.base / 2, r1 = a.pitch / 2;
447
- let need, ratio, contact, aw = al;
765
+ if (centre !== undefined && !isNum(centre))
766
+ throw new Error(`mesh: centre is a distance in mm (got ${shown(centre)})`);
767
+ const ra1 = a.tip / 2,
768
+ rb1 = a.base / 2,
769
+ r1 = a.pitch / 2,
770
+ rf1 = a.root / 2;
771
+ let need,
772
+ ratio,
773
+ aw = al;
448
774
  if (b.kind === 'external') {
449
775
  aw = working(al, a.shift + b.shift, a.teeth + b.teeth);
450
776
  need = ((a.teeth + b.teeth) * m * Math.cos(al)) / (2 * Math.cos(aw));
451
777
  ratio = -a.teeth / b.teeth;
452
- contact = (Math.sqrt(ra1 ** 2 - rb1 ** 2) + Math.sqrt((b.tip / 2) ** 2 - (b.base / 2) ** 2) - need * Math.sin(aw)) / pb;
453
778
  } else if (b.kind === 'internal') {
454
779
  if (b.teeth <= a.teeth) throw new Error(`mesh: a ring of ${b.teeth} teeth can't hold a pinion of ${a.teeth}`);
455
780
  aw = working(al, b.shift - a.shift, b.teeth - a.teeth);
456
781
  need = ((b.teeth - a.teeth) * m * Math.cos(al)) / (2 * Math.cos(aw));
457
782
  ratio = a.teeth / b.teeth;
458
- const rb2 = b.base / 2, ra2 = Math.max(b.tip / 2, rb2); // (a ring's tip under its base circle doesn't roll)
459
- contact = (Math.sqrt(ra1 ** 2 - rb1 ** 2) - Math.sqrt(ra2 ** 2 - rb2 ** 2) + need * Math.sin(aw)) / pb;
460
- const gap = b.teeth - a.teeth;
461
- // Rule of thumb (KHK, Gear Technical Reference, internal gears): with full-depth 20° teeth and no shift, a ring
462
- // under about 10 teeth more than its pinion fouls it (involute or trochoid interference); 12 is the safe side
463
- if (gap < 10) f('fail', `the ring has ${gap} teeth more than its pinion: under 10, their tips foul each other (interference); more teeth on the ring, or fewer on the pinion`, 'mesh.interference', { gap });
464
- else if (gap < 12) f('warn', `the ring has ${gap} teeth more than its pinion: near the limit of 10 where tips foul; check it by contact`, 'mesh.interference', { gap });
465
- } else { // a rack
783
+ } else {
784
+ // a rack
466
785
  need = r1 + a.shift * m; // the pinion's centre above the rack's pitch line
467
786
  ratio = Math.PI * a.pitch; // mm a turn
468
- contact = (Math.sqrt(ra1 ** 2 - rb1 ** 2) - r1 * Math.sin(al) + (m * (b.rack.addendum - a.shift)) / Math.sin(al)) / pb;
469
787
  }
788
+ // Everything from here is judged where the axes are: at the centre given, or else at the one they need. Apart from
789
+ // their nominal place the gears roll on new pitch circles at a new working pressure angle, cos αw = (rb1 ± rb2) / a
790
+ // (the line of action stays tangent to both base circles), and the path of contact, cut by the two tip circles,
791
+ // shortens: a 20 and 40 tooth pair at module 1 has a contact ratio of 1.63 at its 30 mm and 0.74 at 31 mm. (A rack's
792
+ // flanks keep their slope: moving the pinion off it shortens the rack's share of the path instead.)
793
+ const at = centre ?? need,
794
+ given = centre !== undefined && Math.abs(centre - need) > 0.005;
795
+ let awAt = al,
796
+ path;
797
+ // (two outer gears closer than their base circles' radii together, or axes at or past each other, can't roll at all)
798
+ const crowded = !(at > 0) || (b.kind === 'external' && at < rb1 + b.base / 2);
799
+ if (b.kind === 'external') {
800
+ awAt = Math.acos(Math.min(1, (rb1 + b.base / 2) / at));
801
+ path = Math.sqrt(ra1 ** 2 - rb1 ** 2) + Math.sqrt((b.tip / 2) ** 2 - (b.base / 2) ** 2) - at * Math.sin(awAt);
802
+ } else if (b.kind === 'internal') {
803
+ const rb2 = b.base / 2,
804
+ ra2 = Math.max(b.tip / 2, rb2); // (a ring's tip under its base circle doesn't roll)
805
+ awAt = Math.acos(Math.min(1, (rb2 - rb1) / at));
806
+ path = Math.sqrt(ra1 ** 2 - rb1 ** 2) - Math.sqrt(ra2 ** 2 - rb2 ** 2) + at * Math.sin(awAt);
807
+ } else {
808
+ path = Math.sqrt(ra1 ** 2 - rb1 ** 2) - r1 * Math.sin(al) + (m * b.rack.addendum - (at - r1)) / Math.sin(al);
809
+ }
810
+ let contact = path / pb;
470
811
  // the overlap ratio: how far a tooth's own twist carries the contact on across the width (εβ = b tan β / π m, each
471
812
  // half of a herringbone on its own)
472
- const overlap = ha > 0 && width !== undefined ? ((a.herringbone ? width / 2 : width) * Math.tan(ha * DEG)) / (Math.PI * m) : 0;
813
+ const overlap =
814
+ ha > 0 && width !== undefined ? ((a.herringbone ? width / 2 : width) * Math.tan(ha * DEG)) / (Math.PI * m) : 0;
473
815
  if (overlap) contact += overlap;
474
- const sense = b.kind === 'rack' ? `${fmt(ratio)} mm of rack a turn (${fmt(ratio / 360, 4)} mm a degree)` : `${fmt(Math.abs(ratio), 4)} turns of the second for each turn of the first (${a.teeth}:${b.teeth}), ${ratio < 0 ? 'turning opposite ways' : 'the same way'}`;
475
- if (contact < 1) f('fail', `contact ratio ${fmt(contact)}: under 1, a pair of teeth lets go before the next takes up, and the drive jumps: more teeth, or a longer addendum`, 'mesh.contact', { contact });
476
- else if (contact < 1.2) f('warn', `contact ratio ${fmt(contact)}: under 1.2 the drive is rough, and a printed tooth's errors can make it jump`, 'mesh.contact', { contact });
477
- else f('pass', `contact ratio ${fmt(contact)}${overlap ? ` (${fmt(contact - overlap)} across the teeth and ${fmt(overlap)} along their twist)` : ''}: ${fmt(contact)} pairs of teeth share the load on average`, 'mesh.contact', { contact });
816
+ const sense =
817
+ b.kind === 'rack'
818
+ ? `${fmt(ratio)} mm of rack a turn (${fmt(ratio / 360, 4)} mm a degree)`
819
+ : `${fmt(Math.abs(ratio), 4)} turns of the second for each turn of the first (${a.teeth}:${b.teeth}), ${ratio < 0 ? 'turning opposite ways' : 'the same way'}`;
820
+ const where = given ? ` at the ${fmt(at, 3)} mm centre given (${fmt(need, 3)} mm is where they mesh as drawn)` : '';
821
+ // (judged on the path across the teeth: a helical's twist carries on a contact that is there, it makes none)
822
+ if (crowded)
823
+ f(
824
+ 'fail',
825
+ `the axes are too close${where || ` at ${fmt(at, 3)} mm`}: ${at > 0 ? "the gears' base circles overlap, so the teeth can't roll on each other" : 'the distance between them has to be above 0'}, and they jam: bring the axes to ${fmt(need, 3)} mm`,
826
+ 'mesh.contact',
827
+ { contact, centre: at },
828
+ );
829
+ else if (!(path > 0))
830
+ f(
831
+ 'fail',
832
+ `the teeth don't reach each other${where || ` at ${fmt(at, 3)} mm`}: no pair ever takes up the drive, and the gears slip round: bring the axes to ${fmt(need, 3)} mm`,
833
+ 'mesh.contact',
834
+ { contact, centre: at },
835
+ );
836
+ else if (contact < 1)
837
+ f(
838
+ 'fail',
839
+ `contact ratio ${fmt(contact)}${where}: under 1, a pair of teeth lets go before the next takes up, and the drive jumps: ${given && centre > need ? `bring the axes closer, to ${fmt(need, 3)} mm, or ` : ''}more teeth, or a longer addendum`,
840
+ 'mesh.contact',
841
+ { contact, centre: at },
842
+ );
843
+ else if (contact < 1.2)
844
+ f(
845
+ 'warn',
846
+ `contact ratio ${fmt(contact)}${where}: under 1.2 the drive is rough, and a printed tooth's errors can make it jump`,
847
+ 'mesh.contact',
848
+ { contact, centre: at },
849
+ );
850
+ else
851
+ f(
852
+ 'pass',
853
+ `contact ratio ${fmt(contact)}${overlap ? ` (${fmt(contact - overlap)} across the teeth and ${fmt(overlap)} along their twist)` : ''}${where}: ${fmt(contact)} pairs of teeth share the load on average`,
854
+ 'mesh.contact',
855
+ { contact, centre: at },
856
+ );
857
+ // The room under each tip, where the axes are: the centre distance less one gear's tip and the other's root (for a
858
+ // ring, its root less the pinion's far tip, and its own tips outside the pinion's roots). Profile shift pushes the
859
+ // tips out and the gears apart by less than it pushes the tips, so a shifted pair loses the 0.25 module it was drawn
860
+ // with: ISO 21771 and KHK shorten each tip by (x1 + x2 − y) modules, y being how far the shift moved the centre.
861
+ // The tips are drawn full, as each gear is drawn without its mate, so this says how much to take off.
862
+ const clear =
863
+ b.kind === 'external'
864
+ ? [at - ra1 - b.root / 2, at - b.tip / 2 - rf1]
865
+ : b.kind === 'internal'
866
+ ? [b.root / 2 - at - ra1, b.tip / 2 - at - rf1]
867
+ : [at - ra1 - b.rootLine, at - rf1 - b.tipLine];
868
+ const least = Math.min(...clear),
869
+ drawn = m * (a.rack.dedendum - a.rack.addendum),
870
+ names = [
871
+ "the first gear's tips",
872
+ `the ${b.kind === 'internal' ? 'ring' : b.kind === 'rack' ? 'rack' : 'second gear'}'s tips`,
873
+ ];
874
+ // The shortening is reckoned where the gears belong: axes set tighter than that (outer gears or a rack closer, a
875
+ // pinion further out in its ring) want moving back, not shorter tips; at a looser centre, the room there
876
+ const tighter = (b.kind === 'internal' ? at - need : need - at) > 0.005,
877
+ room = tighter ? clear.map((x) => x + Math.abs(need - at)) : clear;
878
+ const addenda = [a.rack.addendum, b.rack.addendum],
879
+ short = room.map((x) => Math.max(0, drawn - x) / m),
880
+ cut = short.map((k, i) => +(addenda[i] - k).toFixed(3));
881
+ const shorten = short.some((k) => k > 1e-3)
882
+ ? `shorten ${short.every((k) => k > 1e-3) ? "both gears' tips" : names[short[0] > 1e-3 ? 0 : 1]} to give back the ${fmt(drawn, 3)} mm of room they were drawn with (${short
883
+ .map((k, i) => (k > 1e-3 ? `addendum: ${cut[i]} on ${i ? 'the second' : 'the first'}` : ''))
884
+ .filter(Boolean)
885
+ .join(', ')}), or less profile shift`
886
+ : '';
887
+ const advice = tighter
888
+ ? `${b.kind === 'internal' ? `bring the pinion's axis to ${fmt(need, 3)} mm from the ring's` : b.kind === 'rack' ? `lift the pinion's axis to ${fmt(need, 3)} mm from the rack's pitch line` : `move the axes apart, to ${fmt(need, 3)} mm`}${shorten ? `, and ${shorten}` : ''}`
889
+ : shorten || 'less profile shift';
890
+ const worst = names[clear[0] <= clear[1] ? 0 : 1];
891
+ if (least < 0)
892
+ f(
893
+ 'fail',
894
+ `${worst} reach ${fmt(-least, 3)} mm into the mate's roots${where || ` at ${fmt(at, 3)} mm`}: the teeth jam: ${advice}`,
895
+ 'mesh.tipClearance',
896
+ { clearance: least, centre: at, addendum: cut },
897
+ );
898
+ else if (least < 0.1 * m)
899
+ f(
900
+ 'warn',
901
+ `${fmt(least, 3)} mm of room under ${worst}${where} (drawn with ${fmt(drawn, 3)}): a print that comes out a little fat rubs there: ${advice}`,
902
+ 'mesh.tipClearance',
903
+ { clearance: least, centre: at, addendum: cut },
904
+ );
905
+ else
906
+ f('pass', `${fmt(least, 3)} mm of room under the tips${where}`, 'mesh.tipClearance', {
907
+ clearance: least,
908
+ centre: at,
909
+ addendum: cut,
910
+ });
911
+ if (b.kind === 'internal') {
912
+ // A pinion in a ring: as a pinion tooth leaves the ring's space its tip swings out past the ring tooth's corner
913
+ // (trochoid interference). KHK's condition (Gear Technical Reference, internal gears), which honours shift and the
914
+ // centre: θ1 z1/z2 + inv αw − inv αa2 ≥ θ2, with θ1 = acos((ra2² − ra1² − a²) / 2a ra1) + inv αa1 − inv αw and
915
+ // θ2 = acos((a² + ra2² − ra1²) / 2a ra2), in radians of the ring's turn. It replaces the rule of thumb that a ring
916
+ // needs 10 teeth more than its pinion, which failed rings that clear (20 in 28) and passed shifted ones that don't.
917
+ // KHK's other condition, involute interference, assumes a cutter's root under the pinion's base circle; the kit's
918
+ // flanks run straight in there, and contact() tests the outlines as drawn.
919
+ const ra2 = b.tip / 2,
920
+ rb2 = b.base / 2,
921
+ z = a.teeth / b.teeth;
922
+ const k1 = (ra2 ** 2 - ra1 ** 2 - at ** 2) / (2 * at * ra1),
923
+ k2 = (at ** 2 + ra2 ** 2 - ra1 ** 2) / (2 * at * ra2);
924
+ if (Math.abs(k1) <= 1 && Math.abs(k2) <= 1) {
925
+ const aa1 = Math.acos(rb1 / ra1),
926
+ aa2 = Math.acos(rb2 / Math.max(ra2, rb2));
927
+ const t1 = Math.acos(k1) + inv(aa1) - inv(awAt),
928
+ t2 = Math.acos(k2);
929
+ const margin = t1 * z + inv(awAt) - inv(aa2) - t2;
930
+ // each tooth's share of the backlash on one flank (a quarter of each gear's), as the same angle of the ring
931
+ const play = (a.backlash / 4 / r1) * z + b.backlash / 4 / (b.pitch / 2),
932
+ mm = (x) => fmt(x * (b.pitch / 2), 3);
933
+ const gap = b.teeth - a.teeth,
934
+ values = { gap, margin: margin * (b.pitch / 2), play: play * (b.pitch / 2) };
935
+ if (margin + play < 0)
936
+ f(
937
+ 'fail',
938
+ `the pinion's tips foul the ring's as they leave (${mm(-(margin + play))} mm of overlap at the ring's pitch circle, with the backlash${where}): a ring of ${gap} teeth more than its pinion is too close for these teeth: more teeth on the ring, fewer on the pinion, or shift the ring out (a positive shift)`,
939
+ 'mesh.interference',
940
+ values,
941
+ );
942
+ else if (margin < 0)
943
+ f(
944
+ 'warn',
945
+ `the pinion's tips clear the ring's as they leave by the backlash alone (${mm(margin + play)} mm at the ring's pitch circle${where}): teeth that print a little fat foul; check the pair with contact()`,
946
+ 'mesh.interference',
947
+ values,
948
+ );
949
+ else
950
+ f(
951
+ 'pass',
952
+ `the pinion's tips clear the ring's as they leave, by ${mm(margin)} mm at the ring's pitch circle with no backlash`,
953
+ 'mesh.interference',
954
+ values,
955
+ );
956
+ }
957
+ }
478
958
  let backlash = a.backlash / 2 + b.backlash / 2;
479
959
  if (centre !== undefined) {
480
- if (!isNum(centre)) throw new Error(`mesh: centre is a distance in mm (got ${shown(centre)})`);
481
- const off = centre - need;
482
- // further apart opens a gap along the line of action of 2 Δa sin αw, which is 2 Δa tan αw round the pitch circle
960
+ // how much looser than they need: further apart for outer gears and a rack; for a pinion in a ring, nearer the
961
+ // ring's centre, as moving it out pushes its teeth into the ring's
962
+ const ring = b.kind === 'internal',
963
+ off = (ring ? -1 : 1) * (centre - need),
964
+ by = fmt(Math.abs(centre - need), 3);
965
+ const tight = ring
966
+ ? `the pinion's axis is ${by} mm further from the ring's than these gears need (${fmt(need, 3)} mm)`
967
+ : `the axes are ${by} mm closer than these gears need (${fmt(need, 3)} mm${b.kind === 'rack' ? ", centre to the rack's pitch line" : ''})`;
968
+ const loose = ring
969
+ ? `the pinion's axis is ${by} mm nearer the ring's than these gears need (${fmt(need, 3)} mm)`
970
+ : `the axes are ${by} mm further apart than these gears need (${fmt(need, 3)} mm)`;
971
+ // looser opens a gap along the line of action of 2 Δa sin αw, which is 2 Δa tan αw round the pitch circle
483
972
  const added = 2 * off * Math.tan(aw);
484
973
  backlash += added;
485
- // closer than they need eats the backlash (2 Δa tan αw of it) and the clearance under the tips (0.25 m); past
486
- // either, the teeth jam
487
- const tipRoom = m * (Math.min(a.rack.dedendum, b.rack?.dedendum ?? a.rack.dedendum) - Math.max(a.rack.addendum, b.rack?.addendum ?? a.rack.addendum)) + off;
488
- if (backlash < 0 || tipRoom < 0) f('fail', `the axes are ${fmt(-off, 3)} mm closer than these gears need (${fmt(need, 3)} mm${b.kind === 'rack' ? ', centre to the rack\'s pitch line' : ''}): ${backlash < 0 ? `more than their ${fmt(a.backlash / 2 + b.backlash / 2, 2)} mm of backlash allows` : 'the tips reach the roots'}, and the teeth jam`, 'mesh.centre', { centre, need });
489
- else if (off < -0.005 && backlash < 0.05) f('warn', `the axes are ${fmt(-off, 3)} mm closer than these gears need (${fmt(need, 3)} mm): ${fmt(backlash, 3)} mm of play left, tight enough to bind as printed`, 'mesh.centre', { centre, need });
490
- else if (backlash > 0.4) f('warn', `the axes are ${fmt(off, 3)} mm further apart than these gears need (${fmt(need, 3)} mm): ${fmt(backlash, 2)} mm of backlash, loose enough to knock`, 'mesh.centre', { centre, need });
491
- else f('pass', `centre distance ${fmt(centre, 3)} mm, ${Math.abs(off) > 0.005 ? `${fmt(Math.abs(off), 3)} mm ${off > 0 ? 'further apart' : 'closer'} than the ${fmt(need, 3)} they need` : 'as they need'}: ${fmt(backlash, 2)} mm of backlash`, 'mesh.centre', { centre, need });
974
+ // tighter eats the backlash (2 Δa tan αw of it) and the clearance under the tips (0.25 m); past either, the teeth jam
975
+ const tipRoom =
976
+ m *
977
+ (Math.min(a.rack.dedendum, b.rack?.dedendum ?? a.rack.dedendum) -
978
+ Math.max(a.rack.addendum, b.rack?.addendum ?? a.rack.addendum)) +
979
+ off;
980
+ if (backlash < 0 || tipRoom < 0)
981
+ f(
982
+ 'fail',
983
+ `${tight}: ${backlash < 0 ? `more than their ${fmt(a.backlash / 2 + b.backlash / 2, 2)} mm of backlash allows` : 'the tips reach the roots'}, and the teeth jam`,
984
+ 'mesh.centre',
985
+ { centre, need },
986
+ );
987
+ else if (off < -0.005 && backlash < 0.05)
988
+ f('warn', `${tight}: ${fmt(backlash, 3)} mm of play left, tight enough to bind as printed`, 'mesh.centre', {
989
+ centre,
990
+ need,
991
+ });
992
+ else if (backlash > 0.4)
993
+ f('warn', `${loose}: ${fmt(backlash, 2)} mm of backlash, loose enough to knock`, 'mesh.centre', { centre, need });
994
+ else
995
+ f(
996
+ 'pass',
997
+ `centre distance ${fmt(centre, 3)} mm, ${Math.abs(centre - need) > 0.005 ? `${by} mm ${centre > need ? 'further apart' : 'closer'} than the ${fmt(need, 3)} they need` : 'as they need'}: ${fmt(backlash, 2)} mm of backlash`,
998
+ 'mesh.centre',
999
+ { centre, need },
1000
+ );
492
1001
  }
493
1002
  const thrust = a.herringbone || !ha ? 0 : Math.tan(ha * DEG);
494
- return { kind: b.kind, centre: need, ratio, contact, overlap, thrust, pressureAngle: aw / DEG, backlash, text: sense, findings: out };
1003
+ return {
1004
+ kind: b.kind,
1005
+ centre: need,
1006
+ ratio,
1007
+ contact,
1008
+ overlap,
1009
+ thrust,
1010
+ pressureAngle: awAt / DEG,
1011
+ clearance: least,
1012
+ backlash,
1013
+ text: sense,
1014
+ findings: out,
1015
+ };
495
1016
  }
496
1017
  const flip = (r) => ({ ...r, ratio: r.kind === 'rack' ? r.ratio : 1 / r.ratio });
497
1018
  const fmt = (x, d = 2) => String(+x.toFixed(d));
@@ -503,10 +1024,17 @@ const fmt = (x, d = 2) => String(+x.toFixed(d));
503
1024
  * @param {GearModel} a @param {GearModel} b @param {number} [angle]
504
1025
  */
505
1026
  export function phase(a, b, angle = 0) {
506
- const z1 = a.teeth, z2 = b.teeth, beta = angle * DEG, pitch2 = TAU / z2;
1027
+ const z1 = a.teeth,
1028
+ z2 = b.teeth,
1029
+ beta = angle * DEG,
1030
+ pitch2 = TAU / z2;
507
1031
  let p;
508
- if (a.kind === 'external' && b.kind === 'external') p = beta + Math.PI - Math.PI / z2 + (z1 / z2) * beta; // a tooth on the line meets a space
509
- else if (a.kind === 'external' && b.kind === 'internal') { const g = beta + Math.PI; p = g - Math.PI / z2 - (z1 / z2) * g; } // the pinion's tooth outward, along ring to pinion
1032
+ if (a.kind === 'external' && b.kind === 'external')
1033
+ p = beta + Math.PI - Math.PI / z2 + (z1 / z2) * beta; // a tooth on the line meets a space
1034
+ else if (a.kind === 'external' && b.kind === 'internal') {
1035
+ const g = beta + Math.PI;
1036
+ p = g - Math.PI / z2 - (z1 / z2) * g;
1037
+ } // the pinion's tooth outward, along ring to pinion
510
1038
  else throw new Error('phase: give an outer gear and an outer or ring gear (for a rack, rackPhase)');
511
1039
  p = ((p % pitch2) + pitch2) % pitch2;
512
1040
  return p / DEG;
@@ -519,7 +1047,8 @@ export function phase(a, b, angle = 0) {
519
1047
  * @param {GearModel} pinion @param {number} [at] @returns {number} mm, in [0, the circular pitch)
520
1048
  */
521
1049
  export function rackPhase(pinion, at = 0) {
522
- const r = pinion.pitch / 2, p = Math.PI * pinion.module;
1050
+ const r = pinion.pitch / 2,
1051
+ p = Math.PI * pinion.module;
523
1052
  // at angle −90° the pinion's first tooth points down at the rack, and must sit over a space (spaces at x = kp): the
524
1053
  // travel there, r (−π/2) + phase, is at, so the phase is at + r π/2. (With the sign the other way the rack sat half a
525
1054
  // tooth out for an odd number of teeth, and right for an even one, where the error is whole pitches.)
@@ -535,29 +1064,83 @@ export function rackPhase(pinion, at = 0) {
535
1064
  * @param {GearModel} g @param {{ line: number, layer: number, nozzle?: number, wall_min?: number }} printer @param {number} [width]
536
1065
  */
537
1066
  export function printable(g, printer, width) {
538
- if (!g || !['external', 'internal', 'rack'].includes(g.kind)) throw new Error(`printable: give a gear's model (gearModel, internalModel or rackModel), not ${shown(g)}`);
539
- if (!printer || !(printer.line > 0) || !(printer.layer > 0)) throw new Error(`printable: the printer needs a line and a layer above 0 mm (got ${shown(printer)})`);
540
- const out = [], f = (level, text, code, at) => out.push({ level, text, code, ...(at ? { at } : {}) });
541
- const { line, layer } = printer, nozzle = printer.nozzle ?? line / 1.05, least = printer.wall_min ?? 2 * line;
1067
+ if (!g || !['external', 'internal', 'rack'].includes(g.kind))
1068
+ throw new Error(`printable: give a gear's model (gearModel, internalModel or rackModel), not ${shown(g)}`);
1069
+ if (!printer || !(printer.line > 0) || !(printer.layer > 0))
1070
+ throw new Error(`printable: the printer needs a line and a layer above 0 mm (got ${shown(printer)})`);
1071
+ const out = [],
1072
+ f = (level, text, code, at) => out.push({ level, text, code, ...(at ? { at } : {}) });
1073
+ const { line, layer } = printer,
1074
+ nozzle = printer.nozzle ?? line / 1.05,
1075
+ least = printer.wall_min ?? 2 * line;
542
1076
  const tipAt = g.kind === 'rack' ? [0.5 * g.circularPitch, g.tipLine, 0] : [g.tip / 2, 0, 0];
543
- const rootAt = g.kind === 'rack' ? [0.5 * g.circularPitch, g.rootLine, 0] : [(g.kind === 'internal' ? g.root : Math.max(g.root, g.base)) / 2, 0, 0];
1077
+ const rootAt =
1078
+ g.kind === 'rack'
1079
+ ? [0.5 * g.circularPitch, g.rootLine, 0]
1080
+ : [(g.kind === 'internal' ? g.root : Math.max(g.root, g.base)) / 2, 0, 0];
544
1081
  const floor = 2 * nozzle;
545
- if (g.module < floor - 1e-9) f('fail', `module ${g.module} on a ${fmt(nozzle)} mm nozzle: under ${fmt(floor)} (twice the nozzle) a tooth is under three lines at its pitch circle and prints as a blob; module ${fmt(floor)} or more`, 'gear.module', tipAt);
546
- else f('pass', `module ${g.module}: ${fmt(g.thickness / line, 1)} lines across a tooth at its pitch circle`, 'gear.module');
1082
+ if (g.module < floor - 1e-9)
1083
+ f(
1084
+ 'fail',
1085
+ `module ${g.module} on a ${fmt(nozzle)} mm nozzle: under ${fmt(floor)} (twice the nozzle) a tooth is under three lines at its pitch circle and prints as a blob; module ${fmt(floor)} or more`,
1086
+ 'gear.module',
1087
+ tipAt,
1088
+ );
1089
+ else
1090
+ f(
1091
+ 'pass',
1092
+ `module ${g.module}: ${fmt(g.thickness / line, 1)} lines across a tooth at its pitch circle`,
1093
+ 'gear.module',
1094
+ );
547
1095
  const rootLines = g.rootThickness / line;
548
- if (g.rootThickness < least - 1e-9) f('fail', `a tooth is ${fmt(g.rootThickness)} mm across at its root, under the thinnest wall (${fmt(least)} mm): a larger module`, 'gear.root', rootAt);
549
- else f('pass', `a tooth is ${fmt(g.rootThickness)} mm across at its root, ${fmt(rootLines, 1)} lines`, 'gear.root', rootAt);
550
- if (g.topLand < line) f('warn', `the tips are ${fmt(g.topLand)} mm across, under a line (${line} mm): they print as one bead, rounded off; fine for meshing, but don't count on the tip`, 'gear.tip', tipAt);
1096
+ if (g.rootThickness < least - 1e-9)
1097
+ f(
1098
+ 'fail',
1099
+ `a tooth is ${fmt(g.rootThickness)} mm across at its root, under the thinnest wall (${fmt(least)} mm): a larger module`,
1100
+ 'gear.root',
1101
+ rootAt,
1102
+ );
1103
+ else
1104
+ f(
1105
+ 'pass',
1106
+ `a tooth is ${fmt(g.rootThickness)} mm across at its root, ${fmt(rootLines, 1)} lines`,
1107
+ 'gear.root',
1108
+ rootAt,
1109
+ );
1110
+ if (g.topLand < line)
1111
+ f(
1112
+ 'warn',
1113
+ `the tips are ${fmt(g.topLand)} mm across, under a line (${line} mm): they print as one bead, rounded off; fine for meshing, but don't count on the tip`,
1114
+ 'gear.tip',
1115
+ tipAt,
1116
+ );
551
1117
  if (g.helix > 0) {
552
1118
  // the flank leans most at the tip: tan β_a = tan β × r_a / r
553
- const ra = g.kind === 'rack' ? 1 : g.tip / (g.kind === 'internal' ? g.root : g.pitch), lean = Math.atan(Math.tan(g.helix * DEG) * Math.max(1, ra)) / DEG;
554
- if (lean > 45) f('warn', `the teeth lean ${fmt(lean, 1)}° from upright at their tips: past 45° the flanks sag as they print; a smaller helix angle`, 'gear.helix', tipAt);
1119
+ const ra = g.kind === 'rack' ? 1 : g.tip / (g.kind === 'internal' ? g.root : g.pitch),
1120
+ lean = Math.atan(Math.tan(g.helix * DEG) * Math.max(1, ra)) / DEG;
1121
+ if (lean > 45)
1122
+ f(
1123
+ 'warn',
1124
+ `the teeth lean ${fmt(lean, 1)}° from upright at their tips: past 45° the flanks sag as they print; a smaller helix angle`,
1125
+ 'gear.helix',
1126
+ tipAt,
1127
+ );
555
1128
  else f('pass', `the teeth lean ${fmt(lean, 1)}° from upright at their tips: prints with no supports`, 'gear.helix');
556
- if (!g.herringbone) f('info', `a helix of ${g.helix}° pushes ${fmt(Math.tan(g.helix * DEG), 2)} N along the axis for each newton it drives: hold the gear on its shaft, or make it a herringbone`, 'gear.thrust');
1129
+ if (!g.herringbone)
1130
+ f(
1131
+ 'info',
1132
+ `a helix of ${g.helix}° pushes ${fmt(Math.tan(g.helix * DEG), 2)} N along the axis for each newton it drives: hold the gear on its shaft, or make it a herringbone`,
1133
+ 'gear.thrust',
1134
+ );
557
1135
  }
558
1136
  if (width !== undefined) {
559
1137
  const layers = width / layer;
560
- if (Math.abs(layers - Math.round(layers)) > 0.05) f('warn', `${width} mm wide is ${fmt(layers)} layers of ${layer} mm: a whole number prints as drawn`, 'gear.layers');
1138
+ if (Math.abs(layers - Math.round(layers)) > 0.05)
1139
+ f(
1140
+ 'warn',
1141
+ `${width} mm wide is ${fmt(layers)} layers of ${layer} mm: a whole number prints as drawn`,
1142
+ 'gear.layers',
1143
+ );
561
1144
  }
562
1145
  return out;
563
1146
  }
@@ -572,25 +1155,61 @@ export function printable(g, printer, width) {
572
1155
  */
573
1156
  export function stageEfficiency(kind, o = {}) {
574
1157
  const each = o.efficiency ?? D('efficiency');
575
- if (!(typeof each === 'number' && each > 0 && each <= 1)) throw new Error(`stageEfficiency: efficiency is from 0 to 1 (got ${shown(o.efficiency)})`);
576
- if (kind === 'worm') { if (!o.worm || !(o.worm.efficiency > 0)) throw new Error('stageEfficiency: a worm needs its model ({ worm: wormModel(…) }), for its lead angle and friction'); return o.worm.efficiency; }
1158
+ if (!(typeof each === 'number' && each > 0 && each <= 1))
1159
+ throw new Error(`stageEfficiency: efficiency is from 0 to 1 (got ${shown(o.efficiency)})`);
1160
+ if (kind === 'worm') {
1161
+ if (!o.worm || !(o.worm.efficiency > 0))
1162
+ throw new Error(
1163
+ 'stageEfficiency: a worm needs its model ({ worm: wormModel(…) }), for its lead angle and friction',
1164
+ );
1165
+ return o.worm.efficiency;
1166
+ }
577
1167
  if (['spur', 'helical', 'herringbone', 'rack', 'internal', 'bevel'].includes(kind)) return each;
578
1168
  if (kind === 'planetary') return each ** 2;
579
- throw new Error(`stageEfficiency: no kind of stage ${shown(kind)} (spur, helical, herringbone, rack, internal, bevel, planetary or worm)`);
1169
+ throw new Error(
1170
+ `stageEfficiency: no kind of stage ${shown(kind)} (spur, helical, herringbone, rack, internal, bevel, planetary or worm)`,
1171
+ );
580
1172
  }
581
1173
 
582
-
583
1174
  // ---------- strength ----------
584
1175
 
585
1176
  // The Lewis form factor for 20° full-depth teeth, by number of teeth (Budynas and Nisbett, Shigley's Mechanical
586
1177
  // Engineering Design, 10th ed., Table 14-2); a rack is 0.485. Between rows, read along a straight line.
587
- const LEWIS = [[12, 0.245], [13, 0.261], [14, 0.277], [15, 0.290], [16, 0.296], [17, 0.303], [18, 0.309], [19, 0.314], [20, 0.322], [21, 0.328], [22, 0.331], [24, 0.337], [26, 0.346], [28, 0.353], [30, 0.359], [34, 0.371], [38, 0.384], [43, 0.397], [50, 0.409], [60, 0.422], [75, 0.435], [100, 0.447], [150, 0.460], [300, 0.472], [400, 0.480]];
1178
+ const LEWIS = [
1179
+ [12, 0.245],
1180
+ [13, 0.261],
1181
+ [14, 0.277],
1182
+ [15, 0.29],
1183
+ [16, 0.296],
1184
+ [17, 0.303],
1185
+ [18, 0.309],
1186
+ [19, 0.314],
1187
+ [20, 0.322],
1188
+ [21, 0.328],
1189
+ [22, 0.331],
1190
+ [24, 0.337],
1191
+ [26, 0.346],
1192
+ [28, 0.353],
1193
+ [30, 0.359],
1194
+ [34, 0.371],
1195
+ [38, 0.384],
1196
+ [43, 0.397],
1197
+ [50, 0.409],
1198
+ [60, 0.422],
1199
+ [75, 0.435],
1200
+ [100, 0.447],
1201
+ [150, 0.46],
1202
+ [300, 0.472],
1203
+ [400, 0.48],
1204
+ ];
588
1205
  /** The Lewis form factor Y for z teeth (20° full depth); Infinity for a rack. @param {number} z */
589
1206
  export function lewisFactor(z) {
590
1207
  if (z === Infinity) return 0.485;
591
1208
  if (z <= LEWIS[0][0]) return LEWIS[0][1];
592
- if (z >= LEWIS.at(-1)[0]) return LEWIS.at(-1)[1] + ((0.485 - LEWIS.at(-1)[1]) * (1 - 400 / z));
593
- const i = LEWIS.findIndex(([n]) => n >= z), [n0, y0] = LEWIS[i - 1], [n1, y1] = LEWIS[i];
1209
+ if (z >= LEWIS.at(-1)[0]) return LEWIS.at(-1)[1] + (0.485 - LEWIS.at(-1)[1]) * (1 - 400 / z);
1210
+ const i = LEWIS.findIndex(([n]) => n >= z),
1211
+ [n0, y0] = LEWIS[i - 1],
1212
+ [n1, y1] = LEWIS[i];
594
1213
  return y0 + ((y1 - y0) * (z - n0)) / (n1 - n0);
595
1214
  }
596
1215
 
@@ -605,27 +1224,52 @@ export function lewisFactor(z) {
605
1224
  * @param {{ width: number, material: { strength: number, name?: string }, torque?: number, safety?: number, speed?: number }} o
606
1225
  */
607
1226
  export function strength(g, o = {}) {
608
- if (!g || !['external', 'internal', 'rack'].includes(g.kind)) throw new Error(`strength: give a gear's model, not ${shown(g)}`);
609
- const width = size('strength', 'width', o.width), sigma = o.material?.strength;
610
- if (!(isNum(sigma) && sigma > 0)) throw new Error(`strength: the material needs a strength above 0 MPa (got ${shown(sigma)})`);
1227
+ if (!g || !['external', 'internal', 'rack'].includes(g.kind))
1228
+ throw new Error(`strength: give a gear's model, not ${shown(g)}`);
1229
+ const width = size('strength', 'width', o.width),
1230
+ sigma = o.material?.strength;
1231
+ if (!(isNum(sigma) && sigma > 0))
1232
+ throw new Error(`strength: the material needs a strength above 0 MPa (got ${shown(sigma)})`);
611
1233
  if (o.torque !== undefined) size('strength', 'torque', o.torque);
612
1234
  const safety = o.safety === undefined ? 2 : size('strength', 'safety', o.safety);
613
- const beta = (g.helix ?? 0) * DEG, mn = g.module * Math.cos(beta);
1235
+ const beta = (g.helix ?? 0) * DEG,
1236
+ mn = g.module * Math.cos(beta);
614
1237
  const teeth = g.kind === 'rack' ? Infinity : g.teeth / Math.cos(beta) ** 3;
615
1238
  // an internal gear's teeth are stouter at the root than an outer gear's of as many teeth: read as a rack's, a little kind
616
1239
  const Y = g.kind === 'internal' ? lewisFactor(Infinity) : lewisFactor(teeth);
617
1240
  const r = g.kind === 'rack' ? null : g.pitch / 2;
618
- const V = o.speed !== undefined && r ? (size('strength', 'speed', o.speed) * 2 * Math.PI * r) / 60000 : 0, Kv = (3.05 + V) / 3.05;
1241
+ const V = o.speed !== undefined && r ? (size('strength', 'speed', o.speed) * 2 * Math.PI * r) / 60000 : 0,
1242
+ Kv = (3.05 + V) / 3.05;
619
1243
  const perNewton = Kv / (width * mn * Y); // MPa for each newton at the pitch circle
620
- const out = [], f = (level, text, code, values) => out.push({ level, text, code, ...(values ? { values } : {}) });
1244
+ const out = [],
1245
+ f = (level, text, code, values) => out.push({ level, text, code, ...(values ? { values } : {}) });
621
1246
  const name = o.material.name ?? 'the material';
622
- const result = { Y, velocity: Kv, force: (sigma / safety) / perNewton, torque: r ? ((sigma / safety) / perNewton) * r : null, findings: out };
1247
+ const result = {
1248
+ Y,
1249
+ velocity: Kv,
1250
+ force: sigma / safety / perNewton,
1251
+ torque: r ? (sigma / safety / perNewton) * r : null,
1252
+ findings: out,
1253
+ };
623
1254
  if (o.torque !== undefined) {
624
- if (!r) throw new Error('strength: a rack takes a force, not a torque (the torque is its pinion\'s)');
625
- const F = o.torque / r, stress = F * perNewton, n = sigma / stress;
1255
+ if (!r) throw new Error("strength: a rack takes a force, not a torque (the torque is its pinion's)");
1256
+ const F = o.torque / r,
1257
+ stress = F * perNewton,
1258
+ n = sigma / stress;
626
1259
  Object.assign(result, { stress, safety: n });
627
- f(n >= safety ? 'pass' : n >= 1 ? 'warn' : 'fail', `at ${fmt(o.torque / 1000, 3)} N·m the teeth see ${fmt(stress, 1)} MPa at their roots (Lewis, Y ${fmt(Y, 3)}${Kv > 1 ? `, ×${fmt(Kv, 2)} for speed` : ''}): ${fmt(n, 1)}× under ${name}'s ${sigma} MPa${n >= safety ? '' : n >= 1 ? `, under the ${safety}× asked` : ': they break'}`, 'gear.strength', { stress, safety: n });
628
- } else if (r) f('info', `the teeth carry ${fmt(result.torque / 1000, 3)} N·m at ${safety}× under ${name}'s ${sigma} MPa (Lewis, Y ${fmt(Y, 3)})`, 'gear.strength', { torque: result.torque });
1260
+ f(
1261
+ n >= safety ? 'pass' : n >= 1 ? 'warn' : 'fail',
1262
+ `at ${fmt(o.torque / 1000, 3)} N·m the teeth see ${fmt(stress, 1)} MPa at their roots (Lewis, Y ${fmt(Y, 3)}${Kv > 1 ? `, ×${fmt(Kv, 2)} for speed` : ''}): ${fmt(n, 1)}× under ${name}'s ${sigma} MPa${n >= safety ? '' : n >= 1 ? `, under the ${safety}× asked` : ': they break'}`,
1263
+ 'gear.strength',
1264
+ { stress, safety: n },
1265
+ );
1266
+ } else if (r)
1267
+ f(
1268
+ 'info',
1269
+ `the teeth carry ${fmt(result.torque / 1000, 3)} N·m at ${safety}× under ${name}'s ${sigma} MPa (Lewis, Y ${fmt(Y, 3)})`,
1270
+ 'gear.strength',
1271
+ { torque: result.torque },
1272
+ );
629
1273
  return result;
630
1274
  }
631
1275
 
@@ -639,16 +1283,39 @@ export function strength(g, o = {}) {
639
1283
  * @param {{ module: number, teeth: number, mate: number, shaftAngle?: number, width?: number, pressureAngle?: number, backlash?: number }} p
640
1284
  */
641
1285
  export function bevelModel(p) {
642
- const what = 'bevelModel', c = common(what, p), z = whole(what, 'teeth', p?.teeth, 6), mate = whole(what, 'mate', p?.mate, 6);
643
- const sigma = between(what, 'shaftAngle', p.shaftAngle ?? 90, 30, 150, '°') * DEG, a = c.pressureAngle * DEG;
644
- const delta = Math.atan2(Math.sin(sigma), mate / z + Math.cos(sigma)), d = c.module * z, R = d / (2 * Math.sin(delta));
1286
+ const what = 'bevelModel',
1287
+ c = common(what, p),
1288
+ z = whole(what, 'teeth', p?.teeth, 6),
1289
+ mate = whole(what, 'mate', p?.mate, 6);
1290
+ const sigma = between(what, 'shaftAngle', p.shaftAngle ?? 90, 30, 150, '°') * DEG,
1291
+ a = c.pressureAngle * DEG;
1292
+ const delta = Math.atan2(Math.sin(sigma), mate / z + Math.cos(sigma)),
1293
+ d = c.module * z,
1294
+ R = d / (2 * Math.sin(delta));
645
1295
  const virtual = z / Math.cos(delta);
646
1296
  const need = c.addendum - (virtual * Math.sin(a) ** 2) / 2;
647
- if (c.shift < need - 0.01) throw new Error(`${what}: ${z} teeth on a ${(delta / DEG).toFixed(1)}° cone are undercut (as ${virtual.toFixed(1)} on their back cone): give a profile shift of at least ${(Math.ceil(need * 100) / 100).toFixed(2)}, or more teeth`);
1297
+ if (c.shift < need - 0.01)
1298
+ throw new Error(
1299
+ `${what}: ${z} teeth on a ${(delta / DEG).toFixed(1)}° cone are undercut (as ${virtual.toFixed(1)} on their back cone): give a profile shift of at least ${(Math.ceil(need * 100) / 100).toFixed(2)}, or more teeth`,
1300
+ );
648
1301
  const width = p.width === undefined ? R / 3 : size(what, 'width', p.width);
649
- if (width > R / 3 + 1e-9) throw new Error(`${what}: a face width of ${width} mm is over a third of the cone distance (${(R / 3).toFixed(2)} mm): the small end's teeth get too small to carry anything`);
1302
+ if (width > R / 3 + 1e-9)
1303
+ throw new Error(
1304
+ `${what}: a face width of ${width} mm is over a third of the cone distance (${(R / 3).toFixed(2)} mm): the small end's teeth get too small to carry anything`,
1305
+ );
650
1306
  const g = gearModel({ ...p, teeth: z, helix: 0 });
651
- return { ...g, kind: 'bevel', mate, shaftAngle: sigma / DEG, pitchAngle: delta / DEG, coneDistance: R, virtualTeeth: virtual, width, height: width * Math.cos(delta), smallEnd: 1 - width / R };
1307
+ return {
1308
+ ...g,
1309
+ kind: 'bevel',
1310
+ mate,
1311
+ shaftAngle: sigma / DEG,
1312
+ pitchAngle: delta / DEG,
1313
+ coneDistance: R,
1314
+ virtualTeeth: virtual,
1315
+ width,
1316
+ height: width * Math.cos(delta),
1317
+ smallEnd: 1 - width / R,
1318
+ };
652
1319
  }
653
1320
 
654
1321
  /**
@@ -658,10 +1325,21 @@ export function bevelModel(p) {
658
1325
  * @param {{ module: number, teeth: number, mate: number, shaftAngle?: number, width?: number, bore?: number, chamfer?: number }} p
659
1326
  */
660
1327
  export function bevel(p) {
661
- const g = bevelModel(p), h = g.height, H = g.coneDistance * Math.cos(g.pitchAngle * DEG), scale = (z) => 1 - z / H;
1328
+ const g = bevelModel(p),
1329
+ h = g.height,
1330
+ H = g.coneDistance * Math.cos(g.pitchAngle * DEG),
1331
+ scale = (z) => 1 - z / H;
662
1332
  const chamfer = chamfers('bevel', { ...p, chamfer: p.chamfer ?? 0 }, h);
663
- if (p.bore != null && !(size('bevel', 'bore', p.bore) < g.root * g.smallEnd - 4 * g.module * g.smallEnd)) throw new Error(`bevel: a bore of ${p.bore} mm leaves under two modules of web under the small end's teeth`);
664
- return loft((grow, z) => [bevelSection(g, grow), ...(p.bore != null ? [reversed(bore(p.bore, p.flat, -grow)).map(([x, y]) => [x / scale(z), y / scale(z)])] : [])], h, { chamfer, scale });
1333
+ if (p.bore != null && !(size('bevel', 'bore', p.bore) < g.root * g.smallEnd - 4 * g.module * g.smallEnd))
1334
+ throw new Error(`bevel: a bore of ${p.bore} mm leaves under two modules of web under the small end's teeth`);
1335
+ return loft(
1336
+ (grow, z) => [
1337
+ bevelSection(g, grow),
1338
+ ...(p.bore != null ? [reversed(bore(p.bore, p.flat, -grow)).map(([x, y]) => [x / scale(z), y / scale(z)])] : []),
1339
+ ],
1340
+ h,
1341
+ { chamfer, scale },
1342
+ );
665
1343
  }
666
1344
 
667
1345
  // A bevel gear's section across its axis at its back end, by Tredgold's construction: the tooth drawn on the back
@@ -669,17 +1347,38 @@ export function bevel(p) {
669
1347
  // angles × 1 / cos δ); then seen from the apex onto the plane of the back end's pitch circle. Every section nearer the
670
1348
  // apex is this one scaled toward the axis, the teeth running straight to the apex.
671
1349
  function bevelSection(g, grow = 0) {
672
- const d = g.pitchAngle * DEG, m = g.module, zv = g.virtualTeeth, a = g.pressureAngle * DEG;
673
- const rv = (m * zv) / 2, r = g.pitch / 2, H = r / Math.tan(d); // the developed pitch radius; the apex over the pitch circle
674
- const { tooth } = loop({ teeth: zv, thickness: g.thickness, r: rv, rb: rv * Math.cos(a), ra: rv + m * (g.rack.addendum + g.shift), rf: rv - m * (g.rack.dedendum - g.shift), fillet: g.rack.rootFillet * m, round: g.rack.tipRound * m, grow });
1350
+ const d = g.pitchAngle * DEG,
1351
+ m = g.module,
1352
+ zv = g.virtualTeeth,
1353
+ a = g.pressureAngle * DEG;
1354
+ const rv = (m * zv) / 2,
1355
+ r = g.pitch / 2,
1356
+ H = r / Math.tan(d); // the developed pitch radius; the apex over the pitch circle
1357
+ const { tooth } = loop({
1358
+ teeth: zv,
1359
+ thickness: g.thickness,
1360
+ r: rv,
1361
+ rb: rv * Math.cos(a),
1362
+ ra: rv + m * (g.rack.addendum + g.shift),
1363
+ rf: rv - m * (g.rack.dedendum - g.shift),
1364
+ fillet: g.rack.rootFillet * m,
1365
+ round: g.rack.tipRound * m,
1366
+ grow,
1367
+ });
675
1368
  const mapped = tooth.map(([x, y]) => {
676
- const rho = Math.hypot(x, y), phi = Math.atan2(y, x) / Math.cos(d); // along the back cone's slant from its apex; round the axis
677
- const q = rho * Math.cos(d), zq = -r * Math.tan(d) + rho * Math.sin(d); // on the back cone: radius, height
1369
+ const rho = Math.hypot(x, y),
1370
+ phi = Math.atan2(y, x) / Math.cos(d); // along the back cone's slant from its apex; round the axis
1371
+ const q = rho * Math.cos(d),
1372
+ zq = -r * Math.tan(d) + rho * Math.sin(d); // on the back cone: radius, height
678
1373
  const k = q * (H / (H - zq)); // seen from the apex, on the plane z = 0
679
1374
  return [k * Math.cos(phi), k * Math.sin(phi)];
680
1375
  });
681
1376
  const out = [];
682
- for (let i = 0; i < g.teeth; i++) { const c = Math.cos((TAU * i) / g.teeth), s = Math.sin((TAU * i) / g.teeth); for (const [x, y] of mapped) out.push([x * c - y * s, x * s + y * c]); }
1377
+ for (let i = 0; i < g.teeth; i++) {
1378
+ const c = Math.cos((TAU * i) / g.teeth),
1379
+ s = Math.sin((TAU * i) / g.teeth);
1380
+ for (const [x, y] of mapped) out.push([x * c - y * s, x * s + y * c]);
1381
+ }
683
1382
  return out;
684
1383
  }
685
1384
 
@@ -688,11 +1387,26 @@ function bevelSection(g, grow = 0) {
688
1387
  * ratio of their back cones' equivalent spur gears (Tredgold). @param {object} a @param {object} b the gears' parameters
689
1388
  */
690
1389
  export function bevelMesh(a, b) {
691
- const ga = bevelModel({ ...a, mate: b.teeth }), gb = bevelModel({ ...b, mate: a.teeth });
692
- const out = [], f = (level, text, code, values) => out.push({ level, text, code, ...(values ? { values } : {}) });
693
- if (Math.abs(ga.shaftAngle - gb.shaftAngle) > 1e-9) f('fail', `shaft angles differ (${ga.shaftAngle}° and ${gb.shaftAngle}°)`, 'mesh.bevel');
694
- const virtual = (g) => gearModel({ module: g.module, teeth: Math.max(6, Math.round(g.virtualTeeth)), shift: Math.max(g.shift, 0), pressureAngle: g.pressureAngle });
1390
+ const ga = bevelModel({ ...a, mate: b.teeth }),
1391
+ gb = bevelModel({ ...b, mate: a.teeth });
1392
+ const out = [],
1393
+ f = (level, text, code, values) => out.push({ level, text, code, ...(values ? { values } : {}) });
1394
+ if (Math.abs(ga.shaftAngle - gb.shaftAngle) > 1e-9)
1395
+ f('fail', `shaft angles differ (${ga.shaftAngle}° and ${gb.shaftAngle}°)`, 'mesh.bevel');
1396
+ const virtual = (g) =>
1397
+ gearModel({
1398
+ module: g.module,
1399
+ teeth: Math.max(6, Math.round(g.virtualTeeth)),
1400
+ shift: Math.max(g.shift, 0),
1401
+ pressureAngle: g.pressureAngle,
1402
+ });
695
1403
  const back = mesh(virtual(ga), virtual(gb));
696
1404
  for (const x of back.findings) out.push({ ...x, text: `on the back cones: ${x.text}` });
697
- return { ratio: ga.teeth / gb.teeth, pitchAngles: [ga.pitchAngle, gb.pitchAngle], coneDistance: ga.coneDistance, contact: back.contact, findings: out };
1405
+ return {
1406
+ ratio: ga.teeth / gb.teeth,
1407
+ pitchAngles: [ga.pitchAngle, gb.pitchAngle],
1408
+ coneDistance: ga.coneDistance,
1409
+ contact: back.contact,
1410
+ findings: out,
1411
+ };
698
1412
  }