@rulecad/model-link 0.3.0 → 0.3.2

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/README.md CHANGED
@@ -30,6 +30,7 @@ const zip = await threemf(back); // Uint8Array, a .3mf (one object, two
30
30
  joint's values, followers included, and `placeItems(motion, values)` gives where each item is. The page uses these
31
31
  for its sliders, and `cad` uses the same functions to place an assembly, so both agree. The format is described at
32
32
  the top of the motion section in `model-link.mjs`.
33
+ - **A machine's link:** a model can carry `task` (the tool's anchor and the plane it moves on, with what the margins read), `steps` (a step file cut down by `compactSteps(file)`, small enough for a link), `wires` (routes drawn faint, never parts) and `build` (the build page's text and numbers). All of it is checked as data when a link is decoded, and a page never runs any of it. The formats are in the comment at the top of the "a machine's link" section in `model-link.mjs`.
33
34
  - **Safety:** links are data, never code. `decode()` checks the format and sizes (`LIMITS`), refuses damaged links,
34
35
  and refuses links from a newer format version.
35
36
  - **Short links:** `parseHash(location.hash)` also reads `#s=<id>`, a GitHub Gist holding the data, and
package/model-link.d.mts CHANGED
@@ -39,6 +39,15 @@ export function check(m: any): {
39
39
  text: string;
40
40
  code: string;
41
41
  }[];
42
+ /**
43
+ * A step file (rulecad.steps/1, from cad plot) as a link or a page carries it: what playback needs, in whole numbers.
44
+ * A very long drawing's blocks and points are merged and thinned to stay small: motion only, the drawing itself is not moved.
45
+ * @param {object} steps @param {{ maxBlocks?: number, maxPoints?: number }} [options] @returns {object} @throws an Error naming what's wrong
46
+ */
47
+ export function compactSteps(steps: object, { maxBlocks, maxPoints }?: {
48
+ maxBlocks?: number;
49
+ maxPoints?: number;
50
+ }): object;
42
51
  export function expand(m: any): any;
43
52
  export function fromShapes(list: any): {
44
53
  shapes: {
@@ -111,7 +120,7 @@ export function bambu3mf(objects: {
111
120
  */
112
121
  export function zip(entries: [string, string][]): Promise<Uint8Array>;
113
122
  /** @typedef {[[number, number, number], [number, number, number], [number, number, number]]} Triangle corners in mm, counter-clockwise seen from outside, Z up */
114
- /** @typedef {{ title?: string, version?: string, src?: string, material?: string, orientation?: string, rules?: [string, any, string][], q?: number, p?: number[], t?: number[], parts?: any[], shapes?: any[], place?: any[], views?: [string, string][], motion?: any }} Model */
123
+ /** @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 */
115
124
  export const VERSION: 1;
116
125
  export namespace LIMITS {
117
126
  let vertices: number;
@@ -121,6 +130,8 @@ export namespace LIMITS {
121
130
  let views: number;
122
131
  let viewSize: number;
123
132
  let sheet: number;
133
+ let fab: number;
134
+ let fabSize: number;
124
135
  let size: number;
125
136
  let text: number;
126
137
  let bytes: number;
@@ -154,6 +165,10 @@ export type Model = {
154
165
  src?: string;
155
166
  material?: string;
156
167
  orientation?: string;
168
+ fab?: {
169
+ name: string;
170
+ zip: string;
171
+ }[];
157
172
  rules?: [string, any, string][];
158
173
  q?: number;
159
174
  p?: number[];
package/model-link.mjs CHANGED
@@ -11,17 +11,20 @@
11
11
  // these come after the parts they stand in for.
12
12
  // views (optional): [[name, svg]], 2D drawings shown beside the 3D model (a board's copper, a schematic); "Group:
13
13
  // view" names share a tab. The page shows them as images, so nothing in them runs.
14
+ // 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.
14
16
  // Or placed shapes, for things made of repeated parts (nine keys): each shape once, then where each copy goes:
15
17
  // { …, shapes: [{ role, label, slot?, q, p, t }], place: [[shape, a, b, c, d, e, f, g, h, i, j, k, l, name?]] }
16
18
  // (a 3 × 4 transform by rows, in mm). decode() expands them, so the rest of the page sees one model.
17
19
  // motion (optional): joints a page can move, each part with its item (see "motion" below); without it, nothing moves.
20
+ // task, steps, wires, build (optional, what a machine's link adds; see "a machine's link" below). Data, read as text.
18
21
  // "1." is the format version: newer pages must keep reading old links.
19
22
 
20
23
  /** @typedef {[[number, number, number], [number, number, number], [number, number, number]]} Triangle corners in mm, counter-clockwise seen from outside, Z up */
21
- /** @typedef {{ title?: string, version?: string, src?: string, material?: string, orientation?: string, rules?: [string, any, string][], q?: number, p?: number[], t?: number[], parts?: any[], shapes?: any[], place?: any[], views?: [string, string][], motion?: any }} Model */
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 */
22
25
 
23
26
  export const VERSION = 1;
24
- export const LIMITS = { vertices: 200000, triangles: 400000, shapes: 512, places: 2048, views: 32, viewSize: 4e6, sheet: 5000, // every keycap with its own legend is its own shape
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
25
28
  size: 1e5, // mm: no corner further than this from the origin (a link is a part or an assembly, not a map)
26
29
  text: 2000, // characters in a title, a name or a label
27
30
  bytes: 160e6 }; // of a link once unpacked: its views at their largest, and the biggest model, with room to spare
@@ -131,7 +134,13 @@ function problems(m) {
131
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'];
132
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})`];
133
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'];
134
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'];
135
144
  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'];
136
145
  return [];
137
146
  }
@@ -157,9 +166,75 @@ function motionOk(mo, places) {
157
166
  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;
158
167
  const pair = (x) => Array.isArray(x) && x.length === 2 && x.every((i) => Number.isInteger(i) && i >= 0 && i < places);
159
168
  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;
169
+ 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;
160
170
  return mo.allow == null || (Array.isArray(mo.allow) && mo.allow.every(pair));
161
171
  }
162
172
 
173
+ // ---------- a machine's link ----------
174
+ // task: { tool, item, point: [x, y, z], plane: { at, u, v, n, width, height }, elbow?, speed?, accuracy?, deflection?,
175
+ // terms?: [[joint index in the chain, name, degrees, kind]], loads?: [{ item (index), at: [x, y, z], mass } |
176
+ // { joint, value }], gravity?: [x, y, z], torque?: [{ joint, available }], heat?: { motor, case, softening } }:
177
+ // the tool's anchor as chainFromMotion takes it (@rulecad/robots), the plane the pen moves on, and what the margins
178
+ // read at each pose: error terms (degrees) carried to the tool, masses carried beyond each joint, what each motor gives.
179
+ // steps: a step file from cad plot, cut down by compactSteps: { name, machine?, names, spu, start, b, drawn }.
180
+ // b: blocks, [kind, milliseconds, stroke, …axis steps]; kind 0 travel, 1 draw, 2 pen up, 3 pen down (those last two
181
+ // are only [kind, milliseconds]). drawn: lines, [stroke, [x, y, z, …] in 0.01 mm, [predicted error in microns, per
182
+ // point] | null], stroke matching a block's.
183
+ // wires: [[id, [[item (index, -1 fixed), x, y, z], …]]], routes drawn faint, moving with their items; never parts.
184
+ // build: the build page's content, read as text and numbers (the shopping list, plates, wiring, steps, settings).
185
+ const INT = 2 ** 31;
186
+ const int = (x) => Number.isInteger(x) && Math.abs(x) < INT;
187
+ const text = (x) => typeof x === 'string' && x.length <= LIMITS.text;
188
+ // Only data: strings in bounds, finite numbers, booleans, null, and arrays or plain objects of those
189
+ function plain(x, depth = 0) {
190
+ if (x === null || typeof x === 'boolean' || (typeof x === 'number' && Number.isFinite(x)) || text(x)) return true;
191
+ if (depth > 8 || typeof x !== 'object') return false;
192
+ 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));
193
+ }
194
+ function taskOk(t) {
195
+ 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;
196
+ 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;
197
+ 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;
198
+ if (t.torque != null && !(Array.isArray(t.torque) && t.torque.every((x) => x && text(x.joint) && nums([x.available])))) return false;
199
+ if (t.gravity != null && !nums(t.gravity, 3)) return false;
200
+ for (const k of ['speed', 'accuracy', 'deflection']) if (t[k] != null && !nums([t[k]])) return false;
201
+ return (t.elbow == null || ['left', 'right'].includes(t.elbow)) && (t.heat == null || (text(t.heat.motor) && nums([t.heat.case, t.heat.softening], 2)));
202
+ }
203
+ function stepsOk(x) {
204
+ 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;
205
+ const n = x.names.length;
206
+ 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;
207
+ 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))));
208
+ }
209
+ 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))));
210
+
211
+ /**
212
+ * A step file (rulecad.steps/1, from cad plot) as a link or a page carries it: what playback needs, in whole numbers.
213
+ * A very long drawing's blocks and points are merged and thinned to stay small: motion only, the drawing itself is not moved.
214
+ * @param {object} steps @param {{ maxBlocks?: number, maxPoints?: number }} [options] @returns {object} @throws an Error naming what's wrong
215
+ */
216
+ export function compactSteps(steps, { maxBlocks = 4000, maxPoints = 8000 } = {}) {
217
+ 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)');
218
+ const names = steps.axes.map((a) => a.name), spu = steps.axes.map((a) => a.stepsPerUnit), n = names.length;
219
+ 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');
220
+ 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)]);
221
+ let b = steps.blocks.map(row);
222
+ while (b.length > maxBlocks) { // neighbouring moves of one kind on one stroke merged, two at a time, until it's few enough
223
+ const out = [];
224
+ for (let i = 0; i < b.length; i++) {
225
+ const x = b[i], y = b[i + 1];
226
+ 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);
227
+ }
228
+ if (out.length === b.length) break; // only pen changes left
229
+ b = out;
230
+ }
231
+ const drawn = (steps.drawn || []).map((d) => [d.stroke ?? -1, d.points, d.error]);
232
+ let count = drawn.reduce((t, d) => t + d[1].length, 0), keep = 1;
233
+ while (count / keep > maxPoints) keep++;
234
+ 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,
235
+ 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]; }) };
236
+ }
237
+
163
238
  // Placed shapes -> one model ({ q, p, t, parts }), each copy its own part.
164
239
  export function expand(m) {
165
240
  const { shapes, place, ...meta } = m;
@@ -204,7 +279,7 @@ export const posesOf = (m) => (m.parts || []).map((part, k) => ({ k, part })).fi
204
279
 
205
280
  // ---------- motion ----------
206
281
  // Joints between items, so a page (or a tool) can move them: an assembly's hinges, rails and ball joints.
207
- // motion: { items: [[name, …12?]], joints: [joint], poses: { name: { joint: value } }, pose?, part: [item per place],
282
+ // 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),
208
283
  // allow?: [[place, place]], swap?: { pose: [[place, place]] } }
209
284
  // An item with 12 numbers sits there (a 3 × 4 transform by rows, as in place); one without is placed by the joint
210
285
  // whose child it is. part[n] is the item place n moves with (-1: it never moves); allow pairs may overlap (press fits).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/model-link",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "Share a printable model as a link (the model lives in the URL), and write STL or multi-colour Bambu Studio 3MF files, in the browser or Node.",
5
5
  "type": "module",
6
6
  "exports": {