@rulecad/model-link 0.1.4 → 0.2.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/README.md CHANGED
@@ -25,6 +25,11 @@ const zip = await threemf(back); // Uint8Array, a .3mf (one object, two
25
25
  - **Precision:** corners are snapped to a grid about 1/5000 of the model's size, and shared corners are stored once.
26
26
  - **Many copies of one shape** (nine keycaps): `fromShapes()` stores each shape once and a transform per copy, and
27
27
  `decode()` expands them.
28
+ - **Things that move:** a model can carry `motion`: its items, the joints between them (fixed, revolute, prismatic,
29
+ cylindrical, ball, path), named poses, and which item each part moves with. `jointValues(motion, pose)` gives every
30
+ joint's values, followers included, and `placeItems(motion, values)` gives where each item is. The page uses these
31
+ for its sliders, and `cad` uses the same functions to place an assembly, so both agree. The format is described at
32
+ the top of the motion section in `model-link.mjs`.
28
33
  - **Safety:** links are data, never code. `decode()` checks the format and sizes (`LIMITS`), refuses damaged links,
29
34
  and refuses links from a newer format version.
30
35
  - **Short links:** `parseHash(location.hash)` also reads `#s=<id>`, a GitHub Gist holding the data, and
package/model-link.d.mts CHANGED
@@ -44,6 +44,29 @@ export function fromShapes(list: any): {
44
44
  };
45
45
  /** The model's triangles, or one part's. @param {Model} m @param {any[]} [part] @returns {Triangle[]} */
46
46
  export function triangles(m: Model, part?: any[]): Triangle[];
47
+ /** m · n, two 3 × 4 transforms by rows @param {number[]} m @param {number[]} n @returns {number[]} */
48
+ export function mul(m: number[], n: number[]): number[];
49
+ /** The inverse of a rigid 3 × 4 transform @param {number[]} m @returns {number[]} */
50
+ export function inv(m: number[]): number[];
51
+ /** @param {number[]} at @param {number[]} [axis] @param {number[]} [ref] @returns {number[]} */
52
+ export function frame(at: number[], axis?: number[], ref?: number[]): number[];
53
+ /** @param {{ id: string, type: string, path?: number[][] }} j @param {number[]} v @returns {number[]} */
54
+ export function jointMatrix(j: {
55
+ id: string;
56
+ type: string;
57
+ path?: number[][];
58
+ }, v: number[]): number[];
59
+ /** @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[]>} */
60
+ export function jointValues(motion: {
61
+ joints: any[];
62
+ poses?: Record<string, Record<string, number | number[]>>;
63
+ pose?: string;
64
+ }, pose?: string | Record<string, number | number[]> | null): Record<string, number[]>;
65
+ /** @param {{ items: any[][], joints: any[] }} motion @param {Record<string, number[]>} values @returns {number[][]} */
66
+ export function placeItems(motion: {
67
+ items: any[][];
68
+ joints: any[];
69
+ }, values: Record<string, number[]>): number[][];
47
70
  /** @param {ArrayBuffer | Uint8Array} bytes binary or text STL @returns {Triangle[]} */
48
71
  export function fromSTL(bytes: ArrayBuffer | Uint8Array): Triangle[];
49
72
  /** A binary STL of the printed parts (or those kept). @param {Model} m @param {(part: any[]) => boolean} [keep] @param {{ generator?: string }} [options] @returns {Uint8Array} */
