brokkr_kitbash.plates: a plate table written into the scene (cut hard-plate-action) #47

Merged
eureka merged 3 commits from nibu/hard-plate-action into main 2026-12-03 15:35:44 +00:00
8 changed files with 1093 additions and 12 deletions

View file

@ -60,6 +60,14 @@ a record: hose is its one writer, and the one thing read back from it is which t
that crosses the same pin (it bends with the pin, so it is measured as an obstacle where it stands and not across the rolls:
follow-up aetheria-release:follow_up:hose-motion-clearance-from-skinning owes that check).
plates writes hard armour plates. plate.py owns the table (brokkr.plates.v0) and every point of a plate, its panels,
bolts and anchor frames, in the table's frame; this file converts its arrays and nothing else. A plate is a mesh
object on its host under an identity parent inverse, with a child per material for its panels and bolts
(<plate>.fit.<material>) and an empty per anchor (<plate>.mark.<id>, <plate>.port.<name>, kit_anchor on each). plates
is the one writer of those objects, their Kit Bevels, plate_kind and kit_plate. kit_plate is the checked row, kept as
a record: its presence admits a rebuild in place and nothing reads it to decide geometry. A plate is no kit part:
joints and report never list it, and a roll of its host carries it by Blender's parenting.
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
@ -85,7 +93,7 @@ try:
except ImportError as error: # register() says so; the classes below only need something to subclass
RESULT, PolishOperator, Refused, mesh_object, MISSING = "brokkr_mesh_polish_result", bpy.types.Operator, RuntimeError, None, error
from . import core, route
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"
@ -115,6 +123,11 @@ 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
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
PLATE_ANGLE, PANEL_ANGLE = math.radians(12.0), math.radians(20.0) # the Kit Bevel's angle limit on a plate, and on a child that holds its panels
ANCHORS = {"mark": "mark", "hose_port": "port"} # an anchor's kind to the part of its empty's name
ROLL_FINEST = 0.3 # degrees: the half width under which a bin of rolls that falls short is refused instead of halved (5 degrees halved 4 times)
@ -147,11 +160,11 @@ def write_mesh(mesh, built) -> None:
crease.data.foreach_set("value", np.isin(key(ends.reshape(-1, 2)), key(built.sharp)))
def sync_bevel(obj, width: float) -> None:
def sync_bevel(obj, width: float, angle: float = BEVEL_ANGLE) -> None:
modifier = obj.modifiers.get(BEVEL)
if modifier is None and width > 0:
modifier = obj.modifiers.new(BEVEL, "BEVEL")
modifier.segments, modifier.limit_method, modifier.angle_limit = BEVEL_SEGMENTS, "ANGLE", BEVEL_ANGLE
modifier.segments, modifier.limit_method, modifier.angle_limit = BEVEL_SEGMENTS, "ANGLE", angle
if modifier is not None:
modifier.width = width
@ -2103,6 +2116,166 @@ class BROKKR_KITBASH_OT_hose(PolishOperator):
return core.joined(shells)
class BROKKR_KITBASH_OT_plates(PolishOperator):
"""Write a table of hard armour plates (brokkr.plates.v0) into the scene: each plate a mesh on its host, with its
panels and bolts as children per material and an empty per anchor; a plate this made is rebuilt in place"""
bl_idname = "brokkr_kitbash.plates"
bl_label = "Write Hard Plates"
host: bpy.props.StringProperty(name="Host", description="The object every plate is parented to; empty: none")
frame: bpy.props.StringProperty(name="Frame", description="The table's frame in the world, a JSON 4x4 of rows; empty: the host's world matrix, or the world with no host")
side: bpy.props.IntProperty(name="Side", default=1, min=-1, max=1, description="1, or -1: the table mirrored across its x = 0")
prefix: bpy.props.StringProperty(name="Prefix", description="Written before every plate's name")
table: bpy.props.StringProperty(name="Table", description="A brokkr.plates.v0 document, as JSON")
@kit_work
def work(self, context):
host, world, table, built = self.read()
plans, taken = [], set()
for entry in built:
plans.append(self.plan(entry, table["plates"][entry["row"]], taken))
inside = [plan["name"] for plan in plans if host is not None and (plan["name"] == host.name or plan["object"] in BROKKR_KITBASH_OT_hose.chain(host))]
if inside:
raise Refused(f"host {host.name!r} is, or stands under, the plate {inside[0]!r} this call writes: a plate is no host of itself; nothing changed.")
report = bounded({"plates": [{"name": plan["name"], "rebuilt": plan["object"] is not None, **plan["entry"]["report"], "anchors": [name for name, _, _ in plan["anchors"]]} for plan in plans],
"host": host.name if host else None, "side": self.side}, "write fewer plates in one call; nothing changed")
basis = (np.linalg.inv(np.array(host.matrix_world)) if host else np.eye(4)) @ world
for plan in plans:
entry, row, obj = plan["entry"], plan["row"], plan["object"]
if obj is None:
obj = bpy.data.objects.new(plan["name"], bpy.data.meshes.new(plan["name"]))
context.scene.collection.objects.link(obj)
self.write(obj.data, [entry["solid"]], row["mat"])
self.stand(obj, host, world, basis)
sync_bevel(obj, row["bevel"], PLATE_ANGLE)
obj[PLATE_KIND], obj[PLATE] = "hard", json.dumps({**row, "side": entry["side"], "prefix": self.prefix})
for child in plan["stale"]:
data = child.data
bpy.data.objects.remove(child)
if data is not None and not data.users:
bpy.data.meshes.remove(data)
for name, material, panels, parts in plan["fits"]:
child = bpy.data.objects.get(name)
if child is None:
child = bpy.data.objects.new(name, bpy.data.meshes.new(name))
context.scene.collection.objects.link(child)
self.write(child.data, parts, material)
self.stand(child, obj, world, np.eye(4))
if panels:
sync_bevel(child, row["clad"]["bevel"], PANEL_ANGLE)
if BEVEL in child.modifiers:
child.modifiers[BEVEL].segments = 1
elif BEVEL in child.modifiers:
child.modifiers.remove(child.modifiers[BEVEL])
for name, record, matrix in plan["anchors"]:
empty = bpy.data.objects.get(name)
if empty is None:
empty = bpy.data.objects.new(name, None)
empty.empty_display_size = 0.05
context.scene.collection.objects.link(empty)
self.stand(empty, obj, world @ matrix, matrix)
empty[ANCHOR] = json.dumps(record)
return report
def read(self):
"""(host or None, the table's frame in the world, the checked table, plate.build's entries), each field refused by
shape, a PlateError with its path."""
for name, text, least, most in (("host", self.host, 0, 63), ("frame", self.frame, 0, 1000), ("table", self.table, 1, 32000)):
if not least <= len(text) <= most:
raise Refused(f"{name} must be {least} to {most} characters, not {len(text)}; nothing changed.")
if not re.fullmatch(r"[A-Za-z0-9_.]{0,32}", self.prefix):
raise Refused(f"prefix {self.prefix!r} must be 0 to 32 characters from a-z A-Z 0-9 _ .; nothing changed.")
if self.side not in (1, -1):
raise Refused(f"side must be 1 or -1, not {self.side}; nothing changed.")
host = None
if self.host:
host = bpy.data.objects.get(self.host)
if host is None:
raise Refused(f"host: no object named {self.host!r}; nothing changed.")
rigid(host)
world = np.array(host.matrix_world) if host else np.eye(4)
if self.frame:
try:
rows = json.loads(self.frame)
except ValueError as error:
raise Refused(f"frame is not JSON ({error}); nothing changed.") from None
if not (isinstance(rows, list) and len(rows) == 4 and all(isinstance(r, list) and len(r) == 4 and all(core.finite(v) for v in r) for r in rows)):
raise Refused("frame must be a JSON array of 4 rows of 4 finite numbers; nothing changed.")
world = np.array(rows, dtype=np.float64)
turn = world[:3, :3]
if np.abs(turn.T @ turn - np.eye(3)).max() > RIGID or np.linalg.det(turn) < 0 or np.abs(world[3] - (0.0, 0.0, 0.0, 1.0)).max() > 0:
raise Refused("frame is not rigid: its 3x3 must be a rotation (no scale, mirror or shear) and its last row 0, 0, 0, 1; nothing changed.")
try:
document = json.loads(self.table)
except ValueError as error:
raise Refused(f"table is not JSON ({error}); nothing changed.") from None
try:
table = plate.check(document)
return host, world, table, plate.build(table, self.side)
except plate.PlateError as error:
raise Refused(f"table: {error}; nothing changed.") from None
def plan(self, entry: dict, row: dict, taken: set) -> dict:
"""What one built entry writes, refused before anything is written: {name, entry, row, object (the plate to
rebuild, or None), fits [(name, material, holds panels, meshes)], anchors [(name, record, matrix)], stale (the
plate's fit children and anchors this call no longer makes)}. `taken` is every name the call has planned."""
name, path, clad = self.prefix + entry["name"], f"table.plates[{entry['row']}]", row["clad"]
for key, material in (("mat", row["mat"]),) + ((("clad.mat", clad["mat"]), ("clad.bolt_mat", clad["bolt_mat"])) if clad else ()):
if material not in bpy.data.materials:
raise Refused(f"{path}.{key}: no material named {material!r}; make it first (createMaterial); nothing changed.")
obj = bpy.data.objects.get(name)
if obj is not None:
if obj.type != "MESH" or PLATE not in obj:
raise Refused(f"{path}: an object named {name!r} exists and is no plate (it carries no {PLATE}): plates rebuilds only what plates made; nothing changed.")
live(obj, "rebuilding")
own_mesh(obj, "rebuilding")
fits = {}
if clad:
for material, panels, mesh in ((clad["mat"], True, entry["panels"]), (clad["bolt_mat"], False, entry["bolts"])):
if len(mesh[1]):
held = fits.setdefault(f"{name}.fit.{material}", [material, False, []])
held[1], held[2] = held[1] or panels, held[2] + [mesh]
anchors = []
for anchor in entry["anchors"]:
record = {"kind": anchor["kind"], "id": anchor["name"], "height": anchor["height"]} if anchor["kind"] == "mark" else {"kind": anchor["kind"], "name": anchor["name"]}
anchors.append((f"{name}.{ANCHORS[anchor['kind']]}.{anchor['name']}", record, np.array(anchor["matrix"])))
for made, kind in [(name, None)] + [(child, "MESH") for child in fits] + [(empty, "EMPTY") for empty, _, _ in anchors]:
if len(made.encode("utf-8")) > 63:
raise Refused(f"{path}: the name {made!r} is {len(made.encode('utf-8'))} bytes, over the 63 an object's name holds: use a shorter prefix, row, material or anchor name; nothing changed.")
if made in taken:
raise Refused(f"{path}: the name {made!r} is made twice in this call; nothing changed.")
taken.add(made)
other = bpy.data.objects.get(made)
if kind is not None and other is not None:
if obj is None or other.parent != obj or other.type != kind:
raise Refused(f"{path}: an object named {made!r} exists and is not this plate's (a {'mesh' if kind == 'MESH' else 'empty'} child of {name!r}); nothing changed.")
if kind == "MESH":
live(other, "rebuilding")
own_mesh(other, "rebuilding")
stale = [] if obj is None else [child for child in obj.children if child.name not in taken
and ((child.type == "MESH" and child.name.startswith(name + ".fit.")) or (child.type == "EMPTY" and ANCHOR in child))]
return {"name": name, "entry": entry, "row": row, "object": obj, "fits": [(child, *held) for child, held in fits.items()], "anchors": anchors, "stale": stale}
@staticmethod
def write(mesh, parts, material: str) -> None:
"""Meshes (V, faces) joined into one datablock, cleared first: every face flat, its first material slot the
material; later slots stay."""
mesh.clear_geometry()
offsets = np.cumsum([0] + [len(V) for V, _ in parts[:-1]])
mesh.from_pydata(np.vstack([V for V, _ in parts]).tolist(), [], [[int(k + offset) for k in face] for (_, faces), offset in zip(parts, offsets) for face in faces])
(mesh.attributes.get("sharp_face") or mesh.attributes.new("sharp_face", "BOOLEAN", "FACE")).data.foreach_set("value", np.ones(len(mesh.polygons), dtype=bool))
mesh.update()
if len(mesh.materials):
mesh.materials[0] = bpy.data.materials[material]
else:
mesh.materials.append(bpy.data.materials[material])
@staticmethod
def stand(obj, parent, world, basis) -> None:
obj.parent = parent
obj.matrix_world = Matrix(np.asarray(world).tolist()) # read by a report; no depsgraph update here
seat(obj, basis)
class BROKKR_KITBASH_OT_describe(PolishOperator):
"""List a kit's parts, or one part: params with type, bounds, default and doc, and sockets in the part's frame
at default params"""
@ -2137,7 +2310,7 @@ classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KI
BROKKR_KITBASH_OT_joint, BROKKR_KITBASH_OT_slide, BROKKR_KITBASH_OT_joints,
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_shell, BROKKR_KITBASH_OT_hose, BROKKR_KITBASH_OT_plates)
SETTLED_ON = (bpy.app.handlers.depsgraph_update_post, bpy.app.handlers.save_pre)

