@rulecad/model-link 0.3.1 → 0.3.3

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.d.mts CHANGED
@@ -95,9 +95,12 @@ export function stl(m: Model, keep?: Set<number> | ((part: any[], index: number)
95
95
  export function threemf(m: Model, keep?: Set<number> | ((part: any[], index: number) => boolean), { generator }?: {
96
96
  generator?: string;
97
97
  }): Promise<Uint8Array>;
98
- export function mesh(tris: any): {
99
- verts: any[];
100
- tris: any[][];
98
+ /** @param {Triangle[]} tris @param {{ budget: number }} [work] @returns {{ verts: number[][], tris: number[][] }} */
99
+ export function mesh(tris: Triangle[], work?: {
100
+ budget: number;
101
+ }): {
102
+ verts: number[][];
103
+ tris: number[][];
101
104
  };
102
105
  /** @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) */
103
106
  export function bambu3mf(objects: {
@@ -120,7 +123,7 @@ export function bambu3mf(objects: {
120
123
  */
121
124
  export function zip(entries: [string, string][]): Promise<Uint8Array>;
122
125
  /** @typedef {[[number, number, number], [number, number, number], [number, number, number]]} Triangle corners in mm, counter-clockwise seen from outside, Z up */
123
- /** @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 */
126
+ /** @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 */
124
127
  export const VERSION: 1;
125
128
  export namespace LIMITS {
126
129
  let vertices: number;
@@ -130,6 +133,8 @@ export namespace LIMITS {
130
133
  let views: number;
131
134
  let viewSize: number;
132
135
  let sheet: number;
136
+ let fab: number;
137
+ let fabSize: number;
133
138
  let size: number;
134
139
  let text: number;
135
140
  let bytes: number;
@@ -152,6 +157,7 @@ export const turn: (degrees: number[]) => number[];
152
157
  /** @type {(points: number[][]) => number} */
153
158
  export const pathLength: (points: number[][]) => number;
154
159
  export function filename(m: any, ext: any, picked?: string): string;
160
+ export function fabName(name: any): string;
155
161
  export function thingOf(name: any): string;
156
162
  /**
157
163
  * corners in mm, counter-clockwise seen from outside, Z up
@@ -163,6 +169,10 @@ export type Model = {
163
169
  src?: string;
164
170
  material?: string;
165
171
  orientation?: string;
172
+ fab?: {
173
+ name: string;
174
+ zip: string;
175
+ }[];
166
176
  rules?: [string, any, string][];
167
177
  q?: number;
168
178
  p?: number[];
package/model-link.mjs CHANGED
@@ -11,6 +11,8 @@
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.
@@ -19,10 +21,10 @@
19
21
  // "1." is the format version: newer pages must keep reading old links.
20
22
 
21
23
  /** @typedef {[[number, number, number], [number, number, number], [number, number, number]]} Triangle corners in mm, counter-clockwise seen from outside, Z up */
22
- /** @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 */
23
25
 
24
26
  export const VERSION = 1;
25
- 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
26
28
  size: 1e5, // mm: no corner further than this from the origin (a link is a part or an assembly, not a map)
27
29
  text: 2000, // characters in a title, a name or a label
28
30
  bytes: 160e6 }; // of a link once unpacked: its views at their largest, and the biggest model, with room to spare
@@ -132,12 +134,20 @@ function problems(m) {
132
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'];
133
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})`];
134
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'];
135
139
  if (m.motion != null && !motionOk(m.motion, m.parts?.length ?? 1)) return ['broken motion'];
136
140
  if (m.task != null && !taskOk(m.task)) return ['broken task'];
137
141
  if (m.steps != null && !stepsOk(m.steps)) return ['broken step file'];
138
142
  if (m.wires != null && !wiresOk(m.wires)) return ['broken wires'];
139
143
  if (m.build != null && !plain(m.build)) return ['broken build page'];
144
+ if (m.show != null && m.show !== 'built') return ['broken show'];
140
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'];
141
151
  return [];
142
152
  }
143
153
 
@@ -178,6 +188,7 @@ function motionOk(mo, places) {
178
188
  // point] | null], stroke matching a block's.
179
189
  // wires: [[id, [[item (index, -1 fixed), x, y, z], …]]], routes drawn faint, moving with their items; never parts.
180
190
  // build: the build page's content, read as text and numbers (the shopping list, plates, wiring, steps, settings).
191
+ // show (optional): 'built', an assembly shown as the thing built: its references drawn solid, as its parts are.
181
192
  const INT = 2 ** 31;
182
193
  const int = (x) => Number.isInteger(x) && Math.abs(x) < INT;
183
194
  const text = (x) => typeof x === 'string' && x.length <= LIMITS.text;
@@ -394,6 +405,11 @@ export function placeItems(motion, values) {
394
405
  // cap@0.6.0.stl; with what was picked, if not everything: staggered-cap-2-4.3mf
395
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}`;
396
407
 
408
+ // A fab zip's name as JLCPCB's upload takes it: letters, digits, _ and - before .zip, and none of the words it refuses
409
+ // (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`;
412
+
397
413
  // Which parts a file holds: all the printed ones (references are only there to check a fit), or the indices picked
398
414
  // keep: which parts, as a Set of their places in partsOf(m), or a function of each part and its place
399
415
  const chosen = (m, keep) => partsOf(m).filter((x, i) => (keep ? (typeof keep === 'function' ? keep(x, i) : keep.has(i)) : x[1] !== 'reference'));
@@ -424,7 +440,8 @@ export function fromSTL(bytes) {
424
440
  // generator: the name the file says made it (rulecad by default)
425
441
  /** 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} */
426
442
  export function stl(m, keep, { generator = 'rulecad' } = {}) {
427
- const tris = chosen(m, keep).flatMap((x) => { const { verts, tris: t } = mesh(triangles(m, x)); return t.map((ids) => ids.map((i) => verts[i])); }), buf = new ArrayBuffer(84 + 50 * tris.length), dv = new DataView(buf);
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);
428
445
  const head = `${generator} ${m.src || m.title || ''}`.slice(0, 80);
429
446
  for (let i = 0; i < head.length; i++) dv.setUint8(i, head.charCodeAt(i) & 0x7f);
430
447
  dv.setUint32(80, tris.length, true);
@@ -476,7 +493,10 @@ const num = (x) => String(Number(x.toFixed(5)));
476
493
  // and its repair can fill a legend's letters with sheets. So a triangle with a loose corner lying along its open edge is
477
494
  // split there, one corner at a time until none is left, and any pinhole still open (a loop of open edges less than a
478
495
  // millimetre round) is closed with a fan. Each part comes out as one closed body per piece (a keycap; each letter).
479
- export function mesh(tris) {
496
+ // work: a mend budget shared by the parts of one file ({ budget }, spent as it goes), so a file of many parts cannot
497
+ // spend a budget for each (stl, threemf and bambu3mf pass one); on its own a part gets a budget sized from it.
498
+ /** @param {Triangle[]} tris @param {{ budget: number }} [work] @returns {{ verts: number[][], tris: number[][] }} */
499
+ export function mesh(tris, work) {
480
500
  const MERGE = 1e-3, verts = [], index = new Map(), out = [];
481
501
  const key = (v) => v.map((c) => Math.round(c / MERGE)).join(',');
482
502
  const at = (v) => { // the same corner as one already seen within MERGE (it may sit across a rounding boundary)
@@ -491,30 +511,78 @@ export function mesh(tris) {
491
511
  const area2 = (ids) => { const [a, b, c] = ids.map((i) => verts[i]); return Math.hypot(...cross(sub(b, a), sub(c, a))); };
492
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); }
493
513
 
494
- // Mend: split a triangle at a loose corner lying along its open edge, one corner at a time, until none is left
514
+ // Mend: split a triangle at a loose corner lying along its open edge, one corner at a time, until none is left.
515
+ // The loose corners are filed in 1 mm cells. Each open edge takes the cheapest of three searches: every cell of its
516
+ // box (a short or square-on edge), only the cells its line passes through and their neighbours (a long slanted edge:
517
+ // a corner within TOL of the line is at most one cell off it, so the work grows with the edge's length), or a plain
518
+ // look at every loose corner (few loose corners). (It always searched the box, which grows with the cube of a slanted
519
+ // edge's length: a short link holding one long diagonal triangle froze the writers for minutes.) All three find the
520
+ // same corner: the nearest the line, ties going to the corner first in cell order, as the box search always did.
521
+ // The searches share a work budget sized from the mesh, cells and corners looked at across all passes, so a mesh
522
+ // made to be slow (thousands of long open edges among thousands of loose corners) cannot freeze the writers: once
523
+ // it is spent, the edges left are not mended and are written as they are.
495
524
  const TOL = 2e-3, CELL = 1, cell = (x) => Math.floor(x / CELL);
525
+ let budget = work ? work.budget : 2e6 + 100 * out.length; // cells and corners looked at, across all passes
496
526
  for (let pass = 0; pass < 50; pass++) {
497
527
  const edges = new Set(); for (const [a, b, c] of out) edges.add(`${a},${b}`).add(`${b},${c}`).add(`${c},${a}`);
498
528
  const isOpen = (a, b) => !edges.has(`${b},${a}`), loose = new Set();
499
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);
500
530
  if (!loose.size) break;
501
- const grid = new Map();
502
- for (const i of loose) { const k = verts[i].map(cell).join(','); if (!grid.has(k)) grid.set(k, []); grid.get(k).push(i); }
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); }
533
+ // Which of two corners the box search met first: the lower cell (x, then y, then z), then the one filed first
534
+ 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; }
536
+ return rank.get(i) < rank.get(j);
537
+ };
503
538
  // The loose corner along a -> b nearest the line, if any
504
539
  const along = (a, b) => {
505
- const p = verts[a], d = sub(verts[b], p), len = Math.sqrt(dot(d, d));
506
- const lo = [0, 1, 2].map((k) => cell(Math.min(p[k], verts[b][k]) - TOL)), hi = [0, 1, 2].map((k) => cell(Math.max(p[k], verts[b][k]) + TOL));
507
- let best = null;
508
- for (let x = lo[0]; x <= hi[0]; x++) for (let y = lo[1]; y <= hi[1]; y++) for (let z = lo[2]; z <= hi[2]; z++) {
509
- for (const i of grid.get(`${x},${y},${z}`) || []) {
510
- if (i === a || i === b) continue;
511
- const w = sub(verts[i], p), t = dot(w, d) / (len * len);
512
- if (t * len < TOL || (1 - t) * len < TOL) continue;
513
- const off = Math.hypot(...cross(w, d)) / len;
514
- if (off < TOL && (!best || off < best[1])) best = [i, off];
540
+ const p = verts[a], q = verts[b], d = sub(q, p), len = Math.sqrt(dot(d, d));
541
+ 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;
543
+ const consider = (i) => {
544
+ if (i === a || i === b) return;
545
+ const w = sub(verts[i], p), t = dot(w, d) / (len * len);
546
+ if (t * len < TOL || (1 - t) * len < TOL) return;
547
+ const off = Math.hypot(...cross(w, d)) / len;
548
+ if (off < TOL && (!best || off < best[1] || (off === best[1] && before(i, best[0])))) best = [i, off];
549
+ };
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);
553
+ const cost = Math.min(box, walk, looseList.length);
554
+ if (cost > budget) return null; // the budget is spent: this edge is left open
555
+ budget -= cost;
556
+ if (cost === looseList.length && cost < box && cost < walk) { for (const i of looseList) consider(i); return best; }
557
+ // The grid searches pay for each corner they find in a cell too: many loose corners packed in a few cells would
558
+ // otherwise cost every edge there all of them, with only its cells counted (a few kilobytes of tiny triangles in
559
+ // 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}`) || []);
563
+ return spent ? null : best;
564
+ }
565
+ // 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) || []);
515
572
  }
573
+ };
574
+ const c = [...from], step = d.map(Math.sign);
575
+ const tMax = [0, 1, 2].map((k) => (d[k] ? ((c[k] + (d[k] > 0 ? 1 : 0)) * CELL - p[k]) / d[k] : Infinity));
576
+ const tDelta = [0, 1, 2].map((k) => (d[k] ? CELL / Math.abs(d[k]) : Infinity));
577
+ look(c);
578
+ 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];
582
+ look(c);
516
583
  }
517
- return best;
584
+ look(to);
585
+ return spent ? null : best;
518
586
  };
519
587
  let split = 0;
520
588
  const n = out.length;
@@ -533,6 +601,7 @@ export function mesh(tris) {
533
601
  }
534
602
  if (!split) break;
535
603
  }
604
+ if (work) work.budget = budget;
536
605
  // What's left are pinholes: a sliver face the booleans lost, a loop of open edges a fraction of a millimetre round.
537
606
  // Close each with a fan.
538
607
  const kept = out.filter((ids) => area2(ids) > 1e-9), edges = new Set();
@@ -563,11 +632,12 @@ const NS = 'xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02" xm
563
632
  /** @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) */
564
633
  export async function bambu3mf(objects, { centre = [128, 128], generator = 'rulecad', date, title } = {}) {
565
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
566
636
  let id = 0;
567
637
  objects.forEach((o, n) => {
568
638
  const path = `/3D/Objects/object_${n + 1}.model`, parts = o.parts.map((p) => ({ ...p, id: ++id }));
569
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`
570
- + parts.map((p) => ` <object id="${p.id}" p:UUID="${uuid(p.id, 1)}" type="model">${meshXml(mesh(p.triangles))}</object>\n`).join('') + ' </resources>\n <build/>\n</model>\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';
571
641
  rels.push(`<Relationship Target="${path}" Id="rel-${n + 1}" Type="http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"/>`);
572
642
  const parent = 100000 + n + 1;
573
643
  resources.push(` <object id="${parent}" p:UUID="${uuid(n + 1, 0)}" type="model">\n <components>\n`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/model-link",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
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": {