@rulecad/gears 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 JoniBach and contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,143 @@
1
- # Temporary Holding Version
1
+ # @rulecad/gears
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Gears for printed parts. An involute spur gear, a rack or a ring gear is drawn from three numbers (its module, its
4
+ teeth and its pressure angle) and the printer, with everything else following from them by rule. Each comes with its
5
+ numbers (pitch, base, tip and root diameters, tooth thickness), how a pair meshes (centre distance, ratio, contact
6
+ ratio, and the phase that puts a tooth in a gap) and how it prints. No dependencies but JSCAD. Part of
7
+ [rulecad](https://github.com/JoniBach/rulecad).
8
+
9
+ ```js
10
+ import { gearModel, rackModel, spur, mesh, phase, printable } from '@rulecad/gears';
11
+
12
+ const pinion = gearModel({ module: 1, teeth: 18 }); // mm; 20° pressure angle unless you say
13
+ const wheel = gearModel({ module: 1, teeth: 42 });
14
+ const m = mesh(pinion, wheel, { centre: 30 }); // the axes you plan, checked
15
+ console.log(m.centre, m.ratio.toFixed(4), m.contact.toFixed(2), m.backlash);
16
+ console.log(m.findings.map((f) => `${f.level} ${f.code}`).join(', '));
17
+ console.log(phase(pinion, wheel, 0).toFixed(3)); // turn the wheel this far (degrees) to put a tooth in a gap
18
+ console.log(pinion.pitch, pinion.base.toFixed(3), pinion.tip, pinion.root);
19
+ console.log(printable(pinion, { line: 0.42, layer: 0.2, nozzle: 0.4 }, 6).map((f) => `${f.level}: ${f.text}`).join('\n'));
20
+ console.log(mesh(pinion, rackModel({ module: 1, teeth: 30 })).text);
21
+
22
+ const solid = spur({ module: 1, teeth: 18, width: 6, bore: 5 }); // a JSCAD solid, its face on the bed
23
+ ```
24
+
25
+ ```text
26
+ 30 -0.4286 1.63 0.15
27
+ pass mesh.contact, pass mesh.centre
28
+ 4.286
29
+ 18 16.914 20 15.5
30
+ pass: module 1: 3.6 lines across a tooth at its pitch circle
31
+ pass: a tooth is 1.66 mm across at its root, 3.9 lines
32
+ 56.55 mm of rack a turn (0.1571 mm a degree)
33
+ ```
34
+
35
+ So the wheel turns 0.4286 times for each turn of the pinion, the other way; 1.63 pairs of teeth share the load on
36
+ average; the axes 30 mm apart leave the 0.15 mm of play the teeth were drawn with.
37
+
38
+ ![Eighteen teeth on thirty, and the mesh close up: pitch circles, base circles, the line of action and the path of contact](https://raw.githubusercontent.com/JoniBach/rulecad/main/packages/gears/pair.svg)
39
+
40
+ The picture is `diagram()` from `@rulecad/gears/diagram`: the pair in phase, and the mesh close up with the geometry
41
+ its numbers come from.
42
+
43
+ ## The gears
44
+
45
+ | | What it is | Call |
46
+ |---|---|---|
47
+ | Spur gear | Teeth on the outside, straight across. Prints flat on the bed with no supports, its teeth in the layers. | `spur({ module, teeth, width, bore?, flat? })` |
48
+ | Rack | A gear of infinite radius: straight teeth on a bar, for a slide driven by a pinion. | `rack({ module, teeth, width, height? })` |
49
+ | Ring gear | Teeth on the inside of a ring, for a pinion turning within it (planetary gearboxes). Turns the same way as its pinion. | `internal({ module, teeth, width, rim? })` |
50
+
51
+ Each has a model with its numbers (`gearModel`, `rackModel`, `internalModel`) and an outline in 2D (`spurProfile`,
52
+ `rackProfile`, `internalProfile`: loops of `[x, y]` points). A spur gear's first tooth is on +x, its axis along z. A
53
+ rack lies along x, its pitch line on y = 0, its teeth up +y, its first space centred at x = 0.
54
+
55
+ What every gear takes:
56
+
57
+ | Parameter | Default | What it does |
58
+ |---|---|---|
59
+ | `module` | (required) | The size of a tooth, in mm: the pitch diameter over the number of teeth. Gears that mesh share it. |
60
+ | `teeth` | (required) | A whole number: 6 or more for a spur gear (17 or more at 20° without a shift), 12 or more for a ring. |
61
+ | `pressureAngle` | 20° | The angle the flanks push at. Gears that mesh share it. |
62
+ | `shift` | 0 | Profile shift, times the module: moves the teeth outwards, so a pinion of few teeth isn't undercut. |
63
+ | `backlash` | 0.15 mm | Play between mating teeth; each gear is drawn with half of it off its teeth. |
64
+ | `width` | (required for a solid) | Up z. A whole number of layers prints as drawn. |
65
+ | `chamfer` | 0.3 mm, at most a quarter module | Round the bed face, so the first layer's squish doesn't widen the teeth there. `[bed, top]` for both faces. |
66
+ | `bore`, `flat` | none | A hole for a shaft, and the depth of a flat across it (a D shaft). |
67
+
68
+ ## How a pair meshes
69
+
70
+ `mesh(a, b, { centre })` takes two models: two outer gears, a pinion and a ring, or a pinion and a rack. It gives:
71
+
72
+ - **`centre`**: how far apart the axes must be (for a rack, the pinion's axis above the rack's pitch line). Shifted
73
+ gears move apart by their working pressure angle.
74
+ - **`ratio`**: turns of b for each turn of a, negative when they turn opposite ways. For a rack, mm of travel a turn.
75
+ - **`contact`**: the contact ratio, how many pairs of teeth share the load on average. Under 1 the drive jumps; under
76
+ 1.2 it is rough.
77
+ - **`backlash`**: the play, with the centre you gave.
78
+ - **`findings`**: `mesh.contact`, `mesh.centre` (axes too close jam the teeth; too far knock), `mesh.module` and
79
+ `mesh.pressure` (gears that can't mesh), `mesh.interference` (a ring too near its pinion's size).
80
+
81
+ `phase(a, b, angle)` is the turn that puts a tooth of a in a space of b: b's angle is `ratio × a's angle + phase`,
82
+ with `angle` the direction from a's centre to b's. `rackPhase(pinion, at)` does the same for a rack.
83
+
84
+ ## How it prints
85
+
86
+ `printable(model, printer, width)` reads the gear against the printer (`{ line, layer, nozzle, wall_min }`, as in
87
+ `@rulecad/rules`) and returns findings, each `{ level, text, code, at }` with `at` on the first tooth:
88
+
89
+ - `gear.module`: a module under twice the nozzle prints a tooth as a blob (module 0.8 at a 0.4 mm nozzle).
90
+ - `gear.root`: a tooth narrower at its root than the thinnest wall.
91
+ - `gear.tip`: tips narrower than a line print as one bead.
92
+ - `gear.layers`: a width that isn't a whole number of layers.
93
+
94
+ Spur gears, racks and rings all print flat, with no supports: the teeth are in the layers, where the filament is
95
+ strongest. Every tooth has a round at its root (the commonest place a tooth cracks) and at its tip.
96
+
97
+ The defaults, each with its rule, are in `DEFAULTS`. The backlash, the chamfer, the tip round and the smallest module
98
+ are estimates until a printed sampler measures them.
99
+
100
+ ## What isn't refused, and what is
101
+
102
+ A model or a solid refuses what isn't a gear, by name, before any maths: `gearModel: teeth is a whole number of 6 or
103
+ more (got 4.5)`. It refuses a gear whose teeth would be undercut, naming the shift that fixes it, and teeth that come to
104
+ a point.
105
+
106
+ ## The formulas
107
+
108
+ | Quantity | Formula | Source |
109
+ |---|---|---|
110
+ | Pitch diameter | d = m z | ISO 21771 |
111
+ | Base circle | d_b = d cos α | ISO 21771 |
112
+ | Tip and root | d_a = d + 2m (h_a + x), d_f = d − 2m (h_f − x); h_a = 1, h_f = 1.25 | ISO 53 basic rack |
113
+ | Tooth thickness on the pitch circle | s = m (π/2 + 2x tan α), less half the backlash | ISO 21771 |
114
+ | Tooth half-angle at radius ρ | s / d + inv α − inv α_ρ, with cos α_ρ = d_b / 2ρ, inv φ = tan φ − φ | Dudley (1984), ch. 2 |
115
+ | Undercut | none when z sin²α / 2 ≥ h_a − x (17 teeth at 20°) | ISO 21771; KHK |
116
+ | Working pressure angle | inv α_w = inv α + 2 tan α (x₁ + x₂) / (z₁ + z₂) | ISO 21771 |
117
+ | Centre distance | a = m (z₁ + z₂) cos α / 2 cos α_w; a ring: z₂ − z₁ | ISO 21771 |
118
+ | Contact ratio | (√(r_a1² − r_b1²) + √(r_a2² − r_b2²) − a sin α_w) / (π m cos α) | Dudley (1984); KHK |
119
+ | Rack contact | (√(r_a² − r_b²) − r sin α + m (h_a − x) / sin α) / (π m cos α) | KHK |
120
+ | Root fillet | 0.38 m | ISO 53 profile A |
121
+ | Ring and pinion | at least 10 teeth apart (12 to be safe) at 20° | KHK, internal gears |
122
+
123
+ ## Words used
124
+
125
+ | Word | Meaning |
126
+ |---|---|
127
+ | Module | Tooth size: pitch diameter over teeth, in mm. Module 1 is about a 3 mm tooth pitch. |
128
+ | Pitch circle | The circle that rolls without slipping on its mate's. |
129
+ | Base circle | The circle the involute flank unwinds from, smaller than the pitch circle by cos α. |
130
+ | Involute | The curve the end of a taut string traces as it unwinds from a circle. Two involute gears turn at a steady ratio even when their centres are a little off. |
131
+ | Pressure angle | The angle the teeth push along, from the tangent to the pitch circles. |
132
+ | Line of action | The line the teeth touch along: tangent to both base circles, through the pitch point. |
133
+ | Contact ratio | The path of contact over the base pitch: how many pairs of teeth share the load on average. |
134
+ | Profile shift | Moving the teeth outwards (or in) by a fraction of the module, without changing the module or the teeth. |
135
+ | Backlash | Play between mating teeth, so they don't bind as printed parts vary. |
136
+ | Undercut | A pinion of few teeth having its flank cut away under the base circle, or its mate's tip fouling there. |
137
+
138
+ ## Sources
139
+
140
+ - ISO 53:1998, *Cylindrical gears for general and heavy engineering: standard basic rack tooth profile*.
141
+ - ISO 21771:2007, *Gears: cylindrical involute gears and gear pairs, concepts and geometry*.
142
+ - D. W. Dudley, *Handbook of Practical Gear Design*, McGraw-Hill, 1984.
143
+ - KHK, *Gear Technical Reference* (khkgears.net): undercut, profile shift, internal gears.
package/diagram.d.mts ADDED
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The pair as an SVG drawing: a (an outer gear, the driver) and b (an outer gear, a ring or a rack), meshing in phase,
3
+ * with the construction close up and the numbers. a and b are the parameters given to gearModel, internalModel or
4
+ * rackModel; b's `kind` says which ('external' by default).
5
+ * @param {object} a @param {object & { kind?: 'external' | 'internal' | 'rack' }} b @param {{ title?: string }} [o]
6
+ * @returns {string} SVG
7
+ */
8
+ export function diagram(a: object, b: object & {
9
+ kind?: "external" | "internal" | "rack";
10
+ }, { title }?: {
11
+ title?: string;
12
+ }): string;
package/diagram.mjs ADDED
@@ -0,0 +1,102 @@
1
+ // A gear pair drawn the way a textbook draws it, as an SVG: the pair as it meshes (in phase), and the mesh close up with
2
+ // the geometry its numbers come from: the pitch circles rolling on each other at the pitch point, the base circles the
3
+ // flanks unwind from, the line of action tangent to both, and the stretch of it where the teeth touch (the path of
4
+ // contact, whose length over the base pitch is the contact ratio).
5
+ import { gearModel, internalModel, rackModel, spurProfile, internalProfile, rackProfile, mesh, phase, rackPhase } from './gears.mjs';
6
+
7
+ const DEG = Math.PI / 180;
8
+ const C = { a: '#2f6fb3', b: '#e07a1f', aFill: '#d6e4f3', bFill: '#f9e0c8', line: '#333', faint: '#999', contact: '#c0392b' };
9
+ const fmt = (x) => String(+x.toFixed(3));
10
+ const esc = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;');
11
+ const turn = (pts, a, [dx, dy] = [0, 0]) => { const c = Math.cos(a), s = Math.sin(a); return pts.map(([x, y]) => [x * c - y * s + dx, x * s + y * c + dy]); };
12
+ const path = (loops) => loops.map((l) => `M${l.map(([x, y]) => `${fmt(x)} ${fmt(-y)}`).join('L')}Z`).join('');
13
+ const circle = ([x, y], r, colour, dash, w) => `<circle cx="${fmt(x)}" cy="${fmt(-y)}" r="${fmt(r)}" fill="none" stroke="${colour}" stroke-width="${fmt(w)}"${dash ? ` stroke-dasharray="${dash}"` : ''}/>`;
14
+ const seg = (p, q, colour, w, dash) => `<line x1="${fmt(p[0])}" y1="${fmt(-p[1])}" x2="${fmt(q[0])}" y2="${fmt(-q[1])}" stroke="${colour}" stroke-width="${fmt(w)}"${dash ? ` stroke-dasharray="${dash}"` : ''}/>`;
15
+ const dot = (p, r, colour) => `<circle cx="${fmt(p[0])}" cy="${fmt(-p[1])}" r="${fmt(r)}" fill="${colour}"/>`;
16
+ const label = (p, text, size, colour = C.line, anchor = 'start') => `<text x="${fmt(p[0])}" y="${fmt(-p[1])}" font-size="${fmt(size)}" fill="${colour}" text-anchor="${anchor}" font-family="system-ui, sans-serif">${esc(text)}</text>`;
17
+ // Where a line (through p along d, d a unit vector) crosses a circle: the crossing nearest p
18
+ function cross(p, d, centre, r) {
19
+ const f = [p[0] - centre[0], p[1] - centre[1]], b = f[0] * d[0] + f[1] * d[1], c = f[0] ** 2 + f[1] ** 2 - r * r, disc = b * b - c;
20
+ if (disc < 0) return null;
21
+ const ts = [-b - Math.sqrt(disc), -b + Math.sqrt(disc)].sort((x, y) => Math.abs(x) - Math.abs(y));
22
+ return [p[0] + ts[0] * d[0], p[1] + ts[0] * d[1]];
23
+ }
24
+
25
+ /**
26
+ * The pair as an SVG drawing: a (an outer gear, the driver) and b (an outer gear, a ring or a rack), meshing in phase,
27
+ * with the construction close up and the numbers. a and b are the parameters given to gearModel, internalModel or
28
+ * rackModel; b's `kind` says which ('external' by default).
29
+ * @param {object} a @param {object & { kind?: 'external' | 'internal' | 'rack' }} b @param {{ title?: string }} [o]
30
+ * @returns {string} SVG
31
+ */
32
+ export function diagram(a, b, { title } = {}) {
33
+ const kind = b.kind ?? 'external', ga = gearModel(a), gb = kind === 'internal' ? internalModel(b) : kind === 'rack' ? rackModel(b) : gearModel(b);
34
+ const m = mesh(ga, gb), al = m.pressureAngle * DEG, mod = ga.module;
35
+ const A = spurProfile(a).loops, rb1 = ga.base / 2, ra1 = ga.tip / 2, rw1 = kind === 'rack' ? ga.pitch / 2 : (m.centre * ga.teeth) / Math.abs(gb.teeth + (kind === 'internal' ? -ga.teeth : ga.teeth));
36
+ let O1, O2 = null, B, P, d, T1, T2 = null, rb2, ra2, rw2, aAngle = 0, extras = [];
37
+ if (kind === 'rack') {
38
+ // the rack along x under the pinion, its pitch line on y = 0; the pinion above, turned so a tooth points down
39
+ O1 = [0, m.centre]; aAngle = -Math.PI / 2;
40
+ const s0 = rackPhase(ga, 0) + (Math.PI * ga.pitch / 360) * -90, shift = s0 - Math.PI * mod * Math.round(gb.teeth / 2);
41
+ B = rackProfile(b).loops.map((l) => l.map(([x, y]) => [x + shift, y]));
42
+ P = [0, m.centre - ga.pitch / 2]; d = [Math.cos(al), -Math.sin(al)];
43
+ T1 = [O1[0] - rb1 * Math.sin(al), O1[1] - rb1 * Math.cos(al)];
44
+ } else {
45
+ O1 = [0, 0]; O2 = [m.centre, 0];
46
+ rb2 = gb.base / 2; ra2 = gb.tip / 2; rw2 = (m.centre * gb.teeth) / Math.abs(gb.teeth + (kind === 'internal' ? -ga.teeth : ga.teeth));
47
+ // b turned to its phase (a at angle 0); a ring drawn round a pinion sits the other way: its centre on −x of the pinion's
48
+ if (kind === 'internal') { O2 = [-m.centre, 0]; B = internalProfile(b).loops.map((l) => turn(l, phase(ga, gb, 180) * DEG, O2)); P = [rw1, 0]; d = [Math.sin(al), Math.cos(al)]; T1 = [rb1 * Math.cos(al), -rb1 * Math.sin(al)]; T2 = [O2[0] + rb2 * Math.cos(al), -rb2 * Math.sin(al)]; }
49
+ else { B = spurProfile(b).loops.map((l) => turn(l, phase(ga, gb, 0) * DEG, O2)); P = [rw1, 0]; d = [Math.sin(al), -Math.cos(al)]; T1 = [rb1 * Math.cos(al), rb1 * Math.sin(al)]; T2 = [O2[0] - rb2 * Math.cos(al), -rb2 * Math.sin(al)]; }
50
+ }
51
+ const Aplaced = A.map((l) => turn(l, aAngle, O1));
52
+ // the path of contact: the line of action between the two tip circles (or the rack's tip line)
53
+ const endA = cross(P, d, O1, ra1);
54
+ const endB = kind === 'rack' ? (() => { const y = gb.tipLine, t = (y - P[1]) / d[1]; return [P[0] + t * d[0], P[1] + t * d[1]]; })() : cross(P, d, O2, kind === 'internal' ? Math.max(ra2, rb2) : ra2);
55
+ const pathLength = endA && endB ? Math.hypot(endA[0] - endB[0], endA[1] - endB[1]) : 0;
56
+
57
+ // ---- the pair, whole (left) ----
58
+ const all = [...Aplaced, ...B].flat(), xs = all.map((p) => p[0]), ys = all.map((p) => p[1]);
59
+ const span = Math.max(Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys)), pad = span * 0.06, w = span * 0.004;
60
+ const vb1 = [Math.min(...xs) - pad, -Math.max(...ys) - pad, Math.max(...xs) - Math.min(...xs) + 2 * pad, Math.max(...ys) - Math.min(...ys) + 2 * pad];
61
+ const pair = [
62
+ `<path d="${path(B)}" fill="${C.bFill}" stroke="${C.b}" stroke-width="${fmt(w)}" fill-rule="evenodd"/>`,
63
+ `<path d="${path(Aplaced)}" fill="${C.aFill}" stroke="${C.a}" stroke-width="${fmt(w)}" fill-rule="evenodd"/>`,
64
+ circle(O1, rw1, C.a, `${fmt(span * 0.01)} ${fmt(span * 0.008)}`, w), ...(O2 ? [circle(O2, rw2, C.b, `${fmt(span * 0.01)} ${fmt(span * 0.008)}`, w)] : [seg([vb1[0], P[1]], [vb1[0] + vb1[2], P[1]], C.b, w, `${fmt(span * 0.01)} ${fmt(span * 0.008)}`)]),
65
+ dot(O1, span * 0.008, C.a), ...(O2 ? [dot(O2, span * 0.008, C.b)] : []),
66
+ `<rect x="${fmt(P[0] - 4 * mod)}" y="${fmt(-P[1] - 4 * mod)}" width="${fmt(8 * mod)}" height="${fmt(8 * mod)}" fill="none" stroke="${C.contact}" stroke-width="${fmt(w)}"/>`,
67
+ ].join('');
68
+
69
+ // ---- the mesh, close up (right) ----
70
+ const h = 4 * mod, vb2 = [P[0] - h, -P[1] - h, 2 * h, 2 * h], w2 = h * 0.008, fs = h * 0.055;
71
+ const along = (p, t) => [p[0] + t * d[0], p[1] + t * d[1]];
72
+ const close = [
73
+ `<path d="${path(B)}" fill="${C.bFill}" stroke="${C.b}" stroke-width="${fmt(w2 * 1.5)}" fill-rule="evenodd"/>`,
74
+ `<path d="${path(Aplaced)}" fill="${C.aFill}" stroke="${C.a}" stroke-width="${fmt(w2 * 1.5)}" fill-rule="evenodd"/>`,
75
+ circle(O1, rw1, C.a, `${fmt(h * 0.03)} ${fmt(h * 0.02)}`, w2), circle(O1, rb1, C.a, `${fmt(h * 0.008)} ${fmt(h * 0.016)}`, w2),
76
+ ...(O2 ? [circle(O2, rw2, C.b, `${fmt(h * 0.03)} ${fmt(h * 0.02)}`, w2), circle(O2, rb2, C.b, `${fmt(h * 0.008)} ${fmt(h * 0.016)}`, w2)]
77
+ : [seg([P[0] - h, P[1]], [P[0] + h, P[1]], C.b, w2, `${fmt(h * 0.03)} ${fmt(h * 0.02)}`)]),
78
+ seg(along(P, -2 * h), along(P, 2 * h), C.line, w2), // the line of action
79
+ ...(endA && endB ? [seg(endA, endB, C.contact, w2 * 4)] : []), // where the teeth touch
80
+ seg(T1, P, C.a, w2, `${fmt(h * 0.012)} ${fmt(h * 0.012)}`), // the string unwound from a's base circle: its end draws the involute
81
+ dot(P, h * 0.018, C.line),
82
+ // a legend in the corner, on white, so nothing is written over a tooth
83
+ `<rect x="${fmt(vb2[0] + h * 0.03)}" y="${fmt(vb2[1] + h * 0.03)}" width="${fmt(h * 1.2)}" height="${fmt(fs * 4.6)}" fill="#fff" fill-opacity="0.88" rx="${fmt(fs * 0.3)}"/>`,
84
+ label([vb2[0] + h * 0.07, -(vb2[1] + h * 0.03 + fs * 1.3)], `line of action, at ${fmt(m.pressureAngle)}° (black)`, fs),
85
+ label([vb2[0] + h * 0.07, -(vb2[1] + h * 0.03 + fs * 2.5)], 'pitch point: where the pitch circles touch (dot)', fs),
86
+ label([vb2[0] + h * 0.07, -(vb2[1] + h * 0.03 + fs * 3.7)], `path of contact: ${fmt(pathLength)} mm (red)`, fs, C.contact),
87
+ ].join('');
88
+
89
+ const lines = [
90
+ title ?? `${ga.teeth} teeth on ${kind === 'rack' ? `a rack of ${gb.teeth}` : `${gb.teeth}${kind === 'internal' ? ' (a ring)' : ''}`}, module ${fmt(mod)}`,
91
+ `pitch circles (dashed) roll on each other at the pitch point; each flank is the involute of its base circle (dotted), drawn by the end of a string unwound from it`,
92
+ `centre distance ${fmt(m.centre)} mm${kind === 'rack' ? ' (to the pitch line)' : ''} · ${m.text} · pressure angle ${fmt(m.pressureAngle)}°`,
93
+ `contact ratio ${fmt(m.contact)}: the path of contact (${fmt(pathLength)} mm, red) over the base pitch (${fmt(ga.basePitch)} mm), how many pairs of teeth share the load · backlash ${fmt(m.backlash)} mm`,
94
+ ];
95
+ const W = 1200, H = 600, text = 110;
96
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H + text}" viewBox="0 0 ${W} ${H + text}">
97
+ <rect width="${W}" height="${H + text}" fill="#fff"/>
98
+ <svg x="0" y="0" width="${W / 2}" height="${H}" viewBox="${vb1.map(fmt).join(' ')}">${pair}</svg>
99
+ <svg x="${W / 2}" y="0" width="${W / 2}" height="${H}" viewBox="${vb2.map(fmt).join(' ')}">${close}</svg>
100
+ <g font-family="system-ui, sans-serif" fill="#333">${lines.map((l, i) => `<text x="20" y="${H + 24 + i * 22}" font-size="${i ? 14 : 17}"${i ? '' : ' font-weight="600"'}>${esc(l)}</text>`).join('')}</g>
101
+ </svg>`;
102
+ }
package/gears.d.mts ADDED
@@ -0,0 +1,249 @@
1
+ /**
2
+ * A spur gear's numbers: its circles, tooth thickness, and the limits it was checked against. Refuses a gear whose teeth
3
+ * would be undercut (fewer than about 17 at 20°: give it a profile shift) or come to a point.
4
+ * @param {GearSpec} p
5
+ * @returns {GearModel}
6
+ */
7
+ export function gearModel(p: GearSpec): GearModel;
8
+ /**
9
+ * An internal (ring) gear's numbers: the teeth point inwards, tip circle inside the pitch circle. Its spaces are shaped
10
+ * as an outer gear's teeth would be. `rim` is the ring's outer diameter (default: the root diameter and six modules).
11
+ * @param {GearSpec & { rim?: number }} p
12
+ * @returns {GearModel & { rim: number, space: number }}
13
+ */
14
+ export function internalModel(p: GearSpec & {
15
+ rim?: number;
16
+ }): GearModel & {
17
+ rim: number;
18
+ space: number;
19
+ };
20
+ /**
21
+ * A rack's numbers: a gear of infinite radius, its teeth straight-flanked at the pressure angle. Its pitch line is y = 0,
22
+ * teeth up +y, the first space centred at x = 0. `height` is how much bar there is under the roots (default 3 modules).
23
+ * @param {GearSpec & { height?: number }} p
24
+ */
25
+ export function rackModel(p: GearSpec & {
26
+ height?: number;
27
+ }): {
28
+ kind: string;
29
+ module: any;
30
+ teeth: any;
31
+ pressureAngle: any;
32
+ shift: number;
33
+ backlash: any;
34
+ height: any;
35
+ thickness: number;
36
+ length: number;
37
+ tipLine: number;
38
+ rootLine: number;
39
+ circularPitch: number;
40
+ basePitch: number;
41
+ topLand: number;
42
+ rootThickness: number;
43
+ rack: {
44
+ pressureAngle: any;
45
+ addendum: any;
46
+ dedendum: any;
47
+ rootFillet: any;
48
+ tipRound: any;
49
+ };
50
+ };
51
+ /**
52
+ * A spur gear's outline in 2D, as loops of [x, y] points (the first the outside, counter-clockwise; then holes,
53
+ * clockwise), and the fillet and round it was drawn with (smaller than asked where the asked one didn't fit).
54
+ * @param {GearSpec & { bore?: number, flat?: number }} p
55
+ * @param {number} [grow] outwards along the outline's normal, mm (negative: inwards)
56
+ */
57
+ export function spurProfile(p: GearSpec & {
58
+ bore?: number;
59
+ flat?: number;
60
+ }, grow?: number): {
61
+ loops: number[][][];
62
+ fillet: any;
63
+ round: any;
64
+ model: GearModel;
65
+ };
66
+ /** An internal gear's outline: the rim (counter-clockwise), then the teeth's inner outline (clockwise). */
67
+ export function internalProfile(p: any, grow?: number): {
68
+ loops: any[][];
69
+ fillet: any;
70
+ round: any;
71
+ model: GearModel & {
72
+ rim: number;
73
+ space: number;
74
+ };
75
+ };
76
+ /** A rack's outline: one loop, counter-clockwise, its pitch line on y = 0, teeth up +y from x = 0. */
77
+ export function rackProfile(p: any, grow?: number): {
78
+ loops: any[][];
79
+ fillet: any;
80
+ round: any;
81
+ model: {
82
+ kind: string;
83
+ module: any;
84
+ teeth: any;
85
+ pressureAngle: any;
86
+ shift: number;
87
+ backlash: any;
88
+ height: any;
89
+ thickness: number;
90
+ length: number;
91
+ tipLine: number;
92
+ rootLine: number;
93
+ circularPitch: number;
94
+ basePitch: number;
95
+ topLand: number;
96
+ rootThickness: number;
97
+ rack: {
98
+ pressureAngle: any;
99
+ addendum: any;
100
+ dedendum: any;
101
+ rootFillet: any;
102
+ tipRound: any;
103
+ };
104
+ };
105
+ };
106
+ /** @typedef {{ width: number, chamfer?: number | [number, number], bore?: number, flat?: number }} Solid width up z; chamfer at the bed face (and the top); bore and flat for a shaft */
107
+ /**
108
+ * A spur gear: the profile extruded up z, its first tooth on +x, the bed face chamfered.
109
+ * @param {GearSpec & Solid} p
110
+ * @returns {object} a JSCAD geom3
111
+ */
112
+ export function spur(p: GearSpec & Solid): object;
113
+ /** An internal (ring) gear, its rim round it. @param {GearSpec & Solid & { rim?: number }} p */
114
+ export function internal(p: GearSpec & Solid & {
115
+ rim?: number;
116
+ }): jscad.geometries.geom3.Geom3;
117
+ /** A rack along x, its teeth up +y, its width up z. @param {GearSpec & Solid & { height?: number }} p */
118
+ export function rack(p: GearSpec & Solid & {
119
+ height?: number;
120
+ }): jscad.geometries.geom3.Geom3;
121
+ /**
122
+ * How two gears mesh: the centre distance they need (with their profile shifts), the ratio (turns of b for one of a,
123
+ * negative when they turn opposite ways; for a rack, mm for one turn of the pinion), the contact ratio (how many teeth
124
+ * share the load on average: under 1 the drive jumps, under 1.2 it is rough), and findings. Give `centre` (mm) to have
125
+ * a centre distance checked: closer than needed jams the teeth, further adds backlash.
126
+ * @param {GearModel} a @param {GearModel} b @param {{ centre?: number }} [o]
127
+ */
128
+ export function mesh(a: GearModel, b: GearModel, { centre }?: {
129
+ centre?: number;
130
+ }): any;
131
+ /**
132
+ * The phase that puts a tooth in a gap: b's angle is ratio × a's angle + phase. Both gears have their first tooth at
133
+ * their own angle 0; `angle` is the direction from a's centre to b's, in degrees, in the frame both angles are measured in.
134
+ * For a pinion in a ring, a is the pinion. Returns degrees, in [0, 360 / b's teeth).
135
+ * @param {GearModel} a @param {GearModel} b @param {number} [angle]
136
+ */
137
+ export function phase(a: GearModel, b: GearModel, angle?: number): number;
138
+ /**
139
+ * Where a rack must stand so the pinion's teeth fall in its spaces: the rack's travel is (π × pitch diameter / 360) ×
140
+ * the pinion's angle + this, in mm. The rack lies along x with its pitch line on y = 0 and its first space at x = 0;
141
+ * the pinion's centre is at x = `at`, above the rack, its first tooth pointing along +x at angle 0.
142
+ * @param {GearModel} pinion @param {number} [at] @returns {number} mm, in [0, the circular pitch)
143
+ */
144
+ export function rackPhase(pinion: GearModel, at?: number): number;
145
+ /**
146
+ * How a gear prints on a printer ({ line, layer, nozzle?, wall_min? }): the module against the nozzle, lines across a
147
+ * tooth at its root and its tip, and the width in layers. Findings in the kit's shape, each placed on the first tooth.
148
+ * @param {GearModel} g @param {{ line: number, layer: number, nozzle?: number, wall_min?: number }} printer @param {number} [width]
149
+ */
150
+ export function printable(g: GearModel, printer: {
151
+ line: number;
152
+ layer: number;
153
+ nozzle?: number;
154
+ wall_min?: number;
155
+ }, width?: number): any[];
156
+ /**
157
+ * The defaults, each with the rule it comes from. Coefficients are times the module.
158
+ * @type {Record<string, { value: number, unit: string, rule: string, kind: string }>}
159
+ */
160
+ export const DEFAULTS: Record<string, {
161
+ value: number;
162
+ unit: string;
163
+ rule: string;
164
+ kind: string;
165
+ }>;
166
+ /**
167
+ * width up z; chamfer at the bed face (and the top); bore and flat for a shaft
168
+ */
169
+ export type Solid = {
170
+ width: number;
171
+ chamfer?: number | [number, number];
172
+ bore?: number;
173
+ flat?: number;
174
+ };
175
+ export type GearSpec = {
176
+ module: number;
177
+ teeth: number;
178
+ pressureAngle?: number;
179
+ shift?: number;
180
+ backlash?: number;
181
+ addendum?: number;
182
+ dedendum?: number;
183
+ rootFillet?: number;
184
+ tipRound?: number;
185
+ };
186
+ export type GearModel = {
187
+ kind: "external" | "internal";
188
+ module: number;
189
+ teeth: number;
190
+ /**
191
+ * degrees
192
+ */
193
+ pressureAngle: number;
194
+ /**
195
+ * times the module
196
+ */
197
+ shift: number;
198
+ /**
199
+ * mm, this gear's share is half
200
+ */
201
+ backlash: number;
202
+ /**
203
+ * pitch diameter, module × teeth
204
+ */
205
+ pitch: number;
206
+ /**
207
+ * base circle diameter
208
+ */
209
+ base: number;
210
+ /**
211
+ * tip diameter
212
+ */
213
+ tip: number;
214
+ /**
215
+ * root diameter
216
+ */
217
+ root: number;
218
+ /**
219
+ * tooth thickness on the pitch circle (an arc, mm), less half the backlash
220
+ */
221
+ thickness: number;
222
+ /**
223
+ * π × module
224
+ */
225
+ circularPitch: number;
226
+ /**
227
+ * π × module × cos(pressure angle)
228
+ */
229
+ basePitch: number;
230
+ /**
231
+ * the tooth's width across its tip (mm)
232
+ */
233
+ topLand: number;
234
+ /**
235
+ * the tooth's width where it meets the root (mm)
236
+ */
237
+ rootThickness: number;
238
+ /**
239
+ * the basic rack it was drawn from
240
+ */
241
+ rack: {
242
+ pressureAngle: number;
243
+ addendum: number;
244
+ dedendum: number;
245
+ rootFillet: number;
246
+ tipRound: number;
247
+ };
248
+ };
249
+ import jscad from '@jscad/modeling';
package/gears.mjs ADDED
@@ -0,0 +1,496 @@
1
+ // Gears for printed parts: involute spur gears, racks and internal (ring) gears drawn from their rules, each with its
2
+ // numbers (pitch, base, tip and root diameters, tooth thickness), how a pair meshes (centre distance, ratio, contact
3
+ // ratio, the phase that puts a tooth in a gap) and how it prints. The involute relations are the standard ones (ISO 53
4
+ // and ISO 21771; Dudley, Handbook of Practical Gear Design, 1984; KHK, Gear Technical Reference); the printing rules
5
+ // are the kit's own, from the printer's line and layer.
6
+ //
7
+ // Every gear is drawn flat: its axis along z, its first tooth on +x, its face on the bed at z = 0. A spur gear printed
8
+ // this way has its teeth in the layers, where the filament is strongest, and needs no supports. Units: mm, degrees.
9
+ import jscad from '@jscad/modeling';
10
+
11
+ const { extrudeFromSlices, slice } = jscad.extrusions;
12
+ const { mat4 } = jscad.maths;
13
+
14
+ const DEG = Math.PI / 180;
15
+ const inv = (a) => Math.tan(a) - a; // the involute function
16
+ const TAU = 2 * Math.PI;
17
+
18
+ /**
19
+ * The defaults, each with the rule it comes from. Coefficients are times the module.
20
+ * @type {Record<string, { value: number, unit: string, rule: string, kind: string }>}
21
+ */
22
+ export const DEFAULTS = {
23
+ 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' },
24
+ addendum: { value: 1, unit: '× module', rule: 'Tooth height above the pitch circle (ISO 53 basic rack)', kind: 'spec' },
25
+ 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' },
26
+ 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' },
27
+ 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' },
28
+ 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' },
29
+ 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' },
30
+ 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' },
31
+ };
32
+ const D = (k) => DEFAULTS[k].value;
33
+
34
+ // ---------- refusing what isn't a gear ----------
35
+
36
+ const isNum = (x) => typeof x === 'number' && Number.isFinite(x);
37
+ const shown = (v) => (v === undefined ? 'nothing' : JSON.stringify(v));
38
+ /** A size above 0, by name. */
39
+ 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; }
40
+ 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; }
41
+ 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; }
42
+ function atLeast0(what, k, v) { if (!(isNum(v) && v >= 0)) throw new Error(`${what}: ${k} is 0 or more (got ${shown(v)})`); return v; }
43
+
44
+ // The parameters every gear shares, checked and with their defaults
45
+ function common(what, p) {
46
+ if (!p || typeof p !== 'object') throw new Error(`${what}: give the gear's parameters as an object ({ module, teeth, … }), not ${shown(p)}`);
47
+ const module = size(what, 'module', p.module);
48
+ const pressureAngle = between(what, 'pressureAngle', p.pressureAngle ?? D('pressureAngle'), 10, 35, '°');
49
+ const shift = between(what, 'shift', p.shift ?? 0, -1, 1.5, ' (times the module)');
50
+ const backlash = atLeast0(what, 'backlash', p.backlash ?? D('backlash'));
51
+ const addendum = between(what, 'addendum', p.addendum ?? D('addendum'), 0.5, 1.5, ' (times the module)');
52
+ const dedendum = between(what, 'dedendum', p.dedendum ?? D('dedendum'), addendum, 2, ' (times the module, at least the addendum)');
53
+ const rootFillet = between(what, 'rootFillet', p.rootFillet ?? D('rootFillet'), 0, 0.6, ' (times the module)');
54
+ const tipRound = between(what, 'tipRound', p.tipRound ?? D('tipRound'), 0, 0.4, ' (times the module)');
55
+ return { module, pressureAngle, shift, backlash, addendum, dedendum, rootFillet, tipRound };
56
+ }
57
+
58
+ // ---------- the numbers ----------
59
+
60
+ /** @typedef {{ module: number, teeth: number, pressureAngle?: number, shift?: number, backlash?: number, addendum?: number, dedendum?: number, rootFillet?: number, tipRound?: number }} GearSpec */
61
+ /**
62
+ * @typedef {object} GearModel
63
+ * @property {'external' | 'internal'} kind
64
+ * @property {number} module @property {number} teeth @property {number} pressureAngle degrees @property {number} shift times the module
65
+ * @property {number} backlash mm, this gear's share is half
66
+ * @property {number} pitch pitch diameter, module × teeth @property {number} base base circle diameter @property {number} tip tip diameter
67
+ * @property {number} root root diameter @property {number} thickness tooth thickness on the pitch circle (an arc, mm), less half the backlash
68
+ * @property {number} circularPitch π × module @property {number} basePitch π × module × cos(pressure angle)
69
+ * @property {number} topLand the tooth's width across its tip (mm) @property {number} rootThickness the tooth's width where it meets the root (mm)
70
+ * @property {{ pressureAngle: number, addendum: number, dedendum: number, rootFillet: number, tipRound: number }} rack the basic rack it was drawn from
71
+ */
72
+
73
+ // The half-angle a tooth (or, for an internal gear, a space) takes at radius ρ, from its thickness s on the pitch circle
74
+ // of radius r: s / 2r + inv α − inv φ, where cos φ = rb / ρ. Under the base circle the flank runs straight down.
75
+ const halfAt = (s, r, rb, rho) => s / (2 * r) + inv(Math.acos(rb / r)) - inv(Math.acos(rb / Math.max(rho, rb)));
76
+
77
+ /**
78
+ * A spur gear's numbers: its circles, tooth thickness, and the limits it was checked against. Refuses a gear whose teeth
79
+ * would be undercut (fewer than about 17 at 20°: give it a profile shift) or come to a point.
80
+ * @param {GearSpec} p
81
+ * @returns {GearModel}
82
+ */
83
+ export function gearModel(p) {
84
+ const what = 'gearModel', c = common(what, p), teeth = whole(what, 'teeth', p?.teeth, 6);
85
+ const { module: m, pressureAngle, shift: x, backlash } = c, a = pressureAngle * DEG;
86
+ // Undercut: the basic rack's tip line reaches under the base circle when z sin²α / 2 < addendum − x (a whisker of
87
+ // slack, so 17 teeth at 20° pass, as tables have it)
88
+ const need = c.addendum - (teeth * Math.sin(a) ** 2) / 2;
89
+ if (x < need - 0.01) {
90
+ 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`);
91
+ }
92
+ const r = (m * teeth) / 2, rb = r * Math.cos(a), ra = r + m * (c.addendum + x), rf = r - m * (c.dedendum - x);
93
+ const s = m * (Math.PI / 2 + 2 * x * Math.tan(a)) - backlash / 2;
94
+ 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)`);
95
+ const tipHalf = halfAt(s, r, rb, ra);
96
+ 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`);
97
+ const rootHalf = halfAt(s, r, rb, Math.max(rf, rb));
98
+ return {
99
+ kind: 'external', module: m, teeth, pressureAngle, shift: x, backlash,
100
+ pitch: 2 * r, base: 2 * rb, tip: 2 * ra, root: 2 * rf, thickness: s,
101
+ circularPitch: Math.PI * m, basePitch: Math.PI * m * Math.cos(a),
102
+ topLand: 2 * ra * Math.sin(tipHalf), rootThickness: 2 * Math.max(rf, rb) * Math.sin(rootHalf),
103
+ rack: { pressureAngle, addendum: c.addendum, dedendum: c.dedendum, rootFillet: c.rootFillet, tipRound: c.tipRound },
104
+ };
105
+ }
106
+
107
+ /**
108
+ * An internal (ring) gear's numbers: the teeth point inwards, tip circle inside the pitch circle. Its spaces are shaped
109
+ * as an outer gear's teeth would be. `rim` is the ring's outer diameter (default: the root diameter and six modules).
110
+ * @param {GearSpec & { rim?: number }} p
111
+ * @returns {GearModel & { rim: number, space: number }}
112
+ */
113
+ export function internalModel(p) {
114
+ const what = 'internalModel', c = common(what, p), teeth = whole(what, 'teeth', p?.teeth, 12);
115
+ const { module: m, pressureAngle, shift: x, backlash } = c, a = pressureAngle * DEG;
116
+ const r = (m * teeth) / 2, rb = r * Math.cos(a), ra = r - m * (c.addendum - x), rf = r + m * (c.dedendum + x);
117
+ // the space on the pitch circle: π m minus the tooth (m (π/2 − 2x tan α)), widened by this gear's half of the backlash
118
+ const e = m * (Math.PI / 2 + 2 * x * Math.tan(a)) + backlash / 2, s = Math.PI * m - e;
119
+ if (!(s > 0)) throw new Error(`${what}: a backlash of ${backlash} mm leaves no tooth`);
120
+ const rim = p.rim ?? 2 * rf + 6 * m;
121
+ 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)})`);
122
+ // An internal tooth's width at a radius is the pitch angle less the space's
123
+ const toothHalf = (rho) => Math.PI / teeth - halfAt(e, r, rb, rho);
124
+ if (!(toothHalf(ra) > 0)) throw new Error(`${what}: the teeth come to a point at the tip circle: less profile shift`);
125
+ return {
126
+ kind: 'internal', module: m, teeth, pressureAngle, shift: x, backlash,
127
+ pitch: 2 * r, base: 2 * rb, tip: 2 * ra, root: 2 * rf, thickness: s, space: e, rim,
128
+ circularPitch: Math.PI * m, basePitch: Math.PI * m * Math.cos(a),
129
+ topLand: 2 * Math.max(ra, rb) * Math.sin(toothHalf(Math.max(ra, rb))), rootThickness: 2 * rf * Math.sin(toothHalf(rf)),
130
+ rack: { pressureAngle, addendum: c.addendum, dedendum: c.dedendum, rootFillet: c.rootFillet, tipRound: c.tipRound },
131
+ };
132
+ }
133
+
134
+ /**
135
+ * A rack's numbers: a gear of infinite radius, its teeth straight-flanked at the pressure angle. Its pitch line is y = 0,
136
+ * teeth up +y, the first space centred at x = 0. `height` is how much bar there is under the roots (default 3 modules).
137
+ * @param {GearSpec & { height?: number }} p
138
+ */
139
+ export function rackModel(p) {
140
+ const what = 'rackModel', c = common(what, p), teeth = whole(what, 'teeth', p?.teeth, 1);
141
+ const { module: m, pressureAngle, backlash } = c, a = pressureAngle * DEG;
142
+ if (p.shift) throw new Error(`${what}: a rack has no profile shift (shift the pinion instead; got ${shown(p.shift)})`);
143
+ const height = p.height === undefined ? 3 * m : size(what, 'height', p.height);
144
+ const s = (Math.PI * m) / 2 - backlash / 2;
145
+ if (!(s > 0)) throw new Error(`${what}: a backlash of ${backlash} mm leaves no tooth`);
146
+ const tipHalf = s / 2 - m * c.addendum * Math.tan(a);
147
+ if (!(tipHalf > 0)) throw new Error(`${what}: the teeth come to a point: a smaller addendum or pressure angle`);
148
+ return {
149
+ kind: 'rack', module: m, teeth, pressureAngle, shift: 0, backlash, height, thickness: s,
150
+ length: teeth * Math.PI * m, tipLine: m * c.addendum, rootLine: -m * c.dedendum,
151
+ circularPitch: Math.PI * m, basePitch: Math.PI * m * Math.cos(a),
152
+ topLand: 2 * tipHalf, rootThickness: s + 2 * m * c.dedendum * Math.tan(a),
153
+ rack: { pressureAngle, addendum: c.addendum, dedendum: c.dedendum, rootFillet: c.rootFillet, tipRound: c.tipRound },
154
+ };
155
+ }
156
+
157
+ // ---------- the outline ----------
158
+
159
+ // How many points each piece of a tooth gets. The same for every tooth and every slice of a solid, so slices loft
160
+ // point to point.
161
+ const N = { root: 3, fillet: 6, flank: 14, round: 4, tip: 3 };
162
+
163
+ const dist = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1]);
164
+ // The nearest point of the flank to c: a scan, then a golden-section search round the best
165
+ function nearest(flank, q0, q1, c) {
166
+ let best = q0, bd = Infinity;
167
+ 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; } }
168
+ let lo = Math.max(q0, best - (q1 - q0) / 48), hi = Math.min(q1, best + (q1 - q0) / 48);
169
+ const g = (Math.sqrt(5) - 1) / 2;
170
+ for (let i = 0; i < 40; i++) {
171
+ const a = hi - g * (hi - lo), b = lo + g * (hi - lo);
172
+ if (dist(flank(a), c) < dist(flank(b), c)) hi = b; else lo = a;
173
+ }
174
+ const q = (lo + hi) / 2;
175
+ return { q, d: dist(flank(q), c) };
176
+ }
177
+ // Points on an arc about c from a to b (the short way), n of them, a included and b not
178
+ function arc(c, a, b, n) {
179
+ const r = dist(a, c), a0 = Math.atan2(a[1] - c[1], a[0] - c[0]);
180
+ let d = Math.atan2(b[1] - c[1], b[0] - c[0]) - a0;
181
+ while (d > Math.PI) d -= TAU;
182
+ while (d < -Math.PI) d += TAU;
183
+ 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)]; });
184
+ }
185
+ // n points along a curve from q0 to q1, evenly spaced along its length, q0 included and q1 not
186
+ function along(curve, q0, q1, n) {
187
+ const fine = Array.from({ length: 121 }, (_, i) => curve(q0 + ((q1 - q0) * i) / 120)), at = [0];
188
+ for (let i = 1; i < fine.length; i++) at.push(at[i - 1] + dist(fine[i], fine[i - 1]));
189
+ const total = at.at(-1), out = [];
190
+ for (let k = 0, j = 0; k < n; k++) {
191
+ const want = (total * k) / n;
192
+ while (j < fine.length - 2 && at[j + 1] < want) j++;
193
+ const f = (want - at[j]) / (at[j + 1] - at[j] || 1);
194
+ out.push([fine[j][0] + f * (fine[j + 1][0] - fine[j][0]), fine[j][1] + f * (fine[j + 1][1] - fine[j][1])]);
195
+ }
196
+ return out;
197
+ }
198
+
199
+ // Half a tooth, from the middle of the space before it to the middle of its tip: the root, the fillet, the flank, the
200
+ // tip's round and the tip. The same for a gear (t an angle, levels radii) and a rack (t along x, levels heights).
201
+ // The fillet and the round are each a circle touching the flank and the root (or tip) circle; one that doesn't fit is
202
+ // made smaller until it does, and its size is reported.
203
+ function half(g) {
204
+ const fit = (want, base, sign, tMid, tooth) => {
205
+ // the circle's centre runs along a level ρ off the base circle (sign: outward from the root, inward from the tip)
206
+ for (let rho = want, tries = 0; ; rho *= 0.8, tries++) {
207
+ const level = base + sign * rho;
208
+ if (rho < 1e-4 || tries > 40) return null;
209
+ if (level <= g.rootLevel || level >= g.tipLevel) continue;
210
+ const tFlank = g.flankT(level), lim = tooth ? tFlank + (tMid - tFlank) * 0.85 : tMid + (tFlank - tMid) * 0.05;
211
+ const d = (t) => nearest(g.flank, g.q0, g.q1, g.point(t, level)).d;
212
+ if (d(lim) < rho) continue; // no room: smaller
213
+ let lo = tFlank, hi = lim; // d(lo) ≈ 0, d(hi) ≥ rho
214
+ for (let i = 0; i < 60; i++) { const mid = (lo + hi) / 2; if (d(mid) < rho) lo = mid; else hi = mid; }
215
+ const c = g.point(hi, level), n = nearest(g.flank, g.q0, g.q1, c);
216
+ return { rho, c, q: n.q, touch: g.flank(n.q), foot: g.point(hi, base), t: hi };
217
+ }
218
+ };
219
+ const root = g.fillet > 0 ? fit(g.fillet, g.rootLevel, 1, g.t0, false) : null;
220
+ const tip = g.round > 0 ? fit(g.round, g.tipLevel, -1, 0, true) : null;
221
+ // without a fillet (or a round), the corner itself
222
+ const rootQ = root ? root.q : g.q0, tipQ = tip ? tip.q : g.q1;
223
+ const rootFoot = root ? root.foot : g.flank(g.q0), tipFoot = tip ? tip.foot : g.flank(g.q1);
224
+ const rootT = root ? root.t : g.flankT(g.rootLevel), tipT = tip ? tip.t : g.flankT(g.tipLevel);
225
+ const pts = [
226
+ ...Array.from({ length: N.root }, (_, i) => g.point(g.t0 + ((rootT - g.t0) * i) / N.root, g.rootLevel)),
227
+ ...(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))),
228
+ ...along(g.flank, rootQ, tipQ, N.flank),
229
+ ...(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))),
230
+ ...Array.from({ length: N.tip }, (_, i) => g.point(tipT + ((0 - tipT) * i) / N.tip, g.tipLevel)),
231
+ ];
232
+ return { pts, fillet: root ? root.rho : 0, round: tip ? tip.rho : 0, wantFillet: g.fillet, wantRound: g.round };
233
+ }
234
+
235
+ // A gear's (or an internal gear's spaces') outline: one loop, counter-clockwise, tooth 0 on +x. grow moves it outwards
236
+ // by that much along its normal (an involute's offset is the same involute, thinner by grow / rb each side).
237
+ function loop({ teeth: z, thickness: s, r, rb, ra, rf, fillet, round, grow = 0 }) {
238
+ s += (2 * grow * r) / rb; ra += grow; rf += grow;
239
+ fillet = Math.max(1e-3, fillet - grow); round = Math.max(1e-3, round + grow);
240
+ const hAt = (rho) => halfAt(s, r, rb, rho), rLow = rf, rHigh = ra;
241
+ const flank = (rho) => { const h = hAt(rho); return [rho * Math.cos(h), -rho * Math.sin(h)]; };
242
+ const h = half({
243
+ t0: -Math.PI / z, rootLevel: rf, tipLevel: ra, q0: rLow, q1: rHigh, flank, fillet, round,
244
+ flankT: (rho) => -hAt(rho), point: (t, rho) => [rho * Math.cos(t), rho * Math.sin(t)],
245
+ });
246
+ const tooth = [...h.pts, [ra, 0], ...h.pts.slice(1).reverse().map(([x, y]) => [x, -y])];
247
+ const out = [];
248
+ for (let k = 0; k < z; k++) {
249
+ const c = Math.cos((TAU * k) / z), sn = Math.sin((TAU * k) / z);
250
+ for (const [x, y] of tooth) out.push([x * c - y * sn, x * sn + y * c]);
251
+ }
252
+ return { points: out, fillet: h.fillet, round: h.round };
253
+ }
254
+
255
+ 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))]);
256
+ // A bore: a circle, or with a flat (a D shape) the points past the flat brought onto it. grow: outwards, into the hole.
257
+ function bore(d, flat, grow = 0) {
258
+ const pts = circle(d, 48, grow);
259
+ if (!flat) return pts;
260
+ const at = d / 2 - flat + grow;
261
+ return pts.map(([x, y]) => (x > at ? [at, y] : [x, y]));
262
+ }
263
+ const reversed = (pts) => [...pts].reverse();
264
+
265
+ /**
266
+ * A spur gear's outline in 2D, as loops of [x, y] points (the first the outside, counter-clockwise; then holes,
267
+ * clockwise), and the fillet and round it was drawn with (smaller than asked where the asked one didn't fit).
268
+ * @param {GearSpec & { bore?: number, flat?: number }} p
269
+ * @param {number} [grow] outwards along the outline's normal, mm (negative: inwards)
270
+ */
271
+ export function spurProfile(p, grow = 0) {
272
+ const g = gearModel(p), r = g.pitch / 2, m = g.module;
273
+ 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 });
274
+ const loops = [l.points];
275
+ if (p.bore != null) {
276
+ size('spur', 'bore', p.bore);
277
+ 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)`);
278
+ 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})`);
279
+ loops.push(reversed(bore(p.bore, p.flat, -grow)));
280
+ }
281
+ return { loops, fillet: l.fillet, round: l.round, model: g };
282
+ }
283
+
284
+ /** An internal gear's outline: the rim (counter-clockwise), then the teeth's inner outline (clockwise). */
285
+ export function internalProfile(p, grow = 0) {
286
+ const g = internalModel(p), r = g.pitch / 2, m = g.module;
287
+ // the spaces, drawn as an outer gear's teeth: their "tips" are the ring's roots (the ring's root fillet there), their
288
+ // "roots" the ring's tips (its round there). Growing the ring is shrinking the spaces.
289
+ 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 });
290
+ // the ring's tooth 0 on +x: the spaces' loop has a space on +x, so turn it half a pitch
291
+ 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]);
292
+ return { loops: [circle(g.rim, 96, grow), reversed(turned)], fillet: l.round, round: l.fillet, model: g };
293
+ }
294
+
295
+ /** A rack's outline: one loop, counter-clockwise, its pitch line on y = 0, teeth up +y from x = 0. */
296
+ export function rackProfile(p, grow = 0) {
297
+ const g = rackModel(p), m = g.module, a = g.pressureAngle * DEG, pitch = Math.PI * m;
298
+ const s = g.thickness + (2 * grow) / Math.cos(a), yt = g.tipLine + grow, yr = g.rootLine + grow;
299
+ const w = (y) => s / 2 - y * Math.tan(a); // half the tooth's width at height y
300
+ const flank = (y) => [-w(y), y];
301
+ const h = half({
302
+ t0: -pitch / 2, rootLevel: yr, tipLevel: yt, q0: yr, q1: yt, flank,
303
+ fillet: Math.max(1e-3, g.rack.rootFillet * m - grow), round: Math.max(1e-3, g.rack.tipRound * m + grow),
304
+ flankT: (y) => -w(y), point: (t, y) => [t, y],
305
+ });
306
+ const tooth = [...h.pts, [0, yt], ...h.pts.slice(1).reverse().map(([x, y]) => [-x, y])];
307
+ const top = [];
308
+ for (let k = 0; k < g.teeth; k++) for (const [x, y] of tooth) top.push([x + (k + 0.5) * pitch, y]);
309
+ top.push([g.length, yr]);
310
+ const bottom = yr - g.height - grow;
311
+ return { loops: [[[0, bottom], [g.length, bottom], ...reversed(top)]], fillet: h.fillet, round: h.round, model: g };
312
+ }
313
+
314
+ // ---------- solids ----------
315
+
316
+ // A solid from loops at heights: each slice is the loops at a height, grown (a chamfer: drawn smaller there) and turned
317
+ // (a helix), all with the same points, so the walls join point to point. Caps are triangulated with their holes.
318
+ function loft(profile, width, { chamfer, twist }) {
319
+ const [bottom, top] = Array.isArray(chamfer) ? chamfer : [chamfer, 0];
320
+ if (bottom + top >= width) throw new Error(`the chamfers (${bottom} and ${top} mm) are as tall as the gear (${width} mm)`);
321
+ // heights: the chamfers' ends, and for a twist enough between that no slice turns more than a degree or so
322
+ const zs = [0, ...(bottom > 0 ? [bottom] : []), ...(top > 0 ? [width - top] : []), width];
323
+ if (twist) {
324
+ const most = Math.max(...zs.map((z) => Math.abs(twist(z)))), n = Math.ceil(most / (1.5 * DEG));
325
+ for (let i = 1; i < n; i++) zs.push((width * i) / n);
326
+ }
327
+ const heights = [...new Set(zs.map((z) => +z.toFixed(9)))].sort((x, y) => x - y);
328
+ const slices = heights.map((z) => {
329
+ const grow = z < bottom ? -(bottom - z) : z > width - top ? -(z - (width - top)) : 0;
330
+ const loops = profile(grow), turn = twist ? twist(z) : 0, c = Math.cos(turn), s = Math.sin(turn);
331
+ const sides = loops.flatMap((pts) => pts.map((p, i) => { const q = pts[(i + 1) % pts.length]; return [[p[0] * c - p[1] * s, p[0] * s + p[1] * c], [q[0] * c - q[1] * s, q[0] * s + q[1] * c]]; }));
332
+ return slice.transform(mat4.fromTranslation(mat4.create(), [0, 0, z]), slice.fromSides(sides));
333
+ });
334
+ return extrudeFromSlices({ numberOfSlices: slices.length, repair: false, callback: (t, i) => slices[i] }, slices[0]);
335
+ }
336
+
337
+ /** @typedef {{ width: number, chamfer?: number | [number, number], bore?: number, flat?: number }} Solid width up z; chamfer at the bed face (and the top); bore and flat for a shaft */
338
+
339
+ /**
340
+ * A spur gear: the profile extruded up z, its first tooth on +x, the bed face chamfered.
341
+ * @param {GearSpec & Solid} p
342
+ * @returns {object} a JSCAD geom3
343
+ */
344
+ export function spur(p) {
345
+ const width = size('spur', 'width', p?.width), chamfer = chamfers('spur', p, width);
346
+ spurProfile(p); // (refuses here, before any slicing)
347
+ return loft((grow) => spurProfile(p, grow).loops, width, { chamfer });
348
+ }
349
+
350
+ /** An internal (ring) gear, its rim round it. @param {GearSpec & Solid & { rim?: number }} p */
351
+ export function internal(p) {
352
+ const width = size('internal', 'width', p?.width), chamfer = chamfers('internal', p, width);
353
+ internalProfile(p);
354
+ return loft((grow) => internalProfile(p, grow).loops, width, { chamfer });
355
+ }
356
+
357
+ /** A rack along x, its teeth up +y, its width up z. @param {GearSpec & Solid & { height?: number }} p */
358
+ export function rack(p) {
359
+ const width = size('rack', 'width', p?.width), chamfer = chamfers('rack', p, width);
360
+ rackProfile(p);
361
+ return loft((grow) => rackProfile(p, grow).loops, width, { chamfer });
362
+ }
363
+
364
+ function chamfers(what, p, width) {
365
+ 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)
366
+ 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)})`);
367
+ 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`);
368
+ if (pair[0] + pair[1] >= width) throw new Error(`${what}: the chamfers (${pair.join(' and ')} mm) are as tall as the gear (${width} mm)`);
369
+ return pair;
370
+ }
371
+
372
+ // ---------- meshing ----------
373
+
374
+ // The working pressure angle of shifted gears: inv αw = inv α + 2 tan α (x1 ± x2) / (z1 ± z2), solved by Newton
375
+ function working(a, sum, zs) {
376
+ const want = inv(a) + (2 * Math.tan(a) * sum) / zs;
377
+ let w = a;
378
+ for (let i = 0; i < 30; i++) w -= (inv(w) - want) / Math.tan(w) ** 2;
379
+ return w;
380
+ }
381
+
382
+ /**
383
+ * How two gears mesh: the centre distance they need (with their profile shifts), the ratio (turns of b for one of a,
384
+ * negative when they turn opposite ways; for a rack, mm for one turn of the pinion), the contact ratio (how many teeth
385
+ * share the load on average: under 1 the drive jumps, under 1.2 it is rough), and findings. Give `centre` (mm) to have
386
+ * a centre distance checked: closer than needed jams the teeth, further adds backlash.
387
+ * @param {GearModel} a @param {GearModel} b @param {{ centre?: number }} [o]
388
+ */
389
+ export function mesh(a, b, { centre } = {}) {
390
+ const out = [], f = (level, text, code, values) => out.push({ level, text, code, ...(values ? { values } : {}) });
391
+ 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)}`);
392
+ 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`);
393
+ if (b.kind === 'external' && a.kind !== 'external') return flip(mesh(b, a, { centre }));
394
+ 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');
395
+ 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');
396
+ const m = a.module, al = a.pressureAngle * DEG, pb = Math.PI * m * Math.cos(al);
397
+ const ra1 = a.tip / 2, rb1 = a.base / 2, r1 = a.pitch / 2;
398
+ let need, ratio, contact, aw = al;
399
+ if (b.kind === 'external') {
400
+ aw = working(al, a.shift + b.shift, a.teeth + b.teeth);
401
+ need = ((a.teeth + b.teeth) * m * Math.cos(al)) / (2 * Math.cos(aw));
402
+ ratio = -a.teeth / b.teeth;
403
+ contact = (Math.sqrt(ra1 ** 2 - rb1 ** 2) + Math.sqrt((b.tip / 2) ** 2 - (b.base / 2) ** 2) - need * Math.sin(aw)) / pb;
404
+ } else if (b.kind === 'internal') {
405
+ if (b.teeth <= a.teeth) throw new Error(`mesh: a ring of ${b.teeth} teeth can't hold a pinion of ${a.teeth}`);
406
+ aw = working(al, b.shift - a.shift, b.teeth - a.teeth);
407
+ need = ((b.teeth - a.teeth) * m * Math.cos(al)) / (2 * Math.cos(aw));
408
+ ratio = a.teeth / b.teeth;
409
+ const rb2 = b.base / 2, ra2 = Math.max(b.tip / 2, rb2); // (a ring's tip under its base circle doesn't roll)
410
+ contact = (Math.sqrt(ra1 ** 2 - rb1 ** 2) - Math.sqrt(ra2 ** 2 - rb2 ** 2) + need * Math.sin(aw)) / pb;
411
+ const gap = b.teeth - a.teeth;
412
+ // Rule of thumb (KHK, Gear Technical Reference, internal gears): with full-depth 20° teeth and no shift, a ring
413
+ // under about 10 teeth more than its pinion fouls it (involute or trochoid interference); 12 is the safe side
414
+ 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 });
415
+ 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 });
416
+ } else { // a rack
417
+ need = r1 + a.shift * m; // the pinion's centre above the rack's pitch line
418
+ ratio = Math.PI * a.pitch; // mm a turn
419
+ contact = (Math.sqrt(ra1 ** 2 - rb1 ** 2) - r1 * Math.sin(al) + (m * (b.rack.addendum - a.shift)) / Math.sin(al)) / pb;
420
+ }
421
+ 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'}`;
422
+ 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 });
423
+ 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 });
424
+ else f('pass', `contact ratio ${fmt(contact)}: ${fmt(contact)} pairs of teeth share the load on average`, 'mesh.contact', { contact });
425
+ let backlash = a.backlash / 2 + b.backlash / 2;
426
+ if (centre !== undefined) {
427
+ if (!isNum(centre)) throw new Error(`mesh: centre is a distance in mm (got ${shown(centre)})`);
428
+ const off = centre - need;
429
+ // 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
430
+ const added = 2 * off * Math.tan(aw);
431
+ backlash += added;
432
+ if (off < -0.01) 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' : ''}): the teeth jam`, 'mesh.centre', { centre, need });
433
+ 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 });
434
+ else f('pass', `centre distance ${fmt(centre, 3)} mm, as they need${Math.abs(off) > 0.005 ? ` (${off > 0 ? '+' : ''}${fmt(off, 3)})` : ''}: ${fmt(backlash, 2)} mm of backlash`, 'mesh.centre', { centre, need });
435
+ }
436
+ return { kind: b.kind, centre: need, ratio, contact, pressureAngle: aw / DEG, backlash, text: sense, findings: out };
437
+ }
438
+ const flip = (r) => ({ ...r, ratio: r.kind === 'rack' ? r.ratio : 1 / r.ratio });
439
+ const fmt = (x, d = 2) => String(+x.toFixed(d));
440
+
441
+ /**
442
+ * The phase that puts a tooth in a gap: b's angle is ratio × a's angle + phase. Both gears have their first tooth at
443
+ * their own angle 0; `angle` is the direction from a's centre to b's, in degrees, in the frame both angles are measured in.
444
+ * For a pinion in a ring, a is the pinion. Returns degrees, in [0, 360 / b's teeth).
445
+ * @param {GearModel} a @param {GearModel} b @param {number} [angle]
446
+ */
447
+ export function phase(a, b, angle = 0) {
448
+ const z1 = a.teeth, z2 = b.teeth, beta = angle * DEG, pitch2 = TAU / z2;
449
+ let p;
450
+ 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
451
+ 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
452
+ else throw new Error('phase: give an outer gear and an outer or ring gear (for a rack, rackPhase)');
453
+ p = ((p % pitch2) + pitch2) % pitch2;
454
+ return p / DEG;
455
+ }
456
+
457
+ /**
458
+ * Where a rack must stand so the pinion's teeth fall in its spaces: the rack's travel is (π × pitch diameter / 360) ×
459
+ * the pinion's angle + this, in mm. The rack lies along x with its pitch line on y = 0 and its first space at x = 0;
460
+ * the pinion's centre is at x = `at`, above the rack, its first tooth pointing along +x at angle 0.
461
+ * @param {GearModel} pinion @param {number} [at] @returns {number} mm, in [0, the circular pitch)
462
+ */
463
+ export function rackPhase(pinion, at = 0) {
464
+ const r = pinion.pitch / 2, p = Math.PI * pinion.module;
465
+ // at angle −90° the pinion's first tooth points down at the rack, and must sit over a space (spaces at x = kp)
466
+ const s = at - r * (Math.PI / 2);
467
+ return ((s % p) + p) % p;
468
+ }
469
+
470
+ // ---------- printing ----------
471
+
472
+ /**
473
+ * How a gear prints on a printer ({ line, layer, nozzle?, wall_min? }): the module against the nozzle, lines across a
474
+ * tooth at its root and its tip, and the width in layers. Findings in the kit's shape, each placed on the first tooth.
475
+ * @param {GearModel} g @param {{ line: number, layer: number, nozzle?: number, wall_min?: number }} printer @param {number} [width]
476
+ */
477
+ export function printable(g, printer, width) {
478
+ if (!g || !['external', 'internal', 'rack'].includes(g.kind)) throw new Error(`printable: give a gear's model (gearModel, internalModel or rackModel), not ${shown(g)}`);
479
+ 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)})`);
480
+ const out = [], f = (level, text, code, at) => out.push({ level, text, code, ...(at ? { at } : {}) });
481
+ const { line, layer } = printer, nozzle = printer.nozzle ?? line / 1.05, least = printer.wall_min ?? 2 * line;
482
+ const tipAt = g.kind === 'rack' ? [0.5 * g.circularPitch, g.tipLine, 0] : [g.tip / 2, 0, 0];
483
+ 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];
484
+ const floor = 2 * nozzle;
485
+ 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);
486
+ else f('pass', `module ${g.module}: ${fmt(g.thickness / line, 1)} lines across a tooth at its pitch circle`, 'gear.module');
487
+ const rootLines = g.rootThickness / line;
488
+ 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);
489
+ else f('pass', `a tooth is ${fmt(g.rootThickness)} mm across at its root, ${fmt(rootLines, 1)} lines`, 'gear.root', rootAt);
490
+ 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);
491
+ if (width !== undefined) {
492
+ const layers = width / layer;
493
+ 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');
494
+ }
495
+ return out;
496
+ }
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@rulecad/gears",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Gears for printed parts: involute spur gears, racks and ring gears drawn from their rules, with their numbers, how a pair meshes (centre distance, ratio, contact ratio, phase) and how they print.",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./gears.d.mts",
9
+ "default": "./gears.mjs"
10
+ },
11
+ "./diagram": {
12
+ "types": "./diagram.d.mts",
13
+ "default": "./diagram.mjs"
14
+ }
15
+ },
16
+ "files": [
17
+ "gears.mjs",
18
+ "diagram.mjs",
19
+ "gears.d.mts",
20
+ "diagram.d.mts",
21
+ "README.md",
22
+ "LICENSE"
23
+ ],
24
+ "license": "MIT",
25
+ "keywords": [
26
+ "jscad",
27
+ "3d-printing",
28
+ "gears",
29
+ "involute",
30
+ "rack-and-pinion",
31
+ "cad"
32
+ ],
33
+ "engines": {
34
+ "node": ">=20"
35
+ },
36
+ "sideEffects": false,
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/JoniBach/rulecad.git",
40
+ "directory": "packages/gears"
41
+ },
42
+ "homepage": "https://github.com/JoniBach/rulecad/tree/main/packages/gears#readme",
43
+ "bugs": {
44
+ "url": "https://github.com/JoniBach/rulecad/issues"
45
+ },
46
+ "scripts": {
47
+ "test": "node --test"
48
+ },
49
+ "peerDependencies": {
50
+ "@jscad/modeling": "^2.12.0"
51
+ },
52
+ "types": "./gears.d.mts"
53
+ }