@rulecad/cad 0.8.0 → 0.10.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.
Files changed (102) hide show
  1. package/AGENTS.md +45 -16
  2. package/CHANGELOG.md +724 -0
  3. package/EXAMPLES.md +61 -54
  4. package/README.md +376 -98
  5. package/TUTORIAL.md +2 -2
  6. package/bin/cad.mjs +2664 -541
  7. package/lib/animate.mjs +173 -49
  8. package/lib/assembly.mjs +1883 -435
  9. package/lib/beams.mjs +256 -52
  10. package/lib/belts.mjs +66 -15
  11. package/lib/board-work.mjs +12 -0
  12. package/lib/bought.mjs +309 -53
  13. package/lib/buildpage.mjs +179 -29
  14. package/lib/cache-file.mjs +105 -0
  15. package/lib/carried.mjs +201 -0
  16. package/lib/clone.mjs +194 -42
  17. package/lib/code-text.mjs +28 -0
  18. package/lib/design-imports.mjs +127 -0
  19. package/lib/design.mjs +871 -147
  20. package/lib/designshapes.mjs +142 -0
  21. package/lib/drive.mjs +187 -63
  22. package/lib/edit.mjs +922 -192
  23. package/lib/errors.mjs +16 -3
  24. package/lib/estimates.mjs +51 -0
  25. package/lib/explain.mjs +62 -13
  26. package/lib/fasten.mjs +2708 -507
  27. package/lib/fe-key.mjs +29 -0
  28. package/lib/fittings.mjs +721 -122
  29. package/lib/fixings.mjs +38 -13
  30. package/lib/framebuild.mjs +790 -175
  31. package/lib/framecheck.mjs +1901 -368
  32. package/lib/framegen.mjs +108 -22
  33. package/lib/frameheat.mjs +225 -42
  34. package/lib/frameprint.mjs +513 -108
  35. package/lib/frames.mjs +86 -18
  36. package/lib/framesize.mjs +719 -120
  37. package/lib/frametip.mjs +235 -0
  38. package/lib/gait.mjs +135 -23
  39. package/lib/grip.mjs +62 -13
  40. package/lib/guides.mjs +1403 -230
  41. package/lib/host.mjs +129 -23
  42. package/lib/inplace.mjs +171 -36
  43. package/lib/jigs.mjs +360 -78
  44. package/lib/joins.mjs +697 -118
  45. package/lib/jsonedit.mjs +88 -26
  46. package/lib/kept.mjs +84 -0
  47. package/lib/kit.mjs +439 -69
  48. package/lib/layout.mjs +2 -1
  49. package/lib/links.mjs +149 -42
  50. package/lib/list.mjs +334 -64
  51. package/lib/live-guard.mjs +68 -0
  52. package/lib/live-shape.mjs +96 -24
  53. package/lib/live.mjs +189 -59
  54. package/lib/loads.mjs +597 -136
  55. package/lib/machine.mjs +372 -74
  56. package/lib/magnets.mjs +162 -44
  57. package/lib/measured.mjs +1080 -117
  58. package/lib/mesh.mjs +526 -119
  59. package/lib/meshcmd.mjs +215 -60
  60. package/lib/motors.mjs +1002 -214
  61. package/lib/motorsvg.mjs +114 -32
  62. package/lib/names.mjs +18 -1
  63. package/lib/optimise.mjs +991 -287
  64. package/lib/order.mjs +515 -114
  65. package/lib/panels.mjs +482 -94
  66. package/lib/parts.mjs +81 -23
  67. package/lib/pins.mjs +163 -44
  68. package/lib/plates.mjs +223 -35
  69. package/lib/player.mjs +37 -9
  70. package/lib/power.mjs +64 -13
  71. package/lib/preview.mjs +83 -16
  72. package/lib/profilemeasure.mjs +572 -129
  73. package/lib/rules.mjs +17 -6
  74. package/lib/sandbox-hooks.mjs +179 -27
  75. package/lib/sandbox-lock.mjs +225 -0
  76. package/lib/sandbox-preload.mjs +2 -2
  77. package/lib/sandbox-run.mjs +122 -25
  78. package/lib/sandbox.mjs +667 -75
  79. package/lib/schema.mjs +42 -11
  80. package/lib/seats.mjs +227 -49
  81. package/lib/services.mjs +261 -52
  82. package/lib/sheet.mjs +963 -179
  83. package/lib/slotnuts.mjs +213 -34
  84. package/lib/targets/gist.mjs +4 -1
  85. package/lib/targets.mjs +22 -4
  86. package/lib/task.mjs +376 -79
  87. package/lib/versions.mjs +285 -39
  88. package/lib/wires.mjs +228 -45
  89. package/lib/workspace.mjs +200 -14
  90. package/package.json +19 -19
  91. package/schemas/assembly.schema.json +2 -2
  92. package/schemas/project.schema.json +6 -0
  93. package/templates/coupons/MEASURE.md +109 -0
  94. package/templates/coupons/assemblies/fixings-test.json +20 -0
  95. package/templates/coupons/assemblies/slot-test.json +11 -0
  96. package/templates/coupons/objects/fixings-coupon.js +88 -0
  97. package/templates/coupons/objects/fixings-coupon.json +26 -0
  98. package/templates/coupons/objects/holds-coupon.js +130 -0
  99. package/templates/coupons/objects/holds-coupon.json +42 -0
  100. package/templates/coupons/objects/slot-coupon.js +89 -0
  101. package/templates/coupons/objects/slot-coupon.json +29 -0
  102. package/templates/coupons/project.json +10 -0
