stack3js 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +141 -2
  3. package/THIRD-PARTY-LICENSES.md +100 -0
  4. package/bin/stack3.mjs +4237 -0
  5. package/examples/future-tank.stack3.json +1 -0
  6. package/examples/traffic-cone-4view.png +0 -0
  7. package/package.json +25 -4
  8. package/viewer/dist/THIRD-PARTY-LICENSES.md +174 -0
  9. package/viewer/dist/assets/GLTFExporter--hziUXc8.js +1 -0
  10. package/viewer/dist/assets/ant-mech-angled-leg-4view-BO2qt1_k.png +0 -0
  11. package/viewer/dist/assets/ant-mech-body-4view-D9xVPpbc.png +0 -0
  12. package/viewer/dist/assets/ant-mech-center-leg-4view-BcphjF_G.png +0 -0
  13. package/viewer/dist/assets/compare-B6DWTZS9.css +1 -0
  14. package/viewer/dist/assets/compare-DJ8rV3Rn.js +6 -0
  15. package/viewer/dist/assets/compare.worker-DK2lJl0n.js +21 -0
  16. package/viewer/dist/assets/concrete-barrier-4view-7PsO3Ftq.png +0 -0
  17. package/viewer/dist/assets/emscripten-module-uFzwHH0Y.wasm +0 -0
  18. package/viewer/dist/assets/emscripten-module.browser-BcR5qphc.js +1 -0
  19. package/viewer/dist/assets/ffi-Boa1QuFa.js +1 -0
  20. package/viewer/dist/assets/fillet-rover-body-4-view-Chk8Mx4R.png +0 -0
  21. package/viewer/dist/assets/fillet-rover-wheel-4-view-B-F8flOC.png +0 -0
  22. package/viewer/dist/assets/hull-4view-BPPqJYUz.png +0 -0
  23. package/viewer/dist/assets/hull-base-color-4view-DrQmdT3h.png +0 -0
  24. package/viewer/dist/assets/hull-clay-4view-3Cu-4Hvr.png +0 -0
  25. package/viewer/dist/assets/hull-depth-4view-DCOdT5ev.png +0 -0
  26. package/viewer/dist/assets/hull-normal-4view-CvLaFITy.png +0 -0
  27. package/viewer/dist/assets/inspection-robot-body-4-view-CLMaHFYm.png +0 -0
  28. package/viewer/dist/assets/inspection-robot-wheel-4-view-27wRsxcs.png +0 -0
  29. package/viewer/dist/assets/plastic-barrier-4view-DQkTBW_i.png +0 -0
  30. package/viewer/dist/assets/presets-DwdZVYhs.js +1 -0
  31. package/viewer/dist/assets/preview-cache-DRF_H5pq.js +58 -0
  32. package/viewer/dist/assets/project-BzR9Ensg.css +1 -0
  33. package/viewer/dist/assets/project-D8tR6U-_.js +17 -0
  34. package/viewer/dist/assets/reconstruct.worker-Cf8iZwT3.js +21 -0
  35. package/viewer/dist/assets/script-engine-CLj7QMLe.js +6 -0
  36. package/viewer/dist/assets/style-CMUT8CmM.css +1 -0
  37. package/viewer/dist/assets/style-CWGgpweN.js +3947 -0
  38. package/viewer/dist/assets/tank-hull-4view-B4sMMkP5.png +0 -0
  39. package/viewer/dist/assets/tank-track-4view-DAIiMTy3.png +0 -0
  40. package/viewer/dist/assets/tank-turret-4view-Cx0FuNFu.png +0 -0
  41. package/viewer/dist/assets/traffic-cone-4view-DG-TkITx.png +0 -0
  42. package/viewer/dist/assets/viewer-CyGodHLY.js +2 -0
  43. package/viewer/dist/assets/wet-floor-sign-4view-CWJDyeTX.png +0 -0
  44. package/viewer/dist/compare.html +47 -0
  45. package/viewer/dist/examples/traffic-cone-4view.png +0 -0
  46. package/viewer/dist/index.html +147 -0
  47. package/viewer/dist/playground/index.html +3342 -0
  48. package/viewer/dist/project.html +83 -0
