brokkr_kitbash follows: a driven joint derived from its driver, by ratio or by closing a loop; joints v2 (cut kit-follows-2) #44

Merged
eureka merged 16 commits from nibu/kit-follows-2 into main 2026-12-03 16:15:35 +00:00
13 changed files with 2403 additions and 154 deletions

View file

@ -29,7 +29,7 @@
{"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"},
{"name": "visible", "type": "boolean", "default": true}
]},
{"name": "setObjectParent", "doc": "Parent an object to another.", "changesScene": true, "editModeSafe": false, "fields": [
{"name": "setObjectParent", "doc": "Parent an object to another. Refused, with nothing changed, when an enabled add-on that defines brokkr_parent_refusal(object, parent) answers a reason, which is the message: brokkr_kitbash refuses a parent that would give a loop that follows a second driver, and any parent of a part such a loop hangs from while the loop already has one (both drivers are named; hold the joint, make it follow the driver, or clear the loop first). An object no loop hangs from is not refused.", "changesScene": true, "editModeSafe": false, "fields": [
{"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"},
{"name": "parentObjectName", "type": "string", "doc": "empty or absent clears the parent"}
]},

View file

@ -47,6 +47,7 @@ HOST_SNAPSHOT_SCHEMA = "brokkr.blender.host_snapshot.v0"
HOST_ACTIONS_FILE = "brokkr_actions.json"
HOST_RESULT_LIMIT = 16000 # characters of a host operator's result copied into a receipt
KIT_RESERVED = "kit_" # brokkr_kitbash owns every custom property so named: kit_owned is the one test, setObjectCustomProperty refuses them and importGltf drops them
PARENT_REFUSAL = "brokkr_parent_refusal" # a function(object, parent or None) -> why not, or None, that an enabled add-on may define: setObjectParent asks each before it writes (brokkr_kitbash: its one-driver rule)
KIT_FROZEN = "kit_frozen" # brokkr_kitbash's frozen state (its FROZEN): read here only, to refuse an export that would apply a stack twice
COMMAND_INTENT_SCHEMA = "brokkr.blender.command_intent.v0"
COMMAND_RECEIPT_SCHEMA = "brokkr.blender.command_receipt.v0"
@ -934,6 +935,11 @@ class BrokkrBlenderTarget:
if ancestor.name == obj.name:
raise sa.ActionRefused(f"{obj.name!r} cannot be parented to itself or to one of its own children.")
ancestor = getattr(ancestor, "parent", None)
for module in self.bpy.context.preferences.addons.keys(): # an enabled add-on that owns a rule over parents is asked before the write
refusal = getattr(sys.modules.get(module), PARENT_REFUSAL, None)
reason = refusal(obj, parent) if callable(refusal) else None
if reason:
raise sa.ActionRefused(reason)
obj.parent = parent
return self._receipt(command, "accepted", "Blender object parent updated.", obj.name)

View file

@ -70,8 +70,17 @@ joints and report never list it, and a roll of its host carries it by Blender's
Connections are a tree. A loop (a brace from one branch to another) is closed by a closure: three ID properties
on the closing part, kit_close_socket, kit_close_to (a pointer to the other part) and kit_close_to_socket. close
writes them, only when the two sockets already meet, and writes nothing else; detach clears them. Nothing here
solves a loop: a closure never places a part, and a report says how far its two sockets stand apart.
writes them, only when the two sockets already meet, and writes nothing else; detach clears them. A closure never
places a part, and a report says how far its two sockets stand apart.
A connection may follow another: kit_follows on the follower (a ratio k and offset, or a loop) and kit_follows_driver,
a pointer to the driver. A follower's kit_roll or kit_slide is then derived: by k x the driver's value + offset, or,
for the closing part of a loop and its parent, by solving the two so the closure holds (core.close_loop, over the
kit's socket frames at stored params: no pin is stored). pose() derives every follower of a driver in the driver's
own action (driven) and write_connections writes them with it, all or none; roll, aim, reach and slide on a follower
are refused. A follower has one driver and a driver is never a follower; follow refuses a loop whose two ends
depend on any joint that is not its driver, a follower of its driver or held by limits of one value, so one driver's
pose is all a loop's value is a function of. No Blender driver or constraint is made.
"""
bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0), "blender": (5, 3, 0),
"category": "Object", "description": "Parametric machine parts from kits, with socket frames; agent-callable through Brokkr."}
@ -98,13 +107,14 @@ from . import core, plate, route
KIT, PART, PARAMS = "kit_kit", "kit_part", "kit_params"
SOCKET, PARENT_SOCKET, ROLL = "kit_socket", "kit_parent_socket", "kit_roll"
SLIDE, LIMIT_MIN, LIMIT_MAX, MECHANISM, COMPLIANCE = "kit_slide", "kit_min", "kit_max", "kit_mechanism", "kit_compliance" # a connection's joint record; write_connection is its one writer
RECORD = (SLIDE, LIMIT_MIN, LIMIT_MAX, MECHANISM, COMPLIANCE)
FOLLOWS, FOLLOWS_DRIVER = "kit_follows", "kit_follows_driver" # on a follower's connection: what its value is derived from, as JSON, and an ID pointer to the driver; write_connections is their one writer
RECORD = (SLIDE, LIMIT_MIN, LIMIT_MAX, MECHANISM, COMPLIANCE, FOLLOWS, FOLLOWS_DRIVER)
LABEL = r"[a-z0-9_]{1,32}" # a mechanism label
TURN, TRAVEL, HERTZ, DAMPING = 360.0, 10.0, 30.0, 2.0 # what a joint record may state: degrees a revolute joint's limits span and stand from 0, metres a prismatic one's stand from 0, a compliance's hertz and damping ratio
FROZEN = "kit_frozen" # on a frozen object: an ID pointer to its live mesh; its presence is the frozen state. hold writes it and nothing else does
KEPT = "kit_kept" # on a live mesh a frozen object holds: an ID pointer to that object's frozen mesh, beside the fake user that keeps the live mesh through a purge. hold writes both
CLOSE, CLOSE_TO, CLOSE_TO_SOCKET = "kit_close_socket", "kit_close_to", "kit_close_to_socket"
HELD = 1e-5 # a connection or a closure holds when its residual is at most this (as RIGID)
HELD = core.HELD # a connection or a closure holds when its residual is at most this (as RIGID)
BEVEL = "Kit Bevel"
CUTTERS = "cutters" # the kit whose parts cut places
OPERATIONS = ("DIFFERENCE", "UNION", "INTERSECT") # a target's Boolean modifiers, "Kit " + operation.title(), in the order they are evaluated
@ -123,6 +133,7 @@ HOSE_OFFSETS = ((0.0, 0.0, 0.0), (0.5, 0.5, 0.5), (0.31, 0.67, 0.13)) # of a st
HOSE_FINEST = 0.005 # metres: the least step, and the least a refused step is halved to for one more round of seeds
HOSE_SEGMENTS = 12 # sides of a hose, a ferrule and a clamp's pad
ROLL_STEP = 5.0 # degrees between the rolls of a joint's range that hose measures first: the step an assembly's clearance is read at
FOLLOW_SLIDE_STEP = 0.02 # metres a prismatic driver moves between the solves of the loops that follow it, as ROLL_STEP degrees for a revolute one: a rule, 0.044 m is what a 0.5 m crank's pin moves in 5 degrees
PLATE = "kit_plate" # on a hard plate: its checked row with side and prefix, as JSON; its presence admits a rebuild, and nothing reads it to decide geometry
PLATE_KIND = "plate_kind" # "hard" on a hard plate: report and paint data; plates is its one writer there
ANCHOR = "kit_anchor" # on a plate's anchor empty: {kind, id, height} of a mark or {kind, name} of a hose port, as JSON
@ -224,23 +235,60 @@ def dof(parent, parent_socket: dict):
return core.load_kit(str(parent.get(KIT, "")))["socketTypes"][parent_socket["type"]].get("dof")
def joint_record(obj) -> dict:
"""The joint record a child's connection states, {limits: (lo, hi) or None, mechanism, compliance}: degrees of
its roll on a revolute joint, metres of its slide on a prismatic one. Every report, the joints report, the
poses and hose read it here. A value written by hand that write_connection would not have written reads None."""
lo, hi, label, spring = obj.get(LIMIT_MIN), obj.get(LIMIT_MAX), obj.get(MECHANISM), None
STANDS = object() # connection_kind's and joint_record's `parent` when it is the one the child has
def connection_kind(obj, kits=None, parent=STANDS) -> tuple:
"""(DOF kind, parent socket type) of the connection a child states, from the parent's kit by the socket's name
alone (a socket's type is the same at every params), or (None, None) when it cannot be read: no parent, a
parent that is no kit part, a socket the part does not have. `kits` is kit_part_of's: one call's read of each
kit file. `parent` is the parent the child is about to be given (parent_refusal), read in place of its own."""
try:
parent = obj.parent if parent is STANDS else parent
name, kits = str(parent.get(KIT, "")), {} if kits is None else kits
if name not in kits:
kits[name] = core.load_kit(name)
kit = kits[name]
socket_type = next(s["type"] for s in core.part(kit, str(parent[PART]))["sockets"] if s["name"] == obj.get(PARENT_SOCKET))
return kit["socketTypes"][socket_type].get("dof"), socket_type
except (AttributeError, KeyError, StopIteration, core.KitError):
return None, None
def joint_record(obj, kits=None, parent=STANDS) -> dict:
"""The joint record a child's connection states, {limits: (lo, hi) or None, mechanism, compliance, follows}:
degrees of its roll on a revolute joint, metres of its slide on a prismatic one; follows is None or {driver (the
object, None once it is gone, as closure's other part), kind 'ratio' | 'loop', k, offset}. Every report, the joints report, the
poses and hose read it here. A value written by hand that write_connections would not have written reads None:
one that is not of its shape, and one record_refusal refuses for this connection's DOF kind (a compliance on a
revolute joint), so no report emits it and the next write clears it. `parent` is connection_kind's."""
lo, hi, label, spring, follows = obj.get(LIMIT_MIN), obj.get(LIMIT_MAX), obj.get(MECHANISM), None, None
with contextlib.suppress(ValueError, TypeError):
spring = json.loads(obj.get(COMPLIANCE, "null"))
return {"limits": (float(lo), float(hi)) if core.finite(lo) and core.finite(hi) and lo <= hi else None,
"mechanism": label if isinstance(label, str) and re.fullmatch(LABEL, label) else None,
"compliance": spring if isinstance(spring, dict) and set(spring) == {"hertz", "damping_ratio"} and all(core.finite(v) for v in spring.values()) else None}
with contextlib.suppress(ValueError, TypeError):
follows = json.loads(obj.get(FOLLOWS, "null"))
ratio = (isinstance(follows, dict) and set(follows) == {"kind", "k", "offset"} and follows["kind"] == "ratio"
and core.finite(follows["k"]) and follows["k"] != 0 and core.finite(follows["offset"]))
driver = obj.get(FOLLOWS_DRIVER)
record = {"limits": (float(lo), float(hi)) if core.finite(lo) and core.finite(hi) and lo <= hi else None,
"mechanism": label if isinstance(label, str) and re.fullmatch(LABEL, label) else None,
"compliance": spring if isinstance(spring, dict) and set(spring) == {"hertz", "damping_ratio"} and all(core.finite(v) for v in spring.values()) else None,
"follows": {"driver": driver if isinstance(driver, bpy.types.Object) and driver.users_collection else None, "kind": follows["kind"],
"k": float(follows["k"]) if ratio else None, "offset": float(follows["offset"]) if ratio else None}
if ratio or follows == {"kind": "loop"} else None}
kind, socket_type = connection_kind(obj, kits, parent)
for field in ("limits", "mechanism", "compliance", "follows"): # limits first: a compliance is read beside the limits that stand
alone = {**dict.fromkeys(record), "limits": record["limits"] if field == "compliance" else None, field: record[field]}
if record[field] is not None and record_refusal(kind, socket_type, alone) is not None:
record[field] = None
return record
def record_refusal(kind, socket_type: str, record: dict) -> str | None:
"""None when a connection of this DOF kind may carry the record, else why not."""
limits, spring = record["limits"], record["compliance"]
if kind is None:
return (f"socket type {socket_type!r} states no dof: the connection is rigid and carries no limits, mechanism or compliance"
return (f"socket type {socket_type!r} states no dof: the connection is rigid and carries no limits, mechanism, compliance or follows"
if any(value is not None for value in record.values()) else None)
if limits is not None and kind == "revolute" and (limits[1] - limits[0] > TURN or max(abs(limits[0]), abs(limits[1])) > TURN):
return f"limits {limits[0]:.6g} to {limits[1]:.6g}: a revolute joint's span at most {TURN:g} degrees, each end within {TURN:g} of 0"
@ -332,38 +380,347 @@ def seat(child, basis) -> None:
child.matrix_basis = Matrix(np.asarray(basis).tolist())
def connection_checks(entries) -> list:
"""What write_connections writes for `entries`, each checked: (child, parent, sockets, socket, parent socket,
roll, slide, DOF kind, record). An entry is (child, parent, mated()'s sockets for `stated`, stated, the joint
record to state or None to keep the one the child states). Refuses, naming the connection, a record its DOF
kind may not carry (record_refusal), a slide on a connection that is not prismatic, and a value with no
representative inside the limits (core.within), naming value and limits; the value answered is that
representative. Writes nothing."""
checked = []
for child, parent, sockets, stated, record in entries:
kind, (socket, parent_socket, roll, slide) = dof(parent, sockets[0]), stated
record, here = joint_record(child) if record is None else record, f"{child.name!r} on {parent.name!r}"
refusal = record_refusal(kind, sockets[0]["type"], record)
if refusal is None and kind != "prismatic" and slide != 0.0:
refusal = f"socket type {sockets[0]['type']!r} is {kind or 'rigid'}: only a prismatic connection slides"
if refusal is None and record["limits"] is not None:
value = roll if kind == "revolute" else slide
inside = core.within(value, *record["limits"], kind == "revolute")
if inside is None:
refusal = (f"its {'roll' if kind == 'revolute' else 'slide'} {value:.6g} is outside the joint's limits "
f"{record['limits'][0]:.6g} to {record['limits'][1]:.6g}")
roll, slide = (inside, slide) if kind == "revolute" else (roll, inside)
if refusal:
raise Refused(f"{here}: {refusal}; nothing changed.")
checked.append((child, parent, sockets, socket, parent_socket, roll, slide, kind, record))
return checked
def write_checks(entries) -> list:
"""Every check a write of `entries` must pass, and what it writes (connection_checks): each entry's own, then
the one-driver rule over the scene as the entries would leave it (one_driver). write_connections asks before
it writes; set_params asks before it rebuilds a mesh, so each refusal leaves the scene as it stood."""
checked = connection_checks(entries)
one_driver({child: (parent, kind, record) for child, parent, _, _, _, _, _, kind, record in checked})
return checked
def write_connections(entries) -> None:
"""State connections and seat them, all or none: each child's parent, its derived matrix_basis, its three
properties and its joint record, kit_follows and its driver pointer with it. Every entry is checked
(write_checks) before any is written, so one refusal leaves every part as it stood. attach, set_params,
roll, aim, reach, slide, joint and follow write a connection here and nowhere else, so what a joint record may
be, and that a follower's value is written with its driver's, is decided here. So is the one-driver rule:
write_checks reads the scene as these entries would leave it (one_driver) before any is written, whatever the
action."""
for child, parent, sockets, socket, parent_socket, roll, slide, kind, record in write_checks(entries):
child.parent = parent
seat(child, core.mate(*sockets, roll, slide))
child[SOCKET], child[PARENT_SOCKET], child[ROLL] = socket, parent_socket, roll
(lo, hi), follows = record["limits"] or (None, None), record["follows"]
for key, value in ((SLIDE, slide if kind == "prismatic" else None), (LIMIT_MIN, lo), (LIMIT_MAX, hi), (MECHANISM, record["mechanism"]),
(COMPLIANCE, record["compliance"] and json.dumps(record["compliance"], sort_keys=True))):
if value is not None:
child[key] = value
elif key in child:
del child[key]
for key in (FOLLOWS, FOLLOWS_DRIVER):
if key in child and (follows is None or follows["driver"] is None and key == FOLLOWS_DRIVER):
del child[key]
if follows is not None:
child[FOLLOWS] = json.dumps({key: follows[key] for key in ("kind", "k", "offset") if follows[key] is not None}, sort_keys=True)
if follows is not None and follows["driver"] is not None:
child[FOLLOWS_DRIVER] = follows["driver"]
def write_connection(child, parent, sockets, stated, record=None) -> None:
"""State a connection and seat it: the child's parent, its derived matrix_basis, its three properties and its
joint record. `sockets` is mated()'s answer for `stated`; `record` is the joint record to state (joint_record's
shape), None to keep the one the child states. attach, roll, aim, reach, slide and joint write a connection
here and nowhere else, so what a joint record may be is decided here: before anything is written it refuses a
record its DOF kind may not carry (record_refusal), a slide on a connection that is not prismatic, and a value
with no representative inside the limits (core.within), naming value and limits; the value written is that
representative."""
kind, (socket, parent_socket, roll, slide) = dof(parent, sockets[0]), stated
record, here = joint_record(child) if record is None else record, f"{child.name!r} on {parent.name!r}"
refusal = record_refusal(kind, sockets[0]["type"], record)
if refusal is None and kind != "prismatic" and slide != 0.0:
refusal = f"socket type {sockets[0]['type']!r} is {kind or 'rigid'}: only a prismatic connection slides"
if refusal is None and record["limits"] is not None:
value = roll if kind == "revolute" else slide
inside = core.within(value, *record["limits"], kind == "revolute")
if inside is None:
refusal = (f"its {'roll' if kind == 'revolute' else 'slide'} {value:.6g} is outside the joint's limits "
f"{record['limits'][0]:.6g} to {record['limits'][1]:.6g}")
roll, slide = (inside, slide) if kind == "revolute" else (roll, inside)
if refusal:
raise Refused(f"{here}: {refusal}; nothing changed.")
child.parent = parent
seat(child, core.mate(*sockets, roll, slide))
child[SOCKET], child[PARENT_SOCKET], child[ROLL] = socket, parent_socket, roll
lo, hi = record["limits"] or (None, None)
for key, value in ((SLIDE, slide if kind == "prismatic" else None), (LIMIT_MIN, lo), (LIMIT_MAX, hi), (MECHANISM, record["mechanism"]),
(COMPLIANCE, record["compliance"] and json.dumps(record["compliance"], sort_keys=True))):
if value is not None:
child[key] = value
elif key in child:
del child[key]
"""write_connections for one connection."""
write_connections([(child, parent, sockets, stated, record)])
def followers(driver) -> list:
"""The parts whose connection states that it follows `driver`, by name."""
return sorted((o for o in bpy.data.objects if o.get(FOLLOWS_DRIVER) == driver and o.users_collection and joint_record(o)["follows"] is not None),
key=lambda o: o.name)
def loop_drivers(closing, parent=None, joint=None):
"""What the two ends of the loop `closing` closes depend on beside its driver: (driver, (the base, the part
closed on), {another driver: why}), or None for a loop that is derived by nothing (its driver is gone or states
no DOF connection, it closes on nothing, or its parent does not follow with it). Each revolute or prismatic
joint between an end and the nearest part both ends hang from (or the root, when they share none) is the
driver, follows it, or is held by limits of one value; one that follows another driver, or follows nothing and
has travel, is another driver. A joint both ends hang from moves them together and is not counted. The one
reading of the rule: one_driver refuses a write by it, reading the scene as the write would leave it (`parent`
and `joint` are then its own), and a report reads the scene as it stands (follows_report, the joints
report's manyDrivers), so a loop with a second driver that no write made is told by every read of it."""
if parent is None:
def parent(o):
return o.parent
if joint is None:
def joint(o):
kind = connection_kind(o)[0]
record = joint_record(o) if kind is not None else None
return (kind, record["limits"], record["follows"]) if kind is not None else (None, None, None)
follows, upper, to = joint(closing)[2], parent(closing), closure(closing)[1]
driver = follows["driver"] if follows is not None and follows["kind"] == "loop" else None
if driver is None or to is None or upper is None or parent(upper) is None or joint(driver)[0] is None or joint(upper)[2] != follows:
return None
ends, chains = (parent(upper), to), [[], []] # each end and what it hangs from, up to the root
for found, o in zip(chains, ends):
while o is not None:
found.append(o)
o = parent(o)
others = {} # {a part whose pose moves one end against the other, and is not the driver: why}
for o in (o for found in chains for o in found if not (o in chains[0] and o in chains[1])):
kind, limits, its = joint(o)
if kind is None or o == driver or its is not None and its["driver"] in (None, driver):
continue
if its is not None:
others.setdefault(its["driver"], f"{o.name!r} follows it")
elif limits is None or limits[0] < limits[1]: # limits of one value hold a joint still
others.setdefault(o, "it follows nothing and its joint has travel, so it is posed by hand")
return driver, ends, dict(sorted(others.items(), key=lambda item: item[0].name))
def one_driver(stating: dict) -> None:
"""The one-driver rule, over each loop a write touches, as it would stand after the write: the driver of a loop
is the only input its two ends (the parent follower's parent, and the part closed on) depend on. `stating` is
{part: (its parent, its connection's DOF kind, its joint record)} for each connection about to be written, and
(None, None, None) for one about to be cleared; every other part is read from the scene. A write touches a loop
when a part in `stating` is the closing follower, the part closed on or the driver, or one of those hangs from
it: nothing else can change what the loop's ends depend on, so no other loop is read, and a loop that already
has a second driver refuses the writes that touch it and no others. Each revolute or
prismatic joint between an end and the nearest part both ends hang from (or the root, when they share none) is
the driver, follows it, or is held by limits of one value: a pin with no travel, which is what a real torque
link's lug is, there to stop the rod rolling in its barrel. A joint there that follows another driver, or that
follows nothing and has travel, is a second driver: a pose of it would open the loop, so the write is refused
naming the loop's driver and each other one. A joint both ends hang from moves them together and is not
counted. A loop whose driver is gone or states no DOF connection is derived by nothing and is not read; it is
read again by the attach that gives the driver a connection. write_checks (every write of a connection,
and set_params before it rebuilds a mesh), detach and parent_refusal (Brokkr's setObjectParent) ask here
before they write, so no action (attach, detach, clearing a follower, limits widened or cleared, any pose, a
new follow, set_params, a new parent) gives a loop a second driver, and a loop edited by hand into one is
refused the next write that touches it. Which joints are drivers is loop_drivers' reading, the one the reports
take of the scene as it stands."""
known, kits, hangs = {}, {}, {} # each part's joint and each kit file are read once; hangs: {part: whether it, or a part it hangs from, is in stating}
def parent(o):
return stating[o][0] if o in stating else o.parent
def joint(o) -> tuple:
"""(DOF kind, limits, follows) of the connection a part would state."""
if o not in known:
kind, record = stating[o][1:] if o in stating else (connection_kind(o, kits)[0], None)
if kind is not None and o not in stating:
record = joint_record(o, kits)
known[o] = (kind, record["limits"], record["follows"]) if kind is not None else (None, None, None)
return known[o]
def touched(o) -> bool:
"""Whether a part, or one it hangs from, is in `stating`: each part is walked once a call."""
walked = []
while isinstance(o, bpy.types.Object) and o not in hangs and o not in stating:
walked.append(o)
o = parent(o)
answer = isinstance(o, bpy.types.Object) and (o in stating or hangs[o])
hangs.update(dict.fromkeys(walked, answer))
return answer
for closing in sorted((o for o in bpy.data.objects if CLOSE in o and (FOLLOWS in o or o in stating)), key=lambda o: o.name):
if not (touched(closing) or touched(closing.get(CLOSE_TO)) or touched(closing.get(FOLLOWS_DRIVER))) or not closing.users_collection:
continue # this write changes nothing the loop's ends depend on (the pointers are read as stored: users_collection searches the scene, so it is asked of a touched loop alone)
driver, ends, others = loop_drivers(closing, parent, joint) or (None, None, None)
if others:
raise Refused(f"the two ends of the loop {closing.name!r} closes, {ends[0].name!r} (the base) and {ends[1].name!r} (closed on), depend on more than one driver: {driver.name!r} and "
f"{', '.join(f'{o.name!r} ({why})' for o, why in others.items())}. A follower takes its value from "
"one driver, and a pose of another would open the loop: every joint between the two ends is the driver, follows it, or is held by "
f"limits of one value. Give it that first, or clear the loop (brokkr_kitbash.follow on {closing.name!r} with record null); nothing changed.")
def brokkr_parent_refusal(obj, parent) -> str | None:
"""Why an object may not be given `parent` (None clears it), or None when it may: the one-driver rule over the
loops the object is part of or stands above (one_driver), as they would stand, the object's stated connection
read on its new parent. An object no loop hangs from is given any parent, whatever else the scene holds. Brokkr's setObjectParent asks
every enabled add-on that defines this name before it writes a parent, so a new parent that would give a
stated loop a second driver is refused there and then. Nothing else is asked: a parent that only leaves a
connection not holding is drift, and reports show it."""
kind = connection_kind(obj, None, parent)[0] if SOCKET in obj else None
try:
one_driver({obj: (parent, kind, joint_record(obj, None, parent) if kind is not None else None)})
except (Refused, core.KitError) as error:
return str(error)
return None
def loop_pair(obj, stating=None):
"""(the parent follower, the closing follower) of the loop a loop follower is one of, or None when it has no
partner. The closing follower states the closure and its parent is the other: both follow one driver as a
loop, and the parent follower states no closure (follow and close keep it so)."""
def loop_of(o):
follows = (stating or {}).get(o) or joint_record(o)["follows"]
return follows["driver"] if follows is not None and follows["kind"] == "loop" else None
driver = loop_of(obj)
if driver is None:
return None
if CLOSE in obj:
return (obj.parent, obj) if obj.parent is not None and CLOSE not in obj.parent and loop_of(obj.parent) == driver else None
closing = [child for child in sorted(attached(obj), key=lambda o: o.name) if CLOSE in child and loop_of(child) == driver]
return (obj, closing[0]) if closing else None
def driven(driver, sockets, stated, roll: float, slide: float, record, stating=None) -> tuple[list, list]:
"""(the entries write_connections takes, [{part, value}]) for a connection given a new value and everything
that follows it: the one place a follower's value is derived. `stating` is {part: follows} for followers a
follow is about to state. With no follower the entry is the connection's own. With some, the driver steps from
its stated value to the new one in ceil(|change| / step) steps (ROLL_STEP degrees, FOLLOW_SLIDE_STEP metres; at
least one, so posing a driver where it stands derives its followers again), and each step places ratio followers
(k x the driver's value + offset) and then solves each loop (core.close_loop, seeded by the step before) in an
order where a loop's base and the part it closes on are placed before it. Worlds are composed from stated mates
and the scene's matrices; nothing is written. Only the last step is answered. Refuses a ratio whose driver
states no limits, a loop without its partner or its closure, loops that wait on each other, and what close_loop
refuses, naming the driver's value and the closing part."""
stating, kits = stating or {}, {}
own = (driver, driver.parent, sockets, (stated[0], stated[1], roll, slide), record)
found = sorted({*followers(driver), *stating}, key=lambda o: o.name)
kind = dof(driver.parent, sockets[0])
if not found or kind is None:
return [own], []
*_, roll, slide, _, record = connection_checks([own])[0] # the driver's value as it will be written, or its refusal
revolute = kind == "revolute"
old, new = (stated[2], roll) if revolute else (stated[3], slide)
change = core._wrapped(new - old) if revolute and record["limits"] is None else new - old
count = max(1, math.ceil(abs(change) / (ROLL_STEP if revolute else FOLLOW_SLIDE_STEP)))
def read(obj):
part, built = built_part(obj, kits)
said = link(obj)
if said is None or obj.parent is None:
raise Refused(f"{obj.name!r} follows {driver.name!r} and states no connection: brokkr_kitbash.follow with record null clears it; nothing changed.")
mates = mated(obj.parent, *built_part(obj.parent, kits), obj, part, built, said)
return mates, dof(obj.parent, mates[0]), said, {**joint_record(obj), **({"follows": stating[obj]} if obj in stating else {})}
links = {obj: read(obj) for obj in found}
links[driver] = (sockets, kind, stated, record)
ratios, loops = [obj for obj in found if links[obj][3]["follows"]["kind"] == "ratio"], []
if ratios and record["limits"] is None:
raise Refused(f"{driver.name!r} on {driver.parent.name!r}: {ratios[0].name!r} follows it by ratio, and a ratio's driver states limits (its value is then "
"one number, not one of many a turn apart): give it limits with brokkr_kitbash.joint; nothing changed.")
for obj in found:
if obj in ratios or CLOSE not in obj and loop_pair(obj, stating) is not None:
continue
pair, closing = loop_pair(obj, stating), closure(obj)
if pair is None or closing is None or closing[1] is None:
raise Refused(f"{obj.name!r} follows {driver.name!r} as a loop and has no {'partner (a closing part and its parent, both following the driver)' if pair is None else 'part to close on'}: "
"brokkr_kitbash.follow with record null clears it; nothing changed.")
other_part, other_built = built_part(closing[1], kits)
there, here = mated(closing[1], other_part, other_built, obj, *built_part(obj, kits), (closing[0], closing[2], 0.0, 0.0), "closing on")
joints = [({**links[o][0][0], "matrix": links[o][0][0]["matrix"] @ core._roll(links[o][2][2])} if links[o][1] == "prismatic" else links[o][0][0],
links[o][0][1], links[o][1]) for o in pair]
loops.append({"pair": pair, "base": pair[0].parent, "to": closing[1], "there": there, "here": here, "joints": joints,
"seed": tuple(links[o][2][2] if links[o][1] == "revolute" else links[o][2][3] for o in pair)})
def above(obj) -> set:
found = set()
while obj is not None:
found.add(obj)
obj = obj.parent
return found
ordered, waiting = [], list(loops) # a loop waits on every loop one of whose pair is its base, the part it closes on, or above either
while waiting:
ready = [loop for loop in waiting if not any(set(other["pair"]) & (above(loop["base"]) | above(loop["to"])) for other in waiting if other is not loop)]
if not ready:
raise Refused(f"{driver.name!r}: the loops closing at {', '.join(repr(loop['pair'][1].name) for loop in waiting)} each wait on another: "
"a loop's base and the part it closes on are placed before it is solved; nothing changed.")
ordered.append(ready[0])
waiting.remove(ready[0])
values = {}
def world(obj, memo):
if obj not in memo:
if obj.parent is None:
memo[obj] = np.array(obj.matrix_world, dtype=np.float64)
elif obj in values:
memo[obj] = world(obj.parent, memo) @ core.mate(*links[obj][0], *values[obj])
else: # it moves with its parent as it stands on it
memo[obj] = world(obj.parent, memo) @ np.linalg.inv(np.array(obj.parent.matrix_world, dtype=np.float64)) @ np.array(obj.matrix_world, dtype=np.float64)
return memo[obj]
def valued(obj, value):
return (value, links[obj][2][3]) if links[obj][1] == "revolute" else (links[obj][2][2], value)
for step in range(1, count + 1):
at = new if step == count else old + change * step / count
values = {driver: valued(driver, at)}
for obj in ratios:
values[obj] = valued(obj, links[obj][3]["follows"]["k"] * at + links[obj][3]["follows"]["offset"])
for loop in ordered:
memo = {}
try:
loop["seed"], _ = core.close_loop(world(loop["base"], memo), loop["joints"], loop["here"], world(loop["to"], memo) @ loop["there"]["matrix"], loop["seed"])
except core.KitError as error:
raise Refused(f"{driver.name!r} at {at:.6g}: the loop {loop['pair'][1].name!r} closes on {loop['to'].name!r} ({loop['pair'][0].name!r} and "
f"{loop['pair'][1].name!r} follow): {error}; nothing changed.") from None
for obj, value in zip(loop["pair"], loop["seed"]):
values[obj] = valued(obj, value)
entries, moved = [own], []
for obj in (*ratios, *(obj for loop in ordered for obj in loop["pair"])):
mates, its_kind, said, its_record = links[obj]
value = values[obj][0] if its_kind == "revolute" else values[obj][1]
if its_kind == "revolute" and its_record["limits"] is None:
value = core._wrapped(value) # a derived roll has no turn to keep
entries.append((obj, obj.parent, mates, (said[0], said[1], *valued(obj, value)), its_record))
moved.append({"part": obj.name, "value": round(value, 6)})
return entries, moved
def follows_report(obj, record: dict, kind, stated) -> dict | None:
"""None for a connection that follows nothing, else {driver, kind, k, offset, holds, reason}. A ratio holds when
the value stands within HELD of k x the driver's + offset (a roll: of a turn of it); a loop when its two ends
depend on its one driver (loop_drivers) and the closure its closing part states holds: a loop with a second
driver (limits widened by hand, a saved file) reads false and names each, whether or not the closure stands
closed, since a pose of the other would open it. holds is false with a reason when the driver is gone or states no DOF connection.
Derived at each report; stored nowhere."""
follows = record["follows"]
if follows is None:
return None
driver = follows["driver"]
row = {"driver": driver and driver.name, "kind": follows["kind"], "k": follows["k"], "offset": follows["offset"], "holds": False, "reason": None}
said, driver_kind = (link(driver), connection_kind(driver)[0]) if driver is not None else (None, None)
if driver is None:
row["reason"] = "the driver is gone: deleted, or in no collection"
elif said is None or driver_kind is None or said[2] is None or said[3] is None:
row["reason"] = "the driver states no DOF connection"
elif follows["kind"] == "ratio":
want = follows["k"] * (said[2] if driver_kind == "revolute" else said[3]) + follows["offset"]
off = abs(core._wrapped(stated[2] - want)) if kind == "revolute" else abs(stated[3] - want)
if off > HELD:
row["reason"] = f"its value stands {off:.6g} from k x the driver's + offset: pose the driver"
else:
pair = loop_pair(obj)
found = closure_report(pair[1], *built_part(pair[1])) if pair is not None else None
others = (loop_drivers(pair[1]) or (None, None, {}))[2] if pair is not None else {}
if found is None:
row["reason"] = "its loop has no partner: a closing part and its parent, both following the driver"
elif others:
row["reason"] = (f"the loop {pair[1].name!r} closes has more than one driver: {driver.name!r} and {', '.join(f'{o.name!r} ({why})' for o, why in others.items())}. "
"Hold that joint by limits of one value, have it follow the driver, or clear the loop (brokkr_kitbash.follow with record null)")
elif not found["holds"]:
row["reason"] = f"the closure {pair[1].name!r} states does not hold ({found['reason']}): pose the driver"
row["holds"] = row["reason"] is None
return row
def connection_report(obj, part, built):
@ -372,7 +729,7 @@ def connection_report(obj, part, built):
stands within HELD of core.mate. A child moved or re-parented by another action reads holds false until
set_params seats it again. With it the joint record: dof (the parent socket's type's: revolute, prismatic or
null for rigid), slide, limits, mechanism, compliance, and within, false only for a value written by hand
outside its limits."""
outside its limits; and follows (follows_report), null for a connection that follows nothing."""
stated = link(obj)
if stated is None:
return None
@ -380,7 +737,7 @@ def connection_report(obj, part, built):
row = {"parent": obj.parent.name if obj.parent else None, "socket": stated[0], "parentSocket": stated[1],
"roll": None if stated[2] is None else round(stated[2], 6), "residual": None, "holds": False,
"dof": None, "slide": None if stated[3] is None else round(stated[3], 6), "limits": record["limits"] and [round(v, 6) for v in record["limits"]],
"mechanism": record["mechanism"], "compliance": record["compliance"], "within": True}
"mechanism": record["mechanism"], "compliance": record["compliance"], "within": True, "follows": None}
try:
if obj.parent is None or stated[2] is None or stated[3] is None:
return row
@ -391,6 +748,7 @@ def connection_report(obj, part, built):
return row
if record["limits"] is not None and row["dof"] is not None:
row["within"] = core.within(stated[2] if row["dof"] == "revolute" else stated[3], *record["limits"], row["dof"] == "revolute") is not None
row["follows"] = follows_report(obj, record, row["dof"], stated)
row["residual"] = round(core.residual(obj.parent.matrix_world, parent_socket, obj.matrix_world, socket, stated[2], stated[3]), 9)
row["holds"] = bool(np.abs(np.array(obj.matrix_parent_inverse) - np.eye(4)).max() <= HELD and row["residual"] <= HELD)
return row
@ -613,13 +971,15 @@ def bounded(report: dict, advice: str) -> dict:
return report
def fitted(report: dict, key: str, rows: list) -> list:
def fitted(report: dict, key: str, rows: list, beside=None) -> list:
"""The rows of one list of a report that fit what a receipt carries beside the rest of the report, in order; those
left off the end are counted in report[key + 'Omitted']. The one rule that trims a report's rows to a receipt:
the scene keeps what the rows would have said."""
the scene keeps what the rows would have said. `beside(row)` is what a caller adds to the report for a row it
keeps (joints: its id in `unlimited`), counted with the row."""
kept, size = [], len(json.dumps(report, separators=(",", ":"))) + 2 * len(key) + 24
for row in rows:
size += len(json.dumps(row, separators=(",", ":"))) + 1
extra = None if beside is None else beside(row)
size += sum(len(json.dumps(value, separators=(",", ":"))) + 1 for value in (row, extra) if value is not None)
if size > REPORT_LIMIT:
report[key + "Omitted"] = len(rows) - len(kept)
break
@ -712,7 +1072,10 @@ class BROKKR_KITBASH_OT_place_part(PolishOperator):
class BROKKR_KITBASH_OT_set_params(PolishOperator):
"""Change params of a placed kit part and rebuild its mesh in place: its modifiers and material slots stay,
each shape keeps its faces' material, the Bevel width follows, and its connection and those of the parts
attached to it are seated again on the moved sockets; a closure is never seated, only reported"""
attached to it are seated again on the moved sockets, through write_connections (a value outside its joint's
limits or a stray slide, written by hand, and a write that touches a loop with a second driver, are refused
before anything changes); a closure is never seated and a
follower never derived again, only reported"""
bl_idname = "brokkr_kitbash.set_params"
bl_label = "Set Kit Part Params"
object_name: bpy.props.StringProperty(name="Object")
@ -730,15 +1093,16 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator):
mated(closing[1], *built_part(closing[1]), obj, part, built, (closing[0], closing[2], 0.0, 0.0), "closing on")
for other in closing_on(obj):
mated(obj, part, built, other, *built_part(other), (closure(other)[0], closure(other)[2], 0.0, 0.0), "closing on")
seats, stated = [], link(obj) # every connection this part is an end of, checked against its new sockets before anything is written
entries, stated = [], link(obj) # every connection this part is an end of, checked against its new sockets and its joint record before anything is written
if stated is not None:
if obj.parent is None:
raise Refused(f"{obj.name!r} states a connection and has no parent: detach it to clear the connection; nothing changed.")
parent_part, parent_built = built_part(obj.parent)
seats.append((obj, core.mate(*mated(obj.parent, parent_part, parent_built, obj, part, built, stated), *stated[2:])))
entries.append((obj, obj.parent, mated(obj.parent, parent_part, parent_built, obj, part, built, stated), stated, None))
for child in attached(obj):
child_part, child_built = built_part(child)
seats.append((child, core.mate(*mated(obj, part, built, child, child_part, child_built, link(child)), *link(child)[2:])))
entries.append((child, obj, mated(obj, part, built, child, child_part, child_built, link(child)), link(child), None))
write_checks(entries) # every refusal write_connections has, the one-driver rule with them, before the mesh is rebuilt
try:
old = core.build(part, stored)
except core.KitError: # stored params an edited kit no longer admits: nothing to map faces by
@ -751,9 +1115,8 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator):
obj.data.update()
sync_bevel(obj, built.bevel)
obj[PARAMS] = json.dumps(built.params)
for seated, basis in seats: # deeper descendants follow through parenting: their sockets did not move
seat(seated, basis)
if seats:
write_connections(entries) # deeper descendants follow through parenting: their sockets did not move
if entries:
context.view_layer.update()
report = part_report(obj, part, built)
report["closures"] = scene_closures(context, report, (obj,))
@ -791,14 +1154,16 @@ class BROKKR_KITBASH_OT_attach(PolishOperator):
sockets = mated(parent, parent_part, parent_built, child, part, built, stated)
free(parent, self.parent_socket)
free(child, self.socket)
write_connection(child, parent, sockets, stated, {"limits": None, "mechanism": None, "compliance": None}) # a new connection states no joint record: brokkr_kitbash.joint gives it one
write_connection(child, parent, sockets, stated, dict.fromkeys(("limits", "mechanism", "compliance", "follows"))) # a new connection states no joint record: brokkr_kitbash.joint and follow give it one
context.view_layer.update()
return part_report(child, part, built)
class BROKKR_KITBASH_OT_detach(PolishOperator):
"""Clear a kit part's connection and the closure it states: it stays where it stands in the world, loses its
parent, and the parts attached to it stay attached to it"""
parent, and the parts attached to it stay attached to it. A loop follower's partner stops following with it; a
driver's followers keep their statements and report that the driver states no DOF connection. Refused when it
would leave a loop with a second driver (one_driver): a part between a loop's end and the part both ends hang from"""
bl_idname = "brokkr_kitbash.detach"
bl_label = "Detach Kit Part"
object_name: bpy.props.StringProperty(name="Object")
@ -809,6 +1174,8 @@ class BROKKR_KITBASH_OT_detach(PolishOperator):
if SOCKET not in obj and CLOSE not in obj:
raise Refused(f"{obj.name!r} is not attached (it has no {SOCKET} property) and states no closure; nothing changed.")
part, built = built_part(obj)
pair = loop_pair(obj) # a loop follower's partner follows nothing once the loop is gone
one_driver({obj: (None, None, None), **{o: (o.parent, connection_kind(o)[0], {**joint_record(o), "follows": None}) for o in pair or () if o != obj}})
if SOCKET in obj:
world = obj.matrix_world.copy()
obj.parent = None
@ -816,17 +1183,24 @@ class BROKKR_KITBASH_OT_detach(PolishOperator):
for key in (SOCKET, PARENT_SOCKET, ROLL, *RECORD, CLOSE, CLOSE_TO, CLOSE_TO_SOCKET):
if key in obj:
del obj[key]
for other in pair or ():
for key in (FOLLOWS, FOLLOWS_DRIVER):
if key in other:
del other[key]
return part_report(obj, part, built)
def pose(context, name: str, solve) -> dict:
def pose(context, name: str, solve, keeps: bool = False) -> dict:
"""Give an attached part a new roll, slide or joint record where it hangs: its parent and both sockets stay, and
what is attached to it follows. `solve(child, built, sockets, stated, joint)` answers (the roll, the slide, what
to add to the report, the joint record to state or None to keep it), or refuses; `joint` is the record the
connection states with its `dof` and the parent socket's `type`. Refuses a part that states no connection or
has no parent, what mated() refuses and what write_connection does: a value outside the joint's limits. The
report is the part's and, as set_params', every closure in the scene with the part's own first: a pose can open
one, and never seats one."""
has no parent, what mated() refuses and what write_connections does: a value outside the joint's limits. A
follower's value is derived: it is refused here, naming its driver, unless the solve `keeps` the value (joint's).
A driver's followers are derived with it (driven) and written with it in one write_connections: one of them
outside its own limits, or a loop that cannot close, refuses the pose with nothing changed. The report is the
part's with followers, [{part, value}] in the order written, and, as set_params', every closure in the scene
with the part's own first: a pose can open one, and seats none but those of the loops that follow it."""
child = mesh_object(name)
part, built = built_part(child)
stated = link(child)
@ -835,13 +1209,18 @@ def pose(context, name: str, solve) -> dict:
if child.parent is None:
raise Refused(f"{child.name!r} states a connection and has no parent: detach it to clear the connection; nothing changed.")
sockets = mated(child.parent, *built_part(child.parent), child, part, built, stated)
follows = joint_record(child)["follows"]
if follows is not None and not keeps:
raise Refused(f"{child.name!r} follows {repr(follows['driver'].name) if follows['driver'] else 'a driver that is gone'} ({follows['kind']}): its value is derived. "
"Pose the driver, or clear the statement with brokkr_kitbash.follow and record null; nothing changed.")
try:
roll, slide, solved, record = solve(child, built, sockets, stated, {**joint_record(child), "dof": dof(child.parent, sockets[0]), "type": sockets[0]["type"]})
except core.KitError as error:
raise Refused(f"{child.name!r} on {child.parent.name!r}: {error}; nothing changed.") from None
write_connection(child, child.parent, sockets, (stated[0], stated[1], float(roll), float(slide)), record)
entries, moved = driven(child, sockets, stated, float(roll), float(slide), record)
write_connections(entries)
context.view_layer.update()
report = {**part_report(child, part, built), **solved}
report = {**part_report(child, part, built), **solved, "followers": moved}
report["closures"] = scene_closures(context, report, (child,))
return report
@ -915,7 +1294,7 @@ class BROKKR_KITBASH_OT_reach(PolishOperator):
class BROKKR_KITBASH_OT_joint(PolishOperator):
"""State the joint record of an attached kit part's connection: its limits, a mechanism label and, on a slide,
its compliance"""
its compliance. A follower keeps its derived value; a driver's followers are derived again"""
bl_idname = "brokkr_kitbash.joint"
bl_label = "State Kit Joint"
object_name: bpy.props.StringProperty(name="Object", description="An attached part on a revolute or prismatic socket")
@ -939,7 +1318,7 @@ class BROKKR_KITBASH_OT_joint(PolishOperator):
def solve(child, built, sockets, stated, joint):
if joint["dof"] is None:
raise Refused(f"{child.name!r} on {child.parent.name!r}: socket type {joint['type']!r} states no dof: the connection is rigid and carries no joint record; nothing changed.")
record = {key: joint[key] for key in ("limits", "mechanism", "compliance")}
record = {key: joint[key] for key in ("limits", "mechanism", "compliance", "follows")}
if "limits" in given:
record["limits"] = limits and (float(limits[0]), float(limits[1]))
if "mechanism" in given:
@ -947,7 +1326,7 @@ class BROKKR_KITBASH_OT_joint(PolishOperator):
if "compliance" in given:
record["compliance"] = spring and {key: float(spring[key]) for key in ("hertz", "damping_ratio")}
return stated[2], stated[3], {}, record
return pose(context, self.object_name, solve)
return pose(context, self.object_name, solve, keeps=True)
class BROKKR_KITBASH_OT_slide(PolishOperator):
@ -971,38 +1350,136 @@ class BROKKR_KITBASH_OT_slide(PolishOperator):
class BROKKR_KITBASH_OT_joints(PolishOperator):
"""Report the joints of the tree of kit parts under a root: each revolute or prismatic connection with its
parent joint, axis, value, limits, mechanism and compliance, in the root's frame"""
parent joint, axis, value, limits, mechanism, compliance and what drives it, in the root's frame"""
bl_idname = "brokkr_kitbash.joints"
bl_label = "Report Kit Joints"
bl_options = {"REGISTER"}
object_name: bpy.props.StringProperty(name="Object", description="The root: a kit part; the report is of what is attached below it")
object_name: bpy.props.StringProperty(name="Object", description="The root: a kit part; the report is of its own joint, when it states one, and of what is attached below it")
after: bpy.props.StringProperty(name="After", description="Empty, or the id of a row: the report carries the rows after it (the `next` of the report before)")
@kit_work
def work(self, context):
root, kits, rows, rigid_count = mesh_object(self.object_name), {}, [], 0
root, kits, entries, tree = mesh_object(self.object_name), {}, [], set()
built_part(root, kits)
frame = np.linalg.inv(np.array(root.matrix_world, dtype=np.float64))
todo = [(child, None) for child in sorted(attached(root), key=lambda o: o.name, reverse=True)]
while todo: # depth first, children by name: a joint's parent joint is the nearest DOF connection above it, and rigid connections fold into it
child, above = todo.pop()
part, built = built_part(child, kits)
stated = link(child)
parent_socket, _ = mated(child.parent, *built_part(child.parent, kits), child, part, built, stated)
kind = dof(child.parent, parent_socket)
if kind is None:
rigid_count += 1
else:
record, value = joint_record(child), stated[2] if kind == "revolute" else stated[3]
at = frame @ np.array(child.parent.matrix_world, dtype=np.float64) @ parent_socket["matrix"]
limits = record["limits"] and [round(v, 6) for v in record["limits"]]
rows.append({"id": child.name, "parent": above, "part": part["name"], "socket": f"{child.parent.name}:{stated[1]}", "kind": kind,
"axis": [round(float(v), 6) for v in at[:3, 2]], "origin": [round(float(v), 6) for v in at[:3, 3]], "value": round(value, 6),
"limits": limits, "min": limits and round(record["limits"][0] - value, 6), "max": limits and round(record["limits"][1] - value, 6),
"mechanism": record["mechanism"], "compliance": record["compliance"]})
above = child.name
todo += [(below, above) for below in sorted(attached(child), key=lambda o: o.name, reverse=True)]
report = {"schema": "brokkr.joints", "version": 1, "root": root.name, "frame": "the root object's: Blender axes (+Z up), metres", "rigid": rigid_count}
report["joints"] = fitted(report, "joints", rows)
todo = [root]
while todo: # depth first, children by name: the order core.joint_rows reads a joint's parent joint in
child = todo.pop()
tree.add(child)
if child != root or link(child) is not None and child.parent is not None and PART in child.parent: # the root's own joint comes first, parent null
part, built = built_part(child, kits)
stated = link(child)
parent_socket, _ = mated(child.parent, *built_part(child.parent, kits), child, part, built, stated)
kind = dof(child.parent, parent_socket)
if kind is not None or child != root:
record = joint_record(child)
follows = record["follows"]
entries.append((child.name, child.parent.name, part["name"], parent_socket, np.array(child.parent.matrix_world, dtype=np.float64), kind,
stated[2] if kind == "revolute" else stated[3], record,
follows and {"by": follows["driver"] and follows["driver"].name, "kind": follows["kind"], "k": follows["k"], "offset": follows["offset"]}))
todo += sorted(attached(child), key=lambda o: o.name, reverse=True)
rows, rigid_count = core.joint_rows(np.array(root.matrix_world, dtype=np.float64), entries)
ids = [row["id"] for row in rows]
report = {"schema": "brokkr.joints", "version": 2, "root": root.name, "frame": "the root object's: Blender axes (+Z up), metres", "rigid": rigid_count,
"unlimited": [], "manyDrivers": [], "next": max(ids, key=lambda name: len(json.dumps(name)), default=None)}
for closing in sorted((o for o in bpy.data.objects if CLOSE in o and FOLLOWS in o and o.users_collection), key=lambda o: o.name):
driver, ends, others = loop_drivers(closing) or (None, None, None) # of the whole tree, as rigid is: every page carries it
if others and tree & {closing, closing.parent, driver, *ends, *others}:
report["manyDrivers"].append({"loop": closing.name, "drivers": [driver.name, *(o.name for o in others)]})
if self.after:
if self.after not in ids:
raise Refused(f"after {self.after!r} is not the id of a joint under {root.name!r}: it is the `next` of the report before, or empty.")
rows = rows[ids.index(self.after) + 1:]
def unlimited(row):
return row["id"] if row["limits"] is None and row["driven"] is None else None
report["joints"] = fitted(report, "joints", rows, unlimited) # a row and its id in `unlimited` are kept or left together: the list pages with the rows
report["unlimited"] = [row["id"] for row in report["joints"] if unlimited(row) is not None]
report["next"] = report["joints"][-1]["id"] if "jointsOmitted" in report and report["joints"] else None
return report
class BROKKR_KITBASH_OT_follow(PolishOperator):
"""State that an attached kit part's joint follows another's: its value is derived from the driver's, by a ratio
or by closing the loop its closure states, whenever the driver is posed"""
bl_idname = "brokkr_kitbash.follow"
bl_label = "Follow Kit Joint"
object_name: bpy.props.StringProperty(name="Object", description="The follower: a part attached on a revolute or prismatic socket; for a loop, the part that states the closure")
record: bpy.props.StringProperty(name="Record", default="null", description='{"driver": name, "kind": "ratio", "k": number, "offset": number}, '
'{"driver": name, "kind": "loop"}, or null to clear')
@kit_work
def work(self, context):
try:
given = json.loads(self.record)
except ValueError as error:
raise Refused(f"record must be JSON ({error}); nothing changed.") from None
ratio = isinstance(given, dict) and set(given) == {"driver", "kind", "k", "offset"} and given["kind"] == "ratio"
if not (given is None or isinstance(given, dict) and isinstance(given.get("driver"), str) and (
ratio and core.finite(given["k"]) and given["k"] != 0 and core.finite(given["offset"]) or set(given) == {"driver", "kind"} and given["kind"] == "loop")):
raise Refused('record must be {"driver": name, "kind": "ratio", "k": a number that is not 0, "offset": a number}, {"driver": name, "kind": "loop"}, '
"or null to clear; nothing changed.")
obj = mesh_object(self.object_name)
part, built = built_part(obj)
def connection(o, what):
"""(sockets, stated, DOF kind) of the DOF connection a part states, or the refusal that names what it is here."""
said = link(o)
if said is None or o.parent is None:
raise Refused(f"{o.name!r} ({what}) is not attached: attach gives it a connection; nothing changed.")
mates = mated(o.parent, *built_part(o.parent), o, *built_part(o), said)
if dof(o.parent, mates[0]) is None:
raise Refused(f"{o.name!r} ({what}) on {o.parent.name!r}: socket type {mates[0]['type']!r} states no dof: the connection is rigid, "
"and only a revolute or prismatic connection follows or drives; nothing changed.")
return mates, said, dof(o.parent, mates[0])
sockets, stated, _ = connection(obj, "the follower")
current = joint_record(obj)["follows"]
if given is None:
if current is None:
raise Refused(f"{obj.name!r} follows nothing; nothing changed.")
cleared = loop_pair(obj) or (obj,)
write_connections([(o, o.parent, connection(o, "a follower")[0], link(o), {**joint_record(o), "follows": None}) for o in cleared])
context.view_layer.update()
return {**part_report(obj, part, built), "cleared": [o.name for o in cleared]}
driver = mesh_object(given["driver"])
pair, closing = (obj,) if ratio else (obj.parent, obj), closure(obj)
if not ratio and (closing is None or closing[1] is None or not closure_report(obj, part, built)["holds"]):
raise Refused(f"{obj.name!r} states no closure that holds: a loop follower is the part that states the closure (brokkr_kitbash.close, where the "
"two sockets meet), and its joint and its parent's are solved to keep it; nothing changed.")
if not ratio:
connection(obj.parent, "the follower's parent: a loop's two unknowns are the closing part's joint and its parent's")
if not ratio and CLOSE in obj.parent:
raise Refused(f"{obj.parent.name!r}, the parent of {obj.name!r}, states a closure itself: a loop's parent follower states none; nothing changed.")
driver_sockets, driver_stated, _ = connection(driver, "the driver")
if joint_record(driver)["follows"] is not None:
raise Refused(f"{driver.name!r} is itself a follower: a driver is never a follower (one joint, one driver); nothing changed.")
for o in pair:
below = driver
while below is not None and below != o:
below = below.parent
if below == o:
raise Refused(f"{driver.name!r} is {'the follower itself' if driver == o else 'below ' + repr(o.name)}: a follower's driver is neither it nor below it; nothing changed.")
if joint_record(o)["follows"] is not None:
raise Refused(f"{o.name!r} already follows: clear it first (brokkr_kitbash.follow with record null); nothing changed.")
if followers(o):
raise Refused(f"{o.name!r} drives {followers(o)[0].name!r}: a driver is never a follower (one joint, one driver); nothing changed.")
if not ratio:
moving = {driver, *followers(driver)} # what moves when the driver is posed: it, what follows it, and what hangs from either
def moves(o) -> bool:
while o is not None and o not in moving:
o = o.parent
return o is not None
ends = (obj.parent.parent, closing[1])
if moves(ends[0]) == moves(ends[1]):
raise Refused(f"the loop's two ends, {ends[0].name!r} (the base) and {ends[1].name!r} (closed on), {'both move' if moves(ends[0]) else 'neither moves'} with "
f"{driver.name!r}: exactly one of them is the driver, follows it, or hangs from one that does; nothing changed.")
follows = {"driver": driver, "kind": given["kind"], "k": float(given["k"]) if ratio else None, "offset": float(given["offset"]) if ratio else None}
entries, moved = driven(driver, driver_sockets, driver_stated, driver_stated[2], driver_stated[3], None, {o: follows for o in pair})
write_connections(entries)
context.view_layer.update()
report = {**part_report(obj, part, built), "followers": moved}
report["closures"] = scene_closures(context, report, (obj,))
return report
@ -1026,6 +1503,8 @@ class BROKKR_KITBASH_OT_close(PolishOperator):
raise Refused(f"{obj.name!r} cannot close on itself; nothing changed.")
if closure(obj) is not None:
raise Refused(f"{obj.name!r} already states a closure (its socket {closure(obj)[0]!r}): a part states one, and detach clears it; nothing changed.")
if (joint_record(obj)["follows"] or {}).get("kind") == "loop":
raise Refused(f"{obj.name!r} follows as the parent of a loop: the closing part of a loop states its closure, and its parent states none; nothing changed.")
there, here = mated(other, other_part, other_built, obj, part, built, (self.socket, self.other_socket, 0.0, 0.0), "closing on")
free(other, self.other_socket)
free(obj, self.socket)
@ -2307,7 +2786,7 @@ class BROKKR_KITBASH_OT_report(PolishOperator):
classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KITBASH_OT_describe, BROKKR_KITBASH_OT_report,
BROKKR_KITBASH_OT_attach, BROKKR_KITBASH_OT_detach, BROKKR_KITBASH_OT_roll, BROKKR_KITBASH_OT_aim, BROKKR_KITBASH_OT_reach,
BROKKR_KITBASH_OT_joint, BROKKR_KITBASH_OT_slide, BROKKR_KITBASH_OT_joints,
BROKKR_KITBASH_OT_joint, BROKKR_KITBASH_OT_slide, BROKKR_KITBASH_OT_joints, BROKKR_KITBASH_OT_follow,
BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, BROKKR_KITBASH_OT_cut_many, BROKKR_KITBASH_OT_freeze, BROKKR_KITBASH_OT_thaw,
BROKKR_KITBASH_OT_ribs,
BROKKR_KITBASH_OT_shell, BROKKR_KITBASH_OT_hose, BROKKR_KITBASH_OT_plates)

View file

@ -109,7 +109,7 @@
},
{
"name": "brokkr_kitbash.attach",
"doc": "Seat a socket of a kit part on a socket of a part of any kit whose socket types agree and parent it there: origins together, normals opposed. Refuses sockets of different types or sizes that do not match, an occupied socket, a child that has a parent, and a loop. The connection's DOF is its parent socket's type's (revolute, prismatic or rigid); it starts with no joint record: brokkr_kitbash.joint states one. Reports the child with its connection.",
"doc": "Seat a socket of a kit part on a socket of a part of any kit whose socket types agree and parent it there: origins together, normals opposed. Refuses sockets of different types or sizes that do not match, an occupied socket, a child that has a parent, a loop, and a new pin or slide between the two ends of a loop that follows (a second driver: both are named; hold it or clear the loop first). The connection's DOF is its parent socket's type's (revolute, prismatic or rigid); it starts with no joint record: brokkr_kitbash.joint states one. Reports the child with its connection.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
@ -160,7 +160,7 @@
},
{
"name": "brokkr_kitbash.detach",
"doc": "Clear a kit part's connection and the closure it states: it keeps its place in the world and loses its parent; parts attached to it stay attached to it.",
"doc": "Clear a kit part's connection and the closure it states: it keeps its place in the world and loses its parent; parts attached to it stay attached to it. A loop follower's partner stops following with it. Refused, with nothing changed, when it would leave a loop that follows with a second driver: a part between one end of the loop and the part both ends hang from, whose going leaves a joint with travel between the ends (both drivers are named).",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
@ -176,7 +176,7 @@
},
{
"name": "brokkr_kitbash.roll",
"doc": "Turn an attached kit part to a roll about its parent socket's normal, in place: its parent and both sockets stay, and what is attached to it follows. Refuses a part that is not attached and, on a revolute joint with limits, a roll with no turn of itself inside them (the roll written is the one inside). Reports the part and closures, every closure in the scene as {part, to, holds}, its own first: a roll can open one and never seats one.",
"doc": "Turn an attached kit part to a roll about its parent socket's normal, in place: its parent and both sockets stay, and what is attached to it follows. Refuses a part that is not attached and, on a revolute joint with limits, a roll with no turn of itself inside them (the roll written is the one inside). Refused on a follower (a part whose connection states follows), naming its driver: its value is derived. On a driver, every follower moves with it in the same action, and a follower outside its own limits or a loop that cannot close refuses the pose with nothing changed; the report's followers lists each as {part, value}. Reports the part and closures, every closure in the scene as {part, to, holds}, its own first: a roll can open one and seats none but those of the loops that follow the part.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
@ -201,7 +201,7 @@
},
{
"name": "brokkr_kitbash.aim",
"doc": "Turn an attached kit part about its pin until one of its own axes points as near a world direction as the pin lets it. The roll is solved exactly, not searched. On a revolute joint with limits the roll stays inside them: where the free roll is outside, the end of the limits that points the axis nearer. Refuses an axis or a direction that lies along the pin (within about 0.06 degrees), and a zero direction. Reports the part, aimed: {roll, dot} (dot 1 when the axis reaches the direction) and closures as roll does.",
"doc": "Turn an attached kit part about its pin until one of its own axes points as near a world direction as the pin lets it. The roll is solved exactly, not searched. On a revolute joint with limits the roll stays inside them: where the free roll is outside, the end of the limits that points the axis nearer. Refuses an axis or a direction that lies along the pin (within about 0.06 degrees), and a zero direction. Refused on a follower, and moves a driver's followers, as roll does. Reports the part, aimed: {roll, dot} (dot 1 when the axis reaches the direction) and closures as roll does.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
@ -254,7 +254,7 @@
},
{
"name": "brokkr_kitbash.reach",
"doc": "Turn an attached kit part about its pin until one of its sockets' origins stands at a height along a world direction (by default world z): of the two rolls that do it, the one nearer the roll it has. Solved exactly. On a revolute joint with limits only a roll inside them is taken; with neither inside it refuses, naming both rolls and the limits. Refuses a height the socket cannot reach, naming the range it can (either end of the range is taken), and a socket that lies on the pin. Reports the part, reached: {roll, residual} and closures as roll does.",
"doc": "Turn an attached kit part about its pin until one of its sockets' origins stands at a height along a world direction (by default world z): of the two rolls that do it, the one nearer the roll it has. Solved exactly. On a revolute joint with limits only a roll inside them is taken; with neither inside it refuses, naming both rolls and the limits. Refuses a height the socket cannot reach, naming the range it can (either end of the range is taken), and a socket that lies on the pin. Reports the part, reached: {roll, residual} and closures as roll does. Refused on a follower, and moves a driver's followers, as roll does.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
@ -310,7 +310,7 @@
},
{
"name": "brokkr_kitbash.joint",
"doc": "State the joint record of an attached kit part's connection. The connection's DOF is its parent socket's type's: revolute (its value is the roll, degrees) or prismatic (the slide, metres). record is a JSON object of any of limits ([lo, hi] or null), mechanism (a label of 1 to 32 a-z, 0-9 and _, or null) and compliance ({\"hertz\": over 0 to 30, \"damping_ratio\": 0 to 2} or null: a slide in the load path that settles under load, a record for a runtime, solved by nothing here); a key left out keeps what is stated and null clears it. Refuses a rigid connection naming its socket type, limits that do not hold the value the joint has, revolute limits spanning over 360 degrees or with an end past 360, prismatic limits with an end past 10 m, and compliance on a revolute joint or without limits. Moves nothing but a roll to its turn inside the limits. Reports the part and closures as roll does.",
"doc": "State the joint record of an attached kit part's connection. The connection's DOF is its parent socket's type's: revolute (its value is the roll, degrees) or prismatic (the slide, metres). record is a JSON object of any of limits ([lo, hi] or null), mechanism (a label of 1 to 32 a-z, 0-9 and _, or null) and compliance ({\"hertz\": over 0 to 30, \"damping_ratio\": 0 to 2} or null: a slide in the load path that settles under load, a record for a runtime, solved by nothing here); a key left out keeps what is stated and null clears it. Refuses a rigid connection naming its socket type, limits that do not hold the value the joint has, revolute limits spanning over 360 degrees or with an end past 360, prismatic limits with an end past 10 m, and compliance on a revolute joint or without limits. Moves nothing but a roll to its turn inside the limits: a follower keeps its derived value (limits that do not hold it are refused), and a driver's followers are derived again where it stands. Limits cannot be cleared from a driver a ratio follows, nor widened or cleared on a pin that limits of one value hold between the two ends of a loop that follows (it would be a second driver: both are named). Reports the part and closures as roll does.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
@ -335,7 +335,7 @@
},
{
"name": "brokkr_kitbash.slide",
"doc": "Slide an attached kit part along its parent socket's normal, in place, on a prismatic connection (a ram_rod in a ram_barrel's bore: slide 0 is closed, the slide is the extension): its parent and both sockets stay, and what is attached to it follows. Refuses a revolute or rigid connection naming its socket type, and a slide outside the joint's limits. Reports the part and closures as roll does.",
"doc": "Slide an attached kit part along its parent socket's normal, in place, on a prismatic connection (a ram_rod in a ram_barrel's bore: slide 0 is closed, the slide is the extension): its parent and both sockets stay, and what is attached to it follows. Refuses a revolute or rigid connection naming its socket type, and a slide outside the joint's limits. Reports the part and closures as roll does. Refused on a follower, and moves a driver's followers, as roll does.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
@ -360,7 +360,7 @@
},
{
"name": "brokkr_kitbash.joints",
"doc": "The joints of the tree of kit parts attached under a root part, as {schema: brokkr.joints, version: 1, root, frame, rigid, joints}. A row per revolute or prismatic connection, depth first with children by name, so a joint's parent row comes before it: id (the child object), parent (the id of the nearest joint above, or null: rigid connections fold into it and are counted in rigid), part, socket ('Object:socket', the parent socket), kind, axis and origin (that socket's z and origin in the root object's frame: Blender axes, +Z up, metres), value (the roll in degrees or the slide in metres now), limits ([lo, hi] or null), min and max (the limits less the value: the travel either way from this pose), mechanism and compliance. Axis, origin and order are derived at each report from the kits and the parent tree; nothing stores them. Rows a receipt cannot carry are counted in jointsOmitted. Refuses a connection that cannot be read. Evaluates no modifier.",
"doc": "The joints of the tree of kit parts attached under a root part, as {schema: brokkr.joints, version: 2, root, frame, rigid, unlimited, manyDrivers, next, joints}. A row per revolute or prismatic connection, depth first with children by name, so a joint's parent row comes before it; a root that itself states a revolute or prismatic connection has its own row first, parent null: id (the child object), parent (the id of the nearest joint above, or null: rigid connections fold into it and are counted in rigid), part, socket ('Object:socket', the parent socket), kind, axis and origin (that socket's z and origin in the root object's frame: Blender axes, +Z up, metres), value (the roll in degrees or the slide in metres now), limits ([lo, hi] or null), min and max (the limits less the value: the travel either way from this pose), held (true when the limits are of one value: the joint has no travel, as a torque link's lug held at [90, 90], so a rig makes a fixed bone and not a DOF; such a row is in neither unlimited nor rigid), mechanism, compliance and driven (null, or {by: the driver's id, kind: ratio | loop, k, offset}: the value is derived from the driver's, so a rig makes a driven bone and not a DOF). kind is revolute or prismatic: Aetheria's ShipJoint calls them rotate and slide, one to one. unlimited lists the ids of the rows this report carries that are not driven and state no limits: an exporter that needs limits refuses by this one field of each report. manyDrivers lists each loop with more than one driver that has a part in the tree (a limit widened by hand, a saved file: no action writes one), as {loop: the closing part, drivers: [the loop's driver, each other one]}: its driven rows are not a function of one driver, so a rig refuses the tree while the list is not empty; it is of the whole tree and every page carries it. Axis, origin and order are derived at each report from the kits and the parent tree; nothing stores them. Rows a receipt cannot carry are counted in jointsOmitted, and next is then the id of the last row carried (else null): call again with after set to it for the rows that follow and their unlimited ids; a report is never over a receipt and always carries a row. after refuses an id that is no row's. Refuses a connection that cannot be read. Evaluates no modifier.",
"changesScene": false,
"editModeSafe": true,
"result": "brokkr_mesh_polish_result",
@ -372,6 +372,38 @@
"minLength": 1,
"maxLength": 63,
"doc": "the root: a kit part"
},
{
"name": "after",
"type": "string",
"maxLength": 63,
"default": "",
"doc": "empty, or the next of the report before: the rows after that id"
}
]
},
{
"name": "brokkr_kitbash.follow",
"doc": "State that an attached kit part's joint follows another's: its roll or slide is then derived from the driver's whenever the driver is posed, and roll, aim, reach and slide on it are refused. record is JSON. {\"driver\": name, \"kind\": \"ratio\", \"k\": number, \"offset\": number}: the value is k x the driver's value + offset (a kneecap at k 0.5, a pinion at minus ring over pinion, a crosshead's slide in metres per degree of a roll); the driver states limits, so its value is one number. {\"driver\": name, \"kind\": \"loop\"}: object_name is a part that states a closure that holds; its joint and its parent's are the two unknowns solved so the closure keeps holding (a rocker and coupler closing on a crank; a ram's barrel and rod closing on the part it pushes; a torque link's two arms), and both follow the driver. Exactly one end of the loop, the parent's parent or the part closed on, moves with the driver: it is the driver, follows it, or hangs from one that does. The driver is the one input the two ends depend on: every revolute or prismatic joint between an end and the part both ends hang from is the driver, follows it, or is held by limits of one value (a torque link's lug on its rod: limits [90, 90]). The loop is planar: its pins are parallel. null clears the statement, and a loop partner's with it; it is refused for a follower between the two ends of another loop, which it would leave with a second driver. The one-driver rule is read again before every write of a connection and before detach, so no later attach, detach, clear, limits or pose breaks it. The follower moves at once and the report's followers lists every follower of the driver as {part, value}. Refuses, with nothing changed: a rigid connection; a driver that is the follower, below it, or itself a follower; a follower that already follows or that drives another; a ratio whose driver states no limits; a value outside the follower's own limits; a loop with no closure that holds, with both ends or neither moving with the driver, whose ends depend on more than one driver (another driver's follower, or a joint with travel that follows nothing: both are named), that is not planar, or at or past a dead centre (its two joints in line, a ram's rod end on its barrel's pin, or a step that would take the pair to its other assembly). Nothing stores a pin or a linkage: a loop is solved from the kits' socket frames each time, and no Blender driver or constraint is made.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
"fields": [
{
"name": "object_name",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 63,
"doc": "the follower: a part attached on a revolute or prismatic socket; for a loop, the part that states the closure"
},
{
"name": "record",
"type": "string",
"required": true,
"minLength": 4,
"maxLength": 400,
"doc": "{driver, kind: ratio, k, offset}, {driver, kind: loop}, or null"
}
]
},