package/lib/host.mjs CHANGED
@@ -2,9 +2,11 @@
2
2
  // check) does its file work through `host`; the CLI uses Node's (the default). A test, or later a browser, swaps in
3
3
  // another with useHost: memoryHost(files) keeps a workspace in memory, reading anything outside it (the tool's
4
4
  // packages, the published rule sets) from disk.
5
- // host.exists(file) host.readText(file) host.writeText(file, text) host.list(dir) host.mtime(file)
5
+ // host.exists(file) host.readText(file) host.writeText(file, text) host.list(dir) host.mtime(file) host.size(file)
6
6
  // host.remove(file) host.touch(file) host.loadModule(file): a design's module (its main), for a design run in the
7
- // tool's own process (a trusted one)
7
+ // tool's own process (a trusted one), loaded afresh when it or a file it imports has changed (design-imports.mjs)
8
+ // host.importsOf(file): a promise of the files of its own (not a package's) the design has imported since its last
9
+ // loadModule, as absolute paths, asked after its main has run, for the build's cache to follow
8
10
  // host.runDesign(request): run a design in the sandbox, another process that can't write files, start programs or
9
11
  // reach the network (sandbox.mjs's runSandboxed, whose request this is). build() uses it for every design it doesn't
10
12
  // run in its own process, a board's too, so a host for a browser or an editor's server never runs a design's code in
@@ -23,12 +25,20 @@ export const nodeHost = {
23
25
  name: 'node',
24
26
  exists: (f) => fs.existsSync(f),
25
27
  readText: (f) => fs.readFileSync(f, 'utf8'),
26
- writeText: (f, text) => { fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, text); },
28
+ writeText: (f, text) => {
29
+ fs.mkdirSync(path.dirname(f), { recursive: true });
30
+ fs.writeFileSync(f, text);
31
+ },
27
32
  list: (d) => (fs.existsSync(d) ? fs.readdirSync(d) : []),
28
33
  mtime: (f) => fs.statSync(f).mtimeMs,
34
+ size: (f) => fs.statSync(f).size,
29
35
  remove: (f) => fs.rmSync(f, { force: true }),
30
- touch: (f) => { const now = new Date(); fs.utimesSync(f, now, now); },
31
- loadModule: (f) => import(`${pathToFileURL(f).href}?t=${fs.statSync(f).mtimeMs}`), // a fresh copy after each edit
36
+ touch: (f) => {
37
+ const now = new Date();
38
+ fs.utimesSync(f, now, now);
39
+ },
40
+ loadModule: async (f) => (await import('./design-imports.mjs')).loadDesign(path.resolve(f)), // (its import hook is set up only when a design is first run here)
41
+ importsOf: async (f) => (await import('./design-imports.mjs')).importsOf(path.resolve(f)),
32
42
  runDesign: (request) => import('./sandbox.mjs').then((s) => s.runSandboxed(request)), // (loaded when first used: sandbox.mjs reads the workspace, which reads through this host)
33
43
  };
34
44
 
@@ -36,17 +46,68 @@ let current = nodeHost;
36
46
  /** The host the core uses now. */
37
47
  export const host = new Proxy({}, { get: (_, k) => current[k] });
38
48
  /** Use another host (until the returned function is called). @param {Partial<typeof nodeHost>} h @returns {() => void} */