View file

@ -969,6 +969,56 @@
"default": ""
}
]
},
{
"name": "brokkr_kitbash.plates",
"doc": "Write a table of hard armour plates into the scene. table is a brokkr.plates.v0 document as JSON (docs/kitbash.md, Hard plates): {\"schema\": \"brokkr.plates.v0\", \"plates\": [row, ...]}, each row a convex faceted solid with optional clad (raised panels and their bolts) and fits (anchors on its face). The table's coordinates are metres in frame: a JSON 4x4 of rows in the world, rigid; empty, the host's world matrix, or the world with no host. side 1 builds the table as written and -1 mirrored across its x = 0. Each built plate is a mesh object named prefix + its name (.R and .L on a two-sided row), every face flat, parented to host under an identity parent inverse, with material mat, a Kit Bevel of the row's bevel (angle 12 degrees) and the properties plate_kind \"hard\" and kit_plate (its checked row, a record). Its panels are the child <plate>.fit.<clad mat> and its bolts <plate>.fit.<clad bolt_mat>, one mesh per material, made only when not empty; a child that holds panels carries a Kit Bevel of clad.bevel (angle 20 degrees, one segment). Each anchor is an empty child at the anchor's frame: <plate>.mark.<id> with kit_anchor {kind, id, height}, <plate>.port.<name> with kit_anchor {kind, name}; brokkr_kitbash.hose takes a port empty's name as an end and leaves along its z. An object that carries kit_plate under a made name is rebuilt in place: it keeps its identity, its other children and its modifiers; its fit children are rewritten, made or removed, its anchors moved, and one the row no longer names removed. A plate is no kit part: joints and report do not list it, and a roll of its host carries it. Every material must exist (createMaterial). Refuses before it writes anything: a table the format refuses (the path is named), a missing material (named with its path), a host that is missing, scaled, mirrored or sheared, a frame that is not a rigid 4x4, a made name of over 63 bytes or taken by an object that is not this plate's, a frozen plate or one sharing its mesh, and a report over 16000 characters. Reports plates [{name, rebuilt, corners, facets, panels, bolts, anchors (the empties' names)}], host and side.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
"fields": [
{
"name": "host",
"type": "string",
"minLength": 0,
"maxLength": 63,
"default": "",
"doc": "the object every plate is parented to; empty: no parent"
},
{
"name": "frame",
"type": "string",
"minLength": 0,
"maxLength": 1000,
"default": "",
"doc": "the table's frame in the world, a JSON array of 4 rows of 4 numbers, rigid; empty: the host's world matrix, or the world with no host"
},
{
"name": "side",
"type": "integer",
"minimum": -1,
"maximum": 1,
"default": 1,
"doc": "1, or -1 for the table mirrored across its x = 0; 0 is refused"
},
{
"name": "prefix",
"type": "string",
"minLength": 0,
"maxLength": 32,
"chars": "id",
"default": "",
"doc": "written before every plate's name: a-z A-Z 0-9 _ . (the action refuses a '-')"
},
{
"name": "table",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 32000,
"doc": "a brokkr.plates.v0 document, as JSON"
}
]
}
]
}

View file

