inkless 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +65 -2
- package/bin/inkless.js +10 -0
- package/console-dist/assets/BlueprintTool-CLWuM21a.js +4226 -0
- package/console-dist/assets/index-CIqLZU6s.js +33 -0
- package/console-dist/assets/index-Dv7Gg9qm.css +1 -0
- package/console-dist/favicon.svg +11 -0
- package/console-dist/index.html +18 -0
- package/native/linux/rfcomm.py +84 -0
- package/native/macos/build/InklessBluetooth.app/Contents/Info.plist +26 -0
- package/native/macos/build/InklessBluetooth.app/Contents/MacOS/InklessBluetooth +0 -0
- package/native/macos/build/InklessBluetooth.app/Contents/_CodeSignature/CodeResources +115 -0
- package/package.json +60 -4
- package/skills/inkless/SKILL.md +213 -0
- package/src/core/bits.js +143 -0
- package/src/core/blueprint/demos.js +119 -0
- package/src/core/blueprint/geometry.js +232 -0
- package/src/core/blueprint/index.js +100 -0
- package/src/core/blueprint/layout.js +210 -0
- package/src/core/blueprint/mesh.js +101 -0
- package/src/core/blueprint/methods.js +95 -0
- package/src/core/blueprint/remesh.js +250 -0
- package/src/core/blueprint/slice.js +134 -0
- package/src/core/blueprint/unfold.js +185 -0
- package/src/core/design/codes.js +39 -0
- package/src/core/design/filters.js +109 -0
- package/src/core/design/render.js +317 -0
- package/src/core/design/schema.js +132 -0
- package/src/core/formats/fit.js +46 -0
- package/src/core/formats/index.js +210 -0
- package/src/core/formats/library.js +341 -0
- package/src/core/formats/share.js +65 -0
- package/src/core/index.js +15 -0
- package/src/core/printers/hp6.js +160 -0
- package/src/core/printers/index.js +14 -0
- package/src/core/printers/pm290.js +115 -0
- package/src/core/session.js +56 -0
- package/src/node/artwork.js +33 -0
- package/src/node/cli.js +430 -0
- package/src/node/console/actions.js +30 -0
- package/src/node/console/client.js +68 -0
- package/src/node/console/paths.js +8 -0
- package/src/node/console/server.js +286 -0
- package/src/node/design.js +99 -0
- package/src/node/formats.js +39 -0
- package/src/node/frames.js +93 -0
- package/src/node/index.js +6 -0
- package/src/node/kit.js +12 -0
- package/src/node/skill.js +44 -0
- package/src/node/transports/index.js +21 -0
- package/src/node/transports/linux.js +52 -0
- package/src/node/transports/macos.js +81 -0
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// Pieces -> labels. Each piece gets its own label, turned a quarter if that
|
|
3
|
+
// saves labels. A piece too big for one label is split into a grid of tiles,
|
|
4
|
+
// with a dashed cut line and triangles at each cut to line the labels up.
|
|
5
|
+
import { area, bounds, clipOutline, clipRing, clipSegment, inside, lerp, spans } from "./geometry.js";
|
|
6
|
+
|
|
7
|
+
/** @typedef {import("./index.js").Part} Part @typedef {import("./geometry.js").Point} Point @typedef {import("./geometry.js").Rect} Rect */
|
|
8
|
+
/** @typedef {{ part: Part, hint: string, cross: boolean }} Piece hint: caption words; cross: draw the model's centre axis */
|
|
9
|
+
|
|
10
|
+
const MARGIN_MM = 1.5;
|
|
11
|
+
const LINE_MM = 0.5; // the outline to trace
|
|
12
|
+
const THIN_MM = 0.25; // ribs, folds, crosses and cut marks
|
|
13
|
+
const PM290 = { printer: "pm290", width: 48, band: 3, minWindow: 6, idMm: 4.5, idPt: 9, captionPt: 6, noteMm: 2.4, notePt: 6 };
|
|
14
|
+
/**
|
|
15
|
+
* The labels a blueprint can use. The roll has no fixed height: each label
|
|
16
|
+
* is as long as its piece (up to maxHeight).
|
|
17
|
+
* @type {Record<import("./index.js").LabelId, { printer: "pm290" | "hp6", width: number, height?: number, maxHeight?: number, band: number, minWindow: number, idMm: number, idPt: number, captionPt: number, noteMm: number, notePt: number }>}
|
|
18
|
+
*/
|
|
19
|
+
export const LABELS = {
|
|
20
|
+
roll: { ...PM290, maxHeight: 500 },
|
|
21
|
+
"48x48": { ...PM290, height: 48 },
|
|
22
|
+
"48x30": { ...PM290, height: 30 },
|
|
23
|
+
hp6: { printer: "hp6", width: 36, height: 12, band: 2.2, minWindow: 0, idMm: 3.4, idPt: 7, captionPt: 5, noteMm: 2, notePt: 5 },
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/** The room for a piece on one label: width and height in mm. @param {keyof typeof LABELS} label */
|
|
27
|
+
export function labelArea(label) {
|
|
28
|
+
const L = LABELS[label];
|
|
29
|
+
return [L.width - 2 * MARGIN_MM, (L.height ?? L.maxHeight) - 2 * MARGIN_MM - L.band];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const r2 = (n) => Math.round(n * 100) / 100;
|
|
33
|
+
const near = (a, b) => Math.abs(a[0] - b[0]) < 1e-6 && Math.abs(a[1] - b[1]) < 1e-6;
|
|
34
|
+
|
|
35
|
+
/** SVG path data for polylines; one that ends where it starts is closed. @param {Point[][]} lines */
|
|
36
|
+
function pathData(lines) {
|
|
37
|
+
return lines.map((pts) => {
|
|
38
|
+
const closed = pts.length > 2 && near(pts[0], pts[pts.length - 1]);
|
|
39
|
+
const body = (closed ? pts.slice(0, -1) : pts).map((p, i) => `${i ? "L" : "M"}${r2(p[0])} ${r2(p[1])}`).join("");
|
|
40
|
+
return closed ? `${body}Z` : body;
|
|
41
|
+
}).join("");
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** A point well inside the piece for its name: the centroid, or the middle of the widest stretch through it. */
|
|
45
|
+
function labelPoint(polygons) {
|
|
46
|
+
const outer = polygons[0];
|
|
47
|
+
let a = 0, cx = 0, cy = 0;
|
|
48
|
+
outer.forEach((p, i) => {
|
|
49
|
+
const q = outer[(i + 1) % outer.length], f = p[0] * q[1] - q[0] * p[1];
|
|
50
|
+
a += f; cx += (p[0] + q[0]) * f; cy += (p[1] + q[1]) * f;
|
|
51
|
+
});
|
|
52
|
+
const c = [cx / (3 * a), cy / (3 * a)];
|
|
53
|
+
if (inside(polygons, c)) return c;
|
|
54
|
+
const widest = spans(polygons, 1, c[1]).sort((s, t) => t[1] - t[0] - (s[1] - s[0]))[0];
|
|
55
|
+
return widest ? [(widest[0] + widest[1]) / 2, c[1]] : outer[0];
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Level ribs `spacing` apart across the piece, centred, clipped to it. */
|
|
59
|
+
function ribLines(polygons, spacing, minLen) {
|
|
60
|
+
const b = bounds(polygons), mid = (b.y0 + b.y1) / 2, lines = [];
|
|
61
|
+
for (let v = mid - Math.floor((mid - b.y0) / spacing) * spacing; v < b.y1; v += spacing) {
|
|
62
|
+
for (const [u0, u1] of spans(polygons, 1, v)) if (u1 - u0 > minLen) lines.push([[u0, v], [u1, v]]);
|
|
63
|
+
}
|
|
64
|
+
return lines;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Segment ab without the part inside rect. @param {Point[]} seg @param {Rect} rect */
|
|
68
|
+
function around([a, b], rect) {
|
|
69
|
+
const t = clipSegment(a, b, rect);
|
|
70
|
+
if (!t) return [[a, b]];
|
|
71
|
+
return [[0, t[0]], [t[1], 1]].filter(([s, e]) => e - s > 1e-6).map(([s, e]) => [lerp(a, b, s), lerp(a, b, e)]);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Dashes along ab. @param {Point} a @param {Point} b */
|
|
75
|
+
function dashes(a, b, on = 1, off = 1) {
|
|
76
|
+
const len = Math.hypot(b[0] - a[0], b[1] - a[1]), out = [];
|
|
77
|
+
for (let d = 0; d < len; d += on + off) out.push([lerp(a, b, d / len), lerp(a, b, Math.min(d + on, len) / len)]);
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Dashed cut lines and alignment triangles (tip on the cut) for a tile of
|
|
83
|
+
* size w x h; `sides` says which edges were cut.
|
|
84
|
+
*/
|
|
85
|
+
function cutMarks(w, h, sides) {
|
|
86
|
+
const edges = [
|
|
87
|
+
sides.left && { a: [0, 0], b: [0, h], inward: [1, 0] },
|
|
88
|
+
sides.right && { a: [w, 0], b: [w, h], inward: [-1, 0] },
|
|
89
|
+
sides.top && { a: [0, 0], b: [w, 0], inward: [0, 1] },
|
|
90
|
+
sides.bottom && { a: [0, h], b: [w, h], inward: [0, -1] },
|
|
91
|
+
].filter(Boolean);
|
|
92
|
+
return edges.flatMap(({ a, b, inward }) => {
|
|
93
|
+
const len = Math.hypot(b[0] - a[0], b[1] - a[1]), across = [inward[1], inward[0]];
|
|
94
|
+
const triangles = (len > 6 ? [0.2, 0.8] : [0.5]).map((f) => {
|
|
95
|
+
const tip = lerp(a, b, f), base = (s) => [tip[0] + inward[0] + across[0] * 0.7 * s, tip[1] + inward[1] + across[1] * 0.7 * s];
|
|
96
|
+
return [tip, base(1), base(-1), tip];
|
|
97
|
+
});
|
|
98
|
+
return [...dashes(a, b), ...triangles];
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** A triangle shrunk toward its incentre by `d` on every side, so filled faces keep a white fold line between them. */
|
|
103
|
+
function inset(tri, d) {
|
|
104
|
+
const sides = tri.map((p, i) => Math.hypot(...[0, 1].map((k) => tri[(i + 2) % 3][k] - tri[(i + 1) % 3][k])));
|
|
105
|
+
const sum = sides[0] + sides[1] + sides[2], r = (2 * Math.abs(area(tri))) / sum;
|
|
106
|
+
if (r < 2 * d) return tri;
|
|
107
|
+
const c = [0, 1].map((k) => tri.reduce((acc, p, i) => acc + p[k] * sides[i], 0) / sum), f = (r - d) / r;
|
|
108
|
+
return tri.map((p) => [c[0] + (p[0] - c[0]) * f, c[1] + (p[1] - c[1]) * f]);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* @param {Piece} piece @param {Required<import("./index.js").BlueprintSettings>} s
|
|
113
|
+
* @returns {import("../design/schema.js").Page[]}
|
|
114
|
+
*/
|
|
115
|
+
function piecePages({ part, hint, cross }, s) {
|
|
116
|
+
const L = LABELS[s.label], [areaW, areaH] = labelArea(s.label);
|
|
117
|
+
const b = bounds(part.polygons), w = b.x1 - b.x0, h = b.y1 - b.y0;
|
|
118
|
+
const grid = (sw, sh) => [Math.ceil(sw / areaW - 1e-9), Math.ceil(sh / areaH - 1e-9)];
|
|
119
|
+
const count = (sw, sh) => grid(sw, sh)[0] * grid(sw, sh)[1];
|
|
120
|
+
// The sheet: the piece with y down, origin at its top-left, maybe turned a quarter.
|
|
121
|
+
const turned = count(h, w) < count(w, h);
|
|
122
|
+
const toSheet = turned ? (p) => [b.y1 - p[1], b.x1 - p[0]] : (p) => [p[0] - b.x0, b.y1 - p[1]];
|
|
123
|
+
const [W, H] = turned ? [h, w] : [w, h];
|
|
124
|
+
const rings = part.polygons.map((ring) => ring.map(toSheet));
|
|
125
|
+
|
|
126
|
+
const [cx, cy] = toSheet(labelPoint(part.polygons)), idW = Math.max(8, part.id.length * 2.3 + 2);
|
|
127
|
+
const fitIn = (c, size, room) => (size >= room ? (room - size) / 2 : Math.min(Math.max(c - size / 2, 0), room - size));
|
|
128
|
+
const idBox = { x0: fitIn(cx, idW, W), y0: fitIn(cy, L.idMm, H) };
|
|
129
|
+
Object.assign(idBox, { x1: idBox.x0 + idW, y1: idBox.y0 + L.idMm });
|
|
130
|
+
|
|
131
|
+
const ribs = s.fill === "ribs" && !part.faces ? ribLines(part.polygons, s.ribSpacingMm, s.penMm).flatMap((seg) => around(seg.map(toSheet), idBox)) : [];
|
|
132
|
+
const axis = cross && 0 >= b.x0 && 0 <= b.x1 && 0 >= b.y0 && 0 <= b.y1
|
|
133
|
+
? [[[-1.5, 0], [1.5, 0]], [[0, -1.5], [0, 1.5]]].map((seg) => seg.map(toSheet))
|
|
134
|
+
: [];
|
|
135
|
+
// Nets: ridge folds as thin lines, valley folds dashed; filled nets show folds as white gaps instead.
|
|
136
|
+
const folds = s.fill === "solid" ? [] : (part.folds ?? []).flatMap((seg, i) => {
|
|
137
|
+
const [a, b2] = seg.map(toSheet);
|
|
138
|
+
return part.valleys?.[i] ? dashes(a, b2, 1.2, 0.8) : [[a, b2]];
|
|
139
|
+
});
|
|
140
|
+
const solidRings = s.fill === "solid" && part.faces ? part.faces.map((tri) => inset(tri, 0.2).map(toSheet)) : rings;
|
|
141
|
+
const notes = (part.notes ?? []).map((note) => ({ text: note.text, at: toSheet(note.at) }));
|
|
142
|
+
|
|
143
|
+
const [cols, rows] = grid(W, H), tw = W / cols, th = H / rows, n = cols * rows;
|
|
144
|
+
const pageH = L.height ?? Math.ceil((Math.max(th, L.minWindow) + 2 * MARGIN_MM + L.band) * 8) / 8;
|
|
145
|
+
const ox = (L.width - tw) / 2, oy = MARGIN_MM + (pageH - 2 * MARGIN_MM - L.band - th) / 2;
|
|
146
|
+
const pages = [];
|
|
147
|
+
for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) {
|
|
148
|
+
const k = r * cols + c + 1, pageId = n > 1 ? `${part.id}-${k}` : part.id;
|
|
149
|
+
const rect = { x0: c * tw, x1: c === cols - 1 ? W : (c + 1) * tw, y0: r * th, y1: r === rows - 1 ? H : (r + 1) * th };
|
|
150
|
+
const tileW = rect.x1 - rect.x0, tileH = rect.y1 - rect.y0;
|
|
151
|
+
const local = (/** @type {Point[][]} */ lines) => pathData(lines.map((pts) => pts.map((p) => [p[0] - rect.x0, p[1] - rect.y0])));
|
|
152
|
+
const clipped = (/** @type {Point[][]} */ segs) => segs.flatMap(([a, b2]) => {
|
|
153
|
+
const t = clipSegment(a, b2, rect);
|
|
154
|
+
return t ? [[lerp(a, b2, t[0]), lerp(a, b2, t[1])]] : [];
|
|
155
|
+
});
|
|
156
|
+
const path = (name, d, extra) => ({ id: `${pageId}-${name}`, type: "path", x: r2(ox), y: r2(oy), w: r2(tileW), h: r2(tileH), d, ...extra });
|
|
157
|
+
const shape = s.fill === "solid"
|
|
158
|
+
? solidRings.map((ring) => clipRing(ring, rect)).filter((ring) => ring.length > 2).map((ring) => [...ring, ring[0]])
|
|
159
|
+
: rings.flatMap((ring) => clipOutline(ring, rect));
|
|
160
|
+
const elements = [path("piece", local(shape), s.fill === "solid" ? { fill: true } : { strokeMm: LINE_MM })];
|
|
161
|
+
const ribsHere = clipped(ribs), axisHere = clipped(axis), foldsHere = clipped(folds);
|
|
162
|
+
if (ribsHere.length) elements.push(path("ribs", local(ribsHere), { strokeMm: THIN_MM }));
|
|
163
|
+
if (axisHere.length) elements.push(path("cross", local(axisHere), { strokeMm: THIN_MM }));
|
|
164
|
+
if (foldsHere.length) elements.push(path("folds", local(foldsHere), { strokeMm: THIN_MM }));
|
|
165
|
+
notes.forEach(({ text, at }, i) => {
|
|
166
|
+
if (at[0] < rect.x0 || at[0] > rect.x1 || at[1] < rect.y0 || at[1] > rect.y1) return;
|
|
167
|
+
const nw = text.length * L.noteMm * 0.62 + 0.6;
|
|
168
|
+
elements.push({
|
|
169
|
+
id: `${pageId}-edge${i + 1}`, type: "text", text, font: "mono", weight: 700, sizePt: L.notePt, align: "center",
|
|
170
|
+
x: r2(ox + fitIn(at[0] - rect.x0, nw, tileW)), y: r2(oy + fitIn(at[1] - rect.y0, L.noteMm, tileH)), w: r2(nw), h: L.noteMm,
|
|
171
|
+
...(s.fill === "solid" ? { invert: true } : {}),
|
|
172
|
+
});
|
|
173
|
+
});
|
|
174
|
+
const sides = { left: c > 0, right: c < cols - 1, top: r > 0, bottom: r < rows - 1 };
|
|
175
|
+
if (n > 1) elements.push(path("marks", pathData(cutMarks(tileW, tileH, sides)), { strokeMm: THIN_MM }));
|
|
176
|
+
|
|
177
|
+
const idX = (idBox.x0 + idBox.x1) / 2, idY = (idBox.y0 + idBox.y1) / 2;
|
|
178
|
+
if (idX >= rect.x0 && idX <= rect.x1 && idY >= rect.y0 && idY <= rect.y1) {
|
|
179
|
+
elements.push({
|
|
180
|
+
id: `${pageId}-name`, type: "text", text: part.id, font: "mono", weight: 700, sizePt: L.idPt, align: "center",
|
|
181
|
+
x: r2(ox + fitIn(idX - rect.x0, idW, tileW)), y: r2(oy + fitIn(idY - rect.y0, L.idMm, tileH)), w: r2(idW), h: L.idMm,
|
|
182
|
+
...(s.fill === "solid" ? { invert: true } : {}),
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
const join = Object.entries({ left: "<", right: ">", top: "^", bottom: "v" }).filter(([side]) => sides[side]).map(([, arrow]) => arrow).join(" ");
|
|
186
|
+
const caption = [`${part.id} ${k}/${n}`, s.printer === "pm290" && hint, join && `join ${join}`].filter(Boolean).join(" · ");
|
|
187
|
+
elements.push({
|
|
188
|
+
id: `${pageId}-caption`, type: "text", text: caption, font: "mono", sizePt: L.captionPt, align: "left",
|
|
189
|
+
x: MARGIN_MM, y: r2(pageH - MARGIN_MM - L.band), w: L.width - 2 * MARGIN_MM, h: L.band,
|
|
190
|
+
});
|
|
191
|
+
pages.push({ id: pageId, name: `${part.id} ${k}/${n}`, ...(L.height ? {} : { heightMm: pageH }), elements });
|
|
192
|
+
}
|
|
193
|
+
return pages;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Every piece on labels.
|
|
198
|
+
* @param {Piece[]} pieces @param {Parameters<typeof piecePages>[1]} s
|
|
199
|
+
* @returns {{ design: import("../design/schema.js").Design, tiled: string[] }}
|
|
200
|
+
*/
|
|
201
|
+
export function layout(pieces, s) {
|
|
202
|
+
const perPiece = pieces.map((piece) => piecePages(piece, s));
|
|
203
|
+
const pages = perPiece.flat();
|
|
204
|
+
const L = LABELS[s.label];
|
|
205
|
+
const size = { widthMm: L.width, heightMm: L.height ?? Math.max(...pages.map((p) => p.heightMm ?? 0)) };
|
|
206
|
+
return {
|
|
207
|
+
design: { version: 1, title: "3D pen blueprint", printer: s.printer, size, pages, blueprint: { ...s } },
|
|
208
|
+
tiled: pieces.filter((_, i) => perPiece[i].length > 1).map(({ part }) => part.id),
|
|
209
|
+
};
|
|
210
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// Mesh input and preparation: any model glyphcss reads (OBJ, STL, glTF/GLB,
|
|
3
|
+
// VOX) as a triangle soup, scaling to the real size, and splitting into closed
|
|
4
|
+
// shells (a model may be several overlapping solids).
|
|
5
|
+
import * as glyph from "@glyphcss/core";
|
|
6
|
+
|
|
7
|
+
/** @typedef {import("./index.js").Mesh} Mesh */
|
|
8
|
+
|
|
9
|
+
/** Model file types loadModel reads, by extension. */
|
|
10
|
+
export const MODEL_TYPES = /** @type {const} */ (["stl", "obj", "glb", "gltf", "vox"]);
|
|
11
|
+
|
|
12
|
+
// glyphcss scales every model to this size; makeBlueprint rescales it anyway.
|
|
13
|
+
const OPTIONS = { gridShift: 0 };
|
|
14
|
+
|
|
15
|
+
/** glyphcss polygons (Z up) -> triangle soup. @param {ReturnType<typeof glyph.parseObj>} result @param {string} format @returns {Mesh} */
|
|
16
|
+
function toMesh(result, format) {
|
|
17
|
+
const values = [];
|
|
18
|
+
for (const { vertices: v } of result.polygons) for (let k = 1; k + 1 < v.length; k++) values.push(...v[0], ...v[k], ...v[k + 1]);
|
|
19
|
+
result.dispose();
|
|
20
|
+
if (!values.length) throw new Error(`${format}: no complete triangles found`);
|
|
21
|
+
const positions = Float32Array.from(values);
|
|
22
|
+
if (positions.some((x) => !Number.isFinite(x))) throw new Error(`${format}: a vertex is not a number`);
|
|
23
|
+
return { positions };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const bytesOf = (/** @type {Uint8Array | ArrayBuffer} */ input) => (input instanceof Uint8Array ? input : new Uint8Array(input));
|
|
27
|
+
|
|
28
|
+
/** Binary or ASCII STL, Z up. @param {Uint8Array | ArrayBuffer | string} input */
|
|
29
|
+
export const parseStl = (input) => toMesh(glyph.parseStl(typeof input === "string" ? input : bytesOf(input), OPTIONS), "stl");
|
|
30
|
+
|
|
31
|
+
/** OBJ text (Y up, turned to Z up); polygons become triangle fans, materials are ignored. @param {string} text */
|
|
32
|
+
export const parseObj = (text) => toMesh(glyph.parseObj(text, OPTIONS), "obj");
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Read a model file by its name's extension. glTF must have its buffers
|
|
36
|
+
* inside the file (GLB, or base64 in the .gltf).
|
|
37
|
+
* @param {string} name @param {Uint8Array | ArrayBuffer | string} data
|
|
38
|
+
*/
|
|
39
|
+
export function loadModel(name, data) {
|
|
40
|
+
const type = name.toLowerCase().split(".").pop();
|
|
41
|
+
const bytes = () => (typeof data === "string" ? new TextEncoder().encode(data) : bytesOf(data));
|
|
42
|
+
if (type === "obj") return parseObj(typeof data === "string" ? data : new TextDecoder().decode(bytes()));
|
|
43
|
+
if (type === "stl") return parseStl(data);
|
|
44
|
+
if (type === "glb" || type === "gltf") {
|
|
45
|
+
try {
|
|
46
|
+
return toMesh(glyph.parseGltf(bytes(), OPTIONS), type);
|
|
47
|
+
} catch (e) {
|
|
48
|
+
if (/external buffer/.test(String(e))) throw new Error(`${name}: its data is in a separate file; save the model as .glb instead`);
|
|
49
|
+
throw e;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
if (type === "vox") {
|
|
53
|
+
const b = bytes();
|
|
54
|
+
return toMesh(glyph.parseVox(/** @type {ArrayBuffer} */ (b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength)), OPTIONS), "vox");
|
|
55
|
+
}
|
|
56
|
+
throw new Error(`${name}: not a model file; use ${MODEL_TYPES.map((t) => `.${t}`).join(", ")}`);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Scale uniformly so the model's largest side (or its height) is `sizeMm`,
|
|
61
|
+
* centred on X and Y, standing on z = 0. Every piece is measured in this frame.
|
|
62
|
+
* @param {Mesh} mesh @param {number} sizeMm @param {"largest" | "height"} by @returns {Mesh}
|
|
63
|
+
*/
|
|
64
|
+
export function fitSize(mesh, sizeMm, by) {
|
|
65
|
+
const p = mesh.positions, min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];
|
|
66
|
+
for (let i = 0; i < p.length; i++) { min[i % 3] = Math.min(min[i % 3], p[i]); max[i % 3] = Math.max(max[i % 3], p[i]); }
|
|
67
|
+
if (!(max[2] > min[2])) throw new Error("blueprint: the model is flat along Z (Z is up)");
|
|
68
|
+
const side = by === "height" ? max[2] - min[2] : Math.max(max[0] - min[0], max[1] - min[1], max[2] - min[2]);
|
|
69
|
+
const scale = sizeMm / side, origin = [(min[0] + max[0]) / 2, (min[1] + max[1]) / 2, min[2]];
|
|
70
|
+
return { positions: p.map((v, i) => (v - origin[i % 3]) * scale) };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Split a triangle soup into shells: triangles joined through shared
|
|
75
|
+
* vertices. Each shell is read on its own, then the shells are joined.
|
|
76
|
+
* @param {Float32Array} p
|
|
77
|
+
* @returns {{ positions: Float32Array, min: number[], max: number[] }[]}
|
|
78
|
+
*/
|
|
79
|
+
export function shells(p) {
|
|
80
|
+
const count = p.length / 9, parent = Int32Array.from({ length: count }, (_, i) => i);
|
|
81
|
+
const find = (i) => { while (parent[i] !== i) i = parent[i] = parent[parent[i]]; return i; };
|
|
82
|
+
const owner = new Map();
|
|
83
|
+
for (let t = 0; t < count; t++) for (let v = 0; v < 3; v++) {
|
|
84
|
+
const o = t * 9 + v * 3, key = `${p[o].toFixed(4)},${p[o + 1].toFixed(4)},${p[o + 2].toFixed(4)}`;
|
|
85
|
+
const other = owner.get(key);
|
|
86
|
+
if (other === undefined) owner.set(key, t); else parent[find(t)] = find(other);
|
|
87
|
+
}
|
|
88
|
+
const groups = new Map();
|
|
89
|
+
for (let t = 0; t < count; t++) {
|
|
90
|
+
const root = find(t), group = groups.get(root);
|
|
91
|
+
if (group) group.push(t); else groups.set(root, [t]);
|
|
92
|
+
}
|
|
93
|
+
return [...groups.values()].map((tris) => {
|
|
94
|
+
const positions = new Float32Array(tris.length * 9), min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];
|
|
95
|
+
tris.forEach((t, k) => {
|
|
96
|
+
positions.set(p.subarray(t * 9, t * 9 + 9), k * 9);
|
|
97
|
+
for (let i = 0; i < 9; i++) { min[i % 3] = Math.min(min[i % 3], p[t * 9 + i]); max[i % 3] = Math.max(max[i % 3], p[t * 9 + i]); }
|
|
98
|
+
});
|
|
99
|
+
return { positions, min, max };
|
|
100
|
+
});
|
|
101
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// The cutting methods that make flat cross sections: slotted (an egg crate
|
|
3
|
+
// of front-back and left-right pieces), stacked (level layers) and radial
|
|
4
|
+
// (fins around the centre, held by level rings). Each returns the pieces and
|
|
5
|
+
// the assembly steps that are its own.
|
|
6
|
+
import { axisFrame, family, finFrame, interlock, planes, cutSlots } from "./slice.js";
|
|
7
|
+
|
|
8
|
+
/** @typedef {import("./layout.js").Piece} Piece @typedef {import("./index.js").Part} Part */
|
|
9
|
+
/** @typedef {{ text: string, parts: string[] }} Step @typedef {{ pieces: Piece[], steps: Step[] }} MethodResult */
|
|
10
|
+
/** @typedef {{ solids: ReturnType<typeof import("./mesh.js").shells>, lo: number[], hi: number[], s: Required<import("./index.js").BlueprintSettings> }} Input */
|
|
11
|
+
|
|
12
|
+
/** "A1", "A1 and A2", "A1, A2 and A3" */
|
|
13
|
+
export const list = (ids) => (ids.length < 2 ? ids.join("") : `${ids.slice(0, -1).join(", ")} and ${ids[ids.length - 1]}`);
|
|
14
|
+
export const mm = (n) => `${Math.round(n)} mm`;
|
|
15
|
+
const unique = (ids) => [...new Set(ids)];
|
|
16
|
+
|
|
17
|
+
/** Pieces that cross nothing: say how to place them. @param {Part[]} parts @param {Step[]} steps */
|
|
18
|
+
function loose(parts, steps) {
|
|
19
|
+
const ids = parts.filter((p) => !p.slots.length).map((p) => p.id);
|
|
20
|
+
if (ids.length) steps.push({ text: `${list(ids)} ${ids.length > 1 ? "cross" : "crosses"} no other piece: hold ${ids.length > 1 ? "them" : "it"} in place using the 3D view and weld with the pen.`, parts: ids });
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** @param {Input} input @returns {MethodResult} */
|
|
24
|
+
export function slotted({ solids, lo, hi, s }) {
|
|
25
|
+
const xs = family(solids, planes(lo[0], hi[0], s.slicesX).map((x) => axisFrame("x", x)), "A", (i) => `front-back section ${i + 1}`, s.penMm);
|
|
26
|
+
const ys = family(solids, planes(lo[1], hi[1], s.slicesY).map((y) => axisFrame("y", y)), "B", (i) => `left-right section ${i + 1}`, s.penMm);
|
|
27
|
+
const joints = [];
|
|
28
|
+
// An X piece and a Y piece meet on a vertical line: X is slotted from the top, Y from the bottom.
|
|
29
|
+
for (const x of xs) for (const y of ys) {
|
|
30
|
+
if (interlock(x, [y.frame.origin[1], 0], [0, 1], y, [x.frame.origin[0], 0], [0, 1], s.penMm)) joints.push({ x: x.id, y: y.id });
|
|
31
|
+
}
|
|
32
|
+
for (const part of [...xs, ...ys]) part.polygons = cutSlots(part);
|
|
33
|
+
const steps = [];
|
|
34
|
+
const standing = xs.filter((p) => p.slots.length).map((p) => p.id);
|
|
35
|
+
const gap = s.slicesX > 1 ? `, ${mm((hi[0] - lo[0]) / (s.slicesX + 1))} apart` : "";
|
|
36
|
+
if (standing.length) steps.push({ text: `Stand ${list(standing)} upright with the slots facing up${gap}.`, parts: standing });
|
|
37
|
+
for (const y of ys) {
|
|
38
|
+
const onto = unique(joints.filter((j) => j.y === y.id).map((j) => j.x));
|
|
39
|
+
if (onto.length) steps.push({ text: `Slide ${y.id} down onto ${list(onto)} so the slots lock.`, parts: [y.id, ...onto] });
|
|
40
|
+
}
|
|
41
|
+
loose([...xs, ...ys], steps);
|
|
42
|
+
steps.push({ text: "Weld each joint with a dot from the pen so the model stays rigid.", parts: [] });
|
|
43
|
+
return {
|
|
44
|
+
pieces: [...xs.map((part) => ({ part, hint: part.slots.length ? "slots at top" : "", cross: false })),
|
|
45
|
+
...ys.map((part) => ({ part, hint: part.slots.length ? "slots at base" : "", cross: false }))],
|
|
46
|
+
steps,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** @param {Input} input @returns {MethodResult} */
|
|
51
|
+
export function stacked({ solids, lo, hi, s }) {
|
|
52
|
+
const gap = (hi[2] - lo[2]) / s.layers;
|
|
53
|
+
const cs = family(solids, Array.from({ length: s.layers }, (_, i) => axisFrame("z", lo[2] + (i + 0.5) * gap)), "C", (i) => `layer ${i + 1}`, s.penMm);
|
|
54
|
+
const heights = unique(cs.map((p) => p.frame.origin[2]));
|
|
55
|
+
const steps = heights.map((z, i) => {
|
|
56
|
+
const ids = cs.filter((p) => p.frame.origin[2] === z).map((p) => p.id);
|
|
57
|
+
return {
|
|
58
|
+
text: i === 0 ? `Lay ${list(ids)} flat: the bottom layer.` : `Hold ${list(ids)} ${mm(gap)} above the layer below, centre crosses in line, and join them with short pen posts.`,
|
|
59
|
+
parts: ids,
|
|
60
|
+
};
|
|
61
|
+
});
|
|
62
|
+
return { pieces: cs.map((part) => ({ part, hint: `${part.name.split(",")[0]} at ${mm(part.frame.origin[2])}`, cross: true })), steps };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** @param {Input} input @returns {MethodResult} */
|
|
66
|
+
export function radial({ solids, lo, hi, s }) {
|
|
67
|
+
const angles = Array.from({ length: s.fins }, (_, i) => Math.round((i * 3600) / s.fins) / 10);
|
|
68
|
+
// Fins stop a pen line short of the axis so they do not crowd each other there.
|
|
69
|
+
const fins = family(solids, angles.map(finFrame), "F", (i) => `fin at ${angles[i]}°`, s.penMm, s.penMm);
|
|
70
|
+
const rings = family(solids, planes(lo[2], hi[2], s.rings).map((z) => axisFrame("z", z)), "R", (i) => `ring ${i + 1}`, s.penMm);
|
|
71
|
+
const joints = [];
|
|
72
|
+
// A ring and a fin meet on a level line out from the axis: the ring is slotted from outside, the fin from inside.
|
|
73
|
+
for (const ring of rings) for (const fin of fins) {
|
|
74
|
+
const dir = fin.frame.u.slice(0, 2), z = ring.frame.origin[2];
|
|
75
|
+
if (interlock(ring, [0, 0], dir, fin, [0, z], [1, 0], s.penMm)) joints.push({ ring: ring.id, fin: fin.id });
|
|
76
|
+
}
|
|
77
|
+
for (const part of [...rings, ...fins]) part.polygons = cutSlots(part);
|
|
78
|
+
const steps = [];
|
|
79
|
+
const held = rings.filter((r) => r.slots.length);
|
|
80
|
+
if (held.length) {
|
|
81
|
+
const where = held.map((r) => `${r.id} ${mm(r.frame.origin[2])} up`);
|
|
82
|
+
steps.push({ text: `Hold ${list(where)}, level, centres on one vertical line, slots facing out.`, parts: held.map((r) => r.id) });
|
|
83
|
+
}
|
|
84
|
+
for (const fin of fins) {
|
|
85
|
+
const into = unique(joints.filter((j) => j.fin === fin.id).map((j) => j.ring));
|
|
86
|
+
if (into.length) steps.push({ text: `Slide ${fin.id} in toward the centre so its slots take ${list(into)}.`, parts: [fin.id, ...into] });
|
|
87
|
+
}
|
|
88
|
+
loose([...rings, ...fins], steps);
|
|
89
|
+
steps.push({ text: "Weld each joint, and the fins to each other where they meet in the middle.", parts: [] });
|
|
90
|
+
return {
|
|
91
|
+
pieces: [...fins.map((part) => ({ part, hint: part.name.split(",")[0], cross: false })),
|
|
92
|
+
...rings.map((part) => ({ part, hint: `ring at ${mm(part.frame.origin[2])}`, cross: true }))],
|
|
93
|
+
steps,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// A clean, simple surface for unfolding. Any model (several overlapping
|
|
3
|
+
// solids, small leaks) is sampled on a grid, the outside of the union is
|
|
4
|
+
// rebuilt as one closed surface (surface nets), and that surface is reduced
|
|
5
|
+
// to a few faces by edge collapses ranked by quadric error (Garland and
|
|
6
|
+
// Heckbert 1997).
|
|
7
|
+
|
|
8
|
+
/** @typedef {ReturnType<typeof import("./mesh.js").shells>} Shells @typedef {{ verts: number[][], faces: number[][] }} Indexed */
|
|
9
|
+
|
|
10
|
+
const sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
|
|
11
|
+
const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
|
|
12
|
+
const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
|
|
13
|
+
const len = (a) => Math.hypot(a[0], a[1], a[2]);
|
|
14
|
+
// Weight that also makes short edges go first, so faces end up of similar size.
|
|
15
|
+
const SHORT = 0.05;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Rays along `axis` through every grid line: where they run inside the union
|
|
19
|
+
* of the shells, as sorted [in, out] stretches per ray.
|
|
20
|
+
* @param {Shells} solids @param {number} axis @param {number[]} n nodes per axis @param {(a: number, i: number) => number} node
|
|
21
|
+
*/
|
|
22
|
+
function rays(solids, axis, n, node) {
|
|
23
|
+
const b = (axis + 1) % 3, c = (axis + 2) % 3, h = node(0, 1) - node(0, 0);
|
|
24
|
+
const out = Array.from({ length: n[b] * n[c] }, () => /** @type {number[][]} */ ([]));
|
|
25
|
+
for (const { positions: p } of solids) {
|
|
26
|
+
const hits = new Map();
|
|
27
|
+
for (let t = 0; t < p.length; t += 9) {
|
|
28
|
+
const v = [0, 3, 6].map((o) => [p[t + o + b], p[t + o + c], p[t + o + axis]]);
|
|
29
|
+
const d = (v[1][0] - v[0][0]) * (v[2][1] - v[0][1]) - (v[2][0] - v[0][0]) * (v[1][1] - v[0][1]);
|
|
30
|
+
if (Math.abs(d) < 1e-12) continue;
|
|
31
|
+
const lo = (k) => Math.max(0, Math.ceil((Math.min(v[0][k], v[1][k], v[2][k]) - node(k ? c : b, 0)) / h));
|
|
32
|
+
const hi = (k) => Math.min(n[k ? c : b] - 1, Math.floor((Math.max(v[0][k], v[1][k], v[2][k]) - node(k ? c : b, 0)) / h));
|
|
33
|
+
for (let j = lo(0); j <= hi(0); j++) for (let k = lo(1); k <= hi(1); k++) {
|
|
34
|
+
const x = node(b, j) - v[0][0], y = node(c, k) - v[0][1];
|
|
35
|
+
const w1 = (x * (v[2][1] - v[0][1]) - (v[2][0] - v[0][0]) * y) / d, w2 = ((v[1][0] - v[0][0]) * y - x * (v[1][1] - v[0][1])) / d;
|
|
36
|
+
if (w1 < 0 || w2 < 0 || w1 + w2 > 1) continue;
|
|
37
|
+
const ray = j * n[c] + k, list = hits.get(ray);
|
|
38
|
+
const at = v[0][2] + w1 * (v[1][2] - v[0][2]) + w2 * (v[2][2] - v[0][2]);
|
|
39
|
+
if (list) list.push(at); else hits.set(ray, [at]);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
for (const [ray, list] of hits) {
|
|
43
|
+
list.sort((x, y) => x - y);
|
|
44
|
+
for (let i = 0; i + 1 < list.length; i += 2) out[ray].push([list[i], list[i + 1]]);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
// The union: merge overlapping stretches from different shells.
|
|
48
|
+
return out.map((list) => list.sort((x, y) => x[0] - y[0]).reduce((acc, [s, e]) => {
|
|
49
|
+
const last = acc[acc.length - 1];
|
|
50
|
+
if (last && s <= last[1]) last[1] = Math.max(last[1], e); else acc.push([s, e]);
|
|
51
|
+
return acc;
|
|
52
|
+
}, /** @type {number[][]} */ ([])));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* One closed surface around the union of the shells, sampled with `cells`
|
|
57
|
+
* grid cells along the largest side. Faces run counter-clockwise seen from outside.
|
|
58
|
+
* @param {Shells} solids @param {number} cells @returns {Indexed}
|
|
59
|
+
*/
|
|
60
|
+
export function remesh(solids, cells) {
|
|
61
|
+
const lo = [0, 1, 2].map((a) => Math.min(...solids.map((s) => s.min[a]))), hi = [0, 1, 2].map((a) => Math.max(...solids.map((s) => s.max[a])));
|
|
62
|
+
const h = Math.max(...hi.map((v, a) => v - lo[a])) / cells;
|
|
63
|
+
const n = [0, 1, 2].map((a) => Math.ceil((hi[a] - lo[a]) / h) + 3);
|
|
64
|
+
// Small odd offsets keep the rays off mesh edges and vertices.
|
|
65
|
+
const start = [0, 1, 2].map((a) => (lo[a] + hi[a]) / 2 - ((n[a] - 1) * h) / 2 + h * [0.0137, 0.0219, 0.0071][a]);
|
|
66
|
+
const node = (a, i) => start[a] + i * h;
|
|
67
|
+
const along = [0, 1, 2].map((a) => rays(solids, a, n, node));
|
|
68
|
+
const at = (i, j, k) => i + n[0] * (j + n[1] * k);
|
|
69
|
+
const inside = new Uint8Array(n[0] * n[1] * n[2]);
|
|
70
|
+
along[2].forEach((list, ray) => {
|
|
71
|
+
const i = Math.floor(ray / n[1]), j = ray % n[1];
|
|
72
|
+
for (const [s, e] of list) for (let k = Math.max(0, Math.ceil((s - start[2]) / h)); k < n[2] && node(2, k) <= e; k++) inside[at(i, j, k)] = 1;
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
const m = n.map((x) => x - 1), cell = (idx) => idx[0] + m[0] * (idx[1] + m[1] * idx[2]);
|
|
76
|
+
const sum = new Float64Array(m[0] * m[1] * m[2] * 3), hits = new Uint16Array(m[0] * m[1] * m[2]);
|
|
77
|
+
/** @type {{ a: number, idx: number[], out: boolean }[]} */ const edges = [];
|
|
78
|
+
for (let a = 0; a < 3; a++) {
|
|
79
|
+
const b = (a + 1) % 3, c = (a + 2) % 3;
|
|
80
|
+
for (let k = 0; k < n[2]; k++) for (let j = 0; j < n[1]; j++) for (let i = 0; i < n[0]; i++) {
|
|
81
|
+
const idx = [i, j, k];
|
|
82
|
+
if (idx[a] + 1 >= n[a]) continue;
|
|
83
|
+
const next = [...idx];
|
|
84
|
+
next[a]++;
|
|
85
|
+
const p = inside[at(i, j, k)];
|
|
86
|
+
if (p === inside[at(next[0], next[1], next[2])]) continue;
|
|
87
|
+
// Where the surface crosses this grid edge: the ray along it says exactly, or take the middle.
|
|
88
|
+
const t0 = node(a, idx[a]), t1 = t0 + h;
|
|
89
|
+
const ends = along[a][idx[b] * n[c] + idx[c]].flat().filter((t) => t >= t0 && t <= t1);
|
|
90
|
+
const point = [node(0, i), node(1, j), node(2, k)];
|
|
91
|
+
point[a] = ends.length ? ends[0] : t0 + h / 2;
|
|
92
|
+
edges.push({ a, idx, out: p === 1 });
|
|
93
|
+
for (const [db, dc] of [[-1, -1], [0, -1], [0, 0], [-1, 0]]) {
|
|
94
|
+
const ci = [...idx];
|
|
95
|
+
ci[b] += db; ci[c] += dc;
|
|
96
|
+
const id = cell(ci);
|
|
97
|
+
for (let x = 0; x < 3; x++) sum[id * 3 + x] += point[x];
|
|
98
|
+
hits[id]++;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
const vertOf = new Int32Array(hits.length).fill(-1), verts = [];
|
|
103
|
+
const vertex = (id) => {
|
|
104
|
+
if (vertOf[id] < 0) { vertOf[id] = verts.length; verts.push([0, 1, 2].map((x) => sum[id * 3 + x] / hits[id])); }
|
|
105
|
+
return vertOf[id];
|
|
106
|
+
};
|
|
107
|
+
const faces = [];
|
|
108
|
+
for (const { a, idx, out } of edges) {
|
|
109
|
+
const b = (a + 1) % 3, c = (a + 2) % 3;
|
|
110
|
+
const quad = [[-1, -1], [0, -1], [0, 0], [-1, 0]].map(([db, dc]) => {
|
|
111
|
+
const ci = [...idx];
|
|
112
|
+
ci[b] += db; ci[c] += dc;
|
|
113
|
+
return vertex(cell(ci));
|
|
114
|
+
});
|
|
115
|
+
// In this order the quad faces +a; flip it when the surface faces -a.
|
|
116
|
+
const [q0, q1, q2, q3] = out ? quad : [...quad].reverse();
|
|
117
|
+
if (len(sub(verts[q0], verts[q2])) <= len(sub(verts[q1], verts[q3]))) faces.push([q0, q1, q2], [q0, q2, q3]);
|
|
118
|
+
else faces.push([q0, q1, q3], [q1, q2, q3]);
|
|
119
|
+
}
|
|
120
|
+
return { verts, faces };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** A small binary heap of collapses, cheapest first. */
|
|
124
|
+
function heap() {
|
|
125
|
+
const items = [];
|
|
126
|
+
return {
|
|
127
|
+
get size() { return items.length; },
|
|
128
|
+
push(item) {
|
|
129
|
+
items.push(item);
|
|
130
|
+
for (let i = items.length - 1; i > 0;) {
|
|
131
|
+
const up = (i - 1) >> 1;
|
|
132
|
+
if (items[up].cost <= items[i].cost) break;
|
|
133
|
+
[items[up], items[i]] = [items[i], items[up]];
|
|
134
|
+
i = up;
|
|
135
|
+
}
|
|
136
|
+
},
|
|
137
|
+
pop() {
|
|
138
|
+
const top = items[0], last = items.pop();
|
|
139
|
+
if (items.length) {
|
|
140
|
+
items[0] = last;
|
|
141
|
+
for (let i = 0; ;) {
|
|
142
|
+
const l = 2 * i + 1, r = l + 1;
|
|
143
|
+
let min = i;
|
|
144
|
+
if (l < items.length && items[l].cost < items[min].cost) min = l;
|
|
145
|
+
if (r < items.length && items[r].cost < items[min].cost) min = r;
|
|
146
|
+
if (min === i) break;
|
|
147
|
+
[items[min], items[i]] = [items[i], items[min]];
|
|
148
|
+
i = min;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return top;
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** How round a triangle is: 1 for equilateral, 0 for flat. */
|
|
157
|
+
function quality(a, b, c) {
|
|
158
|
+
const ab = sub(b, a), ac = sub(c, a), bc = sub(c, b);
|
|
159
|
+
const s = dot(ab, ab) + dot(ac, ac) + dot(bc, bc);
|
|
160
|
+
return s ? (2 * Math.sqrt(3) * len(cross(ab, ac))) / s : 0;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Collapse edges until about `target` faces are left, keeping the shape
|
|
165
|
+
* (quadric error), never folding a face over or pinching the surface.
|
|
166
|
+
* @param {Indexed} mesh @param {number} target @returns {Indexed}
|
|
167
|
+
*/
|
|
168
|
+
export function simplify({ verts, faces }, target) {
|
|
169
|
+
verts = verts.map((v) => [...v]);
|
|
170
|
+
faces = faces.map((f) => [...f]);
|
|
171
|
+
const V = verts.length, Q = new Float64Array(V * 10), around = Array.from({ length: V }, () => /** @type {number[]} */ ([]));
|
|
172
|
+
const alive = new Uint8Array(faces.length).fill(1), dead = new Uint8Array(V), stamp = new Int32Array(V);
|
|
173
|
+
const edgeCount = new Map();
|
|
174
|
+
faces.forEach((f, fi) => {
|
|
175
|
+
const [a, b, c] = f.map((v) => verts[v]), nrm = cross(sub(b, a), sub(c, a)), area = len(nrm);
|
|
176
|
+
if (area > 0) {
|
|
177
|
+
const [x, y, z] = nrm.map((v) => v / area), d = -dot([x, y, z], a), q = [x * x, x * y, x * z, x * d, y * y, y * z, y * d, z * z, z * d, d * d];
|
|
178
|
+
for (const v of f) for (let k = 0; k < 10; k++) Q[v * 10 + k] += (q[k] * area) / 2;
|
|
179
|
+
}
|
|
180
|
+
f.forEach((v, k) => {
|
|
181
|
+
around[v].push(fi);
|
|
182
|
+
const w = f[(k + 1) % 3], key = Math.min(v, w) * V + Math.max(v, w);
|
|
183
|
+
edgeCount.set(key, (edgeCount.get(key) ?? 0) + 1);
|
|
184
|
+
});
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
const error = (q, p) => {
|
|
188
|
+
const [x, y, z] = p;
|
|
189
|
+
return q[0] * x * x + 2 * q[1] * x * y + 2 * q[2] * x * z + 2 * q[3] * x + q[4] * y * y + 2 * q[5] * y * z + 2 * q[6] * y + q[7] * z * z + 2 * q[8] * z + q[9];
|
|
190
|
+
};
|
|
191
|
+
const queue = heap();
|
|
192
|
+
const consider = (u, v) => {
|
|
193
|
+
const q = Array.from({ length: 10 }, (_, k) => Q[u * 10 + k] + Q[v * 10 + k]);
|
|
194
|
+
const pu = verts[u], pv = verts[v], mid = pu.map((x, i) => (x + pv[i]) / 2), span = len(sub(pu, pv));
|
|
195
|
+
const det = q[0] * (q[4] * q[7] - q[5] * q[5]) - q[1] * (q[1] * q[7] - q[5] * q[2]) + q[2] * (q[1] * q[5] - q[4] * q[2]);
|
|
196
|
+
const options = [pu, pv, mid];
|
|
197
|
+
if (Math.abs(det) > 1e-9) {
|
|
198
|
+
// The point of least error: solve the 3 x 3 system by Cramer's rule.
|
|
199
|
+
const r = [-q[3], -q[6], -q[8]], m = [[q[0], q[1], q[2]], [q[1], q[4], q[5]], [q[2], q[5], q[7]]];
|
|
200
|
+
const col = (k) => m.map((row, i) => row.map((x, j) => (j === k ? r[i] : x)));
|
|
201
|
+
const d3 = (a) => a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1]) - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0]) + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0]);
|
|
202
|
+
const best = [0, 1, 2].map((k) => d3(col(k)) / det);
|
|
203
|
+
if (len(sub(best, mid)) < span) options.push(best);
|
|
204
|
+
}
|
|
205
|
+
let pos = mid, cost = Infinity;
|
|
206
|
+
for (const p of options) { const e = error(q, p); if (e < cost) { cost = e; pos = p; } }
|
|
207
|
+
queue.push({ cost: Math.max(0, cost) + SHORT * span ** 4, u, v, su: stamp[u], sv: stamp[v], pos });
|
|
208
|
+
};
|
|
209
|
+
const ring = (v) => new Set(around[v].flatMap((f) => faces[f]).filter((w) => w !== v));
|
|
210
|
+
for (const key of edgeCount.keys()) consider(Math.floor(key / V), key % V);
|
|
211
|
+
|
|
212
|
+
let count = faces.length;
|
|
213
|
+
while (count > target && queue.size) {
|
|
214
|
+
const { u, v, su, sv, pos } = queue.pop();
|
|
215
|
+
if (dead[u] || dead[v] || stamp[u] !== su || stamp[v] !== sv) continue;
|
|
216
|
+
const shared = around[u].filter((f) => faces[f].includes(v));
|
|
217
|
+
if (shared.length !== 2) continue;
|
|
218
|
+
const ru = ring(u), common = [...ring(v)].filter((w) => w !== u && ru.has(w));
|
|
219
|
+
if (common.length !== 2) continue; // would pinch the surface
|
|
220
|
+
const moved = [...around[u], ...around[v]].filter((f) => !shared.includes(f));
|
|
221
|
+
const ok = moved.every((f) => {
|
|
222
|
+
const before = faces[f].map((w) => verts[w]), after = faces[f].map((w) => (w === u || w === v ? pos : verts[w]));
|
|
223
|
+
const n0 = cross(sub(before[1], before[0]), sub(before[2], before[0])), n1 = cross(sub(after[1], after[0]), sub(after[2], after[0]));
|
|
224
|
+
return dot(n0, n1) > 0.2 * len(n0) * len(n1) && quality(after[0], after[1], after[2]) > 0.12;
|
|
225
|
+
});
|
|
226
|
+
if (!ok) continue;
|
|
227
|
+
for (const f of shared) alive[f] = 0;
|
|
228
|
+
for (const f of around[v]) faces[f] = faces[f].map((w) => (w === v ? u : w));
|
|
229
|
+
around[u] = [...new Set(moved)];
|
|
230
|
+
around[v] = [];
|
|
231
|
+
dead[v] = 1;
|
|
232
|
+
verts[u] = pos;
|
|
233
|
+
for (let k = 0; k < 10; k++) Q[u * 10 + k] += Q[v * 10 + k];
|
|
234
|
+
stamp[u]++;
|
|
235
|
+
count -= 2;
|
|
236
|
+
for (const w of ring(u)) {
|
|
237
|
+
around[w] = around[w].filter((f) => alive[f]);
|
|
238
|
+
consider(u, w);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
const keep = new Int32Array(V).fill(-1), out = { verts: /** @type {number[][]} */ ([]), faces: /** @type {number[][]} */ ([]) };
|
|
242
|
+
faces.forEach((f, fi) => {
|
|
243
|
+
if (!alive[fi]) return;
|
|
244
|
+
out.faces.push(f.map((v) => {
|
|
245
|
+
if (keep[v] < 0) { keep[v] = out.verts.length; out.verts.push(verts[v]); }
|
|
246
|
+
return keep[v];
|
|
247
|
+
}));
|
|
248
|
+
});
|
|
249
|
+
return out;
|
|
250
|
+
}
|