39
- export function useHost(h) { const before = current; current = { ...nodeHost, ...h }; return () => { current = before; }; }
49
+ export function useHost(h) {
50
+ const before = current;
51
+ current = { ...nodeHost, ...h };
52
+ return () => {
53
+ current = before;
54
+ };
55
+ }
56
+
57
+ // What a file is checked by before readJson reads it: workspace.mjs sets this to its ownFile, so that a JSON file of the
58
+ // workspace (a rule set, a project, a design, an assembly) is read only where it really is inside the workspace, never
59
+ // through a link to a file elsewhere. (Set from there: this module is what workspace.mjs reads its own files with.)
60
+ let guard = (f) => f;
61
+ /**
62
+ * Check every file readJson reads with this first: it returns the file to read, or throws.
63
+ * @param {(f: string) => string} check
64
+ */
65
+ export function guardReads(check) {
66
+ guard = check;
67
+ }
68
+
69
+ /**
70
+ * A text file, read through the host, checked first as readJson checks it: a file of the workspace (a rule set, a
71
+ * design's code) only where it really is inside the workspace. For readers that hash or show the text as it is.
72
+ * @param {string} f
73
+ */
74
+ export const readOwnText = (f) => host.readText(guard(f));
75
+
76
+ /**
77
+ * Whether a cache file is there to be read: a file of the workspace's .cache/ only where it really is inside the
78
+ * workspace. A cloned workspace may hold a .cache/ of its own, and a kept build or stage there that is a link to a file
79
+ * elsewhere would be read as the tool's own and shown, or handed to a design: such a file is a miss, made afresh (and
80
+ * not written through the link: cache-file.mjs writeCacheFile).
81
+ * @param {string} f
82
+ */
83
+ export function cached(f) {
84
+ try {
85
+ guard(f);
86
+ } catch (e) {
87
+ if (e.code === 'workspace.outside') return false;
88
+ throw e;
89
+ }
90
+ return host.exists(f);
91
+ }
40
92
 
41
93
  /** A JSON file, read through the host. One that doesn't parse is named, with where it stops. @param {string} f */
42
94
  export function readJson(f) {
43
- const text = host.readText(f);
44
- try { return JSON.parse(text); } catch (e) { throw new CadError('json', `not valid JSON: ${e.message}`, { file: f, cause: e }); }
95
+ const text = readOwnText(f);
96
+ try {
97
+ return JSON.parse(text);
98
+ } catch (e) {
99
+ throw new CadError('json', `not valid JSON: ${e.message}`, { file: f, cause: e });
100
+ }
45
101
  }
46
102
 
47
103
  // The folder of node_modules the tool finds JSCAD in: a copy of a project in memory reaches its packages through it
48
104
  function toolModules() {
49
- for (let d = path.dirname(createRequire(import.meta.url).resolve('@jscad/modeling')); path.dirname(d) !== d; d = path.dirname(d)) if (path.basename(d) === 'node_modules') return d;
105
+ for (
106
+ let d = path.dirname(createRequire(import.meta.url).resolve('@jscad/modeling'));
107
+ path.dirname(d) !== d;
108
+ d = path.dirname(d)
109
+ )
110
+ if (path.basename(d) === 'node_modules') return d;
50
111
  return null;
51
112
  }
52
113
 