@ -170,7 +170,7 @@ def _check_slab(slab: Any, path: str) -> dict:
def _check_clad(clad: Any, row: dict, path: str) -> dict:
_object(clad, path, ("mat", "min_area", "lifts", "inset", "gap", "split", "seed"), ("facets", "floor", "bolt_r"))
_object(clad, path, ("mat", "min_area", "lifts", "inset", "gap", "split", "seed"), ("facets", "floor", "bolt_r", "bolt_mat", "bevel"))
out = {"mat": _name(clad["mat"], f"{path}.mat", 63, None)}
facets = clad.get("facets", "outer" if "slab" in row else None)
if facets is None:
@ -217,6 +217,8 @@ def _check_clad(clad: Any, row: dict, path: str) -> dict:
raise PlateError(f"{path}.seed: wants an integer or [right, left]")
out["seed"] = seed
out["bolt_r"] = _number(clad.get("bolt_r", BOLT), f"{path}.bolt_r", 0.001, 1.0)
out["bolt_mat"] = _name(clad.get("bolt_mat", "gunmetal"), f"{path}.bolt_mat", 63, None) # carried, as row bevel is: build draws nothing from these two
out["bevel"] = _number(clad.get("bevel", 0.012), f"{path}.bevel", 0.0, 0.05)
return out

View file

@ -837,9 +837,9 @@ evaluation once for every `ribs` call; iterate planes on the cage before it is c
`brokkr_kitbash/plate.py` owns a hard armour plate's geometry: a convex faceted solid, every facet flat, with
raised detail panels, a bolt inside each panel corner, and the frames of what stands on it. It is numpy and the
standard library, as `core.py` and `route.py` are, and it is a library so far: `plate.check(document)` and
`plate.build(table, side=1)`. No action calls it yet and nothing here makes a Blender object. A plate the concept
draws curved is a shell (Making a shell); the two do not call each other.
standard library, as `core.py` and `route.py` are: `plate.check(document)` and `plate.build(table, side=1)`.
`brokkr_kitbash.plates` (The action, below) writes what `build` returns into the scene and decides none of it. A
plate the concept draws curved is a shell (Making a shell); the two do not call each other.
A plate table is a data document:
@ -937,6 +937,8 @@ first.
| `split` | a facet over this area is cut in two |
| `seed` | an integer, or `[right, left]` on a row with `sides: "both"`. There is no default. One integer on a two-sided row makes a mirrored pair; a pair of seeds draws each side on its own solid, also where the two are equal. |
| `bolt_r` | a bolt's corner radius (default 0.028) |
| `bolt_mat` | the bolts' material, 1 to 63 characters (default `gunmetal`). Carried: `build` draws nothing from it; `brokkr_kitbash.plates` reads it |
| `bevel` | the width of the panels' Bevel, 0 to 0.05 (default 0.012). Carried, as the row's `bevel` is |
One `random.Random(seed)` draws, in facet order. A chosen facet over `split` is cut across its longest edge at a
share drawn from 0.36 to 0.64 of that edge, the two parts `gap` apart; edges within 1e-9 m of the longest tie and
@ -1005,6 +1007,49 @@ pinned from Starfire (Windows 11, numpy 2.5.4) and Yggdrasil (Debian 13, numpy 2
two hosts' coordinates differ by up to 2.7e-15 m, so the bytes of `build`'s arrays are equal between runs on one
host and not between hosts.
### The action
`brokkr_kitbash.plates` writes a table into the scene. It is the one writer of a hard plate's objects.
| field | value |
| --- | --- |
| `table` | the `brokkr.plates.v0` document as JSON, 1 to 32000 characters |
| `host` | the object every plate is parented to, 0 to 63 characters; empty: no parent |
| `frame` | the table's frame in the world, a JSON array of 4 rows of 4 numbers, at most 1000 characters; empty: the host's world matrix, or the world with no host |
| `side` | 1, or -1 for the table mirrored across its x = 0 |
| `prefix` | written before every plate's name: 0 to 32 of a-z A-Z 0-9 _ . |
Per built entry, N = `prefix` + its name:
- A mesh object N: `build`'s solid in the table frame (`mesh.from_pydata`, every face flat), material `mat`. Its
parent is `host` under an identity parent inverse and its `matrix_basis` is host world^-1 x `frame`; with no
host its world matrix is `frame`. A Kit Bevel of the row's `bevel`, angle 12 degrees. ID properties
`plate_kind` = `"hard"` and `kit_plate`: the checked row with `side` and `prefix`, as JSON. `kit_plate` is a
record: its presence admits a rebuild and nothing reads it to decide geometry.
- `N.fit.<clad mat>` holds the panels and `N.fit.<clad bolt_mat>` the bolts: a child mesh per material (one
child when the two are the same material), identity basis, made only when its mesh is not empty. A child that
holds panels carries a Kit Bevel of `clad.bevel`, angle 20 degrees, one segment.
- One empty per anchor, a child of N at the anchor's matrix: `N.mark.<id>` with `kit_anchor`
`{kind, id, height}`, `N.port.<name>` with `kit_anchor` `{kind, name}` (JSON). A port empty is an end
`brokkr_kitbash.hose` takes by name: the hose leaves along its z, out of the face.
An object named N that carries `kit_plate` is rebuilt in place: its mesh is cleared and rewritten, each
`N.fit.<mat>` child rewritten, made or removed as it is now empty or not, anchors kept by name and moved, and one
the row no longer names removed. N keeps its identity, its other children, its later material slots and its
modifiers. A frozen plate or one sharing its mesh is refused, as `shell` refuses. A plate is no kit part:
`joints` and `report` never list it, and a roll of its host carries it by Blender's parenting. The action
evaluates nothing.
It refuses before anything is written, object count and names unchanged: a table `check` or `build` refuses (the
path in the message); a material `bpy.data.materials` lacks, named with its path (`mat`, `clad.mat`,
`clad.bolt_mat`); a host not found, or scaled, mirrored or sheared; a `frame` that is not a JSON 4x4 of finite
numbers or not rigid; N, a child's or an anchor's name taken by an object that is not this plate's (N without
`kit_plate`, or an object that is not N's child); a name made twice in one call; a made name over 63 bytes; a
host that is one of the call's plates or stands under one; a report over 16000 characters.
The report: `{plates: [{name, rebuilt, corners, facets, panels, bolts, anchors}], host, side}`, `anchors` the
empties' names.
## Hoses between sockets
`brokkr_kitbash.hose` routes a bundle of hoses from one socket to another around everything in the scene:
@ -1449,6 +1494,7 @@ under such load (five runs), and reading a 336-face part takes 27 to 37 ms.
| `brokkr_kitbash.ribs` | `object_name` (the cage), `ribs_name`, `planes` (a JSON array of 1 to 64 `{origin, normal}`, up to 16000 characters), `standoff`, `depth`, `thickness`, `step`, `holes`, `posts`, `post_r`, `bridge`, `clearance`, `longerons` (a JSON array of 0 to 16 `{origin, axis, toward}`, up to 8000 characters), `longeron`, `longeron_w`, `longeron_h`, `longeron_t` | Derives ribs, lightening holes, posts and longerons from the cage as it is cut, as one mesh object under it. Refuses before it writes anything, naming the plane or longeron. Reports `object`, `ribs`, `thickness`, `sections: [{plane, chains, pieces, length, open}]`, `posts`, `holes`, `longerons: [{index, stations}]` (trimmed to a receipt, with `longeronsOmitted`), `faces`, `volume` and `nonManifoldEdges`. |
| `brokkr_kitbash.shell` | `object_name`, `sheet` (a JSON object `{rings, closed, mirror, creases, rim, flip}`, up to 32000 characters), `thickness`, `offset`, `levels`, `bevel`, `count_folds` | Makes a faceted, hollow armor shell from a loft of rings with crease runs, or rebuilds a shell's cage in place under its cutters and ribs. Refuses before it writes anything, naming the field and index. Reports `object`, `rebuilt`, `rings`, `points`, `cageFaces`, `creases`, `folded` (with `count_folds`, the number of the evaluated wall's inner faces that fold; else null), `corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`. |
| `brokkr_kitbash.hose` | `object_name`, `start`, `end`, `count`, `radius`, `spread`, `clearance`, `bend`, `step`, `sag`, `clamps` (a JSON array of up to 8 `{socket}`), `joint` (empty, or a JSON object `{socket, standoff}`) | Routes a bundle of hoses between two sockets around every other mesh, over clamps and through a pin's axis across its roll range; on a hose's name, rebuilds it in place. Reports `length`, `lengthChange`, `clearance`, `radii`, `sag`, `voxels`, `seed`, `rolls`, `worstRoll`, `faces`, `nonManifoldEdges`. |
| `brokkr_kitbash.plates` | `table` (a `brokkr.plates.v0` document, JSON), `host`, `frame` (empty, or a JSON 4x4 of rows), `side`, `prefix` | Writes hard plates: each a mesh on its host with `<plate>.fit.<material>` children for panels and bolts and an empty per anchor; a plate it made is rebuilt in place. Reports `plates` (`name`, `rebuilt`, `corners`, `facets`, `panels`, `bolts`, `anchors`), `host`, `side`. |
`params` is `name=value; name=value`; a param left out takes the part's default (`place_part`) or keeps its stored
value (`set_params`). A value outside its bounds is refused with the bounds in the message.

