@rulecad/model-link 0.3.3 → 0.4.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/model-link.mjs CHANGED
@@ -1,18 +1,25 @@
1
1
  // Model links: a printable model in a URL fragment. The fragment never reaches the web
2
- // host, so a public page can open private designs. Data only, never code. Runs in browsers and Node (18+).
2
+ // host, so a public page can open private designs. Data only, never code. Runs in browsers and Node 22.13 or later.
3
3
  //
4
4
  // https://<host>/#m=1.<base64url(deflate-raw(JSON))>[&get=stl|3mf]
5
- // JSON: { title, version, src, set, material, orientation, rules: [[label, value, unit]], q, p, t, parts }
5
+ // JSON: { q, p, t, parts?, title?, version?, src?, set?, material?, orientation?, sheet?, views?, fab?, motion?, task?,
6
+ // steps?, wires?, show?, rules?, build? }
7
+ // Every field is described once, in the table LINK below (the checks and their messages come from it), and this
8
+ // list is held to it by test/schema.test.mjs. A field the table doesn't have opens with a warning and is left out.
9
+ // title, version, src, set, material, orientation: text (the design's name, version, where it came from, its rule
10
+ // set, its material, how it lies on the bed). rules: [[label, value, unit?]], the rules card; sheet: rows of up
11
+ // to 9 text cells, the rules sheet.
6
12
  // p: [x, y, z, …] whole multiples of q (mm); t: [a, b, c, …] triangles as vertex indices, counter-clockwise
7
13
  // seen from outside; Z up, the bed at z = 0.
8
14
  // parts (optional): [[name, role, label, first, count, slot?]], runs of triangles in t; role "support" is printed,
9
- // then removed; slot is the part's AMS slot (1 without one). Without parts, the whole model is one part. Role
15
+ // then removed; slot is the part's AMS slot, a whole number from 1 to 16 (1 without one). Without parts, the whole model is one part. Role
10
16
  // "pose": another shape of a part, shown only in a pose (a flexure bent; see motion.swap), never printed or checked;
11
17
  // these come after the parts they stand in for.
12
18
  // views (optional): [[name, svg]], 2D drawings shown beside the 3D model (a board's copper, a schematic); "Group:
13
19
  // view" names share a tab. The page shows them as images, so nothing in them runs.
14
20
  // fab (optional): [{ name, zip }], a board's files for its fab (Gerbers, drill files, BOM, placement), each a zip
15
- // file's name and its bytes in base64: the page offers each as a download, as it is.
21
+ // file's name and its bytes in base64: the page offers each as a download, as it is. decode() refuses one that is
22
+ // not a zip of a board's files (by their extensions: see FAB_FILE).
16
23
  // Or placed shapes, for things made of repeated parts (nine keys): each shape once, then where each copy goes:
17
24
  // { …, shapes: [{ role, label, slot?, q, p, t }], place: [[shape, a, b, c, d, e, f, g, h, i, j, k, l, name?]] }
18
25
  // (a 3 × 4 transform by rows, in mm). decode() expands them, so the rest of the page sees one model.
@@ -21,30 +28,51 @@
21
28
  // "1." is the format version: newer pages must keep reading old links.
22
29
 
23
30
  /** @typedef {[[number, number, number], [number, number, number], [number, number, number]]} Triangle corners in mm, counter-clockwise seen from outside, Z up */
24
- /** @typedef {{ title?: string, version?: string, src?: string, material?: string, orientation?: string, fab?: { name: string, zip: string }[], rules?: [string, any, string][], q?: number, p?: number[], t?: number[], parts?: any[], shapes?: any[], place?: any[], views?: [string, string][], motion?: any }} Model */
31
+ /** @typedef {{ q?: number, p?: number[], t?: number[], parts?: any[], title?: string, version?: string, src?: string, set?: string, material?: string, orientation?: string, sheet?: string[][], views?: [string, string][], fab?: { name: string, zip: string }[], motion?: any, task?: any, steps?: any, wires?: any[], show?: 'built', rules?: [string, any, string?][], build?: any, shapes?: any[], place?: any[] }} Model */
25
32
 
26
33
  export const VERSION = 1;
27
- export const LIMITS = { vertices: 200000, triangles: 400000, shapes: 512, places: 2048, views: 32, viewSize: 4e6, sheet: 5000, fab: 8, fabSize: 8e6, // a fab zip, in base64 characters // every keycap with its own legend is its own shape
34
+ export const LIMITS = {
35
+ vertices: 200000,
36
+ triangles: 400000,
37
+ shapes: 512,
38
+ places: 2048,
39
+ views: 32,
40
+ viewSize: 4e6,
41
+ sheet: 5000,
42
+ fab: 8,
43
+ fabSize: 8e6, // a fab zip, in base64 characters // every keycap with its own legend is its own shape
28
44
  size: 1e5, // mm: no corner further than this from the origin (a link is a part or an assembly, not a map)
29
45
  text: 2000, // characters in a title, a name or a label
30
- bytes: 160e6 }; // of a link once unpacked: its views at their largest, and the biggest model, with room to spare
46
+ bytes: 160e6,
47
+ }; // of a link once unpacked: its views at their largest, and the biggest model, with room to spare
31
48
 
32
- const b64 = (bytes) => { let s = ''; for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); };
49
+ const b64 = (bytes) => {
50
+ let s = '';
51
+ for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
52
+ return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
53
+ };
33
54
  const unb64 = (s) => Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0));
34
55
  // most: stop reading once this many bytes have come out (a small link can unpack to a great deal)
35
56
  async function pipe(bytes, stream, most = Infinity) {
36
- const reader = new Blob([bytes]).stream().pipeThrough(stream).getReader(), chunks = [];
57
+ const reader = new Blob([bytes]).stream().pipeThrough(stream).getReader(),
58
+ chunks = [];
37
59
  let size = 0;
38
60
  for (;;) {
39
61
  const { done, value } = await reader.read();
40
62
  if (done) break;
41
63
  size += value.length;
42
- if (size > most) { await reader.cancel(); throw Object.assign(new Error('model too big for a link'), { tooBig: true }); }
64
+ if (size > most) {
65
+ await reader.cancel();
66
+ throw Object.assign(new Error('model too big for a link'), { tooBig: true });
67
+ }
43
68
  chunks.push(value);
44
69
  }
45
70
  const out = new Uint8Array(size);
46
71
  let at = 0;
47
- for (const c of chunks) { out.set(c, at); at += c.length; }
72
+ for (const c of chunks) {
73
+ out.set(c, at);
74
+ at += c.length;
75
+ }
48
76
  return out;
49
77
  }
50
78
 
@@ -52,15 +80,33 @@ async function pipe(bytes, stream, most = Infinity) {
52
80
  /** @param {Triangle[]} tris @returns {{ q: number, p: number[], t: number[] }} */
53
81
  export function fromTriangles(tris) {
54
82
  // (triangles: three corners each; a quad or a polygon is split into a fan, not passed through as a broken model)
55
- if (tris.some((t) => !Array.isArray(t) || t.length < 3)) throw new Error('fromTriangles: each face needs three corners or more');
56
- if (tris.some((t) => t.length > 3)) tris = tris.flatMap((t) => (t.length === 3 ? [t] : t.slice(1, -1).map((_, i) => [t[0], t[i + 1], t[i + 2]])));
57
- const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity]; // a loop: spreading big models overflows the stack
58
- for (const tri of tris) for (const v of tri) for (let k = 0; k < 3; k++) { if (v[k] < lo[k]) lo[k] = v[k]; if (v[k] > hi[k]) hi[k] = v[k]; }
83
+ if (tris.some((t) => !Array.isArray(t) || t.length < 3))
84
+ throw new Error('fromTriangles: each face needs three corners or more');
85
+ if (tris.some((t) => t.length > 3))
86
+ tris = tris.flatMap((t) => (t.length === 3 ? [t] : t.slice(1, -1).map((_, i) => [t[0], t[i + 1], t[i + 2]])));
87
+ const lo = [Infinity, Infinity, Infinity],
88
+ hi = [-Infinity, -Infinity, -Infinity]; // a loop: spreading big models overflows the stack
89
+ for (const tri of tris)
90
+ for (const v of tri)
91
+ for (let k = 0; k < 3; k++) {
92
+ if (v[k] < lo[k]) lo[k] = v[k];
93
+ if (v[k] > hi[k]) hi[k] = v[k];
94
+ }
59
95
  const extent = tris.length ? Math.max(hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]) : 0;
60
96
  const q = Number((10 ** Math.floor(Math.log10(extent / 5000 || 1))).toPrecision(1));
61
- const p = [], t = [], index = new Map();
97
+ const p = [],
98
+ t = [],
99
+ index = new Map();
62
100
  for (const tri of tris) {
63
- const ids = tri.map((v) => { const g = v.map((c) => Math.round(c / q)), k = g.join(','); if (!index.has(k)) { index.set(k, p.length / 3); p.push(...g); } return index.get(k); });
101
+ const ids = tri.map((v) => {
102
+ const g = v.map((c) => Math.round(c / q)),
103
+ k = g.join(',');
104
+ if (!index.has(k)) {
105
+ index.set(k, p.length / 3);
106
+ p.push(...g);
107
+ }
108
+ return index.get(k);
109
+ });
64
110
  if (ids[0] !== ids[1] && ids[1] !== ids[2] && ids[0] !== ids[2]) t.push(...ids); // snapping can collapse slivers
65
111
  }
66
112
  return { q, p, t };
