stack3js 0.0.0-stage → 0.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/COMMAND.md +145 -0
  2. package/LICENSE +21 -0
  3. package/README.md +304 -2
  4. package/THIRD-PARTY-LICENSES.md +100 -0
  5. package/bin/stack3.mjs +5437 -0
  6. package/blender/import_stack.py +89 -0
  7. package/examples/future-tank.stack3.json +1 -0
  8. package/examples/traffic-cone-4view.png +0 -0
  9. package/meshing/blocks.py +82 -0
  10. package/meshing/branches.py +62 -0
  11. package/meshing/dexel.py +67 -0
  12. package/meshing/field_data.py +19 -0
  13. package/meshing/finish_blender.py +203 -0
  14. package/meshing/finishing.py +155 -0
  15. package/meshing/geometry.py +71 -0
  16. package/meshing/guided.py +150 -0
  17. package/meshing/implicit.py +178 -0
  18. package/meshing/intersection.py +33 -0
  19. package/meshing/material.py +115 -0
  20. package/meshing/mesh.py +103 -0
  21. package/meshing/network.py +136 -0
  22. package/meshing/regularization.py +213 -0
  23. package/meshing/sections.py +165 -0
  24. package/meshing/signed_distance.py +93 -0
  25. package/package.json +32 -4
  26. package/references/hard-surface/README.md +40 -0
  27. package/references/hard-surface/atlas/concrete-barrier-4view.png +0 -0
  28. package/references/hard-surface/atlas/preview.pipeline.yaml +14 -0
  29. package/references/hard-surface/case-studies/benchmark/README.md +22 -0
  30. package/references/hard-surface/case-studies/benchmark/lod-bevel.pipeline.yaml +258 -0
  31. package/references/hard-surface/finishing/exports.yaml +10 -0
  32. package/references/hard-surface/finishing/finish-lod.pipeline.yaml +33 -0
  33. package/references/hard-surface/finishing/inputs/stack/stack.json +1 -0
  34. package/references/hard-surface/finishing/inputs/stack/stack.png +0 -0
  35. package/references/hard-surface/finishing/regularize.pipeline.yaml +46 -0
  36. package/references/hard-surface/measured-depth/sdf/compare.pipeline.yaml +12 -0
  37. package/references/hard-surface/measured-depth/sdf/inputs/field.npy +0 -0
  38. package/references/hard-surface/measured-depth/sdf/inputs/stack/stack.json +1 -0
  39. package/references/hard-surface/measured-depth/sdf/inputs/stack/stack.png +0 -0
  40. package/references/hard-surface/measured-depth/sdf/inputs/truth.json +1 -0
  41. package/references/hard-surface/measured-depth/sdf/sdf.guide.json +3 -0
  42. package/references/hard-surface/measured-depth/triple-dexel/compare.pipeline.yaml +12 -0
  43. package/references/hard-surface/measured-depth/triple-dexel/dexel.guide.json +3 -0
  44. package/references/hard-surface/measured-depth/triple-dexel/inputs/fixture.json +22 -0
  45. package/references/hard-surface/measured-depth/triple-dexel/inputs/stack/stack.json +22 -0
  46. package/references/hard-surface/measured-depth/triple-dexel/inputs/stack/stack.png +0 -0
  47. package/references/hard-surface/measured-depth/triple-dexel/inputs/triple-dexel.npz +0 -0
  48. package/references/hard-surface/schema/pipeline-fragment.schema.json +5 -0
  49. package/references/hard-surface/schema/pipeline.schema.json +181 -0
  50. package/schema/pipeline-fragment.schema.json +5 -0
  51. package/schema/pipeline.schema.json +181 -0
  52. package/verification/assembly.py +96 -0
  53. package/verification/landmarks.py +53 -0
  54. package/verification/panels.py +137 -0
  55. package/verification/projections.py +135 -0
  56. package/verification/verify.py +108 -0
  57. package/viewer/dist/THIRD-PARTY-LICENSES.md +174 -0
  58. package/viewer/dist/assets/GLTFExporter-xdVCArY-.js +1 -0
  59. package/viewer/dist/assets/ant-mech-angled-leg-4view-BO2qt1_k.png +0 -0
  60. package/viewer/dist/assets/ant-mech-body-4view-D9xVPpbc.png +0 -0
  61. package/viewer/dist/assets/ant-mech-center-leg-4view-BcphjF_G.png +0 -0
  62. package/viewer/dist/assets/compare-B6DWTZS9.css +1 -0
  63. package/viewer/dist/assets/compare-Du4RoRQO.js +6 -0
  64. package/viewer/dist/assets/compare.worker-CgJq-znx.js +21 -0
  65. package/viewer/dist/assets/concrete-barrier-4view-7PsO3Ftq.png +0 -0
  66. package/viewer/dist/assets/emscripten-module-uFzwHH0Y.wasm +0 -0
  67. package/viewer/dist/assets/emscripten-module.browser-BcR5qphc.js +1 -0
  68. package/viewer/dist/assets/ffi-Boa1QuFa.js +1 -0
  69. package/viewer/dist/assets/fillet-rover-body-4-view-Chk8Mx4R.png +0 -0
  70. package/viewer/dist/assets/fillet-rover-wheel-4-view-B-F8flOC.png +0 -0
  71. package/viewer/dist/assets/hull-4view-BPPqJYUz.png +0 -0
  72. package/viewer/dist/assets/hull-base-color-4view-DrQmdT3h.png +0 -0
  73. package/viewer/dist/assets/hull-clay-4view-3Cu-4Hvr.png +0 -0
  74. package/viewer/dist/assets/hull-depth-4view-DCOdT5ev.png +0 -0
  75. package/viewer/dist/assets/hull-normal-4view-CvLaFITy.png +0 -0
  76. package/viewer/dist/assets/inspection-robot-body-4-view-CLMaHFYm.png +0 -0
  77. package/viewer/dist/assets/inspection-robot-wheel-4-view-27wRsxcs.png +0 -0
  78. package/viewer/dist/assets/plastic-barrier-4view-DQkTBW_i.png +0 -0
  79. package/viewer/dist/assets/presets-jXE0t1fU.js +1 -0
  80. package/viewer/dist/assets/preview-cache-BKV0EZl9.js +1 -0
  81. package/viewer/dist/assets/project-BzR9Ensg.css +1 -0
  82. package/viewer/dist/assets/project-DtHHhfo-.js +17 -0
  83. package/viewer/dist/assets/reconstruct.worker-ONc9GyFO.js +21 -0
  84. package/viewer/dist/assets/script-engine-Bs3azDYZ.js +6 -0
  85. package/viewer/dist/assets/style-CMUT8CmM.css +1 -0
  86. package/viewer/dist/assets/style-D6eZHs3D.js +4004 -0
  87. package/viewer/dist/assets/tank-hull-4view-B4sMMkP5.png +0 -0
  88. package/viewer/dist/assets/tank-track-4view-DAIiMTy3.png +0 -0
  89. package/viewer/dist/assets/tank-turret-4view-Cx0FuNFu.png +0 -0
  90. package/viewer/dist/assets/traffic-cone-4view-DG-TkITx.png +0 -0
  91. package/viewer/dist/assets/viewer-DIjS0No7.js +2 -0
  92. package/viewer/dist/assets/wet-floor-sign-4view-CWJDyeTX.png +0 -0
  93. package/viewer/dist/compare.html +47 -0
  94. package/viewer/dist/examples/traffic-cone-4view.png +0 -0
  95. package/viewer/dist/index.html +148 -0
  96. package/viewer/dist/playground/index.html +3342 -0
  97. package/viewer/dist/project.html +83 -0
