brokkr_kitbash: the one-driver rule is read before every write of a connection and before detach

one_driver reads every loop in the scene as the write would leave it. write_connections and detach ask it, so
attach, detach, clearing a follower, widened or cleared limits and any pose refuse a second driver between a
stated loop's ends, naming both. follow's own copy of the rule is gone.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-03 13:55:42 +01:00
commit 1be1bfc1e6
4 changed files with 153 additions and 33 deletions

View file

@ -222,19 +222,23 @@ def dof(parent, parent_socket: dict):
return core.load_kit(str(parent.get(KIT, "")))["socketTypes"][parent_socket["type"]].get("dof")
def connection_kind(obj) -> tuple:
def connection_kind(obj, kits=None) -> 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."""
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."""
try:
kit = core.load_kit(str(obj.parent.get(KIT, "")))
name, kits = str(obj.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(obj.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) -> dict:
def joint_record(obj, kits=None) -> 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
@ -255,7 +259,7 @@ def joint_record(obj) -> dict:
"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)
kind, socket_type = connection_kind(obj, kits)
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:
@ -391,8 +395,11 @@ def write_connections(entries) -> None:
properties and its joint record, kit_follows and its driver pointer with it. Every entry is checked
(connection_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."""
for child, parent, sockets, socket, parent_socket, roll, slide, kind, record in connection_checks(entries):
be, and that a follower's value is written with its driver's, is decided here. So is the one-driver rule: the
scene as these entries would leave it is read by one_driver before any is written, whatever the action."""
checked = connection_checks(entries)
one_driver({child: (parent, kind, record) for child, parent, _, _, _, _, _, kind, record in checked})
for child, parent, sockets, socket, parent_socket, roll, slide, kind, record in checked:
child.parent = parent
seat(child, core.mate(*sockets, roll, slide))
child[SOCKET], child[PARENT_SOCKET], child[ROLL] = socket, parent_socket, roll
@ -423,6 +430,60 @@ def followers(driver) -> list:
key=lambda o: o.name)
def one_driver(stating: dict) -> None:
"""The one-driver rule, over every loop in the scene as it would stand after a 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. 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_connections and detach ask here before
they write, so no action (attach, detach, clearing a follower, limits widened or cleared, any pose, a new
follow) leaves a loop with two drivers, and a scene edited by hand into one is refused its next write."""
known, kits = {}, {} # each part's joint and each kit file are read once
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]
for closing in sorted((o for o in bpy.data.objects if CLOSE in o and o.users_collection and (FOLLOWS in o or o in stating)), key=lambda o: o.name):
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:
continue
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")
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 sorted(others.items(), key=lambda item: item[0].name))}. 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 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
@ -1014,7 +1075,8 @@ class BROKKR_KITBASH_OT_attach(PolishOperator):
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. 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"""
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")
@ -1026,6 +1088,7 @@ class BROKKR_KITBASH_OT_detach(PolishOperator):
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
@ -1319,25 +1382,6 @@ class BROKKR_KITBASH_OT_follow(PolishOperator):
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.")
chains = [[], []] # 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 = o.parent
others = {} # {a part whose pose moves one end against the other, and is not the driver: why}, from the joints under the ends' nearest common part
for o in (o for found in chains for o in found if not (o in chains[0] and o in chains[1])):
its, limits = joint_record(o)["follows"], joint_record(o)["limits"]
if connection_kind(o)[0] 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: a pin with no travel
others.setdefault(o, "it follows nothing and its joint has travel, so it is posed by hand")
if others:
raise Refused(f"the loop's two ends, {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 sorted(others.items(), key=lambda item: item[0].name))}. A follower takes its value from "
"one driver, and a pose of another would open the loop: let every joint between the two ends be the driver, follow it, or be held by "
"limits of one value; 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)

View file

@ -13,10 +13,12 @@ The scene, every strut 0.09 wide so its pins take a ram's: a four-bar (Crank on
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 strut's two pins face one way, so two arms from the
barrel's pin cannot face the rod's own, and the kit has no rigid lug); a second crank (Crank2 on the root Ground2)
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; Idle and Tip for the refusals; a tree of 264 struts with 62-character names for a joints
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; Idle and Tip for the refusals; 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.
"""
@ -406,6 +408,16 @@ try:
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")
@ -452,6 +464,17 @@ try:
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'")
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, 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 has none, 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"]) for row in joints["joints"]] == [
@ -466,6 +489,10 @@ try:
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")
# --- joints, version 2 ----------------------------------------------------------------------------------------------------------
receipt, joints = send("brokkr_kitbash.joints", object_name="Ground")
table = {row["id"]: row for row in (joints or {}).get("joints", [])}

View file

@ -246,6 +246,16 @@
"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,
@ -291,6 +301,31 @@
"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": "with the lug held again the driver is posed",
"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 has none, the arms are driven, and no row is unlimited",
"ok": true,
@ -301,6 +336,11 @@
"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": "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,

View file

@ -2537,12 +2537,21 @@ class OwnershipTests(unittest.TestCase):
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 connection_checks(entries):\n child.parent = parent\n", writer)
self.assertIn(" checked = connection_checks(entries)\n one_driver({child: (parent, kind, record) for child, parent, _, _, _, _, _, kind, record in checked})\n"
" for child, parent, sockets, socket, parent_socket, roll, slide, kind, record in checked:\n child.parent = parent\n", writer)
self.assertNotIn("raise ", writer)
# the one-driver rule has one owner, asked by the one writer and by detach before either writes, and it writes nothing: no action states its own
# copy (live: an attach, a clear, widened limits, a pose and a detach 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")), (3, 1))
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): it reads the record's limits and refuses without them
# 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)
@ -2726,7 +2735,7 @@ 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; mutant J10 (detach's keys without kit_min) dies on the first
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