@@ -69,20 +115,44 @@ export function fromTriangles(tris) {
69
115
  // fromParts([{ name, role, label, triangles }]) -> { q, p, t, parts }: shared corners merged across parts.
70
116
  /** @param {{ name: string, role?: 'part' | 'support' | 'reference', label?: string, slot?: number, triangles: Triangle[] }[]} list @returns {{ q: number, p: number[], t: number[], parts: any[] }} */
71
117
  export function fromParts(list) {
72
- const m = fromTriangles(list.flatMap((x) => x.triangles)), parts = [];
118
+ const m = fromTriangles(list.flatMap((x) => x.triangles)),
119
+ parts = [];
73
120
  // fromTriangles drops triangles that snapping collapses, so count each part's survivors in order
74
- let at = 0, kept = 0;
121
+ let kept = 0;
75
122
  const grid = (v) => v.map((c) => Math.round(c / m.q)).join(',');
76
123
  for (const x of list) {
77
124
  const first = kept;
78
- for (const tri of x.triangles) { const k = tri.map(grid); if (k[0] !== k[1] && k[1] !== k[2] && k[0] !== k[2]) kept++; at++; }
79
- parts.push([x.name, x.role || 'part', x.label || x.name, first, kept - first, ...(x.slot > 1 ? [x.slot] : [])]);
125
+ for (const tri of x.triangles) {
126
+ const k = tri.map(grid);
127
+ if (k[0] !== k[1] && k[1] !== k[2] && k[0] !== k[2]) kept++;
128
+ }
129
+ parts.push([
130
+ x.name,
131
+ x.role || 'part',
132
+ x.label || x.name,
133
+ first,
134
+ kept - first,
135
+ ...(x.slot > 1 ? [Number(x.slot)] : []),
136
+ ]);
80
137
  }
81
138
  return { ...m, parts };
82
139
  }
83
140
 
84
- /** A model as a link token ('1.' + compressed data), for #m= in a URL. @param {Model} model @returns {Promise<string>} */
141
+ /**
142
+ * A model as a link token ('1.' + compressed data), for #m= in a URL. Checked first, as decode() checks it: a model the
143
+ * page would turn away is refused here, when the link is made, not when someone opens it.
144
+ * @param {Model} model @returns {Promise<string>} @throws an Error saying what is wrong with the model
145
+ */
85
146
  export async function encode(model) {
147
+ const found = inspect(model).findings,
148
+ bad = found.find((f) => f.level === 'fail');
149
+ if (bad) throw new Error(bad.text);
150
+ // (a field the page doesn't read would be left out when the link is opened: the link would not be what was made)
151
+ const extra = found.find((f) => f.level === 'warn');
152
+ if (extra)
153
+ throw new Error(
154
+ `a link can't carry ${extra.values.path}: it is not one of a link's fields, so the page would leave it out (the fields are listed in @rulecad/model-link)`,
155
+ );
86
156
  const bytes = await pipe(new TextEncoder().encode(JSON.stringify(model)), new CompressionStream('deflate-raw'));
87
157
  return `${VERSION}.${b64(bytes)}`;
88
158
  }
@@ -107,113 +177,891 @@ export async function fromGist(id) {
107
177
  return (f.truncated ? await (await fetch(f.raw_url)).text() : f.content).trim();
108
178
  }
109
179
 
110
- /** A link token back to a model, checked: damaged, newer or oversized links are refused. @param {string} token @returns {Promise<Model>} */
111
- export async function decode(token) {
180
+ /**
181
+ * A link token back to a model, checked: damaged, newer or oversized links are refused, with a message naming the field
182
+ * (check() gives the same as findings). A field a link doesn't have is left out, not refused, so links made by a newer
183
+ * cad still open: give options.warnings, a list, for a warning about each (findings, level 'warn').
184
+ * @param {string} token @param {{ warnings?: any[] }} [options] @returns {Promise<Model>}
185
+ */
186
+ export async function decode(token, { warnings } = {}) {
112
187
  const m = String(token || '').match(/^(\d+)\.([\w-]+)$/);
113
188
  if (!m) throw new Error("this isn't a model link");
114
189
  if (Number(m[1]) > VERSION) throw new Error(`this link needs a newer page (format ${m[1]})`);
115
190
  let model;
116
- try { model = JSON.parse(new TextDecoder().decode(await pipe(unb64(m[2]), new DecompressionStream('deflate-raw'), LIMITS.bytes))); }
117
- catch (e) { if (e?.tooBig) throw e; throw new Error('This link is damaged: it may have been cut short when it was shared. Copy the whole link again.'); }
118
- if (model && Array.isArray(model.shapes)) model = expand(model);
119
- const errors = problems(model);
120
- if (errors.length) throw new Error(errors[0]);
121
- return model;
122
- }
123
-
124
- function problems(m) {
125
- if (!m || typeof m !== 'object' || !Array.isArray(m.p) || !Array.isArray(m.t)) return ['no model in the link'];
126
- if (typeof m.q !== 'number' || !Number.isFinite(m.q) || !(m.q > 0)) return ['bad grid size'];
127
- if (m.p.length % 3 || m.t.length % 3) return ['broken model data'];
128
- if (m.p.length / 3 > LIMITS.vertices || m.t.length / 3 > LIMITS.triangles) return ['model too big for a link'];
129
- const n = m.p.length / 3, far = LIMITS.size / m.q;
130
- if (m.p.some((x) => !Number.isInteger(x)) || m.t.some((i) => !Number.isInteger(i) || i < 0 || i >= n)) return ['broken model data'];
131
- if (m.p.some((x) => Math.abs(x) > far)) return [`a corner is more than ${LIMITS.size / 1000} m from the origin: too far for a link`];
132
- // what the page and the file writers read as text is text, and short
133
- for (const k of ['title', 'version', 'src', 'set', 'material', 'orientation']) if (m[k] != null && (typeof m[k] !== 'string' || m[k].length > LIMITS.text)) return [`broken ${k}`];
134
- if (m.sheet != null && (!Array.isArray(m.sheet) || m.sheet.length > LIMITS.sheet || m.sheet.some((r) => !Array.isArray(r) || r.length > 9 || r.some((c) => typeof c !== 'string')))) return ['broken rules sheet'];
135
- if (Array.isArray(m.views) && m.views.length > LIMITS.views) return [`${m.views.length} flat views: more than a link can hold (${LIMITS.views})`];
136
- if (m.views != null && (!Array.isArray(m.views) || m.views.some((v) => !Array.isArray(v) || typeof v[0] !== 'string' || typeof v[1] !== 'string' || v[1].length > LIMITS.viewSize))) return ['broken views'];
137
- if (m.fab != null && (!Array.isArray(m.fab) || m.fab.length > LIMITS.fab || m.fab.some((f) => !f || typeof f.name !== 'string' || !/^[\w@.+-]{1,200}\.zip$/.test(f.name)
138
- || typeof f.zip !== 'string' || f.zip.length > LIMITS.fabSize || !/^[A-Za-z0-9+/]*={0,2}$/.test(f.zip)))) return ['broken fab files'];
139
- if (m.motion != null && !motionOk(m.motion, m.parts?.length ?? 1)) return ['broken motion'];
140
- if (m.task != null && !taskOk(m.task)) return ['broken task'];
141
- if (m.steps != null && !stepsOk(m.steps)) return ['broken step file'];
142
- if (m.wires != null && !wiresOk(m.wires)) return ['broken wires'];
143
- if (m.build != null && !plain(m.build)) return ['broken build page'];
144
- if (m.show != null && m.show !== 'built') return ['broken show'];
145
- if (m.parts != null && (!Array.isArray(m.parts) || m.parts.some((x) => !Array.isArray(x) || x.slice(0, 3).some((name, k) => (k === 2 && name == null ? false : typeof name !== 'string' || name.length > LIMITS.text)) || !Number.isInteger(x[3]) || !Number.isInteger(x[4]) || x[3] < 0 || x[4] < 0 || x[3] + x[4] > m.t.length / 3))) return ['broken parts list'];
146
- // parts may share triangles, but all of them together are held to the link's limit: a short list of parts each
147
- // naming every triangle would otherwise make the file writers write (and mend) the model hundreds of times over.
148
- // The list itself is held to an assembly's limit on places: a long list of empty parts made the 3MF writer write
149
- // hundreds of megabytes of part names for nothing.
150
- if (m.parts != null && (m.parts.length > LIMITS.places || m.parts.reduce((n, x) => n + x[4], 0) > LIMITS.triangles)) return ['model too big for a link'];
151
- return [];
191
+ try {
192
+ model = JSON.parse(
193
+ new TextDecoder().decode(await pipe(unb64(m[2]), new DecompressionStream('deflate-raw'), LIMITS.bytes)),
194
+ );
195
+ } catch (e) {
196
+ if (e?.tooBig) throw e;
197
+ throw new Error('This link is damaged: it may have been cut short when it was shared. Copy the whole link again.');
198
+ }
199
+ const { findings: found, unknown, model: made } = inspect(model),
200
+ bad = found.find((f) => f.level === 'fail');
201
+ if (bad) throw new Error(bad.text);
202
+ // what the page doesn't read is left out, so nothing in the model it gets went unchecked
203
+ for (const [, holder, key] of unknown) {
204
+ if (Array.isArray(holder)) holder.length = Math.min(holder.length, key);
205
+ else {
206
+ delete holder[key];
207
+ // (a placed-shapes link's own q, p, t or parts are not what spread() made in their place: those stay)
208
+ if (holder === model && !(made !== model && SPREAD.includes(key))) delete made[key];
209
+ }
210
+ }
211
+ for (const f of found) if (f.level === 'warn') warnings?.push(f);
212
+ return made;
152
213
  }
153
214
 
154
- /**
155
- * What's wrong with a model's data, as findings (the kit's one result shape): [{ level: 'fail', text, code: 'link.data' }],
156
- * empty when it's sound.
157
- * @param {any} m @returns {{ level: 'fail', text: string, code: string }[]}
158
- */
159
- export function check(m) { return problems(m).map((text) => ({ level: 'fail', text, code: 'link.data' })); }
160
-
161
- // A link's motion, as data: numbers where numbers go, items and joints that exist, nothing that could run
162
- const nums = (a, n) => Array.isArray(a) && (n == null || a.length === n) && a.every((x) => typeof x === 'number' && Number.isFinite(x));
163
- function motionOk(mo, places) {
164
- if (!mo || typeof mo !== 'object' || !Array.isArray(mo.items) || !Array.isArray(mo.joints) || mo.items.length > LIMITS.places || mo.joints.length > LIMITS.places) return false;
165
- const n = mo.items.length, item = (i) => Number.isInteger(i) && i >= -1 && i < n;
166
- if (mo.items.some((x) => !Array.isArray(x) || typeof x[0] !== 'string' || !(x.length === 1 || nums(x.slice(1), 12)))) return false;
167
- if (mo.joints.some((j) => !j || typeof j.id !== 'string' || !Object.hasOwn(DOFS, j.type) || (j.cone != null && !nums([j.cone])) || !item(j.parent) || !item(j.child) || j.child < 0 || !nums(j.a, 12) || !nums(j.b, 12)
168
- || !Array.isArray(j.dofs) || j.dofs.length !== DOFS[j.type].length || !j.dofs.every((d) => nums(d, 3))
169
- || (j.type === 'path' && !(Array.isArray(j.path) && j.path.length >= 2 && j.path.length <= LIMITS.places && j.path.every((p) => nums(p, 3))))
170
- || (j.follow != null && !(Array.isArray(j.follow) && typeof j.follow[0] === 'string' && nums(j.follow.slice(1)))))) return false;
171
- if (!Array.isArray(mo.part) || mo.part.length !== places || !mo.part.every(item)) return false;
172
- if (mo.poses != null && (typeof mo.poses !== 'object' || Object.values(mo.poses).some((p) => !p || typeof p !== 'object' || Object.values(p).some((v) => !(typeof v === 'number' || nums(v)))))) return false;
173
- const pair = (x) => Array.isArray(x) && x.length === 2 && x.every((i) => Number.isInteger(i) && i >= 0 && i < places);
174
- if (mo.swap != null && (typeof mo.swap !== 'object' || Object.entries(mo.swap).some(([n, list]) => !mo.poses?.[n] || !Array.isArray(list) || !list.every(pair)))) return false;
175
- if (mo.sequence != null && !(mo.sequence && Array.isArray(mo.sequence.names) && mo.sequence.names.every((n) => typeof n === 'string' && mo.joints.some((j) => j.id === n)) && Array.isArray(mo.sequence.q) && mo.sequence.q.length <= LIMITS.places && mo.sequence.q.every((row) => nums(row, mo.sequence.names.length)) && typeof mo.sequence.period === 'number' && mo.sequence.period > 0)) return false;
176
- return mo.allow == null || (Array.isArray(mo.allow) && mo.allow.every(pair));
215
+ // A filament slot: one of the printer's filament feeders, numbered from 1 (Bambu's AMS units hold 4 each, 16 at most)
216
+ const SLOTS = 16;
217
+ const slotOk = (s) => Number.isInteger(s) && s >= 1 && s <= SLOTS;
218
+
219
+ // The extensions a board's fab zip holds: Gerbers (.gbr, and the Protel names: .gtl top copper, .g1 an inner layer,
220
+ // .gko the outline, .gm1 a mechanical layer, …), drill files (.drl, .xln), the parts list and placement (.csv, .pos)
221
+ // and notes (.txt). KiCad's .gbrjob is a Gerber job file. Nothing that runs, nothing a browser shows as a page.
222
+ const FAB_FILE = /\.(gbr|gbrjob|g[tb][lops]|gko|gm\d*|gml|g\d+|drl|xln|csv|pos|txt)$/i;
223
+ // A fab file's bytes (base64) are a zip of board files only: its directory read for the names (nothing is
224
+ // unpacked), every entry a file with a fab extension (or a folder), no name climbing out of the zip or holding a
225
+ // control character or a colon, and a zip from its first byte (a program with a zip stuck on its end is still a
226
+ // program). The entries the directory lists must fill the zip from its first byte to the directory, end to end, so no
227
+ // file hides between them: an unzipper that reads the entries one after another, not the directory, finds the same
228
+ // files. Unzippers differ in what else they read, so each of those is held to one answer too:
229
+ // - each entry's own header says what its directory record says (name, sizes, packing), so a reader of the headers
230
+ // ends each entry where the directory does; and no entry has its sizes after its bytes (flag 8), which only
231
+ // unpacking could check;
232
+ // - no comments on the zip or its entries, and no zip64 records: free bytes there could hold a second directory that
233
+ // some unzippers read instead of the first;
234
+ // - no extra field naming the file again (Info-ZIP's Unicode name, 0x7075, which some unzippers use in place of the
235
+ // name read here), and no entry that is a link to another file (Unix file type in its attributes: files and folders
236
+ // only).
237
+ // rulecad's own zip() writes none of these.
238
+ function fabZipOk(b64) {
239
+ let z;
240
+ try {
241
+ z = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
242
+ } catch {
243
+ return false;
244
+ }
245
+ const dv = new DataView(z.buffer),
246
+ u32 = (o) => dv.getUint32(o, true),
247
+ u16 = (o) => dv.getUint16(o, true);
248
+ if (z.length < 22 + 30 || u32(0) !== 0x04034b50) return false;
249
+ const end = z.length - 22; // the end record, with no comment after it
250
+ if (u32(end) !== 0x06054b50 || u16(end + 20) !== 0 || u16(end + 4) || u16(end + 6) || u16(end + 8) !== u16(end + 10))
251
+ return false;
252
+ if (u32(end - 20) === 0x07064b50) return false; // a zip64 locator
253
+ const count = u16(end + 10),
254
+ names = new TextDecoder('utf-8', { fatal: true }),
255
+ dir = u32(end + 16),
256
+ spans = [];
257
+ let at = dir;
258
+ if (!count || dir + u32(end + 12) !== end) return false;
259
+ const same = (a, b, n) => {
260
+ for (let k = 0; k < n; k++) if (z[a + k] !== z[b + k]) return false;
261
+ return true;
262
+ };
263
+ // an extra field's records, [id, size, data…]: well formed, and none of the kinds above
264
+ const extraOk = (o, n) => {
265
+ for (let e = o; e < o + n; e += 4 + u16(e + 2))
266
+ if (e + 4 > o + n || e + 4 + u16(e + 2) > o + n || u16(e) === 0x7075 || u16(e) === 0x0001) return false;
267
+ return true;
268
+ };
269
+ for (let i = 0; i < count; i++) {
270
+ if (at + 46 > end || u32(at) !== 0x02014b50) return false;
271
+ const n = u16(at + 28),
272
+ x = u16(at + 30),
273
+ local = u32(at + 42),
274
+ flags = u16(at + 8),
275
+ method = u16(at + 10);
276
+ if (at + 46 + n + x > end || u16(at + 32) || u16(at + 34)) return false; // (no entry comment, one disk)
277
+ let name;
278
+ try {
279
+ name = names.decode(z.subarray(at + 46, at + 46 + n));
280
+ } catch {
281
+ return false;
282
+ }
283
+ // (and the same in the entry's own header: an unzipper that reads those must find the same files, the same size)
284
+ if (local + 30 + n > dir || u32(local) !== 0x04034b50 || u16(local + 26) !== n || !same(local + 30, at + 46, n))
285
+ return false;
286
+ if (flags & ~0x806 || (method !== 0 && method !== 8) || u16(local + 6) !== flags || u16(local + 8) !== method)
287
+ return false;
288
+ if (u32(local + 14) !== u32(at + 16) || u32(local + 18) !== u32(at + 20) || u32(local + 22) !== u32(at + 24))
289
+ return false;
290
+ if (!extraOk(at + 46 + n, x) || !extraOk(local + 30 + n, u16(local + 28))) return false;
291
+ const type = (u32(at + 38) >>> 16) & 0o170000; // a Unix file type: none, a file or a folder
292
+ if (type && type !== 0o100000 && !(type === 0o040000 && name.endsWith('/'))) return false;
293
+ if (!name || /^[/\\]|(^|[/\\])\.\.([/\\]|$)|[\x00-\x1f\x7f:]/.test(name)) return false;
294
+ if (!name.endsWith('/') && !FAB_FILE.test(name)) return false;
295
+ // where the entry ends: its header, name, extra field and packed bytes
296
+ spans.push([local, local + 30 + n + u16(local + 28) + u32(at + 20)]);
297
+ at += 46 + n + x;
298
+ }
299
+ if (at !== end) return false;
300
+ spans.sort((a, b) => a[0] - b[0]);
301
+ let next = 0;
302
+ for (const [from, to] of spans) {
303
+ if (from !== next) return false;
304
+ next = to;
305
+ }
306
+ return next === dir;
177
307
  }
178
308
 
309
+ // ---------- the link's fields, in one table ----------
310
+ // Every field a link may hold is described once, in LINK below (and PLACED, for the placed-shapes form): its kind, its
311
+ // limits, the shape of its entries and whether it may be missing. readNode() reads a link against the table and gives the
312
+ // first thing wrong in each field, with where it is (values.path, such as 'motion.joints[3].dofs'), so encode(),
313
+ // decode() and check() all say the same. A field the table doesn't have is not refused, since links made by a newer
314
+ // cad must still open here: it is named in a warning and left out of the model decode() gives, so nothing the page
315
+ // reads went unchecked. test/schema.test.mjs holds the header comment's field list and the Model typedef to this table.
316
+ //
317
+ // A node: { is, ...options }. Kinds:
318
+ // text (a string of at most LIMITS.text characters, or max), num (a finite number: min, above, max), int (a whole
319
+ // number: min, max), one (one of values), list (of: the entries' node; length, least, most), tuple (items, by place:
320
+ // opt() marks one that may be missing; rest: the node for entries after them, else extras are unknown), obj (fields:
321
+ // a name ending in ? may be missing or null; open: other fields are plain data, else unknown), map (any names, each
322
+ // value of: of), any (the first of nodes that fits), all (every one of nodes), data (plain data: text, numbers,
323
+ // booleans, null, lists and objects of those, nested at most 8 deep).
324
+ // Options on any node: test(value, cx) for what the kinds can't say (one field against another), returning '' or
325
+ // what's wrong ({ at: the path below this node, why, says? }, or a string); why, the words when the node doesn't fit;
326
+ // says, the message for anything wrong at or under it, with {path} where the path goes.
327
+ const S = {
328
+ text: (o) => ({ is: 'text', ...o }),
329
+ num: (o) => ({ is: 'num', ...o }),
330
+ int: (o) => ({ is: 'int', ...o }),
331
+ one: (values, o) => ({ is: 'one', values, ...o }),
332
+ list: (of, o) => ({ is: 'list', of, ...o }),
333
+ tuple: (items, o) => ({ is: 'tuple', items, ...o }),
334
+ obj: (fields, o) => ({ is: 'obj', fields, ...o }),
335
+ map: (of, o) => ({ is: 'map', of, ...o }),
336
+ any: (nodes, o) => ({ is: 'any', nodes, ...o }),
337
+ all: (nodes, o) => ({ is: 'all', nodes, ...o }),
338
+ data: (o) => ({ is: 'data', ...o }),
339
+ };
340
+ const numbers = (n) => `${n} number${n === 1 ? '' : 's'}`;
341
+ const opt = (node) => ({ ...node, optional: true });
342
+ const INT = 2 ** 31;
343
+ const nums = (length, why) => S.list(S.num(), { length, why });
344
+ const xyz = nums(3, 'must be three numbers: x, y and z');
345
+ const frame12 = nums(12, 'must be 12 numbers: a 3 × 4 transform, by rows');
346
+ const whole = S.int({ min: -INT + 1, max: INT - 1 });
347
+ const SLOT_PROBLEM = `a part's filament slot must be a whole number from 1 to ${SLOTS}`;
348
+ const slotNode = S.int({ min: 1, max: SLOTS, says: `${SLOT_PROBLEM} (at {path})` });
349
+ const MODEL_GONE = 'no model in the link';
350
+
351
+ // The model itself: q, the grid (mm); p, the corners as whole multiples of q; t, the triangles as corners' indices
352
+ const core = {
353
+ q: S.num({ above: 0, says: 'bad grid size: {path} must be a number above 0' }),
354
+ p: S.list(null, {
355
+ says: 'broken model data: {path} {why}',
356
+ test: (p, cx) => {
357
+ if (p.length % 3) return 'must hold three numbers for each corner';
358
+ if (p.length / 3 > LIMITS.vertices)
359
+ return { why: '', says: `model too big for a link: more than ${LIMITS.vertices} corners` };
360
+ const far = LIMITS.size / cx.up[cx.up.length - 1].q;
361
+ for (let i = 0; i < p.length; i++) {
362
+ if (!Number.isInteger(p[i])) return { at: [i], why: 'must be a whole number' };
363
+ if (Math.abs(p[i]) > far)
364
+ return {
365
+ at: [i],
366
+ says: `a corner is more than ${LIMITS.size / 1000} m from the origin: too far for a link (at {path})`,
367
+ };
368
+ }
369
+ return '';
370
+ },
371
+ }),
372
+ t: S.list(null, {
373
+ says: 'broken model data: {path} {why}',
374
+ test: (t, cx) => {
375
+ if (t.length % 3) return 'must hold three corners for each triangle';
376
+ if (t.length / 3 > LIMITS.triangles)
377
+ return { why: '', says: `model too big for a link: more than ${LIMITS.triangles} triangles` };
378
+ const n = cx.up[cx.up.length - 1].p.length / 3;
379
+ for (let i = 0; i < t.length; i++)
380
+ if (!Number.isInteger(t[i]) || t[i] < 0 || t[i] >= n)
381
+ return { at: [i], why: `must be the number of one of the ${n} corners (0 to ${n - 1})` };
382
+ return '';
383
+ },
384
+ }),
385
+ };
386
+
387
+ // parts: [[name, role, label, first, count, slot?]], runs of triangles in t. Parts may share triangles, but all of them
388
+ // together are held to the link's limit, and the list to an assembly's limit on places: a short list each naming
389
+ // every triangle, or a long list of empty parts, made the file writers write (and mend) for nothing.
390
+ const partsNode = S.list(
391
+ S.tuple([S.text(), S.text(), opt(S.text()), S.int({ min: 0 }), S.int({ min: 0 }), opt(slotNode)], {
392
+ why: 'must be a part: its name, role, label, first triangle and count',
393
+ test: (x, cx) =>
394
+ x[3] + x[4] > cx.root.t.length / 3
395
+ ? { at: [4], why: `runs past the model's last triangle (${cx.root.t.length / 3})` }
396
+ : '',
397
+ }),
398
+ {
399
+ test: (list) =>
400
+ list.length > LIMITS.places || list.reduce((n, x) => n + x[4], 0) > LIMITS.triangles
401
+ ? {
402
+ why: '',
403
+ says: `model too big for a link: its parts name more than ${LIMITS.triangles} triangles, or are more than ${LIMITS.places}`,
404
+ }
405
+ : '',
406
+ },
407
+ );
408
+
409
+ // The rules card: [[label, value, unit?]], each label text, each value text or a number, each unit text if given
410
+ const RULES_PROBLEM =
411
+ 'broken rules card at {path}: each of its lines must be a name, a value and (if it has one) a unit';
412
+
413
+ // ---------- motion ----------
414
+ // Joints between items, so a page (or a tool) can move them: an assembly's hinges, rails and ball joints.
415
+ // motion: { items: [[name, …12?]], joints: [joint], poses: { name: { joint: value } }, pose?, part: [item per place],
416
+ // sequence?: { period, names: [joint], q: [values per frame], kind? } (a gait, played), allow?: [[place, place]],
417
+ // swap?: { pose: [[place, place]] } }
418
+ // An item with 12 numbers sits there (a 3 × 4 transform by rows, as in place); one without is placed by the joint
419
+ // whose child it is. part[n] is the item place n moves with (-1: it never moves); allow pairs may overlap (press fits).
420
+ // pose: the pose the page opens in. swap: in a pose, each part (its place) is drawn as another (a "pose" part's
421
+ // place): the shape it takes there.
422
+ // joint: { id, type, parent (item, -1 the world), child (item), a (the parent's anchor, 12 numbers, in its own
423
+ // frame), b (the child's anchor), dofs: [[min, max, value]], label?, follow?: [joint id, ratio, offset],
424
+ // path?: [[x, y, z], …], cone?, step? (a slider's step) }. At value 0 the child's anchor lies on the parent's.
425
+ // Types and their dofs: see DOFS.
426
+ const items = (cx) => cx.root.motion.items.length;
427
+ const placeNode = S.int({
428
+ min: 0,
429
+ test: (i, cx) => (i < cx.places ? '' : `must be a place from 0 to ${cx.places - 1}`),
430
+ });
431
+ const pair = S.tuple([placeNode, placeNode], { why: 'must be two places' });
432
+ const poseName = (n, cx) =>
433
+ cx.root.motion.poses && Object.hasOwn(cx.root.motion.poses, n) ? '' : "must name one of the motion's poses";
434
+ const jointId = (n, cx) =>
435
+ cx.root.motion.joints.some((j) => j.id === n) ? '' : "must name one of the motion's joints";
436
+ const joint = S.obj(
437
+ {
438
+ id: S.text(),
439
+ type: S.text({
440
+ test: (type) =>
441
+ Object.hasOwn(DOFS, type) ? '' : `must be one of the joint types: ${Object.keys(DOFS).join(', ')}`,
442
+ }),
443
+ parent: S.int({ min: -1 }),
444
+ child: S.int({ min: 0 }),
445
+ a: frame12,
446
+ b: frame12,
447
+ dofs: S.list(nums(3, 'must be three numbers: the least, the most and the value')),
448
+ 'label?': S.text(),
449
+ 'follow?': S.tuple([S.text(), opt(S.num()), opt(S.num())], { why: 'must be a joint, a ratio and an offset' }),
450
+ 'path?': S.list(xyz, { least: 2, most: LIMITS.places }),
451
+ 'cone?': S.num(),
452
+ 'step?': S.num(),
453
+ },
454
+ {
455
+ why: 'must be a joint: its id, type, parent, child, anchors and values',
456
+ test: (j, cx) => {
457
+ const n = items(cx);
458
+ if (j.parent >= n)
459
+ return { at: ['parent'], why: `must be one of the ${n} items (0 to ${n - 1}), or -1, the world` };
460
+ if (j.child >= n) return { at: ['child'], why: `must be one of the ${n} items (0 to ${n - 1})` };
461
+ const k = DOFS[j.type].length;
462
+ if (j.dofs.length !== k)
463
+ return { at: ['dofs'], why: `must be ${k} [least, most, value] for a ${j.type} joint, not ${j.dofs.length}` };
464
+ if (j.type === 'path' && j.path == null) return { at: ['path'], why: 'is missing: a path joint needs its path' };
465
+ return '';
466
+ },
467
+ },
468
+ );
469
+ const motionNode = S.obj(
470
+ {
471
+ items: S.list(S.tuple([S.text()], { rest: S.num() }), {
472
+ most: LIMITS.places,
473
+ test: (list) => {
474
+ const k = list.findIndex((x) => x.length !== 1 && x.length !== 13);
475
+ return k < 0 ? '' : { at: [k], why: 'must be a name alone, or a name and 12 numbers' };
476
+ },
477
+ }),
478
+ joints: S.list(joint, { most: LIMITS.places }),
479
+ 'poses?': S.map(S.map(S.any([S.num(), S.list(S.num())], { why: 'must be a number, or a list of numbers' }))),
480
+ 'pose?': S.text({ test: poseName }),
481
+ part: S.list(
482
+ S.int({
483
+ min: -1,
484
+ test: (i, cx) => (i < items(cx) ? '' : `must be one of the ${items(cx)} items, or -1 (it never moves)`),
485
+ }),
486
+ {
487
+ test: (list, cx) =>
488
+ list.length === cx.places ? '' : `must name an item for each of the ${cx.places} places, not ${list.length}`,
489
+ },
490
+ ),
491
+ 'allow?': S.list(pair),
492
+ 'swap?': S.map(S.list(pair), {
493
+ test: (swap, cx) => {
494
+ const k = Object.keys(swap).find((n) => poseName(n, cx));
495
+ return k == null ? '' : { at: [k], why: "must be one of the motion's poses" };
496
+ },
497
+ }),
498
+ 'sequence?': S.obj({
499
+ 'kind?': S.text(), // (what the sequence is: 'gait', in links from earlier versions of cad)
500
+ names: S.list(S.text({ test: jointId })),
501
+ q: S.list(S.list(S.num()), {
502
+ most: LIMITS.places,
503
+ test: (q, cx) => {
504
+ const n = cx.up[cx.up.length - 1].names.length,
505
+ k = q.findIndex((row) => row.length !== n);
506
+ return k < 0 ? '' : { at: [k], why: `must be ${numbers(n)}, one for each joint named` };
507
+ },
508
+ }),
509
+ period: S.num({ above: 0 }),
510
+ }),
511
+ },
512
+ { why: 'must be the motion: its items, joints and the item each place moves with' },
513
+ );
514
+
179
515
  // ---------- a machine's link ----------
180
516
  // task: { tool, item, point: [x, y, z], plane: { at, u, v, n, width, height }, elbow?, speed?, accuracy?, deflection?,
181
517
  // terms?: [[joint index in the chain, name, degrees, kind]], loads?: [{ item (index), at: [x, y, z], mass } |
182
518
  // { joint, value }], gravity?: [x, y, z], torque?: [{ joint, available }], heat?: { motor, case, softening } }:
183
519
  // the tool's anchor as chainFromMotion takes it (@rulecad/robots), the plane the pen moves on, and what the margins
184
520
  // read at each pose: error terms (degrees) carried to the tool, masses carried beyond each joint, what each motor gives.
185
- // steps: a step file from cad plot, cut down by compactSteps: { name, machine?, names, spu, start, b, drawn }.
521
+ // steps: a step file from cad plot, cut down by compactSteps: { name?, machine?, names, spu, start, b, drawn }.
186
522
  // b: blocks, [kind, milliseconds, stroke, …axis steps]; kind 0 travel, 1 draw, 2 pen up, 3 pen down (those last two
187
523
  // are only [kind, milliseconds]). drawn: lines, [stroke, [x, y, z, …] in 0.01 mm, [predicted error in microns, per
188
524
  // point] | null], stroke matching a block's.
189
525
  // wires: [[id, [[item (index, -1 fixed), x, y, z], …]]], routes drawn faint, moving with their items; never parts.
190
526
  // build: the build page's content, read as text and numbers (the shopping list, plates, wiring, steps, settings).
191
527
  // show (optional): 'built', an assembly shown as the thing built: its references drawn solid, as its parts are.
192
- const INT = 2 ** 31;
193
- const int = (x) => Number.isInteger(x) && Math.abs(x) < INT;
194
- const text = (x) => typeof x === 'string' && x.length <= LIMITS.text;
195
- // Only data: strings in bounds, finite numbers, booleans, null, and arrays or plain objects of those
196
- function plain(x, depth = 0) {
197
- if (x === null || typeof x === 'boolean' || (typeof x === 'number' && Number.isFinite(x)) || text(x)) return true;
198
- if (depth > 8 || typeof x !== 'object') return false;
199
- return Array.isArray(x) ? x.length <= LIMITS.places * 4 && x.every((y) => plain(y, depth + 1)) : Object.keys(x).length <= 200 && Object.values(x).every((y) => plain(y, depth + 1));
200
- }
201
- function taskOk(t) {
202
- if (!t || typeof t !== 'object' || !text(t.tool) || !text(t.item) || !nums(t.point, 3) || !t.plane || !['at', 'u', 'v', 'n'].every((k) => nums(t.plane[k], 3)) || !(t.plane.width > 0) || !(t.plane.height > 0)) return false;
203
- if (t.terms != null && !(Array.isArray(t.terms) && t.terms.every((x) => Array.isArray(x) && Number.isInteger(x[0]) && text(x[1]) && nums([x[2]]) && text(x[3])))) return false;
204
- if (t.loads != null && !(Array.isArray(t.loads) && t.loads.every((l) => l && typeof l === 'object' && (typeof l.joint === 'string' ? nums([l.value]) : Number.isInteger(l.item) && nums(l.at, 3) && nums([l.mass]))))) return false;
205
- if (t.torque != null && !(Array.isArray(t.torque) && t.torque.every((x) => x && text(x.joint) && nums([x.available])))) return false;
206
- if (t.gravity != null && !nums(t.gravity, 3)) return false;
207
- for (const k of ['speed', 'accuracy', 'deflection']) if (t[k] != null && !nums([t[k]])) return false;
208
- return (t.elbow == null || ['left', 'right'].includes(t.elbow)) && (t.heat == null || (text(t.heat.motor) && nums([t.heat.case, t.heat.softening], 2)));
209
- }
210
- function stepsOk(x) {
211
- if (!x || typeof x !== 'object' || !Array.isArray(x.names) || !x.names.every(text) || !nums(x.spu, x.names.length) || !nums(x.start, x.names.length) || !Array.isArray(x.b) || !Array.isArray(x.drawn)) return false;
212
- const n = x.names.length;
213
- if (x.b.some((r) => !Array.isArray(r) || !int(r[0]) || r[0] < 0 || r[0] > 3 || !int(r[1]) || (r[0] < 2 ? r.length !== n + 3 || !r.slice(2).every(int) : r.length !== 2))) return false;
214
- return x.drawn.every((d) => Array.isArray(d) && int(d[0]) && Array.isArray(d[1]) && d[1].length % 3 === 0 && d[1].every(int) && (d[2] === null || (Array.isArray(d[2]) && d[2].length === d[1].length / 3 && d[2].every(int))));
215
- }
216
- const wiresOk = (w) => Array.isArray(w) && w.every((x) => Array.isArray(x) && text(x[0]) && Array.isArray(x[1]) && x[1].every((p) => Array.isArray(p) && p.length === 4 && p.every((v) => typeof v === 'number' && Number.isFinite(v))));
528
+ const taskNode = S.obj({
529
+ tool: S.text(),
530
+ item: S.text(),
531
+ point: xyz,
532
+ plane: S.obj({
533
+ at: xyz,
534
+ u: xyz,
535
+ v: xyz,
536
+ n: xyz,
537
+ width: S.num({ above: 0 }),
538
+ height: S.num({ above: 0 }),
539
+ }),
540
+ 'elbow?': S.one(['left', 'right']),
541
+ 'speed?': S.num(),
542
+ 'accuracy?': S.num(),
543
+ 'deflection?': S.num(),
544
+ 'terms?': S.list(S.tuple([S.int(), S.text(), S.num(), S.text()]), {
545
+ why: 'must be a list of [joint, name, degrees, kind]',
546
+ }),
547
+ 'loads?': S.list(
548
+ S.any([S.obj({ joint: S.text(), value: S.num() }), S.obj({ item: S.int(), at: xyz, mass: S.num() })], {
549
+ why: 'must be a load: { item, at, mass }, or { joint, value }',
550
+ }),
551
+ ),
552
+ 'gravity?': xyz,
553
+ 'torque?': S.list(S.obj({ joint: S.text(), available: S.num() })),
554
+ 'heat?': S.obj({ motor: S.text(), case: S.num(), softening: S.num() }),
555
+ });
556
+ const stepsNode = S.obj(
557
+ {
558
+ 'name?': S.text(),
559
+ 'machine?': S.text(),
560
+ names: S.list(S.text()),
561
+ spu: S.list(S.num()),
562
+ start: S.list(S.num()),
563
+ b: S.list(S.tuple([S.int({ min: 0, max: 3 }), whole], { rest: whole })),
564
+ drawn: S.list(
565
+ S.tuple(
566
+ [
567
+ whole,
568
+ S.list(whole),
569
+ S.any([S.one([null]), S.list(whole)], { why: 'must be a list of whole numbers, or null' }),
570
+ ],
571
+ {
572
+ why: 'must be a line: its stroke, its points and their errors (or null)',
573
+ test: (d) =>
574
+ d[1].length % 3
575
+ ? { at: [1], why: 'must hold three numbers for each point' }
576
+ : d[2] && d[2].length !== d[1].length / 3
577
+ ? { at: [2], why: `must be ${numbers(d[1].length / 3)}, one for each point` }
578
+ : '',
579
+ },
580
+ ),
581
+ ),
582
+ },
583
+ {
584
+ test: (x) => {
585
+ const n = x.names.length;
586
+ if (x.spu.length !== n) return { at: ['spu'], why: `must be ${numbers(n)}, one for each axis` };
587
+ if (x.start.length !== n) return { at: ['start'], why: `must be ${numbers(n)}, one for each axis` };
588
+ const k = x.b.findIndex((r) => r.length !== (r[0] < 2 ? n + 3 : 2));
589
+ return k < 0
590
+ ? ''
591
+ : {
592
+ at: ['b', k],
593
+ why: x.b[k][0] < 2 ? `must be a kind, a time, a stroke and ${n} axis steps` : 'must be a kind and a time',
594
+ };
595
+ },
596
+ },
597
+ );
598
+ const wiresNode = S.list(S.tuple([S.text(), S.list(nums(4, 'must be four numbers: an item, then x, y and z'))]), {
599
+ why: 'must be a list of [id, points]',
600
+ });
601
+
602
+ // The build page's known sections, by the shape the page reads them in: a list is [item], an object { field }, a
603
+ // field ending in ? may be missing (or null). 'obj' is any object, 'num' a number, 'text' text, 'cell' what a table
604
+ // cell shows (text, a number, true or false, or nothing). Only what the page takes apart is held here: the rest is
605
+ // written as text, so it is data (no unknown fields inside a section). A section may instead be { error } (what cad
606
+ // couldn't make), or null.
607
+ const cells = ['cell'];
608
+ const BUILD_SECTIONS = {
609
+ list: {
610
+ 'bought?': [{ items: cells }],
611
+ 'fasteners?': [{ from: cells }],
612
+ 'wires?': [{ runs: cells }],
613
+ 'printed?': ['obj'],
614
+ totals: { 'pack?': 'obj', 'noMassFor?': cells },
615
+ 'cut?': {
616
+ marks: [{ ops: cells, items: cells }],
617
+ stock: [{ buy: ['obj'], bars: [{ cuts: ['obj'] }] }],
618
+ rules: 'obj',
619
+ },
620
+ },
621
+ beams: { 'sheets?': [{ items: cells }] },
622
+ plates: { plates: [{ parts: ['obj'] }] },
623
+ wires: [{ current: 'num' }],
624
+ order: {
625
+ 'stuck?': { text: 'text' },
626
+ 'steps?': [{ items: cells, 'load?': cells, fasteners: [{ 'tighten?': 'obj' }] }],
627
+ },
628
+ frame: {
629
+ 'stuck?': { text: 'text' },
630
+ 'steps?': [{ 'lines?': cells, 'shown?': cells, 'now?': cells }],
631
+ 'notFlat?': ['obj'],
632
+ 'torques?': [{ fasteners: cells }],
633
+ 'bays?': ['obj'],
634
+ },
635
+ machine: { task: 'obj', axes: [{ limits: cells, 'homing?': 'obj' }] },
636
+ };
637
+ const BUILD_TITLES = {
638
+ list: 'What to buy',
639
+ beams: 'Cut-and-drill sheets',
640
+ plates: 'Plates',
641
+ wires: 'Wiring',
642
+ order: 'Assembly',
643
+ frame: 'Building the frame',
644
+ machine: 'Machine settings',
645
+ };
646
+ const section = (spec) =>
647
+ spec === 'text'
648
+ ? S.text()
649
+ : spec === 'num'
650
+ ? S.num()
651
+ : spec === 'cell'
652
+ ? S.any([S.one([null]), S.text(), S.num(), S.one([true, false])])
653
+ : spec === 'obj'
654
+ ? S.obj({}, { open: true })
655
+ : Array.isArray(spec)
656
+ ? S.list(section(spec[0]))
657
+ : S.obj(Object.fromEntries(Object.entries(spec).map(([k, s]) => [k, section(s)])), { open: true });
658
+ const buildNode = S.all(
659
+ [
660
+ S.data({
661
+ says: `broken build page at {path}: it holds something other than text and numbers, or a piece of text longer than a link may hold (${LIMITS.text} characters)`,
662
+ }),
663
+ S.obj(
664
+ Object.fromEntries(
665
+ Object.entries(BUILD_SECTIONS).map(([k, spec]) => [
666
+ `${k}?`,
667
+ S.any([S.obj({ error: S.text() }, { open: true }), section(spec)], {
668
+ says: `broken build page: its part "${BUILD_TITLES[k]}" is not in the form the page reads, at {path} (the link may be damaged, or made by another version of cad)`,
669
+ }),
670
+ ]),
671
+ ),
672
+ ),
673
+ ],
674
+ { why: 'must be the build page, its parts by name' },
675
+ );
676
+
677
+ // The fields of a link, top to bottom in the order they are checked; FIELD_NAMES are what the page calls them, for a
678
+ // message that says where the trouble is.
679
+ const FIELD_NAMES = {
680
+ rules: 'rules card',
681
+ sheet: 'rules sheet',
682
+ views: 'flat views',
683
+ parts: 'parts list',
684
+ motion: 'motion',
685
+ build: 'build page',
686
+ task: 'task',
687
+ steps: 'step file',
688
+ wires: 'wires',
689
+ fab: 'fab files',
690
+ shapes: 'shapes',
691
+ place: 'placement',
692
+ };
693
+ const META = {
694
+ 'title?': S.text(),
695
+ 'version?': S.text(),
696
+ 'src?': S.text(),
697
+ 'set?': S.text(),
698
+ 'material?': S.text(),
699
+ 'orientation?': S.text(),
700
+ 'sheet?': S.list(S.list(S.text(), { most: 9 }), { most: LIMITS.sheet }),
701
+ 'views?': S.list(
702
+ S.tuple([S.text(), S.text({ max: LIMITS.viewSize })], { why: 'must be a view: a name and a drawing' }),
703
+ {
704
+ most: LIMITS.views,
705
+ },
706
+ ),
707
+ 'fab?': S.list(
708
+ S.obj(
709
+ {
710
+ name: S.text({
711
+ test: (n) =>
712
+ /^[\w@.+-]{1,200}\.zip$/.test(n) ? '' : "must be a zip file's name, letters, digits and . _ - @ +",
713
+ }),
714
+ zip: S.text({
715
+ max: LIMITS.fabSize,
716
+ test: (z) =>
717
+ !/^[A-Za-z0-9+/]*={0,2}$/.test(z)
718
+ ? "must be the zip's bytes, in base64"
719
+ : fabZipOk(z)
720
+ ? ''
721
+ : {
722
+ says: "the link's fab file at {path} is not a board's zip (Gerbers, drill files, parts list and placement): the link may be damaged, or was not made by rulecad",
723
+ },
724
+ }),
725
+ },
726
+ { why: 'must be a fab file: a name and a zip' },
727
+ ),
728
+ { most: LIMITS.fab },
729
+ ),
730
+ 'motion?': motionNode,
731
+ 'task?': taskNode,
732
+ 'steps?': stepsNode,
733
+ 'wires?': wiresNode,
734
+ 'show?': S.one(['built']),
735
+ 'rules?': S.list(S.tuple([S.text(), S.any([S.text(), S.num()]), opt(S.text())]), {
736
+ most: LIMITS.sheet,
737
+ says: RULES_PROBLEM,
738
+ }),
739
+ 'build?': buildNode,
740
+ };
741
+ // A link: the model, its parts, then everything else
742
+ const LINK = S.obj({ ...core, 'parts?': partsNode, ...META }, { why: MODEL_GONE });
743
+ const CORE = S.obj({ ...core, 'parts?': partsNode }, { skip: true });
744
+ // A placed shape: { role?, label?, slot?, q, p, t }, and a place: [shape, a, b, c, d, e, f, g, h, i, j, k, l, name?]
745
+ const SHAPE = S.obj({ 'role?': S.text(), 'label?': S.text(), 'slot?': slotNode, ...core });
746
+ const PLACE_ROW = S.tuple(
747
+ [
748
+ S.int({
749
+ min: 0,
750
+ test: (i, cx) => (i < cx.root.shapes.length ? '' : `must be one of the ${cx.root.shapes.length} shapes`),
751
+ }),
752
+ ...Array.from({ length: 12 }, () => S.num()),
753
+ opt(S.text()),
754
+ ],
755
+ { says: 'broken placement at {path}: each copy must name one of the shapes, then give 12 numbers' },
756
+ );
757
+ // The placed-shapes form, before decode() expands it: its shapes and places in place of q, p, t and parts. Copies are
758
+ // counted before any is made: a few placements of a big shape would otherwise be built in full, then refused.
759
+ const PLACED = S.obj(
760
+ {
761
+ shapes: S.list(SHAPE, { most: LIMITS.shapes, says: 'model too big for a link: more than {most} shapes' }),
762
+ place: S.list(PLACE_ROW, {
763
+ most: LIMITS.places,
764
+ test: (place, cx) => {
765
+ let count = 0;
766
+ for (const [i] of place) count += cx.root.shapes[i].t.length / 3;
767
+ return count > LIMITS.triangles
768
+ ? { why: '', says: `model too big for a link: its copies hold more than ${LIMITS.triangles} triangles` }
769
+ : '';
770
+ },
771
+ }),
772
+ ...META,
773
+ },
774
+ { why: MODEL_GONE },
775
+ );
776
+ /** The names of a link's fields, from the table (the header comment and the Model typedef are held to it). @type {string[]} */
777
+ export const FIELDS = [...new Set([...Object.keys(LINK.fields), ...Object.keys(PLACED.fields)])].map((k) =>
778
+ k.replace(/\?$/, ''),
779
+ );
780
+
781
+ // a path as text: motion.joints[3].dofs
782
+ const pathText = (path) =>
783
+ path
784
+ .map((k, i) =>
785
+ typeof k === 'number'
786
+ ? `[${k}]`
787
+ : /^[A-Za-z_$][\w$]*$/.test(k)
788
+ ? `${i ? '.' : ''}${k}`
789
+ : `[${JSON.stringify(k.length > 40 ? `${k.slice(0, 40)}…` : k)}]`,
790
+ )
791
+ .join('');
792
+ const kindOf = (v) =>
793
+ v === null
794
+ ? 'nothing'
795
+ : Array.isArray(v)
796
+ ? 'a list'
797
+ : typeof v === 'object'
798
+ ? 'a group of fields'
799
+ : typeof v === 'string'
800
+ ? 'text'
801
+ : typeof v === 'number'
802
+ ? 'a number'
803
+ : typeof v;
804
+ const plainKind = (v) => v === null || ['boolean', 'number', 'string'].includes(typeof v);
805
+
806
+ // How each kind of node reads a value: null when it fits, else what's wrong (from fault(why, extra)).
807
+ const KINDS = {
808
+ text: (v, node, fault) =>
809
+ typeof v !== 'string'
810
+ ? fault(`must be text, not ${kindOf(v)}`)
811
+ : v.length <= (node.max ?? LIMITS.text)
812
+ ? null
813
+ : node.max
814
+ ? fault(`is ${v.length} characters long, more than a link may hold (${node.max})`)
815
+ : fault('', { long: v.length }),
816
+ num: (v, node, fault) =>
817
+ typeof v !== 'number' || !Number.isFinite(v)
818
+ ? fault(`must be a number, not ${kindOf(v)}`)
819
+ : node.above != null && !(v > node.above)
820
+ ? fault(`must be more than ${node.above}`)
821
+ : null,
822
+ int: (v, { min, max }, fault) =>
823
+ Number.isInteger(v) && !(min != null && v < min) && !(max != null && v > max)
824
+ ? null
825
+ : fault(
826
+ min != null && max != null
827
+ ? `must be a whole number from ${min} to ${max}`
828
+ : min != null
829
+ ? `must be a whole number, ${min} or more`
830
+ : 'must be a whole number',
831
+ ),
832
+ one: (v, node, fault) =>
833
+ node.values.includes(v) ? null : fault(`must be ${node.values.map((x) => JSON.stringify(x)).join(' or ')}`),
834
+ list(v, node, fault, path, cx) {
835
+ if (!Array.isArray(v)) return fault(node.why || `must be a list, not ${kindOf(v)}`);
836
+ if (node.length != null && v.length !== node.length)
837
+ return fault(node.why || `must hold ${node.length} entries, not ${v.length}`);
838
+ if (node.least != null && v.length < node.least) return fault(`must hold ${node.least} entries or more`);
839
+ if (node.most != null && v.length > node.most)
840
+ return fault(`holds ${v.length} entries, more than a link may hold (${node.most})`, {
841
+ says: node.says?.replace('{most}', node.most),
842
+ });
843
+ return node.of ? walkAll(v, v.keys(), () => node.of, path, cx) : null;
844
+ },
845
+ tuple(v, node, fault, path, cx) {
846
+ const least = node.items.findLastIndex((x) => !x.optional) + 1;
847
+ if (!Array.isArray(v) || v.length < least) return fault(node.why || `must be a list of ${least} or more`);
848
+ const bad = walkAll(v, node.items.keys(), (i) => node.items[i], path, cx);
849
+ if (bad || v.length <= node.items.length) return bad;
850
+ if (node.rest) return walkAll(v, range(node.items.length, v.length), () => node.rest, path, cx);
851
+ unknownAt(cx, [...path, node.items.length], v, node.items.length);
852
+ return null;
853
+ },
854
+ obj(v, node, fault, path, cx) {
855
+ if (!v || typeof v !== 'object' || Array.isArray(v))
856
+ return fault(node.why || `must be a group of fields, not ${kindOf(v)}`);
857
+ cx.up.push(v);
858
+ const bad = objFields(v, node, fault, path, cx) || objOthers(v, node, fault, path, cx);
859
+ cx.up.pop();
860
+ return bad;
861
+ },
862
+ map(v, node, fault, path, cx) {
863
+ if (!v || typeof v !== 'object' || Array.isArray(v)) return fault(`must be a group of fields, not ${kindOf(v)}`);
864
+ cx.up.push(v);
865
+ let bad = null;
866
+ for (const k of Object.keys(v)) {
867
+ path.push(k);
868
+ bad = k.length > LIMITS.text ? fault('', { long: k.length }) : readNode(v[k], node.of, path, cx);
869
+ path.pop();
870
+ if (bad) break;
871
+ }
872
+ cx.up.pop();
873
+ return bad;
874
+ },
875
+ any(v, node, fault, path, cx) {
876
+ const seen = cx.unknown.length;
877
+ let bad = null;
878
+ for (const n of node.nodes) {
879
+ bad = readNode(v, n, path, cx);
880
+ if (!bad) return null;
881
+ cx.unknown.length = seen; // (what a node that didn't fit noted is not the link's)
882
+ }
883
+ // the last kind tried says what's wrong, unless the node has words of its own
884
+ return node.why ? fault(node.why) : bad;
885
+ },
886
+ all(v, node, fault, path, cx) {
887
+ for (const n of node.nodes) {
888
+ const bad = readNode(v, n, path, cx);
889
+ if (bad) return bad;
890
+ }
891
+ return null;
892
+ },
893
+ data: (v, node, fault, path) => dataFault(v, path),
894
+ };
895
+ // An object's own fields, in the table's order: the first fault
896
+ function objFields(v, node, fault, path, cx) {
897
+ for (const [name, field] of Object.entries(node.fields)) {
898
+ const optional = name.endsWith('?'),
899
+ k = optional ? name.slice(0, -1) : name;
900
+ path.push(k);
901
+ const bad = v[k] == null ? (optional ? null : fault('is missing')) : readNode(v[k], field, path, cx);
902
+ path.pop();
903
+ if (bad) return bad;
904
+ }
905
+ return null;
906
+ }
907
+ // Whether k is one of fields' names: as the link spells it, so 'title' is, and 'title?' (the table's own spelling of an
908
+ // optional field) is not: a link's 'title?' is a field the table doesn't have, unknown like any other
909
+ const known = (fields, k) => !k.endsWith('?') && (Object.hasOwn(fields, k) || Object.hasOwn(fields, `${k}?`));
910
+ // At most this many unknown fields are each named in a warning; one more says how many others there are. (A crafted
911
+ // link's long list of rows, each with an extra entry, would otherwise make a warning for every row: millions of them,
912
+ // from a link of a few kilobytes.)
913
+ const WARNED = 20;
914
+ // Notes holder[key] as unknown, at path: every one is left out, the first WARNED + 1 keep their path for the warnings
915
+ function unknownAt(cx, path, holder, key) {
916
+ cx.unknown.push([cx.unknown.length <= WARNED ? [...path] : null, holder, key]);
917
+ }
918
+ // An object's other fields: data in an open one, else noted as unknown (unless skip: another walk reads them)
919
+ function objOthers(v, node, fault, path, cx) {
920
+ if (node.skip) return null;
921
+ for (const k of Object.keys(v)) {
922
+ if (known(node.fields, k) || v[k] === undefined) continue;
923
+ path.push(k);
924
+ const bad = k.length > LIMITS.text ? fault('', { long: k.length }) : node.open ? dataFault(v[k], path) : null;
925
+ if (!bad && !node.open) unknownAt(cx, path, v, k);
926
+ path.pop();
927
+ if (bad) return bad;
928
+ }
929
+ return null;
930
+ }
931
+
932
+ // Reads v against node. Returns null when it fits, else what's wrong: { path, why, says?, long? } (long: a piece of
933
+ // text's length, over LIMITS.text). path is the walk's own, pushed and popped, so a long list isn't paid for in copies;
934
+ // a fault copies it. cx: { root (the link), places (how many parts it has), up (the objects and lists above), unknown
935
+ // (where to note what the table doesn't have: [path, holder, key]) }.
936
+ function readNode(v, node, path, cx) {
937
+ const fault = (why, extra) => ({ path: [...path], why, ...extra });
938
+ let bad = KINDS[node.is](v, node, fault, path, cx);
939
+ if (!bad && node.test) {
940
+ const r = node.test(v, cx);
941
+ if (r)
942
+ bad = typeof r === 'string' ? fault(r) : { path: [...path, ...(r.at || [])], why: r.why ?? '', says: r.says };
943
+ }
944
+ if (bad && node.says && bad.says == null && !bad.long) bad.says = node.says;
945
+ return bad;
946
+ }
947
+ const range = (from, to) => Array.from({ length: to - from }, (_, i) => from + i);
948
+ // Each of v's entries (by index) against its node, with the list on cx.up; the first fault, or null
949
+ function walkAll(v, keys, nodeOf, path, cx) {
950
+ cx.up.push(v);
951
+ let bad = null;
952
+ for (const i of keys) {
953
+ const node = nodeOf(i);
954
+ if (v[i] == null && node.optional) continue;
955
+ path.push(i);
956
+ bad = readNode(v[i], node, path, cx);
957
+ path.pop();
958
+ if (bad) break;
959
+ }
960
+ cx.up.pop();
961
+ return bad;
962
+ }
963
+ // Only data: text in bounds, finite numbers, booleans, null, and lists or plain objects of those, at most 8 deep and
964
+ // not too many: read without recursion, so a deeply nested link can't overflow the stack
965
+ function dataFault(v, path) {
966
+ const stack = [[v, [], 0]];
967
+ while (stack.length) {
968
+ const [x, at, depth] = stack.pop(),
969
+ fault = (why, extra) => ({ path: [...path, ...at], why, ...extra });
970
+ if (typeof x === 'string') {
971
+ if (x.length > LIMITS.text) return fault('', { long: x.length });
972
+ } else if (x === null || typeof x === 'boolean' || (typeof x === 'number' && Number.isFinite(x))) continue;
973
+ else if (typeof x !== 'object') return fault(`must be data: text, numbers, true or false, not ${kindOf(x)}`);
974
+ else if (depth > 8) return fault('holds lists and groups more than 8 deep');
975
+ else if (Array.isArray(x) ? x.length > LIMITS.places * 4 : Object.keys(x).length > 200)
976
+ return fault('holds more entries than a link may hold');
977
+ else
978
+ for (const [k, y] of Object.entries(x)) {
979
+ if (k.length > LIMITS.text) return fault('', { long: k.length });
980
+ if (!plainKind(y) || typeof y === 'string')
981
+ stack.push([y, [...at, Array.isArray(x) ? Number(k) : k], depth + 1]);
982
+ else if (typeof y === 'number' && !Number.isFinite(y))
983
+ return { path: [...path, ...at, Array.isArray(x) ? Number(k) : k], why: 'must be a finite number' };
984
+ }
985
+ }
986
+ return null;
987
+ }
988
+
989
+ // A fault in words, for a person opening the link
990
+ function message(bad) {
991
+ const where = pathText(bad.path),
992
+ top = bad.path[0],
993
+ name = FIELD_NAMES[top] || top;
994
+ if (bad.long)
995
+ return `a piece of text in the link's ${name} is ${bad.long} characters long, more than a link may hold (${LIMITS.text}), at ${where}: the link may be damaged, or was not made by rulecad`;
996
+ if (bad.says) return bad.says.replace('{path}', where).replace('{why}', bad.why);
997
+ if (!bad.path.length) return bad.why;
998
+ if (top === 'p' || top === 't' || top === 'q' || bad.why === MODEL_GONE) return `${MODEL_GONE}: ${where} ${bad.why}`;
999
+ return `broken ${name}: ${where} ${bad.why}`;
1000
+ }
1001
+
1002
+ // A link read against the table: { findings, unknown, model }. findings: each field's first fault (level 'fail'), then a
1003
+ // warning for each thing the table doesn't have; unknown: where those are ([path, holder, key]); model: the link's own
1004
+ // model, or for the placed-shapes form what spread() makes of it (its shapes and places checked first: everything
1005
+ // after reads them). A fault in the model itself (q, p, t, parts, or shapes and places) is the only finding: the rest
1006
+ // can't be read without it.
1007
+ function inspect(m) {
1008
+ const cx = { root: m, places: 1, up: [], unknown: [] },
1009
+ placed = Array.isArray(m?.shapes),
1010
+ node = placed ? PLACED : LINK,
1011
+ first = placed ? ['shapes', 'place'] : ['q', 'p', 't', 'parts'],
1012
+ gone = (bad) => ({ findings: [finding(bad)], unknown: [], model: m });
1013
+ if (!m || typeof m !== 'object' || Array.isArray(m)) return gone({ path: [], why: MODEL_GONE });
1014
+ let bad = readNode(m, S.obj(pickFields(node.fields, first), { skip: true }), [], cx);
1015
+ if (bad) return gone(bad);
1016
+ const model = placed ? spread(m) : m;
1017
+ // (what spread() made is held to the link's limits too: its corners, its parts)
1018
+ if (placed && (bad = readNode(model, CORE, [], { ...cx, root: model, unknown: [] }))) return gone(bad);
1019
+ cx.places = placed ? m.place.length : (m.parts?.length ?? 1);
1020
+ const fails = [];
1021
+ cx.up.push(m);
1022
+ for (const [name, field] of Object.entries(node.fields)) {
1023
+ const k = name.replace(/\?$/, '');
1024
+ if (first.includes(k) || m[k] == null) continue;
1025
+ if ((bad = readNode(m[k], field, [k], cx))) fails.push(finding(bad));
1026
+ }
1027
+ cx.up.pop();
1028
+ for (const k of Object.keys(m))
1029
+ if (!known(node.fields, k) && m[k] !== undefined) unknownAt(cx, [k.length > 40 ? `${k.slice(0, 40)}…` : k], m, k);
1030
+ const more = cx.unknown.length - WARNED,
1031
+ warnings = cx.unknown.slice(0, more > 1 ? WARNED : WARNED + 1).map(([path]) => ({
1032
+ level: 'warn',
1033
+ text: `this link holds a field this page doesn't read, at ${pathText(path)}: it is left out (the link may have been made by a newer version of cad)`,
1034
+ code: 'link.data',
1035
+ values: { path: pathText(path) },
1036
+ }));
1037
+ if (more > 1)
1038
+ warnings.push({
1039
+ level: 'warn',
1040
+ text: `this link holds ${more} more fields this page doesn't read, the first at ${pathText(cx.unknown[WARNED][0])}: they are left out (the link may have been made by a newer version of cad)`,
1041
+ code: 'link.data',
1042
+ values: { path: pathText(cx.unknown[WARNED][0]), more },
1043
+ });
1044
+ return { findings: [...fails, ...warnings], unknown: cx.unknown, model };
1045
+ }
1046
+ const pickFields = (fields, names) =>
1047
+ Object.fromEntries(Object.entries(fields).filter(([k]) => names.includes(k.replace(/\?$/, ''))));
1048
+ const finding = (bad) => ({
1049
+ level: 'fail',
1050
+ text: message(bad),
1051
+ code: 'link.data',
1052
+ values: { path: pathText(bad.path) },
1053
+ });
1054
+
1055
+ /**
1056
+ * What's wrong with a model's data, as findings (the kit's one result shape): the first fault in each field
1057
+ * ({ level: 'fail', text, code: 'link.data', values: { path } }, path naming the field, such as
1058
+ * 'motion.joints[3].dofs'), then a warning for each field a link doesn't have (level 'warn': decode() leaves those out,
1059
+ * encode() refuses them). Empty when it's sound. Takes a model or its placed-shapes form.
1060
+ * @param {any} m @returns {{ level: 'fail' | 'warn', text: string, code: string, values: { path: string } }[]}
1061
+ */
1062
+ export function check(m) {
1063
+ return inspect(m).findings;
1064
+ }
217
1065
 
218
1066
  /**
219
1067
  * A step file (rulecad.steps/1, from cad plot) as a link or a page carries it: what playback needs, in whole numbers.
@@ -221,49 +1069,110 @@ const wiresOk = (w) => Array.isArray(w) && w.every((x) => Array.isArray(x) && te
221
1069
  * @param {object} steps @param {{ maxBlocks?: number, maxPoints?: number }} [options] @returns {object} @throws an Error naming what's wrong
222
1070
  */
223
1071
  export function compactSteps(steps, { maxBlocks = 4000, maxPoints = 8000 } = {}) {
224
- if (!steps || steps.format !== 'rulecad.steps/1' || !Array.isArray(steps.blocks) || !Array.isArray(steps.axes)) throw new Error('this is not a step file (format rulecad.steps/1, from cad plot)');
225
- const names = steps.axes.map((a) => a.name), spu = steps.axes.map((a) => a.stepsPerUnit), n = names.length;
226
- if (!names.every((x) => typeof x === 'string') || !spu.every((x) => x > 0) || !Array.isArray(steps.start) || steps.start.length !== n) throw new Error('this step file has no axes this page can read');
227
- const row = (b) => (b.type === 'pen' ? [b.state === 'down' ? 3 : 2, Math.round(b.dwell * 1000)] : [b.kind === 'draw' ? 1 : 0, Math.round(b.time * 1000), b.stroke ?? -1, ...b.steps.map(Math.round)]);
1072
+ if (!steps || steps.format !== 'rulecad.steps/1' || !Array.isArray(steps.blocks) || !Array.isArray(steps.axes))
1073
+ throw new Error('this is not a step file (format rulecad.steps/1, from cad plot)');
1074
+ const names = steps.axes.map((a) => a.name),
1075
+ spu = steps.axes.map((a) => a.stepsPerUnit),
1076
+ n = names.length;
1077
+ if (
1078
+ !names.every((x) => typeof x === 'string') ||
1079
+ !spu.every((x) => x > 0) ||
1080
+ !Array.isArray(steps.start) ||
1081
+ steps.start.length !== n
1082
+ )
1083
+ throw new Error('this step file has no axes this page can read');
1084
+ const row = (b) =>
1085
+ b.type === 'pen'
1086
+ ? [b.state === 'down' ? 3 : 2, Math.round(b.dwell * 1000)]
1087
+ : [b.kind === 'draw' ? 1 : 0, Math.round(b.time * 1000), b.stroke ?? -1, ...b.steps.map(Math.round)];
228
1088
  let b = steps.blocks.map(row);
229
- while (b.length > maxBlocks) { // neighbouring moves of one kind on one stroke merged, two at a time, until it's few enough
1089
+ while (b.length > maxBlocks) {
1090
+ // neighbouring moves of one kind on one stroke merged, two at a time, until it's few enough
230
1091
  const out = [];
231
1092
  for (let i = 0; i < b.length; i++) {
232
- const x = b[i], y = b[i + 1];
233
- if (y && x[0] < 2 && y[0] === x[0] && y[2] === x[2]) { out.push([x[0], x[1] + y[1], x[2], ...x.slice(3).map((s, k) => s + y[3 + k])]); i++; } else out.push(x);
1093
+ const x = b[i],
1094
+ y = b[i + 1];
1095
+ if (y && x[0] < 2 && y[0] === x[0] && y[2] === x[2]) {
1096
+ out.push([x[0], x[1] + y[1], x[2], ...x.slice(3).map((s, k) => s + y[3 + k])]);
1097
+ i++;
1098
+ } else out.push(x);
234
1099
  }
235
1100
  if (out.length === b.length) break; // only pen changes left
236
1101
  b = out;
237
1102
  }
238
1103
  const drawn = (steps.drawn || []).map((d) => [d.stroke ?? -1, d.points, d.error]);
239
- let count = drawn.reduce((t, d) => t + d[1].length, 0), keep = 1;
1104
+ let count = drawn.reduce((t, d) => t + d[1].length, 0),
1105
+ keep = 1;
240
1106
  while (count / keep > maxPoints) keep++;
241
- return { ...(steps.drawing ? { name: String(steps.drawing).slice(0, LIMITS.text) } : {}), ...(steps.machine ? { machine: String(steps.machine).slice(0, LIMITS.text) } : {}), names, spu, start: steps.start,
242
- b, drawn: drawn.map(([stroke, points, error]) => { const at = points.map((_, i) => i).filter((i) => i === 0 || i === points.length - 1 || i % keep === 0); return [stroke, at.flatMap((i) => points[i].map((v) => Math.round(v * 100))), error ? at.map((i) => Math.round(error[i] * 1000)) : null]; }) };
1107
+ return {
1108
+ ...(steps.drawing ? { name: String(steps.drawing).slice(0, LIMITS.text) } : {}),
1109
+ ...(steps.machine ? { machine: String(steps.machine).slice(0, LIMITS.text) } : {}),
1110
+ names,
1111
+ spu,
1112
+ start: steps.start,
1113
+ b,
1114
+ drawn: drawn.map(([stroke, points, error]) => {
1115
+ const at = points.map((_, i) => i).filter((i) => i === 0 || i === points.length - 1 || i % keep === 0);
1116
+ return [
1117
+ stroke,
1118
+ at.flatMap((i) => points[i].map((v) => Math.round(v * 100))),
1119
+ error ? at.map((i) => Math.round(error[i] * 1000)) : null,
1120
+ ];
1121
+ }),
1122
+ };
243
1123
  }
244
1124
 
245
- // Placed shapes -> one model ({ q, p, t, parts }), each copy its own part.
1125
+ // Placed shapes -> one model ({ q, p, t, parts }), each copy its own part. Checked as decode() checks it.
1126
+ /** @param {any} m the placed-shapes form, { shapes, place, … } @returns {Model} @throws an Error saying what is wrong */
246
1127
  export function expand(m) {
1128
+ if (!Array.isArray(m?.shapes)) throw new Error(`${MODEL_GONE}: shapes must be a list`);
1129
+ const bad = readNode(m, S.obj(pickFields(PLACED.fields, ['shapes', 'place']), { skip: true }), [], {
1130
+ root: m,
1131
+ places: 1,
1132
+ up: [],
1133
+ unknown: [],
1134
+ });
1135
+ if (bad) throw new Error(message(bad));
1136
+ return spread(m);
1137
+ }
1138
+ // (the copies made, once the shapes and places are known to be sound; SPREAD: the fields it makes)
1139
+ const SPREAD = ['q', 'p', 't', 'parts'];
1140
+ function spread(m) {
247
1141
  const { shapes, place, ...meta } = m;
248
- if (!Array.isArray(place) || shapes.length > LIMITS.shapes || place.length > LIMITS.places) throw new Error('model too big for a link');
249
- for (const sh of shapes) { const e = problems(sh); if (e.length) throw new Error(e[0]); }
250
- // (counted before any copy is made: a few placements of a big shape would otherwise be built in full, then refused)
251
- let count = 0;
252
- for (const [i] of place) { count += (shapes[i]?.t.length || 0) / 3; if (count > LIMITS.triangles) throw new Error('model too big for a link'); }
253
1142
  const list = place.map(([i, ...rest], n) => {
254
- const sh = shapes[i], t = rest.slice(0, 12);
255
- if (!sh || t.length !== 12 || t.some((x) => !Number.isFinite(x))) throw new Error('broken placement');
256
- const at = ([x, y, z]) => [t[0] * x + t[1] * y + t[2] * z + t[3], t[4] * x + t[5] * y + t[6] * z + t[7], t[8] * x + t[9] * y + t[10] * z + t[11]];
257
- return { name: rest[12] || `${sh.label || 'shape'} ${n + 1}`, role: sh.role || 'part', label: sh.label || 'shape', slot: sh.slot, triangles: triangles(sh).map((tri) => tri.map(at)) };
1143
+ const sh = shapes[i],
1144
+ t = rest.slice(0, 12);
1145
+ const at = ([x, y, z]) => [
1146
+ t[0] * x + t[1] * y + t[2] * z + t[3],
1147
+ t[4] * x + t[5] * y + t[6] * z + t[7],
1148
+ t[8] * x + t[9] * y + t[10] * z + t[11],
1149
+ ];
1150
+ return {
1151
+ name: rest[12] || `${sh.label || 'shape'} ${n + 1}`,
1152
+ role: sh.role || 'part',
1153
+ label: sh.label || 'shape',
1154
+ slot: sh.slot,
1155
+ triangles: triangles(sh).map((tri) => tri.map(at)),
1156
+ };
258
1157
  });
259
1158
  return { ...meta, ...fromParts(list) };
260
1159
  }
261
1160
 
262
1161
  // fromShapes(parts) for tools: [{ shape, role, label, triangles (local), matrix: 12 numbers, name }] -> { shapes, place }
263
1162
  export function fromShapes(list) {
264
- const index = new Map(), shapes = [], place = [];
1163
+ const index = new Map(),
1164
+ shapes = [],
1165
+ place = [];
265
1166
  for (const x of list) {
266
- if (!index.has(x.shape)) { index.set(x.shape, shapes.length); shapes.push({ role: x.role, label: x.label, ...(x.slot > 1 ? { slot: x.slot } : {}), ...fromTriangles(x.triangles) }); }
1167
+ if (!index.has(x.shape)) {
1168
+ index.set(x.shape, shapes.length);
1169
+ shapes.push({
1170
+ role: x.role,
1171
+ label: x.label,
1172
+ ...(x.slot > 1 ? { slot: Number(x.slot) } : {}),
1173
+ ...fromTriangles(x.triangles),
1174
+ });
1175
+ }
267
1176
  place.push([index.get(x.shape), ...x.matrix, x.name]);
268
1177
  }
269
1178
  return { shapes, place };
@@ -272,21 +1181,23 @@ export function fromShapes(list) {
272
1181
  // Triangles in mm: [[[x,y,z] ×3], …], all of them or one part's ([name, role, label, first, count]).
273
1182
  /** The model's triangles, or one part's. @param {Model} m @param {any[]} [part] @returns {Triangle[]} */
274
1183
  export function triangles(m, part) {
275
- const v = (i) => [m.p[3 * i] * m.q, m.p[3 * i + 1] * m.q, m.p[3 * i + 2] * m.q], out = [];
1184
+ const v = (i) => [m.p[3 * i] * m.q, m.p[3 * i + 1] * m.q, m.p[3 * i + 2] * m.q],
1185
+ out = [];
276
1186
  const [from, to] = part ? [part[3] * 3, (part[3] + part[4]) * 3] : [0, m.t.length];
277
1187
  for (let i = from; i < to; i += 3) out.push([v(m.t[i]), v(m.t[i + 1]), v(m.t[i + 2])]);
278
1188
  return out;
279
1189
  }
280
1190
 
281
1191
  // The model's parts, always at least one: [[name, role, label, first, count]]
282
- export const partsOf = (m) => (m.parts?.length ? m.parts.filter((x) => x[1] !== 'pose') : [['body', 'part', m.title || 'model', 0, m.t.length / 3]]);
1192
+ export const partsOf = (m) =>
1193
+ m.parts?.length ? m.parts.filter((x) => x[1] !== 'pose') : [['body', 'part', m.title || 'model', 0, m.t.length / 3]];
283
1194
  // The shapes parts take only in poses (role "pose"), with their places: [{ k, part }]
284
1195
  /** @param {Model} m @returns {{ k: number, part: any[] }[]} */
285
1196
  export const posesOf = (m) => (m.parts || []).map((part, k) => ({ k, part })).filter((x) => x.part[1] === 'pose');
286
1197
 
287
1198
  // ---------- motion ----------
288
1199
  // Joints between items, so a page (or a tool) can move them: an assembly's hinges, rails and ball joints.
289
- // motion: { items: [[name, …12?]], joints: [joint], poses: { name: { joint: value } }, pose?, part: [item per place], sequence?: { period, names: [joint], q: [values per frame] } (a gait, played),
1200
+ // motion: { items: [[name, …12?]], joints: [joint], poses: { name: { joint: value } }, pose?, part: [item per place], sequence?: { period, names: [joint], q: [values per frame], kind? } (a gait, played),
290
1201
  // allow?: [[place, place]], swap?: { pose: [[place, place]] } }
291
1202
  // An item with 12 numbers sits there (a 3 × 4 transform by rows, as in place); one without is placed by the joint
292
1203
  // whose child it is. part[n] is the item place n moves with (-1: it never moves); allow pairs may overlap (press fits).
@@ -298,25 +1209,50 @@ export const posesOf = (m) => (m.parts || []).map((part, k) => ({ k, part })).fi
298
1209
  // fixed []; revolute [angle]; prismatic [distance]; cylindrical [angle, distance]; ball [x, y, z] (turned about x,
299
1210
  // then y, then z; cone: how far z may tip, in degrees); path [distance along path, a polyline in the parent's anchor
300
1211
  // frame, the child's z along it]
301
- export const DOFS = { fixed: [], revolute: ['angle'], prismatic: ['distance'], cylindrical: ['angle', 'distance'], ball: ['angle', 'angle', 'angle'], path: ['distance'] };
1212
+ export const DOFS = {
1213
+ fixed: [],
1214
+ revolute: ['angle'],
1215
+ prismatic: ['distance'],
1216
+ cylindrical: ['angle', 'distance'],
1217
+ ball: ['angle', 'angle', 'angle'],
1218
+ path: ['distance'],
1219
+ };
302
1220
  const I3 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0];
303
1221
  // 3 × 4 transforms by rows: m · n, the inverse of a rigid one, and the turns and moves they're made from
304
1222
  /** m · n, two 3 × 4 transforms by rows @param {number[]} m @param {number[]} n @returns {number[]} */
305
1223
  export function mul(m, n) {
306
1224
  const o = [];
307
- for (let r = 0; r < 3; r++) for (let c = 0; c < 4; c++) o.push(m[r * 4] * n[c] + m[r * 4 + 1] * n[4 + c] + m[r * 4 + 2] * n[8 + c] + (c === 3 ? m[r * 4 + 3] : 0));
1225
+ for (let r = 0; r < 3; r++)
1226
+ for (let c = 0; c < 4; c++)
1227
+ o.push(m[r * 4] * n[c] + m[r * 4 + 1] * n[4 + c] + m[r * 4 + 2] * n[8 + c] + (c === 3 ? m[r * 4 + 3] : 0));
308
1228
  return o;
309
1229
  }
310
1230
  /** The inverse of a rigid 3 × 4 transform @param {number[]} m @returns {number[]} */
311
1231
  export function inv(m) {
312
- const t = [m[3], m[7], m[11]], o = [];
313
- for (let r = 0; r < 3; r++) { const row = [m[r], m[4 + r], m[8 + r]]; o.push(...row, -(row[0] * t[0] + row[1] * t[1] + row[2] * t[2])); }
1232
+ const t = [m[3], m[7], m[11]],
1233
+ o = [];
1234
+ for (let r = 0; r < 3; r++) {
1235
+ const row = [m[r], m[4 + r], m[8 + r]];
1236
+ o.push(...row, -(row[0] * t[0] + row[1] * t[1] + row[2] * t[2]));
1237
+ }
314
1238
  return o;
315
1239
  }
316
1240
  const D = Math.PI / 180;
317
- const rx = (a) => { const c = Math.cos(a * D), s = Math.sin(a * D); return [1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0]; };
318
- const ry = (a) => { const c = Math.cos(a * D), s = Math.sin(a * D); return [c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0]; };
319
- const rz = (a) => { const c = Math.cos(a * D), s = Math.sin(a * D); return [c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0]; };
1241
+ const rx = (a) => {
1242
+ const c = Math.cos(a * D),
1243
+ s = Math.sin(a * D);
1244
+ return [1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0];
1245
+ };
1246
+ const ry = (a) => {
1247
+ const c = Math.cos(a * D),
1248
+ s = Math.sin(a * D);
1249
+ return [c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0];
1250
+ };
1251
+ const rz = (a) => {
1252
+ const c = Math.cos(a * D),
1253
+ s = Math.sin(a * D);
1254
+ return [c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0];
1255
+ };
320
1256
  const tz = (d) => [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, d];
321
1257
  // Turned about x, then y, then z (degrees), as an assembly's rotate
322
1258
  /** @type {(degrees: number[]) => number[]} */
@@ -324,15 +1260,24 @@ export const turn = ([x, y, z]) => mul(rz(z), mul(ry(y), rx(x)));
324
1260
  // A frame from where it is, its z axis and the way its x axis points (default: along x, or y if z is along x)
325
1261
  /** @param {number[]} at @param {number[]} [axis] @param {number[]} [ref] @returns {number[]} */
326
1262
  export function frame(at, axis = [0, 0, 1], ref) {
327
- const unit = (v) => { const l = Math.hypot(...v); if (!(l > 1e-12)) throw new Error('an anchor axis has no length'); return v.map((x) => x / l); };
328
- const z = unit(axis), dot = (u, v) => u[0] * v[0] + u[1] * v[1] + u[2] * v[2], cross = (u, v) => [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
1263
+ const unit = (v) => {
1264
+ const l = Math.hypot(...v);
1265
+ if (!(l > 1e-12)) throw new Error('an anchor axis has no length');
1266
+ return v.map((x) => x / l);
1267
+ };
1268
+ const z = unit(axis),
1269
+ dot = (u, v) => u[0] * v[0] + u[1] * v[1] + u[2] * v[2],
1270
+ cross = (u, v) => [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
329
1271
  let r = ref || (Math.abs(z[0]) > 0.9 ? [0, 1, 0] : [1, 0, 0]);
330
- const x = unit(r.map((v, k) => v - dot(r, z) * z[k])), y = cross(z, x);
1272
+ const x = unit(r.map((v, k) => v - dot(r, z) * z[k])),
1273
+ y = cross(z, x);
331
1274
  return [x[0], y[0], z[0], at[0], x[1], y[1], z[1], at[1], x[2], y[2], z[2], at[2]];
332
1275
  }
333
1276
  // The turn that takes z to v, the shortest way
334
1277
  function zTo(v) {
335
- const l = Math.hypot(...v), [x, y, z] = v.map((c) => c / l), c = z;
1278
+ const l = Math.hypot(...v),
1279
+ [x, y, z] = v.map((c) => c / l),
1280
+ c = z;
336
1281
  if (c < -1 + 1e-9) return rx(180);
337
1282
  const k = 1 / (1 + c); // Rodrigues, about z × v = (-y, x, 0)
338
1283
  return [1 - x * x * k, -x * y * k, x, 0, -x * y * k, 1 - y * y * k, y, 0, -x, -y, c, 0];
@@ -341,60 +1286,94 @@ function zTo(v) {
341
1286
  function along(points, s) {
342
1287
  let left = Math.max(0, s);
343
1288
  for (let i = 1; i < points.length; i++) {
344
- const a = points[i - 1], b = points[i], d = [b[0] - a[0], b[1] - a[1], b[2] - a[2]], l = Math.hypot(...d);
345
- if (left <= l || i === points.length - 1) { const f = l ? Math.min(left, l) / l : 0, m = zTo(l ? d : [0, 0, 1]); m[3] = a[0] + d[0] * f; m[7] = a[1] + d[1] * f; m[11] = a[2] + d[2] * f; return m; }
1289
+ const a = points[i - 1],
1290
+ b = points[i],
1291
+ d = [b[0] - a[0], b[1] - a[1], b[2] - a[2]],
1292
+ l = Math.hypot(...d);
1293
+ if (left <= l || i === points.length - 1) {
1294
+ const f = l ? Math.min(left, l) / l : 0,
1295
+ m = zTo(l ? d : [0, 0, 1]);
1296
+ m[3] = a[0] + d[0] * f;
1297
+ m[7] = a[1] + d[1] * f;
1298
+ m[11] = a[2] + d[2] * f;
1299
+ return m;
1300
+ }
346
1301
  left -= l;
347
1302
  }
348
1303
  return [...I3];
349
1304
  }
350
1305
  /** @type {(points: number[][]) => number} */
351
- export const pathLength = (points) => points.slice(1).reduce((t, b, i) => t + Math.hypot(b[0] - points[i][0], b[1] - points[i][1], b[2] - points[i][2]), 0);
1306
+ export const pathLength = (points) =>
1307
+ points.slice(1).reduce((t, b, i) => t + Math.hypot(b[0] - points[i][0], b[1] - points[i][1], b[2] - points[i][2]), 0);
352
1308
  // What a joint does at its values: the child's anchor, in the parent's anchor frame
353
1309
  /** @param {{ id: string, type: string, path?: number[][] }} j @param {number[]} v @returns {number[]} */
354
1310
  export function jointMatrix(j, v) {
355
1311
  switch (j.type) {
356
- case 'fixed': return [...I3];
357
- case 'revolute': return rz(v[0]);
358
- case 'prismatic': return tz(v[0]);
359
- case 'cylindrical': return mul(tz(v[1]), rz(v[0]));
360
- case 'ball': return turn(v);
361
- case 'path': return along(j.path, v[0]);
362
- default: throw new Error(`joint ${j.id}: no joint type "${j.type}" (${Object.keys(DOFS).join(', ')})`);
1312
+ case 'fixed':
1313
+ return [...I3];
1314
+ case 'revolute':
1315
+ return rz(v[0]);
1316
+ case 'prismatic':
1317
+ return tz(v[0]);
1318
+ case 'cylindrical':
1319
+ return mul(tz(v[1]), rz(v[0]));
1320
+ case 'ball':
1321
+ return turn(v);
1322
+ case 'path':
1323
+ return along(j.path, v[0]);
1324
+ default:
1325
+ throw new Error(`joint ${j.id}: no joint type "${j.type}" (${Object.keys(DOFS).join(', ')})`);
363
1326
  }
364
1327
  }
365
1328
  // Every joint's values: each at its default, then the pose's, then the joints that follow another
366
1329
  // pose: a name in motion.poses, or { joint: value }; values: [number] per joint, by id
367
1330
  /** @param {{ joints: any[], poses?: Record<string, Record<string, number | number[]>>, pose?: string }} motion @param {string | Record<string, number | number[]> | null} [pose] @returns {Record<string, number[]>} */
368
1331
  export function jointValues(motion, pose) {
369
- const set = typeof pose === 'string' ? motion.poses?.[pose] : pose || (motion.pose ? motion.poses?.[motion.pose] : {});
370
- if (typeof pose === 'string' && !set) throw new Error(`no pose "${pose}" (poses: ${Object.keys(motion.poses || {}).join(', ') || 'none'})`);
1332
+ const set =
1333
+ typeof pose === 'string' ? motion.poses?.[pose] : pose || (motion.pose ? motion.poses?.[motion.pose] : {});
1334
+ if (typeof pose === 'string' && !set)
1335
+ throw new Error(`no pose "${pose}" (poses: ${Object.keys(motion.poses || {}).join(', ') || 'none'})`);
371
1336
  const out = {};
372
1337
  for (const j of motion.joints) {
373
1338
  const given = set?.[j.id];
374
1339
  out[j.id] = given == null ? j.dofs.map((d) => d[2]) : [].concat(given).map(Number);
375
- if (out[j.id].length !== j.dofs.length) throw new Error(`joint ${j.id} (${j.type}) takes ${j.dofs.length} value${j.dofs.length === 1 ? '' : 's'}`);
1340
+ if (out[j.id].length !== j.dofs.length)
1341
+ throw new Error(`joint ${j.id} (${j.type}) takes ${j.dofs.length} value${j.dofs.length === 1 ? '' : 's'}`);
376
1342
  }
377
- const done = new Set(), follow = (j, seen = []) => {
378
- if (!j.follow || done.has(j.id)) return out[j.id];
379
- if (seen.includes(j.id)) throw new Error(`joints follow each other round: ${[...seen, j.id].join(' → ')}`);
380
- const [lead, ratio = 1, offset = 0] = j.follow, l = motion.joints.find((x) => x.id === lead);
381
- if (!l) throw new Error(`joint ${j.id} follows "${lead}", which isn't a joint`);
382
- out[j.id] = follow(l, [...seen, j.id]).map((x) => x * ratio + offset).slice(0, j.dofs.length);
383
- done.add(j.id); return out[j.id];
384
- };
1343
+ const done = new Set(),
1344
+ follow = (j, seen = []) => {
1345
+ if (!j.follow || done.has(j.id)) return out[j.id];
1346
+ if (seen.includes(j.id)) throw new Error(`joints follow each other round: ${[...seen, j.id].join(' → ')}`);
1347
+ const [lead, ratio = 1, offset = 0] = j.follow,
1348
+ l = motion.joints.find((x) => x.id === lead);
1349
+ if (!l) throw new Error(`joint ${j.id} follows "${lead}", which isn't a joint`);
1350
+ out[j.id] = follow(l, [...seen, j.id])
1351
+ .map((x) => x * ratio + offset)
1352
+ .slice(0, j.dofs.length);
1353
+ done.add(j.id);
1354
+ return out[j.id];
1355
+ };
385
1356
  for (const j of motion.joints) follow(j);
386
1357
  return out;
387
1358
  }
388
1359
  // Where every item is at these values (jointValues): [12 numbers] per item, a joint's child from its parent
389
1360
  /** @param {{ items: any[][], joints: any[] }} motion @param {Record<string, number[]>} values @returns {number[][]} */
390
1361
  export function placeItems(motion, values) {
391
- const by = new Map(motion.joints.map((j) => [j.child, j])), out = [];
1362
+ const by = new Map(motion.joints.map((j) => [j.child, j])),
1363
+ out = [];
392
1364
  const at = (i, seen = []) => {
393
1365
  if (out[i]) return out[i];
394
1366
  if (i < 0) return I3;
395
- if (seen.includes(i)) throw new Error(`joints go round in a loop: ${[...seen, i].map((k) => motion.items[k][0]).join(' → ')} (join the loop's last pair with a loops check instead)`);
396
- const j = by.get(i), item = motion.items[i];
397
- if (!j) { if (item.length < 13) throw new Error(`item ${item[0]} has no place and no joint`); return (out[i] = item.slice(1, 13)); }
1367
+ if (seen.includes(i))
1368
+ throw new Error(
1369
+ `joints go round in a loop: ${[...seen, i].map((k) => motion.items[k][0]).join(' → ')} (join the loop's last pair with a loops check instead)`,
1370
+ );
1371
+ const j = by.get(i),
1372
+ item = motion.items[i];
1373
+ if (!j) {
1374
+ if (item.length < 13) throw new Error(`item ${item[0]} has no place and no joint`);
1375
+ return (out[i] = item.slice(1, 13));
1376
+ }
398
1377
  return (out[i] = mul(mul(mul(at(j.parent, [...seen, i]), j.a), jointMatrix(j, values[j.id])), inv(j.b)));
399
1378
  };
400
1379
  motion.items.forEach((_, i) => at(i));
@@ -403,16 +1382,34 @@ export function placeItems(motion, values) {
403
1382
 
404
1383
  // ---------- files ----------
405
1384
  // cap@0.6.0.stl; with what was picked, if not everything: staggered-cap-2-4.3mf
406
- export const filename = (m, ext, picked = '') => `${[String(m.src || m.title || 'model').split('/').pop(), m.set && m.set.replace(/,/g, '-'), picked].filter(Boolean).join('-').replace(/[^\w@.=-]+/g, '-')}.${ext}`;
1385
+ export const filename = (m, ext, picked = '') =>
1386
+ `${[
1387
+ String(m.src || m.title || 'model')
1388
+ .split('/')
1389
+ .pop(),
1390
+ m.set && m.set.replace(/,/g, '-'),
1391
+ picked,
1392
+ ]
1393
+ .filter(Boolean)
1394
+ .join('-')
1395
+ .replace(/[^\w@.=-]+/g, '-')}.${ext}`;
407
1396
 
408
1397
  // A fab zip's name as JLCPCB's upload takes it: letters, digits, _ and - before .zip, and none of the words it refuses
409
1398
  // (eval, copy, convert, confirm). So module@0.7.1-fab.zip is saved as module-v0_7_1-fab.zip
410
- export const fabName = (name) => `${String(name).replace(/\.zip$/i, '').replace(/@/g, '-v').replace(/[^A-Za-z0-9_-]+/g, '_')
411
- .replace(/eval|copy|convert|confirm/gi, (w) => `${w[0]}_${w.slice(1)}`).replace(/^[_-]+|[_-]+$/g, '') || 'board-fab'}.zip`;
1399
+ export const fabName = (name) =>
1400
+ `${
1401
+ String(name)
1402
+ .replace(/\.zip$/i, '')
1403
+ .replace(/@/g, '-v')
1404
+ .replace(/[^A-Za-z0-9_-]+/g, '_')
1405
+ .replace(/eval|copy|convert|confirm/gi, (w) => `${w[0]}_${w.slice(1)}`)
1406
+ .replace(/^[_-]+|[_-]+$/g, '') || 'board-fab'
1407
+ }.zip`;
412
1408
 
413
1409
  // Which parts a file holds: all the printed ones (references are only there to check a fit), or the indices picked
414
1410
  // keep: which parts, as a Set of their places in partsOf(m), or a function of each part and its place
415
- const chosen = (m, keep) => partsOf(m).filter((x, i) => (keep ? (typeof keep === 'function' ? keep(x, i) : keep.has(i)) : x[1] !== 'reference'));
1411
+ const chosen = (m, keep) =>
1412
+ partsOf(m).filter((x, i) => (keep ? (typeof keep === 'function' ? keep(x, i) : keep.has(i)) : x[1] !== 'reference'));
416
1413
 
417
1414
  // Binary STL (mm): the parts picked, as one mesh, each part mended (mesh) as for 3MF.
418
1415
  // fromSTL(bytes) -> triangles [[[x, y, z] ×3], …] from an STL file, binary or text (ASCII). Units are as the file has
@@ -422,33 +1419,50 @@ export function fromSTL(bytes) {
422
1419
  const u8 = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
423
1420
  const view = new DataView(u8.buffer, u8.byteOffset, u8.byteLength);
424
1421
  const count = u8.byteLength >= 84 ? view.getUint32(80, true) : -1;
425
- if (count >= 0 && 84 + count * 50 === u8.byteLength) { // binary: a header, a count, then 50 bytes a triangle
426
- if (count > LIMITS.triangles) throw new Error(`${count} triangles: more than a link can hold (${LIMITS.triangles})`);
1422
+ if (count >= 0 && 84 + count * 50 === u8.byteLength) {
1423
+ // binary: a header, a count, then 50 bytes a triangle
1424
+ if (count > LIMITS.triangles)
1425
+ throw new Error(`${count} triangles: more than a link can hold (${LIMITS.triangles})`);
427
1426
  const tris = [];
428
- for (let i = 0, o = 84; i < count; i++, o += 50) tris.push([0, 1, 2].map((v) => [0, 1, 2].map((k) => view.getFloat32(o + 12 + v * 12 + k * 4, true))));
429
- if (tris.some((t) => t.some((p) => p.some((c) => !Number.isFinite(c))))) throw new Error('this STL file is damaged: some of its corners are not numbers');
1427
+ for (let i = 0, o = 84; i < count; i++, o += 50)
1428
+ tris.push([0, 1, 2].map((v) => [0, 1, 2].map((k) => view.getFloat32(o + 12 + v * 12 + k * 4, true))));
1429
+ if (tris.some((t) => t.some((p) => p.some((c) => !Number.isFinite(c)))))
1430
+ throw new Error('this STL file is damaged: some of its corners are not numbers');
430
1431
  return tris;
431
1432
  }
432
1433
  const text = new TextDecoder().decode(u8);
433
1434
  if (!/^\s*solid\b/i.test(text) || !/\bvertex\b/i.test(text)) throw new Error("this isn't an STL file"); // (keywords in any case: some exporters write SOLID, VERTEX)
434
- const v = [...text.matchAll(/vertex\s+(\S+)\s+(\S+)\s+(\S+)/gi)].map((m) => [Number(m[1]), Number(m[2]), Number(m[3])]);
1435
+ const v = [...text.matchAll(/vertex\s+(\S+)\s+(\S+)\s+(\S+)/gi)].map((m) => [
1436
+ Number(m[1]),
1437
+ Number(m[2]),
1438
+ Number(m[3]),
1439
+ ]);
435
1440
  if (v.length % 3 || v.some((p) => p.some((c) => !Number.isFinite(c)))) throw new Error('this STL file is damaged');
436
- if (v.length / 3 > LIMITS.triangles) throw new Error(`${v.length / 3} triangles: more than a link can hold (${LIMITS.triangles})`);
1441
+ if (v.length / 3 > LIMITS.triangles)
1442
+ throw new Error(`${v.length / 3} triangles: more than a link can hold (${LIMITS.triangles})`);
437
1443
  return Array.from({ length: v.length / 3 }, (_, i) => v.slice(i * 3, i * 3 + 3));
438
1444
  }
439
1445
 
440
1446
  // generator: the name the file says made it (rulecad by default)
441
1447
  /** A binary STL of the printed parts (or those kept). @param {Model} m @param {Set<number> | ((part: any[], index: number) => boolean)} [keep] the parts to write: their places in partsOf(m), or a test of each @param {{ generator?: string }} [options] @returns {Uint8Array} */
442
1448
  export function stl(m, keep, { generator = 'rulecad' } = {}) {
443
- const picked = chosen(m, keep), work = { budget: 2e6 + 100 * picked.reduce((n, x) => n + x[4], 0) }; // one mend budget for the file
444
- const tris = picked.flatMap((x) => { const { verts, tris: t } = mesh(triangles(m, x), work); return t.map((ids) => ids.map((i) => verts[i])); }), buf = new ArrayBuffer(84 + 50 * tris.length), dv = new DataView(buf);
1449
+ const picked = chosen(m, keep),
1450
+ work = { budget: 2e6 + 100 * picked.reduce((n, x) => n + x[4], 0) }; // one mend budget for the file
1451
+ const tris = picked.flatMap((x) => {
1452
+ const { verts, tris: t } = mesh(triangles(m, x), work);
1453
+ return t.map((ids) => ids.map((i) => verts[i]));
1454
+ }),
1455
+ buf = new ArrayBuffer(84 + 50 * tris.length),
1456
+ dv = new DataView(buf);
445
1457
  const head = `${generator} ${m.src || m.title || ''}`.slice(0, 80);
446
1458
  for (let i = 0; i < head.length; i++) dv.setUint8(i, head.charCodeAt(i) & 0x7f);
447
1459
  dv.setUint32(80, tris.length, true);
448
1460
  tris.forEach(([a, b, c], i) => {
449
- const u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]], w = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
1461
+ const u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]],
1462
+ w = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
450
1463
  let n = [u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0]];
451
- const l = Math.hypot(...n) || 1; n = n.map((x) => x / l);
1464
+ const l = Math.hypot(...n) || 1;
1465
+ n = n.map((x) => x / l);
452
1466
  [...n, ...a, ...b, ...c].forEach((x, k) => dv.setFloat32(84 + 50 * i + 4 * k, x, true));
453
1467
  });
454
1468
  return new Uint8Array(buf);
@@ -456,7 +1470,10 @@ export function stl(m, keep, { generator = 'rulecad' } = {}) {
456
1470
 
457
1471
  // The printed thing a part belongs to: key-1-1.cap.legend -> key-1-1.cap, case.body -> case; a single object's parts
458
1472
  // (cap, legend, pillar) are all one thing
459
- export const thingOf = (name) => { const bits = String(name).split('.'); return bits.length > 2 ? bits.slice(0, -1).join('.') : bits.length > 1 ? bits[0] : ''; };
1473
+ export const thingOf = (name) => {
1474
+ const bits = String(name).split('.');
1475
+ return bits.length > 2 ? bits.slice(0, -1).join('.') : bits.length > 1 ? bits[0] : '';
1476
+ };
460
1477
 
461
1478
  // 3MF of the parts picked, in Bambu Studio's layout (bambu3mf): one object per printed thing, its parts on their AMS
462
1479
  // slots (parts' sixth field; slot 1 without one).
@@ -466,9 +1483,14 @@ export async function threemf(m, keep, { generator = 'rulecad' } = {}) {
466
1483
  for (const x of chosen(m, keep)) {
467
1484
  const id = thingOf(x[0]);
468
1485
  if (!things.has(id)) things.set(id, []);
469
- things.get(id).push({ name: id ? x[0].split('.').pop() : x[2] || x[0], triangles: triangles(m, x), slot: x[5] || 1 });
1486
+ things
1487
+ .get(id)
1488
+ .push({ name: id ? x[0].split('.').pop() : x[2] || x[0], triangles: triangles(m, x), slot: x[5] || 1 });
470
1489
  }
471
- return bambu3mf([...things].map(([id, parts]) => ({ name: id || m.title || 'model', parts })), { title: m.title, generator });
1490
+ return bambu3mf(
1491
+ [...things].map(([id, parts]) => ({ name: id || m.title || 'model', parts })),
1492
+ { title: m.title, generator },
1493
+ );
472
1494
  }
473
1495
 
474
1496
  // ---------- Bambu Studio's 3MF ----------
@@ -486,6 +1508,13 @@ export async function threemf(m, keep, { generator = 'rulecad' } = {}) {
486
1508
  // await bambu3mf([{ name, parts: [{ name, triangles, slot }] }], { centre }) -> Uint8Array (a zip)
487
1509
  const esc = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
488
1510
  const num = (x) => String(Number(x.toFixed(5)));
1511
+ // A part's extruder as the settings file holds it: its filament slot, a whole number (1 without one), never the text it
1512
+ // came as (a slot of '2"/><metadata …' once wrote markup of a link's choosing into the slicer project)
1513
+ const extruder = (slot) => {
1514
+ const s = Number(slot || 1);
1515
+ if (!slotOk(s)) throw new Error(`${SLOT_PROBLEM} (not ${JSON.stringify(slot).slice(0, 40)})`);
1516
+ return String(s);
1517
+ };
489
1518
 
490
1519
  // triangles -> { verts, tris }: corners within a micron merged, zero-area triangles (three corners in a line) dropped,
491
1520
  // and the part closed. JSCAD's booleans leave T-junctions (a corner of one face in the middle of a neighbour's edge) and
@@ -497,19 +1526,38 @@ const num = (x) => String(Number(x.toFixed(5)));
497
1526
  // spend a budget for each (stl, threemf and bambu3mf pass one); on its own a part gets a budget sized from it.
498
1527
  /** @param {Triangle[]} tris @param {{ budget: number }} [work] @returns {{ verts: number[][], tris: number[][] }} */
499
1528
  export function mesh(tris, work) {
500
- const MERGE = 1e-3, verts = [], index = new Map(), out = [];
1529
+ const MERGE = 1e-3,
1530
+ verts = [],
1531
+ index = new Map(),
1532
+ out = [];
501
1533
  const key = (v) => v.map((c) => Math.round(c / MERGE)).join(',');
502
- const at = (v) => { // the same corner as one already seen within MERGE (it may sit across a rounding boundary)
1534
+ const at = (v) => {
1535
+ // the same corner as one already seen within MERGE (it may sit across a rounding boundary)
503
1536
  const g = v.map((c) => Math.round(c / MERGE));
504
- for (let dx = -1; dx <= 1; dx++) for (let dy = -1; dy <= 1; dy++) for (let dz = -1; dz <= 1; dz++) {
505
- for (const i of index.get(`${g[0] + dx},${g[1] + dy},${g[2] + dz}`) || []) if (Math.hypot(verts[i][0] - v[0], verts[i][1] - v[1], verts[i][2] - v[2]) < MERGE) return i;
506
- }
507
- const k = key(v); if (!index.has(k)) index.set(k, []); index.get(k).push(verts.length); verts.push(v); return verts.length - 1;
1537
+ for (let dx = -1; dx <= 1; dx++)
1538
+ for (let dy = -1; dy <= 1; dy++)
1539
+ for (let dz = -1; dz <= 1; dz++) {
1540
+ for (const i of index.get(`${g[0] + dx},${g[1] + dy},${g[2] + dz}`) || [])
1541
+ if (Math.hypot(verts[i][0] - v[0], verts[i][1] - v[1], verts[i][2] - v[2]) < MERGE) return i;
1542
+ }
1543
+ const k = key(v);
1544
+ if (!index.has(k)) index.set(k, []);
1545
+ index.get(k).push(verts.length);
1546
+ verts.push(v);
1547
+ return verts.length - 1;
508
1548
  };
509
- const sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]], dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
1549
+ const sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]],
1550
+ dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
510
1551
  const cross = (u, w) => [u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0]];
511
- const area2 = (ids) => { const [a, b, c] = ids.map((i) => verts[i]); return Math.hypot(...cross(sub(b, a), sub(c, a))); };
512
- for (const t of tris) for (let i = 1; i < t.length - 1; i++) { const ids = [at(t[0]), at(t[i]), at(t[i + 1])]; if (new Set(ids).size === 3 && area2(ids) > 1e-9) out.push(ids); }
1552
+ const area2 = (ids) => {
1553
+ const [a, b, c] = ids.map((i) => verts[i]);
1554
+ return Math.hypot(...cross(sub(b, a), sub(c, a)));
1555
+ };
1556
+ for (const t of tris)
1557
+ for (let i = 1; i < t.length - 1; i++) {
1558
+ const ids = [at(t[0]), at(t[i]), at(t[i + 1])];
1559
+ if (new Set(ids).size === 3 && area2(ids) > 1e-9) out.push(ids);
1560
+ }
513
1561
 
514
1562
  // Mend: split a triangle at a loose corner lying along its open edge, one corner at a time, until none is left.
515
1563
  // The loose corners are filed in 1 mm cells. Each open edge takes the cheapest of three searches: every cell of its
@@ -521,64 +1569,117 @@ export function mesh(tris, work) {
521
1569
  // The searches share a work budget sized from the mesh, cells and corners looked at across all passes, so a mesh
522
1570
  // made to be slow (thousands of long open edges among thousands of loose corners) cannot freeze the writers: once
523
1571
  // it is spent, the edges left are not mended and are written as they are.
524
- const TOL = 2e-3, CELL = 1, cell = (x) => Math.floor(x / CELL);
1572
+ const TOL = 2e-3,
1573
+ CELL = 1,
1574
+ cell = (x) => Math.floor(x / CELL);
525
1575
  let budget = work ? work.budget : 2e6 + 100 * out.length; // cells and corners looked at, across all passes
526
1576
  for (let pass = 0; pass < 50; pass++) {
527
- const edges = new Set(); for (const [a, b, c] of out) edges.add(`${a},${b}`).add(`${b},${c}`).add(`${c},${a}`);
528
- const isOpen = (a, b) => !edges.has(`${b},${a}`), loose = new Set();
529
- for (const [a, b, c] of out) for (const [x, y] of [[a, b], [b, c], [c, a]]) if (isOpen(x, y)) loose.add(x).add(y);
1577
+ const edges = new Set();
1578
+ for (const [a, b, c] of out) edges.add(`${a},${b}`).add(`${b},${c}`).add(`${c},${a}`);
1579
+ const isOpen = (a, b) => !edges.has(`${b},${a}`),
1580
+ loose = new Set();
1581
+ for (const [a, b, c] of out)
1582
+ for (const [x, y] of [
1583
+ [a, b],
1584
+ [b, c],
1585
+ [c, a],
1586
+ ])
1587
+ if (isOpen(x, y)) loose.add(x).add(y);
530
1588
  if (!loose.size) break;
531
- const grid = new Map(), rank = new Map(), looseList = [...loose];
532
- for (const i of looseList) { const k = verts[i].map(cell).join(','); if (!grid.has(k)) grid.set(k, []); rank.set(i, rank.size); grid.get(k).push(i); }
1589
+ const grid = new Map(),
1590
+ rank = new Map(),
1591
+ looseList = [...loose];
1592
+ for (const i of looseList) {
1593
+ const k = verts[i].map(cell).join(',');
1594
+ if (!grid.has(k)) grid.set(k, []);
1595
+ rank.set(i, rank.size);
1596
+ grid.get(k).push(i);
1597
+ }
533
1598
  // Which of two corners the box search met first: the lower cell (x, then y, then z), then the one filed first
534
1599
  const before = (i, j) => {
535
- for (let k = 0; k < 3; k++) { const ci = cell(verts[i][k]), cj = cell(verts[j][k]); if (ci !== cj) return ci < cj; }
1600
+ for (let k = 0; k < 3; k++) {
1601
+ const ci = cell(verts[i][k]),
1602
+ cj = cell(verts[j][k]);
1603
+ if (ci !== cj) return ci < cj;
1604
+ }
536
1605
  return rank.get(i) < rank.get(j);
537
1606
  };
538
1607
  // The loose corner along a -> b nearest the line, if any
539
1608
  const along = (a, b) => {
540
- const p = verts[a], q = verts[b], d = sub(q, p), len = Math.sqrt(dot(d, d));
1609
+ const p = verts[a],
1610
+ q = verts[b],
1611
+ d = sub(q, p),
1612
+ len = Math.sqrt(dot(d, d));
541
1613
  if (!(len * len < Infinity)) return null; // corners too far apart to measure (or not numbers): every corner looked on the line
542
- let best = null, spent = false;
1614
+ let best = null,
1615
+ spent = false;
543
1616
  const consider = (i) => {
544
1617
  if (i === a || i === b) return;
545
- const w = sub(verts[i], p), t = dot(w, d) / (len * len);
1618
+ const w = sub(verts[i], p),
1619
+ t = dot(w, d) / (len * len);
546
1620
  if (t * len < TOL || (1 - t) * len < TOL) return;
547
1621
  const off = Math.hypot(...cross(w, d)) / len;
548
1622
  if (off < TOL && (!best || off < best[1] || (off === best[1] && before(i, best[0])))) best = [i, off];
549
1623
  };
550
- const from = p.map(cell), to = q.map(cell), steps = [0, 1, 2].reduce((s, k) => s + Math.abs(to[k] - from[k]), 0);
551
- const lo = [0, 1, 2].map((k) => cell(Math.min(p[k], q[k]) - TOL)), hi = [0, 1, 2].map((k) => cell(Math.max(p[k], q[k]) + TOL));
552
- const box = (hi[0] - lo[0] + 1) * (hi[1] - lo[1] + 1) * (hi[2] - lo[2] + 1), walk = 27 * (steps + 1);
1624
+ const from = p.map(cell),
1625
+ to = q.map(cell),
1626
+ steps = [0, 1, 2].reduce((s, k) => s + Math.abs(to[k] - from[k]), 0);
1627
+ const lo = [0, 1, 2].map((k) => cell(Math.min(p[k], q[k]) - TOL)),
1628
+ hi = [0, 1, 2].map((k) => cell(Math.max(p[k], q[k]) + TOL));
1629
+ const box = (hi[0] - lo[0] + 1) * (hi[1] - lo[1] + 1) * (hi[2] - lo[2] + 1),
1630
+ walk = 27 * (steps + 1);
553
1631
  const cost = Math.min(box, walk, looseList.length);
554
1632
  if (cost > budget) return null; // the budget is spent: this edge is left open
555
1633
  budget -= cost;
556
- if (cost === looseList.length && cost < box && cost < walk) { for (const i of looseList) consider(i); return best; }
1634
+ if (cost === looseList.length && cost < box && cost < walk) {
1635
+ for (const i of looseList) consider(i);
1636
+ return best;
1637
+ }
557
1638
  // The grid searches pay for each corner they find in a cell too: many loose corners packed in a few cells would
558
1639
  // otherwise cost every edge there all of them, with only its cells counted (a few kilobytes of tiny triangles in
559
1640
  // one cell froze the writers). If the budget runs out part way, the edge is left open.
560
- const meet = (list) => { for (const i of list) { if (--budget < 0) { spent = true; return; } consider(i); } };
561
- if (box <= walk) { // a short or square-on edge: its box is fewer cells than the walk
562
- for (let x = lo[0]; x <= hi[0] && !spent; x++) for (let y = lo[1]; y <= hi[1] && !spent; y++) for (let z = lo[2]; z <= hi[2] && !spent; z++) meet(grid.get(`${x},${y},${z}`) || []);
1641
+ const meet = (list) => {
1642
+ for (const i of list) {
1643
+ if (--budget < 0) {
1644
+ spent = true;
1645
+ return;
1646
+ }
1647
+ consider(i);
1648
+ }
1649
+ };
1650
+ if (box <= walk) {
1651
+ // a short or square-on edge: its box is fewer cells than the walk
1652
+ for (let x = lo[0]; x <= hi[0] && !spent; x++)
1653
+ for (let y = lo[1]; y <= hi[1] && !spent; y++)
1654
+ for (let z = lo[2]; z <= hi[2] && !spent; z++) meet(grid.get(`${x},${y},${z}`) || []);
563
1655
  return spent ? null : best;
564
1656
  }
565
1657
  // Walk the cells the segment passes through (a 3D grid walk), looking in each and its 26 neighbours once
566
- const seen = new Set(), look = (c) => {
567
- for (let dx = -1; dx <= 1; dx++) for (let dy = -1; dy <= 1; dy++) for (let dz = -1; dz <= 1; dz++) {
568
- const k = `${c[0] + dx},${c[1] + dy},${c[2] + dz}`;
569
- if (seen.has(k)) continue;
570
- seen.add(k);
571
- if (!spent) meet(grid.get(k) || []);
572
- }
573
- };
574
- const c = [...from], step = d.map(Math.sign);
1658
+ const seen = new Set(),
1659
+ look = (c) => {
1660
+ for (let dx = -1; dx <= 1; dx++)
1661
+ for (let dy = -1; dy <= 1; dy++)
1662
+ for (let dz = -1; dz <= 1; dz++) {
1663
+ const k = `${c[0] + dx},${c[1] + dy},${c[2] + dz}`;
1664
+ if (seen.has(k)) continue;
1665
+ seen.add(k);
1666
+ if (!spent) meet(grid.get(k) || []);
1667
+ }
1668
+ };
1669
+ const c = [...from],
1670
+ step = d.map(Math.sign);
575
1671
  const tMax = [0, 1, 2].map((k) => (d[k] ? ((c[k] + (d[k] > 0 ? 1 : 0)) * CELL - p[k]) / d[k] : Infinity));
576
1672
  const tDelta = [0, 1, 2].map((k) => (d[k] ? CELL / Math.abs(d[k]) : Infinity));
577
1673
  look(c);
578
1674
  for (let n = 0; n < steps; n++) {
579
- const k = tMax[0] <= tMax[1] ? (tMax[0] <= tMax[2] ? 0 : 2) : (tMax[1] <= tMax[2] ? 1 : 2);
580
- if (c[k] === to[k]) { tMax[k] = Infinity; n--; continue; } // rounding: this axis is already at the end cell
581
- c[k] += step[k]; tMax[k] += tDelta[k];
1675
+ const k = tMax[0] <= tMax[1] ? (tMax[0] <= tMax[2] ? 0 : 2) : tMax[1] <= tMax[2] ? 1 : 2;
1676
+ if (c[k] === to[k]) {
1677
+ tMax[k] = Infinity;
1678
+ n--;
1679
+ continue;
1680
+ } // rounding: this axis is already at the end cell
1681
+ c[k] += step[k];
1682
+ tMax[k] += tDelta[k];
582
1683
  look(c);
583
1684
  }
584
1685
  look(to);
@@ -590,24 +1691,34 @@ export function mesh(tris, work) {
590
1691
  const t = out[k];
591
1692
  let pick = null;
592
1693
  for (let e = 0; e < 3; e++) {
593
- const a = t[e], b = t[(e + 1) % 3];
1694
+ const a = t[e],
1695
+ b = t[(e + 1) % 3];
594
1696
  if (!isOpen(a, b)) continue;
595
1697
  const f = along(a, b);
596
1698
  if (f && (!pick || f[1] < pick[1])) pick = [f[0], f[1], e];
597
1699
  }
598
1700
  if (!pick) continue;
599
- const [v, , e] = pick, a = t[e], b = t[(e + 1) % 3], c = t[(e + 2) % 3];
600
- out[k] = [a, v, c]; out.push([v, b, c]); split++;
1701
+ const [v, , e] = pick,
1702
+ a = t[e],
1703
+ b = t[(e + 1) % 3],
1704
+ c = t[(e + 2) % 3];
1705
+ out[k] = [a, v, c];
1706
+ out.push([v, b, c]);
1707
+ split++;
601
1708
  }
602
1709
  if (!split) break;
603
1710
  }
604
1711
  if (work) work.budget = budget;
605
1712
  // What's left are pinholes: a sliver face the booleans lost, a loop of open edges a fraction of a millimetre round.
606
1713
  // Close each with a fan.
607
- const kept = out.filter((ids) => area2(ids) > 1e-9), edges = new Set();
1714
+ const kept = out.filter((ids) => area2(ids) > 1e-9),
1715
+ edges = new Set();
608
1716
  for (const [a, b, c] of kept) edges.add(`${a},${b}`).add(`${b},${c}`).add(`${c},${a}`);
609
1717
  const next = new Map();
610
- for (const k of edges) { const [a, b] = k.split(',').map(Number); if (!edges.has(`${b},${a}`)) next.set(a, b); }
1718
+ for (const k of edges) {
1719
+ const [a, b] = k.split(',').map(Number);
1720
+ if (!edges.has(`${b},${a}`)) next.set(a, b);
1721
+ }
611
1722
  const PINHOLE = 1;
612
1723
  for (const start of [...next.keys()]) {
613
1724
  if (!next.has(start)) continue;
@@ -622,44 +1733,109 @@ export function mesh(tris, work) {
622
1733
  return { verts, tris: kept };
623
1734
  }
624
1735
 
625
- const meshXml = ({ verts, tris }) => `<mesh><vertices>${verts.map((v) => `<vertex x="${num(v[0])}" y="${num(v[1])}" z="${num(v[2])}"/>`).join('')}</vertices>`
626
- + `<triangles>${tris.map(([a, b, c]) => `<triangle v1="${a}" v2="${b}" v3="${c}"/>`).join('')}</triangles></mesh>`;
1736
+ const meshXml = ({ verts, tris }) =>
1737
+ `<mesh><vertices>${verts.map((v) => `<vertex x="${num(v[0])}" y="${num(v[1])}" z="${num(v[2])}"/>`).join('')}</vertices>` +
1738
+ `<triangles>${tris.map(([a, b, c]) => `<triangle v1="${a}" v2="${b}" v3="${c}"/>`).join('')}</triangles></mesh>`;
627
1739
 
628
- const uuid = (n, kind) => `${kind.toString(16).padStart(4, '0')}${(n & 0xffff).toString(16).padStart(4, '0')}-81cb-4c03-9d28-80fed5dfa1dc`;
629
- const IDENTITY = '1 0 0 0 1 0 0 0 1 0 0 0', IDENTITY4 = '1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1';
630
- const NS = 'xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02" xmlns:BambuStudio="http://schemas.bambulab.com/package/2021" xmlns:p="http://schemas.microsoft.com/3dmanufacturing/production/2015/06" requiredextensions="p"';
1740
+ const uuid = (n, kind) =>
1741
+ `${kind.toString(16).padStart(4, '0')}${(n & 0xffff).toString(16).padStart(4, '0')}-81cb-4c03-9d28-80fed5dfa1dc`;
1742
+ const IDENTITY = '1 0 0 0 1 0 0 0 1 0 0 0',
1743
+ IDENTITY4 = '1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1';
1744
+ const NS =
1745
+ 'xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02" xmlns:BambuStudio="http://schemas.bambulab.com/package/2021" xmlns:p="http://schemas.microsoft.com/3dmanufacturing/production/2015/06" requiredextensions="p"';
631
1746
 
632
1747
  /** @param {{ name: string, parts: { name: string, triangles: Triangle[], slot?: number }[] }[]} objects @param {{ centre?: [number, number], generator?: string, date?: string, title?: string }} [options] @returns {Promise<Uint8Array>} a .3mf (a zip) */
633
1748
  export async function bambu3mf(objects, { centre = [128, 128], generator = 'rulecad', date, title } = {}) {
634
- const files = {}, rels = [], resources = [], build = [], settings = [], instances = [];
635
- const work = { budget: 2e6 + 100 * objects.reduce((n, o) => n + o.parts.reduce((k, p) => k + p.triangles.length, 0), 0) }; // one mend budget for the file
1749
+ const files = {},
1750
+ rels = [],
1751
+ resources = [],
1752
+ build = [],
1753
+ settings = [],
1754
+ instances = [];
1755
+ const work = {
1756
+ budget: 2e6 + 100 * objects.reduce((n, o) => n + o.parts.reduce((k, p) => k + p.triangles.length, 0), 0),
1757
+ }; // one mend budget for the file
636
1758
  let id = 0;
637
1759
  objects.forEach((o, n) => {
638
- const path = `/3D/Objects/object_${n + 1}.model`, parts = o.parts.map((p) => ({ ...p, id: ++id }));
639
- files[path.slice(1)] = `<?xml version="1.0" encoding="UTF-8"?>\n<model unit="millimeter" xml:lang="en-US" ${NS}>\n <metadata name="BambuStudio:3mfVersion">1</metadata>\n <resources>\n`
640
- + parts.map((p) => ` <object id="${p.id}" p:UUID="${uuid(p.id, 1)}" type="model">${meshXml(mesh(p.triangles, work))}</object>\n`).join('') + ' </resources>\n <build/>\n</model>\n';
641
- rels.push(`<Relationship Target="${path}" Id="rel-${n + 1}" Type="http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"/>`);
1760
+ const path = `/3D/Objects/object_${n + 1}.model`,
1761
+ parts = o.parts.map((p) => ({ ...p, id: ++id }));
1762
+ files[path.slice(1)] =
1763
+ `<?xml version="1.0" encoding="UTF-8"?>\n<model unit="millimeter" xml:lang="en-US" ${NS}>\n <metadata name="BambuStudio:3mfVersion">1</metadata>\n <resources>\n` +
1764
+ parts
1765
+ .map(
1766
+ (p) =>
1767
+ ` <object id="${p.id}" p:UUID="${uuid(p.id, 1)}" type="model">${meshXml(mesh(p.triangles, work))}</object>\n`,
1768
+ )
1769
+ .join('') +
1770
+ ' </resources>\n <build/>\n</model>\n';
1771
+ rels.push(
1772
+ `<Relationship Target="${path}" Id="rel-${n + 1}" Type="http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"/>`,
1773
+ );
642
1774
  const parent = 100000 + n + 1;
643
- resources.push(` <object id="${parent}" p:UUID="${uuid(n + 1, 0)}" type="model">\n <components>\n`
644
- + parts.map((p) => ` <component p:path="${path}" objectid="${p.id}" p:UUID="${uuid(p.id, 2)}" transform="${IDENTITY}"/>\n`).join('') + ' </components>\n </object>\n');
645
- build.push(` <item objectid="${parent}" p:UUID="${uuid(n + 1, 3)}" transform="1 0 0 0 1 0 0 0 1 ${centre[0]} ${centre[1]} 0" printable="1"/>\n`);
646
- settings.push(` <object id="${parent}">\n <metadata key="name" value="${esc(o.name)}"/>\n <metadata key="extruder" value="${parts[0]?.slot || 1}"/>\n`
647
- + parts.map((p) => ` <part id="${p.id}" subtype="normal_part">\n <metadata key="name" value="${esc(p.name)}"/>\n <metadata key="matrix" value="${IDENTITY4}"/>\n <metadata key="extruder" value="${p.slot || 1}"/>\n </part>\n`).join('') + ' </object>\n');
648
- instances.push(` <model_instance>\n <metadata key="object_id" value="${parent}"/>\n <metadata key="instance_id" value="0"/>\n <metadata key="identify_id" value="${n + 1}"/>\n </model_instance>\n`);
1775
+ resources.push(
1776
+ ` <object id="${parent}" p:UUID="${uuid(n + 1, 0)}" type="model">\n <components>\n` +
1777
+ parts
1778
+ .map(
1779
+ (p) =>
1780
+ ` <component p:path="${path}" objectid="${p.id}" p:UUID="${uuid(p.id, 2)}" transform="${IDENTITY}"/>\n`,
1781
+ )
1782
+ .join('') +
1783
+ ' </components>\n </object>\n',
1784
+ );
1785
+ build.push(
1786
+ ` <item objectid="${parent}" p:UUID="${uuid(n + 1, 3)}" transform="1 0 0 0 1 0 0 0 1 ${centre[0]} ${centre[1]} 0" printable="1"/>\n`,
1787
+ );
1788
+ settings.push(
1789
+ ` <object id="${parent}">\n <metadata key="name" value="${esc(o.name)}"/>\n <metadata key="extruder" value="${extruder(parts[0]?.slot)}"/>\n` +
1790
+ parts
1791
+ .map(
1792
+ (p) =>
1793
+ ` <part id="${p.id}" subtype="normal_part">\n <metadata key="name" value="${esc(p.name)}"/>\n <metadata key="matrix" value="${IDENTITY4}"/>\n <metadata key="extruder" value="${extruder(p.slot)}"/>\n </part>\n`,
1794
+ )
1795
+ .join('') +
1796
+ ' </object>\n',
1797
+ );
1798
+ instances.push(
1799
+ ` <model_instance>\n <metadata key="object_id" value="${parent}"/>\n <metadata key="instance_id" value="0"/>\n <metadata key="identify_id" value="${n + 1}"/>\n </model_instance>\n`,
1800
+ );
649
1801
  });
650
- const xml = '<?xml version="1.0" encoding="UTF-8"?>\n', today = date || new Date().toISOString().slice(0, 10); // date: '2026-10-14' for a reproducible file
1802
+ const xml = '<?xml version="1.0" encoding="UTF-8"?>\n',
1803
+ today = date || new Date().toISOString().slice(0, 10); // date: '2026-10-14' for a reproducible file
651
1804
  return zip([
652
- ['[Content_Types].xml', `${xml}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">\n <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>\n <Default Extension="model" ContentType="application/vnd.ms-package.3dmanufacturing-3dmodel+xml"/>\n</Types>\n`],
653
- ['_rels/.rels', `${xml}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\n <Relationship Target="/3D/3dmodel.model" Id="rel-1" Type="http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"/>\n</Relationships>\n`],
654
- ['3D/_rels/3dmodel.model.rels', `${xml}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\n ${rels.join('\n ')}\n</Relationships>\n`],
655
- ['3D/3dmodel.model', `${xml}<model unit="millimeter" xml:lang="en-US" ${NS}>\n <metadata name="Application">${esc(generator)}</metadata>\n <metadata name="BambuStudio:3mfVersion">1</metadata>\n <metadata name="Title">${esc(title || objects[0]?.name || 'model')}</metadata>\n <metadata name="CreationDate">${today}</metadata>\n <resources>\n${resources.join('')} </resources>\n <build p:UUID="${uuid(0, 4)}">\n${build.join('')} </build>\n</model>\n`],
656
- ['Metadata/model_settings.config', `${xml}<config>\n${settings.join('')} <plate>\n <metadata key="plater_id" value="1"/>\n <metadata key="plater_name" value=""/>\n <metadata key="locked" value="false"/>\n${instances.join('')} </plate>\n</config>\n`],
1805
+ [
1806
+ '[Content_Types].xml',
1807
+ `${xml}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">\n <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>\n <Default Extension="model" ContentType="application/vnd.ms-package.3dmanufacturing-3dmodel+xml"/>\n</Types>\n`,
1808
+ ],
1809
+ [
1810
+ '_rels/.rels',
1811
+ `${xml}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\n <Relationship Target="/3D/3dmodel.model" Id="rel-1" Type="http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"/>\n</Relationships>\n`,
1812
+ ],
1813
+ [
1814
+ '3D/_rels/3dmodel.model.rels',
1815
+ `${xml}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\n ${rels.join('\n ')}\n</Relationships>\n`,
1816
+ ],
1817
+ [
1818
+ '3D/3dmodel.model',
1819
+ `${xml}<model unit="millimeter" xml:lang="en-US" ${NS}>\n <metadata name="Application">${esc(generator)}</metadata>\n <metadata name="BambuStudio:3mfVersion">1</metadata>\n <metadata name="Title">${esc(title || objects[0]?.name || 'model')}</metadata>\n <metadata name="CreationDate">${today}</metadata>\n <resources>\n${resources.join('')} </resources>\n <build p:UUID="${uuid(0, 4)}">\n${build.join('')} </build>\n</model>\n`,
1820
+ ],
1821
+ [
1822
+ 'Metadata/model_settings.config',
1823
+ `${xml}<config>\n${settings.join('')} <plate>\n <metadata key="plater_id" value="1"/>\n <metadata key="plater_name" value=""/>\n <metadata key="locked" value="false"/>\n${instances.join('')} </plate>\n</config>\n`,
1824
+ ],
657
1825
  ...Object.entries(files),
658
1826
  ]);
659
1827
  }
660
1828
 
661
- const CRC = Array.from({ length: 256 }, (_, n) => { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0; });
662
- const crc32 = (b) => { let c = 0xffffffff; for (const x of b) c = CRC[(c ^ x) & 255] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; };
1829
+ const CRC = Array.from({ length: 256 }, (_, n) => {
1830
+ let c = n;
1831
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
1832
+ return c >>> 0;
1833
+ });
1834
+ const crc32 = (b) => {
1835
+ let c = 0xffffffff;
1836
+ for (const x of b) c = CRC[(c ^ x) & 255] ^ (c >>> 8);
1837
+ return (c ^ 0xffffffff) >>> 0;
1838
+ };
663
1839
 
664
1840
  /**
665
1841
  * A ZIP file, each file deflated with the browser's (or Node's) own CompressionStream: no library needed.
@@ -667,22 +1843,56 @@ const crc32 = (b) => { let c = 0xffffffff; for (const x of b) c = CRC[(c ^ x) &
667
1843
  * @returns {Promise<Uint8Array>}
668
1844
  */
669
1845
  export async function zip(entries) {
670
- const enc = new TextEncoder(), parts = [], dir = [];
1846
+ const enc = new TextEncoder(),
1847
+ parts = [],
1848
+ dir = [];
671
1849
  let offset = 0;
672
1850
  for (const [name, text] of entries) {
673
- const n = enc.encode(name), raw = enc.encode(text), crc = crc32(raw), d = await pipe(raw, new CompressionStream('deflate-raw'));
1851
+ const n = enc.encode(name),
1852
+ raw = enc.encode(text),
1853
+ crc = crc32(raw),
1854
+ d = await pipe(raw, new CompressionStream('deflate-raw'));
674
1855
  const local = new DataView(new ArrayBuffer(30));
675
- [[0, 0x04034b50, 4], [4, 20, 2], [8, 8, 2], [14, crc, 4], [18, d.length, 4], [22, raw.length, 4], [26, n.length, 2]].forEach(([o, v, s]) => (s === 4 ? local.setUint32(o, v, true) : local.setUint16(o, v, true)));
1856
+ [
1857
+ [0, 0x04034b50, 4],
1858
+ [4, 20, 2],
1859
+ [8, 8, 2],
1860
+ [14, crc, 4],
1861
+ [18, d.length, 4],
1862
+ [22, raw.length, 4],
1863
+ [26, n.length, 2],
1864
+ ].forEach(([o, v, s]) => (s === 4 ? local.setUint32(o, v, true) : local.setUint16(o, v, true)));
676
1865
  const central = new DataView(new ArrayBuffer(46));
677
- [[0, 0x02014b50, 4], [4, 20, 2], [6, 20, 2], [10, 8, 2], [16, crc, 4], [20, d.length, 4], [24, raw.length, 4], [28, n.length, 2], [42, offset, 4]].forEach(([o, v, s]) => (s === 4 ? central.setUint32(o, v, true) : central.setUint16(o, v, true)));
1866
+ [
1867
+ [0, 0x02014b50, 4],
1868
+ [4, 20, 2],
1869
+ [6, 20, 2],
1870
+ [10, 8, 2],
1871
+ [16, crc, 4],
1872
+ [20, d.length, 4],
1873
+ [24, raw.length, 4],
1874
+ [28, n.length, 2],
1875
+ [42, offset, 4],
1876
+ ].forEach(([o, v, s]) => (s === 4 ? central.setUint32(o, v, true) : central.setUint16(o, v, true)));
678
1877
  parts.push(new Uint8Array(local.buffer), n, d);
679
1878
  dir.push(new Uint8Array(central.buffer), n);
680
1879
  offset += 30 + n.length + d.length;
681
1880
  }
682
- const size = dir.reduce((s, b) => s + b.length, 0), end = new DataView(new ArrayBuffer(22));
683
- [[0, 0x06054b50, 4], [8, entries.length, 2], [10, entries.length, 2], [12, size, 4], [16, offset, 4]].forEach(([o, v, s]) => (s === 4 ? end.setUint32(o, v, true) : end.setUint16(o, v, true)));
684
- const all = [...parts, ...dir, new Uint8Array(end.buffer)], out = new Uint8Array(all.reduce((s, b) => s + b.length, 0));
1881
+ const size = dir.reduce((s, b) => s + b.length, 0),
1882
+ end = new DataView(new ArrayBuffer(22));
1883
+ [
1884
+ [0, 0x06054b50, 4],
1885
+ [8, entries.length, 2],
1886
+ [10, entries.length, 2],
1887
+ [12, size, 4],
1888
+ [16, offset, 4],
1889
+ ].forEach(([o, v, s]) => (s === 4 ? end.setUint32(o, v, true) : end.setUint16(o, v, true)));
1890
+ const all = [...parts, ...dir, new Uint8Array(end.buffer)],
1891
+ out = new Uint8Array(all.reduce((s, b) => s + b.length, 0));
685
1892
  let at = 0;
686
- for (const b of all) { out.set(b, at); at += b.length; }
1893
+ for (const b of all) {
1894
+ out.set(b, at);
1895
+ at += b.length;
1896
+ }
687
1897
  return out;
688
1898
  }