meshck 0.1.0__py3-none-any.whl

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.
meshck/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Check and repair triangle meshes before additive manufacturing."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ __version__ = version("meshck")
meshck/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from meshck.cli import main
4
+
5
+ sys.exit(main())
meshck/analysis.py ADDED
@@ -0,0 +1,487 @@
1
+ """Topological and geometric analysis of a triangle mesh.
2
+
3
+ Everything here only measures the mesh; ``meshck.check`` turns the
4
+ measurements into findings.
5
+
6
+ Terms:
7
+ boundary edge: An edge used by exactly one triangle (the mesh is open).
8
+ hole: A closed loop of boundary edges.
9
+ non-manifold edge: An edge used by more than two triangles.
10
+ shell: A set of triangles connected through shared edges.
11
+ misoriented triangle: A triangle whose normal points the wrong way
12
+ relative to its neighbours or, for the whole shell, relative to the
13
+ solid it encloses. A shell nested at odd depth that mostly points
14
+ inwards is a cavity; one that mostly points outwards is a solid
15
+ inside a solid and counts as overlapping its enclosing shell.
16
+ self-intersecting triangle: A triangle crossing another triangle of the
17
+ same closed shell.
18
+ touching shells: Closed shells that share part of their surface without
19
+ overlapping; touching only along an edge or at a point does not count.
20
+ """
21
+
22
+ from dataclasses import dataclass, field
23
+ from functools import reduce
24
+
25
+ import numpy as np
26
+ import rtree
27
+ from manifold3d import Manifold, Mesh
28
+ from scipy.sparse import coo_matrix
29
+ from scipy.sparse.csgraph import connected_components
30
+
31
+ # Relative tolerance for volumes from boolean intersections.
32
+ _VOLUME_RTOL = 1e-4
33
+
34
+ # Triangle pairs tested for crossings at once (bounds memory use).
35
+ _PAIR_CHUNK = 500_000
36
+
37
+ # A closed shell enclosing less than this fraction of its size cubed is flat;
38
+ # its orientation cannot be decided from the volume.
39
+ FLAT_VOLUME_RTOL = 1e-9
40
+
41
+ # Point–triangle pairs per batch in the winding-number test (bounds memory use).
42
+ _WINDING_BATCH = 1_000_000
43
+
44
+ # Crossings shallower than this (mm) are rounding noise, not defects.
45
+ _CROSSING_DEPTH = 1e-3
46
+
47
+
48
+ @dataclass
49
+ class Shell:
50
+ """Measurements of one shell.
51
+
52
+ Attributes:
53
+ faces: Indices of the shell's triangles in the mesh.
54
+ closed: True if the shell has no boundary or non-manifold edges.
55
+ volume: Enclosed volume in mm³ once misoriented triangles are fixed;
56
+ negative for cavities. Only meaningful if ``closed``.
57
+ depth: Number of other shells enclosing this one.
58
+ parent: Index of the innermost shell enclosing this one, or None.
59
+ flat: True if the shell is closed but encloses no volume, such as a
60
+ zero-thickness fin whose two sides lie on top of each other.
61
+ """
62
+
63
+ faces: np.ndarray
64
+ closed: bool
65
+ volume: float = 0.0
66
+ depth: int = 0
67
+ parent: int | None = None
68
+ flat: bool = False
69
+
70
+
71
+ @dataclass
72
+ class Analysis:
73
+ """Result of ``analyze``.
74
+
75
+ Attributes:
76
+ triangles: Number of triangles.
77
+ edges: Number of distinct edges.
78
+ boundary_edges: Edges used by exactly one triangle.
79
+ holes: Loops formed by the boundary edges.
80
+ nonmanifold_edges: Edges used by more than two triangles.
81
+ degenerate: Boolean mask over all triangles with (near) zero area.
82
+ misoriented: Boolean mask over all triangles.
83
+ self_intersecting: Boolean mask over all triangles crossing another
84
+ triangle of the same closed shell.
85
+ shells: One entry per shell.
86
+ overlapping: Index pairs into ``shells`` of closed shells that
87
+ partially intersect each other, or of a solid and the solid
88
+ enclosing it.
89
+ touching: Index pairs into ``shells`` of closed shells that touch
90
+ over an area without overlapping; they fuse when printed.
91
+ size: Axis-aligned extent in mm along x, y and z.
92
+ volume: Total enclosed volume in mm³ of the closed shells, with
93
+ cavities subtracted and overlaps counted once.
94
+ """
95
+
96
+ triangles: int
97
+ edges: int
98
+ boundary_edges: int
99
+ holes: int
100
+ nonmanifold_edges: int
101
+ degenerate: np.ndarray
102
+ misoriented: np.ndarray
103
+ self_intersecting: np.ndarray
104
+ shells: list[Shell]
105
+ overlapping: list[tuple[int, int]] = field(default_factory=list)
106
+ touching: list[tuple[int, int]] = field(default_factory=list)
107
+ size: tuple[float, float, float] = (0.0, 0.0, 0.0)
108
+ volume: float = 0.0
109
+
110
+
111
+ def analyze(vertices: np.ndarray, faces: np.ndarray) -> Analysis:
112
+ """Measure topology, orientation and shell structure of a mesh.
113
+
114
+ Args:
115
+ vertices: ``(n, 3)`` float array of vertex positions in mm, with
116
+ duplicate vertices already merged.
117
+ faces: ``(m, 3)`` int array of vertex indices per triangle.
118
+
119
+ Returns:
120
+ The measurements.
121
+ """
122
+ vertices = np.asarray(vertices, dtype=np.float64)
123
+ faces = np.asarray(faces, dtype=np.int64)
124
+ n_faces = len(faces)
125
+
126
+ # Triangles with repeated vertex indices have no proper edges; they are
127
+ # only counted as degenerate and left out of the edge topology.
128
+ collapsed = (faces[:, 0] == faces[:, 1]) | (faces[:, 1] == faces[:, 2]) | (faces[:, 2] == faces[:, 0])
129
+ tri = vertices[faces]
130
+ area = 0.5 * np.linalg.norm(np.cross(tri[:, 1] - tri[:, 0], tri[:, 2] - tri[:, 0]), axis=1)
131
+ scale = float(np.ptp(vertices, axis=0).max()) if len(vertices) else 0.0
132
+ degenerate = collapsed | (area <= 1e-12 * max(scale, 1.0) ** 2)
133
+
134
+ valid = np.flatnonzero(~collapsed)
135
+ directed = faces[valid][:, [0, 1, 1, 2, 2, 0]].reshape(-1, 2)
136
+ edge_face = np.repeat(valid, 3)
137
+ edge_id, counts = edge_ids(directed, len(vertices))
138
+ per_edge = counts[edge_id]
139
+
140
+ boundary_mask = per_edge == 1
141
+ holes = _count_loops(directed[boundary_mask])
142
+
143
+ # Pairs of triangles across each edge used exactly twice. "same" means
144
+ # both traverse the edge in the same direction, i.e. inconsistent winding.
145
+ order = np.argsort(edge_id, kind="stable")
146
+ two = order[per_edge[order] == 2].reshape(-1, 2)
147
+ fa, fb = edge_face[two[:, 0]], edge_face[two[:, 1]]
148
+ same = np.all(directed[two[:, 0]] == directed[two[:, 1]], axis=1)
149
+
150
+ # Shells: triangles connected through any shared edge (including
151
+ # non-manifold ones, chained along each edge's triangle list).
152
+ many = order[per_edge[order] > 2]
153
+ many_edges = edge_id[many]
154
+ chain = many_edges[1:] == many_edges[:-1]
155
+ sa = np.concatenate([fa, edge_face[many[:-1][chain]]])
156
+ sb = np.concatenate([fb, edge_face[many[1:][chain]]])
157
+ _, shell_of = connected_components(adjacency(sa, sb, n_faces), directed=False)
158
+
159
+ # Orientation classes: a signed graph over (face, +) and (face, -) nodes.
160
+ # Consistent neighbours share their sign, inconsistent ones swap it; the
161
+ # component of (face, +) then names the face's orientation class.
162
+ cons, flip = ~same, same
163
+ src = np.concatenate([fa[cons], fa[cons] + n_faces, fa[flip], fa[flip] + n_faces])
164
+ dst = np.concatenate([fb[cons], fb[cons] + n_faces, fb[flip] + n_faces, fb[flip]])
165
+ _, signed_comp = connected_components(adjacency(src, dst, 2 * n_faces), directed=False)
166
+ face_class = signed_comp[:n_faces]
167
+
168
+ # Patches: triangles connected through edges used exactly twice. A patch
169
+ # has one orientation of its own; a shell joined only through non-manifold
170
+ # edges (bodies touching along an edge) consists of several patches.
171
+ _, patch_of = connected_components(adjacency(fa, fb, n_faces), directed=False)
172
+
173
+ # Closed means every edge is used exactly twice, within the shell or patch.
174
+ open_faces = np.zeros(n_faces, dtype=bool)
175
+ open_faces[edge_face[per_edge != 2]] = True
176
+ _, pe_id, pe_counts = np.unique(patch_of[edge_face].astype(np.int64) * len(counts) + edge_id,
177
+ return_inverse=True, return_counts=True)
178
+ open_in_patch = np.zeros(n_faces, dtype=bool)
179
+ open_in_patch[edge_face[pe_counts[pe_id.ravel()] != 2]] = True
180
+
181
+ # Each patch's first face defines its reference orientation; faces of the
182
+ # other class get flipped. vol_ref is the volume after that flip.
183
+ contrib = np.einsum("ij,ij->i", tri[:, 0], np.cross(tri[:, 1], tri[:, 2])) / 6.0
184
+ flipped = np.zeros(n_faces, dtype=bool)
185
+ patches = _groups(patch_of, valid)
186
+ vol_ref = np.zeros(len(patches))
187
+ for p, idx in enumerate(patches):
188
+ in_ref = face_class[idx] == face_class[idx[0]]
189
+ flipped[idx[~in_ref]] = True
190
+ vol_ref[p] = contrib[idx][in_ref].sum() - contrib[idx][~in_ref].sum()
191
+
192
+ patch_index = {int(patch_of[idx[0]]): p for p, idx in enumerate(patches)}
193
+ shells: list[Shell] = []
194
+ shell_index = {}
195
+ for idx in _groups(shell_of, valid):
196
+ closed = not open_faces[idx].any()
197
+ # A closed shell is a single patch.
198
+ volume = float(vol_ref[patch_index[int(patch_of[idx[0]])]]) if closed else 0.0
199
+ extent = float(np.ptp(vertices[faces[idx].ravel()], axis=0).max())
200
+ flat = closed and abs(volume) <= FLAT_VOLUME_RTOL * max(extent, 1.0) ** 3
201
+ shell_index[int(shell_of[idx[0]])] = len(shells)
202
+ shells.append(Shell(faces=idx, closed=closed, volume=volume, flat=flat))
203
+
204
+ oriented = faces.copy()
205
+ oriented[flipped] = oriented[flipped][:, ::-1]
206
+ overlapping, touching, solids = _nest(vertices, oriented, shells)
207
+
208
+ # Decide per patch which orientation class is correct. Closed patches at
209
+ # even depth must enclose a positive volume. At odd depth the majority of
210
+ # triangles decides: pointing inwards makes a cavity, pointing outwards
211
+ # a solid inside a solid. Open and flat patches follow the majority.
212
+ misoriented = np.zeros(n_faces, dtype=bool)
213
+ for p, idx in enumerate(patches):
214
+ s = shell_index[int(shell_of[idx[0]])]
215
+ shell = shells[s]
216
+ majority_is_ref = (~flipped[idx]).sum() >= flipped[idx].sum()
217
+ if open_in_patch[idx].any() or shell.flat:
218
+ ref_correct = majority_is_ref
219
+ elif shell.depth % 2 == 0:
220
+ ref_correct = vol_ref[p] > 0
221
+ else:
222
+ solid = (vol_ref[p] > 0) == majority_is_ref
223
+ ref_correct = (vol_ref[p] > 0) == solid
224
+ if solid and shell.parent is not None:
225
+ overlapping.append((min(s, shell.parent), max(s, shell.parent)))
226
+ misoriented[idx] = flipped[idx] if ref_correct else ~flipped[idx]
227
+ if shell.closed and not ref_correct:
228
+ shell.volume = -shell.volume
229
+
230
+ closed_volume = _total_volume(shells, overlapping, solids)
231
+ x, y, z = (float(v) for v in np.ptp(vertices[faces.ravel()], axis=0)) if n_faces else (0.0, 0.0, 0.0)
232
+ return Analysis(
233
+ triangles=n_faces,
234
+ edges=len(counts),
235
+ boundary_edges=int(boundary_mask.sum()),
236
+ holes=holes,
237
+ nonmanifold_edges=int((counts > 2).sum()),
238
+ degenerate=degenerate,
239
+ misoriented=misoriented,
240
+ self_intersecting=_self_intersecting(vertices, faces, shells),
241
+ shells=shells,
242
+ overlapping=overlapping,
243
+ touching=touching,
244
+ size=(x, y, z),
245
+ volume=float(closed_volume),
246
+ )
247
+
248
+
249
+ def edge_ids(directed: np.ndarray, n_vertices: int) -> tuple[np.ndarray, np.ndarray]:
250
+ """Identify undirected edges.
251
+
252
+ Args:
253
+ directed: ``(k, 2)`` int array of directed edges.
254
+ n_vertices: Number of vertices (upper bound of the indices).
255
+
256
+ Returns:
257
+ For each directed edge the id of its undirected edge, and the number
258
+ of directed edges per id.
259
+ """
260
+ lo, hi = np.minimum(directed[:, 0], directed[:, 1]), np.maximum(directed[:, 0], directed[:, 1])
261
+ _, edge_id, counts = np.unique(lo * np.int64(n_vertices) + hi,
262
+ return_inverse=True, return_counts=True)
263
+ return edge_id.ravel(), counts
264
+
265
+
266
+ def adjacency(src: np.ndarray, dst: np.ndarray, n: int) -> coo_matrix:
267
+ """Return an ``n × n`` sparse adjacency matrix with the given edges."""
268
+ return coo_matrix((np.ones(len(src), dtype=np.int8), (src, dst)), shape=(n, n))
269
+
270
+
271
+ def _groups(labels: np.ndarray, idx: np.ndarray) -> list[np.ndarray]:
272
+ """Split ``idx`` into arrays of equal ``labels[idx]``, each sorted."""
273
+ if len(idx) == 0:
274
+ return []
275
+ order = idx[np.argsort(labels[idx], kind="stable")]
276
+ cuts = np.flatnonzero(np.diff(labels[order])) + 1
277
+ return np.split(order, cuts)
278
+
279
+
280
+ def _count_loops(edges: np.ndarray) -> int:
281
+ """Count connected loops formed by a set of (boundary) edges."""
282
+ if len(edges) == 0:
283
+ return 0
284
+ nodes, inv = np.unique(edges, return_inverse=True)
285
+ inv = inv.reshape(-1, 2)
286
+ n, _ = connected_components(adjacency(inv[:, 0], inv[:, 1], len(nodes)), directed=False)
287
+ return int(n)
288
+
289
+
290
+ def _nest(vertices: np.ndarray, faces: np.ndarray, shells: list[Shell]) -> tuple[
291
+ list[tuple[int, int]], list[tuple[int, int]], dict[int, Manifold]]:
292
+ """Set ``depth`` and ``parent`` of closed shells and find pairs that overlap or touch.
293
+
294
+ ``faces`` must be consistently oriented within each shell.
295
+
296
+ Returns:
297
+ Pairs of closed shells that partially overlap, pairs that touch over
298
+ an area without overlapping, and each closed shell as an
299
+ outward-oriented solid (where it is a valid manifold).
300
+ """
301
+ closed = [i for i, s in enumerate(shells) if s.closed and not s.flat]
302
+ if len(closed) < 2:
303
+ return [], [], {}
304
+
305
+ solids: dict[int, Manifold] = {}
306
+ lo, hi, vol = {}, {}, {}
307
+ for i in closed:
308
+ f = faces[shells[i].faces]
309
+ if shells[i].volume < 0:
310
+ f = f[:, ::-1]
311
+ used, local = np.unique(f, return_inverse=True)
312
+ mesh = Mesh(vert_properties=vertices[used].astype(np.float32),
313
+ tri_verts=local.reshape(-1, 3).astype(np.uint32))
314
+ solid = Manifold(mesh)
315
+ if solid.status().name == "NoError":
316
+ solids[i] = solid
317
+ lo[i], hi[i] = vertices[used].min(axis=0), vertices[used].max(axis=0)
318
+ vol[i] = abs(shells[i].volume)
319
+
320
+ overlapping, touching = [], []
321
+ enclosing: dict[int, list[int]] = {}
322
+ for a_pos, a in enumerate(closed):
323
+ for b in closed[a_pos + 1:]:
324
+ if np.any(hi[a] < lo[b]) or np.any(hi[b] < lo[a]):
325
+ continue
326
+ small, big = (a, b) if vol[a] <= vol[b] else (b, a)
327
+ if a in solids and b in solids:
328
+ common = (solids[a] ^ solids[b]).volume()
329
+ if common <= _VOLUME_RTOL * vol[small]:
330
+ # The union fuses solids touching over an area, not
331
+ # those touching only along an edge or at a point.
332
+ if len((solids[a] + solids[b]).decompose()) == 1:
333
+ touching.append((a, b))
334
+ continue
335
+ if common < (1 - _VOLUME_RTOL) * vol[small]:
336
+ overlapping.append((a, b))
337
+ continue
338
+ if _inside(vertices, faces[shells[big].faces], _probe(vertices, faces[shells[small].faces])):
339
+ shells[small].depth += 1
340
+ enclosing.setdefault(small, []).append(big)
341
+ for i, outer in enclosing.items():
342
+ shells[i].parent = max(outer, key=lambda j: shells[j].depth)
343
+ return overlapping, touching, solids
344
+
345
+
346
+ def _total_volume(shells: list[Shell], overlapping: list[tuple[int, int]],
347
+ solids: dict[int, Manifold]) -> float:
348
+ """Sum the volumes of closed shells, counting each group of overlapping solids once."""
349
+ volume = {i: s.volume for i, s in enumerate(shells) if s.closed}
350
+ if overlapping:
351
+ pairs = np.array(overlapping)
352
+ _, group = connected_components(adjacency(pairs[:, 0], pairs[:, 1], len(shells)), directed=False)
353
+ involved = np.unique(pairs)
354
+ for g in np.unique(group[involved]):
355
+ members = [int(i) for i in involved if group[i] == g]
356
+ if all(i in solids and volume[i] > 0 for i in members):
357
+ union = reduce(lambda a, b: a + b, (solids[i] for i in members))
358
+ for i in members:
359
+ volume[i] = 0.0
360
+ volume[members[0]] = union.volume()
361
+ return float(sum(volume.values()))
362
+
363
+
364
+ def _self_intersecting(vertices: np.ndarray, faces: np.ndarray, shells: list[Shell]) -> np.ndarray:
365
+ """Return a mask of triangles that cross another triangle of their closed shell.
366
+
367
+ Two triangles cross if an edge of one passes through the interior of the
368
+ other and each reaches more than ``_CROSSING_DEPTH`` through the plane of
369
+ the other. Touching at shared vertices or edges and coplanar overlaps do
370
+ not count.
371
+ """
372
+ mask = np.zeros(len(faces), dtype=bool)
373
+ closed = [s.faces for s in shells if s.closed]
374
+ if not closed:
375
+ return mask
376
+ cand = np.concatenate(closed)
377
+ shell_of = np.repeat(np.arange(len(closed)), [len(c) for c in closed])
378
+ tri = vertices[faces[cand]]
379
+ lo, hi = tri.min(axis=1), tri.max(axis=1)
380
+ tri = tri - (lo.min(axis=0) + hi.max(axis=0)) / 2
381
+ normal = np.cross(tri[:, 1] - tri[:, 0], tri[:, 2] - tri[:, 0])
382
+ offset = np.einsum("ij,ij->i", normal, tri[:, 0])
383
+ extent = (hi - lo).max(axis=1)
384
+ # Plane distances are scaled by |normal|; this is the depth threshold.
385
+ depth_tol = np.maximum(_CROSSING_DEPTH * np.linalg.norm(normal, axis=1), 1e-10 * extent**3)
386
+
387
+ props = rtree.index.Property()
388
+ props.dimension = 3
389
+ tree = rtree.index.Index((np.arange(len(cand), dtype=np.int64), lo, hi), properties=props)
390
+ ids, counts = tree.intersection_v(lo, hi)
391
+ a, b = np.repeat(np.arange(len(cand)), counts.astype(np.int64)), ids.astype(np.int64)
392
+ keep = (a < b) & (shell_of[a] == shell_of[b])
393
+ a, b = a[keep], b[keep]
394
+ # Neighbours across an edge can only overlap coplanar.
395
+ shared = (faces[cand[a]][:, :, None] == faces[cand[b]][:, None, :]).sum(axis=(1, 2))
396
+ a, b = a[shared < 2], b[shared < 2]
397
+
398
+ for start in range(0, len(a), _PAIR_CHUNK):
399
+ pa, pb = a[start:start + _PAIR_CHUNK], b[start:start + _PAIR_CHUNK]
400
+ tol = 1e-10 * np.maximum(extent[pa], extent[pb]) ** 3
401
+ # Crossing triangles straddle each other's plane; this cheap test
402
+ # rejects almost all pairs, including coplanar fans and shallow folds.
403
+ s = (_straddles(tri[pa], normal[pb], offset[pb], depth_tol[pb])
404
+ & _straddles(tri[pb], normal[pa], offset[pa], depth_tol[pa]))
405
+ pa, pb, tol = pa[s], pb[s], tol[s]
406
+ origin = tri[pa, :1]
407
+ t1, t2 = tri[pa] - origin, tri[pb] - origin
408
+ hit = _edges_cross(t1, t2, tol) | _edges_cross(t2, t1, tol)
409
+ mask[cand[pa[hit]]] = True
410
+ mask[cand[pb[hit]]] = True
411
+ return mask
412
+
413
+
414
+ def _straddles(t: np.ndarray, normal: np.ndarray, offset: np.ndarray, tol: np.ndarray) -> np.ndarray:
415
+ """Return per pair whether triangle ``t`` has corners strictly on both sides of a plane.
416
+
417
+ The plane is the set of points ``x`` with ``normal · x = offset``.
418
+ """
419
+ side = np.einsum("ikj,ij->ik", t, normal) - offset[:, None]
420
+ return (side > tol[:, None]).any(axis=1) & (side < -tol[:, None]).any(axis=1)
421
+
422
+
423
+ def _edges_cross(t1: np.ndarray, t2: np.ndarray, tol: np.ndarray) -> np.ndarray:
424
+ """Return per pair whether an edge of ``t1`` strictly crosses triangle ``t2``.
425
+
426
+ Args:
427
+ t1: ``(k, 3, 3)`` corners of the first triangle of each pair.
428
+ t2: ``(k, 3, 3)`` corners of the second triangle of each pair.
429
+ tol: ``(k,)`` magnitude below which an orientation counts as zero.
430
+ """
431
+ a, b, c = t2[:, 0], t2[:, 1], t2[:, 2]
432
+ side = [_orient(a, b, c, t1[:, k]) for k in range(3)]
433
+ result = np.zeros(len(t1), dtype=bool)
434
+ for i, j in ((0, 1), (1, 2), (2, 0)):
435
+ p, q = t1[:, i], t1[:, j]
436
+ opposite = ((side[i] > tol) & (side[j] < -tol)) | ((side[i] < -tol) & (side[j] > tol))
437
+ o = [_orient(p, q, u, v) for u, v in ((a, b), (b, c), (c, a))]
438
+ inside = ((o[0] > tol) & (o[1] > tol) & (o[2] > tol)) | ((o[0] < -tol) & (o[1] < -tol) & (o[2] < -tol))
439
+ result |= opposite & inside
440
+ return result
441
+
442
+
443
+ def _orient(a: np.ndarray, b: np.ndarray, c: np.ndarray, d: np.ndarray) -> np.ndarray:
444
+ """Return six times the signed volume of each tetrahedron ``abcd``."""
445
+ return np.einsum("ij,ij->i", b - a, np.cross(c - a, d - a))
446
+
447
+
448
+ def _probe(vertices: np.ndarray, faces: np.ndarray) -> np.ndarray:
449
+ """Return a point on the surface: the centroid of the largest triangle."""
450
+ tri = vertices[faces]
451
+ area = np.linalg.norm(np.cross(tri[:, 1] - tri[:, 0], tri[:, 2] - tri[:, 0]), axis=1)
452
+ return tri[np.argmax(area)].mean(axis=0)
453
+
454
+
455
+ def _inside(vertices: np.ndarray, faces: np.ndarray, point: np.ndarray) -> bool:
456
+ """Return whether ``point`` lies inside the closed surface ``faces``."""
457
+ return bool(inside(vertices, faces, point[None])[0])
458
+
459
+
460
+ def inside(vertices: np.ndarray, faces: np.ndarray, points: np.ndarray) -> np.ndarray:
461
+ """Return for each point whether it lies inside the closed surface ``faces``.
462
+
463
+ Uses the winding number (sum of solid angles, Van Oosterom–Strackee),
464
+ which is ±1 inside and 0 outside regardless of orientation sign. Memory
465
+ use is bounded by testing a few points at a time.
466
+
467
+ Args:
468
+ vertices: ``(n, 3)`` float array of vertex positions.
469
+ faces: ``(m, 3)`` int array of a closed surface.
470
+ points: ``(k, 3)`` float array of query points.
471
+
472
+ Returns:
473
+ ``(k,)`` bool array.
474
+ """
475
+ tri = vertices[faces]
476
+ batch = max(1, _WINDING_BATCH // max(len(faces), 1))
477
+ result = np.zeros(len(points), dtype=bool)
478
+ for start in range(0, len(points), batch):
479
+ p = points[start:start + batch, None, :]
480
+ a, b, c = (tri[None, :, k] - p for k in range(3))
481
+ la, lb, lc = (np.linalg.norm(v, axis=2) for v in (a, b, c))
482
+ num = np.einsum("pij,pij->pi", a, np.cross(b, c))
483
+ den = (la * lb * lc + np.einsum("pij,pij->pi", a, b) * lc
484
+ + np.einsum("pij,pij->pi", b, c) * la + np.einsum("pij,pij->pi", c, a) * lb)
485
+ winding = np.arctan2(num, den).sum(axis=1) / (2 * np.pi)
486
+ result[start:start + batch] = np.abs(winding) > 0.5
487
+ return result
meshck/check.py ADDED
@@ -0,0 +1,143 @@
1
+ """Run all checks for one mesh file."""
2
+
3
+ from pathlib import Path
4
+
5
+ import numpy as np
6
+ import trimesh
7
+
8
+ from meshck.analysis import Analysis, analyze
9
+ from meshck.report import Metrics, Report, Severity
10
+
11
+
12
+ class LoadError(Exception):
13
+ """Raised when a file cannot be read as a triangle mesh."""
14
+
15
+
16
+ def load_mesh(path: Path) -> trimesh.Trimesh:
17
+ """Read an STL file (binary or ASCII) into a mesh.
18
+
19
+ Args:
20
+ path: The STL file.
21
+
22
+ Returns:
23
+ The mesh, with duplicate vertices merged.
24
+
25
+ Raises:
26
+ LoadError: If the file is missing, not a readable STL, or empty.
27
+ """
28
+ if not path.is_file():
29
+ raise LoadError(f"{path}: no such file")
30
+ try:
31
+ mesh = trimesh.load_mesh(path, file_type="stl")
32
+ except Exception as exc:
33
+ raise LoadError(f"{path}: cannot read STL ({exc})") from exc
34
+ if len(mesh.faces) == 0:
35
+ raise LoadError(f"{path}: contains no triangles")
36
+ return mesh
37
+
38
+
39
+ def check_file(path: Path) -> Report:
40
+ """Check one STL file.
41
+
42
+ Args:
43
+ path: The STL file.
44
+
45
+ Returns:
46
+ A report with metrics and all findings.
47
+
48
+ Raises:
49
+ LoadError: If the file cannot be read.
50
+ """
51
+ mesh = load_mesh(path)
52
+ return check_mesh(mesh.vertices, mesh.faces, path)
53
+
54
+
55
+ def check_mesh(vertices: np.ndarray, faces: np.ndarray, path: Path) -> Report:
56
+ """Check a mesh given as arrays.
57
+
58
+ Args:
59
+ vertices: ``(n, 3)`` float array of vertex positions in mm.
60
+ faces: ``(m, 3)`` int array of vertex indices per triangle.
61
+ path: File name to show in the report.
62
+
63
+ Returns:
64
+ A report with metrics and all findings.
65
+ """
66
+ return check_analysis(analyze(vertices, faces), path)
67
+
68
+
69
+ def check_analysis(result: Analysis, path: Path) -> Report:
70
+ """Turn an existing analysis into a report.
71
+
72
+ Args:
73
+ result: Analysis of the mesh.
74
+ path: File name to show in the report.
75
+
76
+ Returns:
77
+ A report with metrics and all findings.
78
+ """
79
+ report = Report(path=path, metrics=metrics(result))
80
+ check_topology(result, report)
81
+ check_shells(result, report)
82
+ return report
83
+
84
+
85
+ def write_stl(path: Path, vertices: np.ndarray, faces: np.ndarray) -> None:
86
+ """Write a mesh as binary STL."""
87
+ trimesh.Trimesh(vertices, faces, process=False).export(path, file_type="stl")
88
+
89
+
90
+ def metrics(result: Analysis) -> Metrics:
91
+ """Return the measured values reported for every file."""
92
+ return {
93
+ "triangles": result.triangles,
94
+ "shells": len(result.shells),
95
+ "boundary_edges": result.boundary_edges,
96
+ "holes": result.holes,
97
+ "misoriented": int(result.misoriented.sum()),
98
+ "self_intersecting": int(result.self_intersecting.sum()),
99
+ "nonmanifold_edges": result.nonmanifold_edges,
100
+ "degenerate": int(result.degenerate.sum()),
101
+ "size_mm": [round(v, 3) for v in result.size],
102
+ "volume_mm3": round(result.volume, 3),
103
+ }
104
+
105
+
106
+ def check_topology(result: Analysis, report: Report) -> None:
107
+ """Add findings for rules every printable mesh must meet."""
108
+ if result.triangles == 0:
109
+ report.add("empty", Severity.ERROR, "mesh contains no triangles")
110
+ if result.boundary_edges:
111
+ report.add("closed", Severity.ERROR,
112
+ f"mesh is open: {result.holes} hole(s), {result.boundary_edges} boundary edges")
113
+ if result.nonmanifold_edges:
114
+ report.add("manifold", Severity.ERROR,
115
+ f"{result.nonmanifold_edges} edges are shared by more than two triangles")
116
+ misoriented = int(result.misoriented.sum())
117
+ if misoriented:
118
+ report.add("oriented", Severity.ERROR, f"{misoriented} misoriented triangles")
119
+ crossing = int(result.self_intersecting.sum())
120
+ if crossing:
121
+ report.add("self_intersecting", Severity.ERROR,
122
+ f"{crossing} triangles cross other triangles of the same shell")
123
+ degenerate = int(result.degenerate.sum())
124
+ if degenerate:
125
+ report.add("degenerate", Severity.WARN, f"{degenerate} triangles have zero area")
126
+
127
+
128
+ def check_shells(result: Analysis, report: Report) -> None:
129
+ """Add findings for meshes made of several shells."""
130
+ if result.overlapping:
131
+ report.add("shells.overlapping", Severity.ERROR,
132
+ f"{len(result.overlapping)} pair(s) of shells overlap")
133
+ flat = sum(1 for s in result.shells if s.flat)
134
+ if flat:
135
+ report.add("shells.flat", Severity.WARN,
136
+ f"{flat} closed shell(s) enclose no volume (zero thickness) and will not print")
137
+ if result.touching:
138
+ report.add("shells.touching", Severity.WARN,
139
+ f"{len(result.touching)} pair(s) of shells touch over an area and fuse when printed")
140
+ parts = sum(1 for s in result.shells if s.depth % 2 == 0)
141
+ if parts > 1:
142
+ report.add("shells.separate", Severity.WARN,
143
+ f"{parts} separate parts; fine for parts meant to move, otherwise join them")