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
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Coordinates are XYZ cell-boundary indices until export. All permutations are cyclic."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import shapely as sh
|
|
5
|
+
from shapely.geometry import Polygon
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def cyclic(axis):
|
|
9
|
+
return (axis + 1) % 3, (axis + 2) % 3, axis
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def xyz(uvt, axis):
|
|
13
|
+
return np.asarray(uvt)[..., np.argsort(cyclic(axis))]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def unit(v):
|
|
17
|
+
length = np.linalg.norm(v, axis=-1, keepdims=True)
|
|
18
|
+
return v / np.maximum(length, 1e-30)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def indexed(triangles):
|
|
22
|
+
points = np.asarray(triangles, dtype=float).reshape(-1, 3)
|
|
23
|
+
if not len(points):
|
|
24
|
+
raise ValueError("no surface in the supplied stack and guide")
|
|
25
|
+
_, keep, ids = np.unique(points.round(10), axis=0, return_index=True, return_inverse=True)
|
|
26
|
+
return points[keep], ids.reshape(-1, 3)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def runs(row):
|
|
30
|
+
changes = np.flatnonzero(np.diff(row.astype(np.int8), prepend=0, append=0))
|
|
31
|
+
return list(zip(changes[::2], changes[1::2]))
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def region(mask):
|
|
35
|
+
rects = [sh.box(lo, y, hi, y + 1) for y, row in enumerate(mask.T) for lo, hi in runs(row)]
|
|
36
|
+
return sh.union_all(rects).simplify(0)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def polygons(shape):
|
|
40
|
+
if shape.is_empty:
|
|
41
|
+
return []
|
|
42
|
+
if shape.geom_type == "Polygon":
|
|
43
|
+
return [shape]
|
|
44
|
+
return [poly for child in getattr(shape, "geoms", []) for poly in polygons(child)]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def planar_triangles(poly):
|
|
48
|
+
return [
|
|
49
|
+
np.asarray(sh.orient_polygons(t).exterior.coords)[:3]
|
|
50
|
+
for t in sh.constrained_delaunay_triangles(poly).geoms
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def profile(data):
|
|
55
|
+
if not isinstance(data, dict) or "outer" not in data:
|
|
56
|
+
raise ValueError("profile needs outer and optional holes")
|
|
57
|
+
rings = [data["outer"], *data.get("holes", [])]
|
|
58
|
+
for ring in rings:
|
|
59
|
+
r = np.asarray(ring, dtype=float)
|
|
60
|
+
if r.ndim != 2 or r.shape[1] != 2 or len(r) < 3 or not np.isfinite(r).all():
|
|
61
|
+
raise ValueError("expected finite closed 2D polygon loops (at least three points)")
|
|
62
|
+
poly = Polygon(rings[0], rings[1:])
|
|
63
|
+
if not poly.is_valid or poly.area <= 0:
|
|
64
|
+
raise ValueError("self-intersecting, overlapping or empty profile loops")
|
|
65
|
+
return sh.orient_polygons(poly)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def connect(a, b):
|
|
69
|
+
"""Join two consistently oriented outer (CCW) or hole (CW) station loops."""
|
|
70
|
+
c, d = np.roll(a, -1, axis=0), np.roll(b, -1, axis=0)
|
|
71
|
+
return np.concatenate((np.stack((a, c, d), axis=1), np.stack((a, d, b), axis=1)))
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
from itertools import pairwise, product
|
|
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
|
+
unit,
|
|
14
|
+
xyz,
|
|
15
|
+
)
|
|
16
|
+
from scipy.spatial.transform import Rotation
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def vector(data, key):
|
|
20
|
+
p = np.asarray(data.get(key), dtype=float)
|
|
21
|
+
if p.shape != (3,) or not np.isfinite(p).all():
|
|
22
|
+
raise ValueError(f"{key} must be a finite XYZ point or vector")
|
|
23
|
+
return p
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def revolve(mask, step, origin, guide, axis):
|
|
27
|
+
center = (vector(guide, "origin") - origin) / step
|
|
28
|
+
u, v, _ = cyclic(axis)
|
|
29
|
+
stack = mask.transpose(cyclic(axis))
|
|
30
|
+
if not (0 <= center[u] < mask.shape[u] and 0 <= center[v] < mask.shape[v]):
|
|
31
|
+
raise ValueError("rotation axis outside the stack")
|
|
32
|
+
# Sample the +u half of the meridian at the supplied transverse origin.
|
|
33
|
+
profile_mask = stack[:, int(center[v]), :]
|
|
34
|
+
meridian = region(profile_mask).intersection(sh.box(center[u], 0, mask.shape[u], mask.shape[axis]))
|
|
35
|
+
if meridian.area <= 0:
|
|
36
|
+
raise ValueError("positive meridian of the rotation axis misses the saved stack")
|
|
37
|
+
segments = guide.get("segments", 64)
|
|
38
|
+
if type(segments) is not int or not 8 <= segments <= 512:
|
|
39
|
+
raise ValueError("segments must be an integer from 8 to 512")
|
|
40
|
+
angle = np.arange(segments) * (2 * np.pi / segments)
|
|
41
|
+
triangles = []
|
|
42
|
+
for poly in polygons(meridian):
|
|
43
|
+
poly = sh.orient_polygons(poly)
|
|
44
|
+
for ring in [poly.exterior, *poly.interiors]:
|
|
45
|
+
points = []
|
|
46
|
+
for r, h in ring.coords:
|
|
47
|
+
radius = (r - center[u]) * step[u]
|
|
48
|
+
points.append(
|
|
49
|
+
np.column_stack(
|
|
50
|
+
(
|
|
51
|
+
center[u] + radius * np.cos(angle) / step[u],
|
|
52
|
+
center[v] + radius * np.sin(angle) / step[v],
|
|
53
|
+
np.full(segments, h),
|
|
54
|
+
)
|
|
55
|
+
)
|
|
56
|
+
)
|
|
57
|
+
for a, b in pairwise(points):
|
|
58
|
+
for face in connect(a, b):
|
|
59
|
+
if (
|
|
60
|
+
not np.array_equal(face[0], face[1])
|
|
61
|
+
and not np.array_equal(face[1], face[2])
|
|
62
|
+
and not np.array_equal(face[0], face[2])
|
|
63
|
+
):
|
|
64
|
+
triangles.append(face)
|
|
65
|
+
return indexed(xyz(triangles, axis))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def stack_profile(mask, step, origin, station, tangent, frame):
|
|
69
|
+
"""Sample the actual first cutting plane in its transported metric basis."""
|
|
70
|
+
from shapely.affinity import affine_transform
|
|
71
|
+
from shapely.geometry import Point, Polygon
|
|
72
|
+
|
|
73
|
+
corners = np.array(list(product(*zip(np.zeros(3), mask.shape)))) * step + origin
|
|
74
|
+
bounds = (corners - station) @ frame.T
|
|
75
|
+
pitch = 1 / np.linalg.norm(frame / step, axis=1)
|
|
76
|
+
low = bounds.min(axis=0)
|
|
77
|
+
shape = np.maximum(1, np.ceil((bounds.max(axis=0) - low) / pitch).astype(int))
|
|
78
|
+
indices = np.indices(shape).reshape(2, -1).T
|
|
79
|
+
points = station + ((indices + 0.5) * pitch + low) @ frame + tangent * min(step) * 1e-6
|
|
80
|
+
cells = np.floor((points - origin) / step).astype(int)
|
|
81
|
+
inside = np.all((cells >= 0) & (cells < mask.shape), axis=1)
|
|
82
|
+
inside[inside] = mask[tuple(cells[inside].T)]
|
|
83
|
+
candidates = []
|
|
84
|
+
for section in polygons(region(inside.reshape(shape))):
|
|
85
|
+
poly = affine_transform(section, [pitch[0], 0, 0, pitch[1], *low])
|
|
86
|
+
if Polygon(poly.exterior).covers(Point(0, 0)):
|
|
87
|
+
candidates.append(sh.orient_polygons(poly))
|
|
88
|
+
if len(candidates) != 1:
|
|
89
|
+
raise ValueError(
|
|
90
|
+
"first path station must lie inside a unique outer section; supply profile or move the path"
|
|
91
|
+
)
|
|
92
|
+
print("sweep profile: outer and hole loops from the saved first section")
|
|
93
|
+
return candidates[0]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def sweep(mask, step, origin, guide):
|
|
97
|
+
path = np.asarray(guide.get("path"), dtype=float)
|
|
98
|
+
if path.ndim != 2 or path.shape[1] != 3 or len(path) < 2 or not np.isfinite(path).all():
|
|
99
|
+
raise ValueError("path requires at least two finite XYZ points")
|
|
100
|
+
delta = np.diff(path, axis=0)
|
|
101
|
+
lengths = np.linalg.norm(delta, axis=1)
|
|
102
|
+
if (lengths < 1e-12).any():
|
|
103
|
+
raise ValueError("duplicate stations on sweep path")
|
|
104
|
+
directions = unit(delta)
|
|
105
|
+
bends = directions[:-1] + directions[1:]
|
|
106
|
+
if (np.linalg.norm(bends, axis=1) < 1e-6).any():
|
|
107
|
+
raise ValueError("path reverses through a station")
|
|
108
|
+
tangents = np.vstack((directions[0], unit(bends), directions[-1]))
|
|
109
|
+
up = vector(guide, "up") if "up" in guide else np.eye(3)[np.argmin(abs(tangents[0]))]
|
|
110
|
+
u = up - up.dot(tangents[0]) * tangents[0]
|
|
111
|
+
if np.linalg.norm(u) < 1e-8:
|
|
112
|
+
raise ValueError("up must have a component perpendicular to the initial tangent")
|
|
113
|
+
u = unit(u)
|
|
114
|
+
frames = []
|
|
115
|
+
for i, tangent in enumerate(tangents):
|
|
116
|
+
if i:
|
|
117
|
+
turn = np.cross(tangents[i - 1], tangent)
|
|
118
|
+
angle = np.arctan2(np.linalg.norm(turn), tangents[i - 1].dot(tangent))
|
|
119
|
+
u = Rotation.from_rotvec(unit(turn) * angle).apply(u)
|
|
120
|
+
frames.append(np.stack((u, np.cross(tangent, u))))
|
|
121
|
+
poly = (
|
|
122
|
+
profile(guide["profile"])
|
|
123
|
+
if "profile" in guide
|
|
124
|
+
else stack_profile(mask, step, origin, path[0], tangents[0], frames[0])
|
|
125
|
+
)
|
|
126
|
+
triangles = []
|
|
127
|
+
for ring in [poly.exterior, *poly.interiors]:
|
|
128
|
+
uv = np.asarray(ring.coords[:-1])
|
|
129
|
+
rings = [xy + uv @ frame for xy, frame in zip(path, frames)]
|
|
130
|
+
for a, b, direction in zip(rings, rings[1:], directions):
|
|
131
|
+
if ((b - a) @ direction <= 0).any():
|
|
132
|
+
raise ValueError("bend folds the swept profile; widen the bend or reduce the profile")
|
|
133
|
+
triangles.extend(connect(a, b))
|
|
134
|
+
for tri in planar_triangles(poly):
|
|
135
|
+
triangles.extend((path[0] + tri[::-1] @ frames[0], path[-1] + tri @ frames[-1]))
|
|
136
|
+
verts, faces = indexed(triangles)
|
|
137
|
+
# Non-local crossings cannot be found from tangent or curvature checks alone.
|
|
138
|
+
from intersection import check_intersections
|
|
139
|
+
|
|
140
|
+
check_intersections(verts, faces)
|
|
141
|
+
grid = (verts - origin) / step
|
|
142
|
+
if np.any(grid.min(axis=0) < -1e-6) or np.any(grid.max(axis=0) > np.array(mask.shape) + 1e-6):
|
|
143
|
+
raise ValueError("swept profile leaves the saved part frame")
|
|
144
|
+
cells = np.clip(np.floor((path - origin) / step).astype(int), 0, np.array(mask.shape) - 1)
|
|
145
|
+
radius = np.max(np.linalg.norm(np.asarray(poly.exterior.coords), axis=1))
|
|
146
|
+
from scipy.ndimage import distance_transform_edt
|
|
147
|
+
|
|
148
|
+
if (distance_transform_edt(~mask, sampling=step)[tuple(cells.T)] > radius + np.linalg.norm(step)).any():
|
|
149
|
+
raise ValueError("sweep path and profile miss the saved occupancy")
|
|
150
|
+
return grid, faces
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""MC33, feature insertion in primal MC patches, and dual Hermite QEF extraction."""
|
|
2
|
+
|
|
3
|
+
from collections import defaultdict
|
|
4
|
+
from itertools import product
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
from geometry import cyclic, unit
|
|
8
|
+
from scipy.ndimage import gaussian_filter, label
|
|
9
|
+
from skimage.measure import marching_cubes
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def iso(field, level, method="lewiner"):
|
|
13
|
+
verts, faces, _, _ = marching_cubes(
|
|
14
|
+
field.astype(np.float32), level, method=method, gradient_direction="ascent", allow_degenerate=False
|
|
15
|
+
)
|
|
16
|
+
return verts, faces
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def mc33(mask):
|
|
20
|
+
p, f = iso(np.pad(mask, 1), 0.5)
|
|
21
|
+
return p - 0.5, f
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def feature_mesh(mask, step, dual, signed_distance=None, measured=None):
|
|
25
|
+
field = np.pad(mask, 1)
|
|
26
|
+
if dual:
|
|
27
|
+
# A body diagonal can give two disjoint vertex links although every
|
|
28
|
+
# resulting edge has incidence two. Test both signs before collapsing.
|
|
29
|
+
corner_mask = np.zeros(np.array(field.shape) - 1, dtype=np.uint8)
|
|
30
|
+
for bit, corner in enumerate(product((0, 1), repeat=3)):
|
|
31
|
+
slices = tuple(slice(i, i + n) for i, n in zip(corner, corner_mask.shape))
|
|
32
|
+
corner_mask |= field[slices].astype(np.uint8) << bit
|
|
33
|
+
for code in np.unique(corner_mask):
|
|
34
|
+
corners = ((int(code) >> np.arange(8)) & 1).reshape((2, 2, 2)).astype(bool)
|
|
35
|
+
if label(corners)[1] > 1 or label(~corners)[1] > 1:
|
|
36
|
+
cell = tuple((np.argwhere(corner_mask == code)[0] - 1).tolist())
|
|
37
|
+
raise ValueError(f"multiple sheets in dual cell {cell}; use mc33")
|
|
38
|
+
crosses = {}
|
|
39
|
+
cells = defaultdict(list)
|
|
40
|
+
if measured is None:
|
|
41
|
+
values = signed_distance if signed_distance is not None else -gaussian_filter(field.astype(float), 0.8)
|
|
42
|
+
grads = np.stack(np.gradient(values, *step), axis=-1)
|
|
43
|
+
for axis in range(3):
|
|
44
|
+
u, v, _ = cyclic(axis)
|
|
45
|
+
exposed = np.diff(field.astype(np.int8), axis=axis)
|
|
46
|
+
# An uninterrupted coplanar 2x2 patch supports a flat sample-plane normal.
|
|
47
|
+
# Isolated steps use the gradient of a filtered occupancy field instead.
|
|
48
|
+
if measured is None and signed_distance is None:
|
|
49
|
+
flat = np.zeros_like(exposed, bool)
|
|
50
|
+
view = exposed.transpose(cyclic(axis))
|
|
51
|
+
quads = (
|
|
52
|
+
(view[:-1, :-1] != 0)
|
|
53
|
+
& (view[:-1, :-1] == view[1:, :-1])
|
|
54
|
+
& (view[:-1, :-1] == view[:-1, 1:])
|
|
55
|
+
& (view[:-1, :-1] == view[1:, 1:])
|
|
56
|
+
)
|
|
57
|
+
for i, j in product(range(2), repeat=2):
|
|
58
|
+
flat.transpose(cyclic(axis))[i : i + quads.shape[0], j : j + quads.shape[1]] |= quads
|
|
59
|
+
for p in np.argwhere(exposed):
|
|
60
|
+
key = (*p, axis)
|
|
61
|
+
if measured is not None:
|
|
62
|
+
crosses[key] = measured[key]
|
|
63
|
+
else:
|
|
64
|
+
q = p.copy()
|
|
65
|
+
q[axis] += 1
|
|
66
|
+
t = 0.5
|
|
67
|
+
if signed_distance is not None:
|
|
68
|
+
start, end = values[tuple(p)], values[tuple(q)]
|
|
69
|
+
t = start / (start - end)
|
|
70
|
+
n = unit((1 - t) * grads[tuple(p)] + t * grads[tuple(q)])
|
|
71
|
+
if (signed_distance is None and flat[tuple(p)]) or np.linalg.norm(n) < 0.5:
|
|
72
|
+
n = -np.eye(3)[axis] * exposed[tuple(p)]
|
|
73
|
+
crosses[key] = (p + t * (q - p), n)
|
|
74
|
+
for du, dv in product(range(2), repeat=2):
|
|
75
|
+
cell = p.copy()
|
|
76
|
+
cell[u] -= du
|
|
77
|
+
cell[v] -= dv
|
|
78
|
+
cells[tuple(cell)].append(key)
|
|
79
|
+
|
|
80
|
+
def solution(cell, keys):
|
|
81
|
+
p, n = map(np.array, zip(*(crosses[k] for k in keys)))
|
|
82
|
+
mean = p.mean(axis=0)
|
|
83
|
+
# Solve in physical coordinates, centered at the mass point. SVD drops
|
|
84
|
+
# unsupported directions; parallel planes then retain the mass point.
|
|
85
|
+
rhs = np.einsum("ij,ij->i", n, (p - mean) * step)
|
|
86
|
+
delta, _, rank, _ = np.linalg.lstsq(n, rhs, rcond=0.12)
|
|
87
|
+
sharp = rank >= 2 and (n @ n.T).min() < 0.6
|
|
88
|
+
if dual and not sharp:
|
|
89
|
+
# On nearly parallel constraints the tangential intersection is poorly
|
|
90
|
+
# determined. Penalize drift from the centroid in those smooth cells.
|
|
91
|
+
delta = np.linalg.solve(n.T @ n + 0.1 * len(n) * np.eye(3), n.T @ rhs)
|
|
92
|
+
point = mean + delta / step
|
|
93
|
+
lower = np.asarray(cell)
|
|
94
|
+
if np.any(point < lower - 1e-7) or np.any(point > lower + 1 + 1e-7):
|
|
95
|
+
# An extrapolated intersection on a sampled stair step is unreliable.
|
|
96
|
+
# Clamping it to the wall can fold two neighboring dual quads together.
|
|
97
|
+
point = mean
|
|
98
|
+
else:
|
|
99
|
+
point = np.clip(point, lower, lower + 1)
|
|
100
|
+
return point, sharp
|
|
101
|
+
|
|
102
|
+
if dual:
|
|
103
|
+
reps, positions = {}, []
|
|
104
|
+
for cell, keys in cells.items():
|
|
105
|
+
reps[cell] = len(positions)
|
|
106
|
+
positions.append(solution(cell, keys)[0])
|
|
107
|
+
faces = []
|
|
108
|
+
for key in crosses:
|
|
109
|
+
p, axis = np.array(key[:3]), key[3]
|
|
110
|
+
u, v, _ = cyclic(axis)
|
|
111
|
+
e = np.eye(3, dtype=int)
|
|
112
|
+
quad = [reps[tuple(c)] for c in (p, p - e[u], p - e[u] - e[v], p - e[v])]
|
|
113
|
+
if not field[tuple(p)]:
|
|
114
|
+
quad.reverse()
|
|
115
|
+
a, b, c, d = quad
|
|
116
|
+
faces.extend(((a, b, c), (a, c, d)))
|
|
117
|
+
positions, faces = np.array(positions) - 0.5, np.array(faces)
|
|
118
|
+
# Multiple disjoint sheets in one cell cannot share a dual representative.
|
|
119
|
+
edges = np.sort(faces[:, [[0, 1], [1, 2], [2, 0]]].reshape(-1, 2), axis=1)
|
|
120
|
+
if np.any(np.unique(edges, axis=0, return_counts=True)[1] != 2):
|
|
121
|
+
raise ValueError("ambiguous dual cell joins multiple sheets; use mc33")
|
|
122
|
+
return positions, faces
|
|
123
|
+
|
|
124
|
+
p, f = iso(field, 0.5, "lorensen")
|
|
125
|
+
patches = defaultdict(list)
|
|
126
|
+
for tri in f:
|
|
127
|
+
patches[tuple(np.floor(p[tri].mean(axis=0)).astype(int))].append(tri)
|
|
128
|
+
# Store fans by their original MC boundary edge. Where two feature fans
|
|
129
|
+
# meet, flip the shared diagonal to connect their feature vertices directly.
|
|
130
|
+
positions = list(p)
|
|
131
|
+
result = []
|
|
132
|
+
fan_edges = {}
|
|
133
|
+
for cell, patch in patches.items():
|
|
134
|
+
point, sharp = solution(cell, cells[cell])
|
|
135
|
+
if sharp:
|
|
136
|
+
boundary = set()
|
|
137
|
+
for a, b, c in patch:
|
|
138
|
+
for i, j in ((a, b), (b, c), (c, a)):
|
|
139
|
+
if (j, i) in boundary:
|
|
140
|
+
boundary.remove((j, i))
|
|
141
|
+
else:
|
|
142
|
+
boundary.add((i, j))
|
|
143
|
+
# Fan a single boundary loop. Keep disconnected/ambiguous MC patches intact.
|
|
144
|
+
links = dict(boundary)
|
|
145
|
+
start = next(iter(links))
|
|
146
|
+
order, i = [], start
|
|
147
|
+
while i not in order and i in links:
|
|
148
|
+
order.append(i)
|
|
149
|
+
i = links[i]
|
|
150
|
+
if i == start and len(order) == len(boundary):
|
|
151
|
+
fan = np.array([[p[a], p[b], point] for a, b in boundary])
|
|
152
|
+
if np.all(
|
|
153
|
+
np.linalg.norm(np.cross(fan[:, 1] - fan[:, 0], fan[:, 2] - fan[:, 0]), axis=1) > 1e-9
|
|
154
|
+
):
|
|
155
|
+
feature = len(positions)
|
|
156
|
+
positions.append(point)
|
|
157
|
+
for a, b in zip(order, order[1:] + order[:1]):
|
|
158
|
+
face_id = len(result)
|
|
159
|
+
result.append([a, b, feature])
|
|
160
|
+
other = fan_edges.pop((b, a), None)
|
|
161
|
+
if other is None:
|
|
162
|
+
fan_edges[a, b] = face_id
|
|
163
|
+
continue
|
|
164
|
+
neighbor = result[other][2]
|
|
165
|
+
# Reject a folded or collapsed replacement.
|
|
166
|
+
old = np.array([[p[a], p[b], point], [p[b], p[a], positions[neighbor]]]) * step
|
|
167
|
+
new = (
|
|
168
|
+
np.array([[p[a], positions[neighbor], point], [p[b], point, positions[neighbor]]])
|
|
169
|
+
* step
|
|
170
|
+
)
|
|
171
|
+
reference = np.cross(old[:, 1] - old[:, 0], old[:, 2] - old[:, 0]).sum(axis=0)
|
|
172
|
+
normals = np.cross(new[:, 1] - new[:, 0], new[:, 2] - new[:, 0])
|
|
173
|
+
if np.all(normals @ reference > 0):
|
|
174
|
+
result[other] = [a, neighbor, feature]
|
|
175
|
+
result[face_id] = [b, feature, neighbor]
|
|
176
|
+
continue
|
|
177
|
+
result.extend(patch)
|
|
178
|
+
return np.asarray(positions) - 0.5, np.asarray(result)
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Broad-phase AABBs and the triangle separating-axis test for a transported profile."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
from geometry import unit
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def check_intersections(verts, faces):
|
|
8
|
+
tris = verts[faces]
|
|
9
|
+
lo, hi = tris.min(axis=1), tris.max(axis=1)
|
|
10
|
+
eps = np.linalg.norm(verts.max(axis=0) - verts.min(axis=0)) * 1e-10
|
|
11
|
+
edges = np.roll(tris, -1, axis=1) - tris
|
|
12
|
+
normals = unit(np.cross(edges[:, 0], edges[:, 1]))
|
|
13
|
+
for i, tri in enumerate(tris):
|
|
14
|
+
ids = np.flatnonzero(np.all((hi[:i] >= lo[i] - eps) & (lo[:i] <= hi[i] + eps), axis=1))
|
|
15
|
+
for j in ids:
|
|
16
|
+
if np.isin(faces[i], faces[j]).any():
|
|
17
|
+
continue
|
|
18
|
+
# In-plane edge normals also separate disjoint coplanar triangles.
|
|
19
|
+
axes = np.vstack(
|
|
20
|
+
(
|
|
21
|
+
normals[[i, j]],
|
|
22
|
+
np.cross(edges[i][:, None], edges[j]).reshape(-1, 3),
|
|
23
|
+
np.cross(edges[i], normals[i]),
|
|
24
|
+
np.cross(edges[j], normals[j]),
|
|
25
|
+
)
|
|
26
|
+
)
|
|
27
|
+
axes = unit(axes[np.linalg.norm(axes, axis=1) > 1e-14])
|
|
28
|
+
first, second = tri @ axes.T, tris[j] @ axes.T
|
|
29
|
+
if not np.any(
|
|
30
|
+
(first.max(axis=0) < second.min(axis=0) - eps)
|
|
31
|
+
| (second.max(axis=0) < first.min(axis=0) - eps)
|
|
32
|
+
):
|
|
33
|
+
raise ValueError("sweep intersects itself between non-adjacent faces")
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Project saved RGB onto face charts and split vertices only at UV or hard-normal seams."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import math
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
from geometry import cyclic, unit
|
|
8
|
+
from scipy.ndimage import distance_transform_edt
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def split_creases(faces, normals):
|
|
12
|
+
"""Each connected fan below 55 degrees shares a shading normal."""
|
|
13
|
+
from scipy.sparse import coo_matrix
|
|
14
|
+
from scipy.sparse.csgraph import connected_components
|
|
15
|
+
|
|
16
|
+
ids = np.arange(faces.size).reshape(-1, 3)
|
|
17
|
+
ends = np.stack((ids.ravel(), np.roll(ids, -1, axis=1).ravel()), axis=1)
|
|
18
|
+
edges = faces.ravel()[ends]
|
|
19
|
+
flip = edges[:, 0] > edges[:, 1]
|
|
20
|
+
ends[flip] = ends[flip, ::-1]
|
|
21
|
+
edges.sort(axis=1)
|
|
22
|
+
order = np.lexsort((edges[:, 1], edges[:, 0]))
|
|
23
|
+
pairs = np.all(edges[order[:-1]] == edges[order[1:]], axis=1)
|
|
24
|
+
a, b = order[:-1][pairs], order[1:][pairs]
|
|
25
|
+
unit_normals = unit(normals)
|
|
26
|
+
soft = (unit_normals[a // 3] * unit_normals[b // 3]).sum(axis=1) > np.cos(np.deg2rad(55))
|
|
27
|
+
rows, cols = ends[a[soft]].ravel(), ends[b[soft]].ravel()
|
|
28
|
+
graph = coo_matrix((np.ones(len(rows)), (rows, cols)), shape=(faces.size, faces.size))
|
|
29
|
+
_, fan = connected_components(graph, directed=False)
|
|
30
|
+
_, first = np.unique(fan, return_index=True)
|
|
31
|
+
return faces.ravel()[first], fan.reshape(-1, 3)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def write_mesh(folder, mesh, rgba, step, origin, blocks=False, sharp=False, occlusion=None):
|
|
35
|
+
verts, faces = mesh
|
|
36
|
+
faces = np.asarray(faces, dtype=np.int32)
|
|
37
|
+
local = (verts * step + origin).astype(np.float32).astype(float)
|
|
38
|
+
a, b, c = local[faces].transpose(1, 0, 2)
|
|
39
|
+
normals = np.cross(b - a, c - a)
|
|
40
|
+
if not np.isfinite(local).all() or not len(faces) or (np.linalg.norm(normals, axis=1) == 0).any():
|
|
41
|
+
raise ValueError("invalid surface: empty, nonfinite or degenerate triangles")
|
|
42
|
+
if sharp:
|
|
43
|
+
source, faces = split_creases(faces, normals)
|
|
44
|
+
verts = verts[source]
|
|
45
|
+
if occlusion is not None:
|
|
46
|
+
occlusion = occlusion[source]
|
|
47
|
+
local = verts * step + origin
|
|
48
|
+
smooth = np.zeros_like(local)
|
|
49
|
+
for i in range(3):
|
|
50
|
+
np.add.at(smooth, faces[:, i], normals)
|
|
51
|
+
smooth = unit(smooth)
|
|
52
|
+
axes = np.argmax(abs(normals), axis=1)
|
|
53
|
+
signs = np.sign(normals[np.arange(len(faces)), axes]).astype(int)
|
|
54
|
+
stations = np.zeros(len(faces), dtype=int)
|
|
55
|
+
if blocks:
|
|
56
|
+
stations = verts[faces[:, 0], axes].round().astype(int) - (signs > 0)
|
|
57
|
+
groups, group_ids = np.unique(np.column_stack((axes, signs, stations)), axis=0, return_inverse=True)
|
|
58
|
+
# Each tile contains the saved texels of this plane (or its orthographic projection).
|
|
59
|
+
tiles = []
|
|
60
|
+
for axis, sign, station in groups:
|
|
61
|
+
plane = rgba.transpose((*cyclic(axis), 3))
|
|
62
|
+
if blocks:
|
|
63
|
+
pixels = plane[:, :, station].copy()
|
|
64
|
+
else:
|
|
65
|
+
ray = plane[:, :, ::-1] if sign > 0 else plane
|
|
66
|
+
hit = ray[:, :, :, 3] >= 128
|
|
67
|
+
u, v = np.indices(ray.shape[:2])
|
|
68
|
+
pixels = ray[u, v, hit.argmax(axis=2)].copy()
|
|
69
|
+
valid = pixels[:, :, 3] >= 128
|
|
70
|
+
uu, vv = np.where(valid)
|
|
71
|
+
lo, bot = uu.min(), vv.min()
|
|
72
|
+
tile = pixels[lo : uu.max() + 1, bot : vv.max() + 1].transpose(1, 0, 2).copy()
|
|
73
|
+
empty = tile[:, :, 3] < 128
|
|
74
|
+
if empty.any():
|
|
75
|
+
nearest = distance_transform_edt(empty, return_distances=False, return_indices=True)
|
|
76
|
+
tile[empty] = tile[tuple(nearest[:, empty])]
|
|
77
|
+
tile[:, :, 3] = 255
|
|
78
|
+
tiles.append((np.pad(tile, ((1, 1), (1, 1), (0, 0)), mode="edge"), lo, bot))
|
|
79
|
+
width = max(
|
|
80
|
+
max(t.shape[1] for t, _, _ in tiles), math.ceil(math.sqrt(sum(t.size / 4 for t, _, _ in tiles)))
|
|
81
|
+
)
|
|
82
|
+
x = y = height = 0
|
|
83
|
+
offsets = []
|
|
84
|
+
for tile, lo, bot in tiles:
|
|
85
|
+
h, w = tile.shape[:2]
|
|
86
|
+
if x + w > width:
|
|
87
|
+
x, y = 0, height
|
|
88
|
+
offsets.append((x, y))
|
|
89
|
+
height = max(height, y + h)
|
|
90
|
+
x += w
|
|
91
|
+
texture = np.zeros((height, width, 4), np.uint8)
|
|
92
|
+
corners, ids = np.unique(
|
|
93
|
+
np.column_stack((faces.ravel(), np.repeat(group_ids, 3))), axis=0, return_inverse=True
|
|
94
|
+
)
|
|
95
|
+
pos = local[corners[:, 0]]
|
|
96
|
+
nor = smooth[corners[:, 0]]
|
|
97
|
+
uv = np.empty((len(pos), 2))
|
|
98
|
+
for i, ((tile, lo, bot), (x, y), (axis, sign, _)) in enumerate(zip(tiles, offsets, groups)):
|
|
99
|
+
h, w = tile.shape[:2]
|
|
100
|
+
texture[y : y + h, x : x + w] = tile
|
|
101
|
+
use = corners[:, 1] == i
|
|
102
|
+
u, v, _ = cyclic(axis)
|
|
103
|
+
coords = verts[corners[use, 0]][:, [u, v]] - [lo, bot]
|
|
104
|
+
uv[use] = (np.clip(coords, 0, [w - 2, h - 2]) + [x + 1, y + 1]) / [width, height]
|
|
105
|
+
if blocks:
|
|
106
|
+
nor[use] = np.eye(3)[axis] * sign
|
|
107
|
+
for name, data in [("positions", pos), ("normals", nor)]:
|
|
108
|
+
(data[:, [0, 2, 1]] * [1, 1, -1]).astype("<f4").tofile(folder / name)
|
|
109
|
+
uv.astype("<f4").tofile(folder / "uvs")
|
|
110
|
+
ids.astype("<u4").tofile(folder / "indices")
|
|
111
|
+
texture.tofile(folder / "texture")
|
|
112
|
+
if occlusion is not None:
|
|
113
|
+
rgb = np.repeat(occlusion[corners[:, 0], None], 3, axis=1)
|
|
114
|
+
np.column_stack((rgb, np.ones(len(rgb)))).astype("<f4").tofile(folder / "colors")
|
|
115
|
+
(folder / "output.json").write_text(json.dumps({"width": width, "height": height, "colors": occlusion is not None}))
|
package/meshing/mesh.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
# /// script
|
|
2
|
+
# requires-python = ">=3.11,<3.14"
|
|
3
|
+
# dependencies = ["numpy==2.2.6", "scipy==1.15.3", "scikit-image==0.25.2", "shapely==2.1.2"]
|
|
4
|
+
# ///
|
|
5
|
+
"""Saved stack -> selected surface -> typed buffers for stack3's GLB writer."""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
from blocks import block_mesh
|
|
13
|
+
from branches import branch_loft
|
|
14
|
+
from dexel import load_dexel
|
|
15
|
+
from field_data import load_field
|
|
16
|
+
from guided import revolve, sweep
|
|
17
|
+
from implicit import feature_mesh, mc33
|
|
18
|
+
from material import write_mesh
|
|
19
|
+
from network import section_network
|
|
20
|
+
from sections import heightfield, loft
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def run(method, folder, distance_extractor=None):
|
|
24
|
+
meta = json.loads((folder / "input.json").read_text())
|
|
25
|
+
w, d, l, c = [meta[k] for k in ("width", "depth", "layers", "columns")]
|
|
26
|
+
tiles = np.fromfile(folder / "stack.rgba", np.uint8).reshape(-1, d, c, w, 4)
|
|
27
|
+
rgba = tiles.transpose(0, 2, 3, 1, 4).reshape(-1, w, d, 4)[:l].transpose(1, 2, 0, 3)
|
|
28
|
+
mask = rgba[:, :, :, 3] >= 128
|
|
29
|
+
if not mask.any():
|
|
30
|
+
raise ValueError("saved stack contains no occupied samples")
|
|
31
|
+
size = np.array(meta["size"])
|
|
32
|
+
step = size / mask.shape
|
|
33
|
+
origin = -size * [0.5, 0.5, 0] - meta["pivot"]
|
|
34
|
+
g = meta["guide"]
|
|
35
|
+
options = {
|
|
36
|
+
"section-loft": ["axis", "stations"],
|
|
37
|
+
"smooth-loft": ["axis", "stations"],
|
|
38
|
+
"heightfield": ["axis"],
|
|
39
|
+
"branch-loft": ["axis"],
|
|
40
|
+
"revolve": ["axis", "origin", "segments"],
|
|
41
|
+
"path-sweep": ["path", "up", "profile"],
|
|
42
|
+
"section-network": ["sections", "tolerance"],
|
|
43
|
+
"hermite-dc": ["field", "dexel"],
|
|
44
|
+
"signed-distance-dc": ["field", "outerIterations", "innerIterations"],
|
|
45
|
+
}
|
|
46
|
+
if not isinstance(g, dict) or set(g) - set(options.get(method, [])):
|
|
47
|
+
raise ValueError(f"expected guide object with fields {options.get(method, [])} for {method}")
|
|
48
|
+
if method == "revolve" and "axis" not in g:
|
|
49
|
+
raise ValueError("revolve requires an explicit axis and origin")
|
|
50
|
+
name = g.get("axis", "z")
|
|
51
|
+
if name not in ("x", "y", "z"):
|
|
52
|
+
raise ValueError("axis must be x, y or z")
|
|
53
|
+
axis = "xyz".index(name)
|
|
54
|
+
if method in ("section-loft", "smooth-loft"):
|
|
55
|
+
mesh = loft(mask, step, origin, axis, method == "smooth-loft", g.get("stations"))
|
|
56
|
+
elif method == "heightfield":
|
|
57
|
+
mesh = heightfield(mask, axis)
|
|
58
|
+
elif method == "branch-loft":
|
|
59
|
+
mesh = branch_loft(mask, step, axis)
|
|
60
|
+
elif method == "revolve":
|
|
61
|
+
mesh = revolve(mask, step, origin, g, axis)
|
|
62
|
+
elif method == "path-sweep":
|
|
63
|
+
mesh = sweep(mask, step, origin, g)
|
|
64
|
+
elif method == "section-network":
|
|
65
|
+
mesh = section_network(mask, step, origin, g)
|
|
66
|
+
elif method in ("extended-mc", "hermite-dc"):
|
|
67
|
+
if "field" in g and "dexel" in g:
|
|
68
|
+
raise ValueError("choose either a signed distance field or triple-dexel samples")
|
|
69
|
+
field = load_field(np.pad(mask, 1), g["field"], meta.get("guideDirectory")) if "field" in g else None
|
|
70
|
+
measured = load_dexel(mask, step, origin, g["dexel"], meta.get("guideDirectory")) if "dexel" in g else None
|
|
71
|
+
mesh = feature_mesh(mask, step, method == "hermite-dc", field, measured)
|
|
72
|
+
elif method == "mc33":
|
|
73
|
+
mesh = mc33(mask)
|
|
74
|
+
elif method == "signed-distance-dc" and distance_extractor:
|
|
75
|
+
mesh = distance_extractor(mask, step, g, meta.get("guideDirectory"))
|
|
76
|
+
elif method in ("greedy", "monotone"):
|
|
77
|
+
mesh = block_mesh(mask, method == "monotone")
|
|
78
|
+
else:
|
|
79
|
+
raise ValueError(f"unknown method {method}")
|
|
80
|
+
print(f"{method}: saved alpha/RGB; user guide fields {sorted(g)}")
|
|
81
|
+
finish = meta.get("finish") or {}
|
|
82
|
+
occlusion = None
|
|
83
|
+
if finish:
|
|
84
|
+
from finishing import finish_surface
|
|
85
|
+
|
|
86
|
+
mesh, occlusion = finish_surface(mesh, step, origin, finish, folder, meta["blender"])
|
|
87
|
+
write_mesh(
|
|
88
|
+
folder,
|
|
89
|
+
mesh,
|
|
90
|
+
rgba,
|
|
91
|
+
step,
|
|
92
|
+
origin,
|
|
93
|
+
method in ("greedy", "monotone") and not finish,
|
|
94
|
+
bool(finish) or method in ("extended-mc", "hermite-dc", "signed-distance-dc"),
|
|
95
|
+
occlusion,
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
if __name__ == "__main__":
|
|
100
|
+
try:
|
|
101
|
+
run(sys.argv[1], Path(sys.argv[2]))
|
|
102
|
+
except (OSError, ValueError, TypeError, KeyError) as exc:
|
|
103
|
+
sys.exit(str(exc))
|