@rulecad/fixings 0.0.0-stage → 0.1.1

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/draw.d.mts ADDED
@@ -0,0 +1,46 @@
1
+ /** A cutter drawn going down from z = 0 (into -z), turned to go along `into` from the origin, then moved to `at`. */
2
+ export function along(g: any, into: any, at?: number[]): any;
3
+ /**
4
+ * A solid of revolution about z, from its profile: points [radius, z] running from the axis at the bottom, out, up and
5
+ * back to the axis at the top (or a closed loop clear of the axis, anticlockwise, for a ring). Each edge of the profile
6
+ * is one band of n flat faces, so the count of triangles is known: 2 n for a band, n where it meets the axis.
7
+ * @param {number[][]} profile @param {number} [n] faces round @param {number} [phase] the first corner's angle, radians
8
+ * @returns {object} a JSCAD geom3
9
+ */
10
+ export function lathe(profile: number[][], n?: number, phase?: number): object;
11
+ /** The volume a profile turns into, with true circles: each edge a frustum (mm³). @param {number[][]} profile @returns {number} */
12
+ export function turnedVolume(profile: number[][]): number;
13
+ /**
14
+ * A round cutter going down from z = 0, from its steps: [radius, depth] pairs from the mouth inwards, the radius
15
+ * changing between one depth and the next. It starts OUT above the face, and with through it runs OUT past its end.
16
+ * @param {number[][]} steps @param {{ through?: boolean }} [o] @returns {object} a JSCAD geom3 to subtract
17
+ */
18
+ export function bore(steps: number[][], { through }?: {
19
+ through?: boolean;
20
+ }): object;
21
+ /**
22
+ * A cutter lying on its side, going down from z = 0 in its own drawing, from its steps as bore takes them: at every
23
+ * depth its section is a teardrop, a circle with a 45° pointed roof on the up side, so it prints with no support. One
24
+ * closed solid with no joins in it, for the stepped and coned cutters @rulecad/shapes has no helper for.
25
+ * @param {number[][]} steps [radius, depth] pairs from the mouth inwards @param {number[]} up which way is up in the drawing: [1, 0], [0, 1] …
26
+ * @param {{ through?: boolean }} [o] @returns {object} a JSCAD geom3 to subtract
27
+ */
28
+ export function teardrop(steps: number[][], up: number[], { through }?: {
29
+ through?: boolean;
30
+ }): object;
31
+ export const OUT: 0.1;
32
+ export const SEGMENTS: 48;
33
+ export const LIGHT: 12;
34
+ /** The directions a cutter can go, as @rulecad/shapes names them. */
35
+ export const DIRECTIONS: string[];
36
+ export const UP: {
37
+ '+x': number[];
38
+ '-x': number[];
39
+ '+y': number[];
40
+ '-y': number[];
41
+ };
42
+ export namespace booleans {
43
+ let union: typeof jscad.booleans.union;
44
+ let subtract: typeof jscad.booleans.subtract;
45
+ }
46
+ import jscad from '@jscad/modeling';
package/draw.mjs ADDED
@@ -0,0 +1,85 @@
1
+ // How fixings draws: cutters that start at a point on a face (at) and go into the material along a direction (into),
2
+ // as @rulecad/shapes' features do, and solids of revolution made face by face so a reference screw is a few dozen
3
+ // triangles. Nothing here knows a thread: sizes come in as plain numbers.
4
+ import jscad from '@jscad/modeling';
5
+
6
+ const { translate, rotateX, rotateY } = jscad.transforms, { geom3, poly3 } = jscad.geometries;
7
+
8
+ export const OUT = 0.1; // how far a cutter starts outside the face it enters by, so no faces lie on each other
9
+ export const SEGMENTS = 48; // round cutters
10
+ export const LIGHT = 12; // round reference hardware: an M3x12 cap screw in 96 triangles
11
+ /** The directions a cutter can go, as @rulecad/shapes names them. */
12
+ export const DIRECTIONS = ['+x', '-x', '+y', '-y', '+z', '-z'];
13
+ // Which way is up (+z in the part) in a cutter's own drawing, for one going across: where its roof points
14
+ export const UP = { '+x': [1, 0], '-x': [-1, 0], '+y': [0, 1], '-y': [0, -1] };
15
+ export const booleans = { union: jscad.booleans.union, subtract: jscad.booleans.subtract };
16
+
17
+ /** A cutter drawn going down from z = 0 (into -z), turned to go along `into` from the origin, then moved to `at`. */
18
+ export function along(g, into, at = [0, 0, 0]) {
19
+ const turn = { '-z': (x) => x, '+z': (x) => rotateX(Math.PI, x), '+x': (x) => rotateY(-Math.PI / 2, x), '-x': (x) => rotateY(Math.PI / 2, x),
20
+ '+y': (x) => rotateX(Math.PI / 2, x), '-y': (x) => rotateX(-Math.PI / 2, x) }[into];
21
+ return translate(at, turn(g));
22
+ }
23
+
24
+ /**
25
+ * A solid of revolution about z, from its profile: points [radius, z] running from the axis at the bottom, out, up and
26
+ * back to the axis at the top (or a closed loop clear of the axis, anticlockwise, for a ring). Each edge of the profile
27
+ * is one band of n flat faces, so the count of triangles is known: 2 n for a band, n where it meets the axis.
28
+ * @param {number[][]} profile @param {number} [n] faces round @param {number} [phase] the first corner's angle, radians
29
+ * @returns {object} a JSCAD geom3
30
+ */
31
+ export function lathe(profile, n = SEGMENTS, phase = 0) {
32
+ const ring = (r, z) => Array.from({ length: n }, (_, i) => { const a = phase + (2 * Math.PI * i) / n; return [r * Math.cos(a), r * Math.sin(a), z]; });
33
+ const pts = profile.filter((p, i) => i === 0 || Math.abs(p[0] - profile[i - 1][0]) > 1e-9 || Math.abs(p[1] - profile[i - 1][1]) > 1e-9);
34
+ const rings = pts.map(([r, z]) => (r > 1e-9 ? ring(r, z) : null)), polys = [], closed = !!rings[0] && !!rings.at(-1);
35
+ for (let e = 0; e < (closed ? pts.length : pts.length - 1); e++) {
36
+ const b = (e + 1) % pts.length, P = rings[e], Q = rings[b];
37
+ if (!P && !Q) continue;
38
+ for (let i = 0; i < n; i++) {
39
+ const j = (i + 1) % n;
40
+ polys.push(!P ? [[0, 0, pts[e][1]], Q[j], Q[i]] : !Q ? [P[i], P[j], [0, 0, pts[b][1]]] : [P[i], P[j], Q[j], Q[i]]);
41
+ }
42
+ }
43
+ return geom3.create(polys.map((p) => poly3.create(p)));
44
+ }
45
+
46
+ /** The volume a profile turns into, with true circles: each edge a frustum (mm³). @param {number[][]} profile @returns {number} */
47
+ export function turnedVolume(profile) {
48
+ let v = 0;
49
+ for (let i = 0; i < profile.length; i++) {
50
+ const [r0, z0] = profile[i], [r1, z1] = profile[(i + 1) % profile.length];
51
+ v += (Math.PI / 3) * (z0 - z1) * (r0 * r0 + r0 * r1 + r1 * r1); // (the shoelace sum of a turned outline: edges going down the outside add, going up take away)
52
+ }
53
+ return Math.abs(v);
54
+ }
55
+
56
+ /**
57
+ * A round cutter going down from z = 0, from its steps: [radius, depth] pairs from the mouth inwards, the radius
58
+ * changing between one depth and the next. It starts OUT above the face, and with through it runs OUT past its end.
59
+ * @param {number[][]} steps @param {{ through?: boolean }} [o] @returns {object} a JSCAD geom3 to subtract
60
+ */
61
+ export function bore(steps, { through = false } = {}) {
62
+ const last = steps.at(-1), end = last[1] + (through ? OUT : 0);
63
+ const side = [[steps[0][0], OUT], ...steps.map(([r, d]) => [r, -d])];
64
+ if (through) side.push([last[0], -end]);
65
+ return lathe([[0, -end], ...side.reverse(), [0, OUT]]);
66
+ }
67
+
68
+ /**
69
+ * A cutter lying on its side, going down from z = 0 in its own drawing, from its steps as bore takes them: at every
70
+ * depth its section is a teardrop, a circle with a 45° pointed roof on the up side, so it prints with no support. One
71
+ * closed solid with no joins in it, for the stepped and coned cutters @rulecad/shapes has no helper for.
72
+ * @param {number[][]} steps [radius, depth] pairs from the mouth inwards @param {number[]} up which way is up in the drawing: [1, 0], [0, 1] …
73
+ * @param {{ through?: boolean }} [o] @returns {object} a JSCAD geom3 to subtract
74
+ */
75
+ export function teardrop(steps, up, { through = false } = {}) {
76
+ // 35 steps round: no corner then lies level with the axis or 30° off it, the only places a corner's height is a round
77
+ // number of mm, where it could sit exactly in the plane a slicer (or printcheck) cuts a layer at
78
+ const turn = Math.atan2(up[1], up[0]), n = 35, last = steps.at(-1);
79
+ // the point of the roof, then the circle from 45° past it round to 45° short of it
80
+ const section = (r, z) => [[r * Math.SQRT2 * Math.cos(turn), r * Math.SQRT2 * Math.sin(turn), z], ...Array.from({ length: n + 1 }, (_, i) => { const t = turn + Math.PI / 4 + (1.5 * Math.PI * i) / n; return [r * Math.cos(t), r * Math.sin(t), z]; })];
81
+ const rings = [[steps[0][0], OUT], ...steps.map(([r, d]) => [r, -d]), ...(through ? [[last[0], -last[1] - OUT]] : [])].map(([r, z]) => section(r, z)), polys = [rings[0]];
82
+ for (let k = 0; k < rings.length - 1; k++) for (let i = 0; i < n + 2; i++) { const j = (i + 1) % (n + 2); polys.push([rings[k][i], rings[k + 1][i], rings[k + 1][j], rings[k][j]]); }
83
+ polys.push([...rings.at(-1)].reverse());
84
+ return geom3.create(polys.map((p) => poly3.create(p)));
85
+ }
package/fixings.d.mts ADDED
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Every function of this package with a workspace's rule sets and printer already in hand, so a design writes
3
+ * `fixings.hole('M3', { kind: 'pilot' })` and gets its own project's figures. This is the hook a host such as
4
+ * @rulecad/cad calls once per design: the package itself reads no files.
5
+ * @param {{ sets?: object, printer?: object, ops?: { union: Function, subtract: Function }, display?: 'thread' | 'plain' }} [workspace]
6
+ * sets: the workspace's rule sets, by name ({ m3: { name, rules } }) or as a list: one for a thread is used before the
7
+ * kit's; printer: the printer's rule set ({ name, rules }, so each figure keeps its kind and source) or its values;
8
+ * ops: the design's booleans (v.ops); display: how a printed thread is drawn where a call does not say (thread and a
9
+ * hole of kind 'thread'): 'plain' for a viewer or a link, where a real thread's thousands of triangles are not wanted
10
+ * @returns {Record<string, Function>} fixingModel(name, change, opts) and the rest, each taking (fixing, options); lengthFor takes (stack, fixing, options)
11
+ */
12
+ export function fixingsFor({ sets, printer, ops, display }?: {
13
+ sets?: object;
14
+ printer?: object;
15
+ ops?: {
16
+ union: Function;
17
+ subtract: Function;
18
+ };
19
+ display?: "thread" | "plain";
20
+ }): Record<string, Function>;
21
+ /**
22
+ * What this release is. `release` is `'placeholder'` until the package has functions to call (0.1.0), then `'ready'`:
23
+ * code that wants fixings can test it instead of failing on a missing export.
24
+ * @type {Readonly<{ release: 'placeholder' | 'ready', plan: string }>}
25
+ */
26
+ export const status: Readonly<{
27
+ release: "placeholder" | "ready";
28
+ plan: string;
29
+ }>;
30
+ export { fixingModel, parseName, threads, GRAMMAR, HEADS, NUTS, DEFAULTS } from "./model.mjs";
31
+ export { holeModel, hole, HOLE_KINDS } from "./holes.mjs";
32
+ export { counterboreModel, counterbore, countersinkModel, countersink, nutPocketModel, nutPocket, nutTrapModel, nutTrap, squareNutSlotModel, squareNutSlot, captiveNutModel, captiveNut, insertBossModel, insertBoss, printable } from "./seats.mjs";
33
+ export { screwModel, screw, nutModel, nut, washerModel, washer, insertModel, insert } from "./hardware.mjs";
34
+ export { threadModel, thread, THREAD_FORMS } from "./threads.mjs";
35
+ export { engagement, stripping, preload, torqueFor, seating, lengthFor, MATERIALS, MATERIAL_CLASSES, ENDS } from "./strength.mjs";
package/fixings.mjs ADDED
@@ -0,0 +1,53 @@
1
+ // @rulecad/fixings: screws, nuts, washers and inserts from rule sets, and the holes and seats they need in a printed
2
+ // part. A fixing is a model made from its thread's rule set (fixingModel), and everything else reads that model: a
3
+ // hole sized by what it is for (hole), a seat for a head, a nut or an insert (counterbore, countersink, nutPocket,
4
+ // nutTrap, squareNutSlot, captiveNut, insertBoss), and light solids of the hardware for an assembly (screw, nut,
5
+ // washer, insert), a real thread to print where one is wanted (thread), and first sums for a joint: thread engaged,
6
+ // the load that strips it, clamp force from torque, pressure under a head, and the sold length that fits a stack
7
+ // (engagement, stripping, preload, seating, lengthFor). Where it applies each comes as a pair: one function gives the
8
+ // numbers with findings (holeModel), its twin the solid (hole). Every thread's figures live in @rulecad/rules as open data: this package holds no
9
+ // screw's numbers of its own. Units: mm, degrees, grams. The plan is https://github.com/JoniBach/rulecad/issues/212.
10
+ import { fixingModel } from './model.mjs';
11
+ import { holeModel, hole } from './holes.mjs';
12
+ import { counterboreModel, counterbore, countersinkModel, countersink, nutPocketModel, nutPocket, nutTrapModel, nutTrap, squareNutSlotModel, squareNutSlot, captiveNutModel, captiveNut, insertBossModel, insertBoss, printable } from './seats.mjs';
13
+ import { screwModel, screw, nutModel, nut, washerModel, washer, insertModel, insert } from './hardware.mjs';
14
+ import { threadModel, thread } from './threads.mjs';
15
+ import { engagement, stripping, preload, torqueFor, seating, lengthFor } from './strength.mjs';
16
+
17
+ export { fixingModel, parseName, threads, GRAMMAR, HEADS, NUTS, DEFAULTS } from './model.mjs';
18
+ export { holeModel, hole, HOLE_KINDS } from './holes.mjs';
19
+ export { counterboreModel, counterbore, countersinkModel, countersink, nutPocketModel, nutPocket, nutTrapModel, nutTrap, squareNutSlotModel, squareNutSlot, captiveNutModel, captiveNut, insertBossModel, insertBoss, printable } from './seats.mjs';
20
+ export { screwModel, screw, nutModel, nut, washerModel, washer, insertModel, insert } from './hardware.mjs';
21
+ export { threadModel, thread, THREAD_FORMS } from './threads.mjs';
22
+ export { engagement, stripping, preload, torqueFor, seating, lengthFor, MATERIALS, MATERIAL_CLASSES, ENDS } from './strength.mjs';
23
+
24
+ /**
25
+ * What this release is. `release` is `'placeholder'` until the package has functions to call (0.1.0), then `'ready'`:
26
+ * code that wants fixings can test it instead of failing on a missing export.
27
+ * @type {Readonly<{ release: 'placeholder' | 'ready', plan: string }>}
28
+ */
29
+ export const status = Object.freeze({ release: 'ready', plan: 'https://github.com/JoniBach/rulecad/issues/212' });
30
+
31
+ const MODELS = { engagement, stripping, preload, torqueFor, seating, threadModel, holeModel, counterboreModel, countersinkModel, nutPocketModel, nutTrapModel, squareNutSlotModel, captiveNutModel, insertBossModel, screwModel, nutModel, washerModel, insertModel };
32
+ const SOLIDS = { thread, hole, counterbore, countersink, nutPocket, nutTrap, squareNutSlot, captiveNut, insertBoss, nut, washer, insert }, JOINED = { screw };
33
+
34
+ /**
35
+ * Every function of this package with a workspace's rule sets and printer already in hand, so a design writes
36
+ * `fixings.hole('M3', { kind: 'pilot' })` and gets its own project's figures. This is the hook a host such as
37
+ * @rulecad/cad calls once per design: the package itself reads no files.
38
+ * @param {{ sets?: object, printer?: object, ops?: { union: Function, subtract: Function }, display?: 'thread' | 'plain' }} [workspace]
39
+ * sets: the workspace's rule sets, by name ({ m3: { name, rules } }) or as a list: one for a thread is used before the
40
+ * kit's; printer: the printer's rule set ({ name, rules }, so each figure keeps its kind and source) or its values;
41
+ * ops: the design's booleans (v.ops); display: how a printed thread is drawn where a call does not say (thread and a
42
+ * hole of kind 'thread'): 'plain' for a viewer or a link, where a real thread's thousands of triangles are not wanted
43
+ * @returns {Record<string, Function>} fixingModel(name, change, opts) and the rest, each taking (fixing, options); lengthFor takes (stack, fixing, options)
44
+ */
45
+ export function fixingsFor({ sets, printer, ops, display } = {}) {
46
+ const with_ = (o) => (o && typeof o === 'object' && !Array.isArray(o) ? { ...(sets ? { sets } : {}), ...(printer ? { printer } : {}), ...o } : o);
47
+ const out = { fixingModel: (name, change, opts) => fixingModel(name, change, { ...(sets ? { sets } : {}), ...opts }), printable, status };
48
+ const drawn = ['threadModel', 'thread', 'holeModel', 'hole'], as = (k, o) => (display && drawn.includes(k) && o && typeof o === 'object' && !Array.isArray(o) ? { display, ...o } : o);
49
+ for (const [k, f] of Object.entries({ ...MODELS, ...SOLIDS })) out[k] = (m, o = {}) => f(m, with_(as(k, o)));
50
+ out.lengthFor = (stack, m, o = {}) => lengthFor(stack, m, with_(o));
51
+ for (const [k, f] of Object.entries(JOINED)) out[k] = (m, o = {}) => (ops ? f(m, with_(o), ops) : f(m, with_(o)));
52
+ return out;
53
+ }
package/hardware.d.mts ADDED
@@ -0,0 +1,215 @@
1
+ /**
2
+ * @typedef {{ origin: number[], axis: number[] }} Anchor a point and a direction an assembly places a part by, as a motor's are
3
+ */
4
+ /**
5
+ * A screw as numbers: its outline, the anchors an assembly places it by, and its mass.
6
+ * It stands on the z axis with its head up: the face its head seats on is at z = 0 and its thread runs down to
7
+ * z = -length. A countersunk screw and a set screw are measured overall, so their top is at z = 0.
8
+ * @param {Fixing | string} m a screw's model or name ('M3x12 cap'), or a thread with { length, head }
9
+ * @param {{ length?: number, head?: string, material?: 'steel' | 'stainless', anyLength?: boolean, sets?: object, display?: 'plain' | 'thread', printer?: object,
10
+ * mate?: 'printed' | 'bought', gap?: number, flanks?: 'printed' | 'standard', hand?: 'right' | 'left', segments?: number }} [o]
11
+ * length, head: where the model has none, or to change them; material: for its mass (default steel); display: plain
12
+ * (the light solid, the default) or thread (its thread drawn, to print it standing on its head: then printer, mate,
13
+ * gap, flanks, hand and segments are threadModel's)
14
+ * @returns {{ item: 'screw', name: string, thread: string, head: string, length: number, sold: boolean | null, major: number, headDiameter: number, headHeight: number, sink: number, top: number, key: number | null,
15
+ * mass: number, material: string, display: 'plain' | 'thread', threaded: object | null, anchors: { seat: Anchor, tip: Anchor, axis: Anchor, top: Anchor }, profile: number[][], rests: object[], findings: object[] }}
16
+ * sink: how deep a countersunk head's cone goes; top: the z of the head's top; mass: grams; threaded: threadModel's numbers where its thread is drawn;
17
+ * anchors: seat (under the head, or the flush face of a countersunk screw), tip, axis (the thread's, at the seat) and top (where a key goes in)
18
+ */
19
+ export function screwModel(m: Fixing | string, o?: {
20
+ length?: number;
21
+ head?: string;
22
+ material?: "steel" | "stainless";
23
+ anyLength?: boolean;
24
+ sets?: object;
25
+ display?: "plain" | "thread";
26
+ printer?: object;
27
+ mate?: "printed" | "bought";
28
+ gap?: number;
29
+ flanks?: "printed" | "standard";
30
+ hand?: "right" | "left";
31
+ segments?: number;
32
+ }): {
33
+ item: "screw";
34
+ name: string;
35
+ thread: string;
36
+ head: string;
37
+ length: number;
38
+ sold: boolean | null;
39
+ major: number;
40
+ headDiameter: number;
41
+ headHeight: number;
42
+ sink: number;
43
+ top: number;
44
+ key: number | null;
45
+ mass: number;
46
+ material: string;
47
+ display: "plain" | "thread";
48
+ threaded: object | null;
49
+ anchors: {
50
+ seat: Anchor;
51
+ tip: Anchor;
52
+ axis: Anchor;
53
+ top: Anchor;
54
+ };
55
+ profile: number[][];
56
+ rests: object[];
57
+ findings: object[];
58
+ };
59
+ /**
60
+ * A screw as a light solid: its thread a plain cylinder at the major diameter, its head an outline with no socket.
61
+ * An M3x12 cap screw is 96 triangles. With display: 'thread' its thread is drawn as threadModel gives it, in one
62
+ * closed solid that prints standing on its head: thousands of triangles, so only where it is asked for.
63
+ * @param {Fixing | string} m @param {{ length?: number, head?: string, material?: 'steel' | 'stainless', anyLength?: boolean, sets?: object, display?: 'plain' | 'thread', printer?: object,
64
+ * mate?: 'printed' | 'bought', gap?: number, flanks?: 'printed' | 'standard', hand?: 'right' | 'left', segments?: number }} [o] as screwModel
65
+ * @param {{ union: Function }} [ops] the design's v.ops (a hexagon head is joined to its thread)
66
+ * @returns {object} a JSCAD geom3, with .model holding screwModel's numbers (its anchors and mass)
67
+ */
68
+ export function screw(m: Fixing | string, o?: {
69
+ length?: number;
70
+ head?: string;
71
+ material?: "steel" | "stainless";
72
+ anyLength?: boolean;
73
+ sets?: object;
74
+ display?: "plain" | "thread";
75
+ printer?: object;
76
+ mate?: "printed" | "bought";
77
+ gap?: number;
78
+ flanks?: "printed" | "standard";
79
+ hand?: "right" | "left";
80
+ segments?: number;
81
+ }, ops?: {
82
+ union: Function;
83
+ }): object;
84
+ /**
85
+ * A nut as numbers. It stands on the z axis, the face it bears on at z = 0 and its top at z = its height.
86
+ * @param {Fixing | string} m a nut's model or name ('M3 lock nut'), or a thread with { kind }
87
+ * @param {{ kind?: string, material?: 'steel' | 'stainless', sets?: object, display?: 'plain' | 'thread', printer?: object, mate?: 'printed' | 'bought', gap?: number, flanks?: 'printed' | 'standard', hand?: 'right' | 'left', segments?: number }} [o]
88
+ * kind: hex, square or lock (default the model's, else hex); display: plain (the light solid) or thread (its thread drawn, to print it as it stands)
89
+ * @returns {{ item: 'nut', name: string, thread: string, kind: string, flats: number, across: number, height: number, bore: number, mass: number, material: string, display: 'plain' | 'thread', threaded: object | null,
90
+ * anchors: { seat: Anchor, top: Anchor, axis: Anchor }, rests: object[], findings: object[] }}
91
+ */
92
+ export function nutModel(m: Fixing | string, o?: {
93
+ kind?: string;
94
+ material?: "steel" | "stainless";
95
+ sets?: object;
96
+ display?: "plain" | "thread";
97
+ printer?: object;
98
+ mate?: "printed" | "bought";
99
+ gap?: number;
100
+ flanks?: "printed" | "standard";
101
+ hand?: "right" | "left";
102
+ segments?: number;
103
+ }): {
104
+ item: "nut";
105
+ name: string;
106
+ thread: string;
107
+ kind: string;
108
+ flats: number;
109
+ across: number;
110
+ height: number;
111
+ bore: number;
112
+ mass: number;
113
+ material: string;
114
+ display: "plain" | "thread";
115
+ threaded: object | null;
116
+ anchors: {
117
+ seat: Anchor;
118
+ top: Anchor;
119
+ axis: Anchor;
120
+ };
121
+ rests: object[];
122
+ findings: object[];
123
+ };
124
+ /**
125
+ * A nut as a light solid: a hexagon or a square with a plain bore just clear of the thread. With display: 'thread'
126
+ * its thread is drawn as threadModel gives it, in one closed solid that prints as it stands.
127
+ * @param {Fixing | string} m @param {{ kind?: string, material?: 'steel' | 'stainless', sets?: object, display?: 'plain' | 'thread', printer?: object, mate?: 'printed' | 'bought', gap?: number, flanks?: 'printed' | 'standard', hand?: 'right' | 'left', segments?: number }} [o] as nutModel
128
+ * @returns {object} a JSCAD geom3, with .model
129
+ */
130
+ export function nut(m: Fixing | string, o?: {
131
+ kind?: string;
132
+ material?: "steel" | "stainless";
133
+ sets?: object;
134
+ display?: "plain" | "thread";
135
+ printer?: object;
136
+ mate?: "printed" | "bought";
137
+ gap?: number;
138
+ flanks?: "printed" | "standard";
139
+ hand?: "right" | "left";
140
+ segments?: number;
141
+ }): object;
142
+ /**
143
+ * A plain washer as numbers. It lies on z = 0, its top at z = its thickness.
144
+ * @param {Fixing | string} m a washer's model or name ('M3 washer'), or a thread
145
+ * @param {{ material?: 'steel' | 'stainless', sets?: object }} [o]
146
+ * @returns {{ item: 'washer', name: string, thread: string, bore: number, diameter: number, thickness: number, mass: number, material: string, anchors: { seat: Anchor, top: Anchor, axis: Anchor }, rests: object[], findings: object[] }}
147
+ */
148
+ export function washerModel(m: Fixing | string, o?: {
149
+ material?: "steel" | "stainless";
150
+ sets?: object;
151
+ }): {
152
+ item: "washer";
153
+ name: string;
154
+ thread: string;
155
+ bore: number;
156
+ diameter: number;
157
+ thickness: number;
158
+ mass: number;
159
+ material: string;
160
+ anchors: {
161
+ seat: Anchor;
162
+ top: Anchor;
163
+ axis: Anchor;
164
+ };
165
+ rests: object[];
166
+ findings: object[];
167
+ };
168
+ /** A plain washer as a light solid: a flat ring. @param {Fixing | string} m @param {{ material?: 'steel' | 'stainless', sets?: object }} [o] @returns {object} a JSCAD geom3, with .model */
169
+ export function washer(m: Fixing | string, o?: {
170
+ material?: "steel" | "stainless";
171
+ sets?: object;
172
+ }): object;
173
+ /**
174
+ * A heat-set insert as numbers. It hangs down the z axis from the mouth of its hole: its top at z = 0, flush with the
175
+ * face it went in by, its far end at z = -length.
176
+ * @param {Fixing | string} m an insert's model or name ('M3 insert', 'M3x3 insert'), or a thread
177
+ * @param {{ sets?: object }} [o]
178
+ * @returns {{ item: 'insert', name: string, thread: string, diameter: number, length: number, bore: number, hole: number, mass: number, material: string, anchors: { seat: Anchor, bottom: Anchor, axis: Anchor }, rests: object[], findings: object[] }}
179
+ * diameter: over its knurls; hole: the hole it melts into, as drawn
180
+ */
181
+ export function insertModel(m: Fixing | string, o?: {
182
+ sets?: object;
183
+ }): {
184
+ item: "insert";
185
+ name: string;
186
+ thread: string;
187
+ diameter: number;
188
+ length: number;
189
+ bore: number;
190
+ hole: number;
191
+ mass: number;
192
+ material: string;
193
+ anchors: {
194
+ seat: Anchor;
195
+ bottom: Anchor;
196
+ axis: Anchor;
197
+ };
198
+ rests: object[];
199
+ findings: object[];
200
+ };
201
+ /** A heat-set insert as a light solid: a plain tube. @param {Fixing | string} m @param {{ sets?: object }} [o] @returns {object} a JSCAD geom3, with .model */
202
+ export function insert(m: Fixing | string, o?: {
203
+ sets?: object;
204
+ }): object;
205
+ /**
206
+ * a point and a direction an assembly places a part by, as a motor's are
207
+ */
208
+ export type Anchor = {
209
+ origin: number[];
210
+ axis: number[];
211
+ };
212
+ /**
213
+ * a fixing's model, as fixingModel gives it
214
+ */
215
+ export type Fixing = import("./model.mjs").Fixing;
package/hardware.mjs ADDED
@@ -0,0 +1,181 @@
1
+ // Reference hardware: a screw, a nut, a washer and an insert as light solids, so an assembly can show them and its
2
+ // overlap check can see them without thousands of triangles each. The thread is a plain cylinder at the major
3
+ // diameter, a head is its outline with no socket, and a bore is drawn just clear of the thread it takes. Each has a
4
+ // twin that gives its numbers: the anchors an assembly places it by and its mass. All stand on the z axis.
5
+ import jscad from '@jscad/modeling';
6
+ import { DEFAULTS, fixingOf, headOf, nutOf, lengthOf, screwName, figure, cite, rest, finding, positive, oneOf, shown, mm, r3, a } from './model.mjs';
7
+ import { optionsOf } from './holes.mjs';
8
+ import { lathe, turnedVolume, booleans, LIGHT } from './draw.mjs';
9
+ import { threadModel, threadedScrew, threadedNut } from './threads.mjs';
10
+
11
+ /**
12
+ * @typedef {import('./model.mjs').Fixing} Fixing a fixing's model, as fixingModel gives it
13
+ */
14
+
15
+ const { polygon, circle } = jscad.primitives, { extrudeLinear } = jscad.extrusions, { translate } = jscad.transforms;
16
+ const COS30 = Math.cos(Math.PI / 6), CLEAR = 1 / Math.cos(Math.PI / LIGHT); // a bore's corners lie this far out, so its flats clear the thread
17
+ const anchor = (z, up = 1) => ({ origin: [0, 0, z], axis: [0, 0, up] });
18
+ const MATERIALS = { steel: 'steel_density', stainless: 'stainless_density' };
19
+ // A mass in grams from a volume in mm³, with the density it used
20
+ function massOf(what, volume, material, density = MATERIALS[oneOf(what, 'material', material, Object.keys(MATERIALS))]) {
21
+ return { mass: r3((volume * DEFAULTS[density].value) / 1000), density: rest(`fixings.${density}`, DEFAULTS[density]) };
22
+ }
23
+ // The area a threaded length weighs as: a 60° thread's, at its pitch diameter; a plastic screw's, midway between its root and its crests
24
+ function threadArea(what, fx) {
25
+ const d = fx.form === 'plastic' && fx.figures.root_diameter ? (fx.major + figure(what, fx, 'root_diameter')) / 2 : fx.major - DEFAULTS.pitch_diameter.value * fx.pitch;
26
+ return (Math.PI / 4) * d * d;
27
+ }
28
+ // The thread of a piece of hardware drawn for printing (display: 'thread'): its model, or null for the light solid
29
+ const DISPLAYS = ['plain', 'thread'];
30
+ function drawnThread(what, fx, o, extra) {
31
+ if (oneOf(what, 'display', o.display ?? 'plain', DISPLAYS) === 'plain') return null;
32
+ return threadModel(fx, { what, printer: o.printer, sets: o.sets, mate: o.mate, gap: o.gap, flanks: o.flanks, hand: o.hand, starts: o.starts, pitch: o.pitch, segments: o.segments, ...extra });
33
+ }
34
+ const weighed = (name, mass, material, how) => finding('info', `${name}: ${mm(mass)} g of ${material}, an estimate from its outline (${how})`, 'fixing.mass', { values: { mass }, refs: { material } });
35
+
36
+ /**
37
+ * @typedef {{ origin: number[], axis: number[] }} Anchor a point and a direction an assembly places a part by, as a motor's are
38
+ */
39
+
40
+ /**
41
+ * A screw as numbers: its outline, the anchors an assembly places it by, and its mass.
42
+ * It stands on the z axis with its head up: the face its head seats on is at z = 0 and its thread runs down to
43
+ * z = -length. A countersunk screw and a set screw are measured overall, so their top is at z = 0.
44
+ * @param {Fixing | string} m a screw's model or name ('M3x12 cap'), or a thread with { length, head }
45
+ * @param {{ length?: number, head?: string, material?: 'steel' | 'stainless', anyLength?: boolean, sets?: object, display?: 'plain' | 'thread', printer?: object,
46
+ * mate?: 'printed' | 'bought', gap?: number, flanks?: 'printed' | 'standard', hand?: 'right' | 'left', segments?: number }} [o]
47
+ * length, head: where the model has none, or to change them; material: for its mass (default steel); display: plain
48
+ * (the light solid, the default) or thread (its thread drawn, to print it standing on its head: then printer, mate,
49
+ * gap, flanks, hand and segments are threadModel's)
50
+ * @returns {{ item: 'screw', name: string, thread: string, head: string, length: number, sold: boolean | null, major: number, headDiameter: number, headHeight: number, sink: number, top: number, key: number | null,
51
+ * mass: number, material: string, display: 'plain' | 'thread', threaded: object | null, anchors: { seat: Anchor, tip: Anchor, axis: Anchor, top: Anchor }, profile: number[][], rests: object[], findings: object[] }}
52
+ * sink: how deep a countersunk head's cone goes; top: the z of the head's top; mass: grams; threaded: threadModel's numbers where its thread is drawn;
53
+ * anchors: seat (under the head, or the flush face of a countersunk screw), tip, axis (the thread's, at the seat) and top (where a key goes in)
54
+ */
55
+ export function screwModel(m, o = {}) {
56
+ const what = 'screw';
57
+ optionsOf(what, o, '{ length: 12, head: \'cap\' }');
58
+ const fx = fixingOf(what, m, o);
59
+ if (!['screw', 'thread'].includes(fx.item)) throw new Error(`${what}: ${fx.name} is ${a(fx.item)}, not a screw: use ${fx.item}()`);
60
+ const form = o.head ?? fx.head?.form ?? (fx.made.heads.includes('cap') ? 'cap' : fx.made.heads[0]), head = headOf(what, fx, form);
61
+ if (o.length == null && fx.length == null) throw new Error(`${what}: give a length, in the name ('${fx.thread}x12 ${form}') or as { length: 12 }`);
62
+ const { length, sold } = o.length == null ? fx : form === 'set' ? { length: positive(what, 'length', o.length), sold: null } : lengthOf(what, fx, o.length, !!o.anyLength);
63
+ const r = fx.major / 2, R = head.across / 2, k = head.height, L = length;
64
+ // The outline, turned about z: from the tip up the thread, out under the head and over it
65
+ const sink = form === 'countersunk' ? Math.min(r3((R - r) / Math.tan((((head.angle ?? 90) / 2) * Math.PI) / 180)), L) : 0;
66
+ const profile = form === 'set' ? [[0, -L], [r, -L], [r, 0], [0, 0]]
67
+ : form === 'countersunk' ? [[0, -L], [r, -L], [r, -sink], [R, 0], [0, 0]]
68
+ : form === 'button' ? [[0, -L], [r, -L], [r, 0], [R, 0], [R, 0.3 * k], [0.55 * R, k], [0, k]]
69
+ : [[0, -L], [r, -L], [r, 0], [R, 0], [R, k], [0, k]]; // (a hexagon head's is its corners: the solid has six of them)
70
+ const top = form === 'set' || form === 'countersunk' ? 0 : k, shank = L - sink;
71
+ const headProfile = form === 'countersunk' ? [[0, -sink], [r, -sink], [R, 0], [0, 0]] : profile.filter(([, z]) => z >= 0).map((p, i) => (i === 0 ? [0, 0] : p));
72
+ const headVolume = form === 'set' ? 0 : form === 'hex' ? (Math.sqrt(3) / 2) * head.flats ** 2 * k : turnedVolume(headProfile);
73
+ const material = o.material ?? 'steel', w = massOf(what, threadArea(what, fx) * shank + headVolume, material), name = screwName(fx, L, form);
74
+ const threaded = drawnThread(what, fx, o, { length: shank, top: '-z' }); // (it prints standing on its head, so its tip is up)
75
+ return { item: 'screw', name, thread: fx.thread, head: form, length: L, sold, major: fx.major, headDiameter: head.across, headHeight: k, sink, top, key: head.key ?? null, mass: w.mass, material,
76
+ display: threaded ? 'thread' : 'plain', threaded, anchors: { seat: anchor(0), tip: anchor(-L, -1), axis: anchor(0), top: anchor(top) }, profile,
77
+ rests: [rest(cite(fx, 'major_diameter'), fx.figures.major_diameter), rest(cite(fx, 'pitch'), fx.figures.pitch), ...head.figures.map((n) => rest(cite(fx, n), fx.figures[n])), w.density, ...(threaded ? threaded.rests : [])],
78
+ findings: [weighed(name, w.mass, material, 'the thread at its pitch diameter, the head with no socket'), ...(threaded ? threaded.findings : [])] };
79
+ }
80
+
81
+ /**
82
+ * A screw as a light solid: its thread a plain cylinder at the major diameter, its head an outline with no socket.
83
+ * An M3x12 cap screw is 96 triangles. With display: 'thread' its thread is drawn as threadModel gives it, in one
84
+ * closed solid that prints standing on its head: thousands of triangles, so only where it is asked for.
85
+ * @param {Fixing | string} m @param {{ length?: number, head?: string, material?: 'steel' | 'stainless', anyLength?: boolean, sets?: object, display?: 'plain' | 'thread', printer?: object,
86
+ * mate?: 'printed' | 'bought', gap?: number, flanks?: 'printed' | 'standard', hand?: 'right' | 'left', segments?: number }} [o] as screwModel
87
+ * @param {{ union: Function }} [ops] the design's v.ops (a hexagon head is joined to its thread)
88
+ * @returns {object} a JSCAD geom3, with .model holding screwModel's numbers (its anchors and mass)
89
+ */
90
+ export function screw(m, o = {}, ops = booleans) {
91
+ const s = screwModel(m, o);
92
+ if (s.threaded) return Object.assign(threadedScrew(s, s.threaded), { model: s });
93
+ if (s.head !== 'hex') return Object.assign(lathe(s.profile, LIGHT), { model: s });
94
+ const r = s.major / 2, R = s.headDiameter / 2, k = s.headHeight;
95
+ return Object.assign(ops.union(lathe([[0, 0], [R, 0], [R, k], [0, k]], 6), lathe([[0, -s.length], [r, -s.length], [r, k / 2], [0, k / 2]], LIGHT)), { model: s });
96
+ }
97
+
98
+ /**
99
+ * A nut as numbers. It stands on the z axis, the face it bears on at z = 0 and its top at z = its height.
100
+ * @param {Fixing | string} m a nut's model or name ('M3 lock nut'), or a thread with { kind }
101
+ * @param {{ kind?: string, material?: 'steel' | 'stainless', sets?: object, display?: 'plain' | 'thread', printer?: object, mate?: 'printed' | 'bought', gap?: number, flanks?: 'printed' | 'standard', hand?: 'right' | 'left', segments?: number }} [o]
102
+ * kind: hex, square or lock (default the model's, else hex); display: plain (the light solid) or thread (its thread drawn, to print it as it stands)
103
+ * @returns {{ item: 'nut', name: string, thread: string, kind: string, flats: number, across: number, height: number, bore: number, mass: number, material: string, display: 'plain' | 'thread', threaded: object | null,
104
+ * anchors: { seat: Anchor, top: Anchor, axis: Anchor }, rests: object[], findings: object[] }}
105
+ */
106
+ export function nutModel(m, o = {}) {
107
+ const what = 'nut';
108
+ optionsOf(what, o, '{ kind: \'lock\' }');
109
+ const fx = fixingOf(what, m, o);
110
+ if (!['nut', 'thread'].includes(fx.item)) throw new Error(`${what}: ${fx.name} is ${a(fx.item)}, not a nut: use ${fx.item}()`);
111
+ const n = nutOf(what, fx, o.kind ?? fx.nut?.kind ?? 'hex'), area = n.kind === 'square' ? n.flats ** 2 : (Math.sqrt(3) / 2) * n.flats ** 2, material = o.material ?? 'steel';
112
+ const w = massOf(what, (area - threadArea(what, fx)) * n.height, material), name = `${fx.thread} ${n.kind} nut`, threaded = drawnThread(what, fx, o, { length: n.height, internal: true });
113
+ return { item: 'nut', name, thread: fx.thread, kind: n.kind, flats: n.flats, across: n.across, height: n.height, bore: fx.major, mass: w.mass, material, display: threaded ? 'thread' : 'plain', threaded,
114
+ anchors: { seat: anchor(0), top: anchor(n.height), axis: anchor(0) }, rests: [...n.figures.map((k) => rest(cite(fx, k), fx.figures[k])), rest(cite(fx, 'major_diameter'), fx.figures.major_diameter), w.density, ...(threaded ? threaded.rests : [])],
115
+ findings: [weighed(name, w.mass, material, n.kind === 'lock' ? 'a plain hexagon as tall as the nut with its collar' : 'its thread at the pitch diameter'), ...(threaded ? threaded.findings : [])] };
116
+ }
117
+
118
+ /**
119
+ * A nut as a light solid: a hexagon or a square with a plain bore just clear of the thread. With display: 'thread'
120
+ * its thread is drawn as threadModel gives it, in one closed solid that prints as it stands.
121
+ * @param {Fixing | string} m @param {{ kind?: string, material?: 'steel' | 'stainless', sets?: object, display?: 'plain' | 'thread', printer?: object, mate?: 'printed' | 'bought', gap?: number, flanks?: 'printed' | 'standard', hand?: 'right' | 'left', segments?: number }} [o] as nutModel
122
+ * @returns {object} a JSCAD geom3, with .model
123
+ */
124
+ export function nut(m, o = {}) {
125
+ const n = nutModel(m, o), sides = n.kind === 'square' ? 4 : 6, R = n.across / 2;
126
+ if (n.threaded) return Object.assign(threadedNut(n, n.threaded), { model: n });
127
+ // a hexagon's corner on x, as the pockets of @rulecad/shapes have it; a square's flats square to x and y
128
+ const outline = polygon({ points: Array.from({ length: sides }, (_, i) => { const t = (2 * Math.PI * (i + (sides === 4 ? 0.5 : 0))) / sides; return [R * Math.cos(t), R * Math.sin(t)]; }) });
129
+ return Object.assign(extrudeLinear({ height: n.height }, jscad.booleans.subtract(outline, circle({ radius: (n.bore / 2) * CLEAR, segments: LIGHT }))), { model: n });
130
+ }
131
+
132
+ /**
133
+ * A plain washer as numbers. It lies on z = 0, its top at z = its thickness.
134
+ * @param {Fixing | string} m a washer's model or name ('M3 washer'), or a thread
135
+ * @param {{ material?: 'steel' | 'stainless', sets?: object }} [o]
136
+ * @returns {{ item: 'washer', name: string, thread: string, bore: number, diameter: number, thickness: number, mass: number, material: string, anchors: { seat: Anchor, top: Anchor, axis: Anchor }, rests: object[], findings: object[] }}
137
+ */
138
+ export function washerModel(m, o = {}) {
139
+ const what = 'washer';
140
+ optionsOf(what, o, '{ material: \'stainless\' }');
141
+ const fx = fixingOf(what, m, o);
142
+ if (!['washer', 'thread'].includes(fx.item)) throw new Error(`${what}: ${fx.name} is ${a(fx.item)}, not a washer: use ${fx.item}()`);
143
+ if (!fx.made.washer) throw new Error(`${what}: ${fx.thread} has no washer in its rule set (${fx.set})`);
144
+ const bore = figure(what, fx, 'washer_bore'), diameter = figure(what, fx, 'washer_diameter'), thickness = figure(what, fx, 'washer_thickness'), material = o.material ?? 'steel';
145
+ const w = massOf(what, (Math.PI / 4) * (diameter ** 2 - bore ** 2) * thickness, material), name = `${fx.thread} washer`;
146
+ return { item: 'washer', name, thread: fx.thread, bore, diameter, thickness, mass: w.mass, material, anchors: { seat: anchor(0), top: anchor(thickness), axis: anchor(0) },
147
+ rests: [...['washer_bore', 'washer_diameter', 'washer_thickness'].map((k) => rest(cite(fx, k), fx.figures[k])), w.density], findings: [weighed(name, w.mass, material, 'a flat ring')] };
148
+ }
149
+
150
+ /** A plain washer as a light solid: a flat ring. @param {Fixing | string} m @param {{ material?: 'steel' | 'stainless', sets?: object }} [o] @returns {object} a JSCAD geom3, with .model */
151
+ export function washer(m, o = {}) {
152
+ const w = washerModel(m, o), r = (w.bore / 2) * CLEAR, R = w.diameter / 2;
153
+ return Object.assign(lathe([[r, 0], [R, 0], [R, w.thickness], [r, w.thickness]], LIGHT), { model: w });
154
+ }
155
+
156
+ /**
157
+ * A heat-set insert as numbers. It hangs down the z axis from the mouth of its hole: its top at z = 0, flush with the
158
+ * face it went in by, its far end at z = -length.
159
+ * @param {Fixing | string} m an insert's model or name ('M3 insert', 'M3x3 insert'), or a thread
160
+ * @param {{ sets?: object }} [o]
161
+ * @returns {{ item: 'insert', name: string, thread: string, diameter: number, length: number, bore: number, hole: number, mass: number, material: string, anchors: { seat: Anchor, bottom: Anchor, axis: Anchor }, rests: object[], findings: object[] }}
162
+ * diameter: over its knurls; hole: the hole it melts into, as drawn
163
+ */
164
+ export function insertModel(m, o = {}) {
165
+ const what = 'insert';
166
+ optionsOf(what, o, '{}');
167
+ const fx = fixingOf(what, m, o);
168
+ if (!['insert', 'thread'].includes(fx.item)) throw new Error(`${what}: ${fx.name} is ${a(fx.item)}, not an insert: use ${fx.item}()`);
169
+ if (!fx.made.insert) throw new Error(`${what}: ${fx.thread} has no heat-set insert in its rule set (${fx.set})`);
170
+ const diameter = figure(what, fx, 'insert_diameter'), length = figure(what, fx, 'insert_length');
171
+ const w = massOf(what, ((Math.PI / 4) * diameter ** 2 - threadArea(what, fx)) * length, 'brass', 'brass_density'), name = fx.item === 'insert' ? fx.name : `${fx.thread} insert`;
172
+ return { item: 'insert', name, thread: fx.thread, diameter, length, bore: fx.major, hole: figure(what, fx, 'insert_hole'), mass: w.mass, material: 'brass', anchors: { seat: anchor(0), bottom: anchor(-length, -1), axis: anchor(0) },
173
+ rests: [...['insert_diameter', 'insert_length'].map((k) => rest(cite(fx, k), fx.figures[k])), w.density], findings: [weighed(name, w.mass, 'brass', 'a plain tube over its knurls: the alloy is assumed')] };
174
+ }
175
+
176
+ /** A heat-set insert as a light solid: a plain tube. @param {Fixing | string} m @param {{ sets?: object }} [o] @returns {object} a JSCAD geom3, with .model */
177
+ export function insert(m, o = {}) {
178
+ const i = insertModel(m, o), r = (i.bore / 2) * CLEAR, R = i.diameter / 2;
179
+ if (!(R > r)) throw new Error(`insert: ${i.name} is ${mm(i.diameter)} mm over its knurls, no wider than its ${mm(i.bore)} mm thread (got ${shown(i.diameter)})`);
180
+ return Object.assign(translate([0, 0, -i.length], lathe([[r, 0], [R, 0], [R, i.length], [r, i.length]], LIGHT)), { model: i });
181
+ }