@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/buildpage.mjs CHANGED
@@ -5,14 +5,15 @@
5
5
  import fs from 'node:fs';
6
6
  import path from 'node:path';
7
7
  import { sheetFrame } from '@rulecad/robots';
8
- import { compactSteps } from '@rulecad/model-link';
8
+ import { compactSteps, placeItems, jointValues } from '@rulecad/model-link';
9
9
  import { paths } from './workspace.mjs';
10
10
  import { host } from './host.mjs';
11
11
  import { accuracyOf, sample, chainOf } from './task.mjs';
12
12
  import { machineOf } from './machine.mjs';
13
- import { shoppingList } from './list.mjs';
13
+ import { shoppingList, materialOf } from './list.mjs';
14
+ import { carriedMasses } from './motors.mjs';
14
15
  import { cutListOf, sheetFile } from './beams.mjs';
15
- import { wiresFor, wireRoutesOf } from './assembly.mjs';
16
+ import { wiresFor } from './assembly.mjs';
16
17
  import { orderOf, isBuilt } from './order.mjs';
17
18
  import { withPreload } from './slotnuts.mjs';
18
19
  import { frameBuild } from './framebuild.mjs';
@@ -21,40 +22,116 @@ import { wiringSheet } from './wires.mjs';
21
22
  import { readLedger } from './measured.mjs';
22
23
  import { fmt } from './rules.mjs';
23
24
 
24
- const guard = async (fn) => { try { return await fn(); } catch (e) { return { error: e.message }; } };
25
+ const guard = async (fn) => {
26
+ try {
27
+ return await fn();
28
+ } catch (e) {
29
+ return { error: e.message };
30
+ }
31
+ };
25
32
  const r = (x) => +Number(x).toFixed(6);
26
33
 
27
34
  // The plane the pen moves on: the sheet, or the middle of a region or a volume
28
35
  function planeOf(t) {
29
- if (t.sheet) { const f = sheetFrame(t.sheet); return { at: f.at, u: f.u, v: f.v, n: f.n, width: f.width, height: f.height }; }
30
- const area = t.region ?? t.volume, xr = area.x ?? [area.lo[0], area.hi[0]], yr = area.y ?? [area.lo[1], area.hi[1]], zr = area.z != null ? (Array.isArray(area.z) ? area.z : [area.z, area.z]) : area.lo ? [area.lo[2] ?? 0, area.hi?.[2] ?? area.lo[2] ?? 0] : [0, 0];
36
+ if (t.sheet) {
37
+ const f = sheetFrame(t.sheet);
38
+ return { at: f.at, u: f.u, v: f.v, n: f.n, width: f.width, height: f.height };
39
+ }
40
+ const area = t.region ?? t.volume,
41
+ xr = area.x ?? [area.lo[0], area.hi[0]],
42
+ yr = area.y ?? [area.lo[1], area.hi[1]],
43
+ zr =
44
+ area.z != null
45
+ ? Array.isArray(area.z)
46
+ ? area.z
47
+ : [area.z, area.z]
48
+ : area.lo
49
+ ? [area.lo[2] ?? 0, area.hi?.[2] ?? area.lo[2] ?? 0]
50
+ : [0, 0];
31
51
  // The two longest sides are the plane the page draws on: a volume can be flat in any of its axes, or a single point
32
- const at = [(xr[0] + xr[1]) / 2, (yr[0] + yr[1]) / 2, (zr[0] + zr[1]) / 2], side = [xr[1] - xr[0], yr[1] - yr[0], zr[1] - zr[0]], thin = side.indexOf(Math.min(...side));
33
- const [a, b] = [0, 1, 2].filter((k) => k !== thin), axis = (k) => [0, 1, 2].map((m) => (m === k ? 1 : 0)), n = [0, 1, 2].map((m) => (m === thin ? (thin === 1 ? -1 : 1) : 0));
52
+ const at = [(xr[0] + xr[1]) / 2, (yr[0] + yr[1]) / 2, (zr[0] + zr[1]) / 2],
53
+ side = [xr[1] - xr[0], yr[1] - yr[0], zr[1] - zr[0]],
54
+ thin = side.indexOf(Math.min(...side));
55
+ const [a, b] = [0, 1, 2].filter((k) => k !== thin),
56
+ axis = (k) => [0, 1, 2].map((m) => (m === k ? 1 : 0)),
57
+ n = [0, 1, 2].map((m) => (m === thin ? (thin === 1 ? -1 : 1) : 0));
34
58
  return { at, u: axis(a), v: axis(b), n, width: Math.max(side[a], 1), height: Math.max(side[b], 1) };
35
59
  }