@@ -0,0 +1,136 @@
1
+ """Registered planar constraints blended into the stack distance field, with measured re-cuts."""
2
+
3
+ from itertools import combinations
4
+
5
+ import numpy as np
6
+ import shapely as sh
7
+ from geometry import profile, unit
8
+ from guided import vector
9
+ from implicit import iso
10
+ from scipy.ndimage import distance_transform_edt, map_coordinates
11
+ from shapely.geometry import LineString, MultiLineString
12
+
13
+
14
+ def registered(data, box_min, box_max):
15
+ if not isinstance(data, dict) or data.get("source") != "independent":
16
+ raise ValueError("each section must declare source independent (actual cuts only)")
17
+ origin, u, v = [vector(data, name) for name in ("origin", "u", "v")]
18
+ if not np.allclose([u @ u, v @ v, u @ v], [1, 1, 0], atol=1e-7, rtol=0):
19
+ raise ValueError("section u and v must be orthonormal unit vectors")
20
+ uv = np.stack((u, v))
21
+ shape = profile(data)
22
+ pts = sh.get_coordinates(shape) @ uv + origin
23
+ if np.any(pts < box_min - 1e-8) or np.any(pts > box_max + 1e-8):
24
+ raise ValueError("section leaves the saved part frame")
25
+ return origin, uv, np.cross(u, v), shape
26
+
27
+
28
+ def line_intervals(section, on_line, direction, span):
29
+ origin, uv, _, polygon = section
30
+ endpoints = on_line + np.array([[-2 * span], [2 * span]]) * direction
31
+ hit = polygon.intersection(LineString((endpoints - origin) @ uv.T))
32
+ spans = []
33
+ for piece in sh.get_parts(hit):
34
+ if piece.is_empty:
35
+ continue
36
+ points = sh.get_coordinates(piece) @ uv + origin
37
+ t = (points - on_line) @ direction
38
+ spans.append((t.min(), t.max()))
39
+ merged = []
40
+ for low, high in sorted(spans):
41
+ if merged and low <= merged[-1][1] + span * 1e-8:
42
+ merged[-1][1] = max(high, merged[-1][1])
43
+ else:
44
+ merged.append([low, high])
45
+ return np.asarray(merged).reshape(-1, 2)
46
+
47
+
48
+ def check_pairs(sections, center, span):
49
+ crossing = False
50
+ for a, b in combinations(sections, 2):
51
+ direction = np.cross(a[2], b[2])
52
+ if np.linalg.norm(direction) < 1e-8:
53
+ if abs((a[0] - b[0]) @ a[2]) < span * 1e-8:
54
+ raise ValueError("duplicate section planes")
55
+ continue
56
+ direction = unit(direction)
57
+ on_line = center + np.linalg.solve(
58
+ [a[2], b[2], direction], [(a[0] - center) @ a[2], (b[0] - center) @ b[2], 0]
59
+ )
60
+ first, second = (line_intervals(section, on_line, direction, span) for section in (a, b))
61
+ if len(first) != len(second) or not np.allclose(first, second, rtol=0, atol=span * 1e-6):
62
+ raise ValueError("independent contours disagree along their plane intersection")
63
+ crossing |= np.any(first[:, 1] - first[:, 0] > span * 1e-8)
64
+ if not crossing:
65
+ raise ValueError("need nonparallel independent sections crossing inside the part")
66
+
67
+
68
+ def recut(verts, faces, section, tolerance):
69
+ origin, uv, normal, target = section
70
+ distance = (verts - origin) @ normal
71
+ # Half-open predicate counts a cut passing through a vertex just once.
72
+ tri = faces[(distance[faces].min(axis=1) < 0) & (distance[faces].max(axis=1) >= 0)]
73
+ hits = [[] for _ in range(len(tri))]
74
+ for j in range(3):
75
+ a, b = tri[:, j], tri[:, (j + 1) % 3]
76
+ cut = np.flatnonzero((distance[a] < 0) != (distance[b] < 0))
77
+ t = distance[a[cut]] / (distance[a[cut]] - distance[b[cut]])
78
+ p = verts[a[cut]] + (verts[b[cut]] - verts[a[cut]]) * t[:, None]
79
+ for i, point in zip(cut, (p - origin) @ uv.T):
80
+ hits[i].append(point)
81
+ if not hits:
82
+ return np.inf, False
83
+ lines = sh.set_precision(MultiLineString(hits), tolerance * 1e-5)
84
+ area = sh.build_area(sh.union_all(sh.get_parts(lines)))
85
+ if area.is_empty:
86
+ return np.inf, False
87
+ same = sh.get_num_geometries(area) == 1 and sh.get_num_interior_rings(area) == len(target.interiors)
88
+ return float(sh.hausdorff_distance(area.boundary, target.boundary, densify=0.25)), same
89
+
90
+
91
+ def section_network(mask, step, origin, guide):
92
+ data = guide.get("sections")
93
+ if not isinstance(data, list) or len(data) < 2:
94
+ raise ValueError("sections must contain at least two independent cuts")
95
+ extent = np.array(mask.shape) * step
96
+ sections = [registered(d, origin, origin + extent) for d in data]
97
+ check_pairs(sections, origin + extent * 0.5, np.linalg.norm(extent))
98
+ padded = np.pad(mask, 1)
99
+ prior = distance_transform_edt(padded, sampling=step) - distance_transform_edt(~padded, sampling=step)
100
+ tolerance = guide.get("tolerance", np.linalg.norm(step) * 0.6)
101
+ if not isinstance(tolerance, (int, float)) or not np.isfinite(tolerance) or tolerance <= 0:
102
+ raise ValueError("tolerance must be a positive distance in scene units")
103
+ for factor in (2, 4):
104
+ dimensions = np.array(mask.shape) * factor + 3
105
+ if np.prod(dimensions) > 40_000_000:
106
+ raise ValueError("section-network refinement exceeds 40 million samples")
107
+ field = np.empty(dimensions, dtype=np.float32)
108
+ yz = np.indices(dimensions[1:]).reshape(2, -1).T
109
+ for x in range(dimensions[0]):
110
+ grid = (np.column_stack((np.full(len(yz), x), yz)) - 1) / factor
111
+ p = grid * step + origin
112
+ field_sum = map_coordinates(prior, (grid + 0.5).T, order=1, mode="nearest")
113
+ weights = np.ones(len(p))
114
+ for o, uv, n, shape in sections:
115
+ dist = np.abs((p - o) @ n)
116
+ radius = 3 * np.linalg.norm(step)
117
+ near = dist < radius
118
+ coords = (p[near] - o) @ uv.T
119
+ pts = sh.points(coords)
120
+ signed = sh.distance(pts, shape.boundary) * np.where(sh.contains_xy(shape, *coords.T), 1, -1)
121
+ w = (1 - dist[near] / radius) ** 2 / np.maximum(dist[near] / radius, 1e-7) ** 2
122
+ field_sum[near] += w * signed
123
+ weights[near] += w
124
+ field[x] = (field_sum / weights).reshape(dimensions[1:])
125
+ for a in range(3):
126
+ border = np.moveaxis(field, a, 0)
127
+ border[[0, -1]] = -min(step) / factor
128
+ p, f = iso(field, 0)
129
+ p = (p - 1) / factor
130
+ results = [recut(p * step + origin, f, s, tolerance) for s in sections]
131
+ if all(ok and d <= tolerance for d, ok in results):
132
+ print(
133
+ f"independent re-cut Hausdorff distances {[round(d, 8) for d, _ in results]}, tolerance {tolerance:g}"
134
+ )
135
+ return p, f
136
+ raise ValueError(f"re-cut exceeds tolerance or has wrong loop count: {results}")
@@ -0,0 +1,213 @@
1
+ """Opt-in, guided surface regularization on a shared indexed mesh."""
2
+
3
+ import numpy as np
4
+ from scipy.optimize import least_squares
5
+
6
+ from geometry import unit
7
+
8
+
9
+ def in_bounds(points, bounds):
10
+ lo, hi = np.asarray(bounds, dtype=float)
11
+ return np.all((points >= lo) & (points <= hi), axis=-1)
12
+
13
+
14
+ def plane_fit(points, vertex_normals, guide, tolerance):
15
+ hint = unit(np.asarray(guide["normal"], dtype=float))
16
+ ids = np.flatnonzero(in_bounds(points, guide["bounds"]) & (abs(vertex_normals @ hint) >= 0.85))
17
+ if len(ids) < 6:
18
+ return None
19
+ cloud = points[ids]
20
+ center = cloud.mean(axis=0)
21
+ _, values, basis = np.linalg.svd(cloud - center, full_matrices=False)
22
+ normal = basis[-1]
23
+ if normal @ hint < 0:
24
+ normal = -normal
25
+ if values[1] <= values[0] * 1e-8 or np.max(abs((cloud - center) @ normal)) > tolerance:
26
+ return None
27
+ return ids, center, normal
28
+
29
+
30
+ def round_constraints(points, vertex_normals, guide, tolerance):
31
+ center = np.asarray(guide["center"], dtype=float)
32
+ axis = unit(np.asarray(guide["axis"], dtype=float))
33
+ first = unit(np.cross(axis, np.eye(3)[np.argmin(abs(axis))]))
34
+ basis = np.column_stack((first, np.cross(axis, first)))
35
+ relative = points - center
36
+ coords = relative @ basis
37
+ radial_hint = unit(coords) @ basis.T
38
+ selected = abs(np.linalg.norm(coords, axis=1) - guide["radius"]) <= tolerance
39
+ if guide["type"] == "circle":
40
+ selected &= abs(relative @ axis) <= tolerance
41
+ else:
42
+ selected &= in_bounds(points, guide["bounds"]) & (abs(np.sum(vertex_normals * radial_hint, axis=1)) >= 0.75)
43
+ ids = np.flatnonzero(selected)
44
+ if len(ids) < 6:
45
+ return []
46
+ sample = coords[ids]
47
+ system = np.column_stack((2 * sample, np.ones(len(ids))))
48
+ result, _, rank, _ = np.linalg.lstsq(system, np.sum(sample**2, axis=1), rcond=None)
49
+ radius2 = result[-1] + np.dot(result[:-1], result[:-1])
50
+ if rank != 3 or radius2 <= 0:
51
+ return []
52
+ radius = np.sqrt(radius2)
53
+ radial = sample - result[:2]
54
+ distances = np.linalg.norm(radial, axis=1)
55
+ error = radius - distances
56
+ if (np.linalg.norm(result[:2]) > tolerance or abs(radius - guide["radius"]) > tolerance
57
+ or np.any(distances == 0) or np.max(abs(error)) > tolerance):
58
+ return []
59
+ constraints = [(ids, unit(radial) @ basis.T, error)]
60
+ if guide["type"] == "circle":
61
+ heights = relative[ids] @ axis
62
+ constraints.append((ids, np.broadcast_to(axis, (len(ids), 3)), heights.mean() - heights))
63
+ return constraints
64
+
65
+
66
+ def polygon_constraints(points, guide, tolerance):
67
+ corners = np.asarray(guide["corners"], dtype=float)
68
+ center = corners.mean(axis=0)
69
+ _, values, local = np.linalg.svd(corners - center, full_matrices=False)
70
+ normal = local[-1]
71
+ if values[1] <= values[0] * 1e-8 or np.max(abs((corners - center) @ normal)) > tolerance:
72
+ raise ValueError(f'polygon {guide["id"]}: corners must define a plane')
73
+ basis = local[:2].T
74
+ contour = (corners - center) @ basis
75
+ nearby = np.flatnonzero(abs((points - center) @ normal) <= tolerance)
76
+ coords = (points[nearby] - center) @ basis
77
+ lines = []
78
+ for a, b in zip(contour, np.roll(contour, -1, axis=0)):
79
+ direction = b - a
80
+ squared_length = np.dot(direction, direction)
81
+ if not squared_length:
82
+ raise ValueError(f'polygon {guide["id"]}: two consecutive corners coincide')
83
+ t = (coords - a) @ direction / squared_length
84
+ nearest = a + np.clip(t, 0, 1)[:, None] * direction
85
+ within = np.linalg.norm(coords - nearest, axis=1) <= tolerance
86
+ sample = coords[within & (t > 0.08) & (t < 0.92)]
87
+ if len(sample) < 3:
88
+ return []
89
+ side_center = sample.mean(axis=0)
90
+ _, _, vh = np.linalg.svd(sample - side_center, full_matrices=False)
91
+ side_normal = vh[-1]
92
+ if abs(side_normal @ unit(direction)) > 0.34:
93
+ return []
94
+ lines.append((side_normal, side_center @ side_normal, within))
95
+ # Adjacent fitted lines must meet near the supplied corners.
96
+ for i, corner in enumerate(contour):
97
+ previous, current = lines[i - 1], lines[i]
98
+ matrix = np.asarray([previous[0], current[0]])
99
+ if abs(np.linalg.det(matrix)) < 0.05:
100
+ return []
101
+ fit = np.linalg.solve(matrix, [previous[1], current[1]])
102
+ if np.linalg.norm(fit - corner) > 2 * tolerance:
103
+ return []
104
+ result = []
105
+ selected = np.zeros(len(nearby), dtype=bool)
106
+ for normal2, offset, within in lines:
107
+ ids = nearby[within]
108
+ result.append((ids, np.broadcast_to(basis @ normal2, (len(ids), 3)), offset - coords[within] @ normal2))
109
+ selected |= within
110
+ ids = nearby[selected]
111
+ result.append((ids, np.broadcast_to(normal, (len(ids), 3)), -(points[ids] - center) @ normal))
112
+ return result
113
+
114
+
115
+ def optimize_planes(points, planes, relations, tolerance):
116
+ active = [row for row in relations if all(key in planes for key in row["features"])]
117
+ if not active:
118
+ return {key: (normal, 0.) for key, (_, _, normal) in planes.items()}, 0, 0.
119
+ keys = sorted({key for row in active for key in row["features"]})
120
+ clouds = {key: points[planes[key][0]] - planes[key][1] for key in keys}
121
+ scale = max([tolerance] + [np.linalg.norm(np.ptp(p, axis=0)) for p in clouds.values()])
122
+
123
+ def parameters(value):
124
+ return {key: (unit(row[:3]), row[3] * tolerance) for key, row in zip(keys, value.reshape(-1, 4))}
125
+
126
+ def relation_errors(fits):
127
+ errors = []
128
+ for row in active:
129
+ a, b = row["features"]
130
+ na, da = fits[a]
131
+ nb, db = fits[b]
132
+ if row["type"] == "perpendicular":
133
+ errors.append(np.array([na @ nb]))
134
+ continue
135
+ errors.append(np.cross(na, nb))
136
+ if row["type"] == "coplanar":
137
+ difference = planes[b][1] + nb * db - (planes[a][1] + na * da)
138
+ errors.append(np.array([na @ difference / scale]))
139
+ return np.concatenate(errors)
140
+
141
+ def residual(value):
142
+ fits = parameters(value)
143
+ data = [(clouds[k] @ fits[k][0] - fits[k][1]) / (scale * np.sqrt(len(clouds[k]))) for k in keys]
144
+ lengths = np.linalg.norm(value.reshape(-1, 4)[:, :3], axis=1) - 1.
145
+ return np.concatenate([*data, lengths, 10 * relation_errors(fits)])
146
+
147
+ start = np.array([np.r_[planes[key][2], 0.] for key in keys]).ravel()
148
+ initial = {key: (normal, 0.) for key, (_, _, normal) in planes.items()}
149
+ result = least_squares(residual, start, max_nfev=100)
150
+ fitted = parameters(result.x)
151
+ if not result.success or any(np.max(abs(clouds[key] @ n - d)) > tolerance for key, (n, d) in fitted.items()):
152
+ return initial, 0, float(np.max(abs(relation_errors(initial))))
153
+ initial.update(fitted)
154
+ return initial, len(active), float(np.max(abs(relation_errors(initial))))
155
+
156
+
157
+ def safe_displacement(points, faces, step):
158
+ # Compare at export precision. Restrict only vertices incident to unsafe faces.
159
+ a, b, c = points.astype(np.float32).astype(float)[faces].transpose(1, 0, 2)
160
+ normals = np.cross(b - a, c - a)
161
+ areas = np.sum(normals**2, axis=1)
162
+ step = step.copy()
163
+ for _ in range(10):
164
+ candidate = points + step
165
+ a, b, c = candidate.astype(np.float32).astype(float)[faces].transpose(1, 0, 2)
166
+ bad = np.sum(np.cross(b - a, c - a) * normals, axis=1) <= 0.1 * areas
167
+ if not bad.any():
168
+ return candidate
169
+ blocked = np.unique(faces[bad])
170
+ step[blocked] = 0.
171
+ return points
172
+
173
+
174
+ def regularize(points, faces, options):
175
+ tolerance = options["tolerance"]
176
+ p, q, r = points[faces].transpose(1, 0, 2)
177
+ normals = np.cross(q - p, r - p)
178
+ vertex_normals = np.zeros_like(points)
179
+ for i in range(3):
180
+ np.add.at(vertex_normals, faces[:, i], normals)
181
+ vertex_normals = unit(vertex_normals)
182
+ planes, constraints, accepted = {}, [], []
183
+ for feature in options["features"]:
184
+ key, kind = feature["id"], feature["type"]
185
+ if kind == "plane":
186
+ fit = plane_fit(points, vertex_normals, feature, tolerance)
187
+ if fit is not None:
188
+ planes[key] = fit
189
+ accepted.append(key)
190
+ else:
191
+ fit = polygon_constraints(points, feature, tolerance) if kind == "polygon" else round_constraints(points, vertex_normals, feature, tolerance)
192
+ if fit:
193
+ constraints.extend(fit)
194
+ accepted.append(key)
195
+ fitted, relations, residual = optimize_planes(points, planes, options["relations"], tolerance)
196
+ for key, (ids, center, _) in planes.items():
197
+ normal, offset = fitted[key]
198
+ constraints.append((ids, np.broadcast_to(normal, (len(ids), 3)), offset - (points[ids] - center) @ normal))
199
+ system = np.zeros((len(points), 3, 3))
200
+ rhs = np.zeros_like(points)
201
+ for ids, directions, error in constraints:
202
+ system[ids] += directions[:, :, None] * directions[:, None, :]
203
+ rhs[ids] += directions * error[:, None]
204
+ active = np.flatnonzero(np.any(rhs != 0, axis=1))
205
+ displacement = np.zeros_like(points)
206
+ if len(active):
207
+ displacement[active] = (np.linalg.pinv(system[active], rcond=0.05) @ rhs[active, :, None])[:, :, 0]
208
+ displacement[np.linalg.norm(displacement, axis=1) > 2 * tolerance] = 0.
209
+ result = safe_displacement(points, faces, displacement)
210
+ rejected = [feature["id"] for feature in options["features"] if feature["id"] not in accepted]
211
+ moved = int(np.count_nonzero(np.any(points.astype(np.float32) != result.astype(np.float32), axis=1)))
212
+ print(f"regularization: fitted {accepted}; skipped {rejected}; optimized {relations}/{len(options['relations'])} plane relations; relation residual {residual:.4g}; moved {moved} vertices")
213
+ return result
@@ -0,0 +1,165 @@
1
+ import itertools
2
+
3
+ import numpy as np
4
+ import shapely as sh
5
+ from geometry import (
6
+ connect,
7
+ cyclic,
8
+ indexed,
9
+ planar_triangles,
10
+ polygons,
11
+ profile,
12
+ region,
13
+ xyz,
14
+ )
15
+ from scipy.interpolate import PchipInterpolator
16
+ from scipy.optimize import linear_sum_assignment
17
+ from shapely.geometry import Polygon
18
+
19
+
20
+ def heightfield(mask, axis):
21
+ stack = mask.transpose(cyclic(axis))
22
+ filled = stack.any(axis=2)
23
+ starts = stack & ~np.pad(stack[:, :, :-1], ((0, 0), (0, 0), (1, 0)))
24
+ multiple = int((starts.sum(axis=2) > 1).sum())
25
+ print(f"heightfield filled {multiple} multi-interval columns")
26
+ low = stack.argmax(axis=2)
27
+ high = stack.shape[2] - stack[:, :, ::-1].argmax(axis=2)
28
+ # Average the column endpoints incident on each footprint corner.
29
+ count = np.zeros(np.array(filled.shape) + 1)
30
+ heights = np.zeros((*count.shape, 2))
31
+ for i in (0, 1):
32
+ for j in (0, 1):
33
+ area = np.s_[i : i + filled.shape[0], j : j + filled.shape[1]]
34
+ count[area] += filled
35
+ heights[area] += np.stack((low, high), axis=2) * filled[:, :, None]
36
+ heights /= np.maximum(count, 1)[:, :, None]
37
+ triangles = []
38
+ offsets = np.array([[0, 0], [1, 0], [1, 1], [0, 1]])
39
+ for x, y in np.argwhere(filled):
40
+ uv = offsets + [x, y]
41
+ lo, hi = [np.column_stack((uv, heights[uv[:, 0], uv[:, 1], i])) for i in (0, 1)]
42
+ triangles.extend(lo[[[2, 1, 0], [3, 2, 0]]])
43
+ triangles.extend(hi[[[0, 1, 2], [0, 2, 3]]])
44
+ for i, (dx, dy) in enumerate(((0, -1), (1, 0), (0, 1), (-1, 0))):
45
+ a, b = x + dx, y + dy
46
+ if 0 <= a < filled.shape[0] and 0 <= b < filled.shape[1] and filled[a, b]:
47
+ continue
48
+ j = (i + 1) % 4
49
+ triangles.extend(([lo[i], lo[j], hi[j]], [lo[i], hi[j], hi[i]]))
50
+ return indexed(xyz(triangles, axis))
51
+
52
+
53
+ def match(previous, current):
54
+ if len(previous) != len(current):
55
+ raise ValueError("section loop count changes; choose branch-loft")
56
+ if not previous:
57
+ return []
58
+ overlap = np.array([[a.intersection(b).area for b in current] for a in previous])
59
+ rows, cols = linear_sum_assignment(-overlap)
60
+ if (overlap[rows, cols] <= 0).any():
61
+ raise ValueError("no overlapping section correspondence; choose branch-loft")
62
+ return [current[j] for j in cols]
63
+
64
+
65
+ def sample_ring(ring, count, metric, prev):
66
+ p = np.asarray(ring.coords) * metric
67
+ distance = np.r_[0, np.cumsum(np.linalg.norm(np.diff(p, axis=0), axis=1))]
68
+ stations = np.arange(count) * distance[-1] / count
69
+ pts = np.column_stack([np.interp(stations, distance, p[:, i]) for i in (0, 1)])
70
+ if prev is not None:
71
+ prev = prev * metric
72
+ # Circular least-squares alignment, including the wraparound seam.
73
+ costs = [np.square(np.roll(pts, shift, axis=0) - prev).sum() for shift in range(count)]
74
+ pts = np.roll(pts, np.argmin(costs), axis=0)
75
+ return pts / metric
76
+
77
+
78
+ def loft(mask, step, origin, axis, smooth, controls):
79
+ u, v, _ = cyclic(axis)
80
+ metric = step[[u, v]]
81
+ stack = mask.transpose(cyclic(axis))
82
+ occupied = np.flatnonzero(stack.any(axis=(0, 1)))
83
+ if np.any(np.diff(occupied) != 1):
84
+ raise ValueError("empty intermediate section; choose branch-loft")
85
+ overrides = {}
86
+ if controls is not None:
87
+ if not isinstance(controls, list) or not controls:
88
+ raise ValueError("stations must be a nonempty list of slice objects")
89
+ from shapely.affinity import affine_transform
90
+
91
+ for station in controls:
92
+ if not isinstance(station, dict) or set(station) - {"slice", "outer", "holes"}:
93
+ raise ValueError("station needs slice and optional outer and holes")
94
+ k = station.get("slice")
95
+ if type(k) is not int or k not in occupied or k in overrides:
96
+ raise ValueError(f"duplicate or unoccupied control slice: {k}")
97
+ polygon = None
98
+ if "outer" in station or "holes" in station:
99
+ polygon = affine_transform(
100
+ profile(station),
101
+ [1 / step[u], 0, 0, 1 / step[v], -origin[u] / step[u], -origin[v] / step[v]],
102
+ )
103
+ bounds = sh.box(0, 0, stack.shape[0], stack.shape[1])
104
+ if not bounds.buffer(1e-9).covers(polygon):
105
+ raise ValueError(f"control contour leaves part frame at slice {k}")
106
+ overrides[k] = polygon
107
+ print(
108
+ "loft control slices:",
109
+ sorted(overrides),
110
+ "user contours:",
111
+ sorted(k for k, p in overrides.items() if p is not None),
112
+ )
113
+ series = []
114
+ for k in occupied:
115
+ current = [sh.orient_polygons(p) for p in polygons(region(stack[:, :, k]))]
116
+ replacement = overrides.get(k)
117
+ if replacement is not None:
118
+ if len(current) != 1 or replacement.intersection(current[0]).area == 0:
119
+ raise ValueError(f"control contour does not match a unique occupied part at slice {k}")
120
+ current = [replacement]
121
+ series.append(match(series[-1], current) if series else current)
122
+ triangles = []
123
+ for parts in zip(*series):
124
+ tracks = [[p.exterior for p in parts]]
125
+ ordered_holes = []
126
+ for part in parts:
127
+ holes = [Polygon(h) for h in part.interiors]
128
+ ordered_holes.append(match(ordered_holes[-1], holes) if ordered_holes else holes)
129
+ selected = [
130
+ i
131
+ for i, k in enumerate(occupied)
132
+ if not overrides or k in overrides or i in (0, len(occupied) - 1)
133
+ ]
134
+ tracks.extend([[h.exterior for h in group] for group in zip(*ordered_holes)])
135
+ tracks = [[track[i] for i in selected] for track in tracks]
136
+ stations = np.r_[occupied[0], occupied[selected] + 0.5, occupied[-1] + 1]
137
+ samples = stations
138
+ if smooth:
139
+ intervals = [
140
+ np.linspace(a, b, max(2, int(np.ceil((b - a) * 2))), endpoint=False)
141
+ for a, b in itertools.pairwise(stations)
142
+ ]
143
+ samples = np.concatenate([*intervals, stations[-1:]])
144
+ surfaces = []
145
+ for track in tracks:
146
+ count = min(512, max(16, 4 * max(len(r.coords) for r in track)))
147
+ rings = []
148
+ for r in track:
149
+ rings.append(sample_ring(r, count, metric, rings[-1] if rings else None))
150
+ rings = np.array([rings[0], *rings, rings[-1]])
151
+ if smooth:
152
+ rings = PchipInterpolator(stations, rings, axis=0)(samples)
153
+ surfaces.append(rings)
154
+ points = [np.column_stack((r, np.full(count, t))) for r, t in zip(rings, samples)]
155
+ for a, b in itertools.pairwise(points):
156
+ triangles.extend(connect(a, b))
157
+ for i, t in enumerate(samples):
158
+ section = Polygon(surfaces[0][i], [hole[i] for hole in surfaces[1:]])
159
+ if not section.is_valid:
160
+ raise ValueError(f"loft self-intersects at station {t}; choose branch-loft")
161
+ if i in (0, len(samples) - 1):
162
+ for tri in planar_triangles(section):
163
+ cap = np.column_stack((tri, np.full(3, t)))
164
+ triangles.append(cap[::-1] if i == 0 else cap)
165
+ return indexed(xyz(triangles, axis))
@@ -0,0 +1,93 @@
1
+ # /// script
2
+ # requires-python = ">=3.11,<3.14"
3
+ # dependencies = ["gpytoolbox==0.3.8", "numpy==2.2.6", "scipy==1.15.3", "scikit-image==0.25.2", "shapely==2.1.2"]
4
+ # ///
5
+ """Carrera et al.'s Dual Contouring of Signed Distance Data using Gpytoolbox."""
6
+
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+ from gpytoolbox import dual_contouring_of_signed_distance_data
12
+ from scipy.ndimage import distance_transform_edt, map_coordinates
13
+
14
+ from field_data import load_field
15
+ from finishing import edge_pairs, topology
16
+ from mesh import run
17
+
18
+
19
+ def orient_surface(vertices, faces, field, step):
20
+ directed, edges, owners = edge_pairs(faces)
21
+ if len(edges) % 2 or not np.array_equal(edges[::2], edges[1::2]) or np.any(np.all(edges[2::2] == edges[:-2:2], axis=1)):
22
+ raise ValueError("signed distance contouring produced an ambiguous surface; try mc33 or a finer grid")
23
+ # Join matching edges consistently, then use the field to orient each sheet.
24
+ neighbors = [[] for _ in faces]
25
+ for a, b, same in zip(owners[::2], owners[1::2], directed[::2, 0] == directed[1::2, 0]):
26
+ neighbors[a].append((b, same))
27
+ neighbors[b].append((a, same))
28
+ result = faces.copy()
29
+ parity = np.full(len(faces), -1, dtype=np.int8)
30
+ gradient = np.gradient(field, *step)
31
+ for seed in range(len(faces)):
32
+ if parity[seed] >= 0:
33
+ continue
34
+ parity[seed] = 0
35
+ component = [seed]
36
+ for face in component:
37
+ for next_face, same in neighbors[face]:
38
+ expected = parity[face] ^ same
39
+ if parity[next_face] < 0:
40
+ parity[next_face] = expected
41
+ component.append(next_face)
42
+ elif parity[next_face] != expected:
43
+ raise ValueError("signed distance contouring produced a non-orientable surface")
44
+ indices = np.asarray(component)
45
+ flipped = parity[indices] == 1
46
+ a, b, c = vertices[faces[indices]].transpose(1, 0, 2)
47
+ normal = np.cross(b - a, c - a)
48
+ normal[flipped] *= -1
49
+ centers = ((a + b + c) / 3 / step + 0.5).T
50
+ outward = np.stack([map_coordinates(axis, centers, order=1, mode="nearest") for axis in gradient], axis=1)
51
+ if np.einsum("ij,ij->", normal, outward) < 0:
52
+ flipped = ~flipped
53
+ result[indices[flipped]] = result[indices[flipped], ::-1]
54
+ topology(vertices, result)
55
+ return result
56
+
57
+
58
+ def signed_distance_mesh(mask, step, guide, guide_directory):
59
+ occupied = np.pad(mask, 1)
60
+ if "field" in guide:
61
+ field = load_field(occupied, guide["field"], guide_directory)
62
+ else:
63
+ # Center-to-center distances provide a sampled approximation from occupancy.
64
+ field = distance_transform_edt(~occupied, sampling=step) - distance_transform_edt(occupied, sampling=step)
65
+ iterations = {}
66
+ for field_name, option, default in [("outerIterations", "outer_iters", 3), ("innerIterations", "inner_iters", 12)]:
67
+ value = guide.get(field_name, default)
68
+ if type(value) is not int or not 1 <= value <= 100:
69
+ raise ValueError(f"{field_name} must be an integer from 1 to 100")
70
+ iterations[option] = value
71
+ points = np.stack(np.unravel_index(np.arange(occupied.size), occupied.shape, order="F"), axis=1)
72
+ # Gpytoolbox always includes these near-surface samples. Its larger default
73
+ # batch adds a randomly ordered set of distant samples with no seed option.
74
+ near_band = 3 * np.sqrt(3) * step.min() * (1 - 1e-9)
75
+ batch_size = max(1, int(np.count_nonzero(np.abs(field) < near_band)))
76
+ vertices, quads = dual_contouring_of_signed_distance_data(
77
+ field.ravel(order="F"), (points - 0.5) * step, *occupied.shape, batch_size=batch_size, **iterations,
78
+ )
79
+ if not len(quads):
80
+ raise ValueError("signed distance contouring returned an empty surface")
81
+ d02 = np.linalg.norm(vertices[quads[:, 0]] - vertices[quads[:, 2]], axis=1)
82
+ d13 = np.linalg.norm(vertices[quads[:, 1]] - vertices[quads[:, 3]], axis=1)
83
+ quads = quads.copy()
84
+ quads[d13 < d02] = np.roll(quads[d13 < d02], 1, axis=1)
85
+ faces = quads[:, [[0, 1, 2], [0, 2, 3]]].reshape(-1, 3)
86
+ return vertices / step, orient_surface(vertices, faces, field, step)
87
+
88
+
89
+ if __name__ == "__main__":
90
+ try:
91
+ run(sys.argv[1], Path(sys.argv[2]), signed_distance_mesh)
92
+ except (OSError, ValueError, TypeError, KeyError) as exc:
93
+ sys.exit(str(exc))
package/package.json CHANGED
@@ -1,6 +1,34 @@
1
1
  {
2
2
  "name": "stack3js",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.6.4",
4
+ "type": "module",
5
+ "license": "MIT",
6
+ "description": "Build 3D meshes and sprite stacks from orthographic atlases.",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/ev3rlit/stack3.js.git"
10
+ },
11
+ "engines": {
12
+ "node": ">=22.12"
13
+ },
14
+ "bin": {
15
+ "stack3": "./bin/stack3.mjs"
16
+ },
17
+ "dependencies": {
18
+ "vite": "7.3.8",
19
+ "pngjs": "7.0.0",
20
+ "yaml": "2.9.1"
21
+ },
22
+ "files": [
23
+ "bin",
24
+ "blender",
25
+ "meshing",
26
+ "verification",
27
+ "schema",
28
+ "examples",
29
+ "references",
30
+ "viewer/dist",
31
+ "COMMAND.md",
32
+ "THIRD-PARTY-LICENSES.md"
33
+ ]
34
+ }