View file

@ -0,0 +1,440 @@
"""Live proof, in a background Blender, of brokkr_kitbash.plates through run_intent: a plate table written onto a
mechanical-kit link under a pin, each plate's mesh, fit children and anchor empties against plate.build's own answer
under the frame, the Kit Bevels, joints unchanged by the plates, a roll of the pin carrying every plate, a hose between
two port empties either side of the pin across its range, a rebuild in place, and each refusal leaving the scene as it
was. Not part of the unittest run: it needs Blender.
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_plates.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.
Bounds follow lodur:ruling:deterministic-bound-margin: each sits at the geometric mean of the shipped worst reading
and the least claimed mutant's, both written beside it; the result file carries the readings.
The checks run inside one try: an uncaught error is a failed check that names the section it happened in, and the
result file is written and the checks printed whatever happened.
"""
import copy
import importlib
import json
import math
import os
import sys
import tempfile
import traceback
import types
from pathlib import Path
import bpy
import numpy as np
from mathutils import Euler, 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
reference = types.ModuleType("brokkr_kitbash_plates") # plate.py as the unit tests load it: what every reading here is taken against
reference.__path__ = [str(SURFACE / "brokkr_kitbash")]
sys.modules["brokkr_kitbash_plates"] = reference
plate = importlib.import_module("brokkr_kitbash_plates.plate")
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-plates-"))
target.configure_action_dirs("", str(WORK))
target.reload_host_actions()
R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], "readings": {}, "reports": {}}
COUNT, SECTION = [0], ["setup"]
# The mutants of brokkr_kitbash.plates this suite was run against, each failing a check: X1 the frame applied twice (the
# basis host_world @ frame); X2 a rebuild that deletes the plate and makes it again; X3 an anchor left at its plate's
# origin; X4 a plate written with no parent; X5 the host's inverse as the parent inverse; X6 a kept anchor not moved; X7
# the plate's Kit Bevel at shell's 30 degrees; X8 the panels' at 12; X9 a fit child parented to the host; X10 an
# anchor's basis under the frame again; X11 stale children kept; X12 no sharp_face written; X13 no material refusal;
# X14 no refusal of a taken child or anchor name.
#
# Metres between a written vertex in the world (the object's matrix_world on its mesh's own coordinates) and the same
# vertex of plate.build's answer under the frame this script holds, over every plate and fit child of the suite; inf
# when a face differs or is smooth. Shipped worst 8.5e-08 (float32 meshes and matrices); least claimed mutant 1.7 (X1);
# the geometric mean, separation 4400 each side.
WRITTEN = 3.8e-4
# Largest entry of an anchor empty's matrix_world minus the frame @ plate.build's anchor matrix. Shipped worst 2.2e-07;
# least claimed mutant 0.041 (X6, on the rebuild that moves a port 0.05 along its face; X3 reads 1.5, X10 1.4);
# separation 430 each side.
ANCHORED = 9.5e-5
# Largest entry of matrix_world after a roll of the pin minus (the shin's own motion @ matrix_world before), over
# every plate, fit child and anchor on the shin. Shipped worst 1.0e-07; least claimed mutant 0.23 (X4: the plate stays
# where it stood); separation 1500 each side.
CARRIED = 1.5e-4
# Largest entry of a kept anchor's basis after a rebuild minus plate.build's matrix for the rebuilt row. Shipped worst
# 2.1e-07; least claimed mutant 0.049 (X6); separation 480 each side.
MOVED = 1.0e-4
# Metres along a port's z between the port, as plate.build places it on the panel's top, and the nearest hose vertex
# within 1.5 hose radii of it; 1 when no vertex stands that near, or no hose was made. Shipped worst 3.9e-08; least
# claimed mutant 1 (X10: the hose is routed from where the empty stands, off the plate; under X1, X3 and X4 hose
# refuses); separation 5000 each side.
PORTED = 2.0e-4
RADIUS, CLEARANCE = 0.006, 0.005
def check(name, ok, detail=None):
R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail}) # what was seen, when it was not what was promised
def reading(name, value):
R["readings"][name] = max(R["readings"].get(name, 0.0), float(value))
return float(value)
def section(name):
SECTION[0] = name
print("SECTION", name, flush=True)
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
print("SEND", action, receipt["status"], str(receipt["message"])[:400], flush=True)
return receipt, result
def scene_state():
return {o.name: (o.parent and o.parent.name, o.type, o.session_uid, np.round(np.array(o.matrix_basis), 6).tolist(), np.round(np.array(o.matrix_parent_inverse), 6).tolist(),
{k: repr(o[k]) for k in sorted(o.keys())}, [(m.name, m.type, m.show_viewport) for m in o.modifiers],
o.data.name if o.type == "MESH" else None, len(o.data.polygons) if o.type == "MESH" else None,
[s.material and s.material.name for s in o.material_slots],
np.round(points(o)[:8], 6).tolist() if o.type == "MESH" else None)
for o in bpy.data.objects}, sorted(m.name for m in bpy.data.meshes), sorted(c.name for c in bpy.data.collections)
def refused(label, fields, expected):
state = scene_state()
receipt, _ = send("brokkr_kitbash.plates", **fields)
check(f"refused, scene unchanged: {label}", receipt["status"] != "accepted" and expected in str(receipt["message"]) and scene_state() == state,
[receipt["status"], receipt["message"]])
def place(name, part, params=""):
send("brokkr_kitbash.place_part", part=part, object_name=name, params=params)
return bpy.data.objects[name]
def points(obj):
out = np.zeros(3 * len(obj.data.vertices))
obj.data.vertices.foreach_get("co", out)
return out.reshape(-1, 3)
def world(obj):
return np.array(obj.matrix_world, dtype=np.float64)
def under(matrix, V):
return np.asarray(V) @ matrix[:3, :3].T + matrix[:3, 3]
def joined(parts):
"""Meshes (V, faces) as one: the vertices in order, and each face's vertex indices."""
offsets = np.cumsum([0] + [len(V) for V, _ in parts[:-1]])
return np.vstack([V for V, _ in parts]), [[int(k + offset) for k in face] for (_, faces), offset in zip(parts, offsets) for face in faces]
def written(obj, frame, parts):
"""How far the object's mesh stands, in the world, from the meshes (V, faces) under frame; inf when the vertex
count, a face or a smooth face differs."""
V, faces = joined(parts)
if len(obj.data.vertices) != len(V) or [list(p.vertices) for p in obj.data.polygons] != faces or any(p.use_smooth for p in obj.data.polygons):
return math.inf
return float(np.abs(under(world(obj), points(obj)) - under(frame, V)).max())
def off(V, port):
"""Metres along a port's z between the port and the nearest of the vertices within 1.5 hose radii of it; 1 when
none stands that near."""
near = V[np.linalg.norm(V - port[:3, 3], axis=1) < 1.5 * RADIUS]
return abs(float(((near - port[:3, 3]) @ port[:3, 2]).min())) if len(near) else 1.0
def bevel(obj):
modifier = obj.modifiers.get("Kit Bevel")
return None if modifier is None else (round(modifier.width, 6), round(math.degrees(modifier.angle_limit), 4), modifier.segments, modifier.limit_method)
def fits_of(entry, row):
"""{material: [meshes]} of what a built entry's fit children hold, panels before bolts."""
held = {}
if row["clad"]:
for material, mesh in ((row["clad"]["mat"], entry["panels"]), (row["clad"]["bolt_mat"], entry["bolts"])):
if len(mesh[1]):
held.setdefault(material, []).append(mesh)
return held
def proven(label, document, side, prefix, host, frame, report):
"""Every object one accepted call wrote, against plate.build of the same document: the plates' meshes, parents,
bases, bevels and properties, each fit child, each anchor empty, and the report's rows."""
table = plate.check(document)
built = plate.build(table, side)
host_world = world(host) if host else np.eye(4)
ok, detail, rows = True, [], []
for entry in built:
row, name = table["plates"][entry["row"]], prefix + entry["name"]
obj = bpy.data.objects.get(name)
if obj is None or obj.type != "MESH":
ok, detail = False, detail + [f"{name}: not made"]
continue
apart = reading("written", written(obj, frame, [entry["solid"]]))
basis = np.abs(np.array(obj.matrix_basis) - np.linalg.inv(host_world) @ frame).max()
facts = {"apart": apart < WRITTEN, "parent": obj.parent == host, "inverse": np.array_equal(np.array(obj.matrix_parent_inverse), np.eye(4)), "basis": basis < WRITTEN,
"bevel": bevel(obj) == ((round(row["bevel"], 6), 12.0, 2, "ANGLE") if row["bevel"] > 0 else None), "kind": obj.get("plate_kind") == "hard",
"record": json.loads(obj.get("kit_plate", "null")) == {**row, "side": entry["side"], "prefix": prefix},
"material": obj.material_slots[0].material.name == row["mat"], "noPart": "kit_part" not in obj}
held = fits_of(entry, row)
children = sorted(child.name for child in obj.children if child.type == "MESH")
facts["children"] = children == sorted(f"{name}.fit.{material}" for material in held)
for material, parts in held.items():
child = bpy.data.objects.get(f"{name}.fit.{material}")
if child is None or child.parent != obj:
facts[f"fit {material}"] = False
continue
panels = material == row["clad"]["mat"]
facts[f"fit {material}"] = (reading("written", written(child, frame, parts)) < WRITTEN and np.array_equal(np.array(child.matrix_basis), np.eye(4))
and np.array_equal(np.array(child.matrix_parent_inverse), np.eye(4)) and [s.material.name for s in child.material_slots] == [material]
and bevel(child) == ((round(row["clad"]["bevel"], 6), 20.0, 1, "ANGLE") if panels and row["clad"]["bevel"] > 0 else None))
empties = sorted(child.name for child in obj.children if child.type == "EMPTY" and "kit_anchor" in child)
names = []
for anchor in entry["anchors"]:
mark = anchor["kind"] == "mark"
names.append(f"{name}.{'mark' if mark else 'port'}.{anchor['name']}")
empty = bpy.data.objects.get(names[-1])
if empty is None or empty.parent != obj or empty.type != "EMPTY":
facts[names[-1]] = False
continue
record = {"kind": "mark", "id": anchor["name"], "height": anchor["height"]} if mark else {"kind": "hose_port", "name": anchor["name"]}
facts[names[-1]] = (reading("anchored", np.abs(world(empty) - frame @ np.array(anchor["matrix"])).max()) < ANCHORED and json.loads(empty.get("kit_anchor", "null")) == record
and np.array_equal(np.array(empty.matrix_parent_inverse), np.eye(4)))
facts["anchors"] = empties == sorted(names)
rows.append({"name": name, **entry["report"], "anchors": names})
if not all(facts.values()):
ok, detail = False, detail + [f"{name}: {[k for k, v in facts.items() if not v]}"]
reported = report and [{k: v for k, v in row.items() if k != "rebuilt"} for row in report["plates"]]
check(f"written-is-built: {label}", ok and reported == rows and report["host"] == (host.name if host else None) and report["side"] == side, detail or [reported, rows])
return table, built
try:
section("knee")
for name in ("khaki", "olive_light", "gunmetal", "steel"):
bpy.data.materials.new(name)
STRUT = "length=0.8;width=0.08;thickness=0.05"
thigh = place("Thigh", "strut", STRUT)
send("setObjectTransform", targetObjectName="Thigh", location=[0.3, -0.2, 0.1], rotationEuler=[0.2, -0.3, 0.5]) # no frame here is the identity
shin = place("Shin", "strut", STRUT)
send("brokkr_kitbash.attach", object_name="Shin", socket="end_a", parent_name="Thigh", parent_socket="end_b_back", roll=0.0)
send("brokkr_kitbash.joint", object_name="Shin", record=json.dumps({"limits": [-20, 20]}))
bpy.context.view_layer.update()
_, joints_before = send("brokkr_kitbash.joints", object_name="Thigh")
count = len(bpy.data.objects)
def slab(name, at, port, more=None):
"""A plate facing the link's -y, 0.3 by 0.5, with one panel, a hose port on it and a numeral under it."""
return {"name": name, "mat": "khaki", "bevel": 0.006,
"slab": {"at": at, "normal": [0, -1, 0], "up": [0, 0, 1], "outline": {"w": 0.3, "h": 0.5, "clip": 0.04}, "thick": 0.04},
"clad": {"mat": "olive_light", "min_area": 0.01, "lifts": [0.01, 0.015], "inset": 0.03, "gap": 0.02, "split": 99.0, "seed": 7, "bolt_r": 0.008, **(more or {})},
"fits": [{"kind": "hose_port", "name": port[0], "at": port[1]}, {"kind": "mark", "id": "num", "at": [0.0, -0.15], "height": 0.08}]}
def doc(*rows):
return {"schema": "brokkr.plates.v0", "plates": [copy.deepcopy(r) for r in rows]}
THIGH = doc(slab("Guard", [0.0, -0.12, 0.35], ("feed", [0.0, 0.1])))
SHIN = doc(slab("Guard", [0.0, -0.115, 0.45], ("return", [0.0, -0.1]), {"bevel": 0.009}))
section("on the links")
receipt, report = send("brokkr_kitbash.plates", host="Thigh", prefix="Thigh.", table=json.dumps(THIGH))
check("plates on the thigh are accepted and none is a rebuild", receipt["status"] == "accepted" and [row["rebuilt"] for row in report["plates"]] == [False], [receipt["status"], receipt["message"]])
R["reports"]["thigh"] = report
bpy.context.view_layer.update()
proven("a plate on the thigh, the frame the host's", THIGH, 1, "Thigh.", thigh, world(thigh), report)
receipt, report = send("brokkr_kitbash.plates", host="Shin", prefix="Shin.", table=json.dumps(SHIN))
bpy.context.view_layer.update()
shin_table, shin_built = proven("a plate on the shin, under the pin", SHIN, 1, "Shin.", shin, world(shin), report)
guard = bpy.data.objects["Thigh.Guard"]
check("a plate with a panel and its bolts has two fit children and two anchors, and the panel's child alone a bevel",
sorted(c.name for c in guard.children) == ["Thigh.Guard.fit.gunmetal", "Thigh.Guard.fit.olive_light", "Thigh.Guard.mark.num", "Thigh.Guard.port.feed"]
and len(bpy.data.objects["Thigh.Guard.fit.gunmetal"].data.polygons) == 8 * 8 and bevel(bpy.data.objects["Shin.Guard.fit.olive_light"]) == (0.009, 20.0, 1, "ANGLE")
and len(bpy.data.objects) == count + 10, [sorted(c.name for c in guard.children), len(bpy.data.objects["Thigh.Guard.fit.gunmetal"].data.polygons), len(bpy.data.objects) - count])
_, joints_after = send("brokkr_kitbash.joints", object_name="Thigh")
check("roll-carries: joints lists the same rows with the plates as without", joints_before is not None and joints_after == joints_before, joints_after)
_, parts = send("brokkr_kitbash.report")
check("a plate is no kit part: report lists the two struts", parts is not None and [row["object"] for row in parts["parts"]] == ["Shin", "Thigh"], parts and [row.get("object") for row in parts["parts"]])
section("a frame of its own")
F = np.array(Matrix.Translation((1.5, 0.4, -0.3)) @ Euler((0.7, 0.2, -1.1)).to_matrix().to_4x4(), dtype=np.float64)
TWO = doc({"name": "Wing", "mat": "khaki", "bevel": 0.004, "sides": "both",
"slab": {"at": [0.4, 0.1, 0.0], "normal": [1, 0.2, 0.1], "outline": [[-0.2, 0.3], [0.2, 0.3], [0.3, 0.0], [0.2, -0.3], [-0.2, -0.3]], "thick": 0.05},
"clad": {"mat": "steel", "bolt_mat": "steel", "min_area": 0.01, "lifts": [0.01, 0.02], "inset": 0.03, "gap": 0.02, "split": 0.1, "seed": [3, 4], "bolt_r": 0.006},
"fits": [{"kind": "hose_port", "name": "p", "at": [0.0, 0.0], "lift": 0.01}]},
{"name": "Lump", "mat": "gunmetal", "points": [[0, 0, 0], [0.2, 0, 0], [0, 0.2, 0], [0, 0, 0.2], [0.15, 0.15, 0.15]]})
for side, prefix in ((1, "F."), (-1, "G.")):
receipt, report = send("brokkr_kitbash.plates", host="Thigh", prefix=prefix, frame=json.dumps(F.tolist()), side=side, table=json.dumps(TWO))
bpy.context.view_layer.update()
check(f"plates under a stated frame are accepted at side {side}", receipt["status"] == "accepted", [receipt["status"], receipt["message"]])
proven(f"a two-sided row and a bare one under a stated frame, side {side}: panels and bolts of one material are one child", TWO, side, prefix, thigh, F, report)
check("a bare plate has no child and no bevel; a two-sided row is two plates",
not bpy.data.objects["F.Lump"].children and bevel(bpy.data.objects["F.Lump"]) is None and all(name in bpy.data.objects for name in ("F.Wing.R", "F.Wing.L", "G.Wing.R", "G.Wing.L")), None)
receipt, report = send("brokkr_kitbash.plates", prefix="Free.", table=json.dumps(TWO))
bpy.context.view_layer.update()
proven("no host and no frame: the table's frame is the world", TWO, 1, "Free.", None, np.eye(4), report)
section("roll")
carried = [o for o in bpy.data.objects if o.name.startswith("Shin.")]
stays = [o for o in bpy.data.objects if o.name.startswith(("Thigh.", "F.", "Free."))]
before = {o.name: world(o) for o in carried + stays + [shin]}
receipt, _ = send("brokkr_kitbash.roll", object_name="Shin", roll=15.0)
bpy.context.view_layer.update()
motion = world(shin) @ np.linalg.inv(before["Shin"])
check("the roll moved the shin", receipt["status"] == "accepted" and np.abs(motion - np.eye(4)).max() > 0.05, receipt["message"])
check("roll-carries: every plate, fit child and anchor on the shin stands at the roll @ where it stood", len(carried) == 5
and reading("carried", max(np.abs(world(o) - motion @ before[o.name]).max() for o in carried)) < CARRIED, R["readings"])
check("what stands on the thigh or on nothing stayed", all(np.array_equal(world(o), before[o.name]) for o in stays), None)
send("brokkr_kitbash.roll", object_name="Shin", roll=0.0)
bpy.context.view_layer.update()
section("hose")
ports = [bpy.data.objects["Thigh.Guard.port.feed"], bpy.data.objects["Shin.Guard.port.return"]]
HOSE = {"object_name": "Feed", "start": ports[0].name, "end": ports[1].name, "radius": RADIUS, "clearance": CLEARANCE, "joint": json.dumps({"socket": "Shin:end_a_back", "standoff": 0.25})}
receipt, report = send("brokkr_kitbash.hose", **HOSE)
R["reports"]["hose"] = report
check("hose-between-ports: a hose routes between the two plates' port empties through the pin point, clear across the pin's range",
receipt["status"] == "accepted" and report["hoses"] == 1 and report["nonManifoldEdges"] == 0 and report["rolls"] >= 9 and report["clearance"] >= CLEARANCE
and report["worstClearance"] >= CLEARANCE, [receipt["status"], receipt["message"], report])
if receipt["status"] == "accepted":
feed = bpy.data.objects["Feed"]
bpy.context.view_layer.update()
V = under(world(feed), points(feed))
expected = [world(shin if index else thigh) @ np.array(next(a for a in plate.build(plate.check(SHIN if index else THIGH))[0]["anchors"] if a["kind"] == "hose_port")["matrix"]) for index in (0, 1)]
check("hose-between-ports: each end stands on its port, as plate.build places it on the panel's top, and leaves along its z",
all(reading("ported", off(V, port)) < PORTED for port in expected) and feed.parent == ports[0], R["readings"])
else:
reading("ported", 1.0)
section("rebuild")
wing = bpy.data.objects["F.Wing.R"]
uid, mesh_uid = wing.session_uid, wing.data.session_uid
foreign = bpy.data.objects.new("Foreign", None)
bpy.context.scene.collection.objects.link(foreign)
foreign.parent = wing
later = wing.modifiers.new("Hers", "TRIANGULATE")
wing.data.materials.append(bpy.data.materials["gunmetal"])
AGAIN = copy.deepcopy(TWO)
AGAIN["plates"][0]["slab"]["thick"] = 0.08
AGAIN["plates"][0]["fits"] = [{"kind": "hose_port", "name": "p", "at": [0.05, 0.0], "lift": 0.01}, {"kind": "mark", "id": "n", "at": [0.0, 0.1], "height": 0.05}]
port_uid = bpy.data.objects["F.Wing.R.port.p"].session_uid
count = len(bpy.data.objects)
receipt, report = send("brokkr_kitbash.plates", host="Thigh", prefix="F.", frame=json.dumps(F.tolist()), table=json.dumps(AGAIN))
bpy.context.view_layer.update()
check("rebuild-in-place: a second call on the same names reports every plate rebuilt", receipt["status"] == "accepted" and [row["rebuilt"] for row in report["plates"]] == [True, True, True],
[receipt["status"], receipt["message"]])
_, again_built = proven("the rebuilt plates are the changed table's", AGAIN, 1, "F.", thigh, F, report)
check("rebuild-in-place: the plate is the object it was, on the mesh it had, with her child, her modifier after the Kit Bevel and her second material slot",
bpy.data.objects["F.Wing.R"].session_uid == uid and wing.data.session_uid == mesh_uid and foreign.parent == wing and [m.name for m in wing.modifiers] == ["Kit Bevel", "Hers"]
and [s.material.name for s in wing.material_slots] == ["khaki", "gunmetal"] and len(bpy.data.objects) == count + 2, [m.name for m in wing.modifiers])
port = bpy.data.objects["F.Wing.R.port.p"]
check("rebuild-in-place: a kept anchor is the empty it was, moved to the row's new place", port.session_uid == port_uid
and reading("moved", np.abs(np.array(port.matrix_basis) - np.array(next(a for a in again_built[0]["anchors"] if a["name"] == "p")["matrix"])).max()) < MOVED, R["readings"])
BARE = copy.deepcopy(AGAIN)
del BARE["plates"][0]["clad"]
BARE["plates"][0]["fits"] = [{"kind": "mark", "id": "n", "at": [0.0, 0.1], "height": 0.05}]
receipt, report = send("brokkr_kitbash.plates", host="Thigh", prefix="F.", frame=json.dumps(F.tolist()), table=json.dumps(BARE))
bpy.context.view_layer.update()
proven("a rebuild without clad removes the fit child, and the anchor the row no longer names", BARE, 1, "F.", thigh, F, report)
check("rebuild-in-place: the dropped child and anchor are gone, her child stays, and no mesh is left behind",
"F.Wing.R.fit.steel" not in bpy.data.objects and "F.Wing.R.port.p" not in bpy.data.objects and foreign.parent == wing and "F.Wing.R.fit.steel" not in bpy.data.meshes
and len(bpy.data.objects) == count + 2 - 4, sorted(o.name for o in bpy.data.objects))
receipt, report = send("brokkr_kitbash.plates", host="Shin", prefix="F.", table=json.dumps(AGAIN))
bpy.context.view_layer.update()
proven("a rebuild onto another host and frame makes the child and anchor again", AGAIN, 1, "F.", shin, world(shin), report)
check("rebuild-in-place: still the same object", bpy.data.objects["F.Wing.R"].session_uid == uid and wing.parent == shin, None)
section("refusals")
ONE = doc({"name": "Lump", "mat": "gunmetal", "points": [[0, 0, 0], [0.2, 0, 0], [0, 0.2, 0], [0, 0, 0.2]]})
CLAD = slab("Guard", [0.0, -0.12, 0.35], ("feed", [0.0, 0.1]))
call = lambda document, **more: {"host": "Thigh", "prefix": "N.", "table": json.dumps(document), **more} # noqa: E731
refused("a table the format refuses, by its path", call(doc({**ONE["plates"][0], "colour": "red"})), "table: plates[0].colour: unknown key")
refused("a row that bounds no solid", call(doc({"name": "Flat", "mat": "gunmetal", "points": [[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0]]})), "table: plates[0]")
refused("a table that is not JSON", call(ONE, table="{"), "table is not JSON")
refused("a row material the file lacks", call(doc({**ONE["plates"][0], "mat": "brass"})), "table.plates[0].mat: no material named 'brass'")
refused("a clad material the file lacks", call(doc({**CLAD, "clad": {**CLAD["clad"], "mat": "brass"}})), "table.plates[0].clad.mat: no material named 'brass'")
refused("a bolt material the file lacks", call(doc({**CLAD, "clad": {**CLAD["clad"], "bolt_mat": "brass"}})), "table.plates[0].clad.bolt_mat: no material named 'brass'")
refused("a second row's missing material, after a first row that would be written", call(doc(ONE["plates"][0], {**ONE["plates"][0], "name": "Other", "mat": "brass"})), "table.plates[1].mat")
refused("a host that is not there", call(ONE, host="Hip"), "host: no object named 'Hip'")
scaled = bpy.data.objects.new("Scaled", None)
bpy.context.scene.collection.objects.link(scaled)
scaled.scale = (1.0, 2.0, 1.0)
bpy.context.view_layer.update()
refused("a host that is scaled", call(ONE, host="Scaled"), "'Scaled' is scaled, mirrored or sheared")
eye = np.eye(4)
refused("a frame that is not JSON", call(ONE, frame="[[1, 0"), "frame is not JSON")
refused("a frame of three rows", call(ONE, frame=json.dumps(eye[:3].tolist())), "frame must be a JSON array of 4 rows of 4 finite numbers")
refused("a frame with a number that is not finite", call(ONE, frame=json.dumps(eye.tolist()).replace("1.0", "NaN", 1)), "frame must be a JSON array of 4 rows of 4 finite numbers")
refused("a frame that scales", call(ONE, frame=json.dumps((eye * [2, 1, 1, 1]).tolist())), "frame is not rigid")
refused("a frame that mirrors", call(ONE, frame=json.dumps((eye * [-1, 1, 1, 1]).tolist())), "frame is not rigid")
refused("a frame whose last row is no frame's", call(ONE, frame=json.dumps((eye + np.outer([0, 0, 0, 1], [0.5, 0, 0, 0])).tolist())), "frame is not rigid")
refused("side 0", call(ONE, side=0), "side must be 1 or -1")
refused("a prefix with a character the names do not take", call(ONE, prefix="a-b"), "prefix 'a-b' must be 0 to 32 characters")
refused("a plate's name taken by an object plates did not make", call(ONE, prefix="", table=json.dumps(doc({**ONE["plates"][0], "name": "Shin"}))), "an object named 'Shin' exists and is no plate")
stray = bpy.data.objects.new("N.Guard.fit.olive_light", bpy.data.meshes.new("stray"))
bpy.context.scene.collection.objects.link(stray)
refused("a fit child's name taken, the plate new", call(doc(CLAD)), "an object named 'N.Guard.fit.olive_light' exists and is not this plate's")
stray.name = "Thigh.Guard.port.spare"
spare = copy.deepcopy(THIGH)
spare["plates"][0]["fits"].append({"kind": "hose_port", "name": "spare", "at": [0.05, 0.0]})
refused("an anchor's name taken by an object that is no child of the plate, on a rebuild", call(spare, prefix="Thigh."), "an object named 'Thigh.Guard.port.spare' exists and is not this plate's")
refused("a row whose name is another row's fit child", call(doc(CLAD, {**ONE["plates"][0], "name": "Guard.fit.gunmetal"})), "the name 'N.Guard.fit.gunmetal' is made twice")
refused("a made name over 63 bytes", call(doc({**CLAD, "name": "G" * 40}), prefix="P" * 20), "bytes, over the 63 an object's name holds")
refused("a host that is the plate", call(THIGH, host="Thigh.Guard", prefix="Thigh."), "a plate is no host of itself")
refused("a host under the plate", call(THIGH, host="Thigh.Guard.port.feed", prefix="Thigh."), "a plate is no host of itself")
many = doc(*[{"name": f"a{index:03d}", "mat": "gunmetal", "points": [[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]]} for index in range(256)])
refused("a report a receipt does not carry", call(many, table=json.dumps(many, separators=(",", ":"))), "over the 16000 a receipt carries")
twin = bpy.data.objects.new("Twin", guard.data)
bpy.context.scene.collection.objects.link(twin)
refused("a plate that shares its mesh", call(THIGH, prefix="Thigh."), "'Thigh.Guard' shares its mesh")
bpy.data.objects.remove(twin)
receipt, _ = send("brokkr_kitbash.freeze", object_name="Thigh.Guard")
refused("a frozen plate", call(THIGH, prefix="Thigh."), "'Thigh.Guard' is frozen")
send("brokkr_kitbash.thaw", object_name="Thigh.Guard")
receipt, report = send("brokkr_kitbash.plates", host="Thigh", prefix="Thigh.", table=json.dumps(THIGH))
bpy.context.view_layer.update()
check("thawed, the plate is rebuilt", receipt["status"] == "accepted" and report["plates"][0]["rebuilt"], [receipt["status"], receipt["message"]])
proven("the thawed plate", THIGH, 1, "Thigh.", thigh, world(thigh), report)
except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, not a missing result file
check(f"no uncaught error in section: {SECTION[0]}", False, traceback.format_exc().splitlines()[-6:])
finally:
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())}
Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8")
for c in R["checks"]:
print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True)
print("READINGS", R["readings"], flush=True)
sys.exit(0 if R["ok"] else 1)

