diff --git a/surfaces/blender/brokkr_kitbash/ram.py b/surfaces/blender/brokkr_kitbash/ram.py new file mode 100644 index 0000000..ef20a4b --- /dev/null +++ b/surfaces/blender/brokkr_kitbash/ram.py @@ -0,0 +1,497 @@ +"""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 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 +every body's frame is the parent's). + + direct the ram runs from a on the parent to b on the child. + four_bar a rocker pinned on the parent at `rocker` (R) carries the pin p; a coupler joins p to c on the child; + the ram runs from a on the parent to d on the rocker, and d is p (the excavator bucket linkage). + bell_crank the same loop with d elsewhere on the rocker. + +Every pose quantity is a pure function of (record, angle): pose() holds no solve state. The loop is solved in the +plane across the axis; a pin's coordinate along the axis only says where its member stands: the rocker bars at R's, +the coupler bar at c's, the ram at a's plus each of `offsets`. + + pose(m, degrees) every body's rotation, the ram's base and eye, L, dL/dtheta, per angle + length(m, degrees) pin-to-pin ram length + extension(m, ram, barrel, degrees) rod extension from closed + fit(m, ram, ...) the gates over the range: assembly, stroke, arm, load, clearance + clearance(m, ram, barrel, degrees, distance) the clearance gate's reading at any angles + search(kind, hinge, ram, seats, ...) the best of a seat grid, or the tally and the nearest miss + record(m, ram, barrel), 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 + +Clearance takes a distance oracle, distance(body, points) -> distances, body one of BODIES[kind] and points (N, 3) +in that body's rest frame. The oracle may cap what it returns at Ram.reach(spacing): nothing farther is asked. +""" +import math +from dataclasses import dataclass, field, fields + +import numpy as np + +KINDS = ("direct", "four_bar", "bell_crank") +BODIES = {"direct": ("parent", "child"), "four_bar": ("parent", "child", "rocker", "coupler"), + "bell_crank": ("parent", "child", "rocker", "coupler")} +PINS = {"direct": ("a", "b"), "four_bar": ("a", "rocker", "p", "c", "d"), "bell_crank": ("a", "rocker", "p", "c", "d")} +GATES = ("assembly", "stroke", "toggle", "arm", "load", "clash") +BAND = 1e-9 # the loop is refused within this of a dead centre of the rocker and coupler + + +class RamError(ValueError): + """A refusal: the mechanism kind, the gate, and the angle or pin it failed at. `fit` holds the readings when + the gates got far enough to take them.""" + + def __init__(self, kind, gate, message, angle=None, pin=None, fit=None): + where = f" at {angle:g} deg" if angle is not None else f" (pin {pin})" if pin else "" + super().__init__(f"{kind} ram: {gate}{where}: {message}") + self.kind, self.gate, self.angle, self.pin, self.fit = kind, gate, angle, pin, fit + + +@dataclass +class Ram: + """A ram's proportions. Lengths default from the bore radius.""" + bore: float + rod: float = None # rod radius + barrel_r: float = None # barrel outer radius + e_a: float = None # base pin centre to the barrel's back end + e_b: float = None # rod eye centre to the rod's shoulder (what stays out of the barrel, closed) + gland: float = None # piston and gland: barrel length that is not stroke + over: float = None # spare travel at each end of the stroke + tail: float = 0.0 # trunnion mount: barrel behind the base pin (replaces e_a) + min_arm: float = None # least effective arm |dL/dtheta|, length per radian + gap: float = None # least clearance to a body + link_r: float = None # half thickness of a rocker or coupler bar + max_load: float = 3.0 # greatest coupler pin load per unit ram force + + def __post_init__(self): + b = self.bore + for name, value in (("rod", 0.5 * b), ("barrel_r", 1.25 * b), ("e_a", 1.7 * b), ("e_b", 1.7 * b), ("gland", 1.3 * b), + ("over", 0.2 * b), ("min_arm", 1.5 * b), ("gap", 0.15 * b), ("link_r", 0.7 * b)): + if getattr(self, name) is None: + setattr(self, name, value) + + @property + def back(self): + """Signed distance from the base pin to the barrel's back end along the ram (negative: behind the pin).""" + return -self.tail if self.tail > 0 else self.e_a + + def spacing(self, spacing=None): + return self.barrel_r if spacing is None else float(spacing) + + 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 + + +def _flat(v, n): + """v without its part along the unit axis n.""" + return v - n * (v @ n)[..., None] + + +def _rot(v, n, t): + """v (..., 3) turned about the unit axis n by t radians (Rodrigues); t broadcasts over v's leading shape.""" + t = np.asarray(t, dtype=float)[..., None] + return v * np.cos(t) + np.cross(n, v) * np.sin(t) + n * (v @ n)[..., None] * (1.0 - np.cos(t)) + + +def _angle(v0, v, n): + """Signed angle about n from v0 to v, both across n.""" + return np.arctan2(np.cross(v0, v) @ n, v @ v0) + + +@dataclass +class Mechanism: + kind: str + pivot: np.ndarray + axis: np.ndarray + lo: float + hi: float + a: np.ndarray + b: np.ndarray = None + rocker: np.ndarray = None + p: np.ndarray = None + c: np.ndarray = None + d: np.ndarray = None + offsets: tuple = (0.0,) + + def __post_init__(self): + if self.kind not in KINDS: + raise RamError(str(self.kind), "record", f"kind is one of {', '.join(KINDS)}") + for name in ("pivot", "axis", "a", "b", "rocker", "p", "c", "d"): + value = getattr(self, name) + if value is not None: + value = np.array(value, dtype=float) + if value.shape != (3,) or not np.isfinite(value).all(): + raise RamError(self.kind, "record", "three finite numbers", pin=name) + setattr(self, name, value) + if abs(np.linalg.norm(self.axis) - 1.0) > 1e-6: + raise RamError(self.kind, "record", f"the axis is a unit vector, length {np.linalg.norm(self.axis):.6f}", pin="axis") + self.lo, self.hi = float(self.lo), float(self.hi) + if not self.lo < self.hi or self.hi - self.lo > 360.0: + raise RamError(self.kind, "record", f"lo < hi and hi - lo <= 360, got {self.lo:g}..{self.hi:g}") + self.offsets = tuple(float(o) for o in self.offsets) + if not self.offsets: + raise RamError(self.kind, "record", "at least one offset") + 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 + apart = float(np.linalg.norm(self.d - self.p)) + if self.kind == "four_bar" and apart > 0.0: + raise RamError(self.kind, "record", f"a four-bar's ram eye is the rocker's coupler pin; d is {apart:.4f} from p", pin="d") + if self.kind == "bell_crank" and apart == 0.0: + raise RamError(self.kind, "record", "a bell crank's ram eye stands off the coupler pin; d on p is a four_bar", pin="d") + self.lr = float(np.linalg.norm(_flat(self.p - self.rocker, n))) + self.lc = float(np.linalg.norm(_flat(self.p - self.c, n))) + side = float(n @ np.cross(_flat(self.c - self.rocker, n), _flat(self.p - self.rocker, n))) + if min(self.lr, self.lc) < BAND or abs(side) < BAND: + raise RamError(self.kind, "assembly", "the rest pose is a dead centre: R, p and c are in line", pin="p") + self.branch = 1.0 if side > 0 else -1.0 # which side of R -> c the pin p keeps, through the whole range + + +@dataclass +class Pose: + degrees: np.ndarray # (S,) + base: np.ndarray # (S, 3) ram base pin, parent frame, at offset 0 + eye: np.ndarray # (S, 3) ram eye + u: np.ndarray # (S, 3) unit vector base -> eye + L: np.ndarray # (S,) pin to pin + dL: np.ndarray # (S,) dL/dtheta, length per radian: the effective arm, signed + phi: np.ndarray = None # (S,) rocker angle from rest, radians, in (-pi, pi] + psi: np.ndarray = None # (S,) coupler angle from rest + dphi: np.ndarray = None # (S,) dphi/dtheta + P: np.ndarray = None # (S, 3) the rocker's coupler pin + C: np.ndarray = None # (S, 3) the child's coupler pin + load: np.ndarray = None # (S,) coupler pin load per unit ram force + mu_c: np.ndarray = None # (S,) transmission angle at c, degrees, folded to 0..90 + mu_p: np.ndarray = None # (S,) transmission angle at p + + +def pose(m, degrees): + """The mechanism at each of `degrees` (a number or an array): a pure function of the record and the angle.""" + deg = np.atleast_1d(np.asarray(degrees, dtype=float)) + t, n, O = np.radians(deg), m.axis, m.pivot + if m.kind == "direct": + eye = O + _rot(m.b - O, n, t) + base = np.broadcast_to(m.a, eye.shape) + L = np.linalg.norm(eye - base, axis=1) + u = (eye - base) / np.maximum(L, 1e-12)[:, None] + return Pose(deg, base, eye, u, L, (np.cross(n, eye - O) * u).sum(axis=1)) + R = m.rocker + C = O + _rot(m.c - O, n, t) + g = _flat(C - R, n) + dist = np.linalg.norm(g, axis=1) + lo, hi = abs(m.lr - m.lc) + BAND, m.lr + m.lc - BAND + bad = (dist <= lo) | (dist >= hi) + if bad.any(): + i = int(np.argmax(bad)) + raise RamError(m.kind, "assembly", f"|c - R| is {dist[i]:.4f}, outside ({lo:.4f}, {hi:.4f}): the rocker ({m.lr:.4f}) and coupler " + f"({m.lc:.4f}) cannot close the loop, or reach a dead centre where the branch would change", angle=float(deg[i])) + x = (m.lr * m.lr - m.lc * m.lc + dist * dist) / (2.0 * dist) + h = np.sqrt(np.maximum(m.lr * m.lr - x * x, 0.0)) + across = g / dist[:, None] + v = across * x[:, None] + m.branch * np.cross(n, across) * h[:, None] # p - R across the axis + phi = _angle(_flat(m.p - R, n), v, n) + P = R + _rot(m.p - R, n, phi) + eye = R + _rot(m.d - R, n, phi) + w = _flat(P - C, n) # the coupler, c -> p + k = w / np.linalg.norm(w, axis=1)[:, None] + psi = _angle(_flat(m.p - m.c, n), w, n) + # the coupler's two ends move equally along it + dphi = (np.cross(n, C - O) * k).sum(axis=1) / (np.cross(n, P - R) * k).sum(axis=1) + base = np.broadcast_to(m.a, eye.shape) + L = np.linalg.norm(eye - base, axis=1) + u = (eye - base) / np.maximum(L, 1e-12)[:, None] + dL = (np.cross(n, eye - R) * u).sum(axis=1) * dphi + crank, link = _flat(O - C, n), _flat(R - P, n) + moment = np.abs(np.cross(-crank, k) @ n) + load = np.abs(dL) / np.maximum(moment, 1e-12) + mu_c = np.degrees(np.arcsin(np.clip(moment / np.linalg.norm(crank, axis=1), 0.0, 1.0))) + mu_p = np.degrees(np.arcsin(np.clip(np.abs(np.cross(link, k) @ n) / np.linalg.norm(link, axis=1), 0.0, 1.0))) + return Pose(deg, base, eye, u, L, dL, phi, psi, dphi, P, C, load, mu_c, mu_p) + + +def length(m, degrees): + """Pin-to-pin ram length at each angle.""" + return pose(m, degrees).L + + +def extension(m, ram, barrel, degrees): + """Rod extension from closed at each angle: L - (back + barrel + e_b).""" + return pose(m, degrees).L - (ram.back + barrel + ram.e_b) + + +def _members(m, ram, barrel, p): + """(name, start (S, 3), end (S, 3), radius, own body) of every member in the parent frame, clevis ends left + out: e_a at the ram's base (the barrel starts there), 0.4 e_b at its eye, 1.5 link_r at a link's pins.""" + n = m.axis + for off in m.offsets: + base, eye = p.base + off * n, p.eye + off * n + front = base + p.u * (ram.back + max(barrel, 1e-6)) + yield f"barrel[{off:g}]", base + p.u * ram.back, front, ram.barrel_r, None + yield f"rod[{off:g}]", front, eye - p.u * (0.4 * ram.e_b), ram.rod, None + if m.kind == "direct": + return + R = np.broadcast_to(m.rocker, p.P.shape) + bars = [("rocker", R, p.P - n * ((p.P - R) @ n)[:, None], "rocker"), ("coupler", p.P - n * ((p.P - p.C) @ n)[:, None], p.C, "coupler")] + if m.kind == "bell_crank": + bars.append(("rocker arm", R, p.eye - n * ((p.eye - R) @ n)[:, None], "rocker")) + for name, start, end, own in bars: + along = end - start + span = np.linalg.norm(along, axis=1)[:, None] + cut = along / np.maximum(span, 1e-12) * np.minimum(1.5 * ram.link_r, span / 2.0) + yield name, start + cut, end - cut, ram.link_r, own + + +def _into(m, p, body, pts): + """Parent-frame points (S, N, 3) carried into a body's rest frame at each angle.""" + n = m.axis + if body == "parent": + return pts + if body == "child": + return m.pivot + _rot(pts - m.pivot, n, -np.radians(p.degrees)[:, None]) + if body == "rocker": + return m.rocker + _rot(pts - m.rocker, n, -p.phi[:, None]) + return m.p + _rot(pts - p.P[:, None, :], n, -p.psi[:, None]) + + +def clearance(m, ram, barrel, degrees, distance, spacing=None, at=None): + """The clearance gate's reading: (margin per angle, (angle, member, body) of the least). A member is clear + where margin >= 0: each sample of its axis, taken at most `spacing` apart (default barrel_r), is at least + radius + gap + spacing / 2 from every body, measured in that body's rest frame 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 + body of the mechanism but its own.""" + p = pose(m, degrees) if at is None else at + step = ram.spacing(spacing) + margin, least, where = np.full(len(p.degrees), math.inf), math.inf, None + for name, start, end, radius, own in _members(m, ram, barrel, p): + count = max(int(math.ceil(float(np.linalg.norm(end - start, axis=1).max()) / step)) + 1, 2) + pts = start[:, None, :] + (end - start)[:, None, :] * np.linspace(0.0, 1.0, count)[None, :, None] + need = radius + ram.gap + step / 2.0 + for body in BODIES[m.kind]: + if body == own: + continue + got = np.asarray(distance(body, _into(m, p, body, pts).reshape(-1, 3)), dtype=float).reshape(len(p.degrees), count) + row = got.min(axis=1) - need + margin = np.minimum(margin, row) + i = int(np.argmin(row)) + if row[i] < least: + least, where = float(row[i]), (float(p.degrees[i]), name, body) + return margin, where + + +@dataclass +class Fit: + m: Mechanism + ram: Ram + why: list # (gate, angle or None, message) of every gate that failed; empty when it fits + degrees: np.ndarray + l_min: float + l_max: float + travel: float # L_max - L_min + barrel: float # barrel length + closed: float # pin to pin with the rod home: back + barrel + e_b + stroke: float # travel the barrel holds + spare: float # stroke - (travel + 2 over): negative when the stroke does not fit + arm_min: float # least |dL/dtheta| + arm_at: float # the angle of it + arm_sign: int # 0 when dL/dtheta changes sign (a dead centre inside the range) + swing: float = 0.0 # the rocker's travel, degrees + load_max: float = 0.0 # greatest coupler pin load per unit ram force + mu_c: float = None # least transmission angle at c, degrees: reported, never gated + mu_p: float = None # least transmission angle at p + clear_min: float = math.inf # least clearance beyond what the gate asks; inf with no oracle + clear_at: tuple = None # (angle, member, body) of it + table: list = field(default_factory=list) # (angle, L, dL/dtheta, clearance margin) per step + + @property + def ok(self): + return not self.why + + def error(self): + gate, angle, message = self.why[0] + return RamError(self.m.kind, gate, message, angle=angle, fit=self) + + def report(self): + """One line for a log or a sheet.""" + state = "OK" if self.ok else "NO (" + "; ".join(f"{g}: {msg}" for g, _, msg in self.why) + ")" + links = "" if self.m.kind == "direct" else f", rocker swing {self.swing:.1f}, pin load <= {self.load_max:.2f}, transmission >= {min(self.mu_c, self.mu_p):.1f} deg" + return (f"{state}: L {self.l_min:.3f}..{self.l_max:.3f}, barrel {self.barrel:.3f}, stroke {self.stroke:.3f} for travel {self.travel:.3f} " + f"(spare {self.spare:+.3f}), arm >= {self.arm_min:.3f}{links}, clear {self.clear_min:+.3f}") + + +def _fit(m, ram, steps=25, distance=None, spacing=None, clear=True): + """Every gate's reading; raises only where the loop does not assemble or a bell crank's eye crowds its pin.""" + if m.kind == "bell_crank" and np.linalg.norm(m.d - m.p) < 2.0 * ram.bore: + raise RamError(m.kind, "pins", f"the ram eye stands at least 2 bore ({2.0 * ram.bore:.4f}) from the coupler pin; d is {np.linalg.norm(m.d - m.p):.4f} from p", pin="d") + if (m.kind != "direct") and not (m.lo <= 0.0 <= m.hi): + pose(m, np.linspace(0.0, m.lo if m.lo > 0.0 else m.hi, steps)) # the branch is carried from rest: no dead centre on the way + p = pose(m, np.linspace(m.lo, m.hi, steps)) + l_min, l_max = float(p.L.min()), float(p.L.max()) + travel = l_max - l_min + barrel = l_min - ram.over - ram.back - ram.e_b + stroke = barrel - ram.gland + spare = stroke - (travel + 2.0 * ram.over) + i = int(np.argmin(np.abs(p.dL))) + arm_min, arm_at = float(abs(p.dL[i])), float(p.degrees[i]) + signs = set(np.sign(p.dL[np.abs(p.dL) > 1e-9]).tolist()) + arm_sign = int(signs.pop()) if len(signs) == 1 else 0 + f = Fit(m, ram, [], p.degrees, l_min, l_max, travel, barrel, ram.back + barrel + ram.e_b, stroke, spare, arm_min, arm_at, arm_sign) + if barrel <= ram.gland or spare < -1e-9: + f.why.append(("stroke", None, f"travel {travel:.3f} needs {travel + 3.0 * ram.over + ram.gland + ram.back + ram.e_b:.3f} closed, L_min is {l_min:.3f}")) + if arm_sign == 0: + flip = np.nonzero(np.sign(p.dL[1:]) != np.sign(p.dL[:-1]))[0] + f.why.append(("toggle", float(p.degrees[flip[0] + 1]) if len(flip) else arm_at, "dL/dtheta changes sign: a dead centre inside the range")) + elif arm_min < ram.min_arm: + f.why.append(("arm", arm_at, f"least effective arm {arm_min:.3f} under {ram.min_arm:.3f}")) + if m.kind != "direct": + phi = np.degrees(np.unwrap(p.phi)) + j = int(np.argmax(p.load)) + f.swing, f.load_max = float(phi.max() - phi.min()), float(p.load[j]) + f.mu_c, f.mu_p = float(p.mu_c.min()), float(p.mu_p.min()) + if f.load_max > ram.max_load: + f.why.append(("load", float(p.degrees[j]), f"coupler pin load {f.load_max:.2f} x the ram force, over {ram.max_load:.2f}")) + margin = np.full(steps, math.inf) + if distance is not None and clear: + margin, f.clear_at = clearance(m, ram, barrel, None, distance, spacing, at=p) + f.clear_min = float(margin.min()) + if f.clear_min < 0.0: + angle, member, body = f.clear_at + f.why.append(("clash", angle, f"{member} is {-f.clear_min:.3f} inside the clearance of body {body}")) + f.table = [tuple(row) for row in np.stack([p.degrees, p.L, p.dL, margin], axis=1).tolist()] + return f + + +def fit(m, ram, steps=25, distance=None, spacing=None): + """Check one mechanism from lo to hi. Gates, in order, each over all steps at once: assembly; stroke; effective + arm (one sign, and at least min_arm); coupler pin load (linkages); clearance, when a distance oracle is given. + Returns the Fit; a failed gate raises RamError, its `fit` holding the readings.""" + f = _fit(m, ram, steps, distance, spacing) + if not f.ok: + raise f.error() + return f + + +@dataclass +class Search: + best: Fit # the winner, or the nearest miss when none fits + found: bool + tried: int + fits: int # candidates that pass every gate but clearance + tally: dict # gate -> candidates it failed (a candidate can fail several) + seat: dict # the winner's or nearest miss's pins + + def report(self): + head = f"{self.fits} of {self.tried} candidates pass the gates before clearance" if self.found else f"no candidate of {self.tried} fits" + reasons = ", ".join(f"{k} {v}" for k, v in sorted(self.tally.items())) + return f"{head}{' (failed: ' + reasons + ')' if reasons else ''}; {'best' if self.found else 'nearest'}: {self.best.report() if self.best else 'none assembles'}" + + +def _polar(n, centre, toward, radii, step): + """Points about `centre` across the axis n: each radius, every `step` degrees from the direction `toward`.""" + e = _flat(np.asarray(toward, dtype=float) - centre, n) + if np.linalg.norm(e) < 1e-9: + e = _flat(np.array([0.0, 0.0, 1.0]) if abs(n[2]) < 0.9 else np.array([1.0, 0.0, 0.0]), n) + e = e / np.linalg.norm(e) + return [centre + r * _rot(e, n, math.radians(turn)) for r in radii for turn in range(0, 360, step)] + + +def candidates(kind, hinge, seats): + """The pins of every candidate of a seat grid. direct: seats['a'] x seats['b']. Linkages: seats['rocker'] x + seats['c'] x p on a polar grid about R (lengths seats['link'] = (lo, hi, n), every 15 degrees) x seats['a'], + and for a bell crank x d on a polar grid about R (seats['d'] = (lo, hi, n), every 30 degrees).""" + n = np.asarray(hinge["axis"], dtype=float) + if kind == "direct": + return [{"a": a, "b": b} for a in seats["a"] for b in seats["b"]] + out = [] + for R in seats["rocker"]: + R = np.asarray(R, dtype=float) + for c in seats["c"]: + for p in _polar(n, R, c, np.linspace(*seats["link"]), 15): + eyes = [p] if kind == "four_bar" else _polar(n, R, p, np.linspace(*seats["d"]), 30) + out.extend({"a": a, "rocker": R, "p": p, "c": c, "d": d} for a in seats["a"] for d in eyes) + return out + + +def search(kind, hinge, ram, seats, distance=None, limit=20000, steps=25, spacing=None): + """Seat a mechanism from a grid (see candidates). hinge = {pivot, axis, lo, hi, offsets (optional)}. Best + first: every gate but clearance over all candidates, then clearance in order of least arm, greatest first; + the first clear one wins. 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) + if len(pins) > limit: + raise RamError(kind, "search", f"{len(pins)} candidates, over the limit of {limit}: thin the seat grid") + tally, passed, miss = {}, [], None + + def missed(f, seat): + nonlocal miss + for gate in {g for g, _, _ in f.why}: + tally[gate] = tally.get(gate, 0) + 1 + short = (max(-f.spare, 0.0) + max(ram.min_arm - f.arm_min, 0.0) + (ram.min_arm if f.arm_sign == 0 else 0.0) + + max(f.load_max - ram.max_load, 0.0) + (max(-f.clear_min, 0.0) if f.clear_min < math.inf else 0.0)) + if miss is None or short < miss[0]: + miss = (short, f, seat) + + for seat in pins: + try: + m = Mechanism(kind, hinge["pivot"], hinge["axis"], hinge["lo"], hinge["hi"], offsets=hinge.get("offsets", (0.0,)), **seat) + f = _fit(m, ram, steps, clear=False) + except RamError as refusal: + tally[refusal.gate] = tally.get(refusal.gate, 0) + 1 + continue + if f.ok: + passed.append((f, seat)) + else: + missed(f, seat) + passed.sort(key=lambda entry: -entry[0].arm_min) + for f, seat in passed: + if distance is None: + return Search(f, True, len(pins), len(passed), tally, seat) + f = _fit(f.m, ram, steps, distance, spacing) + if f.ok: + return Search(f, True, len(pins), len(passed), tally, seat) + missed(f, seat) + return Search(miss[1] if miss else None, False, len(pins), len(passed), tally, miss[2] if miss else None) + + +def record(m, ram, barrel): + """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).""" + out = {"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)}, "barrel": float(barrel), "closed": float(ram.back + barrel + ram.e_b)} + if m.kind != "direct": + out["links"] = {"rocker": m.lr, "coupler": m.lc} + return out + + +def from_record(data): + """(Mechanism, Ram, barrel) of a record.""" + ram = Ram(**data["ram"]) + hinge = data["hinge"] + m = Mechanism(data["kind"], hinge["pivot"], hinge["axis"], hinge["lo"], hinge["hi"], offsets=tuple(data["offsets"]), **data["pins"]) + return m, ram, float(data["barrel"]) + + +def swept(f, body, margin=0.0, steps=13, around=8): + """Points on the swept ram's surface in a body's rest frame, the barrel radius grown by `margin`, a trunnion's + tail included: what a recess in that body must clear (their hull or bounding box).""" + m, ram = f.m, f.ram + if body not in BODIES[m.kind]: + raise RamError(m.kind, "swept", f"no body {body!r}; this kind has {', '.join(BODIES[m.kind])}") + p = pose(m, np.linspace(m.lo, m.hi, steps)) + side = np.cross(p.u, m.axis) + side = side / np.linalg.norm(side, axis=1)[:, None] + up = np.cross(side, p.u) + turn = np.linspace(0.0, 2.0 * math.pi, around, endpoint=False) + ring = (ram.barrel_r + margin) * (np.cos(turn)[None, :, None] * side[:, None, :] + np.sin(turn)[None, :, None] * up[:, None, :]) + pts = [] + for off in m.offsets: + 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)