@@ -79,7 +102,7 @@ export function bambu3mf(objects: {
79
102
  */
80
103
  export function zip(entries: [string, string][]): Promise<Uint8Array>;
81
104
  /** @typedef {[[number, number, number], [number, number, number], [number, number, number]]} Triangle corners in mm, counter-clockwise seen from outside, Z up */
82
- /** @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][] }} Model */
105
+ /** @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 */
83
106
  export const VERSION: 1;
84
107
  export namespace LIMITS {
85
108
  let vertices: number;
@@ -88,8 +111,21 @@ export namespace LIMITS {
88
111
  let places: number;
89
112
  let views: number;
90
113
  let viewSize: number;
114
+ let sheet: number;
91
115
  }
92
116
  export function partsOf(m: any): any;
117
+ export namespace DOFS {
118
+ let fixed: any[];
119
+ let revolute: string[];
120
+ let prismatic: string[];
121
+ let cylindrical: string[];
122
+ let ball: string[];
123
+ let path: string[];
124
+ }
125
+ /** @type {(degrees: number[]) => number[]} */
126
+ export const turn: (degrees: number[]) => number[];
127
+ /** @type {(points: number[][]) => number} */
128
+ export const pathLength: (points: number[][]) => number;
93
129
  export function filename(m: any, ext: any, picked?: string): string;
94
130
  export function thingOf(name: any): string;
95
131
  /**
@@ -110,4 +146,5 @@ export type Model = {
110
146
  shapes?: any[];
111
147
  place?: any[];
112
148
  views?: [string, string][];
149
+ motion?: any;
113
150
  };
package/model-link.mjs CHANGED
@@ -12,13 +12,14 @@
12
12
  // Or placed shapes, for things made of repeated parts (nine keys): each shape once, then where each copy goes:
13
13
  // { …, shapes: [{ role, label, slot?, q, p, t }], place: [[shape, a, b, c, d, e, f, g, h, i, j, k, l, name?]] }
14
14
  // (a 3 × 4 transform by rows, in mm). decode() expands them, so the rest of the page sees one model.
15
+ // motion (optional): joints a page can move, each part with its item (see "motion" below); without it, nothing moves.
15
16
  // "1." is the format version: newer pages must keep reading old links.
16
17
 
17
18
  /** @typedef {[[number, number, number], [number, number, number], [number, number, number]]} Triangle corners in mm, counter-clockwise seen from outside, Z up */
18
- /** @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][] }} Model */
19
+ /** @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 */
19
20
 
20
21
  export const VERSION = 1;
21
- export const LIMITS = { vertices: 200000, triangles: 400000, shapes: 512, places: 2048, views: 32, viewSize: 4e6 }; // every keycap with its own legend is its own shape
22
+ 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
22
23
 
23
24
  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(/=+$/, ''); };
24
25
  const unb64 = (s) => Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0));
@@ -101,12 +102,29 @@ export function check(m) {
101
102
  if (m.p.length / 3 > LIMITS.vertices || m.t.length / 3 > LIMITS.triangles) return ['model too big for a link'];
102
103
  const n = m.p.length / 3;
103
104
  if (m.p.some((x) => !Number.isInteger(x)) || m.t.some((i) => !Number.isInteger(i) || i < 0 || i >= n)) return ['broken model data'];
105
+ 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'];
104
106
  if (Array.isArray(m.views) && m.views.length > LIMITS.views) return [`${m.views.length} flat views: more than a link can hold (${LIMITS.views})`];
105
107
  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'];
108
+ if (m.motion != null && !motionOk(m.motion, m.parts?.length ?? 1)) return ['broken motion'];
106
109
  if (m.parts != null && (!Array.isArray(m.parts) || m.parts.some((x) => !Array.isArray(x) || !Number.isInteger(x[3]) || !Number.isInteger(x[4]) || x[3] < 0 || x[3] + x[4] > m.t.length / 3))) return ['broken parts list'];
107
110
  return [];
108
111
  }
109
112
 
113
+ // A link's motion, as data: numbers where numbers go, items and joints that exist, nothing that could run
114
+ const nums = (a, n) => Array.isArray(a) && (n == null || a.length === n) && a.every((x) => typeof x === 'number' && Number.isFinite(x));
115
+ function motionOk(mo, places) {
116
+ 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;
117
+ const n = mo.items.length, item = (i) => Number.isInteger(i) && i >= -1 && i < n;
118
+ if (mo.items.some((x) => !Array.isArray(x) || typeof x[0] !== 'string' || !(x.length === 1 || nums(x.slice(1), 12)))) return false;
119
+ 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)
120
+ || !Array.isArray(j.dofs) || j.dofs.length !== DOFS[j.type].length || !j.dofs.every((d) => nums(d, 3))
121
+ || (j.type === 'path' && !(Array.isArray(j.path) && j.path.length >= 2 && j.path.length <= LIMITS.places && j.path.every((p) => nums(p, 3))))
122
+ || (j.follow != null && !(Array.isArray(j.follow) && typeof j.follow[0] === 'string' && nums(j.follow.slice(1)))))) return false;
123
+ if (!Array.isArray(mo.part) || mo.part.length !== places || !mo.part.every(item)) return false;
124
+ 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;
125
+ return mo.allow == null || (Array.isArray(mo.allow) && mo.allow.every((x) => Array.isArray(x) && x.length === 2 && x.every((i) => Number.isInteger(i) && i >= 0 && i < places)));
126
+ }
127
+
110
128
  // Placed shapes -> one model ({ q, p, t, parts }), each copy its own part.