36
60
 
37
61
  /** The task as the page reads it. @param {object} s a built assembly with a task @param {object[]} findings from checkAssembly */
38
62
  export function taskData(s, findings) {
39
- const t = s.task, { elbow } = sample(s), plane = planeOf(t);
40
- const terms = t.accuracy != null ? accuracyOf(s).list.flatMap((j, i) => j.terms.map((x) => [i, x.term, r(x.value), x.kind ?? ''])) : [];
41
- const loads = (s.motion.loads || []).map((l) => (l.mass != null ? { item: l.item, at: [l.frame[3], l.frame[7], l.frame[11]].map(r), mass: l.mass } : { joint: l.joint, value: l.value }));
42
- const torque = findings.filter((x) => x.code === 'motor.torque' && x.values?.available != null).map((x) => ({ joint: x.refs.joint, available: r(x.values.available) }));
43
- const hot = findings.filter((x) => x.code === 'motor.heat' && x.values?.case != null).sort((a, b) => (b.values.case / b.values.softening) - (a.values.case / a.values.softening))[0];
44
- return { tool: t.tool, item: t.item, point: t.point.map(r), plane: { at: plane.at.map(r), u: plane.u.map(r), v: plane.v.map(r), n: plane.n.map(r), width: r(plane.width), height: r(plane.height) },
45
- ...(elbow ? { elbow } : {}), ...(t.speed != null ? { speed: t.speed } : {}), ...(t.accuracy != null ? { accuracy: t.accuracy } : {}), ...(t.deflection ? { deflection: t.deflection } : {}),
46
- ...(terms.length ? { terms } : {}), ...(loads.length ? { loads, gravity: s.motion.gravity } : {}), ...(torque.length ? { torque } : {}), ...(hot ? { heat: { motor: hot.refs?.item ?? '', case: r(hot.values.case), softening: hot.values.softening } } : {}) };
63
+ const t = s.task,
64
+ { elbow } = sample(s),
65
+ plane = planeOf(t);
66
+ const terms =
67
+ t.accuracy != null
68
+ ? accuracyOf(s).list.flatMap((j, i) => j.terms.map((x) => [i, x.term, r(x.value), x.kind ?? '']))
69
+ : [];
70
+ // what the motors lift, as motor.torque counts it (lib/carried.mjs): every mass on the machine (the parts as drawn,
71
+ // the bought parts, the declared masses, the payload) as a point on its item, and the torques and forces declared on
72
+ // joints (less a belt carriage's own weight, which its parts count already), so the page's torque chip and the check agree
73
+ const worlds = s.motion.drives?.length
74
+ ? placeItems(s.motion, s.jointValues ?? jointValues(s.motion, s.motion.pose ?? undefined))
75
+ : null,
76
+ loads = [
77
+ ...(worlds ? carriedMasses(s, worlds, materialOf(s.project)) : [])
78
+ .filter((m) => m.kg > 0)
79
+ .map((m) => ({ item: m.item, at: m.point.map(r), mass: m.kg })),
80
+ ...(s.motion.loads || [])
81
+ .filter((l) => l.mass == null && l.joint != null && !l.beltWeight)
82
+ .map((l) => ({ joint: l.joint, value: l.value })),
83
+ ];
84
+ const torque = findings
85
+ .filter((x) => x.code === 'motor.torque' && x.values?.available != null)
86
+ .map((x) => ({ joint: x.refs.joint, available: r(x.values.available) }));
87
+ const hot = findings
88
+ .filter((x) => x.code === 'motor.heat' && x.values?.case != null)
89
+ .sort((a, b) => b.values.case / b.values.softening - a.values.case / a.values.softening)[0];
90
+ return {
91
+ tool: t.tool,
92
+ item: t.item,
93
+ point: t.point.map(r),
94
+ plane: {
95
+ at: plane.at.map(r),
96
+ u: plane.u.map(r),
97
+ v: plane.v.map(r),
98
+ n: plane.n.map(r),
99
+ width: r(plane.width),
100
+ height: r(plane.height),
101
+ },
102
+ ...(elbow ? { elbow } : {}),
103
+ ...(t.speed != null ? { speed: t.speed } : {}),
104
+ ...(t.accuracy != null ? { accuracy: t.accuracy } : {}),
105
+ ...(t.deflection ? { deflection: t.deflection } : {}),
106
+ ...(terms.length ? { terms } : {}),
107
+ ...(loads.length ? { loads, gravity: s.motion.gravity } : {}),
108
+ ...(torque.length ? { torque } : {}),
109
+ ...(hot
110
+ ? { heat: { motor: hot.refs?.item ?? '', case: r(hot.values.case), softening: hot.values.softening } }
111
+ : {}),
112
+ };
47
113
  }
