stack3js 0.2.0 → 0.6.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/COMMAND.md +147 -0
- package/README.md +171 -4
- package/bin/stack3.mjs +1445 -186
- package/blender/import_stack.py +89 -0
- package/meshing/blocks.py +82 -0
- package/meshing/branches.py +62 -0
- package/meshing/dexel.py +67 -0
- package/meshing/field_data.py +19 -0
- package/meshing/finish_blender.py +203 -0
- package/meshing/finishing.py +155 -0
- package/meshing/geometry.py +71 -0
- package/meshing/guided.py +150 -0
- package/meshing/implicit.py +178 -0
- package/meshing/intersection.py +33 -0
- package/meshing/material.py +115 -0
- package/meshing/mesh.py +103 -0
- package/meshing/network.py +136 -0
- package/meshing/regularization.py +213 -0
- package/meshing/sections.py +165 -0
- package/meshing/signed_distance.py +93 -0
- package/package.json +9 -2
- package/references/hard-surface/README.md +40 -0
- package/references/hard-surface/atlas/concrete-barrier-4view.png +0 -0
- package/references/hard-surface/atlas/preview.pipeline.yaml +14 -0
- package/references/hard-surface/case-studies/benchmark/README.md +22 -0
- package/references/hard-surface/case-studies/benchmark/lod-bevel.pipeline.yaml +258 -0
- package/references/hard-surface/finishing/exports.yaml +10 -0
- package/references/hard-surface/finishing/finish-lod.pipeline.yaml +33 -0
- package/references/hard-surface/finishing/inputs/stack/stack.json +1 -0
- package/references/hard-surface/finishing/inputs/stack/stack.png +0 -0
- package/references/hard-surface/finishing/regularize.pipeline.yaml +46 -0
- package/references/hard-surface/measured-depth/sdf/compare.pipeline.yaml +12 -0
- package/references/hard-surface/measured-depth/sdf/inputs/field.npy +0 -0
- package/references/hard-surface/measured-depth/sdf/inputs/stack/stack.json +1 -0
- package/references/hard-surface/measured-depth/sdf/inputs/stack/stack.png +0 -0
- package/references/hard-surface/measured-depth/sdf/inputs/truth.json +1 -0
- package/references/hard-surface/measured-depth/sdf/sdf.guide.json +3 -0
- package/references/hard-surface/measured-depth/triple-dexel/compare.pipeline.yaml +12 -0
- package/references/hard-surface/measured-depth/triple-dexel/dexel.guide.json +3 -0
- package/references/hard-surface/measured-depth/triple-dexel/inputs/fixture.json +22 -0
- package/references/hard-surface/measured-depth/triple-dexel/inputs/stack/stack.json +22 -0
- package/references/hard-surface/measured-depth/triple-dexel/inputs/stack/stack.png +0 -0
- package/references/hard-surface/measured-depth/triple-dexel/inputs/triple-dexel.npz +0 -0
- package/references/hard-surface/schema/pipeline-fragment.schema.json +5 -0
- package/references/hard-surface/schema/pipeline.schema.json +181 -0
- package/schema/pipeline-fragment.schema.json +5 -0
- package/schema/pipeline.schema.json +181 -0
- package/verification/acceptance.py +85 -0
- package/verification/assembly.py +96 -0
- package/verification/landmarks.py +53 -0
- package/verification/panels.py +147 -0
- package/verification/projections.py +135 -0
- package/verification/verify.py +115 -0
- package/viewer/dist/assets/{GLTFExporter--hziUXc8.js → GLTFExporter-xdVCArY-.js} +1 -1
- package/viewer/dist/assets/compare-Du4RoRQO.js +6 -0
- package/viewer/dist/assets/compare.worker-CgJq-znx.js +21 -0
- package/viewer/dist/assets/presets-jXE0t1fU.js +1 -0
- package/viewer/dist/assets/preview-cache-BKV0EZl9.js +1 -0
- package/viewer/dist/assets/project-DtHHhfo-.js +17 -0
- package/viewer/dist/assets/reconstruct.worker-ONc9GyFO.js +21 -0
- package/viewer/dist/assets/{script-engine-CLj7QMLe.js → script-engine-Bs3azDYZ.js} +1 -1
- package/viewer/dist/assets/style-D6eZHs3D.js +4004 -0
- package/viewer/dist/assets/viewer-DIjS0No7.js +2 -0
- package/viewer/dist/compare.html +4 -4
- package/viewer/dist/index.html +9 -8
- package/viewer/dist/project.html +3 -3
- package/viewer/dist/assets/compare-DJ8rV3Rn.js +0 -6
- package/viewer/dist/assets/compare.worker-DK2lJl0n.js +0 -21
- package/viewer/dist/assets/presets-DwdZVYhs.js +0 -1
- package/viewer/dist/assets/preview-cache-DRF_H5pq.js +0 -58
- package/viewer/dist/assets/project-D8tR6U-_.js +0 -17
- package/viewer/dist/assets/reconstruct.worker-Cf8iZwT3.js +0 -21
- package/viewer/dist/assets/style-CWGgpweN.js +0 -3947
- package/viewer/dist/assets/viewer-CyGodHLY.js +0 -2
package/bin/stack3.mjs
CHANGED
|
@@ -42,14 +42,19 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
42
42
|
));
|
|
43
43
|
|
|
44
44
|
// packages/core/src/views.ts
|
|
45
|
-
function
|
|
45
|
+
function readPngDimensions(bytes) {
|
|
46
46
|
const signature = [137, 80, 78, 71, 13, 10, 26, 10];
|
|
47
47
|
if (bytes.length < 33 || signature.some((value, index) => bytes[index] !== value) || String.fromCharCode(...bytes.subarray(12, 16)) !== "IHDR") {
|
|
48
48
|
throw new Error("Expected a PNG image.");
|
|
49
49
|
}
|
|
50
50
|
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
51
51
|
const width = view.getUint32(16), height = view.getUint32(20);
|
|
52
|
-
if (!width || !height || width
|
|
52
|
+
if (!width || !height || !Number.isSafeInteger(width * height * 4)) throw new Error("Invalid PNG dimensions.");
|
|
53
|
+
return { width, height };
|
|
54
|
+
}
|
|
55
|
+
function readPngSize(bytes) {
|
|
56
|
+
const { width, height } = readPngDimensions(bytes);
|
|
57
|
+
if (width > 8192 || height > 8192 || width * height > 16e6) {
|
|
53
58
|
throw new Error("PNG dimensions exceed the 8192 px or 16 MP input limit.");
|
|
54
59
|
}
|
|
55
60
|
return { width, height };
|
|
@@ -190,7 +195,12 @@ function inspectViews(views) {
|
|
|
190
195
|
if (Math.abs(expected / observed - 1) > 0.2) warnings.push("Top, left, and front proportions differ by more than 20%. Check alignment.");
|
|
191
196
|
if (Math.abs(rear.width / rear.height / observed - 1) > 0.2) warnings.push("Front and rear proportions differ by more than 20%.");
|
|
192
197
|
const mapped = Object.entries(views).map(([direction, raster]) => ({ direction, width: raster.width, height: raster.height }));
|
|
193
|
-
|
|
198
|
+
const nativeSamples = {
|
|
199
|
+
x: Math.max(top.width, front.width, rear.width, views.bottom?.width ?? 0),
|
|
200
|
+
y: Math.max(top.height, left.width, views.right?.width ?? 0, views.bottom?.height ?? 0),
|
|
201
|
+
z: Math.max(left.height, front.height, rear.height, views.right?.height ?? 0)
|
|
202
|
+
};
|
|
203
|
+
return { views: mapped, nativeSamples, warnings };
|
|
194
204
|
}
|
|
195
205
|
var DIRECTIONS;
|
|
196
206
|
var init_views = __esm({
|
|
@@ -200,6 +210,26 @@ var init_views = __esm({
|
|
|
200
210
|
}
|
|
201
211
|
});
|
|
202
212
|
|
|
213
|
+
// packages/core/src/sampling.ts
|
|
214
|
+
function samplingGrid(width, depth, resolution, layers) {
|
|
215
|
+
if (!Number.isSafeInteger(layers) || layers < 8) throw new Error("Layers must be a safe integer of at least 8.");
|
|
216
|
+
if (!Number.isSafeInteger(resolution) || resolution < 16) throw new Error("Resolution must be a safe integer of at least 16.");
|
|
217
|
+
const longest = Math.max(width, depth);
|
|
218
|
+
const columns2 = Math.max(2, Math.round(width / longest * resolution));
|
|
219
|
+
const rows = Math.max(2, Math.round(depth / longest * resolution));
|
|
220
|
+
if (!Number.isSafeInteger(columns2 * rows * layers * 4)) {
|
|
221
|
+
throw new Error("Requested grid is too large to address its RGBA samples.");
|
|
222
|
+
}
|
|
223
|
+
return { width: columns2, depth: rows, layers };
|
|
224
|
+
}
|
|
225
|
+
var DEFAULT_LAYERS;
|
|
226
|
+
var init_sampling = __esm({
|
|
227
|
+
"packages/core/src/sampling.ts"() {
|
|
228
|
+
"use strict";
|
|
229
|
+
DEFAULT_LAYERS = 128;
|
|
230
|
+
}
|
|
231
|
+
});
|
|
232
|
+
|
|
203
233
|
// packages/core/src/texture-projection.ts
|
|
204
234
|
function visibleFromAbove(mesh, bins) {
|
|
205
235
|
const { positions: p, indices, size } = mesh;
|
|
@@ -241,7 +271,7 @@ function visibleFromAbove(mesh, bins) {
|
|
|
241
271
|
}
|
|
242
272
|
function projectUpperContour(mesh, plan, resolution, layers) {
|
|
243
273
|
const { positions: p, normals, uvs, indices, texture, size } = mesh;
|
|
244
|
-
resolution = Math.max(1, Math.min(
|
|
274
|
+
resolution = Math.max(1, Math.min(Math.max(plan.width, plan.height), Math.round(resolution) || 96));
|
|
245
275
|
const visible = visibleFromAbove(mesh, resolution);
|
|
246
276
|
const axis = size[1] >= size[0] ? 2 : 0;
|
|
247
277
|
const span = axis === 2 ? size[1] : size[0];
|
|
@@ -1668,7 +1698,7 @@ function inferSurfaceDepth(volume, size, directions) {
|
|
|
1668
1698
|
const [axis, high] = depthAxes[direction];
|
|
1669
1699
|
const plane = axes.filter((item) => item !== axis);
|
|
1670
1700
|
const width = size[plane[0]], height = size[plane[1]];
|
|
1671
|
-
const values = new
|
|
1701
|
+
const values = new Int32Array(width * height).fill(-1);
|
|
1672
1702
|
const p = [0, 0, 0];
|
|
1673
1703
|
for (let v = 0; v < height; v++) for (let u = 0; u < width; u++) {
|
|
1674
1704
|
p[plane[0]] = u;
|
|
@@ -1820,7 +1850,7 @@ function regularizeDepth(occupancy, shape, pitch) {
|
|
|
1820
1850
|
}
|
|
1821
1851
|
return current;
|
|
1822
1852
|
}
|
|
1823
|
-
function
|
|
1853
|
+
function paddedOccupancy(volume, width, depth, layers) {
|
|
1824
1854
|
const nx = width + 2, ny = depth + 2, nz = layers + 2;
|
|
1825
1855
|
const plane = nx * ny, count2 = plane * nz;
|
|
1826
1856
|
const occupancy = new Uint8Array(count2);
|
|
@@ -1828,6 +1858,10 @@ function extractSurface(volume, width, depth, layers, worldSize) {
|
|
|
1828
1858
|
const start = (z * depth + y) * width;
|
|
1829
1859
|
occupancy.set(volume.subarray(start, start + width), (z + 1) * plane + (y + 1) * nx + 1);
|
|
1830
1860
|
}
|
|
1861
|
+
return { nx, ny, nz, plane, count: count2, occupancy };
|
|
1862
|
+
}
|
|
1863
|
+
function extractSurface(volume, width, depth, layers, worldSize) {
|
|
1864
|
+
const { nx, ny, nz, plane, count: count2, occupancy } = paddedOccupancy(volume, width, depth, layers);
|
|
1831
1865
|
const field = worldSize ? regularizeDepth(occupancy, [nx, ny, nz], [worldSize[0] / width, worldSize[1] / depth, worldSize[2] / layers]) : new Float32Array(count2);
|
|
1832
1866
|
for (let z = 0; z < nz; z++) for (let y = 0; y < ny; y++) for (let x2 = 0; x2 < nx; x2++) {
|
|
1833
1867
|
const index = z * plane + y * nx + x2;
|
|
@@ -1870,6 +1904,101 @@ function extractSurface(volume, width, depth, layers, worldSize) {
|
|
|
1870
1904
|
}
|
|
1871
1905
|
return { positions, gradients, indices };
|
|
1872
1906
|
}
|
|
1907
|
+
function extractVoxelSurface(volume, width, depth, layers) {
|
|
1908
|
+
const dimensions = [width, depth, layers];
|
|
1909
|
+
const strides = [1, width, width * depth];
|
|
1910
|
+
const positions = [], gradients = [], indices = [];
|
|
1911
|
+
const corners = [[0, 0], [1, 0], [1, 1], [0, 1]];
|
|
1912
|
+
for (let z = 0; z < layers; z++) for (let y = 0; y < depth; y++) for (let x2 = 0; x2 < width; x2++) {
|
|
1913
|
+
const index = (z * depth + y) * width + x2;
|
|
1914
|
+
if (!volume[index]) continue;
|
|
1915
|
+
const cell = [x2, y, z];
|
|
1916
|
+
for (let axis = 0; axis < 3; axis++) {
|
|
1917
|
+
const u = (axis + 1) % 3, v = (axis + 2) % 3;
|
|
1918
|
+
for (const sign of [-1, 1]) {
|
|
1919
|
+
const neighbor = cell[axis] + sign;
|
|
1920
|
+
if (neighbor >= 0 && neighbor < dimensions[axis] && volume[index + sign * strides[axis]]) continue;
|
|
1921
|
+
const normal = [0, 0, 0];
|
|
1922
|
+
normal[axis] = sign;
|
|
1923
|
+
const base = positions.length / 3;
|
|
1924
|
+
for (const [du, dv] of corners) {
|
|
1925
|
+
const vertex = [...cell];
|
|
1926
|
+
vertex[axis] += Number(sign > 0);
|
|
1927
|
+
vertex[u] += du;
|
|
1928
|
+
vertex[v] += dv;
|
|
1929
|
+
positions.push(...vertex);
|
|
1930
|
+
gradients.push(...normal);
|
|
1931
|
+
}
|
|
1932
|
+
const a = base, b = base + 1, c = base + 2, d = base + 3;
|
|
1933
|
+
if (sign > 0) indices.push(a, b, c, a, c, d);
|
|
1934
|
+
else indices.push(a, c, b, a, d, c);
|
|
1935
|
+
}
|
|
1936
|
+
}
|
|
1937
|
+
}
|
|
1938
|
+
return { positions, gradients, indices };
|
|
1939
|
+
}
|
|
1940
|
+
function extractSurfaceNets(volume, width, depth, layers) {
|
|
1941
|
+
const { nx, ny, nz, plane, count: count2, occupancy } = paddedOccupancy(volume, width, depth, layers);
|
|
1942
|
+
const strides = [1, nx, plane];
|
|
1943
|
+
const corners = CORNERS.map(([x2, y, z]) => x2 + nx * y + plane * z);
|
|
1944
|
+
const vertexAt = new Int32Array(count2);
|
|
1945
|
+
const positions = [], gradients = [], indices = [];
|
|
1946
|
+
function faceNormal(a, b, c) {
|
|
1947
|
+
const ax = positions[b * 3] - positions[a * 3];
|
|
1948
|
+
const ay = positions[b * 3 + 1] - positions[a * 3 + 1];
|
|
1949
|
+
const az = positions[b * 3 + 2] - positions[a * 3 + 2];
|
|
1950
|
+
const bx = positions[c * 3] - positions[a * 3];
|
|
1951
|
+
const by = positions[c * 3 + 1] - positions[a * 3 + 1];
|
|
1952
|
+
const bz = positions[c * 3 + 2] - positions[a * 3 + 2];
|
|
1953
|
+
return [ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx];
|
|
1954
|
+
}
|
|
1955
|
+
function triangle(a, b, c) {
|
|
1956
|
+
indices.push(a, b, c);
|
|
1957
|
+
const [nx2, ny2, nz2] = faceNormal(a, b, c);
|
|
1958
|
+
for (const i2 of [a, b, c]) {
|
|
1959
|
+
gradients[i2 * 3] += nx2;
|
|
1960
|
+
gradients[i2 * 3 + 1] += ny2;
|
|
1961
|
+
gradients[i2 * 3 + 2] += nz2;
|
|
1962
|
+
}
|
|
1963
|
+
}
|
|
1964
|
+
for (let z = 0; z < nz - 1; z++) for (let y = 0; y < ny - 1; y++) for (let x2 = 0; x2 < nx - 1; x2++) {
|
|
1965
|
+
const cell = z * plane + y * nx + x2;
|
|
1966
|
+
let mask = 0;
|
|
1967
|
+
for (let i2 = 0; i2 < 8; i2++) mask |= occupancy[cell + corners[i2]] << i2;
|
|
1968
|
+
if (mask === 0 || mask === 255) continue;
|
|
1969
|
+
let sx = 0, sy = 0, sz = 0, crossings = 0;
|
|
1970
|
+
for (const [a2, b] of EDGES) {
|
|
1971
|
+
if ((mask >> a2 & 1) === (mask >> b & 1)) continue;
|
|
1972
|
+
sx += (CORNERS[a2][0] + CORNERS[b][0]) / 2;
|
|
1973
|
+
sy += (CORNERS[a2][1] + CORNERS[b][1]) / 2;
|
|
1974
|
+
sz += (CORNERS[a2][2] + CORNERS[b][2]) / 2;
|
|
1975
|
+
crossings++;
|
|
1976
|
+
}
|
|
1977
|
+
const a = positions.length / 3;
|
|
1978
|
+
vertexAt[cell] = a;
|
|
1979
|
+
positions.push(x2 - 0.5 + sx / crossings, y - 0.5 + sy / crossings, z - 0.5 + sz / crossings);
|
|
1980
|
+
gradients.push(0, 0, 0);
|
|
1981
|
+
for (let axis = 0; axis < 3; axis++) {
|
|
1982
|
+
if (occupancy[cell] === occupancy[cell + strides[axis]]) continue;
|
|
1983
|
+
const u = strides[(axis + 1) % 3], v = strides[(axis + 2) % 3];
|
|
1984
|
+
const b = vertexAt[cell - u], c = vertexAt[cell - u - v], d = vertexAt[cell - v];
|
|
1985
|
+
if (occupancy[cell]) {
|
|
1986
|
+
triangle(a, b, c);
|
|
1987
|
+
triangle(a, c, d);
|
|
1988
|
+
} else {
|
|
1989
|
+
triangle(a, d, c);
|
|
1990
|
+
triangle(a, c, b);
|
|
1991
|
+
}
|
|
1992
|
+
}
|
|
1993
|
+
}
|
|
1994
|
+
for (let i2 = 0; i2 < indices.length; i2++) {
|
|
1995
|
+
const p = indices[i2] * 3;
|
|
1996
|
+
if (Math.abs(gradients[p]) + Math.abs(gradients[p + 1]) + Math.abs(gradients[p + 2]) > 1e-10) continue;
|
|
1997
|
+
const start = i2 - i2 % 3;
|
|
1998
|
+
[gradients[p], gradients[p + 1], gradients[p + 2]] = faceNormal(indices[start], indices[start + 1], indices[start + 2]);
|
|
1999
|
+
}
|
|
2000
|
+
return { positions, gradients, indices };
|
|
2001
|
+
}
|
|
1873
2002
|
var CORNERS, EDGES;
|
|
1874
2003
|
var init_surface = __esm({
|
|
1875
2004
|
"packages/core/src/surface.ts"() {
|
|
@@ -1935,27 +2064,23 @@ function rankedViews(views, nx, ny, nz) {
|
|
|
1935
2064
|
if (!views.bottom) weights[0] = Math.abs(nz);
|
|
1936
2065
|
return [...DIRECTIONS].filter((direction) => views[direction]).sort((a, b) => weights[DIRECTIONS.indexOf(b)] - weights[DIRECTIONS.indexOf(a)]);
|
|
1937
2066
|
}
|
|
1938
|
-
function
|
|
2067
|
+
function reconstructionDimensions(views, settings) {
|
|
1939
2068
|
const top = views.top, front = views.front, left = views.left;
|
|
1940
|
-
const layers = settings.layers ??
|
|
2069
|
+
const layers = settings.layers ?? DEFAULT_LAYERS;
|
|
1941
2070
|
const resolution = settings.resolution ?? 96;
|
|
1942
2071
|
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
2072
|
if (!Number.isFinite(height) || height <= 0) throw new Error("Height must be positive.");
|
|
1946
2073
|
if (settings.pivot && settings.pivot !== "center" && settings.pivot !== "ground") throw new Error("Pivot must be ground or center.");
|
|
1947
2074
|
const depthFromView = left.width / left.height * height;
|
|
1948
2075
|
const [x2, y, z] = settings.size ?? [(front.width / front.height * height + depthFromView * top.width / top.height) / 2, depthFromView, height];
|
|
1949
2076
|
if (![x2, y, z].every((value) => Number.isFinite(value) && value > 0)) throw new Error("Part dimensions must be positive.");
|
|
1950
|
-
const width
|
|
1951
|
-
const depth = Math.max(2, Math.round(y / Math.max(x2, y) * resolution));
|
|
2077
|
+
const { width, depth } = samplingGrid(x2, y, resolution, layers);
|
|
1952
2078
|
const size = [x2, y, z];
|
|
1953
2079
|
const pivot = [0, 0, settings.pivot === "center" ? z / 2 : 0];
|
|
1954
2080
|
return { width, depth, layers, size, pivot };
|
|
1955
2081
|
}
|
|
1956
2082
|
function grid(views, settings, fallback) {
|
|
1957
|
-
const { width, depth, layers, size, pivot } =
|
|
1958
|
-
if (width * depth * layers > 3e6) throw new Error("The grid is too large. Reduce layers or XY resolution.");
|
|
2083
|
+
const { width, depth, layers, size, pivot } = reconstructionDimensions(views, settings);
|
|
1959
2084
|
const aligned = {};
|
|
1960
2085
|
for (const direction of DIRECTIONS) {
|
|
1961
2086
|
const view = views[direction];
|
|
@@ -2027,12 +2152,13 @@ function textureAtlas(views, accentViews = {}, bleed = false) {
|
|
|
2027
2152
|
}
|
|
2028
2153
|
return { tiles, accents, texture: { width, height, data } };
|
|
2029
2154
|
}
|
|
2030
|
-
function makeMesh(g, views, mode = "rgb") {
|
|
2155
|
+
function makeMesh(g, views, mode = "rgb", method = "marching-cubes") {
|
|
2031
2156
|
const { width, depth, layers, size, pivot, volume } = g;
|
|
2032
|
-
const
|
|
2157
|
+
const extract2 = { "marching-cubes": extractSurface, "surface-nets": extractSurfaceNets, voxel: extractVoxelSurface }[method];
|
|
2158
|
+
const surface = extract2(volume, width, depth, layers, mode === "depth" ? size : void 0);
|
|
2033
2159
|
if (!surface.indices.length && mode === "depth") return makeMesh(g, views, "id");
|
|
2034
|
-
const roof = new
|
|
2035
|
-
const floor = new
|
|
2160
|
+
const roof = new Int32Array(width * depth).fill(-1);
|
|
2161
|
+
const floor = new Int32Array(width * depth).fill(layers);
|
|
2036
2162
|
const area3 = width * depth;
|
|
2037
2163
|
for (let z = 0; z < layers; z++) for (let i2 = 0; i2 < area3; i2++) {
|
|
2038
2164
|
if (!volume[z * area3 + i2]) continue;
|
|
@@ -2117,7 +2243,7 @@ function makeMesh(g, views, mode = "rgb") {
|
|
|
2117
2243
|
cache.set(key, index);
|
|
2118
2244
|
const p = original * 3;
|
|
2119
2245
|
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]);
|
|
2246
|
+
positions.push((x2 - 0.5) * size[0] - pivot[0], z * size[2] - pivot[2], (0.5 - y) * size[1] + pivot[1]);
|
|
2121
2247
|
const nx = surface.gradients[p] * width / size[0], ny = surface.gradients[p + 1] * depth / size[1];
|
|
2122
2248
|
const nz = surface.gradients[p + 2] * layers / size[2];
|
|
2123
2249
|
const magnitude = Math.hypot(nx, ny, nz) || 1;
|
|
@@ -2143,13 +2269,50 @@ function makeMesh(g, views, mode = "rgb") {
|
|
|
2143
2269
|
...frontDecal?.mesh && { frontAccents: frontDecal.mesh }
|
|
2144
2270
|
};
|
|
2145
2271
|
}
|
|
2272
|
+
function meshFromStack(stack, method = "marching-cubes") {
|
|
2273
|
+
const { width, depth, layers, columns: columns2, spacing, pivot, texture } = stack;
|
|
2274
|
+
const size = [stack.size[0], stack.size[1], spacing * layers];
|
|
2275
|
+
const volume = new Uint8Array(width * depth * layers);
|
|
2276
|
+
const raster = (w, h) => ({ width: w, height: h, data: new Uint8Array(w * h * 4) });
|
|
2277
|
+
const views = {
|
|
2278
|
+
top: raster(width, depth),
|
|
2279
|
+
bottom: raster(width, depth),
|
|
2280
|
+
left: raster(depth, layers),
|
|
2281
|
+
right: raster(depth, layers),
|
|
2282
|
+
front: raster(width, layers),
|
|
2283
|
+
rear: raster(width, layers)
|
|
2284
|
+
};
|
|
2285
|
+
function paint(view, u, v, src, first) {
|
|
2286
|
+
const dst = (v * view.width + u) * 4;
|
|
2287
|
+
if (first && view.data[dst + 3]) return;
|
|
2288
|
+
for (let channel = 0; channel < 4; channel++) view.data[dst + channel] = texture.data[src + channel];
|
|
2289
|
+
}
|
|
2290
|
+
let occupied = 0;
|
|
2291
|
+
for (let z = 0; z < layers; z++) {
|
|
2292
|
+
const left = z % columns2 * width, top = Math.floor(z / columns2) * depth;
|
|
2293
|
+
for (let y = 0; y < depth; y++) for (let x2 = 0; x2 < width; x2++) {
|
|
2294
|
+
const src = ((top + y) * texture.width + left + x2) * 4;
|
|
2295
|
+
if (texture.data[src + 3] < 128) continue;
|
|
2296
|
+
volume[(z * depth + y) * width + x2] = 1;
|
|
2297
|
+
occupied++;
|
|
2298
|
+
paint(views.top, x2, y, src, false);
|
|
2299
|
+
paint(views.bottom, x2, depth - 1 - y, src, true);
|
|
2300
|
+
paint(views.left, depth - 1 - y, layers - 1 - z, src, true);
|
|
2301
|
+
paint(views.right, y, layers - 1 - z, src, false);
|
|
2302
|
+
paint(views.front, x2, layers - 1 - z, src, false);
|
|
2303
|
+
paint(views.rear, width - 1 - x2, layers - 1 - z, src, true);
|
|
2304
|
+
}
|
|
2305
|
+
}
|
|
2306
|
+
if (!occupied) throw new Error("The saved stack contains no occupied samples.");
|
|
2307
|
+
return makeMesh({ width, depth, layers, volume, size, pivot, aligned: views }, views, "rgb", method);
|
|
2308
|
+
}
|
|
2146
2309
|
function makeStack(g, views) {
|
|
2147
2310
|
const { width, depth, layers, size, pivot, volume } = g;
|
|
2148
2311
|
const columns2 = Math.min(layers, Math.max(1, Math.floor(4096 / width)));
|
|
2149
2312
|
const imageWidth = width * columns2, imageHeight = depth * Math.ceil(layers / columns2);
|
|
2150
2313
|
const data = new Uint8Array(imageWidth * imageHeight * 4);
|
|
2151
2314
|
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
|
|
2315
|
+
const roof = new Int32Array(width * depth).fill(-1);
|
|
2153
2316
|
for (let z = 0; z < layers; z++) for (let i2 = 0; i2 < roof.length; i2++) {
|
|
2154
2317
|
if (volume[z * roof.length + i2]) roof[i2] = z;
|
|
2155
2318
|
}
|
|
@@ -2205,13 +2368,10 @@ function makeStack(g, views) {
|
|
|
2205
2368
|
texture: { width: imageWidth, height: imageHeight, data }
|
|
2206
2369
|
};
|
|
2207
2370
|
}
|
|
2208
|
-
function reconstruct(input, target, settings = {}) {
|
|
2209
|
-
return reconstructPrepared(prepareViews(input, settings.threshold), target, settings);
|
|
2210
|
-
}
|
|
2211
2371
|
function reconstructPrepared(views, target, settings) {
|
|
2212
2372
|
let mesh;
|
|
2213
2373
|
if (target === "mesh" && settings.meshMethod === "contour") {
|
|
2214
|
-
const { size, pivot } =
|
|
2374
|
+
const { size, pivot } = reconstructionDimensions(views, settings);
|
|
2215
2375
|
const { tiles, texture } = textureAtlas(views, {}, true);
|
|
2216
2376
|
const front = views.front;
|
|
2217
2377
|
const scale = Math.min(1, 1024 / Math.max(front.width, front.height));
|
|
@@ -2223,13 +2383,14 @@ function reconstructPrepared(views, target, settings) {
|
|
|
2223
2383
|
mesh = makeMesh(g, views);
|
|
2224
2384
|
}
|
|
2225
2385
|
if (settings.textureProjection === "top-contour")
|
|
2226
|
-
projectUpperContour(mesh, views.top, settings.resolution ?? 96, settings.layers ??
|
|
2386
|
+
projectUpperContour(mesh, views.top, settings.resolution ?? 96, settings.layers ?? DEFAULT_LAYERS);
|
|
2227
2387
|
return mesh;
|
|
2228
2388
|
}
|
|
2229
2389
|
var clamp2;
|
|
2230
2390
|
var init_reconstruct = __esm({
|
|
2231
2391
|
"packages/core/src/reconstruct.ts"() {
|
|
2232
2392
|
"use strict";
|
|
2393
|
+
init_sampling();
|
|
2233
2394
|
init_texture_projection();
|
|
2234
2395
|
init_contour();
|
|
2235
2396
|
init_atlas_comparison();
|
|
@@ -2823,11 +2984,25 @@ function padded(bytes, pad = 0) {
|
|
|
2823
2984
|
function asBytes(data) {
|
|
2824
2985
|
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
2825
2986
|
}
|
|
2826
|
-
function encodeGlb(mesh) {
|
|
2987
|
+
function encodeGlb(mesh, { lit, instances } = {}) {
|
|
2827
2988
|
const sources = [asBytes(mesh.positions), asBytes(mesh.normals), asBytes(mesh.uvs), asBytes(mesh.indices), encodePng(mesh.texture)];
|
|
2989
|
+
const attributes = { POSITION: 0, NORMAL: 1, TEXCOORD_0: 2 };
|
|
2990
|
+
const count2 = mesh.positions.length / 3;
|
|
2991
|
+
const optionalAccessors = [];
|
|
2992
|
+
if (mesh.colors) {
|
|
2993
|
+
attributes.COLOR_0 = 4;
|
|
2994
|
+
optionalAccessors.push({ bufferView: sources.length, componentType: 5126, count: count2, type: "VEC4" });
|
|
2995
|
+
sources.push(asBytes(mesh.colors));
|
|
2996
|
+
}
|
|
2997
|
+
const instanceExtension = "EXT_mesh_gpu_instancing";
|
|
2998
|
+
const translation = instances?.length ? 4 + optionalAccessors.length : void 0;
|
|
2999
|
+
if (instances?.length) {
|
|
3000
|
+
optionalAccessors.push({ bufferView: sources.length, componentType: 5126, count: instances.length, type: "VEC3" });
|
|
3001
|
+
sources.push(asBytes(Float32Array.from(instances.flat())));
|
|
3002
|
+
}
|
|
2828
3003
|
let offset = 0;
|
|
2829
3004
|
const bufferViews = sources.map((source, index) => {
|
|
2830
|
-
const target = index
|
|
3005
|
+
const target = index === 3 ? 34963 : index === 4 ? void 0 : 34962;
|
|
2831
3006
|
const entry = { buffer: 0, byteOffset: offset, byteLength: source.length, target };
|
|
2832
3007
|
offset += align(source.length);
|
|
2833
3008
|
return entry;
|
|
@@ -2837,23 +3012,32 @@ function encodeGlb(mesh) {
|
|
|
2837
3012
|
min[i2 % 3] = Math.min(min[i2 % 3], mesh.positions[i2]);
|
|
2838
3013
|
max2[i2 % 3] = Math.max(max2[i2 % 3], mesh.positions[i2]);
|
|
2839
3014
|
}
|
|
2840
|
-
const
|
|
3015
|
+
const extensions = [...lit ? [] : ["KHR_materials_unlit"], ...translation === void 0 ? [] : [instanceExtension]];
|
|
2841
3016
|
const json2 = padded(encoder.encode(JSON.stringify({
|
|
2842
3017
|
asset: { version: "2.0", generator: "stack3.js" },
|
|
2843
|
-
extensionsUsed:
|
|
3018
|
+
extensionsUsed: extensions.length ? extensions : void 0,
|
|
3019
|
+
extensionsRequired: translation === void 0 ? void 0 : [instanceExtension],
|
|
2844
3020
|
scene: 0,
|
|
2845
3021
|
scenes: [{ nodes: [0] }],
|
|
2846
|
-
nodes: [{
|
|
2847
|
-
|
|
2848
|
-
|
|
3022
|
+
nodes: [{
|
|
3023
|
+
mesh: 0,
|
|
3024
|
+
extras: { size: mesh.size, pivot: mesh.pivot },
|
|
3025
|
+
extensions: translation === void 0 ? void 0 : { [instanceExtension]: { attributes: { TRANSLATION: translation } } }
|
|
3026
|
+
}],
|
|
3027
|
+
meshes: [{ primitives: [{ attributes, indices: 3, material: 0 }] }],
|
|
3028
|
+
materials: [{
|
|
3029
|
+
extensions: lit ? void 0 : { KHR_materials_unlit: {} },
|
|
3030
|
+
pbrMetallicRoughness: { baseColorTexture: { index: 0 }, ...lit ? { metallicFactor: 0, roughnessFactor: 0.65 } : {} }
|
|
3031
|
+
}],
|
|
2849
3032
|
textures: [{ source: 0, sampler: 0 }],
|
|
2850
|
-
samplers: [{ magFilter: 9729, minFilter: 9729, wrapS: 33071, wrapT: 33071 }],
|
|
3033
|
+
samplers: [{ magFilter: mesh.nearestTexture ? 9728 : 9729, minFilter: mesh.nearestTexture ? 9728 : 9729, wrapS: 33071, wrapT: 33071 }],
|
|
2851
3034
|
images: [{ mimeType: "image/png", bufferView: 4 }],
|
|
2852
3035
|
accessors: [
|
|
2853
3036
|
{ bufferView: 0, componentType: 5126, count: count2, type: "VEC3", min, max: max2 },
|
|
2854
3037
|
{ bufferView: 1, componentType: 5126, count: count2, type: "VEC3" },
|
|
2855
3038
|
{ bufferView: 2, componentType: 5126, count: count2, type: "VEC2" },
|
|
2856
|
-
{ bufferView: 3, componentType: 5125, count: mesh.indices.length, type: "SCALAR" }
|
|
3039
|
+
{ bufferView: 3, componentType: 5125, count: mesh.indices.length, type: "SCALAR" },
|
|
3040
|
+
...optionalAccessors
|
|
2857
3041
|
],
|
|
2858
3042
|
bufferViews,
|
|
2859
3043
|
buffers: [{ byteLength: offset }]
|
|
@@ -2890,21 +3074,32 @@ function encodeStack(stack) {
|
|
|
2890
3074
|
}
|
|
2891
3075
|
};
|
|
2892
3076
|
}
|
|
2893
|
-
function
|
|
3077
|
+
function stackMetadata(manifest, texture) {
|
|
2894
3078
|
if (!manifest || typeof manifest !== "object") throw new Error("Expected a stack3 stack manifest.");
|
|
2895
3079
|
const { version: version2, atlas, layout, layerOrder, axes: axes2, width, depth, layers, columns: columns2, spacing, size, pivot } = manifest;
|
|
2896
3080
|
const dimension = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0;
|
|
2897
3081
|
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 ||
|
|
3082
|
+
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 || !Number.isSafeInteger(texture.width * texture.height * 4) || !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)) {
|
|
2899
3083
|
throw new Error("The stack manifest does not match the PNG or uses an unsupported layout.");
|
|
2900
3084
|
}
|
|
2901
|
-
return {
|
|
3085
|
+
return { width, depth, layers, columns: columns2, spacing, size, pivot };
|
|
3086
|
+
}
|
|
3087
|
+
function readStackPngSize(bytes, manifest) {
|
|
3088
|
+
const dimensions = readPngDimensions(bytes);
|
|
3089
|
+
stackMetadata(manifest, dimensions);
|
|
3090
|
+
return dimensions;
|
|
3091
|
+
}
|
|
3092
|
+
function readStackBundle(manifest, texture) {
|
|
3093
|
+
const meta = stackMetadata(manifest, texture);
|
|
3094
|
+
if (texture.data.length !== texture.width * texture.height * 4) throw new Error("Invalid stack texture data length.");
|
|
3095
|
+
return { target: "stack", texture, ...meta };
|
|
2902
3096
|
}
|
|
2903
3097
|
var encoder, crcTable, align;
|
|
2904
3098
|
var init_export = __esm({
|
|
2905
3099
|
"packages/core/src/export.ts"() {
|
|
2906
3100
|
"use strict";
|
|
2907
3101
|
init_esm();
|
|
3102
|
+
init_views();
|
|
2908
3103
|
encoder = new TextEncoder();
|
|
2909
3104
|
crcTable = Uint32Array.from({ length: 256 }, (_, index) => {
|
|
2910
3105
|
let value = index;
|
|
@@ -3317,11 +3512,12 @@ var nodeDefaults, number2, choice, string, boolean, idOrNull, vector, settingsFi
|
|
|
3317
3512
|
var init_project = __esm({
|
|
3318
3513
|
"packages/core/src/project.ts"() {
|
|
3319
3514
|
"use strict";
|
|
3515
|
+
init_sampling();
|
|
3320
3516
|
init_views();
|
|
3321
3517
|
init_scripts();
|
|
3322
3518
|
nodeDefaults = {
|
|
3323
3519
|
format: "stack",
|
|
3324
|
-
layers:
|
|
3520
|
+
layers: DEFAULT_LAYERS,
|
|
3325
3521
|
resolution: 96,
|
|
3326
3522
|
spacing: 1,
|
|
3327
3523
|
height: 1,
|
|
@@ -3343,8 +3539,8 @@ var init_project = __esm({
|
|
|
3343
3539
|
meshMethod: choice("marching-cubes", "contour"),
|
|
3344
3540
|
contourHub: boolean,
|
|
3345
3541
|
format: choice("stack", "glb"),
|
|
3346
|
-
layers: number2(8,
|
|
3347
|
-
resolution: number2(16,
|
|
3542
|
+
layers: number2(8, Number.MAX_SAFE_INTEGER, "integer"),
|
|
3543
|
+
resolution: number2(16, Number.MAX_SAFE_INTEGER, "integer"),
|
|
3348
3544
|
spacing: number2(0.05, 20),
|
|
3349
3545
|
height: number2(0.01, 100),
|
|
3350
3546
|
threshold: number2(0, 255, "integer"),
|
|
@@ -3559,6 +3755,7 @@ var init_depth_fit = __esm({
|
|
|
3559
3755
|
var init_mapped_atlas = __esm({
|
|
3560
3756
|
"packages/core/src/mapped-atlas.ts"() {
|
|
3561
3757
|
"use strict";
|
|
3758
|
+
init_sampling();
|
|
3562
3759
|
init_depth_png();
|
|
3563
3760
|
init_depth_fit();
|
|
3564
3761
|
init_surface();
|
|
@@ -3570,6 +3767,7 @@ var init_src = __esm({
|
|
|
3570
3767
|
"packages/core/src/index.ts"() {
|
|
3571
3768
|
"use strict";
|
|
3572
3769
|
init_views();
|
|
3770
|
+
init_sampling();
|
|
3573
3771
|
init_reconstruct();
|
|
3574
3772
|
init_export();
|
|
3575
3773
|
init_project();
|
|
@@ -3581,20 +3779,1061 @@ var init_src = __esm({
|
|
|
3581
3779
|
}
|
|
3582
3780
|
});
|
|
3583
3781
|
|
|
3782
|
+
// apps/cli/src/verification-gate.ts
|
|
3783
|
+
import { createHash } from "node:crypto";
|
|
3784
|
+
import { readFile } from "node:fs/promises";
|
|
3785
|
+
import { dirname, join } from "node:path";
|
|
3786
|
+
function sha256(bytes) {
|
|
3787
|
+
return createHash("sha256").update(bytes).digest("hex");
|
|
3788
|
+
}
|
|
3789
|
+
function viewFingerprint(view) {
|
|
3790
|
+
const data = new Uint8Array(view.data);
|
|
3791
|
+
for (let i2 = 0; i2 < data.length; i2 += 4) {
|
|
3792
|
+
if (data[i2 + 3] < 128) data.fill(0, i2, i2 + 4);
|
|
3793
|
+
}
|
|
3794
|
+
return createHash("sha256").update(view.width + "x" + view.height + ":").update(data).digest("hex");
|
|
3795
|
+
}
|
|
3796
|
+
async function requireVerifiedViews(reportPath, views, sourceHashes) {
|
|
3797
|
+
const report = JSON.parse(await readFile(reportPath, "utf8"));
|
|
3798
|
+
const acceptance = report?.acceptance;
|
|
3799
|
+
if (report?.kind !== "atlas" || acceptance?.version !== 1 || acceptance.verdict !== "PASS" || !requiredChecks.every((name) => acceptance.checks?.[name]?.verdict === "PASS")) {
|
|
3800
|
+
throw new Error("Build requires a PASS report from a full stack3 verify run.");
|
|
3801
|
+
}
|
|
3802
|
+
const viewEntries = Object.entries(views);
|
|
3803
|
+
if (Object.keys(acceptance.inputs ?? {}).length !== viewEntries.length) {
|
|
3804
|
+
throw new Error("Verification does not match the current set of atlas views. Verify the build inputs again.");
|
|
3805
|
+
}
|
|
3806
|
+
const guide = acceptance.checks.cameras;
|
|
3807
|
+
const overlay = guide.overlay === "atlas-guides.png" ? await readFile(join(dirname(reportPath), guide.overlay)).catch((error) => {
|
|
3808
|
+
if (error.code !== "ENOENT") throw error;
|
|
3809
|
+
}) : void 0;
|
|
3810
|
+
if (!overlay || guide.overlaySha256 !== sha256(overlay)) {
|
|
3811
|
+
throw new Error("Verification guide is missing or stale. Regenerate the report with --output-dir.");
|
|
3812
|
+
}
|
|
3813
|
+
for (const [name, view] of viewEntries) {
|
|
3814
|
+
const input = acceptance.inputs?.[name];
|
|
3815
|
+
if (input?.sourceSha256 !== sourceHashes.get(name) || input?.viewSha256 !== viewFingerprint(view)) {
|
|
3816
|
+
throw new Error("Verification does not match the current " + name.toUpperCase() + " input and mask. Verify the build inputs again.");
|
|
3817
|
+
}
|
|
3818
|
+
}
|
|
3819
|
+
}
|
|
3820
|
+
var requiredChecks;
|
|
3821
|
+
var init_verification_gate = __esm({
|
|
3822
|
+
"apps/cli/src/verification-gate.ts"() {
|
|
3823
|
+
"use strict";
|
|
3824
|
+
requiredChecks = ["dimensions", "cameras", "projections", "landmarks"];
|
|
3825
|
+
}
|
|
3826
|
+
});
|
|
3827
|
+
|
|
3828
|
+
// apps/cli/src/atlas-input.ts
|
|
3829
|
+
import { readFile as readFile2 } from "node:fs/promises";
|
|
3830
|
+
import { dirname as dirname2, extname, resolve } from "node:path";
|
|
3831
|
+
import { PNG } from "pngjs";
|
|
3832
|
+
async function png(path, onRead) {
|
|
3833
|
+
const bytes = await readFile2(path);
|
|
3834
|
+
if (onRead) onRead(sha256(bytes));
|
|
3835
|
+
readPngSize(bytes);
|
|
3836
|
+
const image = PNG.sync.read(bytes);
|
|
3837
|
+
return { width: image.width, height: image.height, data: image.data };
|
|
3838
|
+
}
|
|
3839
|
+
async function readInput(path, layout, threshold, hashes) {
|
|
3840
|
+
if (extname(path).toLowerCase() === ".png") {
|
|
3841
|
+
if (!layout) throw new Error("A PNG atlas needs an explicit --layout.");
|
|
3842
|
+
const directions = parseLayout(layout);
|
|
3843
|
+
const image = await png(path, hashes && ((hash) => directions.forEach((name) => hashes.set(name, hash))));
|
|
3844
|
+
return splitAtlas(image, directions, threshold);
|
|
3845
|
+
}
|
|
3846
|
+
if (extname(path).toLowerCase() !== ".json") throw new Error("Choose a PNG atlas or a JSON view manifest.");
|
|
3847
|
+
if (layout) throw new Error("View manifests define their directions in the views field.");
|
|
3848
|
+
const manifest = JSON.parse(await readFile2(path, "utf8"));
|
|
3849
|
+
const views = manifest && typeof manifest === "object" && "views" in manifest ? manifest.views : null;
|
|
3850
|
+
if (!views || typeof views !== "object" || Array.isArray(views)) throw new Error("The manifest needs a views object.");
|
|
3851
|
+
const entries = Object.entries(views);
|
|
3852
|
+
parseLayout(entries.map(([name]) => name).join(","));
|
|
3853
|
+
return Object.fromEntries(await Promise.all(entries.map(async ([name, file]) => {
|
|
3854
|
+
if (!DIRECTIONS.includes(name) || typeof file !== "string" || !file) throw new Error(`Invalid view entry: ${name}`);
|
|
3855
|
+
return [name, await png(resolve(dirname2(path), file), hashes && ((hash) => hashes.set(name, hash)))];
|
|
3856
|
+
})));
|
|
3857
|
+
}
|
|
3858
|
+
var init_atlas_input = __esm({
|
|
3859
|
+
"apps/cli/src/atlas-input.ts"() {
|
|
3860
|
+
"use strict";
|
|
3861
|
+
init_src();
|
|
3862
|
+
init_verification_gate();
|
|
3863
|
+
}
|
|
3864
|
+
});
|
|
3865
|
+
|
|
3866
|
+
// apps/cli/src/grid-build.ts
|
|
3867
|
+
import { totalmem } from "node:os";
|
|
3868
|
+
function buildFromPreparedViews(views, target, settings) {
|
|
3869
|
+
if (target === "stack" || settings.meshMethod !== "contour") {
|
|
3870
|
+
const { width, depth, layers } = reconstructionDimensions(views, settings);
|
|
3871
|
+
const { nativeSamples } = inspectViews(views);
|
|
3872
|
+
if (width > nativeSamples.x || depth > nativeSamples.y || layers > nativeSamples.z) {
|
|
3873
|
+
console.error(`Sampling ${width} \xD7 ${depth} \xD7 ${layers} from up to ${nativeSamples.x} \xD7 ${nativeSamples.y} \xD7 ${nativeSamples.z} source pixels along X, Y, Z. Oversampled axes reuse input pixels.`);
|
|
3874
|
+
}
|
|
3875
|
+
checkGridMemory(width, depth, layers, target);
|
|
3876
|
+
}
|
|
3877
|
+
return reconstructPrepared(views, target, settings);
|
|
3878
|
+
}
|
|
3879
|
+
function checkGridMemory(width, depth, layers, target) {
|
|
3880
|
+
const cells = width * depth * layers;
|
|
3881
|
+
const bytes = target === "stack" ? cells * 5 : cells + (width + 2) * (depth + 2) * (layers + 2) * 17;
|
|
3882
|
+
const budget = Math.min(totalmem(), process.constrainedMemory() || Infinity);
|
|
3883
|
+
if (bytes > budget) {
|
|
3884
|
+
throw new Error(`Grid ${width} \xD7 ${depth} \xD7 ${layers} needs at least ${Math.ceil(bytes / 2 ** 20)} MiB, exceeding the system memory budget. Reduce layers or resolution.`);
|
|
3885
|
+
}
|
|
3886
|
+
}
|
|
3887
|
+
var init_grid_build = __esm({
|
|
3888
|
+
"apps/cli/src/grid-build.ts"() {
|
|
3889
|
+
"use strict";
|
|
3890
|
+
init_src();
|
|
3891
|
+
}
|
|
3892
|
+
});
|
|
3893
|
+
|
|
3894
|
+
// apps/cli/src/blender.ts
|
|
3895
|
+
var blender_exports = {};
|
|
3896
|
+
__export(blender_exports, {
|
|
3897
|
+
blenderExecutable: () => blenderExecutable,
|
|
3898
|
+
openBlenderStack: () => openBlenderStack
|
|
3899
|
+
});
|
|
3900
|
+
import { execFile, spawn } from "node:child_process";
|
|
3901
|
+
import { existsSync } from "node:fs";
|
|
3902
|
+
import { link, mkdir, mkdtemp, rm } from "node:fs/promises";
|
|
3903
|
+
import { tmpdir } from "node:os";
|
|
3904
|
+
import { basename, dirname as dirname3, extname as extname2, join as join2, resolve as resolve2 } from "node:path";
|
|
3905
|
+
import { fileURLToPath } from "node:url";
|
|
3906
|
+
import { promisify } from "node:util";
|
|
3907
|
+
function blenderExecutable() {
|
|
3908
|
+
const macApp = "/Applications/Blender.app/Contents/MacOS/Blender";
|
|
3909
|
+
return process.env.BLENDER_BIN || (process.platform === "darwin" && existsSync(macApp) ? macApp : "blender");
|
|
3910
|
+
}
|
|
3911
|
+
async function openBlenderStack(directory2, output, open2) {
|
|
3912
|
+
const blender = blenderExecutable();
|
|
3913
|
+
const script = fileURLToPath(new URL("../blender/import_stack.py", import.meta.url));
|
|
3914
|
+
const destination = output && resolve2(output);
|
|
3915
|
+
if (destination && extname2(destination).toLowerCase() !== ".blend") throw new Error("Use a .blend output file.");
|
|
3916
|
+
if (destination && existsSync(destination)) throw new Error("Output already exists: " + destination);
|
|
3917
|
+
if (destination) await mkdir(dirname3(destination), { recursive: true });
|
|
3918
|
+
const scratch = await mkdtemp(join2(destination ? dirname3(destination) : tmpdir(), "stack3-blender-"));
|
|
3919
|
+
const generated = join2(scratch, (basename(directory2) || "stack") + ".blend");
|
|
3920
|
+
const scene = destination || generated;
|
|
3921
|
+
let keepPreview = false;
|
|
3922
|
+
try {
|
|
3923
|
+
await promisify(execFile)(blender, ["-b", "--factory-startup", "--python-exit-code", "1", "-P", script, "--", directory2, generated]);
|
|
3924
|
+
if (destination) await link(generated, destination);
|
|
3925
|
+
console.log("Blender scene " + scene);
|
|
3926
|
+
if (open2) {
|
|
3927
|
+
const child = spawn(blender, [scene], { detached: true, stdio: "ignore" });
|
|
3928
|
+
await new Promise((ok, fail) => {
|
|
3929
|
+
child.once("error", fail);
|
|
3930
|
+
child.once("spawn", ok);
|
|
3931
|
+
});
|
|
3932
|
+
child.unref();
|
|
3933
|
+
}
|
|
3934
|
+
keepPreview = !destination;
|
|
3935
|
+
} catch (error) {
|
|
3936
|
+
if (error.code === "ENOENT" && error.path === blender) {
|
|
3937
|
+
throw new Error("Blender was not found. Set BLENDER_BIN to its executable, or use stack3 view --web.");
|
|
3938
|
+
}
|
|
3939
|
+
throw error;
|
|
3940
|
+
} finally {
|
|
3941
|
+
if (!keepPreview) await rm(scratch, { recursive: true, force: true });
|
|
3942
|
+
}
|
|
3943
|
+
}
|
|
3944
|
+
var init_blender = __esm({
|
|
3945
|
+
"apps/cli/src/blender.ts"() {
|
|
3946
|
+
"use strict";
|
|
3947
|
+
}
|
|
3948
|
+
});
|
|
3949
|
+
|
|
3950
|
+
// apps/cli/src/part-mesh.ts
|
|
3951
|
+
import { execFile as execFile2 } from "node:child_process";
|
|
3952
|
+
import { mkdtemp as mkdtemp2, readFile as readFile3, rm as rm2, writeFile } from "node:fs/promises";
|
|
3953
|
+
import { tmpdir as tmpdir2 } from "node:os";
|
|
3954
|
+
import { dirname as dirname4, join as join3, resolve as resolve3 } from "node:path";
|
|
3955
|
+
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
3956
|
+
import { promisify as promisify2 } from "node:util";
|
|
3957
|
+
function isCoreMeshMethod(method) {
|
|
3958
|
+
return method === "marching-cubes" || method === "surface-nets" || method === "voxel";
|
|
3959
|
+
}
|
|
3960
|
+
function isStackMeshMethod(method) {
|
|
3961
|
+
return isCoreMeshMethod(method) || partMethods.some((name) => name === method);
|
|
3962
|
+
}
|
|
3963
|
+
async function readStackMesh(stack, method, guide, finish) {
|
|
3964
|
+
checkGridMemory(stack.width, stack.depth, stack.layers, "mesh");
|
|
3965
|
+
if (finish && isCoreMeshMethod(method)) throw new Error("Surface finishing needs a Python mesh method, such as hermite-dc or mc33.");
|
|
3966
|
+
return isCoreMeshMethod(method) ? meshFromStack(stack, method) : partMesh(stack, method, guide, finish);
|
|
3967
|
+
}
|
|
3968
|
+
async function partMesh(stack, method, guidePath, finish) {
|
|
3969
|
+
const guide = guidePath ? JSON.parse(await readFile3(guidePath, "utf8")) : {};
|
|
3970
|
+
const { width, depth, layers, columns: columns2, spacing, pivot } = stack;
|
|
3971
|
+
const size = [stack.size[0], stack.size[1], layers * spacing];
|
|
3972
|
+
const temporary = await mkdtemp2(join3(tmpdir2(), "stack3-part-"));
|
|
3973
|
+
try {
|
|
3974
|
+
await Promise.all([
|
|
3975
|
+
writeFile(join3(temporary, "stack.rgba"), stack.texture.data),
|
|
3976
|
+
writeFile(join3(temporary, "input.json"), JSON.stringify({
|
|
3977
|
+
width,
|
|
3978
|
+
depth,
|
|
3979
|
+
layers,
|
|
3980
|
+
columns: columns2,
|
|
3981
|
+
size,
|
|
3982
|
+
pivot,
|
|
3983
|
+
guide,
|
|
3984
|
+
guideDirectory: guidePath && dirname4(resolve3(guidePath)),
|
|
3985
|
+
finish,
|
|
3986
|
+
blender: finish && blenderExecutable()
|
|
3987
|
+
}))
|
|
3988
|
+
]);
|
|
3989
|
+
const scriptName = method === "signed-distance-dc" ? "signed_distance.py" : "mesh.py";
|
|
3990
|
+
const script = fileURLToPath2(new URL("../meshing/" + scriptName, import.meta.url));
|
|
3991
|
+
const python = process.env.STACK3_PYTHON;
|
|
3992
|
+
const args = python ? [script] : ["run", "--no-project", "--script", script];
|
|
3993
|
+
try {
|
|
3994
|
+
const { stdout } = await promisify2(execFile2)(
|
|
3995
|
+
python || "uv",
|
|
3996
|
+
[...args, method, temporary],
|
|
3997
|
+
{ env: { ...process.env, PYTHONDONTWRITEBYTECODE: "1" } }
|
|
3998
|
+
);
|
|
3999
|
+
if (stdout.trim()) console.error(stdout.trim());
|
|
4000
|
+
} catch (error) {
|
|
4001
|
+
const e = error;
|
|
4002
|
+
throw new Error(e.code === "ENOENT" ? "Install uv or set STACK3_PYTHON to a Python environment with the meshing dependencies." : e.stderr?.trim() || e.message);
|
|
4003
|
+
}
|
|
4004
|
+
const read = async (name) => {
|
|
4005
|
+
const bytes = await readFile3(join3(temporary, name));
|
|
4006
|
+
return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
|
|
4007
|
+
};
|
|
4008
|
+
const [positions, normals, uvs, indices, pixels, metadata] = await Promise.all(
|
|
4009
|
+
["positions", "normals", "uvs", "indices", "texture", "output.json"].map(read)
|
|
4010
|
+
);
|
|
4011
|
+
const dims = JSON.parse(new TextDecoder().decode(metadata));
|
|
4012
|
+
const colors = dims.colors ? new Float32Array(await read("colors")) : void 0;
|
|
4013
|
+
return {
|
|
4014
|
+
target: "mesh",
|
|
4015
|
+
size,
|
|
4016
|
+
pivot,
|
|
4017
|
+
positions: new Float32Array(positions),
|
|
4018
|
+
normals: new Float32Array(normals),
|
|
4019
|
+
uvs: new Float32Array(uvs),
|
|
4020
|
+
indices: new Uint32Array(indices),
|
|
4021
|
+
...colors && { colors },
|
|
4022
|
+
texture: {
|
|
4023
|
+
width: dims.width,
|
|
4024
|
+
height: dims.height,
|
|
4025
|
+
data: new Uint8Array(pixels)
|
|
4026
|
+
},
|
|
4027
|
+
nearestTexture: method === "greedy" || method === "monotone"
|
|
4028
|
+
};
|
|
4029
|
+
} finally {
|
|
4030
|
+
await rm2(temporary, { recursive: true, force: true });
|
|
4031
|
+
}
|
|
4032
|
+
}
|
|
4033
|
+
var partMethods;
|
|
4034
|
+
var init_part_mesh = __esm({
|
|
4035
|
+
"apps/cli/src/part-mesh.ts"() {
|
|
4036
|
+
"use strict";
|
|
4037
|
+
init_src();
|
|
4038
|
+
init_grid_build();
|
|
4039
|
+
init_blender();
|
|
4040
|
+
partMethods = [
|
|
4041
|
+
"section-loft",
|
|
4042
|
+
"heightfield",
|
|
4043
|
+
"smooth-loft",
|
|
4044
|
+
"revolve",
|
|
4045
|
+
"extended-mc",
|
|
4046
|
+
"hermite-dc",
|
|
4047
|
+
"mc33",
|
|
4048
|
+
"branch-loft",
|
|
4049
|
+
"path-sweep",
|
|
4050
|
+
"section-network",
|
|
4051
|
+
"greedy",
|
|
4052
|
+
"monotone",
|
|
4053
|
+
"signed-distance-dc"
|
|
4054
|
+
];
|
|
4055
|
+
}
|
|
4056
|
+
});
|
|
4057
|
+
|
|
4058
|
+
// apps/cli/src/stack-input.ts
|
|
4059
|
+
import { readFile as readFile4 } from "node:fs/promises";
|
|
4060
|
+
import { join as join4 } from "node:path";
|
|
4061
|
+
import { PNG as PNG2 } from "pngjs";
|
|
4062
|
+
async function loadStack(directory2) {
|
|
4063
|
+
const [metadata, png2] = await Promise.all([
|
|
4064
|
+
readFile4(join4(directory2, "stack.json"), "utf8"),
|
|
4065
|
+
readFile4(join4(directory2, "stack.png"))
|
|
4066
|
+
]);
|
|
4067
|
+
const manifest = JSON.parse(metadata);
|
|
4068
|
+
readStackPngSize(png2, manifest);
|
|
4069
|
+
const stack = readStackBundle(manifest, PNG2.sync.read(png2));
|
|
4070
|
+
return { metadata, png: png2, stack };
|
|
4071
|
+
}
|
|
4072
|
+
var init_stack_input = __esm({
|
|
4073
|
+
"apps/cli/src/stack-input.ts"() {
|
|
4074
|
+
"use strict";
|
|
4075
|
+
init_src();
|
|
4076
|
+
}
|
|
4077
|
+
});
|
|
4078
|
+
|
|
4079
|
+
// apps/cli/src/build-cache.ts
|
|
4080
|
+
import { createHash as createHash2, randomUUID } from "node:crypto";
|
|
4081
|
+
import { mkdir as mkdir2, readdir, readFile as readFile5, rename, stat, unlink, writeFile as writeFile2 } from "node:fs/promises";
|
|
4082
|
+
import { homedir } from "node:os";
|
|
4083
|
+
import { join as join5, resolve as resolve4 } from "node:path";
|
|
4084
|
+
import { deserialize, serialize } from "node:v8";
|
|
4085
|
+
async function readCache(key) {
|
|
4086
|
+
try {
|
|
4087
|
+
return deserialize(await readFile5(join5(directory, key + ".cache")));
|
|
4088
|
+
} catch {
|
|
4089
|
+
}
|
|
4090
|
+
}
|
|
4091
|
+
function buildCacheKey(views, format, settings, spacing) {
|
|
4092
|
+
const hash = createHash2("sha256");
|
|
4093
|
+
hash.update(JSON.stringify([version, format, settings, spacing]));
|
|
4094
|
+
for (const direction of DIRECTIONS) {
|
|
4095
|
+
const view = views[direction];
|
|
4096
|
+
if (!view) continue;
|
|
4097
|
+
hash.update(JSON.stringify([direction, view.width, view.height]));
|
|
4098
|
+
hash.update(view.data);
|
|
4099
|
+
}
|
|
4100
|
+
return hash.digest("hex");
|
|
4101
|
+
}
|
|
4102
|
+
async function readBuildCache(key, format) {
|
|
4103
|
+
const data = await readCache(key);
|
|
4104
|
+
if (data?.format !== format) return;
|
|
4105
|
+
if (data.format === "glb" ? data.bytes instanceof Uint8Array : data.png instanceof Uint8Array && typeof data.manifest === "string") return data;
|
|
4106
|
+
}
|
|
4107
|
+
async function readSurfaceCache(key) {
|
|
4108
|
+
const data = await readCache(key);
|
|
4109
|
+
if (data?.format === "surface" && data.mesh?.positions instanceof Float32Array && data.mesh.indices instanceof Uint32Array) return data.mesh;
|
|
4110
|
+
}
|
|
4111
|
+
async function writeBuildCache(key, output) {
|
|
4112
|
+
const temporary = join5(directory, randomUUID() + ".tmp");
|
|
4113
|
+
try {
|
|
4114
|
+
await mkdir2(directory, { recursive: true });
|
|
4115
|
+
await writeFile2(temporary, serialize(output), { flag: "wx" });
|
|
4116
|
+
await rename(temporary, join5(directory, key + ".cache"));
|
|
4117
|
+
const entries = (await readdir(directory)).filter((name) => /^[0-9a-f]{64}\.cache$/.test(name));
|
|
4118
|
+
if (entries.length <= 12) return;
|
|
4119
|
+
const dated = await Promise.all(entries.map(async (name) => ({ name, time: (await stat(join5(directory, name))).mtimeMs })));
|
|
4120
|
+
await Promise.all(dated.sort((a, b) => b.time - a.time).slice(12).map(({ name }) => unlink(join5(directory, name))));
|
|
4121
|
+
} catch {
|
|
4122
|
+
await unlink(temporary).catch(() => {
|
|
4123
|
+
});
|
|
4124
|
+
}
|
|
4125
|
+
}
|
|
4126
|
+
var version, directory;
|
|
4127
|
+
var init_build_cache = __esm({
|
|
4128
|
+
"apps/cli/src/build-cache.ts"() {
|
|
4129
|
+
"use strict";
|
|
4130
|
+
init_src();
|
|
4131
|
+
version = "render-data-4";
|
|
4132
|
+
directory = process.env.STACK3_CACHE_DIR ? resolve4(process.env.STACK3_CACHE_DIR) : join5(process.env.XDG_CACHE_HOME || join5(homedir(), ".cache"), "stack3", version);
|
|
4133
|
+
}
|
|
4134
|
+
});
|
|
4135
|
+
|
|
4136
|
+
// apps/cli/src/capabilities.ts
|
|
4137
|
+
var capabilities_exports = {};
|
|
4138
|
+
__export(capabilities_exports, {
|
|
4139
|
+
capabilitiesCommand: () => capabilitiesCommand,
|
|
4140
|
+
printPipelineSchema: () => printPipelineSchema
|
|
4141
|
+
});
|
|
4142
|
+
import { existsSync as existsSync2 } from "node:fs";
|
|
4143
|
+
import { readFile as readFile6 } from "node:fs/promises";
|
|
4144
|
+
import { fileURLToPath as fileURLToPath3 } from "node:url";
|
|
4145
|
+
import { parseArgs } from "node:util";
|
|
4146
|
+
async function printPipelineSchema(kind) {
|
|
4147
|
+
if (kind !== "recipe" && kind !== "fragment") throw new Error("Use stack3 pipeline schema [recipe|fragment].");
|
|
4148
|
+
const recipe = await readFile6(schemaFiles.recipe, "utf8");
|
|
4149
|
+
if (kind === "recipe") {
|
|
4150
|
+
process.stdout.write(recipe);
|
|
4151
|
+
return;
|
|
4152
|
+
}
|
|
4153
|
+
const fragment = JSON.parse(await readFile6(schemaFiles.fragment, "utf8"));
|
|
4154
|
+
const definitions = JSON.parse(recipe).$defs;
|
|
4155
|
+
process.stdout.write(JSON.stringify({ ...fragment, $ref: "#/$defs/manifest", $defs: definitions }, null, 2) + "\n");
|
|
4156
|
+
}
|
|
4157
|
+
function sampleRoot() {
|
|
4158
|
+
const packaged = new URL("../references/hard-surface/", import.meta.url);
|
|
4159
|
+
return existsSync2(packaged) ? packaged : new URL("../../../skills/stack3/references/hard-surface/", import.meta.url);
|
|
4160
|
+
}
|
|
4161
|
+
function catalog() {
|
|
4162
|
+
const root = sampleRoot();
|
|
4163
|
+
return {
|
|
4164
|
+
version: 1,
|
|
4165
|
+
pipeline: {
|
|
4166
|
+
commands: { render: "stack3 pipeline render", run: "stack3 pipeline run", schema: "stack3 pipeline schema [recipe|fragment]" },
|
|
4167
|
+
nodes: {
|
|
4168
|
+
"load-stack": { output: "stack", backend: "node" },
|
|
4169
|
+
"reconstruct-stack": { output: "stack", backend: "node" },
|
|
4170
|
+
"extract-mesh": { input: "stack", output: "mesh", backend: "selected by method and finish options" },
|
|
4171
|
+
"write-glb": { input: "mesh", output: "glb", backend: "node" }
|
|
4172
|
+
},
|
|
4173
|
+
schemas: Object.fromEntries(Object.entries(schemaFiles).map(([kind, file]) => [kind, fileURLToPath3(file)]))
|
|
4174
|
+
},
|
|
4175
|
+
meshMethods: stackMethods.map((id) => ({
|
|
4176
|
+
id,
|
|
4177
|
+
backend: isCoreMeshMethod(id) ? "node" : "python",
|
|
4178
|
+
supportsFinish: !isCoreMeshMethod(id),
|
|
4179
|
+
...meshInfo[id],
|
|
4180
|
+
...id === "signed-distance-dc" && { dependencies: ["gpytoolbox"] }
|
|
4181
|
+
})),
|
|
4182
|
+
stages,
|
|
4183
|
+
samples: samples.map(({ id, path, backends }) => ({ id, path: fileURLToPath3(new URL(path, root)), backends })),
|
|
4184
|
+
backendConfiguration: { python: "uv or STACK3_PYTHON", blender: "Blender executable or BLENDER_BIN" }
|
|
4185
|
+
};
|
|
4186
|
+
}
|
|
4187
|
+
function capabilitiesCommand(args) {
|
|
4188
|
+
const { values } = parseArgs({ args, options: { json: { type: "boolean" }, help: { type: "boolean", short: "h" } } });
|
|
4189
|
+
if (values.help) {
|
|
4190
|
+
console.log(help);
|
|
4191
|
+
return;
|
|
4192
|
+
}
|
|
4193
|
+
const data = catalog();
|
|
4194
|
+
if (values.json) {
|
|
4195
|
+
process.stdout.write(JSON.stringify(data, null, 2) + "\n");
|
|
4196
|
+
return;
|
|
4197
|
+
}
|
|
4198
|
+
console.log(help);
|
|
4199
|
+
console.log("\nPipeline nodes:", Object.keys(data.pipeline.nodes).join(", "));
|
|
4200
|
+
console.log("Mesh methods:", data.meshMethods.map(({ id }) => id).join(", "));
|
|
4201
|
+
console.log("\nGeometry and export stages");
|
|
4202
|
+
for (const { name, backend, options } of data.stages) console.log(` ${name} (${backend}) ${options.join(", ")}`);
|
|
4203
|
+
console.log("\nJSON Schemas");
|
|
4204
|
+
console.log(" stack3 pipeline schema recipe");
|
|
4205
|
+
console.log(" stack3 pipeline schema fragment");
|
|
4206
|
+
console.log("\nBundled recipes");
|
|
4207
|
+
for (const { id, path, backends } of data.samples) console.log(` ${id} (${backends.join(", ")})
|
|
4208
|
+
${path}`);
|
|
4209
|
+
}
|
|
4210
|
+
var schemaFiles, meshInfo, stackMethods, stages, samples, help;
|
|
4211
|
+
var init_capabilities = __esm({
|
|
4212
|
+
"apps/cli/src/capabilities.ts"() {
|
|
4213
|
+
"use strict";
|
|
4214
|
+
init_part_mesh();
|
|
4215
|
+
schemaFiles = {
|
|
4216
|
+
recipe: new URL("../schema/pipeline.schema.json", import.meta.url),
|
|
4217
|
+
fragment: new URL("../schema/pipeline-fragment.schema.json", import.meta.url)
|
|
4218
|
+
};
|
|
4219
|
+
meshInfo = {
|
|
4220
|
+
"marching-cubes": { description: "Default interpolated surface from saved occupancy.", guideFields: [] },
|
|
4221
|
+
"surface-nets": { description: "Averaged dual mesh for fast previews.", guideFields: [] },
|
|
4222
|
+
voxel: { description: "Exposed voxel faces.", guideFields: [] },
|
|
4223
|
+
"section-loft": { description: "Connect sections with linear interpolation.", guideFields: ["axis", "stations"] },
|
|
4224
|
+
heightfield: { description: "Build top and bottom surfaces along one axis.", guideFields: ["axis"] },
|
|
4225
|
+
"smooth-loft": { description: "Connect sections with smooth interpolation.", guideFields: ["axis", "stations"] },
|
|
4226
|
+
revolve: { description: "Revolve a sampled meridian.", guideFields: ["axis", "origin", "segments"] },
|
|
4227
|
+
"extended-mc": { description: "Marching Cubes with QEF feature vertices.", guideFields: [] },
|
|
4228
|
+
"hermite-dc": { description: "Dual Contouring with QEF from estimated or supplied Hermite data.", guideFields: ["field", "dexel"] },
|
|
4229
|
+
mc33: { description: "Topology-aware Marching Cubes for ambiguous configurations.", guideFields: [] },
|
|
4230
|
+
"branch-loft": { description: "Connect sections through branch and merge events.", guideFields: ["axis"] },
|
|
4231
|
+
"path-sweep": { description: "Sweep a section along a specified path.", guideFields: ["path", "up", "profile"] },
|
|
4232
|
+
"section-network": { description: "Reconstruct using independently measured sections.", guideFields: ["sections", "tolerance"] },
|
|
4233
|
+
greedy: { description: "Merge adjoining voxel faces into rectangles.", guideFields: [] },
|
|
4234
|
+
monotone: { description: "Triangulate merged voxel surface regions.", guideFields: [] },
|
|
4235
|
+
"signed-distance-dc": { description: "Carrera Dual Contouring of Signed Distance Data.", guideFields: ["field", "outerIterations", "innerIterations"] }
|
|
4236
|
+
};
|
|
4237
|
+
stackMethods = ["marching-cubes", "surface-nets", "voxel", ...partMethods];
|
|
4238
|
+
stages = [
|
|
4239
|
+
{
|
|
4240
|
+
name: "Voxel Reconstruction",
|
|
4241
|
+
options: ["reconstruct-stack", "load-stack"],
|
|
4242
|
+
backend: "node",
|
|
4243
|
+
description: "Carve occupancy from calibrated silhouettes or reopen saved RGBA slices."
|
|
4244
|
+
},
|
|
4245
|
+
{
|
|
4246
|
+
name: "SDF and Normal Estimation",
|
|
4247
|
+
options: ["hermite-dc", "signed-distance-dc"],
|
|
4248
|
+
backend: "python",
|
|
4249
|
+
description: "Estimate normals or distances from occupancy, or use aligned SDF samples in guide.field."
|
|
4250
|
+
},
|
|
4251
|
+
{
|
|
4252
|
+
name: "Triple-Dexel Hermite Data",
|
|
4253
|
+
options: ["guide.dexel", "hermite-dc"],
|
|
4254
|
+
backend: "python",
|
|
4255
|
+
description: "Use axis-aligned crossing positions and outward normals from a registered NPZ."
|
|
4256
|
+
},
|
|
4257
|
+
{
|
|
4258
|
+
name: "Feature Segmentation and Plane Fitting",
|
|
4259
|
+
options: ["fitTolerance"],
|
|
4260
|
+
backend: "python",
|
|
4261
|
+
description: "Group adjacent faces by normal and fit supported planes with SVD."
|
|
4262
|
+
},
|
|
4263
|
+
{
|
|
4264
|
+
name: "Primitive Fitting",
|
|
4265
|
+
options: ["fitTolerance", "primitives"],
|
|
4266
|
+
backend: "python",
|
|
4267
|
+
description: "Fit supported spherical and cylindrical patches."
|
|
4268
|
+
},
|
|
4269
|
+
{
|
|
4270
|
+
name: "Feature Boundary Stitching",
|
|
4271
|
+
options: ["fitTolerance"],
|
|
4272
|
+
backend: "python",
|
|
4273
|
+
description: "Solve shared boundary vertices together while fitting patches."
|
|
4274
|
+
},
|
|
4275
|
+
{
|
|
4276
|
+
name: "Guided Geometry Regularization",
|
|
4277
|
+
options: ["regularization.tolerance", "regularization.features", "regularization.relations"],
|
|
4278
|
+
backend: "python",
|
|
4279
|
+
description: "Fit selected planes, rim circles, fixed-axis cylinders and polygons. Jointly optimize explicit plane relations."
|
|
4280
|
+
},
|
|
4281
|
+
{
|
|
4282
|
+
name: "Procedural Bevel",
|
|
4283
|
+
options: ["bevelWidth", "bevelSegments"],
|
|
4284
|
+
backend: "blender",
|
|
4285
|
+
description: "Bevel eligible edges in headless Blender."
|
|
4286
|
+
},
|
|
4287
|
+
{
|
|
4288
|
+
name: "Selective Rim Bevel after QEM",
|
|
4289
|
+
options: ["lodBevel.preTriangleBudget", "lodBevel.rims", "triangleBudget", "bevelWidth", "bevelSegments"],
|
|
4290
|
+
backend: "blender",
|
|
4291
|
+
description: "Reserve triangles with QEM, bevel specified circular rims, and verify the final budget and closed topology."
|
|
4292
|
+
},
|
|
4293
|
+
{
|
|
4294
|
+
name: "Mesh Optimization and LOD",
|
|
4295
|
+
options: ["dissolveAngle", "triangleBudget"],
|
|
4296
|
+
backend: "blender",
|
|
4297
|
+
description: "Apply planar dissolve and QEM with topology checks. Use separate branches for LODs."
|
|
4298
|
+
},
|
|
4299
|
+
{
|
|
4300
|
+
name: "Multi-view Texture Projection",
|
|
4301
|
+
options: ["extract-mesh"],
|
|
4302
|
+
backend: "node or python",
|
|
4303
|
+
description: "Project saved RGB from stack views onto the extracted surface."
|
|
4304
|
+
},
|
|
4305
|
+
{
|
|
4306
|
+
name: "Weighted Normals",
|
|
4307
|
+
options: ["extract-mesh", "finish"],
|
|
4308
|
+
backend: "python",
|
|
4309
|
+
description: "Use area-weighted normal accumulation and split hard creases for hard-surface outputs."
|
|
4310
|
+
},
|
|
4311
|
+
{
|
|
4312
|
+
name: "Ambient Occlusion",
|
|
4313
|
+
options: ["aoRadius"],
|
|
4314
|
+
backend: "blender",
|
|
4315
|
+
description: "Bake vertex AO for GLB COLOR_0."
|
|
4316
|
+
},
|
|
4317
|
+
{
|
|
4318
|
+
name: "GLB Export and GPU Instancing",
|
|
4319
|
+
options: ["write-glb", "lit", "instances"],
|
|
4320
|
+
backend: "node",
|
|
4321
|
+
description: "Write GLB and optional per-instance translations."
|
|
4322
|
+
}
|
|
4323
|
+
];
|
|
4324
|
+
samples = [
|
|
4325
|
+
{ id: "atlas-preview", path: "atlas/preview.pipeline.yaml", backends: ["node"] },
|
|
4326
|
+
{ id: "finish-lod", path: "finishing/finish-lod.pipeline.yaml", backends: ["node", "python", "blender"] },
|
|
4327
|
+
{ id: "guided-regularization", path: "finishing/regularize.pipeline.yaml", backends: ["node", "python"] },
|
|
4328
|
+
{ id: "benchmark-beveled-lod", path: "case-studies/benchmark/lod-bevel.pipeline.yaml", backends: ["node", "python", "blender"] },
|
|
4329
|
+
{ id: "triple-dexel", path: "measured-depth/triple-dexel/compare.pipeline.yaml", backends: ["node", "python"] },
|
|
4330
|
+
{ id: "signed-distance", path: "measured-depth/sdf/compare.pipeline.yaml", backends: ["node", "python", "gpytoolbox"] }
|
|
4331
|
+
];
|
|
4332
|
+
help = "Usage: stack3 capabilities [--json]\nList pipeline nodes, mesh methods, backends, schemas and runnable samples.";
|
|
4333
|
+
}
|
|
4334
|
+
});
|
|
4335
|
+
|
|
4336
|
+
// apps/cli/src/pipeline.ts
|
|
4337
|
+
var pipeline_exports = {};
|
|
4338
|
+
__export(pipeline_exports, {
|
|
4339
|
+
pipelineCommand: () => pipelineCommand
|
|
4340
|
+
});
|
|
4341
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
4342
|
+
import { mkdir as mkdir3, readFile as readFile7, realpath, writeFile as writeFile3 } from "node:fs/promises";
|
|
4343
|
+
import { dirname as dirname5, extname as extname3, resolve as resolve5 } from "node:path";
|
|
4344
|
+
import { parseArgs as parseArgs2 } from "node:util";
|
|
4345
|
+
import { parse, stringify } from "yaml";
|
|
4346
|
+
function isMapping(value) {
|
|
4347
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
4348
|
+
}
|
|
4349
|
+
function mapping(value, name, fields) {
|
|
4350
|
+
if (!isMapping(value)) throw new Error(`${name} must be a mapping.`);
|
|
4351
|
+
const invalid = fields && Object.keys(value).find((key) => !fields.includes(key));
|
|
4352
|
+
if (invalid) throw new Error(`${name} has unknown field ${invalid}.`);
|
|
4353
|
+
return value;
|
|
4354
|
+
}
|
|
4355
|
+
function requiredText(value, name) {
|
|
4356
|
+
if (typeof value !== "string" || !value.trim()) throw new Error(`${name} must be a nonempty string.`);
|
|
4357
|
+
return value;
|
|
4358
|
+
}
|
|
4359
|
+
async function readYaml(path) {
|
|
4360
|
+
try {
|
|
4361
|
+
return parse(await readFile7(path, "utf8"), { maxAliasCount: 0 });
|
|
4362
|
+
} catch (error) {
|
|
4363
|
+
throw new Error(`${path}: ${error.message}`);
|
|
4364
|
+
}
|
|
4365
|
+
}
|
|
4366
|
+
function mergeValues(base, overrides) {
|
|
4367
|
+
const merged = { ...base, ...overrides };
|
|
4368
|
+
for (const [key, value] of Object.entries(overrides)) {
|
|
4369
|
+
if (Object.hasOwn(base, key) && isMapping(base[key]) && isMapping(value)) {
|
|
4370
|
+
Object.defineProperty(merged, key, { value: mergeValues(base[key], value) });
|
|
4371
|
+
}
|
|
4372
|
+
}
|
|
4373
|
+
return merged;
|
|
4374
|
+
}
|
|
4375
|
+
function renderValue(value, values, name) {
|
|
4376
|
+
if (Array.isArray(value)) return value.map((entry, i2) => renderValue(entry, values, `${name}[${i2}]`));
|
|
4377
|
+
if (isMapping(value)) return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, renderValue(entry, values, `${name}.${key}`)]));
|
|
4378
|
+
if (typeof value !== "string" || !value.includes("{{")) return value;
|
|
4379
|
+
const reference = /\{\{\s*\.Values\.([\w-]+(?:\.[\w-]+)*)\s*\}\}/g;
|
|
4380
|
+
const get = (path) => {
|
|
4381
|
+
let current = values;
|
|
4382
|
+
for (const key of path.split(".")) {
|
|
4383
|
+
if (!isMapping(current) || !Object.hasOwn(current, key)) throw new Error(`${name}: missing .Values.${path}.`);
|
|
4384
|
+
current = current[key];
|
|
4385
|
+
}
|
|
4386
|
+
if (!["number", "string", "boolean"].includes(typeof current)) throw new Error(`${name}: .Values.${path} must be a scalar.`);
|
|
4387
|
+
return current;
|
|
4388
|
+
};
|
|
4389
|
+
const match = [...value.matchAll(reference)];
|
|
4390
|
+
if (value.replace(reference, "").includes("{{")) throw new Error(`${name}: use {{ .Values.name }} references.`);
|
|
4391
|
+
if (match.length === 1 && value.trim() === match[0][0]) return get(match[0][1]);
|
|
4392
|
+
return value.replace(reference, (_full, path) => String(get(path)));
|
|
4393
|
+
}
|
|
4394
|
+
function optionalBoolean(value, name) {
|
|
4395
|
+
if (value === void 0 || typeof value === "boolean") return value;
|
|
4396
|
+
throw new Error(`${name} must be a boolean.`);
|
|
4397
|
+
}
|
|
4398
|
+
function xyzPoint(value, label) {
|
|
4399
|
+
if (!Array.isArray(value) || value.length !== 3 || value.some((v) => typeof v !== "number" || !Number.isFinite(v))) {
|
|
4400
|
+
throw new Error(`${label} must be three finite XYZ numbers.`);
|
|
4401
|
+
}
|
|
4402
|
+
return [value[0], value[1], value[2]];
|
|
4403
|
+
}
|
|
4404
|
+
function parseRegularization(value, name) {
|
|
4405
|
+
const options = mapping(value, name, ["tolerance", "features", "relations"]);
|
|
4406
|
+
const { tolerance } = options;
|
|
4407
|
+
if (typeof tolerance !== "number" || !Number.isFinite(tolerance) || tolerance <= 0) throw new Error(`${name}.tolerance must be positive.`);
|
|
4408
|
+
if (!Array.isArray(options.features) || !options.features.length) throw new Error(`${name}.features must be a nonempty list.`);
|
|
4409
|
+
const features = options.features.map((value2, index) => {
|
|
4410
|
+
const label = `${name}.features[${index}]`;
|
|
4411
|
+
const entry = mapping(value2, label);
|
|
4412
|
+
const id = requiredText(entry.id, `${label}.id`);
|
|
4413
|
+
const fields = (...keys) => mapping(entry, label, ["id", "type", ...keys]);
|
|
4414
|
+
const direction = (key) => {
|
|
4415
|
+
const result = xyzPoint(entry[key], `${label}.${key}`);
|
|
4416
|
+
if (!Math.hypot(...result)) throw new Error(`${label}.${key} must be nonzero.`);
|
|
4417
|
+
return result;
|
|
4418
|
+
};
|
|
4419
|
+
const bounds2 = () => {
|
|
4420
|
+
if (!Array.isArray(entry.bounds) || entry.bounds.length !== 2) throw new Error(`${label}.bounds must contain minimum and maximum XYZ points.`);
|
|
4421
|
+
const minimum = xyzPoint(entry.bounds[0], `${label}.bounds[0]`), maximum = xyzPoint(entry.bounds[1], `${label}.bounds[1]`);
|
|
4422
|
+
if (minimum.some((v, i2) => v > maximum[i2])) throw new Error(`${label}.bounds minimum must not exceed maximum.`);
|
|
4423
|
+
return [minimum, maximum];
|
|
4424
|
+
};
|
|
4425
|
+
if (entry.type === "plane") {
|
|
4426
|
+
fields("normal", "bounds");
|
|
4427
|
+
return { id, type: entry.type, normal: direction("normal"), bounds: bounds2() };
|
|
4428
|
+
}
|
|
4429
|
+
if (entry.type === "circle" || entry.type === "cylinder") {
|
|
4430
|
+
fields("center", "axis", "radius", ...entry.type === "cylinder" ? ["bounds"] : []);
|
|
4431
|
+
const { radius } = entry;
|
|
4432
|
+
if (typeof radius !== "number" || !Number.isFinite(radius) || radius <= 0) throw new Error(`${label}.radius must be positive.`);
|
|
4433
|
+
const seed = { id, center: xyzPoint(entry.center, `${label}.center`), axis: direction("axis"), radius };
|
|
4434
|
+
return entry.type === "circle" ? { ...seed, type: "circle" } : { ...seed, type: "cylinder", bounds: bounds2() };
|
|
4435
|
+
}
|
|
4436
|
+
if (entry.type === "polygon") {
|
|
4437
|
+
fields("corners");
|
|
4438
|
+
if (!Array.isArray(entry.corners) || entry.corners.length < 3) throw new Error(`${label}.corners needs at least three ordered XYZ points.`);
|
|
4439
|
+
return { id, type: "polygon", corners: entry.corners.map((v, i2) => xyzPoint(v, `${label}.corners[${i2}]`)) };
|
|
4440
|
+
}
|
|
4441
|
+
throw new Error(`${label}.type must be plane, circle, cylinder or polygon.`);
|
|
4442
|
+
});
|
|
4443
|
+
const featureTypes = new Map(features.map(({ id, type }) => [id, type]));
|
|
4444
|
+
if (featureTypes.size !== features.length) throw new Error(`${name}.features has a duplicate id.`);
|
|
4445
|
+
const rawRelations = options.relations === void 0 ? [] : options.relations;
|
|
4446
|
+
if (!Array.isArray(rawRelations)) throw new Error(`${name}.relations must be a list.`);
|
|
4447
|
+
const relations = rawRelations.map((value2, i2) => {
|
|
4448
|
+
const label = `${name}.relations[${i2}]`;
|
|
4449
|
+
const relation = mapping(value2, label, ["type", "features"]);
|
|
4450
|
+
const { type, features: pair } = relation;
|
|
4451
|
+
if (type !== "parallel" && type !== "perpendicular" && type !== "coplanar") throw new Error(`${label}.type must be parallel, perpendicular or coplanar.`);
|
|
4452
|
+
if (!Array.isArray(pair) || pair.length !== 2 || pair[0] === pair[1] || pair.some((id) => featureTypes.get(id) !== "plane")) {
|
|
4453
|
+
throw new Error(`${label}.features must name two different plane features.`);
|
|
4454
|
+
}
|
|
4455
|
+
return { type, features: [pair[0], pair[1]] };
|
|
4456
|
+
});
|
|
4457
|
+
return { tolerance, features, relations };
|
|
4458
|
+
}
|
|
4459
|
+
function parseLodBevel(value, name, finalBudget) {
|
|
4460
|
+
const options = mapping(value, name, ["preTriangleBudget", "rims"]);
|
|
4461
|
+
const { preTriangleBudget } = options;
|
|
4462
|
+
if (typeof preTriangleBudget !== "number" || !Number.isSafeInteger(preTriangleBudget) || preTriangleBudget < 4 || preTriangleBudget >= finalBudget) {
|
|
4463
|
+
throw new Error(`${name}.preTriangleBudget must be an integer of at least 4 and lower than finish.triangleBudget.`);
|
|
4464
|
+
}
|
|
4465
|
+
if (!Array.isArray(options.rims) || !options.rims.length) throw new Error(`${name}.rims must be a nonempty list.`);
|
|
4466
|
+
const rims = options.rims.map((value2, i2) => {
|
|
4467
|
+
const label = `${name}.rims[${i2}]`;
|
|
4468
|
+
const rim = mapping(value2, label, ["id", "axis", "center", "radius", "radialTolerance", "axialTolerance"]);
|
|
4469
|
+
const { axis } = rim;
|
|
4470
|
+
if (axis !== "x" && axis !== "y" && axis !== "z") throw new Error(`${label}.axis must be x, y or z.`);
|
|
4471
|
+
const positive = (key) => {
|
|
4472
|
+
const n = rim[key];
|
|
4473
|
+
if (typeof n !== "number" || !Number.isFinite(n) || n <= 0) throw new Error(`${label}.${key} must be positive.`);
|
|
4474
|
+
return n;
|
|
4475
|
+
};
|
|
4476
|
+
return {
|
|
4477
|
+
id: requiredText(rim.id, `${label}.id`),
|
|
4478
|
+
axis,
|
|
4479
|
+
center: xyzPoint(rim.center, `${label}.center`),
|
|
4480
|
+
radius: positive("radius"),
|
|
4481
|
+
radialTolerance: positive("radialTolerance"),
|
|
4482
|
+
axialTolerance: positive("axialTolerance")
|
|
4483
|
+
};
|
|
4484
|
+
});
|
|
4485
|
+
if (new Set(rims.map((rim) => rim.id)).size !== rims.length) throw new Error(`${name}.rims has a duplicate id.`);
|
|
4486
|
+
return { preTriangleBudget, rims };
|
|
4487
|
+
}
|
|
4488
|
+
function parseFinish(value, id) {
|
|
4489
|
+
if (value === void 0) return;
|
|
4490
|
+
const limits = {
|
|
4491
|
+
fitTolerance: [0, Infinity],
|
|
4492
|
+
bevelWidth: [0, Infinity],
|
|
4493
|
+
bevelSegments: [0, 16],
|
|
4494
|
+
dissolveAngle: [0, 45],
|
|
4495
|
+
triangleBudget: [3, Infinity],
|
|
4496
|
+
aoRadius: [0, Infinity]
|
|
4497
|
+
};
|
|
4498
|
+
const config = mapping(value, `${id}.finish`, [...Object.keys(limits), "primitives", "regularization", "lodBevel"]);
|
|
4499
|
+
const output = {};
|
|
4500
|
+
for (const [key, [min, max2]] of Object.entries(limits)) {
|
|
4501
|
+
const number3 = config[key];
|
|
4502
|
+
if (number3 === void 0) continue;
|
|
4503
|
+
const integer = key === "bevelSegments" || key === "triangleBudget";
|
|
4504
|
+
if (typeof number3 !== "number" || !Number.isFinite(number3) || number3 <= min || number3 > max2 || integer && !Number.isSafeInteger(number3)) {
|
|
4505
|
+
throw new Error(`${id}.finish.${key} must be ${integer ? "an integer" : "a number"} greater than ${min}${max2 !== Infinity ? ` and at most ${max2}` : ""}.`);
|
|
4506
|
+
}
|
|
4507
|
+
output[key] = number3;
|
|
4508
|
+
}
|
|
4509
|
+
const primitives = optionalBoolean(config.primitives, `${id}.finish.primitives`);
|
|
4510
|
+
if (primitives !== void 0) output.primitives = primitives;
|
|
4511
|
+
if (primitives && !output.fitTolerance) throw new Error(`${id}.finish.primitives requires fitTolerance.`);
|
|
4512
|
+
if (output.bevelSegments && !output.bevelWidth) throw new Error(`${id}.finish.bevelSegments requires bevelWidth.`);
|
|
4513
|
+
if (config.regularization !== void 0) output.regularization = parseRegularization(config.regularization, `${id}.finish.regularization`);
|
|
4514
|
+
if (config.lodBevel !== void 0) {
|
|
4515
|
+
if (output.triangleBudget === void 0 || output.bevelWidth === void 0) {
|
|
4516
|
+
throw new Error(`${id}.finish.lodBevel requires triangleBudget and bevelWidth.`);
|
|
4517
|
+
}
|
|
4518
|
+
output.lodBevel = parseLodBevel(config.lodBevel, `${id}.finish.lodBevel`, output.triangleBudget);
|
|
4519
|
+
}
|
|
4520
|
+
return Object.keys(output).length ? output : void 0;
|
|
4521
|
+
}
|
|
4522
|
+
function parseInstances(value, id) {
|
|
4523
|
+
if (value === void 0) return;
|
|
4524
|
+
if (!Array.isArray(value) || !value.length || value.some((row) => !Array.isArray(row) || row.length !== 3 || row.some((number3) => typeof number3 !== "number" || !Number.isFinite(Math.fround(number3))))) {
|
|
4525
|
+
throw new Error(`${id}.instances must be a nonempty list of finite XYZ translations.`);
|
|
4526
|
+
}
|
|
4527
|
+
return value;
|
|
4528
|
+
}
|
|
4529
|
+
function parseAtlasSettings(node) {
|
|
4530
|
+
const settings = {};
|
|
4531
|
+
for (const [key, min, max2] of [["layers", 8, Infinity], ["resolution", 16, Infinity], ["threshold", 0, 255]]) {
|
|
4532
|
+
const value = node[key];
|
|
4533
|
+
if (value === void 0) continue;
|
|
4534
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < min || value > max2) {
|
|
4535
|
+
throw new Error(`${key} must be an integer ${max2 === Infinity ? `\u2265 ${min}` : `from ${min} to ${max2}`}.`);
|
|
4536
|
+
}
|
|
4537
|
+
settings[key] = value;
|
|
4538
|
+
}
|
|
4539
|
+
const { height, pivot, profile } = node;
|
|
4540
|
+
if (height !== void 0) {
|
|
4541
|
+
if (typeof height !== "number" || !Number.isFinite(height) || height <= 0) throw new Error("height must be positive.");
|
|
4542
|
+
settings.height = height;
|
|
4543
|
+
}
|
|
4544
|
+
if (pivot !== void 0) {
|
|
4545
|
+
if (pivot !== "ground" && pivot !== "center") throw new Error("pivot must be ground or center.");
|
|
4546
|
+
settings.pivot = pivot;
|
|
4547
|
+
}
|
|
4548
|
+
if (profile !== void 0) {
|
|
4549
|
+
if (profile !== "silhouette" && profile !== "round" && profile !== "round-base") throw new Error("Unknown reconstruction profile.");
|
|
4550
|
+
settings.profile = profile;
|
|
4551
|
+
}
|
|
4552
|
+
return settings;
|
|
4553
|
+
}
|
|
4554
|
+
function parseNode(raw, values, root, name) {
|
|
4555
|
+
const node = Object.fromEntries(Object.entries(mapping(raw, name)).map(([key, value]) => [key, renderValue(value, values, `${name}.${key}`)]));
|
|
4556
|
+
const id = requiredText(node.id, `${name}.id`);
|
|
4557
|
+
if (!/^[\w-]+$/.test(id)) throw new Error(`${name}.id must use letters, digits, underscores, or hyphens.`);
|
|
4558
|
+
const fields = (...keys) => mapping(node, id, ["id", "type", ...keys]);
|
|
4559
|
+
const path = (key) => resolve5(root, requiredText(node[key], `${id}.${key}`));
|
|
4560
|
+
const input = () => requiredText(node.input, `${id}.input`);
|
|
4561
|
+
switch (node.type) {
|
|
4562
|
+
case "load-stack":
|
|
4563
|
+
fields("path");
|
|
4564
|
+
return { id, type: node.type, path: path("path") };
|
|
4565
|
+
case "reconstruct-stack": {
|
|
4566
|
+
fields("path", "layout", "layers", "resolution", "height", "pivot", "threshold", "profile");
|
|
4567
|
+
const source = path("path");
|
|
4568
|
+
const extension = extname3(source).toLowerCase();
|
|
4569
|
+
const settings = parseAtlasSettings(node);
|
|
4570
|
+
if (extension === ".json" && node.layout === void 0) return { id, type: node.type, path: source, ...settings };
|
|
4571
|
+
if (extension !== ".png") throw new Error(`${id}: use a PNG atlas with layout or a JSON view manifest.`);
|
|
4572
|
+
const layout = parseLayout(requiredText(node.layout, `${id}.layout`)).join(",");
|
|
4573
|
+
return { id, type: node.type, path: source, layout, ...settings };
|
|
4574
|
+
}
|
|
4575
|
+
case "extract-mesh": {
|
|
4576
|
+
fields("input", "method", "guide", "finish", "cache");
|
|
4577
|
+
const method = requiredText(node.method, `${id}.method`);
|
|
4578
|
+
if (!isStackMeshMethod(method)) throw new Error(`${id}: unknown mesh method ${method}.`);
|
|
4579
|
+
const finish = parseFinish(node.finish, id);
|
|
4580
|
+
if (isCoreMeshMethod(method) && (node.guide !== void 0 || finish)) throw new Error(`${id}: ${method} does not accept ${finish ? "finishing options" : "a guide"}.`);
|
|
4581
|
+
const guide = node.guide === void 0 ? void 0 : path("guide");
|
|
4582
|
+
const cache = optionalBoolean(node.cache, `${id}.cache`);
|
|
4583
|
+
return { id, type: node.type, input: input(), method, ...guide && { guide }, ...finish && { finish }, ...cache !== void 0 && { cache } };
|
|
4584
|
+
}
|
|
4585
|
+
case "write-glb": {
|
|
4586
|
+
fields("input", "path", "lit", "instances");
|
|
4587
|
+
const output = path("path");
|
|
4588
|
+
if (extname3(output).toLowerCase() !== ".glb") throw new Error(`${id}: output must have the .glb extension.`);
|
|
4589
|
+
const lit = optionalBoolean(node.lit, `${id}.lit`);
|
|
4590
|
+
const instances = parseInstances(node.instances, id);
|
|
4591
|
+
return { id, type: node.type, input: input(), path: output, ...lit !== void 0 && { lit }, ...instances && { instances } };
|
|
4592
|
+
}
|
|
4593
|
+
default:
|
|
4594
|
+
throw new Error(`${id}: unknown node type ${String(node.type)}.`);
|
|
4595
|
+
}
|
|
4596
|
+
}
|
|
4597
|
+
function orderNodes(nodes) {
|
|
4598
|
+
const byId = /* @__PURE__ */ new Map();
|
|
4599
|
+
const outputs = /* @__PURE__ */ new Set();
|
|
4600
|
+
for (const node of nodes) {
|
|
4601
|
+
if (byId.has(node.id)) throw new Error(`Duplicate node ID ${node.id}.`);
|
|
4602
|
+
byId.set(node.id, node);
|
|
4603
|
+
if (node.type === "write-glb") {
|
|
4604
|
+
if (outputs.has(node.path)) throw new Error(`Duplicate output path ${node.path}.`);
|
|
4605
|
+
outputs.add(node.path);
|
|
4606
|
+
}
|
|
4607
|
+
}
|
|
4608
|
+
if (!outputs.size) throw new Error("The pipeline needs at least one write-glb node.");
|
|
4609
|
+
const ordered = [];
|
|
4610
|
+
const visiting = /* @__PURE__ */ new Set();
|
|
4611
|
+
const visited = /* @__PURE__ */ new Set();
|
|
4612
|
+
function visit(node) {
|
|
4613
|
+
if (visiting.has(node.id)) throw new Error(`Dependency cycle: ${[...visiting, node.id].join(" \u2192 ")}.`);
|
|
4614
|
+
if (visited.has(node.id)) return;
|
|
4615
|
+
visiting.add(node.id);
|
|
4616
|
+
if ("input" in node) {
|
|
4617
|
+
const source = byId.get(node.input);
|
|
4618
|
+
if (!source) throw new Error(`${node.id}: unknown input ${node.input}.`);
|
|
4619
|
+
visit(source);
|
|
4620
|
+
const accepted = node.type === "write-glb" ? source.type === "extract-mesh" : source.type === "load-stack" || source.type === "reconstruct-stack";
|
|
4621
|
+
if (!accepted) throw new Error(`${node.id}: unsupported input type ${source.type} from ${source.id}.`);
|
|
4622
|
+
}
|
|
4623
|
+
visiting.delete(node.id);
|
|
4624
|
+
visited.add(node.id);
|
|
4625
|
+
ordered.push(node);
|
|
4626
|
+
}
|
|
4627
|
+
nodes.forEach(visit);
|
|
4628
|
+
return ordered;
|
|
4629
|
+
}
|
|
4630
|
+
async function renderPipeline(path, overridePaths) {
|
|
4631
|
+
let values = {};
|
|
4632
|
+
const rawNodes = [];
|
|
4633
|
+
const loaded = /* @__PURE__ */ new Set();
|
|
4634
|
+
const loading = /* @__PURE__ */ new Set();
|
|
4635
|
+
async function load(file, root) {
|
|
4636
|
+
const canonical = await realpath(file);
|
|
4637
|
+
if (loading.has(canonical)) throw new Error(`Include cycle at ${file}.`);
|
|
4638
|
+
if (loaded.has(canonical)) return;
|
|
4639
|
+
loading.add(canonical);
|
|
4640
|
+
const doc = mapping(await readYaml(file), file, ["version", "includes", "values", "nodes"]);
|
|
4641
|
+
if ((root || doc.version !== void 0) && doc.version !== 1) throw new Error(`${file}: expected version 1.`);
|
|
4642
|
+
for (const key of ["includes", "nodes"]) {
|
|
4643
|
+
if (doc[key] !== void 0 && !Array.isArray(doc[key])) throw new Error(`${file}.${key} must be a list.`);
|
|
4644
|
+
}
|
|
4645
|
+
if (Array.isArray(doc.includes)) {
|
|
4646
|
+
for (const include of doc.includes) {
|
|
4647
|
+
await load(resolve5(dirname5(file), requiredText(include, `${file}.includes item`)), false);
|
|
4648
|
+
}
|
|
4649
|
+
}
|
|
4650
|
+
if (doc.values !== void 0) values = mergeValues(values, mapping(doc.values, `${file}.values`));
|
|
4651
|
+
if (Array.isArray(doc.nodes)) doc.nodes.forEach((raw, index) => rawNodes.push({ raw, name: `${file}.nodes[${index}]` }));
|
|
4652
|
+
loading.delete(canonical);
|
|
4653
|
+
loaded.add(canonical);
|
|
4654
|
+
}
|
|
4655
|
+
await load(path, true);
|
|
4656
|
+
for (const overridePath of overridePaths) values = mergeValues(values, mapping(await readYaml(overridePath), overridePath));
|
|
4657
|
+
const nodes = orderNodes(rawNodes.map(({ raw, name }) => parseNode(raw, values, dirname5(path), name)));
|
|
4658
|
+
return { version: 1, nodes };
|
|
4659
|
+
}
|
|
4660
|
+
async function surfaceCacheKey(node, stack) {
|
|
4661
|
+
const { texture, ...bounds2 } = stack;
|
|
4662
|
+
const hash = createHash3("sha256");
|
|
4663
|
+
hash.update(JSON.stringify([
|
|
4664
|
+
"surface-v4",
|
|
4665
|
+
node.method,
|
|
4666
|
+
node.finish,
|
|
4667
|
+
bounds2,
|
|
4668
|
+
texture.width,
|
|
4669
|
+
texture.height,
|
|
4670
|
+
process.env.STACK3_PYTHON,
|
|
4671
|
+
process.env.BLENDER_BIN
|
|
4672
|
+
]));
|
|
4673
|
+
hash.update(texture.data);
|
|
4674
|
+
if (node.guide) {
|
|
4675
|
+
const guide = await readFile7(node.guide);
|
|
4676
|
+
hash.update(guide);
|
|
4677
|
+
if (node.method === "signed-distance-dc" || node.method === "hermite-dc") {
|
|
4678
|
+
const { field, dexel } = JSON.parse(guide.toString("utf8"));
|
|
4679
|
+
for (const source of [field, dexel]) {
|
|
4680
|
+
if (typeof source === "string") hash.update(await readFile7(resolve5(dirname5(node.guide), source)));
|
|
4681
|
+
}
|
|
4682
|
+
}
|
|
4683
|
+
}
|
|
4684
|
+
return hash.digest("hex");
|
|
4685
|
+
}
|
|
4686
|
+
async function extract(node, stack) {
|
|
4687
|
+
const key = node.cache ? await surfaceCacheKey(node, stack) : void 0;
|
|
4688
|
+
const cached = key ? await readSurfaceCache(key) : void 0;
|
|
4689
|
+
if (cached) {
|
|
4690
|
+
console.error(`${node.id}: geometry cache hit`);
|
|
4691
|
+
return cached;
|
|
4692
|
+
}
|
|
4693
|
+
const mesh = await readStackMesh(stack, node.method, node.guide, node.finish);
|
|
4694
|
+
if (key && key === await surfaceCacheKey(node, stack)) await writeBuildCache(key, { format: "surface", mesh });
|
|
4695
|
+
return mesh;
|
|
4696
|
+
}
|
|
4697
|
+
async function runPipeline(nodes) {
|
|
4698
|
+
const assets = /* @__PURE__ */ new Map();
|
|
4699
|
+
const remaining = /* @__PURE__ */ new Map();
|
|
4700
|
+
for (const node of nodes) if ("input" in node) remaining.set(node.input, (remaining.get(node.input) ?? 0) + 1);
|
|
4701
|
+
for (const node of nodes) {
|
|
4702
|
+
try {
|
|
4703
|
+
if (node.type === "load-stack") {
|
|
4704
|
+
assets.set(node.id, (await loadStack(node.path)).stack);
|
|
4705
|
+
} else if (node.type === "reconstruct-stack") {
|
|
4706
|
+
const { id, type, path, layout, ...settings } = node;
|
|
4707
|
+
const threshold = settings.threshold ?? 238;
|
|
4708
|
+
const views = prepareViews(await readInput(path, layout, threshold), threshold);
|
|
4709
|
+
assets.set(node.id, buildFromPreparedViews(views, "stack", settings));
|
|
4710
|
+
} else {
|
|
4711
|
+
const source = assets.get(node.input);
|
|
4712
|
+
if (node.type === "extract-mesh" && source?.target === "stack") {
|
|
4713
|
+
assets.set(node.id, await extract(node, source));
|
|
4714
|
+
} else if (node.type === "write-glb" && source?.target === "mesh") {
|
|
4715
|
+
await mkdir3(dirname5(node.path), { recursive: true });
|
|
4716
|
+
await writeFile3(node.path, encodeGlb(source, node));
|
|
4717
|
+
console.log(`${node.id}: ${node.path}`);
|
|
4718
|
+
} else {
|
|
4719
|
+
throw new Error(`Missing resolved input ${node.input}.`);
|
|
4720
|
+
}
|
|
4721
|
+
const count2 = (remaining.get(node.input) ?? 1) - 1;
|
|
4722
|
+
remaining.set(node.input, count2);
|
|
4723
|
+
if (!count2) assets.delete(node.input);
|
|
4724
|
+
}
|
|
4725
|
+
if (!remaining.has(node.id)) assets.delete(node.id);
|
|
4726
|
+
} catch (error) {
|
|
4727
|
+
throw new Error(`${node.id} (${node.type}): ${error.message}`);
|
|
4728
|
+
}
|
|
4729
|
+
}
|
|
4730
|
+
}
|
|
4731
|
+
async function pipelineCommand(args) {
|
|
4732
|
+
const { positionals, values } = parseArgs2({ args, allowPositionals: true, options: {
|
|
4733
|
+
values: { type: "string", short: "f", multiple: true },
|
|
4734
|
+
help: { type: "boolean", short: "h" }
|
|
4735
|
+
} });
|
|
4736
|
+
if (values.help || !args.length) {
|
|
4737
|
+
console.log(help2);
|
|
4738
|
+
return;
|
|
4739
|
+
}
|
|
4740
|
+
const [verb, file] = positionals;
|
|
4741
|
+
if (verb === "schema") {
|
|
4742
|
+
if (positionals.length > 2 || values.values) throw new Error("Use stack3 pipeline schema [recipe|fragment].");
|
|
4743
|
+
await printPipelineSchema(file ?? "recipe");
|
|
4744
|
+
return;
|
|
4745
|
+
}
|
|
4746
|
+
if (verb !== "render" && verb !== "run" || positionals.length !== 2) throw new Error(help2);
|
|
4747
|
+
const pipeline = await renderPipeline(resolve5(file), values.values ?? []);
|
|
4748
|
+
if (verb === "render") process.stdout.write(stringify(pipeline));
|
|
4749
|
+
else await runPipeline(pipeline.nodes);
|
|
4750
|
+
}
|
|
4751
|
+
var help2;
|
|
4752
|
+
var init_pipeline = __esm({
|
|
4753
|
+
"apps/cli/src/pipeline.ts"() {
|
|
4754
|
+
"use strict";
|
|
4755
|
+
init_src();
|
|
4756
|
+
init_atlas_input();
|
|
4757
|
+
init_build_cache();
|
|
4758
|
+
init_capabilities();
|
|
4759
|
+
init_grid_build();
|
|
4760
|
+
init_part_mesh();
|
|
4761
|
+
init_stack_input();
|
|
4762
|
+
help2 = `Usage: stack3 pipeline <render|run> <pipeline.yaml> [-f <values.yaml> ...]
|
|
4763
|
+
stack3 pipeline schema [recipe|fragment]
|
|
4764
|
+
render Resolve includes and values, then print the validated pipeline YAML.
|
|
4765
|
+
run Execute the same resolved pipeline and write its GLB outputs.
|
|
4766
|
+
schema Print a standalone JSON Schema. The default is recipe.
|
|
4767
|
+
-f, --values Override defaults in order. The last file takes precedence.
|
|
4768
|
+
|
|
4769
|
+
Nodes: load-stack, reconstruct-stack, extract-mesh, write-glb.
|
|
4770
|
+
Run stack3 capabilities --json for backends, guide fields and sample paths.`;
|
|
4771
|
+
}
|
|
4772
|
+
});
|
|
4773
|
+
|
|
4774
|
+
// apps/cli/src/verify-command.ts
|
|
4775
|
+
var verify_command_exports = {};
|
|
4776
|
+
__export(verify_command_exports, {
|
|
4777
|
+
verifyCommand: () => verifyCommand
|
|
4778
|
+
});
|
|
4779
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
4780
|
+
import { fileURLToPath as fileURLToPath4 } from "node:url";
|
|
4781
|
+
import { parseArgs as parseArgs3 } from "node:util";
|
|
4782
|
+
async function verifyCommand(args) {
|
|
4783
|
+
const { positionals, values } = parseArgs3({ args, allowPositionals: true, options: {
|
|
4784
|
+
file: { type: "string", short: "f" },
|
|
4785
|
+
output: { type: "string", short: "o" },
|
|
4786
|
+
check: { type: "string" },
|
|
4787
|
+
part: { type: "string" },
|
|
4788
|
+
"output-dir": { type: "string" },
|
|
4789
|
+
help: { type: "boolean", short: "h" }
|
|
4790
|
+
} });
|
|
4791
|
+
if (values.help || !args.length) {
|
|
4792
|
+
console.log(help3);
|
|
4793
|
+
return;
|
|
4794
|
+
}
|
|
4795
|
+
const [kind] = positionals;
|
|
4796
|
+
if (positionals.length > 1 || kind !== void 0 && !["atlas", "assembly"].includes(kind) || !values.file || values.output !== void 0 && values.output !== "json" || values.check !== void 0 && (kind !== "atlas" || !["projections", "landmarks"].includes(values.check)) || values.part !== void 0 && (kind !== "assembly" || !values.part)) throw new Error(help3);
|
|
4797
|
+
const script = fileURLToPath4(new URL("../verification/verify.py", import.meta.url));
|
|
4798
|
+
const python = process.env.STACK3_PYTHON;
|
|
4799
|
+
const params = [...python ? [] : ["run", "--no-project", "--script"], script, values.file];
|
|
4800
|
+
if (kind) params.push("--kind", kind);
|
|
4801
|
+
for (const key of ["check", "part", "output-dir"]) {
|
|
4802
|
+
if (values[key] !== void 0) params.push("--" + key, values[key]);
|
|
4803
|
+
}
|
|
4804
|
+
await new Promise((done, reject) => {
|
|
4805
|
+
const child = spawn2(python || "uv", params, { stdio: "inherit", env: { ...process.env, PYTHONDONTWRITEBYTECODE: "1" } });
|
|
4806
|
+
child.once("error", (error) => reject(new Error(`Cannot start verifier: ${error.message}. Install uv or set STACK3_PYTHON.`)));
|
|
4807
|
+
child.once("close", (code) => code === 0 ? done() : reject(new Error("Verification could not complete.")));
|
|
4808
|
+
});
|
|
4809
|
+
}
|
|
4810
|
+
var help3;
|
|
4811
|
+
var init_verify_command = __esm({
|
|
4812
|
+
"apps/cli/src/verify-command.ts"() {
|
|
4813
|
+
"use strict";
|
|
4814
|
+
help3 = `stack3 verify -f <manifest.yaml> [--output-dir <dir>]
|
|
4815
|
+
Print one JSON measurement report to stdout.
|
|
4816
|
+
Atlas: projections and landmarks. Assembly: whole and part atlases plus mount measurements.
|
|
4817
|
+
A full atlas run reports an acceptance verdict. Use --output-dir to prepare a report for build --verification.
|
|
4818
|
+
--output-dir <dir> Also save report.json and annotated PNG overlays
|
|
4819
|
+
-f, --file Image and child manifest paths are relative to their YAML file.`;
|
|
4820
|
+
}
|
|
4821
|
+
});
|
|
4822
|
+
|
|
3584
4823
|
// apps/cli/src/project-store.ts
|
|
3585
4824
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
3586
|
-
import { mkdir as
|
|
3587
|
-
import { dirname } from "node:path";
|
|
4825
|
+
import { mkdir as mkdir4, open, readFile as readFile8, rename as rename2, stat as stat2, unlink as unlink2, writeFile as writeFile4 } from "node:fs/promises";
|
|
4826
|
+
import { dirname as dirname6 } from "node:path";
|
|
3588
4827
|
import { setTimeout as setTimeout2 } from "node:timers/promises";
|
|
3589
4828
|
async function readProject(file) {
|
|
3590
|
-
const data = JSON.parse(await
|
|
4829
|
+
const data = JSON.parse(await readFile8(file, "utf8"));
|
|
3591
4830
|
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
4831
|
return data;
|
|
3593
4832
|
}
|
|
3594
4833
|
async function initProject(file, name) {
|
|
3595
|
-
await
|
|
4834
|
+
await mkdir4(dirname6(file), { recursive: true });
|
|
3596
4835
|
const project = newProject(name);
|
|
3597
|
-
await
|
|
4836
|
+
await writeFile4(file, JSON.stringify(project) + "\n", { flag: "wx", mode: 384 });
|
|
3598
4837
|
return project;
|
|
3599
4838
|
}
|
|
3600
4839
|
async function editProject(file, actions, expected) {
|
|
@@ -3615,7 +4854,7 @@ async function editProject(file, actions, expected) {
|
|
|
3615
4854
|
const project = await readProject(file);
|
|
3616
4855
|
if (expected !== void 0 && project.revision !== expected) throw new RevisionConflict("Project revision changed.");
|
|
3617
4856
|
const next = applyProjectActions(project, actions);
|
|
3618
|
-
await
|
|
4857
|
+
await writeFile4(temporary, JSON.stringify(next) + "\n", { flag: "wx", mode: 384 });
|
|
3619
4858
|
await rename2(temporary, file);
|
|
3620
4859
|
return next;
|
|
3621
4860
|
} finally {
|
|
@@ -3645,13 +4884,13 @@ var init_project_store = __esm({
|
|
|
3645
4884
|
});
|
|
3646
4885
|
|
|
3647
4886
|
// apps/cli/src/preview-server.ts
|
|
3648
|
-
import { existsSync } from "node:fs";
|
|
3649
|
-
import { fileURLToPath } from "node:url";
|
|
4887
|
+
import { existsSync as existsSync3 } from "node:fs";
|
|
4888
|
+
import { fileURLToPath as fileURLToPath5 } from "node:url";
|
|
3650
4889
|
import { createServer, preview } from "vite";
|
|
3651
4890
|
async function serveViewer(page, open2, middleware) {
|
|
3652
4891
|
const server = { host: "127.0.0.1", port: 0, cors: false, open: open2 ? page : false };
|
|
3653
|
-
const packagedRoot =
|
|
3654
|
-
if (
|
|
4892
|
+
const packagedRoot = fileURLToPath5(new URL("../viewer/", import.meta.url));
|
|
4893
|
+
if (existsSync3(new URL("../viewer/dist/index.html", import.meta.url))) {
|
|
3655
4894
|
const built = await preview({
|
|
3656
4895
|
root: packagedRoot,
|
|
3657
4896
|
configFile: false,
|
|
@@ -3666,7 +4905,7 @@ async function serveViewer(page, open2, middleware) {
|
|
|
3666
4905
|
return new URL(page, built.resolvedUrls.local[0]);
|
|
3667
4906
|
}
|
|
3668
4907
|
const dev = await createServer({
|
|
3669
|
-
root:
|
|
4908
|
+
root: fileURLToPath5(new URL("../../viewer/", import.meta.url)),
|
|
3670
4909
|
server,
|
|
3671
4910
|
plugins: [{
|
|
3672
4911
|
name: "stack3-cli-preview",
|
|
@@ -3689,7 +4928,7 @@ var project_server_exports = {};
|
|
|
3689
4928
|
__export(project_server_exports, {
|
|
3690
4929
|
openProject: () => openProject
|
|
3691
4930
|
});
|
|
3692
|
-
import { createHash as
|
|
4931
|
+
import { createHash as createHash4, randomUUID as randomUUID3 } from "node:crypto";
|
|
3693
4932
|
async function body(request) {
|
|
3694
4933
|
const chunks = [];
|
|
3695
4934
|
let size = 0;
|
|
@@ -3774,7 +5013,7 @@ var init_project_server = __esm({
|
|
|
3774
5013
|
init_src();
|
|
3775
5014
|
init_project_store();
|
|
3776
5015
|
limit = 80 * 1024 * 1024;
|
|
3777
|
-
fingerprint = (png2) =>
|
|
5016
|
+
fingerprint = (png2) => createHash4("sha256").update(png2).digest("hex");
|
|
3778
5017
|
}
|
|
3779
5018
|
});
|
|
3780
5019
|
|
|
@@ -3783,18 +5022,18 @@ var project_command_exports = {};
|
|
|
3783
5022
|
__export(project_command_exports, {
|
|
3784
5023
|
projectCommand: () => projectCommand
|
|
3785
5024
|
});
|
|
3786
|
-
import { createHash as
|
|
3787
|
-
import { readFile as
|
|
3788
|
-
import { basename, dirname as
|
|
3789
|
-
import { parseArgs } from "node:util";
|
|
3790
|
-
import { PNG } from "pngjs";
|
|
5025
|
+
import { createHash as createHash5, randomUUID as randomUUID4 } from "node:crypto";
|
|
5026
|
+
import { readFile as readFile9, writeFile as writeFile5, mkdir as mkdir5 } from "node:fs/promises";
|
|
5027
|
+
import { basename as basename2, dirname as dirname7, extname as extname4, join as join6, resolve as resolve6 } from "node:path";
|
|
5028
|
+
import { parseArgs as parseArgs4 } from "node:util";
|
|
5029
|
+
import { PNG as PNG3 } from "pngjs";
|
|
3791
5030
|
async function stdin() {
|
|
3792
5031
|
const chunks = [];
|
|
3793
5032
|
for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
|
|
3794
5033
|
return Buffer.concat(chunks).toString("utf8");
|
|
3795
5034
|
}
|
|
3796
5035
|
async function projectCommand(args) {
|
|
3797
|
-
const { positionals: [verb, file, ...inputs], values } =
|
|
5036
|
+
const { positionals: [verb, file, ...inputs], values } = parseArgs4({
|
|
3798
5037
|
args,
|
|
3799
5038
|
allowPositionals: true,
|
|
3800
5039
|
options: {
|
|
@@ -3811,7 +5050,7 @@ async function projectCommand(args) {
|
|
|
3811
5050
|
}
|
|
3812
5051
|
});
|
|
3813
5052
|
if (!verb || values.help) {
|
|
3814
|
-
console.log(
|
|
5053
|
+
console.log(help4);
|
|
3815
5054
|
return;
|
|
3816
5055
|
}
|
|
3817
5056
|
if (verb === "schema") {
|
|
@@ -3830,11 +5069,11 @@ async function projectCommand(args) {
|
|
|
3830
5069
|
return;
|
|
3831
5070
|
}
|
|
3832
5071
|
if (!file) throw new Error("Provide a project file.");
|
|
3833
|
-
const path =
|
|
5072
|
+
const path = resolve6(file);
|
|
3834
5073
|
switch (verb) {
|
|
3835
5074
|
case "init": {
|
|
3836
5075
|
if (inputs.length) throw new Error("init expects only a project file.");
|
|
3837
|
-
print(summarizeProject(await initProject(path, values.name ||
|
|
5076
|
+
print(summarizeProject(await initProject(path, values.name || basename2(path, extname4(path)))));
|
|
3838
5077
|
return;
|
|
3839
5078
|
}
|
|
3840
5079
|
case "get":
|
|
@@ -3849,7 +5088,7 @@ async function projectCommand(args) {
|
|
|
3849
5088
|
if (inputs.length !== 1) throw new Error("Provide a JSON action file or - for standard input.");
|
|
3850
5089
|
const revision = values.revision === void 0 ? void 0 : Number(values.revision);
|
|
3851
5090
|
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
|
|
5091
|
+
print(summarizeProject(await editProject(path, JSON.parse(inputs[0] === "-" ? await stdin() : await readFile9(inputs[0], "utf8")), revision)));
|
|
3853
5092
|
return;
|
|
3854
5093
|
}
|
|
3855
5094
|
case "preset": {
|
|
@@ -3873,9 +5112,9 @@ async function projectCommand(args) {
|
|
|
3873
5112
|
const actions = [];
|
|
3874
5113
|
const nodes = [];
|
|
3875
5114
|
for (const image of inputs) {
|
|
3876
|
-
const bytes = await
|
|
3877
|
-
const name =
|
|
3878
|
-
const atlasId =
|
|
5115
|
+
const bytes = await readFile9(image);
|
|
5116
|
+
const name = basename2(image, extname4(image));
|
|
5117
|
+
const atlasId = createHash5("sha256").update(layout).update(bytes).digest("hex");
|
|
3879
5118
|
const id = randomUUID4();
|
|
3880
5119
|
nodes.push(id);
|
|
3881
5120
|
actions.push(
|
|
@@ -3894,21 +5133,22 @@ async function projectCommand(args) {
|
|
|
3894
5133
|
const node = project.nodes.find((item) => item.id === inputs[0]);
|
|
3895
5134
|
const atlas = project.atlases.find((item) => item.id === node?.atlasId);
|
|
3896
5135
|
if (!node || !atlas) throw new Error("Export requires an atlas-backed node.");
|
|
3897
|
-
const format = values.format ?? (
|
|
5136
|
+
const format = values.format ?? (extname4(values.output).toLowerCase() === ".glb" ? "glb" : node.settings.format);
|
|
3898
5137
|
if (format !== "glb" && format !== "stack") throw new Error("Use --format glb or --format stack.");
|
|
3899
|
-
const output =
|
|
3900
|
-
if (format === "glb" &&
|
|
3901
|
-
const image =
|
|
5138
|
+
const output = resolve6(values.output);
|
|
5139
|
+
if (format === "glb" && extname4(output).toLowerCase() !== ".glb") throw new Error("GLB output must end in .glb.");
|
|
5140
|
+
const image = PNG3.sync.read(Buffer.from(atlas.png, "base64"));
|
|
3902
5141
|
const settings = node.settings;
|
|
3903
|
-
const
|
|
5142
|
+
const views = prepareViews(splitAtlas(image, parseLayout(atlas.layout), settings.threshold), settings.threshold);
|
|
5143
|
+
const asset = buildFromPreparedViews(views, format === "glb" ? "mesh" : "stack", settings);
|
|
3904
5144
|
if (asset.target === "mesh") {
|
|
3905
|
-
await
|
|
3906
|
-
await
|
|
5145
|
+
await mkdir5(dirname7(output), { recursive: true });
|
|
5146
|
+
await writeFile5(output, encodeGlb(asset));
|
|
3907
5147
|
} else {
|
|
3908
5148
|
const bundle = encodeStack(respaceStack(asset, settings.spacing));
|
|
3909
|
-
await
|
|
3910
|
-
await
|
|
3911
|
-
await
|
|
5149
|
+
await mkdir5(output, { recursive: true });
|
|
5150
|
+
await writeFile5(join6(output, "stack.png"), bundle.png);
|
|
5151
|
+
await writeFile5(join6(output, "stack.json"), JSON.stringify(bundle.manifest, null, 2) + "\n");
|
|
3912
5152
|
}
|
|
3913
5153
|
print({ node: node.id, format, output });
|
|
3914
5154
|
return;
|
|
@@ -3917,13 +5157,14 @@ async function projectCommand(args) {
|
|
|
3917
5157
|
throw new Error("Unknown project command: " + verb);
|
|
3918
5158
|
}
|
|
3919
5159
|
}
|
|
3920
|
-
var
|
|
5160
|
+
var help4, print;
|
|
3921
5161
|
var init_project_command = __esm({
|
|
3922
5162
|
"apps/cli/src/project-command.ts"() {
|
|
3923
5163
|
"use strict";
|
|
5164
|
+
init_grid_build();
|
|
3924
5165
|
init_src();
|
|
3925
5166
|
init_project_store();
|
|
3926
|
-
|
|
5167
|
+
help4 = `Usage: stack3 project <verb> [project-file] [options]
|
|
3927
5168
|
|
|
3928
5169
|
schema List agent actions and field constraints as JSON
|
|
3929
5170
|
components [component-id] List built-in script components or inspect one
|
|
@@ -3952,16 +5193,14 @@ __export(view_exports, {
|
|
|
3952
5193
|
viewStack: () => viewStack
|
|
3953
5194
|
});
|
|
3954
5195
|
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
3955
|
-
|
|
3956
|
-
|
|
3957
|
-
|
|
3958
|
-
|
|
3959
|
-
|
|
3960
|
-
|
|
3961
|
-
|
|
3962
|
-
|
|
3963
|
-
readPngSize(png2);
|
|
3964
|
-
readStackBundle(JSON.parse(metadata), PNG2.sync.read(png2));
|
|
5196
|
+
async function viewStack(directory2, open2, web = false, output) {
|
|
5197
|
+
if (web && output) throw new Error("Choose --web or a .blend output file.");
|
|
5198
|
+
const { metadata, png: png2 } = await loadStack(directory2);
|
|
5199
|
+
if (!web && (open2 || output)) {
|
|
5200
|
+
const { openBlenderStack: openBlenderStack2 } = await Promise.resolve().then(() => (init_blender(), blender_exports));
|
|
5201
|
+
await openBlenderStack2(directory2, output, open2);
|
|
5202
|
+
return;
|
|
5203
|
+
}
|
|
3965
5204
|
const token = randomUUID5();
|
|
3966
5205
|
const prefix = "/__stack3/" + token + "/";
|
|
3967
5206
|
const url = await serveViewer("/?stack=" + token, open2, (request, response, next) => {
|
|
@@ -3983,69 +5222,47 @@ var init_view = __esm({
|
|
|
3983
5222
|
"apps/cli/src/view.ts"() {
|
|
3984
5223
|
"use strict";
|
|
3985
5224
|
init_preview_server();
|
|
3986
|
-
|
|
5225
|
+
init_stack_input();
|
|
3987
5226
|
}
|
|
3988
5227
|
});
|
|
3989
5228
|
|
|
3990
5229
|
// apps/cli/src/main.ts
|
|
5230
|
+
init_atlas_input();
|
|
5231
|
+
init_part_mesh();
|
|
5232
|
+
init_stack_input();
|
|
5233
|
+
init_grid_build();
|
|
3991
5234
|
init_src();
|
|
3992
|
-
|
|
3993
|
-
|
|
3994
|
-
import {
|
|
3995
|
-
import {
|
|
3996
|
-
import {
|
|
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
|
|
5235
|
+
init_verification_gate();
|
|
5236
|
+
init_build_cache();
|
|
5237
|
+
import { constants, existsSync as existsSync4 } from "node:fs";
|
|
5238
|
+
import { copyFile, mkdir as mkdir6, readFile as readFile10, writeFile as writeFile6 } from "node:fs/promises";
|
|
5239
|
+
import { dirname as dirname8, extname as extname5, join as join7, resolve as resolve7 } from "node:path";
|
|
5240
|
+
import { parseArgs as parseArgs5 } from "node:util";
|
|
4043
5241
|
var HELP = `Usage: stack3 <verb> <input> [options]
|
|
4044
5242
|
|
|
5243
|
+
help [topic] Show command help (pipeline, mesh, or capabilities)
|
|
5244
|
+
capabilities [--json] List mesh methods, runtime requirements, schemas and example recipes
|
|
4045
5245
|
example <name> Copy future-tank or traffic-cone into the current directory
|
|
5246
|
+
verify -f <manifest> Measure atlas views and mounts in one JSON report
|
|
4046
5247
|
inspect <input> Check mapped directions and fitted image sizes
|
|
4047
5248
|
build <input> Build an asset and save it to --output
|
|
4048
|
-
|
|
5249
|
+
pipeline --help Render or run YAML, or export its JSON Schema
|
|
5250
|
+
mesh <stack-directory> Extract a surface from saved stack.png + stack.json (--output mesh.glb)
|
|
5251
|
+
--mesh-method marching-cubes (default), surface-nets, voxel
|
|
5252
|
+
or ${partMethods.join(", ")}
|
|
5253
|
+
--guide <part.json> uses pivot-relative stack XYZ scene units.
|
|
5254
|
+
section-loft, smooth-loft, branch-loft, heightfield: optional axis (x/y/z, default z)
|
|
5255
|
+
section-loft, smooth-loft: optional stations [{slice,outer?,holes?}]
|
|
5256
|
+
revolve: axis + origin, optional segments (8-512, default 64)
|
|
5257
|
+
path-sweep: path; optional up and profile {outer,holes?} (defaults to first stack section)
|
|
5258
|
+
section-network: sections [{source:"independent",origin,u,v,outer,holes?}], optional tolerance
|
|
5259
|
+
hermite-dc: optional field (.npy SDF) or dexel (.npz crossings and normals)
|
|
5260
|
+
signed-distance-dc: optional field, outerIterations and innerIterations
|
|
5261
|
+
extended-mc, mc33, greedy, monotone: no guide
|
|
5262
|
+
New methods use uv or STACK3_PYTHON. See the stack3 skill for guide examples.
|
|
5263
|
+
view <directory> Open a stack bundle in Blender (use --web for the browser viewer)
|
|
5264
|
+
--output scene.blend saves a named scene; add --no-open for headless export
|
|
5265
|
+
--no-open alone prints the web preview URL
|
|
4049
5266
|
project --help Edit a level and control its live viewer and playground
|
|
4050
5267
|
|
|
4051
5268
|
Inputs
|
|
@@ -4059,38 +5276,16 @@ Build options
|
|
|
4059
5276
|
--texture-projection <name> auto (default) or top-contour for GLB output
|
|
4060
5277
|
--mesh-method <name> marching-cubes (default) or contour for GLB output
|
|
4061
5278
|
--contour-hub Add a centered round axle measured from TOP and LEFT
|
|
4062
|
-
--layers <integer>
|
|
5279
|
+
--layers <integer|native> Vertical samples (default ${DEFAULT_LAYERS})
|
|
4063
5280
|
--spacing <number> Sprite stack spacing multiplier (default 1)
|
|
4064
5281
|
--profile <name> silhouette, round, or round-base
|
|
5282
|
+
--verification <file> Require a matching atlas PASS report before building
|
|
4065
5283
|
--no-cache Bypass the local build cache
|
|
4066
|
-
--resolution <integer>
|
|
5284
|
+
--resolution <integer|native> Longer horizontal axis samples (default 96)
|
|
4067
5285
|
--height <number> Asset height in scene units (default 1)
|
|
4068
5286
|
--pivot ground|center Origin position (default ground)
|
|
4069
5287
|
--threshold <0\u2013255> Background threshold for opaque PNGs (default 238)
|
|
4070
5288
|
`;
|
|
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
5289
|
function outputFormat(output, format, target) {
|
|
4095
5290
|
if (format !== void 0 && format !== "glb" && format !== "stack") {
|
|
4096
5291
|
throw new Error("Use --format glb or --format stack.");
|
|
@@ -4100,7 +5295,7 @@ function outputFormat(output, format, target) {
|
|
|
4100
5295
|
}
|
|
4101
5296
|
const legacyFormat = target === "mesh" ? "glb" : target;
|
|
4102
5297
|
if (format && legacyFormat && format !== legacyFormat) throw new Error("--format and --target disagree.");
|
|
4103
|
-
const isGlbPath =
|
|
5298
|
+
const isGlbPath = extname5(output).toLowerCase() === ".glb";
|
|
4104
5299
|
const selected = format ?? legacyFormat ?? (isGlbPath ? "glb" : void 0);
|
|
4105
5300
|
if (!selected) throw new Error("Use --format stack for a stack directory or specify a .glb output file.");
|
|
4106
5301
|
if (selected === "glb" && !isGlbPath) throw new Error("GLB output must have the .glb extension.");
|
|
@@ -4115,18 +5310,45 @@ async function copyExample(name, output) {
|
|
|
4115
5310
|
if (!example) throw new Error("Choose future-tank or traffic-cone.");
|
|
4116
5311
|
const [filename, workspacePath] = example;
|
|
4117
5312
|
const packaged = new URL("../examples/" + filename, import.meta.url);
|
|
4118
|
-
const source =
|
|
4119
|
-
const destination =
|
|
5313
|
+
const source = existsSync4(packaged) ? packaged : new URL("../../../" + workspacePath, import.meta.url);
|
|
5314
|
+
const destination = resolve7(output ?? filename);
|
|
4120
5315
|
await copyFile(source, destination, constants.COPYFILE_EXCL);
|
|
4121
5316
|
console.log(destination);
|
|
4122
5317
|
}
|
|
4123
5318
|
async function main() {
|
|
4124
|
-
|
|
5319
|
+
const args = process.argv.slice(2);
|
|
5320
|
+
if (args[0] === "help") {
|
|
5321
|
+
if (args.length === 1) {
|
|
5322
|
+
console.log(HELP);
|
|
5323
|
+
return;
|
|
5324
|
+
}
|
|
5325
|
+
if (args.length !== 2 || !["pipeline", "mesh", "capabilities"].includes(args[1])) {
|
|
5326
|
+
throw new Error("Use stack3 help [pipeline|mesh|capabilities].");
|
|
5327
|
+
}
|
|
5328
|
+
args.splice(0, 2, args[1], "--help");
|
|
5329
|
+
}
|
|
5330
|
+
if (args[0] === "capabilities") {
|
|
5331
|
+
const { capabilitiesCommand: capabilitiesCommand2 } = await Promise.resolve().then(() => (init_capabilities(), capabilities_exports));
|
|
5332
|
+
capabilitiesCommand2(args.slice(1));
|
|
5333
|
+
return;
|
|
5334
|
+
}
|
|
5335
|
+
if (args[0] === "pipeline") {
|
|
5336
|
+
const { pipelineCommand: pipelineCommand2 } = await Promise.resolve().then(() => (init_pipeline(), pipeline_exports));
|
|
5337
|
+
await pipelineCommand2(args.slice(1));
|
|
5338
|
+
return;
|
|
5339
|
+
}
|
|
5340
|
+
if (args[0] === "verify") {
|
|
5341
|
+
const { verifyCommand: verifyCommand2 } = await Promise.resolve().then(() => (init_verify_command(), verify_command_exports));
|
|
5342
|
+
await verifyCommand2(args.slice(1));
|
|
5343
|
+
return;
|
|
5344
|
+
}
|
|
5345
|
+
if (args[0] === "project") {
|
|
4125
5346
|
const { projectCommand: projectCommand2 } = await Promise.resolve().then(() => (init_project_command(), project_command_exports));
|
|
4126
|
-
await projectCommand2(
|
|
5347
|
+
await projectCommand2(args.slice(1));
|
|
4127
5348
|
return;
|
|
4128
5349
|
}
|
|
4129
|
-
const { positionals, values } =
|
|
5350
|
+
const { positionals, values } = parseArgs5({
|
|
5351
|
+
args,
|
|
4130
5352
|
allowPositionals: true,
|
|
4131
5353
|
options: {
|
|
4132
5354
|
help: { type: "boolean", short: "h" },
|
|
@@ -4134,6 +5356,7 @@ async function main() {
|
|
|
4134
5356
|
layout: { type: "string" },
|
|
4135
5357
|
format: { type: "string" },
|
|
4136
5358
|
target: { type: "string" },
|
|
5359
|
+
verification: { type: "string" },
|
|
4137
5360
|
output: { type: "string", short: "o" },
|
|
4138
5361
|
layers: { type: "string" },
|
|
4139
5362
|
resolution: { type: "string" },
|
|
@@ -4142,15 +5365,17 @@ async function main() {
|
|
|
4142
5365
|
threshold: { type: "string" },
|
|
4143
5366
|
"texture-projection": { type: "string" },
|
|
4144
5367
|
"mesh-method": { type: "string" },
|
|
5368
|
+
guide: { type: "string" },
|
|
4145
5369
|
"contour-hub": { type: "boolean" },
|
|
4146
5370
|
spacing: { type: "string" },
|
|
4147
5371
|
profile: { type: "string" },
|
|
4148
5372
|
"no-cache": { type: "boolean" },
|
|
4149
|
-
"no-open": { type: "boolean" }
|
|
5373
|
+
"no-open": { type: "boolean" },
|
|
5374
|
+
web: { type: "boolean" }
|
|
4150
5375
|
}
|
|
4151
5376
|
});
|
|
4152
5377
|
if (values.version) {
|
|
4153
|
-
const manifest = JSON.parse(await
|
|
5378
|
+
const manifest = JSON.parse(await readFile10(new URL("../package.json", import.meta.url), "utf8"));
|
|
4154
5379
|
console.log(manifest.version);
|
|
4155
5380
|
return;
|
|
4156
5381
|
}
|
|
@@ -4159,16 +5384,40 @@ async function main() {
|
|
|
4159
5384
|
return;
|
|
4160
5385
|
}
|
|
4161
5386
|
const [verb, input] = positionals;
|
|
5387
|
+
if (values.verification !== void 0 && verb !== "build") throw new Error("--verification requires stack3 build.");
|
|
5388
|
+
if (values.guide !== void 0 && verb !== "mesh") throw new Error("--guide requires stack3 mesh.");
|
|
4162
5389
|
if (verb === "example" && positionals.length === 2) {
|
|
4163
5390
|
await copyExample(input, values.output);
|
|
4164
5391
|
return;
|
|
4165
5392
|
}
|
|
4166
|
-
if (positionals.length !== 2 || verb !== "inspect" && verb !== "build" && verb !== "view") {
|
|
5393
|
+
if (positionals.length !== 2 || verb !== "inspect" && verb !== "build" && verb !== "mesh" && verb !== "view") {
|
|
4167
5394
|
throw new Error("See stack3 --help for available commands and arguments.");
|
|
4168
5395
|
}
|
|
5396
|
+
if (verb === "mesh") {
|
|
5397
|
+
if (!values.output || extname5(values.output).toLowerCase() !== ".glb" || Object.keys(values).some((k) => k !== "output" && k !== "mesh-method" && k !== "guide")) {
|
|
5398
|
+
throw new Error("Use stack3 mesh <stack-directory> --output <file.glb>. Geometry settings come from the saved stack.");
|
|
5399
|
+
}
|
|
5400
|
+
const method = values["mesh-method"] ?? "marching-cubes";
|
|
5401
|
+
if (!isStackMeshMethod(method)) {
|
|
5402
|
+
throw new Error(`Stack mesh methods: marching-cubes, surface-nets, voxel, ${partMethods.join(", ")}.`);
|
|
5403
|
+
}
|
|
5404
|
+
if (isCoreMeshMethod(method) && values.guide !== void 0) throw new Error(`${input}: ${method} does not accept --guide.`);
|
|
5405
|
+
const { stack } = await loadStack(resolve7(input));
|
|
5406
|
+
let bytes;
|
|
5407
|
+
try {
|
|
5408
|
+
bytes = encodeGlb(await readStackMesh(stack, method, values.guide));
|
|
5409
|
+
} catch (error) {
|
|
5410
|
+
throw new Error(`${input} (${method}): ${error.message}`);
|
|
5411
|
+
}
|
|
5412
|
+
const output2 = resolve7(values.output);
|
|
5413
|
+
await mkdir6(dirname8(output2), { recursive: true });
|
|
5414
|
+
await writeFile6(output2, bytes);
|
|
5415
|
+
console.log(`Meshed ${stack.layers} saved layers with ${method} into ${output2}`);
|
|
5416
|
+
return;
|
|
5417
|
+
}
|
|
4169
5418
|
if (verb === "view") {
|
|
4170
5419
|
const { viewStack: viewStack2 } = await Promise.resolve().then(() => (init_view(), view_exports));
|
|
4171
|
-
await viewStack2(
|
|
5420
|
+
await viewStack2(resolve7(input), !values["no-open"], values.web ?? false, values.output);
|
|
4172
5421
|
return;
|
|
4173
5422
|
}
|
|
4174
5423
|
const threshold = values.threshold === void 0 ? 238 : Number(values.threshold);
|
|
@@ -4179,7 +5428,7 @@ async function main() {
|
|
|
4179
5428
|
return;
|
|
4180
5429
|
}
|
|
4181
5430
|
if (!values.output) throw new Error("Build requires --output <path>.");
|
|
4182
|
-
const output =
|
|
5431
|
+
const output = resolve7(values.output);
|
|
4183
5432
|
const format = outputFormat(output, values.format, values.target);
|
|
4184
5433
|
const spacing = values.spacing === void 0 ? 1 : Number(values.spacing);
|
|
4185
5434
|
if (!Number.isFinite(spacing) || spacing <= 0) throw new Error("Spacing must be a positive, finite multiplier.");
|
|
@@ -4199,34 +5448,44 @@ async function main() {
|
|
|
4199
5448
|
if ((meshMethod || values["contour-hub"]) && format !== "glb") throw new Error("Mesh methods require GLB output.");
|
|
4200
5449
|
if (values["contour-hub"] && meshMethod !== "contour") throw new Error("--contour-hub requires --mesh-method contour.");
|
|
4201
5450
|
if (meshMethod === "contour" && profile && profile !== "silhouette") throw new Error("Contour extrusion uses the FRONT silhouette.");
|
|
5451
|
+
const sourceHashes = values.verification === void 0 ? void 0 : /* @__PURE__ */ new Map();
|
|
5452
|
+
const views = prepareViews(await readInput(input, values.layout, threshold, sourceHashes), threshold);
|
|
5453
|
+
if (values.verification !== void 0 && sourceHashes) {
|
|
5454
|
+
await requireVerifiedViews(values.verification, views, sourceHashes);
|
|
5455
|
+
}
|
|
5456
|
+
const { nativeSamples } = inspectViews(views);
|
|
4202
5457
|
const settings = {
|
|
4203
5458
|
textureProjection,
|
|
4204
5459
|
meshMethod,
|
|
4205
5460
|
contourHub: values["contour-hub"],
|
|
4206
|
-
layers: values.layers ===
|
|
4207
|
-
resolution: values.resolution === void 0 ? void 0 : Number(values.resolution),
|
|
5461
|
+
layers: values.layers === "native" ? Math.max(8, nativeSamples.z) : Number(values.layers ?? DEFAULT_LAYERS),
|
|
5462
|
+
resolution: values.resolution === "native" || values.resolution === void 0 ? void 0 : Number(values.resolution),
|
|
4208
5463
|
height: values.height === void 0 ? void 0 : Number(values.height),
|
|
4209
5464
|
pivot: values.pivot,
|
|
4210
5465
|
threshold,
|
|
4211
5466
|
profile
|
|
4212
5467
|
};
|
|
4213
|
-
|
|
5468
|
+
if (values.resolution === "native") {
|
|
5469
|
+
const { size: [width, depth] } = reconstructionDimensions(views, settings);
|
|
5470
|
+
const samples2 = width === depth ? Math.max(nativeSamples.x, nativeSamples.y) : width > depth ? nativeSamples.x : nativeSamples.y;
|
|
5471
|
+
settings.resolution = Math.max(16, samples2);
|
|
5472
|
+
}
|
|
4214
5473
|
const key = values["no-cache"] ? void 0 : buildCacheKey(views, format, settings, spacing);
|
|
4215
5474
|
const cached = key ? await readBuildCache(key, format) : void 0;
|
|
4216
5475
|
const artifact = cached ?? buildOutput(views, format, settings, spacing);
|
|
4217
5476
|
if (artifact.format === "glb") {
|
|
4218
|
-
await
|
|
4219
|
-
await
|
|
5477
|
+
await mkdir6(dirname8(output), { recursive: true });
|
|
5478
|
+
await writeFile6(output, artifact.bytes);
|
|
4220
5479
|
} else {
|
|
4221
|
-
await
|
|
4222
|
-
await
|
|
4223
|
-
await
|
|
5480
|
+
await mkdir6(output, { recursive: true });
|
|
5481
|
+
await writeFile6(join7(output, "stack.png"), artifact.png);
|
|
5482
|
+
await writeFile6(join7(output, "stack.json"), artifact.manifest);
|
|
4224
5483
|
}
|
|
4225
5484
|
if (key && !cached) await writeBuildCache(key, artifact);
|
|
4226
5485
|
console.log(`Built ${format} at ${output}${cached ? " \xB7 disk cache" : ""}`);
|
|
4227
5486
|
}
|
|
4228
5487
|
function buildOutput(views, format, settings, spacing) {
|
|
4229
|
-
const asset =
|
|
5488
|
+
const asset = buildFromPreparedViews(views, format === "glb" ? "mesh" : "stack", settings);
|
|
4230
5489
|
if (asset.target === "mesh") return { format: "glb", bytes: encodeGlb(asset) };
|
|
4231
5490
|
const bundle = encodeStack(respaceStack(asset, spacing));
|
|
4232
5491
|
return { format: "stack", png: bundle.png, manifest: JSON.stringify(bundle.manifest, null, 2) + "\n" };
|