diff --git a/surfaces/blender/brokkr_kitbash/ram.py b/surfaces/blender/brokkr_kitbash/ram.py index f27ac23..d5fa6f5 100644 --- a/surfaces/blender/brokkr_kitbash/ram.py +++ b/surfaces/blender/brokkr_kitbash/ram.py @@ -25,6 +25,8 @@ the coupler bar at c's, the ram at a's plus each of `offsets`. record(m, ram), from_record the JSON record a rig or runtime drives from swept(fit, body, ...) points of the swept ram's surface in a body's rest frame winding(vertices, triangles, points) the generalized winding number of a triangle soup about points + inside(vertices, triangles, points) whether points are inside it: the number is 0.5 or more + solids(part, vertices, faces) the closed, outward wound solids of a part, or the refusal Signed(shells, cap) the distance oracle over meshes, signed by the winding number Clearance. The record names the mechanism's `parts`, each a piece of one body (part -> the body whose rest frame @@ -754,11 +756,12 @@ def winding(vertices, triangles, points): 2013): the triangles' signed solid angles, summed, over 4 pi. A triangle counts positive from the side its normal points away from (counterclockwise seen from outside). About a closed mesh it is the whole number of times the surface wraps the point: 0 outside, 1 inside, 2 where two solids of one mesh overlap, whether they share vertices - or cut through one another. About an open mesh it is a fraction that falls off toward the hole: the closed - mesh's number less the missing faces' share of the sphere about the point, so across a flat hole it passes - through 0.5 on the hole's own plane. The plain sum: a point costs every triangle. The corners' offsets from the - point are taken in double precision and the angles in single (2.4 times the pace): the number is good to 1e-5 a - millimetre off a face and to 1e-2 at 1e-7 off it, and nearer than that its side of the face is not held.""" + or cut through one another. About an open mesh it is a fraction that falls off toward the hole (the closed + mesh's number less the missing faces' share of the sphere about the point), and about a mesh wound inside out + it is the negative: neither has an inside to read, and Signed refuses both. The plain sum: a point costs every + triangle. The corners' offsets from the point are taken in double precision and the angles in single (2.4 times + the pace): the number is good to 1e-5 a millimetre off a face and to 1e-2 at 1e-7 off it, and nearer than that + its side of the face is not held.""" v, t, pts = np.asarray(vertices, dtype=float).reshape(-1, 3), np.asarray(triangles, dtype=int).reshape(-1, 3), np.asarray(points, dtype=float).reshape(-1, 3) A, B, C = (np.ascontiguousarray(v[t[:, k]].T) for k in range(3)) # each (3, F): a corner of every triangle out, step = np.zeros(len(pts)), max(1, 32768 // max(len(t), 1)) # a block of pairs that stays in cache: 3.1 times the pace of 400,000 @@ -771,17 +774,61 @@ def winding(vertices, triangles, points): return out / (2.0 * math.pi) +def inside(vertices, triangles, points): + """Whether each of `points` is inside the triangle soup: its winding number is 0.5 or more. About the closed, + outward wound solids `solids` passes the number is whole and any bound over 0 and up to 1 reads the same; 0.5 + is the bound because it is the middle, the farthest from both whole numbers the single-precision sum rounds + about.""" + return winding(vertices, triangles, points) >= 0.5 + + +def solids(part, vertices, faces): + """The solid each face of a part belongs to (faces joined across an edge are one solid), or a RamError where + the part has no inside to sign: a solid with an edge no face runs the other way (a boundary edge, or two faces + wound against each other across it) is open, and a closed solid of negative volume is wound inside out. + Nothing is repaired. A cavity cut as its own inward shell is such a solid and is refused with the rest.""" + v = np.asarray(vertices, dtype=float).reshape(-1, 3) + owner, edges = list(range(len(faces))), {} + + def root(k): + while owner[k] != k: + owner[k] = k = owner[owner[k]] + return k + + for k, face in enumerate(faces): + for i, j in zip(face, tuple(face[1:]) + tuple(face[:1])): + there = edges.setdefault((min(i, j), max(i, j)), [k, 0]) + there[1] += 1 if i < j else -1 + owner[root(k)] = root(there[0]) + of = np.array([root(k) for k in range(len(faces))], dtype=int) + names = {r: n for n, r in enumerate(dict.fromkeys(of.tolist()))} # solids numbered in the order of their first faces + unmatched = {} + for first, balance in edges.values(): + if balance: + unmatched[names[of[first]]] = unmatched.get(names[of[first]], 0) + 1 + for n, count in sorted(unmatched.items()): + raise RamError("mesh", "signed", f"part {part!r} is open: solid {n} of {len(names)} has {count} edge{'s' if count > 1 else ''} no face runs the other way") + of = np.array([names[r] for r in of.tolist()], dtype=int) + fan = np.array([(k, face[0], face[n], face[n + 1]) for k, face in enumerate(faces) for n in range(1, len(face) - 1)], dtype=int).reshape(-1, 4) + volume = np.bincount(of[fan[:, 0]], (v[fan[:, 1]] * np.cross(v[fan[:, 2]], v[fan[:, 3]])).sum(axis=1) / 6.0, len(names)) + for n in np.flatnonzero(volume < 0.0): + raise RamError("mesh", "signed", f"part {part!r} is wound inside out: solid {n} of {len(names)} ({int((of == n).sum())} faces from face {int(np.flatnonzero(of == n)[0])}) has volume {volume[n]:.3g}") + return of + + class Signed: - """The distance oracle over meshes: distance(part, points) is the nearest face's distance, negative where the - point is inside the part (its depth below the nearest face), capped at `cap` outside only. shells: part -> - [(vertices (N, 3), faces)], in the rest frame of the part's body, faces wound counterclockwise seen from - outside. Inside is where the winding number of all the part's faces (winding; a face of more than three corners - as a fan) is 0.5 or more: solids that overlap, in one mesh or several, welded or not, read inside wherever any - is. A mesh wound inside out reads outside everywhere. An open mesh is read as its faces wind: no point is - refused, and a point inside by a flat hole reads inside up to the hole's plane, where the sign turns with no - face there, so the reading steps by twice the distance to the hole's rim. The depth is to the nearest face of - any of the part's meshes, one buried in another included. An unknown part raises. Needs Blender's mathutils - (BVHTree) for the nearest face.""" + """The distance oracle over meshes: distance(part, points) is the distance to the part's surface, negative + where the point is inside the part (its depth), capped at `cap` outside only. shells: part -> [(vertices + (N, 3), faces)], in the rest frame of the part's body. Every solid of a part (`solids`) is closed and wound + counterclockwise seen from outside: a part with an open or an inside-out solid is refused when the oracle is + made, by a RamError that names the part, the solid and the edge count or the volume. Inside is where `inside` + says, by the winding number of all the part's faces (a face of more than three corners as a fan): solids that + overlap, in one mesh or several, welded or not, read inside wherever any is. The depth is to the nearest + exposed face: one whose centroid, set 1e-6 of the part's extent off the face along its normal, is not inside + the part. A face buried in another solid is not the part's surface and is left out. A face that crosses + another solid is taken whole by where its centroid is: left out, the depth by it reads greater than it is; + kept, a point by its buried stretch reads shallower than the part's surface is. Outside, the distance is to + the nearest face of all. An unknown part raises. Needs Blender's mathutils (BVHTree) for the nearest face.""" def __init__(self, shells, cap=None): from mathutils import Vector @@ -795,16 +842,25 @@ class Signed: faces += [tuple(at + int(i) for i in face) for face in f] at += len(v) verts = np.concatenate(verts) + solids(part, verts, faces) fan = np.array([(face[0], face[k], face[k + 1]) for face in faces for k in range(1, len(face) - 1)], dtype=int) - self.parts[part] = (BVHTree.FromPolygons(verts.tolist(), faces, epsilon=0.0), verts, fan) + normal = np.zeros((len(faces), 3)) + np.add.at(normal, np.repeat(np.arange(len(faces)), [len(face) - 2 for face in faces]), np.cross(verts[fan[:, 1]] - verts[fan[:, 0]], verts[fan[:, 2]] - verts[fan[:, 0]])) + size = np.linalg.norm(normal, axis=1) + flat = np.flatnonzero(size > 0.0) # a face of no area has no side to be exposed on + off = np.array([verts[list(faces[k])].mean(axis=0) for k in flat]) + 1e-6 * np.linalg.norm(np.ptp(verts, axis=0)) * normal[flat] / size[flat, None] + exposed = [faces[k] for k in flat[~inside(verts, fan, off)]] + if not exposed: + raise RamError("mesh", "signed", f"part {part!r} has no exposed face") + self.parts[part] = (BVHTree.FromPolygons(verts.tolist(), faces, epsilon=0.0), BVHTree.FromPolygons(verts.tolist(), exposed, epsilon=0.0), verts, fan) def __call__(self, part, pts): pts = np.asarray(pts, dtype=float).reshape(-1, 3) self.asked += len(pts) - tree, verts, fan = self.parts[part] + tree, surface, verts, fan = self.parts[part] out = np.full(len(pts), math.inf if self.cap is None else self.cap) - for i in np.flatnonzero(winding(verts, fan, pts) >= 0.5): - out[i] = -tree.find_nearest(self.vector(pts[i]))[3] + for i in np.flatnonzero(inside(verts, fan, pts)): + out[i] = -surface.find_nearest(self.vector(pts[i]))[3] for i in np.flatnonzero(out >= 0): hit = tree.find_nearest(self.vector(pts[i]), self.cap) if self.cap else tree.find_nearest(self.vector(pts[i])) if hit[0] is not None: diff --git a/surfaces/blender/tests/test_ram.py b/surfaces/blender/tests/test_ram.py index 2074ff8..3cb02f5 100644 --- a/surfaces/blender/tests/test_ram.py +++ b/surfaces/blender/tests/test_ram.py @@ -1351,6 +1351,63 @@ class Refusals(unittest.TestCase): for gone in (top, top[:1]): self.assertEqual(int((R.winding(verts, np.delete(tris, gone, axis=0), inner) < 0.5).sum()), 0) + def test_inside_is_half_a_winding_or_more(self): + # the bound, on a mesh only a test may read: a unit cube less its top winds 0.527 on the hole's axis 0.03 + # under the hole's plane and 0.473 as far over it (1 less, and plainly, asin(0.25 / 0.2509) / pi). A bound + # of 0.45 reads the point over the hole inside and one of 0.55 the point under it outside: 0.473 and 0.527 + # stand at the geometric means of 0.5 and those two, 1.06 from each, all the room there is between them + verts, tris = block((0, 0, 0), (1, 1, 1)) + opened = np.delete(tris, [k for k, t in enumerate(tris) if (verts[t][:, 2] == 1.0).all()], axis=0) + pts = np.array([(0.5, 0.5, 0.97), (0.5, 0.5, 1.03)]) + w = R.winding(verts, opened, pts) + self.assertLess(float(np.abs(w - (0.5270, 0.4730)).max()), 1e-4) + self.assertEqual(R.inside(verts, opened, pts).tolist(), [True, False]) + # about closed solids the number is whole, so there the bound reads as any over 0 and up to 1 would + cloud = np.random.default_rng(5).uniform(-0.2, 1.2, (500, 3)) + self.assertEqual(R.inside(verts, tris, cloud).tolist(), ((cloud > 0) & (cloud < 1)).all(axis=1).tolist()) + + def test_solids_are_the_closed_pieces_of_a_part(self): + # the jointlib rocker plates are four closed bars, each wound outward: none is refused. Two boxes that cut + # through one another are two solids, sharing a corner's index or not + fixture = json.loads((SURFACE / "tests" / "fixtures" / "ram_plates.json").read_text(encoding="utf-8")) + self.assertEqual(np.bincount(R.solids("plates", fixture["verts"], fixture["faces"])).tolist(), [84, 84, 84, 84]) + for weld in (False, True): + verts, tris = joined(block((0, 0, 0), (1, 1, 1)), block((0, 0, 0), (2, 0.5, 0.5)), weld) + self.assertEqual(R.solids("boxes", verts, tris).tolist(), [0] * 12 + [1] * 12) + self.assertEqual(R.solids("stairs", *staircase()).tolist(), [0] * 28) + + def test_an_open_part_is_refused_by_its_edge_count(self): + # a cube less a triangle has 3 edges no face runs back along, less its top 4, less two adjacent faces 6 + # (the edge between them is gone with both); one triangle turned over leaves its 3 edges run twice one way + verts, tris = block((0, 0, 0), (1, 1, 1)) + top = [k for k, t in enumerate(tris) if (verts[t][:, 2] == 1.0).all()] + side = [k for k, t in enumerate(tris) if (verts[t][:, 1] == 1.0).all()] + turned_over = tris.copy() + turned_over[0] = tris[0][::-1] + less = lambda gone: (verts, np.delete(tris, gone, axis=0)) + for name, mesh, count, solid in (("a triangle off", less(top[:1]), 3, "solid 0 of 1"), ("the top off", less(top), 4, "solid 0 of 1"), ("two faces off", less(top + side), 6, "solid 0 of 1"), + ("a triangle turned over", (verts, turned_over), 3, "solid 0 of 1"), ("the second of two open", joined(block((2, 0, 0), (3, 1, 1)), less(top), False), 4, "solid 1 of 2")): + with self.assertRaises(R.RamError, msg=name) as caught: + R.solids("cube", *mesh) + self.assertEqual(caught.exception.gate, "signed", name) + self.assertIn(f"part 'cube' is open: {solid} has {count} edges no face runs the other way", str(caught.exception), name) + + def test_an_inside_out_solid_is_refused_by_name(self): + # a cube with every face turned over, or mirrored with its winding kept, has volume -1. A cube with a bar + # of half its volume turned over beside it has a positive volume in all: the bar is refused as its solid + verts, tris = block((0, 0, 0), (1, 1, 1)) + for name, v, t in (("turned over", verts, tris[:, ::-1]), ("mirrored", verts * (-1, 1, 1), tris)): + with self.assertRaises(R.RamError, msg=name) as caught: + R.solids("cube", v, t) + self.assertIn("part 'cube' is wound inside out: solid 0 of 1 (12 faces from face 0) has volume -1", str(caught.exception), name) + bar_v, bar_t = block((2, 0, 0), (3, 1, 0.5)) + mixed = joined((verts, tris), (bar_v, bar_t[:, ::-1]), False) + self.assertAlmostEqual(sum(float(mixed[0][a] @ np.cross(mixed[0][b], mixed[0][c])) / 6.0 for a, b, c in mixed[1]), 0.5, places=12) + with self.assertRaises(R.RamError) as caught: + R.solids("pair", *mixed) + self.assertIn("part 'pair' is wound inside out: solid 1 of 2 (12 faces from face 12) has volume -0.5", str(caught.exception)) + self.assertEqual(R.solids("pair", *joined((bar_v, bar_t), (verts, tris), False)).tolist(), [0] * 12 + [1] * 12) + def test_no_blender(self): source = (SURFACE / "brokkr_kitbash" / "ram.py").read_text(encoding="utf-8") for word in ("bpy", "np.gradient"):