@rulecad/shapes 0.4.8 → 0.5.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/CHANGELOG.md CHANGED
@@ -4,6 +4,32 @@ What changed in each release, for someone upgrading a workspace. A **printed siz
4
4
  print (a hole's diameter, a seat's depth, a part's outline). Each release says whether any printed size moved, and
5
5
  why.
6
6
 
7
+ ## 0.5.0: an unused name removed; needs Node 22.13 or later, the version the kit is tested on
8
+
9
+ ### Changed
10
+
11
+ - A name the code never used is gone. No printed size moves, and nothing a design or a check does changes.
12
+
13
+ - @rulecad/shapes now states Node 22.13 or later in its `engines`, the same lowest Node as every rulecad package, and
14
+ the tests run on exactly Node 22.13.0 as well as the newest Node 24. Node 20 reached the end of its support on 30
15
+ April 2026, and the kit's packages stated five different lowest versions, some of them too low: on Node 20.6 to 20.9
16
+ `cad` stopped at start-up with "Unexpected token 'with'", and on Node 22.0 to 22.12 every `cad` command that runs a
17
+ design stops, because the sandbox designs run in cannot start there. npm gave no warning at install for either.
18
+
19
+ Upgrading: on a Node older than 22.13, npm now warns at install that this package needs Node 22.13; install Node 22.13
20
+ or later (24 recommended). Nothing else changes, and no printed size moves.
21
+
22
+ ## 0.4.9: swept parts as regions
23
+ ### Added
24
+
25
+ - `regionShape` (and so `optimisedOutline`) takes a region of `rings`: closed outlines solid on their left, holes
26
+ clockwise, as cad gives a part swept past a flat plate. It is cut with its holes open; drawn from its `points`
27
+ alone, the solver's single polygon of all its outlines, it would not be.
28
+
29
+ ### Printed sizes that moved
30
+
31
+ - None.
32
+
7
33
  ## 0.4.8: a part as a region
8
34
  ### Fixed
9
35
 
package/enclosure.mjs CHANGED
@@ -14,27 +14,54 @@
14
14
  // vents({ count, width, pitch, length, depth }) slots side by side along x, centred, each length long in z
15
15
  import jscad from '@jscad/modeling';
16
16
 
17
- const { polygon, roundedRectangle, rectangle, cuboid } = jscad.primitives, { extrudeLinear } = jscad.extrusions;
18
- const { translate, rotateX, rotateY } = jscad.transforms, { subtract, union } = jscad.booleans, { hull } = jscad.hulls;
17
+ const { polygon, roundedRectangle, rectangle, cuboid } = jscad.primitives,
18
+ { extrudeLinear } = jscad.extrusions;
19
+ const { translate, rotateX, rotateY } = jscad.transforms,
20
+ { subtract, union } = jscad.booleans,
21
+ { hull } = jscad.hulls;
19
22
  const THIN = 1e-3; // the height of a slice that hulls join into slopes
20
23
 
21
24
  /** A rectangle with rounded or cut corners, centred on 0. @returns {object} geom2 */
22
25
  export function outline(w, h, { round = 0, bevel = 0, segments = 32 } = {}) {
23
26
  if (!(w > 0) || !(h > 0)) throw new Error(`outline: ${w} × ${h} mm is not a shape`); // (NaN and missing too)
24
- if (round > 0) return roundedRectangle({ size: [w, h], roundRadius: Math.min(round, w / 2 - THIN, h / 2 - THIN), segments });
25
- if (bevel > 0) { const b = Math.min(bevel, w / 2, h / 2); return polygon({ points: [[-w / 2 + b, -h / 2], [w / 2 - b, -h / 2], [w / 2, -h / 2 + b], [w / 2, h / 2 - b], [w / 2 - b, h / 2], [-w / 2 + b, h / 2], [-w / 2, h / 2 - b], [-w / 2, -h / 2 + b]] }); }
27
+ if (round > 0)
28
+ return roundedRectangle({ size: [w, h], roundRadius: Math.min(round, w / 2 - THIN, h / 2 - THIN), segments });
29
+ if (bevel > 0) {
30
+ const b = Math.min(bevel, w / 2, h / 2);
31
+ return polygon({
32
+ points: [
33
+ [-w / 2 + b, -h / 2],
34
+ [w / 2 - b, -h / 2],
35
+ [w / 2, -h / 2 + b],
36
+ [w / 2, h / 2 - b],
37
+ [w / 2 - b, h / 2],
38
+ [-w / 2 + b, h / 2],
39
+ [-w / 2, h / 2 - b],
40
+ [-w / 2, -h / 2 + b],
41
+ ],
42
+ });
43
+ }
26
44
  return rectangle({ size: [w, h] });
27
45
  }
28
46
 
29
47
  // The outline moved in by d all round: a rounded corner keeps its centre, a cut corner its angle
30
- const inset = (o, d) => ({ ...o, width: o.width - d * 2, height: o.height - d * 2, round: o.round ? Math.max(o.round - d, 0) : 0, bevel: o.bevel ? Math.max(o.bevel - d * (2 - Math.SQRT2), 0) : 0 });
31
- const slice = (o, d, z0, z1 = z0 + THIN) => translate([0, 0, z0], extrudeLinear({ height: z1 - z0 }, outline(o.width - d * 2, o.height - d * 2, inset(o, d))));
48
+ const inset = (o, d) => ({
49
+ ...o,
50
+ width: o.width - d * 2,
51
+ height: o.height - d * 2,
52
+ round: o.round ? Math.max(o.round - d, 0) : 0,
53
+ bevel: o.bevel ? Math.max(o.bevel - d * (2 - Math.SQRT2), 0) : 0,
54
+ });
55
+ const slice = (o, d, z0, z1 = z0 + THIN) =>
56
+ translate([0, 0, z0], extrudeLinear({ height: z1 - z0 }, outline(o.width - d * 2, o.height - d * 2, inset(o, d))));
32
57
 
33
58
  /** A block on an outline, its lower and upper edges sloped in at 45 degrees by bottom and top. @returns {object} geom3 */
34
59
  export function slab({ width, height, depth, round = 0, bevel = 0, bottom = 0, top = 0, segments = 32 }) {
35
- for (const [k, v] of Object.entries({ width, height, depth })) if (!(typeof v === 'number' && v > 0)) throw new Error(`slab: ${k} is a size above 0 mm (got ${v})`);
60
+ for (const [k, v] of Object.entries({ width, height, depth }))
61
+ if (!(typeof v === 'number' && v > 0)) throw new Error(`slab: ${k} is a size above 0 mm (got ${v})`);
36
62
  const o = { width, height, round, bevel, segments };
37
- if (bottom + top >= depth) throw new Error(`slab: slopes of ${bottom} and ${top} mm need more than ${depth} mm of depth`);
63
+ if (bottom + top >= depth)
64
+ throw new Error(`slab: slopes of ${bottom} and ${top} mm need more than ${depth} mm of depth`);
38
65
  if (!bottom && !top) return slice(o, 0, 0, depth);
39
66
  return hull(slice(o, bottom, 0), slice(o, 0, bottom, depth - top), slice(o, top, depth - THIN));
40
67
  }
@@ -42,7 +69,10 @@ export function slab({ width, height, depth, round = 0, bevel = 0, bottom = 0, t
42
69
  /** A slab hollowed from floor up, open at the top; the walls wall thick. @returns {object} geom3 */
43
70
  export function shell({ wall, floor, ...o }) {
44
71
  const room = inset({ ...o, round: o.round || 0, bevel: o.bevel || 0 }, wall);
45
- return subtract(slab(o), translate([0, 0, floor], extrudeLinear({ height: o.depth }, outline(room.width, room.height, room))));
72
+ return subtract(
73
+ slab(o),
74
+ translate([0, 0, floor], extrudeLinear({ height: o.depth }, outline(room.width, room.height, room))),
75
+ );
46
76
  }
47
77
 
48
78
  /**
@@ -53,32 +83,54 @@ export function lid({ width, height, round = 0, bevel = 0, thick, edge = 0, wall
53
83
  const o = { width, height, round, bevel, segments };
54
84
  const plate = slab({ ...o, depth: thick, bottom: edge });
55
85
  if (!lip) return plate;
56
- const out = inset(o, wall + fit), hole = inset(o, wall + fit + ring);
86
+ const out = inset(o, wall + fit),
87
+ hole = inset(o, wall + fit + ring);
57
88
  const band = subtract(outline(out.width, out.height, out), outline(hole.width, hole.height, hole));
58
89
  return union(plate, translate([0, 0, thick], extrudeLinear({ height: lip }, band)));
59
90
  }
60
91
 
61
92
  /** A dovetail rail's profile (gap 0) or the slot that takes it (gap > 0), rising from y = 0, flanks at 45 degrees. */
62
93
  export function dovetail({ base, height, gap = 0 }) {
63
- const b = base / 2 + gap, t = b + height + (gap ? gap : 0), y = height + gap;
64
- return polygon({ points: [[-b, gap ? -1 : 0], [b, gap ? -1 : 0], [b, 0], [t, y], [-t, y], [-b, 0]] });
94
+ const b = base / 2 + gap,
95
+ t = b + height + (gap ? gap : 0),
96
+ y = height + gap;
97
+ return polygon({
98
+ points: [
99
+ [-b, gap ? -1 : 0],
100
+ [b, gap ? -1 : 0],
101
+ [b, 0],
102
+ [t, y],
103
+ [-t, y],
104
+ [-b, 0],
105
+ ],
106
+ });
65
107
  }
66
108
 
67
109
  /** A box [x0, x1] × [y0, y1] × [z0, z1] with a 45 degree gabled roof above z1, its ridge along axis ('x' or 'y'). */
68
110
  export function gabled([x0, x1], [y0, y1], [z0, z1], axis = 'y') {
69
- const box = (a0, a1, b0, b1, c0, c1) => translate([(a0 + a1) / 2, (b0 + b1) / 2, (c0 + c1) / 2], cuboid({ size: [a1 - a0, b1 - b0, c1 - c0] }));
70
- const half = axis === 'y' ? (x1 - x0) / 2 : (y1 - y0) / 2, mx = (x0 + x1) / 2, my = (y0 + y1) / 2;
71
- const ridge = axis === 'y' ? box(mx - THIN, mx + THIN, y0, y1, z1, z1 + half) : box(x0, x1, my - THIN, my + THIN, z1, z1 + half);
111
+ const box = (a0, a1, b0, b1, c0, c1) =>
112
+ translate([(a0 + a1) / 2, (b0 + b1) / 2, (c0 + c1) / 2], cuboid({ size: [a1 - a0, b1 - b0, c1 - c0] }));
113
+ const half = axis === 'y' ? (x1 - x0) / 2 : (y1 - y0) / 2,
114
+ mx = (x0 + x1) / 2,
115
+ my = (y0 + y1) / 2;
116
+ const ridge =
117
+ axis === 'y' ? box(mx - THIN, mx + THIN, y0, y1, z1, z1 + half) : box(x0, x1, my - THIN, my + THIN, z1, z1 + half);
72
118
  return hull(box(x0, x1, y0, y1, z0, z1), ridge);
73
119
  }
74
120
 
75
121
  /** A square hole size wide turned 45 degrees about axis, through length, centred on 0. */
76
122
  export function diamond(size, axis = 'y', length = 10) {
77
123
  const a = size / Math.SQRT2;
78
- return axis === 'y' ? rotateY(Math.PI / 4, cuboid({ size: [a, length, a] })) : rotateX(Math.PI / 4, cuboid({ size: [length, a, a] }));
124
+ return axis === 'y'
125
+ ? rotateY(Math.PI / 4, cuboid({ size: [a, length, a] }))
126
+ : rotateX(Math.PI / 4, cuboid({ size: [length, a, a] }));
79
127
  }
80
128
 
81
129
  /** Vent slots side by side along x, centred on 0: count of them, width wide, pitch apart, length long in z, depth in y. */
82
130
  export function vents({ count, width, pitch, length, depth }) {
83
- return union(...Array.from({ length: count }, (_, i) => translate([(i - (count - 1) / 2) * pitch, 0, 0], cuboid({ size: [width, depth, length] }))));
131
+ return union(
132
+ ...Array.from({ length: count }, (_, i) =>
133
+ translate([(i - (count - 1) / 2) * pitch, 0, 0], cuboid({ size: [width, depth, length] })),
134
+ ),
135
+ );
84
136
  }
package/features.mjs CHANGED
@@ -17,16 +17,24 @@
17
17
  // printer's bridge, a wider one rises at 45° each side to a flat that wide (height is the square part)
18
18
  import jscad from '@jscad/modeling';
19
19
 
20
- const { cylinder, cylinderElliptic, cuboid } = jscad.primitives, { translate, rotateX, rotateY, rotateZ } = jscad.transforms;
21
- const { hull } = jscad.hulls, { union } = jscad.booleans;
20
+ const { cylinder, cylinderElliptic, cuboid } = jscad.primitives,
21
+ { translate, rotateX, rotateY, rotateZ } = jscad.transforms;
22
+ const { hull } = jscad.hulls,
23
+ { union } = jscad.booleans;
22
24
  const TINY = 1e-3; // a slice's thickness, where a hull comes to a point
23
25
  const OUT = 0.1; // how far a cutter starts outside the face it enters by, so no faces lie on each other
24
26
  const EDGE = 0.05; // a ridge's width: a sharp point, without the slivers a vanishing one leaves
25
27
 
26
28
  // A cutter drawn going down from z = 0 (into = -z), turned to go along `into` from the origin, then moved to `at`
27
29
  function along(g, into, at = [0, 0, 0]) {
28
- 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),
29
- '+y': (x) => rotateX(Math.PI / 2, x), '-y': (x) => rotateX(-Math.PI / 2, x) }[into];
30
+ const turn = {
31
+ '-z': (x) => x,
32
+ '+z': (x) => rotateX(Math.PI, x),
33
+ '+x': (x) => rotateY(-Math.PI / 2, x),
34
+ '-x': (x) => rotateY(Math.PI / 2, x),
35
+ '+y': (x) => rotateX(Math.PI / 2, x),
36
+ '-y': (x) => rotateX(-Math.PI / 2, x),
37
+ }[into];
30
38
  if (!turn) throw new Error(`into must be +x, -x, +y, -y, +z or -z (got ${into})`);
31
39
  return translate(at, turn(g));
32
40
  }
@@ -37,27 +45,48 @@ const across = (into) => into in UP;
37
45
  // A round cutter from z = z0 down to z1, and its 45° ridge on the up side (r(z) the radius at each end)
38
46
  function tear(r0, r1, z0, z1, up) {
39
47
  // The ridge: a thin square turned 45° about the cutter's axis, its far corner at r√2, so the roof meets it at 45°
40
- const ridge = (r, z) => translate([up[0] * (r * Math.SQRT2 - EDGE / Math.SQRT2), up[1] * (r * Math.SQRT2 - EDGE / Math.SQRT2), z], rotateZ(Math.PI / 4, cuboid({ size: [EDGE, EDGE, TINY] })));
41
- const round = r0 === r1 ? translate([0, 0, (z0 + z1) / 2], cylinder({ radius: r0, height: Math.abs(z0 - z1), segments: 48 }))
42
- : translate([0, 0, (z0 + z1) / 2], cylinderElliptic({ height: Math.abs(z0 - z1), startRadius: [r1, r1], endRadius: [r0, r0], segments: 48 }));
48
+ const ridge = (r, z) =>
49
+ translate(
50
+ [up[0] * (r * Math.SQRT2 - EDGE / Math.SQRT2), up[1] * (r * Math.SQRT2 - EDGE / Math.SQRT2), z],
51
+ rotateZ(Math.PI / 4, cuboid({ size: [EDGE, EDGE, TINY] })),
52
+ );
53
+ const round =
54
+ r0 === r1
55
+ ? translate([0, 0, (z0 + z1) / 2], cylinder({ radius: r0, height: Math.abs(z0 - z1), segments: 48 }))
56
+ : translate(
57
+ [0, 0, (z0 + z1) / 2],
58
+ cylinderElliptic({ height: Math.abs(z0 - z1), startRadius: [r1, r1], endRadius: [r0, r0], segments: 48 }),
59
+ );
43
60
  return up ? hull(round, ridge(r0, z0), ridge(r1, z1)) : round;
44
61
  }
45
62
 
46
-
47
63
  // Sizes are lengths above 0: a feature given 0 or less (or nothing) says so by name, rather than drawing garbage
48
- function sizes(what, o) { for (const [k, v] of Object.entries(o)) if (!(typeof v === 'number' && v > 0)) throw new Error(`${what}: ${k} is a size above 0 mm (got ${v})`); }
64
+ function sizes(what, o) {
65
+ for (const [k, v] of Object.entries(o))
66
+ if (!(typeof v === 'number' && v > 0)) throw new Error(`${what}: ${k} is a size above 0 mm (got ${v})`);
67
+ }
49
68
 
50
69
  /** A flat-head screw's hole and 90° countersink, the head flush with the face at `at`. */
51
70
  export function countersink({ hole, head, length, at = [0, 0, 0], into = '-z', teardrop = across(into) }) {
52
71
  sizes('countersink', { hole, head, length });
53
- const up = teardrop ? UP[into] : null, cone = (head - hole) / 2;
54
- return along(union(tear(head / 2, head / 2, OUT, 0, up), tear(head / 2, hole / 2, 0, -cone, up), tear(hole / 2, hole / 2, -cone / 2, -length, up)), into, at); // overlapping, not touching: clean seams
72
+ const up = teardrop ? UP[into] : null,
73
+ cone = (head - hole) / 2;
74
+ return along(
75
+ union(
76
+ tear(head / 2, head / 2, OUT, 0, up),
77
+ tear(head / 2, hole / 2, 0, -cone, up),
78
+ tear(hole / 2, hole / 2, -cone / 2, -length, up),
79
+ ),
80
+ into,
81
+ at,
82
+ ); // overlapping, not touching: clean seams
55
83
  }
56
84
 
57
85
  /** A round hole across a part, with a 45° roof so it prints without support. */
58
86
  export function teardropHole({ d, length, at = [0, 0, 0], into = '+x', through = false }) {
59
87
  sizes('teardropHole', { d, length });
60
- if (!across(into)) throw new Error('teardropHole goes across a part: into ±x or ±y (a hole up or down is a plain cylinder)');
88
+ if (!across(into))
89
+ throw new Error('teardropHole goes across a part: into ±x or ±y (a hole up or down is a plain cylinder)');
61
90
  // through: out past the far face as it starts out past the near one, so a hole exactly as long as its wall leaves no
62
91
  // skin of faces lying on each other
63
92
  return along(tear(d / 2, d / 2, OUT, -length - (through ? OUT : 0), UP[into]), into, at);
@@ -73,28 +102,50 @@ export function nutPocket({ flats, height, hole, at = [0, 0, 0], into = '-z' })
73
102
  if (into !== '+z') return along(hex(pocket), into, at);
74
103
  // Going up from the bed face: a 45° hexagonal roof from the corners to the hole, so nothing spans
75
104
  const rise = corner - hole / 2;
76
- const roof = translate([0, 0, -height - rise / 2], cylinderElliptic({ height: rise, startRadius: [hole / 2, hole / 2], endRadius: [corner, corner], segments: 6 }));
105
+ const roof = translate(
106
+ [0, 0, -height - rise / 2],
107
+ cylinderElliptic({ height: rise, startRadius: [hole / 2, hole / 2], endRadius: [corner, corner], segments: 6 }),
108
+ );
77
109
  return along(union(pocket, roof), into, at);
78
110
  }
79
111
 
80
112
  /** Half-round crush ribs on a pocket's wall, for a press fit that takes a range of sizes. To add to the part. */
81
113
  export function crushRibs({ at, into, z, radius, protrude }) {
82
114
  sizes('crushRibs', { radius, protrude });
83
- return union(...at.map(([x, y], i) => {
84
- const [nx, ny] = into[i] || into[0], back = radius - protrude;
85
- return translate([x - nx * back, y - ny * back, (z[0] + z[1]) / 2], cylinder({ radius, height: z[1] - z[0], segments: 24 }));
86
- }));
115
+ return union(
116
+ ...at.map(([x, y], i) => {
117
+ const [nx, ny] = into[i] || into[0],
118
+ back = radius - protrude;
119
+ return translate(
120
+ [x - nx * back, y - ny * back, (z[0] + z[1]) / 2],
121
+ cylinder({ radius, height: z[1] - z[0], segments: 24 }),
122
+ );
123
+ }),
124
+ );
87
125
  }
88
126
 
89
127
  /** A square-cornered opening through an upright wall, centred on at (a cable's plug, a switch). */
90
128
  export function wallOpening({ width, height, depth, at = [0, 0, 0], into = '-y', bridge }) {
91
129
  sizes('wallOpening', { width, height, depth });
92
130
  if (!across(into)) throw new Error('wallOpening goes through an upright wall: into ±x or ±y');
93
- const long = depth + OUT, w = into.endsWith('x') ? [long, width, height] : [width, long, height], dir = into[0] === '+' ? 1 : -1;
94
- const off = into.endsWith('x') ? [dir * (depth - OUT) / 2, 0, 0] : [0, dir * (depth - OUT) / 2, 0];
131
+ const long = depth + OUT,
132
+ w = into.endsWith('x') ? [long, width, height] : [width, long, height],
133
+ dir = into[0] === '+' ? 1 : -1;
134
+ const off = into.endsWith('x') ? [(dir * (depth - OUT)) / 2, 0, 0] : [0, (dir * (depth - OUT)) / 2, 0];
95
135
  const box = cuboid({ size: w });
96
- if (bridge == null || width <= bridge) return translate(at.map((a, k) => a + off[k]), box);
136
+ if (bridge == null || width <= bridge)
137
+ return translate(
138
+ at.map((a, k) => a + off[k]),
139
+ box,
140
+ );
97
141
  // Wider than the printer bridges: the top rises at 45° each side to a flat as wide as it can span
98
- const rise = (width - bridge) / 2, top = translate([0, 0, height / 2 + rise], cuboid({ size: into.endsWith('x') ? [long, bridge, TINY] : [bridge, long, TINY] }));
99
- return translate(at.map((a, k) => a + off[k]), hull(box, top));
142
+ const rise = (width - bridge) / 2,
143
+ top = translate(
144
+ [0, 0, height / 2 + rise],
145
+ cuboid({ size: into.endsWith('x') ? [long, bridge, TINY] : [bridge, long, TINY] }),
146
+ );
147
+ return translate(
148
+ at.map((a, k) => a + off[k]),
149
+ hull(box, top),
150
+ );
100
151
  }
package/ops.mjs CHANGED
@@ -17,30 +17,64 @@ export async function ops(engine = 'jscad') {
17
17
  const stats = { ops: 0, fallbacks: 0 };
18
18
  const { union, subtract, intersect } = jscad.booleans;
19
19
  // (the gap between two solids needs Manifold: JSCAD has no distance query, so it says so by name)
20
- const noGap = () => { throw Object.assign(new Error('gap needs the manifold engine: ops(\'manifold\'), with manifold-3d installed'), { code: 'engine.gap' }); };
21
- if (engine === 'jscad') return { engine, stats, union: (...a) => (stats.ops++, union(...flat(a))), subtract: (...a) => (stats.ops++, subtract(...flat(a))), intersect: (...a) => (stats.ops++, intersect(...flat(a))), gap: noGap };
20
+ const noGap = () => {
21
+ throw Object.assign(new Error("gap needs the manifold engine: ops('manifold'), with manifold-3d installed"), {
22
+ code: 'engine.gap',
23
+ });
24
+ };
25
+ if (engine === 'jscad')
26
+ return {
27
+ engine,
28
+ stats,
29
+ union: (...a) => (stats.ops++, union(...flat(a))),
30
+ subtract: (...a) => (stats.ops++, subtract(...flat(a))),
31
+ intersect: (...a) => (stats.ops++, intersect(...flat(a))),
32
+ gap: noGap,
33
+ };
22
34
  if (engine !== 'manifold') throw new Error(`no boolean engine "${engine}" (jscad or manifold)`);
23
35
  let wasm;
24
- try { wasm = await (await import('manifold-3d')).default(); } catch (e) {
25
- throw Object.assign(new Error('the manifold engine needs manifold-3d: npm install manifold-3d (in the workspace)'), { code: 'engine.missing', cause: e });
36
+ try {
37
+ wasm = await (await import('manifold-3d')).default();
38
+ } catch (e) {
39
+ throw Object.assign(
40
+ new Error('the manifold engine needs manifold-3d: npm install manifold-3d (in the workspace)'),
41
+ { code: 'engine.missing', cause: e },
42
+ );
26
43
  }
27
44
  wasm.setup();
28
45
  const { Manifold, Mesh } = wasm;
29
46
  // JSCAD → Manifold: the shape's faces as triangles, corners shared where they meet
30
47
  const toManifold = (g) => {
31
- const verts = [], tris = [], index = new Map();
32
- const at = (v) => { const k = `${v[0]},${v[1]},${v[2]}`; if (!index.has(k)) { index.set(k, verts.length / 3); verts.push(v[0], v[1], v[2]); } return index.get(k); };
33
- for (const p of geom3.toPolygons(g)) { const ids = p.vertices.map(at); for (let i = 1; i < ids.length - 1; i++) tris.push(ids[0], ids[i], ids[i + 1]); }
48
+ const verts = [],
49
+ tris = [],
50
+ index = new Map();
51
+ const at = (v) => {
52
+ const k = `${v[0]},${v[1]},${v[2]}`;
53
+ if (!index.has(k)) {
54
+ index.set(k, verts.length / 3);
55
+ verts.push(v[0], v[1], v[2]);
56
+ }
57
+ return index.get(k);
58
+ };
59
+ for (const p of geom3.toPolygons(g)) {
60
+ const ids = p.vertices.map(at);
61
+ for (let i = 1; i < ids.length - 1; i++) tris.push(ids[0], ids[i], ids[i + 1]);
62
+ }
34
63
  const mesh = new Mesh({ numProp: 3, vertProperties: new Float32Array(verts), triVerts: new Uint32Array(tris) });
35
64
  mesh.merge();
36
65
  const m = new Manifold(mesh);
37
- if (m.status() !== 'NoError') { m.delete(); throw new Error(`not a closed solid (${m.status()})`); }
66
+ if (m.status() !== 'NoError') {
67
+ m.delete();
68
+ throw new Error(`not a closed solid (${m.status()})`);
69
+ }
38
70
  return m;
39
71
  };
40
72
  // Manifold → JSCAD: its triangles as faces
41
73
  const toGeom = (m) => {
42
- const { vertProperties: v, triVerts: t, numProp: n } = m.getMesh(), polys = [];
43
- for (let i = 0; i < t.length; i += 3) polys.push(poly3.create([t[i], t[i + 1], t[i + 2]].map((k) => [v[k * n], v[k * n + 1], v[k * n + 2]])));
74
+ const { vertProperties: v, triVerts: t, numProp: n } = m.getMesh(),
75
+ polys = [];
76
+ for (let i = 0; i < t.length; i += 3)
77
+ polys.push(poly3.create([t[i], t[i + 1], t[i + 2]].map((k) => [v[k * n], v[k * n + 1], v[k * n + 2]])));
44
78
  return geom3.create(polys);
45
79
  };
46
80
  const run = (name, jscadOp, list) => {
@@ -50,22 +84,48 @@ export async function ops(engine = 'jscad') {
50
84
  let made = [];
51
85
  try {
52
86
  made = shapes.map(toManifold);
53
- const out = name === 'union' ? Manifold.union(made) : name === 'intersect' ? Manifold.intersection(made)
54
- : made.slice(1).reduce((a, b) => { const r = a.subtract(b); if (a !== made[0]) a.delete(); return r; }, made[0]);
87
+ const out =
88
+ name === 'union'
89
+ ? Manifold.union(made)
90
+ : name === 'intersect'
91
+ ? Manifold.intersection(made)
92
+ : made.slice(1).reduce((a, b) => {
93
+ const r = a.subtract(b);
94
+ if (a !== made[0]) a.delete();
95
+ return r;
96
+ }, made[0]);
55
97
  const g = toGeom(out);
56
98
  if (!made.includes(out)) out.delete();
57
99
  return g;
58
100
  } catch {
59
101
  stats.fallbacks++;
60
102
  return jscadOp(...shapes);
61
- } finally { for (const m of made) m.delete(); }
103
+ } finally {
104
+ for (const m of made) m.delete();
105
+ }
62
106
  };
63
107
  // The least distance between two solids' surfaces, by Manifold's minGap, up to `within` mm (beyond it, within is
64
108
  // returned: nothing nearer). 0 when they touch or cross.
65
109
  const gap = (a, b, within = 1) => {
66
- if (!(typeof within === 'number' && within > 0)) throw new Error(`gap: within is how far to look, in mm above 0 (got ${JSON.stringify(within)})`);
67
- let ma = null, mb = null;
68
- try { ma = toManifold(a); mb = toManifold(b); return Math.max(0, ma.minGap(mb, within)); } finally { ma?.delete(); mb?.delete(); }
110
+ if (!(typeof within === 'number' && within > 0))
111
+ throw new Error(`gap: within is how far to look, in mm above 0 (got ${JSON.stringify(within)})`);
112
+ let ma = null,
113
+ mb = null;
114
+ try {
115
+ ma = toManifold(a);
116
+ mb = toManifold(b);
117
+ return Math.max(0, ma.minGap(mb, within));
118
+ } finally {
119
+ ma?.delete();
120
+ mb?.delete();
121
+ }
122
+ };
123
+ return {
124
+ engine,
125
+ stats,
126
+ union: (...a) => run('union', union, a),
127
+ subtract: (...a) => run('subtract', subtract, a),
128
+ intersect: (...a) => run('intersect', intersect, a),
129
+ gap,
69
130
  };
70
- return { engine, stats, union: (...a) => run('union', union, a), subtract: (...a) => run('subtract', subtract, a), intersect: (...a) => run('intersect', intersect, a), gap };
71
131
  }
package/optimised.d.mts CHANGED
@@ -4,9 +4,10 @@
4
4
  */
5
5
  export function fromOutlines(loops: [number, number][][]): jscad.geometries.geom2.Geom2;
6
6
  /**
7
- * A region of a problem (a circle, a centred rectangle or a polygon) as a JSCAD 2D shape; a design's part is null (it
8
- * is the design's own to add or cut, as it is in 3D).
9
- * @param {{ at?: [number, number], r?: number, size?: [number, number], points?: [number, number][], part?: string }} r
7
+ * A region of a problem (a circle, a centred rectangle, a polygon, or rings: closed outlines solid on their left, holes
8
+ * clockwise, as a part swept past the plate is cut) as a JSCAD 2D shape; a design's part is null (it is the design's own
9
+ * to add or cut, as it is in 3D).
10
+ * @param {{ at?: [number, number], r?: number, size?: [number, number], points?: [number, number][], rings?: [number, number][][], part?: string }} r
10
11
  * @param {number} [segments]
11
12
  */
12
13
  export function regionShape(r: {
@@ -14,6 +15,7 @@ export function regionShape(r: {
14
15
  r?: number;
15
16
  size?: [number, number];
16
17
  points?: [number, number][];
18
+ rings?: [number, number][][];
17
19
  part?: string;
18
20
  }, segments?: number): jscad.geometries.geom2.Geom2;
19
21
  /**
package/optimised.mjs CHANGED
@@ -9,8 +9,11 @@
9
9
  // mesh is big: pass v.ops, with the object's engine set to manifold
10
10
  import jscad from '@jscad/modeling';
11
11
 
12
- const { geom2 } = jscad.geometries, { circle, rectangle, polygon, polyhedron, cuboid, cylinder, sphere } = jscad.primitives, { union, subtract } = jscad.booleans;
13
- const { rotateX, rotateY, rotateZ, translate } = jscad.transforms, { hull } = jscad.hulls;
12
+ const { geom2 } = jscad.geometries,
13
+ { circle, rectangle, polygon, polyhedron, cuboid, cylinder, sphere } = jscad.primitives,
14
+ { union, subtract } = jscad.booleans;
15
+ const { rotateX, rotateY, rotateZ, translate } = jscad.transforms,
16
+ { hull } = jscad.hulls;
14
17
 
15
18
  /**
16
19
  * Closed loops (solid on the left) as one JSCAD 2D shape.
@@ -23,13 +26,15 @@ export function fromOutlines(loops) {
23
26
  }
24
27
 
25
28
  /**
26
- * A region of a problem (a circle, a centred rectangle or a polygon) as a JSCAD 2D shape; a design's part is null (it
27
- * is the design's own to add or cut, as it is in 3D).
28
- * @param {{ at?: [number, number], r?: number, size?: [number, number], points?: [number, number][], part?: string }} r
29
+ * A region of a problem (a circle, a centred rectangle, a polygon, or rings: closed outlines solid on their left, holes
30
+ * clockwise, as a part swept past the plate is cut) as a JSCAD 2D shape; a design's part is null (it is the design's own
31
+ * to add or cut, as it is in 3D).
32
+ * @param {{ at?: [number, number], r?: number, size?: [number, number], points?: [number, number][], rings?: [number, number][][], part?: string }} r
29
33
  * @param {number} [segments]
30
34
  */
31
35
  export function regionShape(r, segments = 48) {
32
36
  if (r.part || r.triangles) return null;
37
+ if (r.rings) return fromOutlines(r.rings); // a section of several outlines (a part swept past, its holes open), each solid on its left
33
38
  if (r.points) return polygon({ points: r.points });
34
39
  if (r.size) return rectangle({ center: r.at, size: r.size });
35
40
  return circle({ center: r.at, radius: r.r, segments });
@@ -42,7 +47,8 @@ export function regionShape(r, segments = 48) {
42
47
  */
43
48
  export function optimisedOutline(result, { segments = 48 } = {}) {
44
49
  let shape = fromOutlines(result.outlines);
45
- const keep = result.regions.keep.map((r) => regionShape(r, segments)).filter(Boolean), avoid = result.regions.avoid.map((r) => regionShape(r, segments)).filter(Boolean);
50
+ const keep = result.regions.keep.map((r) => regionShape(r, segments)).filter(Boolean),
51
+ avoid = result.regions.avoid.map((r) => regionShape(r, segments)).filter(Boolean);
46
52
  if (keep.length) shape = union(shape, ...keep);
47
53
  if (avoid.length) shape = subtract(shape, ...avoid);
48
54
  return shape;
@@ -58,8 +64,13 @@ export function solidRegion(r, segments = 48) {
58
64
  if (r.part || r.triangles) return null;
59
65
  if (r.size) return cuboid({ center: r.at, size: r.size });
60
66
  if (r.length != null) {
61
- const c = cylinder({ radius: r.r, height: r.length, segments }), axis = r.axis || 'z', ax = 'xyz'.indexOf(axis);
62
- const turned = translate(r.at, axis === 'x' ? rotateY(Math.PI / 2, c) : axis === 'y' ? rotateZ(Math.PI / 2, rotateY(Math.PI / 2, c)) : c);
67
+ const c = cylinder({ radius: r.r, height: r.length, segments }),
68
+ axis = r.axis || 'z',
69
+ ax = 'xyz'.indexOf(axis);
70
+ const turned = translate(
71
+ r.at,
72
+ axis === 'x' ? rotateY(Math.PI / 2, c) : axis === 'y' ? rotateZ(Math.PI / 2, rotateY(Math.PI / 2, c)) : c,
73
+ );
63
74
  // A teardrop (across the axis): the cylinder hulled with a thin ridge r√2 from its axis, below it (a boss) or
64
75
  // above it (a hole), so that side is 45°
65
76
  // The ridge: a thin slice of a square turned 45° about the axis at each end, its far corner a little past r√2: a
@@ -67,9 +78,17 @@ export function solidRegion(r, segments = 48) {
67
78
  // flatter than 45°
68
79
  const pa = r.teardrop ? 'xyz'.indexOf(r.teardrop[1]) : -1;
69
80
  if (pa < 0 || pa === ax) return turned;
70
- const edge = 0.05, slice = 1e-3, reach = (r.teardrop[0] === '-' ? -1 : 1) * (r.r * Math.SQRT2 / Math.cos(Math.PI / segments) - edge / Math.SQRT2);
71
- const square = [0, 1, 2].map((a) => (a === ax ? slice : edge)), spin = [rotateX, rotateY, rotateZ][ax];
72
- const end = (along) => translate(r.at.map((x, a) => x + (a === pa ? reach : 0) + (a === ax ? along : 0)), spin(Math.PI / 4, cuboid({ size: square })));
81
+ const edge = 0.05,
82
+ slice = 1e-3,
83
+ reach =
84
+ (r.teardrop[0] === '-' ? -1 : 1) * ((r.r * Math.SQRT2) / Math.cos(Math.PI / segments) - edge / Math.SQRT2);
85
+ const square = [0, 1, 2].map((a) => (a === ax ? slice : edge)),
86
+ spin = [rotateX, rotateY, rotateZ][ax];
87
+ const end = (along) =>
88
+ translate(
89
+ r.at.map((x, a) => x + (a === pa ? reach : 0) + (a === ax ? along : 0)),
90
+ spin(Math.PI / 4, cuboid({ size: square })),
91
+ );
73
92
  return hull(turned, end((slice - r.length) / 2), end((r.length - slice) / 2));
74
93
  }
75
94
  return sphere({ center: r.at, radius: r.r, segments });
@@ -83,7 +102,8 @@ export function solidRegion(r, segments = 48) {
83
102
  export function optimisedSolid(result, { ops, segments = 48 } = {}) {
84
103
  const o = ops || { union, subtract };
85
104
  let solid = polyhedron({ points: result.mesh.vertices, faces: result.mesh.faces, orientation: 'outward' });
86
- const keep = result.regions.keep.map((r) => solidRegion(r, segments)).filter(Boolean), avoid = result.regions.avoid.map((r) => solidRegion(r, segments)).filter(Boolean);
105
+ const keep = result.regions.keep.map((r) => solidRegion(r, segments)).filter(Boolean),
106
+ avoid = result.regions.avoid.map((r) => solidRegion(r, segments)).filter(Boolean);
87
107
  if (keep.length) solid = o.union(solid, ...keep);
88
108
  if (avoid.length) solid = o.subtract(solid, ...avoid);
89
109
  return solid;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/shapes",
3
- "version": "0.4.8",
3
+ "version": "0.5.0",
4
4
  "description": "Shape helpers for printed JSCAD designs: text that prints cleanly, anchors on a face, clean local cuts, and enclosure pieces (shells, lids, rails, print-safe holes).",
5
5
  "type": "module",
6
6
  "exports": {
@@ -8,21 +8,12 @@
8
8
  "default": "./shapes.mjs"
9
9
  },
10
10
  "files": [
11
- "shapes.mjs",
12
- "shapes.d.mts",
13
- "enclosure.mjs",
14
- "enclosure.d.mts",
11
+ "*.mjs",
12
+ "*.d.mts",
15
13
  "README.md",
16
14
  "CHANGELOG.md",
17
15
  "LICENSE",
18
- "features.mjs",
19
- "features.d.mts",
20
- "seats.mjs",
21
- "seats.d.mts",
22
- "ops.mjs",
23
- "ops.d.mts",
24
- "optimised.mjs",
25
- "optimised.d.mts"
16
+ "!test.mjs"
26
17
  ],
27
18
  "license": "MIT",
28
19
  "keywords": [
@@ -33,7 +24,7 @@
33
24
  "cad"
34
25
  ],
35
26
  "engines": {
36
- "node": ">=20"
27
+ "node": ">=22.13"
37
28
  },
38
29
  "sideEffects": false,
39
30
  "repository": {
@@ -49,7 +40,7 @@
49
40
  "test": "node --test"
50
41
  },
51
42
  "dependencies": {
52
- "@rulecad/variables": "^0.3.0"
43
+ "@rulecad/variables": "^0.4.0"
53
44
  },
54
45
  "peerDependencies": {
55
46
  "@jscad/modeling": "^2.12.0",
package/seats.d.mts CHANGED
@@ -42,7 +42,7 @@ export function bearingSeat(bearing: {
42
42
  bore: number;
43
43
  outer_diameter: number;
44
44
  width: number;
45
- }, { fit, lip, relief, through, into, lead, printer, at }?: {
45
+ }, { fit, lip, relief, through, into, lead, printer, at, }?: {
46
46
  fit?: "press" | "slip" | number;
47
47
  lip?: number;
48
48
  relief?: number;