diff --git a/surfaces/blender/tests/live/ram_knee.py b/surfaces/blender/tests/live/ram_knee.py new file mode 100644 index 0000000..d364092 --- /dev/null +++ b/surfaces/blender/tests/live/ram_knee.py @@ -0,0 +1,450 @@ +"""Live proof, in a background Blender, of brokkr_kitbash/ram.py's clearance gate on meshes: the R-3 knee (thigh, +shin, the bracket and horn, a bell crank's or a four-bar's plates, pins and clevises), every piece a closed mesh this +file generates, each a named part of a body, and the gate answered by a signed BVH oracle over them. Not part of the +unittest run: it needs Blender (mathutils' BVHTree). + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/ram_knee.py -- + +Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses +without them). is an absolute path; writes .result.json and .r3_.png (the bell crank at 0, +-62.5 and -125) and exits 1 when a check failed. + +The oracle. distance(part, points) is the nearest face's distance, negative where the point is inside one of the +part's shells. Inside is the crossing parity of three rays, by majority: one ray that grazes an edge or a vertex +miscounts, and an isolated sample then reads inside a plate it stands clear of. + +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. +""" +import importlib.util +import json +import math +import os +import sys +import time +import traceback +from dataclasses import replace +from pathlib import Path + +import bmesh +import bpy +import numpy as np +from mathutils import Matrix, Vector +from mathutils.bvhtree import BVHTree + +SURFACE = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(SURFACE / "tools")) +import private_dirs # noqa: E402 + +_refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind)) +if _refused: + raise SystemExit(_refused) +OUT = sys.argv[sys.argv.index("--") + 1] +if not Path(OUT).is_absolute(): + raise SystemExit(f"{OUT!r} is not an absolute path") +spec = importlib.util.spec_from_file_location("brokkr_kitbash_ram", SURFACE / "brokkr_kitbash" / "ram.py") +R = importlib.util.module_from_spec(spec) # ram.py as the unit tests load it +sys.modules[spec.name] = R +spec.loader.exec_module(R) + +RES = {"blender": bpy.app.version_string, "checks": [], "readings": {}} +SECTION = ["setup"] +# Metres between the oracle's reading and 0.0225, on a grid a plate's thickness off a rocker plate's face. Shipped +# worst 1.3e-08 (float32 faces); least claimed mutant 0.045 (a sample signed inside reads -0.0225); the geometric mean. +FLAT = 2.4e-5 + +BORE, PIN, AXLE = 0.042, 0.026, 0.028 +SLAB_C, SLAB_R = (0.31, 0.345), (0.35, 0.385) # the twin link plates along the axis: the coupler's inside the rocker's +X_C, X_R = 0.5 * sum(SLAB_C), 0.5 * sum(SLAB_R) +HALF = 0.5 * (SLAB_R[1] - SLAB_R[0]) # half a plate's thickness +W_ROCKER, W_COUPLER, W_ARM, W_HORN, W_BRACKET, COLLAR = 0.045, 0.04, 0.04, 0.05, 0.055, 0.05 +CHEEK = (0.03, 0.05) # a clevis's cheeks, either side of the ram's eye +SLACK = 0.001 # a zone's depth over the burial it lets: a float32 face reads a burial to 1e-8 +# P2's seats, (y, z): the deep four-bar behind the knee and the bell crank in front of it +DEEP = {"a": (-0.45, 1.15), "rocker": (-0.2320142211320173, 0.4604939911625098), "p": (-0.43650046730511183, -0.017951928782268284), + "c": (0.06881023105761902, -0.3143743967236484), "d": (-0.43650046730511183, -0.017951928782268284)} +CRANK = {"a": (0.45, 1.15), "rocker": (0.3171126791600819, 0.3216537818398838), "p": (0.7282866960904424, 0.43261578669776135), + "c": (0.34929485118682846, 0.14862538079826304), "d": (0.48651463351122515, 0.49166254003196397)} +ROOTS = {"bell_crank": {"horn": (0.10, -0.40), "bracket": (0.10, 0.55)}, "four_bar": {"horn": (0.0, -0.42), "bracket": (-0.10, 0.55)}} +THIGH_FRONT, EMBED = 0.14, 0.01 # the thigh core's faces stand at y +-0.14; a foot runs this far into it +RAYS = [Vector(v).normalized() for v in ((0.5377, 0.6211, 0.5701), (-0.7071, 0.2903, 0.6447), (0.1873, -0.8011, -0.5684))] + + +def check(name, ok, detail=None): + RES["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail}) + + +def prism(outline, x0, x1): + """A closed shell: the convex (y, z) outline, counter-clockwise seen from +x, run from x0 to x1.""" + x0, x1 = min(x0, x1), max(x0, x1) + n = len(outline) + verts = [(x, y, z) for x in (x0, x1) for y, z in outline] + faces = [tuple(range(n - 1, -1, -1)), tuple(range(n, 2 * n))] + [(k, (k + 1) % n, n + (k + 1) % n, n + k) for k in range(n)] + return np.array(verts, dtype=float), faces + + +def box(centre, size): + (cx, cy, cz), (sx, sy, sz) = centre, size + return prism([(cy - sy / 2, cz - sz / 2), (cy + sy / 2, cz - sz / 2), (cy + sy / 2, cz + sz / 2), (cy - sy / 2, cz + sz / 2)], cx - sx / 2, cx + sx / 2) + + +def disc(at, r, x0, x1, n=32): + return prism([(at[0] + r * math.cos(2 * math.pi * k / n), at[1] + r * math.sin(2 * math.pi * k / n)) for k in range(n)], x0, x1) + + +def bar(p, q, w, x0, x1, n=10): + """A link plate: the stadium of half width w about the segment p -> q.""" + p, q = np.array(p, float), np.array(q, float) + base = math.atan2(*((q - p) / np.linalg.norm(q - p))[::-1]) + pts = [(c[0] + w * math.cos(a0 + math.pi * k / n), c[1] + w * math.sin(a0 + math.pi * k / n)) for c, a0 in ((q, base - math.pi / 2), (p, base + math.pi / 2)) for k in range(n + 1)] + return prism(pts, x0, x1) + + +def knee(kind, pn, links=True): + """part -> [shell], part -> body: the knee at rest (angle 0, every frame the parent's).""" + shells, front = {}, kind == "bell_crank" + + def add(part, *made): + shells.setdefault(part, []).extend(made) + r, gap, cheek = 0.25, 0.22, 0.07 + half = gap / 2 + cheek + add("parent.body", box((0, 0, 0.725), (0.26, 2 * THIGH_FRONT, 0.85)), box((0, 0.185, 0.725), (0.34, 0.06, 0.77)), box((0, 0, 0.2), (gap - 0.03, 0.24, 0.4)), + disc((0, 0), 0.9 * r, -(gap - 0.03) / 2, (gap - 0.03) / 2)) + outline = [(r * math.cos(math.radians(a)), r * math.sin(math.radians(a))) for a in range(0, 181, 15)] + [(-0.12, -0.95), (0.12, -0.95)] + add("child.body", box((0, 0, -0.72), (gap, 0.22, 0.46)), box((0, 0.15, -0.62), (2 * half + 0.06, 0.06, 0.58))) + Rk, P, C, A, D = (pn[k] for k in ("rocker", "p", "c", "a", "d")) + for s in (-1, 1): + add("child.body", prism(outline, s * gap / 2, s * half), disc((0, 0), 0.19, s * half, s * (half + 0.025)), box((s * (half + 0.03), 0.0, -0.62), (0.045, 0.2, 0.5))) + add("child.horn", bar(ROOTS[kind]["horn"], C, W_HORN, s * (half + 0.05), s * SLAB_C[0])) + add("parent.bracket", bar(ROOTS[kind]["bracket"], Rk, W_BRACKET, s * 0.13, s * SLAB_R[0])) + # the base clevis: cheeks about the pin and a foot that runs into the thigh's core, toward it + toward = -1.0 if front else 1.0 + foot = (A[0] + toward * 0.2, A[1]) + add("parent.seat", bar(A, foot, 1.7 * BORE, s * CHEEK[0], s * CHEEK[1])) + if links: + add("rocker.plate", bar(Rk, P, W_ROCKER, s * SLAB_R[0], s * SLAB_R[1])) + add("coupler.plate", bar(P, C, W_COUPLER, s * SLAB_C[0], s * SLAB_C[1])) + add("rocker.seat", disc(D, COLLAR, s * CHEEK[0], s * CHEEK[1])) # the eye's collars on its pin + if front: + add("rocker.plate", bar(Rk, D, W_ARM, s * SLAB_R[0], s * SLAB_R[1])) + face = toward * (THIGH_FRONT - EMBED) + add("parent.seat", box((0, 0.5 * (face + foot[0]), A[1]), (2 * CHEEK[1], abs(foot[0] - face), 3.4 * BORE))) + if links: + add("rocker.pin.R", disc(Rk, AXLE, -SLAB_R[1] - 0.015, SLAB_R[1] + 0.015)) + add("rocker.pin.p", disc(P, PIN, -SLAB_R[1] - 0.015, SLAB_R[1] + 0.015)) + add("coupler.pin.c", disc(C, PIN, -SLAB_C[1] - 0.015, SLAB_C[1] + 0.015)) + if front: + add("rocker.pin.d", disc(D, PIN, -SLAB_R[1] - 0.015, SLAB_R[1] + 0.015)) + return shells, {part: {"parent": "parent", "child": "child", "rocker": "rocker", "coupler": "coupler"}[part.split(".")[0]] for part in shells} + + +class Signed: + """distance(part, points): negative inside a part's shell (the depth below its nearest face), capped outside + only. Inside is the crossing parity of `rays` rays, by majority. An unknown part raises.""" + + def __init__(self, shells, cap=None, rays=3): + self.cap, self.asked, self.rays = cap, 0, RAYS[:rays] + self.trees = {part: [(BVHTree.FromPolygons(v.tolist(), f, epsilon=0.0), v.min(axis=0), v.max(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 = 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 + + +def near(ram, member): + return {"barrel": ram.barrel_r, "rod": ram.rod}.get(member, ram.link_r) + ram.gap + ram.spacing() / 2 + + +def parting(ram, w, degrees): + """How far from a pin a link parts from a plate of half width w that stands beside it on the pin, a plate's + thickness off along the axis, the two crossing at `degrees` at the least: where the link's axis is what a link + keeps from the plate's edge, and never less than the plate's round end.""" + lateral = math.sqrt(near(ram, "rocker") ** 2 - HALF ** 2) + return max((w + lateral) / math.sin(math.radians(min(degrees, 90.0))), w + near(ram, "rocker")) + + +def crossing(m, kind): + """The least angle, over the range, at which the rocker, the rocker arm and the coupler cross what stands beside + them: the bracket's bar at the pivot, the horn's at c (seen from the shin), each other at p.""" + p, n = R.pose(m, np.linspace(m.lo, m.hi, 126)), m.axis + + def least(a, b): + a, b = R._flat(a, n), R._flat(np.broadcast_to(b, a.shape), n) + return float(np.degrees(np.arccos(np.clip((a * b).sum(axis=1) / (np.linalg.norm(a, axis=1) * np.linalg.norm(b, axis=1)), -1.0, 1.0))).min()) + root = {key: np.array((0.0, *value)) for key, value in ROOTS[kind].items()} + seen = R._into(m, p, "child", p.P[:, None, :])[:, 0, :] + return {"rocker": least(p.P - m.rocker, root["bracket"] - m.rocker), "rocker arm": least(p.eye - m.rocker, root["bracket"] - m.rocker), + "coupler": least(seen - m.c, root["horn"] - m.c), "p": float(p.mu_p.min())} + + +def zones(m, ram, parts): + """Each member's zones. About a pin: the pin's, collar's or cheek's radius plus what the member keeps, as deep as + the pin where it runs through the member's eye and 0 beside a collar, a cheek, the bracket or the horn; a link's + own plate over its length, half its thickness deep; a plate beside a link as far as the two part. A depth that + is not 0 is stated SLACK over the burial.""" + kind, link, at = m.kind, near(ram, "rocker"), crossing(m, m.kind) + PIN, AXLE, HALF = (value + SLACK for value in (globals()["PIN"], globals()["AXLE"], globals()["HALF"])) + reach = {"pin": globals()["PIN"] + link, "axle": globals()["AXLE"] + link} + eye = "rocker.pin.d" if kind == "bell_crank" else "rocker.pin.p" + touch = {member: [("parent.seat", "a", 1.7 * BORE + near(ram, member), 0.0), ("rocker.seat", "d", COLLAR + near(ram, member), 0.0), + (eye, "d", globals()["PIN"] + near(ram, member), PIN if member == "rod" else 0.0)] for member in ("barrel", "rod")} + pivot = [("parent.bracket", "rocker", None, 0.0), ("rocker.pin.R", "rocker", reach["axle"], AXLE)] + touch["rocker"] = pivot + [("rocker.pin.p", "p", reach["pin"], PIN), ("rocker.plate", "rocker", 1.01 * m.lr, HALF), ("coupler.plate", "p", parting(ram, W_COUPLER, at["p"]), 0.0)] + touch["coupler"] = [("child.horn", "c", parting(ram, W_HORN, at["coupler"]), 0.0), ("coupler.pin.c", "c", reach["pin"], PIN), ("rocker.pin.p", "p", reach["pin"], PIN), + ("coupler.plate", "p", 1.01 * m.lc, HALF), ("rocker.plate", "p", parting(ram, W_ROCKER, at["p"]), 0.0)] + if kind == "bell_crank": + touch["rocker arm"] = pivot + [("rocker.pin.d", "d", reach["pin"], PIN), ("rocker.plate", "rocker", 1.01 * float(np.linalg.norm(R._flat(m.d - m.rocker, m.axis))), HALF)] + for member in ("rocker", "rocker arm"): + if member in touch: + touch[member][0] = ("parent.bracket", "rocker", parting(ram, W_BRACKET, at[member]), 0.0) + return {member: [zone for zone in given if zone[0] in parts] for member, given in touch.items()} + + +def pins3(pn, side=1.0, **moved): + at = {"a": 0.0, "p": 0.0, "d": 0.0, "rocker": side * X_R, "c": side * X_C, **moved} + return {k: (at[k], float(pn[k][0]), float(pn[k][1])) for k in pn} + + +def needs(m, ram, parts, distance, steps=49): + """(member, part) -> (pin, radius, depth): for every pair refused with nothing let, the least zone that lets it.""" + p = R.pose(m, np.linspace(m.lo, m.hi, steps)) + at = {"a": p.base, R.EYE[m.kind]: p.eye, "rocker": m.rocker, "p": p.P, "c": p.C} + step, out = ram.spacing(), {} + for member, label, start, end, radius, pins in R._members(m, ram, R.barrel_length(m, ram), 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] + for part, body in parts.items(): + got = distance(part, R._into(m, p, body, pts).reshape(-1, 3)).reshape(len(p.degrees), count) + bad = got < radius + ram.gap + step / 2 + if bad.any(): + best = None + for pin in pins: + across = np.linalg.norm(R._flat(pts - np.broadcast_to(at[pin], start.shape)[:, None, :], m.axis), axis=2) + reach = float(across[bad].max()) + if best is None or reach < best[1]: + best = (pin, reach, max(-float(got[across <= reach].min()), 0.0)) + out[(label, part)] = best + return out + + +def refused(f): + return sorted((pair, round(reading[0], 4), reading[1]) for pair, reading in f.pairs.items() if reading[0] < 0.0) + + +def label(member): + return member + "[0]" if member in ("barrel", "rod") else member + + +def hinge4(pivot, degrees): + return Matrix.Translation(Vector(pivot)) @ Matrix.Rotation(math.radians(degrees), 4, "X") @ Matrix.Translation(-Vector(pivot)) + + +def render(m, ram, f, shells, parts): + """The bell crank at 0, -62.5 and -125, each piece coloured by its part, the ram as the gate holds it.""" + scene = bpy.context.scene + colour = {"horn": (0.95, 0.45, 0.1, 1), "bracket": (0.15, 0.45, 0.9, 1), "plate": (0.75, 0.75, 0.78, 1), "seat": (0.55, 0.3, 0.6, 1), "pin": (0.9, 0.9, 0.3, 1)} + objects = [] + for part, made in shells.items(): + for k, (verts, faces) in enumerate(made): + me = bpy.data.meshes.new(f"{part}.{k}") + me.from_pydata(verts.tolist(), [], faces) + o = bpy.data.objects.new(me.name, me) + scene.collection.objects.link(o) + o.color = colour.get(part.split(".")[1], (0.33, 0.38, 0.24, 1) if parts[part] == "child" else (0.3, 0.32, 0.36, 1)) + objects.append((o, parts[part])) + + def tube(name, r, col): + me, bm = bpy.data.meshes.new(name), bmesh.new() + bmesh.ops.create_cone(bm, cap_ends=True, segments=24, radius1=r, radius2=r, depth=1.0) + bmesh.ops.translate(bm, verts=bm.verts[:], vec=(0, 0, 0.5)) + bm.to_mesh(me) + bm.free() + o = bpy.data.objects.new(name, me) + scene.collection.objects.link(o) + o.color = col + return o + barrel, rod = tube("ram.barrel", ram.barrel_r, (0.85, 0.15, 0.12, 1)), tube("ram.rod", ram.rod, (0.95, 0.95, 0.95, 1)) + scene.render.engine = "BLENDER_WORKBENCH" + scene.display.shading.light, scene.display.shading.color_type = "STUDIO", "OBJECT" + scene.display.shading.show_shadows = scene.display.shading.show_cavity = True + scene.render.resolution_x, scene.render.resolution_y, scene.render.film_transparent = 1400, 1500, False + scene.world = bpy.data.worlds.new("w") + scene.world.color = (0.82, 0.83, 0.85) + cam = bpy.data.objects.new("cam", bpy.data.cameras.new("cam")) + scene.collection.objects.link(cam) + cam.data.type, cam.data.ortho_scale = "ORTHO", 2.75 + target = Vector((0.0, 0.1, 0.12)) + cam.location = target + Vector((0.72, 0.62, 0.22)).normalized() * 8.0 + cam.rotation_euler = (target - cam.location).to_track_quat("-Z", "Y").to_euler() + scene.camera = cam + made = [] + for angle in (0.0, -62.5, -125.0): + p = R.pose(m, angle) + T = {"parent": Matrix.Identity(4), "child": hinge4((0, 0, 0), angle), "rocker": hinge4(m.rocker, math.degrees(p.phi[0])), + "coupler": Matrix.Translation(Vector(p.P[0] - m.p)) @ hinge4(m.p, math.degrees(p.psi[0]))} + for o, body in objects: + o.matrix_world = T[body] + u, base = Vector(p.u[0]), Vector(p.base[0]) + frame = u.to_track_quat("Z", "Y").to_matrix().to_4x4() + barrel.matrix_world = Matrix.Translation(base + u * ram.back) @ frame @ Matrix.Diagonal((1, 1, f.barrel, 1)) + rod.matrix_world = Matrix.Translation(base + u * (ram.back + f.barrel)) @ frame @ Matrix.Diagonal((1, 1, float(p.L[0]) - ram.back - f.barrel, 1)) + scene.render.filepath = f"{OUT}.r3_{abs(angle):g}".replace(".5", "p5") + ".png" + bpy.ops.render.render(write_still=True) + made.append(scene.render.filepath) + return made + + +try: + bpy.ops.wm.read_factory_settings(use_empty=True) + ram = R.Ram(BORE) + HINGE = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), -125.0, 0.0) + + SECTION[0] = "oracle" + shells, parts = knee("bell_crank", CRANK) + rows = [] + for name, part, point, depth in (("the thigh core's centre", "parent.body", (0.0, 0.0, 0.7), -0.13), ("0.02 inside the thigh's wall", "parent.body", (0.11, 0.0, 0.7), -0.02), + ("the shin's leg centre", "child.body", (0.0, 0.0, -0.7), -0.11), ("0.125 off the thigh's plate", "parent.body", (0.0, 0.34, 0.7), 0.125)): + capped, free = (float(Signed(shells, cap)(part, np.array([point]))[0]) for cap in (ram.reach(), None)) + rows.append((name, capped, free, abs(free - depth) < FLAT and capped == (free if depth < 0 else min(free, ram.reach())))) + check("inside-is-negative: a point inside a part reads its depth, negative, capped or not; a cap changes only what is outside", all(row[3] for row in rows), rows) + # a grid a plate's thickness off the rocker plates' inner face, over the knee: every point is 0.0225 or more from the + # 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) + 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 + 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())) + + SECTION[0] = "seat" + seat = np.concatenate([v for v, _ in shells["parent.seat"]]) + deepest = float(Signed(shells)("parent.body", seat).min()) + RES["readings"]["the base clevis's foot inside the thigh"] = deepest + check("the base clevis is seated: its foot runs 0.01 into the thigh's core, through the front plate", abs(deepest + EMBED) < FLAT, deepest) + + SECTION[0] = "bell crank" + winner = None + for side in (1.0, -1.0): + m = R.Mechanism("bell_crank", *HINGE, **pins3(CRANK, side), parts=parts) + touch = zones(m, ram, parts) + m = replace(m, touch=touch) + zoned = {(label(member), zone[0]) for member, given in touch.items() for zone in given} + t0 = time.perf_counter() + f = R._fit(m, ram, steps=49, distance=Signed(shells, ram.reach())) + seconds = time.perf_counter() - t0 + check(f"bell-crank-clears-on-meshes (side {side:+.0f}): over 0..-125 at 49 steps every member is clear of every part, 5 x {len(parts)} pairs, beside its pins by the record's zones", + f.ok and len(f.pairs) == 5 * len(parts) and set(f.allowed) == zoned, [f.report(), refused(f)]) + fine = R._fit(m, ram, steps=251, distance=Signed(shells)) + check(f"bell-crank-clears-on-meshes (side {side:+.0f}): and at 251 steps with the oracle uncapped", fine.ok, [fine.report(), refused(fine)]) + bare = R._fit(replace(m, touch={}), ram, steps=49, distance=Signed(shells, ram.reach())) + need = needs(m, ram, parts, Signed(shells)) + stated = {(label(member), zone[0]): zone for member, given in touch.items() for zone in given} + slack = {pair: (stated[pair][1] == pin and stated[pair][2] >= radius and stated[pair][3] >= depth) for pair, (pin, radius, depth) in need.items() if pair in stated} + check(f"zones (side {side:+.0f}): with nothing let the gate refuses, and only pairs the record zones; each stated zone takes in the least that lets its pair", + {pair for pair, _, _ in refused(bare)} == set(need) and set(need) <= zoned and all(slack.values()), [refused(bare), sorted(set(need) - zoned), [k for k, v in slack.items() if not v]]) + if side > 0: + winner = (m, f) + def free(fit): # the least margin of the pairs no zone lets: a zoned pair's is its depth's slack at the pin + return min(reading[0] for pair, reading in fit.pairs.items() if pair not in zoned) + RES["readings"].update({"bell crank: least margin of a pair with no zone, 251 steps uncapped": free(fine), + "bell crank: least margin of a zoned pair, 251 steps uncapped": min(reading[0] for pair, reading in fine.pairs.items() if pair in zoned), + "bell crank: pairs": len(f.pairs), "bell crank: zoned pairs": len(f.allowed), "bell crank: pairs refused with nothing let": len(refused(bare)), + "bell crank: seconds, 49 steps capped": seconds}) + RES["zones"] = {f"{pair[0]} | {pair[1]}": {"stated": list(stated[pair][1:]), "least": [pin, round(radius, 4), round(depth, 4)]} for pair, (pin, radius, depth) in sorted(need.items()) if pair in stated} + RES["least pairs"] = sorted((round(v[0], 4), v[1], k[0], k[1]) for k, v in fine.pairs.items() if k not in zoned)[:8] + + SECTION[0] = "zones end" + m, f = winner + for member, part in (("rocker", "parent.bracket"), ("coupler", "child.horn"), ("rod", "rocker.pin.d")): + short = {**m.touch, member: tuple((p_, pin, 0.5 * radius, depth) if p_ == part else (p_, pin, radius, depth) for p_, pin, radius, depth in m.touch[member])} + got = R._fit(replace(m, touch=short), ram, steps=49, distance=Signed(shells, ram.reach())) + check(f"a zone ends at its radius: {member}'s about {part} cut to half, that pair alone is refused", [pair for pair, _, _ in refused(got)] == [(label(member), part)], refused(got)) + + SECTION[0] = "moved x" + # Soul's let_hide probes: a link's place along the axis moved from beside the bracket or horn into it + for name, moved, expect in (("the rocker at x 0.25, inside the bracket's 0.13..0.35", {"rocker": 0.25}, {("rocker", "parent.bracket"), ("rocker arm", "parent.bracket")}), + ("the coupler at x 0.25, inside the horn's 0.23..0.31", {"c": 0.25}, {("coupler", "child.horn")}), + ("both", {"rocker": 0.25, "c": 0.25}, {("rocker", "parent.bracket"), ("rocker arm", "parent.bracket"), ("coupler", "child.horn")})): + mm = R.Mechanism("bell_crank", *HINGE, **pins3(CRANK, 1.0, **moved), parts=parts, touch=m.touch) + got = R._fit(mm, ram, steps=49, distance=Signed(shells, ram.reach())) + inside = {pair: reading for pair, reading, _ in refused(got)} + RES["readings"]["moved x: " + name] = min(inside.values()) if inside else 0.0 + check(f"a pin stood inside what it stands beside is refused: {name}", not got.ok and expect <= set(inside) and all(inside[pair] < -0.015 for pair in expect), refused(got)) + + SECTION[0] = "four bar" + shells4, parts4 = knee("four_bar", DEEP) + m4 = R.Mechanism("four_bar", *HINGE, **pins3(DEEP), parts=parts4) + m4 = replace(m4, touch=zones(m4, ram, parts4)) + f4 = R._fit(m4, ram, steps=49, distance=Signed(shells4, ram.reach())) + hit = {pair: reading for pair, reading, _ in refused(f4)} + RES["readings"]["four bar: barrel inside the shin's clearance"] = hit.get(("barrel[0]", "child.body"), 0.0) + check("third-body: the deep four-bar's ram is refused on the shin, which folds into it", not f4.ok and {("barrel[0]", "child.body"), ("rod[0]", "child.body")} <= set(hit) and f4.clear_at[2] == "child.body", refused(f4)) + + SECTION[0] = "search" + seats = {"rocker": [(X_R, *CRANK["rocker"]), (X_R, CRANK["rocker"][0] - 0.07, CRANK["rocker"][1] + 0.03)], "c": [(X_C, *CRANK["c"]), (X_C, CRANK["c"][0] - 0.05, CRANK["c"][1] + 0.03)], + "a": [(0.0, *CRANK["a"]), (0.0, 0.4, 1.0)], "link": (0.35, 0.5, 3), "d": (0.2, 0.26, 2)} + built = [] + + def world(mech): + made, bodies = knee("bell_crank", {k: (float(getattr(mech, k)[1]), float(getattr(mech, k)[2])) for k in CRANK}) + built.append(mech) + return bodies, zones(mech, ram, bodies), Signed(made, ram.reach()) + t0 = time.perf_counter() + s = R.search("bell_crank", {"pivot": HINGE[0], "axis": HINGE[1], "lo": -125, "hi": 0}, ram, seats, world=world, steps=49) + RES["readings"].update({"search: seconds": time.perf_counter() - t0, "search: candidates": s.tried, "search: pass the gates before clearance": s.fits, + "search: worlds built": len(built), "search: refused on their own parts": s.tally.get("clash", 0)}) + RES["search"] = {"report": s.report(), "seat": {k: np.round(v, 4).tolist() for k, v in (s.seat or {}).items()}, "tally": s.tally} + again = R._fit(s.best.m, ram, steps=251, distance=world(s.best.m)[2]) if s.found else None + check("search-holds-candidate-links: a seat grid about the probe's bell crank, each candidate met with the meshes its own pins place, runs to a fit that holds at 251 steps", + s.found and s.best.ok and len(built) - 1 == s.tally.get("clash", 0) + 1 and again.ok and len(s.best.pairs) == 5 * len(parts), [s.report(), refused(again) if again else None]) + + SECTION[0] = "render" + RES["renders"] = render(winner[0], ram, winner[1], shells, parts) + check("the bell crank is drawn at 0, -62.5 and -125", all(Path(path).is_file() for path in RES["renders"]), RES["renders"]) +except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, not a missing result file + check(f"no uncaught error in section: {SECTION[0]}", False, traceback.format_exc().splitlines()[-8:]) +finally: + RES["ok"] = all(c["ok"] for c in RES["checks"]) + RES["readings"] = {name: (float(f"{value:.3g}") if isinstance(value, float) else value) for name, value in sorted(RES["readings"].items())} + Path(OUT + ".result.json").write_text(json.dumps(RES, indent=1, default=str), encoding="utf-8") + for c in RES["checks"]: + print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) + print("READINGS", RES["readings"], flush=True) +sys.exit(0 if RES["ok"] else 1) diff --git a/surfaces/blender/tests/live/ram_knee.result.json b/surfaces/blender/tests/live/ram_knee.result.json new file mode 100644 index 0000000..6ad67fe --- /dev/null +++ b/surfaces/blender/tests/live/ram_knee.result.json @@ -0,0 +1,444 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "inside-is-negative: a point inside a part reads its depth, negative, capped or not; a cap changes only what is outside", + "ok": true, + "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", + "ok": true, + "detail": null + }, + { + "name": "three-rays: 4000 random points about a box are signed as the box signs them", + "ok": true, + "detail": null + }, + { + "name": "the base clevis is seated: its foot runs 0.01 into the thigh's core, through the front plate", + "ok": true, + "detail": null + }, + { + "name": "bell-crank-clears-on-meshes (side +1): over 0..-125 at 49 steps every member is clear of every part, 5 x 12 pairs, beside its pins by the record's zones", + "ok": true, + "detail": null + }, + { + "name": "bell-crank-clears-on-meshes (side +1): and at 251 steps with the oracle uncapped", + "ok": true, + "detail": null + }, + { + "name": "zones (side +1): with nothing let the gate refuses, and only pairs the record zones; each stated zone takes in the least that lets its pair", + "ok": true, + "detail": null + }, + { + "name": "bell-crank-clears-on-meshes (side -1): over 0..-125 at 49 steps every member is clear of every part, 5 x 12 pairs, beside its pins by the record's zones", + "ok": true, + "detail": null + }, + { + "name": "bell-crank-clears-on-meshes (side -1): and at 251 steps with the oracle uncapped", + "ok": true, + "detail": null + }, + { + "name": "zones (side -1): with nothing let the gate refuses, and only pairs the record zones; each stated zone takes in the least that lets its pair", + "ok": true, + "detail": null + }, + { + "name": "a zone ends at its radius: rocker's about parent.bracket cut to half, that pair alone is refused", + "ok": true, + "detail": null + }, + { + "name": "a zone ends at its radius: coupler's about child.horn cut to half, that pair alone is refused", + "ok": true, + "detail": null + }, + { + "name": "a zone ends at its radius: rod's about rocker.pin.d cut to half, that pair alone is refused", + "ok": true, + "detail": null + }, + { + "name": "a pin stood inside what it stands beside is refused: the rocker at x 0.25, inside the bracket's 0.13..0.35", + "ok": true, + "detail": null + }, + { + "name": "a pin stood inside what it stands beside is refused: the coupler at x 0.25, inside the horn's 0.23..0.31", + "ok": true, + "detail": null + }, + { + "name": "a pin stood inside what it stands beside is refused: both", + "ok": true, + "detail": null + }, + { + "name": "third-body: the deep four-bar's ram is refused on the shin, which folds into it", + "ok": true, + "detail": null + }, + { + "name": "search-holds-candidate-links: a seat grid about the probe's bell crank, each candidate met with the meshes its own pins place, runs to a fit that holds at 251 steps", + "ok": true, + "detail": null + }, + { + "name": "the bell crank is drawn at 0, -62.5 and -125", + "ok": true, + "detail": null + } + ], + "readings": { + "FLAT": 8.34e-09, + "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": 0.835, + "bell crank: zoned pairs": 20, + "four bar: barrel inside the shin's clearance": -0.122, + "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, + "search: candidates": 13824, + "search: pass the gates before clearance": 78, + "search: refused on their own parts": 21, + "search: seconds": 42.8, + "search: worlds built": 22, + "the base clevis's foot inside the thigh": -0.01 + }, + "zones": { + "barrel[0] | parent.seat": { + "stated": [ + "a", + 0.15645000000000003, + 0.0 + ], + "least": [ + "a", + 0.1222, + 0.0 + ] + }, + "barrel[0] | rocker.pin.d": { + "stated": [ + "d", + 0.11105000000000001, + 0.0 + ], + "least": [ + "d", + 0.1108, + 0.0 + ] + }, + "barrel[0] | rocker.seat": { + "stated": [ + "d", + 0.13505, + 0.0 + ], + "least": [ + "d", + 0.1263, + 0.0 + ] + }, + "coupler | child.horn": { + "stated": [ + "c", + 0.11195, + 0.0 + ], + "least": [ + "c", + 0.0947, + 0.0 + ] + }, + "coupler | coupler.pin.c": { + "stated": [ + "c", + 0.08795, + 0.027 + ], + "least": [ + "c", + 0.0474, + 0.0259 + ] + }, + "coupler | coupler.plate": { + "stated": [ + "p", + 0.47832364050530635, + 0.018500000000000016 + ], + "least": [ + "p", + 0.4736, + 0.0175 + ] + }, + "coupler | rocker.pin.p": { + "stated": [ + "p", + 0.08795, + 0.027 + ], + "least": [ + "p", + 0.0474, + 0.0259 + ] + }, + "coupler | rocker.plate": { + "stated": [ + "p", + 0.2818973893266964, + 0.0 + ], + "least": [ + "p", + 0.2368, + 0.0 + ] + }, + "rocker | coupler.plate": { + "stated": [ + "p", + 0.26840002998268986, + 0.0 + ], + "least": [ + "p", + 0.2366, + 0.0 + ] + }, + "rocker | parent.bracket": { + "stated": [ + "rocker", + 0.11695, + 0.0 + ], + "least": [ + "rocker", + 0.0946, + 0.0 + ] + }, + "rocker | rocker.pin.R": { + "stated": [ + "rocker", + 0.08995, + 0.029 + ], + "least": [ + "rocker", + 0.0473, + 0.0279 + ] + }, + "rocker | rocker.pin.p": { + "stated": [ + "p", + 0.08795, + 0.027 + ], + "least": [ + "p", + 0.0473, + 0.0259 + ] + }, + "rocker | rocker.plate": { + "stated": [ + "rocker", + 0.43014219644091495, + 0.018500000000000016 + ], + "least": [ + "rocker", + 0.4259, + 0.0175 + ] + }, + "rocker arm | parent.bracket": { + "stated": [ + "rocker", + 0.11695, + 0.0 + ], + "least": [ + "rocker", + 0.096, + 0.0 + ] + }, + "rocker arm | rocker.pin.R": { + "stated": [ + "rocker", + 0.08995, + 0.029 + ], + "least": [ + "rocker", + 0.048, + 0.0279 + ] + }, + "rocker arm | rocker.pin.d": { + "stated": [ + "d", + 0.08795, + 0.027 + ], + "least": [ + "d", + 0.048, + 0.0259 + ] + }, + "rocker arm | rocker.plate": { + "stated": [ + "rocker", + 0.24240000000000003, + 0.018500000000000016 + ], + "least": [ + "rocker", + 0.24, + 0.0175 + ] + }, + "rod[0] | rocker.pin.d": { + "stated": [ + "d", + 0.07955, + 0.027 + ], + "least": [ + "d", + 0.0794, + 0.0259 + ] + }, + "rod[0] | rocker.seat": { + "stated": [ + "d", + 0.10355, + 0.0 + ], + "least": [ + "d", + 0.0938, + 0.0 + ] + } + }, + "least pairs": [ + [ + 0.0336, + -125.0, + "rocker", + "rocker.pin.d" + ], + [ + 0.0393, + -125.0, + "rod[0]", + "rocker.pin.R" + ], + [ + 0.0417, + 0.0, + "coupler", + "parent.bracket" + ], + [ + 0.0579, + 0.0, + "rocker arm", + "coupler.plate" + ], + [ + 0.0687, + 0.0, + "coupler", + "rocker.pin.R" + ], + [ + 0.0766, + 0.0, + "rocker", + "child.horn" + ], + [ + 0.0766, + 0.0, + "rocker arm", + "child.horn" + ], + [ + 0.0808, + -125.0, + "coupler", + "child.body" + ] + ], + "search": { + "report": "78 of 13824 candidates pass the gates before clearance (failed: arm 1406, assembly 4800, clash 21, load 1355, stroke 1160, toggle 7352); best: OK: L 0.664..0.968, barrel 0.513, stroke 0.458 for travel 0.304 (spare +0.137), arm >= 0.090, rocker swing 99.9, pin load <= 0.73, transmission >= 17.3 deg, clear +0.000", + "seat": { + "a": [ + 0.0, + 0.45, + 1.15 + ], + "rocker": [ + 0.3675, + 0.3171, + 0.3217 + ], + "p": [ + 0.3675, + 0.7683, + 0.5372 + ], + "c": [ + 0.3275, + 0.3493, + 0.1486 + ], + "d": [ + 0.0, + 0.4303, + 0.4866 + ] + }, + "tally": { + "assembly": 4800, + "toggle": 7352, + "arm": 1406, + "stroke": 1160, + "load": 1355, + "clash": 21 + } + }, + "renders": [ + "F:/aeth-wt/fable-ramcore/scratch/h3/out/live3.r3_0.png", + "F:/aeth-wt/fable-ramcore/scratch/h3/out/live3.r3_62p5.png", + "F:/aeth-wt/fable-ramcore/scratch/h3/out/live3.r3_125.png" + ], + "ok": true +} \ No newline at end of file