package/bin/stack3.mjs ADDED
@@ -0,0 +1,4237 @@
1
+ #!/usr/bin/env node
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res, err) => function __init() {
9
+ if (err) throw err[0];
10
+ try {
11
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
12
+ } catch (e) {
13
+ throw err = [e], e;
14
+ }
15
+ };
16
+ var __commonJS = (cb, mod) => function __require() {
17
+ try {
18
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
19
+ } catch (e) {
20
+ throw mod = 0, e;
21
+ }
22
+ };
23
+ var __export = (target, all) => {
24
+ for (var name in all)
25
+ __defProp(target, name, { get: all[name], enumerable: true });
26
+ };
27
+ var __copyProps = (to, from, except, desc) => {
28
+ if (from && typeof from === "object" || typeof from === "function") {
29
+ for (let key of __getOwnPropNames(from))
30
+ if (!__hasOwnProp.call(to, key) && key !== except)
31
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
32
+ }
33
+ return to;
34
+ };
35
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
36
+ // If the importer is in node compatibility mode or this is not an ESM
37
+ // file that has been converted to a CommonJS file using a Babel-
38
+ // compatible transform (i.e. "__esModule" has not been set), then set
39
+ // "default" to the CommonJS "module.exports" for node compatibility.
40
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
41
+ mod
42
+ ));
43
+
44
+ // packages/core/src/views.ts
45
+ function readPngSize(bytes) {
46
+ const signature = [137, 80, 78, 71, 13, 10, 26, 10];
47
+ if (bytes.length < 33 || signature.some((value, index) => bytes[index] !== value) || String.fromCharCode(...bytes.subarray(12, 16)) !== "IHDR") {
48
+ throw new Error("Expected a PNG image.");
49
+ }
50
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
51
+ const width = view.getUint32(16), height = view.getUint32(20);
52
+ if (!width || !height || width > 8192 || height > 8192 || width * height > 16e6) {
53
+ throw new Error("PNG dimensions exceed the 8192 px or 16 MP input limit.");
54
+ }
55
+ return { width, height };
56
+ }
57
+ function parseLayout(value) {
58
+ const directions = value.split(",").map((item) => item.trim());
59
+ if (directions.some((direction) => !DIRECTIONS.includes(direction))) {
60
+ throw new Error("Use directions top, left, front, rear, right, and bottom.");
61
+ }
62
+ if (directions.length !== 4 && directions.length !== 6 || new Set(directions).size !== directions.length || DIRECTIONS.slice(0, directions.length).some((direction) => !directions.includes(direction))) {
63
+ throw new Error("A layout needs the four required directions or all six, with no duplicates.");
64
+ }
65
+ return directions;
66
+ }
67
+ function maskedRaster(image, threshold) {
68
+ const { width, height } = image;
69
+ const data = new Uint8Array(image.data);
70
+ const count2 = width * height;
71
+ for (let i2 = 3; i2 < data.length; i2 += 4) {
72
+ if (data[i2] < 128) return { width, height, data };
73
+ }
74
+ const seen = new Uint8Array(count2);
75
+ const queue = new Uint32Array(count2);
76
+ let read = 0, write = 0;
77
+ function enqueue(index) {
78
+ if (seen[index]) return;
79
+ seen[index] = 1;
80
+ const p = index * 4;
81
+ if (Math.min(data[p], data[p + 1], data[p + 2]) >= threshold) queue[write++] = index;
82
+ }
83
+ for (let x2 = 0; x2 < width; x2++) {
84
+ enqueue(x2);
85
+ enqueue((height - 1) * width + x2);
86
+ }
87
+ for (let y = 1; y < height - 1; y++) {
88
+ enqueue(y * width);
89
+ enqueue(y * width + width - 1);
90
+ }
91
+ while (read < write) {
92
+ const index = queue[read++];
93
+ data[index * 4 + 3] = 0;
94
+ const x2 = index % width;
95
+ if (x2) enqueue(index - 1);
96
+ if (x2 + 1 < width) enqueue(index + 1);
97
+ if (index >= width) enqueue(index - width);
98
+ if (index + width < count2) enqueue(index + width);
99
+ }
100
+ return { width, height, data };
101
+ }
102
+ function crop(image, box) {
103
+ const { left, top, width, height } = box;
104
+ const data = new Uint8Array(width * height * 4);
105
+ for (let y = 0; y < height; y++) {
106
+ const start = ((top + y) * image.width + left) * 4;
107
+ data.set(image.data.subarray(start, start + width * 4), y * width * 4);
108
+ }
109
+ return { width, height, data };
110
+ }
111
+ function bounds(image, region) {
112
+ const { left, top, width, height } = region;
113
+ let minX = left + width, maxX = -1, minY = top + height, maxY = -1;
114
+ for (let y = top; y < top + height; y++) for (let x2 = left; x2 < left + width; x2++) {
115
+ if (image.data[(y * image.width + x2) * 4 + 3] < 128) continue;
116
+ minX = Math.min(minX, x2);
117
+ maxX = Math.max(maxX, x2);
118
+ minY = Math.min(minY, y);
119
+ maxY = Math.max(maxY, y);
120
+ }
121
+ return maxX < 0 ? null : { left: minX, top: minY, width: maxX - minX + 1, height: maxY - minY + 1 };
122
+ }
123
+ function runs(occupied) {
124
+ const result = [];
125
+ let start = -1;
126
+ for (let i2 = 0; i2 <= occupied.length; i2++) {
127
+ if (occupied[i2]) {
128
+ if (start < 0) start = i2;
129
+ } else if (start >= 0) {
130
+ result.push([start, i2]);
131
+ start = -1;
132
+ }
133
+ }
134
+ return result;
135
+ }
136
+ function columns(image, top, bottom) {
137
+ const used = new Uint8Array(image.width);
138
+ for (let y = top; y < bottom; y++) for (let x2 = 0; x2 < image.width; x2++) {
139
+ if (image.data[(y * image.width + x2) * 4 + 3] >= 128) used[x2] = 1;
140
+ }
141
+ return runs(used);
142
+ }
143
+ function boxesFromMask(clean, layout) {
144
+ parseLayout(layout.join(","));
145
+ let regions = columns(clean, 0, clean.height).map(([left, end]) => ({ left, top: 0, width: end - left, height: clean.height }));
146
+ if (regions.length !== layout.length) {
147
+ const rows = new Uint8Array(clean.height);
148
+ for (let y = 0; y < clean.height; y++) {
149
+ for (let x2 = 0; x2 < clean.width; x2++) {
150
+ if (clean.data[(y * clean.width + x2) * 4 + 3] >= 128) {
151
+ rows[y] = 1;
152
+ break;
153
+ }
154
+ }
155
+ }
156
+ regions = runs(rows).flatMap(([top, bottom]) => columns(clean, top, bottom).map(([left, end]) => ({ left, top, width: end - left, height: bottom - top })));
157
+ }
158
+ if (regions.length !== layout.length) {
159
+ throw new Error(`Expected ${layout.length} separated views, found ${regions.length}. Use clear gutters or individual PNGs.`);
160
+ }
161
+ return regions.map((region) => bounds(clean, region));
162
+ }
163
+ function splitAtlas(image, layout, threshold = 238) {
164
+ const clean = maskedRaster(image, threshold);
165
+ return Object.fromEntries(boxesFromMask(clean, layout).map((box, index) => {
166
+ const tile = crop(clean, box);
167
+ const width = tile.width + 2, height = tile.height + 2;
168
+ const data = new Uint8Array(width * height * 4);
169
+ for (let y = 0; y < tile.height; y++) {
170
+ data.set(tile.data.subarray(y * tile.width * 4, (y + 1) * tile.width * 4), ((y + 1) * width + 1) * 4);
171
+ }
172
+ return [layout[index], { width, height, data }];
173
+ }));
174
+ }
175
+ function prepareViews(input, threshold = 238) {
176
+ parseLayout(Object.keys(input).join(","));
177
+ const entries = Object.entries(input);
178
+ return Object.fromEntries(entries.map(([direction, image]) => {
179
+ const clean = maskedRaster(image, threshold);
180
+ const box = bounds(clean, { left: 0, top: 0, width: clean.width, height: clean.height });
181
+ if (!box) throw new Error(`The ${direction} view has an empty silhouette.`);
182
+ return [direction, crop(clean, box)];
183
+ }));
184
+ }
185
+ function inspectViews(views) {
186
+ const { top, left, front, rear } = views;
187
+ const expected = left.width / left.height * top.width / top.height;
188
+ const observed = front.width / front.height;
189
+ const warnings = [];
190
+ if (Math.abs(expected / observed - 1) > 0.2) warnings.push("Top, left, and front proportions differ by more than 20%. Check alignment.");
191
+ if (Math.abs(rear.width / rear.height / observed - 1) > 0.2) warnings.push("Front and rear proportions differ by more than 20%.");
192
+ const mapped = Object.entries(views).map(([direction, raster]) => ({ direction, width: raster.width, height: raster.height }));
193
+ return { views: mapped, warnings };
194
+ }
195
+ var DIRECTIONS;
196
+ var init_views = __esm({
197
+ "packages/core/src/views.ts"() {
198
+ "use strict";
199
+ DIRECTIONS = ["top", "left", "front", "rear", "right", "bottom"];
200
+ }
201
+ });
202
+
203
+ // packages/core/src/texture-projection.ts
204
+ function visibleFromAbove(mesh, bins) {
205
+ const { positions: p, indices, size } = mesh;
206
+ const span = Math.max(size[0], size[1]);
207
+ const nx = Math.max(1, Math.round(bins * size[0] / span));
208
+ const nz = Math.max(1, Math.round(bins * size[1] / span));
209
+ const col = (x2) => Math.min(nx - 1, Math.floor(clamp(x2 / size[0] + 0.5) * nx));
210
+ const row = (z) => Math.min(nz - 1, Math.floor(clamp(z / size[1] + 0.5) * nz));
211
+ const cells = Array.from({ length: nx * nz }, () => []);
212
+ const visible = new Uint8Array(indices.length / 3);
213
+ for (let f = 0; f < indices.length; f += 3) {
214
+ const a = indices[f] * 3, b = indices[f + 1] * 3, c = indices[f + 2] * 3;
215
+ const up = (p[b + 2] - p[a + 2]) * (p[c] - p[a]) - (p[b] - p[a]) * (p[c + 2] - p[a + 2]);
216
+ if (up <= 0) continue;
217
+ visible[f / 3] = 1;
218
+ const x0 = col(Math.min(p[a], p[b], p[c])), x1 = col(Math.max(p[a], p[b], p[c]));
219
+ const z0 = row(Math.min(p[a + 2], p[b + 2], p[c + 2])), z1 = row(Math.max(p[a + 2], p[b + 2], p[c + 2]));
220
+ for (let z = z0; z <= z1; z++) for (let x2 = x0; x2 <= x1; x2++) cells[z * nx + x2].push(f);
221
+ }
222
+ for (let f = 0; f < indices.length; f += 3) {
223
+ if (!visible[f / 3]) continue;
224
+ const a = indices[f] * 3, b = indices[f + 1] * 3, c = indices[f + 2] * 3;
225
+ const x2 = (p[a] + p[b] + p[c]) / 3, z = (p[a + 2] + p[b + 2] + p[c + 2]) / 3, y = (p[a + 1] + p[b + 1] + p[c + 1]) / 3;
226
+ for (const other of cells[row(z) * nx + col(x2)]) {
227
+ if (other === f) continue;
228
+ const i2 = indices[other] * 3, j = indices[other + 1] * 3, k = indices[other + 2] * 3;
229
+ const ux = p[j] - p[i2], uz = p[j + 2] - p[i2 + 2], vx = p[k] - p[i2], vz = p[k + 2] - p[i2 + 2];
230
+ const det = ux * vz - uz * vx;
231
+ const u = ((x2 - p[i2]) * vz - (z - p[i2 + 2]) * vx) / det, v = (ux * (z - p[i2 + 2]) - uz * (x2 - p[i2])) / det;
232
+ if (u < 0 || v < 0 || u + v > 1) continue;
233
+ const above2 = p[i2 + 1] + u * (p[j + 1] - p[i2 + 1]) + v * (p[k + 1] - p[i2 + 1]);
234
+ if (above2 > y + size[2] * 1e-6) {
235
+ visible[f / 3] = 0;
236
+ break;
237
+ }
238
+ }
239
+ }
240
+ return visible;
241
+ }
242
+ function projectUpperContour(mesh, plan, resolution, layers) {
243
+ const { positions: p, normals, uvs, indices, texture, size } = mesh;
244
+ resolution = Math.max(1, Math.min(192, Math.round(resolution) || 96));
245
+ const visible = visibleFromAbove(mesh, resolution);
246
+ const axis = size[1] >= size[0] ? 2 : 0;
247
+ const span = axis === 2 ? size[1] : size[0];
248
+ const bin = (s) => Math.min(resolution - 1, Math.floor(clamp(s / span + 0.5) * resolution));
249
+ const crest = new Float32Array(resolution).fill(-Infinity);
250
+ for (let i2 = 0; i2 < p.length; i2 += 3) {
251
+ const k = bin(p[i2 + axis]);
252
+ crest[k] = Math.max(crest[k], p[i2 + 1]);
253
+ }
254
+ const depth = size[2] * Math.max(0.1, 1.5 / layers);
255
+ const used = /* @__PURE__ */ new Map();
256
+ let triangles = 0;
257
+ for (let f = 0; f < indices.length; f += 3) {
258
+ const a = indices[f] * 3, b = indices[f + 1] * 3, c = indices[f + 2] * 3;
259
+ const s = (p[a + axis] + p[b + axis] + p[c + axis]) / 3;
260
+ const nearCrest = (p[a + 1] + p[b + 1] + p[c + 1]) / 3 >= crest[bin(s)] - depth;
261
+ const dx1 = p[b] - p[a], dy1 = p[b + 1] - p[a + 1], dz1 = p[b + 2] - p[a + 2];
262
+ const dx2 = p[c] - p[a], dy2 = p[c + 1] - p[a + 1], dz2 = p[c + 2] - p[a + 2];
263
+ const up = dz1 * dx2 - dx1 * dz2;
264
+ const nx = Math.abs(dy1 * dz2 - dz1 * dy2), nz = Math.abs(dx1 * dy2 - dy1 * dx2);
265
+ const riser = nearCrest && up === 0 && Math.abs(s) < span * 0.46 && (axis === 2 ? nz > nx : nx > nz);
266
+ if (!visible[f / 3] && !riser) continue;
267
+ triangles++;
268
+ for (let j = f; j < f + 3; j++) {
269
+ const old = indices[j];
270
+ if (!used.has(old)) used.set(old, p.length / 3 + used.size);
271
+ indices[j] = used.get(old);
272
+ }
273
+ }
274
+ if (!triangles) return 0;
275
+ const scale = Math.min(1, 512 / Math.max(plan.width, plan.height));
276
+ const w = Math.max(1, Math.round(plan.width * scale)), h = Math.max(1, Math.round(plan.height * scale));
277
+ for (let y = -1; y <= h; y++) {
278
+ const yy = Math.min(h - 1, Math.max(0, y));
279
+ const row = Math.floor((yy + 0.5) * plan.height / h) * plan.width;
280
+ const texel = (x2) => (row + Math.floor((x2 + 0.5) * plan.width / w)) * 4;
281
+ let first = 0, last = w - 1;
282
+ while (first <= last && plan.data[texel(first) + 3] < 128) first++;
283
+ while (last >= first && plan.data[texel(last) + 3] < 128) last--;
284
+ if (first > last) continue;
285
+ for (let x2 = -1; x2 <= w; x2++) {
286
+ if (x2 >= first && x2 <= last) continue;
287
+ const src = texel(x2 < first ? first : last);
288
+ texture.data.set(plan.data.subarray(src, src + 3), ((y + 1) * texture.width + x2 + 1) * 4);
289
+ }
290
+ }
291
+ const positions = new Float32Array(p.length + used.size * 3), ns = new Float32Array(positions.length);
292
+ const uv = new Float32Array(uvs.length + used.size * 2);
293
+ positions.set(p);
294
+ ns.set(normals);
295
+ uv.set(uvs);
296
+ for (const [old, v] of used) {
297
+ positions.set(p.subarray(old * 3, old * 3 + 3), v * 3);
298
+ ns.set(normals.subarray(old * 3, old * 3 + 3), v * 3);
299
+ uv[v * 2] = (1.5 + clamp(p[old * 3] / size[0] + 0.5) * (w - 1)) / texture.width;
300
+ uv[v * 2 + 1] = (1.5 + clamp(0.5 - p[old * 3 + 2] / size[1]) * (h - 1)) / texture.height;
301
+ }
302
+ Object.assign(mesh, { positions, normals: ns, uvs: uv });
303
+ return triangles;
304
+ }
305
+ var clamp;
306
+ var init_texture_projection = __esm({
307
+ "packages/core/src/texture-projection.ts"() {
308
+ "use strict";
309
+ clamp = (x2) => Math.max(0, Math.min(1, x2));
310
+ }
311
+ });
312
+
313
+ // node_modules/d3-array/dist/d3-array.mjs
314
+ function ascending(a, b) {
315
+ return a == null || b == null ? NaN : a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
316
+ }
317
+ function descending(a, b) {
318
+ return a == null || b == null ? NaN : b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
319
+ }
320
+ function bisector(f) {
321
+ let compare1, compare2, delta;
322
+ if (f.length !== 2) {
323
+ compare1 = ascending;
324
+ compare2 = (d, x2) => ascending(f(d), x2);
325
+ delta = (d, x2) => f(d) - x2;
326
+ } else {
327
+ compare1 = f === ascending || f === descending ? f : zero;
328
+ compare2 = f;
329
+ delta = f;
330
+ }
331
+ function left(a, x2, lo = 0, hi = a.length) {
332
+ if (lo < hi) {
333
+ if (compare1(x2, x2) !== 0) return hi;
334
+ do {
335
+ const mid = lo + hi >>> 1;
336
+ if (compare2(a[mid], x2) < 0) lo = mid + 1;
337
+ else hi = mid;
338
+ } while (lo < hi);
339
+ }
340
+ return lo;
341
+ }
342
+ function right(a, x2, lo = 0, hi = a.length) {
343
+ if (lo < hi) {
344
+ if (compare1(x2, x2) !== 0) return hi;
345
+ do {
346
+ const mid = lo + hi >>> 1;
347
+ if (compare2(a[mid], x2) <= 0) lo = mid + 1;
348
+ else hi = mid;
349
+ } while (lo < hi);
350
+ }
351
+ return lo;
352
+ }
353
+ function center(a, x2, lo = 0, hi = a.length) {
354
+ const i2 = left(a, x2, lo, hi - 1);
355
+ return i2 > lo && delta(a[i2 - 1], x2) > -delta(a[i2], x2) ? i2 - 1 : i2;
356
+ }
357
+ return { left, center, right };
358
+ }
359
+ function zero() {
360
+ return 0;
361
+ }
362
+ function number(x2) {
363
+ return x2 === null ? NaN : +x2;
364
+ }
365
+ function Blur2(blur) {
366
+ return function(data, rx, ry = rx) {
367
+ if (!((rx = +rx) >= 0)) throw new RangeError("invalid rx");
368
+ if (!((ry = +ry) >= 0)) throw new RangeError("invalid ry");
369
+ let { data: values, width, height } = data;
370
+ if (!((width = Math.floor(width)) >= 0)) throw new RangeError("invalid width");
371
+ if (!((height = Math.floor(height !== void 0 ? height : values.length / width)) >= 0)) throw new RangeError("invalid height");
372
+ if (!width || !height || !rx && !ry) return data;
373
+ const blurx = rx && blur(rx);
374
+ const blury = ry && blur(ry);
375
+ const temp = values.slice();
376
+ if (blurx && blury) {
377
+ blurh(blurx, temp, values, width, height);
378
+ blurh(blurx, values, temp, width, height);
379
+ blurh(blurx, temp, values, width, height);
380
+ blurv(blury, values, temp, width, height);
381
+ blurv(blury, temp, values, width, height);
382
+ blurv(blury, values, temp, width, height);
383
+ } else if (blurx) {
384
+ blurh(blurx, values, temp, width, height);
385
+ blurh(blurx, temp, values, width, height);
386
+ blurh(blurx, values, temp, width, height);
387
+ } else if (blury) {
388
+ blurv(blury, values, temp, width, height);
389
+ blurv(blury, temp, values, width, height);
390
+ blurv(blury, values, temp, width, height);
391
+ }
392
+ return data;
393
+ };
394
+ }
395
+ function blurh(blur, T, S, w, h) {
396
+ for (let y = 0, n = w * h; y < n; ) {
397
+ blur(T, S, y, y += w, 1);
398
+ }
399
+ }
400
+ function blurv(blur, T, S, w, h) {
401
+ for (let x2 = 0, n = w * h; x2 < w; ++x2) {
402
+ blur(T, S, x2, x2 + n, w);
403
+ }
404
+ }
405
+ function blurfImage(radius) {
406
+ const blur = blurf(radius);
407
+ return (T, S, start, stop, step) => {
408
+ start <<= 2, stop <<= 2, step <<= 2;
409
+ blur(T, S, start + 0, stop + 0, step);
410
+ blur(T, S, start + 1, stop + 1, step);
411
+ blur(T, S, start + 2, stop + 2, step);
412
+ blur(T, S, start + 3, stop + 3, step);
413
+ };
414
+ }
415
+ function blurf(radius) {
416
+ const radius0 = Math.floor(radius);
417
+ if (radius0 === radius) return bluri(radius);
418
+ const t = radius - radius0;
419
+ const w = 2 * radius + 1;
420
+ return (T, S, start, stop, step) => {
421
+ if (!((stop -= step) >= start)) return;
422
+ let sum = radius0 * S[start];
423
+ const s0 = step * radius0;
424
+ const s1 = s0 + step;
425
+ for (let i2 = start, j = start + s0; i2 < j; i2 += step) {
426
+ sum += S[Math.min(stop, i2)];
427
+ }
428
+ for (let i2 = start, j = stop; i2 <= j; i2 += step) {
429
+ sum += S[Math.min(stop, i2 + s0)];
430
+ T[i2] = (sum + t * (S[Math.max(start, i2 - s1)] + S[Math.min(stop, i2 + s1)])) / w;
431
+ sum -= S[Math.max(start, i2 - s0)];
432
+ }
433
+ };
434
+ }
435
+ function bluri(radius) {
436
+ const w = 2 * radius + 1;
437
+ return (T, S, start, stop, step) => {
438
+ if (!((stop -= step) >= start)) return;
439
+ let sum = radius * S[start];
440
+ const s = step * radius;
441
+ for (let i2 = start, j = start + s; i2 < j; i2 += step) {
442
+ sum += S[Math.min(stop, i2)];
443
+ }
444
+ for (let i2 = start, j = stop; i2 <= j; i2 += step) {
445
+ sum += S[Math.min(stop, i2 + s)];
446
+ T[i2] = sum / w;
447
+ sum -= S[Math.max(start, i2 - s)];
448
+ }
449
+ };
450
+ }
451
+ function count(values, valueof) {
452
+ let count2 = 0;
453
+ if (valueof === void 0) {
454
+ for (let value of values) {
455
+ if (value != null && (value = +value) >= value) {
456
+ ++count2;
457
+ }
458
+ }
459
+ } else {
460
+ let index = -1;
461
+ for (let value of values) {
462
+ if ((value = valueof(value, ++index, values)) != null && (value = +value) >= value) {
463
+ ++count2;
464
+ }
465
+ }
466
+ }
467
+ return count2;
468
+ }
469
+ function extent(values, valueof) {
470
+ let min;
471
+ let max2;
472
+ if (valueof === void 0) {
473
+ for (const value of values) {
474
+ if (value != null) {
475
+ if (min === void 0) {
476
+ if (value >= value) min = max2 = value;
477
+ } else {
478
+ if (min > value) min = value;
479
+ if (max2 < value) max2 = value;
480
+ }
481
+ }
482
+ }
483
+ } else {
484
+ let index = -1;
485
+ for (let value of values) {
486
+ if ((value = valueof(value, ++index, values)) != null) {
487
+ if (min === void 0) {
488
+ if (value >= value) min = max2 = value;
489
+ } else {
490
+ if (min > value) min = value;
491
+ if (max2 < value) max2 = value;
492
+ }
493
+ }
494
+ }
495
+ }
496
+ return [min, max2];
497
+ }
498
+ function tickSpec(start, stop, count2) {
499
+ const step = (stop - start) / Math.max(0, count2), power = Math.floor(Math.log10(step)), error = step / Math.pow(10, power), factor = error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1;
500
+ let i1, i2, inc;
501
+ if (power < 0) {
502
+ inc = Math.pow(10, -power) / factor;
503
+ i1 = Math.round(start * inc);
504
+ i2 = Math.round(stop * inc);
505
+ if (i1 / inc < start) ++i1;
506
+ if (i2 / inc > stop) --i2;
507
+ inc = -inc;
508
+ } else {
509
+ inc = Math.pow(10, power) * factor;
510
+ i1 = Math.round(start / inc);
511
+ i2 = Math.round(stop / inc);
512
+ if (i1 * inc < start) ++i1;
513
+ if (i2 * inc > stop) --i2;
514
+ }
515
+ if (i2 < i1 && 0.5 <= count2 && count2 < 2) return tickSpec(start, stop, count2 * 2);
516
+ return [i1, i2, inc];
517
+ }
518
+ function ticks(start, stop, count2) {
519
+ stop = +stop, start = +start, count2 = +count2;
520
+ if (!(count2 > 0)) return [];
521
+ if (start === stop) return [start];
522
+ const reverse = stop < start, [i1, i2, inc] = reverse ? tickSpec(stop, start, count2) : tickSpec(start, stop, count2);
523
+ if (!(i2 >= i1)) return [];
524
+ const n = i2 - i1 + 1, ticks2 = new Array(n);
525
+ if (reverse) {
526
+ if (inc < 0) for (let i3 = 0; i3 < n; ++i3) ticks2[i3] = (i2 - i3) / -inc;
527
+ else for (let i3 = 0; i3 < n; ++i3) ticks2[i3] = (i2 - i3) * inc;
528
+ } else {
529
+ if (inc < 0) for (let i3 = 0; i3 < n; ++i3) ticks2[i3] = (i1 + i3) / -inc;
530
+ else for (let i3 = 0; i3 < n; ++i3) ticks2[i3] = (i1 + i3) * inc;
531
+ }
532
+ return ticks2;
533
+ }
534
+ function tickIncrement(start, stop, count2) {
535
+ stop = +stop, start = +start, count2 = +count2;
536
+ return tickSpec(start, stop, count2)[2];
537
+ }
538
+ function nice(start, stop, count2) {
539
+ let prestep;
540
+ while (true) {
541
+ const step = tickIncrement(start, stop, count2);
542
+ if (step === prestep || step === 0 || !isFinite(step)) {
543
+ return [start, stop];
544
+ } else if (step > 0) {
545
+ const i2 = Math.ceil(start / step);
546
+ const j = Math.floor(stop / step);
547
+ start = (i2 - (i2 * step > start)) * step;
548
+ stop = (j + (j * step < stop)) * step;
549
+ } else if (step < 0) {
550
+ const s = -step;
551
+ const i2 = Math.ceil(start * s);
552
+ const j = Math.floor(stop * s);
553
+ start = (i2 - (i2 / s > start)) / s;
554
+ stop = (j + (j / s < stop)) / s;
555
+ }
556
+ prestep = step;
557
+ }
558
+ }
559
+ function thresholdSturges(values) {
560
+ return Math.max(1, Math.ceil(Math.log(count(values)) / Math.LN2) + 1);
561
+ }
562
+ function shuffler(random) {
563
+ return function shuffle2(array3, i0 = 0, i1 = array3.length) {
564
+ let m = i1 - (i0 = +i0);
565
+ while (m) {
566
+ const i2 = random() * m-- | 0, t = array3[m + i0];
567
+ array3[m + i0] = array3[i2 + i0];
568
+ array3[i2 + i0] = t;
569
+ }
570
+ return array3;
571
+ };
572
+ }
573
+ var ascendingBisect, bisectRight, bisectLeft, bisectCenter, blur2, blurImage, array, slice, e10, e5, e2, shuffle;
574
+ var init_d3_array = __esm({
575
+ "node_modules/d3-array/dist/d3-array.mjs"() {
576
+ ascendingBisect = bisector(ascending);
577
+ bisectRight = ascendingBisect.right;
578
+ bisectLeft = ascendingBisect.left;
579
+ bisectCenter = bisector(number).center;
580
+ blur2 = Blur2(blurf);
581
+ blurImage = Blur2(blurfImage);
582
+ array = Array.prototype;
583
+ slice = array.slice;
584
+ e10 = Math.sqrt(50);
585
+ e5 = Math.sqrt(10);
586
+ e2 = Math.sqrt(2);
587
+ shuffle = shuffler(Math.random);
588
+ }
589
+ });
590
+
591
+ // node_modules/d3-contour/dist/d3-contour.mjs
592
+ function ascending2(a, b) {
593
+ return a - b;
594
+ }
595
+ function area(ring) {
596
+ var i2 = 0, n = ring.length, area3 = ring[n - 1][1] * ring[0][0] - ring[n - 1][0] * ring[0][1];
597
+ while (++i2 < n) area3 += ring[i2 - 1][1] * ring[i2][0] - ring[i2 - 1][0] * ring[i2][1];
598
+ return area3;
599
+ }
600
+ function contains(ring, hole) {
601
+ var i2 = -1, n = hole.length, c;
602
+ while (++i2 < n) if (c = ringContains(ring, hole[i2])) return c;
603
+ return 0;
604
+ }
605
+ function ringContains(ring, point) {
606
+ var x2 = point[0], y = point[1], contains2 = -1;
607
+ for (var i2 = 0, n = ring.length, j = n - 1; i2 < n; j = i2++) {
608
+ var pi = ring[i2], xi = pi[0], yi = pi[1], pj = ring[j], xj = pj[0], yj = pj[1];
609
+ if (segmentContains(pi, pj, point)) return 0;
610
+ if (yi > y !== yj > y && x2 < (xj - xi) * (y - yi) / (yj - yi) + xi) contains2 = -contains2;
611
+ }
612
+ return contains2;
613
+ }
614
+ function segmentContains(a, b, c) {
615
+ var i2;
616
+ return collinear(a, b, c) && within(a[i2 = +(a[0] === b[0])], c[i2], b[i2]);
617
+ }
618
+ function collinear(a, b, c) {
619
+ return (b[0] - a[0]) * (c[1] - a[1]) === (c[0] - a[0]) * (b[1] - a[1]);
620
+ }
621
+ function within(p, q, r) {
622
+ return p <= q && q <= r || r <= q && q <= p;
623
+ }
624
+ function noop() {
625
+ }
626
+ function Contours() {
627
+ var dx = 1, dy = 1, threshold = thresholdSturges, smooth = smoothLinear;
628
+ function contours(values) {
629
+ var tz = threshold(values);
630
+ if (!Array.isArray(tz)) {
631
+ const e = extent(values, finite);
632
+ tz = ticks(...nice(e[0], e[1], tz), tz);
633
+ while (tz[tz.length - 1] >= e[1]) tz.pop();
634
+ while (tz[1] < e[0]) tz.shift();
635
+ } else {
636
+ tz = tz.slice().sort(ascending2);
637
+ }
638
+ return tz.map((value) => contour(values, value));
639
+ }
640
+ function contour(values, value) {
641
+ const v = value == null ? NaN : +value;
642
+ if (isNaN(v)) throw new Error(`invalid value: ${value}`);
643
+ var polygons = [], holes = [];
644
+ isorings(values, v, function(ring) {
645
+ smooth(ring, values, v);
646
+ if (area(ring) > 0) polygons.push([ring]);
647
+ else holes.push(ring);
648
+ });
649
+ holes.forEach(function(hole) {
650
+ for (var i2 = 0, n = polygons.length, polygon; i2 < n; ++i2) {
651
+ if (contains((polygon = polygons[i2])[0], hole) !== -1) {
652
+ polygon.push(hole);
653
+ return;
654
+ }
655
+ }
656
+ });
657
+ return {
658
+ type: "MultiPolygon",
659
+ value,
660
+ coordinates: polygons
661
+ };
662
+ }
663
+ function isorings(values, value, callback) {
664
+ var fragmentByStart = new Array(), fragmentByEnd = new Array(), x2, y, t0, t1, t2, t3;
665
+ x2 = y = -1;
666
+ t1 = above(values[0], value);
667
+ cases[t1 << 1].forEach(stitch);
668
+ while (++x2 < dx - 1) {
669
+ t0 = t1, t1 = above(values[x2 + 1], value);
670
+ cases[t0 | t1 << 1].forEach(stitch);
671
+ }
672
+ cases[t1 << 0].forEach(stitch);
673
+ while (++y < dy - 1) {
674
+ x2 = -1;
675
+ t1 = above(values[y * dx + dx], value);
676
+ t2 = above(values[y * dx], value);
677
+ cases[t1 << 1 | t2 << 2].forEach(stitch);
678
+ while (++x2 < dx - 1) {
679
+ t0 = t1, t1 = above(values[y * dx + dx + x2 + 1], value);
680
+ t3 = t2, t2 = above(values[y * dx + x2 + 1], value);
681
+ cases[t0 | t1 << 1 | t2 << 2 | t3 << 3].forEach(stitch);
682
+ }
683
+ cases[t1 | t2 << 3].forEach(stitch);
684
+ }
685
+ x2 = -1;
686
+ t2 = values[y * dx] >= value;
687
+ cases[t2 << 2].forEach(stitch);
688
+ while (++x2 < dx - 1) {
689
+ t3 = t2, t2 = above(values[y * dx + x2 + 1], value);
690
+ cases[t2 << 2 | t3 << 3].forEach(stitch);
691
+ }
692
+ cases[t2 << 3].forEach(stitch);
693
+ function stitch(line) {
694
+ var start = [line[0][0] + x2, line[0][1] + y], end = [line[1][0] + x2, line[1][1] + y], startIndex = index(start), endIndex = index(end), f, g;
695
+ if (f = fragmentByEnd[startIndex]) {
696
+ if (g = fragmentByStart[endIndex]) {
697
+ delete fragmentByEnd[f.end];
698
+ delete fragmentByStart[g.start];
699
+ if (f === g) {
700
+ f.ring.push(end);
701
+ callback(f.ring);
702
+ } else {
703
+ fragmentByStart[f.start] = fragmentByEnd[g.end] = { start: f.start, end: g.end, ring: f.ring.concat(g.ring) };
704
+ }
705
+ } else {
706
+ delete fragmentByEnd[f.end];
707
+ f.ring.push(end);
708
+ fragmentByEnd[f.end = endIndex] = f;
709
+ }
710
+ } else if (f = fragmentByStart[endIndex]) {
711
+ if (g = fragmentByEnd[startIndex]) {
712
+ delete fragmentByStart[f.start];
713
+ delete fragmentByEnd[g.end];
714
+ if (f === g) {
715
+ f.ring.push(end);
716
+ callback(f.ring);
717
+ } else {
718
+ fragmentByStart[g.start] = fragmentByEnd[f.end] = { start: g.start, end: f.end, ring: g.ring.concat(f.ring) };
719
+ }
720
+ } else {
721
+ delete fragmentByStart[f.start];
722
+ f.ring.unshift(start);
723
+ fragmentByStart[f.start = startIndex] = f;
724
+ }
725
+ } else {
726
+ fragmentByStart[startIndex] = fragmentByEnd[endIndex] = { start: startIndex, end: endIndex, ring: [start, end] };
727
+ }
728
+ }
729
+ }
730
+ function index(point) {
731
+ return point[0] * 2 + point[1] * (dx + 1) * 4;
732
+ }
733
+ function smoothLinear(ring, values, value) {
734
+ ring.forEach(function(point) {
735
+ var x2 = point[0], y = point[1], xt = x2 | 0, yt = y | 0, v1 = valid(values[yt * dx + xt]);
736
+ if (x2 > 0 && x2 < dx && xt === x2) {
737
+ point[0] = smooth1(x2, valid(values[yt * dx + xt - 1]), v1, value);
738
+ }
739
+ if (y > 0 && y < dy && yt === y) {
740
+ point[1] = smooth1(y, valid(values[(yt - 1) * dx + xt]), v1, value);
741
+ }
742
+ });
743
+ }
744
+ contours.contour = contour;
745
+ contours.size = function(_) {
746
+ if (!arguments.length) return [dx, dy];
747
+ var _0 = Math.floor(_[0]), _1 = Math.floor(_[1]);
748
+ if (!(_0 >= 0 && _1 >= 0)) throw new Error("invalid size");
749
+ return dx = _0, dy = _1, contours;
750
+ };
751
+ contours.thresholds = function(_) {
752
+ return arguments.length ? (threshold = typeof _ === "function" ? _ : Array.isArray(_) ? constant(slice2.call(_)) : constant(_), contours) : threshold;
753
+ };
754
+ contours.smooth = function(_) {
755
+ return arguments.length ? (smooth = _ ? smoothLinear : noop, contours) : smooth === smoothLinear;
756
+ };
757
+ return contours;
758
+ }
759
+ function finite(x2) {
760
+ return isFinite(x2) ? x2 : NaN;
761
+ }
762
+ function above(x2, value) {
763
+ return x2 == null ? false : +x2 >= value;
764
+ }
765
+ function valid(v) {
766
+ return v == null || isNaN(v = +v) ? -Infinity : v;
767
+ }
768
+ function smooth1(x2, v0, v1, value) {
769
+ const a = value - v0;
770
+ const b = v1 - v0;
771
+ const d = isFinite(a) || isFinite(b) ? a / b : Math.sign(a) / Math.sign(b);
772
+ return isNaN(d) ? x2 : x2 + d - 0.5;
773
+ }
774
+ var array2, slice2, constant, cases;
775
+ var init_d3_contour = __esm({
776
+ "node_modules/d3-contour/dist/d3-contour.mjs"() {
777
+ init_d3_array();
778
+ array2 = Array.prototype;
779
+ slice2 = array2.slice;
780
+ constant = (x2) => () => x2;
781
+ cases = [
782
+ [],
783
+ [[[1, 1.5], [0.5, 1]]],
784
+ [[[1.5, 1], [1, 1.5]]],
785
+ [[[1.5, 1], [0.5, 1]]],
786
+ [[[1, 0.5], [1.5, 1]]],
787
+ [[[1, 1.5], [0.5, 1]], [[1, 0.5], [1.5, 1]]],
788
+ [[[1, 0.5], [1, 1.5]]],
789
+ [[[1, 0.5], [0.5, 1]]],
790
+ [[[0.5, 1], [1, 0.5]]],
791
+ [[[1, 1.5], [1, 0.5]]],
792
+ [[[0.5, 1], [1, 0.5]], [[1.5, 1], [1, 1.5]]],
793
+ [[[1.5, 1], [1, 0.5]]],
794
+ [[[0.5, 1], [1.5, 1]]],
795
+ [[[1, 1.5], [1.5, 1]]],
796
+ [[[0.5, 1], [1, 1.5]]],
797
+ []
798
+ ];
799
+ }
800
+ });
801
+
802
+ // node_modules/earcut/src/earcut.js
803
+ function earcut(data, holeIndices, dim = 2) {
804
+ const hasHoles = holeIndices && holeIndices.length;
805
+ const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
806
+ if (steiners.size) steiners.clear();
807
+ let outerNode = linkedList(data, 0, outerLen, dim, true);
808
+ const triangles = [];
809
+ if (!outerNode || outerNode.next === outerNode.prev) return triangles;
810
+ let minX = 0, minY = 0, invSize = 0;
811
+ if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
812
+ if (data.length > 80 * dim) {
813
+ minX = data[0];
814
+ minY = data[1];
815
+ let maxX = minX;
816
+ let maxY = minY;
817
+ for (let i2 = dim; i2 < outerLen; i2 += dim) {
818
+ const x2 = data[i2];
819
+ const y = data[i2 + 1];
820
+ if (x2 < minX) minX = x2;
821
+ if (y < minY) minY = y;
822
+ if (x2 > maxX) maxX = x2;
823
+ if (y > maxY) maxY = y;
824
+ }
825
+ invSize = Math.max(maxX - minX, maxY - minY);
826
+ invSize = invSize !== 0 ? 32767 / invSize : 0;
827
+ }
828
+ earcutLinked(outerNode, triangles, minX, minY, invSize);
829
+ return triangles;
830
+ }
831
+ function linkedList(data, start, end, dim, clockwise) {
832
+ let last = null;
833
+ if (clockwise === signedArea(data, start, end, dim) > 0) {
834
+ for (let i2 = start; i2 < end; i2 += dim) last = insertNode(i2 / dim | 0, data[i2], data[i2 + 1], last);
835
+ } else {
836
+ for (let i2 = end - dim; i2 >= start; i2 -= dim) last = insertNode(i2 / dim | 0, data[i2], data[i2 + 1], last);
837
+ }
838
+ if (last && equals(last, last.next)) {
839
+ removeNode(last);
840
+ last = last.next;
841
+ }
842
+ return last;
843
+ }
844
+ function filterPoints(start, end = start) {
845
+ const full = end === start;
846
+ let p = start, again;
847
+ do {
848
+ again = false;
849
+ if (p !== p.next && (steiners.size === 0 || !steiners.has(p)) && (equals(p, p.next) || area2(p.prev, p, p.next) === 0)) {
850
+ if (full || p === end) end = p.prev;
851
+ filteredOut = true;
852
+ removeNode(p);
853
+ p = p.prev;
854
+ again = true;
855
+ } else if (full || p !== end) {
856
+ p = p.next;
857
+ again = !full;
858
+ }
859
+ } while (again || p !== end);
860
+ return end;
861
+ }
862
+ function earcutLinked(ear, triangles, minX, minY, invSize) {
863
+ if (invSize) indexCurve(ear, minX, minY, invSize);
864
+ let stop = ear, cured = false;
865
+ while (ear.prev !== ear.next) {
866
+ const prev = ear.prev;
867
+ const next = ear.next;
868
+ if (area2(prev, ear, next) < 0 && (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear))) {
869
+ triangles.push(prev.i, ear.i, next.i);
870
+ removeNode(ear);
871
+ ear = next;
872
+ stop = next;
873
+ continue;
874
+ }
875
+ ear = next;
876
+ if (ear === stop) {
877
+ filteredOut = false;
878
+ ear = filterPoints(ear);
879
+ if (filteredOut) {
880
+ stop = ear;
881
+ continue;
882
+ }
883
+ if (!cured) {
884
+ ear = cureLocalIntersections(ear, triangles);
885
+ stop = ear;
886
+ cured = true;
887
+ continue;
888
+ }
889
+ splitEarcut(ear, triangles, minX, minY, invSize);
890
+ break;
891
+ }
892
+ }
893
+ }
894
+ function isEar(ear) {
895
+ const a = ear.prev, b = ear, c = ear.next, ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y, x0 = Math.min(ax, bx, cx), y0 = Math.min(ay, by, cy), x1 = Math.max(ax, bx, cx), y1 = Math.max(ay, by, cy);
896
+ let p = c.next;
897
+ while (p !== a) {
898
+ if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && !(ax === p.x && ay === p.y) && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area2(p.prev, p, p.next) >= 0) return false;
899
+ p = p.next;
900
+ }
901
+ return true;
902
+ }
903
+ function isEarHashed(ear, minX, minY, invSize) {
904
+ const a = ear.prev, b = ear, c = ear.next, ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y, x0 = Math.min(ax, bx, cx), y0 = Math.min(ay, by, cy), x1 = Math.max(ax, bx, cx), y1 = Math.max(ay, by, cy), minZ = zOrder(x0, y0, minX, minY, invSize), maxZ = zOrder(x1, y1, minX, minY, invSize);
905
+ let p = ear.prevZ;
906
+ while (p && p.z >= minZ) {
907
+ if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== c && !(ax === p.x && ay === p.y) && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area2(p.prev, p, p.next) >= 0) return false;
908
+ p = p.prevZ;
909
+ }
910
+ let n = ear.nextZ;
911
+ while (n && n.z <= maxZ) {
912
+ if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== c && !(ax === n.x && ay === n.y) && pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area2(n.prev, n, n.next) >= 0) return false;
913
+ n = n.nextZ;
914
+ }
915
+ return true;
916
+ }
917
+ function cureLocalIntersections(start, triangles) {
918
+ let p = start;
919
+ let cured = false;
920
+ do {
921
+ const a = p.prev, b = p.next.next;
922
+ if (intersects(a, p, p.next, b, false) && locallyInside(a, b) && locallyInside(b, a)) {
923
+ triangles.push(a.i, p.i, b.i);
924
+ removeNode(p);
925
+ removeNode(p.next);
926
+ p = start = b;
927
+ cured = true;
928
+ }
929
+ p = p.next;
930
+ } while (p !== start);
931
+ return cured ? filterPoints(p) : p;
932
+ }
933
+ function splitEarcut(start, triangles, minX, minY, invSize) {
934
+ let a = start;
935
+ do {
936
+ let b = a.next.next;
937
+ while (b !== a.prev) {
938
+ if (a.i !== b.i && isValidDiagonal(a, b)) {
939
+ let c = splitPolygon(a, b);
940
+ a = filterPoints(a, a.next);
941
+ c = filterPoints(c, c.next);
942
+ earcutLinked(a, triangles, minX, minY, invSize);
943
+ earcutLinked(c, triangles, minX, minY, invSize);
944
+ return;
945
+ }
946
+ b = b.next;
947
+ }
948
+ a = a.next;
949
+ } while (a !== start);
950
+ }
951
+ function eliminateHoles(data, holeIndices, outerNode, dim) {
952
+ const queue = [];
953
+ for (let i2 = 0, len = holeIndices.length; i2 < len; i2++) {
954
+ const start = holeIndices[i2] * dim;
955
+ const end = i2 < len - 1 ? holeIndices[i2 + 1] * dim : data.length;
956
+ const list = (
957
+ /** @type {Node} */
958
+ linkedList(data, start, end, dim, false)
959
+ );
960
+ if (list === list.next) steiners.add(list);
961
+ queue.push(getLeftmost(list));
962
+ }
963
+ queue.sort(compareXYSlope);
964
+ buildBlockIndex(data.length / dim, holeIndices.length);
965
+ indexSegment(outerNode, outerNode);
966
+ indexActive = true;
967
+ for (let i2 = 0; i2 < queue.length; i2++) {
968
+ outerNode = eliminateHole(queue[i2], outerNode);
969
+ }
970
+ indexActive = false;
971
+ return filterPoints(outerNode);
972
+ }
973
+ function compareXYSlope(a, b) {
974
+ return a.x - b.x || a.y - b.y || (a.next.y - a.y) / (a.next.x - a.x) - (b.next.y - b.y) / (b.next.x - b.x);
975
+ }
976
+ function eliminateHole(hole, outerNode) {
977
+ const bridge = findHoleBridge(hole, outerNode);
978
+ if (!bridge) {
979
+ return outerNode;
980
+ }
981
+ const bridgeReverse = splitPolygon(bridge, hole);
982
+ const bridge2 = bridgeReverse.next;
983
+ indexSegment(bridge, bridge2.next);
984
+ filterPoints(bridgeReverse, bridgeReverse.next);
985
+ return filterPoints(bridge, bridge.next);
986
+ }
987
+ function buildBlockIndex(maxNodes, numHoles) {
988
+ const maxBlocks = Math.ceil((maxNodes + 2 * numHoles) / K) + numHoles + 2;
989
+ if (blockBBox.length < maxBlocks * 4) blockBBox = new Float64Array(maxBlocks * 4);
990
+ numBlocks = 0;
991
+ }
992
+ function indexSegment(head, stop) {
993
+ let p = head;
994
+ do {
995
+ const b = numBlocks++;
996
+ blockHead[b] = p;
997
+ let minX = p.x, minY = p.y, maxX = p.x, maxY = p.y;
998
+ let k = 0;
999
+ do {
1000
+ const c = p.next;
1001
+ p.z = b;
1002
+ if (c.x < minX) minX = c.x;
1003
+ if (c.x > maxX) maxX = c.x;
1004
+ if (c.y < minY) minY = c.y;
1005
+ if (c.y > maxY) maxY = c.y;
1006
+ p = c;
1007
+ } while (++k < K && p !== stop);
1008
+ blockStop[b] = p;
1009
+ const g = b * 4;
1010
+ blockBBox[g] = minX;
1011
+ blockBBox[g + 1] = minY;
1012
+ blockBBox[g + 2] = maxX;
1013
+ blockBBox[g + 3] = maxY;
1014
+ } while (p !== stop);
1015
+ }
1016
+ function growBlock(head, tail) {
1017
+ const g = head.z * 4;
1018
+ if (tail.x < blockBBox[g]) blockBBox[g] = tail.x;
1019
+ if (tail.y < blockBBox[g + 1]) blockBBox[g + 1] = tail.y;
1020
+ if (tail.x > blockBBox[g + 2]) blockBBox[g + 2] = tail.x;
1021
+ if (tail.y > blockBBox[g + 3]) blockBBox[g + 3] = tail.y;
1022
+ }
1023
+ function liveBlockStop(b) {
1024
+ let stop = blockStop[b];
1025
+ while (stop.prev.next !== stop) stop = stop.next;
1026
+ blockStop[b] = stop;
1027
+ return stop;
1028
+ }
1029
+ function liveBlockHead(b) {
1030
+ let head = blockHead[b];
1031
+ while (head.prev.next !== head) head = head.next;
1032
+ blockHead[b] = head;
1033
+ return head;
1034
+ }
1035
+ function findHoleBridge(hole, outerNode) {
1036
+ let p = outerNode;
1037
+ const hx = hole.x;
1038
+ const hy = hole.y;
1039
+ let qx = -Infinity;
1040
+ let m;
1041
+ if (equals(hole, p)) return p;
1042
+ for (let b = 0, g = 0; b < numBlocks; b++, g += 4) {
1043
+ if (hy < blockBBox[g + 1] || hy > blockBBox[g + 3] || blockBBox[g] > hx || blockBBox[g + 2] <= qx) continue;
1044
+ const stop = liveBlockStop(b);
1045
+ p = liveBlockHead(b);
1046
+ do {
1047
+ if (p.prev.next === p) {
1048
+ if (equals(hole, p.next)) return p.next;
1049
+ else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
1050
+ const x2 = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
1051
+ if (x2 <= hx && x2 > qx) {
1052
+ qx = x2;
1053
+ m = p.x < p.next.x ? p : p.next;
1054
+ if (x2 === hx) return m;
1055
+ }
1056
+ }
1057
+ }
1058
+ p = p.next;
1059
+ } while (p !== stop);
1060
+ }
1061
+ if (!m) return null;
1062
+ const mx = m.x;
1063
+ const my = m.y;
1064
+ const tminY = Math.min(hy, my);
1065
+ const tmaxY = Math.max(hy, my);
1066
+ let tanMin = Infinity;
1067
+ for (let b = 0, g = 0; b < numBlocks; b++, g += 4) {
1068
+ if (blockBBox[g + 2] < mx || blockBBox[g] > hx || blockBBox[g + 3] < tminY || blockBBox[g + 1] > tmaxY) continue;
1069
+ const stop = liveBlockStop(b);
1070
+ p = liveBlockHead(b);
1071
+ do {
1072
+ if (p.prev.next === p && hx >= p.x && p.x >= mx && hx !== p.x && // skip dead nodes
1073
+ pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
1074
+ const tan = Math.abs(hy - p.y) / (hx - p.x);
1075
+ if ((locallyInside(p, hole) || p.y === hy && p.next.y === hy && p.next.x > hx) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
1076
+ m = p;
1077
+ tanMin = tan;
1078
+ }
1079
+ }
1080
+ p = p.next;
1081
+ } while (p !== stop);
1082
+ }
1083
+ return m;
1084
+ }
1085
+ function sectorContainsSector(m, p) {
1086
+ return area2(m.prev, m, p.prev) < 0 && area2(p.next, m, m.next) < 0;
1087
+ }
1088
+ function indexCurve(start, minX, minY, invSize) {
1089
+ let p = start;
1090
+ let n = 0;
1091
+ do {
1092
+ p.z = zOrder(p.x, p.y, minX, minY, invSize);
1093
+ sortArr[n++] = p;
1094
+ p = p.next;
1095
+ } while (p !== start);
1096
+ sortNodes(n);
1097
+ let prev = null;
1098
+ for (let i2 = 0; i2 < n; i2++) {
1099
+ const node = sortArr[i2];
1100
+ node.prevZ = prev;
1101
+ if (prev) prev.nextZ = node;
1102
+ prev = node;
1103
+ }
1104
+ prev.nextZ = null;
1105
+ sortArr.fill(
1106
+ /** @type {Node} */
1107
+ /** @type {unknown} */
1108
+ null,
1109
+ 0,
1110
+ n
1111
+ );
1112
+ sortBuf.fill(
1113
+ /** @type {Node} */
1114
+ /** @type {unknown} */
1115
+ null,
1116
+ 0,
1117
+ n
1118
+ );
1119
+ }
1120
+ function sortNodes(n) {
1121
+ if (n <= 32) {
1122
+ for (let i2 = 1; i2 < n; i2++) {
1123
+ const node = sortArr[i2], z = node.z;
1124
+ let j = i2 - 1;
1125
+ while (j >= 0 && sortArr[j].z > z) {
1126
+ sortArr[j + 1] = sortArr[j];
1127
+ j--;
1128
+ }
1129
+ sortArr[j + 1] = node;
1130
+ }
1131
+ return;
1132
+ }
1133
+ if (zArr.length < n) {
1134
+ zArr = new Uint32Array(n);
1135
+ zBuf = new Uint32Array(n);
1136
+ sortBuf = new Array(n);
1137
+ }
1138
+ for (let i2 = 0; i2 < n; i2++) zArr[i2] = sortArr[i2].z;
1139
+ radixPass(n, sortArr, zArr, sortBuf, zBuf, 0);
1140
+ radixPass(n, sortBuf, zBuf, sortArr, zArr, 8);
1141
+ radixPass(n, sortArr, zArr, sortBuf, zBuf, 16);
1142
+ radixPass(n, sortBuf, zBuf, sortArr, zArr, 24);
1143
+ }
1144
+ function radixPass(n, src, srcZ, dst, dstZ, shift) {
1145
+ counts.fill(0);
1146
+ for (let i2 = 0; i2 < n; i2++) counts[srcZ[i2] >>> shift & 255]++;
1147
+ let sum = 0;
1148
+ for (let b = 0; b < 256; b++) {
1149
+ const c = counts[b];
1150
+ counts[b] = sum;
1151
+ sum += c;
1152
+ }
1153
+ for (let i2 = 0; i2 < n; i2++) {
1154
+ const z = srcZ[i2];
1155
+ const pos = counts[z >>> shift & 255]++;
1156
+ dst[pos] = src[i2];
1157
+ dstZ[pos] = z;
1158
+ }
1159
+ }
1160
+ function zOrder(x2, y, minX, minY, invSize) {
1161
+ x2 = (x2 - minX) * invSize | 0;
1162
+ y = (y - minY) * invSize | 0;
1163
+ x2 = (x2 | x2 << 8) & 16711935;
1164
+ x2 = (x2 | x2 << 4) & 252645135;
1165
+ x2 = (x2 | x2 << 2) & 858993459;
1166
+ x2 = (x2 | x2 << 1) & 1431655765;
1167
+ y = (y | y << 8) & 16711935;
1168
+ y = (y | y << 4) & 252645135;
1169
+ y = (y | y << 2) & 858993459;
1170
+ y = (y | y << 1) & 1431655765;
1171
+ return x2 | y << 1;
1172
+ }
1173
+ function getLeftmost(start) {
1174
+ let p = start, leftmost = start;
1175
+ do {
1176
+ if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
1177
+ p = p.next;
1178
+ } while (p !== start);
1179
+ return leftmost;
1180
+ }
1181
+ function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
1182
+ return (cx - px) * (ay - py) >= (ax - px) * (cy - py) && (ax - px) * (by - py) >= (bx - px) * (ay - py) && (bx - px) * (cy - py) >= (cx - px) * (by - py);
1183
+ }
1184
+ function isValidDiagonal(a, b) {
1185
+ const zeroLength = equals(a, b) && area2(a.prev, a, a.next) > 0 && area2(b.prev, b, b.next) > 0;
1186
+ return a.next.i !== b.i && (zeroLength || locallyInside(a, b) && locallyInside(b, a) && // // locally visible
1187
+ (area2(a.prev, a, b.prev) !== 0 || area2(a, b.prev, b) !== 0)) && // no opposite-facing sectors
1188
+ !intersectsPolygon(a, b) && (zeroLength || middleInside(a, b));
1189
+ }
1190
+ function area2(p, q, r) {
1191
+ return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
1192
+ }
1193
+ function equals(p1, p2) {
1194
+ return p1.x === p2.x && p1.y === p2.y;
1195
+ }
1196
+ function intersects(p1, q1, p2, q2, includeBoundary = true) {
1197
+ const o1 = area2(p1, q1, p2);
1198
+ const o2 = area2(p1, q1, q2);
1199
+ const o3 = area2(p2, q2, p1);
1200
+ const o4 = area2(p2, q2, q1);
1201
+ if ((o1 > 0 && o2 < 0 || o1 < 0 && o2 > 0) && (o3 > 0 && o4 < 0 || o3 < 0 && o4 > 0)) return true;
1202
+ if (!includeBoundary) return false;
1203
+ if (o1 === 0 && onSegment(p1, p2, q1)) return true;
1204
+ if (o2 === 0 && onSegment(p1, q2, q1)) return true;
1205
+ if (o3 === 0 && onSegment(p2, p1, q2)) return true;
1206
+ if (o4 === 0 && onSegment(p2, q1, q2)) return true;
1207
+ return false;
1208
+ }
1209
+ function onSegment(p, q, r) {
1210
+ return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);
1211
+ }
1212
+ function intersectsPolygon(a, b) {
1213
+ const minX = Math.min(a.x, b.x);
1214
+ const maxX = Math.max(a.x, b.x);
1215
+ const minY = Math.min(a.y, b.y);
1216
+ const maxY = Math.max(a.y, b.y);
1217
+ let p = a;
1218
+ do {
1219
+ const n = p.next;
1220
+ if (p.x > maxX && n.x > maxX || p.x < minX && n.x < minX || p.y > maxY && n.y > maxY || p.y < minY && n.y < minY) {
1221
+ p = n;
1222
+ continue;
1223
+ }
1224
+ if (p.i !== a.i && n.i !== a.i && p.i !== b.i && n.i !== b.i && intersects(p, n, a, b)) return true;
1225
+ p = n;
1226
+ } while (p !== a);
1227
+ return false;
1228
+ }
1229
+ function locallyInside(a, b) {
1230
+ return area2(a.prev, a, a.next) < 0 ? area2(a, b, a.next) >= 0 && area2(a, a.prev, b) >= 0 : area2(a, b, a.prev) < 0 || area2(a, a.next, b) < 0;
1231
+ }
1232
+ function middleInside(a, b) {
1233
+ let p = a;
1234
+ let inside = false;
1235
+ const px = (a.x + b.x) / 2;
1236
+ const py = (a.y + b.y) / 2;
1237
+ do {
1238
+ const n = p.next;
1239
+ if (p.y > py !== n.y > py && px < (n.x - p.x) * (py - p.y) / (n.y - p.y) + p.x)
1240
+ inside = !inside;
1241
+ p = n;
1242
+ } while (p !== a);
1243
+ return inside;
1244
+ }
1245
+ function splitPolygon(a, b) {
1246
+ const a2 = createNode(a.i, a.x, a.y), b2 = createNode(b.i, b.x, b.y), an = a.next, bp = b.prev;
1247
+ a.next = b;
1248
+ b.prev = a;
1249
+ a2.next = an;
1250
+ an.prev = a2;
1251
+ b2.next = a2;
1252
+ a2.prev = b2;
1253
+ bp.next = b2;
1254
+ b2.prev = bp;
1255
+ return b2;
1256
+ }
1257
+ function insertNode(i2, x2, y, last) {
1258
+ const p = createNode(i2, x2, y);
1259
+ if (!last) {
1260
+ p.prev = p;
1261
+ p.next = p;
1262
+ } else {
1263
+ p.next = last.next;
1264
+ p.prev = last;
1265
+ last.next.prev = p;
1266
+ last.next = p;
1267
+ }
1268
+ return p;
1269
+ }
1270
+ function removeNode(p) {
1271
+ p.next.prev = p.prev;
1272
+ p.prev.next = p.next;
1273
+ if (p.prevZ) p.prevZ.nextZ = p.nextZ;
1274
+ if (p.nextZ) p.nextZ.prevZ = p.prevZ;
1275
+ if (indexActive) growBlock(p.prev, p.next);
1276
+ }
1277
+ function createNode(i2, x2, y) {
1278
+ return (
1279
+ /** @type {Node} */
1280
+ /** @type {unknown} */
1281
+ {
1282
+ i: i2,
1283
+ // vertex index in coordinates array
1284
+ x: x2,
1285
+ y,
1286
+ // vertex coordinates
1287
+ prev: null,
1288
+ // previous and next vertex nodes in a polygon ring
1289
+ next: null,
1290
+ z: 0,
1291
+ // z-order curve value; doubles as owning block in the hole-bridge index during eliminateHoles
1292
+ prevZ: null,
1293
+ // previous and next nodes in z-order
1294
+ nextZ: null
1295
+ }
1296
+ );
1297
+ }
1298
+ function signedArea(data, start, end, dim) {
1299
+ let sum = 0;
1300
+ for (let i2 = start, j = end - dim; i2 < end; i2 += dim) {
1301
+ sum += (data[j] - data[i2]) * (data[i2 + 1] + data[j + 1]);
1302
+ j = i2;
1303
+ }
1304
+ return sum;
1305
+ }
1306
+ var steiners, filteredOut, indexActive, K, blockBBox, numBlocks, blockHead, blockStop, sortArr, sortBuf, zArr, zBuf, counts;
1307
+ var init_earcut = __esm({
1308
+ "node_modules/earcut/src/earcut.js"() {
1309
+ steiners = /* @__PURE__ */ new Set();
1310
+ filteredOut = false;
1311
+ indexActive = false;
1312
+ K = 16;
1313
+ blockBBox = new Float64Array(0);
1314
+ numBlocks = 0;
1315
+ blockHead = [];
1316
+ blockStop = [];
1317
+ sortArr = [];
1318
+ sortBuf = [];
1319
+ zArr = new Uint32Array(0);
1320
+ zBuf = new Uint32Array(0);
1321
+ counts = new Uint32Array(256);
1322
+ }
1323
+ });
1324
+
1325
+ // node_modules/simplify-js/simplify.js
1326
+ var require_simplify = __commonJS({
1327
+ "node_modules/simplify-js/simplify.js"(exports, module) {
1328
+ (function() {
1329
+ "use strict";
1330
+ function getSqDist(p1, p2) {
1331
+ var dx = p1.x - p2.x, dy = p1.y - p2.y;
1332
+ return dx * dx + dy * dy;
1333
+ }
1334
+ function getSqSegDist(p, p1, p2) {
1335
+ var x2 = p1.x, y = p1.y, dx = p2.x - x2, dy = p2.y - y;
1336
+ if (dx !== 0 || dy !== 0) {
1337
+ var t = ((p.x - x2) * dx + (p.y - y) * dy) / (dx * dx + dy * dy);
1338
+ if (t > 1) {
1339
+ x2 = p2.x;
1340
+ y = p2.y;
1341
+ } else if (t > 0) {
1342
+ x2 += dx * t;
1343
+ y += dy * t;
1344
+ }
1345
+ }
1346
+ dx = p.x - x2;
1347
+ dy = p.y - y;
1348
+ return dx * dx + dy * dy;
1349
+ }
1350
+ function simplifyRadialDist(points, sqTolerance) {
1351
+ var prevPoint = points[0], newPoints = [prevPoint], point;
1352
+ for (var i2 = 1, len = points.length; i2 < len; i2++) {
1353
+ point = points[i2];
1354
+ if (getSqDist(point, prevPoint) > sqTolerance) {
1355
+ newPoints.push(point);
1356
+ prevPoint = point;
1357
+ }
1358
+ }
1359
+ if (prevPoint !== point) newPoints.push(point);
1360
+ return newPoints;
1361
+ }
1362
+ function simplifyDPStep(points, first, last, sqTolerance, simplified) {
1363
+ var maxSqDist = sqTolerance, index;
1364
+ for (var i2 = first + 1; i2 < last; i2++) {
1365
+ var sqDist = getSqSegDist(points[i2], points[first], points[last]);
1366
+ if (sqDist > maxSqDist) {
1367
+ index = i2;
1368
+ maxSqDist = sqDist;
1369
+ }
1370
+ }
1371
+ if (maxSqDist > sqTolerance) {
1372
+ if (index - first > 1) simplifyDPStep(points, first, index, sqTolerance, simplified);
1373
+ simplified.push(points[index]);
1374
+ if (last - index > 1) simplifyDPStep(points, index, last, sqTolerance, simplified);
1375
+ }
1376
+ }
1377
+ function simplifyDouglasPeucker(points, sqTolerance) {
1378
+ var last = points.length - 1;
1379
+ var simplified = [points[0]];
1380
+ simplifyDPStep(points, 0, last, sqTolerance, simplified);
1381
+ simplified.push(points[last]);
1382
+ return simplified;
1383
+ }
1384
+ function simplify2(points, tolerance, highestQuality) {
1385
+ if (points.length <= 2) return points;
1386
+ var sqTolerance = tolerance !== void 0 ? tolerance * tolerance : 1;
1387
+ points = highestQuality ? points : simplifyRadialDist(points, sqTolerance);
1388
+ points = simplifyDouglasPeucker(points, sqTolerance);
1389
+ return points;
1390
+ }
1391
+ if (typeof define === "function" && define.amd) define(function() {
1392
+ return simplify2;
1393
+ });
1394
+ else if (typeof module !== "undefined") {
1395
+ module.exports = simplify2;
1396
+ module.exports.default = simplify2;
1397
+ } else if (typeof self !== "undefined") self.simplify = simplify2;
1398
+ else window.simplify = simplify2;
1399
+ })();
1400
+ }
1401
+ });
1402
+
1403
+ // packages/core/src/contour.ts
1404
+ function bleedEdges(image) {
1405
+ const { width, height } = image;
1406
+ const data = image.data.slice();
1407
+ const queue = new Int32Array(width * height);
1408
+ let read = 0, write = 0;
1409
+ for (let i2 = 0; i2 < queue.length; i2++) if (data[i2 * 4 + 3] >= 128) queue[write++] = i2;
1410
+ function spread(from, to) {
1411
+ if (data[to * 4 + 3] >= 128) return;
1412
+ data.set(data.subarray(from * 4, from * 4 + 3), to * 4);
1413
+ data[to * 4 + 3] = 255;
1414
+ queue[write++] = to;
1415
+ }
1416
+ while (read < write) {
1417
+ const i2 = queue[read++], x2 = i2 % width;
1418
+ if (x2) spread(i2, i2 - 1);
1419
+ if (x2 + 1 < width) spread(i2, i2 + 1);
1420
+ if (i2 >= width) spread(i2, i2 - width);
1421
+ if (i2 + width < queue.length) spread(i2, i2 + width);
1422
+ }
1423
+ return { width, height, data };
1424
+ }
1425
+ function outline(image) {
1426
+ const { width, height, data } = image;
1427
+ const alpha = new Array(width * height);
1428
+ for (let i2 = 0; i2 < alpha.length; i2++) alpha[i2] = data[i2 * 4 + 3];
1429
+ return Contours().size([width, height]).contour(alpha, 127.5).coordinates.map((polygon) => polygon.map((ring, index) => {
1430
+ const raw = ring.map(([x2, y]) => ({ x: x2, y }));
1431
+ const reduced = (0, import_simplify_js.default)(raw, 0.75, true);
1432
+ const points = (reduced.length >= 4 ? reduced : raw).slice(0, -1);
1433
+ const area3 = points.reduce((sum, a, i2) => {
1434
+ const b = points[(i2 + 1) % points.length];
1435
+ return sum + a.x * b.y - b.x * a.y;
1436
+ }, 0);
1437
+ if (area3 > 0 !== (index === 0)) points.reverse();
1438
+ return points.map((p) => ({ x: p.x / width, y: p.y / height }));
1439
+ }));
1440
+ }
1441
+ function containsCenter(ring) {
1442
+ let inside = false;
1443
+ for (let i2 = 0; i2 < ring.length; i2++) {
1444
+ const a = ring[i2], b = ring[(i2 + 1) % ring.length];
1445
+ if (a.y > 0.5 !== b.y > 0.5 && 0.5 < a.x + (0.5 - a.y) * (b.x - a.x) / (b.y - a.y)) inside = !inside;
1446
+ }
1447
+ return inside;
1448
+ }
1449
+ function columnSpan(image, x2) {
1450
+ let first = image.height, last = -1;
1451
+ for (let y = 0; y < image.height; y++) if (image.data[4 * (y * image.width + x2) + 3] >= 128) {
1452
+ first = Math.min(first, y);
1453
+ last = y;
1454
+ }
1455
+ if (last >= first) return [first / image.height, (last + 1) / image.height];
1456
+ }
1457
+ function measureHub(views, rings, [width, , height]) {
1458
+ const top = views.top, left = views.left;
1459
+ const widths = [];
1460
+ for (let x2 = 0; x2 < top.width; x2++) {
1461
+ const span = columnSpan(top, x2);
1462
+ if (span) widths.push(span[1] - span[0]);
1463
+ }
1464
+ widths.sort((a, b) => a - b);
1465
+ const plate = widths[Math.floor(widths.length / 2)];
1466
+ if (!(plate > 0 && plate < 1)) throw new Error("Contour hub needs a projecting axle in TOP.");
1467
+ let clearance = Infinity;
1468
+ for (const ring of rings) for (let i2 = 0; i2 < ring.length; i2++) {
1469
+ const a = ring[i2], b = ring[(i2 + 1) % ring.length];
1470
+ const x2 = (a.x - 0.5) * width, y = (a.y - 0.5) * height;
1471
+ const dx = (b.x - a.x) * width, dy = (b.y - a.y) * height;
1472
+ const t = Math.max(0, Math.min(1, -(x2 * dx + y * dy) / (dx * dx + dy * dy || 1)));
1473
+ clearance = Math.min(clearance, Math.hypot(x2 + t * dx, y + t * dy));
1474
+ }
1475
+ const spans = [0.12, 0.88].map((u) => columnSpan(left, Math.floor(u * left.width)));
1476
+ if (spans.some((s) => !s)) throw new Error("Contour hub needs a centered collar in LEFT.");
1477
+ const radii = spans.map((s) => Math.min((s[1] - s[0]) * height / 2, clearance * 0.95));
1478
+ return { plate, radii };
1479
+ }
1480
+ function extrudeContours(views, size, pivot, front, tiles, texture, withHub, segments) {
1481
+ const [width, depth, height] = size;
1482
+ const polygons = outline(front);
1483
+ if (!polygons.length) throw new Error("Empty FRONT contour.");
1484
+ const centered = withHub ? polygons.find((rings) => containsCenter(rings[0]) && !rings.slice(1).some(containsCenter)) : void 0;
1485
+ if (withHub && !centered) throw new Error("Contour hub needs solid material at the center of FRONT.");
1486
+ const hub = centered && measureHub(views, centered, size);
1487
+ const half = depth * (hub?.plate ?? 1) / 2;
1488
+ const positions = [], normals = [], uvs = [], indices = [];
1489
+ function vertex(p, z, n, direction) {
1490
+ const i2 = positions.length / 3;
1491
+ positions.push((p.x - 0.5) * width, (1 - p.y) * height - pivot[2], z);
1492
+ normals.push(...n);
1493
+ const d = z / depth + 0.5;
1494
+ let u = p.x, v = p.y;
1495
+ if (direction === "rear") u = 1 - u;
1496
+ if (direction === "top") v = 1 - d;
1497
+ if (direction === "bottom") v = d;
1498
+ if (direction === "left") u = d;
1499
+ if (direction === "right") u = 1 - d;
1500
+ const tile = tiles.get(direction);
1501
+ uvs.push(
1502
+ (tile.left + 0.5 + u * (tile.image.width - 1)) / texture.width,
1503
+ (1.5 + v * (tile.image.height - 1)) / texture.height
1504
+ );
1505
+ return i2;
1506
+ }
1507
+ function circle(radius) {
1508
+ return Array.from({ length: segments }, (_, i2) => {
1509
+ const angle = -2 * Math.PI * i2 / segments;
1510
+ return { x: 0.5 + radius * Math.cos(angle) / width, y: 0.5 + radius * Math.sin(angle) / height };
1511
+ });
1512
+ }
1513
+ function cap(rings, z, side) {
1514
+ const holes = [], xy = [];
1515
+ const base = positions.length / 3;
1516
+ for (const [i2, ring] of rings.entries()) {
1517
+ if (i2) holes.push(xy.length / 2);
1518
+ for (const p of ring) {
1519
+ xy.push(p.x, p.y);
1520
+ vertex(p, z, [0, 0, side], side < 0 ? "front" : "rear");
1521
+ }
1522
+ }
1523
+ const triangles = earcut(xy, holes);
1524
+ for (let i2 = 0; i2 < triangles.length; i2 += 3) {
1525
+ const a = base + triangles[i2], b = base + triangles[i2 + 1], c = base + triangles[i2 + 2];
1526
+ if (side < 0) indices.push(a, b, c);
1527
+ else indices.push(a, c, b);
1528
+ }
1529
+ }
1530
+ function collar(radius, side, root) {
1531
+ const length = depth / 2 - half;
1532
+ const sections = [[0, 1], [0.38, 1], [0.44, 0.93], [0.87, 0.93], [1, 0.82]];
1533
+ let previous = root;
1534
+ for (let j = 1; j < sections.length; j++) {
1535
+ const [t, r] = sections[j], [t0, r0] = sections[j - 1];
1536
+ const next = circle(radius * r);
1537
+ const slope = (r0 - r) * radius / ((t - t0) * length);
1538
+ const mag = Math.hypot(1, slope);
1539
+ const base = positions.length / 3;
1540
+ for (let i2 = 0; i2 < segments; i2++) {
1541
+ const angle = -2 * Math.PI * i2 / segments;
1542
+ const n = [Math.cos(angle) / mag, -Math.sin(angle) / mag, side * slope / mag];
1543
+ vertex(previous[i2], side * (half + t0 * length), n, "left");
1544
+ vertex(next[i2], side * (half + t * length), n, "left");
1545
+ }
1546
+ for (let i2 = 0; i2 < segments; i2++) {
1547
+ const a = base + i2 * 2, b = base + (i2 + 1) % segments * 2;
1548
+ if (side > 0) indices.push(a, b, b + 1, a, b + 1, a + 1);
1549
+ else indices.push(a, b + 1, b, a, a + 1, b + 1);
1550
+ }
1551
+ previous = next;
1552
+ }
1553
+ cap([previous], side * depth / 2, side);
1554
+ }
1555
+ for (const rings of polygons) {
1556
+ for (const side of [-1, 1]) {
1557
+ if (rings === centered && hub) {
1558
+ const radius = hub.radii[side < 0 ? 0 : 1], root = circle(radius);
1559
+ cap([...rings, root], side * half, side);
1560
+ collar(radius, side, root);
1561
+ } else cap(rings, side * half, side);
1562
+ }
1563
+ for (const ring of rings) for (let i2 = 0; i2 < ring.length; i2++) {
1564
+ const a = ring[i2], b = ring[(i2 + 1) % ring.length];
1565
+ const dx = (b.x - a.x) * width, dy = (b.y - a.y) * height, mag = Math.hypot(dx, dy);
1566
+ if (!mag) continue;
1567
+ const n = [dy / mag, dx / mag, 0];
1568
+ const direction = Math.abs(n[1]) >= Math.abs(n[0]) ? n[1] < 0 && views.bottom ? "bottom" : "top" : n[0] > 0 && views.right ? "right" : "left";
1569
+ const start = vertex(a, -half, n, direction);
1570
+ vertex(b, -half, n, direction);
1571
+ vertex(b, half, n, direction);
1572
+ vertex(a, half, n, direction);
1573
+ indices.push(start, start + 2, start + 1, start, start + 3, start + 2);
1574
+ }
1575
+ }
1576
+ return {
1577
+ target: "mesh",
1578
+ positions: Float32Array.from(positions),
1579
+ normals: Float32Array.from(normals),
1580
+ indices: Uint32Array.from(indices),
1581
+ uvs: Float32Array.from(uvs),
1582
+ texture,
1583
+ size,
1584
+ pivot
1585
+ };
1586
+ }
1587
+ var import_simplify_js;
1588
+ var init_contour = __esm({
1589
+ "packages/core/src/contour.ts"() {
1590
+ "use strict";
1591
+ init_d3_contour();
1592
+ init_earcut();
1593
+ import_simplify_js = __toESM(require_simplify(), 1);
1594
+ }
1595
+ });
1596
+
1597
+ // packages/core/src/atlas-comparison.ts
1598
+ function accent(data, offset) {
1599
+ const r = data[offset], g = data[offset + 1], b = data[offset + 2];
1600
+ if (data[offset + 3] < 128) return 0;
1601
+ if (r > 145 && r - b > 70 && g - b > 20 && r - g > 22) return 1;
1602
+ if (g > 95 && b > 105 && Math.min(g, b) - r > 46 && b - g > -20) return 2;
1603
+ return 0;
1604
+ }
1605
+ function inferAccentViews(views) {
1606
+ const clean = {};
1607
+ const masks = {};
1608
+ const owner = /* @__PURE__ */ new Map();
1609
+ const bestArea = /* @__PURE__ */ new Map();
1610
+ for (const [direction, image] of Object.entries(views)) {
1611
+ let extend2 = function(from, to) {
1612
+ if (!mask[to] || distance[to] >= 0) return;
1613
+ distance[to] = distance[from] + 1;
1614
+ output.set(output.subarray(from * 4, from * 4 + 3), to * 4);
1615
+ queue[end++] = to;
1616
+ };
1617
+ var extend = extend2;
1618
+ const { width, height, data } = image;
1619
+ const mask = new Uint8Array(width * height);
1620
+ const distance = new Int32Array(mask.length).fill(-1);
1621
+ const queue = new Int32Array(mask.length);
1622
+ const output = new Uint8Array(data);
1623
+ const area3 = [0, 0, 0];
1624
+ for (let i2 = 0; i2 < mask.length; i2++) {
1625
+ const id = mask[i2] = accent(data, i2 * 4);
1626
+ if (id) area3[id]++;
1627
+ }
1628
+ const seeds = mask.slice();
1629
+ for (let i2 = 0; i2 < seeds.length; i2++) {
1630
+ const id = seeds[i2];
1631
+ if (!id) continue;
1632
+ const x2 = i2 % width, y = Math.floor(i2 / width);
1633
+ for (let dy = -3; dy <= 3; dy++) for (let dx = -3; dx <= 3; dx++) {
1634
+ if (dx * dx + dy * dy > 9 || x2 + dx < 0 || x2 + dx >= width || y + dy < 0 || y + dy >= height) continue;
1635
+ const j = i2 + dy * width + dx, p = j * 4;
1636
+ if (mask[j] || data[p + 3] < 128) continue;
1637
+ const r = data[p], g = data[p + 1], b = data[p + 2];
1638
+ if (id === 1 ? r - b > 12 && g - b > 5 && r >= g - 8 : Math.min(g, b) - r > 12) mask[j] = id;
1639
+ }
1640
+ }
1641
+ let end = 0;
1642
+ for (let i2 = 0; i2 < mask.length; i2++) {
1643
+ if (mask[i2] || data[i2 * 4 + 3] < 128) continue;
1644
+ distance[i2] = 0;
1645
+ queue[end++] = i2;
1646
+ }
1647
+ for (let start = 0; start < end; start++) {
1648
+ const i2 = queue[start], x2 = i2 % width;
1649
+ if (x2 > 0) extend2(i2, i2 - 1);
1650
+ if (x2 + 1 < width) extend2(i2, i2 + 1);
1651
+ if (i2 >= width) extend2(i2, i2 - width);
1652
+ if (i2 + width < mask.length) extend2(i2, i2 + width);
1653
+ }
1654
+ for (const id of [1, 2]) {
1655
+ const score = area3[id] / (width * height) * (direction === "front" ? 1.35 : 1);
1656
+ if (score <= (bestArea.get(id) ?? 0)) continue;
1657
+ bestArea.set(id, score);
1658
+ owner.set(id, direction);
1659
+ }
1660
+ masks[direction] = mask;
1661
+ clean[direction] = { width, height, data: output };
1662
+ }
1663
+ return { clean, masks, owner };
1664
+ }
1665
+ function inferSurfaceDepth(volume, size, directions) {
1666
+ const maps = {};
1667
+ for (const direction of directions) {
1668
+ const [axis, high] = depthAxes[direction];
1669
+ const plane = axes.filter((item) => item !== axis);
1670
+ const width = size[plane[0]], height = size[plane[1]];
1671
+ const values = new Int16Array(width * height).fill(-1);
1672
+ const p = [0, 0, 0];
1673
+ for (let v = 0; v < height; v++) for (let u = 0; u < width; u++) {
1674
+ p[plane[0]] = u;
1675
+ p[plane[1]] = v;
1676
+ for (let step = 0; step < size[axis]; step++) {
1677
+ p[axis] = high ? size[axis] - 1 - step : step;
1678
+ if (!volume[(p[2] * size[1] + p[1]) * size[0] + p[0]]) continue;
1679
+ values[v * width + u] = p[axis] + Number(high);
1680
+ break;
1681
+ }
1682
+ }
1683
+ maps[direction] = { axis, axes: plane, width, height, values };
1684
+ }
1685
+ function at(map, point) {
1686
+ return [
1687
+ Math.max(0, Math.min(map.width - 1, Math.floor(point[map.axes[0]]))),
1688
+ Math.max(0, Math.min(map.height - 1, Math.floor(point[map.axes[1]])))
1689
+ ];
1690
+ }
1691
+ function firstHit(direction, point) {
1692
+ const map = maps[direction];
1693
+ if (!map) return -1;
1694
+ const [u, v] = at(map, point);
1695
+ return map.values[v * map.width + u];
1696
+ }
1697
+ function visible(direction, point, tolerance = 1.5) {
1698
+ const depth = firstHit(direction, point);
1699
+ return depth >= 0 && Math.abs(depth - point[depthAxes[direction][0]]) <= tolerance;
1700
+ }
1701
+ return { visible, firstHit };
1702
+ }
1703
+ function frontAccentDecals(image, mask, cells, size, pivot, firstHit) {
1704
+ const { width, height, data } = image;
1705
+ const marked = new Uint8Array(mask.length);
1706
+ const visited = new Uint8Array(mask.length);
1707
+ const deck = new Uint8Array(data.length);
1708
+ const positions = [], normals = [], indices = [], uvs = [];
1709
+ for (let start = 0; start < mask.length; start++) {
1710
+ if (mask[start] !== 1 || visited[start]) continue;
1711
+ const pixels = [start];
1712
+ const rows = /* @__PURE__ */ new Map();
1713
+ let minX = width, maxX = 0, minY = height, maxY = 0;
1714
+ visited[start] = 1;
1715
+ for (const index of pixels) {
1716
+ const x2 = index % width, y = Math.floor(index / width);
1717
+ minX = Math.min(minX, x2);
1718
+ maxX = Math.max(maxX, x2);
1719
+ minY = Math.min(minY, y);
1720
+ maxY = Math.max(maxY, y);
1721
+ const row = rows.get(y) ?? [x2, x2];
1722
+ rows.set(y, [Math.min(row[0], x2), Math.max(row[1], x2)]);
1723
+ for (const next of [x2 > 0 ? index - 1 : -1, x2 + 1 < width ? index + 1 : -1, index - width, index + width]) {
1724
+ if (mask[next] !== 1 || visited[next]) continue;
1725
+ visited[next] = 1;
1726
+ pixels.push(next);
1727
+ }
1728
+ }
1729
+ if (pixels.length < 5 || maxX - minX > width / 4 || maxY - minY > height / 4) continue;
1730
+ const fronts = /* @__PURE__ */ new Map();
1731
+ for (const [y, [from, to]] of rows) {
1732
+ let near = -1;
1733
+ for (let x2 = from; x2 <= to; x2++) {
1734
+ const point = [(x2 + 0.5) / width * cells[0], 0, (1 - (y + 0.5) / height) * cells[2]];
1735
+ near = Math.max(near, firstHit("front", point));
1736
+ }
1737
+ if (near >= 0) fronts.set(y, near);
1738
+ }
1739
+ if (fronts.size < 2) continue;
1740
+ for (const index of pixels) {
1741
+ if (!fronts.has(Math.floor(index / width))) continue;
1742
+ marked[index] = 1;
1743
+ deck.set(data.subarray(index * 4, index * 4 + 4), index * 4);
1744
+ }
1745
+ for (const [y, near] of fronts) {
1746
+ const [from, to] = rows.get(y);
1747
+ const u0 = from / width, u1 = (to + 1) / width;
1748
+ const v0 = y / height, v1 = (y + 1) / height;
1749
+ const x0 = (u0 - 0.5) * size[0], x1 = (u1 - 0.5) * size[0];
1750
+ const y0 = (1 - v0) * size[2] - pivot[2], y1 = (1 - v1) * size[2] - pivot[2];
1751
+ const z = (0.5 - (near + 0.65) / cells[1]) * size[1];
1752
+ const base = positions.length / 3;
1753
+ positions.push(x0, y0, z, x1, y0, z, x1, y1, z, x0, y1, z);
1754
+ normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1);
1755
+ indices.push(base, base + 1, base + 2, base, base + 2, base + 3);
1756
+ uvs.push(u0, v0, u1, v0, u1, v1, u0, v1);
1757
+ }
1758
+ }
1759
+ const mesh = indices.length ? {
1760
+ target: "mesh",
1761
+ size,
1762
+ pivot,
1763
+ texture: { width, height, data: deck },
1764
+ positions: Float32Array.from(positions),
1765
+ normals: Float32Array.from(normals),
1766
+ indices: Uint32Array.from(indices),
1767
+ uvs: Float32Array.from(uvs)
1768
+ } : void 0;
1769
+ return { mesh, marked };
1770
+ }
1771
+ var depthAxes, axes;
1772
+ var init_atlas_comparison = __esm({
1773
+ "packages/core/src/atlas-comparison.ts"() {
1774
+ "use strict";
1775
+ depthAxes = {
1776
+ top: [2, true],
1777
+ bottom: [2, false],
1778
+ left: [0, false],
1779
+ right: [0, true],
1780
+ front: [1, true],
1781
+ rear: [1, false]
1782
+ };
1783
+ axes = [0, 1, 2];
1784
+ }
1785
+ });
1786
+
1787
+ // packages/core/src/marching-table.ts
1788
+ var MC_TRIANGLES;
1789
+ var init_marching_table = __esm({
1790
+ "packages/core/src/marching-table.ts"() {
1791
+ "use strict";
1792
+ MC_TRIANGLES = Int8Array.from(atob("/////////////////////wAIA/////////////////8AAQn/////////////////AQgDCQgB/////////////wECCv////////////////8ACAMBAgr/////////////CQIKAAIJ/////////////wIIAwIKCAoJCP////////8DCwL/////////////////AAsCCAsA/////////////wEJAAIDC/////////////8BCwIBCQsJCAv/////////AwoBCwoD/////////////wAKAQAICggLCv////////8DCQADCwkLCgn/////////CQgKCggL/////////////wQHCP////////////////8EAwAHAwT/////////////AAEJCAQH/////////////wQBCQQHAQcDAf////////8BAgoIBAf/////////////AwQHAwAEAQIK/////////wkCCgkAAggEB/////////8CCgkCCQcCBwMHCQT/////CAQHAwsC/////////////wsEBwsCBAIABP////////8JAAEIBAcCAwv/////////BAcLCQQLCQsCCQIB/////wMKAQMLCgcIBP////////8BCwoBBAsBAAQHCwT/////BAcICQALCQsKCwAD/////wQHCwQLCQkLCv////////8JBQT/////////////////CQUEAAgD/////////////wAFBAEFAP////////////8IBQQIAwUDAQX/////////AQIKCQUE/////////////wMACAECCgQJBf////////8FAgoFBAIEAAL/////////AgoFAwIFAwUEAwQI/////wkFBAIDC/////////////8ACwIACAsECQX/////////AAUEAAEFAgML/////////wIBBQIFCAIICwQIBf////8KAwsKAQMJBQT/////////BAkFAAgBCAoBCAsK/////wUEAAUACwULCgsAA/////8FBAgFCAoKCAv/////////CQcIBQcJ/////////////wkDAAkFAwUHA/////////8ABwgAAQcBBQf/////////AQUDAwUH/////////////wkHCAkFBwoBAv////////8KAQIJBQAFAwAFBwP/////CAACCAIFCAUHCgUC/////wIKBQIFAwMFB/////////8HCQUHCAkDCwL/////////CQUHCQcCCQIAAgcL/////wIDCwABCAEHCAEFB/////8LAgELAQcHAQX/////////CQUICAUHCgEDCgML/////wUHAAUACQcLAAEACgsKAP8LCgALAAMKBQAIAAcFBwD/CwoFBwsF/////////////woGBf////////////////8ACAMFCgb/////////////CQABBQoG/////////////wEIAwEJCAUKBv////////8BBgUCBgH/////////////AQYFAQIGAwAI/////////wkGBQkABgACBv////////8FCQgFCAIFAgYDAgj/////AgMLCgYF/////////////wsACAsCAAoGBf////////8AAQkCAwsFCgb/////////BQoGAQkCCQsCCQgL/////wYDCwYFAwUBA/////////8ACAsACwUABQEFCwb/////AwsGAAMGAAYFAAUJ/////wYFCQYJCwsJCP////////8FCgYEBwj/////////////BAMABAcDBgUK/////////wEJAAUKBggEB/////////8KBgUBCQcBBwMHCQT/////BgECBgUBBAcI/////////wECBQUCBgMABAMEB/////8IBAcJAAUABgUAAgb/////BwMJBwkEAwIJBQkGAgYJ/wMLAgcIBAoGBf////////8FCgYEBwIEAgACBwv/////AAEJBAcIAgMLBQoG/////wkCAQkLAgkECwcLBAUKBv8IBAcDCwUDBQEFCwb/////BQELBQsGAQALBwsEAAQL/wAFCQAGBQADBgsGAwgEB/8GBQkGCQsEBwkHCwn/////CgQJBgQK/////////////wQKBgQJCgAIA/////////8KAAEKBgAGBAD/////////CAMBCAEGCAYEBgEK/////wEECQECBAIGBP////////8DAAgBAgkCBAkCBgT/////AAIEBAIG/////////////wgDAggCBAQCBv////////8KBAkKBgQLAgP/////////AAgCAggLBAkKBAoG/////wMLAgABBgAGBAYBCv////8GBAEGAQoECAECAQsICwH/CQYECQMGCQEDCwYD/////wgLAQgBAAsGAQkBBAYEAf8DCwYDBgAABgT/////////BgQICwYI/////////////wcKBgcICggJCv////////8ABwMACgcACQoGBwr/////CgYHAQoHAQcIAQgA/////woGBwoHAQEHA/////////8BAgYBBggBCAkIBgf/////AgYJAgkBBgcJAAkDBwMJ/wcIAAcABgYAAv////////8HAwIGBwL/////////////AgMLCgYICggJCAYH/////wIABwIHCwAJBwYHCgkKB/8BCAABBwgBCgcGBwoCAwv/CwIBCwEHCgYBBgcB/////wgJBggGBwkBBgsGAwEDBv8ACQELBgf/////////////BwgABwAGAwsACwYA/////wcLBv////////////////8HBgv/////////////////AwAICwcG/////////////wABCQsHBv////////////8IAQkIAwELBwb/////////CgECBgsH/////////////wECCgMACAYLB/////////8CCQACCgkGCwf/////////BgsHAgoDCggDCgkI/////wcCAwYCB/////////////8HAAgHBgAGAgD/////////AgcGAgMHAAEJ/////////wEGAgEIBgEJCAgHBv////8KBwYKAQcBAwf/////////CgcGAQcKAQgHAQAI/////wADBwAHCgAKCQYKB/////8HBgoHCggICgn/////////BggECwgG/////////////wMGCwMABgAEBv////////8IBgsIBAYJAAH/////////CQQGCQYDCQMBCwMG/////wYIBAYLCAIKAf////////8BAgoDAAsABgsABAb/////BAsIBAYLAAIJAgoJ/////woJAwoDAgkEAwsDBgQGA/8IAgMIBAIEBgL/////////AAQCBAYC/////////////wEJAAIDBAIEBgQDCP////8BCQQBBAICBAb/////////CAEDCAYBCAQGBgoB/////woBAAoABgYABP////////8EBgMEAwgGCgMAAwkKCQP/CgkEBgoE/////////////wQJBQcGC/////////////8ACAMECQULBwb/////////BQABBQQABwYL/////////wsHBggDBAMFBAMBBf////8JBQQKAQIHBgv/////////BgsHAQIKAAgDBAkF/////wcGCwUECgQCCgQAAv////8DBAgDBQQDAgUKBQILBwb/BwIDBwYCBQQJ/////////wkFBAAIBgAGAgYIB/////8DBgIDBwYBBQAFBAD/////BgIIBggHAgEIBAgFAQUI/wkFBAoBBgEHBgEDB/////8BBgoBBwYBAAcIBwAJBQT/BAAKBAoFAAMKBgoHAwcK/wcGCgcKCAUECgQICv////8GCQUGCwkLCAn/////////AwYLAAYDAAUGAAkF/////wALCAAFCwABBQUGC/////8GCwMGAwUFAwH/////////AQIKCQULCQsICwUG/////wALAwAGCwAJBgUGCQECCv8LCAULBQYIAAUKBQIAAgX/BgsDBgMFAgoDCgUD/////wUICQUCCAUGAgMIAv////8JBQYJBgAABgL/////////AQUIAQgABQYIAwgCBgII/wEFBgIBBv////////////8BAwYBBgoDCAYFBgkICQb/CgEACgAGCQUABQYA/////wADCAUGCv////////////8KBQb/////////////////CwUKBwUL/////////////wsFCgsHBQgDAP////////8FCwcFCgsBCQD/////////CgcFCgsHCQgBCAMB/////wsBAgsHAQcFAf////////8ACAMBAgcBBwUHAgv/////CQcFCQIHCQACAgsH/////wcFAgcCCwUJAgMCCAkIAv8CBQoCAwUDBwX/////////CAIACAUCCAcFCgIF/////wkAAQUKAwUDBwMKAv////8JCAIJAgEIBwIKAgUHBQL/AQMFAwcF/////////////wAIBwAHAQEHBf////////8JAAMJAwUFAwf/////////CQgHBQkH/////////////wUIBAUKCAoLCP////////8FAAQFCwAFCgsLAwD/////AAEJCAQKCAoLCgQF/////woLBAoEBQsDBAkEAQMBBP8CBQECCAUCCwgEBQj/////AAQLAAsDBAULAgsBBQEL/wACBQAFCQILBQQFCAsIBf8JBAUCCwP/////////////AgUKAwUCAwQFAwgE/////wUKAgUCBAQCAP////////8DCgIDBQoDCAUEBQgAAQn/BQoCBQIEAQkCCQQC/////wgEBQgFAwMFAf////////8ABAUBAAX/////////////CAQFCAUDCQAFAAMF/////wkEBf////////////////8ECwcECQsJCgv/////////AAgDBAkHCQsHCQoL/////wEKCwELBAEEAAcEC/////8DAQQDBAgBCgQHBAsKCwT/BAsHCQsECQILCQEC/////wkHBAkLBwkBCwILAQAIA/8LBwQLBAICBAD/////////CwcECwQCCAMEAwIE/////wIJCgIHCQIDBwcECf////8JCgcJBwQKAgcIBwACAAf/AwcKAwoCBwQKAQoABAAK/wEKAggHBP////////////8ECQEEAQcHAQP/////////BAkBBAEHAAgBCAcB/////wQAAwcEA/////////////8ECAf/////////////////CQoICgsI/////////////wMACQMJCwsJCv////////8AAQoACggICgv/////////AwEKCwMK/////////////wECCwELCQkLCP////////8DAAkDCQsBAgkCCwn/////AAILCAAL/////////////wMCC/////////////////8CAwgCCAoKCAn/////////CQoCAAkC/////////////wIDCAIICgABCAEKCP////8BCgL/////////////////AQMICQEI/////////////wAJAf////////////////8AAwj//////////////////////////////////////w=="), (c) => c.charCodeAt(0));
1793
+ }
1794
+ });
1795
+
1796
+ // packages/core/src/surface.ts
1797
+ function regularizeDepth(occupancy, shape, pitch) {
1798
+ const extent2 = Math.min(pitch[2] * (shape[2] - 2) * 0.042, Math.max(pitch[0], pitch[1]) * 1.65);
1799
+ const strides = [1, shape[0], shape[0] * shape[1]];
1800
+ let current = Float32Array.from(occupancy);
1801
+ let output = new Float32Array(current.length);
1802
+ for (let axis = 0; axis < shape.length; axis++) {
1803
+ const sigma = Math.max(0.6, Math.min(5, extent2 / pitch[axis]));
1804
+ const radius = Math.ceil(sigma * 2.5);
1805
+ const weights = Array.from({ length: radius + 1 }, (_, d) => Math.exp(-d * d / (2 * sigma * sigma)));
1806
+ const total = weights[0] + 2 * weights.slice(1).reduce((sum, weight) => sum + weight, 0);
1807
+ const step = strides[axis], length = shape[axis], block = step * length;
1808
+ for (let base = 0; base < current.length; base += block) for (let offset = 0; offset < step; offset++) {
1809
+ for (let i2 = 0; i2 < length; i2++) {
1810
+ const index = base + offset + i2 * step;
1811
+ let value = weights[0] * current[index];
1812
+ for (let d = 1; d <= radius; d++) {
1813
+ if (i2 >= d) value += weights[d] * current[index - d * step];
1814
+ if (i2 + d < length) value += weights[d] * current[index + d * step];
1815
+ }
1816
+ output[index] = value / total;
1817
+ }
1818
+ }
1819
+ [current, output] = [output, current];
1820
+ }
1821
+ return current;
1822
+ }
1823
+ function extractSurface(volume, width, depth, layers, worldSize) {
1824
+ const nx = width + 2, ny = depth + 2, nz = layers + 2;
1825
+ const plane = nx * ny, count2 = plane * nz;
1826
+ const occupancy = new Uint8Array(count2);
1827
+ for (let z = 0; z < layers; z++) for (let y = 0; y < depth; y++) {
1828
+ const start = (z * depth + y) * width;
1829
+ occupancy.set(volume.subarray(start, start + width), (z + 1) * plane + (y + 1) * nx + 1);
1830
+ }
1831
+ const field = worldSize ? regularizeDepth(occupancy, [nx, ny, nz], [worldSize[0] / width, worldSize[1] / depth, worldSize[2] / layers]) : new Float32Array(count2);
1832
+ for (let z = 0; z < nz; z++) for (let y = 0; y < ny; y++) for (let x2 = 0; x2 < nx; x2++) {
1833
+ const index = z * plane + y * nx + x2;
1834
+ const neighbors = (x2 > 0 ? occupancy[index - 1] : 0) + (x2 + 1 < nx ? occupancy[index + 1] : 0) + (y > 0 ? occupancy[index - nx] : 0) + (y + 1 < ny ? occupancy[index + nx] : 0) + (z > 0 ? occupancy[index - plane] : 0) + (z + 1 < nz ? occupancy[index + plane] : 0);
1835
+ const silhouetteField = occupancy[index] * 0.64 + neighbors * 0.06;
1836
+ field[index] = worldSize ? field[index] * 0.92 + silhouetteField * 0.08 : silhouetteField;
1837
+ }
1838
+ const corners = [0, 1, nx + 1, nx, plane, plane + 1, plane + nx + 1, plane + nx];
1839
+ const cached = new Int32Array(count2 * 3).fill(-1);
1840
+ const positions = [], gradients = [], indices = [];
1841
+ function derivative(index, stride) {
1842
+ return (field[index - stride] ?? 0) - (field[index + stride] ?? 0);
1843
+ }
1844
+ function vertex(x2, y, z, cell, edge) {
1845
+ const [a, b] = EDGES[edge];
1846
+ const A = CORNERS[a], B = CORNERS[b];
1847
+ const ca = cell + corners[a], cb = cell + corners[b];
1848
+ const axis = A[0] !== B[0] ? 0 : A[1] !== B[1] ? 1 : 2;
1849
+ const key = Math.min(ca, cb) * 3 + axis;
1850
+ if (cached[key] >= 0) return cached[key];
1851
+ const id = positions.length / 3;
1852
+ const t = (0.5 - field[ca]) / (field[cb] - field[ca]);
1853
+ positions.push(
1854
+ x2 - 0.5 + A[0] + (B[0] - A[0]) * t,
1855
+ y - 0.5 + A[1] + (B[1] - A[1]) * t,
1856
+ z - 0.5 + A[2] + (B[2] - A[2]) * t
1857
+ );
1858
+ gradients.push(...[1, nx, plane].map((stride) => derivative(ca, stride) * (1 - t) + derivative(cb, stride) * t));
1859
+ cached[key] = id;
1860
+ return id;
1861
+ }
1862
+ for (let z = 0; z < nz - 1; z++) for (let y = 0; y < ny - 1; y++) for (let x2 = 0; x2 < nx - 1; x2++) {
1863
+ const cell = z * plane + y * nx + x2;
1864
+ let configuration = 0;
1865
+ for (let i2 = 0; i2 < 8; i2++) if (field[cell + corners[i2]] < 0.5) configuration |= 1 << i2;
1866
+ if (configuration === 0 || configuration === 255) continue;
1867
+ for (let row = configuration * 16; MC_TRIANGLES[row] >= 0; row++) {
1868
+ indices.push(vertex(x2, y, z, cell, MC_TRIANGLES[row]));
1869
+ }
1870
+ }
1871
+ return { positions, gradients, indices };
1872
+ }
1873
+ var CORNERS, EDGES;
1874
+ var init_surface = __esm({
1875
+ "packages/core/src/surface.ts"() {
1876
+ "use strict";
1877
+ init_marching_table();
1878
+ CORNERS = [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0], [0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1]];
1879
+ EDGES = [[0, 1], [1, 2], [2, 3], [3, 0], [4, 5], [5, 6], [6, 7], [7, 4], [0, 4], [1, 5], [2, 6], [3, 7]];
1880
+ }
1881
+ });
1882
+
1883
+ // packages/core/src/reconstruct.ts
1884
+ function respaceStack(stack, multiplier) {
1885
+ if (!Number.isFinite(multiplier) || multiplier <= 0 || !Number.isFinite(multiplier * stack.size[2])) {
1886
+ throw new Error("Spacing must be a positive, finite multiplier.");
1887
+ }
1888
+ if (multiplier === 1) return stack;
1889
+ return {
1890
+ ...stack,
1891
+ spacing: stack.spacing * multiplier,
1892
+ size: [stack.size[0], stack.size[1], stack.size[2] * multiplier],
1893
+ pivot: [stack.pivot[0], stack.pivot[1], stack.pivot[2] * multiplier]
1894
+ };
1895
+ }
1896
+ function viewUV(direction, x2, y, z) {
1897
+ switch (direction) {
1898
+ case "top":
1899
+ return [x2, y];
1900
+ case "bottom":
1901
+ return [x2, 1 - y];
1902
+ case "left":
1903
+ return [1 - y, 1 - z];
1904
+ case "right":
1905
+ return [y, 1 - z];
1906
+ case "front":
1907
+ return [x2, 1 - z];
1908
+ case "rear":
1909
+ return [1 - x2, 1 - z];
1910
+ }
1911
+ }
1912
+ function sample(image, u, v) {
1913
+ return (clamp2(Math.floor(v * image.height), 0, image.height - 1) * image.width + clamp2(Math.floor(u * image.width), 0, image.width - 1)) * 4;
1914
+ }
1915
+ function resize(image, width, height) {
1916
+ if (image.width === width && image.height === height) return image;
1917
+ const data = new Uint8Array(width * height * 4);
1918
+ for (let y = 0; y < height; y++) for (let x2 = 0; x2 < width; x2++) {
1919
+ const p = sample(image, (x2 + 0.5) / width, (y + 0.5) / height);
1920
+ const q = (y * width + x2) * 4;
1921
+ for (let k = 0; k < 4; k++) data[q + k] = image.data[p + k];
1922
+ }
1923
+ return { width, height, data };
1924
+ }
1925
+ function rankedViews(views, nx, ny, nz) {
1926
+ const weights = [
1927
+ Math.max(0, nz),
1928
+ Math.max(0, -nx),
1929
+ Math.max(0, ny),
1930
+ Math.max(0, -ny),
1931
+ Math.max(0, nx),
1932
+ Math.max(0, -nz)
1933
+ ];
1934
+ if (!views.right) weights[1] = Math.abs(nx);
1935
+ if (!views.bottom) weights[0] = Math.abs(nz);
1936
+ return [...DIRECTIONS].filter((direction) => views[direction]).sort((a, b) => weights[DIRECTIONS.indexOf(b)] - weights[DIRECTIONS.indexOf(a)]);
1937
+ }
1938
+ function dimensions(views, settings) {
1939
+ const top = views.top, front = views.front, left = views.left;
1940
+ const layers = settings.layers ?? 48;
1941
+ const resolution = settings.resolution ?? 96;
1942
+ const height = settings.height ?? 1;
1943
+ if (!Number.isInteger(layers) || layers < 8 || layers > 128) throw new Error("Layers must be an integer from 8 to 128.");
1944
+ if (!Number.isInteger(resolution) || resolution < 16 || resolution > 192) throw new Error("Resolution must be an integer from 16 to 192.");
1945
+ if (!Number.isFinite(height) || height <= 0) throw new Error("Height must be positive.");
1946
+ if (settings.pivot && settings.pivot !== "center" && settings.pivot !== "ground") throw new Error("Pivot must be ground or center.");
1947
+ const depthFromView = left.width / left.height * height;
1948
+ const [x2, y, z] = settings.size ?? [(front.width / front.height * height + depthFromView * top.width / top.height) / 2, depthFromView, height];
1949
+ if (![x2, y, z].every((value) => Number.isFinite(value) && value > 0)) throw new Error("Part dimensions must be positive.");
1950
+ const width = Math.max(2, Math.round(x2 / Math.max(x2, y) * resolution));
1951
+ const depth = Math.max(2, Math.round(y / Math.max(x2, y) * resolution));
1952
+ const size = [x2, y, z];
1953
+ const pivot = [0, 0, settings.pivot === "center" ? z / 2 : 0];
1954
+ return { width, depth, layers, size, pivot };
1955
+ }
1956
+ function grid(views, settings, fallback) {
1957
+ const { width, depth, layers, size, pivot } = dimensions(views, settings);
1958
+ if (width * depth * layers > 3e6) throw new Error("The grid is too large. Reduce layers or XY resolution.");
1959
+ const aligned = {};
1960
+ for (const direction of DIRECTIONS) {
1961
+ const view = views[direction];
1962
+ if (!view) continue;
1963
+ const vertical = direction !== "top" && direction !== "bottom";
1964
+ aligned[direction] = resize(view, direction === "left" || direction === "right" ? depth : width, vertical ? layers : depth);
1965
+ }
1966
+ const entries = Object.entries(aligned);
1967
+ const covered = (direction, view, u, v, h) => view.data[sample(view, ...viewUV(direction, u, v, h)) + 3] >= 128;
1968
+ const volume = new Uint8Array(width * depth * layers);
1969
+ let occupied = 0;
1970
+ const rounded = settings.profile === "round" || settings.profile === "round-base";
1971
+ for (let z = 0; z < layers; z++) for (let y = 0; y < depth; y++) for (let x2 = 0; x2 < width; x2++) {
1972
+ const u = (x2 + 0.5) / width, v = (y + 0.5) / depth, h = (z + 0.5) / layers;
1973
+ const solid = views.right ? entries.every(([direction, view]) => covered(direction, view, u, v, h)) : covered("top", aligned.top, u, v, h) && covered("left", aligned.left, u, v, h) && (covered("front", aligned.front, u, v, h) || covered("rear", aligned.rear, u, v, h));
1974
+ if (solid) {
1975
+ volume[(z * depth + y) * width + x2] = 1;
1976
+ occupied++;
1977
+ }
1978
+ }
1979
+ if (rounded) {
1980
+ const area3 = width * depth;
1981
+ for (let z = 0; z < layers; z++) {
1982
+ if (settings.profile === "round-base" && (z + 0.5) / layers < 0.03) continue;
1983
+ let x0 = width, x1 = -1, y0 = depth, y1 = -1;
1984
+ const offset = z * area3;
1985
+ for (let y = 0; y < depth; y++) for (let x2 = 0; x2 < width; x2++) {
1986
+ if (!volume[offset + y * width + x2]) continue;
1987
+ x0 = Math.min(x0, x2);
1988
+ x1 = Math.max(x1, x2);
1989
+ y0 = Math.min(y0, y);
1990
+ y1 = Math.max(y1, y);
1991
+ }
1992
+ if (x1 < x0) continue;
1993
+ for (let y = y0; y <= y1; y++) for (let x2 = x0; x2 <= x1; x2++) {
1994
+ if (((2 * x2 - x0 - x1) / (x1 - x0 + 1)) ** 2 + ((2 * y - y0 - y1) / (y1 - y0 + 1)) ** 2 <= 1) continue;
1995
+ const index = offset + y * width + x2;
1996
+ occupied -= volume[index];
1997
+ volume[index] = 0;
1998
+ }
1999
+ }
2000
+ }
2001
+ if (!occupied) {
2002
+ if (fallback) return fallback;
2003
+ throw new Error("The aligned views have no common volume.");
2004
+ }
2005
+ return { width, depth, layers, size, pivot, volume, aligned };
2006
+ }
2007
+ function textureAtlas(views, accentViews = {}, bleed = false) {
2008
+ const tiles = /* @__PURE__ */ new Map();
2009
+ const accents = new Map(tiles);
2010
+ let width = 0, height = 0;
2011
+ for (const [sources, target] of [[views, tiles], [accentViews, accents]]) for (const direction of DIRECTIONS) {
2012
+ const view = sources[direction];
2013
+ if (!view) continue;
2014
+ const scale = Math.min(1, 512 / Math.max(view.width, view.height));
2015
+ const image = resize(view, Math.max(1, Math.round(view.width * scale)), Math.max(1, Math.round(view.height * scale)));
2016
+ target.set(direction, { image: bleed ? bleedEdges(image) : image, left: width + 1 });
2017
+ width += image.width + 2;
2018
+ height = Math.max(height, image.height + 2);
2019
+ }
2020
+ const data = new Uint8Array(width * height * 4).fill(255);
2021
+ for (const { image, left } of [...tiles.values(), ...accents.values()]) {
2022
+ for (let y = -1; y <= image.height; y++) for (let x2 = -1; x2 <= image.width; x2++) {
2023
+ const p = (clamp2(y, 0, image.height - 1) * image.width + clamp2(x2, 0, image.width - 1)) * 4;
2024
+ const q = ((y + 1) * width + left + x2) * 4;
2025
+ for (let k = 0; k < 3; k++) data[q + k] = image.data[p + 3] >= 128 ? image.data[p + k] : 137;
2026
+ }
2027
+ }
2028
+ return { tiles, accents, texture: { width, height, data } };
2029
+ }
2030
+ function makeMesh(g, views, mode = "rgb") {
2031
+ const { width, depth, layers, size, pivot, volume } = g;
2032
+ const surface = extractSurface(volume, width, depth, layers, mode === "depth" ? size : void 0);
2033
+ if (!surface.indices.length && mode === "depth") return makeMesh(g, views, "id");
2034
+ const roof = new Int16Array(width * depth).fill(-1);
2035
+ const floor = new Int16Array(width * depth).fill(layers);
2036
+ const area3 = width * depth;
2037
+ for (let z = 0; z < layers; z++) for (let i2 = 0; i2 < area3; i2++) {
2038
+ if (!volume[z * area3 + i2]) continue;
2039
+ roof[i2] = z;
2040
+ floor[i2] = Math.min(floor[i2], z);
2041
+ }
2042
+ function nearFlatSurface(columns2, x2, y, z) {
2043
+ const px = clamp2(Math.floor(x2 * width), 0, width - 1);
2044
+ const py = clamp2(Math.floor(y * depth), 0, depth - 1);
2045
+ const point = columns2[py * width + px];
2046
+ if (Math.abs(point + 0.5 - z * layers) > 2) return false;
2047
+ let neighbors = 0;
2048
+ for (const [dx, dy] of [[2, 0], [-2, 0], [0, 2], [0, -2]]) {
2049
+ const nx = px + dx, ny = py + dy;
2050
+ if (nx < 0 || nx >= width || ny < 0 || ny >= depth) continue;
2051
+ if (Math.abs(columns2[ny * width + nx] - point) > (views.bottom ? 2 : 1)) return false;
2052
+ neighbors++;
2053
+ }
2054
+ return neighbors >= (views.bottom ? 2 : 3);
2055
+ }
2056
+ const accents = mode === "rgb" ? void 0 : inferAccentViews(views);
2057
+ const ownerViews = {};
2058
+ for (const owner of accents?.owner.values() ?? []) ownerViews[owner] = views[owner];
2059
+ const inferredDepth = accents ? inferSurfaceDepth(volume, [width, depth, layers], DIRECTIONS) : void 0;
2060
+ const frontDecal = accents?.owner.get(1) === "front" && inferredDepth && views.front && accents.masks.front ? frontAccentDecals(views.front, accents.masks.front, [width, depth, layers], size, pivot, inferredDepth.firstHit) : void 0;
2061
+ const { texture, tiles, accents: accentTiles } = textureAtlas(accents?.clean ?? views, ownerViews);
2062
+ const positions = [], normals = [], indices = [], uvs = [];
2063
+ const cache = /* @__PURE__ */ new Map();
2064
+ for (let i2 = 0; i2 < surface.indices.length; i2 += 3) {
2065
+ const tri = surface.indices.slice(i2, i2 + 3);
2066
+ const average = [0, 1, 2].map((axis) => tri.reduce((sum, index) => sum + surface.gradients[index * 3 + axis], 0));
2067
+ const centerSum = [0, 1, 2].map((axis) => tri.reduce((sum, index) => sum + surface.positions[index * 3 + axis], 0));
2068
+ const center = [centerSum[0] / (3 * width), centerSum[1] / (3 * depth), centerSum[2] / (3 * layers)];
2069
+ let choices = rankedViews(views, average[0], average[1], average[2]);
2070
+ const verticalView = average[2] < 0 && views.bottom ? "bottom" : "top";
2071
+ const envelope = average[2] < 0 ? floor : roof;
2072
+ const planFacing = mode === "depth" && inferredDepth && Math.abs(average[2]) * layers / size[2] > 1.55 * Math.max(
2073
+ Math.abs(average[0]) * width / size[0],
2074
+ Math.abs(average[1]) * depth / size[1]
2075
+ ) && inferredDepth.visible(verticalView, centerSum.map((value) => value / 3), 3);
2076
+ if (!planFacing && !nearFlatSurface(envelope, center[0], center[1], center[2])) {
2077
+ const nx = average[0], ny = average[1];
2078
+ choices = Math.hypot(nx, ny) > 0.1 ? rankedViews(views, nx, ny, 0) : rankedViews(views, center[0] - 0.5, center[1] - 0.5, 0);
2079
+ choices = [...choices.filter((name) => name !== "top" && name !== "bottom"), verticalView];
2080
+ }
2081
+ const covered = (name) => {
2082
+ const view = views[name];
2083
+ return view.data[sample(view, ...viewUV(name, ...center)) + 3] >= 128;
2084
+ };
2085
+ let direction = planFacing && covered(verticalView) ? verticalView : choices.find(covered) ?? choices[0];
2086
+ let useAccent = false;
2087
+ if (accents && inferredDepth) {
2088
+ const centerCell = centerSum.map((value) => value / 3);
2089
+ const tolerance = mode === "depth" ? 3 : 1.5;
2090
+ const candidates = rankedViews(views, average[0], average[1], average[2]);
2091
+ const facing = [
2092
+ Math.max(0, average[2]),
2093
+ Math.max(0, -average[0]),
2094
+ Math.max(0, average[1]),
2095
+ Math.max(0, -average[1]),
2096
+ Math.max(0, average[0]),
2097
+ Math.max(0, -average[2])
2098
+ ];
2099
+ const strongest = Math.max(...facing);
2100
+ for (const candidate of candidates) {
2101
+ if (!ownerViews[candidate] || facing[DIRECTIONS.indexOf(candidate)] <= strongest * 0.45 || !inferredDepth.visible(candidate, centerCell, tolerance)) continue;
2102
+ const view = ownerViews[candidate];
2103
+ const texel = sample(view, ...viewUV(candidate, ...center)) / 4;
2104
+ const id = accents.masks[candidate][texel];
2105
+ if (accents.owner.get(id) !== candidate || candidate === "front" && frontDecal?.marked[texel]) continue;
2106
+ direction = candidate;
2107
+ useAccent = true;
2108
+ break;
2109
+ }
2110
+ }
2111
+ const { image, left } = (useAccent ? accentTiles : tiles).get(direction);
2112
+ for (const original of tri) {
2113
+ const key = original * 12 + DIRECTIONS.indexOf(direction) + (useAccent ? 6 : 0);
2114
+ let index = cache.get(key);
2115
+ if (index === void 0) {
2116
+ index = positions.length / 3;
2117
+ cache.set(key, index);
2118
+ const p = original * 3;
2119
+ const x2 = surface.positions[p] / width, y = surface.positions[p + 1] / depth, z = surface.positions[p + 2] / layers;
2120
+ positions.push((x2 - 0.5) * size[0], z * size[2] - pivot[2], (0.5 - y) * size[1]);
2121
+ const nx = surface.gradients[p] * width / size[0], ny = surface.gradients[p + 1] * depth / size[1];
2122
+ const nz = surface.gradients[p + 2] * layers / size[2];
2123
+ const magnitude = Math.hypot(nx, ny, nz) || 1;
2124
+ normals.push(nx / magnitude, nz / magnitude, -ny / magnitude);
2125
+ const [u, v] = viewUV(direction, x2, y, z);
2126
+ uvs.push(
2127
+ (left + 0.5 + clamp2(u, 0, 1) * (image.width - 1)) / texture.width,
2128
+ (1.5 + clamp2(v, 0, 1) * (image.height - 1)) / texture.height
2129
+ );
2130
+ }
2131
+ indices.push(index);
2132
+ }
2133
+ }
2134
+ return {
2135
+ target: "mesh",
2136
+ size,
2137
+ pivot,
2138
+ texture,
2139
+ positions: Float32Array.from(positions),
2140
+ normals: Float32Array.from(normals),
2141
+ indices: Uint32Array.from(indices),
2142
+ uvs: Float32Array.from(uvs),
2143
+ ...frontDecal?.mesh && { frontAccents: frontDecal.mesh }
2144
+ };
2145
+ }
2146
+ function makeStack(g, views) {
2147
+ const { width, depth, layers, size, pivot, volume } = g;
2148
+ const columns2 = Math.min(layers, Math.max(1, Math.floor(4096 / width)));
2149
+ const imageWidth = width * columns2, imageHeight = depth * Math.ceil(layers / columns2);
2150
+ const data = new Uint8Array(imageWidth * imageHeight * 4);
2151
+ const filled = (x2, y, z) => Number(x2 >= 0 && x2 < width && y >= 0 && y < depth && z >= 0 && z < layers && volume[(z * depth + y) * width + x2] > 0);
2152
+ const roof = new Int16Array(width * depth).fill(-1);
2153
+ for (let z = 0; z < layers; z++) for (let i2 = 0; i2 < roof.length; i2++) {
2154
+ if (volume[z * roof.length + i2]) roof[i2] = z;
2155
+ }
2156
+ const surfaceViews = Array.from({ length: 27 }, (_, index) => rankedViews(
2157
+ views,
2158
+ index % 3 - 1,
2159
+ Math.floor(index / 3) % 3 - 1,
2160
+ Math.floor(index / 9) - 1
2161
+ ));
2162
+ const flatAt = (x2, y, z) => x2 < 0 || x2 >= width || y < 0 || y >= depth || Math.abs(roof[y * width + x2] - z) <= 1;
2163
+ for (let z = 0; z < layers; z++) for (let y = 0; y < depth; y++) for (let x2 = 0; x2 < width; x2++) {
2164
+ if (!filled(x2, y, z)) continue;
2165
+ const nx = filled(x2 - 1, y, z) - filled(x2 + 1, y, z);
2166
+ const ny = filled(x2, y - 1, z) - filled(x2, y + 1, z);
2167
+ const nz = filled(x2, y, z - 1) - filled(x2, y, z + 1);
2168
+ const index = nx + 1 + (ny + 1) * 3 + (nz + 1) * 9;
2169
+ const q = ((Math.floor(z / columns2) * depth + y) * imageWidth + z % columns2 * width + x2) * 4;
2170
+ const roofZ = roof[y * width + x2];
2171
+ const planSurface = z === roofZ && flatAt(x2 - 2, y, z) && flatAt(x2 + 2, y, z) && flatAt(x2, y - 2, z) && flatAt(x2, y + 2, z);
2172
+ const choices = surfaceViews[index];
2173
+ const visible = planSurface || nz < 0 && views.bottom ? choices : surfaceViews[index - nz * 9];
2174
+ let total = 0;
2175
+ let red = 0, green = 0, blue = 0;
2176
+ for (const direction of visible) {
2177
+ if (!planSurface && direction === "top") continue;
2178
+ const view = views[direction];
2179
+ const p = sample(view, ...viewUV(direction, (x2 + 0.5) / width, (y + 0.5) / depth, (z + 0.5) / layers));
2180
+ if (view.data[p + 3] < 128) continue;
2181
+ const r = view.data[p], g2 = view.data[p + 1], b = view.data[p + 2];
2182
+ if (total && Math.max(Math.abs(r - red / total), Math.abs(g2 - green / total), Math.abs(b - blue / total)) > 66) continue;
2183
+ const weight = direction === "front" || direction === "rear" ? 0.1 + Math.abs(ny) : direction === "left" || direction === "right" ? 0.1 + Math.abs(nx) : 0.1 + Math.abs(nz);
2184
+ red += r * weight;
2185
+ green += g2 * weight;
2186
+ blue += b * weight;
2187
+ total += weight;
2188
+ }
2189
+ if (total) {
2190
+ data[q] = Math.round(red / total);
2191
+ data[q + 1] = Math.round(green / total);
2192
+ data[q + 2] = Math.round(blue / total);
2193
+ data[q + 3] = 255;
2194
+ }
2195
+ }
2196
+ return {
2197
+ target: "stack",
2198
+ size,
2199
+ pivot,
2200
+ width,
2201
+ depth,
2202
+ layers,
2203
+ columns: columns2,
2204
+ spacing: size[2] / layers,
2205
+ texture: { width: imageWidth, height: imageHeight, data }
2206
+ };
2207
+ }
2208
+ function reconstruct(input, target, settings = {}) {
2209
+ return reconstructPrepared(prepareViews(input, settings.threshold), target, settings);
2210
+ }
2211
+ function reconstructPrepared(views, target, settings) {
2212
+ let mesh;
2213
+ if (target === "mesh" && settings.meshMethod === "contour") {
2214
+ const { size, pivot } = dimensions(views, settings);
2215
+ const { tiles, texture } = textureAtlas(views, {}, true);
2216
+ const front = views.front;
2217
+ const scale = Math.min(1, 1024 / Math.max(front.width, front.height));
2218
+ const mask = resize(front, Math.max(1, Math.round(front.width * scale)), Math.max(1, Math.round(front.height * scale)));
2219
+ mesh = extrudeContours(views, size, pivot, mask, tiles, texture, settings.contourHub ?? false, settings.resolution ?? 96);
2220
+ } else {
2221
+ const g = grid(views, settings);
2222
+ if (target === "stack") return makeStack(g, g.aligned);
2223
+ mesh = makeMesh(g, views);
2224
+ }
2225
+ if (settings.textureProjection === "top-contour")
2226
+ projectUpperContour(mesh, views.top, settings.resolution ?? 96, settings.layers ?? 48);
2227
+ return mesh;
2228
+ }
2229
+ var clamp2;
2230
+ var init_reconstruct = __esm({
2231
+ "packages/core/src/reconstruct.ts"() {
2232
+ "use strict";
2233
+ init_texture_projection();
2234
+ init_contour();
2235
+ init_atlas_comparison();
2236
+ init_surface();
2237
+ init_views();
2238
+ clamp2 = (value, min, max2) => Math.min(max2, Math.max(min, value));
2239
+ }
2240
+ });
2241
+
2242
+ // node_modules/fflate/esm/index.mjs
2243
+ import { createRequire } from "module";
2244
+ function zlibSync(data, opts) {
2245
+ if (!opts)
2246
+ opts = {};
2247
+ var a = adler();
2248
+ a.p(data);
2249
+ var d = dopt(data, opts, opts.dictionary ? 6 : 2, 4);
2250
+ return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d;
2251
+ }
2252
+ var require2, _a, Worker, isMarkedAsUntransferable, u8, u16, i32, fleb, fdeb, clim, freb, _a, fl, revfl, _b, fd, revfd, rev, x, i, hMap, flt, i, i, i, i, fdt, i, flm, fdm, shft, slc, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, deo, et, dflt, adler, dopt, wbytes, zlh, td, tds;
2253
+ var init_esm = __esm({
2254
+ "node_modules/fflate/esm/index.mjs"() {
2255
+ require2 = createRequire("/");
2256
+ try {
2257
+ _a = require2("worker_threads"), Worker = _a.Worker, isMarkedAsUntransferable = _a.isMarkedAsUntransferable;
2258
+ } catch (e) {
2259
+ }
2260
+ u8 = Uint8Array;
2261
+ u16 = Uint16Array;
2262
+ i32 = Int32Array;
2263
+ fleb = new u8([
2264
+ 0,
2265
+ 0,
2266
+ 0,
2267
+ 0,
2268
+ 0,
2269
+ 0,
2270
+ 0,
2271
+ 0,
2272
+ 1,
2273
+ 1,
2274
+ 1,
2275
+ 1,
2276
+ 2,
2277
+ 2,
2278
+ 2,
2279
+ 2,
2280
+ 3,
2281
+ 3,
2282
+ 3,
2283
+ 3,
2284
+ 4,
2285
+ 4,
2286
+ 4,
2287
+ 4,
2288
+ 5,
2289
+ 5,
2290
+ 5,
2291
+ 5,
2292
+ 0,
2293
+ /* unused */
2294
+ 0,
2295
+ 0,
2296
+ /* impossible */
2297
+ 0
2298
+ ]);
2299
+ fdeb = new u8([
2300
+ 0,
2301
+ 0,
2302
+ 0,
2303
+ 0,
2304
+ 1,
2305
+ 1,
2306
+ 2,
2307
+ 2,
2308
+ 3,
2309
+ 3,
2310
+ 4,
2311
+ 4,
2312
+ 5,
2313
+ 5,
2314
+ 6,
2315
+ 6,
2316
+ 7,
2317
+ 7,
2318
+ 8,
2319
+ 8,
2320
+ 9,
2321
+ 9,
2322
+ 10,
2323
+ 10,
2324
+ 11,
2325
+ 11,
2326
+ 12,
2327
+ 12,
2328
+ 13,
2329
+ 13,
2330
+ /* unused */
2331
+ 0,
2332
+ 0
2333
+ ]);
2334
+ clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
2335
+ freb = function(eb, start) {
2336
+ var b = new u16(31);
2337
+ for (var i2 = 0; i2 < 31; ++i2) {
2338
+ b[i2] = start += 1 << eb[i2 - 1];
2339
+ }
2340
+ var r = new i32(b[30]);
2341
+ for (var i2 = 1; i2 < 30; ++i2) {
2342
+ for (var j = b[i2]; j < b[i2 + 1]; ++j) {
2343
+ r[j] = j - b[i2] << 5 | i2;
2344
+ }
2345
+ }
2346
+ return { b, r };
2347
+ };
2348
+ _a = freb(fleb, 2);
2349
+ fl = _a.b;
2350
+ revfl = _a.r;
2351
+ fl[28] = 258, revfl[258] = 28;
2352
+ _b = freb(fdeb, 0);
2353
+ fd = _b.b;
2354
+ revfd = _b.r;
2355
+ rev = new u16(32768);
2356
+ for (i = 0; i < 32768; ++i) {
2357
+ x = (i & 43690) >> 1 | (i & 21845) << 1;
2358
+ x = (x & 52428) >> 2 | (x & 13107) << 2;
2359
+ x = (x & 61680) >> 4 | (x & 3855) << 4;
2360
+ rev[i] = ((x & 65280) >> 8 | (x & 255) << 8) >> 1;
2361
+ }
2362
+ hMap = (function(cd, mb, r) {
2363
+ var s = cd.length;
2364
+ var i2 = 0;
2365
+ var l = new u16(mb);
2366
+ for (; i2 < s; ++i2) {
2367
+ if (cd[i2])
2368
+ ++l[cd[i2] - 1];
2369
+ }
2370
+ var le = new u16(mb);
2371
+ for (i2 = 1; i2 < mb; ++i2) {
2372
+ le[i2] = le[i2 - 1] + l[i2 - 1] << 1;
2373
+ }
2374
+ var co;
2375
+ if (r) {
2376
+ co = new u16(1 << mb);
2377
+ var rvb = 15 - mb;
2378
+ for (i2 = 0; i2 < s; ++i2) {
2379
+ if (cd[i2]) {
2380
+ var sv = i2 << 4 | cd[i2];
2381
+ var r_1 = mb - cd[i2];
2382
+ var v = le[cd[i2] - 1]++ << r_1;
2383
+ for (var m = v | (1 << r_1) - 1; v <= m; ++v) {
2384
+ co[rev[v] >> rvb] = sv;
2385
+ }
2386
+ }
2387
+ }
2388
+ } else {
2389
+ co = new u16(s);
2390
+ for (i2 = 0; i2 < s; ++i2) {
2391
+ if (cd[i2]) {
2392
+ co[i2] = rev[le[cd[i2] - 1]++] >> 15 - cd[i2];
2393
+ }
2394
+ }
2395
+ }
2396
+ return co;
2397
+ });
2398
+ flt = new u8(288);
2399
+ for (i = 0; i < 144; ++i)
2400
+ flt[i] = 8;
2401
+ for (i = 144; i < 256; ++i)
2402
+ flt[i] = 9;
2403
+ for (i = 256; i < 280; ++i)
2404
+ flt[i] = 7;
2405
+ for (i = 280; i < 288; ++i)
2406
+ flt[i] = 8;
2407
+ fdt = new u8(32);
2408
+ for (i = 0; i < 32; ++i)
2409
+ fdt[i] = 5;
2410
+ flm = /* @__PURE__ */ hMap(flt, 9, 0);
2411
+ fdm = /* @__PURE__ */ hMap(fdt, 5, 0);
2412
+ shft = function(p) {
2413
+ return (p + 7) / 8 | 0;
2414
+ };
2415
+ slc = function(v, s, e) {
2416
+ if (s == null || s < 0)
2417
+ s = 0;
2418
+ if (e == null || e > v.length)
2419
+ e = v.length;
2420
+ return new u8(v.subarray(s, e));
2421
+ };
2422
+ wbits = function(d, p, v) {
2423
+ v <<= p & 7;
2424
+ var o = p / 8 | 0;
2425
+ d[o] |= v;
2426
+ d[o + 1] |= v >> 8;
2427
+ };
2428
+ wbits16 = function(d, p, v) {
2429
+ v <<= p & 7;
2430
+ var o = p / 8 | 0;
2431
+ d[o] |= v;
2432
+ d[o + 1] |= v >> 8;
2433
+ d[o + 2] |= v >> 16;
2434
+ };
2435
+ hTree = function(d, mb) {
2436
+ var t = [];
2437
+ for (var i2 = 0; i2 < d.length; ++i2) {
2438
+ if (d[i2])
2439
+ t.push({ s: i2, f: d[i2] });
2440
+ }
2441
+ var s = t.length;
2442
+ var t2 = t.slice();
2443
+ if (!s)
2444
+ return { t: et, l: 0 };
2445
+ if (s == 1) {
2446
+ var v = new u8(t[0].s + 1);
2447
+ v[t[0].s] = 1;
2448
+ return { t: v, l: 1 };
2449
+ }
2450
+ t.sort(function(a, b) {
2451
+ return a.f - b.f;
2452
+ });
2453
+ t.push({ s: -1, f: 25001 });
2454
+ var l = t[0], r = t[1], i0 = 0, i1 = 1, i22 = 2;
2455
+ t[0] = { s: -1, f: l.f + r.f, l, r };
2456
+ while (i1 != s - 1) {
2457
+ l = t[t[i0].f < t[i22].f ? i0++ : i22++];
2458
+ r = t[i0 != i1 && t[i0].f < t[i22].f ? i0++ : i22++];
2459
+ t[i1++] = { s: -1, f: l.f + r.f, l, r };
2460
+ }
2461
+ var maxSym = t2[0].s;
2462
+ for (var i2 = 1; i2 < s; ++i2) {
2463
+ if (t2[i2].s > maxSym)
2464
+ maxSym = t2[i2].s;
2465
+ }
2466
+ var tr = new u16(maxSym + 1);
2467
+ var mbt = ln(t[i1 - 1], tr, 0);
2468
+ if (mbt > mb) {
2469
+ var i2 = 0, dt = 0;
2470
+ var lft = mbt - mb, cst = 1 << lft;
2471
+ t2.sort(function(a, b) {
2472
+ return tr[b.s] - tr[a.s] || a.f - b.f;
2473
+ });
2474
+ for (; i2 < s; ++i2) {
2475
+ var i2_1 = t2[i2].s;
2476
+ if (tr[i2_1] > mb) {
2477
+ dt += cst - (1 << mbt - tr[i2_1]);
2478
+ tr[i2_1] = mb;
2479
+ } else
2480
+ break;
2481
+ }
2482
+ dt >>= lft;
2483
+ while (dt > 0) {
2484
+ var i2_2 = t2[i2].s;
2485
+ if (tr[i2_2] < mb)
2486
+ dt -= 1 << mb - tr[i2_2]++ - 1;
2487
+ else
2488
+ ++i2;
2489
+ }
2490
+ for (; i2 >= 0 && dt; --i2) {
2491
+ var i2_3 = t2[i2].s;
2492
+ if (tr[i2_3] == mb) {
2493
+ --tr[i2_3];
2494
+ ++dt;
2495
+ }
2496
+ }
2497
+ mbt = mb;
2498
+ }
2499
+ return { t: new u8(tr), l: mbt };
2500
+ };
2501
+ ln = function(n, l, d) {
2502
+ return n.s == -1 ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1)) : l[n.s] = d;
2503
+ };
2504
+ lc = function(c) {
2505
+ var s = c.length;
2506
+ while (s && !c[--s])
2507
+ ;
2508
+ var cl = new u16(++s);
2509
+ var cli = 0, cln = c[0], cls = 1;
2510
+ var w = function(v) {
2511
+ cl[cli++] = v;
2512
+ };
2513
+ for (var i2 = 1; i2 <= s; ++i2) {
2514
+ if (c[i2] == cln && i2 != s)
2515
+ ++cls;
2516
+ else {
2517
+ if (!cln && cls > 2) {
2518
+ for (; cls > 138; cls -= 138)
2519
+ w(32754);
2520
+ if (cls > 2) {
2521
+ w(cls > 10 ? cls - 11 << 5 | 28690 : cls - 3 << 5 | 12305);
2522
+ cls = 0;
2523
+ }
2524
+ } else if (cls > 3) {
2525
+ w(cln), --cls;
2526
+ for (; cls > 6; cls -= 6)
2527
+ w(8304);
2528
+ if (cls > 2)
2529
+ w(cls - 3 << 5 | 8208), cls = 0;
2530
+ }
2531
+ while (cls--)
2532
+ w(cln);
2533
+ cls = 1;
2534
+ cln = c[i2];
2535
+ }
2536
+ }
2537
+ return { c: cl.subarray(0, cli), n: s };
2538
+ };
2539
+ clen = function(cf, cl) {
2540
+ var l = 0;
2541
+ for (var i2 = 0; i2 < cl.length; ++i2)
2542
+ l += cf[i2] * cl[i2];
2543
+ return l;
2544
+ };
2545
+ wfblk = function(out, pos, dat) {
2546
+ var s = dat.length;
2547
+ var o = shft(pos + 2);
2548
+ out[o] = s & 255;
2549
+ out[o + 1] = s >> 8;
2550
+ out[o + 2] = out[o] ^ 255;
2551
+ out[o + 3] = out[o + 1] ^ 255;
2552
+ for (var i2 = 0; i2 < s; ++i2)
2553
+ out[o + i2 + 4] = dat[i2];
2554
+ return (o + 4 + s) * 8;
2555
+ };
2556
+ wblk = function(dat, out, final, syms, lf, df, eb, li, bs, bl, p) {
2557
+ wbits(out, p++, final);
2558
+ ++lf[256];
2559
+ var _a2 = hTree(lf, 15), dlt = _a2.t, mlb = _a2.l;
2560
+ var _b2 = hTree(df, 15), ddt = _b2.t, mdb = _b2.l;
2561
+ var _c = lc(dlt), lclt = _c.c, nlc = _c.n;
2562
+ var _d = lc(ddt), lcdt = _d.c, ndc = _d.n;
2563
+ var lcfreq = new u16(19);
2564
+ for (var i2 = 0; i2 < lclt.length; ++i2)
2565
+ ++lcfreq[lclt[i2] & 31];
2566
+ for (var i2 = 0; i2 < lcdt.length; ++i2)
2567
+ ++lcfreq[lcdt[i2] & 31];
2568
+ var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l;
2569
+ var nlcc = 19;
2570
+ for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)
2571
+ ;
2572
+ var flen = bl + 5 << 3;
2573
+ var ftlen = clen(lf, flt) + clen(df, fdt) + eb;
2574
+ var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18];
2575
+ if (bs >= 0 && flen <= ftlen && flen <= dtlen)
2576
+ return wfblk(out, p, dat.subarray(bs, bs + bl));
2577
+ var lm, ll, dm, dl;
2578
+ wbits(out, p, 1 + (dtlen < ftlen)), p += 2;
2579
+ if (dtlen < ftlen) {
2580
+ lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;
2581
+ var llm = hMap(lct, mlcb, 0);
2582
+ wbits(out, p, nlc - 257);
2583
+ wbits(out, p + 5, ndc - 1);
2584
+ wbits(out, p + 10, nlcc - 4);
2585
+ p += 14;
2586
+ for (var i2 = 0; i2 < nlcc; ++i2)
2587
+ wbits(out, p + 3 * i2, lct[clim[i2]]);
2588
+ p += 3 * nlcc;
2589
+ var lcts = [lclt, lcdt];
2590
+ for (var it = 0; it < 2; ++it) {
2591
+ var clct = lcts[it];
2592
+ for (var i2 = 0; i2 < clct.length; ++i2) {
2593
+ var len = clct[i2] & 31;
2594
+ wbits(out, p, llm[len]), p += lct[len];
2595
+ if (len > 15)
2596
+ wbits(out, p, clct[i2] >> 5 & 127), p += clct[i2] >> 12;
2597
+ }
2598
+ }
2599
+ } else {
2600
+ lm = flm, ll = flt, dm = fdm, dl = fdt;
2601
+ }
2602
+ for (var i2 = 0; i2 < li; ++i2) {
2603
+ var sym = syms[i2];
2604
+ if (sym > 255) {
2605
+ var len = sym >> 18 & 31;
2606
+ wbits16(out, p, lm[len + 257]), p += ll[len + 257];
2607
+ if (len > 7)
2608
+ wbits(out, p, sym >> 23 & 31), p += fleb[len];
2609
+ var dst = sym & 31;
2610
+ wbits16(out, p, dm[dst]), p += dl[dst];
2611
+ if (dst > 3)
2612
+ wbits16(out, p, sym >> 5 & 8191), p += fdeb[dst];
2613
+ } else {
2614
+ wbits16(out, p, lm[sym]), p += ll[sym];
2615
+ }
2616
+ }
2617
+ wbits16(out, p, lm[256]);
2618
+ return p + ll[256];
2619
+ };
2620
+ deo = /* @__PURE__ */ new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);
2621
+ et = /* @__PURE__ */ new u8(0);
2622
+ dflt = function(dat, lvl, plvl, pre, post, st) {
2623
+ var s = st.z || dat.length;
2624
+ var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7e3)) + post);
2625
+ var w = o.subarray(pre, o.length - post);
2626
+ var lst = st.l;
2627
+ var pos = (st.r || 0) & 7;
2628
+ if (lvl) {
2629
+ if (pos)
2630
+ w[0] = st.r >> 3;
2631
+ var opt = deo[lvl - 1];
2632
+ var n = opt >> 13, c = opt & 8191;
2633
+ var msk_1 = (1 << plvl) - 1;
2634
+ var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1);
2635
+ var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;
2636
+ var hsh = function(i3) {
2637
+ return (dat[i3] ^ dat[i3 + 1] << bs1_1 ^ dat[i3 + 2] << bs2_1) & msk_1;
2638
+ };
2639
+ var syms = new i32(25e3);
2640
+ var lf = new u16(288), df = new u16(32);
2641
+ var lc_1 = 0, eb = 0, i2 = st.i || 0, li = 0, wi = st.w || 0, bs = 0;
2642
+ for (; i2 + 2 < s; ++i2) {
2643
+ var hv = hsh(i2);
2644
+ var imod = i2 & 32767, pimod = head[hv];
2645
+ prev[imod] = pimod;
2646
+ head[hv] = imod;
2647
+ if (wi <= i2) {
2648
+ var rem = s - i2;
2649
+ if ((lc_1 > 7e3 || li > 24576) && (rem > 423 || !lst)) {
2650
+ pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i2 - bs, pos);
2651
+ li = lc_1 = eb = 0, bs = i2;
2652
+ for (var j = 0; j < 286; ++j)
2653
+ lf[j] = 0;
2654
+ for (var j = 0; j < 30; ++j)
2655
+ df[j] = 0;
2656
+ }
2657
+ var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767;
2658
+ if (rem > 2 && hv == hsh(i2 - dif)) {
2659
+ var maxn = Math.min(n, rem) - 1;
2660
+ var maxd = Math.min(32767, i2);
2661
+ var ml = Math.min(258, rem);
2662
+ while (dif <= maxd && --ch_1 && imod != pimod) {
2663
+ if (dat[i2 + l] == dat[i2 + l - dif]) {
2664
+ var nl = 0;
2665
+ for (; nl < ml && dat[i2 + nl] == dat[i2 + nl - dif]; ++nl)
2666
+ ;
2667
+ if (nl > l) {
2668
+ l = nl, d = dif;
2669
+ if (nl > maxn)
2670
+ break;
2671
+ var mmd = Math.min(dif, nl - 2);
2672
+ var md = 0;
2673
+ for (var j = 0; j < mmd; ++j) {
2674
+ var ti = i2 - dif + j & 32767;
2675
+ var pti = prev[ti];
2676
+ var cd = ti - pti & 32767;
2677
+ if (cd > md)
2678
+ md = cd, pimod = ti;
2679
+ }
2680
+ }
2681
+ }
2682
+ imod = pimod, pimod = prev[imod];
2683
+ dif += imod - pimod & 32767;
2684
+ }
2685
+ }
2686
+ if (d) {
2687
+ syms[li++] = 268435456 | revfl[l] << 18 | revfd[d];
2688
+ var lin = revfl[l] & 31, din = revfd[d] & 31;
2689
+ eb += fleb[lin] + fdeb[din];
2690
+ ++lf[257 + lin];
2691
+ ++df[din];
2692
+ wi = i2 + l;
2693
+ ++lc_1;
2694
+ } else {
2695
+ syms[li++] = dat[i2];
2696
+ ++lf[dat[i2]];
2697
+ }
2698
+ }
2699
+ }
2700
+ for (i2 = Math.max(i2, wi); i2 < s; ++i2) {
2701
+ syms[li++] = dat[i2];
2702
+ ++lf[dat[i2]];
2703
+ }
2704
+ pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i2 - bs, pos);
2705
+ if (!lst) {
2706
+ st.r = pos & 7 | w[pos / 8 | 0] << 3;
2707
+ pos -= 7;
2708
+ st.h = head, st.p = prev, st.i = i2, st.w = wi;
2709
+ }
2710
+ } else {
2711
+ for (var i2 = st.w || 0; i2 < s + lst; i2 += 65535) {
2712
+ var e = i2 + 65535;
2713
+ if (e >= s) {
2714
+ w[pos / 8 | 0] = lst;
2715
+ e = s;
2716
+ }
2717
+ pos = wfblk(w, pos + 1, dat.subarray(i2, e));
2718
+ }
2719
+ st.i = s;
2720
+ }
2721
+ return slc(o, 0, pre + shft(pos) + post);
2722
+ };
2723
+ adler = function() {
2724
+ var a = 1, b = 0;
2725
+ return {
2726
+ p: function(d) {
2727
+ var n = a, m = b;
2728
+ var l = d.length | 0;
2729
+ for (var i2 = 0; i2 != l; ) {
2730
+ var e = Math.min(i2 + 2655, l);
2731
+ for (; i2 < e; ++i2)
2732
+ m += n += d[i2];
2733
+ n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16);
2734
+ }
2735
+ a = n, b = m;
2736
+ },
2737
+ d: function() {
2738
+ a %= 65521, b %= 65521;
2739
+ return (a & 255) << 24 | (a & 65280) << 8 | (b & 255) << 8 | b >> 8;
2740
+ }
2741
+ };
2742
+ };
2743
+ dopt = function(dat, opt, pre, post, st) {
2744
+ if (!st) {
2745
+ st = { l: 1 };
2746
+ if (opt.dictionary) {
2747
+ var dict = opt.dictionary.subarray(-32768);
2748
+ var newDat = new u8(dict.length + dat.length);
2749
+ newDat.set(dict);
2750
+ newDat.set(dat, dict.length);
2751
+ dat = newDat;
2752
+ st.w = dict.length;
2753
+ }
2754
+ }
2755
+ return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20 : 12 + opt.mem, pre, post, st);
2756
+ };
2757
+ wbytes = function(d, b, v) {
2758
+ for (; v; ++b)
2759
+ d[b] = v, v >>>= 8;
2760
+ };
2761
+ zlh = function(c, o) {
2762
+ var lv = o.level, fl2 = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2;
2763
+ c[0] = 120, c[1] = fl2 << 6 | (o.dictionary && 32);
2764
+ c[1] |= 31 - (c[0] << 8 | c[1]) % 31;
2765
+ if (o.dictionary) {
2766
+ var h = adler();
2767
+ h.p(o.dictionary);
2768
+ wbytes(c, 2, h.d());
2769
+ }
2770
+ };
2771
+ td = typeof TextDecoder != "undefined" && /* @__PURE__ */ new TextDecoder();
2772
+ tds = 0;
2773
+ try {
2774
+ td.decode(et, { stream: true });
2775
+ tds = 1;
2776
+ } catch (e) {
2777
+ }
2778
+ }
2779
+ });
2780
+
2781
+ // packages/core/src/export.ts
2782
+ function concat(parts) {
2783
+ const output = new Uint8Array(parts.reduce((total, part) => total + part.length, 0));
2784
+ let offset = 0;
2785
+ for (const part of parts) {
2786
+ output.set(part, offset);
2787
+ offset += part.length;
2788
+ }
2789
+ return output;
2790
+ }
2791
+ function pngChunk(name, bytes) {
2792
+ const chunk = new Uint8Array(bytes.length + 12);
2793
+ const view = new DataView(chunk.buffer);
2794
+ view.setUint32(0, bytes.length);
2795
+ chunk.set(encoder.encode(name), 4);
2796
+ chunk.set(bytes, 8);
2797
+ let crc = 4294967295;
2798
+ for (let i2 = 4; i2 < chunk.length - 4; i2++) crc = crc >>> 8 ^ crcTable[(crc ^ chunk[i2]) & 255];
2799
+ view.setUint32(chunk.length - 4, crc ^ 4294967295);
2800
+ return chunk;
2801
+ }
2802
+ function encodePng({ width, height, data }) {
2803
+ const header = new Uint8Array(13), view = new DataView(header.buffer);
2804
+ view.setUint32(0, width);
2805
+ view.setUint32(4, height);
2806
+ header[8] = 8;
2807
+ header[9] = 6;
2808
+ const stride = width * 4;
2809
+ const rows = new Uint8Array((stride + 1) * height);
2810
+ for (let y = 0; y < height; y++) rows.set(data.subarray(y * stride, (y + 1) * stride), y * (stride + 1) + 1);
2811
+ return concat([
2812
+ Uint8Array.of(137, 80, 78, 71, 13, 10, 26, 10),
2813
+ pngChunk("IHDR", header),
2814
+ pngChunk("IDAT", zlibSync(rows)),
2815
+ pngChunk("IEND", new Uint8Array(0))
2816
+ ]);
2817
+ }
2818
+ function padded(bytes, pad = 0) {
2819
+ const output = new Uint8Array(align(bytes.length)).fill(pad);
2820
+ output.set(bytes);
2821
+ return output;
2822
+ }
2823
+ function asBytes(data) {
2824
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
2825
+ }
2826
+ function encodeGlb(mesh) {
2827
+ const sources = [asBytes(mesh.positions), asBytes(mesh.normals), asBytes(mesh.uvs), asBytes(mesh.indices), encodePng(mesh.texture)];
2828
+ let offset = 0;
2829
+ const bufferViews = sources.map((source, index) => {
2830
+ const target = index < 3 ? 34962 : index === 3 ? 34963 : void 0;
2831
+ const entry = { buffer: 0, byteOffset: offset, byteLength: source.length, target };
2832
+ offset += align(source.length);
2833
+ return entry;
2834
+ });
2835
+ const min = [Infinity, Infinity, Infinity], max2 = [-Infinity, -Infinity, -Infinity];
2836
+ for (let i2 = 0; i2 < mesh.positions.length; i2++) {
2837
+ min[i2 % 3] = Math.min(min[i2 % 3], mesh.positions[i2]);
2838
+ max2[i2 % 3] = Math.max(max2[i2 % 3], mesh.positions[i2]);
2839
+ }
2840
+ const count2 = mesh.positions.length / 3;
2841
+ const json2 = padded(encoder.encode(JSON.stringify({
2842
+ asset: { version: "2.0", generator: "stack3.js" },
2843
+ extensionsUsed: ["KHR_materials_unlit"],
2844
+ scene: 0,
2845
+ scenes: [{ nodes: [0] }],
2846
+ nodes: [{ mesh: 0, extras: { size: mesh.size, pivot: mesh.pivot } }],
2847
+ meshes: [{ primitives: [{ attributes: { POSITION: 0, NORMAL: 1, TEXCOORD_0: 2 }, indices: 3, material: 0 }] }],
2848
+ materials: [{ extensions: { KHR_materials_unlit: {} }, pbrMetallicRoughness: { baseColorTexture: { index: 0 } } }],
2849
+ textures: [{ source: 0, sampler: 0 }],
2850
+ samplers: [{ magFilter: 9729, minFilter: 9729, wrapS: 33071, wrapT: 33071 }],
2851
+ images: [{ mimeType: "image/png", bufferView: 4 }],
2852
+ accessors: [
2853
+ { bufferView: 0, componentType: 5126, count: count2, type: "VEC3", min, max: max2 },
2854
+ { bufferView: 1, componentType: 5126, count: count2, type: "VEC3" },
2855
+ { bufferView: 2, componentType: 5126, count: count2, type: "VEC2" },
2856
+ { bufferView: 3, componentType: 5125, count: mesh.indices.length, type: "SCALAR" }
2857
+ ],
2858
+ bufferViews,
2859
+ buffers: [{ byteLength: offset }]
2860
+ })), 32);
2861
+ const binary = concat(sources.map((source) => padded(source)));
2862
+ const header = new Uint8Array(20), head = new DataView(header.buffer);
2863
+ head.setUint32(0, 1179937895, true);
2864
+ head.setUint32(4, 2, true);
2865
+ head.setUint32(8, 28 + json2.length + binary.length, true);
2866
+ head.setUint32(12, json2.length, true);
2867
+ head.setUint32(16, 1313821514, true);
2868
+ const chunk = new Uint8Array(8), bin = new DataView(chunk.buffer);
2869
+ bin.setUint32(0, binary.length, true);
2870
+ bin.setUint32(4, 5130562, true);
2871
+ return concat([header, json2, chunk, binary]);
2872
+ }
2873
+ function encodeStack(stack) {
2874
+ const { width, depth, layers, columns: columns2, spacing, size, pivot } = stack;
2875
+ return {
2876
+ png: encodePng(stack.texture),
2877
+ manifest: {
2878
+ version: 1,
2879
+ atlas: "stack.png",
2880
+ width,
2881
+ depth,
2882
+ layers,
2883
+ columns: columns2,
2884
+ spacing,
2885
+ size,
2886
+ pivot,
2887
+ layerOrder: "bottom-to-top",
2888
+ layout: "row-major",
2889
+ axes: "xy-ground-z-up-y-forward"
2890
+ }
2891
+ };
2892
+ }
2893
+ function readStackBundle(manifest, texture) {
2894
+ if (!manifest || typeof manifest !== "object") throw new Error("Expected a stack3 stack manifest.");
2895
+ const { version: version2, atlas, layout, layerOrder, axes: axes2, width, depth, layers, columns: columns2, spacing, size, pivot } = manifest;
2896
+ const dimension = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0;
2897
+ const vector2 = (value) => Array.isArray(value) && value.length === 3 && value.every(Number.isFinite);
2898
+ if (version2 !== 1 || atlas !== "stack.png" || layout !== "row-major" || layerOrder !== "bottom-to-top" || axes2 !== "xy-ground-z-up-y-forward" || !dimension(width) || !dimension(depth) || !dimension(layers) || !dimension(columns2) || columns2 > layers || layers > 128 || !vector2(size) || size.some((value) => value <= 0) || !vector2(pivot) || typeof spacing !== "number" || !Number.isFinite(spacing) || spacing <= 0 || texture.width !== width * columns2 || texture.height !== depth * Math.ceil(layers / columns2) || texture.data.length !== texture.width * texture.height * 4) {
2899
+ throw new Error("The stack manifest does not match the PNG or uses an unsupported layout.");
2900
+ }
2901
+ return { target: "stack", texture, width, depth, layers, columns: columns2, spacing, size, pivot };
2902
+ }
2903
+ var encoder, crcTable, align;
2904
+ var init_export = __esm({
2905
+ "packages/core/src/export.ts"() {
2906
+ "use strict";
2907
+ init_esm();
2908
+ encoder = new TextEncoder();
2909
+ crcTable = Uint32Array.from({ length: 256 }, (_, index) => {
2910
+ let value = index;
2911
+ for (let i2 = 0; i2 < 8; i2++) value = value >>> 1 ^ (value & 1 ? 3988292384 : 0);
2912
+ return value;
2913
+ });
2914
+ align = (length) => length + 3 & ~3;
2915
+ }
2916
+ });
2917
+
2918
+ // packages/core/src/scripts.ts
2919
+ function validateScript(script) {
2920
+ if (typeof script.source !== "string" || !script.source.trim() || script.source.length > 16e3) {
2921
+ throw new Error("Script source must contain 1\u201316,000 characters.");
2922
+ }
2923
+ const names = /* @__PURE__ */ new Set();
2924
+ for (const field of script.fields) {
2925
+ if (!/^[A-Za-z_]\w{0,47}$/.test(field.name) || names.has(field.name)) throw new Error("Invalid or repeated script field name: " + field.name);
2926
+ if (!field.label.trim() || field.label.length > 80 || field.min >= field.max || field.value < field.min || field.value > field.max) {
2927
+ throw new Error("Invalid bounds or label for script field: " + field.name);
2928
+ }
2929
+ names.add(field.name);
2930
+ }
2931
+ }
2932
+ function vehicleSource(wheels) {
2933
+ const routeWheels = wheels ? ` const wheels = ${JSON.stringify(wheels)};
2934
+ for (let i = 0; i < wheels.length; i++) {
2935
+ wheelRotations[wheels[i]] = [spin, i < 2 ? steering : 0, 0];
2936
+ }` : ` for (const child of children) {
2937
+ if (/wheel/i.test(child.name)) {
2938
+ wheelRotations[child.id] = [spin, /^front/i.test(child.name) ? steering : 0, 0];
2939
+ }
2940
+ }`;
2941
+ return `function update({ dt, keys, fields, state, rotation, children }) {
2942
+ const pressed = (...codes) => codes.some(code => keys.includes(code));
2943
+ const throttle = Number(pressed('KeyW', 'ArrowUp')) - Number(pressed('KeyS', 'ArrowDown'));
2944
+ const steer = Number(pressed('KeyA', 'ArrowLeft')) - Number(pressed('KeyD', 'ArrowRight'));
2945
+ const radians = Math.PI / 180;
2946
+ const target = throttle * (throttle < 0 ? fields.reverseSpeed : fields.forwardSpeed);
2947
+ const speed = state.speed || 0;
2948
+ const change = fields.acceleration * dt;
2949
+ const nextSpeed = speed + Math.max(-change, Math.min(change, target - speed));
2950
+ const distance = (speed + nextSpeed) * .5 * dt;
2951
+ const steering = steer * fields.steeringAngle;
2952
+ const turn = distance / fields.wheelbase * Math.tan(steering * radians) / radians;
2953
+ const yaw = ((state.yaw || 0) + turn) % 360;
2954
+ const heading = (rotation[1] + yaw - turn * .5) * radians;
2955
+ const x = (state.x || 0) - Math.sin(heading) * distance;
2956
+ const z = (state.z || 0) - Math.cos(heading) * distance;
2957
+ const spin = ((state.spin || 0) - distance / fields.wheelRadius / radians) % 360;
2958
+ const wheelRotations = {};
2959
+ ${routeWheels}
2960
+ return { state: { speed: nextSpeed, x, z, yaw, spin }, translation: [x, 0, z],
2961
+ rotation: [0, yaw, 0], childRotations: wheelRotations };
2962
+ }`;
2963
+ }
2964
+ function bindVehicleWheels(wheels, wheelbase, wheelRadius) {
2965
+ return { ...vehicleScript, source: vehicleSource(wheels), fields: vehicleScript.fields.map((field) => {
2966
+ const value = field.name === "wheelbase" ? wheelbase : field.name === "wheelRadius" ? wheelRadius : field.value;
2967
+ return { ...field, value, min: Math.min(field.min, value), max: Math.max(field.max, value) };
2968
+ }) };
2969
+ }
2970
+ function isBuiltInVehicleSource(source) {
2971
+ if (source === vehicleScript.source) return true;
2972
+ const bindings = /^ const wheels = (\[.*\]);$/m.exec(source);
2973
+ if (!bindings) return false;
2974
+ try {
2975
+ const ids = JSON.parse(bindings[1]);
2976
+ return Array.isArray(ids) && ids.length === 4 && ids.every((id) => typeof id === "string") && vehicleSource(ids) === source;
2977
+ } catch {
2978
+ return false;
2979
+ }
2980
+ }
2981
+ function trackedDriveSource(tracks) {
2982
+ return `function update({ dt, keys, fields, state, rotation }) {
2983
+ const tracks = ${JSON.stringify(tracks)};
2984
+ const held = (...codes) => codes.some(code => keys.includes(code));
2985
+ const throttle = Number(held('KeyW', 'ArrowUp')) - Number(held('KeyS', 'ArrowDown'));
2986
+ const direction = Number(held('KeyA', 'ArrowLeft')) - Number(held('KeyD', 'ArrowRight'));
2987
+ const target = throttle * (throttle < 0 ? fields.reverseSpeed : fields.forwardSpeed);
2988
+ const oldSpeed = state.speed ?? 0;
2989
+ const speed = oldSpeed + (target - oldSpeed) * (1 - Math.exp(-fields.response * dt));
2990
+ const distance = (oldSpeed + speed) * .5 * dt;
2991
+ const turn = direction * fields.turnRate * dt;
2992
+ const radians = Math.PI / 180;
2993
+ const previous = state.yaw ?? 0;
2994
+ const heading = (rotation[1] + previous + turn * .5) * radians;
2995
+ const yaw = (previous + turn) % 360;
2996
+ const x = (state.x ?? 0) - Math.sin(heading) * distance;
2997
+ const z = (state.z ?? 0) - Math.cos(heading) * distance;
2998
+ const travel = tracks.map((track, i) => (state.travel?.[i] ?? 0) + distance + turn * radians * track[1]);
2999
+ return { translation: [x, 0, z], rotation: [0, yaw, 0],
3000
+ childTrackTravel: Object.fromEntries(tracks.map((track, i) => [track[0], travel[i]])),
3001
+ state: { speed, yaw, x, z, travel } };
3002
+ }`;
3003
+ }
3004
+ function bindTrackedDrive(ids, lateralOffsets) {
3005
+ return { ...trackedDrive, source: trackedDriveSource(ids.map((id, i2) => [id, lateralOffsets[i2]])) };
3006
+ }
3007
+ function isBuiltInTrackedDriveSource(source) {
3008
+ const bindings = /^ const tracks = (\[.*\]);$/m.exec(source);
3009
+ if (!bindings) return false;
3010
+ try {
3011
+ const tracks = JSON.parse(bindings[1]);
3012
+ return Array.isArray(tracks) && tracks.every((track) => Array.isArray(track) && track.length === 2 && typeof track[0] === "string" && Number.isFinite(track[1])) && trackedDriveSource(tracks) === source;
3013
+ } catch {
3014
+ return false;
3015
+ }
3016
+ }
3017
+ var stackWheelScript, text, scalar, scriptFields, vehicleScript, trackedDrive, turretControl, trackBelt, builtinComponents;
3018
+ var init_scripts = __esm({
3019
+ "packages/core/src/scripts.ts"() {
3020
+ "use strict";
3021
+ stackWheelScript = {
3022
+ name: "Sprite Stack Wheel",
3023
+ enabled: true,
3024
+ fields: [
3025
+ { name: "rollScale", label: "Roll multiplier", value: 1, min: -4, max: 4, step: 0.1 },
3026
+ { name: "steeringScale", label: "Steering multiplier", value: 1, min: -4, max: 4, step: 0.1 }
3027
+ ],
3028
+ source: `function update({ fields }) {
3029
+ return { stackWheel: { rollScale: fields.rollScale, steeringScale: fields.steeringScale } };
3030
+ }`
3031
+ };
3032
+ text = { type: "string" };
3033
+ scalar = { type: "number", minimum: -1e5, maximum: 1e5 };
3034
+ scriptFields = {
3035
+ name: text,
3036
+ label: text,
3037
+ value: scalar,
3038
+ min: scalar,
3039
+ max: scalar,
3040
+ step: { type: "number", minimum: 1e-4, maximum: 1e5 }
3041
+ };
3042
+ vehicleScript = {
3043
+ name: "WASD Vehicle",
3044
+ enabled: true,
3045
+ fields: [
3046
+ { name: "forwardSpeed", label: "Forward speed", value: 1.25, min: 0, max: 8, step: 0.05 },
3047
+ { name: "reverseSpeed", label: "Reverse speed", value: 0.65, min: 0, max: 5, step: 0.05 },
3048
+ { name: "acceleration", label: "Acceleration", value: 2.8, min: 0.1, max: 15, step: 0.1 },
3049
+ { name: "steeringAngle", label: "Steering angle (\xB0)", value: 32, min: 0, max: 65, step: 1 },
3050
+ { name: "wheelbase", label: "Wheelbase", value: 0.73, min: 0.05, max: 10, step: 0.01 },
3051
+ { name: "wheelRadius", label: "Wheel radius", value: 0.16, min: 0.01, max: 5, step: 0.01 }
3052
+ ],
3053
+ source: vehicleSource()
3054
+ };
3055
+ trackedDrive = {
3056
+ name: "Tracked Drive",
3057
+ enabled: true,
3058
+ fields: [
3059
+ { name: "forwardSpeed", label: "Forward speed", value: 0.74, min: 0, max: 3, step: 0.01 },
3060
+ { name: "reverseSpeed", label: "Reverse speed", value: 0.39, min: 0, max: 2, step: 0.01 },
3061
+ { name: "turnRate", label: "Hull turn (\xB0/s)", value: 83, min: 0, max: 180, step: 1 },
3062
+ { name: "response", label: "Throttle response", value: 9, min: 0.1, max: 24, step: 0.1 }
3063
+ ],
3064
+ source: trackedDriveSource([])
3065
+ };
3066
+ turretControl = {
3067
+ name: "Turret Control",
3068
+ enabled: true,
3069
+ fields: [{ name: "turnRate", label: "Turret turn (\xB0/s)", value: 85, min: 0, max: 180, step: 1 }],
3070
+ source: `function update({ dt, keys, fields, state }) {
3071
+ const input = Number(keys.includes('KeyQ')) - Number(keys.includes('KeyE'));
3072
+ const yaw = ((state.yaw ?? 0) + input * fields.turnRate * dt) % 360;
3073
+ return { rotation: [0, yaw, 0], state: { yaw } };
3074
+ }`
3075
+ };
3076
+ trackBelt = {
3077
+ name: "Track Belt",
3078
+ enabled: true,
3079
+ fields: [{ name: "travelScale", label: "Belt travel multiplier", value: 1, min: -4, max: 4, step: 0.1 }],
3080
+ source: `function update({ fields }) {
3081
+ return { trackBelt: fields.travelScale };
3082
+ }`
3083
+ };
3084
+ builtinComponents = {
3085
+ "wasd-vehicle": { description: "Drive a vehicle with WASD or arrow keys and send roll and steering to its wheels.", script: vehicleScript },
3086
+ "sprite-stack-wheel": { description: "Resample a rolling wheel stack and apply steering around the hub.", script: stackWheelScript },
3087
+ "tracked-drive": { description: "Drive a tracked vehicle with WASD. The tank preset binds the two tread travel outputs.", script: trackedDrive },
3088
+ "turret-control": { description: "Turn the selected turret pivot independently with Q and E.", script: turretControl },
3089
+ "track-belt": { description: "Animate tread texture around a Sprite stack belt using travel from its parent.", script: trackBelt }
3090
+ };
3091
+ }
3092
+ });
3093
+
3094
+ // packages/core/src/project.ts
3095
+ function object(value) {
3096
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Expected an object.");
3097
+ return value;
3098
+ }
3099
+ function validateFields(value, fields) {
3100
+ for (const [key, item] of Object.entries(value)) {
3101
+ if (!Object.hasOwn(fields, key)) throw new Error("Unknown field: " + key);
3102
+ const rule = fields[key];
3103
+ if (rule.nullable && item === null) continue;
3104
+ if (rule.type === "object") {
3105
+ validateFields(object(item), rule.fields);
3106
+ continue;
3107
+ }
3108
+ if (rule.type === "list") {
3109
+ if (!Array.isArray(item) || item.length > rule.maximum) throw new Error("Invalid list for " + key);
3110
+ for (const entry of item) {
3111
+ const record = object(entry);
3112
+ if (Object.keys(rule.fields).some((field) => !Object.hasOwn(record, field))) throw new Error("Incomplete script field.");
3113
+ validateFields(record, rule.fields);
3114
+ }
3115
+ continue;
3116
+ }
3117
+ if (rule.type === "array") {
3118
+ if (!Array.isArray(item) || item.length !== 3 || item.some((n) => !Number.isFinite(n) || n < rule.minimum || n > rule.maximum)) {
3119
+ throw new Error(key + " needs three numbers in range.");
3120
+ }
3121
+ } else if (rule.type === "number" || rule.type === "integer") {
3122
+ if (typeof item !== "number" || !Number.isFinite(item) || item < rule.minimum || item > rule.maximum || rule.type === "integer" && !Number.isInteger(item)) throw new Error(key + " is out of range.");
3123
+ } else if (typeof item !== rule.type || rule.enum && !rule.enum.includes(item)) {
3124
+ throw new Error("Invalid value for " + key);
3125
+ }
3126
+ }
3127
+ }
3128
+ function identifier(id) {
3129
+ if (typeof id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,95}$/.test(id)) throw new Error("Invalid ID.");
3130
+ return id;
3131
+ }
3132
+ function nameOf(name) {
3133
+ if (typeof name !== "string" || !name.trim() || name.length > 200) throw new Error("Name must contain 1\u2013200 characters.");
3134
+ return name.trim();
3135
+ }
3136
+ function newProject(name) {
3137
+ return {
3138
+ version: 1,
3139
+ revision: 0,
3140
+ name: nameOf(name),
3141
+ atlases: [],
3142
+ nodes: [],
3143
+ view: { backend: "gpu", grid: true, supersampling: false, squash: 0.65, scale: 1, yaw: 45, selected: null, frame: 0 },
3144
+ play: { time: 0, startedAt: null }
3145
+ };
3146
+ }
3147
+ function summarizeProject(project) {
3148
+ return { ...project, atlases: project.atlases.map(({ id, name, layout }) => ({ id, name, layout })) };
3149
+ }
3150
+ function playTime(play, now = Date.now()) {
3151
+ return play.time + (play.startedAt === null ? 0 : Math.max(0, (now - play.startedAt) / 1e3));
3152
+ }
3153
+ function assertAtlas(png2, layout) {
3154
+ parseLayout(layout);
3155
+ if (png2.length > 22e6 || png2.length % 4 || !/^[A-Za-z0-9+/]+={0,2}$/.test(png2)) throw new Error("Expected an embedded PNG of 16 MB or less.");
3156
+ readPngSize(Uint8Array.from(atob(png2.slice(0, 44)), (char) => char.charCodeAt(0)));
3157
+ }
3158
+ function applyProjectActions(project, input, now = Date.now()) {
3159
+ if (!Array.isArray(input) || !input.length || input.length > 500) throw new Error("Provide a batch of 1\u2013500 project actions.");
3160
+ const next = {
3161
+ ...project,
3162
+ nodes: structuredClone(project.nodes),
3163
+ atlases: [...project.atlases],
3164
+ view: { ...project.view },
3165
+ play: structuredClone(project.play)
3166
+ };
3167
+ const node = (id) => {
3168
+ const found = next.nodes.find((item) => item.id === identifier(id));
3169
+ if (!found) throw new Error("Unknown node: " + id);
3170
+ return found;
3171
+ };
3172
+ const atlas = (id) => {
3173
+ const found = next.atlases.find((item) => item.id === identifier(id));
3174
+ if (!found) throw new Error("Unknown atlas: " + id);
3175
+ return found;
3176
+ };
3177
+ for (const item of input) {
3178
+ const { action, ...params } = object(item);
3179
+ if (typeof action !== "string" || !Object.hasOwn(projectActions, action)) throw new Error("Unknown action: " + action);
3180
+ const spec = projectActions[action];
3181
+ for (const field of spec.required) if (!Object.hasOwn(params, field)) throw new Error("Missing field: " + field);
3182
+ validateFields(params, spec.fields);
3183
+ switch (action) {
3184
+ case "atlas.embed": {
3185
+ const id = identifier(params.id), name = nameOf(params.name), layout = params.layout, png2 = params.png;
3186
+ assertAtlas(png2, layout);
3187
+ const existing = next.atlases.find((item2) => item2.id === id);
3188
+ if (existing && (existing.png !== png2 || existing.layout !== layout)) throw new Error("Atlas ID already exists: " + id);
3189
+ if (!existing) next.atlases.push({ id, name, layout, png: png2 });
3190
+ break;
3191
+ }
3192
+ case "atlas.remove": {
3193
+ const source = atlas(params.id);
3194
+ if (next.nodes.some((item2) => item2.atlasId === source.id)) throw new Error("Atlas is still in use.");
3195
+ next.atlases = next.atlases.filter((item2) => item2 !== source);
3196
+ break;
3197
+ }
3198
+ case "node.add": {
3199
+ const id = identifier(params.id);
3200
+ if (next.nodes.some((item2) => item2.id === id)) throw new Error("Node ID already exists: " + id);
3201
+ const parentId = params.parentId ? node(params.parentId).id : null;
3202
+ const atlasId = params.atlasId ? atlas(params.atlasId).id : null;
3203
+ const siblings = next.nodes.filter((item2) => item2.parentId === parentId && item2.atlasId);
3204
+ next.nodes.push({
3205
+ id,
3206
+ name: nameOf(params.name),
3207
+ parentId,
3208
+ atlasId,
3209
+ visible: true,
3210
+ position: params.position ?? [atlasId ? siblings.length * 1.5 : 0, 0, 0],
3211
+ rotation: [0, 0, 0],
3212
+ scale: [1, 1, 1],
3213
+ velocity: [0, 0, 0],
3214
+ angularVelocity: [0, 0, 0],
3215
+ settings: { ...nodeDefaults, ...params.settings }
3216
+ });
3217
+ break;
3218
+ }
3219
+ case "node.set": {
3220
+ const current = node(params.id);
3221
+ const { settings, ...patch } = params.patch;
3222
+ if (patch.name !== void 0) patch.name = nameOf(patch.name);
3223
+ Object.assign(current, patch);
3224
+ if (settings) Object.assign(current.settings, settings);
3225
+ break;
3226
+ }
3227
+ case "node.move": {
3228
+ const current = node(params.id);
3229
+ const parent = params.parentId === null ? null : node(params.parentId);
3230
+ for (let ancestor = parent; ancestor; ancestor = ancestor.parentId === null ? null : node(ancestor.parentId)) {
3231
+ if (ancestor.id === current.id) throw new Error("A node cannot be its own ancestor.");
3232
+ }
3233
+ current.parentId = parent?.id ?? null;
3234
+ break;
3235
+ }
3236
+ case "node.remove": {
3237
+ const removed = /* @__PURE__ */ new Set([node(params.id).id]);
3238
+ do {
3239
+ const before = removed.size;
3240
+ for (const item2 of next.nodes) if (item2.parentId && removed.has(item2.parentId)) removed.add(item2.id);
3241
+ if (removed.size === before) break;
3242
+ } while (true);
3243
+ next.nodes = next.nodes.filter((item2) => !removed.has(item2.id));
3244
+ next.play.offsets = next.play.offsets?.filter((item2) => !removed.has(item2.id));
3245
+ if (next.view.selected && removed.has(next.view.selected)) next.view.selected = null;
3246
+ if (next.view.follow && removed.has(next.view.follow)) next.view.follow = null;
3247
+ break;
3248
+ }
3249
+ case "script.set": {
3250
+ const owner = node(params.nodeId);
3251
+ const id = identifier(params.id);
3252
+ const scripts = owner.scripts ??= [];
3253
+ const index = scripts.findIndex((script2) => script2.id === id);
3254
+ const previous = index >= 0 ? scripts[index] : { id, name: "", source: "", enabled: true, fields: [] };
3255
+ const script = { ...previous, ...params.patch };
3256
+ script.name = nameOf(script.name);
3257
+ validateScript(script);
3258
+ if (index >= 0) scripts[index] = script;
3259
+ else {
3260
+ if (next.nodes.reduce((count2, item2) => count2 + (item2.scripts?.length ?? 0), 0) >= 16) {
3261
+ throw new Error("A scene supports up to 16 script components.");
3262
+ }
3263
+ scripts.push(script);
3264
+ }
3265
+ break;
3266
+ }
3267
+ case "script.remove": {
3268
+ const owner = node(params.nodeId);
3269
+ const id = identifier(params.id);
3270
+ if (!owner.scripts?.some((script) => script.id === id)) throw new Error("Unknown script: " + id);
3271
+ owner.scripts = owner.scripts.filter((script) => script.id !== id);
3272
+ break;
3273
+ }
3274
+ case "view.set": {
3275
+ const patch = params.patch;
3276
+ if (patch.selected !== void 0 && patch.selected !== null) node(patch.selected);
3277
+ if (patch.follow) node(patch.follow);
3278
+ Object.assign(next.view, patch);
3279
+ break;
3280
+ }
3281
+ case "view.frame":
3282
+ next.view.frame++;
3283
+ break;
3284
+ case "play.start":
3285
+ next.play.startedAt ??= now;
3286
+ break;
3287
+ case "play.pause":
3288
+ next.play = { ...next.play, time: playTime(next.play, now), startedAt: null };
3289
+ break;
3290
+ case "play.reset":
3291
+ next.play = { time: 0, startedAt: null, resetCount: (next.play.resetCount ?? 0) + 1 };
3292
+ break;
3293
+ case "play.step":
3294
+ next.play = { ...next.play, time: playTime(next.play, now) + params.seconds, startedAt: null };
3295
+ break;
3296
+ case "play.nudge": {
3297
+ const id = node(params.id).id;
3298
+ if (!params.translation && !params.rotation) throw new Error("Provide translation or rotation.");
3299
+ const offsets = next.play.offsets ??= [];
3300
+ let offset = offsets.find((item2) => item2.id === id);
3301
+ if (!offset) {
3302
+ offset = { id, translation: [0, 0, 0], rotation: [0, 0, 0] };
3303
+ offsets.push(offset);
3304
+ }
3305
+ for (const field of ["translation", "rotation"]) {
3306
+ const delta = params[field];
3307
+ if (delta) for (let axis = 0; axis < 3; axis++) offset[field][axis] += delta[axis];
3308
+ }
3309
+ break;
3310
+ }
3311
+ }
3312
+ }
3313
+ next.revision++;
3314
+ return next;
3315
+ }
3316
+ var nodeDefaults, number2, choice, string, boolean, idOrNull, vector, settingsFields, nodeFields, viewFields, projectActions;
3317
+ var init_project = __esm({
3318
+ "packages/core/src/project.ts"() {
3319
+ "use strict";
3320
+ init_views();
3321
+ init_scripts();
3322
+ nodeDefaults = {
3323
+ format: "stack",
3324
+ layers: 48,
3325
+ resolution: 96,
3326
+ spacing: 1,
3327
+ height: 1,
3328
+ threshold: 238,
3329
+ pivot: "ground",
3330
+ profile: "silhouette",
3331
+ pixelArt: false,
3332
+ smoothEdges: true,
3333
+ lighting: false
3334
+ };
3335
+ number2 = (minimum, maximum, type = "number") => ({ type, minimum, maximum });
3336
+ choice = (...values) => ({ type: "string", enum: values });
3337
+ string = { type: "string" };
3338
+ boolean = { type: "boolean" };
3339
+ idOrNull = { type: "string", nullable: true };
3340
+ vector = (...limits) => ({ ...number2(...limits), type: "array" });
3341
+ settingsFields = {
3342
+ textureProjection: choice("auto", "top-contour"),
3343
+ meshMethod: choice("marching-cubes", "contour"),
3344
+ contourHub: boolean,
3345
+ format: choice("stack", "glb"),
3346
+ layers: number2(8, 128, "integer"),
3347
+ resolution: number2(16, 192, "integer"),
3348
+ spacing: number2(0.05, 20),
3349
+ height: number2(0.01, 100),
3350
+ threshold: number2(0, 255, "integer"),
3351
+ pivot: choice("ground", "center"),
3352
+ profile: choice("silhouette", "round", "round-base"),
3353
+ pixelArt: boolean,
3354
+ smoothEdges: boolean,
3355
+ lighting: boolean
3356
+ };
3357
+ nodeFields = {
3358
+ name: string,
3359
+ visible: boolean,
3360
+ position: vector(-1e4, 1e4),
3361
+ rotation: vector(-360, 360),
3362
+ scale: vector(0.01, 100),
3363
+ velocity: vector(-100, 100),
3364
+ angularVelocity: vector(-720, 720),
3365
+ settings: { type: "object", fields: settingsFields }
3366
+ };
3367
+ viewFields = {
3368
+ backend: choice("cpu", "gpu"),
3369
+ grid: boolean,
3370
+ supersampling: boolean,
3371
+ squash: number2(0.2, 1),
3372
+ detailNormals: boolean,
3373
+ subpixelAA: boolean,
3374
+ specularAA: boolean,
3375
+ scale: number2(0.1, 10),
3376
+ yaw: number2(-360, 360),
3377
+ selected: idOrNull,
3378
+ follow: idOrNull
3379
+ };
3380
+ projectActions = {
3381
+ "atlas.embed": {
3382
+ description: "Embed a four- or six-view PNG in the project asset library.",
3383
+ required: ["id", "name", "layout", "png"],
3384
+ fields: { id: string, name: string, layout: string, png: string }
3385
+ },
3386
+ "atlas.remove": { description: "Remove an unreferenced atlas from the library.", required: ["id"], fields: { id: string } },
3387
+ "node.add": {
3388
+ description: "Create a group or an instance of an embedded atlas, with an optional parent.",
3389
+ required: ["id", "name"],
3390
+ fields: { id: string, name: string, parentId: idOrNull, atlasId: idOrNull, position: nodeFields.position, settings: nodeFields.settings }
3391
+ },
3392
+ "node.set": {
3393
+ description: "Change a node\u2019s display, transform, animation, or reconstruction settings.",
3394
+ required: ["id", "patch"],
3395
+ fields: { id: string, patch: { type: "object", fields: nodeFields } }
3396
+ },
3397
+ "node.move": { description: "Set a node\u2019s parent. Null moves it to the root.", required: ["id", "parentId"], fields: { id: string, parentId: idOrNull } },
3398
+ "node.remove": { description: "Remove a node and its descendants. Embedded atlas data remains in the library.", required: ["id"], fields: { id: string } },
3399
+ "script.set": {
3400
+ description: "Attach or update an isolated JavaScript component on a node. A new component requires name and source.",
3401
+ required: ["nodeId", "id", "patch"],
3402
+ fields: { nodeId: string, id: string, patch: { type: "object", fields: {
3403
+ name: string,
3404
+ source: string,
3405
+ enabled: boolean,
3406
+ fields: { type: "list", maximum: 24, fields: scriptFields }
3407
+ } } }
3408
+ },
3409
+ "script.remove": { description: "Detach a component from its node.", required: ["nodeId", "id"], fields: { nodeId: string, id: string } },
3410
+ "view.set": { description: "Change view options or select an object.", required: ["patch"], fields: { patch: { type: "object", fields: viewFields } } },
3411
+ "view.frame": { description: "Frame the visible scene in the viewport.", required: [], fields: {} },
3412
+ "play.start": { description: "Start or resume time-based motion.", required: [], fields: {} },
3413
+ "play.pause": { description: "Pause while retaining the current simulation time.", required: [], fields: {} },
3414
+ "play.reset": { description: "Pause and reset simulation time to zero.", required: [], fields: {} },
3415
+ "play.step": { description: "Pause and advance by a fixed number of seconds.", required: ["seconds"], fields: { seconds: number2(0, 3600) } },
3416
+ "play.nudge": {
3417
+ description: "Move or rotate a node in the Playground without changing its authored transform.",
3418
+ required: ["id"],
3419
+ fields: { id: string, translation: vector(-100, 100), rotation: vector(-360, 360) }
3420
+ }
3421
+ };
3422
+ }
3423
+ });
3424
+
3425
+ // packages/core/src/project-preset.ts
3426
+ function resolveWheels(project, root, explicit) {
3427
+ const atlases = new Set(project.atlases.map((atlas) => atlas.id));
3428
+ const children = project.nodes.filter((node) => node.parentId === root.id && node.atlasId && atlases.has(node.atlasId));
3429
+ if (explicit !== void 0) {
3430
+ const ids = explicit.split(",").map((id) => id.trim());
3431
+ if (ids.length !== 4 || new Set(ids).size !== 4 || ids.some((id) => !id)) {
3432
+ throw new Error("--wheels requires four distinct node IDs in front-left, front-right, rear-left, rear-right order.");
3433
+ }
3434
+ return ids.map((id) => {
3435
+ const node = children.find((child) => child.id === id);
3436
+ if (!node) throw new Error("Wheel must be an atlas-backed direct child of " + root.id + ": " + id);
3437
+ return node;
3438
+ });
3439
+ }
3440
+ const named = children.filter((node) => /wheel|tire|tyre|바퀴|타이어/i.test(node.name + " " + node.id));
3441
+ const byAtlas = /* @__PURE__ */ new Map();
3442
+ for (const child of children) {
3443
+ const group = byAtlas.get(child.atlasId) ?? [];
3444
+ group.push(child);
3445
+ byAtlas.set(child.atlasId, group);
3446
+ }
3447
+ const matched = [...byAtlas.values()].filter((group) => group.length === 4 && named.every((wheel) => group.includes(wheel)));
3448
+ const candidates = named.length === 4 ? named : children.length === 4 ? children : matched.length === 1 ? matched[0] : null;
3449
+ if (!candidates) throw new Error("Cannot identify four wheels under " + root.id + ". Supply --wheels <front-left,front-right,rear-left,rear-right>.");
3450
+ const ordered = [...candidates].sort((a, b) => a.position[2] - b.position[2]);
3451
+ const bySide = (a, b) => a.position[0] - b.position[0];
3452
+ return [...ordered.slice(0, 2).sort(bySide), ...ordered.slice(2).sort(bySide)];
3453
+ }
3454
+ function addComponent(actions, node, id, script) {
3455
+ const matches = (node.scripts ?? []).filter((entry) => entry.id === id || entry.name === script.name || (id === "wasd-vehicle" ? isBuiltInVehicleSource(entry.source) : entry.source === script.source));
3456
+ if (matches.length > 1) throw new Error("Multiple " + script.name + " components on node " + node.id + ".");
3457
+ const existing = matches[0];
3458
+ if (!existing) {
3459
+ actions.push({ action: "script.set", nodeId: node.id, id, patch: script });
3460
+ return id;
3461
+ }
3462
+ if (existing.source !== script.source) {
3463
+ const canRebind = id === "wasd-vehicle" && isBuiltInVehicleSource(existing.source) || id === "tracked-drive" && isBuiltInTrackedDriveSource(existing.source);
3464
+ if (!canRebind) {
3465
+ throw new Error("Cannot replace customized " + script.name + " source on node " + node.id + ".");
3466
+ }
3467
+ actions.push({ action: "script.set", nodeId: node.id, id: existing.id, patch: { source: script.source } });
3468
+ }
3469
+ return existing.id;
3470
+ }
3471
+ function fourWheelPreset(project, rootId, explicit) {
3472
+ const root = project.nodes.find((node) => node.id === rootId);
3473
+ if (!root) throw new Error("Unknown vehicle root: " + rootId);
3474
+ const wheels = resolveWheels(project, root, explicit);
3475
+ const [fl2, fr, rl, rr] = wheels;
3476
+ if (Math.max(fl2.position[2], fr.position[2]) >= Math.min(rl.position[2], rr.position[2]) || Math.max(fl2.position[0], rl.position[0]) >= Math.min(fr.position[0], rr.position[0])) {
3477
+ throw new Error("Wheel positions must form two axles facing local \u2212Z, with left wheels at smaller local X.");
3478
+ }
3479
+ const wheelbase = (rl.position[2] + rr.position[2] - (fl2.position[2] + fr.position[2])) / 2 * root.scale[2];
3480
+ const wheelRadius = wheels.reduce((total, wheel) => {
3481
+ const { format, height, spacing } = wheel.settings;
3482
+ return total + height * wheel.scale[1] * (format === "stack" ? spacing : 1) / 2;
3483
+ }, 0) / 4 * root.scale[1];
3484
+ if (![wheelbase, wheelRadius].every((value) => value > 0 && value <= 1e5)) {
3485
+ throw new Error("Vehicle wheelbase and radius must be positive and at most 100000 scene units.");
3486
+ }
3487
+ const actions = [];
3488
+ const driver = addComponent(actions, root, "wasd-vehicle", bindVehicleWheels(wheels.map((wheel) => wheel.id), wheelbase, wheelRadius));
3489
+ const placements = wheels.map((wheel, i2) => ({
3490
+ role: ["front-left", "front-right", "rear-left", "rear-right"][i2],
3491
+ node: wheel.id,
3492
+ component: addComponent(actions, wheel, "sprite-stack-wheel", builtinComponents["sprite-stack-wheel"].script)
3493
+ }));
3494
+ return { actions, root: root.id, component: driver, wheels: placements };
3495
+ }
3496
+ function trackedTankPreset(project, rootId) {
3497
+ const root = project.nodes.find((node) => node.id === rootId);
3498
+ if (!root) throw new Error("Unknown tank root: " + rootId);
3499
+ const children = project.nodes.filter((node) => node.parentId === root.id);
3500
+ const atlasById = new Map(project.atlases.map((atlas2) => [atlas2.id, atlas2]));
3501
+ const atlas = (node) => node.atlasId ? atlasById.get(node.atlasId) : void 0;
3502
+ const tracks = children.filter((node) => {
3503
+ const source = atlas(node);
3504
+ return source && /track|tread|트랙|궤도/i.test([node.name, node.id, source.name].join(" "));
3505
+ }).sort((a, b) => a.position[0] - b.position[0]);
3506
+ if (tracks.length !== 2 || tracks[0].position[0] >= 0 || tracks[1].position[0] <= 0) {
3507
+ throw new Error("Provide two atlas-backed track children with track or tread in their names, one on each side of the root.");
3508
+ }
3509
+ const turrets = children.filter((node) => {
3510
+ const source = atlas(node);
3511
+ if (/turret|포탑/i.test([node.name, node.id, source?.name].join(" "))) {
3512
+ return source || project.nodes.some((child) => child.parentId === node.id && atlas(child));
3513
+ }
3514
+ return false;
3515
+ });
3516
+ if (turrets.length !== 1) throw new Error("Provide one turret child or a named turret pivot with an atlas-backed child.");
3517
+ const actions = [];
3518
+ const component = addComponent(actions, root, "tracked-drive", bindTrackedDrive(
3519
+ tracks.map((track) => track.id),
3520
+ tracks.map((track) => track.position[0] * root.scale[0])
3521
+ ));
3522
+ const turretComponent = addComponent(actions, turrets[0], "turret-control", builtinComponents["turret-control"].script);
3523
+ const placements = tracks.map((track, i2) => {
3524
+ if (track.settings.format !== "stack") {
3525
+ throw new Error(track.name + " must use Sprite stack to animate its belt.");
3526
+ }
3527
+ return {
3528
+ role: i2 === 0 ? "left" : "right",
3529
+ node: track.id,
3530
+ component: addComponent(actions, track, "track-belt", builtinComponents["track-belt"].script)
3531
+ };
3532
+ });
3533
+ return { actions, root: root.id, component, turret: { node: turrets[0].id, component: turretComponent }, tracks: placements };
3534
+ }
3535
+ var init_project_preset = __esm({
3536
+ "packages/core/src/project-preset.ts"() {
3537
+ "use strict";
3538
+ init_scripts();
3539
+ }
3540
+ });
3541
+
3542
+ // packages/core/src/depth-png.ts
3543
+ var init_depth_png = __esm({
3544
+ "packages/core/src/depth-png.ts"() {
3545
+ "use strict";
3546
+ init_views();
3547
+ }
3548
+ });
3549
+
3550
+ // packages/core/src/depth-fit.ts
3551
+ var init_depth_fit = __esm({
3552
+ "packages/core/src/depth-fit.ts"() {
3553
+ "use strict";
3554
+ init_depth_png();
3555
+ }
3556
+ });
3557
+
3558
+ // packages/core/src/mapped-atlas.ts
3559
+ var init_mapped_atlas = __esm({
3560
+ "packages/core/src/mapped-atlas.ts"() {
3561
+ "use strict";
3562
+ init_depth_png();
3563
+ init_depth_fit();
3564
+ init_surface();
3565
+ }
3566
+ });
3567
+
3568
+ // packages/core/src/index.ts
3569
+ var init_src = __esm({
3570
+ "packages/core/src/index.ts"() {
3571
+ "use strict";
3572
+ init_views();
3573
+ init_reconstruct();
3574
+ init_export();
3575
+ init_project();
3576
+ init_scripts();
3577
+ init_project_preset();
3578
+ init_depth_png();
3579
+ init_mapped_atlas();
3580
+ init_texture_projection();
3581
+ }
3582
+ });
3583
+
3584
+ // apps/cli/src/project-store.ts
3585
+ import { randomUUID as randomUUID2 } from "node:crypto";
3586
+ import { mkdir as mkdir2, open, readFile as readFile2, rename as rename2, stat as stat2, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
3587
+ import { dirname } from "node:path";
3588
+ import { setTimeout as setTimeout2 } from "node:timers/promises";
3589
+ async function readProject(file) {
3590
+ const data = JSON.parse(await readFile2(file, "utf8"));
3591
+ if (data.version !== 1 || !Number.isInteger(data.revision) || !Array.isArray(data.nodes) || !Array.isArray(data.atlases) || !data.view || !data.play) throw new Error("Expected a version 1 stack3 scene project.");
3592
+ return data;
3593
+ }
3594
+ async function initProject(file, name) {
3595
+ await mkdir2(dirname(file), { recursive: true });
3596
+ const project = newProject(name);
3597
+ await writeFile2(file, JSON.stringify(project) + "\n", { flag: "wx", mode: 384 });
3598
+ return project;
3599
+ }
3600
+ async function editProject(file, actions, expected) {
3601
+ const lock = file + ".lock";
3602
+ const deadline = Date.now() + 5e3;
3603
+ let handle;
3604
+ while (!handle) {
3605
+ try {
3606
+ handle = await open(lock, "wx", 384);
3607
+ } catch (error) {
3608
+ if (error.code !== "EEXIST") throw error;
3609
+ if (Date.now() > deadline) throw new Error("The project is locked by another editor: " + lock);
3610
+ await setTimeout2(35);
3611
+ }
3612
+ }
3613
+ const temporary = file + "." + randomUUID2() + ".tmp";
3614
+ try {
3615
+ const project = await readProject(file);
3616
+ if (expected !== void 0 && project.revision !== expected) throw new RevisionConflict("Project revision changed.");
3617
+ const next = applyProjectActions(project, actions);
3618
+ await writeFile2(temporary, JSON.stringify(next) + "\n", { flag: "wx", mode: 384 });
3619
+ await rename2(temporary, file);
3620
+ return next;
3621
+ } finally {
3622
+ await handle.close();
3623
+ await unlink2(lock);
3624
+ await unlink2(temporary).catch(() => {
3625
+ });
3626
+ }
3627
+ }
3628
+ function projectReader(file) {
3629
+ let previous;
3630
+ return async () => {
3631
+ const stats = await stat2(file, { bigint: true });
3632
+ const signature = [stats.ino, stats.mtimeNs, stats.size].join(":");
3633
+ if (previous?.signature !== signature) previous = { signature, value: await readProject(file) };
3634
+ return previous.value;
3635
+ };
3636
+ }
3637
+ var RevisionConflict;
3638
+ var init_project_store = __esm({
3639
+ "apps/cli/src/project-store.ts"() {
3640
+ "use strict";
3641
+ init_src();
3642
+ RevisionConflict = class extends Error {
3643
+ };
3644
+ }
3645
+ });
3646
+
3647
+ // apps/cli/src/preview-server.ts
3648
+ import { existsSync } from "node:fs";
3649
+ import { fileURLToPath } from "node:url";
3650
+ import { createServer, preview } from "vite";
3651
+ async function serveViewer(page, open2, middleware) {
3652
+ const server = { host: "127.0.0.1", port: 0, cors: false, open: open2 ? page : false };
3653
+ const packagedRoot = fileURLToPath(new URL("../viewer/", import.meta.url));
3654
+ if (existsSync(new URL("../viewer/dist/index.html", import.meta.url))) {
3655
+ const built = await preview({
3656
+ root: packagedRoot,
3657
+ configFile: false,
3658
+ preview: server,
3659
+ plugins: [{
3660
+ name: "stack3-cli-preview",
3661
+ configurePreviewServer(server2) {
3662
+ server2.middlewares.use(middleware);
3663
+ }
3664
+ }]
3665
+ });
3666
+ return new URL(page, built.resolvedUrls.local[0]);
3667
+ }
3668
+ const dev = await createServer({
3669
+ root: fileURLToPath(new URL("../../viewer/", import.meta.url)),
3670
+ server,
3671
+ plugins: [{
3672
+ name: "stack3-cli-preview",
3673
+ configureServer(server2) {
3674
+ server2.middlewares.use(middleware);
3675
+ }
3676
+ }]
3677
+ });
3678
+ await dev.listen();
3679
+ return new URL(page, dev.resolvedUrls.local[0]);
3680
+ }
3681
+ var init_preview_server = __esm({
3682
+ "apps/cli/src/preview-server.ts"() {
3683
+ "use strict";
3684
+ }
3685
+ });
3686
+
3687
+ // apps/cli/src/project-server.ts
3688
+ var project_server_exports = {};
3689
+ __export(project_server_exports, {
3690
+ openProject: () => openProject
3691
+ });
3692
+ import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
3693
+ async function body(request) {
3694
+ const chunks = [];
3695
+ let size = 0;
3696
+ for await (const data of request) {
3697
+ const chunk = Buffer.from(data);
3698
+ size += chunk.length;
3699
+ if (size > limit) throw new Error("Request exceeds the project editor upload limit.");
3700
+ chunks.push(chunk);
3701
+ }
3702
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
3703
+ }
3704
+ function json(response, value, status = 200) {
3705
+ response.writeHead(status, { "Content-Type": "application/json", "Cache-Control": "no-store" });
3706
+ response.end(JSON.stringify(value));
3707
+ }
3708
+ function browserSummary(project) {
3709
+ const summary = summarizeProject(project);
3710
+ for (const [index, item] of summary.atlases.entries()) {
3711
+ item.fingerprint = fingerprint(project.atlases[index].png);
3712
+ }
3713
+ return summary;
3714
+ }
3715
+ async function openProject(file, open2, playground) {
3716
+ const read = projectReader(file);
3717
+ await read();
3718
+ const token = randomUUID3();
3719
+ const prefix = "/__stack3_project/" + token;
3720
+ const page = "/project.html?session=" + token + (playground ? "&playground=1" : "");
3721
+ const address = await serveViewer(page, open2, async (request, response, next) => {
3722
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
3723
+ if (!url.pathname.startsWith(prefix + "/")) return next();
3724
+ const route = url.pathname.slice(prefix.length + 1);
3725
+ try {
3726
+ if (request.method === "GET" && route === "state") {
3727
+ const project = await read();
3728
+ if (url.searchParams.get("after") === String(project.revision)) {
3729
+ response.writeHead(204).end();
3730
+ return;
3731
+ }
3732
+ json(response, browserSummary(project));
3733
+ return;
3734
+ }
3735
+ if (request.method === "GET" && route.startsWith("atlas/")) {
3736
+ const id = route.slice(6);
3737
+ const embedded = (await read()).atlases.find((item) => item.id === id);
3738
+ if (!embedded) {
3739
+ json(response, { error: "Atlas not found." }, 404);
3740
+ return;
3741
+ }
3742
+ const expected = url.searchParams.get("fingerprint");
3743
+ if (expected && expected !== fingerprint(embedded.png)) {
3744
+ json(response, { error: "Atlas changed." }, 409);
3745
+ return;
3746
+ }
3747
+ const bytes = Buffer.from(embedded.png, "base64");
3748
+ response.writeHead(200, { "Content-Type": "image/png", "Cache-Control": "no-store", "Content-Length": bytes.length });
3749
+ response.end(bytes);
3750
+ return;
3751
+ }
3752
+ if (request.method === "POST" && route === "actions") {
3753
+ if (!request.headers["content-type"]?.startsWith("application/json") || request.headers.origin && request.headers.origin !== "http://" + request.headers.host) {
3754
+ json(response, { error: "Expected same-origin JSON." }, 403);
3755
+ return;
3756
+ }
3757
+ const { actions, revision } = await body(request);
3758
+ if (!Number.isInteger(revision)) throw new Error("Expected a numeric project revision.");
3759
+ json(response, browserSummary(await editProject(file, actions, revision)));
3760
+ return;
3761
+ }
3762
+ json(response, { error: "Unknown project route." }, 404);
3763
+ } catch (error) {
3764
+ json(response, { error: error.message }, error instanceof RevisionConflict ? 409 : 400);
3765
+ }
3766
+ });
3767
+ console.log(JSON.stringify({ file, url: address.href, mode: playground ? "playground" : "editor" }));
3768
+ }
3769
+ var limit, fingerprint;
3770
+ var init_project_server = __esm({
3771
+ "apps/cli/src/project-server.ts"() {
3772
+ "use strict";
3773
+ init_preview_server();
3774
+ init_src();
3775
+ init_project_store();
3776
+ limit = 80 * 1024 * 1024;
3777
+ fingerprint = (png2) => createHash2("sha256").update(png2).digest("hex");
3778
+ }
3779
+ });
3780
+
3781
+ // apps/cli/src/project-command.ts
3782
+ var project_command_exports = {};
3783
+ __export(project_command_exports, {
3784
+ projectCommand: () => projectCommand
3785
+ });
3786
+ import { createHash as createHash3, randomUUID as randomUUID4 } from "node:crypto";
3787
+ import { readFile as readFile3, writeFile as writeFile3, mkdir as mkdir3 } from "node:fs/promises";
3788
+ import { basename, dirname as dirname2, extname, join as join2, resolve as resolve2 } from "node:path";
3789
+ import { parseArgs } from "node:util";
3790
+ import { PNG } from "pngjs";
3791
+ async function stdin() {
3792
+ const chunks = [];
3793
+ for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
3794
+ return Buffer.concat(chunks).toString("utf8");
3795
+ }
3796
+ async function projectCommand(args) {
3797
+ const { positionals: [verb, file, ...inputs], values } = parseArgs({
3798
+ args,
3799
+ allowPositionals: true,
3800
+ options: {
3801
+ help: { type: "boolean", short: "h" },
3802
+ name: { type: "string" },
3803
+ layout: { type: "string" },
3804
+ parent: { type: "string" },
3805
+ revision: { type: "string" },
3806
+ output: { type: "string", short: "o" },
3807
+ format: { type: "string" },
3808
+ "no-open": { type: "boolean" },
3809
+ playground: { type: "boolean" },
3810
+ wheels: { type: "string" }
3811
+ }
3812
+ });
3813
+ if (!verb || values.help) {
3814
+ console.log(help);
3815
+ return;
3816
+ }
3817
+ if (verb === "schema") {
3818
+ print(projectActions);
3819
+ return;
3820
+ }
3821
+ if (verb === "components") {
3822
+ if (inputs.length) throw new Error("components expects at most one component ID.");
3823
+ if (!file) {
3824
+ print(Object.entries(builtinComponents).map(([id, { description: description2, script: script2 }]) => ({ id, name: script2.name, description: description2 })));
3825
+ return;
3826
+ }
3827
+ if (!Object.hasOwn(builtinComponents, file)) throw new Error("Unknown built-in component: " + file);
3828
+ const { description, script } = builtinComponents[file];
3829
+ print({ id: file, description, ...script });
3830
+ return;
3831
+ }
3832
+ if (!file) throw new Error("Provide a project file.");
3833
+ const path = resolve2(file);
3834
+ switch (verb) {
3835
+ case "init": {
3836
+ if (inputs.length) throw new Error("init expects only a project file.");
3837
+ print(summarizeProject(await initProject(path, values.name || basename(path, extname(path)))));
3838
+ return;
3839
+ }
3840
+ case "get":
3841
+ print(summarizeProject(await readProject(path)));
3842
+ return;
3843
+ case "open": {
3844
+ const { openProject: openProject2 } = await Promise.resolve().then(() => (init_project_server(), project_server_exports));
3845
+ await openProject2(path, !values["no-open"], !!values.playground);
3846
+ return;
3847
+ }
3848
+ case "apply": {
3849
+ if (inputs.length !== 1) throw new Error("Provide a JSON action file or - for standard input.");
3850
+ const revision = values.revision === void 0 ? void 0 : Number(values.revision);
3851
+ if (revision !== void 0 && (!Number.isInteger(revision) || revision < 0)) throw new Error("Invalid project revision.");
3852
+ print(summarizeProject(await editProject(path, JSON.parse(inputs[0] === "-" ? await stdin() : await readFile3(inputs[0], "utf8")), revision)));
3853
+ return;
3854
+ }
3855
+ case "preset": {
3856
+ const [kind, rootId] = inputs;
3857
+ if (inputs.length !== 2 || kind !== "four-wheel" && kind !== "tracked-tank") {
3858
+ throw new Error("Use stack3 project preset <file> <four-wheel|tracked-tank> <root-id>.");
3859
+ }
3860
+ if (kind === "tracked-tank" && values.wheels !== void 0) throw new Error("--wheels applies to the four-wheel preset.");
3861
+ const project = await readProject(path);
3862
+ const revision = values.revision === void 0 ? project.revision : Number(values.revision);
3863
+ if (!Number.isInteger(revision) || revision < 0) throw new Error("Invalid project revision.");
3864
+ if (revision !== project.revision) throw new Error("Project revision changed.");
3865
+ const { actions, ...preset } = kind === "four-wheel" ? fourWheelPreset(project, rootId, values.wheels) : trackedTankPreset(project, rootId);
3866
+ const next = actions.length ? await editProject(path, actions, revision) : project;
3867
+ print({ preset: kind, revision: next.revision, changed: actions.length > 0, ...preset });
3868
+ return;
3869
+ }
3870
+ case "import": {
3871
+ if (!inputs.length || inputs.length > 128) throw new Error("Provide 1\u2013128 PNG atlas paths.");
3872
+ const layout = parseLayout(values.layout ?? "top,left,front,rear").join(",");
3873
+ const actions = [];
3874
+ const nodes = [];
3875
+ for (const image of inputs) {
3876
+ const bytes = await readFile3(image);
3877
+ const name = basename(image, extname(image));
3878
+ const atlasId = createHash3("sha256").update(layout).update(bytes).digest("hex");
3879
+ const id = randomUUID4();
3880
+ nodes.push(id);
3881
+ actions.push(
3882
+ { action: "atlas.embed", id: atlasId, name, layout, png: bytes.toString("base64") },
3883
+ { action: "node.add", id, name, atlasId, parentId: values.parent ?? null }
3884
+ );
3885
+ }
3886
+ actions.push({ action: "view.set", patch: { selected: nodes.at(-1) } }, { action: "view.frame" });
3887
+ const project = await editProject(path, actions);
3888
+ print({ revision: project.revision, nodes: project.nodes.filter((node) => nodes.includes(node.id)) });
3889
+ return;
3890
+ }
3891
+ case "export": {
3892
+ if (inputs.length !== 1 || !values.output) throw new Error("Provide a node ID and --output.");
3893
+ const project = await readProject(path);
3894
+ const node = project.nodes.find((item) => item.id === inputs[0]);
3895
+ const atlas = project.atlases.find((item) => item.id === node?.atlasId);
3896
+ if (!node || !atlas) throw new Error("Export requires an atlas-backed node.");
3897
+ const format = values.format ?? (extname(values.output).toLowerCase() === ".glb" ? "glb" : node.settings.format);
3898
+ if (format !== "glb" && format !== "stack") throw new Error("Use --format glb or --format stack.");
3899
+ const output = resolve2(values.output);
3900
+ if (format === "glb" && extname(output).toLowerCase() !== ".glb") throw new Error("GLB output must end in .glb.");
3901
+ const image = PNG.sync.read(Buffer.from(atlas.png, "base64"));
3902
+ const settings = node.settings;
3903
+ const asset = reconstruct(splitAtlas(image, parseLayout(atlas.layout), settings.threshold), format === "glb" ? "mesh" : "stack", settings);
3904
+ if (asset.target === "mesh") {
3905
+ await mkdir3(dirname2(output), { recursive: true });
3906
+ await writeFile3(output, encodeGlb(asset));
3907
+ } else {
3908
+ const bundle = encodeStack(respaceStack(asset, settings.spacing));
3909
+ await mkdir3(output, { recursive: true });
3910
+ await writeFile3(join2(output, "stack.png"), bundle.png);
3911
+ await writeFile3(join2(output, "stack.json"), JSON.stringify(bundle.manifest, null, 2) + "\n");
3912
+ }
3913
+ print({ node: node.id, format, output });
3914
+ return;
3915
+ }
3916
+ default:
3917
+ throw new Error("Unknown project command: " + verb);
3918
+ }
3919
+ }
3920
+ var help, print;
3921
+ var init_project_command = __esm({
3922
+ "apps/cli/src/project-command.ts"() {
3923
+ "use strict";
3924
+ init_src();
3925
+ init_project_store();
3926
+ help = `Usage: stack3 project <verb> [project-file] [options]
3927
+
3928
+ schema List agent actions and field constraints as JSON
3929
+ components [component-id] List built-in script components or inspect one
3930
+ init <file> [--name <name>] Create a level project
3931
+ get <file> Read JSON hierarchy, settings, and current view state
3932
+ import <file> <atlas.png>... Embed PNGs and add a scene object for each
3933
+ [--layout top,left,front,rear] Direction order shared by inputs in this command
3934
+ [--parent <node-id>] Place the new objects under an existing node
3935
+ apply <file> <actions.json|-> Apply an atomic JSON action batch or read it from stdin
3936
+ [--revision <number>] Require this revision before applying changes
3937
+ preset <file> four-wheel <root-id> Attach WASD Vehicle and four Sprite Stack Wheel components
3938
+ [--wheels <fl,fr,rl,rr>] Specify wheel IDs in front-left, front-right, rear-left, rear-right order
3939
+ [--revision <number>] Require this revision before applying changes
3940
+ preset <file> tracked-tank <root-id> Attach Tracked Drive, Turret Control, and both Track Belt components
3941
+ open <file> [--no-open] [--playground] Open the live editor or interactive play view
3942
+ export <file> <node-id> --output <path> Export one object's asset with its reconstruction settings
3943
+ [--format stack|glb] Overrides the object's output format
3944
+ `;
3945
+ print = (value) => console.log(JSON.stringify(value, null, 2));
3946
+ }
3947
+ });
3948
+
3949
+ // apps/cli/src/view.ts
3950
+ var view_exports = {};
3951
+ __export(view_exports, {
3952
+ viewStack: () => viewStack
3953
+ });
3954
+ import { randomUUID as randomUUID5 } from "node:crypto";
3955
+ import { readFile as readFile4 } from "node:fs/promises";
3956
+ import { join as join3 } from "node:path";
3957
+ import { PNG as PNG2 } from "pngjs";
3958
+ async function viewStack(directory2, open2) {
3959
+ const [metadata, png2] = await Promise.all([
3960
+ readFile4(join3(directory2, "stack.json"), "utf8"),
3961
+ readFile4(join3(directory2, "stack.png"))
3962
+ ]);
3963
+ readPngSize(png2);
3964
+ readStackBundle(JSON.parse(metadata), PNG2.sync.read(png2));
3965
+ const token = randomUUID5();
3966
+ const prefix = "/__stack3/" + token + "/";
3967
+ const url = await serveViewer("/?stack=" + token, open2, (request, response, next) => {
3968
+ if (request.method !== "GET") return next();
3969
+ if (request.url === prefix + "stack.json") {
3970
+ response.setHeader("Content-Type", "application/json");
3971
+ response.end(metadata);
3972
+ } else if (request.url === prefix + "stack.png") {
3973
+ response.setHeader("Content-Type", "image/png");
3974
+ response.end(png2);
3975
+ } else {
3976
+ next();
3977
+ }
3978
+ });
3979
+ console.log("Stack preview " + url.href);
3980
+ console.log("Press Ctrl+C to stop the local viewer.");
3981
+ }
3982
+ var init_view = __esm({
3983
+ "apps/cli/src/view.ts"() {
3984
+ "use strict";
3985
+ init_preview_server();
3986
+ init_src();
3987
+ }
3988
+ });
3989
+
3990
+ // apps/cli/src/main.ts
3991
+ init_src();
3992
+ import { constants, existsSync as existsSync2 } from "node:fs";
3993
+ import { copyFile, mkdir as mkdir4, readFile as readFile5, writeFile as writeFile4 } from "node:fs/promises";
3994
+ import { dirname as dirname3, extname as extname2, join as join4, resolve as resolve3 } from "node:path";
3995
+ import { parseArgs as parseArgs2 } from "node:util";
3996
+ import { PNG as PNG3 } from "pngjs";
3997
+
3998
+ // apps/cli/src/build-cache.ts
3999
+ init_src();
4000
+ import { createHash, randomUUID } from "node:crypto";
4001
+ import { mkdir, readdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
4002
+ import { homedir } from "node:os";
4003
+ import { join, resolve } from "node:path";
4004
+ import { deserialize, serialize } from "node:v8";
4005
+ var version = "render-data-3";
4006
+ var directory = process.env.STACK3_CACHE_DIR ? resolve(process.env.STACK3_CACHE_DIR) : join(process.env.XDG_CACHE_HOME || join(homedir(), ".cache"), "stack3", version);
4007
+ function buildCacheKey(views, format, settings, spacing) {
4008
+ const hash = createHash("sha256");
4009
+ hash.update(JSON.stringify([version, format, settings, spacing]));
4010
+ for (const direction of DIRECTIONS) {
4011
+ const view = views[direction];
4012
+ if (!view) continue;
4013
+ hash.update(JSON.stringify([direction, view.width, view.height]));
4014
+ hash.update(view.data);
4015
+ }
4016
+ return hash.digest("hex");
4017
+ }
4018
+ async function readBuildCache(key, format) {
4019
+ try {
4020
+ const data = deserialize(await readFile(join(directory, key + ".cache")));
4021
+ if (data.format !== format) return;
4022
+ if (data.format === "glb" ? data.bytes instanceof Uint8Array : data.png instanceof Uint8Array && typeof data.manifest === "string") return data;
4023
+ } catch {
4024
+ }
4025
+ }
4026
+ async function writeBuildCache(key, output) {
4027
+ const temporary = join(directory, randomUUID() + ".tmp");
4028
+ try {
4029
+ await mkdir(directory, { recursive: true });
4030
+ await writeFile(temporary, serialize(output), { flag: "wx" });
4031
+ await rename(temporary, join(directory, key + ".cache"));
4032
+ const entries = (await readdir(directory)).filter((name) => /^[0-9a-f]{64}\.cache$/.test(name));
4033
+ if (entries.length <= 12) return;
4034
+ const dated = await Promise.all(entries.map(async (name) => ({ name, time: (await stat(join(directory, name))).mtimeMs })));
4035
+ await Promise.all(dated.sort((a, b) => b.time - a.time).slice(12).map(({ name }) => unlink(join(directory, name))));
4036
+ } catch {
4037
+ await unlink(temporary).catch(() => {
4038
+ });
4039
+ }
4040
+ }
4041
+
4042
+ // apps/cli/src/main.ts
4043
+ var HELP = `Usage: stack3 <verb> <input> [options]
4044
+
4045
+ example <name> Copy future-tank or traffic-cone into the current directory
4046
+ inspect <input> Check mapped directions and fitted image sizes
4047
+ build <input> Build an asset and save it to --output
4048
+ view <directory> Open a stack bundle in the local viewer (--no-open to print the URL only)
4049
+ project --help Edit a level and control its live viewer and playground
4050
+
4051
+ Inputs
4052
+ PNG atlas Supply --layout top,left,front,rear (add right,bottom for six views)
4053
+ JSON manifest Map directions to separate PNG paths under "views"
4054
+
4055
+ Build options
4056
+ --format glb|stack Write a GLB file or a directory with stack.png and stack.json
4057
+ Can be omitted when --output ends in .glb
4058
+ --output <path> Required output path
4059
+ --texture-projection <name> auto (default) or top-contour for GLB output
4060
+ --mesh-method <name> marching-cubes (default) or contour for GLB output
4061
+ --contour-hub Add a centered round axle measured from TOP and LEFT
4062
+ --layers <integer> Vertical samples (default 48)
4063
+ --spacing <number> Sprite stack spacing multiplier (default 1)
4064
+ --profile <name> silhouette, round, or round-base
4065
+ --no-cache Bypass the local build cache
4066
+ --resolution <integer> Maximum horizontal axis samples (default 96)
4067
+ --height <number> Asset height in scene units (default 1)
4068
+ --pivot ground|center Origin position (default ground)
4069
+ --threshold <0\u2013255> Background threshold for opaque PNGs (default 238)
4070
+ `;
4071
+ async function png(path) {
4072
+ const bytes = await readFile5(path);
4073
+ readPngSize(bytes);
4074
+ const image = PNG3.sync.read(bytes);
4075
+ return { width: image.width, height: image.height, data: image.data };
4076
+ }
4077
+ async function readInput(path, layout, threshold) {
4078
+ if (extname2(path).toLowerCase() === ".png") {
4079
+ if (!layout) throw new Error("A PNG atlas needs an explicit --layout.");
4080
+ return splitAtlas(await png(path), parseLayout(layout), threshold);
4081
+ }
4082
+ if (extname2(path).toLowerCase() !== ".json") throw new Error("Choose a PNG atlas or a JSON view manifest.");
4083
+ if (layout) throw new Error("View manifests define their directions in the views field.");
4084
+ const manifest = JSON.parse(await readFile5(path, "utf8"));
4085
+ const views = manifest && typeof manifest === "object" && "views" in manifest ? manifest.views : null;
4086
+ if (!views || typeof views !== "object" || Array.isArray(views)) throw new Error("The manifest needs a views object.");
4087
+ const entries = Object.entries(views);
4088
+ parseLayout(entries.map(([name]) => name).join(","));
4089
+ return Object.fromEntries(await Promise.all(entries.map(async ([name, file]) => {
4090
+ if (!DIRECTIONS.includes(name) || typeof file !== "string" || !file) throw new Error(`Invalid view entry: ${name}`);
4091
+ return [name, await png(resolve3(dirname3(path), file))];
4092
+ })));
4093
+ }
4094
+ function outputFormat(output, format, target) {
4095
+ if (format !== void 0 && format !== "glb" && format !== "stack") {
4096
+ throw new Error("Use --format glb or --format stack.");
4097
+ }
4098
+ if (target !== void 0 && target !== "mesh" && target !== "stack") {
4099
+ throw new Error("Use --format glb or --format stack.");
4100
+ }
4101
+ const legacyFormat = target === "mesh" ? "glb" : target;
4102
+ if (format && legacyFormat && format !== legacyFormat) throw new Error("--format and --target disagree.");
4103
+ const isGlbPath = extname2(output).toLowerCase() === ".glb";
4104
+ const selected = format ?? legacyFormat ?? (isGlbPath ? "glb" : void 0);
4105
+ if (!selected) throw new Error("Use --format stack for a stack directory or specify a .glb output file.");
4106
+ if (selected === "glb" && !isGlbPath) throw new Error("GLB output must have the .glb extension.");
4107
+ return selected;
4108
+ }
4109
+ async function copyExample(name, output) {
4110
+ const examples = /* @__PURE__ */ new Map([
4111
+ ["future-tank", ["future-tank.stack3.json", "samples/future-tank/future-tank.stack3.json"]],
4112
+ ["traffic-cone", ["traffic-cone-4view.png", "samples/props/traffic-cone-4view.png"]]
4113
+ ]);
4114
+ const example = examples.get(name);
4115
+ if (!example) throw new Error("Choose future-tank or traffic-cone.");
4116
+ const [filename, workspacePath] = example;
4117
+ const packaged = new URL("../examples/" + filename, import.meta.url);
4118
+ const source = existsSync2(packaged) ? packaged : new URL("../../../" + workspacePath, import.meta.url);
4119
+ const destination = resolve3(output ?? filename);
4120
+ await copyFile(source, destination, constants.COPYFILE_EXCL);
4121
+ console.log(destination);
4122
+ }
4123
+ async function main() {
4124
+ if (process.argv[2] === "project") {
4125
+ const { projectCommand: projectCommand2 } = await Promise.resolve().then(() => (init_project_command(), project_command_exports));
4126
+ await projectCommand2(process.argv.slice(3));
4127
+ return;
4128
+ }
4129
+ const { positionals, values } = parseArgs2({
4130
+ allowPositionals: true,
4131
+ options: {
4132
+ help: { type: "boolean", short: "h" },
4133
+ version: { type: "boolean", short: "v" },
4134
+ layout: { type: "string" },
4135
+ format: { type: "string" },
4136
+ target: { type: "string" },
4137
+ output: { type: "string", short: "o" },
4138
+ layers: { type: "string" },
4139
+ resolution: { type: "string" },
4140
+ height: { type: "string" },
4141
+ pivot: { type: "string" },
4142
+ threshold: { type: "string" },
4143
+ "texture-projection": { type: "string" },
4144
+ "mesh-method": { type: "string" },
4145
+ "contour-hub": { type: "boolean" },
4146
+ spacing: { type: "string" },
4147
+ profile: { type: "string" },
4148
+ "no-cache": { type: "boolean" },
4149
+ "no-open": { type: "boolean" }
4150
+ }
4151
+ });
4152
+ if (values.version) {
4153
+ const manifest = JSON.parse(await readFile5(new URL("../package.json", import.meta.url), "utf8"));
4154
+ console.log(manifest.version);
4155
+ return;
4156
+ }
4157
+ if (values.help || positionals.length === 0) {
4158
+ console.log(HELP);
4159
+ return;
4160
+ }
4161
+ const [verb, input] = positionals;
4162
+ if (verb === "example" && positionals.length === 2) {
4163
+ await copyExample(input, values.output);
4164
+ return;
4165
+ }
4166
+ if (positionals.length !== 2 || verb !== "inspect" && verb !== "build" && verb !== "view") {
4167
+ throw new Error("See stack3 --help for available commands and arguments.");
4168
+ }
4169
+ if (verb === "view") {
4170
+ const { viewStack: viewStack2 } = await Promise.resolve().then(() => (init_view(), view_exports));
4171
+ await viewStack2(resolve3(input), !values["no-open"]);
4172
+ return;
4173
+ }
4174
+ const threshold = values.threshold === void 0 ? 238 : Number(values.threshold);
4175
+ if (!Number.isInteger(threshold) || threshold < 0 || threshold > 255) throw new Error("Threshold must be an integer from 0 to 255.");
4176
+ if (verb === "inspect") {
4177
+ const views2 = await readInput(input, values.layout, threshold);
4178
+ console.log(JSON.stringify(inspectViews(prepareViews(views2, threshold)), null, 2));
4179
+ return;
4180
+ }
4181
+ if (!values.output) throw new Error("Build requires --output <path>.");
4182
+ const output = resolve3(values.output);
4183
+ const format = outputFormat(output, values.format, values.target);
4184
+ const spacing = values.spacing === void 0 ? 1 : Number(values.spacing);
4185
+ if (!Number.isFinite(spacing) || spacing <= 0) throw new Error("Spacing must be a positive, finite multiplier.");
4186
+ if (values.spacing !== void 0 && format !== "stack") throw new Error("--spacing is available with --format stack.");
4187
+ const profile = values.profile;
4188
+ if (profile !== void 0 && profile !== "silhouette" && profile !== "round" && profile !== "round-base") {
4189
+ throw new Error("Use --profile silhouette, round, or round-base.");
4190
+ }
4191
+ if (values.pivot !== void 0 && values.pivot !== "ground" && values.pivot !== "center") throw new Error("Pivot must be ground or center.");
4192
+ const textureProjection = values["texture-projection"];
4193
+ if (textureProjection !== void 0 && textureProjection !== "auto" && textureProjection !== "top-contour")
4194
+ throw new Error("Use --texture-projection auto or top-contour.");
4195
+ if (textureProjection !== void 0 && format !== "glb") throw new Error("--texture-projection requires GLB output.");
4196
+ const meshMethod = values["mesh-method"];
4197
+ if (meshMethod !== void 0 && meshMethod !== "marching-cubes" && meshMethod !== "contour")
4198
+ throw new Error("Use --mesh-method marching-cubes or contour.");
4199
+ if ((meshMethod || values["contour-hub"]) && format !== "glb") throw new Error("Mesh methods require GLB output.");
4200
+ if (values["contour-hub"] && meshMethod !== "contour") throw new Error("--contour-hub requires --mesh-method contour.");
4201
+ if (meshMethod === "contour" && profile && profile !== "silhouette") throw new Error("Contour extrusion uses the FRONT silhouette.");
4202
+ const settings = {
4203
+ textureProjection,
4204
+ meshMethod,
4205
+ contourHub: values["contour-hub"],
4206
+ layers: values.layers === void 0 ? void 0 : Number(values.layers),
4207
+ resolution: values.resolution === void 0 ? void 0 : Number(values.resolution),
4208
+ height: values.height === void 0 ? void 0 : Number(values.height),
4209
+ pivot: values.pivot,
4210
+ threshold,
4211
+ profile
4212
+ };
4213
+ const views = await readInput(input, values.layout, threshold);
4214
+ const key = values["no-cache"] ? void 0 : buildCacheKey(views, format, settings, spacing);
4215
+ const cached = key ? await readBuildCache(key, format) : void 0;
4216
+ const artifact = cached ?? buildOutput(views, format, settings, spacing);
4217
+ if (artifact.format === "glb") {
4218
+ await mkdir4(dirname3(output), { recursive: true });
4219
+ await writeFile4(output, artifact.bytes);
4220
+ } else {
4221
+ await mkdir4(output, { recursive: true });
4222
+ await writeFile4(join4(output, "stack.png"), artifact.png);
4223
+ await writeFile4(join4(output, "stack.json"), artifact.manifest);
4224
+ }
4225
+ if (key && !cached) await writeBuildCache(key, artifact);
4226
+ console.log(`Built ${format} at ${output}${cached ? " \xB7 disk cache" : ""}`);
4227
+ }
4228
+ function buildOutput(views, format, settings, spacing) {
4229
+ const asset = reconstruct(views, format === "glb" ? "mesh" : "stack", settings);
4230
+ if (asset.target === "mesh") return { format: "glb", bytes: encodeGlb(asset) };
4231
+ const bundle = encodeStack(respaceStack(asset, spacing));
4232
+ return { format: "stack", png: bundle.png, manifest: JSON.stringify(bundle.manifest, null, 2) + "\n" };
4233
+ }
4234
+ main().catch((error) => {
4235
+ console.error("stack3: " + (error instanceof Error ? error.message : String(error)));
4236
+ process.exitCode = 1;
4237
+ });