diff --git a/surfaces/blender/brokkr_kitbash/ram.py b/surfaces/blender/brokkr_kitbash/ram.py index dd250a4..22c8e10 100644 --- a/surfaces/blender/brokkr_kitbash/ram.py +++ b/surfaces/blender/brokkr_kitbash/ram.py @@ -26,6 +26,7 @@ the coupler bar at c's, the ram at a's plus each of `offsets`. 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 + weld(vertices, tolerance) the vertex each vertex is read as: those within the tolerance are one solids(part, vertices, faces) the closed, outward wound solids of a part, or the refusal placed(vertices, faces, matrix) a local mesh carried by a matrix, turned back where it mirrors Signed(shells, cap) the distance oracle over meshes, signed by the winding number @@ -83,9 +84,9 @@ GATES = ("assembly", "stroke", "toggle", "arm", "load", "clash") SCHEMA, VERSION = "brokkr.ram", 2 ZONE = ("part", "pin", "radius", "depth") # a zone of `touch`, as the record writes it BAND = 1e-9 # the loop is refused within this of a dead centre of the rocker and coupler -WELD = 3e-4 # of a part's extent: vertices this near along every axis are one vertex to `solids` +WELD = 3e-4 # of a part's extent: vertices no farther apart than this along every axis are one vertex to `solids` NUDGE = 1e-6 # of a part's extent: how far off a face's centroid its two sides are read -THIN = 1.1e-4 # of a part's extent cubed: a region winding -1 that holds less is not read as the part turned over +THIN = 1.1e-4 # of a part's extent cubed: a region winding -1 where no solid's volume is negative is let be when it holds less FINE = 64 # in a zone a segment between samples is halved down to spacing / FINE @@ -788,20 +789,33 @@ def inside(vertices, triangles, points): def weld(vertices, tolerance): - """The vertex each of `vertices` is read as: one index for all that stand within `tolerance` of one another - along every axis, and for a chain of such. Each is found by the cell it falls in on eight grids of twice the - tolerance, each half a cell off the last along some axes: two points that near share a cell of one.""" + """The vertex each of `vertices` is read as: one index, the least, for all that stand within `tolerance` of one + another along every axis, and for a chain of such. Two vertices are joined where no coordinate of theirs differs + by more than the tolerance, and only there, wherever the mesh stands: each vertex is compared with those of its + own cell and of the cells about it on one grid of the tolerance, and the grid only finds the pairs.""" v = np.asarray(vertices, dtype=float).reshape(-1, 3) label = np.arange(len(v)) if not len(v) or not tolerance > 0.0: return label - cells = [np.unique(np.floor(v / (2.0 * tolerance) + shift).astype(np.int64), axis=0, return_inverse=True)[1].reshape(-1) for shift in itertools.product((0.0, 0.5), repeat=3)] + cell = np.floor((v - v.min(axis=0)) / (tolerance * (1.0 + 1e-9))).astype(np.int64) # two within the tolerance are in one cell or in two that touch + about = [step for step in itertools.product((-1, 0, 1), repeat=3) if step >= (0, 0, 0)] # a cell and half the 26 about it: each pair of cells once + at = np.unique(np.concatenate([cell + step for step in about]), axis=0, return_inverse=True)[1].reshape(len(about), len(v)) + order, count = np.argsort(at[0], kind="stable"), np.bincount(at[0], minlength=int(at.max()) + 1) + start, first, second = np.cumsum(count) - count, [], [] + for there in at: + n = count[there] + i = np.repeat(label, n) + j = order[np.repeat(start[there], n) + np.arange(int(n.sum())) - np.repeat(np.cumsum(n) - n, n)] + near = (np.abs(v[i] - v[j]) <= tolerance).all(axis=1) + first.append(i[near]) + second.append(j[near]) + first, second = np.concatenate(first), np.concatenate(second) while True: - before = label - for cell in cells: - least = np.full(int(cell.max()) + 1, len(v)) - np.minimum.at(least, cell, label) - label = least[cell] + before, least = label, label.copy() + low = np.minimum(label[first], label[second]) + np.minimum.at(least, first, low) + np.minimum.at(least, second, low) + label = least[least] if (label == before).all(): return label @@ -814,7 +828,7 @@ def _read(part, vertices, 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).reshape(-1, 3) extent = float(np.linalg.norm(np.ptp(v, axis=0))) if len(v) else 0.0 one = weld(v, WELD * extent) - owner, edges = list(range(len(faces))), {} + owner, edges, seam = list(range(len(faces))), {}, np.zeros(len(faces), dtype=bool) def root(k): while owner[k] != k: @@ -823,6 +837,7 @@ def _read(part, vertices, faces): for k, face in enumerate(faces): face = [int(one[i]) for i in face] + seam[k] = len(set(face)) < 3 # the weld leaves it a point or a line for i, j in zip(face, face[1:] + face[:1]): if i != j: there = edges.setdefault((min(i, j), max(i, j)), [k, 0]) @@ -845,12 +860,22 @@ def _read(part, vertices, faces): before = winding(v, fan, centre + NUDGE * extent * normal[flat] / size[flat, None]) turned = np.flatnonzero(before < -0.5) if len(turned): + mid = v.mean(axis=0) + cone = np.einsum("ij,ij->i", v[fan[:, 0]] - mid, np.cross(v[fan[:, 1]] - mid, v[fan[:, 2]] - mid)) / 6.0 + for n in dict.fromkeys(of[flat[turned]].tolist()): # the solids with a turned face, in the order of those faces + volume = math.fsum(cone[of[face_of] == n].tolist()) + if volume < 0.0 and not seam[of == n].all(): # faces the weld closes up alone hold nothing: their sum is no volume + mine = flat[turned[of[flat[turned]] == n]] + raise RamError("mesh", "signed", f"part {part!r} is wound inside out: solid {n} of {len(names)} has a volume of {volume / extent ** 3:.3g} of the part's extent cubed, and {len(mine)} of its faces, from face {int(mine[0])}, stand before a region that winds {float(before[turned[of[flat[turned]] == n][0]]):.3g}") unit, rungs = normal[flat[turned]] / size[flat[turned], None], NUDGE * 10.0 ** (np.arange(25) / 4.0) # the nudge to the whole extent, four to a decade still = winding(v, fan, (centre[turned][:, None, :] + (rungs[1:] * extent)[None, :, None] * unit[:, None, :]).reshape(-1, 3)).reshape(len(turned), -1) < -0.5 held = float((0.5 * size[flat[turned]] * rungs[np.cumprod(still, axis=1).sum(axis=1)]).sum()) / extent ** 2 if held >= THIN: - k = int(flat[turned[0]]) - raise RamError("mesh", "signed", f"part {part!r} is wound inside out: {len(turned)} faces, from face {k} of solid {int(of[k])} of {len(names)}, stand before a region that winds {float(before[turned[0]]):.3g} and holds {held:.3g} of the part's extent cubed") + k, area = int(flat[turned[0]]), size[flat[turned]] + about = (centre[turned] * area[:, None]).sum(axis=0) / area.sum() + reach = float(np.linalg.norm(centre[turned] - about, axis=1).max()) + raise RamError("mesh", "signed", f"part {part!r} crosses itself: {len(turned)} faces, from face {k} of solid {int(of[k])} of {len(names)}, stand before a region that winds {float(before[turned[0]]):.3g} and holds {held:.3g} of the part's extent cubed, " + f"about ({about[0]:.4g}, {about[1]:.4g}, {about[2]:.4g}) and within {reach:.3g} of it, and no solid there has a negative volume: its surfaces cut through one another (cutters never joined, a fold), or a turned piece is welded into a whole one") return of, fan, flat, before @@ -858,19 +883,29 @@ 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. Nothing is repaired. - Vertices within WELD of the part's extent (its box's diagonal) of one another are read as one, so a seam of - coincident vertices is no hole. 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. + Open. Vertices within WELD of the part's extent (its box's diagonal) of one another along every axis are read + as one (`weld`), so a seam of coincident vertices is no hole. 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. A face is read NUDGE of the extent before its centroid, along its normal. Before a face of a whole solid the winding number is 0, or more where another solid covers it. A face is turned where the number there is under - -0.5: it stands before a region that winds -1, the inside of a solid wound inside out. That region is measured: - each turned face's area by how far out along its normal the number stays under -0.5 (the nudge, then four rungs - to a decade up to the extent), summed. A part whose region holds THIN of its extent cubed or more is wound - inside out, whether the turned solid stands free or is welded to a whole one. Less is the crossing of a bevel - or of a lathe's profile and is let be: there the part reads outside in what its author took for inside. A - cavity cut as its own inward shell has the cavity before its faces, which winds 0, and passes; so does a - sliver, two sheets back to back, with nothing between them to wind.""" + -0.5: it stands before a region that winds -1. + + Inside out. A solid with a turned face whose signed volume (the sum of a . (b x c) / 6 over its triangles, summed + exactly) is negative is wound inside out, however little it holds: the bound is zero. A solid whose every face + the weld closes up to a point or a line is a seam's leftover and has no volume to read. The turned face tells it + from a cavity cut as its own inward shell, whose volume is negative too but whose faces have the cavity before + them, which winds 0: that passes. So does a sliver, two sheets back to back, with no volume and nothing between + the sheets to wind. + + Crossing. Turned faces where no solid's volume is negative stand before a region where the part's surfaces cut + through one another: two cutters taken out of one solid and never joined, a bevel folded over a corner, a + lathe's profile crossing itself, or a turned piece welded into a whole one, which the volume of the one solid + hides. The region is measured: each turned face's area by how far out along its normal the number stays under + -0.5 (the nudge, then four rungs to a decade up to the extent), summed. A part whose region holds THIN of its + extent cubed or more is refused as crossing itself, with the faces, the region and where it lies (the turned + faces' centre by area, in the frame the vertices are given in, and how far the farthest is from it). Less is + let be: there the part reads outside in what its author took for inside.""" return _read(part, vertices, faces)[0] @@ -887,8 +922,9 @@ class Signed: """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 that is open or wound inside out is refused when the oracle is - made, by a RamError that names the part, the solid and the edge count or the turned faces and their region. A + counterclockwise seen from outside: a part that is open, wound inside out or crossing itself is refused when + the oracle is made, by a RamError that names the part and the solid with its edge count or its negative volume, + or the turned faces, their region and where it lies. A shell may be (vertices, faces, matrix), a local mesh and the 4 by 4 that carries it to the body's rest frame: it is read as `placed` gives it, the faces of a mirrored one (a negative scale) turned back, so a caller hands a mirrored object's own mesh and its matrix and never a mesh it carried itself. Inside is where `inside` diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 91669fe..c6cea31 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -1042,19 +1042,32 @@ staircase prism a line crosses six times. made (`ram.solids`, a `RamError` at gate `signed`). Nothing is repaired or guessed. The checks read the mesh as the winding number does, by where its faces are and not by how its vertices are numbered. -Open. Vertices within `WELD` (3e-4) of the part's extent of one another along every axis are one vertex -(`ram.weld`), so a seam of coincident vertices is no hole. A part's faces fall into solids, the faces joined across -an edge, and every solid is closed: each edge one face runs is run the other way by another. A solid with an edge -that is not (a boundary edge, or two faces wound against each other) is refused with the count of such edges. +Open. Vertices no farther apart than `WELD` (3e-4) of the part's extent along every axis are one vertex +(`ram.weld`), and a chain of such is one, so a seam of coincident vertices is no hole. The tolerance is the same +wherever the part stands: a pair 0.99 of it apart is joined and a pair 1.01 apart is not. A part's faces fall into +solids, the faces joined across an edge, and every solid is closed: each edge one face runs is run the other way by +another. A solid with an edge that is not (a boundary edge, or two faces wound against each other) is refused with +the count of such edges. -Inside out. Each face is read `NUDGE` (1e-6) of the extent before its centroid, along its normal. Before a face of -a whole solid the number is 0, or more where another solid covers it. A face is turned where the number there is -under -0.5: it stands before a region that winds -1. That region is measured, each turned face's area by how far out -along its normal the number stays under -0.5, and a part whose region holds `THIN` (1.1e-4) of its extent cubed or -more is refused with the count of turned faces, the first, its solid, the number and the share. A turned-over bar is -refused beside a whole cube and welded to one, where the volume in all is positive. A hollow mass, its cavity an -inward shell, has the cavity before those faces, which winds 0, and passes; so does a sliver of two sheets back to -back. +Each face is read `NUDGE` (1e-6) of the extent before its centroid, along its normal. Before a face of a whole solid +the number is 0, or more where another solid covers it. A face is turned where the number there is under -0.5: it +stands before a region that winds -1. Two things put a face there, and they are refused under two names. + +Inside out. A solid with a turned face whose signed volume is negative (the sum of `a . (b x c) / 6` over its +triangles, summed exactly) is wound inside out, and is refused with the solid, its volume and its turned faces. The +bound is zero: a cube of side 0.2 turned over beside a 6 m bar and a turned plate 1e-5 thick are refused as a whole +part turned over is. A hollow mass, its cavity an inward shell, holds a negative volume there too, but the cavity is +before those faces and winds 0, and it passes; so does a sliver of two sheets back to back. A solid whose every face +the weld closes up to a point or a line is a seam's leftover with no volume to read. + +Crossing. Turned faces where no solid's volume is negative stand where the part's surfaces cut through one another: +cutters taken out of one solid and never joined, a bevel folded over a corner, a lathe's profile crossing itself, or +a turned piece welded into a whole one, which the one solid's volume hides. That region is measured, each turned +face's area by how far out along its normal the number stays under -0.5, and a part whose region holds `THIN` +(1.1e-4) of its extent cubed or more is refused as crossing itself: the count of turned faces, the first, its solid, +the number, the share, and where the region lies (the turned faces' centre by area, in the frame the mesh was given +in, and how far the farthest stands from it). The message never calls such a part inside out: its winding is right +and its cut is not. A member cannot be seated against it honestly, so it stays refused until its builder is fixed. Mirrored. A shell may be `(vertices, faces, matrix)`: the object's own mesh and the 4 by 4 that carries it to the body's rest frame. `ram.placed` carries the vertices and turns each face back where the matrix mirrors, so a part @@ -1065,24 +1078,29 @@ The bounds stand on real meshes, and the unit suite holds them there (`tests.tes build passes at the corners of its params (316 here; 3,224 over the kits of ten other trees). Of the 1,832 mesh objects the mech experiments make (r3, mcr3, seraph, spectre, walker, chimera, paladin, kestrel), 42 are refused and 1,790 pass, the 115 mirrored ones the same in their own frame and placed. 21 are open: marks, recesses and plates with a -hole. 21 are wound inside out: 17 lathe and ball bodies; walker's two guns, whose turned barrel is welded into a -whole solid; and seraph's two Torso.LowerIn plates. `tests/fixtures/ram_meshes.npz` holds those 21 and the parts -nearest each bound. +hole. 17 are wound inside out: lathe and ball bodies, the least a solid of -1.4e-3 of the extent cubed (paladin +Waist.torso). 4 cross themselves with every solid's volume positive: walker's two guns, a box whose bore and cross +slots were cut and never joined (242 pairs of faces cross), and seraph's two Torso.LowerIn plates, folded at one +corner by a bevel over a boolean. `tests/fixtures/ram_meshes.npz` holds those 21, three of the open, the parts +nearest each bound and ten passing parts of each mech drawn at random: 89 that pass, so a change that refuses +passing parts is seen. | bound | nearest below | nearest above | | --- | --- | --- | | `WELD` 3e-4 | a plate's seam closes at 3.7e-5 (seraph Torso.SideBlockR; thirteen more from 7.8e-8 up) | a real hole closes at 2.2e-3 (seraph PauldronR.Outer) | -| `THIN` 1.1e-4 | 6.7e-5 held and let be (chimera CannonBody.gunmetal, 178 turned faces at a bevel's crossings) | 1.88e-4 held and refused (seraph Torso.LowerInL) | +| `THIN` 1.1e-4 | 6.7e-5 held and let be (chimera CannonBody.gunmetal, 178 turned faces at a bevel's crossings) | 1.88e-4 held and refused as crossing (seraph Torso.LowerInL) | | `NUDGE` 1e-6 | a turned cube's faces are held to 1e-8 and four are lost at 1e-9 | plates 1e-5 apart read as one at 1e-4 | What it gives up. A part exported open is capped before it is given. Two sheets nearer than `WELD` are one seam to -the open check, and a hole that narrow is not seen. A region winding -1 that holds under `THIN` is let be: 198 of the +the open check, and a hole that narrow is not seen. A crossing whose region holds under `THIN` is let be: 198 of the 1,790 passing mech parts have one, the crossing of a bevel or of a lathe's profile, and there the part reads outside -in what its author took for inside (the phalanges' 10 of 82 faces, 3e-6 to 3e-5 held). What a region holds is -measured along its faces' normals, not counted: by 60,000 sampled points the region is 2.4e-4 of the extent cubed in -Torso.LowerInL, 2.7e-4 in walker's gun (2.2e-3 held), 1.7e-3 in the Ankle root (1.4e-3 held) and 1.2e-5 in -CannonBody. A solid turned over inside a whole one is a cavity to the winding number and reads so, whatever its -author meant. +in what its author took for inside (the phalanges' 10 of 82 faces, 3e-6 to 3e-5 held). `THIN` is on crossings alone: +a turned piece welded into a whole solid is one solid of positive volume, so it is read as a crossing and one under +`THIN` passes (a turned plate 1e-4 thick welded to a cube along an edge). What a region holds is measured along its +faces' normals, not counted: by 60,000 sampled points the region is 2.4e-4 of the extent cubed in Torso.LowerInL, +2.7e-4 in walker's gun (2.2e-3 held) and 1.2e-5 in CannonBody. A solid turned over inside a whole one is a cavity to +the winding number and reads so, whatever its author meant. The four crossing parts cannot carry a ram's seat until +their builders join the gun's cutters and unfold the plate's corner. With every solid closed the number is whole, so `ram.inside` reads the same at any bound over 0 and up to 1; 0.5 is pinned in the unit suite on a test-only open cube, where the number is 0.527 under the hole and 0.473 over it. diff --git a/surfaces/blender/tests/fixtures/ram_meshes.npz b/surfaces/blender/tests/fixtures/ram_meshes.npz index f5a339e..a60cb44 100644 Binary files a/surfaces/blender/tests/fixtures/ram_meshes.npz and b/surfaces/blender/tests/fixtures/ram_meshes.npz differ diff --git a/surfaces/blender/tests/test_ram.py b/surfaces/blender/tests/test_ram.py index 6bf64bc..a0cc7b4 100644 --- a/surfaces/blender/tests/test_ram.py +++ b/surfaces/blender/tests/test_ram.py @@ -9,6 +9,7 @@ import importlib.util import json import math import sys +import types import unittest from dataclasses import replace from pathlib import Path @@ -543,7 +544,8 @@ WHOLE = 3.8e-4 # a winding number against the count or share a hand val SPAN_RAM = 0.848 # the ram's span with its base 0.1 from the rocker's pivot: shipped 0.5390 (about that pivot), the span about the knee's pivot 1.3347, separation 1.57 each side -SMALL = (0.05, 0.06) # the sides of a turned-over cube beside a unit cube that hold 7.5e-5 and 1.9e-4 of the extent cubed: THIN, 1.1e-4, is 1.5 and 1.7 from them +SMALL = (0.009, 0.015) # the sides of a turned-over bar welded along a unit cube's edge whose regions hold 6.75e-5 and 1.93e-4 of the extent cubed: THIN, 1.1e-4, is 1.63 and 1.75 from them +MECH_SAMPLE = (17, 4, 3, 89, 12) # the mech sample's rows: inside out, crossing, open, pass; and the mirrored among them KIT_VARIANTS = 316 # kit parts built over the corners of their params @@ -1399,7 +1401,7 @@ class Refusals(unittest.TestCase): def test_a_seam_of_coincident_vertices_is_no_hole(self): # a cube whose every triangle has its own three vertices is closed to the eye and to the winding number, and # is one solid. Its top stood off by a third of WELD of the extent is a seam and closes; by 3.4 times WELD - # (past the two cells' width, where no grid joins them) it is a hole of 4 edges on the box and 4 on the lid + # it is a hole of 4 edges on the box and 4 on the lid verts, tris = block((0, 0, 0), (1, 1, 1)) soup = verts[tris].reshape(-1, 3) self.assertEqual(R.solids("soup", soup, np.arange(36).reshape(-1, 3)).tolist(), [0] * 12) @@ -1418,24 +1420,72 @@ class Refusals(unittest.TestCase): self.assertEqual(R.weld(row, 1e-3).tolist(), [0, 0, 2, 2, 2, 5]) self.assertEqual(R.weld(row, 0.0).tolist(), [0, 1, 2, 3, 4, 5]) - def test_an_inside_out_solid_is_refused_by_its_region(self): - # a cube with every face turned over, or mirrored with its winding kept, winds -1 inside: every face stands - # before that region + def test_weld_joins_within_the_tolerance_and_no_farther_wherever_it_stands(self): + # a pair 0.99 of the tolerance apart is one vertex and a pair 1.01 apart is two, at 100 places beside a + # vertex that stands still (so the pair falls anywhere in a cell), along each axis and along all three: the + # tolerance is along every axis, and a pair 0.99 apart on all three (1.71 in all) is one + tolerance, still = 1e-3, (-7.0, -7.0, -7.0) + places = np.random.default_rng(11).uniform(-5.0, 5.0, (100, 3)) + for step in ((1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 1, 1), (-1, 1, -1)): + for at in places: + for share, reads in ((0.99, [0, 1, 1]), (1.01, [0, 1, 2])): + self.assertEqual(R.weld([still, at, at + share * tolerance * np.array(step)], tolerance).tolist(), reads, (step, at.tolist(), share)) + # one axis past the tolerance parts a pair the other two hold together + for at in places: + self.assertEqual(R.weld([still, at, at + tolerance * np.array((0.99, 1.01, 0.99))], tolerance).tolist(), [0, 1, 2]) + + def test_an_inside_out_solid_is_refused_by_its_volume(self): + # a cube with every face turned over, or mirrored with its winding kept, holds a negative volume (-1 of an + # extent cubed of 3 sqrt 3) and winds -1 inside: every face stands before that region 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.assertEqual(caught.exception.gate, "signed", name) - self.assertIn("part 'cube' is wound inside out: 12 faces, from face 0 of solid 0 of 1, stand before a region that winds -1 and holds ", str(caught.exception), name) - # a bar turned over is refused beside the cube, welded to it along an edge and welded to it on a face (there - # the volume of the one solid is positive: 0.96 and 0.8), and the same bars wound outward pass. On the face - # the cube's own face lies on the bar's and stands before the bar with it: 14 faces, the cube's two first - for name, bar, weld, said in (("beside", block((2, 0, 0), (3, 1, 0.5)), False, "12 faces, from face 12 of solid 1 of 2"), ("on an edge", block((1, 0, -0.2), (1.2, 1, 0)), True, "12 faces, from face 12 of solid 0 of 1"), - ("on a face", block((1, 0, 0), (1.2, 1, 1)), True, "14 faces, from face 2 of solid 0 of 1")): + self.assertIn("part 'cube' is wound inside out: solid 0 of 1 has a volume of -0.192 of the part's extent cubed, and 12 of its faces, from face 0, stand before a region that winds -1", str(caught.exception), name) + # a bar turned over beside the cube is a solid of its own, of negative volume, and the same bar wound outward + # passes + bar = block((2, 0, 0), (3, 1, 0.5)) + with self.assertRaises(R.RamError) as caught: + R.solids("pair", *joined((verts, tris), (bar[0], bar[1][:, ::-1]), False)) + self.assertIn("part 'pair' is wound inside out: solid 1 of 2 has a volume of -0.0137 of the part's extent cubed, and 12 of its faces, from face 12, stand before a region that winds -1", str(caught.exception)) + self.assertEqual(len(R.solids("pair", *joined((verts, tris), bar, False))), 24) + + def test_the_least_turned_solid_is_refused(self): + # the bound on a turned solid's volume is zero (verdict cut-kit-ram-lows.s4, thin-hides-small-inversions): a + # cube of side 0.2 turned over beside a whole bar 6 by 0.3 by 0.3 holds 2.1e-5 of the extent cubed, a plate 1 + # by 1 by 1e-5 turned over holds 3.5e-6, and a cube of side 0.01 by the bar 2.9e-9: each is under THIN and + # each is wound inside out. The same wound outward pass + bar = block((0, 0, 0), (6, 0.3, 0.3)) + over = lambda mesh: (mesh[0], mesh[1][:, ::-1]) + for name, whole, turned, said, first in (("a cube by a bar", joined(bar, block((7, 0, 0), (7.2, 0.2, 0.2)), False), joined(bar, over(block((7, 0, 0), (7.2, 0.2, 0.2))), False), "solid 1 of 2 has a volume of -2.13e-05", 12), + ("a plate", block((0, 0, 0), (1, 1, 1e-5)), over(block((0, 0, 0), (1, 1, 1e-5))), "solid 0 of 1 has a volume of -3.54e-06", 0), + ("a speck by a bar", joined(bar, block((7, 0, 0), (7.01, 0.01, 0.01)), False), joined(bar, over(block((7, 0, 0), (7.01, 0.01, 0.01))), False), "solid 1 of 2 has a volume of -2.89e-09", 12)): + self.assertEqual(len(R.solids("least", *whole)), len(whole[1]), name) with self.assertRaises(R.RamError, msg=name) as caught: - R.solids("pair", *joined((verts, tris), (bar[0], bar[1][:, ::-1]), weld)) - self.assertIn(f"part 'pair' is wound inside out: {said}, stand before a region that winds -1 and holds ", str(caught.exception), name) - self.assertEqual(len(R.solids("pair", *joined((verts, tris), bar, weld))), 24, name) + R.solids("least", *turned) + self.assertIn(f"part 'least' is wound inside out: {said} of the part's extent cubed, and 12 of its faces, from face {first}, stand before a region that winds -1", str(caught.exception), name) + + def test_a_part_that_crosses_itself_is_refused_by_its_region_and_where(self): + # a bar turned over and welded to the cube along an edge or on a face is one solid with it, of positive + # volume (0.96 and 0.8): no solid is inside out, and the faces before the region that winds -1 are named as + # the part crossing itself, with the region's centre and reach. On the face the cube's own face lies on the + # bar's and stands before the bar with it: 14 faces, the cube's two first. The same bars wound outward pass + verts, tris = block((0, 0, 0), (1, 1, 1)) + for name, bar, said, about in (("on an edge", block((1, 0, -0.2), (1.2, 1, 0)), "12 faces, from face 12 of solid 0 of 1", (1.1, 0.5, -0.1)), ("on a face", block((1, 0, 0), (1.2, 1, 1)), "14 faces, from face 2 of solid 0 of 1", None)): + with self.assertRaises(R.RamError, msg=name) as caught: + R.solids("pair", *joined((verts, tris), (bar[0], bar[1][:, ::-1]), True)) + self.assertEqual(caught.exception.gate, "signed", name) + self.assertIn(f"part 'pair' crosses itself: {said}, stand before a region that winds -1 and holds ", str(caught.exception), name) + self.assertIn("and no solid there has a negative volume", str(caught.exception), name) + self.assertNotIn("inside out", str(caught.exception), name) + centre = [float(x) for x in str(caught.exception).split("about (")[1].split(")")[0].split(", ")] + reach = float(str(caught.exception).split("and within ")[1].split(" of it")[0]) + inside_bar = all(lo - 1e-9 <= x <= hi + 1e-9 for x, lo, hi in zip(centre, bar[0].min(axis=0), bar[0].max(axis=0))) + self.assertTrue(inside_bar and 0.5 <= reach <= 0.55, (name, centre, reach)) # the bar is 1 long: its end faces' centres are 0.5 from the middle + if about: + self.assertLess(max(abs(a - b) for a, b in zip(centre, about)), 1e-3, name) + self.assertEqual(len(R.solids("pair", *joined((verts, tris), bar, True))), 24, name) def test_a_cavity_and_a_sliver_are_not_turned_over(self): # a cube of half side 1 with a cube of half side 0.5 turned over in it is a hollow mass: the winding number @@ -1444,6 +1494,10 @@ class Refusals(unittest.TestCase): hollow = joined(block((-1, -1, -1), (1, 1, 1)), (lambda v, t: (v, t[:, ::-1]))(*block((-0.5, -0.5, -0.5), (0.5, 0.5, 0.5))), False) self.assertEqual(R.solids("hollow", *hollow).tolist(), [0] * 12 + [1] * 12) self.assertLess(float(np.abs(R.winding(*hollow, [(0, 0, 0), (0.75, 0, 0), (0, 0.75, 0.75), (1.5, 0, 0)]) - (0, 1, 1, 0)).max()), WHOLE) + # the inner shell's volume is negative and none of its faces is turned. With a crossing the part is let (a bar + # of side SMALL[0] turned over and welded along the outer cube's edge) it is a cavity still, and passes + bar = block((1, -1, -1 - SMALL[0]), (1 + SMALL[0], 1, -1)) + self.assertEqual(R.solids("hollow", *joined(hollow, (bar[0], bar[1][:, ::-1]), True)).tolist(), [0] * 12 + [1] * 12 + [0] * 12) # a sliver is two sheets back to back, a closed solid of no volume: before either sheet is the outside, and # it passes alone, beside a cube and sharing a corner of one sheet = np.array([(0, 0, 0), (1, 0, 0), (0, 1, 0)], float), np.array([(0, 1, 2), (0, 2, 1)]) @@ -1451,18 +1505,19 @@ class Refusals(unittest.TestCase): self.assertEqual(R.solids("beside", *joined(block((2, 0, 0), (3, 1, 1)), sheet, False)).tolist(), [0] * 12 + [1] * 2) self.assertEqual(R.solids("welded", *joined(block((-1, -1, -1), (0, 0, 0)), sheet, True)).tolist(), [0] * 12 + [1] * 2) - def test_a_turned_region_is_read_by_what_it_holds(self): - # THIN, by a cube of side s turned over beside a unit cube (extent about 1.4 + s): its six faces stand before - # a region measured by the rungs their normals reach. Side 0.05 holds 7.5e-5 and passes; side 0.06 holds 1.9e-4 - # and is refused. So a bound of 7.5e-5 or of 1.9e-4 is seen, as near THIN as the mech parts either side of it + def test_a_crossing_is_read_by_what_its_region_holds(self): + # THIN, by a bar of side s and length 1 turned over and welded along a unit cube's edge (one solid of positive + # volume, extent about 1.74): its faces stand before a region measured by the rungs their normals reach. Side + # 0.009 holds 6.75e-5 and passes; side 0.015 holds 1.93e-4 and is refused. So a bound of 6.75e-5 or of + # 1.93e-4 is seen, as near THIN as the mech parts either side of it verts, tris = block((0, 0, 0), (1, 1, 1)) - small = lambda s: joined((verts, tris), (lambda v, t: (v, t[:, ::-1]))(*block((1.2, 0, 0), (1.2 + s, s, s))), False) + small = lambda s: joined((verts, tris), (lambda v, t: (v, t[:, ::-1]))(*block((1, 0, -s), (1 + s, 1, 0))), True) self.assertEqual(len(R.solids("small", *small(SMALL[0]))), 24) with self.assertRaises(R.RamError) as caught: R.solids("small", *small(SMALL[1])) - self.assertIn("part 'small' is wound inside out: 12 faces, from face 12 of solid 1 of 2, stand before a region that winds -1 and holds ", str(caught.exception)) + self.assertIn("part 'small' crosses itself: 12 faces, from face 12 of solid 0 of 1, stand before a region that winds -1 and holds ", str(caught.exception)) held = float(str(caught.exception).split("holds ")[1].split(" of")[0]) - self.assertTrue(1.8e-4 < held < 2.0e-4, held) + self.assertTrue(1.83e-4 < held < 2.03e-4, held) # the nudge, from below: a cube turned over and turned 0.3, 0.5 and 0.7 radians about x, y and z has no face # along an axis. Its sides are held at 1e-6 of the extent and to 1e-8; at 1e-9 they are not and it would pass (ca, sa), (cb, sb), (cc, sc) = ((math.cos(t), math.sin(t)) for t in (0.3, 0.5, 0.7)) @@ -1496,18 +1551,66 @@ class Refusals(unittest.TestCase): self.assertEqual(source.count("\nclass Signed:"), 1) +class Tree: + """Blender's BVHTree as Signed makes it, keeping only the faces it was given.""" + made = [] + + @classmethod + def FromPolygons(cls, verts, faces, epsilon=0.0): + cls.made.append([tuple(face) for face in faces]) + return cls() + + +@unittest.skipIf(np is None, "numpy is not installed") +class Exposed(unittest.TestCase): + """What Signed hands its trees, under a stand-in mathutils that records the polygons: the faces of all, then the + exposed ones (verdict cut-kit-ram-lows.s4, survivors-killable-by-stub). The distances are the live suite's.""" + + def setUp(self): + mathutils, bvhtree = types.ModuleType("mathutils"), types.ModuleType("mathutils.bvhtree") + mathutils.Vector, bvhtree.BVHTree, Tree.made = tuple, Tree, [] + self.kept = {name: sys.modules.get(name) for name in ("mathutils", "mathutils.bvhtree")} + sys.modules.update({"mathutils": mathutils, "mathutils.bvhtree": bvhtree}) + + def tearDown(self): + for name, module in self.kept.items(): + if module is None: + sys.modules.pop(name, None) + else: + sys.modules[name] = module + + # two triangles of no area on one line, wound both ways: closed, and with no side to be read on + LINE = [(5.0, 0.0, 0.0), (6.0, 0.0, 0.0), (7.0, 0.0, 0.0)], [(0, 1, 2), (0, 2, 1)] + + def test_a_part_with_no_exposed_face_is_refused(self): + with self.assertRaises(R.RamError) as caught: + R.Signed({"line": [self.LINE]}) + self.assertEqual((caught.exception.gate, str(caught.exception)), ("signed", "mesh ram: signed: part 'line' has no exposed face")) + self.assertEqual(Tree.made, []) + + def test_a_face_of_no_area_is_not_exposed(self): + verts, tris = block((0, 0, 0), (1, 1, 1)) + cube = [tuple(int(i) for i in t) for t in tris] + R.Signed({"p": [(verts, cube), self.LINE]}) + every, exposed = Tree.made + self.assertEqual((len(every), exposed), (14, cube)) # the cube's twelve are its surface; the two of no area are not + + @unittest.skipIf(np is None, "numpy is not installed") class Corpus(unittest.TestCase): """The refusals against meshes nobody made for them: every part the kits build, and a sample of the 1,832 mesh objects the mech experiments make (r3, mcr3, seraph, spectre, walker, chimera, paladin, kestrel, as Blender evaluates them, each in its own frame with its world matrix). Of the 1,832, solids refuses 42: 21 open (marks, - recesses, plates with a hole) and 21 wound inside out (17 lathe and ball bodies; walker's two guns, whose - turned barrel is welded into a whole solid; seraph's two Torso.LowerIn plates). The sample is those 21, the - open and the passing parts nearest each bound, and three mirrored parts. + recesses, plates with a hole), 17 wound inside out (lathe and ball bodies, each with a solid of negative volume, + -1.4e-3 of the extent cubed at the least) and 4 that cross themselves, every solid of positive volume: walker's + two guns, a box whose bore and cross slots were cut and never joined, and seraph's two Torso.LowerIn plates, + folded at a corner by a bevel over a boolean. The sample is those 21, three open, the passing parts nearest + each bound, three mirrored parts, and ten passing parts of each mech drawn by a seeded generator from those of + 400 faces or fewer: 89 pass, so a change that refuses one passing part in twenty fails here 99 times in 100. WELD 3e-4 seams close up to 3.7e-5 of the extent (seraph Torso.SideBlockR; r3 Prow.Upper 2.3e-6, chimera Pauldron.Band 4.1e-7); the least hole closes at 2.2e-3 (seraph PauldronR.Outer): 8 and 7 apart - THIN 1.1e-4 the least region refused holds 1.88e-4 (seraph Torso.LowerInL; by 60,000 sampled points 2.4e-4 + THIN 1.1e-4 the least crossing refused holds 1.88e-4 (seraph Torso.LowerInL; by 60,000 sampled points 2.4e-4 of its extent cubed winds -1, as 2.7e-4 of walker's gun does); the greatest let be holds 6.7e-5 (chimera CannonBody.gunmetal, 178 faces at a bevel's crossings, 1.2e-5 sampled): 1.68 each side""" @@ -1539,8 +1642,8 @@ class Corpus(unittest.TestCase): self.assertEqual(built, KIT_VARIANTS) def test_the_mech_sample_reads_as_recorded(self): - # each mesh in its own frame, and placed by its world matrix (three are mirrored and pass both ways; r3's - # Hand.palm is mirrored and inside out both ways) + # each mesh in its own frame, and placed by its world matrix: the twelve mirrored ones read the same both + # ways, pass or inside out (r3's Hand.palm) sample = np.load(SURFACE / "tests" / "fixtures" / "ram_meshes.npz") rows = json.loads(str(sample["rows"])) got = {} @@ -1552,10 +1655,11 @@ class Corpus(unittest.TestCase): R.solids(row["name"], *mesh) got[row["name"], frame] = "pass" except R.RamError as error: - got[row["name"], frame] = "open" if " is open: " in str(error) else "inside out" if " is wound inside out: " in str(error) else str(error) + got[row["name"], frame] = "open" if " is open: " in str(error) else "inside out" if " is wound inside out: " in str(error) else "crossing" if " crosses itself: " in str(error) else str(error) self.assertEqual(got, {(row["name"], frame): row["reads"] for row in rows for frame in ("own", "placed")}) reads = [row["reads"] for row in rows] - self.assertEqual((reads.count("inside out"), reads.count("open"), reads.count("pass"), sum(row["mirrored"] for row in rows)), (21, 3, 9, 7)) + self.assertEqual(tuple(reads.count(kind) for kind in ("inside out", "crossing", "open", "pass")) + (sum(row["mirrored"] for row in rows),), MECH_SAMPLE) + self.assertEqual(sorted(row["name"] for row in rows if row["reads"] == "crossing"), ["seraph:Torso.LowerInL", "seraph:Torso.LowerInR", "walker:GunL.gunmetal", "walker:GunR.gunmetal"]) if __name__ == "__main__":