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.
Files changed (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +65 -2
  3. package/bin/inkless.js +10 -0
  4. package/console-dist/assets/BlueprintTool-CLWuM21a.js +4226 -0
  5. package/console-dist/assets/index-CIqLZU6s.js +33 -0
  6. package/console-dist/assets/index-Dv7Gg9qm.css +1 -0
  7. package/console-dist/favicon.svg +11 -0
  8. package/console-dist/index.html +18 -0
  9. package/native/linux/rfcomm.py +84 -0
  10. package/native/macos/build/InklessBluetooth.app/Contents/Info.plist +26 -0
  11. package/native/macos/build/InklessBluetooth.app/Contents/MacOS/InklessBluetooth +0 -0
  12. package/native/macos/build/InklessBluetooth.app/Contents/_CodeSignature/CodeResources +115 -0
  13. package/package.json +60 -4
  14. package/skills/inkless/SKILL.md +213 -0
  15. package/src/core/bits.js +143 -0
  16. package/src/core/blueprint/demos.js +119 -0
  17. package/src/core/blueprint/geometry.js +232 -0
  18. package/src/core/blueprint/index.js +100 -0
  19. package/src/core/blueprint/layout.js +210 -0
  20. package/src/core/blueprint/mesh.js +101 -0
  21. package/src/core/blueprint/methods.js +95 -0
  22. package/src/core/blueprint/remesh.js +250 -0
  23. package/src/core/blueprint/slice.js +134 -0
  24. package/src/core/blueprint/unfold.js +185 -0
  25. package/src/core/design/codes.js +39 -0
  26. package/src/core/design/filters.js +109 -0
  27. package/src/core/design/render.js +317 -0
  28. package/src/core/design/schema.js +132 -0
  29. package/src/core/formats/fit.js +46 -0
  30. package/src/core/formats/index.js +210 -0
  31. package/src/core/formats/library.js +341 -0
  32. package/src/core/formats/share.js +65 -0
  33. package/src/core/index.js +15 -0
  34. package/src/core/printers/hp6.js +160 -0
  35. package/src/core/printers/index.js +14 -0
  36. package/src/core/printers/pm290.js +115 -0
  37. package/src/core/session.js +56 -0
  38. package/src/node/artwork.js +33 -0
  39. package/src/node/cli.js +430 -0
  40. package/src/node/console/actions.js +30 -0
  41. package/src/node/console/client.js +68 -0
  42. package/src/node/console/paths.js +8 -0
  43. package/src/node/console/server.js +286 -0
  44. package/src/node/design.js +99 -0
  45. package/src/node/formats.js +39 -0
  46. package/src/node/frames.js +93 -0
  47. package/src/node/index.js +6 -0
  48. package/src/node/kit.js +12 -0
  49. package/src/node/skill.js +44 -0
  50. package/src/node/transports/index.js +21 -0
  51. package/src/node/transports/linux.js +52 -0
  52. package/src/node/transports/macos.js +81 -0
@@ -0,0 +1,143 @@
1
+ // @ts-check
2
+ // Pure 1-bit raster helpers shared by the CLI, the console and the website.
3
+ // A "bits" array is row-major, one byte per dot, 1 = black.
4
+
5
+ export const DEFAULT_LUMA_WEIGHTS = { r: 0.299, g: 0.587, b: 0.114 };
6
+
7
+ /** RGBA (alpha composited over white) to 0..255 gray. */
8
+ export function rgbaToGray(rgba, width, height, weights = DEFAULT_LUMA_WEIGHTS) {
9
+ const gray = new Float32Array(width * height);
10
+ for (let i = 0, p = 0; p < gray.length; i += 4, p++) {
11
+ const a = rgba[i + 3] / 255;
12
+ const v = weights.r * rgba[i] + weights.g * rgba[i + 1] + weights.b * rgba[i + 2];
13
+ const over = v * a + 255 * (1 - a);
14
+ gray[p] = over < 0 ? 0 : over > 255 ? 255 : over;
15
+ }
16
+ return gray;
17
+ }
18
+
19
+ const clamp = (v) => (v < 0 ? 0 : v > 255 ? 255 : v);
20
+
21
+ /** brightness -> contrast -> gamma -> invert; all no-ops at their defaults. */
22
+ export function adjustGray(gray, { brightness = 0, contrast = 0, gamma = 1, invert = false } = {}) {
23
+ const factor = (259 * (contrast + 255)) / (255 * (259 - contrast));
24
+ const inv = gamma > 0 ? 1 / gamma : 1;
25
+ const out = new Float32Array(gray.length);
26
+ for (let i = 0; i < gray.length; i++) {
27
+ let v = clamp(gray[i] + brightness);
28
+ v = clamp(factor * (v - 128) + 128);
29
+ v = clamp(255 * Math.pow(v / 255, inv));
30
+ out[i] = invert ? 255 - v : v;
31
+ }
32
+ return out;
33
+ }
34
+
35
+ function threshold(gray, width, height, level) {
36
+ const bits = new Uint8Array(width * height);
37
+ for (let i = 0; i < bits.length; i++) bits[i] = gray[i] < level ? 1 : 0;
38
+ return bits;
39
+ }
40
+
41
+ /** Error diffusion with a kernel of [dx, dy, weight] taps. */
42
+ function diffuse(gray, width, height, level, kernel, divisor) {
43
+ const buf = Float32Array.from(gray);
44
+ const bits = new Uint8Array(width * height);
45
+ for (let y = 0; y < height; y++) {
46
+ for (let x = 0; x < width; x++) {
47
+ const i = y * width + x;
48
+ const black = buf[i] < level;
49
+ bits[i] = black ? 1 : 0;
50
+ const error = (buf[i] - (black ? 0 : 255)) / divisor;
51
+ for (const [dx, dy, w] of kernel) {
52
+ const xx = x + dx;
53
+ const yy = y + dy;
54
+ if (xx >= 0 && xx < width && yy < height) buf[yy * width + xx] += error * w;
55
+ }
56
+ }
57
+ }
58
+ return bits;
59
+ }
60
+
61
+ const FLOYD = [[1, 0, 7], [-1, 1, 3], [0, 1, 5], [1, 1, 1]];
62
+ // Atkinson spreads only 6/8 of the error: crisper, lighter shadows on thermal paper.
63
+ const ATKINSON = [[1, 0, 1], [2, 0, 1], [-1, 1, 1], [0, 1, 1], [1, 1, 1], [0, 2, 1]];
64
+ const BAYER4 = [0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5];
65
+
66
+ function ordered(gray, width, height, level) {
67
+ const bits = new Uint8Array(width * height);
68
+ const shift = level - 128;
69
+ for (let y = 0; y < height; y++) {
70
+ for (let x = 0; x < width; x++) {
71
+ const t = ((BAYER4[(y & 3) * 4 + (x & 3)] + 0.5) / 16) * 255 + shift;
72
+ bits[y * width + x] = gray[y * width + x] < t ? 1 : 0;
73
+ }
74
+ }
75
+ return bits;
76
+ }
77
+
78
+ export const DITHER_STYLES = ["threshold", "floyd", "atkinson", "ordered"];
79
+
80
+ /** @param {"threshold"|"floyd"|"atkinson"|"ordered"} style */
81
+ export function dither(gray, width, height, style = "floyd", level = 128) {
82
+ switch (style) {
83
+ case "threshold": return threshold(gray, width, height, level);
84
+ case "floyd": return diffuse(gray, width, height, level, FLOYD, 16);
85
+ case "atkinson": return diffuse(gray, width, height, level, ATKINSON, 8);
86
+ case "ordered": return ordered(gray, width, height, level);
87
+ default: throw new Error(`unknown style ${style}; use ${DITHER_STYLES.join(", ")}`);
88
+ }
89
+ }
90
+
91
+ export function invertBits(bits) {
92
+ const out = new Uint8Array(bits.length);
93
+ for (let i = 0; i < bits.length; i++) out[i] = bits[i] ? 0 : 1;
94
+ return out;
95
+ }
96
+
97
+ export function countInk(bits) {
98
+ let n = 0;
99
+ for (let i = 0; i < bits.length; i++) n += bits[i];
100
+ return n;
101
+ }
102
+
103
+ /** MSB-first rows, ceil(width / 8) bytes each. */
104
+ export function packRows(bits, width, height) {
105
+ const bytesPerRow = Math.ceil(width / 8);
106
+ const out = new Uint8Array(bytesPerRow * height);
107
+ for (let y = 0; y < height; y++) {
108
+ for (let x = 0; x < width; x++) {
109
+ if (bits[y * width + x]) out[y * bytesPerRow + (x >> 3)] |= 0x80 >> (x & 7);
110
+ }
111
+ }
112
+ return out;
113
+ }
114
+
115
+ export function unpackRows(packed, width, height) {
116
+ const bytesPerRow = Math.ceil(width / 8);
117
+ const bits = new Uint8Array(width * height);
118
+ for (let y = 0; y < height; y++) {
119
+ for (let x = 0; x < width; x++) {
120
+ bits[y * width + x] = (packed[y * bytesPerRow + (x >> 3)] >> (7 - (x & 7))) & 1;
121
+ }
122
+ }
123
+ return bits;
124
+ }
125
+
126
+ /** Binary PBM (P4), the simplest lossless 1-bit file. */
127
+ export function encodePbm(bits, width, height) {
128
+ const header = new TextEncoder().encode(`P4\n${width} ${height}\n`);
129
+ const body = packRows(bits, width, height);
130
+ const out = new Uint8Array(header.length + body.length);
131
+ out.set(header);
132
+ out.set(body, header.length);
133
+ return out;
134
+ }
135
+
136
+ export function decodePbm(bytes) {
137
+ const text = new TextDecoder("latin1").decode(bytes.subarray(0, 64));
138
+ const match = /^P4\s+(?:#.*\s+)*(\d+)\s+(\d+)\s/.exec(text);
139
+ if (!match) throw new Error("not a binary PBM (P4) file");
140
+ const width = Number(match[1]);
141
+ const height = Number(match[2]);
142
+ return { width, height, bits: unpackRows(bytes.subarray(match[0].length), width, height) };
143
+ }
@@ -0,0 +1,119 @@
1
+ // @ts-check
2
+ // Built-in models so the console works without a file. Each is a few simple
3
+ // solids (turned shapes, boxes, flat plates) that may overlap; the slicer
4
+ // joins them. Z is up; units are arbitrary, makeBlueprint scales them.
5
+
6
+ /** @typedef {number[]} Vec */
7
+
8
+ /** Names accepted by demoModel. */
9
+ export const DEMO_MODELS = /** @type {const} */ (["duck", "rocket", "chair", "dino", "vase"]);
10
+
11
+ const BUILDERS = {
12
+ // A bath duck: round body, head on a short neck, flat beak and a tail tipped up.
13
+ duck: () => [
14
+ ...ellipsoid([0, 0, 7], [11, 8, 6.5]),
15
+ ...tube([6, 0, 9], [8, 0, 15], 3.8, 3.4),
16
+ ...ellipsoid([8.5, 0, 17.5], [4.8, 4.5, 4.8]),
17
+ ...ellipsoid([13.6, 0, 16.6], [3, 2, 0.9]),
18
+ ...tube([-8, 0, 8], [-13.5, 0, 12.5], 3.6, 0.6),
19
+ ],
20
+ // Body of revolution with an elliptical nose and four fins along the axes.
21
+ rocket: () => [
22
+ ...lathe([[0, 0], [7, 0], [8, 4], [8, 40], ...arc(9).map(([s, c]) => [8 * c, 40 + 20 * s])]),
23
+ ...[0, 90, 180, 270].flatMap((deg) => plate([[5, 0], [13, -4], [13, 5], [5, 16]], 1.6, deg)),
24
+ ],
25
+ // Seat, four legs set in from the edges, and a solid back.
26
+ chair: () => [
27
+ ...box([-10, -10, 18], [10, 10, 21]),
28
+ ...[-7, 3].flatMap((x) => [-7, 3].flatMap((y) => box([x, y, 0], [x + 4, y + 4, 19]))),
29
+ ...box([-10, 7, 20], [10, 10, 40]),
30
+ ],
31
+ // A long-necked dinosaur: egg body, four legs, neck, head and tail.
32
+ dino: () => [
33
+ ...ellipsoid([0, 0, 10], [11, 6, 6.5]),
34
+ ...[-6, 6].flatMap((x) => [-3.5, 3.5].flatMap((y) => tube([x, y, 0], [x, y, 9], 2.2, 2.2))),
35
+ ...tube([8, 0, 12], [16, 0, 23], 3, 2.4),
36
+ ...ellipsoid([18, 0, 24], [3.4, 2.4, 2.2]),
37
+ ...tube([-9, 0, 11], [-26, 0, 5], 3.5, 0.6),
38
+ ],
39
+ // A turned vase: wide belly, narrow neck, a lip at the top.
40
+ vase: () => lathe([[0, 0], [6, 0], [9, 6], [10, 14], [7.5, 24], [5, 30], [5.5, 34], [6.5, 36], [0, 36]]),
41
+ };
42
+
43
+ /** @param {string} name @returns {import("./index.js").Mesh} */
44
+ export function demoModel(name) {
45
+ const build = BUILDERS[name];
46
+ if (!build) throw new Error(`demoModel: unknown model "${name}"; try ${DEMO_MODELS.join(", ")}`);
47
+ return { positions: Float32Array.from(build()) };
48
+ }
49
+
50
+ /** [sin, cos] pairs for a quarter turn in `steps` steps. */
51
+ const arc = (steps) => Array.from({ length: steps + 1 }, (_, k) => (k === steps ? [1, 0] : [Math.sin((k / steps) * Math.PI / 2), Math.cos((k / steps) * Math.PI / 2)]));
52
+
53
+ /** @param {number[]} out @param {Vec} a @param {Vec} b @param {Vec} c */
54
+ function tri(out, a, b, c) {
55
+ const same = (p, q) => p[0] === q[0] && p[1] === q[1] && p[2] === q[2];
56
+ if (!same(a, b) && !same(b, c) && !same(a, c)) out.push(...a, ...b, ...c);
57
+ }
58
+
59
+ /**
60
+ * Turn a profile of [radius, z] points (bottom to top) around the Z axis.
61
+ * Ends with a radius above zero are capped. `place` moves the local result.
62
+ * @param {number[][]} profile @param {(p: Vec) => Vec} [place]
63
+ */
64
+ function lathe(profile, place = (p) => p, segments = 24) {
65
+ const rings = profile.map(([r, z]) => Array.from({ length: segments }, (_, k) => {
66
+ const a = (2 * Math.PI * k) / segments;
67
+ return place([r * Math.cos(a), r * Math.sin(a), z]);
68
+ }));
69
+ const out = [];
70
+ for (let i = 0; i + 1 < rings.length; i++) for (let k = 0; k < segments; k++) {
71
+ const k1 = (k + 1) % segments;
72
+ tri(out, rings[i][k], rings[i][k1], rings[i + 1][k1]);
73
+ tri(out, rings[i][k], rings[i + 1][k1], rings[i + 1][k]);
74
+ }
75
+ for (const [i, flip] of [[0, true], [rings.length - 1, false]]) {
76
+ const centre = place([0, 0, profile[i][1]]);
77
+ if (profile[i][0] > 0) for (let k = 0; k < segments; k++) {
78
+ const a = rings[i][k], b = rings[i][(k + 1) % segments];
79
+ if (flip) tri(out, centre, b, a); else tri(out, centre, a, b);
80
+ }
81
+ }
82
+ return out;
83
+ }
84
+
85
+ /** @param {Vec} centre @param {Vec} radii */
86
+ function ellipsoid(centre, radii) {
87
+ const profile = [...arc(6).reverse().map(([s, c]) => [c, -s]), ...arc(6).slice(1).map(([s, c]) => [c, s])];
88
+ return lathe(profile, ([x, y, z]) => [centre[0] + x * radii[0], centre[1] + y * radii[1], centre[2] + z * radii[2]]);
89
+ }
90
+
91
+ /** A capped cone from point a (radius ra) to point b (radius rb). @param {Vec} a @param {Vec} b */
92
+ function tube(a, b, ra, rb) {
93
+ const axis = b.map((v, i) => v - a[i]), len = Math.hypot(...axis), d = axis.map((v) => v / len);
94
+ const helper = Math.abs(d[2]) < 0.9 ? [0, 0, 1] : [1, 0, 0];
95
+ const cross = (p, q) => [p[1] * q[2] - p[2] * q[1], p[2] * q[0] - p[0] * q[2], p[0] * q[1] - p[1] * q[0]];
96
+ const e1 = cross(d, helper), n1 = Math.hypot(...e1), u = e1.map((v) => v / n1), w = cross(d, u);
97
+ return lathe([[ra, 0], [rb, 1]], ([x, y, z]) => a.map((v, i) => v + x * u[i] + y * w[i] + z * axis[i]));
98
+ }
99
+
100
+ /** @param {Vec} lo @param {Vec} hi */
101
+ const box = (lo, hi) => plate([[lo[0], lo[2]], [hi[0], lo[2]], [hi[0], hi[2]], [lo[0], hi[2]]], hi[1] - lo[1], 0, (lo[1] + hi[1]) / 2);
102
+
103
+ /**
104
+ * A flat plate: a convex polygon of [s, z] points given thickness, centred on
105
+ * `t`, then turned `deg` degrees around Z. Fins and boxes.
106
+ * @param {number[][]} poly
107
+ */
108
+ function plate(poly, thickness, deg, t = 0) {
109
+ const a = (deg * Math.PI) / 180, cos = Math.cos(a), sin = Math.sin(a);
110
+ const side = (off) => poly.map(([s, z]) => [s * cos - (t + off) * sin, s * sin + (t + off) * cos, z]);
111
+ const front = side(-thickness / 2), back = side(thickness / 2), out = [];
112
+ for (let k = 1; k + 1 < poly.length; k++) { tri(out, front[0], front[k + 1], front[k]); tri(out, back[0], back[k], back[k + 1]); }
113
+ poly.forEach((_, k) => {
114
+ const k1 = (k + 1) % poly.length;
115
+ tri(out, front[k], front[k1], back[k1]);
116
+ tri(out, front[k], back[k1], back[k]);
117
+ });
118
+ return out;
119
+ }
@@ -0,0 +1,232 @@
1
+ // @ts-check
2
+ // Flat geometry in millimetres. A ring is a closed list of [x, y] points (the
3
+ // last point does not repeat the first). A region is a list of rings read with
4
+ // the even-odd rule, so holes need no special marking.
5
+
6
+ /** @typedef {number[]} Point @typedef {Point[]} Ring @typedef {{ x0: number, y0: number, x1: number, y1: number }} Rect */
7
+
8
+ const SIDE_MM = 1e-4; // how far off an edge the inside test looks
9
+ const SNAP_MM = 1e-3; // points closer than this are the same point
10
+
11
+ /** @param {Point} a @param {Point} b @param {number} t @returns {Point} */
12
+ export const lerp = (a, b, t) => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t];
13
+
14
+ /** Signed area, positive when the ring runs counter-clockwise (y up). @param {Ring} ring */
15
+ export function area(ring) {
16
+ let sum = 0;
17
+ for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) sum += ring[j][0] * ring[i][1] - ring[i][0] * ring[j][1];
18
+ return sum / 2;
19
+ }
20
+
21
+ /** @param {Ring} ring */
22
+ const perimeter = (ring) => ring.reduce((sum, p, i) => sum + Math.hypot(...sub(ring[(i + 1) % ring.length], p)), 0);
23
+ const sub = (a, b) => [a[0] - b[0], a[1] - b[1]];
24
+
25
+ /** @param {Ring[]} rings @returns {Rect} */
26
+ export function bounds(rings) {
27
+ const b = { x0: Infinity, y0: Infinity, x1: -Infinity, y1: -Infinity };
28
+ for (const ring of rings) for (const [x, y] of ring) {
29
+ b.x0 = Math.min(b.x0, x); b.y0 = Math.min(b.y0, y);
30
+ b.x1 = Math.max(b.x1, x); b.y1 = Math.max(b.y1, y);
31
+ }
32
+ return b;
33
+ }
34
+
35
+ /**
36
+ * Where the line `point[axis] = c` crosses the rings, as sorted values of the
37
+ * other coordinate. Half-open edges, so a vertex on the line counts once.
38
+ * @param {Ring[]} rings @param {0 | 1} axis @param {number} c
39
+ */
40
+ export function crossings(rings, axis, c) {
41
+ const other = 1 - axis, hits = [];
42
+ for (const ring of rings) for (let i = 0; i < ring.length; i++) {
43
+ const a = ring[i], b = ring[(i + 1) % ring.length];
44
+ if ((a[axis] <= c) !== (b[axis] <= c)) hits.push(a[other] + ((c - a[axis]) / (b[axis] - a[axis])) * (b[other] - a[other]));
45
+ }
46
+ return hits.sort((x, y) => x - y);
47
+ }
48
+
49
+ /** The stretches of the line `point[axis] = c` that lie inside the region. @param {Ring[]} rings @param {0 | 1} axis @param {number} c */
50
+ export function spans(rings, axis, c) {
51
+ const hits = crossings(rings, axis, c), out = [];
52
+ for (let i = 0; i + 1 < hits.length; i += 2) out.push([hits[i], hits[i + 1]]);
53
+ return out;
54
+ }
55
+
56
+ /** @param {Ring[]} rings @param {Point} p */
57
+ export const inside = (rings, p) => crossings(rings, 1, p[1]).filter((x) => x < p[0]).length % 2 === 1;
58
+
59
+ /**
60
+ * Join loose segments into rings, matching ends within SNAP_MM. A segment that
61
+ * appears twice is used once. Chains that never close (a leaky mesh) are kept
62
+ * if they have three points, closed by the ring's implicit last edge.
63
+ * @param {Point[][]} segments
64
+ */
65
+ export function chain(segments) {
66
+ /** @type {Point[]} */ const points = [];
67
+ const grid = new Map();
68
+ const cell = (/** @type {Point} */ p) => [Math.floor(p[0] / SNAP_MM), Math.floor(p[1] / SNAP_MM)];
69
+ const idOf = (/** @type {Point} */ p) => {
70
+ const [cx, cy] = cell(p);
71
+ for (let dx = -1; dx <= 1; dx++) for (let dy = -1; dy <= 1; dy++) {
72
+ for (const k of grid.get(`${cx + dx},${cy + dy}`) ?? []) if (Math.hypot(...sub(points[k], p)) <= SNAP_MM) return k;
73
+ }
74
+ points.push(p);
75
+ const key = `${cx},${cy}`;
76
+ grid.set(key, [...(grid.get(key) ?? []), points.length - 1]);
77
+ return points.length - 1;
78
+ };
79
+ const edgeKey = (i, j) => (i < j ? `${i},${j}` : `${j},${i}`);
80
+ const links = new Map(), known = new Set();
81
+ for (const [a, b] of segments) {
82
+ const i = idOf(a), j = idOf(b), key = edgeKey(i, j);
83
+ if (i === j || known.has(key)) continue;
84
+ known.add(key);
85
+ links.set(i, [...(links.get(i) ?? []), j]);
86
+ links.set(j, [...(links.get(j) ?? []), i]);
87
+ }
88
+ const used = new Set();
89
+ const take = (i, j) => !used.has(edgeKey(i, j)) && Boolean(used.add(edgeKey(i, j)));
90
+ const rings = [];
91
+ for (const [start, nexts] of links) for (const first of nexts) {
92
+ if (!take(start, first)) continue;
93
+ const ring = [start];
94
+ for (let at = first; at !== start && at !== undefined; at = links.get(at).find((/** @type {number} */ n) => take(at, n))) ring.push(at);
95
+ if (ring.length >= 3) rings.push(ring.map((k) => points[k]));
96
+ }
97
+ return rings;
98
+ }
99
+
100
+ /** Drop points that sit on the line between their neighbours. @param {Ring} ring */
101
+ export function simplify(ring, tol = 0.01) {
102
+ let pts = ring, changed = true;
103
+ while (changed && pts.length > 3) {
104
+ changed = false;
105
+ const out = [];
106
+ pts.forEach((p, i) => {
107
+ const prev = out.length ? out[out.length - 1] : pts[pts.length - 1], next = pts[(i + 1) % pts.length];
108
+ const [dx, dy] = sub(next, prev), len = Math.hypot(dx, dy);
109
+ const off = len ? Math.abs(dx * (p[1] - prev[1]) - dy * (p[0] - prev[0])) / len : Math.hypot(...sub(p, prev));
110
+ if (off < tol) changed = true; else out.push(p);
111
+ });
112
+ pts = out;
113
+ }
114
+ return pts;
115
+ }
116
+
117
+ /** Positions (0..1 along ab) where cd crosses or overlaps ab. */
118
+ function cutParams(a, b, c, d) {
119
+ const [rx, ry] = sub(b, a), [sx, sy] = sub(d, c), [qx, qy] = sub(c, a);
120
+ const rr = rx * rx + ry * ry, den = rx * sy - ry * sx;
121
+ if (Math.abs(den) <= 1e-12 * Math.sqrt(rr * (sx * sx + sy * sy))) {
122
+ if (Math.abs(qx * ry - qy * rx) > 1e-6 * Math.sqrt(rr)) return [];
123
+ return [(qx * rx + qy * ry) / rr, ((d[0] - a[0]) * rx + (d[1] - a[1]) * ry) / rr].filter((t) => t > 0 && t < 1);
124
+ }
125
+ const t = (qx * sy - qy * sx) / den, u = (qx * ry - qy * rx) / den;
126
+ return t > 0 && t < 1 && u >= -1e-9 && u <= 1 + 1e-9 ? [t] : [];
127
+ }
128
+
129
+ /**
130
+ * Outline of a region built from several shapes (each a list of rings), as
131
+ * rings. Every edge is split where other shapes cross it and kept when exactly
132
+ * one of its two sides is inside. With "inside any shape" this is a union,
133
+ * with "inside A and not inside B" a difference.
134
+ * @param {Ring[][]} shapes @param {(p: Point) => boolean} isInside
135
+ */
136
+ export function outline(shapes, isInside) {
137
+ const edges = shapes.map((rings) => rings.flatMap((ring) => ring.map((p, i) => [p, ring[(i + 1) % ring.length]])));
138
+ const boxes = edges.map((list) => list.map(([a, b]) => bounds([[a, b]])));
139
+ const kept = [];
140
+ edges.forEach((own, s) => own.forEach(([a, b], e) => {
141
+ const box = boxes[s][e], cuts = [0, 1];
142
+ edges.forEach((list, t) => {
143
+ if (t !== s) list.forEach(([c, d], f) => {
144
+ const o = boxes[t][f];
145
+ if (o.x0 <= box.x1 && o.x1 >= box.x0 && o.y0 <= box.y1 && o.y1 >= box.y0) cuts.push(...cutParams(a, b, c, d));
146
+ });
147
+ });
148
+ cuts.sort((x, y) => x - y);
149
+ for (let k = 1; k < cuts.length; k++) {
150
+ if (cuts[k] - cuts[k - 1] < 1e-9) continue;
151
+ const p = lerp(a, b, cuts[k - 1]), q = lerp(a, b, cuts[k]), m = lerp(p, q, 0.5);
152
+ const [dx, dy] = sub(q, p), len = Math.hypot(dx, dy), nx = (-dy / len) * SIDE_MM, ny = (dx / len) * SIDE_MM;
153
+ if (isInside([m[0] + nx, m[1] + ny]) !== isInside([m[0] - nx, m[1] - ny])) kept.push([p, q]);
154
+ }
155
+ }));
156
+ return chain(kept);
157
+ }
158
+
159
+ /** Make a ring run counter-clockwise (sign 1) or clockwise (sign -1). @param {Ring} ring @param {1 | -1} sign */
160
+ const orient = (ring, sign) => (Math.sign(area(ring)) === sign ? ring : [...ring].reverse());
161
+
162
+ /**
163
+ * Group rings into regions, each `[outer, ...holes]` with the outer ring
164
+ * counter-clockwise and holes clockwise. Regions thinner than `minWidth`
165
+ * (twice the area over the perimeter) are dropped: a pen cannot draw them.
166
+ * @param {Ring[]} rings @param {number} minWidth @returns {Ring[][]}
167
+ */
168
+ export function regions(rings, minWidth) {
169
+ const items = rings.map((ring) => ({ ring, size: Math.abs(area(ring)) })).filter((it) => it.size > 1e-6);
170
+ const depth = (it) => items.filter((o) => o.size > it.size && inside([o.ring], it.ring[0])).length;
171
+ const outers = [], holes = [];
172
+ for (const it of items) (depth(it) % 2 ? holes : outers).push(it);
173
+ const found = outers.map((o) => ({ size: o.size, rings: [orient(o.ring, 1)] }));
174
+ for (const h of holes) {
175
+ const parent = found.filter((o) => inside([o.rings[0]], h.ring[0])).sort((a, b) => a.size - b.size)[0];
176
+ parent?.rings.push(orient(h.ring, -1));
177
+ }
178
+ return found
179
+ .filter(({ rings: r }) => (2 * r.reduce((s, ring) => s + area(ring), 0)) / r.reduce((s, ring) => s + perimeter(ring), 0) >= minWidth)
180
+ .sort((a, b) => b.size - a.size)
181
+ .map((o) => o.rings);
182
+ }
183
+
184
+ /** The part of segment ab inside rect, as [t0, t1] along it, or null. @param {Point} a @param {Point} b @param {Rect} rect */
185
+ export function clipSegment(a, b, rect) {
186
+ let t0 = 0, t1 = 1;
187
+ const [dx, dy] = sub(b, a);
188
+ for (const [p, q] of [[-dx, a[0] - rect.x0], [dx, rect.x1 - a[0]], [-dy, a[1] - rect.y0], [dy, rect.y1 - a[1]]]) {
189
+ if (p === 0) { if (q < 0) return null; continue; }
190
+ const r = q / p;
191
+ if (p < 0) { if (r > t1) return null; t0 = Math.max(t0, r); }
192
+ else { if (r < t0) return null; t1 = Math.min(t1, r); }
193
+ }
194
+ return t1 > t0 ? [t0, t1] : null;
195
+ }
196
+
197
+ /**
198
+ * The stretches of a ring's outline inside rect, as open polylines. A ring
199
+ * wholly inside comes back as one polyline that ends on its first point.
200
+ * @param {Ring} ring @param {Rect} rect @returns {Point[][]}
201
+ */
202
+ export function clipOutline(ring, rect) {
203
+ const runs = [];
204
+ let run = null, wraps = false;
205
+ ring.forEach((a, i) => {
206
+ const b = ring[(i + 1) % ring.length], t = clipSegment(a, b, rect);
207
+ if (!t) { run = null; return; }
208
+ if (run && t[0] === 0) run.push(lerp(a, b, t[1]));
209
+ else runs.push(run = [lerp(a, b, t[0]), lerp(a, b, t[1])]);
210
+ if (i === 0) wraps = t[0] === 0;
211
+ if (t[1] < 1) run = null;
212
+ });
213
+ // The first point is inside and the last run reaches it: one stretch, not two.
214
+ if (run && wraps && runs.length > 1) runs[0] = [...runs.pop(), ...runs[0].slice(1)];
215
+ return runs;
216
+ }
217
+
218
+ /** A ring cut down to rect (Sutherland-Hodgman); good for filling. @param {Ring} ring @param {Rect} rect */
219
+ export function clipRing(ring, rect) {
220
+ let pts = ring;
221
+ for (const [axis, at, sign] of [[0, rect.x0, 1], [0, rect.x1, -1], [1, rect.y0, 1], [1, rect.y1, -1]]) {
222
+ const keep = (/** @type {Point} */ p) => (p[axis] - at) * sign >= 0;
223
+ const out = [];
224
+ pts.forEach((p, i) => {
225
+ const prev = pts[(i + pts.length - 1) % pts.length];
226
+ if (keep(p) !== keep(prev)) out.push(lerp(prev, p, (at - prev[axis]) / (p[axis] - prev[axis])));
227
+ if (keep(p)) out.push(p);
228
+ });
229
+ pts = out;
230
+ }
231
+ return pts;
232
+ }
@@ -0,0 +1,100 @@
1
+ // @ts-check
2
+ // 3D model -> flat pieces a 3D pen can trace, laid out on labels. Methods:
3
+ // slotted cross sections that lock like an egg crate (a sliceform), stacked
4
+ // layers, radial fins held by rings, and unfold (papercraft nets). Files:
5
+ // mesh.js (input), slice.js (cutting), methods.js (the cross section methods),
6
+ // remesh.js and unfold.js (nets), layout.js (labels), geometry.js (flat
7
+ // shapes), demos.js (built-in models).
8
+ import { DEMO_MODELS, demoModel } from "./demos.js";
9
+ import { LABELS, layout } from "./layout.js";
10
+ import { MODEL_TYPES, fitSize, loadModel, parseObj, parseStl, shells } from "./mesh.js";
11
+ import { list, radial, slotted, stacked } from "./methods.js";
12
+ import { unfold } from "./unfold.js";
13
+
14
+ export { DEMO_MODELS, LABELS, MODEL_TYPES, demoModel, loadModel, parseObj, parseStl };
15
+
16
+ /**
17
+ * @typedef {{ positions: Float32Array }} Mesh triangle soup, 9 floats per triangle, model units, Z up
18
+ * @typedef {"roll" | "48x48" | "48x30" | "hp6"} LabelId PM290 roll (any length) or fixed labels; hp6 is the HP6-C 36 x 12 mm label
19
+ * @typedef {object} BlueprintSettings
20
+ * @property {"slotted" | "stacked" | "radial" | "unfold"} method
21
+ * slotted: interlocking cross sections; stacked: level layers; radial: fins
22
+ * around the centre held by rings; unfold: papercraft nets of a simplified model
23
+ * @property {"outline" | "solid" | "ribs"} fill how each piece is drawn for the pen (unfold nets have no ribs)
24
+ * @property {number} [sizeMm] real size of the finished object, default 120
25
+ * @property {"largest" | "height"} [sizeBy] sizeMm is its largest side (default) or its height
26
+ * @property {number} [heightMm] same as sizeMm with sizeBy "height"
27
+ * @property {number} penMm pen line width, default 1.2
28
+ * @property {LabelId} [label] default roll, or hp6 when printer is hp6
29
+ * @property {"pm290" | "hp6"} [printer] only picks the label when label is not set
30
+ * @property {number} [slicesX] slotted: pieces across X (default 2)
31
+ * @property {number} [slicesY] slotted: pieces across Y (default 2)
32
+ * @property {number} [layers] stacked: number of layers (default 8)
33
+ * @property {number} [fins] radial: fins around the centre (default 6)
34
+ * @property {number} [rings] radial: level rings that hold the fins (default 2)
35
+ * @property {number} [faces] unfold: faces of the simplified model; 0 or unset picks enough that faces fit the labels
36
+ * @property {number} [ribSpacingMm] default 8
37
+ *
38
+ * Model frame: millimetres, centred on X and Y, standing on z = 0
39
+ * (`Blueprint.mesh` is the model in this frame). A flat piece lies in its
40
+ * `frame`: point [u, v] sits at origin + u * frame.u + v * frame.v.
41
+ *
42
+ * @typedef {{ origin: number[], u: number[], v: number[] }} Frame
43
+ * @typedef {{ from: number[], to: number[], w: number }} Slot a cut-out w wide from `from` on the edge to `to` inside
44
+ * @typedef {object} Part
45
+ * @property {string} id e.g. "A1"; printed in the middle of the piece. A: across X, B: across Y, C: layers, F: fins, R: rings, N: nets
46
+ * @property {string} name e.g. "front-back section 1"
47
+ * @property {number[][][]} polygons outer ring then hole rings in mm, piece coordinates (v up), slots already cut out
48
+ * @property {Slot[]} slots
49
+ * @property {Frame} [frame] where a flat piece sits in the model (all methods but unfold)
50
+ * @property {Float32Array} [surface] unfold: the net's faces on the simplified model, as a triangle soup
51
+ * @property {number[][][]} [faces] unfold: the net's faces laid flat, piece coordinates
52
+ * @property {number[][][]} [folds] unfold: fold lines [a, b] in piece coordinates
53
+ * @property {boolean[]} [valleys] unfold: per fold line, true when it folds toward you (dashed)
54
+ * @property {{ text: string, at: number[] }[]} [notes] unfold: edge numbers; edges with the same number are welded together
55
+ *
56
+ * @typedef {object} Blueprint
57
+ * @property {Part[]} parts
58
+ * @property {import("../design/schema.js").Design} design one or more labels per part; big parts are tiled with alignment marks
59
+ * @property {{ step: number, text: string, parts: string[] }[]} assembly
60
+ * @property {Mesh} mesh the model scaled into the parts' frame, for a 3D view
61
+ * @property {number[]} sizeMm the finished object's width, depth and height
62
+ */
63
+
64
+ const DEFAULTS = {
65
+ method: "slotted", fill: "outline", sizeMm: 120, sizeBy: "largest", penMm: 1.2, label: "roll",
66
+ slicesX: 2, slicesY: 2, layers: 8, fins: 6, rings: 2, faces: 0, ribSpacingMm: 8,
67
+ };
68
+ const METHODS = { slotted, stacked, radial, unfold };
69
+ const count = (n, fallback, max = 40) => Math.min(max, Math.max(1, Math.round(Number(n) || fallback)));
70
+
71
+ /** @param {Mesh} mesh @param {BlueprintSettings} settings @returns {Blueprint} */
72
+ export function makeBlueprint(mesh, settings) {
73
+ const s = { ...DEFAULTS, ...settings };
74
+ if (settings.sizeMm === undefined && settings.heightMm !== undefined) Object.assign(s, { sizeMm: settings.heightMm, sizeBy: "height" });
75
+ if (!(s.sizeMm > 0) || !(s.penMm > 0) || !(s.ribSpacingMm > 0)) throw new Error("blueprint: size, pen line and rib spacing must be above zero");
76
+ const label = settings.label ?? (settings.printer === "hp6" ? "hp6" : "roll");
77
+ if (!LABELS[label]) throw new Error(`blueprint: unknown label "${label}"; use ${Object.keys(LABELS).join(", ")}`);
78
+ if (!METHODS[s.method]) throw new Error(`blueprint: unknown method "${s.method}"; use ${Object.keys(METHODS).join(", ")}`);
79
+ Object.assign(s, {
80
+ label, printer: LABELS[label].printer, sizeBy: s.sizeBy === "height" ? "height" : "largest",
81
+ slicesX: count(s.slicesX, 2), slicesY: count(s.slicesY, 2), layers: count(s.layers, 8),
82
+ fins: Math.max(2, count(s.fins, 6, 24)), rings: count(s.rings, 2, 12), faces: s.faces ? Math.max(8, count(s.faces, 60, 400)) : 0,
83
+ });
84
+ delete s.heightMm;
85
+ const scaled = fitSize(mesh, s.sizeMm, s.sizeBy);
86
+ const solids = shells(scaled.positions);
87
+ const lo = [0, 1, 2].map((a) => Math.min(...solids.map((x) => x.min[a]))), hi = [0, 1, 2].map((a) => Math.max(...solids.map((x) => x.max[a])));
88
+ const { pieces, steps } = METHODS[s.method]({ solids, lo, hi, s });
89
+
90
+ if (!pieces.length) throw new Error("blueprint: no piece is thicker than the pen line; try a bigger size or other settings");
91
+ const { design, tiled } = layout(pieces, s);
92
+ const intro = [
93
+ tiled.length && { text: `${list(tiled)} ${tiled.length > 1 ? "span" : "spans"} several labels: line them up at the triangles, tip to tip.`, parts: tiled },
94
+ { text: s.method === "unfold"
95
+ ? "Trace each net: the outline and every thin line. Let it cool and peel it off."
96
+ : "Trace each piece with the pen, let it cool and peel it off.", parts: pieces.map((p) => p.part.id) },
97
+ ].filter(Boolean);
98
+ const assembly = [...intro, ...steps].map((step, i) => ({ ...step, step: i + 1 }));
99
+ return { parts: pieces.map((p) => p.part), design, assembly, mesh: scaled, sizeMm: hi.map((v, a) => v - lo[a]) };
100
+ }