48
114
 
49
115
  /** A step file for the link: the one asked for, or the newest cad plot wrote for this assembly. @returns {object|null} the compact form */
50
116
  export function stepsData(s, asked) {
51
- const dir = paths.exports(s.project), base = `${s.name}-`;
117
+ const dir = paths.exports(s.project),
118
+ base = `${s.name}-`;
52
119
  let file = typeof asked === 'string' ? asked : null;
53
- if (!file && asked !== false && fs.existsSync(dir)) file = fs.readdirSync(dir).filter((f) => f.startsWith(base) && f.endsWith('.steps.json')).map((f) => path.join(dir, f)).sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs)[0] ?? null;
120
+ if (!file && asked !== false && fs.existsSync(dir))
121
+ file =
122
+ fs
123
+ .readdirSync(dir)
124
+ .filter((f) => f.startsWith(base) && f.endsWith('.steps.json'))
125
+ .map((f) => path.join(dir, f))
126
+ .sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs)[0] ?? null;
54
127
  if (!file) return null;
55
128
  if (!host.exists(file)) throw new Error(`no step file "${file}": cad plot writes them to exports/`);
56
- const steps = compactSteps(JSON.parse(fs.readFileSync(file, 'utf8'))), names = chainOf(s).names;
57
- if (names.join() !== steps.names.join()) throw new Error(`the step file ${path.basename(file)} is for joints ${steps.names.join(', ')}, and this machine's are ${names.join(', ')}: plot it again`);
129
+ const steps = compactSteps(JSON.parse(fs.readFileSync(file, 'utf8'))),
130
+ names = chainOf(s).names;
131
+ if (names.join() !== steps.names.join())
132
+ throw new Error(
133
+ `the step file ${path.basename(file)} is for joints ${steps.names.join(', ')}, and this machine's are ${names.join(', ')}: plot it again`,
134
+ );
58
135
  return steps;
59
136
  }
60
137
 