View file

@ -0,0 +1,347 @@
{
"blender": "5.3.0",
"checks": [
{
"name": "plates on the thigh are accepted and none is a rebuild",
"ok": true,
"detail": null
},
{
"name": "written-is-built: a plate on the thigh, the frame the host's",
"ok": true,
"detail": null
},
{
"name": "written-is-built: a plate on the shin, under the pin",
"ok": true,
"detail": null
},
{
"name": "a plate with a panel and its bolts has two fit children and two anchors, and the panel's child alone a bevel",
"ok": true,
"detail": null
},
{
"name": "roll-carries: joints lists the same rows with the plates as without",
"ok": true,
"detail": null
},
{
"name": "a plate is no kit part: report lists the two struts",
"ok": true,
"detail": null
},
{
"name": "plates under a stated frame are accepted at side 1",
"ok": true,
"detail": null
},
{
"name": "written-is-built: a two-sided row and a bare one under a stated frame, side 1: panels and bolts of one material are one child",
"ok": true,
"detail": null
},
{
"name": "plates under a stated frame are accepted at side -1",
"ok": true,
"detail": null
},
{
"name": "written-is-built: a two-sided row and a bare one under a stated frame, side -1: panels and bolts of one material are one child",
"ok": true,
"detail": null
},
{
"name": "a bare plate has no child and no bevel; a two-sided row is two plates",
"ok": true,
"detail": null
},
{
"name": "written-is-built: no host and no frame: the table's frame is the world",
"ok": true,
"detail": null
},
{
"name": "the roll moved the shin",
"ok": true,
"detail": null
},
{
"name": "roll-carries: every plate, fit child and anchor on the shin stands at the roll @ where it stood",
"ok": true,
"detail": null
},
{
"name": "what stands on the thigh or on nothing stayed",
"ok": true,
"detail": null
},
{
"name": "hose-between-ports: a hose routes between the two plates' port empties through the pin point, clear across the pin's range",
"ok": true,
"detail": null
},
{
"name": "hose-between-ports: each end stands on its port, as plate.build places it on the panel's top, and leaves along its z",
"ok": true,
"detail": null
},
{
"name": "rebuild-in-place: a second call on the same names reports every plate rebuilt",
"ok": true,
"detail": null
},
{
"name": "written-is-built: the rebuilt plates are the changed table's",
"ok": true,
"detail": null
},
{
"name": "rebuild-in-place: the plate is the object it was, on the mesh it had, with her child, her modifier after the Kit Bevel and her second material slot",
"ok": true,
"detail": null
},
{
"name": "rebuild-in-place: a kept anchor is the empty it was, moved to the row's new place",
"ok": true,
"detail": null
},
{
"name": "written-is-built: a rebuild without clad removes the fit child, and the anchor the row no longer names",
"ok": true,
"detail": null
},
{
"name": "rebuild-in-place: the dropped child and anchor are gone, her child stays, and no mesh is left behind",
"ok": true,
"detail": null
},
{
"name": "written-is-built: a rebuild onto another host and frame makes the child and anchor again",
"ok": true,
"detail": null
},
{
"name": "rebuild-in-place: still the same object",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a table the format refuses, by its path",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a row that bounds no solid",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a table that is not JSON",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a row material the file lacks",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a clad material the file lacks",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a bolt material the file lacks",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a second row's missing material, after a first row that would be written",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a host that is not there",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a host that is scaled",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a frame that is not JSON",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a frame of three rows",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a frame with a number that is not finite",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a frame that scales",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a frame that mirrors",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a frame whose last row is no frame's",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: side 0",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a prefix with a character the names do not take",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a plate's name taken by an object plates did not make",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a fit child's name taken, the plate new",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: an anchor's name taken by an object that is no child of the plate, on a rebuild",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a row whose name is another row's fit child",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a made name over 63 bytes",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a host that is the plate",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a host under the plate",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a report a receipt does not carry",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a plate that shares its mesh",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a frozen plate",
"ok": true,
"detail": null
},
{
"name": "thawed, the plate is rebuilt",
"ok": true,
"detail": null
},
{
"name": "written-is-built: the thawed plate",
"ok": true,
"detail": null
}
],
"hostErrors": [],
"readings": {
"anchored": 2.2e-07,
"carried": 1e-07,
"moved": 2.1e-07,
"ported": 3.9e-08,
"written": 8.5e-08
},
"reports": {
"thigh": {
"plates": [
{
"name": "Thigh.Guard",
"rebuilt": false,
"corners": 16,
"facets": 10,
"panels": 1,
"bolts": 8,
"anchors": [
"Thigh.Guard.port.feed",
"Thigh.Guard.mark.num"
]
}
],
"host": "Thigh",
"side": 1
},
"hose": {
"object": "Feed",
"rebuilt": false,
"hoses": 1,
"length": 0.834382,
"lengthChange": 0.002158,
"floor": 0.048,
"clearance": 0.042341,
"capped": 0.121,
"voxels": [
42560,
36456
],
"seed": {
"step": 0.02,
"offset": [
0.0,
0.0,
0.0
],
"refined": false
},
"sag": [
0.007788,
0.003557
],
"rolls": 9,
"worstRoll": -20.0,
"worstClearance": 0.043363,
"faces": 1078,
"volume": 0.000105174,
"nonManifoldEdges": 0,
"radii": {
"least": 0.056641,
"corners": [
0.071927,
1.931459,
0.258593,
3.432944,
0.056641
]
}
}
},
"ok": true
}

