Merge remote-tracking branch 'origin/main' into nibu/trace-block

This commit is contained in:
Meta Vens 2026-12-03 10:00:45 +01:00
commit 4779e6cc5c
13 changed files with 1214 additions and 202 deletions

View file

@ -1650,7 +1650,9 @@ class BROKKR_KITBASH_OT_shell(PolishOperator):
smooth.levels = smooth.render_levels = self.levels
smooth.subdivision_type, smooth.boundary_smooth, smooth.use_creases = "CATMULL_CLARK", built.boundary, True
wall = obj.modifiers.get(SOLIDIFY) or obj.modifiers.new(SOLIDIFY, "SOLIDIFY")
wall.thickness, wall.offset, wall.use_even_offset, wall.use_rim = self.thickness, self.offset, True, True
# plain offset: each inner vertex stands the thickness off its outer one along the vertex normal. Even offset divides by the cosine
# of the crease's half-angle, and at a pinned corner of a narrow plate that factor throws a needle (docs/kitbash.md, Thickness at a crease)
wall.thickness, wall.offset, wall.use_even_offset, wall.use_rim = self.thickness, self.offset, False, True
sync_bevel(obj, self.bevel)
obj[SHELL] = json.dumps({"sheet": document, "thickness": self.thickness, "offset": self.offset, "levels": self.levels, "bevel": self.bevel})
starts = np.cumsum(built.counts) - built.counts

View file