@@ -62,28 +139,101 @@ export function stepsData(s, asked) {
62
139
  export async function buildData(s) {
63
140
  const list = await guard(() => shoppingList(s));
64
141
  const wires = await guard(() => (s.wires?.length ? wiresFor(s).map(({ route, ...w }) => w) : null));
65
- const plates = await guard(() => platesOf(s).then(({ bed, gap, plates: p, findings }) => ({ bed, gap, plates: p, findings })));
142
+ const plates = await guard(() =>
143
+ platesOf(s).then(({ bed, gap, plates: p, findings }) => ({ bed, gap, plates: p, findings })),
144
+ );
66
145
  const order = isBuilt(s) ? await guard(() => withPreload(s, orderOf(s))) : null; // (with the slot nuts to load before a join closes their slot)
67
146
  const machine = s.task ? await guard(() => machineOf(s)) : null;
68
147
  // each mark's cut-and-drill sheet, by its file in the exports (cad beams writes them), and whether it is there yet
69
- const beams = await guard(() => { const c = cutListOf(s); return c ? { sheets: c.marks.map((m) => ({ mark: m.mark, items: m.items, file: ['exports', s.project, path.basename(sheetFile(s, m.mark))].join('/'), written: fs.existsSync(sheetFile(s, m.mark)) })) } : null; });
70
- const frame = s.joins?.length ? await guard(() => { const { steps, sides, notFlat, bays, torques, stuck } = frameBuild(s); return { steps, sides: sides.map((x) => ({ beams: x.beams, name: x.name })), notFlat, bays: bays.map((b) => ({ beams: b.beams, name: b.name, width: b.width, height: b.height, diagonal: b.square.diagonal, accept: b.square.accept, rss: b.square.rss, lean: b.square.lean, terms: b.square.terms })), torques, stuck }; }) : null; // (from bars to a square frame)
148
+ const beams = await guard(() => {
149
+ const c = cutListOf(s);
150
+ return c
151
+ ? {
152
+ sheets: c.marks.map((m) => ({
153
+ mark: m.mark,
154
+ items: m.items,
155
+ file: ['exports', s.project, path.basename(sheetFile(s, m.mark))].join('/'),
156
+ written: fs.existsSync(sheetFile(s, m.mark)),
157
+ })),
158
+ }
159
+ : null;
160
+ });
161
+ const frame = s.joins?.length
162
+ ? await guard(() => {
163
+ const { steps, sides, notFlat, bays, torques, stuck } = frameBuild(s);
164
+ return {
165
+ steps,
166
+ sides: sides.map((x) => ({ beams: x.beams, name: x.name })),
167
+ notFlat,
168
+ bays: bays.map((b) => ({
169
+ beams: b.beams,
170
+ name: b.name,
171
+ width: b.width,
172
+ height: b.height,
173
+ diagonal: b.square.diagonal,
174
+ accept: b.square.accept,
175
+ rss: b.square.rss,
176
+ lean: b.square.lean,
177
+ terms: b.square.terms,
178
+ })),
179
+ torques,
180
+ stuck,
181
+ };
182
+ })
183
+ : null; // (from bars to a square frame)
71
184
  // a frame's build is its one sequence, from bars to square with the rest mounted: the assembly order is not shown beside it
72
- return { build: { list, wires, plates, order: frame && !frame.error ? null : order, machine, beams, ...(frame ? { frame } : {}) } };
185
+ return {
186
+ build: {
187
+ list,
188
+ wires,
189
+ plates,
190
+ order: frame && !frame.error ? null : order,
191
+ machine,
192
+ beams,
193
+ ...(frame ? { frame } : {}),
194
+ },
195
+ };
73
196
  }
74
197
 
75
198
  // The ledger, in the rules sheet's own rows: each prediction the bench can measure, the measurement once it's in
76
199
  export function ledgerRows(s, findings) {
77
- const entries = readLedger(s.project).filter((e) => e.assembly === s.name), rows = [], done = new Set();
78
- for (const e of entries) { done.add(e.name); rows.push(['Predicted against measured', e.name, fmt(e.measured), e.unit || '', `predicted ${e.predicted != null ? `${fmt(e.predicted)}${e.was ? ` (${e.was})` : ''}` : 'nothing'}${e.ratio != null ? `, ratio ${fmt(+e.ratio.toFixed(3))}` : ''}${e.figure ? `, ${e.figure}` : ''}`, '', 'measured', e.source ?? '', e.date ?? '']); }
79
- for (const x of findings) if (x.predict && !done.has(x.predict.name ?? x.code)) rows.push(['Predicted against measured', x.predict.name ?? x.code, fmt(x.predict.value), x.predict.unit ?? '', `${x.predict.figure}: nobody has measured it yet (cad measured ${s.project}/${s.name} ${x.predict.name ?? x.code}=<value>)`, '', 'prediction']);
200
+ const entries = readLedger(s.project).filter((e) => e.assembly === s.name),
201
+ rows = [],
202
+ done = new Set();
203
+ for (const e of entries) {
204
+ done.add(e.name);
205
+ rows.push([
206
+ 'Predicted against measured',
207
+ e.name,
208
+ fmt(e.measured),
209
+ e.unit || '',
210
+ `predicted ${e.predicted != null ? `${fmt(e.predicted)}${e.was ? ` (${e.was})` : ''}` : 'nothing'}${e.ratio != null ? `, ratio ${fmt(+e.ratio.toFixed(3))}` : ''}${e.figure ? `, ${e.figure}` : ''}`,
211
+ '',
212
+ 'measured',
213
+ e.source ?? '',
214
+ e.date ?? '',
215
+ ]);
216
+ }
217
+ for (const x of findings)
218
+ if (x.predict && !done.has(x.predict.name ?? x.code))
219
+ rows.push([
220
+ 'Predicted against measured',
221
+ x.predict.name ?? x.code,
222
+ fmt(x.predict.value),
223
+ x.predict.unit ?? '',
224
+ `${x.predict.figure}: nobody has measured it yet (cad measured ${s.project}/${s.name} ${x.predict.name ?? x.code}=<value>)`,
225
+ '',
226
+ 'prediction',
227
+ ]);
80
228
  return rows.map((row) => row.map(String));
81
229
  }
82
230
 
83
231
  /** The wiring sheet in the exports: <assembly>.wiring.md. @returns {string|null} the file */
84
232
  export function writeWiring(s) {
85
233
  if (!s.wires?.length) return null;
86
- const dir = paths.exports(s.project), file = path.join(dir, `${s.name}.wiring.md`);
87
- fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(file, `# ${s.project}/${s.name}: wiring\n\n${wiringSheet(wiresFor(s))}\n`);
234
+ const dir = paths.exports(s.project),
235
+ file = path.join(dir, `${s.name}.wiring.md`);
236
+ fs.mkdirSync(dir, { recursive: true });
237
+ fs.writeFileSync(file, `# ${s.project}/${s.name}: wiring\n\n${wiringSheet(wiresFor(s))}\n`);
88
238
  return file;
89
239
  }
@@ -0,0 +1,105 @@
1
+ // The workspace's .cache/ folder, written and read one way (issue #633). Everything cad keeps there (builds, stages,
2
+ // routes, overlaps, the gears' contact, the finite elements' results, assembly orders, optimised shapes and their
3
+ // densities, recorded runs, links, the record of AGENTS.md) is written by writeCacheFile and, where it is JSON, read by
4
+ // readCacheJson. test/cache-writes.test.mjs holds every file of lib/ and bin/ to that.
5
+ //
6
+ // Two dangers. A workspace cloned from someone else may carry a .cache/ of its own, and a file there that is a link to a
7
+ // file elsewhere (the user's trust list, a file in their home) would be written through, overwritten with what the tool
8
+ // worked out: so a cache file is written only where it, and every folder between it and the workspace, is a plain file
9
+ // and plain folders, or not there yet (ownCacheFile); otherwise the result is simply not kept. And a run stopped part way
10
+ // through writing (Ctrl-C, a test's time running out, a full disc) would leave a file cut short that every later run
11
+ // failed to read: so a file is written whole beside its place and then renamed over it, which leaves either the old
12
+ // file or the new one, never part of one; and a kept file that does not read as JSON is a miss, removed and made again.
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+ import crypto from 'node:crypto';
16
+ import { host, nodeHost, cached } from './host.mjs';
17
+ import { WS } from './workspace.mjs';
18
+
19
+ /**
20
+ * Whether the tool may write a cache file at `file`: it lies inside the workspace (root), and it and every folder on its
21
+ * way down from there are a plain file (not a link, and not hard-linked to another name) and plain folders, or are not
22
+ * there yet. A workspace in memory has nothing on disk to follow, so any file of it is the tool's own.
23
+ * @param {string} file @param {string} [root] the workspace @returns {boolean}
24
+ */
25
+ export function ownCacheFile(file, root = WS) {
26
+ if (host.name === 'memory') return true;
27
+ const top = path.resolve(root);
28
+ let p = path.resolve(file);
29
+ if (!p.startsWith(top + path.sep)) return false;
30
+ for (let first = true; p !== top; p = path.dirname(p), first = false) {
31
+ let st;
32
+ try {
33
+ st = fs.lstatSync(p);
34
+ } catch (e) {
35
+ if (e.code === 'ENOENT') continue;
36
+ return false;
37
+ }
38
+ if (first ? !(st.isFile() && st.nlink === 1) : !st.isDirectory()) return false;
39
+ }
40
+ return true;
41
+ }
42
+
43
+ /**
44
+ * Keep `text` in the cache file `file`, whole or not at all: only where ownCacheFile allows (a link, or a folder that is
45
+ * a link, is left as it is and the text not kept), written to a new file beside it that is then renamed over it. A
46
+ * cache that can't be written is only slower, so nothing is thrown.
47
+ * @param {string} file @param {string} text @returns {boolean} whether it was kept
48
+ */
49
+ export function writeCacheFile(file, text) {
50
+ try {
51
+ if (!ownCacheFile(file)) return false;
52
+ if (host.writeText !== nodeHost.writeText) {
53
+ host.writeText(file, text); // (a host of another kind, a workspace in memory: what it writes is its own business)
54
+ return true;
55
+ }
56
+ const dir = path.dirname(file);
57
+ fs.mkdirSync(dir, { recursive: true });
58
+ if (!ownCacheFile(file)) return false; // (the folders just made, checked again)
59
+ const temp = path.join(dir, `.${path.basename(file)}.${process.pid}-${crypto.randomBytes(6).toString('hex')}.tmp`);
60
+ try {
61
+ fs.writeFileSync(temp, text, { flag: 'wx' }); // (wx: a new file, never one that is there already, nor a link)
62
+ fs.renameSync(temp, file);
63
+ } catch (e) {
64
+ fs.rmSync(temp, { force: true });
65
+ throw e;
66
+ }
67
+ return true;
68
+ } catch {
69
+ return false;
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Remove a cache file that is the tool's own (ownCacheFile): a link, or a file elsewhere, is left alone.
75
+ * @param {string} file
76
+ */
77
+ export function dropCacheFile(file) {
78
+ try {
79
+ if (ownCacheFile(file)) host.remove(file);
80
+ } catch {
81
+ // (left for another run: it is a miss each time until then)
82
+ }
83
+ }
84
+
85
+ /**
86
+ * A kept JSON file of the cache, or undefined when there is none to read: not there, a link out of the workspace
87
+ * (host.mjs cached), or a file that does not read as JSON (cut short by a run that was stopped while writing it under an
88
+ * older version of the tool, or spoiled since), which is removed so that it is made again.
89
+ * @param {string} file @returns {any}
90
+ */
91
+ export function readCacheJson(file) {
92
+ if (!cached(file)) return undefined;
93
+ let text;
94
+ try {
95
+ text = host.readText(file);
96
+ } catch {
97
+ return undefined;
98
+ }
99
+ try {
100
+ return JSON.parse(text);
101
+ } catch {
102
+ dropCacheFile(file);
103
+ return undefined;
104
+ }
105
+ }
@@ -0,0 +1,201 @@
1
+ // What a joint carries: every mass beyond it (the parts as drawn, the bought parts by their rules, the loads the
2
+ // assembly declares, the task's payload) and the force and moment their weight puts on it. The motor checks
3
+ // (motor.torque, motor.holds, lib/motors.mjs) and motor.accel (lib/loads.mjs) both read this one sum, so they cannot
4
+ // disagree about what a motor lifts. It imports nothing of the kit's own, so both can import it without a loop.
5
+
6
+ const G = 9.80665; // m/s²
7
+ const sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]],
8
+ dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2],
9
+ add = (a, b) => [a[0] + b[0], a[1] + b[1], a[2] + b[2]],
10
+ scale = (a, k) => a.map((x) => x * k),
11
+ norm = (a) => Math.hypot(a[0], a[1], a[2]);
12
+ const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
13
+ const rowsAt = (W, p) =>
14
+ [0, 1, 2].map((k) => W[4 * k] * p[0] + W[4 * k + 1] * p[1] + W[4 * k + 2] * p[2] + W[4 * k + 3]);
15
+ const invAt = (W, p) => {
16
+ const q = [p[0] - W[3], p[1] - W[7], p[2] - W[11]];
17
+ return [
18
+ W[0] * q[0] + W[4] * q[1] + W[8] * q[2],
19
+ W[1] * q[0] + W[5] * q[1] + W[9] * q[2],
20
+ W[2] * q[0] + W[6] * q[1] + W[10] * q[2],
21
+ ];
22
+ };
23
+
24
+ /**
25
+ * A joint's axis in the world: its origin O and its direction Z, at one placing of the items.
26
+ * @param {object} motion @param {number[][]} worlds each item's world matrix @param {object} j the joint
27
+ * @param {Function} mul a 4×4 matrix product @returns {{ O: number[], Z: number[] }}
28
+ */
29
+ export const axisOf = (motion, worlds, j, mul) => {
30
+ const P = j.parent < 0 ? j.a : mul(worlds[j.parent], j.a);
31
+ return { O: [P[3], P[7], P[11]], Z: [P[2], P[6], P[10]] };
32
+ };
33
+
34
+ /**
35
+ * Whether an item moves with a joint: the joint is on its chain to the base.
36
+ * @param {object} motion @param {object} j the joint @param {number} item the item's index @returns {boolean}
37
+ */
38
+ export const beyond = (motion, j, item) => {
39
+ const by = new Map(motion.joints.map((x) => [x.child, x]));
40
+ for (let i = item, n = 0; i >= 0 && n < 99; n++) {
41
+ const x = by.get(i);
42
+ if (!x) return false;
43
+ if (x === j) return true;
44
+ i = x.parent;
45
+ }
46
+ return false;
47
+ };
48
+
49
+ // A mesh's volume and centroid: signed tetrahedra from the origin
50
+ function solidOf(tris) {
51
+ let V = 0;
52
+ const c = [0, 0, 0];
53
+ for (const [a, b, d] of tris) {
54
+ const v = dot(a, cross(b, d)) / 6;
55
+ V += v;
56
+ for (let k = 0; k < 3; k++) c[k] += (v * (a[k] + b[k] + d[k])) / 4;
57
+ }
58
+ return { volume: Math.abs(V), centroid: V ? c.map((x) => x / V) : [0, 0, 0] };
59
+ }
60
+
61
+ /**
62
+ * Each moving thing's mass in kg and its centre in its item's frame: a printed part by its volume and the material's
63
+ * density, a bought part (a motor, a bearing) by the mass its rules give, or none (known: false).
64
+ * @param {object} s a built assembly @param {number[][]} W each item's world matrix as the parts were built
65
+ * @param {number} density g/cm³ of the printed parts
66
+ * @returns {{ item: number, id: string, kg: number, centre: number[], known: boolean }[]}
67
+ */
68
+ export function partMasses(s, W, density) {
69
+ const out = [];
70
+ s.motion.items.forEach(([id], k) => {
71
+ const parts = s.parts.filter((p) => p.item === id && p.role !== 'support');
72
+ if (!parts.length) return;
73
+ const o = s.objects.find((x) => x.id === id || String(x.id).startsWith(`${id}.`)),
74
+ reference = parts.every((p) => p.role === 'reference');
75
+ let total = 0,
76
+ c = [0, 0, 0];
77
+ for (const p of parts) {
78
+ const q = solidOf(p.triangles);
79
+ const kg = reference ? 0 : ((q.volume / 1000) * density) / 1000;
80
+ total += kg;
81
+ c = add(c, scale(q.centroid, kg || q.volume));
82
+ }
83
+ const weightSum = reference ? parts.reduce((t, p) => t + solidOf(p.triangles).volume, 0) : total;
84
+ const bought = reference ? (o?.bought?.mass ?? null) : null;
85
+ out.push({
86
+ item: k,
87
+ id,
88
+ kg: reference ? (bought ?? 0) : total,
89
+ centre: invAt(W[k], weightSum ? scale(c, 1 / weightSum) : c),
90
+ known: !reference || bought != null,
91
+ });
92
+ });
93
+ return out;
94
+ }
95
+
96
+ /**
97
+ * Every mass the machine carries, as points on its items: the parts' own (partMasses), each declared load with a
98
+ * "mass", and the task's payload (less what is declared at the tool already). Each says what it is, so a finding can
99
+ * say what it counted.
100
+ * @param {object} s a built assembly @param {ReturnType<typeof partMasses>} parts
101
+ * @returns {{ item: number, kg: number, point: number[], kind: 'part' | 'load' | 'payload' }[]}
102
+ */
103
+ export function pointMasses(s, parts) {
104
+ const motion = s.motion,
105
+ ids = motion.items.map((x) => x[0]),
106
+ out = parts.map((m) => ({ item: m.item, kg: m.kg, point: m.centre, kind: 'part' }));
107
+ for (const l of motion.loads || [])
108
+ if (l.mass != null && !l.belt && l.frame) {
109
+ const item = typeof l.item === 'number' ? l.item : ids.indexOf(l.item);
110
+ if (item >= 0) out.push({ item, kg: l.mass, point: [l.frame[3], l.frame[7], l.frame[11]], kind: 'load' });
111
+ }
112
+ // the task's payload, at its tool; where the assembly also declares a mass at the tool itself (as the motor checks
113
+ // asked before they counted the payload), that mass is taken to be the payload, so it is counted once: the larger
114
+ if (s.task?.payload) {
115
+ const item = ids.indexOf(s.task.item),
116
+ atTool = out
117
+ .filter((m) => m.kind === 'load' && m.item === item && Math.hypot(...sub(m.point, s.task.point)) < 1e-6)
118
+ .reduce((t, m) => t + m.kg, 0),
119
+ extra = s.task.payload - atTool;
120
+ if (item >= 0 && extra > 1e-12) out.push({ item, kg: extra, point: s.task.point, kind: 'payload' });
121
+ }
122
+ return out;
123
+ }
124
+
125
+ /**
126
+ * The weight of every mass beyond a joint, at one placing of the items: the force (N) and its moment about the joint's
127
+ * origin (N m), split into what bears on the joint (axial and radial force, tipping moment) and what drives it (the
128
+ * torque about its axis, the force along its slide).
129
+ * @param {object} motion @param {{ item: number, kg: number, point: number[] }[]} masses points on items
130
+ * @param {number[][]} worlds @param {object} j the joint @param {Function} mul
131
+ */
132
+ export function loadAt(motion, masses, worlds, j, mul) {
133
+ const { O, Z } = axisOf(motion, worlds, j, mul),
134
+ g = motion.gravity || [0, 0, -1],
135
+ dir = scale(g, 1 / norm(g));
136
+ let F = [0, 0, 0],
137
+ M = [0, 0, 0],
138
+ carried = 0;
139
+ for (const m of masses)
140
+ if (beyond(motion, j, m.item)) {
141
+ const f = scale(dir, m.kg * G);
142
+ F = add(F, f);
143
+ M = add(M, scale(cross(sub(rowsAt(worlds[m.item], m.point), O), f), 1 / 1000));
144
+ carried += m.kg;
145
+ }
146
+ const along = dot(F, Z),
147
+ radial = norm(sub(F, scale(Z, along))),
148
+ torque = dot(M, Z),
149
+ tipping = norm(sub(M, scale(Z, torque)));
150
+ return { axial: Math.abs(along), along, radial, tipping, torque, carried, F, O, Z };
151
+ }
152
+
153
+ /**
154
+ * What a joint's motor works against at one placing: N m about a revolute, N along a slide. The weight of every mass
155
+ * beyond it, then the torques and forces the assembly declares on it and a belt's push at the carriage's acceleration.
156
+ * Those say what the motor has to do, not which way, so each adds in the direction that makes it worse (on a vertical
157
+ * axis, the weight plus 12 N, never the weight less it: a declared force never cancels the parts' own weight). The
158
+ * carriage's own weight that lib/belts.mjs also declares (beltWeight) is left out: its parts are counted here already.
159
+ * @param {object} motion @param {{ item: number, kg: number, point: number[] }[]} masses @param {object[]} loads the
160
+ * declared loads (motion.loads) @param {number[][]} worlds @param {object} j @param {Function} mul @returns {number}
161
+ */
162
+ export function driveLoadAt(motion, masses, loads, worlds, j, mul) {
163
+ const L = loadAt(motion, masses, worlds, j, mul);
164
+ let total = j.type === 'prismatic' ? L.along : L.torque,
165
+ push = 0;
166
+ for (const l of loads)
167
+ if (l.joint !== j.id || l.beltWeight) continue;
168
+ else push += Math.abs(l.value);
169
+ return push ? total + (total < 0 ? -push : push) : total;
170
+ }
171
+
172
+ /**
173
+ * What a joint's motor was checked against, in words and figures: the parts' own mass beyond it, the declared and
174
+ * task masses, the declared torques or forces, and gravity's direction (down, -Z, when the assembly gives none).
175
+ * @param {object} s a built assembly @param {{ item: number, kg: number, kind: string }[]} masses
176
+ * @param {object[]} loads @param {object} j @returns {{ text: string, values: object }}
177
+ */
178
+ export function countedFor(s, masses, loads, j) {
179
+ const motion = s.motion;
180
+ const kg = (kind) => masses.filter((m) => m.kind === kind && beyond(motion, j, m.item)).reduce((t, m) => t + m.kg, 0),
181
+ parts = kg('part'),
182
+ payload = kg('load') + kg('payload'),
183
+ declared = loads.filter((l) => l.joint === j.id && !l.belt && !l.beltWeight).length,
184
+ pushed = loads.some((l) => l.joint === j.id && l.belt),
185
+ given = s.a?.gravity != null,
186
+ g = motion.gravity || [0, 0, -1];
187
+ const grams = (x) => `${String(Number((x * 1000).toFixed(0)))} g`;
188
+ const bits = [
189
+ `the parts' own ${grams(parts)}`,
190
+ ...(payload ? [`${grams(payload)} of payload`] : []),
191
+ ...(declared
192
+ ? [`${declared} declared ${j.type === 'prismatic' ? 'force' : 'torque'}${declared > 1 ? 's' : ''}`]
193
+ : []),
194
+ ...(pushed ? [`the belt's push`] : []),
195
+ given ? `gravity along [${g.join(', ')}]` : 'gravity down (-Z, as the assembly gives no "gravity")',
196
+ ];
197
+ return {
198
+ text: `counted: ${bits.join(', ')}`,
199
+ values: { parts, payload, declared, gravity: g, gravityGiven: given },
200
+ };
201
+ }