111
129
  export function expand(m) {
112
130
  const { shapes, place, ...meta } = m;
@@ -143,6 +161,122 @@ export function triangles(m, part) {
143
161
  // The model's parts, always at least one: [[name, role, label, first, count]]
144
162
  export const partsOf = (m) => (m.parts?.length ? m.parts : [['body', 'part', m.title || 'model', 0, m.t.length / 3]]);
145
163
 
164
+ // ---------- motion ----------
165
+ // Joints between items, so a page (or a tool) can move them: an assembly's hinges, rails and ball joints.
166
+ // motion: { items: [[name, …12?]], joints: [joint], poses: { name: { joint: value } }, pose?, part: [item per place],
167
+ // allow?: [[place, place]] }
168
+ // An item with 12 numbers sits there (a 3 × 4 transform by rows, as in place); one without is placed by the joint
169
+ // whose child it is. part[n] is the item place n moves with (-1: it never moves); allow pairs may overlap (press fits).
170
+ // joint: { id, type, parent (item, -1 the world), child (item), a (the parent's anchor, 12 numbers, in its own
171
+ // frame), b (the child's anchor), dofs: [[min, max, value]], label?, follow?: [joint id, ratio, offset],
172
+ // path?: [[x, y, z], …], cone? }. At value 0 the child's anchor lies on the parent's: same place, same axes.
173
+ // Types and their dofs (angles in degrees, distances in mm, along and about the anchor's z axis):
174
+ // fixed []; revolute [angle]; prismatic [distance]; cylindrical [angle, distance]; ball [x, y, z] (turned about x,
175
+ // then y, then z; cone: how far z may tip, in degrees); path [distance along path, a polyline in the parent's anchor
176
+ // frame, the child's z along it]
177
+ export const DOFS = { fixed: [], revolute: ['angle'], prismatic: ['distance'], cylindrical: ['angle', 'distance'], ball: ['angle', 'angle', 'angle'], path: ['distance'] };
178
+ const I3 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0];
179
+ // 3 × 4 transforms by rows: m · n, the inverse of a rigid one, and the turns and moves they're made from
180
+ /** m · n, two 3 × 4 transforms by rows @param {number[]} m @param {number[]} n @returns {number[]} */
181
+ export function mul(m, n) {
182
+ const o = [];
183
+ 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));
184
+ return o;
185
+ }
186
+ /** The inverse of a rigid 3 × 4 transform @param {number[]} m @returns {number[]} */
187
+ export function inv(m) {
188
+ const t = [m[3], m[7], m[11]], o = [];
189
+ 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])); }
190
+ return o;
191
+ }
192
+ const D = Math.PI / 180;
193
+ 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]; };
194
+ 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]; };
195
+ 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]; };
196
+ const tz = (d) => [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, d];
197
+ // Turned about x, then y, then z (degrees), as an assembly's rotate
198
+ /** @type {(degrees: number[]) => number[]} */
199
+ export const turn = ([x, y, z]) => mul(rz(z), mul(ry(y), rx(x)));
200
+ // 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)
201
+ /** @param {number[]} at @param {number[]} [axis] @param {number[]} [ref] @returns {number[]} */
202
+ export function frame(at, axis = [0, 0, 1], ref) {
203
+ 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); };
204
+ 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]];
205
+ let r = ref || (Math.abs(z[0]) > 0.9 ? [0, 1, 0] : [1, 0, 0]);
206
+ const x = unit(r.map((v, k) => v - dot(r, z) * z[k])), y = cross(z, x);
207
+ 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]];
208
+ }
209
+ // The turn that takes z to v, the shortest way
210
+ function zTo(v) {
211
+ const l = Math.hypot(...v), [x, y, z] = v.map((c) => c / l), c = z;
212
+ if (c < -1 + 1e-9) return rx(180);
213
+ const k = 1 / (1 + c); // Rodrigues, about z × v = (-y, x, 0)
214
+ return [1 - x * x * k, -x * y * k, x, 0, -x * y * k, 1 - y * y * k, y, 0, -x, -y, c, 0];
215
+ }
216
+ // Along a polyline (distance s, kept within it): where, with z along the segment there
217
+ function along(points, s) {
218
+ let left = Math.max(0, s);
219
+ for (let i = 1; i < points.length; i++) {
220
+ 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);
221
+ 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; }
222
+ left -= l;
223
+ }
224
+ return [...I3];
225
+ }
226
+ /** @type {(points: number[][]) => number} */
227
+ 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);
228
+ // What a joint does at its values: the child's anchor, in the parent's anchor frame
229
+ /** @param {{ id: string, type: string, path?: number[][] }} j @param {number[]} v @returns {number[]} */
230
+ export function jointMatrix(j, v) {
231
+ switch (j.type) {
232
+ case 'fixed': return [...I3];
233
+ case 'revolute': return rz(v[0]);
234
+ case 'prismatic': return tz(v[0]);
235
+ case 'cylindrical': return mul(tz(v[1]), rz(v[0]));
236
+ case 'ball': return turn(v);
237
+ case 'path': return along(j.path, v[0]);
238
+ default: throw new Error(`joint ${j.id}: no joint type "${j.type}" (${Object.keys(DOFS).join(', ')})`);
239
+ }
240
+ }
241
+ // Every joint's values: each at its default, then the pose's, then the joints that follow another
242
+ // pose: a name in motion.poses, or { joint: value }; values: [number] per joint, by id
243
+ /** @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[]>} */
244
+ export function jointValues(motion, pose) {
245
+ const set = typeof pose === 'string' ? motion.poses?.[pose] : pose || (motion.pose ? motion.poses?.[motion.pose] : {});
246
+ if (typeof pose === 'string' && !set) throw new Error(`no pose "${pose}" (poses: ${Object.keys(motion.poses || {}).join(', ') || 'none'})`);
247
+ const out = {};
248
+ for (const j of motion.joints) {
249
+ const given = set?.[j.id];
250
+ out[j.id] = given == null ? j.dofs.map((d) => d[2]) : [].concat(given).map(Number);
251
+ 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'}`);
252
+ }
253
+ const done = new Set(), follow = (j, seen = []) => {
254
+ if (!j.follow || done.has(j.id)) return out[j.id];
255
+ if (seen.includes(j.id)) throw new Error(`joints follow each other round: ${[...seen, j.id].join(' → ')}`);
256
+ const [lead, ratio = 1, offset = 0] = j.follow, l = motion.joints.find((x) => x.id === lead);
257
+ if (!l) throw new Error(`joint ${j.id} follows "${lead}", which isn't a joint`);
258
+ out[j.id] = follow(l, [...seen, j.id]).map((x) => x * ratio + offset).slice(0, j.dofs.length);
259
+ done.add(j.id); return out[j.id];
260
+ };
261
+ for (const j of motion.joints) follow(j);
262
+ return out;
263
+ }
264
+ // Where every item is at these values (jointValues): [12 numbers] per item, a joint's child from its parent
265
+ /** @param {{ items: any[][], joints: any[] }} motion @param {Record<string, number[]>} values @returns {number[][]} */
266
+ export function placeItems(motion, values) {
267
+ const by = new Map(motion.joints.map((j) => [j.child, j])), out = [];
268
+ const at = (i, seen = []) => {
269
+ if (out[i]) return out[i];
270
+ if (i < 0) return I3;
271
+ 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)`);
272
+ const j = by.get(i), item = motion.items[i];
273
+ 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)); }
274
+ return (out[i] = mul(mul(mul(at(j.parent, [...seen, i]), j.a), jointMatrix(j, values[j.id])), inv(j.b)));
275
+ };
276
+ motion.items.forEach((_, i) => at(i));
277
+ return out;
278
+ }
279
+
146
280
  // ---------- files ----------
147
281
  // cap@0.6.0.stl; with what was picked, if not everything: staggered-cap-2-4.3mf
148
282
  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}`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/model-link",
3
- "version": "0.1.4",
3
+ "version": "0.2.0",
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": {