@ -24,13 +24,21 @@ the coupler bar at c's, the ram at a's plus each of `offsets`.
search(kind, hinge, ram, seats, ...) the best of a seat grid, or the tally and the nearest miss
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
Signed(shells, cap) the distance oracle over closed meshes, signed by three rays
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
Clearance. The record names the mechanism's `parts`, each a piece of one body (part -> the body whose rest frame
it turns with: a thigh's core, the bracket that carries the rocker's pivot, a link's plates, a pin), and `touch`:
for each member of MEMBERS[kind], zones (part, pin, radius, depth). Every member meets every part. A zone lowers
what the member's samples keep from one part, and only within `radius` of the axis of `pin`, one of the member's
own (RIDES), measured across the hinge axis: there a sample may come as near the part as -depth and no nearer.
The part is one of a body that pin joins (JOINS: a the parent; the rocker's pivot the parent and the rocker; p the
rocker and the coupler; c the coupler and the child; b the child; d the rocker), or the record is refused: what a
member meets at a pin is of the bodies pinned there, and a part of any other body is never let near it.
depth is 0 for what is stacked beside the member on the pin (a plate, the bracket or horn the pin stands in: the
member's axis stays outside it, so a pin whose place along the axis is inside the part it claims to stand beside
is refused), the pin's radius for the pin through the member's eye, half the thickness for the member's own plate
@ -54,6 +62,7 @@ between two points.
A RamError of a gate (assembly, stroke, toggle, arm, load, clash) names the angle and the pin; one of the record
or of a call (an unknown kind, a range, a grid over the limit, a version) names the pin or the field it refuses.
"""
import itertools
import math
from dataclasses import dataclass, field, fields, replace
@ -68,13 +77,17 @@ MEMBERS = {"direct": ("barrel", "rod"), "four_bar": ("barrel", "rod", "rocker",
EYE = {"direct": "b", "four_bar": "d", "bell_crank": "d"} # the pin the rod's eye rides
RIDES = {kind: {"barrel": ("a", EYE[kind]), "rod": ("a", EYE[kind]), "rocker": ("rocker", "p"), "coupler": ("p", "c"), "rocker arm": ("rocker", "d")}
for kind in KINDS} # member -> the pins at its start and its end
JOINS = {kind: {"a": ("parent",), "b": ("child",)} if kind == "direct" else
{"a": ("parent",), "rocker": ("parent", "rocker"), "p": ("rocker", "coupler"), "c": ("coupler", "child"), "d": ("rocker",)}
for kind in KINDS} # pin -> the bodies it joins: only their parts are zoned about it
GATES = ("assembly", "stroke", "toggle", "arm", "load", "clash")
SCHEMA, VERSION = "brokkr.ram", 1
SCHEMA, VERSION = "brokkr.ram", 2
ZONE = ("part", "pin", "radius", "depth") # a zone of `touch`, as the record writes it
COMPLIANCE = ("stiffness", "damping", "travel") # reserved: a load-path ram's settle, solved by a later version
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 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 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
RAYS = ((0.5377, 0.6211, 0.5701), (-0.7071, 0.2903, 0.6447), (0.1873, -0.8011, -0.5684)) # Signed's, in order
class RamError(ValueError):
@ -216,6 +229,9 @@ class Mechanism:
radius, depth = _number(self.kind, f"{member} {part} radius", radius, 0.0), _number(self.kind, f"{member} {part} depth", depth)
if depth < 0.0:
raise RamError(self.kind, "record", f"a depth of 0 or more, got {depth!r}", pin=f"{member} {part} depth")
if self.parts[part] not in JOINS[self.kind][pin]:
raise RamError(self.kind, "record", f"{member} may touch about {pin} a part of a body the pin joins ({', '.join(JOINS[self.kind][pin])}); "
f"{part!r} turns with {self.parts[part]}", pin=f"{member} {part} pin")
span = _span(self, member)
for name, value in (("radius", radius), ("depth", depth)):
if value > span:
@ -661,21 +677,20 @@ def search(kind, hinge, ram, seats, world=None, limit=20000, steps=25, spacing=N
def record(m, ram):
"""The mechanism record: plain JSON types, everything a rig or runtime needs to drive the ram from the hinge
angle (from_record, then length or extension). It holds what is authored and nothing derived from it: barrel,
closed length and link lengths come from the pins and the ram. `compliance` is reserved for a load-path ram's
settle (COMPLIANCE: stiffness, damping, travel); version 1 writes it null and solves none."""
closed length and link lengths come from the pins and the ram."""
return {"schema": SCHEMA, "version": VERSION, "kind": m.kind,
"hinge": {"pivot": m.pivot.tolist(), "axis": m.axis.tolist(), "lo": m.lo, "hi": m.hi},
"pins": {name: getattr(m, name).tolist() for name in PINS[m.kind]}, "offsets": list(m.offsets),
"ram": {f.name: getattr(ram, f.name) for f in fields(Ram)},
"parts": dict(m.parts), "compliance": None,
"parts": dict(m.parts),
"touch": {member: [dict(zip(ZONE, zone)) for zone in zones] for member, zones in m.touch.items()}}
def from_record(data):
"""(Mechanism, Ram) of a record. A record of another schema or version (the integer 1: not 1.0, not true), with
a key this version does not know or without one it does, with a compliance block, or with a value that is not
its field's type (a finite number, three of them, a name), or with a zone wider or deeper than its member is
refused whole, as a RamError naming the field: nothing is read past and dropped."""
"""(Mechanism, Ram) of a record. A record of another schema or version (the integer 2: not 2.0, not true), with
a key this version does not know or without one it does, or with a value that is not its field's type (a finite
number, three of them, a name), or with a zone of a body its pin does not join, or wider or deeper than its
member, is refused whole, as a RamError naming the field: nothing is read past and dropped."""
if not isinstance(data, dict):
raise RamError("None", "record", f"a record is an object, got {type(data).__name__}")
kind, version = str(data.get("kind")), data.get("version")
@ -695,13 +710,11 @@ def from_record(data):
raise RamError(kind, "record", f"three finite numbers, got {value!r}", pin=name)
return [_number(kind, name, x) for x in value]
keys("record", data, ("schema", "version", "kind", "hinge", "pins", "offsets", "ram", "parts", "touch", "compliance"))
keys("record", data, ("schema", "version", "kind", "hinge", "pins", "offsets", "ram", "parts", "touch"))
hinge, pins, ram = data["hinge"], data["pins"], data["ram"]
keys("hinge", hinge, ("pivot", "axis", "lo", "hi"))
keys("pins", pins, PINS[kind])
keys("ram", ram, [f.name for f in fields(Ram)])
if data["compliance"] is not None:
raise RamError(kind, "record", f"a compliance block ({', '.join(COMPLIANCE)}) is a later version's: version {VERSION} solves none and will not drop it")
for name, value in ram.items():
_number(kind, name, value, 0.0 if name == "bore" else None)
if not isinstance(data["offsets"], list):
@ -744,47 +757,212 @@ def swept(f, body, margin=0.0, steps=13, around=8):
return _into(m, p, body, np.concatenate(pts, axis=1)).reshape(-1, 3)
class Signed:
"""The distance oracle over closed meshes: distance(part, points) is the nearest face's distance, negative
where the point is inside one of the part's shells (its depth below the nearest face), capped at `cap` outside
only. shells: part -> [(vertices (N, 3), faces)], each shell closed, in the rest frame of the part's body.
Inside is the crossing parity of `rays` of RAYS, by majority: one ray that runs through an edge or a vertex
miscounts, and a sample then reads inside a plate it stands clear of. An unknown part raises. Needs Blender's
mathutils (BVHTree)."""
def winding(vertices, triangles, points):
"""The generalized winding number of a triangle soup about each of `points` (Jacobson, Kavan and Sorkine-Hornung
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), 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
for k in range(0, len(pts), step):
p = pts[k:k + step].T[:, :, None]
(ax, ay, az), (bx, by, bz), (cx, cy, cz) = ((corner[:, None, :] - p).astype(np.float32) for corner in (A, B, C))
la, lb, lc = np.sqrt(ax * ax + ay * ay + az * az), np.sqrt(bx * bx + by * by + bz * bz), np.sqrt(cx * cx + cy * cy + cz * cz)
volume = ax * (by * cz - bz * cy) + ay * (bz * cx - bx * cz) + az * (bx * cy - by * cx)
out[k:k + step] = np.arctan2(volume, la * lb * lc + (ax * bx + ay * by + az * bz) * lc + (bx * cx + by * cy + bz * cz) * la + (cx * ax + cy * ay + cz * az) * lb).sum(axis=1, dtype=float)
return out / (2.0 * math.pi)
def __init__(self, shells, cap=None, rays=3):
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 weld(vertices, tolerance):
"""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
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, 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
def _read(part, vertices, faces):
"""`solids`, and with each face's solid the fan of triangles, the faces of some area and the winding number
before each of those: what Signed keeps."""
v = np.asarray(vertices, dtype=float).reshape(-1, 3)
face_of = np.repeat(np.arange(len(faces)), [len(face) - 2 for face in 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, seam = list(range(len(faces))), {}, np.zeros(len(faces), dtype=bool)
def root(k):
while owner[k] != k:
owner[k] = k = owner[owner[k]]
return k
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])
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)
normal = np.zeros((len(faces), 3))
np.add.at(normal, face_of, np.cross(v[fan[:, 1]] - v[fan[:, 0]], v[fan[:, 2]] - v[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 read on
centre = np.array([v[list(faces[k])].mean(axis=0) for k in flat]).reshape(-1, 3)
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, 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
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.
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.
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]
def placed(vertices, faces, matrix):
"""A local mesh in the frame a 4 by 4 `matrix` carries it to: the vertices carried, and each face turned back
where the matrix mirrors (its determinant is negative), so a part mirrored by a negative scale is wound as its
own mesh is."""
m = np.asarray(matrix, dtype=float).reshape(4, 4)
v = np.asarray(vertices, dtype=float).reshape(-1, 3) @ m[:3, :3].T + m[:3, 3]
return v, [tuple(face)[::-1] if np.linalg.det(m[:3, :3]) < 0.0 else tuple(face) for face in faces]
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, 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`
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 NUDGE 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
from mathutils.bvhtree import BVHTree
self.cap, self.asked, self.vector = cap, 0, Vector
self.rays = [Vector(ray).normalized() for ray in RAYS[:rays]]
self.trees = {part: [(BVHTree.FromPolygons(np.asarray(v, dtype=float).tolist(), [tuple(face) for face in f], epsilon=0.0),
np.min(v, axis=0), np.max(v, axis=0)) for v, f in made] for part, made in shells.items()}
@staticmethod
def crossings(tree, v, ray):
count, o = 0, v
for _ in range(64):
loc = tree.ray_cast(o, ray)[0]
if loc is None:
break
count, o = count + 1, loc + ray * 1e-6
return count
def inside(self, tree, v):
return 2 * sum(self.crossings(tree, v, ray) % 2 for ray in self.rays) > len(self.rays)
self.cap, self.asked, self.vector, self.parts = cap, 0, Vector, {}
for part, made in shells.items():
verts, faces, at = [], [], 0
for v, f, *matrix in made:
v, f = placed(v, f, *matrix) if matrix else (np.asarray(v, dtype=float).reshape(-1, 3), f)
verts.append(v)
faces += [tuple(at + int(i) for i in face) for face in f]
at += len(v)
verts = np.concatenate(verts)
_, fan, flat, before = _read(part, verts, faces)
exposed = [faces[k] for k in flat[before < 0.5]]
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)
pts = np.asarray(pts, dtype=float).reshape(-1, 3)
self.asked += len(pts)
tree, surface, verts, fan = self.parts[part]
out = np.full(len(pts), math.inf if self.cap is None else self.cap)
for tree, lo, hi in self.trees[part]:
boxed = ((pts >= lo) & (pts <= hi)).all(axis=1)
for i, p in enumerate(pts):
v = self.vector(p)
if boxed[i] and self.inside(tree, v):
out[i] = min(out[i], -tree.find_nearest(v)[3])
continue
hit = tree.find_nearest(v, self.cap) if self.cap else tree.find_nearest(v)
if hit[0] is not None and hit[3] < out[i]:
out[i] = hit[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:
out[i] = hit[3]
return out

View file

@ -491,7 +491,7 @@ column 3, the shoulder line, is creased, so the crown and the steep outer face a
dips: the plate is concave there, which no convex hull can be.
The object carries the cage, `crease_edge` and `crease_vert`, and the modifiers `Kit Subsurf` (`levels`, creases
used) then `Kit Solidify` (`thickness`, `offset`, even, rim filled), then any Booleans `cut` adds, then the `Kit
used) then `Kit Solidify` (`thickness`, `offset`, plain offset, rim filled), then any Booleans `cut` adds, then the `Kit
Bevel` when `bevel` is over 0. `kit_shell` on it is the request, and it owns the cage as `kit_params` owns a
part's mesh: an edit of the cage by hand is lost at the next `shell` call. `shell` reports `object`, `rebuilt`,
`rings`, `points`, `cageFaces`, `creases` (edges with a weight over 0), `folded` (see Thickness at a crease),
@ -513,29 +513,46 @@ the outline, and the plate left between two bites is a tab.
it; a rib deeper than the room a tight crease leaves is refused with the size to lower.
**Thickness at a crease.** `shell` takes any `thickness` in its range and does not refuse one the cage cannot
hold: the limit is a fact of the subdivided mesh, not of the cage. Even thickness moves a vertex on a
full crease along the crease's bisector, which slides it `thickness` x tan(phi) across each facet, phi being half
the angle between the two facets' normals; the vertices beside it move straight in. Where that slide is longer than
the first row of subdivided faces, the wall's far face folds over itself beside the crease: at a wall depth over
(W / 2^`levels`) / tan(phi), W the width across the crease of the narrower of its two facets. The fold is on the
crease's concave side: behind a ridge, so under a wall grown inward, and in front of a valley, under a wall grown
outward; the two read the same. Measured on two flat facets, a crease of 1.0: the fold starts at 1.00 of that
figure in 23 of 23 readings (W 1 and 0.4; phi 15 to 60; levels 1 to 3; a ridge and a valley), which is 0.217 for W
1, phi 30, levels 3, and 0.029 for W 0.4, phi 60, levels 3. Facets 1.0 and 0.3 wide at phi 45, levels 2, fold at
0.075, the narrow facet's figure, not the wide one's 0.25. A crease of 0.5 folds at 1.02 to 1.32 of it, and an
uncreased edge folds too, at 1.17 to 4.2 of it. The fold is inside the wall and one subdivided row wide: the
designed surface is unchanged and the mesh has no open or non-manifold edge, but the solid passes through itself
there, and a cut through that place is untested.
hold: the limit is a fact of the subdivided mesh, not of the cage. `Kit Solidify` is a plain offset (Even Thickness
off): each vertex of the wall's far face stands `thickness` from its vertex of the designed surface, along that
vertex's normal. On a full crease that normal is the crease's bisector, so the wall there is `thickness` x cos(phi)
thick square to a facet, phi being half the angle between the two facets' normals: 0.71 of it at a right-angled
crease, and the rim strip at a creased corner is narrower by the same factor. A wall of 0.06 reads 0.0539 behind
the pauldron's shoulder crease above. The crease vertex slides `thickness` x sin(phi) across each facet; the
vertices beside it move straight in. Where that slide is longer than the first row of subdivided faces, the wall's
far face folds over itself beside the crease: at a wall depth over (W / 2^`levels`) / sin(phi), W the width across
the crease of the narrower of its two facets. The fold is on the crease's concave side: behind a ridge, so under a
wall grown inward, and in front of a valley, under a wall grown outward; the two read the same. Measured on two
flat facets, a crease of 1.0: the fold starts at 1.00 of that figure in 31 of 31 readings (W 1 and 0.4; phi 15 to
60; levels 1 to 3; a ridge, and a valley at levels 2), which is 0.25 for W 1, phi 30, levels 3, and 0.058 for W
0.4, phi 60, levels 3. Facets 1.0 and 0.3 wide at phi 45, levels 2, fold at 0.106, the narrow facet's figure, not
the wide one's 0.354. A crease of 0.5 folds at 0.72 to 1.14 of it, and an uncreased edge folds too, at 1.21 to 3.3
of it (three readings each). The fold is inside the wall and one subdivided row wide: the designed surface is
unchanged and the mesh has no open or non-manifold edge, but the solid passes through itself there, and a cut
through that place is untested.
No figure read from the cage bounds this. The flat-facet figure above, taken over every cage edge, is neither a
floor nor a ceiling on a real plate: on seeded lofts of planar trapezoid facets with partial crease runs the
evaluated wall first folded at 0.44 of it with the wall grown inward, at 0.03 of it at `offset` 0 and at 0.08 of it
grown outward, and on the Seraph's plates a first face normal turned at 0.74 to 2.6 of it (`tests/fixtures/fold_lofts.json` holds three of
those lofts; 2026-12-02). So `shell` counts instead of estimating: with `count_folds` it evaluates the wall alone,
Even Thickness would hold the wall at `thickness` square to both facets by moving the crease vertex `thickness` /
cos(phi) along the bisector. That slides it `thickness` x tan(phi) across each facet, so the wall folds sooner, at
(W / 2^`levels`) / tan(phi) (1.00 of it in the same 31 readings), and where creases meet at a pinned corner of a
narrow plate the factor runs away and the wall throws a needle. A plate of a crown ring, a flared skirt and a
domed centre, 0.13 m wide and 1.2 m long, with a wall of 0.04, stood 3.28 thicknesses beyond its cage's bounds
with Even Thickness and stands 0.95 with the plain offset (0.372 m against 0.076 m at a wall of 0.08). A hexagon of
the same make 1.2 m across folded 20 of its 168 inner faces at 0.015, 28 at 0.03 and 44 at 0.07; with the plain
offset it folds 0, 2 and 20. `tests/live/kitbash_cage.py` holds the two plates. Solidify's thickness clamp with
its angle clamp changed no fold count and no bound in either mode, and its complex mode threw a vertex 2.07 m
beyond a 1.0 m plate's cage at a wall of 0.08 (2026-12-03).
No figure read from the cage bounds this. Of three seeded lofts of planar trapezoid facets with partial crease
runs (`tests/fixtures/fold_lofts.json`), the evaluated wall first folds at 0.042 with the wall grown inward and
at 0.023 grown outward, and at `offset` 0 it folds at the least thickness `shell` takes (2026-12-03). The lofts
were drawn against Even Thickness, where the flat-facet figure of that mode, taken over every cage edge, was
neither a floor nor a ceiling: the wall first folded at 0.44 of it grown inward, at 0.03 of it at `offset` 0 and at
0.08 of it grown outward, and on the Seraph's plates a first face normal turned at 0.74 to 2.6 of it (2026-12-02).
So `shell` counts instead of estimating: with `count_folds` it evaluates the wall alone,
`Kit Subsurf` and `Kit Solidify` with every other modifier hidden for the reading and shown again, and reports
`folded`, the number of the wall's inner faces that fold. An inner face folds when the turn at any of its corners
runs with its outer twin's normal: the corner has passed over its neighbour. That is sooner than the face's own
normal turning: on the Seraph's cap a corner turned at 0.033 and no face normal had at 0.0416. Without `count_folds`, `folded` is null
normal turning: on the Seraph's cap, with Even Thickness, a corner turned at 0.033 and no face normal had at 0.0416. Without `count_folds`, `folded` is null
and nothing is evaluated. The count cost 3.9 ms on a new plate of 1600 subdivided faces (a call of 7.7 ms against
3.8 ms), and nothing measurable on a rebuild under six cutters (0.94 s against 0.92 s, the call's own Boolean),
medians of three interleaved calls in the live suite (Blender 5.3 on Starfire). On a shell whose `Kit Subsurf` or
@ -543,7 +560,7 @@ medians of three interleaved calls in the live suite (Blender 5.3 on Starfire).
`folded` 0 is not yet a wall an Exact Boolean takes cleanly. Short of the fold the inner quads at a tight rim corner
are twisted, and the Boolean, which cuts quads into triangles, can read the wall as passing through itself and
leave edges with four faces. On the Seraph's cap that began at 0.91 of the thickness at which the first face
leave edges with four faces. On the Seraph's cap, read with Even Thickness, that began at 0.91 of the thickness at which the first face
folds (0.0301 against 0.033), on the left cap and not on its mirror, the right; on its breast plate at 0.91 as
well (0.032 against 0.035). Read `nonManifoldEdges` after cutting (`boolean`, `freeze`, or a count on the evaluated
mesh), and keep `thickness` clear of the first folding one with a thinner wall, fewer `levels` or wider facets at
@ -1043,7 +1060,10 @@ body whose rest frame it turns with), and `touch`: for each member (`barrel`, `r
bell crank's `rocker arm`), zones `(part, pin, radius, depth)`. Every member meets every part. A zone changes what
the member's samples keep from one part, and only within `radius` of the axis of `pin`, measured across the hinge
axis; the pin is one the member rides (the ram `a` and its eye, the rocker its pivot and `p`, the coupler `p` and
`c`, the arm the pivot and `d`). Inside the zone a sample may come as near the part as `-depth`; beyond it the
`c`, the arm the pivot and `d`), and the part is one of a body that pin joins: `a` the parent; the rocker's pivot
the parent and the rocker; `p` the rocker and the coupler; `c` the coupler and the child; a direct ram's `b` the
child; `d` the rocker (`JOINS`). A zone naming a part of any other body is refused by the record, whatever its
radius and depth. Inside the zone a sample may come as near the part as `-depth`; beyond it the
pair is checked like any other. Nothing is exempt by a name, by a length cut from a member's end, or by the
member's own body: the barrel runs from its back end, the rod to the eye, a bar from pin to pin. Every body of the
kind owns at least one part, or the gate refuses the record.
@ -1063,7 +1083,9 @@ to pin: a bar's length between its pins, and for the barrel and the rod the base
the centre the eye turns about, added. A `Mechanism` refuses a zone past that from its pins alone. Its depth is
also no more than the member's eye on that pin (`Ram.eye`: `e_a` at the base, `e_b` at the rod's eye, `link_r` on
a bar), which `from_record` and the gate refuse, so a world's answer is held to it as well. The record holds no
plate widths, so the radius has no tighter bound than the length.
plate widths, so the radius has no tighter bound than the length, and two zones of half a member's length about
its two pins cover it whole. What the record does hold is which body a part turns with: a member is let near only
what is pinned where it is pinned.
Between two samples of which either is in a zone the gate does not rely on the spacing. A distance changes by no
more than the way between two points, so along a segment it is at least (g(a) + g(b) - length) / 2. Where that
@ -1074,7 +1096,12 @@ samples' readings stand, so a burial is read to spacing / 128. This asks of the
than the true distance.
What it gives up: inside a zone the gate holds only the member's axis `depth` from the part, not its surface a
gap from it, so a link may graze the plate it scissors with anywhere within the stated radius. The members are
gap from it, so a link may graze the plate it scissors with anywhere within the stated radius. Among the parts of
the bodies a pin joins the gate still cannot tell a member's own plate from another: a zone over the whole member
lets its axis `depth` into any of them. A part of a third body is never zoned, so a plate stacked on a pin from a
body the pin does not join is refused where it stands; it is stated as a part of a body the pin joins. A four-bar's
eye rides `d`, which joins the rocker alone, though it stands on `p`: the ram is let near the coupler's plates
there by no zone. The members are
round bars; a plate's flat sides are not modelled, which is why stacked plates need a zone at all. The proof
between samples costs oracle calls: a depth stated with no slack over the burial (a bar's own plates at `link_r`)
is halved to the floor along the whole zone. And it is along the axis at each checked angle; between two angles
@ -1095,20 +1122,20 @@ about R, and `d` about R for a bell crank, the eye standing at `a`'s place along
least arm; a miss returns the tally by gate and the nearest miss. Clearance takes `world(m) -> (parts, touch,
distance)`: a linkage's brackets and links are the candidate's own, so each candidate that reaches the gate is met
with the parts its own pins place. What `world` returns is read as a record's: anything but the three, a part on
no body of the kind, a zone that is not a part, a pin the member rides, a radius and a depth, or a zone wider or
deeper than its member is refused.
no body of the kind, a zone that is not a part, a pin the member rides, a radius and a depth, a zone of a body
its pin does not join, or a zone wider or deeper than its member is refused.
`swept` gives the ram's swept surface in any body's frame, for a recess.
### The record
`record` and `from_record` carry a mechanism as JSON: `schema` (`brokkr.ram`), `version` (1), `kind`, `hinge`,
`pins`, `offsets`, `ram`, `parts`, `touch` (member -> zones, each `{part, pin, radius, depth}`), and `compliance`.
It holds what is authored; barrel, closed length and link lengths are derived by the reader. `compliance` is
reserved for a load-path ram's settle (stiffness, damping, travel); version 1 writes it null and solves none. A
record of another schema or version (the integer 1: 1.0 and true are not it), with a key version 1 does not know or
without one it does (at the top, in `ram`, `hinge`, `pins` or a zone), with a compliance block, or with a value
that is not its field's (a finite number, the bore over 0, three numbers for a point), or with a zone wider or
deeper than its member is refused whole, as a
`record` and `from_record` carry a mechanism as JSON: `schema` (`brokkr.ram`), `version` (2), `kind`, `hinge`,
`pins`, `offsets`, `ram`, `parts` and `touch` (member -> zones, each `{part, pin, radius, depth}`).
It holds what is authored; barrel, closed length and link lengths are derived by the reader. It holds nothing of
how a load-path cylinder settles: that is a slide joint's, in the joint's own record. A
record of another schema or version (the integer 2: 2.0 and true are not it), with a key version 2 does not know or
without one it does (at the top, in `ram`, `hinge`, `pins` or a zone), or with a value
that is not its field's (a finite number, the bore over 0, three numbers for a point), or with a zone of a body
its pin does not join, or wider or deeper than its member, is refused whole, as a
`RamError` that names the field: a reader never reads past what it cannot solve. A `Ram` built by hand refuses the
same numbers.
@ -1119,11 +1146,88 @@ Bore 0.042, range 0..-125. The kinematic rows are tests/test_ram.py's. The clear
test generates (thigh with its front plate, shin with caps and armour, the bracket that carries R, the horn that
carries `c`, twin link plates stacked 5 mm apart at x 0.31..0.345 and 0.35..0.385, pins through the knee's width,
collars at the eye and a base clevis whose foot runs 0.01 into the thigh; 12 parts) and the package's signed BVH
oracle, `ram.Signed(shells, cap)`: the nearest face for the depth, the crossing parity of three rays, by majority,
for the side. One ray that runs through an edge or a vertex miscounts and signs a sample inside a plate it stands
clear of. `tests/fixtures/ram_rays.json` holds the ray count: the rocker plates as the joint library builds them
and 24 points between the plates, each on the first ray short of an edge or a vertex. One ray signs all 24
inside; three sign none. Three rays are not a proof: of 146 such points one ray missigned, two rays missigned 16.
oracle, `ram.Signed(shells, cap)`: the nearest face for the depth, the generalized winding number for the side
(Jacobson, Kavan and Sorkine-Hornung 2013). `ram.winding` sums the signed solid angle of every triangle of the part
about the point, over 4 pi: about a closed mesh the whole number of times the surface wraps the point, 0 outside, 1
inside, 2 where two solids overlap. A point is inside the part at 0.5 or more. The joint library's plates are one
mesh of four bars, a side's two overlapping about the pivot (`tests/fixtures/ram_plates.json`, with 29 points
inside them, 13 inside two bars): each reads inside, as does the overlap of two boxes welded at a corner and a
staircase prism a line crosses six times.
`Signed` checks what the winding number needs before it answers, and refuses a part by its reason when the oracle is
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 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.
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
mirrored by a negative scale reads as its own mesh does. A caller that carries a mirrored mesh itself and keeps the
winding hands over a part wound inside out.
The bounds stand on real meshes, and the unit suite holds them there (`tests.test_ram.Corpus`). Every part the kits
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. 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 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 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). `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.
Outside, the distance is to the nearest face of all. Inside, the depth is to the nearest exposed face: one whose
centroid, set `NUDGE` of the part's extent off the face along its normal, is not inside the part. A face buried in
another of the part's solids is left out, so a pin sunk 0.056 into a slab with a thin sheet buried along it reads
0.056 and is refused by a zone of depth 0.01. A face that crosses another solid is kept or left whole by where its
centroid is, not split: left out, the depth by it reads greater than it is, which the gate takes as a refusal;
kept, a point by its buried stretch reads shallower than the union's surface is (a boss through a wall: 0.500 for
0.502 and 0.539 for 0.583 in the live readings).
| drive | reading |
| --- | --- |
@ -1138,8 +1242,15 @@ Cost on Starfire, Python 3.13, 100 repetitions paired and interleaved: one candi
49 steps took 0.79 ms median on the bell crank; its clearance against the analytic parts (50 pairs) took 42 ms
(5th to 95th percentile 38 to 57) over 97,875 points, of which 23,520 are the samples and the rest the halving in
zones (the own plates, stated with no slack, to the floor); the samples alone took 11 ms. A search without a world ran 1.6 to 1.8 ms a candidate over 3,456, so `limit`
(20,000) is 30 to 40 s. On the meshes the bell crank's 60 pairs at 49 steps took 1.95 to 2.12 s capped (two runs), in a
Python loop of BVH queries with three rays a sample, and the 13,824-candidate search with its 22 worlds 43 s (one run).
(20,000) is 30 to 40 s. On the meshes the bell crank's 60 pairs at 49 steps took 0.80 to 1.00 s capped (two runs), the
winding number as the plain sum over a part's 124 to 408 triangles in numpy (single precision over double offsets,
blocks of 32,768 pairs) and the depth a Python loop of BVH queries, and the 13,824-candidate search with its 22
worlds 34.5 and 38.5 s (two runs) on a quiet machine. With the angles in double precision the search took 47.7 to
47.9 s (three runs). The live result reports the search's seconds as a reading and no check holds it: beside other
agents' Blenders at full load the same search took 61 to 94 s. With the refusals and
the exposed faces found as each of its 22 worlds is made it took 66.8 s, run after 59.3 s for the oracle before
them under that load (one pair). With the vertices welded and every face read before its centroid it took 45 to 81 s
under such load (five runs), and reading a 336-face part takes 27 to 37 ms.
## The actions