View file

@ -1470,9 +1470,12 @@ def residual(parent_world, parent_socket: dict, child_world, child_socket: dict,
DOFS = ("revolute", "prismatic") # what a socket type's dof may state: the child turns about the parent socket's z, or slides along it
# How far past an end of its limits a joint's value may stand and still be inside them, as a fraction of the larger
# of 1 and the ends' sizes. A rule: an action's roll and slide are float32 fields and limits are JSON doubles, so a
# value typed as an end of its own limits stands up to 6e-08 of itself off that end; 1e-06 is 17 of those.
LIMIT_SLACK = 1e-6
# of 1 and the ends' sizes. An action's roll and slide are float32 fields and limits are JSON doubles, so a value
# typed as an end of its own limits stands off that end: shipped worst 1.9e-08 of it (float32(-20.1), which must be
# inside); the least a test refuses stood 3e-06 off. The geometric mean, separation 12.6 each side. JointRecordTests
# reads both sides of it at 1.2: a slack of 2e-06 or 2.9e-06 takes the value 2.9e-07 off, one of 1.9e-08 loses the
# one 2e-07 off.
LIMIT_SLACK = 2.4e-7
def within(value: float, lo: float, hi: float, revolute: bool) -> float | None:
@ -1577,6 +1580,118 @@ def closure_residual(world_a, socket_a: dict, world_b, socket_b: dict) -> float:
return float(max(np.abs(a[:3, 3] - b[:3, 3]).max(), np.abs(a[:3, 2] + b[:3, 2]).max()))
HELD = 1e-5 # a connection or a closure holds when its residual is at most this: the add-on's HELD is this one
# close_loop's three bounds, each read in FollowTests (lodur:ruling:deterministic-bound-margin).
# Metres of in-plane closure error Newton stops at. Shipped worst error of an accepted solve 4.1e-11; the least
# error it was still iterating on 2.5e-10, which a tolerance of 3e-10 accepts; the geometric mean, separation 2.4
# each side. FollowTests reads both from the solved frames: its sweep's worst error is under 1.0e-10.
FOLLOW_TOLERANCE = 1e-10
# Newton steps one solve may take. Shipped worst 4 (a driver step of 5 degrees toward a dead centre, and one solve
# across a 40 degree jump); a rule, four times the worst, which FollowTests asserts of its sweep.
FOLLOW_ITERATIONS = 16
# The smaller singular value of the Jacobian with each column scaled by its lever: about sin(angle between the columns)
# / sqrt(2) for two revolute joints, 0 at a dead centre, where the two unknowns move the closing pin along one line. A
# revolute column is scaled to unit length (so a linkage's size and the metres-per-degree of a column do not move
# it), but for a ram, a revolute joint and then a prismatic one, by its lever with the slide at 0: that column is across
# the slide wherever the rod's end is on the bore's axis, and its dead centre is the rod's end on the barrel's pin,
# where the column vanishes; so a ram reads its lever over its closed lever, 1 at most. The reading is negative once
# the pair stands on the other assembly from its seed (the Jacobian's determinant about the pin has changed sign: an
# elbow bent the other way, a rod's end past its barrel's pin). Shipped least over the solves that are accepted 0.184
# (the four-bar 30 degrees back from rest; a ram at 0.184 of its closed lever is accepted too); the greatest a refused
# solve reads 0.047 (the four-bar 6.7 degrees from straight; a ram at 0.047 of its closed lever); the geometric mean,
# separation 2.0 each side.
FOLLOW_SINGULAR = 0.093
def close_loop(base_world, joints, closing: dict, target_world, seed) -> tuple[tuple[float, float], int]:
"""((value 1, value 2), Newton iterations) that close a planar loop of two unknowns. `joints` is two
(parent socket, child socket, kind) in series: the first child mated on a socket of the part at base_world, the
second on a socket of the first; a value is a revolute joint's roll in degrees or a prismatic one's slide in
metres (its other coordinate is 0: a caller with a prismatic joint's stated roll turns the parent socket by it).
`closing` is the second child's socket that closes, target_world the 4x4 world frame of the socket it closes on.
Newton on the closing origin's error across the target's z, with the analytic Jacobian (a revolute column
z x (q - o) pi / 180 for the joint's pin z through o, a prismatic one z), from `seed`: the root found is the one
on the seed's assembly branch when the seed is near, so a caller steps its input. Refuses, naming which: pins
that are not parallel (each revolute z along the target's z, each prismatic z across it, the closing z opposed
to it: the loop is planar); a dead centre (FOLLOW_SINGULAR), and an iterate past one, on the other assembly from
the seed, so no solve answers the other branch; no convergence in FOLLOW_ITERATIONS; and a loop that closes in
the plane and misses along the pin (closure_residual over HELD)."""
base, target = np.asarray(base_world, dtype=np.float64), np.asarray(target_world, dtype=np.float64)
(parent_1, child_1, kind_1), (parent_2, child_2, kind_2) = joints
n, values = target[:3, 2], np.array([float(seed[0]), float(seed[1])], dtype=np.float64)
def placed(values):
at_1 = base @ parent_1["matrix"]
world_1 = base @ (mate(parent_1, child_1, values[0]) if kind_1 == "revolute" else mate(parent_1, child_1, 0.0, values[0]))
at_2 = world_1 @ parent_2["matrix"]
world_2 = world_1 @ (mate(parent_2, child_2, values[1]) if kind_2 == "revolute" else mate(parent_2, child_2, 0.0, values[1]))
return at_1, at_2, world_2 @ closing["matrix"]
at_1, at_2, end = placed(values)
for name, kind, at in ((parent_1["name"], kind_1, at_1), (parent_2["name"], kind_2, at_2)):
off = float(np.abs(np.cross(at[:3, 2], n)).max() if kind == "revolute" else abs(at[:3, 2] @ n))
if off > HELD:
raise KitError(f"the loop is not planar: the {kind} joint on socket {name!r} "
f"{'turns about a pin that is not parallel to' if kind == 'revolute' else 'slides along a line that is not across'} "
f"the pin it closes on (off by {off:.6g})")
if float(np.abs(end[:3, 2] + n).max()) > HELD:
raise KitError(f"the loop is not planar: closing socket {closing['name']!r} does not face the pin it closes on "
f"(normals off by {float(np.abs(end[:3, 2] + n).max()):.6g})")
ram, side = (kind_1, kind_2) == ("revolute", "prismatic"), None
for iteration in range(FOLLOW_ITERATIONS + 1):
at_1, at_2, end = placed(values)
error = target[:3, 3] - end[:3, 3]
error = error - n * (error @ n)
J = np.stack([np.cross(at[:3, 2], end[:3, 3] - at[:3, 3]) * (math.pi / 180.0) if kind == "revolute" else at[:3, 2]
for kind, at in ((kind_1, at_1), (kind_2, at_2))], axis=1)
levers = np.linalg.norm(J, axis=0)
if ram: # the barrel's lever with the rod's slide at 0
levers[0] = np.linalg.norm(np.cross(at_1[:3, 2], placed((values[0], 0.0))[2][:3, 3] - at_1[:3, 3])) * (math.pi / 180.0)
singular = 0.0 if levers.min() < 1e-12 else float(np.linalg.svd(J / levers, compute_uv=False)[-1])
here = float(n @ np.cross(J[:, 0], J[:, 1])) > 0.0
side = here if side is None else side
if here != side:
raise KitError(f"the loop is past a dead centre (the step takes the two joints that move closing socket {closing['name']!r} to their "
f"other assembly: conditioning {singular:.3g} on that side)")
if singular < FOLLOW_SINGULAR:
raise KitError(f"the loop is at a dead centre (its two joints move closing socket {closing['name']!r} along one line: "
f"conditioning {singular:.3g}, under {FOLLOW_SINGULAR:g})")
if float(np.linalg.norm(error)) <= FOLLOW_TOLERANCE:
break
if iteration == FOLLOW_ITERATIONS:
raise KitError(f"the loop did not close in {FOLLOW_ITERATIONS} steps (closing socket {closing['name']!r} stands "
f"{float(np.linalg.norm(error)):.6g} m off in the plane)")
values = values + np.linalg.lstsq(J, error, rcond=None)[0]
apart = closure_residual(np.eye(4), {"matrix": end}, np.eye(4), {"matrix": target})
if apart > HELD:
raise KitError(f"the loop closes in its plane and closing socket {closing['name']!r} misses along the pin by {apart:.6g} m")
return (float(values[0]), float(values[1])), iteration
def joint_rows(root_world, entries) -> tuple[list, int]:
"""(the rows of a joints report, how many rigid connections folded into them). `entries` is every connection of
a tree in an order where a part comes after its parent: (id, the parent part's id, part name, parent socket, the
parent's 4x4 world, DOF kind or None for rigid, value, joint record, driven: what the report says drives it, or
None). A row is a revolute or prismatic connection; its parent is the nearest one above it (a rigid connection
belongs to the joint above it), its axis and origin the parent socket's z and origin in the frame of root_world,
min and max what the limits leave of the value either way, and held whether the limits are of one value: a
joint with no travel, which is no degree of freedom (the one-driver rule's held pin)."""
frame, nearest, rows, rigid = np.linalg.inv(np.asarray(root_world, dtype=np.float64)), {}, [], 0
for name, parent, part_name, socket, parent_world, kind, value, record, driven in entries:
if kind is None:
nearest[name], rigid = nearest.get(parent), rigid + 1
continue
at = frame @ np.asarray(parent_world, dtype=np.float64) @ socket["matrix"]
limits = record["limits"] and [round(v, 6) for v in record["limits"]]
rows.append({"id": name, "parent": nearest.get(parent), "part": part_name, "socket": f"{parent}:{socket['name']}", "kind": kind,
"axis": [round(float(v), 6) for v in at[:3, 2]], "origin": [round(float(v), 6) for v in at[:3, 3]], "value": round(value, 6),
"limits": limits, "min": limits and round(record["limits"][0] - value, 6), "max": limits and round(record["limits"][1] - value, 6),
"held": limits is not None and record["limits"][0] == record["limits"][1],
"mechanism": record["mechanism"], "compliance": record["compliance"], "driven": driven})
nearest[name] = name
return rows, rigid
EQUAL, SLACK = 0.01, 1e-9 # 'equal' sizes may differ by 1 percent of the larger; SLACK keeps a size at the limit inside it

View file

@ -182,7 +182,10 @@ Behaviour the table does not say, per action:
- `createObject`: a `MESH` is a cube of `size`. `lightType`, `emptyDisplayType` and `meshType` apply
only to their own `objectType`.
- `setObjectParent`: an empty or absent `parentObjectName` clears the parent.
- `setObjectParent`: an empty or absent `parentObjectName` clears the parent. Before it writes, each enabled
add-on that defines `brokkr_parent_refusal(object, parent)` is asked, and a reason it answers refuses the
intent with nothing changed (`brokkr_kitbash` answers its one-driver rule over the loops the object is part
of or stands above, `docs/kitbash.md`; an object no loop hangs from is never refused by it).
- `importGltf`: `filepath`, `.gltf` or `.glb`, relative to the add-on preference
`Import Directory` (absolute paths, `..` and symlinks that resolve outside it are
refused). Empty `Import Directory` disables the action. Needs Blender's glTF add-on.

View file

@ -176,8 +176,8 @@ matrix_basis = S_parent @ T(0, 0, slide) @ Rz(roll) @ FLIP @ inverse(S_child)
```
with `S` each socket's frame in its own part at that part's stored params (`core.mate`); a turn about z and a move
along it commute, so one connection carries both. `attach`, `set_params`, `roll`, `aim`, `reach`, `slide` and
`joint` write it; nothing else should.
along it commute, so one connection carries both. `attach`, `set_params`, `roll`, `aim`, `reach`, `slide`,
`joint` and `follow` write it; nothing else should.
**Joint records.** A connection's degree of freedom is its parent socket's type's: a socket type states
`"dof": "revolute"` (the child turns about the socket's z: `pivot`), `"dof": "prismatic"` (it slides along it:
@ -191,14 +191,91 @@ roll is a build angle. Beside the value the child's connection carries a record:
| `kit_min`, `kit_max` | the limits of the value, both or neither: degrees on a revolute joint (a span of at most 360, each end within 360 of 0), metres on a prismatic one (each end within 10 m of 0) | `joint` |
| `kit_mechanism` | a label of 1 to 32 `a-z`, `0-9` and `_`: which mechanism the joint is (`knee`, `shock`) | `joint` |
| `kit_compliance` | `{"hertz", "damping_ratio"}` (hertz over 0 to 30, damping ratio 0 to 2): a slide in the load path that settles and rebounds under load. Prismatic only, and it needs limits, the travel it settles within | `joint` |
| `kit_follows`, `kit_follows_driver` | that the value is derived from another joint's: `{"kind": "ratio", "k", "offset"}` or `{"kind": "loop"}`, and an ID pointer to the driver, which follows a rename | `follow` |
Every one of them is written by one function, `write_connection`, which `attach`, `roll`, `aim`, `reach`, `slide`
and `joint` all seat through; `detach` clears them with the connection. So the limits have one check: a value with
no representative inside them is refused before anything is written, naming value and limits, and a roll a turn
away from its limits is written as the roll inside them (limits 150 to 210 and a roll of -170: 190). `aim` inside
limits takes the free roll when the limits hold it and otherwise the end that points the axis nearer; `reach`
takes only a root inside them. A new connection states no record. A value written by hand outside its limits
reads `within: false` in every report and the next pose of that part is refused.
Every one of them is written by one function, `write_connections`, which `attach`, `set_params`, `roll`, `aim`,
`reach`, `slide`, `joint` and `follow` all seat through; `detach` clears them with the connection. It takes
several connections and checks every one before it writes any, so a driver and its followers are written together
or not at all. So the limits have one check: a value with no representative inside them is refused before anything
is written, naming value and limits, and a roll a turn away from its limits is written as the roll inside them
(limits 150 to 210 and a roll of -170: 190). `aim` inside limits takes the free roll when the limits hold it and
otherwise the end that points the axis nearer; `reach` takes only a root inside them. A new connection states no
record. A value written by hand outside its limits reads `within: false` in every report; a pose that puts it
inside them is accepted and clears that, and `set_params` of the part or of its parent is refused until then, as
it is for a slide written by hand on a connection that is not prismatic. A record written by hand that its
connection may not carry (a compliance on a revolute joint) reads null in every report and goes at the next write.
**Followers.** A joint whose value is a function of another's is a follower, and `follow` states it. A follower has
exactly one driver and a driver is never a follower (aetheria-release:ruling:one-joint-one-driver); `roll`, `aim`,
`reach` and `slide` on a follower are refused naming its driver, and `joint` on one states limits and a mechanism
and keeps the derived value. Posing a driver derives every follower in the same action and writes them with it: a
follower outside its own limits, or a loop that cannot close, refuses the pose with nothing changed.
| Kind | The follower's value | For |
| --- | --- | --- |
| `ratio` | `k` x the driver's value + `offset`, either joint revolute or prismatic (a slide following a roll has `k` in metres per degree). The driver states limits, so its value is one number and not one of many a turn apart | a kneecap on the bisector (`k` 0.5), lames at `k/n` of the knee, a pinion at minus ring over pinion, a crosshead |
| `loop` | solved: the part that states a closure and its parent both follow, and their two values are the ones at which the closure holds | a rocker and coupler closing on a crank; a ram's barrel and rod closing on the part it pushes; a torque link's two arms |
A loop has exactly two unknowns, the closing part's joint and its parent's, and it is planar: each revolute pin is
parallel to the pin it closes on and each slide runs across it. Exactly one of its two ends (the parent's parent,
and the part closed on) moves with the driver: it is the driver, follows it, or hangs from one that does. And the
driver is the only input the two ends depend on: every revolute or prismatic joint between an end and the part the
two ends share (or the root, when they share none) is the driver, follows it, or is held by limits of one value. A
joint there that follows another driver, or that follows nothing and has travel, is a second driver: a pose of it
would open the loop, and nothing here solves a loop for two drivers. The rule is read before each write, over
each loop the write touches, as the scene would stand after it (`one_driver`, asked by the one writer of
connections, by `set_params` before it rebuilds a mesh, by `detach` and by Brokkr's `setObjectParent`), so it holds
after the loop is stated as it does when `follow` states it. A write touches a loop when a part it writes is the
closing follower, the part closed on or the driver, or one of those hangs from it; no other write can change what
the loop's ends depend on, and no other loop is read. Each of these is refused with
nothing changed, naming the loop's driver and each other one: `attach` of an end's root on a pin or a slide,
`detach` of a part between an end and the part both ends hang from, `follow` with null on a follower between the
ends, `joint` widening or clearing limits that held a pin there, `setObjectParent` giving or clearing a parent
between the ends, and any write that touches the loop once such a joint was written by hand. To change a mechanism between a loop's ends, give the new joint its one driver or its one value first, or
clear the loop and state it again. A loop whose driver is detached is derived by nothing and is not read; the
attach that gives the driver a connection again reads it. A torque link is the case for limits of one value: a
real torque link exists to stop the rod rolling in its barrel, so its lug has no travel, and a strut pinned to
the rod's end and held by limits `[90, 90]` is that lug (a strut's two pins face one way, so the lower arm cannot
close on the rod's own pin). The lug is held before the arms follow the rod's slide. Nothing
stores a pin position or a linkage record: `core.close_loop` solves the pair from the kits' socket frames at the
parts' stored params each time, by Newton's method on the closing pin's error in the loop's plane with the analytic
Jacobian. That is the position analysis of the kinematics texts (Nikravesh, *Computer-Aided Analysis of Mechanical
Systems*, 1988, ch. 4; Uicker, Pennock and Shigley, *Theory of Machines and Mechanisms*); the ratio is Box2D's
`b2GearJoint` and Jolt's `GearConstraint` and `RackAndPinionConstraint`. A loop has two assembly branches and
Newton finds the one nearest its seed, so a driver steps to its new value 5 degrees or 0.02 m at a time, each solve
seeded by the one before, and only the last step is written: the linkage stays on the branch it was built on.
Loops are solved in an order where a loop's base and the part it closes on are already placed (a ram closing on a
four-bar's rocker waits for the four-bar); loops that wait on each other are refused. At a dead centre, where the
pair's two joints move the closing pin along one line, the pose is refused naming the driver's value and the
closing part: the bound is 0.093 on the smaller singular value of the Jacobian with each column scaled by its lever.
For two revolute joints the columns are unit vectors and the reading is the two joints within about 7.6 degrees of
in line (the four-bar of `tests/test_kitbash.py` reads 0.184 at its last accepted step and 0.047 at the first
refused one). A ram's dead centre is its rod's end on its barrel's pin, where the barrel's roll is undefined, and
its two columns are across each other everywhere else, so the barrel's column is scaled by its lever with the slide
at 0 and the reading is the ram's lever over its closed lever: a ram drawn in to 0.184 of its closed lever is
accepted and one at 0.047 refused. The sign of the Jacobian's determinant about the pin is the assembly branch (an
elbow bent one way or the other, a rod's end on one side of its barrel's pin or the other), and a Newton step that
lands on the other sign from its seed is refused as past the dead centre, so no pose answers the other branch.
A ram whose limits keep its slide clear of minus its closed length never comes near either: its slide leaves its
limits first. One whose limits reach that far is refused by the bound above before it leaves them.
What followers give up: a loop of three or more unknowns, or one out of a plane, is not solved (follow-up
`kit-follows-wider-loops`); a follower does not drive another; `set_params` never derives a follower again, so a
loop it opens reads `holds: false` until its driver is posed; and a loop
with a second driver (a limit widened by hand, a parent set in Blender's own interface, a saved file) refuses
every write that touches it (a write of a connection, a `set_params` or a `setObjectParent` of one of its parts
or of a part it hangs from, whether or not that write is the fault) until the joint is held again, follows the
driver, or the loop is cleared. A write that touches no such loop is made: a camera, an empty or a part of
another mechanism is posed and given a parent as before, and so is an object parented under a part of the loop. A connection's row in a report carries `follows: {driver, kind, k, offset, holds, reason}`:
`holds` is false, with a reason, when the value stands off the ratio, the loop has more than one driver, the loop's
closure does not hold, or the driver is gone or states no revolute or prismatic connection. A loop with a second
driver reads `holds: false` on both its followers whether or not its closure stands closed, and the reason names
the loop, its driver and each other one: the remedy is to hold that joint, have it follow the driver or clear the
loop, not to pose the driver. The joints report lists the same loops in `manyDrivers`. Both read the scene as it
stands by the reading the refusals use, so a second driver that no action wrote is told by the next report and
not first by a refused write. Detaching a driver leaves its followers'
statements; detaching a loop follower clears its partner's. No Blender driver or constraint is made: a follower's
pose is its stored value, as every connection's is.
Limits and springs follow Box2D v3's `b2PrismaticJointDef` and Jolt's `SliderConstraintSettings`: the slide's
limits and a spring as a frequency in hertz and a damping ratio sit on the joint itself. Frequency and damping
@ -211,24 +288,49 @@ is the parent tree. `brokkr_kitbash.joints` derives both at each call and emits
nothing:
```json
{"schema": "brokkr.joints", "version": 1, "root": "Tank", "frame": "the root object's: Blender axes (+Z up), metres",
"rigid": 2, "joints": [
{"schema": "brokkr.joints", "version": 2, "root": "Tank", "frame": "the root object's: Blender axes (+Z up), metres",
"rigid": 2, "unlimited": ["Barrel"], "manyDrivers": [], "next": null, "joints": [
{"id": "Strut", "parent": null, "part": "strut", "socket": "Mount:pivot", "kind": "revolute",
"axis": [0.0, 1.0, 0.0], "origin": [0.436, 0.0, 0.85368], "value": -113.019997, "limits": [-116.02, -40.02],
"min": -3.000003, "max": 72.999997, "mechanism": "knee", "compliance": null},
"min": -3.000003, "max": 72.999997, "mechanism": "knee", "compliance": null, "held": false, "driven": null},
{"id": "Cap", "parent": "Strut", "part": "strut", "socket": "Strut:end_a_back", "kind": "revolute",
"axis": [0.0, -1.0, 0.0], "origin": [0.436, -0.09, 0.85368], "value": -56.509999, "limits": null,
"min": null, "max": null, "mechanism": null, "compliance": null, "held": false,
"driven": {"by": "Strut", "kind": "ratio", "k": 0.5, "offset": 0.0}},
{"id": "Rod", "parent": "Barrel", "part": "ram_rod", "socket": "Barrel:bore", "kind": "prismatic",
"axis": [0.97429, 0.0, 0.225296], "origin": [1.072572, 0.124, 1.312762], "value": 0.12, "limits": [0.0, 0.3],
"min": -0.12, "max": 0.18, "mechanism": "shock", "compliance": {"damping_ratio": 0.7, "hertz": 4.0}}]}
"min": -0.12, "max": 0.18, "mechanism": "shock", "compliance": {"damping_ratio": 0.7, "hertz": 4.0},
"held": false, "driven": null}]}
```
A row per revolute or prismatic connection under the root, depth first with children by name, so a row's parent
comes before it. `parent` is the nearest joint above, not the object the part hangs from: rigid connections fold
into it and are counted in `rigid`. `axis` and `origin` are the parent socket's z and origin in the root object's
comes before it; a root that itself states a revolute or prismatic connection has its own row first, with `parent`
null, so a report of a sub-tree carries the joint the sub-tree hangs by. `parent` is the nearest joint above, not
the object the part hangs from: rigid connections fold into it and are counted in `rigid`. `axis` and `origin` are the parent socket's z and origin in the root object's
frame. `min` and `max` are the limits less the value, the travel either way from the pose the report was taken at,
which is the shape of Aetheria's `ShipJoint` (`Min` and `Max` about rest). What the report gives up: it is the
pose at the call, so rest is whatever the assembly stood at; it carries no meshes or bone names, so a consumer
joins rows to the exported objects by `id`; and `ShipJoint` has no slide and no spring yet
(aetheria-release:question:shipjoint-prismatic-dof), so a prismatic row has no Aetheria reader today.
which is the shape of Aetheria's `ShipJoint` (`Min` and `Max` about rest). `held` is true when the limits are of
one value: the joint has no travel (a torque link's lug held at `[90, 90]`), its `min` and `max` are 0, and the
rig generator will make a fixed bone for it and not a degree of freedom (nothing reads joints rows yet:
`brokkr_rig` reads meshes); a held row is in neither `unlimited` nor `rigid`. `held` is computed from the limits
alone and is not the free `mechanism` label: a joint labelled `"held"` that has travel reads `held: false`. `driven` is null, or what the row follows
(`by` the driver's id, `kind`, `k`, `offset`): a driven row's value is derived, so the rig generator will make a
driven bone for it and not a degree of freedom. `unlimited` lists the ids of the rows this report carries that are not driven and
state no limits, so an exporter that needs limits on every degree of freedom refuses by reading one field of each
report. `manyDrivers` lists each loop with more than one driver that has a part in the tree under the root (its
closing part, that part's parent, the part closed on, the base, or one of its drivers), as
`{"loop": the closing part, "drivers": [the loop's driver, each other one]}` by the closing part's name: its
driven rows are not a function of one driver, so a rig generator refuses the tree while the list is not empty. It
is of the whole tree, as `rigid` is, and every page carries it. A tree whose rows a receipt cannot carry (about 60 rows, 33 with names of 62 characters) is read in pages:
`jointsOmitted` counts the rows left off, `next` is then the id of the last row carried, and a call with `after`
set to it carries the rows that follow, with their own `unlimited`. A row and its id in `unlimited` are kept or left
off together, so a report is never over a receipt and always carries a row.
`ShipJoint` is ruled to gain a kind per degree of freedom and an optional spring
(aetheria-release:ruling:shipjoint-gains-kind-and-spring), and the rows map to it one to one: `revolute` is its
`rotate` and `prismatic` its `slide`, with slide limits in metres, and `compliance` is its spring's hertz and
damping ratio. Brokkr keeps the kinematics names, which its kits' socket types state. What the report gives up: it
is the pose at the call, so rest is whatever the assembly stood at, and it carries no meshes or bone names, so a
consumer joins rows to the exported objects by `id`.
**What may mate** (`core.mate_refusal`): two sockets of one type whose sizes agree as the type's
`match` says: `equal` within 1 percent of the larger, `fits` with the child at most the parent. Socket types are a
@ -341,7 +443,9 @@ that breaks one (a `pipe_r` that no longer matches the flange it is bolted to) i
connection.
**Drift.** `setObjectTransform` and `setObjectParent` are Brokkr's own rows and can move or re-parent an attached
child. Reports show it: a part's `connection` is `null`, or
child; `setObjectParent` refuses only a parent that would give a stated loop a second driver, or the parent of a
part a loop that already has one hangs from ("Followers").
Reports show it: a part's `connection` is `null`, or
```json
{"parent": "Tee", "socket": "mount", "parentSocket": "c", "roll": 37.0, "residual": 2.1e-07, "holds": true}
@ -413,8 +517,8 @@ off in viewports and renders. Nothing is removed: the cutter objects stay, a cut
is attached to it, and `booleans` still lists what cuts the object. The frozen mesh's material slots are the
object's own (an empty one it had included), followed by any a cutter brought; faces a cutter made from an empty
slot of its own take the first slot. A frozen kit part keeps `kit_kit`, `kit_part`, `kit_params` and its
connections: its sockets are still derived from the params, so `attach`, `detach`, `roll`, `aim`, `reach` and
`close` work on it and on what hangs from it. `freeze` reports the part (or `object`), `frozen`, `faces` (the live
connections: its sockets are still derived from the params, so `attach`, `detach`, `roll`, `aim`, `reach`, `joint`,
`slide`, `joints`, `follow` and `close` work on it and on what hangs from it. `freeze` reports the part (or `object`), `frozen`, `faces` (the live
mesh's count, as in every report), `evaluated: {faces, volume, nonManifoldEdges}` (the frozen mesh), `modifiers`
and `booleans`. `report` on a frozen part gives `faces`, still the live mesh's, and `evaluated: {faces}`, the
frozen mesh's.
@ -1479,12 +1583,13 @@ under such load (five runs), and reading a 336-face part takes 27 to 37 ms.
| `brokkr_kitbash.report` | `object_name` (default: every kit part) | Each part as the scene has it: kit, part, params, faces, shells, each socket's world frame, `connection`, `closure` and `frozen`; a frozen part adds `evaluated: {faces}`, and `dirty` (with `frozen` false) when a modifier of it is shown again. `faces` is the live mesh's count. Changes nothing and evaluates no modifier. |
| `brokkr_kitbash.attach` | `object_name` (the child), `socket`, `parent_name`, `parent_socket`, `roll` (degrees, -360 to 360, default 0) | Seats the child's socket on the parent's and parents it there; the two parts are of one kit or of two whose socket types agree. Reports the child. |
| `brokkr_kitbash.detach` | `object_name` | Clears the part's connection and the closure it states; it stays where it stands. Refuses a part that has neither. |
| `brokkr_kitbash.roll` | `object_name`, `roll` (degrees, -360 to 360) | Turns an attached part to that roll where it hangs. Refuses a part that is not attached. Reports the part and `closures` as `set_params` does. |
| `brokkr_kitbash.roll` | `object_name`, `roll` (degrees, -360 to 360) | Turns an attached part to that roll where it hangs, and every follower of it with it ("Followers"; the report's `followers` lists each as `{part, value}`). Refuses a part that is not attached, and a follower, naming its driver. Reports the part and `closures` as `set_params` does. |
| `brokkr_kitbash.aim` | `object_name`, `axis` (`+x`, `-x`, `+y`, `-y`, `+z` or `-z`, the part's own), `direction_x`, `direction_y`, `direction_z` (world, any length) | Solves the roll that turns the axis as far toward the direction as the pin lets it, and turns the part to it. Refuses an axis or direction along the pin. Reports the part, `aimed: {roll, dot}` and `closures`. |
| `brokkr_kitbash.reach` | `object_name`, `socket` (one of the part's), `height` (metres, -1000 to 1000), `direction_x`, `direction_y`, `direction_z` (world; default 0, 0, 1) | Solves the roll that brings the socket's origin to `height` along the direction, the nearer of the two, and turns the part to it. Refuses a height out of reach, naming the range. Reports the part, `reached: {roll, residual}` and `closures`. |
| `brokkr_kitbash.joint` | `object_name`, `record` (a JSON object of any of `limits`: `[lo, hi]` or null; `mechanism`: a label or null; `compliance`: `{hertz, damping_ratio}` or null) | States the joint record of an attached part's connection; a key left out keeps what is stated and null clears it. Refuses a rigid connection naming its socket type, limits that do not hold the value the joint has, revolute limits over a turn or past 360, prismatic limits past 10 m, and compliance on a revolute joint or without limits. Reports the part and `closures` as `roll` does |
| `brokkr_kitbash.slide` | `object_name`, `slide` (metres, -10 to 10) | Slides an attached part along its parent socket's normal on a prismatic connection, where it hangs. Refuses a revolute or rigid connection naming its socket type, and a slide outside the joint's limits. Reports the part and `closures` as `roll` does |
| `brokkr_kitbash.joints` | `object_name` (the root, a kit part) | Reports the joints of the tree attached under the root as `brokkr.joints` version 1: a row per revolute or prismatic connection, parents first, with `id`, `parent`, `part`, `socket`, `kind`, `axis`, `origin`, `value`, `limits`, `min`, `max`, `mechanism` and `compliance`, in the root's frame ("Joint records"). Changes nothing |
| `brokkr_kitbash.joint` | `object_name`, `record` (a JSON object of any of `limits`: `[lo, hi]` or null; `mechanism`: a label or null; `compliance`: `{hertz, damping_ratio}` or null) | States the joint record of an attached part's connection; a key left out keeps what is stated and null clears it. A follower keeps its derived value, and a driver's followers are derived again. Refuses a rigid connection naming its socket type, limits that do not hold the value the joint has, revolute limits over a turn or past 360, prismatic limits past 10 m, and compliance on a revolute joint or without limits. Reports the part and `closures` as `roll` does |
| `brokkr_kitbash.slide` | `object_name`, `slide` (metres, -10 to 10) | Slides an attached part along its parent socket's normal on a prismatic connection, where it hangs, and every follower of it with it. Refuses a revolute or rigid connection naming its socket type, a slide outside the joint's limits, and a follower. Reports the part and `closures` as `roll` does |
| `brokkr_kitbash.joints` | `object_name` (the root, a kit part), `after` (default empty: an id, the `next` of the report before) | Reports the joints of the tree attached under the root as `brokkr.joints` version 2: a row per revolute or prismatic connection, parents first and the root's own first when it states one, with `id`, `parent`, `part`, `socket`, `kind`, `axis`, `origin`, `value`, `limits`, `min`, `max`, `held`, `mechanism`, `compliance` and `driven`, in the root's frame, and `unlimited`, `manyDrivers` (the loops with more than one driver) and `next` beside them ("Joint records"). With `after`, the rows after that id. Changes nothing and evaluates no modifier. |
| `brokkr_kitbash.follow` | `object_name` (the follower; for a loop, the part that states the closure), `record` (JSON: `{driver, kind: "ratio", k, offset}`, `{driver, kind: "loop"}` or null) | States that the part's joint follows the driver's, by a ratio or by keeping its closure closed with its parent's joint, and moves it there at once; null clears the statement, and a loop partner's with it ("Followers"). Refuses a rigid connection, a driver that is the follower, below it or itself a follower, a follower that already follows or drives another, a ratio whose driver states no limits, and a loop without a closure that holds, with both ends or neither moving with the driver, whose ends depend on another driver or on a joint posed by hand, that is not planar or that stands at a dead centre. Reports the part, `followers` and `closures`. |
| `brokkr_kitbash.close` | `object_name` (the closing part), `socket`, `other_name`, `other_socket` | States that the closing part's socket meets the other part's, closing a loop. Accepted only when they already meet; moves nothing. Reports the closing part. |
| `brokkr_kitbash.boolean` | `object_name` (any mesh), `cutter`, `operation` (`DIFFERENCE`, `UNION` or `INTERSECT`; default `DIFFERENCE`) | Adds the cutter to the collection of the target's one live Exact Boolean for the operation, above the Bevel. Refuses a cutter that is the target, is not a mesh, or already cuts it, and a scaled target. Reports the part (or `object` for a mesh that is not one), `booleans: [{cutter, operation}]` (difference, union, intersect; each in the order added; `booleansOmitted` counts rows a receipt had no room for) and `evaluated`. |
| `brokkr_kitbash.cut` | `object_name` (any mesh), `cutter_name`, `part` (`box`, `cyl`, `slot`, `slab`), `params`, `origin_x/y/z`, `direction_x/y/z`, `up_x/y/z` (default 0, 0, 1), `roll` (degrees, default 0), `axis_x/y/z` (default 0, 0, 0: the surface normal) | Places a `cutters` part where the ray meets the target, parented to it, and adds it to the target's difference Boolean. Refuses a ray that misses or has no direction, a name an object has, an `up` along the cutter's axis, an `axis` into the surface and a scaled target. Reports `object`, the `cutter` with its floor sockets, and `booleans` (with `booleansOmitted`, as `boolean`). |
@ -1624,4 +1729,5 @@ frame `cut` gives a cutter. `MateTests` covers the mate arithmetic and what may
re-parameterised, a beam seated on a bracket), `tests/live/kitbash_assembly.py` (attach, detach,
`set_params` on assemblies, a braced leg closed by `close`, boolean, and freeze and thaw with what a frozen part costs), `tests/live/kitbash_shell.py`
(`cut` and `cut_many` on a cage that is not a kit part, a part on a cutter's floor, the three Boolean modifiers, an object in no
collection) and `tests/live/kitbash_pose.py` (roll, aim and reach).
collection), `tests/live/kitbash_pose.py` (roll, aim, reach and joint records) and `tests/live/kitbash_follows.py`
(followers: a four-bar, a ram closing on its rocker, ratios, a torque link, the one-driver refusals, and a joints report in pages).

View file

@ -518,6 +518,7 @@
"brokkr_kitbash.joint",
"brokkr_kitbash.slide",
"brokkr_kitbash.joints",
"brokkr_kitbash.follow",
"brokkr_kitbash.close",
"brokkr_kitbash.boolean",
"brokkr_kitbash.cut",

View file

@ -0,0 +1,669 @@
"""Live proof, in a background Blender, of brokkr_kitbash followers through run_intent: brokkr_kitbash.follow states a
ratio or a loop, posing a driver derives every follower in the same action (core.close_loop for a loop), a follower
refuses to be posed, brokkr.joints version 2 marks driven rows and pages, and each refusal changes nothing. Not part of
the unittest run: it needs Blender.
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_follows.py -- <out>
Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses
without them). <out> is an absolute path; writes <out>.result.json and exits 1 when a check failed. The checks run
inside one try: an uncaught error is a failed check that names the check before it.
The scene, every strut 0.09 wide so its pins take a ram's: a four-bar (Crank on the root Ground, Rocker on the root
Base, Coupler closing on the crank); a ram (A_Barrel on the root Pad, A_Rod in its bore, closing on the rocker), named
to sort before the four-bar it waits on; ratio followers of the crank (Cap, Pinion, and X_Rod's slide in X_Barrel); a
torque link (T_Rod sliding in the root T_Barrel, T_Upper and T_Lower closing on T_Lug, a strut on the rod's
rod_end_back held at 90 degrees by limits of that one value. A real torque link exists to stop the rod rolling in its
barrel, so a lug with no travel is the mechanism and not a way around the kit; and a strut's two pins face one way, so
two arms from the barrel's pin cannot face the rod's own); a second crank (Crank2 on the root Ground2)
whose ram closes on the rocker, and a loop hung from its own driver (K3, B3, Rk3, Cp3 on the root G3), for the
one-driver refusals at the statement, and after it an attach, a clear, widened limits, a pose over limits written by hand and a
detach that would each give a stated loop a second driver, and the reads that tell of one made by hand (follows.holds, the joints report's manyDrivers); Idle and Tip for the refusals and for the writes a two-driver loop does not refuse; a tree of 264 struts with 62-character names for a joints
report over several receipts. Bounds follow lodur:ruling:deterministic-bound-margin, both readings beside each; the
result file carries the readings.
"""
import importlib.util
import json
import math
import os
import sys
import tempfile
import time
import traceback
import types
from pathlib import Path
import bpy
import numpy as np
from mathutils import Matrix
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")
package = types.ModuleType("brokkr_bridge")
package.__path__ = [str(SURFACE / "brokkr_bridge")]
sys.modules["brokkr_bridge"] = package
from brokkr_bridge import blender_target as bt # noqa: E402
import addon_utils # noqa: E402
spec = importlib.util.spec_from_file_location("brokkr_kitbash_core_reference", SURFACE / "brokkr_kitbash" / "core.py")
core = importlib.util.module_from_spec(spec) # core as the unit tests load it: the frames every reading here is taken against
spec.loader.exec_module(core)
sys.path.append(str(SURFACE))
bpy.ops.wm.read_factory_settings(use_empty=True)
for module in ("brokkr_mesh_polish", "brokkr_kitbash"):
addon_utils.enable(module, default_set=True)
target = bt.BrokkrBlenderTarget(bpy)
WORK = Path(tempfile.mkdtemp(prefix="brokkr-kitbash-follows-"))
target.configure_action_dirs("", str(WORK))
target.reload_host_actions()
R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], "readings": {}}
COUNT = [0]
kit = core.load_kit("mechanical")
# Each mutant's reading below is its least over the cases here that it changes; the shipped reading is the worst.
# Metres (or a difference of unit vectors) between a loop's closing socket and the socket it closes on, read from the two
# world matrices after a driver was posed; a rod's slide against this file's own solve reads against it too. Shipped
# worst 6.4e-07 (float32 matrices); least claimed mutant 0.041 (F11, the ram solved before the four-bar whose rocker it
# closes on, at the smallest turn here); separation 250 each side.
CLOSED = 1.6e-4
# Degrees between a loop follower's roll and the one this file solves by its own steps of core.close_loop from the rest
# pose. Shipped worst 3.3e-05 (an action's roll is a float32 field); least claimed mutant 2.7 (F11 again: the barrel
# aimed at where the rocker was); separation 290 each side.
SOLVED = 9.4e-3
# A ratio follower's roll in degrees or slide in metres against k x the driver's value + offset, read from the stored
# values. Shipped 0: the same doubles. A rule, a double's rounding at these sizes (6e-14 at 360) with room; mutant R1
# (the ratio taken from the driver's value before the pose) reads 0.09 on the crosshead's slide and 45 on the kneecap.
RATIO = 1e-9
ROT = [0.3, -0.2, 0.5] # the roots' rotation: no axis of the scene lines up with the world's
D0, REST = 30.0, (-40.0, 70.0) # the four-bar at rest: the crank's roll, and the rocker's and coupler's
RAM_REST = (200.0, 0.1) # the ram at rest: the barrel's roll and the rod's slide
def check(name, ok, detail=None):
try:
json.dumps(detail, default=str)
except TypeError:
detail = repr(detail)
R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail})
def reading(name, value):
R["readings"][name] = max(R["readings"].get(name, 0.0), float(value))
return float(value)
def send(action, **fields):
COUNT[0] += 1
receipt = target.run_intent(bpy.context, {"commandId": f"live-{COUNT[0]}", "requestedBy": "test/driver", "action": action, **fields})
result = None
if receipt.get("hostResult"):
try:
result = json.loads(receipt["hostResult"])
except ValueError:
result = None
if not action.endswith(("place_part", "attach")) or receipt["status"] != "accepted":
print("SEND", action, receipt["status"], str(receipt["message"])[:300], flush=True)
return receipt, result
def place(name, part, params="", world=None):
send("brokkr_kitbash.place_part", part=part, object_name=name, params=params)
if world is not None:
world = Matrix(np.asarray(world).tolist())
send("setObjectTransform", targetObjectName=name, location=list(world.translation), rotationEuler=list(world.to_euler("XYZ")))
return bpy.data.objects[name]
def attach(name, socket_name, parent, parent_socket, roll=0.0):
receipt, _ = send("brokkr_kitbash.attach", object_name=name, socket=socket_name, parent_name=parent, parent_socket=parent_socket, roll=roll)
return receipt["status"] == "accepted"
def socket(obj, name):
built = core.build(core.part(kit, obj["kit_part"]), json.loads(obj["kit_params"]))
return next(s for s in built.sockets if s["name"] == name)
def world(obj):
return np.array(obj.matrix_world, dtype=np.float64)
def frame(obj, name):
"""A socket's world frame, from the object's matrix_world and core's build of its stored params."""
return world(obj) @ socket(obj, name)["matrix"]
def apart(obj, name, other, other_name):
"""How far two sockets stand from meeting as a pin, read from the scene: origins apart, or normals not opposed."""
a, b = frame(obj, name), frame(other, other_name)
return max(float(np.abs(a[:3, 3] - b[:3, 3]).max()), float(np.abs(a[:3, 2] + b[:3, 2]).max()))
def connection(name):
receipt, report = send("brokkr_kitbash.report", object_name=name)
return report["parts"][0]["connection"] if report else {"error": receipt["message"]}
def scene_state():
return {o.name: (o.parent and o.parent.name, np.round(np.array(o.matrix_basis), 6).tolist(), np.round(np.array(o.matrix_parent_inverse), 6).tolist(), len(o.data.vertices),
{k: repr(o[k]) for k in sorted(o.keys()) if k.startswith("kit_")}) for o in bpy.data.objects}
def refused(label, action, fields, *expected):
state = scene_state()
receipt, _ = send(action, **fields)
check(f"refused, scene unchanged: {label}", receipt["status"] != "accepted" and all(text in str(receipt["message"]) for text in expected) and scene_state() == state,
[receipt["status"], receipt["message"], expected])
def stepped(solve, seed, start, end, step):
"""This file's own derivation: the loop's two values after the input goes from start to end in steps of at most `step`."""
count = max(1, math.ceil(abs(end - start) / step))
for index in range(1, count + 1):
seed, _ = solve(start + (end - start) * index / count, seed)
return seed
def turned(a, b):
return abs((a - b + 180.0) % 360.0 - 180.0)
try:
rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")]
check("follow loads as a host action after joints, with no errors", not R["hostErrors"] and "brokkr_kitbash.joints" in rows
and rows[rows.index("brokkr_kitbash.joints") + 1] == "brokkr_kitbash.follow", [R["hostErrors"], rows])
# --- the four-bar -----------------------------------------------------------------------------------------------------
turn = np.eye(4)
turn[:3, :3] = core._rotation([math.degrees(v) for v in ROT])
turn[:3, 3] = [1.0, 2.0, 3.0]
W = "width=0.09; "
ground = place("Ground", "strut", W + "length=0.8", turn)
crank, rocker, coupler = place("Crank", "strut", W + "length=0.5"), place("Rocker", "strut", W + "length=0.9"), place("Coupler", "strut", W + "length=0.7")
attach("Crank", "end_a", "Ground", "end_a", D0)
def crank_pin(roll, name="end_b"):
return world(ground) @ core.mate(socket(ground, "end_a"), socket(crank, "end_a"), roll) @ socket(crank, name)["matrix"]
def rocker_world(base_world, roll):
return base_world @ core.mate(socket(ground, "end_a"), socket(rocker, "end_a"), roll)
end = rocker_world(turn, REST[0]) @ core.mate(socket(rocker, "end_b"), socket(coupler, "end_a"), REST[1]) @ socket(coupler, "end_b")["matrix"]
shift = np.eye(4)
shift[:3, 3] = crank_pin(D0)[:3, 3] - end[:3, 3]
base = place("Base", "strut", W + "length=0.8", shift @ turn) # where the loop closes at rest
attach("Rocker", "end_a", "Base", "end_a", REST[0])
attach("Coupler", "end_a", "Rocker", "end_b", REST[1])
receipt, report = send("brokkr_kitbash.close", object_name="Coupler", socket="end_b", other_name="Crank", other_socket="end_b")
check("the four-bar stands closed at rest: crank on Ground, rocker on Base, the coupler's end closing on the crank's", receipt["status"] == "accepted"
and report["closure"]["holds"] is True, [receipt["message"], report and report["closure"]])
four_bar = [(socket(base, "end_a"), socket(rocker, "end_a"), "revolute"), (socket(rocker, "end_b"), socket(coupler, "end_a"), "revolute")]
def solve_four_bar(roll, seed):
return core.close_loop(world(base), four_bar, socket(coupler, "end_b"), crank_pin(roll), seed)
# --- parts for the refusals ---------------------------------------------------------------------------------------------
far = np.eye(4)
far[:3, 3] = [0.0, -8.0, 0.0]
place("Idle", "strut", W), place("Tip", "strut", W), place("Loose", "strut", W)
attach("Idle", "end_a", "Ground", "end_b", 15.0)
attach("Tip", "end_a", "Idle", "end_b", 0.0)
tank = place("Tank", "tank", "radius=0.3; length=1.2")
place("Brk", "bracket")
attach("Brk", "mount", "Tank", "lug_b")
loop = '{"driver": "Crank", "kind": "loop"}'
refused("a loop whose two ends both stand still when the driver moves (F7)", "brokkr_kitbash.follow", {"object_name": "Coupler", "record": '{"driver": "Idle", "kind": "loop"}'},
"'Base' (the base) and 'Crank' (closed on), neither moves with 'Idle'")
place("G3", "strut", W + "length=0.8", far @ far @ far @ turn)
k3, b3, rk3, cp3 = place("K3", "strut", W + "length=0.5"), place("B3", "strut", W + "length=0.8"), place("Rk3", "strut", W + "length=0.9"), place("Cp3", "strut", W + "length=0.7")
attach("K3", "end_a", "G3", "end_a", 10.0)
attach("B3", "end_a", "K3", "end_a_back", 0.0)
hung = None
for guess in ((g0, g1) for g0 in range(-180, 180, 45) for g1 in range(-180, 180, 45)): # a pose at which a rocker and coupler on B3 close on K3
try:
hung, _ = core.close_loop(world(b3), [(socket(b3, "end_b"), socket(rk3, "end_a"), "revolute"), (socket(rk3, "end_b_back"), socket(cp3, "end_a"), "revolute")],
socket(cp3, "end_b"), frame(k3, "end_b"), (float(guess[0]), float(guess[1])))
break
except core.KitError:
continue
attach("Rk3", "end_a", "B3", "end_b", core._wrapped(hung[0]) if hung else 0.0)
attach("Cp3", "end_a", "Rk3", "end_b_back", core._wrapped(hung[1]) if hung else 0.0)
receipt, report = send("brokkr_kitbash.close", object_name="Cp3", socket="end_b", other_name="K3", other_socket="end_b")
check("a loop whose base hangs from the part it closes on stands closed", hung is not None and receipt["status"] == "accepted" and report["closure"]["holds"] is True, [hung, receipt["message"]])
refused("a loop whose two ends both move with the driver (F7, the other half)", "brokkr_kitbash.follow", {"object_name": "Cp3", "record": '{"driver": "K3", "kind": "loop"}'},
"'B3' (the base) and 'K3' (closed on), both move with 'K3'")
refused("a loop follower that states no closure", "brokkr_kitbash.follow", {"object_name": "Rocker", "record": loop}, "'Rocker' states no closure that holds")
refused("a follower on a rigid connection", "brokkr_kitbash.follow", {"object_name": "Brk", "record": '{"driver": "Crank", "kind": "ratio", "k": 1, "offset": 0}'},
"socket type 'mount' states no dof")
refused("a follower that is not attached", "brokkr_kitbash.follow", {"object_name": "Loose", "record": loop}, "'Loose' (the follower) is not attached")
refused("a part that follows itself", "brokkr_kitbash.follow", {"object_name": "Idle", "record": '{"driver": "Idle", "kind": "ratio", "k": 1, "offset": 0}'}, "'Idle' is the follower itself")
refused("a driver below its follower", "brokkr_kitbash.follow", {"object_name": "Idle", "record": '{"driver": "Tip", "kind": "ratio", "k": 1, "offset": 0}'}, "'Tip' is below 'Idle'")
for bad in ('{"driver": "Crank", "kind": "ratio", "k": 0, "offset": 0}', '{"driver": "Crank", "kind": "ratio", "k": 1}', '{"driver": "Crank", "kind": "gear"}',
'{"driver": "Crank", "kind": "loop", "k": 1}', "[1, 2]", '{"a"'):
refused(f"a record that is not one of the three shapes: {bad}", "brokkr_kitbash.follow", {"object_name": "Idle", "record": bad}, "record must be")
refused("clearing a part that follows nothing", "brokkr_kitbash.follow", {"object_name": "Idle", "record": "null"}, "'Idle' follows nothing")
# --- a loop follows -----------------------------------------------------------------------------------------------------
receipt, report = send("brokkr_kitbash.follow", object_name="Coupler", record=loop)
rocker_row, coupler_row = connection("Rocker"), report["connection"] if report else None
check("follow states the loop on the closing part and its parent, both following the crank, and the report lists them as written",
receipt["status"] == "accepted" and [f["part"] for f in report["followers"]] == ["Rocker", "Coupler"]
and coupler_row["follows"] == {"driver": "Crank", "kind": "loop", "k": None, "offset": None, "holds": True, "reason": None} == rocker_row["follows"]
and json.loads(rocker["kit_follows"]) == {"kind": "loop"} == json.loads(coupler["kit_follows"]) and rocker["kit_follows_driver"] == crank == coupler["kit_follows_driver"],
[receipt["message"], report and report.get("followers"), rocker_row, coupler_row])
seed = REST
for roll, label in ((75.0, "a 45 degree turn"), (150.0, "to 120 past rest"), (D0, "and back to rest"), (0.0, "30 the other way")):
was = crank["kit_roll"]
receipt, report = send("brokkr_kitbash.roll", object_name="Crank", roll=roll)
seed = stepped(solve_four_bar, seed, was, roll, 5.0)
ok = receipt["status"] == "accepted" and reading("closed", apart(coupler, "end_b", crank, "end_b")) < CLOSED
ok = ok and max(reading("solved", turned(rocker["kit_roll"], seed[0])), reading("solved", turned(coupler["kit_roll"], seed[1]))) < SOLVED
check(f"rolling the crank {label} moves rocker and coupler with it: the closure holds in the scene and the rolls are this file's own stepped solve",
ok and [f["part"] for f in report["followers"]] == ["Rocker", "Coupler"] and report["closures"][0] == {"part": "Coupler", "to": "Crank", "holds": True}
and connection("Rocker")["holds"] and connection("Coupler")["holds"], [receipt["message"], R["readings"], report and report.get("followers"), seed])
refused("the crank driven past the loop's dead centre, naming the driver's value and the closing part", "brokkr_kitbash.roll", {"object_name": "Crank", "roll": -5.0},
"'Crank' at -5: the loop 'Coupler' closes on 'Crank' ('Rocker' and 'Coupler' follow): the loop is at a dead centre", "nothing changed")
send("brokkr_kitbash.roll", object_name="Crank", roll=-2.0) # beside the toggle: 32 back from rest
seed = stepped(solve_four_bar, seed, 0.0, -2.0, 5.0)
jump = None
for roll in range(10, 151): # the nearest jump from here that one solve from the stated rolls does not survive: refused in the dead centre, or on the other branch
direct = stepped(solve_four_bar, seed, -2.0, float(roll), 5.0)
try:
once, _ = solve_four_bar(float(roll), seed)
except core.KitError:
once = None
if once is None or turned(once[0], direct[0]) > 1.0:
jump = float(roll)
break
R["readings"]["jump"] = jump or 0.0
receipt, report = send("brokkr_kitbash.roll", object_name="Crank", roll=jump or 47.0)
seed = stepped(solve_four_bar, seed, -2.0, jump or 47.0, 5.0)
check("a jump from beside the toggle that one solve from the stated rolls does not survive ends on the stepped answer, the branch the linkage is on (F2)",
jump is not None and receipt["status"] == "accepted" and reading("solved", turned(rocker["kit_roll"], seed[0])) < SOLVED and reading("solved", turned(coupler["kit_roll"], seed[1])) < SOLVED
and reading("closed", apart(coupler, "end_b", crank, "end_b")) < CLOSED, [jump, receipt["message"], rocker["kit_roll"], coupler["kit_roll"], seed])
send("brokkr_kitbash.roll", object_name="Crank", roll=D0)
seed = stepped(solve_four_bar, seed, jump or 47.0, D0, 5.0)
# --- followers are derived only ---------------------------------------------------------------------------------------
for name in ("Rocker", "Coupler"):
refused(f"roll on the follower {name}, naming its driver (F4)", "brokkr_kitbash.roll", {"object_name": name, "roll": 10.0}, f"{name!r} follows 'Crank' (loop): its value is derived")
refused("aim on a follower", "brokkr_kitbash.aim", {"object_name": "Rocker", "axis": "+z", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0}, "'Rocker' follows 'Crank'")
refused("reach on a follower", "brokkr_kitbash.reach", {"object_name": "Rocker", "socket": "end_b", "direction_x": 0.0, "direction_y": 0.0, "direction_z": 1.0, "height": 3.0}, "'Rocker' follows 'Crank'")
was = rocker["kit_roll"]
receipt, report = send("brokkr_kitbash.joint", object_name="Rocker", record='{"limits": [-100, 20], "mechanism": "rocker"}')
check("joint on a follower states limits and a mechanism and keeps its derived value and its statement", receipt["status"] == "accepted" and rocker["kit_roll"] == was
and report["connection"]["limits"] == [-100.0, 20.0] and report["connection"]["mechanism"] == "rocker" and report["connection"]["follows"]["holds"] is True,
[receipt["message"], report and report["connection"]])
refused("joint limits on a follower that do not hold its derived value", "brokkr_kitbash.joint", {"object_name": "Rocker", "record": '{"limits": [0, 20]}'}, "is outside the joint's limits")
refused("a driver that is itself a follower", "brokkr_kitbash.follow", {"object_name": "Idle", "record": '{"driver": "Rocker", "kind": "ratio", "k": 1, "offset": 0}'},
"'Rocker' is itself a follower")
refused("a follower that drives another", "brokkr_kitbash.follow", {"object_name": "Crank", "record": '{"driver": "Idle", "kind": "ratio", "k": 1, "offset": 0}'},
"'Crank' drives 'Coupler': a driver is never a follower")
refused("a follower that already follows", "brokkr_kitbash.follow", {"object_name": "Coupler", "record": loop}, "'Rocker' already follows")
refused("a closure stated by a loop's parent follower", "brokkr_kitbash.close", {"object_name": "Rocker", "socket": "end_a_back", "other_name": "Loose", "other_socket": "end_a"},
"'Rocker' follows as the parent of a loop")
# --- ratios -----------------------------------------------------------------------------------------------------------------
place("Cap", "strut", W), place("Pinion", "strut", W), place("X_Barrel", "ram_barrel"), place("X_Rod", "ram_rod")
attach("Cap", "end_a", "Crank", "end_a_back", 0.0)
attach("Pinion", "end_a", "Ground", "end_b_back", 0.0)
attach("X_Barrel", "base", "Ground", "end_a_back", 90.0)
attach("X_Rod", "piston", "X_Barrel", "bore", 0.0)
cap, pinion, x_rod = (bpy.data.objects[name] for name in ("Cap", "Pinion", "X_Rod"))
half = '{"driver": "Crank", "kind": "ratio", "k": 0.5, "offset": 0}'
refused("a ratio whose driver states no limits (F3)", "brokkr_kitbash.follow", {"object_name": "Cap", "record": half}, "'Cap' follows it by ratio, and a ratio's driver states limits")
send("brokkr_kitbash.joint", object_name="Crank", record='{"limits": [-2, 160], "mechanism": "crank"}')
receipts = [send("brokkr_kitbash.follow", object_name="Cap", record=half), send("brokkr_kitbash.follow", object_name="Pinion", record='{"driver": "Crank", "kind": "ratio", "k": -3, "offset": 10}'),
send("brokkr_kitbash.follow", object_name="X_Rod", record='{"driver": "Crank", "kind": "ratio", "k": 0.001, "offset": 0.02}')]
def ratios():
at = crank["kit_roll"]
return max(reading("ratio", turned(cap["kit_roll"], 0.5 * at)), reading("ratio", turned(pinion["kit_roll"], -3.0 * at + 10.0)), reading("ratio", abs(x_rod["kit_slide"] - (0.001 * at + 0.02))))
check("a kneecap at k 0.5, a pinion at k -3 and a crosshead's slide at 0.001 m a degree follow the crank at once: each is k x its roll + offset",
all(receipt["status"] == "accepted" for receipt, _ in receipts) and ratios() < RATIO and abs(cap["kit_roll"] - 15.0) < RATIO and abs(x_rod["kit_slide"] - 0.05) < RATIO
and [f["part"] for f in receipts[2][1]["followers"]] == ["Cap", "Pinion", "X_Rod", "Rocker", "Coupler"]
and receipts[2][1]["connection"]["follows"] == {"driver": "Crank", "kind": "ratio", "k": 0.001, "offset": 0.02, "holds": True, "reason": None}
and connection("X_Rod")["holds"] and connection("Cap")["holds"], [[r["message"] for r, _ in receipts], R["readings"], receipts[2][1] and receipts[2][1].get("followers")])
receipt, report = send("brokkr_kitbash.roll", object_name="Crank", roll=120.0)
seed = stepped(solve_four_bar, seed, D0, 120.0, 5.0)
check("rolling the crank moves ratio followers and the loop in one action: ratios first in the report, the pinion's roll brought inside a turn",
receipt["status"] == "accepted" and ratios() < RATIO and abs(pinion["kit_roll"] - 10.0) < RATIO and abs(x_rod["kit_slide"] - 0.14) < RATIO
and reading("closed", apart(coupler, "end_b", crank, "end_b")) < CLOSED and reading("solved", turned(rocker["kit_roll"], seed[0])) < SOLVED
and reading("slid", float(np.linalg.norm(frame(x_rod, "piston")[:3, 3] - frame(x_rod.parent, "bore")[:3, 3] - 0.14 * frame(x_rod.parent, "bore")[:3, 2]))) < CLOSED
and [f["part"] for f in report["followers"]] == ["Cap", "Pinion", "X_Rod", "Rocker", "Coupler"], [receipt["message"], R["readings"], pinion["kit_roll"], x_rod["kit_slide"]])
refused("slide on a follower", "brokkr_kitbash.slide", {"object_name": "X_Rod", "slide": 0.1}, "'X_Rod' follows 'Crank' (ratio): its value is derived")
send("brokkr_kitbash.joint", object_name="Cap", record='{"limits": [0, 70]}')
refused("a pose of the driver that takes a follower outside its own limits: the driver is not written either (F5)", "brokkr_kitbash.roll", {"object_name": "Crank", "roll": 150.0},
"'Cap' on 'Crank': its roll 75 is outside the joint's limits 0 to 70")
refused("clearing the limits of a driver a ratio follows", "brokkr_kitbash.joint", {"object_name": "Crank", "record": '{"limits": null}'}, "'Cap' follows it by ratio, and a ratio's driver states limits")
receipt, report = send("brokkr_kitbash.follow", object_name="Pinion", record="null")
cleared = receipt["status"] == "accepted" and report["cleared"] == ["Pinion"] and report["connection"]["follows"] is None and "kit_follows" not in pinion and "kit_follows_driver" not in pinion
receipt, report = send("brokkr_kitbash.roll", object_name="Pinion", roll=33.0)
check("follow with null clears the statement, and the part is posed by hand again", cleared and receipt["status"] == "accepted" and abs(pinion["kit_roll"] - 33.0) < RATIO, [receipt["message"]])
# --- two loops: a ram closing on the rocker, solved after the four-bar ---------------------------------------------------
send("brokkr_kitbash.roll", object_name="Crank", roll=D0)
seed = stepped(solve_four_bar, seed, 120.0, D0, 5.0)
a_barrel, a_rod = place("A_Barrel", "ram_barrel"), place("A_Rod", "ram_rod")
def rod_end(pad_world, values, pin=None):
return (pad_world @ core.mate(pin or socket(ground, "end_a"), socket(a_barrel, "base"), values[0]) @ core.mate(socket(a_barrel, "bore"), socket(a_rod, "piston"), 0.0, values[1])
@ socket(a_rod, "rod_end")["matrix"])
# one driver: a ram on a second crank closes on the rocker, which follows the first (the probe of finding second-driver-loop-opens)
place("S_Barrel", "ram_barrel"), place("S_Rod", "ram_rod")
crank2 = place("Crank2", "strut", W + "length=0.4")
shift = np.eye(4)
shift[:3, 3] = frame(rocker, "end_b_back")[:3, 3] - rod_end(turn, RAM_REST, socket(crank2, "end_b"))[:3, 3]
place("Ground2", "strut", W + "length=0.8", shift @ turn @ np.linalg.inv(core.mate(socket(ground, "end_a"), socket(crank2, "end_a"), 20.0)))
attach("Crank2", "end_a", "Ground2", "end_a", 20.0)
attach("S_Barrel", "base", "Crank2", "end_b", RAM_REST[0])
attach("S_Rod", "piston", "S_Barrel", "bore", 0.0)
send("brokkr_kitbash.slide", object_name="S_Rod", slide=RAM_REST[1])
receipt, report = send("brokkr_kitbash.close", object_name="S_Rod", socket="rod_end", other_name="Rocker", other_socket="end_b_back")
check("a ram on a second crank stands closed on the rocker", receipt["status"] == "accepted" and report["closure"]["holds"] is True, [receipt["message"], report and report["closure"]])
refused("a loop whose ends depend on two drivers: its base is its own driver and the part it closes on follows another", "brokkr_kitbash.follow",
{"object_name": "S_Rod", "record": '{"driver": "Crank2", "kind": "loop"}'},
"'Crank2' (the base) and 'Rocker' (closed on), depend on more than one driver: 'Crank2' and 'Crank' ('Rocker' follows it)", "A follower takes its value from one driver")
refused("and with the crank as the driver: the ram's base hangs from the second crank, which is posed by hand", "brokkr_kitbash.follow", {"object_name": "S_Rod", "record": loop},
"depend on more than one driver: 'Crank' and 'Crank2' (it follows nothing and its joint has travel, so it is posed by hand)")
receipt, _ = send("brokkr_kitbash.detach", object_name="S_Rod")
check("the refused ram is detached, and the rocker's pin is free again", receipt["status"] == "accepted" and "kit_close" not in bpy.data.objects["S_Rod"], receipt["message"])
shift = np.eye(4)
shift[:3, 3] = frame(rocker, "end_b_back")[:3, 3] - rod_end(turn, RAM_REST)[:3, 3]
pad = place("Pad", "strut", W + "length=0.8", shift @ turn)
attach("A_Barrel", "base", "Pad", "end_a", RAM_REST[0])
attach("A_Rod", "piston", "A_Barrel", "bore", 0.0)
send("brokkr_kitbash.slide", object_name="A_Rod", slide=RAM_REST[1])
send("brokkr_kitbash.close", object_name="A_Rod", socket="rod_end", other_name="Rocker", other_socket="end_b_back")
receipt, report = send("brokkr_kitbash.follow", object_name="A_Rod", record=loop)
check("a ram on its own ground pin closes on the rocker and follows the crank: the end it closes on follows the driver",
receipt["status"] == "accepted" and [f["part"] for f in report["followers"]] == ["Cap", "X_Rod", "Rocker", "Coupler", "A_Barrel", "A_Rod"]
and report["connection"]["follows"]["holds"] is True, [receipt["message"], report and report.get("followers")])
ram_loop = [(socket(pad, "end_a"), socket(a_barrel, "base"), "revolute"), (socket(a_barrel, "bore"), socket(a_rod, "piston"), "prismatic")]
ram_seed = RAM_REST
for roll in (60.0, 110.0, 45.0):
was = crank["kit_roll"]
receipt, report = send("brokkr_kitbash.roll", object_name="Crank", roll=roll)
count = max(1, math.ceil(abs(roll - was) / 5.0))
for index in range(1, count + 1): # this file's own derivation: at each step the four-bar, then the ram against the rocker where that step put it
seed, _ = solve_four_bar(was + (roll - was) * index / count, seed)
pin = rocker_world(world(base), seed[0]) @ socket(rocker, "end_b_back")["matrix"]
ram_seed, _ = core.close_loop(world(pad), ram_loop, socket(a_rod, "rod_end"), pin, ram_seed)
R["readings"][f"ram closed at {roll:g}"], R["readings"][f"ram solved at {roll:g}"] = apart(a_rod, "rod_end", rocker, "end_b_back"), turned(a_barrel["kit_roll"], ram_seed[0])
check(f"rolling the crank to {roll:g} solves the four-bar and then the ram that closes on its rocker (F11): both closures hold and the barrel's roll and rod's slide are this file's own",
receipt["status"] == "accepted" and reading("closed", apart(a_rod, "rod_end", rocker, "end_b_back")) < CLOSED and reading("closed", apart(coupler, "end_b", crank, "end_b")) < CLOSED
and reading("solved", turned(a_barrel["kit_roll"], ram_seed[0])) < SOLVED and reading("closed", abs(a_rod["kit_slide"] - ram_seed[1])) < CLOSED
and [f["part"] for f in report["followers"]][-4:] == ["Rocker", "Coupler", "A_Barrel", "A_Rod"]
and [row for row in report["closures"] if not row["holds"]] == [], [receipt["message"], R["readings"], a_barrel["kit_roll"], a_rod["kit_slide"], ram_seed])
# --- one driver, after the loop is stated: each action that could give a loop a second one refuses it -------------------------
place("P_Mount", "strut", W + "length=0.8", far @ far @ far @ far @ far @ turn)
refused("attach after the loop is stated: the ram's pad hung on a free pin is a second driver between the loop's ends", "brokkr_kitbash.attach",
{"object_name": "Pad", "socket": "end_b", "parent_name": "P_Mount", "parent_socket": "end_a", "roll": 0.0},
"the two ends of the loop 'A_Rod' closes, 'Pad' (the base) and 'Rocker' (closed on), depend on more than one driver: 'Crank' and 'Pad' (it follows nothing and its joint has travel",
"clear the loop (brokkr_kitbash.follow on 'A_Rod' with record null)")
refused("clear after the loop is stated: the four-bar's rocker, no longer a follower, is a second driver of the ram that closes on it", "brokkr_kitbash.follow",
{"object_name": "Coupler", "record": "null"},
"the two ends of the loop 'A_Rod' closes, 'Pad' (the base) and 'Rocker' (closed on), depend on more than one driver: 'Crank' and 'Rocker' (it follows nothing and its joint has travel")
# --- a torque link: a slide drives two arms ---------------------------------------------------------------------------------
t_barrel, t_rod = place("T_Barrel", "ram_barrel", "", far @ turn), place("T_Rod", "ram_rod")
t_upper, t_lower, t_lug = place("T_Upper", "strut", W + "length=0.5"), place("T_Lower", "strut", W + "length=0.5"), place("T_Lug", "strut", W + "length=0.3")
attach("T_Rod", "piston", "T_Barrel", "bore", 0.0)
send("brokkr_kitbash.joint", object_name="T_Rod", record='{"limits": [0, 0.3], "mechanism": "oleo", "compliance": {"hertz": 3, "damping_ratio": 0.6}}')
send("brokkr_kitbash.slide", object_name="T_Rod", slide=0.05)
attach("T_Lug", "end_a", "T_Rod", "rod_end_back", 90.0)
link = [(socket(t_barrel, "base_back"), socket(t_upper, "end_a"), "revolute"), (socket(t_upper, "end_b"), socket(t_lower, "end_a"), "revolute")]
def lug_pin(slide):
return (world(t_barrel) @ core.mate(socket(t_barrel, "bore"), socket(t_rod, "piston"), 0.0, slide) @ core.mate(socket(t_rod, "rod_end_back"), socket(t_lug, "end_a"), 90.0)
@ socket(t_lug, "end_b")["matrix"])
def solve_link(slide, values):
return core.close_loop(world(t_barrel), link, socket(t_lower, "end_b"), lug_pin(slide), values)
arms = None
for guess in ((40.0, 100.0), (-40.0, -100.0), (140.0, 100.0), (-140.0, -100.0), (90.0, 90.0), (-90.0, -90.0), (10.0, 150.0), (-10.0, -150.0)):
try:
arms, _ = solve_link(0.05, guess)
break
except core.KitError:
continue
check("the torque link's rest pose is found: two arms from the barrel's pin to the lug on the rod", arms is not None, "no guess closed the loop")
arms = tuple(core._wrapped(v) for v in arms)
attach("T_Upper", "end_a", "T_Barrel", "base_back", arms[0])
attach("T_Lower", "end_a", "T_Upper", "end_b", arms[1])
send("brokkr_kitbash.close", object_name="T_Lower", socket="end_b", other_name="T_Lug", other_socket="end_b")
refused("a loop that closes on a part hung from the driver by a free pin: the lug's roll is a second input (the probe of finding torque-link-lug-is-a-free-dof)", "brokkr_kitbash.follow",
{"object_name": "T_Lower", "record": '{"driver": "T_Rod", "kind": "loop"}'},
"'T_Barrel' (the base) and 'T_Lug' (closed on), depend on more than one driver: 'T_Rod' and 'T_Lug' (it follows nothing and its joint has travel, so it is posed by hand)")
receipt, report = send("brokkr_kitbash.joint", object_name="T_Lug", record='{"limits": [90, 90], "mechanism": "lug"}')
check("limits of one value hold the lug on the rod: a pin with no travel", receipt["status"] == "accepted" and report["connection"]["limits"] == [90.0, 90.0], receipt["message"])
receipt, report = send("brokkr_kitbash.follow", object_name="T_Lower", record='{"driver": "T_Rod", "kind": "loop"}')
check("the arms follow the rod's slide as a loop: its base is the barrel, above the driver, and it closes on a part that hangs from the driver",
receipt["status"] == "accepted" and [f["part"] for f in report["followers"]] == ["T_Upper", "T_Lower"], [receipt["message"], report and report.get("followers")])
for slide in (0.15, 0.0, 0.11):
was = t_rod["kit_slide"]
receipt, report = send("brokkr_kitbash.slide", object_name="T_Rod", slide=slide)
arms = stepped(solve_link, arms, was, slide, 0.02)
check(f"sliding the rod to {slide:g} folds the arms: the closure holds in the scene and the rolls are this file's own stepped solve",
receipt["status"] == "accepted" and reading("closed", apart(t_lower, "end_b", t_lug, "end_b")) < CLOSED
and max(reading("solved", turned(t_upper["kit_roll"], arms[0])), reading("solved", turned(t_lower["kit_roll"], arms[1]))) < SOLVED
and report["closures"][0]["holds"] is True, [receipt["message"], R["readings"], t_upper["kit_roll"], t_lower["kit_roll"], arms])
refused("a slide outside the driver's limits", "brokkr_kitbash.slide", {"object_name": "T_Rod", "slide": 0.4}, "its slide 0.4 is outside the joint's limits 0 to 0.3")
refused("a roll of the held lug: no pose opens the torque link", "brokkr_kitbash.roll", {"object_name": "T_Lug", "roll": 100.0}, "'T_Lug' on 'T_Rod': its roll 100 is outside the joint's limits 90 to 90")
for label, limits in (("widened", "[80, 100]"), ("cleared", "null")):
refused(f"limits {label} after the loop is stated: the lug, given travel, is a second driver of the torque link", "brokkr_kitbash.joint",
{"object_name": "T_Lug", "record": '{"limits": %s}' % limits},
"the two ends of the loop 'T_Lower' closes, 'T_Barrel' (the base) and 'T_Lug' (closed on), depend on more than one driver: 'T_Rod' and 'T_Lug' (it follows nothing and its joint has travel")
t_lug["kit_min"], t_lug["kit_max"] = 80.0, 100.0 # by hand, past every action: the next write of any pose reads the rule
refused("a pose of the driver after the lug's limits were widened by hand: the writer reads the rule before it writes", "brokkr_kitbash.slide", {"object_name": "T_Rod", "slide": 0.1},
"depend on more than one driver: 'T_Rod' and 'T_Lug' (it follows nothing and its joint has travel")
refused("and a pose of the lug itself", "brokkr_kitbash.roll", {"object_name": "T_Lug", "roll": 95.0}, "depend on more than one driver: 'T_Rod' and 'T_Lug'")
# a second driver no write made is told by every read of the loop, while its closure still stands closed (finding two-driver-loop-reported-nowhere):
# each follower's follows row reads holds false and names both drivers, and the joints report of a tree the loop is in lists the loop by its closing part
told = "the loop 'T_Lower' closes has more than one driver: 'T_Rod' and 'T_Lug' (it follows nothing and its joint has travel, so it is posed by hand)"
rows = {name: send("brokkr_kitbash.report", object_name=name)[1]["parts"][0] for name in ("T_Upper", "T_Lower")}
check("a loop given a second driver by hand reads follows.holds false on both followers, naming both drivers, while its closure holds",
all(row["connection"]["follows"]["holds"] is False and row["connection"]["follows"]["reason"].startswith(told) for row in rows.values())
and rows["T_Lower"]["closure"]["holds"] is True, [{name: row["connection"] for name, row in rows.items()}, rows["T_Lower"]["closure"]])
receipt, joints = send("brokkr_kitbash.joints", object_name="T_Barrel")
receipt2, joints2 = send("brokkr_kitbash.joints", object_name="T_Lug")
receipt3, joints3 = send("brokkr_kitbash.joints", object_name="Ground")
check("the joints report lists a loop with a second driver in manyDrivers, by its closing part and with both drivers: in a report of the whole mechanism, "
"in one of the second driver's own sub-tree, and not in one of a tree the loop is no part of",
all(r["status"] == "accepted" for r in (receipt, receipt2, receipt3)) and joints["manyDrivers"] == [{"loop": "T_Lower", "drivers": ["T_Rod", "T_Lug"]}] == joints2["manyDrivers"]
and joints3["manyDrivers"] == [], [receipt["message"], joints and joints.get("manyDrivers"), joints2 and joints2.get("manyDrivers"), joints3 and joints3.get("manyDrivers")])
# the rule judges the write, not the scene: with the torque link holding a second driver, a write is refused when it touches that loop (a part of it,
# or one it hangs from) or would give another loop a second driver, and every other write is made (finding parent-hook-gates-on-scene-not-change)
shape = lambda *names: {name: np.array([v.co[:] for v in bpy.data.objects[name].data.vertices]).tobytes() for name in names} # noqa: E731
was = shape("T_Lug", "T_Lower")
refused("set_params of the part a two-driver loop closes on (finding set-params-writes-before-the-guard): the rule is read before the mesh is rebuilt",
"brokkr_kitbash.set_params", {"object_name": "T_Lug", "params": "length=0.31"},
"the two ends of the loop 'T_Lower' closes, 'T_Barrel' (the base) and 'T_Lug' (closed on), depend on more than one driver: 'T_Rod' and 'T_Lug' (it follows nothing and its joint has travel", "nothing changed")
check("and nothing moved: the part's vertices read as before the refusal", shape("T_Lug", "T_Lower") == was)
refused("setObjectParent of the root a two-driver loop hangs from: the write touches the loop", "setObjectParent", {"targetObjectName": "T_Barrel", "parentObjectName": "Loose"},
"the two ends of the loop 'T_Lower' closes, 'T_Barrel' (the base) and 'T_Lug' (closed on), depend on more than one driver: 'T_Rod' and 'T_Lug'", "nothing changed")
refused("setObjectParent that gives another loop a second driver, in a scene that already holds one: the four-bar's base under Idle", "setObjectParent",
{"targetObjectName": "Base", "parentObjectName": "Idle"},
"the two ends of the loop 'A_Rod' closes, 'Pad' (the base) and 'Rocker' (closed on), depend on more than one driver: 'Crank' and 'Idle' (it follows nothing and its joint has travel", "nothing changed")
idle, tip_was = bpy.data.objects["Idle"], connection("Tip")
length, was = json.loads(idle["kit_params"])["length"], shape("Idle")
receipt, _ = send("brokkr_kitbash.set_params", object_name="Idle", params="length=0.6")
grown = receipt["status"] == "accepted" and shape("Idle") != was and connection("Tip")["holds"] is True
receipt2, _ = send("brokkr_kitbash.set_params", object_name="Idle", params=f"length={length!r}")
check("set_params of a part no loop hangs from is written in a scene that holds a second driver, and set back",
grown and receipt2["status"] == "accepted" and shape("Idle") == was and connection("Tip") == tip_was and tip_was["holds"] is True, [receipt["message"], receipt2["message"], tip_was, connection("Tip")])
rolled = idle["kit_roll"]
receipt, _ = send("brokkr_kitbash.roll", object_name="Idle", roll=rolled + 5.0)
receipt2, _ = send("brokkr_kitbash.roll", object_name="Idle", roll=rolled)
check("a pose of a joint no loop hangs from is written in a scene that holds a second driver", receipt["status"] == "accepted" and receipt2["status"] == "accepted", [receipt["message"], receipt2["message"]])
plain, cam = bpy.data.objects.new("PlainEmpty", None), bpy.data.objects.new("Cam", bpy.data.cameras.new("Cam")) # Soul's probe P2a, P2b: neither is a kit part
for made in (plain, cam):
bpy.context.scene.collection.objects.link(made)
asked = []
for name, parent in (("Cam", "PlainEmpty"), ("PlainEmpty", "Ground"), ("PlainEmpty", "T_Lug"), ("Cam", "")):
receipt, _ = send("setObjectParent", targetObjectName=name, parentObjectName=parent)
asked.append((receipt["status"], bpy.data.objects[name].parent and bpy.data.objects[name].parent.name, str(receipt["message"])[:200]))
check("setObjectParent of a camera under an empty, of the empty under a kit part and under a part of the two-driver loop itself, and clearing the camera's, "
"are written in a scene that holds a second driver: nothing of a loop hangs from them",
[row[:2] for row in asked] == [("accepted", "PlainEmpty"), ("accepted", "Ground"), ("accepted", "T_Lug"), ("accepted", None)], asked)
receipt, _ = send("setObjectParent", targetObjectName="T_Barrel", parentObjectName="Cam")
check("and the loop's root under that camera is refused: the camera is no kit part, the root is what the loop hangs from",
receipt["status"] != "accepted" and "depend on more than one driver: 'T_Rod' and 'T_Lug'" in str(receipt["message"]) and t_barrel.parent is None, [receipt["status"], receipt["message"]])
for made in (cam, plain):
bpy.data.objects.remove(made)
# a loop whose driver neither end hangs from, stated by hand on Loose and closing on Tip, whose two free pins are second drivers: a write of the
# driver that poses nothing (its followers are not written) still touches the loop
place("H_Upper", "strut", W), place("H_Lower", "strut", W)
attach("H_Upper", "end_a", "Loose", "end_a", 30.0), attach("H_Lower", "end_a", "H_Upper", "end_b", 40.0)
h_upper, h_lower = bpy.data.objects["H_Upper"], bpy.data.objects["H_Lower"]
h_lower["kit_close_socket"], h_lower["kit_close_to"], h_lower["kit_close_to_socket"] = "end_b", bpy.data.objects["Tip"], "end_b"
for made in (h_upper, h_lower):
made["kit_follows"], made["kit_follows_driver"] = '{"kind": "loop"}', crank
refused("set_params of the driver of a two-driver loop that neither end hangs from: the write touches the loop", "brokkr_kitbash.set_params",
{"object_name": "Crank", "params": f"length={json.loads(crank['kit_params'])['length']!r}"},
"the two ends of the loop 'H_Lower' closes, 'Loose' (the base) and 'Tip' (closed on), depend on more than one driver: 'Crank' and 'Idle' (it follows nothing and its joint has travel", "nothing changed")
for made in (h_lower, h_upper):
bpy.data.objects.remove(made)
t_lug["kit_min"], t_lug["kit_max"] = 90.0, 90.0
receipt, report = send("brokkr_kitbash.slide", object_name="T_Rod", slide=0.11)
check("with the lug held again the driver is posed", receipt["status"] == "accepted" and report["closures"][0]["holds"] is True, receipt["message"])
receipt, report = send("brokkr_kitbash.report", object_name="T_Lower")
receipt2, joints = send("brokkr_kitbash.joints", object_name="T_Barrel")
check("and with one driver again the follower's follows row holds and the joints report lists no loop",
receipt["status"] == "accepted" and receipt2["status"] == "accepted" and report["parts"][0]["connection"]["follows"] == {"driver": "T_Rod", "kind": "loop", "k": None, "offset": None, "holds": True, "reason": None}
and joints["manyDrivers"] == [], [receipt["message"], report and report["parts"][0]["connection"], joints and joints.get("manyDrivers")])
receipt, joints = send("brokkr_kitbash.joints", object_name="T_Barrel")
check("the torque link has one degree of freedom: the rod's slide is its one row with travel that nothing drives, the lug is its one held row, the arms are driven, and no row is unlimited",
receipt["status"] == "accepted" and [(row["id"], row["kind"], row["driven"] and row["driven"]["by"], row["min"], row["max"], row["held"]) for row in joints["joints"]] == [
("T_Rod", "prismatic", None, -0.11, 0.19, False), ("T_Lug", "revolute", None, 0.0, 0.0, True), ("T_Upper", "revolute", "T_Rod", None, None, False), ("T_Lower", "revolute", "T_Rod", None, None, False)]
and joints["unlimited"] == [] and reading("closed", apart(t_lower, "end_b", t_lug, "end_b")) < CLOSED, [receipt["message"], joints])
place("T_Mount", "strut", W, far @ far @ far @ far @ turn)
hinged = attach("T_Barrel", "base", "T_Mount", "end_a", 25.0)
receipt, report = send("brokkr_kitbash.follow", object_name="T_Lower", record="null")
cleared = receipt["status"] == "accepted" and report["cleared"] == ["T_Upper", "T_Lower"]
receipt, report = send("brokkr_kitbash.follow", object_name="T_Lower", record='{"driver": "T_Rod", "kind": "loop"}')
check("a joint both ends of a loop hang from is not one the loop depends on: the barrel hung on a free hinge, the arms follow the rod again",
hinged and cleared and receipt["status"] == "accepted" and [f["part"] for f in report["followers"]] == ["T_Upper", "T_Lower"]
and reading("closed", apart(t_lower, "end_b", t_lug, "end_b")) < CLOSED, [hinged, cleared, receipt["message"]])
refused("detach after the loop is stated: the lug cut from the rod no longer hangs from the barrel, so the barrel's free hinge is a second driver", "brokkr_kitbash.detach",
{"object_name": "T_Lug"},
"the two ends of the loop 'T_Lower' closes, 'T_Barrel' (the base) and 'T_Lug' (closed on), depend on more than one driver: 'T_Rod' and 'T_Barrel' (it follows nothing and its joint has travel")
refused("setObjectParent clearing the lug's parent (finding bridge-reparent-bypasses-the-guard): Brokkr's own row asks the same rule before it writes a parent", "setObjectParent",
{"targetObjectName": "T_Lug", "parentObjectName": ""},
"the two ends of the loop 'T_Lower' closes, 'T_Barrel' (the base) and 'T_Lug' (closed on), depend on more than one driver: 'T_Rod' and 'T_Barrel' (it follows nothing and its joint has travel", "nothing changed")
refused("setObjectParent of a root onto a part on a free pin: with the four-bar's base under Idle, the rocker the ram closes on depends on Idle's roll", "setObjectParent",
{"targetObjectName": "Base", "parentObjectName": "Idle"},
"the two ends of the loop 'A_Rod' closes, 'Pad' (the base) and 'Rocker' (closed on), depend on more than one driver: 'Crank' and 'Idle' (it follows nothing and its joint has travel", "nothing changed")
receipt, _ = send("setObjectParent", targetObjectName="Loose", parentObjectName="Idle")
under = bpy.data.objects["Loose"].parent
receipt2, _ = send("setObjectParent", targetObjectName="Loose", parentObjectName="")
check("setObjectParent of a part no loop depends on is written as before, and cleared again", receipt["status"] == "accepted" and under == bpy.data.objects["Idle"]
and receipt2["status"] == "accepted" and bpy.data.objects["Loose"].parent is None, [receipt["message"], receipt2["message"]])
# --- joints, version 2 ----------------------------------------------------------------------------------------------------------
receipt, joints = send("brokkr_kitbash.joints", object_name="Ground")
table = {row["id"]: row for row in (joints or {}).get("joints", [])}
check("joints is version 2: a driven row names what drives it (F6), and unlimited lists the rows that are not driven and state no limits",
receipt["status"] == "accepted" and joints["version"] == 2 and [row["id"] for row in joints["joints"]] == ["Crank", "Cap", "Idle", "Tip", "Pinion", "X_Barrel", "X_Rod"]
and table["Crank"]["driven"] is None and table["Cap"]["driven"] == {"by": "Crank", "kind": "ratio", "k": 0.5, "offset": 0.0}
and table["X_Rod"]["driven"] == {"by": "Crank", "kind": "ratio", "k": 0.001, "offset": 0.02} and table["X_Rod"]["kind"] == "prismatic"
and joints["unlimited"] == ["Idle", "Tip", "Pinion", "X_Barrel"] and joints["next"] is None and "jointsOmitted" not in joints, [receipt["message"], joints])
receipt, joints = send("brokkr_kitbash.joints", object_name="Base")
check("a loop's two followers are driven rows, kind loop", receipt["status"] == "accepted" and [(row["id"], row["driven"]) for row in joints["joints"]] == [
("Rocker", {"by": "Crank", "kind": "loop", "k": None, "offset": None}), ("Coupler", {"by": "Crank", "kind": "loop", "k": None, "offset": None})] and joints["unlimited"] == [], joints)
receipt, joints = send("brokkr_kitbash.joints", object_name="T_Rod")
check("a root that states a DOF connection has its own row first, parent null", receipt["status"] == "accepted"
and [(row["id"], row["parent"], row["kind"]) for row in joints["joints"]] == [("T_Rod", None, "prismatic"), ("T_Lug", "T_Rod", "revolute")]
and joints["joints"][0]["compliance"] == {"damping_ratio": 0.6, "hertz": 3.0} and joints["rigid"] == 0, joints)
receipt, joints = send("brokkr_kitbash.joints", object_name="Ground", after="Idle")
check("after carries the rows after an id (F12)", receipt["status"] == "accepted" and [row["id"] for row in joints["joints"]] == ["Tip", "Pinion", "X_Barrel", "X_Rod"]
and joints["joints"][0]["parent"] == "Idle" and joints["unlimited"] == ["Tip", "Pinion", "X_Barrel"], joints)
refused("after an id that is no row's", "brokkr_kitbash.joints", {"object_name": "Ground", "after": "Base"}, "after 'Base' is not the id of a joint under 'Ground'")
long = [f"Actuator_joint_name_that_is_long_but_legal_in_blender_{index:04d}_x" for index in range(265)] # 62 characters, of the 63 Blender takes
place(long[0], "strut", W + "length=0.3", far @ far @ turn)
place(long[1], "strut", W + "length=0.3")
attach(long[1], "end_a", long[0], "end_a", 7.0)
for chain, on in enumerate(("end_a", "end_a_back", "end_b", "end_b_back")): # four chains of 66 on the root's four pins: 264 joints, none limited
for index in range(max(2, chain * 66 + 1), chain * 66 + 67): # copies of the one attached by the actions, each stating its own connection: the report reads what is stated
copy = bpy.data.objects[long[1]].copy()
copy.name, copy.parent = long[index], bpy.data.objects[long[0] if index == chain * 66 + 1 else long[index - 1]]
copy["kit_parent_socket"] = on if index == chain * 66 + 1 else "end_b"
bpy.context.scene.collection.objects.link(copy)
pages, after = [], ""
for _ in range(2): # the first two reports; each costs a pass over the 264 parts
receipt, page = send("brokkr_kitbash.joints", object_name=long[0], after=after)
pages.append((receipt["status"], len(receipt.get("hostResult") or ""), page or {}))
after = (page or {}).get("next") or ""
carried = [[row["id"] for row in page.get("joints", [])] for _, _, page in pages]
R["readings"]["rows in the first receipt"], R["readings"]["longest receipt"] = len(carried[0]), max(size for _, size, _ in pages)
check("a tree of 264 unlimited joints with long names, whose ids alone are over a receipt, is many reports and none over a receipt: each carries rows, the ids of its own "
"rows as unlimited, a count of what it omits and the last id it carries as next, and after it the next carries on",
all(status == "accepted" and size <= 16000 and page.get("joints") and page["unlimited"] == ids and page["next"] == ids[-1] for (status, size, page), ids in zip(pages, carried))
and sum(len(json.dumps(name)) + 1 for name in long[1:]) > 16000 and [name for ids in carried for name in ids] == long[1:len(carried[0]) + len(carried[1]) + 1]
and [page["jointsOmitted"] for _, _, page in pages] == [264 - len(carried[0]), 264 - len(carried[0]) - len(carried[1])],
[[(status, size, len(ids), page.get("jointsOmitted"), page.get("next")) for (status, size, page), ids in zip(pages, carried)]])
# --- the joint-records Lows -------------------------------------------------------------------------------------------------
send("brokkr_kitbash.joint", object_name="Idle", record='{"limits": [0, 30]}')
idle = bpy.data.objects["Idle"]
idle["kit_roll"] = 50.0 # by hand: no action writes a roll outside its limits
refused("set_params of a part whose roll was written by hand outside its limits (F9): the mesh is not rebuilt", "brokkr_kitbash.set_params", {"object_name": "Idle", "params": "length=0.6"},
"'Idle' on 'Ground': its roll 50 is outside the joint's limits 0 to 30")
refused("and of its parent", "brokkr_kitbash.set_params", {"object_name": "Ground", "params": "length=0.9"}, "'Idle' on 'Ground': its roll 50 is outside the joint's limits 0 to 30")
idle["kit_roll"], idle["kit_slide"] = 15.0, 0.1
refused("set_params of a part with a slide written by hand on a revolute connection", "brokkr_kitbash.set_params", {"object_name": "Idle", "params": "length=0.6"},
"socket type 'pivot' is revolute: only a prismatic connection slides")
del idle["kit_slide"]
idle["kit_compliance"] = '{"damping_ratio": 0.7, "hertz": 4.0}' # by hand: a compliance is a prismatic joint's
receipt, joints = send("brokkr_kitbash.joints", object_name="Idle")
row = connection("Idle")
check("a compliance written by hand on a revolute joint reads null in the report and the joints report (F10), and the limits beside it still read",
receipt["status"] == "accepted" and row["compliance"] is None and row["limits"] == [0.0, 30.0] and joints["joints"][0]["id"] == "Idle" and joints["joints"][0]["compliance"] is None, [row, joints])
receipt, report = send("brokkr_kitbash.set_params", object_name="Idle", params="length=0.6")
check("set_params seats through the one writer: the part is rebuilt, its child seated on the moved socket, and the hand-written compliance is gone",
receipt["status"] == "accepted" and "kit_compliance" not in idle and connection("Tip")["holds"] and reading("closed", apart(bpy.data.objects["Tip"], "end_a", idle, "end_b")) < CLOSED,
[receipt["message"], sorted(idle.keys())])
# --- detach ---------------------------------------------------------------------------------------------------------------------
receipt, report = send("brokkr_kitbash.detach", object_name="T_Lower")
upper_row = connection("T_Upper")
check("detaching a loop's closing follower clears its partner's statement too", receipt["status"] == "accepted" and upper_row["follows"] is None
and not [k for o in (t_upper, t_lower) for k in o.keys() if k.startswith("kit_follows")], [receipt["message"], upper_row, sorted(t_upper.keys())])
receipt, report = send("brokkr_kitbash.roll", object_name="T_Upper", roll=12.0)
check("and the partner is posed by hand again", receipt["status"] == "accepted", receipt["message"])
receipt, report = send("brokkr_kitbash.detach", object_name="Crank")
cap_row, coupler_row = connection("Cap"), connection("Coupler")
check("detaching a driver leaves its followers' statements, which report that the driver states no DOF connection",
receipt["status"] == "accepted" and cap_row["follows"] == {"driver": "Crank", "kind": "ratio", "k": 0.5, "offset": 0.0, "holds": False, "reason": "the driver states no DOF connection"}
and coupler_row["follows"]["holds"] is False and coupler_row["follows"]["reason"] == "the driver states no DOF connection", [receipt["message"], cap_row, coupler_row])
bpy.data.objects.remove(crank)
coupler_row = connection("Coupler")
check("and once the driver is deleted, that it is gone", coupler_row["follows"]["driver"] is None and coupler_row["follows"]["reason"] == "the driver is gone: deleted, or in no collection", coupler_row)
constrained = [o.name for o in bpy.data.objects if o.constraints or (o.animation_data and o.animation_data.drivers)]
check("no Blender driver or constraint was made", constrained == [], constrained)
except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file
check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-8:])
R["ok"] = all(c["ok"] for c in R["checks"])
R["readings"] = {name: float(f"{value:.2g}") for name, value in sorted(R["readings"].items())}
for c in R["checks"]:
print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True)
Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8")
print("READINGS", R["readings"], flush=True)
sys.exit(0 if R["ok"] else 1)

View file

@ -0,0 +1,517 @@
{
"blender": "5.3.0",
"checks": [
{
"name": "follow loads as a host action after joints, with no errors",
"ok": true,
"detail": null
},
{
"name": "the four-bar stands closed at rest: crank on Ground, rocker on Base, the coupler's end closing on the crank's",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a loop whose two ends both stand still when the driver moves (F7)",
"ok": true,
"detail": null
},
{
"name": "a loop whose base hangs from the part it closes on stands closed",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a loop whose two ends both move with the driver (F7, the other half)",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a loop follower that states no closure",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a follower on a rigid connection",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a follower that is not attached",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a part that follows itself",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a driver below its follower",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a record that is not one of the three shapes: {\"driver\": \"Crank\", \"kind\": \"ratio\", \"k\": 0, \"offset\": 0}",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a record that is not one of the three shapes: {\"driver\": \"Crank\", \"kind\": \"ratio\", \"k\": 1}",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a record that is not one of the three shapes: {\"driver\": \"Crank\", \"kind\": \"gear\"}",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a record that is not one of the three shapes: {\"driver\": \"Crank\", \"kind\": \"loop\", \"k\": 1}",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a record that is not one of the three shapes: [1, 2]",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a record that is not one of the three shapes: {\"a\"",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: clearing a part that follows nothing",
"ok": true,
"detail": null
},
{
"name": "follow states the loop on the closing part and its parent, both following the crank, and the report lists them as written",
"ok": true,
"detail": null
},
{
"name": "rolling the crank a 45 degree turn moves rocker and coupler with it: the closure holds in the scene and the rolls are this file's own stepped solve",
"ok": true,
"detail": null
},
{
"name": "rolling the crank to 120 past rest moves rocker and coupler with it: the closure holds in the scene and the rolls are this file's own stepped solve",
"ok": true,
"detail": null
},
{
"name": "rolling the crank and back to rest moves rocker and coupler with it: the closure holds in the scene and the rolls are this file's own stepped solve",
"ok": true,
"detail": null
},
{
"name": "rolling the crank 30 the other way moves rocker and coupler with it: the closure holds in the scene and the rolls are this file's own stepped solve",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: the crank driven past the loop's dead centre, naming the driver's value and the closing part",
"ok": true,
"detail": null
},
{
"name": "a jump from beside the toggle that one solve from the stated rolls does not survive ends on the stepped answer, the branch the linkage is on (F2)",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: roll on the follower Rocker, naming its driver (F4)",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: roll on the follower Coupler, naming its driver (F4)",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: aim on a follower",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: reach on a follower",
"ok": true,
"detail": null
},
{
"name": "joint on a follower states limits and a mechanism and keeps its derived value and its statement",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: joint limits on a follower that do not hold its derived value",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a driver that is itself a follower",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a follower that drives another",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a follower that already follows",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a closure stated by a loop's parent follower",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a ratio whose driver states no limits (F3)",
"ok": true,
"detail": null
},
{
"name": "a kneecap at k 0.5, a pinion at k -3 and a crosshead's slide at 0.001 m a degree follow the crank at once: each is k x its roll + offset",
"ok": true,
"detail": null
},
{
"name": "rolling the crank moves ratio followers and the loop in one action: ratios first in the report, the pinion's roll brought inside a turn",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: slide on a follower",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a pose of the driver that takes a follower outside its own limits: the driver is not written either (F5)",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: clearing the limits of a driver a ratio follows",
"ok": true,
"detail": null
},
{
"name": "follow with null clears the statement, and the part is posed by hand again",
"ok": true,
"detail": null
},
{
"name": "a ram on a second crank stands closed on the rocker",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a loop whose ends depend on two drivers: its base is its own driver and the part it closes on follows another",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: and with the crank as the driver: the ram's base hangs from the second crank, which is posed by hand",
"ok": true,
"detail": null
},
{
"name": "the refused ram is detached, and the rocker's pin is free again",
"ok": true,
"detail": null
},
{
"name": "a ram on its own ground pin closes on the rocker and follows the crank: the end it closes on follows the driver",
"ok": true,
"detail": null
},
{
"name": "rolling the crank to 60 solves the four-bar and then the ram that closes on its rocker (F11): both closures hold and the barrel's roll and rod's slide are this file's own",
"ok": true,
"detail": null
},
{
"name": "rolling the crank to 110 solves the four-bar and then the ram that closes on its rocker (F11): both closures hold and the barrel's roll and rod's slide are this file's own",
"ok": true,
"detail": null
},
{
"name": "rolling the crank to 45 solves the four-bar and then the ram that closes on its rocker (F11): both closures hold and the barrel's roll and rod's slide are this file's own",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: attach after the loop is stated: the ram's pad hung on a free pin is a second driver between the loop's ends",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: clear after the loop is stated: the four-bar's rocker, no longer a follower, is a second driver of the ram that closes on it",
"ok": true,
"detail": null
},
{
"name": "the torque link's rest pose is found: two arms from the barrel's pin to the lug on the rod",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a loop that closes on a part hung from the driver by a free pin: the lug's roll is a second input (the probe of finding torque-link-lug-is-a-free-dof)",
"ok": true,
"detail": null
},
{
"name": "limits of one value hold the lug on the rod: a pin with no travel",
"ok": true,
"detail": null
},
{
"name": "the arms follow the rod's slide as a loop: its base is the barrel, above the driver, and it closes on a part that hangs from the driver",
"ok": true,
"detail": null
},
{
"name": "sliding the rod to 0.15 folds the arms: the closure holds in the scene and the rolls are this file's own stepped solve",
"ok": true,
"detail": null
},
{
"name": "sliding the rod to 0 folds the arms: the closure holds in the scene and the rolls are this file's own stepped solve",
"ok": true,
"detail": null
},
{
"name": "sliding the rod to 0.11 folds the arms: the closure holds in the scene and the rolls are this file's own stepped solve",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a slide outside the driver's limits",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a roll of the held lug: no pose opens the torque link",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: limits widened after the loop is stated: the lug, given travel, is a second driver of the torque link",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: limits cleared after the loop is stated: the lug, given travel, is a second driver of the torque link",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a pose of the driver after the lug's limits were widened by hand: the writer reads the rule before it writes",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: and a pose of the lug itself",
"ok": true,
"detail": null
},
{
"name": "a loop given a second driver by hand reads follows.holds false on both followers, naming both drivers, while its closure holds",
"ok": true,
"detail": null
},
{
"name": "the joints report lists a loop with a second driver in manyDrivers, by its closing part and with both drivers: in a report of the whole mechanism, in one of the second driver's own sub-tree, and not in one of a tree the loop is no part of",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: set_params of the part a two-driver loop closes on (finding set-params-writes-before-the-guard): the rule is read before the mesh is rebuilt",
"ok": true,
"detail": null
},
{
"name": "and nothing moved: the part's vertices read as before the refusal",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: setObjectParent of the root a two-driver loop hangs from: the write touches the loop",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: setObjectParent that gives another loop a second driver, in a scene that already holds one: the four-bar's base under Idle",
"ok": true,
"detail": null
},
{
"name": "set_params of a part no loop hangs from is written in a scene that holds a second driver, and set back",
"ok": true,
"detail": null
},
{
"name": "a pose of a joint no loop hangs from is written in a scene that holds a second driver",
"ok": true,
"detail": null
},
{
"name": "setObjectParent of a camera under an empty, of the empty under a kit part and under a part of the two-driver loop itself, and clearing the camera's, are written in a scene that holds a second driver: nothing of a loop hangs from them",
"ok": true,
"detail": null
},
{
"name": "and the loop's root under that camera is refused: the camera is no kit part, the root is what the loop hangs from",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: set_params of the driver of a two-driver loop that neither end hangs from: the write touches the loop",
"ok": true,
"detail": null
},
{
"name": "with the lug held again the driver is posed",
"ok": true,
"detail": null
},
{
"name": "and with one driver again the follower's follows row holds and the joints report lists no loop",
"ok": true,
"detail": null
},
{
"name": "the torque link has one degree of freedom: the rod's slide is its one row with travel that nothing drives, the lug is its one held row, the arms are driven, and no row is unlimited",
"ok": true,
"detail": null
},
{
"name": "a joint both ends of a loop hang from is not one the loop depends on: the barrel hung on a free hinge, the arms follow the rod again",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: detach after the loop is stated: the lug cut from the rod no longer hangs from the barrel, so the barrel's free hinge is a second driver",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: setObjectParent clearing the lug's parent (finding bridge-reparent-bypasses-the-guard): Brokkr's own row asks the same rule before it writes a parent",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: setObjectParent of a root onto a part on a free pin: with the four-bar's base under Idle, the rocker the ram closes on depends on Idle's roll",
"ok": true,
"detail": null
},
{
"name": "setObjectParent of a part no loop depends on is written as before, and cleared again",
"ok": true,
"detail": null
},
{
"name": "joints is version 2: a driven row names what drives it (F6), and unlimited lists the rows that are not driven and state no limits",
"ok": true,
"detail": null
},
{
"name": "a loop's two followers are driven rows, kind loop",
"ok": true,
"detail": null
},
{
"name": "a root that states a DOF connection has its own row first, parent null",
"ok": true,
"detail": null
},
{
"name": "after carries the rows after an id (F12)",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: after an id that is no row's",
"ok": true,
"detail": null
},
{
"name": "a tree of 264 unlimited joints with long names, whose ids alone are over a receipt, is many reports and none over a receipt: each carries rows, the ids of its own rows as unlimited, a count of what it omits and the last id it carries as next, and after it the next carries on",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: set_params of a part whose roll was written by hand outside its limits (F9): the mesh is not rebuilt",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: and of its parent",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: set_params of a part with a slide written by hand on a revolute connection",
"ok": true,
"detail": null
},
{
"name": "a compliance written by hand on a revolute joint reads null in the report and the joints report (F10), and the limits beside it still read",
"ok": true,
"detail": null
},
{
"name": "set_params seats through the one writer: the part is rebuilt, its child seated on the moved socket, and the hand-written compliance is gone",
"ok": true,
"detail": null
},
{
"name": "detaching a loop's closing follower clears its partner's statement too",
"ok": true,
"detail": null
},
{
"name": "and the partner is posed by hand again",
"ok": true,
"detail": null
},
{
"name": "detaching a driver leaves its followers' statements, which report that the driver states no DOF connection",
"ok": true,
"detail": null
},
{
"name": "and once the driver is deleted, that it is gone",
"ok": true,
"detail": null
},
{
"name": "no Blender driver or constraint was made",
"ok": true,
"detail": null
}
],
"hostErrors": [],
"readings": {
"closed": 6.4e-07,
"jump": 49.0,
"longest receipt": 16000.0,
"ram closed at 110": 2.9e-07,
"ram closed at 45": 5.3e-07,
"ram closed at 60": 2.8e-07,
"ram solved at 110": 5.7e-14,
"ram solved at 45": 0.0,
"ram solved at 60": 0.0,
"ratio": 0.0,
"rows in the first receipt": 32.0,
"slid": 1e-07,
"solved": 3.3e-05
},
"ok": true
}

View file

@ -445,7 +445,8 @@ try:
R["joints"] = joints
table = {row["id"]: row for row in (joints or {}).get("joints", [])}
check("joints reports the tree under the tank: schema, the root's frame, a row per DOF connection depth first with children by name, parents first, rigid ones counted",
receipt["status"] == "accepted" and {k: v for k, v in joints.items() if k != "joints"} == {"schema": "brokkr.joints", "version": 1, "root": "Tank", "frame": "the root object's: Blender axes (+Z up), metres", "rigid": 2}
receipt["status"] == "accepted" and {k: v for k, v in joints.items() if k != "joints"} == {"schema": "brokkr.joints", "version": 2, "root": "Tank", "frame": "the root object's: Blender axes (+Z up), metres", "rigid": 2,
"unlimited": ["Barrel", "Toe", "Ram"], "manyDrivers": [], "next": None}
and [row["id"] for row in joints["joints"]] == ["Strut", "Barrel", "Rod", "Hinge", "Toe", "Ram"], [receipt["message"], joints])
check("a joint's parent is the nearest DOF connection above it, not the object it hangs from: the toe's is the hinge, through the rigid foot; the rod's is the barrel",
{name: row["parent"] for name, row in table.items()} == {"Strut": None, "Barrel": "Strut", "Rod": "Barrel", "Hinge": "Strut", "Toe": "Hinge", "Ram": "Strut"} and toe.parent == foot,
@ -466,8 +467,9 @@ try:
and table["Strut"] == {**table["Strut"], "value": round(value, 6), "min": round(round(near + 2.0, 3) - value, 6), "max": round(round(far - 2.0, 3) - value, 6), "mechanism": "knee"}
and table["Ram"] == {**table["Ram"], "value": -36.0, "limits": None, "min": None, "max": None, "mechanism": None, "compliance": None}, table)
receipt, below = send("brokkr_kitbash.joints", object_name="Hinge")
check("under another root the rows are in its frame and begin below it", receipt["status"] == "accepted" and [(row["id"], row["parent"]) for row in below["joints"]] == [("Toe", None)] and below["rigid"] == 1
and float(np.abs((np.linalg.inv(np.array(hinge.matrix_world, dtype=np.float64)) @ frame(foot, "pivot"))[:3, 3] - below["joints"][0]["origin"]).max()) < JOINT_FRAME, below)
check("under another root the rows are in its frame and begin with the root's own joint, parent null", receipt["status"] == "accepted"
and [(row["id"], row["parent"]) for row in below["joints"]] == [("Hinge", None), ("Toe", "Hinge")] and below["rigid"] == 1 and below["unlimited"] == ["Toe"]
and float(np.abs((np.linalg.inv(np.array(hinge.matrix_world, dtype=np.float64)) @ frame(foot, "pivot"))[:3, 3] - below["joints"][1]["origin"]).max()) < JOINT_FRAME, below)
refused("joints of a mesh that is not a kit part", "brokkr_kitbash.joints", {"object_name": "Plain"}, "'Plain' is not a kit part")
# --- detach clears the record -------------------------------------------------------------------------------------------

View file

@ -457,7 +457,7 @@
"detail": null
},
{
"name": "under another root the rows are in its frame and begin below it",
"name": "under another root the rows are in its frame and begin with the root's own joint, parent null",
"ok": true,
"detail": null
},
@ -494,10 +494,17 @@
},
"joints": {
"schema": "brokkr.joints",
"version": 1,
"version": 2,
"root": "Tank",
"frame": "the root object's: Blender axes (+Z up), metres",
"rigid": 2,
"unlimited": [
"Barrel",
"Toe",
"Ram"
],
"manyDrivers": [],
"next": null,
"joints": [
{
"id": "Strut",
@ -522,8 +529,10 @@
],
"min": -3.000003,
"max": 72.999997,
"held": false,
"mechanism": "knee",
"compliance": null
"compliance": null,
"driven": null
},
{
"id": "Barrel",
@ -545,8 +554,10 @@
"limits": null,
"min": null,
"max": null,
"held": false,
"mechanism": null,
"compliance": null
"compliance": null,
"driven": null
},
{
"id": "Rod",
@ -571,11 +582,13 @@
],
"min": -0.12,
"max": 0.18,
"held": false,
"mechanism": "shock",
"compliance": {
"damping_ratio": 0.7,
"hertz": 4.0
}
},
"driven": null
},
{
"id": "Hinge",
@ -600,8 +613,10 @@
],
"min": -75.0,
"max": 35.0,
"held": false,
"mechanism": "ankle",
"compliance": null
"compliance": null,
"driven": null
},
{
"id": "Toe",
@ -623,8 +638,10 @@
"limits": null,
"min": null,
"max": null,
"held": false,
"mechanism": null,
"compliance": null
"compliance": null,
"driven": null
},
{
"id": "Ram",
@ -646,8 +663,10 @@
"limits": null,
"min": null,
"max": null,
"held": false,
"mechanism": null,
"compliance": null
"compliance": null,
"driven": null
}
]
},

View file

@ -1594,6 +1594,241 @@ class JointRecordTests(unittest.TestCase):
with self.assertRaisesRegex(core.KitError, "it reaches -1.000000 m to 1.000000 m"):
core.reach_roll(np.eye(4), ident, ident, (0.0, 1.0, 0.0), (1.0, 0.0, 0.0), 1.5, 0.0, (0.0, 90.0))
def test_joint_rows_are_the_tree_s_dof_connections_in_the_root_s_frame(self):
"""core.joint_rows, what brokkr_kitbash.joints reports: a barrel on a strut's pin (revolute), its rod (prismatic)
and, on a root turned and moved in the world, a rigid part between two joints. Mutants J7 (a row's parent the
part's parent, not the nearest joint above: 'Plate'), J8 (min and max the limits themselves: -20 and 60 for
-50 and 30) and J11 (axis and origin in the world's frame: the origin stands 5.4 m off)."""
parts = self.kit["parts"]
strut, barrel, rod = (core.build(parts[name], {}) for name in ("strut", "ram_barrel", "ram_rod"))
socket = lambda built, name: next(s for s in built.sockets if s["name"] == name) # noqa: E731
root = np.eye(4)
root[:3, :3] = core._rotation((20.0, -35.0, 50.0))
root[:3, 3] = (1.0, -2.0, 5.0)
barrel_world = root @ core.mate(socket(strut, "end_b"), socket(barrel, "base"), 30.0)
record = {"limits": (-20.0, 60.0), "mechanism": "elbow", "compliance": None}
free = {"limits": None, "mechanism": None, "compliance": None}
rows, rigid = core.joint_rows(root, [
("Barrel", "Root", "ram_barrel", socket(strut, "end_b"), root, "revolute", 30.0, record, None),
("Plate", "Barrel", "bracket", socket(barrel, "port_cap"), barrel_world, None, 0.0, free, None),
("Rod", "Plate", "ram_rod", socket(barrel, "bore"), barrel_world, "prismatic", 0.125, free, {"by": "Barrel", "kind": "ratio", "k": 0.001, "offset": 0.095})])
self.assertEqual(rigid, 1)
self.assertEqual([(row["id"], row["parent"], row["kind"], row["socket"]) for row in rows],
[("Barrel", None, "revolute", "Root:end_b"), ("Rod", "Barrel", "prismatic", "Plate:bore")])
self.assertEqual((rows[0]["value"], rows[0]["limits"], rows[0]["min"], rows[0]["max"], rows[0]["mechanism"], rows[0]["driven"]), (30.0, [-20.0, 60.0], -50.0, 30.0, "elbow", None))
self.assertEqual((rows[1]["value"], rows[1]["limits"], rows[1]["min"], rows[1]["max"], rows[1]["driven"]["by"]), (0.125, None, None, None, "Barrel"))
self.assertEqual([row["held"] for row in rows], [False, False])
(held,), _ = core.joint_rows(root, [("Lug", "Root", "strut", socket(strut, "end_b"), root, "revolute", 90.0, {**free, "limits": (90.0, 90.0)}, None)])
self.assertEqual((held["limits"], held["min"], held["max"], held["held"]), ([90.0, 90.0], 0.0, 0.0, True)) # limits of one value: no travel, and the row says so
pin = socket(strut, "end_b")["matrix"]
self.assertEqual((rows[0]["axis"], rows[0]["origin"]), ([round(float(v), 6) for v in pin[:3, 2]], [round(float(v), 6) for v in pin[:3, 3]])) # in the root's frame: the socket as the part has it
bore = core.mate(socket(strut, "end_b"), socket(barrel, "base"), 30.0) @ socket(barrel, "bore")["matrix"]
self.assertEqual((rows[1]["axis"], rows[1]["origin"]), ([round(float(v), 6) for v in bore[:3, 2]], [round(float(v), 6) for v in bore[:3, 3]]))
self.assertGreater(float(np.linalg.norm((root @ pin)[:3, 3] - pin[:3, 3])), 5.0) # the world's frame is not the root's here
def test_limit_slack_sits_between_a_typed_end_and_the_least_refused(self):
"""joint-records-lows. core.LIMIT_SLACK at the midpoint of its readings (2.4e-07), read 1.2 either side: a
slack of 1.9e-08 loses float32(-20.1) and the value 2e-07 off; one of 2e-06 or 2.9e-06 (or the 1e-06 there
was) takes the value 2.9e-07 off."""
typed = float(np.float32(-20.1))
self.assertAlmostEqual(abs(typed + 20.1) / 20.1, 1.9e-8, delta=1e-9)
for revolute in (False, True):
self.assertEqual(core.within(typed, -20.1, 5.0, revolute), -20.1)
self.assertEqual(core.within(-20.1 * (1 + 2.0e-7), -20.1, 5.0, revolute), -20.1)
self.assertIsNone(core.within(5.0 + 20.1 * 2.9e-7, -20.1, 5.0, revolute))
self.assertIsNone(core.within(-20.1 * (1 + 2.9e-7), -20.1, 5.0, False))
@unittest.skipIf(np is None, "numpy is not installed")
class FollowTests(unittest.TestCase):
"""core.close_loop: a driven pair of joints solved from the kit's socket frames and one closure. The four-bar is
three mechanical struts, crank (the driver, on a ground pin), rocker and coupler, the coupler's end_b closing on the
crank's end_b, against ram.pose's analytic four-bar; the ram is a ram_barrel on a ground pin and a ram_rod in its
bore, rod_end closing on the crank's end_b_back. Bounds by lodur:ruling:deterministic-bound-margin; T1 is
core.FOLLOW_TOLERANCE at core.HELD."""
D0, REST, RAM_REST = 30.0, (-40.0, 70.0), (200.0, 0.1)
PHI = 2.8e-7 # degrees between the rocker's roll change and ram.pose's phi. shipped 1.9e-10; least mutant 4.0e-4 (T1); separation 1.4e3 each side
SLID = 5.6e-10 # metres between the rod's slide and |pin - base| less the closed length. shipped 5.4e-13; least mutant 5.9e-7 (T1); separation 1.0e3 each side
BRANCH = 1e-6 # degrees between one solve across a jump and the stepped answer. shipped 4e-12 (both converge to FOLLOW_TOLERANCE); a rule: the other branch stands tens of degrees off
CLOSED = 1.0e-10 # metres an accepted solve's closing origin stands from the pin, read from the frames. shipped worst 4.1e-11; a FOLLOW_TOLERANCE of 3e-10 reads 2.5e-10; separation 2.5 each side
@classmethod
def setUpClass(cls):
spec = importlib.util.spec_from_file_location("brokkr_kitbash_ram_reference", SURFACE / "brokkr_kitbash" / "ram.py")
cls.ram = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = cls.ram
spec.loader.exec_module(cls.ram)
kit = core.load_kit("mechanical")
sockets = lambda name, **params: {s["name"]: s for s in core.build(core.part(kit, name), params).sockets} # noqa: E731
cls.crank, cls.rocker, cls.coupler = sockets("strut", length=0.5), sockets("strut", length=0.9), sockets("strut", length=0.7)
cls.barrel, cls.rod = sockets("ram_barrel"), sockets("ram_rod")
cls.ground = cls.pin((0.0, 0.0, 0.0))
cls.rocker_pin = cls.pin(cls.crank_pin(cls.D0)[:3, 3] - cls.coupler_end(cls.ground, cls.REST)[:3, 3]) # where the loop closes at rest
cls.four_bar = [(cls.rocker_pin, cls.rocker["end_a"], "revolute"), (cls.rocker["end_b"], cls.coupler["end_a"], "revolute")]
cls.barrel_pin = cls.pin(cls.crank_pin(cls.D0, "end_b_back")[:3, 3] - cls.rod_end(cls.ground, cls.RAM_REST)[:3, 3])
cls.ram_loop = [(cls.barrel_pin, cls.barrel["base"], "revolute"), (cls.barrel["bore"], cls.rod["piston"], "prismatic")]
@staticmethod
def pin(origin, z=(0.0, 1.0, 0.0), y=(0.0, 0.0, 1.0)):
z, y, frame = np.array(z, dtype=np.float64), np.array(y, dtype=np.float64), np.eye(4)
frame[:3, 0], frame[:3, 1], frame[:3, 2], frame[:3, 3] = np.cross(y, z), y, z, origin
return {"name": "ground", "type": "pivot", "matrix": frame}
@classmethod
def crank_pin(cls, driver, socket="end_b"):
return core.mate(cls.ground, cls.crank["end_a"], driver) @ cls.crank[socket]["matrix"]
@classmethod
def coupler_end(cls, pin, values):
return core.mate(pin, cls.rocker["end_a"], values[0]) @ core.mate(cls.rocker["end_b"], cls.coupler["end_a"], values[1]) @ cls.coupler["end_b"]["matrix"]
@classmethod
def rod_end(cls, pin, values):
return core.mate(pin, cls.barrel["base"], values[0]) @ core.mate(cls.barrel["bore"], cls.rod["piston"], 0.0, values[1]) @ cls.rod["rod_end"]["matrix"]
def solve(self, driver, seed):
return core.close_loop(np.eye(4), self.four_bar, self.coupler["end_b"], self.crank_pin(driver), seed)
def conditioning(self, values):
"""The reading core.FOLLOW_SINGULAR bounds, by this file's own route: the two unit Jacobian columns' smaller singular value."""
first = core.mate(self.rocker_pin, self.rocker["end_a"], values[0])
q, columns = self.coupler_end(self.rocker_pin, values)[:3, 3], []
for at in (self.rocker_pin["matrix"], first @ self.rocker["end_b"]["matrix"]):
column = np.cross(at[:3, 2], q - at[:3, 3])
columns.append(column / np.linalg.norm(column))
return float(np.linalg.svd(np.stack(columns, axis=1), compute_uv=False)[-1])
def stepped(self, deltas):
seed, worst = self.REST, {"phi": 0.0, "iterations": 0, "conditioning": math.inf, "closed": 0.0}
rest = (core.mate(self.rocker_pin, self.rocker["end_a"], self.REST[0]) @ self.rocker["end_b"]["matrix"])[:3, 3]
four_bar = self.ram.Mechanism("four_bar", pivot=self.ground["matrix"][:3, 3], axis=self.ground["matrix"][:3, 2], lo=-90, hi=130, a=np.array([0.3, 0.0, -0.4]),
rocker=self.rocker_pin["matrix"][:3, 3], p=rest, c=self.crank_pin(self.D0)[:3, 3], d=rest)
for delta in deltas:
seed, iterations = self.solve(self.D0 + delta, seed)
worst["phi"] = max(worst["phi"], abs(seed[0] - self.REST[0] - math.degrees(self.ram.pose(four_bar, delta).phi[0])))
worst["iterations"], worst["conditioning"] = max(worst["iterations"], iterations), min(worst["conditioning"], self.conditioning(seed))
worst["closed"] = max(worst["closed"], float(np.linalg.norm(self.crank_pin(self.D0 + delta)[:3, 3] - self.coupler_end(self.rocker_pin, seed)[:3, 3])))
return seed, worst
def test_a_four_bar_loop_matches_ram_pose(self):
"""loop-matches-ram-pose. 56 driver steps of 5 degrees, +120 and back to -30. Mutant F1 (a revolute Jacobian
column's sign flipped: no solve converges). The readings here are the shipped side of core's three bounds:
conditioning least 0.184 (at -30), iterations at most 4 (the step to -30), and the closing origin 4.1e-11 m
from the pin at worst: a FOLLOW_TOLERANCE of 3e-10 stops one step short on 2.5e-10. FOLLOW_ITERATIONS is its
rule, four times the worst."""
_, worst = self.stepped([*np.arange(0.0, 121.0, 5.0), *np.arange(120.0, -31.0, -5.0)])
self.assertLess(worst["phi"], self.PHI)
self.assertEqual(worst["iterations"], 4)
self.assertEqual(core.FOLLOW_ITERATIONS, 4 * worst["iterations"])
self.assertLess(worst["closed"], self.CLOSED)
self.assertLess(worst["closed"], core.FOLLOW_TOLERANCE)
self.assertAlmostEqual(worst["conditioning"], 0.184, delta=0.001)
self.assertGreater(worst["conditioning"], 1.2 * core.FOLLOW_SINGULAR)
def test_a_ram_loop_slides_to_the_pin(self):
"""loop-matches-ram-pose, a revolute and a prismatic unknown: the slide is the distance from the barrel's base
pin to the pin the rod closes on, less that distance closed."""
seed, base, worst = self.RAM_REST, self.barrel_pin["matrix"][:3, 3], 0.0
closed = float(np.linalg.norm(self.rod_end(self.barrel_pin, (self.RAM_REST[0], 0.0))[:3, 3] - base))
for delta in np.arange(0.0, 121.0, 5.0):
target = self.crank_pin(self.D0 + delta, "end_b_back")
seed, iterations = core.close_loop(np.eye(4), self.ram_loop, self.rod["rod_end"], target, seed)
worst = max(worst, abs(seed[1] - (float(np.linalg.norm(target[:3, 3] - base)) - closed)))
self.assertLessEqual(iterations, 3)
self.assertLess(worst, self.SLID)
self.assertGreater(seed[1] - self.RAM_REST[1], 0.2) # the rod moved
def test_a_ram_s_dead_centre_is_its_rod_end_on_the_barrel_pin(self):
"""A ram's conditioning is its lever over its lever closed, and its dead centre the rod's end on the barrel's
pin: drawn in along its own line the ram is accepted at 0.184 of the closed lever and refused at 0.047, the two
readings core.FOLLOW_SINGULAR sits between; and one solve to a pin on the far side of the barrel's, which
Newton answers in one step with the rod's end through the pin, is refused as past the dead centre and not
answered. Mutants C1 (the ram's revolute column scaled to unit length as a four-bar's: it reads 1 at 0.047)
and C2 (the side not read: the far pin is answered at a slide of -1.2 closed levers)."""
base, rest = self.barrel_pin["matrix"][:3, 3], self.crank_pin(self.D0, "end_b_back")
closed = float(np.linalg.norm(self.rod_end(self.barrel_pin, (self.RAM_REST[0], 0.0))[:3, 3] - base))
along = (rest[:3, 3] - base) / np.linalg.norm(rest[:3, 3] - base)
def pin(lever):
target = rest.copy()
target[:3, 3] = base + along * lever * closed
return target
seed = self.RAM_REST
for lever in (1.0, 0.8, 0.6, 0.4, 0.3, 0.184):
seed, _ = core.close_loop(np.eye(4), self.ram_loop, self.rod["rod_end"], pin(lever), seed)
self.assertAlmostEqual(seed[1], (lever - 1.0) * closed, delta=self.SLID)
self.assertAlmostEqual(seed[0], self.RAM_REST[0], delta=self.BRANCH)
self.assertGreater(0.184, 1.2 * core.FOLLOW_SINGULAR)
self.assertLess(0.047, core.FOLLOW_SINGULAR / 1.2)
with self.assertRaisesRegex(core.KitError, r"^the loop is at a dead centre \(its two joints move closing socket 'rod_end' along one line: conditioning 0\.047, under 0\.093\)$"):
core.close_loop(np.eye(4), self.ram_loop, self.rod["rod_end"], pin(0.047), seed)
with self.assertRaisesRegex(core.KitError, r"^the loop is past a dead centre \(the step takes the two joints that move closing socket 'rod_end' to their other assembly: "
r"conditioning 0\.184 on that side\)$"):
core.close_loop(np.eye(4), self.ram_loop, self.rod["rod_end"], pin(-0.184), seed)
def test_a_dead_centre_is_refused(self):
"""loop-refusals. Stepping the crank back, rocker and coupler straighten: the step to -35 stands 6.7 degrees
from straight, conditioning 0.047, the refused side of core.FOLLOW_SINGULAR; past it no pose closes the loop,
and at -60 Newton's first step bends the pair the other way, which is refused as past the dead centre."""
seed, _ = self.stepped(np.arange(0.0, -31.0, -5.0))
self.assertLess(0.047, core.FOLLOW_SINGULAR / 1.2)
for delta in (-35.0, -40.0):
with self.assertRaisesRegex(core.KitError, r"^the loop is at a dead centre \(its two joints move closing socket 'end_b' along one line"):
self.solve(self.D0 + delta, seed)
with self.assertRaisesRegex(core.KitError, r"^the loop is past a dead centre \(the step takes the two joints that move closing socket 'end_b' to their other assembly"):
self.solve(self.D0 - 60.0, seed)
near, _ = self.stepped(np.arange(0.0, -34.0, -1.0)) # by single degrees it is accepted to -33, and -34 reads 0.092
self.assertAlmostEqual(self.conditioning(near), 0.1212, delta=0.001)
with self.assertRaisesRegex(core.KitError, r"conditioning 0\.0919, under 0\.093\)$"):
self.solve(self.D0 - 34.0, near)
def test_a_loop_that_is_not_planar_is_refused(self):
"""loop-refusals. Mutant F8 (the parallel check dropped). A pin a degree off the closure's, a slide a degree out
of the plane, a closing socket facing the wrong way, and a loop that closes in the plane and misses along the pin."""
tilted = self.pin(self.rocker_pin["matrix"][:3, 3], z=(math.sin(math.radians(1.0)), math.cos(math.radians(1.0)), 0.0))
with self.assertRaisesRegex(core.KitError, r"^the loop is not planar: the revolute joint on socket 'ground' turns about a pin that is not parallel to the pin it closes on \(off by 0\.0174"):
core.close_loop(np.eye(4), [(tilted, self.rocker["end_a"], "revolute"), self.four_bar[1]], self.coupler["end_b"], self.crank_pin(self.D0), self.REST)
lean = np.eye(4)
lean[:3, :3] = core._rotation((1.0, 0.0, 0.0))
bore = {**self.barrel["bore"], "matrix": self.barrel["bore"]["matrix"] @ lean}
with self.assertRaisesRegex(core.KitError, r"the prismatic joint on socket 'bore' slides along a line that is not across the pin it closes on"):
core.close_loop(np.eye(4), [self.ram_loop[0], (bore, self.rod["piston"], "prismatic")], self.rod["rod_end"], self.crank_pin(self.D0, "end_b_back"), self.RAM_REST)
with self.assertRaisesRegex(core.KitError, r"closing socket 'end_b_back' does not face the pin it closes on"):
core.close_loop(np.eye(4), self.four_bar, self.coupler["end_b_back"], self.crank_pin(self.D0), self.REST)
missed = self.crank_pin(self.D0)
missed[:3, 3] += 0.001 * missed[:3, 2]
with self.assertRaisesRegex(core.KitError, r"^the loop closes in its plane and closing socket 'end_b' misses along the pin by 0\.001 m$"):
core.close_loop(np.eye(4), self.four_bar, self.coupler["end_b"], missed, self.REST)
self.assertEqual(self.solve(self.D0, self.REST), (self.REST, 0)) # at rest it holds: no step is taken
def test_a_loop_that_does_not_converge_is_refused(self):
"""loop-refusals. A pin 3.9 m out of the reach of a 0.9 and a 0.7 strut, where Newton from rest neither
straightens the pair nor bends it the other way in FOLLOW_ITERATIONS steps: refused by its own name, with
how far off it stands."""
target = self.crank_pin(self.D0)
target[:3, 3] += (-1.2, 0.0, 3.8)
with self.assertRaisesRegex(core.KitError, r"^the loop did not close in 16 steps \(closing socket 'end_b' stands 3\.94584 m off in the plane\)$"):
core.close_loop(np.eye(4), self.four_bar, self.coupler["end_b"], target, self.REST)
def test_stepping_keeps_the_assembly_branch(self):
"""branch-kept. One solve across a 40 degree jump lands on the stepped answer; one solve from near the toggle
(-32) across 49 degrees does not: Newton's first step throws the pair through the dead centre, where it is
refused instead of landing on the other branch, and the same jump stepped by 5 arrives. Mutant F2 is the
add-on's (pose solving once from the stated value): tests/live/kitbash_follows.py kills it."""
stepped, _ = self.stepped(np.arange(0.0, 41.0, 5.0))
jumped, iterations = self.solve(self.D0 + 40.0, self.REST)
self.assertLess(max(abs(a - b) for a, b in zip(stepped, jumped)), self.BRANCH)
self.assertEqual(iterations, 4)
toggle, _ = self.stepped(np.arange(0.0, -33.0, -1.0))
with self.assertRaisesRegex(core.KitError, "dead centre"):
self.solve(self.D0 + 17.0, toggle)
seed = toggle
for delta in (-27.0, -22.0, -17.0, -12.0, -7.0, -2.0, 3.0, 8.0, 13.0, 17.0):
seed, _ = self.solve(self.D0 + delta, seed)
direct, _ = self.stepped([17.0])
self.assertLess(max(abs(a - b) for a, b in zip(seed, direct)), self.BRANCH)
@unittest.skipIf(np is None, "numpy is not installed")
class StructureTests(unittest.TestCase):
@ -1998,7 +2233,7 @@ class SheetTests(unittest.TestCase):
ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report",
"brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach",
"brokkr_kitbash.joint", "brokkr_kitbash.slide", "brokkr_kitbash.joints", "brokkr_kitbash.close",
"brokkr_kitbash.joint", "brokkr_kitbash.slide", "brokkr_kitbash.joints", "brokkr_kitbash.follow", "brokkr_kitbash.close",
"brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.freeze", "brokkr_kitbash.thaw", "brokkr_kitbash.ribs",
"brokkr_kitbash.shell", "brokkr_kitbash.hose", "brokkr_kitbash.plates"]
@ -2294,6 +2529,66 @@ class OwnershipTests(unittest.TestCase):
for path in schemas:
self.assertIsNone(re.search(self.SCHEMAS, path.read_text(encoding="utf-8", errors="replace")), path.name)
def test_a_follower_has_one_writer_and_one_place_it_is_derived(self):
"""The negative patterns of cut kit-follows-2: kit_follows and its driver pointer are written only inside
write_connections; set_params seats through it, its checks before the mesh is rebuilt; no linkage record is
stored and no Blender driver or constraint is made; close_loop is called from driven alone."""
source = self.sources()["__init__.py"]
writer = source.split("\ndef write_connections(")[1].split("\n\n\n")[0]
writes = r"\[FOLLOWS(?:_DRIVER)?\] ="
self.assertEqual(re.findall(writes, source), re.findall(writes, writer))
self.assertEqual(len(re.findall(writes, writer)), 2)
for name, text in self.sources().items():
self.assertIsNone(re.search("kit_" "drive" r"\b", text), name)
self.assertIsNone(re.search(r"seat\(seated|driver_add\(|constraints\.new\(", source))
self.assertEqual(source.count("seat("), 6) # its def, write_connections, and a cutter's, a ribs' and a hose's own frames, and a plate's own frame
body = source.split("class BROKKR_KITBASH_OT_set_params(")[1].split("class BROKKR_KITBASH_OT_")[0]
self.assertLess(body.index("write_checks(entries)"), body.index("clear_geometry()")) # the writer's own checks, the one-driver rule with them (live: 'set_params of the part a two-driver loop closes on')
self.assertLess(body.index("write_checks(entries)"), body.index("obj[PARAMS] ="))
self.assertLess(body.index("clear_geometry()"), body.index("write_connections(entries)"))
self.assertEqual(source.count("core.close_loop("), 1)
self.assertIn("core.close_loop(", source.split("\ndef driven(")[1].split("\n\n\n")[0])
self.assertEqual(source.count("write_connections(["), 2) # write_connection, and follow clearing a statement
# every entry is checked before one is written (mutant J5, a refusal raised after the writes; F5 is its live twin): the writer's loop runs over the
# checks' whole answer and raises nothing itself, and the checks write nothing
self.assertIn(" for child, parent, sockets, socket, parent_socket, roll, slide, kind, record in write_checks(entries):\n child.parent = parent\n", writer)
asked = source.split("\ndef write_checks(")[1].split("\n\n\n")[0]
self.assertIn(" checked = connection_checks(entries)\n one_driver({child: (parent, kind, record) for child, parent, _, _, _, _, _, kind, record in checked})\n return checked", asked)
self.assertNotIn("raise ", writer)
# the one-driver rule has one owner, asked by write_checks (the one writer, and set_params before its mesh), by detach and by
# brokkr_parent_refusal (Brokkr's setObjectParent) before any writes, and it writes nothing: no action states its own copy (live: an attach, a
# clear, widened limits, a pose, a set_params, a detach and a new parent after the loop is stated are each refused)
rule = source.split("\ndef one_driver(")[1].split("\n\n\n")[0]
self.assertEqual((source.count("one_driver("), source.count("depend on more than one driver")), (4, 1))
# which joints are a loop's drivers is read in one place, loop_drivers: the rule refuses by it and the reads tell by it (finding
# two-driver-loop-reported-nowhere), so a second driver no write made is in a follower's follows row and the joints report's manyDrivers
# (live: 'a loop given a second driver by hand reads follows.holds false' and 'the joints report lists a loop with a second driver')
self.assertEqual((source.count("loop_drivers("), source.count("it follows nothing and its joint has travel"), rule.count("loop_drivers(closing, parent, joint)")), (4, 1, 1))
teller = source.split("\ndef follows_report(")[1].split("\n\n\n")[0]
self.assertLess(teller.index("loop_drivers(pair[1])"), teller.index("elif others:"))
self.assertLess(teller.index("elif others:"), teller.index('elif not found["holds"]:')) # a second driver is told before an open closure: 'pose the driver' is not its remedy
joints = source.split("class BROKKR_KITBASH_OT_joints(")[1].split("class BROKKR_KITBASH_OT_")[0]
self.assertIn('report["manyDrivers"].append({"loop": closing.name, "drivers": [driver.name, *(o.name for o in others)]})', joints)
self.assertIsNone(re.search(r"\.parent\s*=(?!=)|\bseat\(|\w+\[[A-Z_]+\]\s*=(?!=)|\bdel ", source.split("\ndef loop_drivers(")[1].split("\n\n\n")[0]))
asker = source.split("\ndef brokkr_parent_refusal(")[1].split("\n\n\n")[0]
self.assertIn("one_driver({obj: (parent, kind,", asker)
self.assertIsNone(re.search(r"\.parent\s*=(?!=)|\bseat\(|\w+\[\w+\]\s*=(?!=)|\bdel ", asker + asked))
self.assertIsNone(re.search(r"\.parent\s*=(?!=)|\bseat\(|\w+\[[A-Z_]+\]\s*=(?!=)|\bdel ", rule))
detach = source.split("class BROKKR_KITBASH_OT_detach(")[1].split("class BROKKR_KITBASH_OT_")[0]
self.assertLess(detach.index("one_driver("), detach.index("obj.parent = None"))
self.assertLess(detach.index("one_driver("), detach.index("del obj[key]"))
checks = source.split("\ndef connection_checks(")[1].split("\n\n\n")[0]
self.assertIsNone(re.search(r"\.parent\s*=(?!=)|\bseat\(|\w+\[\w+\]\s*=(?!=)|\bdel ", checks))
self.assertEqual(checks.count("raise Refused("), 1)
# a hose keeps no roll range of its own (mutant J9, a default range for a pin that states no limits; live it dies in kitbash_hose.py, 'a pin with no limits'): it reads the record's limits and refuses without them
hose = source.split("class BROKKR_KITBASH_OT_hose(")[1].split("\n\n\n")[0]
self.assertEqual(re.findall(r"[^\n]*\blimits\s*=(?!=)[^\n]*", hose), [' limits = joint_record(child)["limits"] # the roll range the hose is proven over is the pin\'s own: its connection\'s limits'])
self.assertIn(' if limits is None:\n raise Refused(f"{child.name!r} on {child.parent.name!r}: the pin the hose crosses states no limits', hose)
pose = source.split("\ndef pose(")[1].split("\n\n\n")[0]
self.assertLess(pose.index("if follows is not None and not keeps:"), pose.index("= solve(child"))
self.assertEqual(source.count("keeps=True"), 1)
self.assertIn("keeps=True", source.split("class BROKKR_KITBASH_OT_joint(")[1].split("class BROKKR_KITBASH_OT_")[0])
def test_only_cut_boolean_and_ribs_evaluate_a_modifier_stack(self):
"""An Exact Boolean costs from tenths of a second to seconds: report, attach, detach and set_params read stored
state only, and cut evaluates its target with the Booleans off."""
@ -2429,23 +2724,26 @@ class OwnershipTests(unittest.TestCase):
its own, and no DOF kind is read from a socket type's name."""
source = self.sources()["__init__.py"]
writes = re.findall(r'[^\n]*(?:\[ROLL\]|\["kit_roll"\])\s*=(?!=)[^\n]*', source)
self.assertEqual(writes, [" child[SOCKET], child[PARENT_SOCKET], child[ROLL] = socket, parent_socket, roll"])
writer = source.split("def write_connection(")[1].split("\n\n\n")[0]
self.assertEqual(writes, [" child[SOCKET], child[PARENT_SOCKET], child[ROLL] = socket, parent_socket, roll"])
writer = source.split("def write_connections(")[1].split("\n\n\n")[0]
self.assertIn(writes[0], writer)
record = r"SLIDE|LIMIT_MIN|LIMIT_MAX|MECHANISM|COMPLIANCE|RECORD"
written = rf'\[(?:{record})\](?:, \w+\[\w+\])*\s*=(?!=)|\["kit_(?:slide|min|max|mechanism|compliance)"\]'
self.assertIsNone(re.search(written, source))
self.assertEqual(re.findall(r"[^\n]*\[key\] = [^\n]*", source), [" child[key] = value"])
self.assertIn(" child[key] = value", writer)
self.assertEqual(re.findall(r"[^\n]*\[key\] = [^\n]*", source), [" child[key] = value"])
self.assertIn(" child[key] = value", writer)
named = [body.split("(")[0] for body in re.split(r"\n(?:def|class) ", source)[1:] if re.search(rf"\b(?:{record})\b", body)]
self.assertEqual(named, ["link", "joint_record", "mated", "write_connection", "BROKKR_KITBASH_OT_detach"])
self.assertEqual(named, ["link", "joint_record", "mated", "write_connections", "BROKKR_KITBASH_OT_detach"])
for text in ("child[SLIDE] = slide", "obj[LIMIT_MIN], obj[LIMIT_MAX] = limits", 'obj["kit_compliance"] = text'):
self.assertIsNotNone(re.search(written, text))
self.assertNotIn('"range"', source)
self.assertNotIn('"pivot"', source)
bodies = {body.split("(")[0]: body.split("\n\n\n")[0] for body in source.split("class BROKKR_KITBASH_OT_")[1:]}
callers = [name for name, body in bodies.items() if "write_connection(" in body]
self.assertEqual((callers, source.count("write_connection("), source.split("def pose(")[1].split("\n\n\n")[0].count("write_connection(")), (["attach"], 3, 1))
self.assertEqual((callers, source.count("write_connection(")), (["attach"], 2)) # its def, which is write_connections for one, and attach
callers = [name for name, body in bodies.items() if "write_connections(" in body]
self.assertEqual((callers, source.count("write_connections("), source.split("def pose(")[1].split("\n\n\n")[0].count("write_connections(entries)")),
(["set_params", "follow"], 6, 1)) # its def, write_connection, set_params, pose, and follow stating and clearing
for name in ("roll", "aim", "reach", "slide", "joint"):
self.assertEqual((bodies[name].count("pose(context, self.object_name, "), bool(re.search(r"\.parent\s*=(?!=)|\bseat\(|matrix_basis", bodies[name]))), (1, False), name)
self.assertIsNone(re.search(r"\.parent\s*=(?!=)|\bseat\(|matrix_basis", bodies["attach"]))
@ -2466,13 +2764,15 @@ class OwnershipTests(unittest.TestCase):
self.assertEqual(assigned, [" obj[CLOSE], obj[CLOSE_TO], obj[CLOSE_TO_SOCKET] = self.socket, other, self.other_socket"])
self.assertIn(assigned[0], bodies["close"])
deleted = re.findall(r"[^\n]*\(SOCKET, PARENT_SOCKET, ROLL, \*RECORD, CLOSE, CLOSE_TO, CLOSE_TO_SOCKET\)[^\n]*\n[^\n]*\n\s*del obj\[key\]", source)
self.assertEqual((len(deleted), source.count("del obj["), "del obj[key]" in bodies["detach"]), (1, 2, True)) # detach's keys, and hold's kit_frozen
self.assertEqual((len(deleted), source.count("del obj["), "del obj[key]" in bodies["detach"]), (1, 2, True)) # detach's keys, and hold's kit_frozen; mutant J10 (detach's keys without kit_min) dies on the first, and live in kitbash_pose.py, 'detach leaves none of the eight connection keys'
record = re.search(r"^RECORD = \((.*)\)$", source, re.M).group(1).split(", ")
self.assertEqual(record, ["SLIDE", "LIMIT_MIN", "LIMIT_MAX", "MECHANISM", "COMPLIANCE", "FOLLOWS", "FOLLOWS_DRIVER"]) # the whole joint record: what detach clears
self.assertEqual(source.count("CLOSE_TO]"), 1) # the one subscript write above; every read goes through .get
placing = r"matrix_basis|matrix_world\s*=(?!=)|matrix_parent_inverse|\.parent\s*=(?!=)|\bseat\(|\.location|\.rotation"
self.assertIsNone(re.search(placing, bodies["close"]))
for text in ("child.matrix_basis = basis", "obj.matrix_world = world", "obj.parent = other", "seat(obj, basis)"):
self.assertIsNotNone(re.search(placing, text))
self.assertIsNotNone(re.search(placing, source.split("def write_connection(")[1].split("\n\n\n")[0]))
self.assertIsNotNone(re.search(placing, source.split("def write_connections(")[1].split("\n\n\n")[0]))
def test_the_patterns_bite(self):
planted = ("value = eval(text)", "from brokkr_bridge import x", 'modifier.solver = "MANIFOLD"', "cutter.hide_render = True", 'obj["kit_parent"] = parent.name',