View file

@ -2000,7 +2000,7 @@ ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbas
"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.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.shell", "brokkr_kitbash.hose", "brokkr_kitbash.plates"]
class CageTests(unittest.TestCase):
@ -2208,7 +2208,14 @@ class HostFileTests(unittest.TestCase):
self.assertEqual([(row["name"], field["name"], field["default"]) for row in self.document["actions"] for field in row["fields"] if field["type"] == "boolean"],
[("brokkr_kitbash.shell", "count_folds", False)]) # the one evaluation shell makes is asked for, never the default
self.assertEqual([(row["name"], field["name"]) for row in self.document["actions"] for field in row["fields"] if field["type"] == "integer"],
[("brokkr_kitbash.shell", "levels"), ("brokkr_kitbash.hose", "count")])
[("brokkr_kitbash.shell", "levels"), ("brokkr_kitbash.hose", "count"), ("brokkr_kitbash.plates", "side")])
plates = {**envelope, "action": "brokkr_kitbash.plates", "table": '{"schema": "brokkr.plates.v0", "plates": []}'}
self.assertEqual([at.validate(plates, host)[k] for k in ("host", "frame", "side", "prefix")], ["", "", 1, ""])
self.assertEqual(at.validate({**plates, "side": -1, "prefix": "Shin.", "table": "{" + " " * 31999, "frame": "[" + " " * 999}, host)["side"], -1)
for bad in ({**plates, "side": 2}, {**plates, "side": -2}, {**plates, "side": 0.5}, {**plates, "table": "{" + " " * 32000}, {**plates, "table": ""}, {**plates, "frame": "[" + " " * 1000},
{**plates, "prefix": "a b"}, {**plates, "prefix": "p" * 33}, {**plates, "host": "h" * 64}, {k: v for k, v in plates.items() if k != "table"}, {**plates, "object_name": "P"}):
with self.assertRaises(at.IntentInvalid, msg=str(bad)[:200]):
at.validate(bad, host)
sheet = json.dumps({"rings": [[[0, 0, 0], [1, 0, 0]], [[0, 0, 1], [1, 0, 1]]]})
shell = {**envelope, "action": "brokkr_kitbash.shell", "object_name": "Plate", "sheet": sheet}
self.assertEqual([at.validate(shell, host)[k] for k in ("thickness", "offset", "levels", "bevel", "count_folds")], [0.05, -1, 3, 0, False])
@ -2311,9 +2318,9 @@ class OwnershipTests(unittest.TestCase):
self.assertNotIn(call, bodies["thaw"])
for body, first_write in ((place, "bpy.data.meshes.new("), (bodies["boolean"], ".objects.link("), (bodies["freeze"], "bpy.data.meshes.new_from_object("),
(bodies["ribs"], "show_viewport = False"), (bodies["shell"], "clear_geometry()"), (bodies["set_params"], "write_mesh("),
(bodies["hose"], "write_mesh(")):
(bodies["hose"], "write_mesh("), (bodies["plates"], "clear_geometry()")):
self.assertLess(body.index("live("), body.index(first_write))
self.assertEqual(source.count("live("), 8) # its def and the seven callers above
self.assertEqual(source.count("live("), 10) # its def, the seven callers above and plates' two: a plate and a fit child
# the frozen state has one writer: every write of kit_frozen, kit_kept and a fake user is in hold, which swaps the meshes too
hold = source.split("\ndef hold(")[1].split("\n\n\n")[0]
writes = r"\[(?:FROZEN|KEPT)\](?:, obj\.data)? =(?!=)|del \w+\[(?:FROZEN|KEPT)\]|use_fake_user = "

