brokkr_kitbash.ram: a zone is no wider or deeper than its member; between samples in a zone the axis is proved, not sampled; the signed mesh oracle
A zone's radius and depth are refused past the member's pin-to-pin length (by the pins alone) and its depth past the member's eye on that pin (Ram.eye; at the gate and in from_record, so a world's answer too). Between samples of which either is in a zone the segment is halved until the readings at its ends prove it holds -depth; at the floor a part the axis is held outside reads as touched. Signed, three rays by majority, moves here from the live test. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
941e146bc6
commit
481690fb5c
1 changed files with 143 additions and 13 deletions
|
|
@ -1,5 +1,6 @@
|
|||
"""Rams and linkages across a one-axis hinge: numpy and the standard library only, and nothing from the package, so
|
||||
a rig, a runtime or a test loads this file alone.
|
||||
a rig, a runtime or a test loads this file alone. Signed, the mesh oracle, asks for Blender's BVH tree when one is
|
||||
made and not before.
|
||||
|
||||
A Mechanism is the record of one hinge's drive: the hinge (pivot, unit axis, lo and hi in degrees, positive
|
||||
right-handed about the axis), a kind, and pins, each in its own body's rest frame (the pose at angle 0, where
|
||||
|
|
@ -23,6 +24,7 @@ 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
|
||||
|
||||
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`:
|
||||
|
|
@ -35,10 +37,19 @@ is refused), the pin's radius for the pin through the member's eye, half the thi
|
|||
or clevis. Beyond the radius the pair is checked like any other; nothing is exempt by a name, a length or the
|
||||
member's own body. Every body of the kind owns at least one part, or the gate refuses.
|
||||
|
||||
A zone is bounded by its member. Its radius and its depth are finite and no more than the member's length from pin
|
||||
to pin (a bar's between its pins; the ram's at the most its pins allow), which the record refuses by its pins
|
||||
alone; its depth is 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, a world's answer included. Between two samples of which
|
||||
either is in a zone, the gate does not trust the spacing: it halves the segment until the readings at its ends
|
||||
prove it holds -depth throughout (see _between), so a part of any thickness that the axis crosses there is read.
|
||||
|
||||
The oracle is distance(part, points) -> distances, points (N, 3) in the rest frame of the part's body. A distance
|
||||
is signed: negative inside the part, by any depth. The oracle may cap what it returns at Ram.reach(spacing),
|
||||
outside a part only: a point inside reads negative however deep it lies. An oracle that cannot tell inside from
|
||||
outside (a nearest-surface query on an open mesh) raises instead of answering; nan is refused here.
|
||||
outside (a nearest-surface query on an open mesh) raises instead of answering; nan is refused here. It never reads
|
||||
more than the true distance: the gate's proof between samples is that a distance changes by no more than the way
|
||||
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.
|
||||
|
|
@ -62,6 +73,8 @@ SCHEMA, VERSION = "brokkr.ram", 1
|
|||
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
|
||||
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):
|
||||
|
|
@ -117,6 +130,12 @@ class Ram:
|
|||
def spacing(self, spacing=None):
|
||||
return self.barrel_r if spacing is None else float(spacing)
|
||||
|
||||
def eye(self, member, pin):
|
||||
"""The radius of a member's eye on one of its pins: the most a zone's depth lets its axis into a part."""
|
||||
if member in ("barrel", "rod"):
|
||||
return self.e_a if pin == "a" else self.e_b
|
||||
return self.link_r
|
||||
|
||||
def reach(self, spacing=None):
|
||||
"""The greatest distance the clearance gate asks of any member: what a distance oracle may cap at."""
|
||||
return max(self.barrel_r, self.rod, self.link_r) + self.gap + self.spacing(spacing) / 2
|
||||
|
|
@ -177,6 +196,10 @@ class Mechanism:
|
|||
for part, body in self.parts.items():
|
||||
if body not in BODIES[self.kind]:
|
||||
raise RamError(self.kind, "record", f"part {part!r} turns with {body!r}; this kind has {', '.join(BODIES[self.kind])}")
|
||||
for name in ("a", "b", "rocker", "p", "c", "d"):
|
||||
needed, given = name in PINS[self.kind], getattr(self, name) is not None
|
||||
if needed != given:
|
||||
raise RamError(self.kind, "record", "this kind needs the pin" if needed else "this kind has no such pin", pin=name)
|
||||
touch = {}
|
||||
for member, zones in dict(self.touch).items():
|
||||
if member not in MEMBERS[self.kind]:
|
||||
|
|
@ -193,13 +216,14 @@ 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")
|
||||
span = _span(self, member)
|
||||
for name, value in (("radius", radius), ("depth", depth)):
|
||||
if value > span:
|
||||
raise RamError(self.kind, "record", f"a zone no wider or deeper than its member: {member} is at most {span:.4f} from pin to pin, got {value!r}",
|
||||
pin=f"{member} {part} {name}")
|
||||
touch[member].append((part, pin, radius, depth))
|
||||
touch[member] = tuple(touch[member])
|
||||
self.touch = touch
|
||||
for name in ("a", "b", "rocker", "p", "c", "d"):
|
||||
needed, given = name in PINS[self.kind], getattr(self, name) is not None
|
||||
if needed != given:
|
||||
raise RamError(self.kind, "record", "this kind needs the pin" if needed else "this kind has no such pin", pin=name)
|
||||
if self.kind == "direct":
|
||||
return
|
||||
n = self.axis
|
||||
|
|
@ -216,6 +240,25 @@ class Mechanism:
|
|||
self.branch = 1.0 if side > 0 else -1.0 # which side of R -> c the pin p keeps, through the whole range
|
||||
|
||||
|
||||
def _span(m, member):
|
||||
"""The most a member measures from pin to pin, by the pins alone: a bar's length across the axis; for the ram's
|
||||
two, the base's and the eye's distances from the centre the eye turns about, added."""
|
||||
if member in ("barrel", "rod"):
|
||||
centre, eye = m.pivot if m.kind == "direct" else m.rocker, getattr(m, EYE[m.kind])
|
||||
return float(np.linalg.norm(m.a - centre) + np.linalg.norm(eye - centre))
|
||||
start, end = RIDES[m.kind][member]
|
||||
return float(np.linalg.norm(_flat(getattr(m, end) - getattr(m, start), m.axis)))
|
||||
|
||||
|
||||
def _eyes(m, ram):
|
||||
"""Refuse a zone deeper than its member's eye on its pin."""
|
||||
for member, zones in m.touch.items():
|
||||
for part, pin, _, depth in zones:
|
||||
if depth > ram.eye(member, pin):
|
||||
raise RamError(m.kind, "record", f"a zone no deeper than its member's eye: {member}'s on {pin} is {ram.eye(member, pin):.4f}, got {depth!r}",
|
||||
pin=f"{member} {part} depth")
|
||||
|
||||
|
||||
@dataclass
|
||||
class Pose:
|
||||
degrees: np.ndarray # (S,)
|
||||
|
|
@ -343,11 +386,46 @@ def clearance(m, ram, degrees, distance, spacing=None):
|
|||
rest frame of the part's body at that angle. A sample is at most spacing / 2 from any point of the axis, so
|
||||
the member's surface keeps the gap. Every member meets every part of the record. Inside a zone of `touch`
|
||||
(within its radius of its pin's axis, across the hinge axis) a sample keeps -depth from the zone's part
|
||||
instead: the margin there is the distance plus the depth."""
|
||||
instead: the margin there is the distance plus the depth, and the segment to the next sample is proved to
|
||||
hold -depth throughout (_between). Two zones of one pair that both reach a sample let it the deeper."""
|
||||
return _clearance(m, ram, barrel_length(m, ram), pose(m, degrees), distance, spacing)
|
||||
|
||||
|
||||
def _between(kind, distance, part, pts, got, keep, zoned, floor):
|
||||
"""(S,) the least margin found between samples, inf where none is: for each segment between consecutive samples
|
||||
of which either is in a zone, whether the axis holds -depth (the deeper of its ends') all along it. A distance
|
||||
changes by no more than the way between two points, so along a segment it is at least (g(a) + g(b) - |ab|) / 2;
|
||||
where that does not prove the segment it is halved, the midpoint read (its margin is counted), down to `floor`.
|
||||
A segment still unproved at the floor against a part the axis is held outside (depth 0) reads that bound, so
|
||||
it is refused: the part is within floor / 2 of the axis there, crossed or touched. Against a part the axis may
|
||||
enter, the samples' readings stand: a burial is read to floor / 2."""
|
||||
out = np.full(len(pts), math.inf)
|
||||
pair = zoned[:, :-1] | zoned[:, 1:]
|
||||
row = np.nonzero(pair)[0]
|
||||
a, b, ga, gb = pts[:, :-1][pair], pts[:, 1:][pair], got[:, :-1][pair], got[:, 1:][pair]
|
||||
hold = np.minimum(keep[:, :-1], keep[:, 1:])[pair]
|
||||
while len(row):
|
||||
span = np.linalg.norm(b - a, axis=1)
|
||||
bound = (ga + gb - span) / 2.0
|
||||
unproved = (bound < hold) & (np.minimum(ga, gb) >= hold) # an end under its hold is already refused
|
||||
touched = unproved & (span <= floor) & (hold == 0.0)
|
||||
np.minimum.at(out, row[touched], bound[touched])
|
||||
go = unproved & (span > floor)
|
||||
if not go.any():
|
||||
break
|
||||
a, b, ga, gb, hold, row = (x[go] for x in (a, b, ga, gb, hold, row))
|
||||
mid = (a + b) / 2.0
|
||||
gm = np.asarray(distance(part, mid), dtype=float)
|
||||
if np.isnan(gm).any():
|
||||
raise RamError(kind, "oracle", f"the distance oracle answered nan for part {part!r}")
|
||||
np.minimum.at(out, row, gm - hold)
|
||||
a, b, ga, gb = np.concatenate([a, mid]), np.concatenate([mid, b]), np.concatenate([ga, gm]), np.concatenate([gm, gb])
|
||||
hold, row = np.concatenate([hold, hold]), np.concatenate([row, row])
|
||||
return out
|
||||
|
||||
|
||||
def _clearance(m, ram, barrel, p, distance, spacing):
|
||||
_eyes(m, ram)
|
||||
for body in BODIES[m.kind]:
|
||||
if body not in m.parts.values():
|
||||
raise RamError(m.kind, "record", f"no part turns with body {body}: the clearance gate would pass it unseen")
|
||||
|
|
@ -367,14 +445,17 @@ def _clearance(m, ram, barrel, p, distance, spacing):
|
|||
if np.isnan(got).any():
|
||||
raise RamError(m.kind, "oracle", f"the distance oracle answered nan for part {part!r}")
|
||||
keep = np.full(got.shape, need) # what each sample keeps from the part
|
||||
zoned = np.zeros(got.shape, dtype=bool)
|
||||
zones = [zone for zone in m.touch.get(member, ()) if zone[0] == part]
|
||||
for _, pin, reach, depth in zones:
|
||||
across = np.linalg.norm(_flat(pts - np.broadcast_to(at[pin], start.shape)[:, None, :], m.axis), axis=2)
|
||||
keep = np.where(across <= reach, np.minimum(keep, -depth), keep)
|
||||
if zones:
|
||||
out.allowed.append((label, part))
|
||||
zoned |= across <= reach
|
||||
over = got - keep
|
||||
row = over.min(axis=1)
|
||||
if zones:
|
||||
out.allowed.append((label, part))
|
||||
row = np.minimum(row, _between(m.kind, distance, part, seen[body].reshape(len(p.degrees), count, 3), got, keep, zoned, step / FINE))
|
||||
out.margin = np.minimum(out.margin, row)
|
||||
i = int(np.argmin(row))
|
||||
out.pairs[(label, part)] = (float(row[i]), float(p.degrees[i]))
|
||||
|
|
@ -533,7 +614,8 @@ def search(kind, hinge, ram, seats, world=None, limit=20000, steps=25, spacing=N
|
|||
the first clear one wins. world(m) -> (parts, touch, distance) builds a candidate's own parts, the brackets
|
||||
and links its pins place among them, and the oracle that answers for them: a linkage's links are the
|
||||
candidate's, so no one oracle serves a grid. What it returns is read as a record's: anything but the three,
|
||||
a part on no body of the kind or a zone that is not (part, pin the member rides, radius, depth) is refused. A grid past `limit` candidates is refused naming the count. A
|
||||
a part on no body of the kind, a zone that is not (part, pin the member rides, radius, depth) or one wider or
|
||||
deeper than its member is refused. A grid past `limit` candidates is refused naming the count. A
|
||||
miss returns the tally and the nearest miss (the least total shortfall: stroke, arm, load excess,
|
||||
clearance)."""
|
||||
pins = candidates(kind, hinge, seats)
|
||||
|
|
@ -592,8 +674,8 @@ def record(m, ram):
|
|||
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) is refused whole, as a RamError naming the field:
|
||||
nothing is read past and dropped."""
|
||||
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."""
|
||||
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")
|
||||
|
|
@ -638,7 +720,9 @@ def from_record(data):
|
|||
m = Mechanism(kind, point("pivot", hinge["pivot"]), point("axis", hinge["axis"]), _number(kind, "lo", hinge["lo"]), _number(kind, "hi", hinge["hi"]),
|
||||
offsets=tuple(_number(kind, "offsets", o) for o in data["offsets"]), parts=data["parts"], touch=touch,
|
||||
**{name: point(name, value) for name, value in pins.items()})
|
||||
return m, Ram(**ram)
|
||||
ram = Ram(**ram)
|
||||
_eyes(m, ram)
|
||||
return m, ram
|
||||
|
||||
|
||||
def swept(f, body, margin=0.0, steps=13, around=8):
|
||||
|
|
@ -658,3 +742,49 @@ def swept(f, body, margin=0.0, steps=13, around=8):
|
|||
for centre in (p.base + off * m.axis + p.u * min(ram.back, 0.0), p.eye + off * m.axis):
|
||||
pts.append(centre[:, None, :] + ring)
|
||||
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 __init__(self, shells, cap=None, rays=3):
|
||||
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)
|
||||
|
||||
def __call__(self, part, pts):
|
||||
pts = np.asarray(pts, dtype=float)
|
||||
self.asked += len(pts)
|
||||
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]
|
||||
return out
|
||||
|
|
|
|||
Loading…
Reference in a new issue