@@ -58,37 +119,82 @@ function toolModules() {
58
119
  * @param {Record<string, string>} files paths relative to root @param {{ root?: string }} [options]
59
120
  */
60
121
  export function memoryHost(files = {}, { root = path.resolve('/rulecad-memory') } = {}) {
61
- const mem = new Map(Object.entries(files).map(([k, v]) => [path.resolve(root, k), v])), times = new Map();
122
+ const mem = new Map(Object.entries(files).map(([k, v]) => [path.resolve(root, k), v])),
123
+ times = new Map();
62
124
  const inside = (f) => path.resolve(f).startsWith(root);
63
125
  const tick = () => Date.now() + times.size;
64
126
  const req = createRequire(import.meta.url);
65
127
  const bare = (spec) => pathToFileURL(req.resolve(spec)).href;
66
128
  return {
67
- name: 'memory', root, files: mem,
68
- exists: (f) => (inside(f) ? mem.has(path.resolve(f)) || [...mem.keys()].some((k) => k.startsWith(path.resolve(f) + path.sep)) : fs.existsSync(f)),
69
- readText: (f) => { if (!inside(f)) return fs.readFileSync(f, 'utf8'); const t = mem.get(path.resolve(f)); if (t == null) throw Object.assign(new Error(`ENOENT: no such file, '${f}'`), { code: 'ENOENT' }); return t; },
70
- writeText: (f, text) => { mem.set(path.resolve(f), text); times.set(path.resolve(f), tick()); },
71
- list: (d) => { if (!inside(d)) return fs.existsSync(d) ? fs.readdirSync(d) : []; const p = path.resolve(d) + path.sep; return [...new Set([...mem.keys()].filter((k) => k.startsWith(p)).map((k) => k.slice(p.length).split(path.sep)[0]))]; },
129
+ name: 'memory',
130
+ root,
131
+ files: mem,
132
+ exists: (f) =>
133
+ inside(f)
134
+ ? mem.has(path.resolve(f)) || [...mem.keys()].some((k) => k.startsWith(path.resolve(f) + path.sep))
135
+ : fs.existsSync(f),
136
+ readText: (f) => {
137
+ if (!inside(f)) return fs.readFileSync(f, 'utf8');
138
+ const t = mem.get(path.resolve(f));
139
+ if (t == null) throw Object.assign(new Error(`ENOENT: no such file, '${f}'`), { code: 'ENOENT' });
140
+ return t;
141
+ },
142
+ writeText: (f, text) => {
143
+ mem.set(path.resolve(f), text);
144
+ times.set(path.resolve(f), tick());
145
+ },
146
+ list: (d) => {
147
+ if (!inside(d)) return fs.existsSync(d) ? fs.readdirSync(d) : [];
148
+ const p = path.resolve(d) + path.sep;
149
+ return [
150
+ ...new Set([...mem.keys()].filter((k) => k.startsWith(p)).map((k) => k.slice(p.length).split(path.sep)[0])),
151
+ ];
152
+ },
72
153
  mtime: (f) => (inside(f) ? times.get(path.resolve(f)) || 0 : fs.statSync(f).mtimeMs),
73
- remove: (f) => { mem.delete(path.resolve(f)); },
74
- touch: (f) => { times.set(path.resolve(f), tick()); },
154
+ size: (f) => (inside(f) ? Buffer.byteLength(mem.get(path.resolve(f)) ?? '', 'utf8') : fs.statSync(f).size),
155
+ remove: (f) => {
156
+ mem.delete(path.resolve(f));
157
+ },
158
+ touch: (f) => {
159
+ times.set(path.resolve(f), tick());
160
+ },
75
161
  loadModule: (f) => {
76
- const src = (inside(f) ? mem.get(path.resolve(f)) : fs.readFileSync(f, 'utf8'))
77
- .replace(/from\s+'(@jscad\/modeling|@rulecad\/shapes)'/g, (_, s) => `from '${bare(s)}'`);
162
+ const src = (inside(f) ? mem.get(path.resolve(f)) : fs.readFileSync(f, 'utf8')).replace(
163
+ /from\s+'(@jscad\/modeling|@rulecad\/shapes)'/g,
164
+ (_, s) => `from '${bare(s)}'`,
165
+ );
78
166
  return import(`data:text/javascript;base64,${Buffer.from(src).toString('base64')}`);
79
167
  },
168
+ importsOf: async () => [], // (a module loaded from its text can't import a file of its project)
80
169
  runDesign: async (request) => {
81
- const { d } = request, project = path.resolve(path.dirname(path.dirname(d.js)));
170
+ const { d } = request,
171
+ project = path.resolve(path.dirname(path.dirname(d.js)));
82
172
  if (!inside(d.js)) return nodeHost.runDesign(request); // (a design on disk runs where it is)
83
173
  const tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'rulecad-memory-design-')));
84
174
  try {
85
175
  const copy = path.join(tmp, 'projects', path.basename(project));
86
- for (const [f, text] of mem) if (f.startsWith(project + path.sep)) { const to = path.join(copy, path.relative(project, f)); fs.mkdirSync(path.dirname(to), { recursive: true }); fs.writeFileSync(to, text); }
176
+ for (const [f, text] of mem)
177
+ if (f.startsWith(project + path.sep)) {
178
+ const to = path.join(copy, path.relative(project, f));
179
+ fs.mkdirSync(path.dirname(to), { recursive: true });
180
+ fs.writeFileSync(to, text);
181
+ }
87
182
  fs.writeFileSync(path.join(tmp, 'package.json'), JSON.stringify({ type: 'module' }));
88
183
  const modules = toolModules();
89
184
  if (modules) fs.symlinkSync(modules, path.join(tmp, 'node_modules'), 'junction');
90
- return await nodeHost.runDesign({ ...request, d: { ...d, js: path.join(copy, path.relative(project, path.resolve(d.js))) }, read: [...(request.read || []), tmp] });
91
- } finally { try { fs.unlinkSync(path.join(tmp, 'node_modules')); } catch {} fs.rmSync(tmp, { recursive: true, force: true }); } // (the link first, on its own: never a walk into the tool's packages)
185
+ return await nodeHost.runDesign({
186
+ ...request,
187
+ d: { ...d, js: path.join(copy, path.relative(project, path.resolve(d.js))) },
188
+ read: [...(request.read || []), tmp],
189
+ });
190
+ } finally {
191
+ try {
192
+ fs.unlinkSync(path.join(tmp, 'node_modules'));
193
+ } catch {
194
+ // (the link was never made, or is gone already: the folder is removed whole below)
195
+ }
196
+ fs.rmSync(tmp, { recursive: true, force: true });
197
+ } // (the link first, on its own: never a walk into the tool's packages)
92
198
  },
93
199
  };
94
200
  }