View file

@ -101,8 +101,24 @@ class CheckTests(unittest.TestCase):
slab = table["plates"][0]["slab"]
self.assertEqual((slab["taper"], slab["back"], slab["gap"], slab["up"]), (0.04, 1.0, 0.0, [0.0, 0.0, 1.0]))
self.assertEqual((table["plates"][0]["sides"], table["plates"][0]["mirror"], table["plates"][0]["clad"]["facets"], table["plates"][0]["clad"]["bolt_r"]), ("one", False, "outer", 0.028))
self.assertEqual((table["plates"][0]["clad"]["bolt_mat"], table["plates"][0]["clad"]["bevel"]), ("gunmetal", 0.012))
self.assertEqual(plate.check(table), table)
def test_clad_carries_its_bolt_material_and_panel_bevel(self):
"""Carried and never drawn from: a table that states them builds what one that leaves them out builds."""
stated = plate.check(doc(row(slab=SLAB, clad=dict(CLAD, bolt_mat="steel", bevel=0.009))))
self.assertEqual((stated["plates"][0]["clad"]["bolt_mat"], stated["plates"][0]["clad"]["bevel"]), ("steel", 0.009))
ours, theirs = plate.build(stated)[0], plate.build(doc(row(slab=SLAB, clad=CLAD)))[0]
for key in ("solid", "panels", "bolts"):
self.assertTrue(np.array_equal(ours[key][0], theirs[key][0]) and ours[key][1] == theirs[key][1], key)
for value in (0.0, 0.05):
plate.check(doc(row(slab=SLAB, clad=dict(CLAD, bevel=value))))
plate.check(doc(row(slab=SLAB, clad=dict(CLAD, bolt_mat="m" * 63))))
for bad in (-0.001, 0.0501, "0.01", None, True):
self.refused(doc(row(slab=SLAB, clad=dict(CLAD, bevel=bad))), "plates[0].clad.bevel")
for bad in ("", "m" * 64, 3, None):
self.refused(doc(row(slab=SLAB, clad=dict(CLAD, bolt_mat=bad))), "plates[0].clad.bolt_mat")
def test_schema(self):
self.refused({"schema": "brokkr.plates.v1", "plates": [row()]}, "document.schema")