View file

@ -1,12 +1,12 @@
{
"about": "Lofts of planar trapezoid facets on which a shell's wall folds well under any figure read from the cage: the seeded lofts of Soul's probe of 2026-12-02 (aetheria-release:verdict:cut-kit-faceted-shell.s3), seed, levels and offset as drawn there. thickness is one at which the evaluated wall folds; holds, where the action's range reaches it, one at which it does not.",
"about": "Lofts of planar trapezoid facets: the seeded lofts of Soul's probe of 2026-12-02 (aetheria-release:verdict:cut-kit-faceted-shell.s3), seed, levels and offset as drawn there, on which a wall of even offset folded well under any figure read from the cage (at 0.006342, 0.010394 and 0.00617). thickness is one at which the evaluated wall, Kit Solidify's plain offset, folds; holds, where the action's range reaches it, one at which it does not. Read 2026-12-03: seed 5185 first folds at 0.0425 and seed 5196 at 0.0232, thickness and holds standing 1.2 over and under; seed 5101 folds at the range's floor.",
"lofts": [
{
"seed": 5185,
"levels": 1,
"offset": -1.0,
"thickness": 0.006342,
"holds": 0.001,
"thickness": 0.051,
"holds": 0.0354,
"sheet": {
"rings": [
[
@ -357,8 +357,8 @@
"seed": 5196,
"levels": 1,
"offset": 1.0,
"thickness": 0.00617,
"holds": null,
"thickness": 0.0279,
"holds": 0.0194,
"sheet": {
"rings": [
[

Binary file not shown.

File diff suppressed because one or more lines are too long

View file

@ -1,6 +1,7 @@
"""Live proof, in a background Blender, of brokkr_kitbash.shell's free cage through run_intent: a cage of triangles
and quads with declared poles becomes a shell whose subdivided face count is the reported one at each level, takes a
wall, counts folds and is cut; a mirrored cage closes over its seam; a loft shell is rebuilt in place as a free cage
wall, counts folds and is cut; a narrow plate's wall throws no needle and a hexagon's thin wall does not fold; a
mirrored cage closes over its seam; a loft shell is rebuilt in place as a free cage
under its cutters; the pole gate refuses without writing; tools/cage_export.py reads a cage back, an open one
included, as its maker's Subdivision draws it; and tools/cage_score.py ranks a near copy, a moved vertex, an
over-creased and a creaseless cage in that order. Not part of the unittest run: it needs Blender.
@ -72,6 +73,13 @@ SAME = 1.3e-2
# Keep Corners, read here by setting it) 7.7; the geometric mean, separation 670 each side. A closed cage does not tell
# the two apart, and a hand-modelled hull's own round trip is 0.28 (its seam snap): the open plate stands inside that.
OPEN = 1.1e-2
# Wall thicknesses: how far the furthest vertex of a narrow plate, as evaluated, stands beyond its cage's bounds.
# Shipped 0.95; mutant W1 (Kit Solidify at even offset, read here by setting it: a pinned corner's vertex moves the
# thickness over the cosine of its crease's half-angle) 3.28; the geometric mean, separation 1.86 each side.
NEEDLE = 1.77
# Inner faces of a hexagon plate's wall that fold, read as the count + 1. Shipped 0, read 1; W1 20, read 21; the
# geometric mean, separation 4.6 each side.
FOLDS = 4.6
# A tent: four triangles round an apex of valence 4 with two ridges creased, and a quad hung under one edge: 7
@ -82,6 +90,9 @@ TENT = {"verts": [[0.0, 0.0, 0.5], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [-1.0, 0.0,
HULL = {"verts": [[0.0, -1.0, 0.0], [0.004, 0.0, 0.3], [0.0, 1.0, 0.0], [0.0, 0.0, -0.3], [0.6, 0.0, 0.0]],
"faces": [[0, 4, 1], [1, 4, 2], [2, 4, 3], [3, 4, 0]], "creases": [[0, 4, 1.0], [4, 2, 1.0]], "mirror": True}
LOFT = {"rings": [[[0.3 * j - 0.45, 0.02 * j * j, 0.3 * i] for j in range(4)] for i in range(3)], "flip": True}
# Two crowns, each the outline of a plate's raised face in the plane y = 0: a strip 0.13 m wide and 1.2 m long, and a hexagon 1.2 m across.
STRIP = [[-0.06, 0.0, 0.6], [-0.07, 0.0, -0.6], [0.07, 0.0, -0.6], [0.06, 0.0, 0.6]]
HEXAGON = [[-0.5, 0.0, 0.6], [-0.62, 0.0, 0.1], [-0.4, 0.0, -0.7], [0.4, 0.0, -0.7], [0.62, 0.0, 0.1], [0.5, 0.0, 0.6]]
CUTS = [{"name": "TentLine", "part": "slab", "params": "gap=0.02; length=0.4; depth=0.03", "origin": [0.3, -0.35, 3.0], "direction": [0, 0, -1]}]
@ -132,6 +143,31 @@ def sharpest(obj):
return worst
def crown_plate(crown, flare=0.06, drop=0.07, dome=0.03):
"""The cage of a plate as the mech experiments block one, facing -y: the crown ring with its sides creased, a skirt
ring flared out of it and dropped back, one centre vertex domed, every ring corner pinned: 2N + 1 vertices."""
P = np.array(crown, dtype=float)
N = len(P)
normal = np.cross(P, np.roll(P, -1, axis=0)).sum(axis=0)
if normal[1] > 0:
P, normal = P[::-1].copy(), -normal
normal, centre = normal / np.linalg.norm(normal), P.mean(axis=0)
out = (P - centre) - np.outer((P - centre) @ normal, normal)
skirt = P + flare * out / np.linalg.norm(out, axis=1)[:, None] - drop * normal
return {"verts": np.vstack([P, skirt, centre + dome * normal]).round(5).tolist(),
"faces": [[i, (i + 1) % N, 2 * N] for i in range(N)] + [[N + i, N + (i + 1) % N, (i + 1) % N, i] for i in range(N)],
"creases": [[i, (i + 1) % N, 1.0] for i in range(N)], "corners": [[i, 1.0] for i in range(2 * N)], "poles": [] if N == 4 else [2 * N], "rim": 0.0}
def beyond(obj, sheet):
"""Metres: how far the furthest vertex of an object, as evaluated, stands outside its cage's bounds along an axis."""
bm = evaluated(obj)
at = np.array([v.co[:] for v in bm.verts])
bm.free()
cage = np.array(sheet["verts"])
return float(max((cage.min(axis=0) - at).max(), (at - cage.max(axis=0)).max(), 0.0))
def state():
return {o.name: (sorted(k for k in o.keys() if k.startswith("kit_")), len(o.data.vertices) if o.type == "MESH" else None, [m.name for m in o.modifiers]) for o in bpy.data.objects}, sorted(m.name for m in bpy.data.meshes)
@ -161,6 +197,28 @@ try:
[tuple(p.vertices) for p in tent.data.polygons] == [tuple(f) for f in TENT["faces"]] and np.abs(np.array([v.co[:] for v in tent.data.vertices]) - built.V).max() < 1e-6
and json.loads(tent["kit_shell"])["sheet"] == TENT, tent["kit_shell"])
# --- plain-wall: the Solidify's plain offset ---------------------------------------------------------------------------
section("plain-wall")
strip, hexagon = crown_plate(STRIP), crown_plate(HEXAGON)
receipt, report = send("brokkr_kitbash.shell", object_name="Strip", sheet=json.dumps(strip), thickness=0.04, levels=2, bevel=0.01)
plate = bpy.data.objects.get("Strip")
needle = beyond(plate, strip) / 0.04
plate.modifiers["Kit Solidify"].use_even_offset = True # W1
R["readings"].update({"needleThicknesses": needle, "needleThicknessesW1": beyond(plate, strip) / 0.04})
check(f"plain-wall-no-needle: a plate 0.13 m wide with a wall of 0.04 stands under {NEEDLE} thicknesses beyond its cage's bounds, and over that at even offset",
receipt["status"] == "accepted" and report["cageVerts"] == 9 and needle < NEEDLE < R["readings"]["needleThicknessesW1"], [receipt["message"], R["readings"]])
receipt, report = send("brokkr_kitbash.shell", object_name="Hexagon", sheet=json.dumps(hexagon), thickness=0.015, levels=2, count_folds=True)
plate = bpy.data.objects.get("Hexagon")
plate.modifiers["Kit Solidify"].use_even_offset = True # W1
even = sys.modules["brokkr_kitbash"].BROKKR_KITBASH_OT_shell.folded_faces(bpy.context, plate, report["subdividedFaces"])
R["readings"].update({"foldedPlusOne": report["folded"] + 1, "foldedPlusOneW1": even + 1})
check(f"plain-wall-folds: a hexagon plate 1.2 m across with a wall of 0.015 folds no inner face of its 168 (the count + 1 under {FOLDS}), and over that at even offset",
receipt["status"] == "accepted" and (report["cageVerts"], report["subdividedFaces"], report["poles"]) == (13, 168, {"6": 1}) and report["folded"] + 1 < FOLDS < even + 1, [receipt["message"], report, even])
for name in ("Strip", "Hexagon"):
mesh = bpy.data.objects[name].data
bpy.data.objects.remove(bpy.data.objects[name])
bpy.data.meshes.remove(mesh)
# --- the creases reach the surface -----------------------------------------------------------------------------------
section("free-cage-crisp")
crisp = sharpest(tent)

View file

@ -41,6 +41,16 @@
"ok": true,
"detail": null
},
{
"name": "plain-wall-no-needle: a plate 0.13 m wide with a wall of 0.04 stands under 1.77 thicknesses beyond its cage's bounds, and over that at even offset",
"ok": true,
"detail": null
},
{
"name": "plain-wall-folds: a hexagon plate 1.2 m across with a wall of 0.015 folds no inner face of its 168 (the count + 1 under 4.6), and over that at even offset",
"ok": true,
"detail": null
},
{
"name": "the creased ridge stays an edge under subdivision: over 34.0 degrees, and under it with crease_edge cleared",
"ok": true,
@ -144,6 +154,10 @@
"costSelf": 0.28,
"crispDegrees": 71.0,
"crispDegreesK1": 16.0,
"foldedPlusOne": 1.0,
"foldedPlusOneW1": 21.0,
"needleThicknesses": 0.95,
"needleThicknessesW1": 3.3,
"openRoundTripPct": 1.7e-05,
"openRoundTripPctB1": 7.7,
"scoreLiftedHausdorffPct": 3.3,

View file

@ -1,5 +1,5 @@
"""Live proof, in a background Blender, of brokkr_kitbash.shell through run_intent: a loft of rings becomes a cage whose
crease runs stay crisp under subdivision while the rest stays smooth, a wall of even thickness with a filled rim, a
crease runs stay crisp under subdivision while the rest stays smooth, a wall of plain offset with a filled rim, a
mirror, a rebuild in place under cutters and ribs, cut_many and ribs on the shell, and the refusals. Not part of the
unittest run: it needs Blender.
@ -78,18 +78,20 @@ SOFT = 12.0
# the surface keeps the cage's corner. Shipped 0 (read as 1e-7, what a float32 mesh is good to); least claimed mutant
# 0.15 (S5, boundary_smooth ALL: the corner rounds off); the geometric mean, separation 900 each side.
CORNER = 1.6e-4
# The wall's volume over the designed surface's area times the thickness, less 1, as a magnitude. Shipped 0.027 (a wall
# grown inward loses volume inside the crown's curve); least claimed mutant 0.036 (S6, the Solidify above the
# Subdivision: the wall's own edges are rounded off); the geometric mean, a total separation of 1.34.
SOLID = 0.0313
# The wall's volume over the designed surface's area times the thickness, less 1, as a magnitude. Shipped 0.028 (a wall
# grown inward loses volume inside the crown's curve, and a plain offset is thinner behind the creased shoulder); least
# claimed mutant 0.071 (S6, the Solidify above the Subdivision: the wall's own edges are rounded off); the geometric
# mean, separation 1.58 each side.
SOLID = 0.0447
# Metres between the thickness and the distance from a vertex of the wall's inner face to the designed surface. Shipped
# 0.0001 (a float32 mesh under three levels of subdivision); least claimed mutant 0.024 (S6: the inner face is subdivided again and pulls in); the geometric mean, separation 15 each side.
EVEN = 1.5e-3
# Metres: the thickness at which the wedge of shell-fold folds, (W / 2^levels) / tan(phi) of its narrower facet, as
# 0.0061 (a plain offset behind the creased shoulder: the wall is 0.0539 there, the thickness x cos(phi)); least claimed
# mutant 0.024 (S6: the inner face is subdivided again and pulls in); the geometric mean, separation 1.99 each side.
WALL_OFF = 0.0122
# Metres: the thickness at which the wedge of shell-fold folds, (W / 2^levels) / sin(phi) of its narrower facet, as
# measured on flat facets (docs/kitbash.md, Thickness at a crease). The wall is built at FOLD / FOLD_STEP (no inner
# face folded) and at FOLD x FOLD_STEP (some folded); FOLD_STEP is the 1.2 separation the margin rule asks on each
# side of the onset. The counts themselves are exact: count_folds is held to this script's own count, face for face.
FOLD, FOLD_STEP = 0.075, 1.2
FOLD, FOLD_STEP = 0.106, 1.2
def check(name, ok, detail=None):
@ -220,9 +222,9 @@ try:
report["thickness"], report["offset"], report["children"]) == ("Pauldron", False, 6, 6, 25, 25, 0, 1600, 3, 0.06, -1.0, [])
and report["facing"][2] > 0.5 and abs(np.linalg.norm(report["facing"]) - 1.0) < 1e-5, report)
smooth, wall = pauldron.modifiers.get("Kit Subsurf"), pauldron.modifiers.get("Kit Solidify")
check("the stack is Kit Subsurf, Kit Solidify, Kit Bevel: creases used, corners preserved, an even wall inward with its rim filled",
check("the stack is Kit Subsurf, Kit Solidify, Kit Bevel: creases used, corners preserved, a wall of plain offset inward with its rim filled",
stack(pauldron) == ["Kit Subsurf", "Kit Solidify", "Kit Bevel"] and (smooth.levels, smooth.render_levels, smooth.use_creases, smooth.boundary_smooth) == (3, 3, True, "PRESERVE_CORNERS")
and (wall.use_even_offset, wall.use_rim, wall.offset) == (True, True, -1.0) and abs(wall.thickness - WALL) < 1e-7 and abs(pauldron.modifiers["Kit Bevel"].width - 0.004) < 1e-7,
and (wall.use_even_offset, wall.use_rim, wall.offset) == (False, True, -1.0) and abs(wall.thickness - WALL) < 1e-7 and abs(pauldron.modifiers["Kit Bevel"].width - 0.004) < 1e-7,
stack(pauldron))
# W1 dies here: the mesh's edges are not in the order core.sheet lists its creases, so the weights must be looked up by pair
expected = {tuple(pair): round(weight, 6) for pair, weight in zip(built.creases.tolist(), built.weights.tolist())}
@ -256,7 +258,7 @@ try:
# --- shell-fold: count_folds, against this script's own count on the evaluated wall -------------------------------------------
section("shell-fold")
# a ridge of two flat facets 0.3 and 1.0 wide, each tilted 45 degrees, full crease, levels 2: the narrower facet binds, (0.3 / 4) / tan 45 = 0.075
# a ridge of two flat facets 0.3 and 1.0 wide, each tilted 45 degrees, full crease, levels 2: the narrower facet binds, (0.3 / 4) / sin 45 = 0.106
wedge = {"rings": [[[-1.0 * math.sqrt(0.5), y, -1.0 * math.sqrt(0.5)], [0.0, y, 0.0], [0.3 * math.sqrt(0.5), y, -0.3 * math.sqrt(0.5)]] for y in (0.0, 0.5, 1.0)],
"creases": [{"column": 1, "from": 0, "to": 2, "weight": 1.0}]}
@ -290,7 +292,7 @@ try:
seeded = {f"{loft['seed']} offset {loft['offset']:g}": folded(f"Loft{loft['seed']}", loft["sheet"], loft["thickness"], offset=loft["offset"], levels=loft["levels"], count_folds=True) for loft in lofts}
held = {f"{loft['seed']} offset {loft['offset']:g}": folded(f"Held{loft['seed']}", loft["sheet"], loft["holds"], offset=loft["offset"], levels=loft["levels"], count_folds=True) for loft in lofts if loft["holds"]}
R["folds"] = {"seeded": seeded, "held": held}
check("shell-fold: on seeded lofts whose walls fold under any figure of the cage, at offsets -1, 0 and 1, count_folds counts the faces this script counts, and none at a thickness the wall holds",
check("shell-fold: on seeded lofts, at offsets -1, 0 and 1, count_folds counts the faces this script counts at a thickness the wall folds at, and none at one it holds",
len(seeded) == 3 and all(told == own > 0 for told, own in seeded.values()) and held and all(pair == [0, 0] for pair in held.values()), [seeded, held])
for name in ["FoldUnder", "FoldOver", "FoldUnasked", "FoldOut"] + [f"{kind}{loft['seed']}" for loft in lofts for kind in ("Loft", "Held")]:
if name in bpy.data.objects:
@ -306,10 +308,10 @@ try:
inner = [v.co for v in whole.verts if all(outer.find_nearest(f.calc_center_median())[3] > WALL / 2 for f in v.link_faces)]
reading("solid", abs(whole.calc_volume(signed=True) / (area * WALL) - 1.0))
for co in inner:
reading("even", abs(outer.find_nearest(co)[3] - WALL))
check("shell-solid: the plate is a closed wall of even thickness behind the designed surface, its rim filled",
reading("wallOff", abs(outer.find_nearest(co)[3] - WALL))
check("shell-solid: the plate is a closed wall behind the designed surface, its thickness off it but for the creased shoulder's cosine, its rim filled",
sum(1 for e in whole.edges if not e.is_manifold) == 0 and whole.calc_volume(signed=True) > 0 and len(whole.faces) == 2 * 1600 + 4 * 40 and len(inner) > 0.9 * len(designed.verts)
and R["readings"]["solid"] < SOLID and R["readings"]["even"] < EVEN, [R["readings"], len(whole.faces), len(inner), len(designed.verts)])
and R["readings"]["solid"] < SOLID and R["readings"]["wallOff"] < WALL_OFF, [R["readings"], len(whole.faces), len(inner), len(designed.verts)])
whole.free()
# a mirrored breast sheet: symmetric as evaluated

View file

@ -12,7 +12,7 @@
"detail": null
},
{
"name": "the stack is Kit Subsurf, Kit Solidify, Kit Bevel: creases used, corners preserved, an even wall inward with its rim filled",
"name": "the stack is Kit Subsurf, Kit Solidify, Kit Bevel: creases used, corners preserved, a wall of plain offset inward with its rim filled",
"ok": true,
"detail": null
},
@ -47,12 +47,12 @@
"detail": null
},
{
"name": "shell-fold: on seeded lofts whose walls fold under any figure of the cage, at offsets -1, 0 and 1, count_folds counts the faces this script counts, and none at a thickness the wall holds",
"name": "shell-fold: on seeded lofts, at offsets -1, 0 and 1, count_folds counts the faces this script counts at a thickness the wall folds at, and none at one it holds",
"ok": true,
"detail": null
},
{
"name": "shell-solid: the plate is a closed wall of even thickness behind the designed surface, its rim filled",
"name": "shell-solid: the plate is a closed wall behind the designed surface, its thickness off it but for the creased shoulder's cosine, its rim filled",
"ok": true,
"detail": null
},
@ -176,32 +176,36 @@
"readings": {
"corner": 1.8e-07,
"crisp": 52.0,
"even": 0.0001,
"foldOver": 8.0,
"foldUnder": 0.0,
"ribsAcrossTheCrease": 1.0,
"soft": 5.8,
"solid": 0.027
"solid": 0.028,
"wallOff": 0.0061
},
"folds": {
"seeded": {
"5185 offset -1": [
2,
2
1,
1
],
"5101 offset 0": [
13,
13
9,
9
],
"5196 offset 1": [
4,
4
1,
1
]
},
"held": {
"5185 offset -1": [
0,
0
],
"5196 offset 1": [
0,
0
]
}
},

View file

@ -9,9 +9,12 @@ Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USE
without them). <out> is an absolute path; writes <out>.result.json and <out>.r3_<angle>.png (the bell crank at 0,
-62.5 and -125) and exits 1 when a check failed.
The oracle is ram.Signed, three rays by majority. Its ray count is held by tests/fixtures/ram_rays.json: the rocker
plates as Imagination's jointlib builds them and points between the plates that stand on the first ray short of an
edge or a vertex. One ray reads them inside a plate they stand clear of; the oracle as it is made reads none inside.
The oracle is ram.Signed: a point is inside a part where the winding number of the part's faces about it is 0.5 or
more. tests/fixtures/ram_plates.json holds the rocker plates as Imagination's jointlib builds them, four closed bars
joined into one mesh, a side's two overlapping, and 29 points inside them: none reads outside. Nor does a point where
two welded boxes overlap. A part that is open, wound inside out or crossing itself is refused when the oracle is made, a
hollow mass and a part mirrored by its matrix are read, and the depth is to the part's surface: a face buried in another of the
part's solids is not read, and outside the distance is to the nearest face of all.
A clearance verdict is a sign, the gate's own. FLAT follows lodur:ruling:deterministic-bound-margin. The checks run
inside one try: an uncaught error is a failed check that names its section, and the result file is always written.
@ -304,32 +307,116 @@ try:
# plates and none is inside; where the plate is under the point the reading is the 0.0225
ys, zs = np.meshgrid(np.linspace(0.1, 0.9, 96), np.linspace(0.1, 0.7, 72))
plane = np.stack([np.full(ys.size, X_C), ys.ravel(), zs.ravel()], axis=1)
three, one = Signed(shells)("rocker.plate", plane), Signed(shells, rays=1)("rocker.plate", plane)
off_plates = Signed(shells)("rocker.plate", plane)
def off(a, b): # each grid point's distance from the segment a -> b, across the axis
a, b = np.array(a), np.array(b)
t = np.clip(((plane[:, 1:] - a) @ (b - a)) / ((b - a) @ (b - a)), 0.0, 1.0)
return np.linalg.norm(plane[:, 1:] - a - t[:, None] * (b - a), axis=1)
under = (off(CRANK["rocker"], CRANK["p"]) < W_ROCKER - 0.005) | (off(CRANK["rocker"], CRANK["d"]) < W_ARM - 0.005)
RES["readings"]["FLAT"] = float(np.abs(three[under] - (SLAB_R[0] - X_C)).max())
RES["readings"]["one ray: samples signed inside, of %d" % len(plane)] = int((one < 0).sum())
check("three-rays: on a plane 0.0225 off the rocker plates no sample reads inside or nearer, and under a plate each reads the 0.0225",
(three >= SLAB_R[0] - X_C - FLAT).all() and under.sum() > 500 and RES["readings"]["FLAT"] < FLAT, [float(three.min()), int(under.sum()), RES["readings"]["FLAT"]])
# against shells whose inside is known in closed form: a box and a disc, random points, each ray's edges and vertices among them
RES["readings"]["FLAT"] = float(np.abs(off_plates[under] - (SLAB_R[0] - X_C)).max())
check("off-the-plates: on a plane 0.0225 off the rocker plates no sample reads inside or nearer, and under a plate each reads the 0.0225",
(off_plates >= SLAB_R[0] - X_C - FLAT).all() and under.sum() > 500 and RES["readings"]["FLAT"] < FLAT, [float(off_plates.min()), int(under.sum()), RES["readings"]["FLAT"]])
# against a shell whose inside is known in closed form: a box, random points
rng = np.random.default_rng(7)
cloud = rng.uniform((-0.2, -0.2, 0.2), (0.2, 0.2, 1.25), (4000, 3))
core = Signed({"core": [box((0, 0, 0.725), (0.26, 0.28, 0.85))]})("core", cloud)
exact = np.maximum.reduce([np.abs(cloud[:, 0]) - 0.13, np.abs(cloud[:, 1]) - 0.14, np.abs(cloud[:, 2] - 0.725) - 0.425])
check("three-rays: 4000 random points about a box are signed as the box signs them", ((core < 0) == (exact < 0)).all(), int(((core < 0) != (exact < 0)).sum()))
check("box: 4000 random points about a box are signed as the box signs them", ((core < 0) == (exact < 0)).all(), int(((core < 0) != (exact < 0)).sum()))
# the ray count: the jointlib rocker plates, and points between them aimed along the first ray at an edge or a vertex
fixture = json.loads((SURFACE / "tests" / "fixtures" / "ram_rays.json").read_text(encoding="utf-8"))
plates, aimed = {"plates": [(np.array(fixture["verts"]), fixture["faces"])]}, np.array(fixture["points"])
made, single = Signed(plates)("plates", aimed), Signed(plates, rays=1)("plates", aimed)
RES["readings"]["jointlib plates: points one ray signs inside, of %d" % len(aimed)] = int((single < 0).sum())
RES["readings"]["jointlib plates: points the oracle signs inside"] = int((made < 0).sum())
# one ray reads all 24 inside; the oracle as made reads none. The bound on one ray's count is the geometric mean of 1 and 24
check("ray-count: between the jointlib rocker plates, points on the first ray short of an edge or a vertex read outside by the oracle as it is made, inside by one ray",
(np.abs(aimed[:, 0]) < 0.349).all() and (made > 0).all() and (single < 0).sum() >= 5, [int((made < 0).sum()), int((single < 0).sum())])
# what the gate's proof between samples leans on: no point inside a part reads outside. The jointlib rocker plates
# are four closed bars in one mesh, a side's two overlapping about the pivot (crossing parity read the overlap
# outside); the fixture's 29 points are 0.001 or more inside a bar, 13 of them inside two. A count of points
fixture = json.loads((SURFACE / "tests" / "fixtures" / "ram_plates.json").read_text(encoding="utf-8"))
plates = Signed({"plates": [(np.array(fixture["verts"]), fixture["faces"])]})("plates", np.array(fixture["inside"]))
# two boxes cut through one another and welded at the corner they share
def wound(lo, hi):
verts = np.array([[x, y, z] for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])], float)
return verts, [(0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (2, 3, 7, 6), (0, 2, 6, 4), (1, 5, 7, 3)]
(v1, f1), (v2, f2) = wound((0, 0, 0), (1, 1, 1)), wound((0, 0, 0), (2, 0.5, 0.5))
welded = (np.concatenate([v1, v2[1:]]), f1 + [tuple(i + 7 if i else 0 for i in face) for face in f2])
cloud = rng.uniform(-0.2, 2.2, (6000, 3))
truth = ((cloud >= 0) & (cloud <= 1)).all(axis=1) | ((cloud >= 0) & (cloud <= (2, 0.5, 0.5))).all(axis=1)
both = ((cloud >= 0) & (cloud <= (1, 0.5, 0.5))).all(axis=1)
got = Signed({"welded": [welded]})("welded", cloud) < 0
RES["readings"]["jointlib plates: inside points read outside, of %d" % len(plates)] = int((plates >= 0).sum())
RES["readings"]["welded boxes: points missigned, of %d (%d in the overlap)" % (len(cloud), int(both.sum()))] = int((got != truth).sum())
check("inside-reads-inside: no point inside the jointlib rocker plates' bars or in two welded boxes' overlap reads outside, and none outside the boxes reads inside",
len(plates) == 29 and int((plates >= 0).sum()) == 0 and int(both.sum()) > 50 and int((got != truth).sum()) == 0,
[int((plates >= 0).sum()), int(both.sum()), int((got != truth).sum())])
# a part with no inside to sign is refused when the oracle is made, by its reason: a cube with its top off, or
# two adjacent faces off, is open; a cube turned over or mirrored with its winding kept, or a turned-over bar beside
# a whole cube, is a solid of negative volume and wound inside out; the bar welded to the cube along an edge (one
# solid, a positive volume in all) crosses itself, and is told where. What has an inside is read: a mirrored cube handed as its own mesh and its matrix, and a hollow mass, its cavity an inward shell
def one(*meshes):
at, faces = {}, []
for v, f in meshes:
index = [at.setdefault(tuple(float(x) for x in q), len(at)) for q in v]
faces += [tuple(index[i] for i in face) for face in f]
return np.array(list(at)), faces
turned = [face[::-1] for face in f1]
rail = wound((1, 0, -0.2), (1.2, 1, 0))
said = {}
for name, made in (("top off", [(v1, [face for face in f1 if face != (1, 5, 7, 3)])]), ("two faces off", [(v1, [face for face in f1 if face not in ((1, 5, 7, 3), (2, 3, 7, 6))])]),
("turned over", [(v1, turned)]), ("mirrored", [(v1 * (-1, 1, 1), f1)]), ("a turned-over bar beside a cube", [(v1, f1), (v2 + (0, 2, 0), [face[::-1] for face in f2])]),
("a turned-over bar welded to a cube", [one((v1, f1), (rail[0], [face[::-1] for face in rail[1]]))])):
try:
Signed({"cube": made})
said[name] = None
except R.RamError as error:
said[name] = str(error)
RES["refusals"] = said
want = {"top off": "is open: solid 0 of 1 has 4 edges", "two faces off": "is open: solid 0 of 1 has 6 edges", "turned over": "is wound inside out: solid 0 of 1 has a volume of -0.192 of the part's extent cubed, and 6 of its faces, from face 0, stand before a region that winds -1",
"mirrored": "is wound inside out: solid 0 of 1 has a volume of -0.192 of the part's extent cubed, and 6 of its faces, from face 0, stand before a region that winds -1",
"a turned-over bar beside a cube": "is wound inside out: solid 1 of 2 has a volume of -0.0133 of the part's extent cubed, and 6 of its faces, from face 6, stand before a region that winds -1",
"a turned-over bar welded to a cube": "crosses itself: 6 faces, from face 6 of solid 0 of 1, stand before a region that winds -1"}
check("no-inside-is-refused: an open part is refused by its solid and edge count, an inside-out one by its solid's negative volume, and a turned-over bar welded to a whole cube as crossing itself about (1.1, 0.5, -0.1), never as inside out",
len(one((v1, f1), rail)[0]) == 14 and all(said[name] is not None and "part 'cube' " + text in said[name] for name, text in want.items())
and "about (1.1, 0.5, -0.1) and within 0.5 of it" in said["a turned-over bar welded to a cube"] and "inside out" not in said["a turned-over bar welded to a cube"], said)
hollow = [wound((-1, -1, -1), (1, 1, 1)), (lambda v, f: (v, [face[::-1] for face in f]))(*wound((0.4, 0.4, 0.4), (0.6, 0.6, 0.6)))]
at = np.array([(0.5, 0.5, 0.5), (0.0, 0.0, 0.0), (0.5, 0.5, 0.95), (1.2, 0.0, 0.0)])
left = np.array([(-0.5, 0.5, 0.5), (0.5, 0.5, 0.5), (-0.5, 0.5, 0.9)])
cavity, mirrored = Signed({"p": hollow})("p", at), Signed({"p": [(v1, f1, np.diag((-1.0, 1.0, 1.0, 1.0)))]})("p", left)
RES["readings"]["hollow mass: in the cavity, in the wall by it, under the outer face, outside"] = cavity.tolist()
RES["readings"]["mirrored cube by its matrix: inside, across the mirror, under its top"] = mirrored.tolist()
check("an-inside-is-read: a cavity reads outside and the wall about it by its depth to the cavity; a cube mirrored by its matrix reads as the cube it is",
float(np.abs(cavity - (0.1, -0.4 * math.sqrt(3.0), -0.05, 0.2)).max()) < FLAT and float(np.abs(mirrored - (-0.5, 0.5, -0.1)).max()) < FLAT, [cavity.tolist(), mirrored.tolist()])
# the exposed faces, where a reading turns on them. Outside, the distance is to the nearest face of all: a slab
# with a boss through its middle has its two great faces left out (their centroids are in the boss), and points
# off them read 0.05 and 0.02, not the 0.206 and 0.4 to the nearest exposed face. Two plates stacked 1e-5 of the
# extent apart are two surfaces: under the lower one's top the depth is 0.02, where a nudge of 1e-4 reads that
# face buried in the upper plate and the depth 0.08 to the bottom. A cube turned 0.3, 0.5 and 0.7 radians about
# x, y and z has no face along an axis: its six sides are held at 1e-6 and to 1e-8 (the corners' offsets are
# single precision), and at 1e-9 four read buried
slab = [wound((-1, -1, -0.1), (1, 1, 0.1)), wound((-0.2, -0.2, -0.5), (0.2, 0.2, 0.5))]
off = Signed({"p": slab})("p", np.array([(0.8, 0.0, 0.15), (0.6, 0.6, 0.12), (0.0, 0.0, 0.7), (0.5, 0.0, -0.3)]))
gap = 1e-5 * math.sqrt(2.0 + 0.2 ** 2)
stacked = Signed({"p": [wound((0, 0, 0), (1, 1, 0.1)), wound((0, 0, 0.1 + gap), (1, 1, 0.2 + gap))]})("p", np.array([(0.5, 0.5, 0.08), (0.5, 0.5, 0.12 + gap), (0.5, 0.5, 0.1 + 0.5 * gap)]))
(ca, sa), (cb, sb), (cc, sc) = ((math.cos(t), math.sin(t)) for t in (0.3, 0.5, 0.7))
spin = np.array([[1, 0, 0], [0, ca, -sa], [0, sa, ca]]) @ np.array([[cb, 0, sb], [0, 1, 0], [-sb, 0, cb]]) @ np.array([[cc, -sc, 0], [sc, cc, 0], [0, 0, 1]])
under = 0.9 * np.array([(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)], float)
spun = Signed({"p": [(cube_v @ spin.T, cube_f) for cube_v, cube_f in [wound((-1, -1, -1), (1, 1, 1))]]})("p", under @ spin.T)
RES["readings"]["slab with a boss through it: off its faces (0.05, 0.02), off the boss's end (0.2), under it (0.2)"] = off.tolist()
RES["readings"]["plates stacked 1e-5 of the extent apart: under the lower's top (0.02), over the upper's bottom (0.02), between them"] = stacked.tolist()
RES["readings"]["a turned cube: 0.1 under each face"] = spun.tolist()
check("exposed-faces-are-read-where-they-are: outside is to the nearest face of all, plates 1e-5 of the extent apart are two surfaces, and a turned cube's six faces are all its surface",
float(np.abs(off - (0.05, 0.02, 0.2, 0.2)).max()) < FLAT and float(np.abs(stacked - (-0.02, -0.02, 0.5 * gap)).max()) < FLAT and float(np.abs(spun + 0.1).max()) < FLAT, [off.tolist(), stacked.tolist(), spun.tolist()])
# the depth is to the part's surface, not to a face buried in another of its solids: a cube of half side 1 with a
# box of side 0.2 buried about (0.5, 0.5, 0.5) reads its own depth by the box and at its centre (the nearest face
# of all is the buried box's: 0.05 and 0.693). A boss through a wall is read, not checked: its side faces cross the
# wall and are kept whole by their centroids, so in the wall by the boss the depth reads to their buried stretch
cube, small = wound((-1, -1, -1), (1, 1, 1)), wound((0.4, 0.4, 0.4), (0.6, 0.6, 0.6))
boss = wound((0.9, -0.5, -0.5), (1.5, 0.5, 0.5))
at = np.array([(0.5, 0.5, 0.55), (0.0, 0.0, 0.0), (0.5, 0.5, 0.95), (0.5, 0.5, 0.5), (1.2, 0.0, 0.0)])
alone, buried, bossed = Signed({"p": [cube]})("p", at), Signed({"p": [cube, small]})("p", at), Signed({"p": [cube, boss]})("p", np.array([(0.95, 0.0, 0.0), (0.7, 0.0, 0.0), (1.2, 0.0, 0.0), (1.6, 0.0, 0.0)]))
RES["readings"]["buried box: depth by it, at the cube's centre, under the cube's face, at the box's centre; outside"] = buried.tolist()
RES["readings"]["boss through a wall (faces that cross a solid are kept or left whole): in both (the surface is 0.502 off), in the wall (0.583), in the boss (0.2), off it (0.1)"] = bossed.tolist()
check("depth-is-to-the-surface: a face buried in another solid of the part is not read: by a buried box the cube reads as the cube alone",
float(np.abs(buried - (-0.45, -1.0, -0.05, -0.5, 0.2)).max()) < FLAT and float(np.abs(buried - alone).max()) < FLAT,
[buried.tolist(), alone.tolist()])
SECTION[0] = "seat"
seat = np.concatenate([v for v, _ in shells["parent.seat"]])

View file

@ -7,17 +7,37 @@
"detail": null
},
{
"name": "three-rays: on a plane 0.0225 off the rocker plates no sample reads inside or nearer, and under a plate each reads the 0.0225",
"name": "off-the-plates: on a plane 0.0225 off the rocker plates no sample reads inside or nearer, and under a plate each reads the 0.0225",
"ok": true,
"detail": null
},
{
"name": "three-rays: 4000 random points about a box are signed as the box signs them",
"name": "box: 4000 random points about a box are signed as the box signs them",
"ok": true,
"detail": null
},
{
"name": "ray-count: between the jointlib rocker plates, points on the first ray short of an edge or a vertex read outside by the oracle as it is made, inside by one ray",
"name": "inside-reads-inside: no point inside the jointlib rocker plates' bars or in two welded boxes' overlap reads outside, and none outside the boxes reads inside",
"ok": true,
"detail": null
},
{
"name": "no-inside-is-refused: an open part is refused by its solid and edge count, an inside-out one by its solid's negative volume, and a turned-over bar welded to a whole cube as crossing itself about (1.1, 0.5, -0.1), never as inside out",
"ok": true,
"detail": null
},
{
"name": "an-inside-is-read: a cavity reads outside and the wall about it by its depth to the cavity; a cube mirrored by its matrix reads as the cube it is",
"ok": true,
"detail": null
},
{
"name": "exposed-faces-are-read-where-they-are: outside is to the nearest face of all, plates 1e-5 of the extent apart are two surfaces, and a turned cube's six faces are all its surface",
"ok": true,
"detail": null
},
{
"name": "depth-is-to-the-surface: a face buried in another solid of the part is not read: by a buried box the cube reads as the cube alone",
"ok": true,
"detail": null
},
@ -104,25 +124,75 @@
],
"readings": {
"FLAT": 8.34e-09,
"a turned cube: 0.1 under each face": [
-0.09999994188547134,
-0.09999997913837433,
-0.09999998658895493,
-0.09999998658895493,
-0.10000001639127731,
-0.10000001639127731
],
"bell crank: least margin of a pair with no zone, 251 steps uncapped": 0.0336,
"bell crank: least margin of a zoned pair, 251 steps uncapped": 0.000118,
"bell crank: pairs": 60,
"bell crank: pairs refused with nothing let": 19,
"bell crank: seconds, 49 steps capped": 2.12,
"bell crank: seconds, 49 steps capped": 1.87,
"bell crank: zoned pairs": 20,
"boss through a wall (faces that cross a solid are kept or left whole): in both (the surface is 0.502 off), in the wall (0.583), in the boss (0.2), off it (0.1)": [
-0.5,
-0.5385164618492126,
-0.2999999523162842,
0.10000002384185791
],
"buried box: depth by it, at the cube's centre, under the cube's face, at the box's centre; outside": [
-0.44999998807907104,
-1.0,
-0.050000011920928955,
-0.5,
0.20000004768371582
],
"four bar: barrel inside the shin's clearance": -0.122,
"jointlib plates: points one ray signs inside, of 24": 24,
"jointlib plates: points the oracle signs inside": 0,
"hollow mass: in the cavity, in the wall by it, under the outer face, outside": [
0.09999999403953552,
-0.6928203105926514,
-0.050000011920928955,
0.20000004768371582
],
"jointlib plates: inside points read outside, of 29": 0,
"mirrored cube by its matrix: inside, across the mirror, under its top": [
-0.5,
0.5,
-0.10000002384185791
],
"moved x: both": -0.0543,
"moved x: the coupler at x 0.25, inside the horn's 0.23..0.31": -0.02,
"moved x: the rocker at x 0.25, inside the bracket's 0.13..0.35": -0.0543,
"one ray: samples signed inside, of 6912": 0,
"plates stacked 1e-5 of the extent apart: under the lower's top (0.02), over the upper's bottom (0.02), between them": [
-0.020000003278255463,
-0.019999995827674866,
7.137656211853027e-06
],
"search: candidates": 13824,
"search: pass the gates before clearance": 78,
"search: refused on their own parts": 21,
"search: seconds": 43.3,
"search: seconds": 45.2,
"search: worlds built": 22,
"the base clevis's foot inside the thigh": -0.01
"slab with a boss through it: off its faces (0.05, 0.02), off the boss's end (0.2), under it (0.2)": [
0.05000000447034836,
0.019999995827674866,
0.19999998807907104,
0.20000001788139343
],
"the base clevis's foot inside the thigh": -0.01,
"welded boxes: points missigned, of 6000 (91 in the overlap)": 0
},
"refusals": {
"top off": "mesh ram: signed: part 'cube' is open: solid 0 of 1 has 4 edges no face runs the other way",
"two faces off": "mesh ram: signed: part 'cube' is open: solid 0 of 1 has 6 edges no face runs the other way",
"turned over": "mesh ram: signed: part 'cube' is wound inside out: solid 0 of 1 has a volume of -0.192 of the part's extent cubed, and 6 of its faces, from face 0, stand before a region that winds -1.01",
"mirrored": "mesh ram: signed: part 'cube' is wound inside out: solid 0 of 1 has a volume of -0.192 of the part's extent cubed, and 6 of its faces, from face 0, stand before a region that winds -1.01",
"a turned-over bar beside a cube": "mesh ram: signed: part 'cube' is wound inside out: solid 1 of 2 has a volume of -0.0133 of the part's extent cubed, and 6 of its faces, from face 6, stand before a region that winds -1",
"a turned-over bar welded to a cube": "mesh ram: signed: part 'cube' crosses itself: 6 faces, from face 6 of solid 0 of 1, stand before a region that winds -1 and holds 0.0271 of the part's extent cubed, about (1.1, 0.5, -0.1) and within 0.5 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"
},
"zones": {
"barrel[0] | parent.seat": {
@ -496,9 +566,9 @@
}
},
"renders": [
"F:/aeth-wt/fable-ramcore/scratch/h4/out/live_h4.r3_0.png",
"F:/aeth-wt/fable-ramcore/scratch/h4/out/live_h4.r3_62p5.png",
"F:/aeth-wt/fable-ramcore/scratch/h4/out/live_h4.r3_125.png"
"F:/aeth-wt/hands-ramlows6-scratch/out/live/knee.r3_0.png",
"F:/aeth-wt/hands-ramlows6-scratch/out/live/knee.r3_62p5.png",
"F:/aeth-wt/hands-ramlows6-scratch/out/live/knee.r3_125.png"
],
"ok": true
}

View file

@ -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
@ -83,6 +84,40 @@ def yz(p, x=0.0):
return (x, float(p[0]), float(p[1]))
def block(lo, hi):
"""A box as a mesh: 8 vertices and 12 triangles wound counterclockwise seen from outside."""
lo, hi = np.asarray(lo, float), np.asarray(hi, float)
verts = np.array([[x, y, z] for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])])
quads = ((0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (2, 3, 7, 6), (0, 2, 6, 4), (1, 5, 7, 3))
return verts, np.array([t for a, b, c, d in quads for t in ((a, b, c), (a, c, d))])
def joined(first, second, weld):
"""Two meshes as one; with `weld`, vertices of the second that stand on one of the first take its index."""
(v1, t1), (v2, t2) = first, second
verts, index = [tuple(p) for p in v1], []
for p in map(tuple, v2):
if weld and p in verts:
index.append(verts.index(p))
else:
index.append(len(verts))
verts.append(p)
return np.array(verts), np.concatenate([t1, np.array(index)[t2]])
def staircase():
"""A prism of three steps along y from 0 to 1: under z = 1 for x in 0..1, z = 2 for 1..2, z = 3 for 2..3."""
profile = ((0, 0), (3, 0), (3, 3), (2, 3), (2, 2), (1, 2), (1, 1), (0, 1)) # (x, z)
verts = np.array([(x, y, z) for y in (0.0, 1.0) for x, z in profile], float)
tris = []
for k in range(8):
n = (k + 1) % 8
tris += [(k, n + 8, n), (k, k + 8, n + 8)]
for a, b, c in ((0, 1, 6), (0, 6, 7), (1, 4, 5), (1, 5, 6), (1, 2, 3), (1, 3, 4)): # the cap at y = 0, and at y = 1 turned over
tris += [(a, b, c), (a + 8, c + 8, b + 8)]
return verts, np.array(tris)
def grid(lo, hi, counts):
lo, hi = np.asarray(lo, float), np.asarray(hi, float)
axes = [np.linspace(lo[k], hi[k], n) if n > 1 else np.array([(lo[k] + hi[k]) / 2]) for k, n in enumerate(counts)]
@ -499,6 +534,21 @@ SWING_BOUND = 0.81
TOGGLE_ARM = 0.0386
# The clearance gate's zones on the R-3 bell crank. A reading a hand value states is bounded by its deviation from it;
# a shipped deviation of 0 counts as half an ulp of the value (lodur:ruling:deterministic-bound-zero-reading).
ZONED = 2.2e-10 # a rocker sample against its own plates: shipped 0 (half an ulp of link_r, 1.7e-18), W1..W3 (a zone's edge strict, the first zone only, the last zone overriding) 0.0294 and 0.0914 off, separation 1.3e8 each side
BESIDE = 1.2e-10 # a wall 0.02 beside the coupler, read at the nearest sample: shipped 0 (half an ulp of 0.0242, 1.7e-18), B1 (the proof by the nearer end's reading less the span, which halves and reads beside the wall) 0.00423 off, separation 4.9e7 each side
FLOOR_UNDER = 0.319 # how near the axis a wall held outside reads as touched, in spacing / 64: shipped under 0.451, FINE 128 under 0.2255, separation 1.41 each side
FLOOR_OVER = 0.638 # shipped under 0.451, FINE 32 under 0.902, separation 1.41 each side
WHOLE = 3.8e-4 # a winding number against the count or share a hand value states: shipped 6.3e-6 at most (the plates; the angles are single precision), W1 (the denominator's a.b term without the third length) 0.0224 off on the open cube's axis, separation 60 each side
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.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
@unittest.skipIf(np is None, "numpy is not installed")
class DeepKnee(unittest.TestCase):
"""The R-3 knee over 0..-125 (probes P1 to P3)."""
@ -562,8 +612,9 @@ class DeepKnee(unittest.TestCase):
def test_a_part_in_the_rams_way_on_each_link(self):
# a lug on the rocker, then on the coupler, on the rod's axis 0.12 from the eye at -60: refused naming the part
# and its body. A zone about the eye lets the rod and the barrel by it only if it reaches the lug and is as
# deep as the lug; a zone of another member's changes nothing
# and its body. A zone about the eye lets the rod and the barrel by the rocker's only if it reaches the lug and
# is as deep as the lug; a zone of another member's changes nothing. The coupler's lug is let by no zone of
# the ram's: the eye's pin does not join the coupler
m, ram = r3("bell_crank", CRANK), R.Ram(BORE)
at = R.pose(m, -60.0)
on_rod = (at.eye - 0.12 * at.u)[:, None, :]
@ -574,13 +625,20 @@ class DeepKnee(unittest.TestCase):
def zones(radius, depth, members=("rod", "barrel")):
return {**touch, **{member: touch[member] + [("lug", "d" if member != "coupler" else "p", radius, depth)] for member in members}}
for label, given in (("nothing let", touch), ("the coupler's zone", zones(0.4, 0.02, ("coupler",))), ("a zone short of the lug", zones(0.1, 0.02)),
("a zone too shallow", zones(0.4, 0.01))):
if body == "coupler": # d joins the rocker alone: no zone of the ram's names a part of the coupler
with self.assertRaises(R.RamError) as caught:
dressed(m, bodies, zones(0.4, 0.02))
self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", "barrel lug pin"))
self.assertIn("a body the pin joins (rocker); 'lug' turns with coupler", str(caught.exception))
for label, given in (("nothing let", touch), ("the coupler's zone", zones(0.4, 0.02, ("coupler",))),
*((("a zone short of the lug", zones(0.1, 0.02)), ("a zone too shallow", zones(0.4, 0.01))) if body == "rocker" else ())):
with self.assertRaises(R.RamError) as caught:
R.fit(dressed(m, bodies, given), ram, steps=49, distance=bodies)
self.assertEqual((caught.exception.gate, caught.exception.fit.clear_at[2]), ("clash", "lug"), (body, label))
self.assertIn(caught.exception.fit.clear_at[1], ("rod[0]", "barrel[0]"))
self.assertIn(f"part 'lug' ({body})", str(caught.exception))
if body == "coupler":
continue
f = R.fit(dressed(m, bodies, zones(0.4, 0.02)), ram, steps=49, distance=bodies)
self.assertIn(("rod[0]", "lug"), f.allowed)
self.assertNotIn(("rocker arm", "lug"), f.allowed)
@ -645,16 +703,26 @@ class DeepKnee(unittest.TestCase):
self.assertAlmostEqual(R._span(m, "rocker arm"), 0.24, places=9)
self.assertGreaterEqual(R._span(m, "rod"), float(R.pose(m, np.linspace(-125.0, 0.0, 126)).L.max()))
self.assertEqual([ram.eye(*of) for of in (("barrel", "a"), ("rod", "a"), ("rod", "d"), ("coupler", "c"))], [ram.e_a, ram.e_a, ram.e_b, ram.link_r])
for member, pin in (("barrel", "a"), ("rod", "d"), ("rocker", "p"), ("coupler", "c"), ("rocker arm", "rocker")):
# a linkage's ram spans from the rocker's pivot, which its eye turns about, not the knee's: a base seated 0.1
# from the rocker's pivot makes a ram of 0.539 at the most, and a zone between that and the 1.335 the knee's
# pivot would give is refused
seated = replace(m, a=m.rocker + (0.0, 0.0, 0.1), parts=bodies.parts)
self.assertAlmostEqual(R._span(seated, "rod"), 0.1 + math.hypot(X_ROCKER, 0.24), places=12)
for member in ("barrel", "rod"):
replace(seated, touch={member: [("thigh", "a", 0.53, 0.0)]})
with self.assertRaises(R.RamError) as caught:
replace(seated, touch={member: [("thigh", "a", SPAN_RAM, 0.0)]})
self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", f"{member} thigh radius"))
for member, pin, part in (("barrel", "a", "thigh"), ("rod", "d", "pin d"), ("rocker", "p", "coupler plates"), ("coupler", "c", "horn"), ("rocker arm", "rocker", "bracket")):
span, eye = R._span(m, member), ram.eye(member, pin)
def zoned(radius, depth):
return dressed(m, bodies, {member: [("thigh", pin, radius, depth)]})
return dressed(m, bodies, {member: [(part, pin, radius, depth)]})
zoned(span, 0.0)
for radius, depth, field in ((1.2 * span, 0.0, "radius"), (1e308, 0.0, "radius"), (1e9, 1e9, "radius"), (0.1, 1.2 * span, "depth"), (0.1, 1e308, "depth")):
with self.assertRaises(R.RamError) as caught:
zoned(radius, depth)
self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", f"{member} thigh {field}"))
self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", f"{member} {part} {field}"))
self.assertIn(f"{member} is at most {span:.4f} from pin to pin", str(caught.exception))
R.clearance(zoned(0.1, eye), ram, [-60.0], bodies)
wrote = R.record(zoned(0.1, eye), ram)
@ -664,19 +732,66 @@ class DeepKnee(unittest.TestCase):
lambda: R.from_record(wrote)):
with self.assertRaises(R.RamError) as caught:
read()
self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", f"{member} thigh depth"))
self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", f"{member} {part} depth"))
self.assertIn(f"{member}'s on {pin} is {eye:.4f}", str(caught.exception))
def test_a_zone_names_a_part_of_a_body_its_pin_joins(self):
# Soul's whole-member zones: two of 0.51 of its length about p and c covered the coupler and let its axis
# 0.0294 into a capsule of the thigh. No bound on a radius stops that; the record says which bodies a pin
# joins, and a part of any other is zoned about it by no member, whatever the radius and depth
joins = {"a": ("parent",), "b": ("child",), "rocker": ("parent", "rocker"), "p": ("rocker", "coupler"), "c": ("coupler", "child"), "d": ("rocker",)}
for m in (R.Mechanism("direct", O, X, -62, 0, a=(0.05, -0.3, 0.8), b=(0.05, -0.3, -0.6)), r3("four_bar", DEEP), r3("bell_crank", CRANK)):
parts = {"of " + body: body for body in R.BODIES[m.kind]}
for member in R.MEMBERS[m.kind]:
for pin in R.RIDES[m.kind][member]:
for part, body in parts.items():
zone = {member: [(part, pin, 0.01, 0.0)]}
if body in joins[pin]:
self.assertEqual(replace(m, parts=parts, touch=zone).touch[member], ((part, pin, 0.01, 0.0),))
continue
with self.assertRaises(R.RamError) as caught:
replace(m, parts=parts, touch=zone)
self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", f"{member} {part} pin"), (m.kind, member, pin, body))
self.assertIn(f"{member} may touch about {pin} a part of a body the pin joins ({', '.join(joins[pin])}); "
f"'{part}' turns with {body}", str(caught.exception))
# Soul's capsule of the parent under the coupler, zoned as the probe zoned it: refused by the record, by
# from_record and as a world's answer; the shipped zones, each a part of a body its pin joins, are read
m, ram = r3("bell_crank", CRANK), R.Ram(BORE)
bodies, touch = r3_bodies(m, ram)
wire = json.loads(json.dumps(R.record(dressed(m, bodies, touch), ram)))
self.assertEqual(R.from_record(wire)[0].touch, dressed(m, bodies, touch).touch)
bodies.parts["under"], bodies.shapes["under"] = "parent", [("capsule", (X_COUPLER, 0.5, 0.2), (X_COUPLER, 0.6, 0.3), 0.08)]
halves = [("under", "p", 0.51 * m.lc, ram.link_r), ("under", "c", 0.51 * m.lc, ram.link_r)]
wire["parts"]["under"] = "parent"
for k, zone in enumerate(halves):
given = {**touch, "coupler": touch["coupler"] + halves[k:]}
wrote = {**wire, "touch": {**wire["touch"], "coupler": wire["touch"]["coupler"] + [dict(zip(R.ZONE, zone))]}}
hinge, seat = {"pivot": O, "axis": X, "lo": -125, "hi": 0}, {name: [getattr(m, name)] for name in ("a", "rocker", "c")}
for read in (lambda: dressed(m, bodies, given), lambda: R.from_record(wrote),
lambda: R.search("bell_crank", hinge, ram, {**seat, "link": (m.lr, m.lr, 1), "d": (0.24, 0.24, 1)}, world=lambda made: (bodies.parts, given, bodies))):
with self.assertRaises(R.RamError) as caught:
read()
self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", "coupler under pin"))
self.assertIn(f"about {zone[1]} a part of a body the pin joins", str(caught.exception))
# the body is refused before the zone is measured: a zone both foreign and wider than its member names the pin
with self.assertRaises(R.RamError) as caught:
dressed(m, bodies, {"coupler": [("under", "p", 1e9, 0.0)]})
self.assertEqual(caught.exception.pin, "coupler under pin")
def test_a_wall_the_axis_crosses_in_a_zone_is_read_whatever_its_thickness(self):
# Soul's tunnel: a wall of the thigh across the coupler, midway between two of its samples, inside a zone
# about p of depth 0. Every sample stands outside it; the segment between them is what crosses
# Soul's tunnel: a wall of the rocker across the coupler, midway between two of its samples, inside a zone
# about p of depth 0. Every sample stands outside it; the segment between them is what crosses. The wall is
# the rocker's, which p joins, and stands in the rocker's frame, where the coupler's samples at -60 are `samples`
m, ram = r3("bell_crank", CRANK), R.Ram(BORE)
at = R.pose(m, -60.0)
start = at.P[0] - np.array(X) * ((at.P[0] - at.C[0]) @ np.array(X))
count = int(math.ceil(m.lc / ram.spacing())) + 1
samples = start + (at.C[0] - start) * np.linspace(0.0, 1.0, count)[:, None]
def seen(n, body="rocker"):
return R._into(m, at, body, (start + (at.C[0] - start) * np.linspace(0.0, 1.0, n)[:, None])[None])[0]
samples = seen(count)
spot = 0.5 * (samples[2] + samples[3])
along = (at.C[0] - start) / m.lc
along = (samples[-1] - samples[0]) / m.lc
k = 1 if abs(along[1]) > abs(along[2]) else 2
def reading(half, shift=0.0):
@ -684,26 +799,41 @@ class DeepKnee(unittest.TestCase):
lo[k], hi[k] = spot[k] - half, spot[k] + half
lo[0], hi[0] = X_COUPLER - 0.05 + shift, X_COUPLER + 0.05 + shift
bodies = r3_parts(m, ram)
bodies.parts["wall"], bodies.shapes["wall"] = "parent", [("box", lo, hi)]
self.assertGreater(float(bodies("wall", samples).min()), 0.0)
bodies.parts["wall"], bodies.shapes["wall"] = "rocker", [("box", lo, hi)]
reading.sampled = float(bodies("wall", samples).min())
self.assertGreater(reading.sampled, 0.0)
return R.clearance(dressed(m, bodies, {"coupler": [("wall", "p", 0.28, 0.0)]}), ram, [-60.0], bodies).pairs[("coupler", "wall")][0]
for half in (0.01, 0.003, 1e-4, 1e-7, 1e-10):
self.assertLess(reading(half), 0.0, half)
# the same walls beside the axis, 0.02 off along the hinge axis: held outside, and let
# the same walls beside the axis, 0.02 off along the hinge axis: held outside, and let. The samples either
# side prove the segment, so the reading is the nearer sample's (0.0242: 0.02 across, 0.0137 along), not the
# 0.02 a point between them would read
for half in (0.01, 1e-7):
self.assertGreaterEqual(reading(half, 0.07), 0.02)
# nearer the axis than the floor of the halving, a part the axis is held outside reads as touched
self.assertLess(reading(0.01, 0.05 + 0.2 * ram.spacing() / R.FINE), 0.0)
self.assertGreaterEqual(reading(0.01, 0.05 + 1.2 * ram.spacing() / R.FINE), 0.0)
self.assertLess(abs(reading(half, 0.07) - reading.sampled), BESIDE, half)
self.assertGreater(reading.sampled, 0.024)
# nearer the axis than the floor of the halving, a part the axis is held outside reads as touched. The floor is
# the spacing over 64, written here as the number: the doc's, and what the gate's cost was measured at
self.assertEqual(R.FINE, 64)
self.assertLess(reading(0.01, 0.05 + FLOOR_UNDER * ram.spacing() / 64), 0.0)
self.assertGreaterEqual(reading(0.01, 0.05 + FLOOR_OVER * ram.spacing() / 64), 0.0)
# a segment with one end in the zone is proved as well. Sampled 0.3 apart, the sample beyond the zone keeps its
# 0.186 from a bead on the axis 0.008 past the last sample in the zone; the bead is read all the same
wide = start + (at.C[0] - start) * np.linspace(0.0, 1.0, 3)[:, None]
wide = seen(3)
bodies, spot = r3_parts(m, ram), wide[1] + 0.012 * along
bodies.parts["bead"], bodies.shapes["bead"] = "parent", [("capsule", spot, spot, 0.004)]
bodies.parts["bead"], bodies.shapes["bead"] = "rocker", [("capsule", spot, spot, 0.004)]
self.assertGreater(float(bodies("bead", wide[:2]).min()), 0.0)
self.assertGreaterEqual(float(bodies("bead", wide[2:])[0]), near(ram, "coupler", 0.3))
got = R.clearance(dressed(m, bodies, {"coupler": [("bead", "p", 0.25, 0.0)]}), ram, [-60.0], bodies, spacing=0.3)
self.assertLess(got.pairs[("coupler", "bead")][0], 0.0)
# and so is the segment whose far end alone is in the zone: a bead of the shin 0.008 short of the first sample
# in a zone about c, the sample before it out of the zone and keeping its 0.186
wide = seen(3, "child")
bodies, spot = r3_parts(m, ram), wide[1] - 0.012 * (wide[2] - wide[0]) / m.lc
bodies.parts["bead"], bodies.shapes["bead"] = "child", [("capsule", spot, spot, 0.004)]
self.assertGreater(float(bodies("bead", wide[1:]).min()), 0.0)
self.assertGreaterEqual(float(bodies("bead", wide[:1])[0]), near(ram, "coupler", 0.3))
got = R.clearance(dressed(m, bodies, {"coupler": [("bead", "c", 0.25, 0.0)]}), ram, [-60.0], bodies, spacing=0.3)
self.assertLess(got.pairs[("coupler", "bead")][0], 0.0)
def test_two_zones_of_one_pair_and_a_sample_at_a_zones_radius(self):
# Soul's W1..W3. A pair zoned twice: a sample both reach is let the deeper, in either order, and each zone
@ -718,8 +848,11 @@ class DeepKnee(unittest.TestCase):
self.assertAlmostEqual(reading(deep, beside, far), 0.0, places=12)
self.assertAlmostEqual(reading(beside, deep, far), 0.0, places=12)
self.assertAlmostEqual(reading(far, beside, deep), 0.0, places=12)
for short in ((beside, beside, far), (deep, beside), (far, deep[:2] + (0.3 * m.lr, ram.link_r))):
self.assertLess(reading(*short), -0.9 * ram.link_r, short)
# short of that the sample reads what it is: link_r inside its own plate where the zone holds it outside, and
# where no zone reaches it link_r inside and all it keeps short
own = ram.link_r + near(ram, "rocker")
for short, reads in (((beside, beside, far), -ram.link_r), ((deep, beside), -own), ((far, deep[:2] + (0.3 * m.lr, ram.link_r)), -own)):
self.assertLess(abs(reading(*short) - reads), ZONED, short)
at = R.pose(m, [-60.0])
end = at.P - np.array(X) * ((at.P - m.rocker) @ np.array(X))[:, None]
count = int(math.ceil(m.lr / ram.spacing())) + 1
@ -727,7 +860,7 @@ class DeepKnee(unittest.TestCase):
across = np.linalg.norm(R._flat(pts - m.rocker, np.array(X)), axis=2)[0]
edge, beyond = float(across[3]), m.lr - 0.5 * float(across[3] + across[4])
self.assertAlmostEqual(reading(("rocker plates", "rocker", edge, ram.link_r), ("rocker plates", "p", beyond, ram.link_r), degrees=[-60.0]), 0.0, places=12)
self.assertLess(reading(("rocker plates", "rocker", float(np.nextafter(edge, 0.0)), ram.link_r), ("rocker plates", "p", beyond, ram.link_r), degrees=[-60.0]), -0.9 * ram.link_r)
self.assertLess(abs(reading(("rocker plates", "rocker", float(np.nextafter(edge, 0.0)), ram.link_r), ("rocker plates", "p", beyond, ram.link_r), degrees=[-60.0]) + own), ZONED)
def test_a_pin_stood_inside_what_it_stands_beside_is_refused(self):
# Soul's moved-x probes: the rocker's x moved from its plate's place (0.3675) into the bracket's 0.13..0.35,
@ -843,8 +976,13 @@ class OracleRule(unittest.TestCase):
lugged = two(a=seats.shapes["a"] and ("parent", seats.shapes["a"]), b=("child", seats.shapes["b"]), **{"b.lug": ("child", seats.shapes["b"])})
got = R.clearance(dressed(m, lugged, zones), ram, 0.0, lugged)
self.assertEqual({pair: round(reading[0], 9) for pair, reading in got.pairs.items() if reading[0] < 0.0}, {("rod[0]", "b.lug"): round(-0.03 - near(ram, "rod"), 9)})
for crossed in ({"barrel": [("b", "b", 0.2, 0.03)], "rod": [("a", "a", 0.2, 0.03)]}, {"barrel": [("a", "b", 0.2, 0.03)], "rod": [("b", "a", 0.2, 0.03)]}):
self.assertLess(float(R.clearance(dressed(m, seats, crossed), ram, 0.0, seats).margin[0]), 0.0)
crossed = {"barrel": [("b", "b", 0.2, 0.03)], "rod": [("a", "a", 0.2, 0.03)]}
self.assertLess(float(R.clearance(dressed(m, seats, crossed), ram, 0.0, seats).margin[0]), 0.0)
# and a part zoned about the pin at the member's other end, which does not join its body, is no zone at all
for crossed, pin in (({"barrel": [("a", "b", 0.2, 0.03)]}, "barrel a pin"), ({"rod": [("b", "a", 0.2, 0.03)]}, "rod b pin")):
with self.assertRaises(R.RamError) as caught:
dressed(m, seats, crossed)
self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", pin))
def test_every_body_owns_a_part(self):
ball = Bodies({"ball": ("parent", [("capsule", (0, 0, 0), (0, 0, 0), 0.1)])})
@ -942,19 +1080,20 @@ class SearchBestFirst(unittest.TestCase):
((ball.parts, {}, None), "search", "world(m) returns"), ((ball.parts, {"rod": ["parent"]}, ball), "record", "zone is (part, pin, radius, depth)"),
((ball.parts, {"rod": [("parent", "c", 1.0, 0.0)]}, ball), "record", "a pin it rides (a, b)"),
((ball.parts, {"rod": [("thigh", "b", 1.0, 0.0)]}, ball), "record", "no part of the record"),
((ball.parts, {"rod": [("parent", "b", 1e308, 0.0)]}, ball), "record", "rod is at most"),
((ball.parts, {"rod": [("parent", "b", 0.5, 1e308)]}, ball), "record", "rod is at most"),
((ball.parts, {"rod": [("parent", "b", 1e9, 1e9)]}, ball), "record", "rod is at most"),
((ball.parts, {"rod": [("parent", "b", float("inf"), 0.0)]}, ball), "record", "a finite number"),
((ball.parts, {"rod": [("parent", "b", 0.5, float("nan"))]}, ball), "record", "a finite number"),
((ball.parts, {"rod": [("parent", "b", 0.5, 1.2 * ram.e_b)]}, ball), "record", "rod's on b is 0.0850"),
((ball.parts, {"rod": [("child", "b", 1e308, 0.0)]}, ball), "record", "rod is at most"),
((ball.parts, {"rod": [("parent", "b", 0.5, 0.0)]}, ball), "record", "a body the pin joins (child); 'parent' turns with parent"),
((ball.parts, {"rod": [("child", "b", 0.5, 1e308)]}, ball), "record", "rod is at most"),
((ball.parts, {"rod": [("child", "b", 1e9, 1e9)]}, ball), "record", "rod is at most"),
((ball.parts, {"rod": [("child", "b", float("inf"), 0.0)]}, ball), "record", "a finite number"),
((ball.parts, {"rod": [("child", "b", 0.5, float("nan"))]}, ball), "record", "a finite number"),
((ball.parts, {"rod": [("child", "b", 0.5, 1.2 * ram.e_b)]}, ball), "record", "rod's on b is 0.0850"),
(({"ball": "rocker"}, {}, ball), "record", "turns with 'rocker'"), (({"ball": "parent"}, {}, ball), "record", "no part turns with body child")):
with self.assertRaises(R.RamError) as caught:
R.search("direct", self.HINGE, ram, seats, world=lambda m: made)
self.assertEqual(caught.exception.gate, gate, said)
self.assertIn(said, str(caught.exception))
self.assertTrue(R.search("direct", self.HINGE, ram, seats, world=lambda m: (ball.parts, {}, ball)).found)
self.assertTrue(R.search("direct", self.HINGE, ram, seats, world=lambda m: (ball.parts, {"rod": [("parent", "b", 0.5, ram.e_b)]}, ball)).found)
self.assertTrue(R.search("direct", self.HINGE, ram, seats, world=lambda m: (ball.parts, {"rod": [("child", "b", 0.5, ram.e_b)]}, ball)).found)
def test_the_limit_is_refused_naming_the_count(self):
seats = {"a": grid((0, -0.5, 0.4), (0, -0.2, 1.2), (1, 3, 5)), "b": grid((0, -0.5, -1.2), (0, -0.2, -0.4), (1, 3, 5))}
@ -1021,8 +1160,8 @@ class RecordDrives(unittest.TestCase):
data = R.record(m, ram)
wire = json.loads(json.dumps(data))
self.assertEqual(wire, data)
self.assertEqual(sorted(data), ["compliance", "hinge", "kind", "offsets", "parts", "pins", "ram", "schema", "touch", "version"])
self.assertEqual((data["schema"], data["version"], data["compliance"]), ("brokkr.ram", 1, None))
self.assertEqual(sorted(data), ["hinge", "kind", "offsets", "parts", "pins", "ram", "schema", "touch", "version"])
self.assertEqual((data["schema"], data["version"]), ("brokkr.ram", 2))
again, ram2 = R.from_record(wire)
self.assertEqual(R.record(again, ram2), data)
self.assertEqual((again.parts, again.touch), (m.parts, m.touch))
@ -1053,18 +1192,18 @@ class RecordDrives(unittest.TestCase):
def test_a_record_this_version_cannot_read_is_refused_whole(self):
data = R.record(R.Mechanism("direct", O, X, -62, 0, a=(0.05, -0.3, 0.8), b=(0.05, -0.3, -0.6)), R.Ram(BORE))
settle = {"stiffness": 2.0e6, "damping": 4.0e3, "travel": 0.02}
self.assertEqual(tuple(settle), R.COMPLIANCE)
ram = dict(data["ram"], stiffness=2.0e6)
short = {k: v for k, v in data.items() if k != "touch"}
for change, said in (({"version": 2}, "version 2"), ({"version": 2, "compliance": settle}, "version 2"), ({"compliance": settle}, "compliance block"),
for change, said in (({"version": 1}, "reads brokkr.ram version 2; the record is brokkr.ram version 1"), ({"version": 3}, "version 3"), ({"version": 1, "settle": settle}, "version 1"),
({"schema": "brokkr.kit"}, "brokkr.kit"), ({"settle": settle}, "unknown ['settle']"), ({"ram": ram}, "unknown ['stiffness']"),
({"hinge": dict(data["hinge"], rate=1.0)}, "unknown ['rate']"),
# a block that is falsy is a block (S23); the version is the integer 1
({"compliance": {}}, "compliance block"), ({"compliance": 0}, "compliance block"), ({"compliance": False}, "compliance block"),
({"version": 1.0}, "version 1.0"), ({"version": True}, "version True"), ({"version": "1"}, "version '1'"),
# a key the record does not know is refused whatever it holds, null and falsy included (S23): a ram
# record carries no settle. The version is the integer 2
({"settle": None}, "unknown ['settle']"), ({"settle": {}}, "unknown ['settle']"), ({"settle": False}, "unknown ['settle']"),
({"version": 2.0}, "version 2.0"), ({"version": True}, "version True"), ({"version": "2"}, "version '2'"),
({"kind": "scissor"}, "kind is one of"),
# a pin this kind has not, or a key that is no pin, is refused by name; so is one missing
({"pins": dict(data["pins"], q=[0.0, 0.0, 0.0])}, "the pins's keys are not version 1's: unknown ['q']"),
({"pins": dict(data["pins"], q=[0.0, 0.0, 0.0])}, "the pins's keys are not version 2's: unknown ['q']"),
({"pins": dict(data["pins"], parts={})}, "unknown ['parts']"), ({"pins": {"a": data["pins"]["a"]}}, "missing ['b']"),
({"pins": [1, 2]}, "(pin pins): an object, got list"), ({"ram": None}, "(pin ram): an object, got NoneType"),
# every number is a finite number, the bore over 0; three of them make a point
@ -1082,7 +1221,8 @@ class RecordDrives(unittest.TestCase):
({"parts": {"knee": "parent"}, "touch": {"rod": "knee"}}, "rod's zones are a list"),
({"parts": {"knee": "parent"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": 0.1}]}}, "missing ['depth']"),
({"parts": {"knee": "parent"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": 0.1, "depth": 0.0, "whole": True}]}}, "unknown ['whole']"),
({"parts": {"knee": "parent"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": None, "depth": 0.0}]}}, "(pin rod knee radius)")):
({"parts": {"knee": "parent"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": None, "depth": 0.0}]}}, "(pin rod knee radius)"),
({"parts": {"knee": "parent"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": 0.1, "depth": 0.0}]}}, "(pin rod knee pin): rod may touch about b a part of a body the pin joins (child)")):
with self.assertRaises(R.RamError) as caught:
R.from_record({**data, **change})
self.assertEqual(caught.exception.gate, "record", change)
@ -1090,7 +1230,7 @@ class RecordDrives(unittest.TestCase):
with self.assertRaises(R.RamError) as caught:
R.from_record([data])
self.assertIn("a record is an object, got list", str(caught.exception))
zoned = R.from_record({**data, "parts": {"knee": "parent"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": 0.1, "depth": 0}]}})[0]
zoned = R.from_record({**data, "parts": {"knee": "child"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": 0.1, "depth": 0}]}})[0]
self.assertEqual(zoned.touch, {"rod": (("knee", "b", 0.1, 0.0),)})
# a ram refuses the same numbers when built by hand
for bad in ({"bore": -0.05}, {"bore": 0.0}, {"bore": None}, {"bore": True}, {"bore": 0.05, "gap": float("nan")}, {"bore": 0.05, "tail": float("inf")}, {"bore": 0.05, "rod": "0.02"}):
@ -1144,6 +1284,8 @@ class Refusals(unittest.TestCase):
self.refused("record", "rod knee radius", **knee, touch={"rod": [("knee", "d", "0.1", 0.0)]})
self.refused("record", "rod knee depth", **knee, touch={"rod": [("knee", "d", 0.1, -0.01)]})
self.refused("record", "rod knee depth", **knee, touch={"rod": [("knee", "d", 0.1, float("nan"))]})
self.assertIn("a body the pin joins (rocker); 'knee' turns with parent", str(self.refused("record", "rod knee pin", **knee, touch={"rod": [("knee", "d", 0.1, 0.0)]})))
self.assertEqual(R.Mechanism("four_bar", O, X, -125, 0, **{name: yz(DEEP[name]) for name in DEEP}, **knee, touch={"rod": [("knee", "a", 0.1, 0.0)]}).touch["rod"], (("knee", "a", 0.1, 0.0),))
self.refused("record", "a", a=(0, 1))
self.refused("record", "c", c=(0, float("nan"), 1))
self.refused("record", "b", b=(0, 0, -1)) # a four-bar has no b
@ -1167,6 +1309,239 @@ class Refusals(unittest.TestCase):
self.assertEqual((caught.exception.gate, caught.exception.pin), ("arm", "b"))
self.assertIn(f"arm at {caught.exception.angle:g} deg (pin b)", str(caught.exception))
def test_overlapping_solids_wind_by_their_count(self):
# two boxes that cut through one another in one mesh, each with its own vertices, then sharing the one index
# at the corner they have in common (all a merge by distance welds): the winding number is the count of
# boxes about the point, 2 in the overlap, where crossing parity read outside
big, small = block((0, 0, 0), (1, 1, 1)), block((0, 0, 0), (2, 0.5, 0.5))
pts = np.random.default_rng(1).uniform(-0.2, 2.2, (6000, 3))
count = sum(((pts >= lo) & (pts <= hi)).all(axis=1).astype(int) for lo, hi in (((0, 0, 0), (1, 1, 1)), ((0, 0, 0), (2, 0.5, 0.5))))
self.assertGreater(int((count == 2).sum()), 50)
for weld in (False, True):
verts, tris = joined(big, small, weld)
self.assertEqual(len(verts), 15 if weld else 16)
self.assertLess(float(np.abs(R.winding(verts, tris, pts) - count).max()), WHOLE, weld)
def test_the_plates_overlapping_bars_wind_by_their_count(self):
# the jointlib rocker plates: four closed bars in one mesh, a side's two overlapping. Every inside point of
# the fixture winds 1, or 2 where two bars overlap
fixture = json.loads((SURFACE / "tests" / "fixtures" / "ram_plates.json").read_text(encoding="utf-8"))
w = R.winding(fixture["verts"], fixture["faces"], fixture["inside"])
self.assertLess(float(np.abs(w - np.round(w)).max()), WHOLE)
self.assertEqual((int((np.round(w) == 1).sum()), int((np.round(w) == 2).sum())), (16, 13))
def test_a_staircase_winds_whole(self):
# a nonconvex prism of three steps, which a line crosses up to six times: 1 inside, 0 outside
verts, tris = staircase()
g = np.arange(-0.375, 3.5, 0.25)
pts = np.array([(x, y, z) for x in g for y in (-0.25, 0.125, 0.5, 0.875, 1.25) for z in g])
truth = (pts[:, 1] > 0) & (pts[:, 1] < 1) & (pts[:, 0] > 0) & (pts[:, 0] < 3) & (pts[:, 2] > 0) & (pts[:, 2] < np.ceil(pts[:, 0]))
self.assertGreater(min(int(truth.sum()), int((~truth).sum())), 200)
self.assertLess(float(np.abs(R.winding(verts, tris, pts) - truth).max()), WHOLE)
def test_an_open_cube_winds_by_what_its_hole_takes(self):
# a unit cube less its top face: about a point on the hole's axis the winding number is 1 less the hole's
# share of the sphere inside, and that share outside, 4 asin(a^2 / (a^2 + h^2)) of 4 pi for a square of half
# side a seen from h off its centre. So it is over 0.5 everywhere inside and under 0.5 over the hole, and
# passes through 0.5 on the hole's plane, where no face is. Less one triangle of the top it is the same
verts, tris = block((0, 0, 0), (1, 1, 1))
top = [k for k, t in enumerate(tris) if (verts[t][:, 2] == 1.0).all()]
self.assertEqual(len(top), 2)
z = np.array((0.5, 0.9, 0.999, 1.001, 1.1, 1.5))
share = np.arcsin(0.25 / (0.25 + (1.0 - z) ** 2)) / math.pi
w = R.winding(verts, np.delete(tris, top, axis=0), np.stack([np.full(6, 0.5), np.full(6, 0.5), z], axis=1))
self.assertLess(float(np.abs(w - np.where(z < 1, 1.0 - share, share)).max()), WHOLE)
self.assertTrue((w[:3] > 0.5).all() and (w[3:] < 0.5).all(), w.tolist()) # 0.001 under the plane 0.5009, 0.001 over it 0.4991
# no point inside either open cube, down to 0.001 from its faces and its hole, winds under 0.5: a count
inner = np.random.default_rng(3).uniform(0.001, 0.999, (4000, 3))
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_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
# 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)
top = np.flatnonzero((verts[tris][:, :, 2] == 1.0).all(axis=1))
for gap, closes in ((R.WELD / 3.0, True), (R.WELD * 3.4, False)):
lifted = soup.copy()
lifted[(3 * top[:, None] + np.arange(3)).ravel(), 2] += gap * math.sqrt(3.0)
if closes:
self.assertEqual(R.solids("lid", lifted, np.arange(36).reshape(-1, 3)).tolist(), [0] * 12)
else:
with self.assertRaises(R.RamError) as caught:
R.solids("lid", lifted, np.arange(36).reshape(-1, 3))
self.assertIn("part 'lid' is open: solid 0 of 2 has 4 edges no face runs the other way", str(caught.exception))
# weld alone: the nearest are one, a chain is one, and nothing is joined at no tolerance
row = np.array([(0, 0, 0), (0.5, 0, 0), (9, 0, 0), (9, 0.9, 0), (9, 1.8, 0), (20, 0, 0)], float) * 1e-3
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_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: 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("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
# is 0 in the cavity, 1 in the wall and 0 outside, before every face of the inner shell is the cavity, and
# the part passes as two solids
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)])
self.assertEqual(R.solids("sliver", *sheet).tolist(), [0, 0])
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_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, 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' 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.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))
spin = np.array([[1, 0, 0], [0, ca, -sa], [0, sa, ca]]) @ np.array([[cb, 0, sb], [0, 1, 0], [-sb, 0, cb]]) @ np.array([[cc, -sc, 0], [sc, cc, 0], [0, 0, 1]])
with self.assertRaises(R.RamError):
R.solids("spun", (verts - 0.5) @ spin.T, tris[:, ::-1])
def test_a_mirrored_mesh_is_placed_turned_back(self):
# a part mirrored by a negative scale is wound as its own mesh is: placed by its matrix the faces are turned
# back and it passes; carried with its winding kept it is the mirrored cube above. A matrix that does not
# mirror keeps every face, and the vertices are carried either way
verts, tris = block((0, 0, 0), (1, 1, 1))
faces = [tuple(int(i) for i in t) for t in tris]
mirror, shift = np.diag((-1.0, 1.0, 1.0, 1.0)), np.eye(4)
mirror[:3, 3] = shift[:3, 3] = (3.0, 0.0, 0.5)
v, f = R.placed(verts, faces, mirror)
self.assertEqual(np.abs(v - (verts * (-1, 1, 1) + (3.0, 0.0, 0.5))).max(), 0.0)
self.assertEqual(f, [face[::-1] for face in faces])
self.assertEqual(R.solids("left", v, f).tolist(), [0] * 12)
with self.assertRaises(R.RamError):
R.solids("left", v, faces)
v, f = R.placed(verts, faces, shift)
self.assertEqual((np.abs(v - (verts + (3.0, 0.0, 0.5))).max(), f), (0.0, faces))
def test_no_blender(self):
source = (SURFACE / "brokkr_kitbash" / "ram.py").read_text(encoding="utf-8")
for word in ("bpy", "np.gradient"):
@ -1176,5 +1551,116 @@ 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), 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 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"""
def test_every_kit_part_is_accepted(self):
# every part of every kit, at its defaults, all params at min, all at max, and each param at min and at max
spec = importlib.util.spec_from_file_location("brokkr_kitbash_core_ram", SURFACE / "brokkr_kitbash" / "core.py")
core = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = core
spec.loader.exec_module(core)
built, refused = 0, []
for name in core.kit_names():
for part_name, part in core.load_kit(name)["parts"].items():
params = part["params"]
variants = {"default": {}, "min": {p["name"]: p["min"] for p in params}, "max": {p["name"]: p["max"] for p in params}}
for p in params:
variants.update({p["name"] + " min": {p["name"]: p["min"]}, p["name"] + " max": {p["name"]: p["max"]}})
for variant, given in variants.items():
try:
made = core.build(part, given)
except core.KitError:
continue # a corner of the params the kit itself refuses
ends = np.cumsum(made.counts)
built += 1
try:
R.solids(f"{name}.{part_name}", made.V, [tuple(int(i) for i in made.faces[a:b]) for a, b in zip(ends - made.counts, ends)])
except R.RamError as error:
refused.append((name, part_name, variant, str(error)))
self.assertEqual(refused, [])
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: 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 = {}
for n, row in enumerate(rows):
ends = np.cumsum(sample[f"counts{n}"])
faces = [tuple(int(i) for i in sample[f"loops{n}"][a:b]) for a, b in zip(ends - sample[f"counts{n}"], ends)]
for frame, mesh in (("own", (sample[f"v{n}"], faces)), ("placed", R.placed(sample[f"v{n}"], faces, sample[f"matrix{n}"]))):
try:
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 "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(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__":
unittest.main()