package/lib/inplace.mjs CHANGED
@@ -22,7 +22,8 @@ function onBed(tris) {
22
22
  for (const t of tris) {
23
23
  if (t.some((p) => Math.abs(p[2]) > BED)) continue;
24
24
  for (let i = 1; i < t.length - 1; i++) {
25
- const [a, b, c] = [t[0], t[i], t[i + 1]], z = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
25
+ const [a, b, c] = [t[0], t[i], t[i + 1]],
26
+ z = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
26
27
  if (z < 0) area += -z / 2; // (wound clockwise seen from above: facing down)
27
28
  }
28
29
  }
@@ -31,7 +32,11 @@ function onBed(tris) {
31
32
 
32
33
  // How far apart two boxes are, 0 if they overlap; and the box they share, grown to touch, as where to look
33
34
  const boxGap = (a, b) => Math.hypot(...[0, 1, 2].map((k) => Math.max(0, a.lo[k] - b.hi[k], b.lo[k] - a.hi[k])));
34
- const between = (a, b) => { const lo = [0, 1, 2].map((k) => Math.min(Math.max(a.lo[k], b.lo[k]), Math.min(a.hi[k], b.hi[k]))), hi = [0, 1, 2].map((k) => Math.max(Math.max(a.lo[k], b.lo[k]), Math.min(a.hi[k], b.hi[k]))); return { lo, hi }; };
35
+ const between = (a, b) => {
36
+ const lo = [0, 1, 2].map((k) => Math.min(Math.max(a.lo[k], b.lo[k]), Math.min(a.hi[k], b.hi[k]))),
37
+ hi = [0, 1, 2].map((k) => Math.max(Math.max(a.lo[k], b.lo[k]), Math.min(a.hi[k], b.hi[k])));
38
+ return { lo, hi };
39
+ };
35
40
 
36
41
  // What printcheck only warns of for a part printed alone, and why each can't be printed in place
37
42
  const SUPPORTS = {
@@ -53,59 +58,189 @@ const SUPPORTS = {
53
58
  * @returns {Promise<object[]>}
54
59
  */
55
60
  export async function inPlaceChecks(b, printer, printed = [], o = {}) {
56
- const out = [], f = (level, text, code, extra = {}) => out.push({ level, text, code, ...extra });
57
- const parts = b.parts.filter((p) => p.role !== 'support'), need = printer.print_gap;
58
- if (!(typeof need === 'number' && need > 0)) throw new Error(`printInPlace: the printer's print_gap is the gap each side that prints apart, a number above 0 (got ${JSON.stringify(need)}): add it to the printer's rule set`);
59
- if (parts.length < 2) { f('fail', `printed in place, but ${parts.length ? `only one part (${parts[0].name})` : 'no parts'}: return the parts that move apart as named parts ({ housing, sun, ... }), each described in the .json's parts`, 'inplace.parts'); return out; }
61
+ const out = [],
62
+ f = (level, text, code, extra = {}) => out.push({ level, text, code, ...extra });
63
+ const parts = b.parts.filter((p) => p.role !== 'support'),
64
+ need = printer.print_gap;
65
+ if (!(typeof need === 'number' && need > 0))
66
+ throw new Error(
67
+ `printInPlace: the printer's print_gap is the gap each side that prints apart, a number above 0 (got ${JSON.stringify(need)}): add it to the printer's rule set`,
68
+ );
69
+ if (parts.length < 2) {
70
+ f(
71
+ 'fail',
72
+ `printed in place, but ${parts.length ? `only one part (${parts[0].name})` : 'no parts'}: return the parts that move apart as named parts ({ housing, sun, ... }), each described in the .json's parts`,
73
+ 'inplace.parts',
74
+ );
75
+ return out;
76
+ }
60
77
 
61
78
  // Each on the bed
62
79
  const boxes = new Map(parts.map((p) => [p.name, bounds(p.triangles)]));
63
80
  const off = [];
64
- for (const p of parts) { const area = onBed(p.triangles), box = boxes.get(p.name); if (area < LEAST_BED) off.push({ p, area, box }); }
65
- for (const { p, area, box } of off) f('fail', `${p.name} has ${area > 0 ? `only ${mm(area)} mm²` : 'nothing'} on the bed${box.lo[2] > BED ? ` (its lowest point is ${mm(box.lo[2])} mm up)` : ''}: printed in place, a part that starts on another part is printed onto it and fuses. Give it a face of its own on the bed, slanting at 45° up to the rest of it`, 'inplace.bed', { values: { area, least: LEAST_BED }, at: [(box.lo[0] + box.hi[0]) / 2, (box.lo[1] + box.hi[1]) / 2, box.lo[2]], box, refs: { part: p.name } });
66
- if (!off.length) f('pass', `each of the ${parts.length} parts stands on the bed (${parts.map((p) => `${p.name} ${mm(onBed(p.triangles), 0)} mm²`).join(', ')})`, 'inplace.bed', { values: { parts: Object.fromEntries(parts.map((p) => [p.name, onBed(p.triangles)])) } });
81
+ for (const p of parts) {
82
+ const area = onBed(p.triangles),
83
+ box = boxes.get(p.name);
84
+ if (area < LEAST_BED) off.push({ p, area, box });
85
+ }
86
+ for (const { p, area, box } of off)
87
+ f(
88
+ 'fail',
89
+ `${p.name} has ${area > 0 ? `only ${mm(area)} mm²` : 'nothing'} on the bed${box.lo[2] > BED ? ` (its lowest point is ${mm(box.lo[2])} mm up)` : ''}: printed in place, a part that starts on another part is printed onto it and fuses. Give it a face of its own on the bed, slanting at 45° up to the rest of it`,
90
+ 'inplace.bed',
91
+ {
92
+ values: { area, least: LEAST_BED },
93
+ at: [(box.lo[0] + box.hi[0]) / 2, (box.lo[1] + box.hi[1]) / 2, box.lo[2]],
94
+ box,
95
+ refs: { part: p.name },
96
+ },
97
+ );
98
+ if (!off.length)
99
+ f(
100
+ 'pass',
101
+ `each of the ${parts.length} parts stands on the bed (${parts.map((p) => `${p.name} ${mm(onBed(p.triangles), 0)} mm²`).join(', ')})`,
102
+ 'inplace.bed',
103
+ { values: { parts: Object.fromEntries(parts.map((p) => [p.name, onBed(p.triangles)])) } },
104
+ );
67
105
 
68
106
  // Every two apart by the print gap, measured by Manifold
69
107
  let ops = o.ops;
70
- if (!ops) { try { ops = await booleans('manifold'); } catch { ops = null; } }
71
- if (!ops) { f('warn', 'the gaps between the parts are not measured: they need manifold-3d (npm install manifold-3d in the workspace)', 'inplace.gap'); }
72
- else {
73
- const within = need + 1, gaps = []; // (looking a millimetre past the gap: a pair further apart reads as that)
74
- for (let i = 0; i < parts.length; i++) for (let j = i + 1; j < parts.length; j++) {
75
- const a = parts[i], c = parts[j], ba = boxes.get(a.name), bc = boxes.get(c.name);
76
- if (boxGap(ba, bc) >= within) continue;
77
- let gap;
78
- try { gap = ops.gap(a.geometry, c.geometry, within); } catch (e) { f('warn', `${a.name} and ${c.name}: the gap between them is not measured (${e.message})`, 'inplace.gap', { refs: { parts: [a.name, c.name] } }); continue; }
79
- gaps.push({ a: a.name, b: c.name, gap, box: between(ba, bc) });
108
+ if (!ops) {
109
+ try {
110
+ ops = await booleans('manifold');
111
+ } catch {
112
+ ops = null;
80
113
  }
114
+ }
115
+ if (!ops) {
116
+ f(
117
+ 'warn',
118
+ 'the gaps between the parts are not measured: they need manifold-3d (npm install manifold-3d in the workspace)',
119
+ 'inplace.gap',
120
+ );
121
+ } else {
122
+ const within = need + 1,
123
+ gaps = []; // (looking a millimetre past the gap: a pair further apart reads as that)
124
+ for (let i = 0; i < parts.length; i++)
125
+ for (let j = i + 1; j < parts.length; j++) {
126
+ const a = parts[i],
127
+ c = parts[j],
128
+ ba = boxes.get(a.name),
129
+ bc = boxes.get(c.name);
130
+ if (boxGap(ba, bc) >= within) continue;
131
+ let gap;
132
+ try {
133
+ gap = ops.gap(a.geometry, c.geometry, within);
134
+ } catch (e) {
135
+ f('warn', `${a.name} and ${c.name}: the gap between them is not measured (${e.message})`, 'inplace.gap', {
136
+ refs: { parts: [a.name, c.name] },
137
+ });
138
+ continue;
139
+ }
140
+ gaps.push({ a: a.name, b: c.name, gap, box: between(ba, bc) });
141
+ }
81
142
  const near = gaps.filter((g) => g.gap < need - 1e-3).sort((x, y) => x.gap - y.gap);
82
- for (const g of near) f('fail', `${g.a} and ${g.b} are ${g.gap > 0 ? `${mm(g.gap, 3)} mm apart at their nearest` : 'touching'}, under the ${mm(need)} mm that prints apart (print_gap): printed in place they fuse there. Move them apart, or widen the gap in the design`, 'inplace.gap', { values: { gap: g.gap, need }, at: g.box.lo.map((x, k) => (x + g.box.hi[k]) / 2), box: g.box, refs: { parts: [g.a, g.b] } });
143
+ for (const g of near)
144
+ f(
145
+ 'fail',
146
+ `${g.a} and ${g.b} are ${g.gap > 0 ? `${mm(g.gap, 3)} mm apart at their nearest` : 'touching'}, under the ${mm(need)} mm that prints apart (print_gap): printed in place they fuse there. Move them apart, or widen the gap in the design`,
147
+ 'inplace.gap',
148
+ {
149
+ values: { gap: g.gap, need },
150
+ at: g.box.lo.map((x, k) => (x + g.box.hi[k]) / 2),
151
+ box: g.box,
152
+ refs: { parts: [g.a, g.b] },
153
+ },
154
+ );
83
155
  if (!near.length) {
84
156
  const least = gaps.reduce((m, g) => (!m || g.gap < m.gap ? g : m), null);
85
- f('pass', least ? `every two parts stand ${mm(need)} mm (print_gap) apart or more: the nearest, ${least.a} and ${least.b}, ${mm(least.gap, 3)} mm` : `no two parts come within ${mm(within)} mm of each other`, 'inplace.gap', { values: { gap: least ? least.gap : within, need, pairs: gaps.map(({ a, b: c, gap }) => ({ a, b: c, gap })) }, ...(least ? { refs: { parts: [least.a, least.b] } } : {}) });
157
+ f(
158
+ 'pass',
159
+ least
160
+ ? `every two parts stand ${mm(need)} mm (print_gap) apart or more: the nearest, ${least.a} and ${least.b}, ${mm(least.gap, 3)} mm`
161
+ : `no two parts come within ${mm(within)} mm of each other`,
162
+ 'inplace.gap',
163
+ {
164
+ values: { gap: least ? least.gap : within, need, pairs: gaps.map(({ a, b: c, gap }) => ({ a, b: c, gap })) },
165
+ ...(least ? { refs: { parts: [least.a, least.b] } } : {}),
166
+ },
167
+ );
86
168
  }
87
169
  }
88
170
 
89
171
  // On the first layer: the parts as cut half a layer up, apart by the print gap and the spread each side
90
- const layer = printer.layer ?? 0.2, foot = printer.foot ?? 0, firstNeed = need + 2 * foot;
172
+ const layer = printer.layer ?? 0.2,
173
+ foot = printer.foot ?? 0,
174
+ firstNeed = need + 2 * foot;
91
175
  if (ops && foot > 0) {
92
- const slab = (p) => { const bx = boxes.get(p.name); return ops.intersect(p.geometry, jscad.primitives.cuboid({ size: [bx.hi[0] - bx.lo[0] + 2, bx.hi[1] - bx.lo[1] + 2, layer / 2], center: [(bx.lo[0] + bx.hi[0]) / 2, (bx.lo[1] + bx.hi[1]) / 2, layer / 4] })); };
93
- const low = parts.filter((p) => boxes.get(p.name).lo[2] <= BED).map((p) => ({ name: p.name, g: slab(p), box: boxes.get(p.name) })), near = [];
176
+ const slab = (p) => {
177
+ const bx = boxes.get(p.name);
178
+ return ops.intersect(
179
+ p.geometry,
180
+ jscad.primitives.cuboid({
181
+ size: [bx.hi[0] - bx.lo[0] + 2, bx.hi[1] - bx.lo[1] + 2, layer / 2],
182
+ center: [(bx.lo[0] + bx.hi[0]) / 2, (bx.lo[1] + bx.hi[1]) / 2, layer / 4],
183
+ }),
184
+ );
185
+ };
186
+ const low = parts
187
+ .filter((p) => boxes.get(p.name).lo[2] <= BED)
188
+ .map((p) => ({ name: p.name, g: slab(p), box: boxes.get(p.name) })),
189
+ near = [];
94
190
  let least = null;
95
- for (let i = 0; i < low.length; i++) for (let j = i + 1; j < low.length; j++) {
96
- const a = low[i], c = low[j];
97
- if (boxGap(a.box, c.box) >= firstNeed + 1) continue;
98
- let gap; try { gap = ops.gap(a.g, c.g, firstNeed + 1); } catch { continue; }
99
- if (!least || gap < least.gap) least = { a: a.name, b: c.name, gap };
100
- if (gap < firstNeed - 1e-3) near.push({ a: a.name, b: c.name, gap, box: between(a.box, c.box) });
101
- }
102
- for (const g of near) f('fail', `on the first layer, ${g.a} and ${g.b} are ${mm(g.gap, 3)} mm apart half a layer up, under the ${mm(firstNeed)} mm they need there (print_gap and the first layer's ${mm(foot)} mm spread each side): they print as one. Chamfer their bed edges, or move them apart`, 'inplace.first-layer', { values: { gap: g.gap, need: firstNeed }, at: [(g.box.lo[0] + g.box.hi[0]) / 2, (g.box.lo[1] + g.box.hi[1]) / 2, 0], box: { lo: [g.box.lo[0], g.box.lo[1], 0], hi: [g.box.hi[0], g.box.hi[1], layer] }, refs: { parts: [g.a, g.b] } });
103
- if (!near.length && least) f('pass', `on the first layer, every two parts stand ${mm(firstNeed)} mm apart or more half a layer up (print_gap and the ${mm(foot)} mm spread each side): the nearest, ${least.a} and ${least.b}, ${mm(least.gap, 3)} mm`, 'inplace.first-layer', { values: { gap: least.gap, need: firstNeed }, refs: { parts: [least.a, least.b] } });
191
+ for (let i = 0; i < low.length; i++)
192
+ for (let j = i + 1; j < low.length; j++) {
193
+ const a = low[i],
194
+ c = low[j];
195
+ if (boxGap(a.box, c.box) >= firstNeed + 1) continue;
196
+ let gap;
197
+ try {
198
+ gap = ops.gap(a.g, c.g, firstNeed + 1);
199
+ } catch {
200
+ continue;
201
+ }
202
+ if (!least || gap < least.gap) least = { a: a.name, b: c.name, gap };
203
+ if (gap < firstNeed - 1e-3) near.push({ a: a.name, b: c.name, gap, box: between(a.box, c.box) });
204
+ }
205
+ for (const g of near)
206
+ f(
207
+ 'fail',
208
+ `on the first layer, ${g.a} and ${g.b} are ${mm(g.gap, 3)} mm apart half a layer up, under the ${mm(firstNeed)} mm they need there (print_gap and the first layer's ${mm(foot)} mm spread each side): they print as one. Chamfer their bed edges, or move them apart`,
209
+ 'inplace.first-layer',
210
+ {
211
+ values: { gap: g.gap, need: firstNeed },
212
+ at: [(g.box.lo[0] + g.box.hi[0]) / 2, (g.box.lo[1] + g.box.hi[1]) / 2, 0],
213
+ box: { lo: [g.box.lo[0], g.box.lo[1], 0], hi: [g.box.hi[0], g.box.hi[1], layer] },
214
+ refs: { parts: [g.a, g.b] },
215
+ },
216
+ );
217
+ if (!near.length && least)
218
+ f(
219
+ 'pass',
220
+ `on the first layer, every two parts stand ${mm(firstNeed)} mm apart or more half a layer up (print_gap and the ${mm(foot)} mm spread each side): the nearest, ${least.a} and ${least.b}, ${mm(least.gap, 3)} mm`,
221
+ 'inplace.first-layer',
222
+ { values: { gap: least.gap, need: firstNeed }, refs: { parts: [least.a, least.b] } },
223
+ );
104
224
  }
105
225
 
106
226
  // Nothing that needs a support
107
- const needs = printed.filter((x) => SUPPORTS[x.code] && (x.code === 'print.breakaway' ? x.level === 'pass' && x.values?.area > 0 : x.level === 'warn'));
108
- for (const x of needs) f('fail', `${SUPPORTS[x.code]} (${x.text}): printed in place, no support can come out from between the parts, so it can't be printed. ${x.code === 'print.bridge' ? `Narrow the span to the printer's ${mm(x.values?.max ?? 5)} mm, or slant the underside at 45°` : 'Slant the underside at 45° down to the bed, or give that part a face of its own there'}`, 'inplace.support', { values: { was: x.code, ...(x.values || {}) }, ...(x.at ? { at: x.at } : {}), ...(x.box ? { box: x.box } : {}) });
109
- if (!needs.length) f('pass', 'nothing needs a support: every bridge within what the printer spans, no underside in mid-air or on another part', 'inplace.support');
227
+ const needs = printed.filter(
228
+ (x) =>
229
+ SUPPORTS[x.code] &&
230
+ (x.code === 'print.breakaway' ? x.level === 'pass' && x.values?.area > 0 : x.level === 'warn'),
231
+ );
232
+ for (const x of needs)
233
+ f(
234
+ 'fail',
235
+ `${SUPPORTS[x.code]} (${x.text}): printed in place, no support can come out from between the parts, so it can't be printed. ${x.code === 'print.bridge' ? `Narrow the span to the printer's ${mm(x.values?.max ?? 5)} mm, or slant the underside at 45°` : 'Slant the underside at 45° down to the bed, or give that part a face of its own there'}`,
236
+ 'inplace.support',
237
+ { values: { was: x.code, ...(x.values || {}) }, ...(x.at ? { at: x.at } : {}), ...(x.box ? { box: x.box } : {}) },
238
+ );
239
+ if (!needs.length)
240
+ f(
241
+ 'pass',
242
+ 'nothing needs a support: every bridge within what the printer spans, no underside in mid-air or on another part',
243
+ 'inplace.support',
244
+ );
110
245
  return out;
111
246
  }