Compare commits

..
Author SHA1 Message Date
eed171efad Merge pull request 'brokkr_kitbash.shell takes a free cage (verts, tri/quad faces, creases, declared poles, mirror seam); cage export and scorer (cut kit-minimal-cage)' (#40) from nibu/kit-minimal-cage into main 2026-12-03 03:16:01 +00:00
a038e05520 brokkr_reference: pair, lift_pair and the lift helpers deleted; PR 36 lands as flow_score and the honest lens band
Camera-solve honesty, flow_score and hiding margin; lift_pair deleted (ruling lift-pair-held-for-redesign).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 03:12:57 +00:00
Meta Vens
1755ffaada brokkr_kitbash free cage: boundary smoothed as a hand-modelled cage's (Sheet.boundary; All on a free cage, Keep Corners on a loft); the seam relative to extent and read before the side; a pinched vertex refused by its fans; flip and the quad's area pinned
cage_export writes vertices as authored (core.sheet owns the seam) and refuses a Subdivision at Keep Corners.
cage_score: distance each way with area-weighted mean and Hausdorff; crease agreement read off the surfaces'
sharp edges (miss, spur) in place of the cage-tag chamfer; cost = fit + complexity after Hoppe et al. 1994.
Live kitbash_cage: the open-plate round trip with its bound, the cost ranking on a creased box, exact wall
counts, bounds compared as they stand (lodur:ruling:deterministic-bound-margin).
Fix batch h2 for aetheria-release:verdict:cut-kit-minimal-cage.s1.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-03 03:49:11 +01:00
Meta Vens
224eefa57b docs/kitbash.md: A free cage: the form, the mirror seam, the pole gate, triangles, the budget from two hand-modelled cages, and what it gives up
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-03 02:47:00 +01:00
Meta Vens
739cdb1e6b tools/cage_export.py and cage_score.py: a mesh read as a free cage, and two cages scored through shell (counts, limit distance, silhouette IoU, crease chamfer); core.poles; live proof kitbash_cage with its bounds by the margin rule
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-03 02:46:57 +01:00
Meta Vens
d80b164026 brokkr_kitbash.shell: the sheet takes a free cage (verts, faces of 3 or 4 sides, creases, corners, declared poles, mirror seam) beside the loft; core.sheet compiles both to one Sheet; report gains cageVerts, triangles, poles, closed
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-03 02:38:12 +01:00
8690a43c77 Merge pull request 'brokkr_kitbash joint records: DOF from the socket type, limits, slide, the joints report; hose reads its range from the pin (cut kit-joint-records)' (#39) from nibu/kit-joint-records into main 2026-12-02 22:39:26 +00:00
Meta Vens
7bc14ecc82 docs/kitbash.md: joint records, the joints report and what it gives up; a pin's range is its connection's limits; ram_barrel and ram_rod
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 23:04:16 +01:00
Meta Vens
66fd7bb644 live: thirteen parts in kitbash.py; the joint frame bound from its mutant; result files of the four kitbash runs
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 22:57:36 +01:00
Meta Vens
5475a763af live: joint records on the pose scene, the knee's limits before each hose; close and the hose's second reader take the new shapes
kitbash_pose: a rod in its barrel, limits on a pin for roll, aim and reach, the record's refusals,
the joints report under the tank (a toe below a rigid foot reads the hinge as its parent joint),
detach clears the eight keys. kitbash_hose: JOINT drops range; the -20..90 and -10..20 cases are
the knee's limits, 30..60 and -200..200 are the joint action's refusals; a pin without limits and
a hose across a slide are refused.

Fixes two callers the last commit missed: close's mated() tuple and hose.through's crossed().

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 22:57:36 +01:00
Meta Vens
12e73c9dc3 kitbash: joint records on the connection; joint, slide and joints actions; the hose reads its range from the pin's limits
A connection's DOF kind is its parent socket's type's. write_connection, the one writer, states
kit_slide, kit_min, kit_max, kit_mechanism and kit_compliance, refusing before it writes a record
the DOF may not carry and a value with no representative inside the limits. roll, aim and reach
stay inside a revolute joint's limits; slide poses a prismatic one; joint states the record;
joints reports the tree as brokkr.joints v1 rows with axis and order derived. detach clears the
record.

Deleted with it: the hose's joint.range key, its shape check and its current-roll refusal. A
crossed pin is a revolute connection and its range is that connection's limits; a pin without
limits and a slide between the ends are refused.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 22:57:35 +01:00
Meta Vens
ed4d7729eb kits: pivot is revolute; a prismatic slide type; ram_barrel and ram_rod cut from the actuator at its gland
Slide 0 is closed and the slide is the extension: a rod of length body_len + 1.1 body_r in its
barrel stands as the actuator does. JointRecordTests: slide, within, limits on aim and reach, dof
across kits; mutants J1 J2 J3 J4 J6 each die there.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 22:57:09 +01:00
Meta Vens
2439b23af8 kitbash core: a socket type states its dof; mate and residual take a slide; within; aim_roll and reach_roll inside limits
check_kit admits socketTypes[..].dof (revolute | prismatic; absent is rigid). mate is
S_parent @ T(0, 0, slide) @ Rz(roll) @ FLIP @ inv(S_child). within() is the one rule for a value
inside its limits. Two kits mate a type only when match and dof agree.

Cut aetheria-release:cut_spec:cut-kit-joint-records.r1.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 22:57:08 +01:00
2864e9f3fd Merge pull request 'brokkr_kitbash.freeze and thaw: a finished cut object keeps its evaluated mesh and stops paying for every live Boolean; apply is cut (cut kit-freeze)' (#37) from nibu/kit-freeze into main 2026-12-02 21:54:38 +00:00
Meta Vens
7845b13ed0 brokkr_kitbash freeze: one writer of the frozen state, hold; a deleted frozen object releases its live mesh; importGltf drops kit_* extras (cut kit-freeze, fix batch h3)
hold is the only writer of kit_frozen, kit_kept and a held live mesh's fake user, and it swaps the meshes. It settles
every live mesh after each depsgraph update and before each save: held meshes are kept, kit_kept pointing at the frozen
mesh; a mesh no kit_frozen points at is released unless an object still carries the frozen mesh its kit_kept names.
The bridge's kit_owned is the one test for kit_*: setObjectCustomProperty refuses, importGltf drops and reports.
thaw removes the frozen mesh by user_map, names the kept mesh when kit_frozen was lost; a dirty part is refused as
dirty; the export refusal counts show_render as the report does.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 22:34:24 +01:00
Meta Vens
6743e5680b brokkr_kitbash freeze: kit_* refused by the bridge's property setter, the held live mesh kept by a fake user, a dirty frozen part reported and refused at export (cut kit-freeze, fix batch h2)
Answers verdict aetheria-release:verdict:cut-kit-freeze.s1.

- setObjectCustomProperty refuses any name starting with kit_: those properties are brokkr_kitbash's state, so
  kit_frozen keeps freeze and thaw as its only writers.
- freeze gives the held live mesh a fake user (marked kit_kept, taken back by the last thaw), so a purge cannot
  delete it when kit_frozen is overwritten by hand; thaw's refusal then names the kept meshes no frozen object holds.
- part_report: faces is the live mesh's count, frozen or not; a frozen part adds evaluated {faces}; a frozen part
  with a modifier shown again reports dirty (the modifiers) and frozen false. freeze reports faces (live) and
  evaluated {faces, volume, nonManifoldEdges}.
- exportGltf with applyModifiers refuses an export that includes a frozen object with a modifier shown.
- Live pins: kitbash_hose freezes a hose and its rebuild is refused; kitbash_assembly pins the setter refusal, the
  purge with an overwritten kit_frozen, the dirty report and the export refusal.
- kitbash_assembly and kitbash_faceted print their wall times and keep them out of the result files.
- docs/kitbash.md: the KESTREL wall-time ratio as a range (about 2.7 to 5.7), the Boolean evaluation counts
  (1035 against 139) as the stable measure.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 22:13:08 +01:00
Meta Vens
a69bb89374 docs/kitbash.md: freezing, what triggers a live collection Boolean, and what freeze buys on KESTREL (cut kit-freeze)
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 22:13:08 +01:00
Meta Vens
6ea9202555 brokkr_kitbash.freeze and thaw: a cut object carries its evaluated mesh, its live mesh held in kit_frozen, its stack kept and off (cut kit-freeze, 2 of 2)
Blender re-evaluates every live collection Boolean after any datablock removal,
hide or mesh read in the scene. freeze swaps in the evaluated mesh and turns
every modifier off; thaw is its one undo. live() refuses a frozen object in
set_params, boolean, cut, cut_many, ribs, a shell or hose rebuild and freeze.

Live: three cut tanks frozen cost 0.0022 of what they cost live when an orphan
mesh is removed (mutant F1, modifiers left on: 1.5; bound 0.057).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 22:13:08 +01:00
Meta Vens
8767699767 brokkr_kitbash: cut apply and kit_baked (cut kit-freeze, 1 of 2)
apply's class, action row, docs and tests go, with BAKED and report's baked key.
A destructive bake removed the stack and the collections that say what cuts a
part; freeze and thaw replace it in the next commit.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 22:13:07 +01:00
1c399a2c09 Merge pull request 'brokkr_kitbash.ram: a ram and linkage solver across a hinge: direct, four-bar, bell crank (cut kit-ram-core)' (#34) from nibu/kit-ram-core into main 2026-12-02 21:04:27 +00:00
Meta Vens
f1d479b3a1 docs/kitbash.md: Rams and linkages: a zone's bounds, the proof between samples and what it costs, ram.Signed and the ray count's fixture
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 20:59:28 +01:00
Meta Vens
f97beab77e live ram_knee: the package's oracle; the ray count held by the jointlib rocker plates; own plates zoned about both pins; parting zones no wider than the member
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 20:59:27 +01:00
Meta Vens
5726b37692 tests/test_ram: zone bounds in the record, the gate, from_record and a world; a wall of any thickness crossed in a zone; two zones of one pair; a sample at a zone's radius
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 20:59:27 +01:00
Meta Vens
481690fb5c brokkr_kitbash.ram: a zone is no wider or deeper than its member; between samples in a zone the axis is proved, not sampled; the signed mesh oracle
A zone's radius and depth are refused past the member's pin-to-pin length (by the pins alone) and its depth past
the member's eye on that pin (Ram.eye; at the gate and in from_record, so a world's answer too). Between samples
of which either is in a zone the segment is halved until the readings at its ends prove it holds -depth; at the
floor a part the axis is held outside reads as touched. Signed, three rays by majority, moves here from the
live test.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 20:59:27 +01:00
Meta Vens
941e146bc6 docs/kitbash.md: Rams and linkages: zones, the strict record, the live knee's readings and costs
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 20:33:26 +01:00
Meta Vens
bafdb171cd live ram_knee: the R-3 knee on generated meshes under a three-ray signed oracle, zones, moved x, the seated clevis, the search
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 20:33:26 +01:00
Meta Vens
451f1c4ee2 tests/test_ram: zones end at their radius, a pin stood inside what it stands beside, frames, the barrel's back end, the record's wall, a world's answer
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 20:33:26 +01:00
Meta Vens
f3d8a73f2a brokkr_kitbash.ram: touch is zones about a member's pins, each a radius and a depth; a strict record; what a world returns is read as a record
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 20:33:26 +01:00
Meta Vens
2678c09101 docs/kitbash.md: Rams and linkages: parts and touch, the signed oracle, the record, R-3 readings on meshes, costs with their conditions
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 20:33:26 +01:00
Meta Vens
1da1c213fa tests/test_ram: parts and touch on the R-3 knee at the probe's plate stack, inside a part, a candidate's own links, the record's version wall, bounds with their readings
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 20:33:26 +01:00
Meta Vens
780b0dae66 brokkr_kitbash.ram: clearance by parts and what a member may touch; a signed oracle; the barrel derived; a versioned record
The record names parts (part -> body) and touch (member -> parts it may touch): the allowed-collision pairs are
skipped whole and every other member-part pair is checked. The end cuts (e_a, 0.4 e_b, 1.5 link_r) and the
own-body exemption are gone; every body owns a part or the gate refuses. Distances are signed, capped outside
only; nan is refused. search takes world(m) -> (parts, touch, distance), so a candidate's own brackets and
links are its parts; a candidate's eye stands at a's place along the axis. barrel_length derives the barrel;
record holds nothing derived, carries schema, version and a reserved compliance block, and from_record refuses
another version, an unknown key or a compliance block whole. Gate refusals name the angle and the pin.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 20:33:26 +01:00
Meta Vens
048b3b3d7c docs/kitbash.md: Rams and linkages: the model, the three kinds, the gates, the oracle rule, R-3 readings and costs
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 20:33:26 +01:00
Meta Vens
1b12ef9a08 tests/test_ram: hand cases, loop closure, rates, the R-3 deep knee, the third body, the bell crank clear of every body
test_kitbash's package file list admits ram.py, which puts it under the package's negative patterns.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 20:33:26 +01:00
Meta Vens
8686a8cc09 brokkr_kitbash.ram: a ram and linkage solver across a hinge (direct, four_bar, bell_crank)
Every pose quantity is a pure function of the record and the hinge angle; rates are closed form; clearance is a
capped distance oracle met in every body's rest frame (cut kit-ram-core).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 20:33:18 +01:00
5b5657977e Merge pull request 'brokkr_kitbash.hose: hoses routed between sockets, clamped, through a pin's axis across its roll range (cut kit-hose)' (#33) from nibu/kit-hose into main 2026-12-02 19:17:19 +00:00
92f6144196 Merge pull request 'brokkr_reference: a reference view's camera solved from marked points (cut reference-camera)' (#35) from nibu/reference-camera into main 2026-12-02 19:07:56 +00:00
Meta Vens
dcd06e9af8 live kitbash_hose: the steps refused at s2 route, seeds named, a port proven too stiff under a wall; docs: a seed refined, what a refusal claims, the pose-only gap's follow-up (cut kit-hose, h3)
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 19:21:34 +01:00
Meta Vens
edbd04f1ef brokkr_kitbash.hose: a search's polyline is a seed, refined in continuous space; other grid origins and half the step before a refusal; too stiff only where proven (cut kit-hose, h3)
route.tangents gives each corner its floor's tangent before a neighbour gets more, and the pin's corner the
tangent of its sharpest roll (sharpest_turn, exact over a range; passes sizes a bin's bend by it). route.relax
drops, moves and adds a seed's free vertices until every segment has the straight its corners take (strain),
each change proven clear by the oracle. hose searches each leg on three grid origins and then at half the step,
names what it tried when it refuses, and says too stiff only where route.leaves proves no curve of the floor
radius leaves a port.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 19:21:33 +01:00
Meta Vens
d3650ce669 live kitbash_hose: a 1 mm plate between two rolls, the coarsest step, a second bundle at the default step, a straight only verify measures; CLEAR and KEPT by the margin rule; docs (cut kit-hose, h2)
CLEAR 0.017: shipped worst 0.032, mutant H4b (verify refuses nothing) 0.0089. KEPT 0.019: shipped 0.028, C1 0.013.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 18:48:37 +01:00
Meta Vens
b21e745d2e brokkr_kitbash.hose: clearance measured between readings, the roll range swept by bins, legs searched with room for their bends (cut kit-hose, h2)
route.measure replaces sampling at half a voxel: a reading answers for its piece less half the piece's length,
pieces are halved to 1 mm, so no plate stands unseen between two readings and no measurement depends on step.
route.passes measures a range, not a list of rolls: each roll answers for a bin by what a point can move within
it (rho x half width), the bend at the pin has one radius through a bin with its dip added to the need, and a bin
that falls short is halved down to 0.3 degrees. A leg is searched and pulled with 0.29 of the floor beyond need
where a way has it: a line pulled at need grazed what it wrapped and left its corner an accidental room that
changed with step. A corner under the floor says what limits it; a refusal names the sagged and the taut attempt;
another hose through the same pin is an obstacle where it stands and is not measured across the rolls as if rigid.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 18:48:37 +01:00
Meta Vens
336f94de54 docs/kitbash.md: hoses between sockets; kitbash live result with the hose row and the actuator's ports (cut kit-hose)
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 18:48:37 +01:00
Meta Vens
ee45731e00 brokkr_kitbash.hose: a hose bundle routed between two sockets, clamped, through a pin's axis across its roll range (cut kit-hose)
The action is the bpy around route.py: ends and clamps from kit sockets, the crossed pin from the parent chain,
obstacles from every evaluated mesh as two trees split at the pin, one mesh object swept by core.sweep. Each free
span sags a little, bounded by its measured room, and a hose stays one object across a pin (ruling
hose-slack-and-skinned). Row in brokkr_actions.json; tests/live/kitbash_hose.py and its result.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 18:48:37 +01:00
Meta Vens
305efd541f mechanical kit: socket type hose, and port_cap and port_rod on the actuator's port bosses (cut kit-hose)
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 18:48:37 +01:00
Meta Vens
13f60bbff1 brokkr_kitbash/route.py: a hose's path from waypoints and a distance oracle (cut kit-hose)
grid, wavefront, pull and leg search a leg; fillet rounds the polyline by each corner's measured room; sag lowers a
span by half its room (ruling hose-slack-and-skinned); passes turns the child's side through a pin's rolls; frames
are rotation minimising. numpy only; tests/test_route.py.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 18:48:12 +01:00
43 changed files with 10853 additions and 375 deletions

View file

@ -33,7 +33,7 @@
{"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"},
{"name": "parentObjectName", "type": "string", "doc": "empty or absent clears the parent"}
]},
{"name": "setObjectCustomProperty", "doc": "Set one custom property on an object.", "changesScene": true, "editModeSafe": false, "fields": [
{"name": "setObjectCustomProperty", "doc": "Set one custom property on an object. Refuses a name starting with kit_: those are brokkr_kitbash's own state, written by its actions.", "changesScene": true, "editModeSafe": false, "fields": [
{"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"},
{"name": "propertyName", "type": "string", "default": "brokkrValue"},
{"name": "value", "type": "any", "required": true, "doc": "any JSON value Blender accepts as a property"}

View file

@ -46,6 +46,8 @@ DEFAULT_DEBUG_MIRROR_ROOT = "//.brokkr/blender-editor-debug"
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
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"
SYNC_SESSION_SCHEMA = "brokkr.sync.session.v0"
@ -944,6 +946,9 @@ class BrokkrBlenderTarget:
property_name = command["propertyName"]
if property_name.startswith("customProperties."):
property_name = property_name[len("customProperties."):]
if kit_owned(property_name):
raise sa.ActionRefused(f"{property_name!r} is brokkr_kitbash's own state ({KIT_RESERVED}*): its actions write it, and a value set "
"here would leave the object and the property disagreeing. Use the brokkr_kitbash action; nothing changed.")
modifier_name = na.drives_modifier_input(obj, property_name)
if modifier_name:
return self._receipt(command, "failed", f"{property_name!r} is an input of Geometry Nodes modifier {modifier_name!r}; "
@ -1003,7 +1008,19 @@ class BrokkrBlenderTarget:
before = set(self.bpy.data.objects.keys())
self.bpy.ops.import_scene.gltf("EXEC_DEFAULT", False, filepath=str(path))
added = sorted(set(self.bpy.data.objects.keys()) - before)
return self._receipt(command, "accepted", f"Imported {len(added)} object(s) from {path.name}.", added[0] if added else "")
# A file's extras become custom properties, and kit_* is brokkr_kitbash's own state, as setObjectCustomProperty
# has it: an imported kit_frozen would make a frozen object with no live mesh to thaw to.
dropped = []
for name in added:
obj = self.bpy.data.objects[name]
for holder in (obj, obj.data):
for key in [key for key in (holder.keys() if holder is not None else ()) if kit_owned(key)]:
del holder[key]
dropped.append(name)
dropped = sorted(set(dropped))
return self._receipt(command, "accepted", f"Imported {len(added)} object(s) from {path.name}." + (
f" Dropped the file's {KIT_RESERVED}* properties from {', '.join(dropped)}: they are brokkr_kitbash's own state and its actions write them." if dropped else ""),
added[0] if added else "")
def _exportGltf(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
"""Write the scene (or the named objects) as .glb or .gltf under the output directory."""
@ -1027,6 +1044,13 @@ class BrokkrBlenderTarget:
off_layer = [o.name for o in chosen if o.name not in context.view_layer.objects]
if off_layer:
raise sa.ActionRefused(f"Selection object is not in the active view layer: {off_layer[0]}")
if command["applyModifiers"]:
# A frozen object's mesh is already its stack's result: a modifier shown on it again would be applied twice.
dirty = sorted(o.name for o in (chosen or context.view_layer.objects.values())
if o.get(KIT_FROZEN) is not None and any(m.show_viewport or m.show_render for m in o.modifiers))
if dirty:
raise sa.ActionRefused(f"{', '.join(dirty)}: frozen (brokkr_kitbash.freeze) with a modifier shown again, so the export would apply "
"the stack on top of its own result. Thaw it (brokkr_kitbash.thaw), or hide its modifiers in viewports and renders; nothing written.")
# The exporter writes into a fresh staging folder beside the target, never onto the output
# directory: it may also write a .bin and texture files whose names Brokkr does not choose. Only
# after it finishes does every file move into place, each refused if its name is taken, so no
@ -1916,6 +1940,11 @@ def _sync_session(session_id: str, display_name: str, updated_at: str) -> dict[s
}
def kit_owned(property_name: str) -> bool:
"""A custom property brokkr_kitbash owns: no bridge action writes one from outside input."""
return property_name.startswith(KIT_RESERVED)
def _unity_custom_property_path(component_type: str, property_path: str) -> str:
property_path = (property_path or "value").strip()
component_type = (component_type or "").strip()

File diff suppressed because it is too large Load diff

View file

@ -45,7 +45,7 @@
},
{
"name": "brokkr_kitbash.set_params",
"doc": "Change params of a placed kit part and rebuild its mesh in place; modifiers and materials stay, and its connection and the parts attached to it are seated again. Refuses a change that breaks a connection, a baked part, a mesh another object shares and a scaled part. Reports as place_part.",
"doc": "Change params of a placed kit part and rebuild its mesh in place; modifiers and materials stay, and its connection and the parts attached to it are seated again. Refuses a change that breaks a connection, a frozen part, a mesh another object shares and a scaled part. Reports as place_part.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
@ -93,7 +93,7 @@
},
{
"name": "brokkr_kitbash.report",
"doc": "Placed kit parts as the scene has them: kit, part, params, faces, shells, each socket's world 4x4, the connection (parent, sockets, roll, residual, holds) and baked. Evaluates no modifier. Refuses a part scaled in the world: resize with set_params.",
"doc": "Placed kit parts as the scene has them: kit, part, params, faces, shells, each socket's world 4x4, the connection (parent, sockets, roll, residual, holds, and its joint record: dof, slide, limits, mechanism, compliance, within) and frozen. faces counts the live mesh; a frozen part adds evaluated {faces}, and dirty (the modifiers shown again by hand, with frozen false). Evaluates no modifier. Refuses a part scaled in the world: resize with set_params.",
"changesScene": false,
"editModeSafe": true,
"result": "brokkr_mesh_polish_result",
@ -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. 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, 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.",
"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. 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). 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.",
"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. 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. 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. 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.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
@ -308,6 +308,73 @@
}
]
},
{
"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.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
"fields": [
{
"name": "object_name",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 63,
"doc": "a part attached on a revolute or prismatic socket"
},
{
"name": "record",
"type": "string",
"required": true,
"minLength": 2,
"maxLength": 400,
"doc": "a JSON object of any of limits, mechanism, compliance"
}
]
},
{
"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.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
"fields": [
{
"name": "object_name",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 63,
"doc": "a part attached on a prismatic socket"
},
{
"name": "slide",
"type": "number",
"required": true,
"minimum": -10,
"maximum": 10,
"doc": "metres along the parent socket's normal from where the two sockets' origins meet"
}
]
},
{
"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.",
"changesScene": false,
"editModeSafe": true,
"result": "brokkr_mesh_polish_result",
"fields": [
{
"name": "object_name",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 63,
"doc": "the root: a kit part"
}
]
},
{
"name": "brokkr_kitbash.close",
"doc": "Close a loop: state that a socket of a kit part meets a socket of a part of any kit whose socket types agree, where attach cannot (the part already has its parent). Accepted only when the two sockets already meet, origins together and normals opposed, any roll; it moves nothing. Attach the parts with the rolls that make them meet first; brokkr_kitbash.report shows the closure and whether it holds.",
@ -552,8 +619,24 @@
]
},
{
"name": "brokkr_kitbash.apply",
"doc": "Bake a kit part: its mesh becomes its evaluated mesh, every modifier goes, material slots stay, and it is marked baked (set_params then refuses it). Sockets and connections stay. Refuses a part with no modifiers, a mesh another object shares and a part Blender does not evaluate.",
"name": "brokkr_kitbash.freeze",
"doc": "Freeze a mesh object that has modifiers (a kit part, a shell or any mesh) when its cuts are settled: its mesh becomes its evaluated mesh, its live mesh is held by its kit_frozen property, and every modifier stays in the stack, turned off, with its collections and cutters. Blender re-evaluates a live collection Boolean after any removal, hide or mesh read anywhere in the scene; a frozen object costs nothing there. Sockets, connections and report rows stay. set_params, boolean, cut, cut_many, ribs and a shell or hose rebuild refuse a frozen object: thaw it first. Refuses a frozen object, one with no modifiers, one with a modifier already off (named) and one Blender does not evaluate. Reports object (or the part), frozen, faces (the live mesh's), evaluated {faces, volume, nonManifoldEdges}, modifiers and booleans.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
"fields": [
{
"name": "object_name",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 63
}
]
},
{
"name": "brokkr_kitbash.thaw",
"doc": "Thaw a frozen object: its live mesh comes back, every modifier is turned on, and the frozen mesh is removed. Evaluates nothing; Blender evaluates the object once afterwards. Refuses an object that is not frozen or whose held mesh is gone. Reports object, frozen false, modifiers and the live mesh's faces.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
@ -721,7 +804,7 @@
},
{
"name": "brokkr_kitbash.shell",
"doc": "Make a faceted, hollow armor shell: the cage that cut, cut_many and ribs work on. sheet is a JSON object {\"rings\": 2 to 64 rings of 2 to 64 [x, y, z] points with equal counts, in the shell's own frame; \"closed\": each ring joins back to its first point (false); \"mirror\": each ring is authored from its point 0 on x = 0 toward +x and mirrored across x (false; not with closed); \"creases\": [{\"ring\": i, \"from\": a, \"to\": b, \"weight\": w} | {\"column\": j, \"from\": a, \"to\": b, \"weight\": w} | {\"point\": [i, j], \"weight\": w}], runs of ring or column edges and single points, weights 0 to 1, 1 a hard facet edge; \"rim\": the weight of every boundary edge no run names (1); \"flip\": reverse every face (false)}. Quads lie between neighbouring rings; the surface faces out where, seen from outside, a ring's points run left to right and the rings run upward. The cage is subdivided (Kit Subsurf, creases kept) and given a wall (Kit Solidify, rim filled). On an object that is already a shell the cage is rebuilt in place: the object, its cutters, ribs, Booleans and material slots stay, and ribs are stale until run again. A thickness the cage cannot hold is not refused: the wall folds over itself beside a tight crease or rim corner, and a cut there is unsound. count_folds evaluates the wall alone (Kit Subsurf and Kit Solidify, no Boolean; 4 ms on a plate of 1600 subdivided faces) and counts the folded inner faces; nothing else in the report reads an evaluated mesh, and no figure of the cage bounds the fold. Refuses before it writes anything, naming the field and index. Reports object, rebuilt, rings, points, cageFaces, creases, folded (null unless count_folds: then the number of the wall's inner faces that fold over, counted on the evaluated wall; 0 is a wall with no folded face, which an Exact Boolean can still fail on just short of a fold: read nonManifoldEdges after cutting), corners, subdividedFaces, facing, thickness, offset, levels and children.",
"doc": "Make a faceted, hollow armor shell: the cage that cut, cut_many and ribs work on. sheet is a JSON object in one of two forms, a loft of rings or a free cage; exactly one of rings and verts. The loft: {\"rings\": 2 to 64 rings of 2 to 64 [x, y, z] points with equal counts, in the shell's own frame; \"closed\": each ring joins back to its first point (false); \"mirror\": each ring is authored from its point 0 on x = 0 toward +x and mirrored across x (false; not with closed); \"creases\": [{\"ring\": i, \"from\": a, \"to\": b, \"weight\": w} | {\"column\": j, \"from\": a, \"to\": b, \"weight\": w} | {\"point\": [i, j], \"weight\": w}], runs of ring or column edges and single points, weights 0 to 1, 1 a hard facet edge; \"rim\": the weight of every boundary edge no run names (1); \"flip\": reverse every face (false)}. Quads lie between neighbouring rings; the surface faces out where, seen from outside, a ring's points run left to right and the rings run upward. The free cage, for a form a few vertices and creases hold: {\"verts\": 4 to 256 [x, y, z]; \"faces\": each 3 or 4 vertex indices, counter-clockwise seen from outside; \"creases\": [[a, b, w]], an edge by its two vertices, weight 0 to 1; \"corners\": [[vertex, w]]; \"poles\": the vertex indices of irregular valence (not 4 off the boundary, not 2 or 3 on it); \"mirror\": every vertex is authored on one side of x = 0, one within 0.005 of the cage's largest extent of it is on the seam (snapped to x = 0 and shared), the others are reflected with their faces, creases, corners and poles (false); \"rim\" and \"flip\" as on the loft}. The pole gate: poles must equal the poles the faces make, or the sheet is refused naming each undeclared pole and each declared vertex that is none, with its valence. A free cage is also refused for a vertex in no face, a repeated index, a duplicate or collapsed face, an edge in three faces, two faces wound against each other, a pinched vertex (its faces meet only at it), a crease on no edge, and a face or shared edge lying on the mirror plane. A triangle subdivides to three quads. The cage is subdivided (Kit Subsurf, creases kept; a loft's boundary keeps its corners, a free cage's is smoothed through every vertex, Boundary Smooth All, so pin a corner with corners) and given a wall (Kit Solidify, rim filled). On an object that is already a shell the cage is rebuilt in place: the object, its cutters, ribs, Booleans and material slots stay, and ribs are stale until run again. A thickness the cage cannot hold is not refused: the wall folds over itself beside a tight crease or rim corner, and a cut there is unsound. count_folds evaluates the wall alone (Kit Subsurf and Kit Solidify, no Boolean; 4 ms on a plate of 1600 subdivided faces) and counts the folded inner faces; nothing else in the report reads an evaluated mesh, and no figure of the cage bounds the fold. Refuses before it writes anything, naming the field and index. Reports object, rebuilt, rings and points (null on a free cage), cageVerts, cageFaces, triangles, creases, poles ({valence: how many vertices}, on the cage as built), closed (no boundary edge), folded (null unless count_folds: then the number of the wall's inner faces that fold over, counted on the evaluated wall; 0 is a wall with no folded face, which an Exact Boolean can still fail on just short of a fold: read nonManifoldEdges after cutting), corners, subdividedFaces, facing, thickness, offset, levels and children.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
@ -740,7 +823,7 @@
"required": true,
"minLength": 2,
"maxLength": 32000,
"doc": "the shell description, a JSON object: rings, closed, mirror, creases, rim, flip"
"doc": "the shell description, a JSON object: a loft (rings, closed, mirror, creases, rim, flip) or a free cage (verts, faces, creases, corners, poles, mirror, rim, flip)"
},
{
"name": "thickness",
@ -764,7 +847,7 @@
"minimum": 1,
"maximum": 4,
"default": 3,
"doc": "subdivision levels; cage quads times 4 to the levels may not pass 262144"
"doc": "subdivision levels; the subdivided faces (a quad 4 to the levels, a triangle three quarters of that) may not pass 262144"
},
{
"name": "bevel",
@ -781,6 +864,111 @@
"doc": "evaluate the wall (Kit Subsurf and Kit Solidify alone) and report folded, the number of its inner faces that fold over"
}
]
},
{
"name": "brokkr_kitbash.hose",
"doc": "Route a bundle of hoses between two sockets, around every mesh Blender evaluates in the scene. start and end are 'Object:socket' on a kit part (a hose or flange socket no narrower than the bundle) or 'Object' alone, an empty whose z the hose leaves along. A leg runs between each pair of waypoints (a fitting's lead end, each clamp, the pin point): it is searched on a voxel grid of its ends' box plus 0.25 m (at most 524288 voxels), pulled taut with room for its bends where a way has it, and the whole polyline is rounded, each corner by the largest arc its measured room allows. That polyline is a seed: one refused for want of straight between its corners is refined in continuous space (vertices dropped, moved and added, each change proven clear), and before a route is refused the legs are searched again on two more grid origins and at half the step. The refusal then names the steps and origins tried and the first seed's refusal, and says this shows no route was found, not that none exists; it says the bundle is too stiff only where that is proven at a port. The innermost hose's bend radius is at least bend outside diameters, and a fitting keeps a straight of 8 radii (a ferrule, then 1.5 outside diameters). The centre line keeps the bundle's half width plus clearance from every other mesh, other hoses included, outside those leads. sag hangs the middle of each free span by that many outside diameters, never by more than half the room measured along the span; a route the sag breaks is made taut instead (sag in the report reads 0). clamps is a JSON array of up to 8 {\"socket\": \"Object:socket\"}, mount sockets in order along the hose: the bundle runs straight over each, along the socket's y, and gets a pad and a strap. A hose may cross one pin (a revolute connection between its ends' parts, with limits stated by brokkr_kitbash.joint: they are the roll range lo to hi; a pin without limits and a prismatic connection between the ends are refused): joint is then {\"socket\": \"Object:socket\", \"standoff\": metres}, a socket on that pin's axis whose z runs along it; the hose passes through the point standoff beyond it, so each side's straights move with their own part and only the bend at that point changes. The whole range from lo to hi is measured without posing anything, each side against the other side's parts: a roll every 5 degrees answers for the rolls about it by what a point can move within them, and more are measured between where that falls short; another hose through the same pin is kept clear of where it stands, not across the rolls (follow-up aetheria-release:follow_up:hose-motion-clearance-from-skinning owes that check). Every line is measured so that nothing thinner than a spacing can stand between two readings, whatever the step. The hose is one mesh object, a child of the start's object, and a bake of the scene at the call: after a part moves or rolls, run hose again on its name to rebuild it in place. Where it crosses a pin it is meant to be skinned between the bones on either side; no weights are written. Refuses before it writes anything, naming the leg, corner, point or roll. Reports object, rebuilt, hoses, length, lengthChange (over the range, of the centre line as each roll rounds it), floor, clearance (least beyond the bundle, outside the leads; readings stop at capped), voxels per leg, seed {step, offset, refined} (the grid that gave the route, and whether its polyline was refined), sag per leg in metres, rolls (how many were measured), worstRoll, worstClearance (least over the range, each reading less what its point can move within its roll's bin), faces, volume, nonManifoldEdges and radii {least, corners}.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
"fields": [
{
"name": "object_name",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 63,
"doc": "the hose's name: no object's name, or a hose's, which is then rebuilt"
},
{
"name": "start",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 96,
"doc": "'Object:socket' (a hose or flange socket of a kit part), or 'Object' (an empty: the hose leaves along its z)"
},
{
"name": "end",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 96,
"doc": "as start"
},
{
"name": "count",
"type": "integer",
"minimum": 1,
"maximum": 8,
"default": 1,
"doc": "hoses in the bundle, side by side"
},
{
"name": "radius",
"type": "number",
"minimum": 0.003,
"maximum": 0.1,
"default": 0.01,
"doc": "a hose's outside radius"
},
{
"name": "spread",
"type": "number",
"minimum": 0,
"maximum": 0.5,
"default": 0,
"doc": "centre to centre between hoses; 0: 2.6 radii"
},
{
"name": "clearance",
"type": "number",
"minimum": 0,
"maximum": 0.5,
"default": 0.01,
"doc": "free space kept between the bundle and every other mesh"
},
{
"name": "bend",
"type": "number",
"minimum": 1,
"maximum": 20,
"default": 4,
"doc": "least bend radius of the innermost hose, in outside diameters"
},
{
"name": "step",
"type": "number",
"minimum": 0.005,
"maximum": 0.2,
"default": 0.02,
"doc": "voxel size of the search; a way narrower than the bundle plus two voxels is not found"
},
{
"name": "sag",
"type": "number",
"minimum": 0,
"maximum": 8,
"default": 1,
"doc": "how far the middle of each free span hangs, in outside diameters; 0: taut"
},
{
"name": "clamps",
"type": "string",
"minLength": 2,
"maxLength": 4000,
"doc": "a JSON array of 0 to 8 {\"socket\": \"Object:socket\"}, mount sockets in order along the hose",
"default": "[]"
},
{
"name": "joint",
"type": "string",
"minLength": 0,
"maxLength": 4000,
"doc": "empty, or a JSON object {\"socket\": \"Object:socket\", \"standoff\": 0 to 10}: the pin the hose crosses; its roll range is that connection's limits",
"default": ""
}
]
}
]
}

View file

@ -303,10 +303,12 @@ def check_kit(document: Any) -> dict:
for name, entry in document["socketTypes"].items():
where = f"{here} socket type {name!r}"
_name(name, where, set())
_keys(entry, where, ("match", "doc"))
_keys(entry, where, ("match", "doc"), ("dof",))
if entry["match"] not in ("equal", "fits"):
raise KitError(f"{where}: match must be 'equal' or 'fits'")
types[name] = {"match": entry["match"], "doc": _text(entry["doc"], f"{where} doc")}
if "dof" in entry and entry["dof"] not in DOFS:
raise KitError(f"{where}: dof must be 'revolute' or 'prismatic' (a type that states none is rigid)")
types[name] = {"match": entry["match"], "doc": _text(entry["doc"], f"{where} doc"), **({"dof": entry["dof"]} if "dof" in entry else {})}
parts, part_names = {}, set()
for index, part in enumerate(document["parts"]):
name = _name(part.get("name") if isinstance(part, dict) else None, f"{here} part {index}", part_names)
@ -1022,19 +1024,27 @@ def spans(flags, lengths, closed: bool, bridge: float, clearance: float) -> list
return kept
# --- shells: a loft of rings and its creases -------------------------------------------------------------------
# --- shells: a cage (a loft of rings, or free) and its creases --------------------------------------------------
SHEET_LIMIT = 64 # rings in a sheet, and authored points in a ring
SHEET_AREA = 1e-8 # square metres: a cage quad under this is a collapsed corner
MIRROR_EPS = 1e-6 # metres a mirrored ring's point 0 may stand off x = 0, and any of its points behind it
SEAM_REL = 5e-3 # of a mirrored free cage's largest authored extent: a vertex that near x = 0 is on the seam, snapped to 0 and shared
CAGE_VERTS = 256 # authored vertices in a free cage
SHEET_KEYS = ("closed", "mirror", "creases", "rim", "flip")
CAGE_KEYS = ("creases", "corners", "poles", "mirror", "rim", "flip")
class Sheet(NamedTuple):
"""A shell's cage, in the shell's frame, metres: the five fields a mesh is written from (every face a quad,
"""A shell's cage, in the shell's frame, metres: the five fields a mesh is written from (faces of 3 or 4 sides,
shaded smooth, no sharp edge) and what a subdivision surface creases. creases is an (E, 2) array of vertex index
pairs with weights (E,) in (0, 1]; corners (K,) are vertex indices with corner_weights (K,) in (0, 1]. Vertex
i * points + j is ring i's point j, of rings rings of points points (2C - 1 when mirrored)."""
pairs with weights (E,) in (0, 1]; corners (K,) are vertex indices with corner_weights (K,) in (0, 1]. On a loft
vertex i * points + j is ring i's point j, of rings rings of points points (2C - 1 when mirrored); on a free
cage rings and points are None, the authored vertices keep their indices and a mirror's reflections follow them.
poles (P,) are the cage's vertices of irregular valence, as built; triangles is how many faces have 3 sides.
boundary is the Subdivision's Boundary Smooth, by Blender's name: PRESERVE_CORNERS on a loft (a boundary vertex
of two edges stays a corner), ALL on a free cage (the boundary is smoothed through it unless a corner pins it),
which is how a cage modelled by hand is set."""
V: np.ndarray
faces: np.ndarray
counts: np.ndarray
@ -1044,8 +1054,11 @@ class Sheet(NamedTuple):
weights: np.ndarray
corners: np.ndarray
corner_weights: np.ndarray
rings: int
points: int
rings: int | None
points: int | None
poles: np.ndarray
triangles: int
boundary: str
def _index(value: Any, where: str, least: int, most: int) -> int:
@ -1061,7 +1074,8 @@ def _weight(value: Any, where: str) -> float:
def sheet(document: Any) -> Sheet:
"""The cage of a shell description {rings, closed, mirror, creases, rim, flip}.
"""The cage of a shell description, in one of two forms: a loft {rings, closed, mirror, creases, rim, flip}, or
a free cage {verts, faces, creases, corners, poles, mirror, rim, flip} (see _cage). Exactly one of rings, verts.
rings: 2 to 64 rings of 2 to 64 [x, y, z] points, equal counts. Quad (i, j) is P[i][j], P[i][j+1], P[i+1][j+1],
P[i+1][j], so its normal (P[i][j+1] - P[i][j]) x (P[i+1][j] - P[i][j]) faces out: seen from outside, a ring's
@ -1073,6 +1087,11 @@ def sheet(document: Any) -> Sheet:
may be the count: the edge back to point 0); {column, from, to, weight} a column's edges from ring `from` to
ring `to`; {point: [ring, point], weight} one vertex. rim is the weight of every boundary edge no run names.
An edge has one weight: two runs that give it different ones are refused."""
if isinstance(document, dict) and ("rings" in document) == ("verts" in document):
raise KitError("sheet states both rings and verts: a sheet is a loft of rings or a free cage of verts and faces, one of them" if "rings" in document else
"sheet lacks 'rings' and 'verts': a sheet is a loft of rings or a free cage of verts and faces")
if isinstance(document, dict) and "verts" in document:
return _cage(document)
_keys(document, "sheet", ("rings",), SHEET_KEYS)
flags = {}
for key in ("closed", "mirror", "flip"):
@ -1176,7 +1195,210 @@ def sheet(document: Any) -> Sheet:
pinned = sorted((key, weight) for key, (weight, _) in verts.items() if weight > 0)
return Sheet(V=V.copy(), faces=quads.ravel().astype(np.int32), counts=np.full(len(quads), 4, dtype=np.int32), smooth=np.ones(len(quads), dtype=bool),
sharp=NO_SHARP, creases=np.array([key for key, _ in kept], dtype=np.int64).reshape(-1, 2), weights=np.array([w for _, w in kept], dtype=np.float64),
corners=np.array([key for key, _ in pinned], dtype=np.int64), corner_weights=np.array([w for _, w in pinned], dtype=np.float64), rings=R, points=N)
corners=np.array([key for key, _ in pinned], dtype=np.int64), corner_weights=np.array([w for _, w in pinned], dtype=np.float64), rings=R, points=N,
poles=np.zeros(0, dtype=np.int64), triangles=0, boundary="PRESERVE_CORNERS")
def _cage_facts(vertices: int, faces, counts):
"""What a cage's connectivity says: (edges, boundary, valences, poles). edges maps each (low, high) vertex pair
to how many faces use it; boundary lists the pairs one face uses; valences (vertices,) counts each vertex's
edges; poles are the vertices of irregular valence, ascending: not 4 off the boundary, not 2 or 3 on it."""
edges: dict[tuple[int, int], int] = {}
at = 0
for count in counts:
face = [int(v) for v in faces[at:at + count]]
at += count
for a, b in zip(face, face[1:] + face[:1]):
key = (min(a, b), max(a, b))
edges[key] = edges.get(key, 0) + 1
boundary = sorted(key for key, used in edges.items() if used == 1)
valences = np.zeros(vertices, dtype=np.int64)
for a, b in edges:
valences[a] += 1
valences[b] += 1
rim = np.zeros(vertices, dtype=bool)
rim[[v for key in boundary for v in key]] = True
poles = np.flatnonzero(np.where(rim, (valences != 2) & (valences != 3), valences != 4))
return edges, boundary, valences, poles
def cage_report(built: Sheet) -> dict:
"""A cage's counts for a report, either form: cageVerts, cageFaces, triangles, creases, corners, poles (valence
-> how many vertices, the irregular ones only) and closed (no boundary edge)."""
_, boundary, valences, poles = _cage_facts(len(built.V), built.faces, built.counts)
tally: dict[str, int] = {}
for valence in sorted(int(valences[v]) for v in poles):
tally[str(valence)] = tally.get(str(valence), 0) + 1
return {"cageVerts": len(built.V), "cageFaces": len(built.counts), "triangles": built.triangles, "creases": len(built.creases),
"corners": len(built.corners), "poles": tally, "closed": not boundary}
def subdivided_faces(built: Sheet, levels: int) -> int:
"""Faces of the cage after `levels` Catmull-Clark levels (1 or more): a quad gives 4^levels, a triangle three
quads at the first level and so 3 * 4^(levels - 1)."""
return (len(built.counts) - built.triangles) * 4 ** levels + built.triangles * 3 * 4 ** (levels - 1)
def poles(document: Any) -> list[int]:
"""The poles a free cage's faces make, by authored index, ascending: what its sheet.poles must state. For a
reader of a cage someone else modelled (tools/cage_export.py); every other refusal of the free form stands."""
return [int(v) for v in _cage(document, gate=False).poles if v < len(document["verts"])]
def _cage(document: Any, gate: bool = True) -> Sheet:
"""The cage of a free description {verts, faces, creases, corners, poles, mirror, rim, flip}.
verts: 4 to 256 [x, y, z]. faces: 3 or 4 vertex indices each, wound so the normal (counter-clockwise seen from
outside) faces out; flip reverses every face. creases: [a, b, weight], an edge by its two vertices; corners:
[vertex, weight]. rim is the weight of every boundary edge no crease names. The boundary is smoothed through
every vertex (Sheet.boundary ALL): a boundary vertex of two edges is a corner only where corners pins it or its
edges are creased apart. mirror: every vertex is authored on one side of x = 0; one within SEAM_REL of the
authored vertices' largest extent of it is on the seam, snapped to x = 0 and shared; the others are
reflected (vertex len(verts) + k is the k-th of them), each face gets a reversed twin, and creases, corners and
poles land on both halves. poles: the vertices of irregular valence on the cage as built (not 4 off the
boundary, not 2 or 3 on it), by authored index. The list is a gate, not a setting: it must equal what the
faces make, so a pole is never an accident. A vertex's faces are one fan, each joined to the next by an edge at
the vertex: one whose faces meet only at it (a pinched vertex) is refused."""
_keys(document, "sheet", ("verts", "faces"), CAGE_KEYS)
flags = {}
for key in ("mirror", "flip"):
flags[key] = document.get(key, False)
if not isinstance(flags[key], bool):
raise KitError(f"sheet.{key} must be true or false, not {flags[key]!r}")
mirror, flip = flags["mirror"], flags["flip"]
rim = _weight(document.get("rim", 1.0), "sheet.rim")
verts, faces = document["verts"], document["faces"]
if not isinstance(verts, list) or not 4 <= len(verts) <= CAGE_VERTS:
raise KitError(f"sheet.verts must be 4 to {CAGE_VERTS} vertices, not {len(verts) if isinstance(verts, list) else verts!r}")
for i, point in enumerate(verts):
if not isinstance(point, list) or len(point) != 3 or not all(finite(v) for v in point):
raise KitError(f"sheet.verts[{i}] must be three finite numbers [x, y, z]")
A = len(verts)
if not isinstance(faces, list) or not faces:
raise KitError("sheet.faces must be an array of faces, each 3 or 4 vertex indices")
for f, face in enumerate(faces):
if not isinstance(face, list) or len(face) not in (3, 4):
raise KitError(f"sheet.faces[{f}] must be 3 or 4 vertex indices, not {len(face) if isinstance(face, list) else face!r}: a cage's faces are triangles and quads")
for k, v in enumerate(face):
_index(v, f"sheet.faces[{f}][{k}]", 0, A - 1)
if len(set(face)) != len(face):
raise KitError(f"sheet.faces[{f}] names vertex {next(v for v in face if face.count(v) > 1)} twice")
used = {v for face in faces for v in face}
if len(used) != A:
raise KitError(f"sheet.verts[{min(set(range(A)) - used)}] is in no face: every vertex of a cage is used")
V = np.array(verts, dtype=np.float64)
seam = np.zeros(A, dtype=bool)
if mirror:
near = SEAM_REL * float(np.ptp(V, axis=0).max())
seam = np.abs(V[:, 0]) <= near
V[seam, 0] = 0.0 # the seam first: a seam vertex may stand a hair on either side
if (V[:, 0] < 0).any() and (V[:, 0] > 0).any():
side = 1.0 if (V[:, 0] > 0).sum() >= (V[:, 0] < 0).sum() else -1.0
worst = int((V[:, 0] * side).argmin())
raise KitError(f"sheet.verts[{worst}] has x = {V[worst, 0]:.6g}: a mirrored cage is authored on one side of x = 0, and the others stand on the {'+' if side > 0 else '-'}x side")
seen, directed = {}, {}
for f, face in enumerate(faces):
key = tuple(sorted(face))
if key in seen:
raise KitError(f"sheet.faces[{f}] has the vertices of sheet.faces[{seen[key]}]: a duplicate face")
seen[key] = f
if mirror and all(seam[v] for v in face):
raise KitError(f"sheet.faces[{f}] lies on the mirror plane (every vertex within {near:.3g} m of x = 0, {SEAM_REL:g} of the cage's extent): its reflection is itself")
corners = V[face]
area = 0.5 * np.linalg.norm(np.cross(corners[1] - corners[0], corners[-1] - corners[0]))
if len(face) == 4:
area += 0.5 * np.linalg.norm(np.cross(corners[3] - corners[2], corners[1] - corners[2]))
if area < SHEET_AREA:
raise KitError(f"sheet.faces[{f}] has area {area:.3g} m2, under {SHEET_AREA:g}: a collapsed face. Move its vertices apart")
for a, b in zip(face, face[1:] + face[:1]):
directed.setdefault((a, b), []).append(f)
for (a, b), users in sorted(directed.items()):
both = users + directed.get((b, a), [])
if len(both) > 2 and a < b or len(users) > 2:
raise KitError(f"sheet.faces: the edge between vertices {min(a, b)} and {max(a, b)} is in {len(both)} faces ({', '.join(str(f) for f in sorted(both))}): a cage's edge is in at most two")
if len(users) == 2:
raise KitError(f"sheet.faces[{users[1]}] crosses the edge between vertices {a} and {b} the same way as sheet.faces[{users[0]}]: the two are wound against each other. Reverse one")
if mirror and seam[a] and seam[b] and len(both) == 2:
raise KitError(f"sheet.faces[{both[0]}] and sheet.faces[{both[1]}] share the edge between vertices {min(a, b)} and {max(a, b)}, which lies on the mirror plane: "
"with their reflections that edge is in four faces (a fin on the plane)")
twin = np.arange(A)
if mirror:
twin[~seam] = A + np.arange(int((~seam).sum()))
V = np.concatenate([V, V[~seam] * (-1.0, 1.0, 1.0)])
built = [list(face) for face in faces] + [[int(twin[v]) for v in reversed(face)] for face in faces]
else:
built = [list(face) for face in faces]
if flip:
built = [face[::-1] for face in built]
counts = np.array([len(face) for face in built], dtype=np.int32)
flat = np.array([v for face in built for v in face], dtype=np.int32)
cage_edges, boundary, valences, poles = _cage_facts(len(V), flat, counts)
fans: dict[int, list[tuple[set[int], list[int]]]] = {} # each vertex's faces, grouped while they share an edge at it
for f, face in enumerate(built):
for k, v in enumerate(face):
spokes, members, apart = {face[k - 1], face[(k + 1) % len(face)]}, [f], []
for others, theirs in fans.get(v, []):
if others & spokes:
spokes, members = spokes | others, members + theirs
else:
apart.append((others, theirs))
fans[v] = apart + [(spokes, members)]
pinched = min((v for v, parts in fans.items() if len(parts) > 1), default=None)
if pinched is not None:
named = lambda f: str(f) if f < len(faces) else f"{f - len(faces)} mirrored" # noqa: E731
raise KitError(f"sheet.verts[{pinched}] is pinched: its faces meet only at it, in {len(fans[pinched])} fans (faces "
f"{' | '.join(', '.join(named(f) for f in sorted(theirs)) for _, theirs in sorted(fans[pinched], key=lambda part: min(part[1])))}). "
"A vertex's faces are one fan: join them by a face, or give each fan its own vertex")
declared = document.get("poles", []) if gate else [int(v) for v in poles if v < A]
if not isinstance(declared, list):
raise KitError("sheet.poles must be an array of vertex indices")
for k, v in enumerate(declared):
_index(v, f"sheet.poles[{k}]", 0, A - 1)
if v in declared[:k]:
raise KitError(f"sheet.poles[{k}] names vertex {v} twice")
computed = [int(v) for v in poles if v < A]
where = lambda v: f"vertex {v} (valence {int(valences[v])}{', on the boundary' if any(v in key for key in boundary) else ''})" # noqa: E731
undeclared, regular = [v for v in computed if v not in declared], [v for v in declared if v not in computed]
if undeclared:
raise KitError(f"sheet.poles lacks {', '.join(where(v) for v in undeclared)}: a pole is declared or the faces are changed. "
"A vertex is a pole when its valence is not 4 off the boundary, or not 2 or 3 on it")
if regular:
raise KitError(f"sheet.poles[{declared.index(regular[0])}] names {where(regular[0])}, which is no pole; the regular ones named: {', '.join(str(v) for v in regular)}")
def state(table, key, weight, where, what):
if key in table and table[key][0] != weight:
raise KitError(f"{where} gives {what} weight {weight:g} that {table[key][1]} gives {table[key][0]:g}: {what} has one weight")
table.setdefault(key, (weight, where))
edges, pinned = {}, {}
for name, table, size in (("creases", edges, 3), ("corners", pinned, 2)):
runs = document.get(name, [])
if not isinstance(runs, list):
raise KitError(f"sheet.{name} must be an array")
for k, run in enumerate(runs):
where_run = f"sheet.{name}[{k}]"
if not isinstance(run, list) or len(run) != size:
raise KitError(f"{where_run} must be {'[a, b, weight]: an edge by its two vertices' if size == 3 else '[vertex, weight]'}")
ends = [_index(v, f"{where_run}[{i}]", 0, A - 1) for i, v in enumerate(run[:-1])]
weight = _weight(run[-1], f"{where_run}[{size - 1}]")
if size == 2:
for v in {ends[0], int(twin[ends[0]])}:
state(pinned, v, weight, where_run, "a point")
continue
key = (min(ends), max(ends))
if key not in cage_edges:
raise KitError(f"{where_run}: vertices {ends[0]} and {ends[1]} share no face's edge: a crease lies on an edge of the cage")
for a, b in {key, tuple(sorted((int(twin[ends[0]]), int(twin[ends[1]]))))}:
state(edges, (a, b), weight, where_run, "an edge")
for key in boundary:
edges.setdefault(key, (rim, "sheet.rim"))
kept = sorted((key, weight) for key, (weight, _) in edges.items() if weight > 0)
held = sorted((key, weight) for key, (weight, _) in pinned.items() if weight > 0)
return Sheet(V=V, faces=flat, counts=counts, smooth=np.ones(len(counts), dtype=bool), sharp=NO_SHARP,
creases=np.array([key for key, _ in kept], dtype=np.int64).reshape(-1, 2), weights=np.array([w for _, w in kept], dtype=np.float64),
corners=np.array([key for key, _ in held], dtype=np.int64), corner_weights=np.array([w for _, w in held], dtype=np.float64),
rings=None, points=None, poles=poles, triangles=int((counts == 3).sum()), boundary="ALL")
# --- reports -------------------------------------------------------------------------------------------------
@ -1219,19 +1441,44 @@ def surface_frame(point, normal, up, roll_degrees: float = 0.0) -> np.ndarray:
return frame @ _roll(roll_degrees)
def mate(parent_socket: dict, child_socket: dict, roll_degrees: float = 0.0) -> np.ndarray:
"""The child's 4x4 in its parent's frame that seats child_socket on parent_socket: origins together, normals
opposed, the child turned roll_degrees about the parent socket's z (right-handed; at 0 the two ys line up)."""
return parent_socket["matrix"] @ _roll(roll_degrees) @ FLIP @ np.linalg.inv(child_socket["matrix"])
def _slid(metres: float) -> np.ndarray:
move = np.eye(4)
move[2, 3] = metres
return move
def residual(parent_world, parent_socket: dict, child_world, child_socket: dict, roll_degrees: float) -> float:
def mate(parent_socket: dict, child_socket: dict, roll_degrees: float = 0.0, slide: float = 0.0) -> np.ndarray:
"""The child's 4x4 in its parent's frame that seats child_socket on parent_socket: normals opposed, the child
turned roll_degrees about the parent socket's z (right-handed; at 0 the two ys line up) and its socket's origin
`slide` metres along that z from the parent socket's (0: origins together). A turn about z and a move along it
commute, so one connection carries both."""
return parent_socket["matrix"] @ _slid(slide) @ _roll(roll_degrees) @ FLIP @ np.linalg.inv(child_socket["matrix"])
def residual(parent_world, parent_socket: dict, child_world, child_socket: dict, roll_degrees: float, slide: float = 0.0) -> float:
"""How far a child stands from where mate puts it: the largest absolute entry of the difference between the
frame its socket should have in the world and the frame it has."""
wanted = np.asarray(parent_world, dtype=np.float64) @ parent_socket["matrix"] @ _roll(roll_degrees) @ FLIP
wanted = np.asarray(parent_world, dtype=np.float64) @ parent_socket["matrix"] @ _slid(slide) @ _roll(roll_degrees) @ FLIP
return float(np.abs(wanted - np.asarray(child_world, dtype=np.float64) @ child_socket["matrix"]).max())
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
def within(value: float, lo: float, hi: float, revolute: bool) -> float | None:
"""The representative of a joint's value inside its limits [lo, hi], or None when it has none: the value itself
on a prismatic joint; on a revolute one the value itself when it is inside, else value + 360 k, the least at or
above lo. A value within LIMIT_SLACK of an end is that end."""
slack = LIMIT_SLACK * max(1.0, abs(lo), abs(hi))
if revolute and not lo - slack <= value <= hi + slack:
value += 360.0 * math.ceil((lo - slack - value) / 360.0)
return min(max(value, lo), hi) if lo - slack <= value <= hi + slack else None
def roll_terms(parent_world, parent_socket: dict, child_socket: dict, local, w: float, direction) -> tuple[float, float, float]:
"""(A, B, C) with direction . (the child's `local`, in the world) = A cos(roll) + B sin(roll) + C when the child
is mated on parent_socket at that roll. `local` is in the child's own frame: a point with w 1, an axis with w 0.
@ -1263,26 +1510,36 @@ def _wrapped(degrees: float) -> float:
return 180.0 - (180.0 - degrees) % 360.0
def aim_roll(parent_world, parent_socket: dict, child_socket: dict, axis, direction) -> tuple[float, float]:
def aim_roll(parent_world, parent_socket: dict, child_socket: dict, axis, direction, limits=None) -> tuple[float, float]:
"""(roll in degrees in (-180, 180], the dot it achieves) that turns the child's own `axis` as far toward the
world `direction` as its pin lets it: roll = atan2(B, A), dot = C + hypot(A, B), for unit vectors. Refuses an
axis or a direction along the pin (hypot(A, B) at most AIM_FLOOR), which no roll turns."""
axis or a direction along the pin (hypot(A, B) at most AIM_FLOOR), which no roll turns. With `limits` (lo, hi)
the roll is its representative inside them (within); when the free roll has none, the end of the limits whose
dot is the larger (the dot is a sinusoid of the roll: over an interval of at most a turn it peaks at its
optimum or at an end; a tie takes lo), and the dot is that end's."""
direction = np.asarray(direction, dtype=np.float64)
direction = direction / np.linalg.norm(direction)
A, B, C = roll_terms(parent_world, parent_socket, child_socket, axis, 0.0, direction)
if math.hypot(A, B) <= AIM_FLOOR:
raise KitError(f"socket {child_socket['name']!r} on parent socket {parent_socket['name']!r}: the axis {tuple(float(v) for v in axis)} of the part "
f"or the direction {tuple(round(float(v), 6) for v in direction)} lies along the pin, so no roll turns one toward the other")
return _wrapped(math.degrees(math.atan2(B, A))), C + math.hypot(A, B)
roll = _wrapped(math.degrees(math.atan2(B, A)))
if limits is None:
return roll, C + math.hypot(A, B)
inside = within(roll, *limits, True)
if inside is not None:
return inside, C + math.hypot(A, B)
return max(((end, A * math.cos(math.radians(end)) + B * math.sin(math.radians(end)) + C) for end in limits), key=lambda found: found[1])
def reach_roll(parent_world, parent_socket: dict, child_socket: dict, point, direction, height: float, current_roll: float) -> tuple[float, float]:
def reach_roll(parent_world, parent_socket: dict, child_socket: dict, point, direction, height: float, current_roll: float, limits=None) -> tuple[float, float]:
"""(roll in degrees in (-180, 180], residual |direction . p - height| in metres) that brings the child's own
`point` to the plane direction . x = height, for a unit direction: atan2(B, A) +- acos((height - C) / hypot(A, B)),
of the two the one nearer current_roll round the circle (a tie takes the smaller roll). A height up to REACH_EDGE
past the top or bottom of the circle is taken as the top or bottom. Refuses a height farther out, naming the
range the point reaches, and a point no roll moves along the direction (it lies on the pin, or the direction
does)."""
does). With `limits` (lo, hi) only a root with a representative inside them (within) is taken, as that
representative; with none inside it refuses, naming both roots and the limits."""
direction = np.asarray(direction, dtype=np.float64)
direction = direction / np.linalg.norm(direction)
A, B, C = roll_terms(parent_world, parent_socket, child_socket, point, 1.0, direction)
@ -1295,6 +1552,12 @@ def reach_roll(parent_world, parent_socket: dict, child_socket: dict, point, dir
f"it reaches {C - swing:.6f} m to {C + swing:.6f} m")
middle, spread = math.degrees(math.atan2(B, A)), math.degrees(math.acos(max(-1.0, min(1.0, (height - C) / swing))))
roots = sorted({_wrapped(middle - spread), _wrapped(middle + spread)})
if limits is not None:
inside = [found for found in (within(root, *limits, True) for root in roots) if found is not None]
if not inside:
raise KitError(f"{here}: the rolls that bring the point to {height:.6f} m, {' and '.join(f'{root:.6g}' for root in roots)}, are outside "
f"the joint's limits {limits[0]:.6g} to {limits[1]:.6g}")
roots = inside
roll = min(roots, key=lambda root: (round(abs(_wrapped(root - current_roll)), 9), root))
return roll, abs(A * math.cos(math.radians(roll)) + B * math.sin(math.radians(roll)) + C - height)
@ -1316,7 +1579,7 @@ def mate_refusal(kit_types: dict, parent_socket: dict, child_socket: dict, child
agree as that type's match says ('equal': within 1 percent of the larger; 'fits': the child at most the parent).
kit_types is the socketTypes of the parent's kit. For parts of two kits, child_types is the socketTypes of the
child's and `kits` the two kits' names: socket types are a vocabulary kits share, and the two sockets mate only
when the child's kit declares the type with the same match."""
when the child's kit declares the type with the same match and the same dof."""
p, c = parent_socket, child_socket
both = f"socket {c['name']!r} ({c['type']}, size {c['size']:.6g}) and parent socket {p['name']!r} ({p['type']}, size {p['size']:.6g})"
if p["type"] != c["type"]:
@ -1325,6 +1588,10 @@ def mate_refusal(kit_types: dict, parent_socket: dict, child_socket: dict, child
theirs = child_types.get(c["type"], {}).get("match")
return (f"{both}: kit {kits[0]!r} declares socket type {p['type']!r} with match {kit_types[p['type']]['match']!r} and kit {kits[1]!r} "
f"{'with match ' + repr(theirs) if theirs else 'does not declare it'}; parts of two kits mate by socket types both declare alike")
if child_types is not None and child_types[c["type"]].get("dof") != kit_types[p["type"]].get("dof"):
ours, theirs = (types[p["type"]].get("dof", "none (rigid)") for types in (kit_types, child_types))
return (f"{both}: kit {kits[0]!r} declares socket type {p['type']!r} with dof {ours} and kit {kits[1]!r} with dof {theirs}; "
"parts of two kits mate by socket types both declare alike")
if kit_types[p["type"]]["match"] == "equal":
if abs(p["size"] - c["size"]) > EQUAL * max(p["size"], c["size"]) * (1 + SLACK):
return f"{both} are {p['type']} sockets, which mate at equal sizes (within 1 percent)"

View file

@ -4,7 +4,7 @@
"doc": "Chassis structure: sectioned beams, a truss, a portal, a gusset and a wedge, each a section swept along a path. Metres.",
"socketTypes": {
"mount": {"match": "fits", "doc": "flat seat; size is the free diameter around the socket"},
"pivot": {"match": "equal", "doc": "pin joint; size is the pin diameter"}
"pivot": {"match": "equal", "dof": "revolute", "doc": "pin joint; size is the pin diameter"}
},
"parts": [
{

View file

@ -5,7 +5,9 @@
"socketTypes": {
"flange": {"match": "equal", "doc": "bolted pipe or duct face; size is the bore diameter"},
"mount": {"match": "fits", "doc": "flat seat; size is the free diameter around the socket"},
"pivot": {"match": "equal", "doc": "pin joint; size is the pin diameter"}
"pivot": {"match": "equal", "dof": "revolute", "doc": "pin joint; size is the pin diameter"},
"slide": {"match": "equal", "dof": "prismatic", "doc": "telescoping bore; size is the bore diameter; the child slides along the socket's z"},
"hose": {"match": "fits", "doc": "hose port; size is the widest bundle it takes"}
},
"parts": [
{
@ -173,7 +175,62 @@
{"name": "base", "type": "pivot", "size": "0.9*body_r", "at": [0, "0.65*body_r", "0.8*body_r"], "z": "+y", "y": "+z"},
{"name": "base_back", "type": "pivot", "size": "0.9*body_r", "at": [0, "-0.65*body_r", "0.8*body_r"], "z": "-y", "y": "+z"},
{"name": "rod_end", "type": "pivot", "size": "0.9*body_r", "at": [0, "0.65*body_r", "3.8*body_r+body_len+extension"], "z": "+y", "y": "+z"},
{"name": "rod_end_back", "type": "pivot", "size": "0.9*body_r", "at": [0, "-0.65*body_r", "3.8*body_r+body_len+extension"], "z": "-y", "y": "+z"}
{"name": "rod_end_back", "type": "pivot", "size": "0.9*body_r", "at": [0, "-0.65*body_r", "3.8*body_r+body_len+extension"], "z": "-y", "y": "+z"},
{"name": "port_cap", "type": "hose", "size": "0.4*body_r", "at": ["1.45*body_r", 0, "1.75*body_r"], "z": "+x", "y": "+z"},
{"name": "port_rod", "type": "hose", "size": "0.4*body_r", "at": ["1.45*body_r", 0, "2.25*body_r+body_len"], "z": "+x", "y": "+z"}
]
},
{
"name": "ram_barrel",
"doc": "The barrel of a tie-rod hydraulic cylinder, the actuator's up to its gland: base eye on a cross pin with a socket on each end face, square caps, barrel, ports, and a bore a ram_rod slides in.",
"params": [
{"name": "body_r", "type": "number", "min": 0.05, "max": 0.12, "default": 0.06, "doc": "barrel radius"},
{"name": "body_len", "type": "number", "min": 0.2, "max": 1.0, "default": 0.4, "doc": "barrel length between caps"},
{"name": "rod_r", "type": "number", "min": 0.01, "max": 0.02, "default": 0.018, "doc": "radius of the rod its gland takes"},
{"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of every round"}
],
"bevel": "0.04*body_r",
"shapes": [
{"shape": "box", "size": ["1.2*body_r", "0.9*body_r", "1.6*body_r"], "at": [0, 0, "0.8*body_r"]},
{"shape": "tube", "r0": "0.45*body_r", "r1": "0.45*body_r", "length": "1.3*body_r", "segments": "segments", "smooth": true, "rot": [-90, 0, 0], "at": [0, "-0.65*body_r", "0.8*body_r"]},
{"shape": "box", "size": ["2.4*body_r", "2.4*body_r", "0.5*body_r"], "at": [0, 0, "1.75*body_r"]},
{"shape": "tube", "r0": "body_r", "r1": "body_r", "length": "body_len+0.2*body_r", "segments": "segments", "smooth": true, "at": [0, 0, "1.9*body_r"]},
{"shape": "box", "size": ["2.4*body_r", "2.4*body_r", "0.5*body_r"], "at": [0, 0, "2.25*body_r+body_len"]},
{"shape": "repeat", "count": 2, "step": ["1.9*body_r", 0, 0], "of":
{"shape": "tube", "r0": "0.12*body_r", "r1": "0.12*body_r", "length": "body_len+1.3*body_r", "segments": 6, "at": ["-0.95*body_r", "-0.95*body_r", "1.35*body_r"]}},
{"shape": "repeat", "count": 2, "step": ["1.9*body_r", 0, 0], "of":
{"shape": "tube", "r0": "0.12*body_r", "r1": "0.12*body_r", "length": "body_len+1.3*body_r", "segments": 6, "at": ["-0.95*body_r", "0.95*body_r", "1.35*body_r"]}},
{"shape": "repeat", "count": 2, "step": [0, 0, "body_len+0.5*body_r"], "of":
{"shape": "tube", "r0": "0.2*body_r", "r1": "0.2*body_r", "length": "0.45*body_r", "segments": "segments", "smooth": true, "rot": [0, 90, 0], "at": ["body_r", 0, "1.75*body_r"]}},
{"shape": "tube", "r0": "rod_r+0.25*body_r", "r1": "rod_r+0.25*body_r", "length": "0.4*body_r", "segments": "segments", "smooth": true, "at": [0, 0, "2.4*body_r+body_len"]}
],
"sockets": [
{"name": "base", "type": "pivot", "size": "0.9*body_r", "at": [0, "0.65*body_r", "0.8*body_r"], "z": "+y", "y": "+z"},
{"name": "base_back", "type": "pivot", "size": "0.9*body_r", "at": [0, "-0.65*body_r", "0.8*body_r"], "z": "-y", "y": "+z"},
{"name": "bore", "type": "slide", "size": "2*rod_r", "at": [0, 0, "2*body_r"], "z": "+z", "y": "+y"},
{"name": "port_cap", "type": "hose", "size": "0.4*body_r", "at": ["1.45*body_r", 0, "1.75*body_r"], "z": "+x", "y": "+z"},
{"name": "port_rod", "type": "hose", "size": "0.4*body_r", "at": ["1.45*body_r", 0, "2.25*body_r+body_len"], "z": "+x", "y": "+z"}
]
},
{
"name": "ram_rod",
"doc": "The rod of a hydraulic cylinder, the actuator's from its gland: a rod from its piston face to a rod eye on a cross pin with a socket on each end face. Its piston slides in a ram_barrel's bore: slide 0 is closed, the slide is the extension.",
"params": [
{"name": "body_r", "type": "number", "min": 0.05, "max": 0.12, "default": 0.06, "doc": "its barrel's radius: sizes the rod eye"},
{"name": "rod_r", "type": "number", "min": 0.01, "max": 0.02, "default": 0.018, "doc": "rod radius"},
{"name": "length", "type": "number", "min": 0.2, "max": 2.0, "default": 0.466, "doc": "piston face to the rod eye's block; its barrel's body_len + 1.1*body_r stands as the actuator does at extension 0"},
{"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of every round"}
],
"bevel": "0.04*body_r",
"shapes": [
{"shape": "tube", "r0": "rod_r", "r1": "rod_r", "length": "length+0.2*body_r", "segments": "segments", "smooth": true, "at": [0, 0, 0]},
{"shape": "box", "size": ["1.2*body_r", "0.9*body_r", "1.4*body_r"], "at": [0, 0, "length+0.7*body_r"]},
{"shape": "tube", "r0": "0.45*body_r", "r1": "0.45*body_r", "length": "1.3*body_r", "segments": "segments", "smooth": true, "rot": [-90, 0, 0], "at": [0, "-0.65*body_r", "length+0.7*body_r"]}
],
"sockets": [
{"name": "piston", "type": "slide", "size": "2*rod_r", "at": [0, 0, 0], "z": "-z", "y": "+y"},
{"name": "rod_end", "type": "pivot", "size": "0.9*body_r", "at": [0, "0.65*body_r", "length+0.7*body_r"], "z": "+y", "y": "+z"},
{"name": "rod_end_back", "type": "pivot", "size": "0.9*body_r", "at": [0, "-0.65*body_r", "length+0.7*body_r"], "z": "-y", "y": "+z"}
]
},
{

View file

@ -0,0 +1,790 @@
"""Rams and linkages across a one-axis hinge: numpy and the standard library only, and nothing from the package, so
a rig, a runtime or a test loads this file alone. Signed, the mesh oracle, asks for Blender's BVH tree when one is
made and not before.
A Mechanism is the record of one hinge's drive: the hinge (pivot, unit axis, lo and hi in degrees, positive
right-handed about the axis), a kind, and pins, each in its own body's rest frame (the pose at angle 0, where
every body's frame is the parent's).
direct the ram runs from a on the parent to b on the child.
four_bar a rocker pinned on the parent at `rocker` (R) carries the pin p; a coupler joins p to c on the child;
the ram runs from a on the parent to d on the rocker, and d is p (the excavator bucket linkage).
bell_crank the same loop with d elsewhere on the rocker.
Every pose quantity is a pure function of (record, angle): pose() holds no solve state. The loop is solved in the
plane across the axis; a pin's coordinate along the axis only says where its member stands: the rocker bars at R's,
the coupler bar at c's, the ram at a's plus each of `offsets`.
pose(m, degrees) every body's rotation, the ram's base and eye, L, dL/dtheta, per angle
length(m, degrees) pin-to-pin ram length
barrel_length(m, ram) the barrel the range's shorter end leaves room for
extension(m, ram, degrees) rod extension from closed
fit(m, ram, ...) the gates over the range: assembly, stroke, arm, load, clearance
clearance(m, ram, degrees, distance) the clearance gate's reading at any angles, per member and part
search(kind, hinge, ram, seats, ...) the best of a seat grid, or the tally and the nearest miss
record(m, ram), from_record the JSON record a rig or runtime drives from
swept(fit, body, ...) points of the swept ram's surface in a body's rest frame
Signed(shells, cap) the distance oracle over closed meshes, signed by three rays
Clearance. The record names the mechanism's `parts`, each a piece of one body (part -> the body whose rest frame
it turns with: a thigh's core, the bracket that carries the rocker's pivot, a link's plates, a pin), and `touch`:
for each member of MEMBERS[kind], zones (part, pin, radius, depth). Every member meets every part. A zone lowers
what the member's samples keep from one part, and only within `radius` of the axis of `pin`, one of the member's
own (RIDES), measured across the hinge axis: there a sample may come as near the part as -depth and no nearer.
depth is 0 for what is stacked beside the member on the pin (a plate, the bracket or horn the pin stands in: the
member's axis stays outside it, so a pin whose place along the axis is inside the part it claims to stand beside
is refused), the pin's radius for the pin through the member's eye, half the thickness for the member's own plate
or clevis. Beyond the radius the pair is checked like any other; nothing is exempt by a name, a length or the
member's own body. Every body of the kind owns at least one part, or the gate refuses.
A zone is bounded by its member. Its radius and its depth are finite and no more than the member's length from pin
to pin (a bar's between its pins; the ram's at the most its pins allow), which the record refuses by its pins
alone; its depth is no more than the member's eye on that pin (Ram.eye: e_a at the base, e_b at the rod's eye,
link_r on a bar), which from_record and the gate refuse, a world's answer included. Between two samples of which
either is in a zone, the gate does not trust the spacing: it halves the segment until the readings at its ends
prove it holds -depth throughout (see _between), so a part of any thickness that the axis crosses there is read.
The oracle is distance(part, points) -> distances, points (N, 3) in the rest frame of the part's body. A distance
is signed: negative inside the part, by any depth. The oracle may cap what it returns at Ram.reach(spacing),
outside a part only: a point inside reads negative however deep it lies. An oracle that cannot tell inside from
outside (a nearest-surface query on an open mesh) raises instead of answering; nan is refused here. It never reads
more than the true distance: the gate's proof between samples is that a distance changes by no more than the way
between two points.
A RamError of a gate (assembly, stroke, toggle, arm, load, clash) names the angle and the pin; one of the record
or of a call (an unknown kind, a range, a grid over the limit, a version) names the pin or the field it refuses.
"""
import math
from dataclasses import dataclass, field, fields, replace
import numpy as np
KINDS = ("direct", "four_bar", "bell_crank")
BODIES = {"direct": ("parent", "child"), "four_bar": ("parent", "child", "rocker", "coupler"),
"bell_crank": ("parent", "child", "rocker", "coupler")}
PINS = {"direct": ("a", "b"), "four_bar": ("a", "rocker", "p", "c", "d"), "bell_crank": ("a", "rocker", "p", "c", "d")}
MEMBERS = {"direct": ("barrel", "rod"), "four_bar": ("barrel", "rod", "rocker", "coupler"),
"bell_crank": ("barrel", "rod", "rocker", "coupler", "rocker arm")}
EYE = {"direct": "b", "four_bar": "d", "bell_crank": "d"} # the pin the rod's eye rides
RIDES = {kind: {"barrel": ("a", EYE[kind]), "rod": ("a", EYE[kind]), "rocker": ("rocker", "p"), "coupler": ("p", "c"), "rocker arm": ("rocker", "d")}
for kind in KINDS} # member -> the pins at its start and its end
GATES = ("assembly", "stroke", "toggle", "arm", "load", "clash")
SCHEMA, VERSION = "brokkr.ram", 1
ZONE = ("part", "pin", "radius", "depth") # a zone of `touch`, as the record writes it
COMPLIANCE = ("stiffness", "damping", "travel") # reserved: a load-path ram's settle, solved by a later version
BAND = 1e-9 # the loop is refused within this of a dead centre of the rocker and coupler
FINE = 64 # in a zone a segment between samples is halved down to spacing / FINE
RAYS = ((0.5377, 0.6211, 0.5701), (-0.7071, 0.2903, 0.6447), (0.1873, -0.8011, -0.5684)) # Signed's, in order
class RamError(ValueError):
"""A refusal: the mechanism kind, the gate, the angle and the pin it failed at. `fit` holds the readings when
the gates got far enough to take them."""
def __init__(self, kind, gate, message, angle=None, pin=None, fit=None):
where = (f" at {angle:g} deg" if angle is not None else "") + (f" (pin {pin})" if pin else "")
super().__init__(f"{kind} ram: {gate}{where}: {message}")
self.kind, self.gate, self.angle, self.pin, self.fit = kind, gate, angle, pin, fit
def _number(kind, name, value, least=None):
"""A record's number: an int or a float, finite, never a bool, a string or null; above `least` when given."""
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
raise RamError(kind, "record", f"a finite number, got {value!r}", pin=name)
if least is not None and not value > least:
raise RamError(kind, "record", f"a number greater than {least:g}, got {value!r}", pin=name)
return float(value)
@dataclass
class Ram:
"""A ram's proportions. Lengths default from the bore radius. Every one is a finite number and the bore is
greater than 0, or the ram is refused naming the field (as the ram of `any` kind: a ram knows none)."""
bore: float
rod: float = None # rod radius
barrel_r: float = None # barrel outer radius
e_a: float = None # base pin centre to the barrel's back end
e_b: float = None # rod eye centre to the rod's shoulder (what stays out of the barrel, closed)
gland: float = None # piston and gland: barrel length that is not stroke
over: float = None # spare travel at each end of the stroke
tail: float = 0.0 # trunnion mount: barrel behind the base pin (replaces e_a)
min_arm: float = None # least effective arm |dL/dtheta|, length per radian
gap: float = None # least clearance to a body
link_r: float = None # half thickness of a rocker or coupler bar
max_load: float = 3.0 # greatest coupler pin load per unit ram force
def __post_init__(self):
b = self.bore = _number("any", "bore", self.bore, 0.0)
for name, value in (("rod", 0.5 * b), ("barrel_r", 1.25 * b), ("e_a", 1.7 * b), ("e_b", 1.7 * b), ("gland", 1.3 * b),
("over", 0.2 * b), ("min_arm", 1.5 * b), ("gap", 0.15 * b), ("link_r", 0.7 * b)):
if getattr(self, name) is None:
setattr(self, name, value)
for f in fields(self):
setattr(self, f.name, _number("any", f.name, getattr(self, f.name)))
@property
def back(self):
"""Signed distance from the base pin to the barrel's back end along the ram (negative: behind the pin)."""
return -self.tail if self.tail > 0 else self.e_a
def spacing(self, spacing=None):
return self.barrel_r if spacing is None else float(spacing)
def eye(self, member, pin):
"""The radius of a member's eye on one of its pins: the most a zone's depth lets its axis into a part."""
if member in ("barrel", "rod"):
return self.e_a if pin == "a" else self.e_b
return self.link_r
def reach(self, spacing=None):
"""The greatest distance the clearance gate asks of any member: what a distance oracle may cap at."""
return max(self.barrel_r, self.rod, self.link_r) + self.gap + self.spacing(spacing) / 2
def _flat(v, n):
"""v without its part along the unit axis n."""
return v - n * (v @ n)[..., None]
def _rot(v, n, t):
"""v (..., 3) turned about the unit axis n by t radians (Rodrigues); t broadcasts over v's leading shape."""
t = np.asarray(t, dtype=float)[..., None]
return v * np.cos(t) + np.cross(n, v) * np.sin(t) + n * (v @ n)[..., None] * (1.0 - np.cos(t))
def _angle(v0, v, n):
"""Signed angle about n from v0 to v, both across n."""
return np.arctan2(np.cross(v0, v) @ n, v @ v0)
@dataclass
class Mechanism:
kind: str
pivot: np.ndarray
axis: np.ndarray
lo: float
hi: float
a: np.ndarray
b: np.ndarray = None
rocker: np.ndarray = None
p: np.ndarray = None
c: np.ndarray = None
d: np.ndarray = None
offsets: tuple = (0.0,)
parts: dict = field(default_factory=dict) # part -> the body it turns with
touch: dict = field(default_factory=dict) # member -> zones (part, pin, radius, depth)
def __post_init__(self):
if self.kind not in KINDS:
raise RamError(str(self.kind), "record", f"kind is one of {', '.join(KINDS)}")
for name in ("pivot", "axis", "a", "b", "rocker", "p", "c", "d"):
value = getattr(self, name)
if value is not None:
value = np.array(value, dtype=float)
if value.shape != (3,) or not np.isfinite(value).all():
raise RamError(self.kind, "record", "three finite numbers", pin=name)
setattr(self, name, value)
if abs(np.linalg.norm(self.axis) - 1.0) > 1e-6:
raise RamError(self.kind, "record", f"the axis is a unit vector, length {np.linalg.norm(self.axis):.6f}", pin="axis")
self.lo, self.hi = float(self.lo), float(self.hi)
if not self.lo < self.hi or self.hi - self.lo > 360.0:
raise RamError(self.kind, "record", f"lo < hi and hi - lo <= 360, got {self.lo:g}..{self.hi:g}", angle=self.lo)
self.offsets = tuple(float(o) for o in self.offsets)
if not self.offsets:
raise RamError(self.kind, "record", "at least one offset: where the ram stands along the axis from a", pin="a")
self.parts = {str(part): body for part, body in dict(self.parts).items()}
for part, body in self.parts.items():
if body not in BODIES[self.kind]:
raise RamError(self.kind, "record", f"part {part!r} turns with {body!r}; this kind has {', '.join(BODIES[self.kind])}")
for name in ("a", "b", "rocker", "p", "c", "d"):
needed, given = name in PINS[self.kind], getattr(self, name) is not None
if needed != given:
raise RamError(self.kind, "record", "this kind needs the pin" if needed else "this kind has no such pin", pin=name)
touch = {}
for member, zones in dict(self.touch).items():
if member not in MEMBERS[self.kind]:
raise RamError(self.kind, "record", f"touch names {member!r}; this kind's members are {', '.join(MEMBERS[self.kind])}")
touch[member] = []
for zone in zones:
if isinstance(zone, (str, dict)) or len(zone) != 4:
raise RamError(self.kind, "record", f"{member}'s zone is (part, pin, radius, depth), got {zone!r}")
part, pin, radius, depth = zone
if part not in self.parts:
raise RamError(self.kind, "record", f"{member} may touch {part!r}, which is no part of the record")
if pin not in RIDES[self.kind][member]:
raise RamError(self.kind, "record", f"{member} may touch {part!r} about a pin it rides ({', '.join(RIDES[self.kind][member])}), not {pin!r}", pin=str(pin))
radius, depth = _number(self.kind, f"{member} {part} radius", radius, 0.0), _number(self.kind, f"{member} {part} depth", depth)
if depth < 0.0:
raise RamError(self.kind, "record", f"a depth of 0 or more, got {depth!r}", pin=f"{member} {part} depth")
span = _span(self, member)
for name, value in (("radius", radius), ("depth", depth)):
if value > span:
raise RamError(self.kind, "record", f"a zone no wider or deeper than its member: {member} is at most {span:.4f} from pin to pin, got {value!r}",
pin=f"{member} {part} {name}")
touch[member].append((part, pin, radius, depth))
touch[member] = tuple(touch[member])
self.touch = touch
if self.kind == "direct":
return
n = self.axis
apart = float(np.linalg.norm(self.d - self.p))
if self.kind == "four_bar" and apart > 0.0:
raise RamError(self.kind, "record", f"a four-bar's ram eye is the rocker's coupler pin; d is {apart:.4f} from p", pin="d")
if self.kind == "bell_crank" and apart == 0.0:
raise RamError(self.kind, "record", "a bell crank's ram eye stands off the coupler pin; d on p is a four_bar", pin="d")
self.lr = float(np.linalg.norm(_flat(self.p - self.rocker, n)))
self.lc = float(np.linalg.norm(_flat(self.p - self.c, n)))
side = float(n @ np.cross(_flat(self.c - self.rocker, n), _flat(self.p - self.rocker, n)))
if min(self.lr, self.lc) < BAND or abs(side) < BAND:
raise RamError(self.kind, "assembly", "the rest pose is a dead centre: R, p and c are in line", pin="p")
self.branch = 1.0 if side > 0 else -1.0 # which side of R -> c the pin p keeps, through the whole range
def _span(m, member):
"""The most a member measures from pin to pin, by the pins alone: a bar's length across the axis; for the ram's
two, the base's and the eye's distances from the centre the eye turns about, added."""
if member in ("barrel", "rod"):
centre, eye = m.pivot if m.kind == "direct" else m.rocker, getattr(m, EYE[m.kind])
return float(np.linalg.norm(m.a - centre) + np.linalg.norm(eye - centre))
start, end = RIDES[m.kind][member]
return float(np.linalg.norm(_flat(getattr(m, end) - getattr(m, start), m.axis)))
def _eyes(m, ram):
"""Refuse a zone deeper than its member's eye on its pin."""
for member, zones in m.touch.items():
for part, pin, _, depth in zones:
if depth > ram.eye(member, pin):
raise RamError(m.kind, "record", f"a zone no deeper than its member's eye: {member}'s on {pin} is {ram.eye(member, pin):.4f}, got {depth!r}",
pin=f"{member} {part} depth")
@dataclass
class Pose:
degrees: np.ndarray # (S,)
base: np.ndarray # (S, 3) ram base pin, parent frame, at offset 0
eye: np.ndarray # (S, 3) ram eye
u: np.ndarray # (S, 3) unit vector base -> eye
L: np.ndarray # (S,) pin to pin
dL: np.ndarray # (S,) dL/dtheta, length per radian: the effective arm, signed
phi: np.ndarray = None # (S,) rocker angle from rest, radians, in (-pi, pi]
psi: np.ndarray = None # (S,) coupler angle from rest
dphi: np.ndarray = None # (S,) dphi/dtheta
P: np.ndarray = None # (S, 3) the rocker's coupler pin
C: np.ndarray = None # (S, 3) the child's coupler pin
load: np.ndarray = None # (S,) coupler pin load per unit ram force
mu_c: np.ndarray = None # (S,) transmission angle at c, degrees, folded to 0..90
mu_p: np.ndarray = None # (S,) transmission angle at p
def pose(m, degrees):
"""The mechanism at each of `degrees` (a number or an array): a pure function of the record and the angle."""
deg = np.atleast_1d(np.asarray(degrees, dtype=float))
t, n, O = np.radians(deg), m.axis, m.pivot
if m.kind == "direct":
eye = O + _rot(m.b - O, n, t)
base = np.broadcast_to(m.a, eye.shape)
L = np.linalg.norm(eye - base, axis=1)
u = (eye - base) / np.maximum(L, 1e-12)[:, None]
return Pose(deg, base, eye, u, L, (np.cross(n, eye - O) * u).sum(axis=1))
R = m.rocker
C = O + _rot(m.c - O, n, t)
g = _flat(C - R, n)
dist = np.linalg.norm(g, axis=1)
lo, hi = abs(m.lr - m.lc) + BAND, m.lr + m.lc - BAND
bad = (dist <= lo) | (dist >= hi)
if bad.any():
i = int(np.argmax(bad))
raise RamError(m.kind, "assembly", f"|c - R| is {dist[i]:.4f}, outside ({lo:.4f}, {hi:.4f}): the rocker ({m.lr:.4f}) and coupler "
f"({m.lc:.4f}) cannot close the loop, or reach a dead centre where the branch would change", angle=float(deg[i]), pin="c")
x = (m.lr * m.lr - m.lc * m.lc + dist * dist) / (2.0 * dist)
h = np.sqrt(np.maximum(m.lr * m.lr - x * x, 0.0))
across = g / dist[:, None]
v = across * x[:, None] + m.branch * np.cross(n, across) * h[:, None] # p - R across the axis
phi = _angle(_flat(m.p - R, n), v, n)
P = R + _rot(m.p - R, n, phi)
eye = R + _rot(m.d - R, n, phi)
w = _flat(P - C, n) # the coupler, c -> p
k = w / np.linalg.norm(w, axis=1)[:, None]
psi = _angle(_flat(m.p - m.c, n), w, n)
# the coupler's two ends move equally along it
dphi = (np.cross(n, C - O) * k).sum(axis=1) / (np.cross(n, P - R) * k).sum(axis=1)
base = np.broadcast_to(m.a, eye.shape)
L = np.linalg.norm(eye - base, axis=1)
u = (eye - base) / np.maximum(L, 1e-12)[:, None]
dL = (np.cross(n, eye - R) * u).sum(axis=1) * dphi
crank, link = _flat(O - C, n), _flat(R - P, n)
moment = np.abs(np.cross(-crank, k) @ n)
load = np.abs(dL) / np.maximum(moment, 1e-12)
mu_c = np.degrees(np.arcsin(np.clip(moment / np.linalg.norm(crank, axis=1), 0.0, 1.0)))
mu_p = np.degrees(np.arcsin(np.clip(np.abs(np.cross(link, k) @ n) / np.linalg.norm(link, axis=1), 0.0, 1.0)))
return Pose(deg, base, eye, u, L, dL, phi, psi, dphi, P, C, load, mu_c, mu_p)
def length(m, degrees):
"""Pin-to-pin ram length at each angle."""
return pose(m, degrees).L
def barrel_length(m, ram):
"""The barrel the mechanism leaves room for: the ram's length at the shorter end of the range, less the
overtravel, the base clevis (or nothing, on a trunnion) and the eye. L runs one way over a range that fits
(the toggle gate), so that end is the least. Derived, never stored: a record holds the pins and the ram."""
return _barrel(ram, pose(m, (m.lo, m.hi)).L)
def _barrel(ram, ends):
return float(min(ends[0], ends[-1])) - ram.over - ram.back - ram.e_b
def extension(m, ram, degrees):
"""Rod extension from closed at each angle: L - (back + barrel + e_b)."""
return pose(m, degrees).L - (ram.back + barrel_length(m, ram) + ram.e_b)
def _members(m, ram, barrel, p):
"""(member, label, start (S, 3), end (S, 3), radius, (pin at start, pin at end)) of every member in the parent
frame, each from pin to pin: the barrel from its back end, the rod to the eye, a bar between its pins."""
n, rides = m.axis, RIDES[m.kind]
for off in m.offsets:
base, tip = p.base + off * n, p.eye + off * n
front = base + p.u * (ram.back + max(barrel, 1e-6))
yield "barrel", f"barrel[{off:g}]", base + p.u * ram.back, front, ram.barrel_r, rides["barrel"]
yield "rod", f"rod[{off:g}]", front, tip, ram.rod, rides["rod"]
if m.kind == "direct":
return
R = np.broadcast_to(m.rocker, p.P.shape)
yield "rocker", "rocker", R, p.P - n * ((p.P - R) @ n)[:, None], ram.link_r, rides["rocker"]
yield "coupler", "coupler", p.P - n * ((p.P - p.C) @ n)[:, None], p.C, ram.link_r, rides["coupler"]
if m.kind == "bell_crank":
yield "rocker arm", "rocker arm", R, p.eye - n * ((p.eye - R) @ n)[:, None], ram.link_r, rides["rocker arm"]
def _into(m, p, body, pts):
"""Parent-frame points (S, N, 3) carried into a body's rest frame at each angle."""
n = m.axis
if body == "parent":
return pts
if body == "child":
return m.pivot + _rot(pts - m.pivot, n, -np.radians(p.degrees)[:, None])
if body == "rocker":
return m.rocker + _rot(pts - m.rocker, n, -p.phi[:, None])
return m.p + _rot(pts - p.P[:, None, :], n, -p.psi[:, None])
@dataclass
class Clearance:
margin: np.ndarray # (S,) the least margin of any checked pair at each angle
where: tuple # (angle, member label, part, pin) of the least: the pin is the member's nearer one
pairs: dict # (member label, part) -> (least margin, angle) of every pair: every member, every part
allowed: list # (member label, part) of every pair a zone of the record's `touch` lets near a pin
def clearance(m, ram, degrees, distance, spacing=None):
"""The clearance gate's reading. A member is clear where margin >= 0: each sample of its axis, taken at most
`spacing` apart (default barrel_r), is at least radius + gap + spacing / 2 from every part, measured in the
rest frame of the part's body at that angle. A sample is at most spacing / 2 from any point of the axis, so
the member's surface keeps the gap. Every member meets every part of the record. Inside a zone of `touch`
(within its radius of its pin's axis, across the hinge axis) a sample keeps -depth from the zone's part
instead: the margin there is the distance plus the depth, and the segment to the next sample is proved to
hold -depth throughout (_between). Two zones of one pair that both reach a sample let it the deeper."""
return _clearance(m, ram, barrel_length(m, ram), pose(m, degrees), distance, spacing)
def _between(kind, distance, part, pts, got, keep, zoned, floor):
"""(S,) the least margin found between samples, inf where none is: for each segment between consecutive samples
of which either is in a zone, whether the axis holds -depth (the deeper of its ends') all along it. A distance
changes by no more than the way between two points, so along a segment it is at least (g(a) + g(b) - |ab|) / 2;
where that does not prove the segment it is halved, the midpoint read (its margin is counted), down to `floor`.
A segment still unproved at the floor against a part the axis is held outside (depth 0) reads that bound, so
it is refused: the part is within floor / 2 of the axis there, crossed or touched. Against a part the axis may
enter, the samples' readings stand: a burial is read to floor / 2."""
out = np.full(len(pts), math.inf)
pair = zoned[:, :-1] | zoned[:, 1:]
row = np.nonzero(pair)[0]
a, b, ga, gb = pts[:, :-1][pair], pts[:, 1:][pair], got[:, :-1][pair], got[:, 1:][pair]
hold = np.minimum(keep[:, :-1], keep[:, 1:])[pair]
while len(row):
span = np.linalg.norm(b - a, axis=1)
bound = (ga + gb - span) / 2.0
unproved = (bound < hold) & (np.minimum(ga, gb) >= hold) # an end under its hold is already refused
touched = unproved & (span <= floor) & (hold == 0.0)
np.minimum.at(out, row[touched], bound[touched])
go = unproved & (span > floor)
if not go.any():
break
a, b, ga, gb, hold, row = (x[go] for x in (a, b, ga, gb, hold, row))
mid = (a + b) / 2.0
gm = np.asarray(distance(part, mid), dtype=float)
if np.isnan(gm).any():
raise RamError(kind, "oracle", f"the distance oracle answered nan for part {part!r}")
np.minimum.at(out, row, gm - hold)
a, b, ga, gb = np.concatenate([a, mid]), np.concatenate([mid, b]), np.concatenate([ga, gm]), np.concatenate([gm, gb])
hold, row = np.concatenate([hold, hold]), np.concatenate([row, row])
return out
def _clearance(m, ram, barrel, p, distance, spacing):
_eyes(m, ram)
for body in BODIES[m.kind]:
if body not in m.parts.values():
raise RamError(m.kind, "record", f"no part turns with body {body}: the clearance gate would pass it unseen")
step = ram.spacing(spacing)
out = Clearance(np.full(len(p.degrees), math.inf), None, {}, [])
least = math.inf
at = {"a": p.base, EYE[m.kind]: p.eye, "rocker": m.rocker, "p": p.P, "c": p.C} # each pin over the angles, parent frame
for member, label, start, end, radius, pins in _members(m, ram, barrel, p):
count = max(int(math.ceil(float(np.linalg.norm(end - start, axis=1).max()) / step)) + 1, 2)
pts = start[:, None, :] + (end - start)[:, None, :] * np.linspace(0.0, 1.0, count)[None, :, None]
need = radius + ram.gap + step / 2.0
seen = {}
for part, body in m.parts.items():
if body not in seen:
seen[body] = _into(m, p, body, pts).reshape(-1, 3)
got = np.asarray(distance(part, seen[body]), dtype=float).reshape(len(p.degrees), count)
if np.isnan(got).any():
raise RamError(m.kind, "oracle", f"the distance oracle answered nan for part {part!r}")
keep = np.full(got.shape, need) # what each sample keeps from the part
zoned = np.zeros(got.shape, dtype=bool)
zones = [zone for zone in m.touch.get(member, ()) if zone[0] == part]
for _, pin, reach, depth in zones:
across = np.linalg.norm(_flat(pts - np.broadcast_to(at[pin], start.shape)[:, None, :], m.axis), axis=2)
keep = np.where(across <= reach, np.minimum(keep, -depth), keep)
zoned |= across <= reach
over = got - keep
row = over.min(axis=1)
if zones:
out.allowed.append((label, part))
row = np.minimum(row, _between(m.kind, distance, part, seen[body].reshape(len(p.degrees), count, 3), got, keep, zoned, step / FINE))
out.margin = np.minimum(out.margin, row)
i = int(np.argmin(row))
out.pairs[(label, part)] = (float(row[i]), float(p.degrees[i]))
if row[i] < least:
least = float(row[i])
out.where = (float(p.degrees[i]), label, part, pins[int(np.argmin(over[i])) * 2 >= count])
return out
@dataclass
class Fit:
m: Mechanism
ram: Ram
why: list # (gate, angle, pin, message) of every gate that failed; empty when it fits
degrees: np.ndarray
l_min: float
l_max: float
travel: float # L_max - L_min
barrel: float # barrel length: barrel_length(m, ram)
closed: float # pin to pin with the rod home: back + barrel + e_b
stroke: float # travel the barrel holds
spare: float # stroke - (travel + 2 over): negative when the stroke does not fit
arm_min: float # least |dL/dtheta|
arm_at: float # the angle of it
arm_sign: int # 0 when dL/dtheta changes sign (a dead centre inside the range)
swing: float = 0.0 # the rocker's travel, degrees
load_max: float = 0.0 # greatest coupler pin load per unit ram force
mu_c: float = None # least transmission angle at c, degrees: reported, never gated
mu_p: float = None # least transmission angle at p
clear_min: float = math.inf # least clearance beyond what the gate asks; inf with no oracle
clear_at: tuple = None # (angle, member, part, pin) of it
pairs: dict = field(default_factory=dict) # (member, part) -> (least margin, angle) of every pair
allowed: list = field(default_factory=list) # (member, part) of every pair a zone of `touch` lets near a pin
table: list = field(default_factory=list) # (angle, L, dL/dtheta, clearance margin) per step
@property
def ok(self):
return not self.why
def error(self):
gate, angle, pin, message = self.why[0]
return RamError(self.m.kind, gate, message, angle=angle, pin=pin, fit=self)
def report(self):
"""One line for a log or a sheet."""
state = "OK" if self.ok else "NO (" + "; ".join(f"{g}: {msg}" for g, _, _, msg in self.why) + ")"
links = "" if self.m.kind == "direct" else f", rocker swing {self.swing:.1f}, pin load <= {self.load_max:.2f}, transmission >= {min(self.mu_c, self.mu_p):.1f} deg"
return (f"{state}: L {self.l_min:.3f}..{self.l_max:.3f}, barrel {self.barrel:.3f}, stroke {self.stroke:.3f} for travel {self.travel:.3f} "
f"(spare {self.spare:+.3f}), arm >= {self.arm_min:.3f}{links}, clear {self.clear_min:+.3f}")
def _fit(m, ram, steps=25, distance=None, spacing=None, clear=True):
"""Every gate's reading; raises only where the loop does not assemble or a bell crank's eye crowds its pin."""
if m.kind == "bell_crank" and np.linalg.norm(m.d - m.p) < 2.0 * ram.bore:
raise RamError(m.kind, "pins", f"the ram eye stands at least 2 bore ({2.0 * ram.bore:.4f}) from the coupler pin; d is {np.linalg.norm(m.d - m.p):.4f} from p", pin="d")
if (m.kind != "direct") and not (m.lo <= 0.0 <= m.hi):
pose(m, np.linspace(0.0, m.lo if m.lo > 0.0 else m.hi, steps)) # the branch is carried from rest: no dead centre on the way
p = pose(m, np.linspace(m.lo, m.hi, steps))
l_min, l_max = float(p.L.min()), float(p.L.max())
eye = EYE[m.kind]
travel = l_max - l_min
barrel = _barrel(ram, p.L) # the samples' ends are lo and hi: barrel_length's own two angles
stroke = barrel - ram.gland
spare = stroke - (travel + 2.0 * ram.over)
i = int(np.argmin(np.abs(p.dL)))
arm_min, arm_at = float(abs(p.dL[i])), float(p.degrees[i])
signs = set(np.sign(p.dL[np.abs(p.dL) > 1e-9]).tolist())
arm_sign = int(signs.pop()) if len(signs) == 1 else 0
f = Fit(m, ram, [], p.degrees, l_min, l_max, travel, barrel, ram.back + barrel + ram.e_b, stroke, spare, arm_min, arm_at, arm_sign)
if barrel <= ram.gland or spare < -1e-9:
f.why.append(("stroke", float(p.degrees[int(np.argmin(p.L))]), eye, f"travel {travel:.3f} needs {travel + 3.0 * ram.over + ram.gland + ram.back + ram.e_b:.3f} closed, L_min is {l_min:.3f}"))
if arm_sign == 0:
flip = np.nonzero(np.sign(p.dL[1:]) != np.sign(p.dL[:-1]))[0]
f.why.append(("toggle", float(p.degrees[flip[0] + 1]) if len(flip) else arm_at, eye, "dL/dtheta changes sign: a dead centre inside the range"))
elif arm_min < ram.min_arm:
f.why.append(("arm", arm_at, eye, f"least effective arm {arm_min:.3f} under {ram.min_arm:.3f}"))
if m.kind != "direct":
phi = np.degrees(np.unwrap(p.phi))
j = int(np.argmax(p.load))
f.swing, f.load_max = float(phi.max() - phi.min()), float(p.load[j])
f.mu_c, f.mu_p = float(p.mu_c.min()), float(p.mu_p.min())
if f.load_max > ram.max_load:
f.why.append(("load", float(p.degrees[j]), "c", f"coupler pin load {f.load_max:.2f} x the ram force, over {ram.max_load:.2f}"))
margin = np.full(steps, math.inf)
if distance is not None and clear:
c = _clearance(m, ram, barrel, p, distance, spacing)
margin, f.clear_at, f.pairs, f.allowed = c.margin, c.where, c.pairs, c.allowed
f.clear_min = float(margin.min())
if f.clear_min < 0.0:
angle, member, part, pin = f.clear_at
f.why.append(("clash", angle, pin, f"{member} is {-f.clear_min:.3f} inside the clearance of part {part!r} ({m.parts[part]})"))
f.table = [tuple(row) for row in np.stack([p.degrees, p.L, p.dL, margin], axis=1).tolist()]
return f
def fit(m, ram, steps=25, distance=None, spacing=None):
"""Check one mechanism from lo to hi. Gates, in order, each over all steps at once: assembly; stroke; effective
arm (one sign, and at least min_arm); coupler pin load (linkages); clearance, when a distance oracle is given
(see clearance: the record's parts say what it meets, its touch how near a pin).
Returns the Fit; a failed gate raises RamError, its `fit` holding the readings."""
f = _fit(m, ram, steps, distance, spacing)
if not f.ok:
raise f.error()
return f
@dataclass
class Search:
best: Fit # the winner, or the nearest miss when none fits
found: bool
tried: int
fits: int # candidates that pass every gate but clearance
tally: dict # gate -> candidates it failed (a candidate can fail several)
seat: dict # the winner's or nearest miss's pins
def report(self):
head = f"{self.fits} of {self.tried} candidates pass the gates before clearance" if self.found else f"no candidate of {self.tried} fits"
reasons = ", ".join(f"{k} {v}" for k, v in sorted(self.tally.items()))
return f"{head}{' (failed: ' + reasons + ')' if reasons else ''}; {'best' if self.found else 'nearest'}: {self.best.report() if self.best else 'none assembles'}"
def _polar(n, centre, toward, radii, step):
"""Points about `centre` across the axis n: each radius, every `step` degrees from the direction `toward`."""
e = _flat(np.asarray(toward, dtype=float) - centre, n)
if np.linalg.norm(e) < 1e-9:
e = _flat(np.array([0.0, 0.0, 1.0]) if abs(n[2]) < 0.9 else np.array([1.0, 0.0, 0.0]), n)
e = e / np.linalg.norm(e)
return [centre + r * _rot(e, n, math.radians(turn)) for r in radii for turn in range(0, 360, step)]
def candidates(kind, hinge, seats):
"""The pins of every candidate of a seat grid. direct: seats['a'] x seats['b']. Linkages: seats['rocker'] x
seats['c'] x p on a polar grid about R (lengths seats['link'] = (lo, hi, n), every 15 degrees) x seats['a'],
and for a bell crank x d on a polar grid about R (seats['d'] = (lo, hi, n), every 30 degrees). The ram's eye
(d, and a four-bar's p) stands at a's place along the axis, so the ram runs across it."""
n = np.asarray(hinge["axis"], dtype=float)
if kind == "direct":
return [{"a": a, "b": b} for a in seats["a"] for b in seats["b"]]
out = []
for R in seats["rocker"]:
R = np.asarray(R, dtype=float)
for c in seats["c"]:
for p in _polar(n, R, c, np.linspace(*seats["link"]), 15):
eyes = [p] if kind == "four_bar" else _polar(n, R, p, np.linspace(*seats["d"]), 30)
for a in seats["a"]:
a = np.asarray(a, dtype=float)
for d in eyes:
d = d - n * ((d - a) @ n)
out.append({"a": a, "rocker": R, "p": d if kind == "four_bar" else p, "c": c, "d": d})
return out
def search(kind, hinge, ram, seats, world=None, limit=20000, steps=25, spacing=None):
"""Seat a mechanism from a grid (see candidates). hinge = {pivot, axis, lo, hi, offsets (optional)}. Best
first: every gate but clearance over all candidates, then clearance in order of least arm, greatest first;
the first clear one wins. world(m) -> (parts, touch, distance) builds a candidate's own parts, the brackets
and links its pins place among them, and the oracle that answers for them: a linkage's links are the
candidate's, so no one oracle serves a grid. What it returns is read as a record's: anything but the three,
a part on no body of the kind, a zone that is not (part, pin the member rides, radius, depth) or one wider or
deeper than its member is refused. A grid past `limit` candidates is refused naming the count. A
miss returns the tally and the nearest miss (the least total shortfall: stroke, arm, load excess,
clearance)."""
pins = candidates(kind, hinge, seats)
if len(pins) > limit:
raise RamError(kind, "search", f"{len(pins)} candidates, over the limit of {limit}: thin the seat grid")
tally, passed, miss = {}, [], None
def missed(f, seat):
nonlocal miss
for gate in {g for g, _, _, _ in f.why}:
tally[gate] = tally.get(gate, 0) + 1
short = (max(-f.spare, 0.0) + max(ram.min_arm - f.arm_min, 0.0) + (ram.min_arm if f.arm_sign == 0 else 0.0)
+ max(f.load_max - ram.max_load, 0.0) + (max(-f.clear_min, 0.0) if f.clear_min < math.inf else 0.0))
if miss is None or short < miss[0]:
miss = (short, f, seat)
for seat in pins:
try:
m = Mechanism(kind, hinge["pivot"], hinge["axis"], hinge["lo"], hinge["hi"], offsets=hinge.get("offsets", (0.0,)), **seat)
f = _fit(m, ram, steps, clear=False)
except RamError as refusal:
tally[refusal.gate] = tally.get(refusal.gate, 0) + 1
continue
if f.ok:
passed.append((f, seat))
else:
missed(f, seat)
passed.sort(key=lambda entry: -entry[0].arm_min)
for f, seat in passed:
if world is None:
return Search(f, True, len(pins), len(passed), tally, seat)
made = world(f.m)
if not isinstance(made, tuple) or len(made) != 3 or not callable(made[2]):
raise RamError(kind, "search", f"world(m) returns (parts, touch, distance), got {type(made).__name__}")
parts, touch, distance = made
f = _fit(replace(f.m, parts=parts, touch=touch), ram, steps, distance, spacing)
if f.ok:
return Search(f, True, len(pins), len(passed), tally, seat)
missed(f, seat)
return Search(miss[1] if miss else None, False, len(pins), len(passed), tally, miss[2] if miss else None)
def record(m, ram):
"""The mechanism record: plain JSON types, everything a rig or runtime needs to drive the ram from the hinge
angle (from_record, then length or extension). It holds what is authored and nothing derived from it: barrel,
closed length and link lengths come from the pins and the ram. `compliance` is reserved for a load-path ram's
settle (COMPLIANCE: stiffness, damping, travel); version 1 writes it null and solves none."""
return {"schema": SCHEMA, "version": VERSION, "kind": m.kind,
"hinge": {"pivot": m.pivot.tolist(), "axis": m.axis.tolist(), "lo": m.lo, "hi": m.hi},
"pins": {name: getattr(m, name).tolist() for name in PINS[m.kind]}, "offsets": list(m.offsets),
"ram": {f.name: getattr(ram, f.name) for f in fields(Ram)},
"parts": dict(m.parts), "compliance": None,
"touch": {member: [dict(zip(ZONE, zone)) for zone in zones] for member, zones in m.touch.items()}}
def from_record(data):
"""(Mechanism, Ram) of a record. A record of another schema or version (the integer 1: not 1.0, not true), with
a key this version does not know or without one it does, with a compliance block, or with a value that is not
its field's type (a finite number, three of them, a name), or with a zone wider or deeper than its member is
refused whole, as a RamError naming the field: nothing is read past and dropped."""
if not isinstance(data, dict):
raise RamError("None", "record", f"a record is an object, got {type(data).__name__}")
kind, version = str(data.get("kind")), data.get("version")
if data.get("schema") != SCHEMA or type(version) is not int or version != VERSION:
raise RamError(kind, "record", f"this reader reads {SCHEMA} version {VERSION}; the record is {data.get('schema')} version {version!r}")
if kind not in KINDS:
raise RamError(kind, "record", f"kind is one of {', '.join(KINDS)}")
def keys(name, given, known):
if not isinstance(given, dict):
raise RamError(kind, "record", f"an object, got {type(given).__name__}", pin=name)
if set(given) != set(known):
raise RamError(kind, "record", f"the {name}'s keys are not version {VERSION}'s: unknown {sorted(set(given) - set(known), key=str)}, missing {sorted(set(known) - set(given))}")
def point(name, value):
if not isinstance(value, list) or len(value) != 3:
raise RamError(kind, "record", f"three finite numbers, got {value!r}", pin=name)
return [_number(kind, name, x) for x in value]
keys("record", data, ("schema", "version", "kind", "hinge", "pins", "offsets", "ram", "parts", "touch", "compliance"))
hinge, pins, ram = data["hinge"], data["pins"], data["ram"]
keys("hinge", hinge, ("pivot", "axis", "lo", "hi"))
keys("pins", pins, PINS[kind])
keys("ram", ram, [f.name for f in fields(Ram)])
if data["compliance"] is not None:
raise RamError(kind, "record", f"a compliance block ({', '.join(COMPLIANCE)}) is a later version's: version {VERSION} solves none and will not drop it")
for name, value in ram.items():
_number(kind, name, value, 0.0 if name == "bore" else None)
if not isinstance(data["offsets"], list):
raise RamError(kind, "record", f"a list of numbers, got {data['offsets']!r}", pin="offsets")
if not isinstance(data["parts"], dict) or not all(isinstance(body, str) for body in data["parts"].values()):
raise RamError(kind, "record", "an object of part: body", pin="parts")
if not isinstance(data["touch"], dict):
raise RamError(kind, "record", "an object of member: zones", pin="touch")
touch = {}
for member, zones in data["touch"].items():
if not isinstance(zones, list):
raise RamError(kind, "record", f"{member}'s zones are a list, got {zones!r}", pin="touch")
for zone in zones:
keys(f"{member} zone", zone, ZONE)
touch[member] = [tuple(zone[key] for key in ZONE) for zone in zones]
m = Mechanism(kind, point("pivot", hinge["pivot"]), point("axis", hinge["axis"]), _number(kind, "lo", hinge["lo"]), _number(kind, "hi", hinge["hi"]),
offsets=tuple(_number(kind, "offsets", o) for o in data["offsets"]), parts=data["parts"], touch=touch,
**{name: point(name, value) for name, value in pins.items()})
ram = Ram(**ram)
_eyes(m, ram)
return m, ram
def swept(f, body, margin=0.0, steps=13, around=8):
"""Points on the swept ram's surface in a body's rest frame, the barrel radius grown by `margin`, a trunnion's
tail included: what a recess in that body must clear (their hull or bounding box)."""
m, ram = f.m, f.ram
if body not in BODIES[m.kind]:
raise RamError(m.kind, "swept", f"no body {body!r}; this kind has {', '.join(BODIES[m.kind])}")
p = pose(m, np.linspace(m.lo, m.hi, steps))
side = np.cross(p.u, m.axis)
side = side / np.linalg.norm(side, axis=1)[:, None]
up = np.cross(side, p.u)
turn = np.linspace(0.0, 2.0 * math.pi, around, endpoint=False)
ring = (ram.barrel_r + margin) * (np.cos(turn)[None, :, None] * side[:, None, :] + np.sin(turn)[None, :, None] * up[:, None, :])
pts = []
for off in m.offsets:
for centre in (p.base + off * m.axis + p.u * min(ram.back, 0.0), p.eye + off * m.axis):
pts.append(centre[:, None, :] + ring)
return _into(m, p, body, np.concatenate(pts, axis=1)).reshape(-1, 3)
class Signed:
"""The distance oracle over closed meshes: distance(part, points) is the nearest face's distance, negative
where the point is inside one of the part's shells (its depth below the nearest face), capped at `cap` outside
only. shells: part -> [(vertices (N, 3), faces)], each shell closed, in the rest frame of the part's body.
Inside is the crossing parity of `rays` of RAYS, by majority: one ray that runs through an edge or a vertex
miscounts, and a sample then reads inside a plate it stands clear of. An unknown part raises. Needs Blender's
mathutils (BVHTree)."""
def __init__(self, shells, cap=None, rays=3):
from mathutils import Vector
from mathutils.bvhtree import BVHTree
self.cap, self.asked, self.vector = cap, 0, Vector
self.rays = [Vector(ray).normalized() for ray in RAYS[:rays]]
self.trees = {part: [(BVHTree.FromPolygons(np.asarray(v, dtype=float).tolist(), [tuple(face) for face in f], epsilon=0.0),
np.min(v, axis=0), np.max(v, axis=0)) for v, f in made] for part, made in shells.items()}
@staticmethod
def crossings(tree, v, ray):
count, o = 0, v
for _ in range(64):
loc = tree.ray_cast(o, ray)[0]
if loc is None:
break
count, o = count + 1, loc + ray * 1e-6
return count
def inside(self, tree, v):
return 2 * sum(self.crossings(tree, v, ray) % 2 for ray in self.rays) > len(self.rays)
def __call__(self, part, pts):
pts = np.asarray(pts, dtype=float)
self.asked += len(pts)
out = np.full(len(pts), math.inf if self.cap is None else self.cap)
for tree, lo, hi in self.trees[part]:
boxed = ((pts >= lo) & (pts <= hi)).all(axis=1)
for i, p in enumerate(pts):
v = self.vector(p)
if boxed[i] and self.inside(tree, v):
out[i] = min(out[i], -tree.find_nearest(v)[3])
continue
hit = tree.find_nearest(v, self.cap) if self.cap else tree.find_nearest(v)
if hit[0] is not None and hit[3] < out[i]:
out[i] = hit[3]
return out

View file

@ -0,0 +1,656 @@
"""The path of a hose: from waypoints and a distance oracle to a curve with frames. numpy only, tested without
Blender (tests/test_route.py); brokkr_kitbash.hose is the bpy around it (docs/kitbash.md, Hoses between sockets).
A `distance` is a callable over (N, 3) points that answers how far each stands from the nearest obstacle; the caller
owns what an obstacle is and may cap the answer. `need` is how far a hose's centre line must stay from every
obstacle: the bundle's half width plus its clearance.
A leg between two waypoints is searched on a voxel grid of the box around them (grid, wavefront), then pulled taut
(pull). That polyline is a seed and no more: where its vertices stand follows the grid's lattice, so whether its
corners have straight enough for their bends does too. relax then moves, drops and adds vertices in continuous
space until every segment has the straight its corners' tangents take at the floor radius (strain), each move kept
only if the oracle proves its segments clear; tangents gives every corner its floor's tangent before any corner gets
more. leaves is the one proof of a bundle too stiff: a curve that bends no tighter than the floor cannot get out of
what stands about the end of a fitting's lead. A voxel is free when it stands need plus half a voxel's diagonal from every obstacle: distance changes by at
most the distance moved, so every point of a step between two neighbouring free voxels keeps need. The same bound is
what every measurement of a line rests on (measure): a reading answers for the piece around it, less half the piece's
length, and pieces are halved until that proves need, so nothing thinner than the spacing of some samples can stand
unseen between them; no measurement depends on the search's step. The legs joined are one polyline; fillet rounds its
corners, each by the largest arc its measured room allows, and verify measures the curve. sag lowers the middle of a leg
by what its room allows. passes turns the part of a polyline beyond a point on a pin's axis through the pin's rolls,
each roll answering for the rolls about it by what a point can move within them. frames gives the rotation-minimising ups the tubes are swept
with (Wang, Juettler, Zheng and Liu, "Computation of rotation minimizing frames", ACM TOG 27(1), 2008: the double
reflection method).
Every refusal is a RouteError that names the leg, corner, point or roll.
"""
from __future__ import annotations
import math
from typing import NamedTuple
import numpy as np
class RouteError(ValueError):
"""A route that cannot be made, in words that name where."""
class Blocked(RouteError):
"""A refusal that rests on where a waypoint stands, not on a search: no other grid lifts it."""
NEIGHBOURS = [(i, j, k) for i in (-1, 0, 1) for j in (-1, 0, 1) for k in (-1, 0, 1) if (i, j, k) != (0, 0, 0)]
REACH = math.sqrt(3.0) / 2.0 # of a voxel: how far a point of a step between two neighbouring voxels can stand from the nearer one
STRAIGHT = 1e-9 # radians: a corner that turns less is no corner
HELD = 1e-9 # metres under need that a reading may stand and hold it
FINE = 1e-3 # metres: the shortest piece measure halves to; a line must keep need by half of this to be proven
BEND = 1.0 - math.cos(math.pi / 4.0) # of a radius: how far the arc of a quarter turn stands from its tangent segments
ARC = 24 # arc segments a radian of turn
STIFF = math.radians(170.0) # a turn past this is priced as this one: its tangent at the floor is already 11 floors long
AXES = [np.array(v, dtype=np.float64) for v in ((1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1))]
def spot(point) -> str:
return "[" + ", ".join(f"{float(v):.4g}" for v in point) + "]"
def bundle(count: int, radius: float, spread: float, clearance: float, bend: float) -> dict:
"""The sizes a bundle of `count` hoses of `radius` routes by. spread is centre to centre (0: 2.6 radii). width is
across the bundle; envelope its half; need is how far the centre line stays from obstacles; floor the least
radius of the centre line, bend outside diameters for the innermost hose, which runs half the bundle's spread
inside it; lead the straight a fitting keeps: a ferrule of 5 radii, then 1.5 outside diameters before any bend."""
spread = spread if spread > 0.0 else 2.6 * radius
half = (count - 1) / 2.0 * spread
return {"spread": spread, "width": 2.0 * half + 2.0 * radius, "envelope": half + radius, "need": half + radius + clearance,
"floor": bend * 2.0 * radius + half, "lead": 5.0 * radius + 1.5 * 2.0 * radius}
class Grid(NamedTuple):
"""Voxels of a box: free[i, j, k] is the voxel centred at lo + step * (i, j, k)."""
free: np.ndarray
lo: np.ndarray
step: float
def grid(lo, hi, step: float, distance, need: float, limit: int = 2 ** 19) -> Grid:
"""The voxels of the box lo..hi at `step` that stand at least `need` from every obstacle. Refuses a box of more
than `limit` voxels, naming a step that fits."""
lo, hi = np.asarray(lo, dtype=np.float64), np.asarray(hi, dtype=np.float64)
shape = lambda s: np.maximum(1, np.ceil((hi - lo) / s - 1e-9).astype(np.int64) + 1) # noqa: E731
n = shape(step)
if int(n.prod()) > limit:
fits = step
while int(shape(fits).prod()) > limit:
fits *= 1.05
raise RouteError(f"its search box of {spot(hi - lo)} m is {int(n.prod())} voxels at step {step:g}, over {limit}: a step of {math.ceil(fits * 1e4) / 1e4:g} fits")
axes = [lo[i] + step * np.arange(n[i]) for i in range(3)]
points = np.stack(np.meshgrid(*axes, indexing="ij"), axis=-1).reshape(-1, 3)
return Grid(free=(np.asarray(distance(points)) >= need).reshape(n), lo=lo, step=float(step))
def _grow(front: np.ndarray) -> np.ndarray:
"""The 26 neighbours of a front's voxels, by array shifts."""
n, padded, grown = front.shape, np.pad(front, 1), np.zeros(front.shape, dtype=bool)
for i, j, k in NEIGHBOURS:
grown |= padded[1 + i:1 + i + n[0], 1 + j:1 + j + n[1], 1 + k:1 + k + n[2]]
return grown
def wavefront(free: np.ndarray, start, goal) -> list:
"""The voxels of a shortest 26-connected way from start to goal through free voxels, both ends included: a
wavefront grown from the goal by array shifts, then walked down from the start, at each step to the neighbour one
wave nearer that stands nearest the goal. Refuses an end that is not free, and a start no wave reaches."""
start, goal, n = tuple(int(v) for v in start), tuple(int(v) for v in goal), free.shape
for name, voxel in (("start", start), ("end", goal)):
if not free[voxel]:
raise RouteError(f"its {name} voxel is not free")
unreached = np.iinfo(np.int32).max
waves = np.full(n, unreached, dtype=np.int32)
waves[goal] = 0
front = np.zeros(n, dtype=bool)
front[goal] = True
wave = 0
while waves[start] == unreached and front.any():
wave += 1
front = _grow(front) & free & (waves == unreached)
waves[front] = wave
if waves[start] == unreached:
raise RouteError("no free way joins its ends: obstacles close every way through its search box")
way, at = [start], start
while waves[at] > 0:
nearer = [(math.dist(m, goal), m) for m in ((at[0] + i, at[1] + j, at[2] + k) for i, j, k in NEIGHBOURS)
if all(0 <= m[axis] < n[axis] for axis in range(3)) and waves[m] == waves[at] - 1]
at = min(nearer)[1]
way.append(at)
return way
class Measured(NamedTuple):
least: float # the least reading taken; of a measure that fell short, the reading that fell short
where: np.ndarray # the point it was taken at
short: bool # a piece is not proven to keep need
def measure(a, b, distance, need: float, rate: float = 1.0, within: float | None = None) -> Measured:
"""The segments a[i]..b[i] measured so that what stands between two readings is bounded, not sampled. A piece's
middle reads d, and a reading changes by at most `rate` times the distance moved (1 for a distance to obstacles),
so every point of a piece of length L reads at least d - rate x L / 2. A piece whose bound holds need is proven;
one whose middle reads under need falls short; any other is halved, down to FINE, where a piece still unproven
falls short too: a measure that is not short has proven need of every point, and a line that keeps need by under
rate x FINE / 2 is refused with the ones that do not keep it. With `within`, pieces are halved further until each
one's bound is within that much of the least reading (or the piece is FINE long): least less `within` then bounds
every point from below."""
a, b = np.atleast_2d(np.asarray(a, dtype=np.float64)), np.atleast_2d(np.asarray(b, dtype=np.float64))
least, where = math.inf, None
while len(a):
middle, length = (a + b) / 2.0, np.linalg.norm(b - a, axis=1)
reads = np.asarray(distance(middle), dtype=np.float64)
bound = reads - rate * length / 2.0
unproven = bound < need - HELD
short = np.flatnonzero(unproven & ((reads < need - HELD) | (length <= FINE)))
if len(short):
worst = int(short[np.argmin(reads[short])])
return Measured(float(reads[worst]), middle[worst], True)
if reads.min() < least:
least, where = float(reads.min()), middle[int(np.argmin(reads))]
again = unproven if within is None else unproven | ((bound < least - within) & (length > FINE))
a, b = np.concatenate([a[again], middle[again]]), np.concatenate([middle[again], b[again]])
return Measured(least, where, False)
def falls(reading: float, need: float) -> str:
"""How a reading that fell short of need reads in a refusal."""
return (f"under the {need:.4g} m the bundle needs" if reading < need - HELD else
f"too near the {need:.4g} m the bundle needs to prove it of what stands between two readings")
def clear(a, b, distance, need: float, rate: float = 1.0) -> bool:
return not measure(a, b, distance, need, rate).short
def room(a, b, distance, need: float) -> float:
"""What every point of the segment a..b stands beyond need, less what verify needs to prove an arc that uses it
all: the least reading of a measure within FINE, less FINE for its bound and half of FINE more."""
return measure(a, b, distance, -math.inf, within=FINE).least - need - 1.5 * FINE
def span(curve, low: float, high: float) -> np.ndarray:
"""The part of a polyline between two lengths along it; no point when low is not under high."""
curve = np.asarray(curve, dtype=np.float64)
s = np.r_[0.0, np.cumsum(np.linalg.norm(np.diff(curve, axis=0), axis=1))]
low, high = max(low, 0.0), min(high, float(s[-1]))
if not low < high:
return curve[:0]
ends = np.stack([np.interp((low, high), s, curve[:, axis]) for axis in range(3)], axis=1)
return np.vstack([ends[:1], curve[(s > low) & (s < high)], ends[1:]])
def pull(points, distance, need: float, rate: float = 1.0) -> np.ndarray:
"""A polyline pulled taut: from each kept point, the farthest later point in clear sight (the line between them
swept at need); the next point when none is."""
points = np.asarray(points, dtype=np.float64)
kept, i = [points[0]], 0
while i < len(points) - 1:
j = len(points) - 1
while j > i + 1 and not clear(points[i], points[j], distance, need, rate):
j -= 1
kept.append(points[j])
i = j
return np.array(kept)
def leg(a, b, occupancy, distance, need: float, step: float, margin: float, limit: int, name: str, pad: float = 0.0, offset=(0.0, 0.0, 0.0)):
"""(the pulled polyline from a to b, the voxels searched): a grid over the two ends' box plus margin, free where
`occupancy` reads need plus pad plus REACH of a voxel, a wavefront between the free voxels beside the ends, pulled
against `distance`. `pad` is room kept beyond need for the bends the leg's corners will get: a line pulled at
need alone grazes what it wraps, and the corner there has no room for an arc. Within twice pad of an end the pull
asks for half the distance from that end instead, since an end stands where it is given. `offset`, in steps along
each axis, moves the lattice's origin: the polyline is a seed whose vertices follow the lattice, and another origin
gives another seed. Refuses, naming the leg: an end nearer an obstacle than need (Blocked: no grid lifts that), an
end with no free voxel in sight beside it, a box over the limit, and no way through."""
a, b = np.asarray(a, dtype=np.float64), np.asarray(b, dtype=np.float64)
for label, point in (("start", a), ("end", b)):
reads = float(np.asarray(distance(point[None]))[0])
if reads < need - HELD:
raise Blocked(f"{name}: its {label} {spot(point)} stands {reads:.4g} m from an obstacle, under the {need:.4g} m the bundle needs")
try:
cells = grid(np.minimum(a, b) - margin - step * np.asarray(offset, dtype=np.float64), np.maximum(a, b) + margin, step, occupancy, need + pad + REACH * step, limit)
except RouteError as error:
raise RouteError(f"{name}: {error}") from None
ends = []
for label, point in (("start", a), ("end", b)):
middle = np.clip(np.round((point - cells.lo) / step).astype(int), 0, np.array(cells.free.shape) - 1)
beside = [tuple(int(v) for v in middle + np.array(d)) for d in [(0, 0, 0)] + NEIGHBOURS]
beside = [m for m in beside if all(0 <= m[axis] < cells.free.shape[axis] for axis in range(3)) and cells.free[m]]
beside.sort(key=lambda m: float(np.linalg.norm(cells.lo + step * np.array(m) - point)))
seen = [m for m in beside if clear(point, cells.lo + step * np.array(m), distance, need)]
if not seen:
raise RouteError(f"{name}: no free voxel stands in sight of its {label} {spot(point)}: an obstacle is nearer it than {need + pad + REACH * step:.4g} m on every side")
ends.append(seen[0])
try:
way = wavefront(cells.free, ends[0], ends[1])
except RouteError as error:
raise RouteError(f"{name}: {error}") from None
padded = distance if pad <= 0.0 else lambda p: np.asarray(distance(p)) - np.minimum(pad, 0.5 * np.minimum(np.linalg.norm(p - a, axis=1), np.linalg.norm(p - b, axis=1)))
return pull(np.vstack([a[None], cells.lo + step * np.array(way, dtype=np.float64), b[None]]), padded, need, 1.0 if pad <= 0.0 else 1.5), int(cells.free.size)
def sag(points, depth: float, room, down=(0.0, 0.0, -1.0)):
"""(the polyline, the metres it was lowered): the middle of a leg's longest segment lowered by `depth`, less where
the segment runs along `down` (a hanging span sags, a vertical one does not) and never by more than half the room
`room(a, b)` measures along that segment: both halves then stand within that much of the taut segment, so they keep
need with as much room again for the arc at the middle. A segment shorter than 8 times the drop is left taut."""
points = np.asarray(points, dtype=np.float64)
lengths = np.linalg.norm(np.diff(points, axis=0), axis=1)
i = int(np.argmax(lengths))
a, b = points[i], points[i + 1]
across = np.asarray(down, dtype=np.float64) - (b - a) / lengths[i] * float(np.asarray(down) @ (b - a) / lengths[i])
hang = float(np.linalg.norm(across))
if depth <= 0.0 or hang < 1e-6:
return points, 0.0
drop = min(depth, 0.5 * (math.inf if room is None else float(room(a, b)))) * hang
if drop <= 1e-6 or lengths[i] < 8.0 * drop:
return points, 0.0
return np.vstack([points[:i + 1], ((a + b) / 2.0 + across / hang * drop)[None], points[i + 1:]]), drop
def _turns(points):
steps = np.diff(points, axis=0)
lengths = np.linalg.norm(steps, axis=1)
if (lengths < 1e-9).any():
raise RouteError(f"point {int(np.argmax(lengths < 1e-9))} {spot(points[int(np.argmax(lengths < 1e-9))])}: the segment from it is shorter than 1e-9")
unit = steps / lengths[:, None]
return lengths, unit, np.arccos(np.clip(np.einsum("ij,ij->i", unit[:-1], unit[1:]), -1.0, 1.0))
def _kept(count: int, lead: float, keep) -> np.ndarray:
keep = np.zeros(count) if keep is None else np.array(keep, dtype=np.float64)
keep[0] += lead
keep[-1] += lead
return keep
def _radius(point, before, after, turn: float, cap: float, room) -> float:
"""The largest radius of the arc at a corner whose tangent lengths stay within cap and whose room allows it: the
arc stands within radius x (1 - cos(turn / 2)) of its two tangent segments, so with that much room beyond need
measured along them it keeps need (the triangle inequality). The tangent segments grow with the radius, so the
room can only shrink: the largest radius is found by bisection."""
most = max(cap, 0.0) / math.tan(turn / 2.0)
if room is None:
return most
depth = 1.0 - math.cos(turn / 2.0)
def fits(radius: float) -> bool:
t = radius * math.tan(turn / 2.0)
return radius * depth <= min(room(point - before * t, point), room(point, point + after * t))
if fits(most):
return most
low, high = 0.0, most
for _ in range(24):
middle = (low + high) / 2.0
low, high = (middle, high) if fits(middle) else (low, middle)
return low
def _straights(lengths, lead: float, keep, centred):
"""(free, each, centred) of a polyline's segments: the straight a segment has to give its corners' tangents (its
length less what it keeps: `keep`, and `lead` more on the first and last), and what one end of it may take: all of
it, or half on a centred segment, whose kept straight stays in its middle."""
free = np.maximum(lengths - _kept(len(lengths), lead, keep), 0.0)
centred = np.zeros(len(lengths), dtype=bool) if centred is None else np.asarray(centred, dtype=bool)
return free, np.where(centred, free / 2.0, free), centred
def _floors(turn, floor: float, least) -> np.ndarray:
"""The tangent length each corner needs: its turn's at the floor radius, and `least` where that is more (a corner
that will turn further than it does here: the one at a pin)."""
need = floor * np.tan(np.minimum(turn, STIFF) / 2.0)
return need if least is None else np.maximum(need, np.asarray(least, dtype=np.float64))
def tangents(points, room, lead: float, keep=None, centred=None, floor: float = 0.0, least=None) -> np.ndarray:
"""The tangent length of the arc at each interior point of a polyline (0 where it runs straight on). Each corner
first gets the largest radius its room allows (_radius) within the straight its two segments have to give
(_straights). Where two corners' tangents overlap on a segment, each keeps what it needs (_floors: its tangent at
`floor`, or `least`) and what the segment has beyond that is shared in proportion to what each asked beyond its
need; a corner holds its `least` of a segment even where its arc here is shorter. Where the two needs do not fit
the segment both shrink in proportion, and fillet refuses the corner."""
points = np.asarray(points, dtype=np.float64)
lengths, unit, turn = _turns(points)
free, each, _ = _straights(lengths, lead, keep, centred)
t = np.zeros(len(turn))
for c in np.flatnonzero(turn >= STRAIGHT):
t[c] = _radius(points[c + 1], unit[c], unit[c + 1], float(turn[c]), float(min(each[c], each[c + 1])), room) * math.tan(turn[c] / 2.0)
need = _floors(turn, floor, least)
claim = np.maximum(t, need)
held = claim.copy()
for s in range(1, len(lengths) - 1): # segment s, between corners s - 1 and s
both, needs = claim[s - 1] + claim[s], need[s - 1] + need[s]
if both > free[s]:
for c in (s - 1, s):
held[c] = min(held[c], need[c] + (claim[c] - need[c]) * (free[s] - needs) / (both - needs) if needs <= free[s] else claim[c] * free[s] / both)
return np.minimum(t, held)
def strain(points, floor: float, lead: float, keep=None, centred=None, least=None) -> np.ndarray:
"""For each segment of a polyline, the straight its corners' tangents take at the floor radius beyond what the
segment has to give (_straights, _floors); all 0 where every corner has the straight for its bend. What fillet
refuses for want of straight, as lengths relax can lower."""
lengths, _, turn = _turns(np.asarray(points, dtype=np.float64))
free, each, centred = _straights(lengths, lead, keep, centred)
need = _floors(turn, floor, least)
first, last = np.r_[0.0, need], np.r_[need, 0.0] # of the corner a segment starts at, and the one it ends at
return np.where(centred, np.maximum(first - each, 0.0) + np.maximum(last - each, 0.0), np.maximum(first + last - free, 0.0))
def relax(points, tags, cost, clear, reach: float, rounds: int = 64):
"""(points, tags) of a polyline refined in continuous space until `cost(points, tags)`, an amount for each
segment, is all 0 or nothing tried lowers its sum. A vertex whose tag is None is free; the others stay. Each round
tries, about the segments that cost: a free vertex dropped; a free vertex moved by a length (first `reach`) along
each axis and along its two segments; and a vertex added at a segment's middle, moved that length along an axis.
The try that lowers the sum most among those whose changed segments `clear(a, b)` proves is kept; with none, the
length is halved, down to FINE. The oracle alone says what is clear: no lattice is read."""
points, tags = np.asarray(points, dtype=np.float64), list(tags)
def price(p, g):
try:
return float(np.sum(cost(p, g)))
except RouteError: # two vertices on one point
return math.inf
now, delta, most = price(points, tags), float(reach), len(points) + 4
for _ in range(rounds):
if not 0.0 < now < math.inf or delta < FINE:
break
strained = np.flatnonzero(np.asarray(cost(points, tags)) > 0.0)
tries = []
for v in sorted({v for s in strained for v in range(s - 1, s + 3) if 0 < v < len(points) - 1 and tags[v] is None}):
tries.append((np.delete(points, v, axis=0), tags[:v] + tags[v + 1:], (v - 1,)))
along = [(points[v + side] - points[v]) / max(float(np.linalg.norm(points[v + side] - points[v])), 1e-12) for side in (-1, 1)]
for way in AXES + along + [-d for d in along]:
moved = points.copy()
moved[v] += delta * way
tries.append((moved, tags, (v - 1, v)))
if len(points) < most:
for s in sorted({q for s in strained for q in (s - 1, s, s + 1) if 0 <= q < len(points) - 1}):
for way in AXES:
tries.append((np.insert(points, s + 1, (points[s] + points[s + 1]) / 2.0 + delta * way, axis=0), tags[:s + 1] + [None] + tags[s + 1:], (s, s + 1)))
priced = sorted(((price(p, g), index) for index, (p, g, _) in enumerate(tries)), key=lambda row: row[0])
for value, index in priced:
if not value < now - 1e-12:
delta /= 2.0
break
p, g, changed = tries[index]
if all(clear(p[q], p[q + 1]) for q in changed):
now, points, tags = value, p, g
break
else:
delta /= 2.0
return points, tags
def leaves(point, heading, floor: float, distance, need: float, cells: int = 6) -> bool:
"""Whether a curve that bends no tighter than `floor` and keeps need can get 2 floors away from `point`, which it
leaves along `heading`. False is a proof that none can: the bundle is too stiff for the room there.
Until such a curve is pi floors long it stays out of every ball of radius floor that touches its line at the
point and never falls behind the point (it has gone floor x sin(length / floor) along its heading), and by then
it stands at least 2 floors from the point (Schwarz's bound on a curve's chord; Dubins, "On curves of minimal
length with a constraint on average curvature", Amer. J. Math. 79, 1957). So it reaches the sphere of 2 floors
through points that keep need, stand outside those balls and are not behind the point. On voxels of floor / cells
a voxel is open unless its centre reads under need less REACH of a voxel, or stands more than that inside the
balls or behind the point: every point of such a curve then lies in an open voxel, and neighbouring points in neighbouring voxels.
When no open voxel on the sphere is joined to the point's, no curve exists; the grid sets how often the proof is
found, never whether it is true."""
point, heading = np.asarray(point, dtype=np.float64), np.asarray(heading, dtype=np.float64) / np.linalg.norm(heading)
step, n = floor / cells, 4 * cells + 3 # 2 floors and a voxel each way
axis = step * (np.arange(n) - (n - 1) / 2.0)
offsets = np.stack(np.meshgrid(axis, axis, axis, indexing="ij"), axis=-1).reshape(-1, 3)
along = offsets @ heading
inside = floor - np.sqrt((np.linalg.norm(offsets - along[:, None] * heading, axis=1) - floor) ** 2 + along ** 2)
opened = ((np.asarray(distance(point + offsets)) >= need - REACH * step) & (inside <= REACH * step) & (along >= -REACH * step)).reshape(n, n, n)
reached = np.zeros((n, n, n), dtype=bool)
reached[(n - 1) // 2, (n - 1) // 2, (n - 1) // 2] = True
while True:
front = _grow(reached) & opened & ~reached
if not front.any():
break
reached |= front
return bool((reached.reshape(-1) & (np.linalg.norm(offsets, axis=1) >= 2.0 * floor - REACH * step)).any())
def arcs(points, t):
"""(curve, owner): the polyline with the arc of tangent length t[c] at each interior point c + 1, as points
ARC to the radian, and for each curve point the corner whose arc it is on (-1 on the straights' ends). Every arc
is tangent to both its segments."""
points = np.asarray(points, dtype=np.float64)
_, unit, turn = _turns(points)
curve, owner = [points[0]], [-1]
for c in range(len(turn)):
corner, before, after = points[c + 1], unit[c], unit[c + 1]
if turn[c] < STRAIGHT or t[c] < 1e-9:
curve.append(corner)
owner.append(c)
continue
radius = t[c] / math.tan(turn[c] / 2.0)
inward = after - before * float(before @ after)
inward /= np.linalg.norm(inward)
centre = corner - before * t[c] + inward * radius
for angle in np.linspace(0.0, turn[c], max(2, int(math.ceil(turn[c] * ARC))) + 1):
curve.append(centre + radius * (before * math.sin(angle) - inward * math.cos(angle)))
owner.append(c)
curve.append(points[-1])
owner.append(-1)
curve, owner = np.array(curve), np.array(owner)
keep = np.r_[True, np.linalg.norm(np.diff(curve, axis=0), axis=1) > 1e-9]
return curve[keep], owner[keep]
class Filleted(NamedTuple):
curve: np.ndarray # (N, 3)
owner: np.ndarray # (N,) the corner a curve point's arc belongs to, -1 off the arcs
t: np.ndarray # tangent length at each interior point of the polyline
radii: np.ndarray # radius at each interior point, inf where the polyline runs straight on
def fillet(polyline, room, floor: float, lead: float, keep=None, centred=None, least=None) -> Filleted:
"""A polyline with its corners rounded (tangents, arcs). `room(a, b)` is the least obstacle distance along the
segment a..b less need, or None where nothing stands near. `least` is the tangent length a corner holds of its
segments whatever it turns here. Refuses a corner whose radius is under `floor`, naming the corner, its point, the
radius it got, the floor and what this polyline lacks there: it speaks of this polyline, not of every route."""
polyline = np.asarray(polyline, dtype=np.float64)
if len(polyline) < 3:
return Filleted(polyline, np.full(len(polyline), -1), np.zeros(0), np.zeros(0))
t = tangents(polyline, room, lead, keep, centred, floor, least)
turn = _turns(polyline)[2]
radii = np.where(turn >= STRAIGHT, t / np.tan(np.maximum(turn, STRAIGHT) / 2.0), np.inf)
under = np.flatnonzero(radii < floor * (1.0 - 1e-9))
if len(under):
c = int(under[np.argmin(radii[under])])
lengths, unit, _ = _turns(polyline)
each = _straights(lengths, lead, keep, centred)[1]
straight, tangent, depth = float(min(each[c], each[c + 1])), floor * math.tan(turn[c] / 2.0), floor * (1.0 - math.cos(turn[c] / 2.0))
if straight < tangent:
why = (f"the corner's segments leave {straight:.4g} m of straight for the {tangent:.4g} m its tangent takes at the floor "
"(a lower bend, thinner hoses, or ends, clamps and the pin point further apart)")
elif room is not None and _radius(polyline[c + 1], unit[c], unit[c + 1], float(turn[c]), straight, room) < floor * (1.0 - 1e-9):
stands = min(room(polyline[c + 1] - unit[c] * tangent, polyline[c + 1]), room(polyline[c + 1], polyline[c + 1] + unit[c + 1] * tangent))
why = (f"the route passes too near an obstacle to bend here: its segments stand {max(stands, 0.0):.4g} m clear beyond what the bundle needs and the arc at the floor takes {depth:.4g} "
"(a lower bend, more room about the obstacle, or a clamp that leads the hose wide of it)")
else:
why = "it shares a segment with the corner beside it and their tangents do not both fit on it (a lower bend, or the two further apart)"
raise RouteError(f"corner {c + 1} at {spot(polyline[c + 1])} turns {math.degrees(turn[c]):.1f} degrees and gets a bend of radius {radii[c]:.4g} m, under the floor {floor:.4g}: {why}")
return Filleted(*arcs(polyline, t), t, radii)
def verify(curve, distance, need: float, lead: float, name: str = "the hose") -> float:
"""The least distance the curve stands from an obstacle outside its two leads (the first and last `lead` of its
length, where it leaves its own ports), within half of FINE (measure). Refuses a curve not proven to keep need at
every point, naming the point."""
curve = np.asarray(curve, dtype=np.float64)
inside = span(curve, lead, float(np.linalg.norm(np.diff(curve, axis=0), axis=1).sum()) - lead)
if len(inside) < 2:
return math.inf
swept = measure(inside[:-1], inside[1:], distance, need, within=FINE / 2.0)
if swept.short:
raise RouteError(f"{name} stands {swept.least:.4g} m from an obstacle at {spot(swept.where)}, {falls(swept.least, need)}")
return swept.least
def thinned(curve, gap: float) -> np.ndarray:
"""A curve without the points that stand within `gap` of the point kept before them; its two ends stay. Where two
arcs meet tangent to tangent they can leave a straight far shorter than a tube is wide between them, and a
section swept over it would fold; with the short straight gone the two arcs meet at one point."""
curve = np.asarray(curve, dtype=np.float64)
kept = [0]
for index in range(1, len(curve)):
if np.linalg.norm(curve[index] - curve[kept[-1]]) > gap:
kept.append(index)
if kept[-1] != len(curve) - 1:
kept[-1 if len(kept) > 1 else len(kept):] = [len(curve) - 1]
return curve[kept]
def frames(curve, up0) -> np.ndarray:
"""An up for each point of a curve, rotation minimising: the first is up0 projected off the tangent, each next the
last reflected twice (Wang et al. 2008), so the ups do not twist about the curve. Tangents are the unit bisectors
core.sweep stands its sections on. Refuses an up0 along the first tangent."""
curve, up = np.asarray(curve, dtype=np.float64), np.asarray(up0, dtype=np.float64)
steps = np.diff(curve, axis=0)
steps = steps / np.linalg.norm(steps, axis=1)[:, None]
tangent = np.vstack([steps[:1], steps[:-1] + steps[1:], steps[-1:]])
tangent /= np.linalg.norm(tangent, axis=1)[:, None]
r = up - tangent[0] * float(up @ tangent[0])
if not np.linalg.norm(r) > 1e-6 * np.linalg.norm(up):
raise RouteError(f"up {spot(up)} runs along the curve's first tangent (or is zero)")
r = r / np.linalg.norm(r)
ups = [r]
for i in range(len(curve) - 1):
v1 = curve[i + 1] - curve[i]
c1 = float(v1 @ v1)
r_left = r - (2.0 / c1) * float(v1 @ r) * v1
t_left = tangent[i] - (2.0 / c1) * float(v1 @ tangent[i]) * v1
v2 = tangent[i + 1] - t_left
c2 = float(v2 @ v2)
r = r_left - (2.0 / c2) * float(v2 @ r_left) * v2 if c2 > 1e-18 else r_left
ups.append(r)
return np.array(ups)
def turned(points, origin, axis, degrees: float) -> np.ndarray:
"""Points turned `degrees` about the line through origin along axis, right-handed."""
axis = np.asarray(axis, dtype=np.float64) / np.linalg.norm(axis)
p = np.asarray(points, dtype=np.float64) - origin
c, s = math.cos(math.radians(degrees)), math.sin(math.radians(degrees))
return origin + p * c + np.cross(axis, p) * s + axis[None] * (p @ axis)[:, None] * (1.0 - c)
def sharpest_turn(before, after, axis, low: float, high: float) -> float:
"""The largest turn, in radians, from the unit `before` to the unit `after` turned about `axis` by any angle of
low..high degrees. The turn's cosine is a + b cos + c sin of the angle, least at one angle of a full turn: the
largest turn is there where the range holds that angle, and at an end of the range where it does not."""
axis = np.asarray(axis, dtype=np.float64) / np.linalg.norm(axis)
along = axis * float(after @ axis)
a, b, c = float(before @ along), float(before @ (after - along)), float(before @ np.cross(axis, after))
worst = math.degrees(math.atan2(-c, -b))
angles = [low, high] + [worst + 360.0 * k for k in range(-2, 3) if low < worst + 360.0 * k < high]
return max(math.acos(max(-1.0, min(1.0, a + b * math.cos(math.radians(v)) + c * math.sin(math.radians(v))))) for v in angles)
def rolls_of(low: float, high: float, step: float) -> list:
"""low, then every step up to high, and high."""
return [float(v) for v in np.arange(low, high - 1e-9, step)] + [float(high)]
def passes(polyline, t, j: int, origin, axis, rolls, finest: float, current: float, parent, child, need: float, floor: float, lead: float, keep=None) -> dict:
"""A hose through a pin's rolls, every roll between the first and last of `rolls` and not those alone. `polyline`
runs from the parent's side through point j, which stands on the pin's axis (origin, axis), to the child's side;
`t` are its tangent lengths at the roll `current`. The points beyond j turn about the axis with the child's parts
and the straights and bends on each side move with their own part; only the corner at j is rounded again.
Each roll of `rolls` answers for a bin: the rolls nearer it than any other. Within a bin of half width w a point
that stands rho from the axis moves at most rho x w against the other side's parts, so its reading against them
counts for that much less (`parent` and `child` read each side's parts where they stand at `current`; samples are
turned back for the child's). The bend at the pin has one radius through a bin, the largest that fits at the bin's
sharpest turn (sharpest_turn, over the bin's rolls): its arc then stands within radius x (1 - cos(turn / 2)) of its two tangent segments, which are swept
for need and that much more. Everything else outside the leads is swept for need (measure). A bin that falls short
is halved and measured at each half's middle, down to `finest` degrees of half width, where it is refused, naming
the roll, the side, the point and the reading; so is a bin whose bend at the pin has no room for the floor.
{rolls: how many were measured, worstRoll, least: the least reading, each less what its point moves within its
bin, lengthChange, radius}."""
polyline, origin = np.asarray(polyline, dtype=np.float64), np.asarray(origin, dtype=np.float64)
axis = np.asarray(axis, dtype=np.float64) / np.linalg.norm(axis)
c, least, lengths, radius = j - 1, (math.inf, None), [], math.inf
off = float(np.linalg.norm(np.cross(polyline[j] - origin, axis)))
if off > 1e-6: # a point counted wrong (a sag's point before it, say) would turn the hose about a point it does not pass
raise RouteError(f"point {j} {spot(polyline[j])} of the hose stands {off:.4g} m off the pin's axis: the hose passes the pin at a point on it")
kept, sharp = _kept(len(polyline) - 1, lead, keep), np.array(t, dtype=np.float64)
sharp[c] = 0.0
rolls = [float(v) for v in rolls]
edges = [rolls[0]] + [(u + v) / 2.0 for u, v in zip(rolls, rolls[1:])] + [rolls[-1]]
bins = [(edges[k + 1], edges[k], roll) for k, roll in reversed(list(enumerate(rolls)))] # a stack: the lowest roll is measured first
while bins:
high, low, roll = bins.pop()
half = max(high - roll, roll - low)
width = math.radians(half)
posed = np.vstack([polyline[:j + 1], turned(polyline[j + 1:], origin, axis, roll - current)])
back = lambda points, roll=roll: turned(points, origin, axis, current - roll) # noqa: E731
moves = lambda points: np.linalg.norm(np.cross(points - origin, axis), axis=1) * width # noqa: E731
sides = {"parent's side": lambda p: np.minimum(np.asarray(parent(p)), np.asarray(child(back(p))) - moves(p)),
"child's side": lambda p: np.minimum(np.asarray(child(back(p))), np.asarray(parent(p)) - moves(p))}
lengths_, unit, turn = _turns(posed)
corner, sharpest = posed[j], min(sharpest_turn(unit[c], unit[c + 1], axis, low - roll, high - roll), math.pi - 1e-6)
cap = min(lengths_[c] - kept[c] - (sharp[c - 1] if c > 0 else 0.0), lengths_[c + 1] - kept[c + 1] - (sharp[c + 1] if c + 1 < len(sharp) else 0.0))
def fits(bend: float):
"""None, or (side, the measure that fell short, the dip) of the bend's two tangent segments at the bin's sharpest turn."""
reach, depth = bend * math.tan(sharpest / 2.0), bend * (1.0 - math.cos(sharpest / 2.0))
for side, a, b in (("parent's side", corner - unit[c] * reach, corner), ("child's side", corner, corner + unit[c + 1] * reach)):
swept = measure(a, b, sides[side], need + depth, 1.0 + width)
if swept.short:
return side, swept, depth
return None
failed, bend, reach = None, math.inf, 0.0
if sharpest >= STRAIGHT:
most = max(cap, 0.0) / math.tan(sharpest / 2.0)
if most < floor * (1.0 - 1e-9):
failed = (f"the bend at the pin turns up to {math.degrees(sharpest):.1f} degrees and its segments leave room for a radius of {most:.4g} m, under the floor {floor:.4g}", None)
else:
short = fits(floor)
if short is not None:
failed = (f"the bend at the pin turns up to {math.degrees(sharpest):.1f} degrees and at the floor radius {floor:.4g} its arc can dip {short[2]:.4g} m; "
f"the hose's {short[0]} beside it", short[1], need + short[2])
else:
bend, high_ = floor, most
for _ in range(12 if fits(most) is not None else 0):
middle = (bend + high_) / 2.0
bend, high_ = (middle, high_) if fits(middle) is None else (bend, middle)
bend = bend if high_ < most else most
reach = bend * math.tan(sharpest / 2.0)
curve, owner = arcs(posed, sharp)
s = np.r_[0.0, np.cumsum(np.linalg.norm(np.diff(curve, axis=0), axis=1))]
at = float(s[np.flatnonzero(owner == c)[0]])
for side, part in (("parent's side", span(curve, lead, at - reach)), ("child's side", span(curve, at + reach, float(s[-1]) - lead))):
if failed is None and len(part) >= 2:
swept = measure(part[:-1], part[1:], sides[side], need, 1.0 + width)
if swept.short:
failed = (f"the hose's {side}", swept, need)
else:
least = min(least, (swept.least, float(roll)))
if failed is None:
radius = min(radius, bend)
lengths.append(float(s[-1]) + (0.0 if not math.isfinite(bend) else bend * (float(turn[c]) - 2.0 * math.tan(float(turn[c]) / 2.0))))
continue
if half > finest and high > low:
bins += [(high, (low + high) / 2.0, (low + 3.0 * high) / 4.0), ((low + high) / 2.0, low, (3.0 * low + high) / 4.0)]
continue
through = f" through the {half:.3g} degrees either side of it" if half > 0.0 else ""
if failed[1] is None:
raise RouteError(f"roll {roll:.4g}: {failed[0]}{through}")
swept, bar = failed[1], failed[2]
raise RouteError(f"roll {roll:.4g}: {failed[0]} reads {swept.least:.4g} m from the parts about the pin at {spot(swept.where)}, counting the {float(moves(swept.where[None])[0]):.4g} m it can move against the other side's{through}: "
f"{falls(swept.least, bar)}")
return {"rolls": len(lengths), "worstRoll": least[1], "least": least[0], "lengthChange": max(lengths) - min(lengths), "radius": radius}

View file

@ -1,4 +1,5 @@
"""Fit a scene to a reference image: the camera a reference view was drawn through, solved from marked points.
"""Fit a scene to a reference image: the camera a reference view was drawn through, solved from marked points,
and traced lines scored against the edges the camera sees on the build.
A host add-on for Brokkr beside brokkr_mesh_polish (it imports that package's operator base, and nothing from
Brokkr): brokkr_actions.json beside this file lists the operators agents may run (docs/reference.md). The
@ -6,14 +7,18 @@ arithmetic is core.py (numpy, tested without Blender); this file is the bpy arou
JSON report to WindowManager.brokkr_mesh_polish_result, as the polish operators do.
The camera record core.solve returns is the truth; a Blender camera stood at it is derived by core.blender, and
core.camera_of reads one back. The images, traces and masks a view is marked on stay with whoever marked them:
this package takes points and gives cameras.
core.camera_of reads one back (flow_score takes the camera that way, by its object's name). The images, traces
and masks a view is marked on stay with whoever marked them: this package takes points and lines and gives
cameras and scores. The edges flow_score reads are computed on each call and kept nowhere.
"""
bl_info = {"name": "Brokkr Reference", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0),
"category": "Camera", "description": "Solve a reference view's camera from marked points; agent-callable through Brokkr."}
import math
import bpy
from mathutils import Matrix
import numpy as np
from mathutils import Matrix, Vector
try:
from brokkr_mesh_polish import RESULT, PolishOperator, Refused
@ -75,7 +80,131 @@ class BROKKR_REFERENCE_OT_solve_camera(PolishOperator):
return report
classes = (BROKKR_REFERENCE_OT_solve_camera,)
def record(context, name, box):
"""The camera record of the scene camera `name` (core.camera_of), the frame being `box` on the image ('' for
the render's own frame from 0, 0)."""
obj = bpy.data.objects.get(name)
if obj is None or obj.type != "CAMERA":
raise Refused(f"{name!r} is not a camera object.")
data, render = obj.data, context.scene.render
if data.type != "PERSP":
raise Refused(f"camera {name!r} is {data.type}; a camera record is a perspective camera's.")
fit = "HORIZONTAL" if data.sensor_fit == "AUTO" and render.resolution_x >= render.resolution_y else data.sensor_fit
place, turn, _ = obj.matrix_world.decompose() # a scaled camera object draws the same picture
return core.camera_of({"matrix_world": [list(row) for row in Matrix.LocRotScale(place, turn, None)], "lens": data.lens, "shift_x": data.shift_x, "shift_y": data.shift_y,
"sensor_width": data.sensor_width, "sensor_fit": fit, "resolution": [render.resolution_x, render.resolution_y]},
core.numbers(box, 4, "box") if box.strip() else None)
HIDE = 1e-3 # of a diagonal: a sight line stops this share of the edge's own piece of mesh short of the edge, so that the edge's own faces do not hide it; a surface nearer the edge than that hides it only from further than this share of its own object
def _diagonal(obj, placed, dg):
"""The diagonal of an object's evaluated bounding box as `placed` (a world matrix) stands it."""
return float(np.linalg.norm(np.ptp(np.array([placed @ Vector(corner) for corner in obj.evaluated_get(dg).bound_box]), axis=0)))
def built_edges(context, cam, objects, angle):
"""The edges a camera record sees on the build as it stands, modifiers evaluated: creases (two faces meeting at
more than `angle` degrees, one of them toward the camera), contours (one face toward the camera, the other
away) and open borders, each kept where two of three points along it are hidden behind nothing: a ray from the
camera toward the point meets no surface nearer it than the hiding margin: HIDE of the diagonal of the edge's
own piece (the connected part of its mesh it lies on: a box joined into one mesh with a ground is still a
box) or of the object met, the smaller of the two, so the margin is the same share of the parts involved at
any scale and whatever else the scene or the mesh holds (a ground plane, a hull). Past the own piece's margin
the ray is cast once more, and the first surface it meets there decides; the object met is measured whole. `objects` are the meshes read; anything the
scene renders hides. Returns {kind: [[u0, v0, u1, v1], ...]} in the record's pixels."""
scene, dg = context.scene, context.evaluated_depsgraph_get()
eye, out, cos_a = np.array(cam["C"]), {"crease": [], "contour": [], "border": []}, math.cos(math.radians(angle))
def hidden(p, short):
d = float(np.linalg.norm(p - eye))
toward = (p - eye) / d
if scene.ray_cast(dg, Vector(eye), Vector(toward), distance=d - short)[0]:
return True
hit, where, _, _, other, placed = scene.ray_cast(dg, Vector(eye + toward * (d - short)), Vector(toward), distance=short)
return hit and d - float(np.linalg.norm(np.array(where) - eye)) > HIDE * _diagonal(other, placed, dg)
for obj in objects:
ev = obj.evaluated_get(dg)
me = ev.to_mesh()
nv, ne, nl, nf = len(me.vertices), len(me.edges), len(me.loops), len(me.polygons)
if not nf:
ev.to_mesh_clear()
continue
co, ends, loop_edge, totals, normal, centre = np.empty(nv * 3), np.empty(ne * 2, np.int32), np.empty(nl, np.int32), np.empty(nf, np.int32), np.empty(nf * 3), np.empty(nf * 3)
me.vertices.foreach_get("co", co)
me.edges.foreach_get("vertices", ends)
me.loops.foreach_get("edge_index", loop_edge)
me.polygons.foreach_get("loop_total", totals)
me.polygons.foreach_get("normal", normal)
me.polygons.foreach_get("center", centre)
ev.to_mesh_clear()
world = np.array(obj.matrix_world)
co, centre = co.reshape(-1, 3) @ world[:3, :3].T + world[:3, 3], centre.reshape(-1, 3) @ world[:3, :3].T + world[:3, 3]
normal = normal.reshape(-1, 3) @ np.linalg.inv(world[:3, :3])
normal /= np.maximum(np.linalg.norm(normal, axis=1), 1e-12)[:, None]
order = np.argsort(loop_edge, kind="stable")
faces, count = np.repeat(np.arange(nf), totals)[order], np.bincount(loop_edge, minlength=ne)
first = np.searchsorted(loop_edge[order], np.arange(ne))
two = count == 2
f0, f1 = faces[np.minimum(first, nl - 1)], faces[np.minimum(first + 1, nl - 1)]
toward = ((eye - centre) * normal).sum(1) > 0
crease = two & ((normal[f0] * normal[f1]).sum(1) < cos_a) & (toward[f0] | toward[f1])
contour = two & (toward[f0] != toward[f1])
ends = ends.reshape(-1, 2)
piece, shorts = np.arange(nv), {} # each vertex's connected piece, named by its least vertex
while True:
low = np.minimum(piece[ends[:, 0]], piece[ends[:, 1]])
spread = piece.copy()
np.minimum.at(spread, ends[:, 0], low)
np.minimum.at(spread, ends[:, 1], low)
spread = spread[spread]
if (spread == piece).all():
break
piece = spread
for k in np.nonzero(crease | contour | (count == 1))[0]:
a, b = co[ends[k, 0]], co[ends[k, 1]]
if piece[ends[k, 0]] not in shorts:
shorts[piece[ends[k, 0]]] = HIDE * float(np.linalg.norm(np.ptp(co[piece == piece[ends[k, 0]]], axis=0)))
short = shorts[piece[ends[k, 0]]]
if sum(not hidden(a + t * (b - a), short) for t in (0.2, 0.5, 0.8)) >= 2:
(u0, v0), (u1, v1) = core.project(cam, [a, b])
out["contour" if contour[k] else "crease" if crease[k] else "border"].append([float(u0), float(v0), float(u1), float(v1)])
return out
class BROKKR_REFERENCE_OT_flow_score(PolishOperator):
"""Score traced lines against the edges a camera sees on the build: how much of each line has a built crease,
contour or border running along it"""
bl_idname = "brokkr_reference.flow_score"
bl_label = "Flow Score"
camera_name: bpy.props.StringProperty(name="Camera", maxlen=63, description="The camera object the view is seen through (solve_camera stands one)")
box: bpy.props.StringProperty(name="Box", maxlen=120, description="u0,v0,u1,v1: the camera's frame on the image, in the pixels the lines were traced in; empty is the render's own frame")
height: bpy.props.FloatProperty(name="Height", default=0.0, min=0.0, max=1000000.0, description="The figure's height in those pixels: an edge within 1% of it is near; 0 is the box's height")
lines: bpy.props.StringProperty(name="Lines", maxlen=12000, description="tag: u,v u,v ...; tag: u,v u,v ... the traced lines")
objects: bpy.props.StringProperty(name="Objects", maxlen=4000, description="Mesh objects whose edges are read, name; name; ... empty is every mesh the render shows")
angle: bpy.props.FloatProperty(name="Angle", default=18.0, min=1.0, max=179.0, description="Degrees between two faces' normals past which their edge is a crease")
def work(self, context):
try:
cam = record(context, self.camera_name, self.box)
lines = core.polylines(self.lines, "lines")
except core.ReferenceFitError as refusal:
raise Refused(str(refusal)) from None
names = [name.strip() for name in self.objects.split(";") if name.strip()]
meshes = [bpy.data.objects.get(name) for name in names] if names else [o for o in context.scene.objects if o.type == "MESH" and not o.hide_render]
for name, obj in zip(names, meshes):
if obj is None or obj.type != "MESH" or obj.name not in context.scene.objects:
raise Refused(f"{name!r} is not a mesh object of this scene.")
edges = built_edges(context, cam, meshes, self.angle)
height = self.height or cam["box"][3] - cam["box"][1]
segments = [seg for kind in edges.values() for seg in kind]
return {"lines": {tag: core.along(line, segments, height) for tag, line in lines.items()}, "edges": {kind: len(found) for kind, found in edges.items()},
"objects": [o.name for o in meshes], "height": height}
classes = (BROKKR_REFERENCE_OT_solve_camera, BROKKR_REFERENCE_OT_flow_score)
def register():

View file

@ -80,6 +80,59 @@
"doc": "pixels across the frame the box becomes when camera_name is given"
}
]
},
{
"name": "brokkr_reference.flow_score",
"doc": "Score traced lines against the edges a camera sees on the evaluated build (creases, contours and open borders, unhidden): per line, the share with a built edge running along it (on), the mean distance to one in % of height (off) and the longest unbroken share (run); and the count of edges by kind (docs/reference.md).",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
"fields": [
{
"name": "camera_name",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 63,
"doc": "the camera object the view is seen through (solve_camera stands one)"
},
{
"name": "box",
"type": "string",
"maxLength": 120,
"doc": "u0,v0,u1,v1: the camera's frame on the image, in the pixels the lines were traced in; absent is the render's own frame from 0,0"
},
{
"name": "height",
"type": "number",
"minimum": 0,
"maximum": 1000000,
"default": 0,
"doc": "the figure's height in those pixels: an edge within 1% of it is near; 0 is the box's height"
},
{
"name": "lines",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 12000,
"doc": "tag: u,v u,v ...; tag: u,v u,v ... the traced lines"
},
{
"name": "objects",
"type": "string",
"maxLength": 4000,
"doc": "mesh objects whose edges are read, name; name; ... absent is every mesh the render shows"
},
{
"name": "angle",
"type": "number",
"minimum": 1,
"maximum": 179,
"default": 18,
"doc": "degrees between two faces' normals past which their edge is a crease"
}
]
}
]
}

View file

@ -23,7 +23,13 @@ focal length trade against each other (a dolly zoom), and "lens_band" says how f
blender(cam, width) what a Blender camera takes to be this one, the frame being the box
camera_of(params, box) the record of a Blender camera: blender() read back
in_frame(cam, pixels, width) image pixels as pixels of the frame blender() renders
points(text, size), numbers(text, count) the action's string fields
points, numbers, polyline, polylines the actions' string fields
A traced line is pixels; a part's points are given in its frame, a 4 x 4 frame-to-world matrix.
seen(cam, frame, points) pixels of points of a frame
crease_run(points) where Blender builds the hard crease of a cage column at one level
along(line, segments, height) the flow score: how much of a traced line has a seen edge along it
"""
from __future__ import annotations
@ -36,6 +42,9 @@ SENSOR = 36.0 # mm, fitted to the box's width
LENS_MM = (4.0, 4000.0) # the focal length never leaves this: past 4000 mm a view is orthographic to any marking, and an unbounded solve runs off (docs/reference.md)
BAND = 1.1 # lens_band: the lenses whose refitted rms is within this multiple of the best
STEP = 0.1 # the band is walked in steps of this in log f
FINE = 1.0 # pixels: no mark is placed truer than this, so the band is never judged against a smaller error (exact marks fit every lens of a flat view to 1e-6 px and would call one of them best)
PLANAR = 0.12 # marks thinner than this share of their spread (their planarity) are near a plane: a band of theirs that is open at one end of LENS_MM is reported open at both. The geometric mean of 0.041, a panel with relief whose band does open at one end, and 0.36, marks with depth: separation 2.9 each side (tests/test_reference.py)
DECIDED = 1.57 # a lens is determined when its band is inside LENS_MM and spans no more than this factor. A band's span is a whole number of STEPs: this is the geometric mean of four steps (1.49, the widest that marks with depth 3 px off read) and five (1.65). An exception to lodur:ruling:deterministic-bound-margin: the two readings are one STEP apart, 1.105, and readings quantised in STEPs have no pair 1.2 apart with nothing between; a host that moves a band by a step fails the span assertion in tests/test_reference.py
MODELS = {"upright": (), "rolled": ("roll",), "free": ("roll", "centre"), "square": ("square",)} # what a model solves beyond place, yaw, pitch and focal length; "square" holds the yaw at a quarter turn instead
QUARTER = math.pi / 2
@ -194,24 +203,30 @@ def _left_out(W, P, c0, model, logf, f_fixed, near, turned, pivot):
return float(np.sqrt(np.mean(np.square(miss))))
def _decidable(names, W, P, plane_will_do):
EXACT = 1e-9 # of the marks' extent: under this a set of marks is exactly degenerate (true lines and planes read 1e-16); marks placed by hand are never within 1e-3
def _decidable(names, W, P, model):
"""Refuses marks that cannot decide a camera, by which they are, before anything is solved: the place is solved
in units of the marks' extent, so marks of no extent have no solve at all (a logarithm of zero, a record of
NaN). These are exact degeneracies, to nine digits of the marks' extent; points nearly in a line or a plane are
solved, and what they leave undecided is the band's to say."""
NaN). These are exact degeneracies, to EXACT of the marks' extent; points nearly in a line or a plane are
solved, and what they leave undecided is the band's to say. Returns (the unit normal of the plane the world
points all lie in, or None; the marks' planarity: their least extent over their greatest, 0 for a plane)."""
for what, A in (("world point", W), ("pixel", P)):
first = {}
twins = [(first[row], k) for k, row in zip(names, map(tuple, A.tolist())) if row in first or first.setdefault(row, k) is None]
if len(first) < 6:
raise ReferenceFitError(f"{len(first)} different {what}s are marked; six are needed ({twins[0][0]!r} and {twins[0][1]!r} share one)")
flat = lambda A: np.linalg.svd(A - A.mean(0), compute_uv=False) # noqa: E731 the marks' extents along their own axes, widest first
w, p = flat(W), flat(P)
if p[1] <= 1e-9 * p[0]:
(_, w, axes), p = np.linalg.svd(W - W.mean(0), full_matrices=False), np.linalg.svd(P - P.mean(0), compute_uv=False) # the marks' extents along their own axes, widest first
if p[1] <= EXACT * p[0]:
raise ReferenceFitError("the pixels lie on one line: marks along a line of the image cannot say how the camera is turned about it")
if w[1] <= 1e-9 * w[0]:
if w[1] <= EXACT * w[0]:
raise ReferenceFitError("the world points lie on one line: the camera could stand anywhere round it")
if w[2] <= 1e-9 * w[0] and not plane_will_do:
raise ReferenceFitError("the world points lie in one plane, which does not decide the lens or the centre: mark a point off the plane, or hold `lens` and name a model other than free")
if w[2] > EXACT * w[0]:
return None, float(w[2] / w[0])
if model == "free":
raise ReferenceFitError("the world points lie in one plane, which does not decide the centre: mark a point off the plane, or name a model other than free")
return axes[2], float(w[2] / w[0])
def solve(world, pixels, box, model="auto", lens=None, turned=(), pivot=(0.0, 0.0)):
@ -227,18 +242,29 @@ def solve(world, pixels, box, model="auto", lens=None, turned=(), pivot=(0.0, 0.
torso on its waist ring): the angle is solved with the camera, and "twist" is how far they turn from where
they were given.
Returns the camera record: {"C", "R", "f", "c", "box", "lens" (mm), "lens_band" [low, high] (the lenses that
refit within BAND of the best rms, walked out from the best in steps of STEP in log f, about 10%, to the first
that misses: an equal-error band, not a confidence interval, and no finer than its step, so [x, x] says the
band is narrower than one step each way, not that the lens is exact),
Returns the camera record: {"C", "R", "f", "c", "box", "lens" (mm), "lens_band" [low, high] (walked out from the
best lens in steps of STEP in log f, about 10%, to the first lens each way whose refit misses BAND of the best
rms, or of FINE pixels where the marks fit closer than any hand places them: every lens outside it misses,
and its ends are the first that do, so it is an equal-error band no finer than its step, not a confidence
interval. Near a plane (planarity under PLANAR) a band that reaches one end of LENS_MM is the whole of
LENS_MM), "lens_determined" (True when the band is inside LENS_MM and spans no more than DECIDED times;
False when the marks leave the lens open, and the headline lens is then one of many that fit; None when
`lens` was held), "planarity" (the marks' least extent over their greatest: 0 for a plane),
"lens_at_bound" (None, or "short" or "long" when the solve stopped at an end of LENS_MM), "rms", "median"
(pixels), "worst" [name, pixels], "left_out" (the leave-one-out rms), "model", "tried" {model: rms, left_out,
lens}, "azimuth", "elevation" (degrees: where the camera stands round the points' middle), "distance", "roll",
"twist" (degrees), "residuals" {name: [du, dv]}}. Every number in it is finite.
"twist" (degrees), "plane" (None, or when the world points all lie in one plane the degrees between the line
of sight and square-on to it), "residuals" {name: [du, dv]}}. Every number in it is finite.
World points in or near one plane may not decide the lens: seen obliquely they do, by the plane's
foreshortening; the nearer square-on, the less, and "lens_determined" and the band say so (a headline lens
then sits anywhere in LENS_MM: a tilt of the plane seen through a long lens draws what a short lens draws
square-on, and the marks' error chooses between them). The centre a plane never decides, so "auto" leaves
"free" untried.
Refuses with ReferenceFitError, before solving, what cannot decide a camera: fewer than six shared names, or
fewer than six different world points or different pixels among them; pixels on one line; world points on one
line; world points in one plane, unless `lens` is held and the model is upright, rolled or square."""
line; world points in one plane with the model "free"."""
if model != "auto" and model not in MODELS:
raise ReferenceFitError(f"unknown model {model!r}: one of auto, {', '.join(MODELS)}")
box = [float(v) for v in box]
@ -254,43 +280,49 @@ def solve(world, pixels, box, model="auto", lens=None, turned=(), pivot=(0.0, 0.
if len(world[k]) != 3 or len(pixels[k]) != 2 or not all(math.isfinite(v) for v in (*world[k], *pixels[k])):
raise ReferenceFitError(f"point {k!r} is not three finite world numbers and two finite pixel numbers: {list(world[k])}, {list(pixels[k])}")
W, P = np.array([world[k] for k in names], float), np.array([pixels[k] for k in names], float)
_decidable(names, W, P, lens is not None and model not in ("auto", "free"))
normal, planarity = _decidable(names, W, P, model)
T = np.array([k in turned for k in names])
c0 = [(box[0] + box[2]) / 2, (box[1] + box[3]) / 2]
logf = (math.log(LENS_MM[0] * width / SENSOR), math.log(LENS_MM[1] * width / SENSOR))
fixed = None if lens is None else lens * width / SENSOR
tried = {}
for m in (("upright", "rolled", "free") if model == "auto" else (model,)):
for m in ((("upright", "rolled", "free") if normal is None else ("upright", "rolled")) if model == "auto" else (model,)):
rms, p, cam, X, angle = _fit(W, P, c0, m, logf, f_fixed=fixed, turned=T, pivot=pivot)
tried[m] = (rms, p, cam, X, angle, _left_out(W, P, c0, m, logf, fixed, p, T, pivot))
kind = min(tried, key=lambda k: tried[k][5])
rms, p, cam, X, angle, left = tried[kind]
mm = lambda f: min(max(f * SENSOR / width, LENS_MM[0]), LENS_MM[1]) # noqa: E731 an end of the range reads as exactly that end
span, best = [cam["f"]], math.log(cam["f"])
for way in ((-1, 1) if fixed is None else ()): # walk the lens out each way from the best, each solve started at the last, to the first that misses or to the bound
walked, best = [(cam["f"], True)], math.log(cam["f"]) # (focal length, whether its refit is within the band)
for way in ((-1, 1) if fixed is None else ()): # walk the lens out each way from the best, each solve started at the last
q, step = np.delete(p, 5 + ("roll" in MODELS[kind])), 1
while True:
at = best + STEP * way * step
f = math.exp(min(max(at, logf[0]), logf[1]))
r_f, q = _fit(W, P, c0, kind, logf, f_fixed=f, near=q, turned=T, pivot=pivot)[:2]
if r_f > BAND * rms + 1e-9:
break
span.append(f)
if not logf[0] < at < logf[1]:
walked.append((f, r_f <= BAND * max(rms, FINE) + 1e-9))
if not walked[-1][1] or not logf[0] < at < logf[1]: # marks with depth stop at the first miss; near a plane the error can come back under, so the walk runs to the bound
break
step += 1
walked.sort()
within = [k for k, (_, ok) in enumerate(walked) if ok]
span = [walked[max(within[0] - 1, 0)][0], walked[min(within[-1] + 1, len(walked) - 1)][0]] # out to the first miss past each end: the band's end is somewhere in that step, and the band never leaves it out
if fixed is None and planarity < PLANAR and (math.log(walked[within[0]][0]) <= logf[0] + 1e-9 or math.log(walked[within[-1]][0]) >= logf[1] - 1e-9):
span = [math.exp(logf[0]), math.exp(logf[1])] # near a plane, a band open at one end is open at both: what closes the other is a tilt traded for the lens, which the marks' error sets either way
off = cam["C"] - X.mean(0)
res = project(cam, X) - P
if not (math.isfinite(rms) and math.isfinite(left) and np.isfinite(cam["C"]).all() and np.isfinite(res).all()):
raise ReferenceFitError("the solve did not come to finite numbers: the marks do not decide a camera")
worst = int(np.argmax(np.linalg.norm(res, axis=1)))
band = [float(mm(span[0])), float(mm(span[1]))]
edge = None if fixed is not None else "short" if best <= logf[0] + 1e-9 else "long" if best >= logf[1] - 1e-9 else None
return {"C": [float(v) for v in cam["C"]], "R": [[float(v) for v in row] for row in cam["R"]], "f": float(cam["f"]), "c": [float(v) for v in cam["c"]],
"box": box, "lens": float(mm(cam["f"])), "lens_band": [float(mm(min(span))), float(mm(max(span)))], "lens_at_bound": edge,
"box": box, "lens": float(mm(cam["f"])), "lens_band": band, "lens_at_bound": edge, "lens_determined": None if fixed is not None else bool(LENS_MM[0] < band[0] and band[1] < LENS_MM[1] and band[1] <= DECIDED * band[0]),
"planarity": planarity,
"rms": float(rms), "median": float(np.median(np.linalg.norm(res, axis=1))), "worst": [names[worst], float(np.linalg.norm(res[worst]))],
"left_out": left, "model": kind, "tried": {k: {"rms": float(v[0]), "left_out": v[5], "lens": float(mm(v[2]["f"]))} for k, v in tried.items()},
"azimuth": float(math.degrees(math.atan2(-off[0], off[1]))), "elevation": float(math.degrees(math.atan2(off[2], math.hypot(off[0], off[1])))),
"distance": float(np.linalg.norm(off)), "roll": float(math.degrees(p[5])) if "roll" in MODELS[kind] else 0.0, "twist": float(math.degrees(angle)),
"plane": None if normal is None else float(math.degrees(math.acos(min(1.0, abs(float(cam["R"][2] @ normal)))))),
"residuals": {k: [float(v) for v in r] for k, r in zip(names, res)}}
@ -334,6 +366,81 @@ def in_frame(cam, pixels, width):
return (np.asarray(pixels, float) - np.array([u0, v0], float)) * k + np.array([0.0, (round(k * (v1 - v0)) - k * (v1 - v0)) / 2])
# --- traced lines and built edges -------------------------------------------------------------------------------------
def resampled(points, n):
"""A polyline as n points evenly spaced along it."""
p = np.asarray(points, float)
d = np.concatenate([[0], np.cumsum(np.linalg.norm(np.diff(p, axis=0), axis=1))])
t = np.linspace(0, d[-1], n)
return np.stack([np.interp(t, d, p[:, k]) for k in range(p.shape[1])], 1)
def seen(cam, frame, points):
"""Pixels of points of a frame."""
F = np.asarray(frame, float)
return project(cam, np.asarray(points, float) @ F[:3, :3].T + F[:3, 3])
def crease_run(points):
"""The built edges of a hard crease whose cage column is `points`, after one level of Catmull-Clark as Blender's
Subdivision modifier builds it: each inner cage point moves to (1, 6, 1) / 8 of itself and its neighbours, a
new point stands at each middle, the ends stay; then every point but the ends is set on the limit curve,
(1, 4, 1) / 6 of itself and its new neighbours (the modifier's Limit Surface, on by default; with it off the
crease stands at the first step and this is not it). A polyline of 2n - 1 points; the cage's own points are
its even ones, each at (1, 4, 1) / 6 of the cage."""
p = np.asarray(points, float)
v = p.copy()
v[1:-1] = (p[:-2] + 6 * p[1:-1] + p[2:]) / 8
out = np.empty((2 * len(p) - 1, p.shape[1]))
out[0::2], out[1::2] = v, (p[:-1] + p[1:]) / 2
out[1:-1] = (out[:-2] + 4 * out[1:-1] + out[2:]) / 6
return out
def _off(points, line):
"""Per point, its distance to a polyline."""
p, q = np.asarray(points, float), np.asarray(line, float)
a, d = q[:-1], q[1:] - q[:-1]
t = np.clip(((p[:, None] - a) * d).sum(2) / np.maximum((d * d).sum(1), 1e-18), 0, 1)
return np.linalg.norm(a + t[:, :, None] * d - p[:, None], axis=2).min(1)
def along(line, segments, height, near=0.01, turn=20.0, cap=0.05):
"""The flow score: how much of a traced line (pixels) has a seen edge running along it. `segments` are
[u0, v0, u1, v1] in the same pixels, `height` the figure's height there. Per point of the line: the distance to
the nearest segment within `turn` degrees of the line's direction. Returns {"on": the share of the line with
such an edge within `near` of the height, "off": the mean distance to one in % of the height, capped at `cap`,
"run": the longest unbroken share that is on}."""
p = resampled(line, 80)
tan = np.gradient(p, axis=0)
tan /= np.linalg.norm(tan, axis=1)[:, None]
S = np.asarray(segments, float).reshape(-1, 4)
if not len(S):
return {"on": 0.0, "off": 100 * cap, "run": 0.0}
a, d = S[:, :2], S[:, 2:] - S[:, :2]
length = np.maximum(np.linalg.norm(d, axis=1), 1e-9)
u = d / length[:, None]
dist = np.empty(len(p))
for i, (q, t) in enumerate(zip(p, tan)):
ok = np.abs(u @ t) >= math.cos(math.radians(turn))
if not ok.any():
dist[i] = np.inf
continue
s = np.clip(((q - a[ok]) * u[ok]).sum(1), 0, length[ok])
dist[i] = np.linalg.norm(a[ok] + s[:, None] * u[ok] - q, axis=1).min()
on = dist <= near * height
run = best = 0
for flag in on:
run = run + 1 if flag else 0
best = max(best, run)
return {"on": round(float(on.mean()), 3), "off": round(float(100 * np.minimum(dist / height, cap).mean()), 2), "run": round(best / len(on), 3)}
# --- fields ----------------------------------------------------------------------------------------------------------
def numbers(text, count, what):
"""'1, 2.5, 3' as `count` finite floats; ReferenceFitError names `what`."""
try:
@ -360,3 +467,29 @@ def points(text, size, what):
raise ReferenceFitError(f"{what} names {name!r} twice")
out[name] = numbers(values, size, f"{what} point {name!r}:")
return out
def polyline(text, what):
"""'u,v u,v ...' as an (n, 2) array of two or more different points; ReferenceFitError names `what`."""
line = np.array([numbers(piece, 2, f"{what} point") for piece in text.split()], float).reshape(-1, 2)
if len(line) < 2 or not np.ptp(line, axis=0).max() > 0:
raise ReferenceFitError(f"{what} is {len(line)} points of no length; a traced line is two or more, 'u,v u,v ...'")
return line
def polylines(text, what):
"""'tag: u,v u,v ...; tag: ...' as {tag: polyline}; a tag given twice is refused."""
out = {}
for entry in (piece.strip() for piece in text.split(";")):
if not entry:
continue
tag, colon, line = entry.partition(":")
tag = tag.strip()
if not colon or not tag:
raise ReferenceFitError(f"{what} entry {entry[:40]!r} has no tag; it is 'tag: u,v u,v ...'")
if tag in out:
raise ReferenceFitError(f"{what} names {tag!r} twice")
out[tag] = polyline(line, f"{what} line {tag!r}")
if not out:
raise ReferenceFitError(f"{what} holds no line; it is 'tag: u,v u,v ...; tag: ...'")
return out

View file

@ -186,6 +186,8 @@ Behaviour the table does not say, per action:
- `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.
Custom properties named `kit_*` that the file's extras carry are dropped from the imported
objects and their data, and the receipt names the objects: they are brokkr_kitbash's own state.
- `exportGltf`: `filepath`, `.glb` (binary) or `.gltf` (separate `.bin`), relative to the
add-on preference `Render Output Directory` (the renderStill rules: no `..`, no links, and an
existing name is refused; there is no overwrite).

View file

@ -1,7 +1,7 @@
# Kitbash parts: machinery from kits
`surfaces/blender/brokkr_kitbash` is a Blender add-on that places parametric machine parts from a **kit**, mates
them **socket** to socket, cuts them with booleans and bakes them, and makes the faceted armor **shell** they sit under. It is the machinery vocabulary of a ship's fixed chassis: the frame, tanks,
them **socket** to socket, cuts them with booleans and freezes them, and makes the faceted armor **shell** they sit under. It is the machinery vocabulary of a ship's fixed chassis: the frame, tanks,
actuators, housings and plumbing an agent assembles offline under a hand-fit armor cage, baked once. It is a host
add-on in Brokkr's sense (`install.md`, "Host add-on actions"), a sibling of `brokkr_mesh_polish` and `brokkr_rig`:
it imports the polish package's operator base, `Refused` and `mesh_object`, and nothing from `brokkr_bridge`.
@ -25,13 +25,21 @@ Who owns what:
included: a part's size is its params, and a socket's frame is a rotation and an origin. Set scale to 1 and
resize with `set_params`.
- A connection between two parts belongs to the child: its parent pointer and its `kit_socket`,
`kit_parent_socket` and `kit_roll` properties. Where the child stands is derived from them
("Assembling parts").
`kit_parent_socket` and `kit_roll` properties, and its joint record (`kit_slide`, `kit_min`, `kit_max`,
`kit_mechanism`, `kit_compliance`). Where the child stands is derived from them ("Assembling parts"). The
joint's kind belongs to the kit's socket type and its axis to the parent socket's frame: neither is stored on
the connection.
- A closure, the joint that closes a loop, belongs to the closing part: its `kit_close_socket`, `kit_close_to`
and `kit_close_to_socket` properties. Only `close` writes them and only `detach` clears them. A closure places
nothing: whether it holds is derived at each report.
- A boolean belongs to its Boolean modifier on the part that is cut. `kit_baked` says `apply` replaced the part's
mesh with the evaluated one.
- A boolean belongs to its Boolean modifier on the part that is cut.
- Whether a cut object is live or frozen belongs to its `kit_frozen` property, which holds the live mesh while
the object carries its evaluated one. Only `freeze` sets it, and `thaw`, which deletes it, is its one undo.
Both go through one function, `hold`, which is also the only writer of `kit_kept` and of the fake user on a held
live mesh ("Freezing").
- Every `kit_*` custom property is the kit's: Brokkr's `setObjectCustomProperty` refuses a name that starts with
`kit_`, and `importGltf` drops such properties from the objects and meshes it imports and names the objects in
its receipt, so each has only the writers named here. A kit part exported with extras comes back as a plain mesh.
## A part, end to end
@ -143,7 +151,8 @@ well under the part's thinnest feature at its smallest params.
**Sockets** are frames. `at` is the origin; `z` is the outward normal (a mating socket faces it), `y` is up (the
roll reference), and x is y cross z; each is one of `+x -x +y -y +z -z` in the part's frame, on different axes.
`size` is a diameter in metres. `type` names one of the kit's `socketTypes`, whose `match` says how sizes are to
be compared when sockets are mated: `equal` (within 1 percent) or `fits` (the child at most the parent). A socket
be compared when sockets are mated: `equal` (within 1 percent) or `fits` (the child at most the parent), and
whose optional `dof` (`revolute` or `prismatic`; absent is rigid) says how a child seated on such a socket moves. A socket
sits on a flat face of the part whose normal is its `z`; `test_kitbash` checks this for every part of a shipped
kit at its default, smallest and largest params and at seeded draws between.
@ -156,20 +165,75 @@ angle: at 0 the two parts line up, side by side. A pin carries a socket on each
**A connection** seats one socket of a child part on one socket of a parent part: the two origins together, the
two normals opposed, and the child turned `roll` degrees about the parent socket's normal (right-handed; at 0 the
two sockets' up axes line up). The child owns it. It is the child's parent pointer, under an identity parent
inverse, and three ID properties on the child: `kit_socket` (its own socket), `kit_parent_socket` and `kit_roll`.
Nothing else stores it: no parent name, no world matrix, no empties. The child's `matrix_basis` is derived,
two sockets' up axes line up). On a prismatic socket the child also stands `slide` metres along that normal. The
child owns it. It is the child's parent pointer, under an identity parent inverse, and three ID properties on the
child: `kit_socket` (its own socket), `kit_parent_socket` and `kit_roll`, with its joint record ("Joint records",
below). Nothing else stores it: no parent name, no world matrix, no empties. The child's `matrix_basis` is
derived,
```text
matrix_basis = S_parent @ Rz(roll) @ FLIP @ inverse(S_child) FLIP = half a turn about y
matrix_basis = S_parent @ T(0, 0, slide) @ Rz(roll) @ FLIP @ inverse(S_child) FLIP = half a turn about y
```
with `S` each socket's frame in its own part at that part's stored params (`core.mate`). `attach`, `set_params`,
`roll`, `aim` and `reach` write it; nothing else should.
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.
**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:
`slide`) or nothing, and is then rigid (`flange`, `mount`, `hose`). No part, socket or object name decides it. A
revolute joint's value is its `kit_roll`, in degrees; a prismatic joint's is its `kit_slide`, in metres, and its
roll is a build angle. Beside the value the child's connection carries a record:
| Property | States | Stated by |
| --- | --- | --- |
| `kit_slide` | metres along the parent socket's z; prismatic only, 0 where the two origins meet | `slide` |
| `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` |
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.
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
ratio describe how the strut feels whatever mass it carries; a stiffness in N/m would need the mass the kit does
not know. `kit_compliance` is a record for a runtime: nothing in Brokkr solves it.
Two things a rig needs are not stored, because each is already stated once. The axis is the parent socket's z in
the kit at the parent's stored params: a copy on the connection would go stale at the next `set_params`. The order
is the parent tree. `brokkr_kitbash.joints` derives both at each call and emits them, so a consumer derives
nothing:
```json
{"schema": "brokkr.joints", "version": 1, "root": "Tank", "frame": "the root object's: Blender axes (+Z up), metres",
"rigid": 2, "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},
{"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}}]}
```
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
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.
**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
vocabulary kits share: parts of two kits mate when both kits declare the socket's type with the same `match`
vocabulary kits share: parts of two kits mate when both kits declare the socket's type with the same `match` and
the same `dof`
(`cutters` declares `mount` as `mechanical` does, so a vent seats on a recess floor), and are refused, naming both
kits and the type, when one does not declare it or declares it otherwise. KSP's attach nodes and LDraw's snap
types are connector vocabularies of this kind: global, matched by type and size. `attach` also
@ -318,27 +382,78 @@ took 1.89 s through the collection modifier, 12.6 s with a Boolean modifier for
eight cutters joined into one mesh (medians of five interleaved evaluations, Blender 5.3 on Starfire; an earlier
probe with raw cutters read 2.04, 14.7 and 1.94 s). All three give the same faces and volume. The cost is the
target's, hardly the cutters': one cutter on that shell already costs 1.4 s. The target pays it each time it is
evaluated, and Blender evaluates it after every action that changes it or a cutter. `apply` a kit part when its
shape is settled; a mesh that is not a kit part is baked by `exportGltf` with `applyModifiers`. `boolean`
evaluated, and Blender evaluates it after every action that changes it or a cutter, and after much that changes
neither ("Freezing", below): `freeze` an object when its cuts are settled. `boolean`
evaluates the target once and reports `evaluated: {faces, volume, nonManifoldEdges}`; `report` never evaluates a
modifier. The cutter is any other mesh object and is not changed: hide it with `setObjectVisibility`. A cutter
with no material leaves the target's material slots as they are; a cutter that has materials brings them, after
the target's own, on the faces it makes.
**`apply`** bakes a kit part: its mesh becomes the evaluated mesh (booleans and bevel applied), every modifier
goes with the collections its Booleans held, and `kit_baked` is set. The cutter objects stay: a cutter placed by
`cut` keeps its floor socket and what is attached to it. The material slots are the part'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 part's first slot. A baked part
keeps `kit_kit`, `kit_part`, `kit_params` and its connections: its sockets are still derived from the params,
so what is attached to it stays attached and new parts can attach to it, and it can be cut and baked again.
`set_params` refuses it, since the params no longer make the mesh. `exportGltf` with `applyModifiers` already
exports the evaluated mesh; `apply` is for a baked `.blend`.
### Freezing
A live Boolean over a collection is paid for far more often than its target changes. In Blender 5.3 every such
Boolean in the scene is evaluated again, whatever it cuts, after any datablock is removed (an orphan mesh
included), after any object's `hide_viewport` changes, and after any evaluated mesh is copied out
(`new_from_object`). Adding objects, collections or modifiers does not do it. Nearly every action here does one of
the three (`cut_many` hides its target's Booleans to cast, `ribs` makes and removes working objects), so each
finished cut object is paid for again at each later action. Hiding the finished object does not help while its
cutters show, and the hide is itself one more trigger. On a replica of six cut plates (a subdivided, solidified
sphere under one Exact Boolean of four cutters each), each trigger on an unrelated datablock cost 19 to 23 s; with
the plates frozen, 0.004 to 0.014 s (three interleaved repetitions, Blender 5.3 on Starfire).
**`freeze`** takes any mesh object that has modifiers, a kit part, a shell or a plain mesh. Its mesh becomes its
evaluated mesh (named `<object> frozen`), its live mesh is held by an ID-pointer property, `kit_frozen`, and
given a fake user and `kit_kept`, a pointer to the frozen mesh, so it survives a purge of orphans and a save even
if `kit_frozen` is edited by hand. The kit settles this after every depsgraph update and before every save: a live
mesh that no `kit_frozen` points at loses its fake user and `kit_kept`, unless an object still carries the frozen
mesh its `kit_kept` names. So deleting a frozen object, by `deleteObject` or in Blender, releases its live mesh to
the next purge or save, and a `kit_kept` cleared by hand is written again. The fake user is the kit's: one already
set on a live mesh goes when the mesh is released. Every modifier stays in the stack with its collections, turned
off in viewports and renders. Nothing is removed: the cutter objects stay, a cutter placed by `cut` keeps its floor socket and what
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
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.
**`thaw`** puts the live mesh back, deletes `kit_frozen`, turns every modifier on and removes the frozen mesh. It
evaluates nothing itself; Blender evaluates the object once afterwards, and the thawed object evaluates to the
faces and volume it had.
A frozen object's mesh is not its design, so every action that would write its live mesh or its stack refuses it
with "thaw it first": `set_params`, `boolean`, `cut`, `cut_many`, `ribs` from it, a `shell` or `hose` rebuild of
it, and `freeze`. Derive ribs before freezing a cage. `freeze` also refuses an object with no modifiers, one with a
modifier already off in viewports or renders (it names them: `thaw` turns every modifier on, and would not give
that stack back), and one Blender does not evaluate. `thaw` refuses an object that is not frozen, and one whose
`kit_frozen` no longer holds a mesh; if a hand edit overwrote or deleted it, the refusal names the kept live mesh
whose `kit_kept` points at the mesh the object carries, and setting `kit_frozen` back to that mesh by hand lets
`thaw` through.
A modifier of a frozen object turned on by hand is applied on top of the frozen mesh. `report` shows such a part
with `frozen` false and `dirty`, the names of the modifiers shown in viewports or renders; it stays refused by the
actions above, as "frozen and dirty", until it is thawed. `exportGltf` with `applyModifiers` exports a frozen
object's frozen mesh, since its modifiers are off, and refuses an export that includes a dirty one, by the same
rule: a modifier shown in viewports or renders. What nothing detects: a
material assigned to a frozen object, which lands on the frozen mesh and goes at `thaw`.
What it buys on an assembly: KESTREL, an experiment mech of 22 cut shells and blocks, evaluated 1035 Booleans
where its cuts need 139 when each finished component was only hidden, and 139 when each was frozen as it was
finished. The evaluation counts are the stable measure: they repeat exactly. Wall time follows the machine's
load: the whole build took about 2.7 to 5.7 times as long hidden as frozen across two series of three interleaved
pairs (Blender 5.3 on Starfire under other load; 133 to 149 s against 32 to 54 s in the later one). In
`tests/live/kitbash_assembly.py`, removing an orphan mesh beside three cut tanks costs about 1 s with them live
and about 0.002 s with them frozen.
## Making a shell
`shell` makes an armor plate the way one is modelled by hand: fit a sparse subdivision cage, crease the edges that
are facets' borders, give it a wall, then cut into it. The cage is a **loft**: rings of points with equal counts,
quads between neighbouring rings. The description is a JSON object, `sheet`:
are facets' borders, give it a wall, then cut into it. The description is a JSON object, `sheet`, in one of two
forms, both compiled by `core.sheet` into the same cage: a **loft** (`rings`), below, or a **free cage** (`verts`
and `faces`, [A free cage](#a-free-cage)). A sheet states exactly one of `rings` and `verts`. The loft is rings of
points with equal counts, quads between neighbouring rings:
| key | default | what it says |
| --- | --- | --- |
@ -430,21 +545,118 @@ medians of three interleaved calls in the live suite (Blender 5.3 on Starfire).
are twisted, and the Boolean, which cuts quads into triangles, can read the wall as passing through itself and
leave edges with four faces. On the Seraph's cap that began at 0.91 of the thickness at which the first face
folds (0.0301 against 0.033), on the left cap and not on its mirror, the right; on its breast plate at 0.91 as
well (0.032 against 0.035). Read `nonManifoldEdges` after cutting (`boolean`, `apply`, or a count on the evaluated
well (0.032 against 0.035). Read `nonManifoldEdges` after cutting (`boolean`, `freeze`, or a count on the evaluated
mesh), and keep `thickness` clear of the first folding one with a thinner wall, fewer `levels` or wider facets at
the corner.
Refused, each before anything is written and naming the field and index: a missing or unknown key; a non-finite
number; fewer than 2 or more than 64 rings or points; rings of unequal counts; a quad under 1e-8 m2 (a collapsed
corner); a mirrored ring that does not start on x = 0 or has a point behind it; `mirror` with `closed`; a run out
of range or with `from` not under `to`; a weight outside 0 to 1; more than 262144 subdivided faces (cage quads
times 4 to the `levels`).
of range or with `from` not under `to`; a weight outside 0 to 1; more than 262144 subdivided faces (a quad gives
4 to the `levels`, a triangle three quarters of that).
On the pauldron (25 cage quads, 1600 subdivided faces, 3360 with the wall), `shell` took 3.5 ms a call with
Blender's own update after it, and one whole evaluation of the Subdivision and Solidify 1.7 ms. With six cutters
(four panel lines, two insets) and ribs under it, a rebuild took 0.92 s, which is its one Boolean evaluation.
Medians of 3, interleaved, Blender 5.3 on Starfire (`tests/live/kitbash_faceted.py`, `costs`).
### A free cage
A loft is a grid: every vertex off its boundary has four edges, so it cannot state a triangle, a pole, or a crease
that ends inside the surface. A hull modelled by hand uses all three. The bar is the fewest cage vertices that
hold the form, with creases doing the work: a dense cage that only looks smooth after subdivision is the failure.
The free form states the cage directly:
| key | default | what it says |
| --- | --- | --- |
| `verts` | required | 4 to 256 `[x, y, z]` in the shell's own frame |
| `faces` | required | each 3 or 4 vertex indices, counter-clockwise seen from outside |
| `creases` | `[]` | `[a, b, w]`: the edge between vertices a and b, weight 0 to 1 |
| `corners` | `[]` | `[vertex, w]`: a vertex held as a corner |
| `poles` | `[]` | the vertices of irregular valence, by index: a gate, below |
| `mirror` | `false` | the cage is authored on one side of x = 0 and reflected |
| `rim` | `1` | the weight of every boundary edge no crease names |
| `flip` | `false` | reverse every face |
```json
{"verts": [[0, 0, 0.5], [1, 0, 0], [0, 1, 0], [-1, 0, 0], [0, -1, 0], [1, 0, -1], [0, 1, -1]],
"faces": [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [2, 1, 5, 6]],
"creases": [[0, 1, 1.0], [0, 3, 1.0]], "poles": [1, 2], "rim": 0}
```
**Boundary.** A free cage's open boundary is smoothed through every vertex (Kit Subsurf at Boundary Smooth All),
as the hand-modelled cages are set: an uncreased outline is a soft curve and a plate's tip is round. A boundary
vertex is a corner only where `corners` pins it at weight 1 or its two edges are creased apart by the form. A loft
keeps its corners (Keep Corners), as it always has. With the outline uncreased the two settings differ by 7.7% of
extent on a 3 m plate, so the setting is the form's and not a taste.
**Mirror.** Every vertex off the seam stands on one side of x = 0 (either side, all the same). One within 0.005
of the cage's largest authored extent of the plane (5 mm on a 1 m hull) is on the seam, on whichever side it
strays: it is snapped to x = 0 and shared by both halves, so a cage reads the same at any scale. The others are
reflected (the k-th of them is vertex `len(verts) + k`), each face gets a reversed twin, and creases, corners and
poles land on both halves. A vertex further off the plane is not on the seam: the cage is open there, and a face
that then meets its reflection at one vertex alone is refused as pinched. A face lying on the plane, and an edge
on the plane that two authored faces share (a fin), are refused.
**The pole gate.** A vertex's valence is the number of cage edges at it, on the cage as built (after the
mirror). A pole is a vertex whose valence is not 4 off the boundary, or not 2 or 3 on it. `poles` must list
exactly the poles the faces make. An undeclared pole and a declared vertex that is none are both refused, naming
the vertex and its valence. The list changes nothing in the mesh: it is there so that no pole is an accident,
since a pole is where a subdivision surface pinches or flattens. Put one where a crease runs through it or a
triangle stands beside it, and where the form turns anyway.
**Triangles.** A triangle subdivides to three quads, so after one level the surface is all quads, and the wall,
`cut`, `ribs` and `count_folds` take it as any shell. Use one where a crease run ends: the two cage edges
either side of the crease close onto a point instead of carrying a loop across the rest of the form. Faces of
five or more sides are refused.
**Budget.** Two cages modelled by hand are the measure. A whole ship hull, 1 m long: 46 control vertices (29
authored under a mirror), 25 faces a side of which 6 are triangles, 9 creased edges a side, every one at weight
1, six poles, each on a crease or beside a triangle. A petal: 10 vertices, 4 quads and 6 triangles, 5 creased
ridges at weight 1, an uncreased outline. In both the creases are full weight and stand only where the form
truly breaks (turns of 40 to 170 degrees); the longest straight silhouette edges are single cage edges; the cage's
vertices stand outside the form, as subdivision shrinks toward the inside. An armour plate should cost about what
the petal does. Add a vertex only where the limit surface cannot otherwise reach the form, and say why.
**Refused**, before anything is written and naming the field and index: fewer than 4 or more than 256 vertices;
a vertex in no face; a face of other than 3 or 4 indices, with a repeated or out-of-range index, with another
face's vertices, or under 1e-8 m2; an edge in three faces; two faces crossing an edge the same way (wound
against each other); a pinched vertex, whose faces meet only at it and are not one fan, naming the fans; a crease
on no cage edge; two weights for one edge or point; a mirrored cage with vertices
on both sides; the pole gate. `closed` and the loft's crease runs belong to the loft and are refused here, as
`poles`, `corners` and `verts` are on a loft.
**The report** carries, for both forms, `cageVerts`, `cageFaces`, `triangles`, `creases`, `corners`, `poles`
(`{"3": 2, "5": 1}`: valence to how many vertices, on the cage as built) and `closed` (no boundary edge);
`rings` and `points` are null on a free cage.
**What it gives up.** A free cage is authored by index, by hand or by an agent: nothing derives it from a
silhouette, and a wrong index is caught only where it breaks a rule above, not where it merely makes a worse form.
There are no pentagons. A loft remains the shorter description of anything that is a grid.
**Reading and scoring a cage.** `tools/cage_export.py` writes an object of a `.blend` copy as a free cage document
(vertices as authored, creases from `crease_edge`, poles computed); it writes only that document and never saves
the `.blend`. `shell` builds that document as the object's own Subdivision draws it: an open plate with an
uncreased outline to 2e-5% of its extent, a mirrored hull to 0.28% (its seam snap). A Subdivision at Keep Corners
is refused, saying how to state the corners.
`tools/cage_score.py` builds two documents through `shell` and reports, with no pass bar and every figure a share
of the reference's largest extent: each one's counts; the distance between their level-3 surfaces, whose vertices
lie on the limit surface, each way and together (area-weighted mean, Hausdorff, median, 95th centile); silhouette
overlap along x, y and z; and `crease`, where each surface is sharp (level-3 edges turning 30 degrees or more,
read off the surface, not off the crease weights): `missPct`, how far the reference's sharp features lie from the
agent's, and `spurPct`, the reverse; 100 when one side has them and the other none. The headline is `cost`, after
the energy of Hoppe et al., *Piecewise Smooth Surface Reconstruction* (1994), fit plus complexity:
`fit = meanPct + hausdorffPct + (missPct + spurPct) / 2`, `complexity = 0.01 * cageVerts + 0.002 * creases` of the
agent's cage, a sharp edge a fifth of a vertex as in the paper. Lower is better; a cage against itself costs its
complexity. On the 46-vertex hull: itself 0.50, every vertex 0.5% off 1.26, one vertex moved 5% 1.56, nine more
edges creased 5.49, every edge creased 16.2, no crease 16.6. The median and the silhouettes cannot make that
order: a moved vertex leaves the median at 0 and every silhouette at 1, and the creaseless cage has the lower
median of the two. What the cost gives up: the three fit terms are summed at weight 1 and the vertex price is a
chosen 0.01, knobs and not measurements; the Hausdorff term is one point, so one stray vertex costs as much as
a broad error of the same size; and sharpness is a 30 degree threshold, so a crease softer than that is not a
feature to it.
## Cutting a shell
An armor plate is not a kit part: it is any mesh, usually one made by `shell`. `cut` cuts it, or a
@ -504,7 +716,7 @@ attaching a part to a floor) costs an evaluation again while the target is visib
more cutters than fit (about 150 of long names), the rows left off the end are counted in `booleansOmitted`. The
scene keeps every cutter; the target's `Kit` modifier collections list them.
`cut`, `cut_many`, `boolean` and `apply` evaluate their object, and refuse one Blender does not evaluate in the
`cut`, `cut_many`, `boolean` and `freeze` evaluate their object, and refuse one Blender does not evaluate in the
view layer: an object disabled in viewports that nothing evaluated depends on, or one whose collections no view
layer shows. A disabled object that an evaluated object needs (a parent of one, a cutter of one) is evaluated
all the same, and is cut.
@ -604,6 +816,169 @@ evaluate, but deleting the copy costs the same whole evaluation (1.44 to 1.54 s
included, and the hole cut's temporary objects must be deleted too. So a hull with twenty cutters pays their
evaluation once for every `ribs` call; iterate planes on the cage before it is cut, or with its Booleans off.
## Hoses between sockets
`brokkr_kitbash.hose` routes a bundle of hoses from one socket to another around everything in the scene:
```json
{"action": "brokkr_kitbash.hose", "object_name": "Feed", "start": "ThighRam:port_cap", "end": "ShinRam:port_cap",
"count": 3, "radius": 0.006, "clearance": 0.005,
"joint": "{\"socket\": \"Shin:end_a_back\", \"standoff\": 0.08}"}
```
**Ends.** `start` and `end` are `Object:socket` on a kit part, a `hose` socket (an actuator's `port_cap` and
`port_rod`) or a `flange`, no narrower than the bundle; or `Object` alone, an empty whose z the hose leaves along.
A fitting keeps a straight lead of 8 radii (a ferrule of 5, then 1.5 outside diameters before any bend), and the
bundle's clearance is not asked of that lead: it stands on its own port.
**The path.** `route.py` (numpy, no Blender) owns it. Waypoints are each fitting's lead end, each clamp and the
pin point. A leg between two waypoints is searched on a voxel grid of their box plus 0.25 m: a voxel is free when it
stands the bundle's half width, the clearance and half a voxel's diagonal from every other mesh, so every step
between neighbouring free voxels keeps the clearance; a 26-connected wavefront finds a shortest way and it is
pulled taut. The legs joined are one polyline, and each corner is rounded by the largest arc its measured room
allows: the arc stands within `radius * (1 - cos(turn / 2))` of its two tangent segments, so with that much room
beyond the clearance measured along them it keeps the clearance. Where two arcs would overlap on a segment each
keeps the tangent its bend takes at the floor and they share what the segment has left, in proportion to what each
asked beyond that; the corner at a pin holds the tangent its sharpest roll takes. The floor is `bend` outside diameters for the innermost hose (the centre line's is half the
bundle's spread more). The finished curve is measured once more against every mesh before anything is written.
**Measured, not sampled.** Every line the route trusts (a sight line of the pull, a tangent segment's room, the
finished curve, each side at each roll) is measured by `route.measure`: a reading answers for the piece of line
around it, less half the piece's length, because a distance to obstacles changes by no more than the distance
moved. A piece that this proves clear is done, one that reads under the need is refused, and any other is halved,
down to 1 mm. So a plate thinner than any spacing cannot stand unseen between two readings, and no measurement
depends on `step`: `step` sets only how fine the search for a way is. The price is half a millimetre: a line that
keeps the clearance by less than that cannot be proven and is refused as too near.
**Room for the bends.** A line pulled taut at the clearance alone grazes whatever it wraps, and the corner there
has no room for an arc; how much it happened to keep changed with `step`, so a bundle could route at 0.02 and at
0.03 and be refused at 0.0125. Each leg is therefore searched and pulled with room for its bends first: 0.29 of the
floor beyond the clearance, what the arc of a quarter turn at the floor takes (within twice that of a leg's end
the pull asks half the distance from the end instead, since an end stands where it is given). A leg with no way
that roomy (a clamp stands nearer its seat than that, and so does a gap the bundle only just passes) is searched
again without, and the hose is longer where the roomy way goes round.
**A seed, refined.** The polyline a search gives is a seed. Its vertices stand where the grid's lattice put them,
so whether two corners have the straight between them for both bends follows the lattice too: searched and pulled
with room alone, the first bundle on the knee routed at steps 0.125 and 0.13 and was refused at 0.1275, and the
second was refused at 26 of the 76 steps from 0.0125 to 0.2. Three things take the lattice out of the answer.
- A corner keeps its floor's tangent before a neighbour gets more (above), and the pin's corner holds what its
sharpest roll takes, exactly (`route.sharpest_turn`: the turn's cosine over a range of rolls is a + b cos + c sin).
- A seed that is refused is refined in continuous space (`route.relax`). About each segment too short for its
corners' tangents at the floor (`route.strain`), a vertex the search placed is dropped, moved along each axis and
along its own two segments, or joined by a new one beside a segment's middle; the try that lowers the shortfall
most is kept if `route.measure` proves its changed segments clear with the room a leg is pulled with. The moves
start a floor long and halve when nothing helps, down to 1 mm. Ports, lead ends, clamp straights and the pin
point do not move. The refinement prices straight only: room for an arc is still measured by the fillet after it.
- A route still refused is searched again on two more grid origins (half a step along each axis; then 0.31, 0.67
and 0.13 of a step), and then at half the step on all three, each seed refined the same way. `seed` in the
report is the step and origin that gave the route and whether it was refined.
The cost is in the refusals and in sameness: a route that cannot be made runs up to six seeds, three of them on 8
times the voxels, before it is refused, and the same request at another `step` may take another way round, though
never one that clears less than the clearance or bends under the floor.
A refusal after all that says what was tried, and that this shows no route was found, not that none exists: `the
search found no route: it tried steps 0.02 and 0.01, each on grid origins (0, 0, 0), (0.5, 0.5, 0.5), (0.31, 0.67,
0.13) of a step, and refined each seed in continuous space; this does not show that no route exists. The first
refusal: corner 2 at ...`. The first refusal is the requested step's own seed's, by corner, point or roll, with
what that polyline lacked: straight for a tangent, room for an arc (both distances named), or a segment two corners
cannot share. An end that stands nearer an obstacle than the bundle needs is refused at once: no grid lifts that.
`too stiff` is said only where it is proven (`route.leaves`). For its first pi floors of length a curve that bends
no tighter than the floor stays out of every ball of radius floor that touches its line where it starts, and ahead
of that point, and by then it stands 2 floors away (Schwarz's bound on a chord; Dubins 1957). So where a fitting's
lead ends, the hose must reach the sphere of 2 floors through points that keep the clearance and lie outside those
balls. They are read on voxels of a sixth of the floor with the bound every other measurement uses, and when they
do not join the lead's end to the sphere no route exists at that `bend`: `the bundle is too stiff to leave its
start: from the end of its lead at ... no curve that bends at the floor radius ... or wider keeps ... from what
stands within ... of it`. The proof is tried at both ports when no route was found. It does not look at clamps or
the pin, so a bundle too stiff for the room there gets the search's refusal. The remedies are a lower `bend`,
thinner or fewer hoses, waypoints further apart (a larger `standoff`), or a clamp that leads the hose wide.
**Slack.** `sag` (outside diameters, default 1) lowers the middle of each free span's longest segment along world
-z, by less where the span runs steeply, and never by more than half the room measured along it: both halves then
keep the clearance with as much room again for the arc at the middle. A route that the sag would break is made
taut instead; the report's `sag` lists the metres each leg hangs. 0 routes taut.
**Clamps.** `clamps` is a JSON array of up to 8 `{"socket": "Object:socket"}`, `mount` sockets in order along the
hose. The bundle runs straight along the socket's y through the point its half width, the clearance and one hose
radius above the face, for 2 outside diameters each side, and gets a pad on the face and a strap around it. The
bundle lies flat on the first clamp; its ups are rotation minimising (Wang et al. 2008), so it does not twist
between clamps, and a later clamp's strap follows the bundle as it arrives.
**A pin.** A hose may cross one pin: a revolute connection between its ends' parts, found from their parent
chains. `joint` names a socket on that pin's axis whose z runs along it (the free end face of the pin: a strut's
`end_a_back`) and a `standoff`. The roll range the hose is proven over is the pin's own: its connection's limits,
stated once with `brokkr_kitbash.joint` (`{"limits": [-120, 20]}`) and read by every hose across it. A pin with no
limits is refused, naming that action, and so is a prismatic connection between the ends: a hose across a slide
is not routed. The hose passes through the point `standoff` beyond that
socket, on the axis, as a robot's dress pack does: the straights on each side then move with their own part and
only the bend at that point changes with the roll. The whole range is measured without posing anything, not a
list of rolls in it. Each roll from `lo` to `hi` in steps of 5 degrees answers for the rolls nearer it than any
other: within such a bin of half width w a point that stands rho from the pin's axis moves at most `rho * w`
against the other side's parts, so its reading against them counts for that much less. The bend at the pin has one
radius through a bin, the largest that fits at the bin's sharpest turn, and its two tangent segments are measured
for the clearance and the arc's dip more. A bin that falls short is halved and measured again at each half's
middle, down to 0.3 degrees of half width, so a range that is clear costs 9 rolls for 40 degrees and one that
passes near a part costs more only there (`rolls` reports how many were measured). A range that fails is refused
by roll, side and point (`roll 50.78: the hose's child's side reads 0.0264 m from the parts about the pin at
[-0.2122, -0.2044, 0.7269], counting the 0.0005875 m it can move against the other side's through the 0.156 degrees
either side of it: under the 0.0266 m the bundle needs`); when the sagged route and the taut one both fail the
refusal names both. `worstClearance` is the least reading over the range, each less what its point can move within
its bin. `lengthChange` is the centre line's longest less its shortest over the rolls measured, as each rounds the
bend. Two pins between the ends are refused: end the hose on a part between them.
Another hose through the same pin bends with it and belongs to neither side. A route keeps clear of it where it
stands, and across the rolls each hose is measured against the parts of the two sides, not against where the other
hose stood: give two hoses through one pin different standoffs, and their clearance from each other holds at the
pose they were routed at. That is a ruled limit (`aetheria-release:ruling:hose-same-pin-pose-only-now`), and the
check it leaves out has an owner: follow-up `aetheria-release:follow_up:hose-motion-clearance-from-skinning` will pose
each other hose across the range with the skin blend the output mesh uses. Until it lands nothing measures two hoses
through one pin against each other in motion.
**What it writes.** One mesh object, a child of the start's object under identity matrices, with no modifier and
no material: each hose, two ferrule collars at each of its ends, and the clamps, all swept by `core.sweep`.
`kit_hose` on it is the request as JSON; the one thing read back from it is which two parts a hose joins, by a
later hose that crosses the same pin. Other hoses are obstacles like any mesh, so route the stiffest first. The hose is a bake of the scene at the call: after a part moves or rolls, run `hose`
again with the same `object_name` and it is rebuilt in place.
A hose that crosses a pin stays one object. In the exported mesh it is skinned geometry, meant to be weighted
between the bones on either side of the pin, blending near the pin point; the posed shape then comes from the
skin, and the rebuild is for stills and for checking the range. This package writes no weights or vertex groups:
skin weights are `brokkr_rig`'s.
**Refusals**, each before anything is written: a name taken by an object that is no hose; an end or clamp that
names no object, no such socket, or a socket of the wrong type; a bundle wider than a port, naming both sizes; a
part that is scaled or that Blender does not evaluate; a pin crossed with no `joint`, a `joint` with no pin, two
pins, a `joint` socket off the pin's axis, a pin with no limits or standing outside them, a slide between the
ends; a search box over 524288 voxels,
naming a step that fits; an end nearer an obstacle than the bundle needs; a bundle proven too stiff to leave a
port; and, once every seed has been tried, no route found, with the first seed's refusal: no way through, a corner
under the floor by what its polyline lacked, a curve not proven to keep the clearance at a named point, or a roll
that fails.
**Cost.** Probes in Blender 5.3 on Starfire, medians of 3 interleaved repetitions: a nearest-face query on a tree of
81,920 faces takes 100 to 123 us uncapped and 3.4 us capped at 0.06 m, so every query is capped; on a grid of
97,061 voxels with a wall and a hole a heap A* took 8.47 s (56,824 pops) and the wavefront 0.26 s (100 waves); on
a knee of five boxes (96,565 voxels at 0.02 m) the occupancy took 0.46 s uncapped, the search 0.19 s, the pull, the
fillet and the verification under 2 ms together, 27 rolls 0.056 s and the sweep of three hoses 4 ms. The live
knee of `tests/live/kitbash_hose.py` (two struts, two actuators and a plate; two legs of 79,488 and 53,406
voxels at roll 0, timed at roll 10; three hoses, 9 rolls) took 0.80 s a call, median of 3 each after one report
action, where it took 0.50 s when lines were sampled at half a voxel and each leg was searched once: the occupancy
is read to a larger cap and the room, the curve and the rolls are measured to 1 mm near what they pass. With
seeds refined and retried the same call took 0.64 s. Over the 76 steps from 0.0125 to 0.2 on that knee, one call
each with three other Blenders running, the first bundle took 0.53 s at the median and 2.34 s at most, and the
second 0.32 s and 2.56 s; of the second's 76 routes 8 came from a refined seed, 3 from another grid origin and 12
from half the step.
`tests/test_route.py` proves the path without Blender (the half-diagonal rule, a plate between two readings, a leg's
room where it wraps, the fillet's tangency, sharing, room and floor, a corner's floor before its neighbour's share, a
seed refined where the oracle allows, the proof of too stiff, the sharpest turn of a range of rolls, the sag's bound, the frames against the double
reflection method, the rolls and a plate between two of them, the bend at the pin's room), and
`tests/live/kitbash_hose.py` the action in Blender.
## Expressions
Every numeric field of a shape or socket, and `bevel`, is a number or a string over the part's params:
@ -618,26 +993,179 @@ field. Nothing in a kit is run as Python. Division by zero, a result that is not
or `segments` that is not whole are refused when the part is built, naming the expression; so is a shape whose
vertices overflow.
## Rams and linkages
`brokkr_kitbash/ram.py` owns the motion of a ram across one hinge. It is numpy and the standard library, imports
nothing from the package, and no action calls it yet: a rig or a runtime loads the file alone. Its input is a
mechanism record: the hinge (pivot, unit axis, `lo` and `hi` in degrees, positive right-handed about the axis like
a pin joint's roll), a kind, and pins, each in its own body's rest frame.
| kind | pins | the ram runs |
| --- | --- | --- |
| `direct` | `a` on the parent, `b` on the child | `a` to `b` |
| `four_bar` | `a`; `rocker` (R), the rocker's pivot on the parent; `p` on the rocker; `c` on the child; `d` = `p` | `a` to `p`: the excavator bucket linkage, a coupler from `p` to `c` turning the child |
| `bell_crank` | the same, `d` elsewhere on the rocker, at least 2 bore from `p` | `a` to `d` |
Everything is a function of the record and the hinge angle: `pose` gives each body's rotation, the ram's base and
eye, its pin-to-pin length L and dL/dtheta; `length` and `extension` (L less the closed length) are what a rig
drives a rod from. Nothing stores a rocker angle or an extension. The loop is solved in the plane across the axis:
`p` lies where the rocker's circle about R meets the coupler's about `c`, on the side of R -> `c` it has at rest,
so an angle gives the same pose whatever was asked before it. A pin's coordinate along the axis says only where
its member stands: the rocker bars at R's, the coupler at `c`'s, the ram at `a`'s plus each of `offsets` (twins).
Rates are closed form: for a linkage dphi/dtheta = (axis x (c - O)) . k / ((axis x (p - R)) . k), k along the
coupler, and dL/dtheta = (axis x (d - R)) . u x dphi/dtheta, u along the ram.
`fit` runs the gates over the range, in this order. A failed gate is a `RamError` naming the kind, the gate, the
angle and the pin, with the readings attached; a refusal of the record or of a call (an unknown kind, a range, a
grid over the limit, a version) names the pin or the field it refuses.
- **assembly**: the rocker and coupler close the loop at every step, and on the way from rest when the range does
not hold 0; within 1e-9 of a dead centre is refused, since the branch would change there. Names `c`.
- **stroke**: the barrel holds the travel, the overtravel at both ends and the gland. Names the angle of the
shortest length and the eye's pin.
- **toggle**, **arm**: dL/dtheta keeps one sign, and |dL/dtheta| (the effective arm: hinge torque per unit ram
force) stays at or above `min_arm`. Name the eye's pin.
- **load** (linkages): the coupler's pin load per unit ram force, |dL/dtheta| over the coupler's moment arm about
the hinge, stays at or under `max_load` (3). Names `c`.
- **clash**: clearance, when a distance oracle is given. Names the member, the part, and the member's nearer pin.
The barrel is derived, never stored: `barrel_length` is the length at the shorter end of the range less the
overtravel, the base clevis and the eye, and `fit` reads it from its own two end samples.
Transmission angles at `c` and `p` are reported and not gated. Over the R-3 knee's 125 degrees the best least
transmission angle of 200,000 sampled four-bars was 21.9 degrees, under the 30 to 40 a textbook asks; a gate there
would have refused every one of them. What a poor angle costs is pin load, and that is the gate.
### Clearance: parts, and zones about a member's pins
The record names the mechanism's `parts`, each a piece of one body (part -> parent, child, rocker or coupler: the
body whose rest frame it turns with), and `touch`: for each member (`barrel`, `rod`, `rocker`, `coupler`, and a
bell crank's `rocker arm`), zones `(part, pin, radius, depth)`. Every member meets every part. A zone changes what
the member's samples keep from one part, and only within `radius` of the axis of `pin`, measured across the hinge
axis; the pin is one the member rides (the ram `a` and its eye, the rocker its pivot and `p`, the coupler `p` and
`c`, the arm the pivot and `d`). Inside the zone a sample may come as near the part as `-depth`; beyond it the
pair is checked like any other. Nothing is exempt by a name, by a length cut from a member's end, or by the
member's own body: the barrel runs from its back end, the rod to the eye, a bar from pin to pin. Every body of the
kind owns at least one part, or the gate refuses the record.
A zone's radius is the eye's radius plus a margin: the pin's, collar's or cheek's radius plus what the member
keeps (radius, gap, half the spacing). Its depth says how the member stands to the part there. 0 is beside it: a
plate stacked on the pin, the bracket or horn the pin stands in. The member's axis then stays outside the part, so
a pin whose place along the axis is inside what it claims to stand beside is refused: the gate does not take the
record's x on trust. The pin's radius is for the pin through the member's eye, half the plate's thickness for the
member's own plate, which is zoned about both of the member's pins. Two plates stacked on a pin cross like
scissors; the zone that lets one link by the other's plate reaches as far as the two part, (half width + what a
link keeps) / sin of the least angle they cross at, and no further than the link is long. Two zones of one pair
that both reach a sample let it the deeper of the two.
A zone is bounded by its member. Its radius and its depth are finite and no more than the member's length from pin
to pin: a bar's length between its pins, and for the barrel and the rod the base's and the eye's distances from
the centre the eye turns about, added. A `Mechanism` refuses a zone past that from its pins alone. Its depth is
also no more than the member's eye on that pin (`Ram.eye`: `e_a` at the base, `e_b` at the rod's eye, `link_r` on
a bar), which `from_record` and the gate refuse, so a world's answer is held to it as well. The record holds no
plate widths, so the radius has no tighter bound than the length.
Between two samples of which either is in a zone the gate does not rely on the spacing. A distance changes by no
more than the way between two points, so along a segment it is at least (g(a) + g(b) - length) / 2. Where that
does not show the segment keeps `-depth`, the gate halves it and reads the midpoint, down to spacing / 64. A
segment still unproved there against a part the axis is held outside (depth 0) is refused: the part is within
spacing / 128 of the axis, crossed or touched, whatever its thickness. Against a part the axis may enter, the
samples' readings stand, so a burial is read to spacing / 128. This asks of the oracle that it never reads more
than the true distance.
What it gives up: inside a zone the gate holds only the member's axis `depth` from the part, not its surface a
gap from it, so a link may graze the plate it scissors with anywhere within the stated radius. The members are
round bars; a plate's flat sides are not modelled, which is why stacked plates need a zone at all. The proof
between samples costs oracle calls: a depth stated with no slack over the burial (a bar's own plates at `link_r`)
is halved to the floor along the whole zone. And it is along the axis at each checked angle; between two angles
nothing is proved.
The oracle is `distance(part, points) -> distances`, `points` in the rest frame of the part's body. Each member is
sampled along its axis at most `spacing` apart (default the barrel's radius) and carried into each body's rest
frame at each angle; a sample is clear at radius + gap + spacing / 2 or more, which keeps the gap for the surface
between samples. A distance is signed: negative inside a part, by any depth. The oracle may cap what it returns at
`Ram.reach(spacing)`, outside a part only; a point inside reads negative however deep it lies. An oracle that
cannot tell inside from outside raises instead of answering (a nearest-surface query alone reads 0.13 at the
centre of the R-3 thigh's core, and reads clear when capped); nan is refused. `Fit.pairs` holds the least margin
and its angle for every pair, `Fit.allowed` the pairs a zone lets near a pin.
`search` seats a mechanism from a grid (ram seats; for linkages rocker pivots, child pins, `p` on a polar grid
about R, and `d` about R for a bell crank, the eye standing at `a`'s place along the axis), refuses a grid over
`limit` candidates naming the count, runs every gate but clearance on all of them, then clearance in order of
least arm; a miss returns the tally by gate and the nearest miss. Clearance takes `world(m) -> (parts, touch,
distance)`: a linkage's brackets and links are the candidate's own, so each candidate that reaches the gate is met
with the parts its own pins place. What `world` returns is read as a record's: anything but the three, a part on
no body of the kind, a zone that is not a part, a pin the member rides, a radius and a depth, or a zone wider or
deeper than its member is refused.
`swept` gives the ram's swept surface in any body's frame, for a recess.
### The record
`record` and `from_record` carry a mechanism as JSON: `schema` (`brokkr.ram`), `version` (1), `kind`, `hinge`,
`pins`, `offsets`, `ram`, `parts`, `touch` (member -> zones, each `{part, pin, radius, depth}`), and `compliance`.
It holds what is authored; barrel, closed length and link lengths are derived by the reader. `compliance` is
reserved for a load-path ram's settle (stiffness, damping, travel); version 1 writes it null and solves none. A
record of another schema or version (the integer 1: 1.0 and true are not it), with a key version 1 does not know or
without one it does (at the top, in `ram`, `hinge`, `pins` or a zone), with a compliance block, or with a value
that is not its field's (a finite number, the bore over 0, three numbers for a point), or with a zone wider or
deeper than its member is refused whole, as a
`RamError` that names the field: a reader never reads past what it cannot solve. A `Ram` built by hand refuses the
same numbers.
### Readings on the R-3 knee
Bore 0.042, range 0..-125. The kinematic rows are tests/test_ram.py's. The clearance rows are
`tests/live/ram_knee.py`'s, Blender 5.3 (`ram_knee.result.json` is the last run): the knee as closed meshes the
test generates (thigh with its front plate, shin with caps and armour, the bracket that carries R, the horn that
carries `c`, twin link plates stacked 5 mm apart at x 0.31..0.345 and 0.35..0.385, pins through the knee's width,
collars at the eye and a base clevis whose foot runs 0.01 into the thigh; 12 parts) and the package's signed BVH
oracle, `ram.Signed(shells, cap)`: the nearest face for the depth, the crossing parity of three rays, by majority,
for the side. One ray that runs through an edge or a vertex miscounts and signs a sample inside a plate it stands
clear of. `tests/fixtures/ram_rays.json` holds the ray count: the rocker plates as the joint library builds them
and 24 points between the plates, each on the first ray short of an edge or a vertex. One ray signs all 24
inside; three sign none. Three rays are not a proof: of 146 such points one ray missigned, two rays missigned 16.
| drive | reading |
| --- | --- |
| direct, the joint library's seats, 0..-62 | fits (analytic thigh and shin) |
| direct, 2,000 seat pairs behind the knee | none fits (analytic thigh and shin) |
| four-bar behind the knee | passes every gate before clearance: rocker swing 70.5, L 0.722..1.168, arm 0.096..0.265, pin load 1.61, transmission 16.5. Refused on the meshes: the barrel and the rod against the shin's body (the barrel 0.122 inside its clearance, 49 steps), a body the ram is not pinned to |
| bell crank in front of the knee | fits on the meshes, the plates on either side: rocker swing 105.7, L 0.659..1.038, arm 0.091..0.215, pin load 1.13, transmission 13.8. 60 pairs, 20 of them with a zone. Over 251 steps, uncapped, the least margin of a pair with no zone is 0.034 (the rocker and the eye's pin at -125), then 0.039 (the rod and the rocker's pivot pin at -125) and 0.042 (the coupler and the bracket at 0). With `touch` empty the same gate refuses 19 pairs, each one a zoned pair; each stated zone takes in the least zone that lets its pair. A zone cut to half its radius refuses its pair |
| the same, a link's x moved | the rocker at x 0.25 (inside the bracket's 0.13..0.35) is refused 0.054 inside the bracket; the coupler at 0.25 (inside the horn's 0.23..0.31) 0.020 inside the horn |
| bell-crank search on the meshes | 13,824 candidates, each world built from the candidate's pins: 78 pass the gates before clearance, 21 of them are refused on their own parts, the 22nd fits (arm 0.090, swing 99.9, pin load 0.73) and holds at 251 steps |
Cost on Starfire, Python 3.13, 100 repetitions paired and interleaved: one candidate's gates before clearance at
49 steps took 0.79 ms median on the bell crank; its clearance against the analytic parts (50 pairs) took 42 ms
(5th to 95th percentile 38 to 57) over 97,875 points, of which 23,520 are the samples and the rest the halving in
zones (the own plates, stated with no slack, to the floor); the samples alone took 11 ms. A search without a world ran 1.6 to 1.8 ms a candidate over 3,456, so `limit`
(20,000) is 30 to 40 s. On the meshes the bell crank's 60 pairs at 49 steps took 1.95 to 2.12 s capped (two runs), in a
Python loop of BVH queries with three rays a sample, and the 13,824-candidate search with its 22 worlds 43 s (one run).
## The actions
| action | fields | what it does |
| --- | --- | --- |
| `brokkr_kitbash.describe` | `kit` (default `mechanical`), `part` (default: all) | Parts with their params (type, min, max, default, doc) and sockets in the part frame at default params. Changes nothing. |
| `brokkr_kitbash.place_part` | `kit`, `part`, `object_name`, `params` | A new mesh object at the origin: the part's mesh, a `Kit Bevel` modifier when the part has a bevel, and the three ID properties. Refuses a name an object already has. |
| `brokkr_kitbash.set_params` | `object_name`, `params` | Overlays `params` on the stored ones and rebuilds the mesh in the same datablock: modifiers and material slots stay, and the Bevel width follows. Per-face materials are carried by shape: each shape of the part keeps the material most of its faces had, whatever the new face count. Seats the part and the parts attached to it again; refuses a change that breaks a connection or a closure's mate, and a baked part. Reports the part and `closures`, every closure in the scene as `{part, to, holds}`: its own first, then the broken, then the rest; rows that would not fit a receipt are left off the end and counted in `closuresOmitted`. Each closure in the scene adds a few milliseconds (both its parts are built again to find their sockets). |
| `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 `baked`. Changes nothing and evaluates no modifier. |
| `brokkr_kitbash.set_params` | `object_name`, `params` | Overlays `params` on the stored ones and rebuilds the mesh in the same datablock: modifiers and material slots stay, and the Bevel width follows. Per-face materials are carried by shape: each shape of the part keeps the material most of its faces had, whatever the new face count. Seats the part and the parts attached to it again; refuses a change that breaks a connection or a closure's mate, and a frozen part. Reports the part and `closures`, every closure in the scene as `{part, to, holds}`: its own first, then the broken, then the rest; rows that would not fit a receipt are left off the end and counted in `closuresOmitted`. Each closure in the scene adds a few milliseconds (both its parts are built again to find their sockets). |
| `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.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.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`). |
| `brokkr_kitbash.cut_many` | `object_name` (any mesh), `cuts` (a JSON array of 1 to 64 cutters) | `cut` for several cutters in one action: all placed or none, one evaluation of the target afterwards. Reports `object`, `cutters` (names) and `booleans` (with `booleansOmitted`, as `boolean`). |
| `brokkr_kitbash.apply` | `object_name` | Bakes the evaluated mesh into the kit part and clears its modifiers and the collections its Booleans held. Refuses a part with no modifiers, a mesh another object shares and a part Blender does not evaluate. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. |
| `brokkr_kitbash.freeze` | `object_name` (any mesh with modifiers) | Makes the evaluated mesh the object's mesh, holds the live mesh in `kit_frozen` and turns every modifier off, keeping the stack, its collections and the cutters. Refuses a frozen object, one with no modifiers, one with a modifier already off and one Blender does not evaluate. Reports the part (or `object`), `frozen`, `faces` (live), `evaluated: {faces, volume, nonManifoldEdges}`, `modifiers` and `booleans`. |
| `brokkr_kitbash.thaw` | `object_name` | Puts the live mesh back, turns every modifier on and removes the frozen mesh; evaluates nothing. Refuses an object that is not frozen or whose held mesh is gone. Reports `object`, `frozen`, `modifiers` and the live mesh's `faces`. |
| `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`. |
`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.
@ -671,7 +1199,7 @@ assembly by its root: an attached part is placed by its connection.
{"action": "createObject", "objectType": "MESH", "name": "Cutter", "location": [0.3, 0.6, 0], "size": 0.2},
{"action": "brokkr_kitbash.boolean", "object_name": "Tank", "cutter": "Cutter"},
{"action": "setObjectVisibility", "targetObjectName": "Cutter", "visible": false},
{"action": "brokkr_kitbash.apply", "object_name": "Tank"},
{"action": "brokkr_kitbash.freeze", "object_name": "Tank"},
{"action": "brokkr_kitbash.report", "object_name": "Nozzle"},
{"action": "exportGltf", "filepath": "engine.glb", "selection": ["Tank", "Tee", "Nozzle"]}
]}
@ -683,8 +1211,9 @@ file holds each report in `hostResult`. `tools/turntable_recipe.py` renders the
## The mechanical kit
`kits/mechanical.v0.json`: eleven parts, each along +z, with socket types `flange` (equal), `mount` (fits) and
`pivot` (equal).
`kits/mechanical.v0.json`: thirteen parts, each along +z, with socket types `flange` (equal), `mount` (fits),
`pivot` (equal, revolute), `slide` (equal, prismatic: a telescoping bore, sized by its diameter) and `hose` (fits:
a port takes a bundle no wider than its size).
| part | params | sockets |
| --- | --- | --- |
@ -692,7 +1221,9 @@ file holds each report in `hostResult`. `tools/turntable_recipe.py` renders the
| `tank` | `radius`, `length`, `segments` | `port_a`, `port_b` (flange), `saddle` (mount), `lug_a`, `lug_b`, `lug_a_back`, `lug_b_back` (mount): a lug on each side (+x, and -x for `_back`) of each strap |
| `ribbed_cylinder` | `radius`, `length`, `ribs`, `rib_depth`, `rib_width`, `segments` | `end_a`, `end_b` (flange) |
| `strut` | `length`, `width`, `thickness`, `segments` | `end_a`, `end_a_back`, `end_b`, `end_b_back` (pivot): the two end faces of the pin at each end |
| `actuator` | `body_r`, `body_len`, `rod_r`, `extension`, `segments` | `base`, `base_back`, `rod_end`, `rod_end_back` (pivot); the rod end's two move with `extension` |
| `actuator` | `body_r`, `body_len`, `rod_r`, `extension`, `segments` | `base`, `base_back`, `rod_end`, `rod_end_back` (pivot); the rod end's two move with `extension`; `port_cap`, `port_rod` (hose, `0.4*body_r` wide) on the end faces of its two port bosses |
| `ram_barrel` | `body_r`, `body_len`, `rod_r`, `segments` | the actuator up to its gland: `base`, `base_back` (pivot); `bore` (slide, `2*rod_r`) at the closed piston face, its z along the barrel; `port_cap`, `port_rod` (hose) |
| `ram_rod` | `body_r`, `rod_r`, `length`, `segments` | the actuator from its gland: `piston` (slide, `2*rod_r`); `rod_end`, `rod_end_back` (pivot). In a barrel's bore slide 0 is closed and the slide is the extension; a rod of `length` `body_len + 1.1*body_r` stands as the actuator does |
| `pipe_fitting` | `pipe_r`, `run`, `branch`, `flange_r`, `flange_t`, `segments` | `a`, `b`, `c` (flange) |
| `radiator_stack` | `fins`, `fin_w`, `fin_h`, `fin_t`, `pitch`, `segments` | `base` (mount) |
| `vent` | `width`, `height`, `depth`, `slats`, `slat_t`, `tilt` | `back` (mount) |
@ -724,7 +1255,7 @@ on the other then lie in one plane and can meet at a pin: a braced leg.
## The frame kit
`kits/frame.v0.json`: nine parts of chassis structure, every shell an extrude. Its socket types are `mount` (fits)
and `pivot` (equal), the same two lines as `mechanical`'s, so a frame part seats on a mechanical one and the other
and `pivot` (equal, revolute), the same two lines as `mechanical`'s, so a frame part seats on a mechanical one and the other
way round (`place_part` and `describe` take `kit: "frame"`).
| part | params | what it is | sockets |
@ -753,7 +1284,7 @@ python -m unittest discover -s surfaces/blender/tests -p "test_kitbash.py" -v
16 seeded draws, and checks that every shell is closed and wound outward, every socket frame is right-handed and
seated on a face that faces its `z`, and no build passes 20000 faces. Choose param ranges so every combination
builds: a `min` or `max` in an expression keeps a derived length positive where two params could cross. A new
part of `mechanical` also joins the part and socket list in `test_the_kit_is_the_eleven_parts_and_three_socket_types`.
part of `mechanical` also joins the part and socket list in `test_the_kit_is_the_thirteen_parts_and_five_socket_types`.
`FrameKitTests` holds `frame` to the same (the seat check reads a cap that is not convex, an I section's, as it
reads a convex one), with the truss's shells and chords, the portal's mitres, its web in the frame's plane and its
feet apart, each beam's `w` across x and `h` along y, and a beam seated on a mechanical
@ -762,6 +1293,6 @@ frame `cut` gives a cutter. `MateTests` covers the mate arithmetic and what may
`PoseTests` the closed-form rolls. The operators are exercised in a real Blender by
`tests/live/kitbash.py` (placing and re-parameterising, and the frame kit: its nine parts placed, the truss
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 apply), `tests/live/kitbash_shell.py`
`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).

View file

@ -1,18 +1,18 @@
# Reference views: the camera a picture was drawn through
# Reference views: the camera a picture was drawn through, and traced lines scored against the build
`surfaces/blender/brokkr_reference` is a Blender add-on that fits a scene to a reference image. A concept sheet,
a render or a photograph draws its subject through a camera nobody wrote down; given points whose place in the
world is known and the pixel where the image draws each, `solve_camera` finds that camera, so that a render through
it lays over the image pixel for pixel and a line traced on the image can be lifted into the scene.
it lays over the image pixel for pixel and a line traced on the image can be scored against the build's edges.
It is a host add-on in Brokkr's sense (`install.md`, "Host add-on actions"), a sibling of `brokkr_mesh_polish`: it
imports that package's operator base and `Refused`, and nothing from `brokkr_bridge`. Enable `brokkr_mesh_polish`
first; `brokkr_reference` refuses to register without it. `brokkr_actions.json` beside its `__init__.py` lists the
one operator agents may run; the arithmetic is `core.py` (numpy only, tested without Blender), which a script may
two operators agents may run (`solve_camera`, `flow_score`); the arithmetic is `core.py` (numpy only, tested without Blender), which a script may
import directly. The action writes its JSON report to `brokkr_mesh_polish_result`, returned in the receipt's
`hostResult`.
The package takes points and gives cameras. The images, the marks on them, traces and masks belong to whoever
The package takes points and traced lines and gives cameras and scores. The images, the marks on them, traces and masks belong to whoever
made them; nothing here opens an image.
## Conventions
@ -29,7 +29,7 @@ made them; nothing here opens an image.
The record is the truth. A Blender camera stood at it (`core.blender`) is derived, and `core.camera_of` reads one
back into a record.
## The action
## solve_camera
`brokkr_reference.solve_camera`. Host action fields are scalar, so points go in as text:
@ -63,7 +63,7 @@ proportion. It does not make it the scene's active camera and does not touch `re
render through it at 100% is then the image's pixel less the box's corner, times `width` over the box's width
(`core.in_frame`; the frame's height is a whole number of pixels, so it can stand half a pixel off the box's).
The report is the camera record: `C`, `R`, `f`, `c`, `box`, `lens`, `lens_band`, `lens_at_bound`, `rms`, `median`
The report is the camera record: `C`, `R`, `f`, `c`, `box`, `lens`, `lens_band`, `lens_at_bound`, `lens_determined`, `planarity`, `plane`, `rms`, `median`
and `worst` (`[name, pixels]`), `left_out` (the leave-one-out rms), `model`, `tried` (each model's `rms`,
`left_out` and `lens`), `azimuth`, `elevation` and `distance` (where the camera stands round the points' middle),
`roll`, `twist`, and `residuals` (`{name: [du, dv]}`, to a hundredth of a pixel in a receipt); plus `camera` (the
@ -72,9 +72,33 @@ object's name or null) and, when a camera was stood, `blender` (what `core.blend
Refusals name their cause: fewer than six shared names, a point that is not finite numbers, a name given twice, a
box of no width or height, a lens outside 4 to 4000 mm. Marks that cannot decide a camera are refused before any
solve: fewer than six different world points or six different pixels among the shared names (the message names two
that share one), pixels all on one line, world points all on one line, and world points all in one plane unless
`lens` is held and the model is `upright`, `rolled` or `square`. These are exact cases; points nearly in a line or
a plane are solved, and the band says what they leave open. A report never holds a number that is not finite.
that share one), pixels all on one line, world points all on one line, and world points all in one plane with the
model `free`. These are exact cases, to a billionth of the marks' extent (`core.EXACT`); points nearly in a line or
a plane are solved, and `lens_determined` and the band say what they leave open. A report never holds a number
that is not finite.
`planarity` is how flat the marked world points are: their least extent over their greatest, 0 for a plane, 0.3
for points spread through a box. World points all in one plane (a deck, a wall, a flat sheet of marks) are solved,
and `plane` is then the degrees between the line of sight and square-on to that plane (it is null otherwise). A
plane never decides the centre, so `auto` tries `upright` and `rolled` only.
Flat marks may not decide the lens, and `lens_determined` says whether these did. Seen obliquely a plane does, by
its foreshortening. Seen square-on it does not: every lens draws it the same from its own distance, and a small
tilt of the plane seen through a long lens draws what a short lens draws square-on, so the marks' error picks the
headline lens. Measured on a plane of thirteen marks through a 50 mm lens, each mark a pixel off, six seeds a tilt:
| degrees off square-on | headline lens, mm | band, mm | `lens_determined` |
| --- | --- | --- | --- |
| 0 | 4 to 4000 | 4 to 4000 | false, all six |
| 3 | 4 to 90 | 4 to 4000 (one 45 to 134) | false, all six |
| 6 | 42 to 62 | from 13 to 84, one 4 to 4000 | false, all six |
| 9 | 46 to 57 | from 35 to 69 | true in five |
| 15 | 48 to 53 | from 44 to 59 | true, all six |
| 30 | 49 to 51 | from 45 to 57 | true, all six |
The band held 50 mm in all 36. With marks 3 px off, one band of nine at 5 degrees did not (68 to 152, not
determined). When `lens_determined` is false, do not read `lens` as the lens: hold `lens` from another view, or mark
a point off the plane.
## How far to trust the lens
@ -85,13 +109,21 @@ and focal length trade against each other (a dolly zoom) and the picture barely
- The focal length is held inside 4 to 4000 mm. Without a bound the solve ran the focal length to overflow on long
views; past 4000 mm a view is orthographic to any marking. `lens_at_bound` is `"long"` or `"short"` when the
answer sits at an end: read that as "at least this long", not as a lens.
- `lens_band` is `[low, high]`: the lenses that, held and refitted, come within 1.1 times the best rms, walked out
from the best in steps of a tenth in log f until one misses or the bound is reached. It is an **equal-error
band, not a confidence interval**: it says which lenses the marks cannot tell apart, not where the true lens
lies, and on a probe one such band excluded the true lens. A band that ends at 4000 was stopped by the bound.
The walk's step is the band's resolution: each end is the last step that still fitted, so the true end lies up
to one step (about 10%) further out, and a band of `[x, x]` means the first step each way already missed, that
is, a band narrower than one 10% step each way, not a lens known exactly.
- `lens_band` is `[low, high]`, walked out from the best lens in steps of a tenth in log f (about 10%) to the first
lens each way that, held and refitted, misses 1.1 times the best rms. Every lens outside the band misses; each
end is the first step that did, so the lenses that fit end somewhere in the step before it, and a band is never
narrower than a step each way. The rms the walk is judged against is never taken under 1 pixel (`core.FINE`):
marks placed truer than a hand places them fit every lens of a flat view to a millionth of a pixel, and one of
those would be called best. It is an **equal-error band, not a confidence interval**: it says which lenses the
marks cannot tell apart, and on probes a few such bands excluded the true lens. A band that ends at 4000 or at 4
was stopped by the bound.
- For flat marks (`planarity` under 0.12, `core.PLANAR`) a band that reaches one end of the range is reported as
the whole range, 4 to 4000. What closes the other end of such a band is a tilt of the plane traded against the
lens, and the marks' error sets that either way: a square-on plane's band read 309 to 4000 mm on one seed with
the true lens at 50. This gives up the one-sided reading ("at least 300 mm") for flat marks; marks with depth
keep it.
- `lens_determined` is true when the band lies inside 4 to 4000 mm and spans no more than 1.57 times
(`core.DECIDED`), false otherwise, and null when `lens` was held.
- There is no prior. Where the data cannot decide, the answer is a wide band rather than a plausible-looking 50 mm.
- Hold `lens` only when views must agree: two views of one subject solved alone may each sit anywhere in their
bands, and a fit rendered from elsewhere than the reference view depends on the lens the band does not fix.
@ -107,6 +139,39 @@ place, not about a lift made in the view's own frame.
pseudo-Huber loss; `median` beside it shows when a few points carry the error. A solve with `auto` on 13 points
takes several seconds (three models, each from 16 starts, plus a left-out solve per point per model).
## flow_score: traced lines against built edges
`flow_score` says how much of each traced line the build already carries as an edge. It reads the evaluated meshes
(modifiers applied) and keeps the edges the camera sees: creases (two faces whose normals differ by more than
`angle` degrees, at least one of them facing the camera), contours (one face toward the camera, one away) and open
borders, each where two of three points along it are hidden behind nothing the scene shows. A face that looks away
by its winding does not count as seen, so a cage with flipped normals shows no creases.
| field | |
| --- | --- |
| `camera_name` | the camera object the view is seen through (`solve_camera` stands one) |
| `box` | `u0,v0,u1,v1`: the camera's frame on the image, in the pixels the lines were traced in; absent is the render's own frame from 0,0 |
| `height` | the figure's height in the box's pixels; an edge within 1% of it is near. 0 (default) is the box's height |
| `lines` | `tag: u,v u,v ...; tag: u,v u,v ...` |
| `objects` | `name; name; ...`, the meshes whose edges are read; absent is every mesh the render shows. Everything the scene shows hides |
| `angle` | degrees (default 18) |
The report: `lines` (`{tag: {on, off, run}}`), `edges` (the count of seen edges by kind), `objects` and `height`.
`on` is the share of the line with a seen edge within 1% of the height and within 20 degrees of the line's own
direction; `off` the mean distance to such an edge in % of the height, capped at 5; `run` the longest unbroken
share that is on. The edges themselves are not returned and not kept: they are computed on each call.
The hiding test's sight line stops short of each point by a thousandth (`HIDE`) of the diagonal of the edge's own
piece, the connected part of its mesh that it lies on, so that the edge's own faces do not hide it: a box joined
into one mesh with a ground 200 times its size keeps the box's margin. A surface nearer the edge than that hides
it when it stands further off than a thousandth of the diagonal of the object it belongs to, measured whole: the
margin is the smaller of the two, whatever else the scene holds. A greeble modelled into its hull's own connected
surface has the hull's margin, and a surface nearer it than a thousandth of the hull does not hide it. A strip 0.3% of a box's diagonal in front of an edge hides it at scales 0.01, 1 and
100, and with a ground 20 or 40 times the box among the meshes read; chips a fortieth of a box hide its edge from
0.05% of its diagonal. Past the own object's margin the first surface met decides. Edges read true from cameras to
about 20000 diagonals off, where the ray's own rounding reaches the margin. The action writes nothing to the scene (its row says `changesScene`
because the operator base pushes an undo step).
## What it cannot do
It solves one pinhole camera for one view: no lens distortion, no two views solved together, one turned group and
@ -122,9 +187,13 @@ cam = core.solve(world, pixels, box, model="auto") # dicts by name; the
u_v = core.project(cam, points) # where it draws world points
origin, direction = core.ray(cam, (u, v)) # a pixel's line of sight
point = core.lift(cam, (u, v), plane_point, plane_normal) # a traced pixel on a plane
run = core.crease_run(column) # the hard crease Blender builds from a cage column
score = core.along(line, segments, height) # on, off, run against [u0, v0, u1, v1] segments
params = core.blender(cam, 1000) # matrix_world, lens, shifts, resolution
cam2 = core.camera_of(params, box) # and back
```
The tests are `tests/test_reference.py` (no Blender) and `tests/live/reference.py` (a known scene rendered,
solved through the action and rendered again; `reference.result.json` is its last run).
The tests are `tests/test_reference.py` (no Blender), `tests/live/reference.py` (a known scene rendered, solved
through the action and rendered again; `reference.result.json` is its last run) and `tests/live/reference_flow.py`
(`crease_run` against Blender's own subdivision, a box and a folded sheet scored by `flow_score`;
`reference_flow.result.json` is its last run).

File diff suppressed because one or more lines are too long

View file

@ -1,5 +1,5 @@
"""Live proof, in a background Blender, that the brokkr_kitbash rows are admitted by Brokkr as host actions and that
the mechanical kit goes through run_intent: describe, place_part for all eleven parts, setObjectTransform,
the mechanical kit goes through run_intent: describe, place_part for all thirteen parts, setObjectTransform,
assignMaterial, set_params, report, the refusals, the frame kit's nine parts (placed, a truss re-parameterised, a beam
seated on a mechanical bracket), and exportGltf. Not part of the unittest run: it needs Blender.
@ -93,7 +93,7 @@ try:
kit = core.load_kit("mechanical")
receipt, described = send("brokkr_kitbash.describe")
names = [p["name"] for p in described["parts"]] if described else []
check("describe lists eleven parts, whole, inside a receipt", receipt["status"] == "accepted" and names == list(kit["parts"]) and len(names) == 11
check("describe lists thirteen parts, whole, inside a receipt", receipt["status"] == "accepted" and names == list(kit["parts"]) and len(names) == 13
and "[truncated]" not in receipt["hostResult"], [names, len(receipt.get("hostResult") or "")])
receipt, one = send("brokkr_kitbash.describe", part="actuator")
check("describe of one part gives its params and its sockets at default params", one and [p["name"] for p in one["parts"]] == ["actuator"]
@ -133,7 +133,7 @@ try:
check(f"place_part {name}: kit, part and every resolved param stored on the object, sockets reported in the part frame", obj is not None
and obj["kit_kit"] == "mechanical" and obj["kit_part"] == name and json.loads(obj["kit_params"]) == reference.params == report["params"]
and report["sockets"] == core.socket_rows(reference.sockets), report)
check("eleven parts are eleven mesh objects", len(bpy.data.objects) == 11 and all(o.type == "MESH" for o in bpy.data.objects), len(bpy.data.objects))
check("thirteen parts are thirteen mesh objects", len(bpy.data.objects) == 13 and all(o.type == "MESH" for o in bpy.data.objects), len(bpy.data.objects))
# --- set_params keeps what is not derived --------------------------------------------------------------------------------
reducer = bpy.data.objects["P_reducer"]
@ -252,7 +252,7 @@ try:
check("with the duplicate gone the vent's mesh is its own again and set_params rebuilds it", receipt["status"] == "accepted" and alone
and alone["params"]["slats"] == 9 and len(bpy.data.objects["P_vent"].data.polygons) == len(core.build(kit["parts"]["vent"], {"slats": 9}).counts), receipt["message"])
receipt, whole = send("brokkr_kitbash.report")
check("with scale back at 1 every part reports again", receipt["status"] == "accepted" and whole and len(whole["parts"]) == 11, receipt["message"])
check("with scale back at 1 every part reports again", receipt["status"] == "accepted" and whole and len(whole["parts"]) == 13, receipt["message"])
# --- the frame kit: every shell an extrude, a section swept along a path --------------------------------------------------
frame = core.load_kit("frame")
@ -301,7 +301,7 @@ try:
if glb.is_file():
blob = glb.read_bytes()
meshes = len(json.loads(blob[20:20 + int.from_bytes(blob[12:16], "little")]).get("meshes", []))
check("exportGltf of all eleven parts succeeds", receipt["status"] == "accepted" and meshes == 11, [receipt["message"], meshes])
check("exportGltf of all thirteen parts succeeds", receipt["status"] == "accepted" and meshes == 13, [receipt["message"], meshes])
R["placed"] = {name: {"faces": report["faces"], "shells": report["shells"], "bevel": report["bevel"], "sockets": [s["name"] for s in report["sockets"]]}
for name, report in placed.items() if report}

View file

@ -7,7 +7,7 @@
"detail": null
},
{
"name": "describe lists eleven parts, whole, inside a receipt",
"name": "describe lists thirteen parts, whole, inside a receipt",
"ok": true,
"detail": null
},
@ -121,6 +121,46 @@
"ok": true,
"detail": null
},
{
"name": "place_part ram_barrel: sharp_edge is true on exactly core's sharp edges (0)",
"ok": true,
"detail": null
},
{
"name": "place_part ram_barrel: core's faces, a valid mesh, core's flat faces, at the origin",
"ok": true,
"detail": null
},
{
"name": "place_part ram_barrel: a Bevel of the part's width, 2 segments, angle 30, that evaluates",
"ok": true,
"detail": null
},
{
"name": "place_part ram_barrel: kit, part and every resolved param stored on the object, sockets reported in the part frame",
"ok": true,
"detail": null
},
{
"name": "place_part ram_rod: sharp_edge is true on exactly core's sharp edges (0)",
"ok": true,
"detail": null
},
{
"name": "place_part ram_rod: core's faces, a valid mesh, core's flat faces, at the origin",
"ok": true,
"detail": null
},
{
"name": "place_part ram_rod: a Bevel of the part's width, 2 segments, angle 30, that evaluates",
"ok": true,
"detail": null
},
{
"name": "place_part ram_rod: kit, part and every resolved param stored on the object, sockets reported in the part frame",
"ok": true,
"detail": null
},
{
"name": "place_part pipe_fitting: sharp_edge is true on exactly core's sharp edges (0)",
"ok": true,
@ -242,7 +282,7 @@
"detail": null
},
{
"name": "eleven parts are eleven mesh objects",
"name": "thirteen parts are thirteen mesh objects",
"ok": true,
"detail": null
},
@ -452,7 +492,7 @@
"detail": null
},
{
"name": "exportGltf of all eleven parts succeeds",
"name": "exportGltf of all thirteen parts succeeds",
"ok": true,
"detail": null
}
@ -475,13 +515,18 @@
"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.apply",
"brokkr_kitbash.freeze",
"brokkr_kitbash.thaw",
"brokkr_kitbash.ribs",
"brokkr_kitbash.shell"
"brokkr_kitbash.shell",
"brokkr_kitbash.hose"
],
"frame": {
"beam_i": {
@ -608,6 +653,30 @@
"base",
"base_back",
"rod_end",
"rod_end_back",
"port_cap",
"port_rod"
]
},
"ram_barrel": {
"faces": 180,
"shells": 12,
"bevel": 0.0024,
"sockets": [
"base",
"base_back",
"bore",
"port_cap",
"port_rod"
]
},
"ram_rod": {
"faces": 58,
"shells": 3,
"bevel": 0.0024,
"sockets": [
"piston",
"rod_end",
"rod_end_back"
]
},

View file

@ -1,6 +1,6 @@
"""Live proof, in a background Blender, of brokkr_kitbash assembly through run_intent: attach and its refusals,
set_params seating a part and the parts attached to it again, a braced leg closed by close and what set_params,
attach and detach then do, drift and how it is cleared, a roll that is not a number, detach, boolean (one Exact Boolean modifier per operation over a collection of cutters, self-intersection on, above the Bevel), and apply with its material slots. Not part
attach and detach then do, drift and how it is cleared, a roll that is not a number, detach, boolean (one Exact Boolean modifier per operation over a collection of cutters, self-intersection on, above the Bevel), and freeze and thaw: the frozen shape, the round trip, the refusals, and what a frozen part costs. Not part
of the unittest run: it needs Blender.
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_assembly.py -- <out>
@ -21,6 +21,7 @@ import math
import os
import re
import sys
import time
import traceback
import tempfile
import types
@ -85,6 +86,12 @@ KEPT = 2.1e-4
# intersection off: overlapping shells cancel); separation 6.5 each side. A box through the barrel alone no longer
# tells the two apart: the barrel is one shell.
CUT = 0.039
# Seconds the scene's update takes after an orphan mesh is removed with three cut tanks frozen, over the same with them
# live (medians of three, interleaved; every other Boolean in the scene frozen first). Shipped 0.0022 (0.0023 s over 1.05 s); least
# claimed mutant 1.5 (F1, freeze leaves the modifiers on: the Booleans run again, on the frozen mesh); the
# geometric mean, separation 26 each side. A ratio of two times read in one process: what other work
# on the machine does to it is far under the separation.
FROZEN_COST = 0.057
# Metres an attached child is moved to read holds false. HELD is a rule, 1e-5; least claimed mutant 1e-2 (K12);
# the geometric mean of the two, separation 32 each side.
NUDGE = 3.2e-4
@ -178,6 +185,10 @@ def measure(mesh):
return row
def stack(obj):
return [m.name for m in obj.modifiers]
def evaluated(obj):
"""(faces, volume, non-manifold edges, material slot names) of the object with its modifiers, read here and not through the add-on."""
shown = obj.evaluated_get(bpy.context.evaluated_depsgraph_get())
@ -199,8 +210,7 @@ try:
radiator = place("Radiator", "radiator_stack", location=[0.0, 10.0, 0.0])
send("createObject", objectType="MESH", name="Plain", location=[0.0, 12.0, 0.0], size=0.3)
receipt, report = send("brokkr_kitbash.report", object_name="Tank")
check("a part nobody attached reports connection null and baked false", report and report["parts"][0]["connection"] is None
and report["parts"][0]["baked"] is False, report)
check("a part nobody attached reports connection null", report and report["parts"][0]["connection"] is None, report)
receipt, report = send("brokkr_kitbash.attach", object_name="Nozzle", socket="mount", parent_name="Tee", parent_socket="c", roll=37.0)
check("attach parents the nozzle to the tee under an identity parent inverse and stores the three properties", receipt["status"] == "accepted"
@ -599,35 +609,173 @@ try:
and len(tank.data.polygons) == len(core.build(kit["parts"]["tank"], report["params"]).counts) != raw["faces"]
and CUT < resized["volume"] < measure(tank.data)["volume"] - 0.005 and holds("Tee", "Tank", "b", "port_a", 180.0)[0], [receipt["message"], resized])
# --- apply ------------------------------------------------------------------------------------------------------------------------
refused("apply on a mesh that is not a kit part", "brokkr_kitbash.apply", {"object_name": "Plain"}, "'Plain' is not a kit part")
# --- freeze and thaw ----------------------------------------------------------------------------------------------------------
THAW = "thaw it first"
refused("freeze on a mesh with no modifiers", "brokkr_kitbash.freeze", {"object_name": "Plain"}, "'Plain' has no modifiers to freeze")
refused("thaw on a live part", "brokkr_kitbash.thaw", {"object_name": "Tank"}, "'Tank' is not frozen")
tank.modifiers["Kit Bevel"].show_render = False
refused("freeze on a part with a modifier already off names it", "brokkr_kitbash.freeze", {"object_name": "Tank"}, "'Tank' has Kit Bevel off in viewports or renders")
tank.modifiers["Kit Bevel"].show_render = True
slots = [s.material and s.material.name for s in tank.material_slots]
shown, shown_slots = evaluated(tank)
index = np.zeros(len(tank.data.polygons), dtype=np.int32)
tank.data.polygons.foreach_get("material_index", index)
mesh_name, meshes, collections = tank.data.name, len(bpy.data.meshes), len(bpy.data.collections)
mesh_name, live_faces, meshes, collections = tank.data.name, len(tank.data.polygons), len(bpy.data.meshes), len(bpy.data.collections)
sockets_before = send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0]["sockets"]
receipt, baked = send("brokkr_kitbash.apply", object_name="Tank")
receipt, frozen = send("brokkr_kitbash.freeze", object_name="Tank")
after = np.zeros(len(tank.data.polygons), dtype=np.int32)
tank.data.polygons.foreach_get("material_index", after)
check("apply makes the evaluated mesh the tank's mesh: the same faces and volume, no modifiers, one mesh datablock of the old name",
receipt["status"] == "accepted" and baked and {k: baked[k] for k in ("faces", "volume", "nonManifoldEdges")} == shown == measure(tank.data)
and len(tank.modifiers) == 0 and tank.data.name == mesh_name and len(bpy.data.meshes) == meshes and baked["cutters"] == ["Box"]
and len(bpy.data.collections) == collections - 1 and "Tank difference" not in bpy.data.collections and "Box" in bpy.context.scene.objects, [receipt["message"], baked, shown])
check("apply keeps the material slots exactly, and faces of both materials", slots == shown_slots == ["Tank Paint", "Strap Steel"]
facts = frozen and frozen["evaluated"]
check("freeze makes the evaluated mesh the tank's mesh: the same faces, volume and non-manifold edges, and the tank still evaluates to them",
receipt["status"] == "accepted" and facts == shown == measure(tank.data) == evaluated(tank)[0] and tank.data.name == "Tank frozen"
and len(bpy.data.meshes) == meshes + 1, [receipt["message"], facts, shown])
check("freeze holds the live mesh in kit_frozen and keeps the stack, off, with its collection and cutter", frozen and frozen["frozen"] is True and frozen["faces"] == live_faces
and tank["kit_frozen"].name == mesh_name and len(tank["kit_frozen"].polygons) == live_faces and stack(tank) == frozen["modifiers"] == ["Kit Difference", "Kit Bevel"]
and not any(m.show_viewport or m.show_render for m in tank.modifiers) and tank.modifiers["Kit Difference"].collection.objects[:] == [box]
and frozen["booleans"] == [{"cutter": "Box", "operation": "DIFFERENCE"}] and len(bpy.data.collections) == collections and "Box" in bpy.context.scene.objects,
[frozen, [(m.name, m.show_viewport, m.show_render) for m in tank.modifiers]])
check("freeze keeps the material slots exactly, and faces of both materials", slots == shown_slots == ["Tank Paint", "Strap Steel"]
and [s.material and s.material.name for s in tank.material_slots] == slots and [m and m.name for m in tank.data.materials] == slots
and index.max() == 1 and sorted(set(after.tolist())) == [0, 1], [slots, [m and m.name for m in tank.data.materials], sorted(set(after.tolist()))])
check("apply marks the part baked and keeps what it is", tank.get("kit_baked") is True and baked and baked["baked"] is True and tank["kit_part"] == "tank"
and json.loads(tank["kit_params"])["segments"] == 16, dict(tank.items()))
refused("set_params on a baked part", "brokkr_kitbash.set_params", {"object_name": "Tank", "params": "length=1.0"}, "'Tank' is baked")
refused("apply on a baked part with no modifiers left", "brokkr_kitbash.apply", {"object_name": "Tank"}, "'Tank' has no modifiers to apply")
check("a frozen part keeps what it is", frozen and tank["kit_part"] == "tank" and json.loads(tank["kit_params"])["segments"] == 16 and frozen["part"] == "tank", dict(tank.items()))
RAY = {"origin": [0.0, 0.0, 3.0], "direction": [0.0, 0.0, -1.0], "up": [0.0, 1.0, 0.0]}
refused("set_params on a frozen part", "brokkr_kitbash.set_params", {"object_name": "Tank", "params": "length=1.0"}, THAW)
refused("boolean on a frozen part", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Plain"}, THAW)
refused("cut on a frozen part", "brokkr_kitbash.cut", {"object_name": "Tank", "cutter_name": "Late", "part": "box", "origin_x": 0.0, "origin_y": 0.0, "origin_z": 3.0,
"direction_x": 0.0, "direction_y": 0.0, "direction_z": -1.0, "up_y": 1.0, "up_z": 0.0}, THAW)
refused("cut_many on a frozen part", "brokkr_kitbash.cut_many", {"object_name": "Tank", "cuts": json.dumps([{"name": "Late", "part": "box", **RAY}])}, THAW)
refused("freeze on a frozen part", "brokkr_kitbash.freeze", {"object_name": "Tank"}, THAW)
receipt, report = send("brokkr_kitbash.report", object_name="Tank")
check("a baked part still reports its sockets where its params put them, and what is attached to it still holds", report and report["parts"][0]["baked"] is True
and report["parts"][0]["sockets"] == sockets_before and report["parts"][0]["faces"] == baked["faces"] and holds("Tee", "Tank", "b", "port_a", 180.0)[0]
check("a frozen part still reports its sockets where its params put them, and what is attached to it still holds", report and report["parts"][0]["frozen"] is True
and report["parts"][0]["sockets"] == sockets_before and report["parts"][0]["faces"] == live_faces != shown["faces"] and report["parts"][0]["evaluated"] == {"faces": shown["faces"]}
and "dirty" not in report["parts"][0] and holds("Tee", "Tank", "b", "port_a", 180.0)[0]
and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], report)
receipt, report = send("brokkr_kitbash.attach", object_name="Radiator", socket="base", parent_name="Tank", parent_socket="saddle")
check("a new part attaches to a baked one", receipt["status"] == "accepted" and held(report)
check("a new part attaches to a frozen one", receipt["status"] == "accepted" and held(report)
and reading("seated", seated(radiator, "base", tank, "saddle", 0.0)) < SEATED, receipt["message"])
receipt, chilled = send("brokkr_kitbash.freeze", object_name="Tee")
receipt, report = send("brokkr_kitbash.roll", object_name="Tee", roll=90.0)
check("a frozen child rolls where it hangs on a frozen parent, and what hangs on it follows", receipt["status"] == "accepted" and chilled and chilled["frozen"] is True
and holds("Tee", "Tank", "b", "port_a", 90.0)[0] and reading("seated", seated(tee, "b", tank, "port_a", 90.0)) < SEATED
and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], [receipt["message"], connection("Tee")])
send("brokkr_kitbash.roll", object_name="Tee", roll=180.0)
bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True)
check("the held live mesh survives a purge of orphans", bpy.data.meshes.get(mesh_name) is not None and tank["kit_frozen"] == bpy.data.meshes[mesh_name]
and len(tank["kit_frozen"].polygons) == live_faces, sorted(m.name for m in bpy.data.meshes))
# kit_* belongs to the kit: the bridge's property setter refuses it, so kit_frozen keeps its one writer
for name in ("kit_frozen", "customProperties.kit_frozen", "kit_roll", "kit_anything"):
refused(f"setObjectCustomProperty on {name}", "setObjectCustomProperty", {"targetObjectName": "Tank", "propertyName": name, "value": "oops"}, "is brokkr_kitbash's own state (kit_*)")
# a modifier shown again by hand on a frozen part: the report says dirty, not frozen, and an export that applies modifiers refuses it
tank.modifiers["Kit Bevel"].show_viewport = True
dirty = send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0]
check("a frozen part with a modifier shown again reports dirty with the modifier, and not frozen", dirty["frozen"] is False and dirty["dirty"] == ["Kit Bevel"]
and dirty["faces"] == live_faces, dirty)
for label, fields in (("the scene", {}), ("the part by name", {"selection": ["Tank"]})):
refused(f"exportGltf applying modifiers over a dirty frozen part: {label}", "exportGltf", {"filepath": "dirty.glb", "applyModifiers": True, **fields},
"Tank: frozen (brokkr_kitbash.freeze) with a modifier shown again")
refused("set_params on a dirty frozen part, named dirty as its report names it", "brokkr_kitbash.set_params", {"object_name": "Tank", "params": "length=1.0"},
"'Tank' is frozen and dirty (Kit Bevel shown again), and setting params of it needs its live mesh and modifiers: thaw it first")
tank.modifiers["Kit Bevel"].show_viewport = False
tank.modifiers["Kit Bevel"].show_render = True # shown in renders only: dirty by the same rule, in the report and at the export
check("a frozen part with a modifier shown in renders only reports dirty", send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0].get("dirty") == ["Kit Bevel"])
refused("exportGltf applying modifiers over a frozen part dirty in renders only", "exportGltf", {"filepath": "dirty.glb", "applyModifiers": True, "selection": ["Tank"]},
"Tank: frozen (brokkr_kitbash.freeze) with a modifier shown again")
tank.modifiers["Kit Bevel"].show_render = False
check("with the modifier hidden again the part reports frozen; the refused exports wrote nothing", "dirty" not in send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0]
and send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0]["frozen"] is True and not (WORK / "dirty.glb").exists(), sorted(p.name for p in WORK.iterdir()))
for name in ("Tee", "Tank"):
receipt, thawed = send("brokkr_kitbash.thaw", object_name=name)
check("thaw puts the live mesh back, turns every modifier on and removes the frozen mesh", receipt["status"] == "accepted" and tank.data.name == mesh_name and "kit_frozen" not in tank
and thawed == {"object": "Tank", "frozen": False, "modifiers": ["Kit Difference", "Kit Bevel"], "faces": live_faces} and stack(tank) == ["Kit Difference", "Kit Bevel"]
and all(m.show_viewport and m.show_render for m in tank.modifiers) and "Tank frozen" not in bpy.data.meshes and "kit_frozen" not in tee
and len(bpy.data.collections) == collections and not tank.data.use_fake_user and "kit_kept" not in tank.data and tank.data.users == 1,
[receipt["message"], thawed, sorted(m.name for m in bpy.data.meshes), tank.data.users])
check("the thawed tank evaluates to what it did before freeze, and reports frozen false", evaluated(tank)[0] == shown
and send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0]["frozen"] is False, [evaluated(tank)[0], shown])
lost = place("Lost", "plate", location=[0.0, -24.0, 0.0])
lost_mesh = lost.data.name
send("brokkr_kitbash.freeze", object_name="Lost")
lost["kit_frozen"] = "oops" # by hand: no action writes it. The live mesh has lost its one real user
bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True)
check("a live mesh whose kit_frozen was overwritten by hand survives a purge of orphans", lost_mesh in bpy.data.meshes and bpy.data.meshes[lost_mesh].use_fake_user,
sorted(m.name for m in bpy.data.meshes))
refused("thaw on a frozen part whose kit_frozen was overwritten names the kept mesh", "brokkr_kitbash.thaw", {"object_name": "Lost"},
f"its kit_frozen no longer points at a mesh: freeze kept its live mesh {lost_mesh!r}. Point kit_frozen back at it by hand")
lost["kit_frozen"] = bpy.data.meshes[lost_mesh] # the way back, by hand, that the refusal names
receipt, _ = send("brokkr_kitbash.thaw", object_name="Lost")
check("and with the kept mesh put back in kit_frozen it thaws", receipt["status"] == "accepted" and lost.data.name == lost_mesh and not lost.data.use_fake_user, receipt["message"])
send("brokkr_kitbash.freeze", object_name="Lost")
bpy.data.meshes.remove(lost["kit_frozen"])
refused("thaw on a frozen part whose held mesh was removed", "brokkr_kitbash.thaw", {"object_name": "Lost"}, "no kept live mesh names the mesh it carries: there is nothing to thaw to")
# --- the frozen state has one writer, hold: what it does when the holder goes, by an action or by hand, and what an import may not bring ---
def purge():
bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True)
def saved_meshes(name):
"""The meshes a save writes, read from the file: a save and reload keeps these and no others."""
bpy.ops.wm.save_as_mainfile(filepath=str(WORK / name), copy=True)
with bpy.data.libraries.load(str(WORK / name)) as (source, _):
return sorted(source.meshes)
def kept_state(name):
mesh = bpy.data.meshes.get(name)
return mesh and [mesh.use_fake_user, getattr(mesh.get("kit_kept"), "name", mesh.get("kit_kept"))]
target.configure_action_dirs(str(WORK), str(WORK))
gone = place("Gone", "plate", location=[0.0, -27.0, 0.0])
gone_mesh = gone.data.name
send("brokkr_kitbash.freeze", object_name="Gone")
receipt, _ = send("exportGltf", filepath="gone_applied.glb", applyModifiers=True, selection=["Gone"])
send("brokkr_kitbash.thaw", object_name="Gone")
check("thaw after an export that applied modifiers leaves no frozen mesh behind", receipt["status"] == "accepted" and "Gone frozen" not in bpy.data.meshes
and gone.data.name == gone_mesh, [receipt["message"], sorted(m.name for m in bpy.data.meshes)])
send("brokkr_kitbash.freeze", object_name="Gone")
check("freeze gives the live mesh a fake user and kit_kept, a pointer to the frozen mesh; a save writes both", kept_state(gone_mesh) == [True, "Gone frozen"]
and {gone_mesh, "Gone frozen"} <= set(saved_meshes("held.blend")), kept_state(gone_mesh))
receipt, _ = send("exportGltf", filepath="gone.glb", applyModifiers=False, extras=True, selection=["Gone"])
exported = receipt["status"]
receipt, _ = send("deleteObject", targetObjectName="Gone")
purge()
check("deleteObject on a frozen object releases its live mesh: a purge takes it and the frozen mesh", receipt["status"] == "accepted" and exported == "accepted"
and gone_mesh not in bpy.data.meshes and "Gone frozen" not in bpy.data.meshes, [kept_state(gone_mesh), sorted(m.name for m in bpy.data.meshes)])
receipt, _ = send("importGltf", filepath="gone.glb")
back = bpy.data.objects.get("Gone")
check("importGltf drops the kit_* properties a file's extras carry, and says so: the imported object is not frozen and not a part", receipt["status"] == "accepted"
and back is not None and not [key for holder in (back, back.data) for key in holder.keys() if key.startswith("kit_")]
and "Dropped the file's kit_* properties from Gone" in receipt["message"], [receipt["message"], back and dict(back.items())])
refused("thaw on the imported object", "brokkr_kitbash.thaw", {"object_name": "Gone"}, "'Gone' is not frozen")
send("deleteObject", targetObjectName="Gone")
purge()
plain = place("Plain_gone", "plate", location=[0.0, -30.0, 0.0])
plain_mesh = plain.data.name
send("brokkr_kitbash.freeze", object_name="Plain_gone")
with bpy.context.temp_override(selected_objects=[plain]):
deleted = bpy.ops.object.delete()
written = saved_meshes("deleted.blend")
purge()
check("a frozen object deleted in Blender, by no action: a save writes neither mesh, and a purge takes both", deleted == {"FINISHED"} and "Plain_gone" not in bpy.data.objects
and plain_mesh not in written and "Plain_gone frozen" not in written and plain_mesh not in bpy.data.meshes and "Plain_gone frozen" not in bpy.data.meshes,
[deleted, written, sorted(m.name for m in bpy.data.meshes)])
hand = place("Hand", "plate", location=[0.0, -33.0, 0.0])
hand_mesh = hand.data.name
send("brokkr_kitbash.freeze", object_name="Hand")
del bpy.data.meshes[hand_mesh]["kit_kept"] # by hand
receipt, _ = send("brokkr_kitbash.thaw", object_name="Hand")
check("a kept mesh whose kit_kept was cleared by hand still gives its fake user back at thaw", receipt["status"] == "accepted" and kept_state(hand_mesh) == [False, None]
and hand.data.name == hand_mesh, [receipt["message"], kept_state(hand_mesh)])
send("brokkr_kitbash.freeze", object_name="Hand")
del hand["kit_frozen"] # by hand: the object still carries the frozen mesh the kept mesh names
purge()
check("a live mesh whose kit_frozen was deleted by hand stays kept through a purge and a save", kept_state(hand_mesh) == [True, "Hand frozen"]
and hand_mesh in saved_meshes("lost.blend"), kept_state(hand_mesh))
refused("thaw on a frozen part whose kit_frozen was deleted names the kept mesh", "brokkr_kitbash.thaw", {"object_name": "Hand"},
f"'Hand' carries a frozen mesh and its kit_frozen is gone: freeze kept its live mesh {hand_mesh!r}. Point kit_frozen back at it by hand")
hand["kit_frozen"] = bpy.data.meshes[hand_mesh]
receipt, _ = send("brokkr_kitbash.thaw", object_name="Hand")
check("and with kit_frozen pointed back it thaws and the mesh is released", receipt["status"] == "accepted" and hand.data.name == hand_mesh
and kept_state(hand_mesh) == [False, None] and "Hand frozen" not in bpy.data.meshes, [receipt["message"], kept_state(hand_mesh)])
target.configure_action_dirs("", str(WORK))
# --- the second target: a plate with no material slot, cut twice ----------------------------------------------------------------------
plate = place("Plate", "plate", location=[0.0, -3.0, 0.0])
@ -643,33 +791,35 @@ try:
and all(m.use_self and m.solver == "EXACT" for m in plate.modifiers if m.type == "BOOLEAN"),
[[m.name for m in plate.modifiers], first and first["evaluated"], second and second["evaluated"]])
R["plate"] = {"raw": measure(plate.data), "slot": first and first["evaluated"], "slotAndHole": second and second["evaluated"]}
twin = plate.copy()
twin = plate.copy() # a linked duplicate: it shares the live mesh, and keeps it
twin.name = "Plate_twin"
bpy.context.scene.collection.objects.link(twin)
refused("apply on a mesh a linked duplicate shares", "brokkr_kitbash.apply", {"object_name": "Plate"}, "shares its mesh 'Plate' with 1 other user(s): baking it")
bpy.data.objects.remove(twin)
shown, shown_slots = evaluated(plate)
receipt, baked = send("brokkr_kitbash.apply", object_name="Plate")
check("apply on a part with no material slot leaves it with none (Blender's Boolean shows it with one empty slot)", receipt["status"] == "accepted"
and shown_slots == [None] and len(plate.data.materials) == 0 and len(plate.material_slots) == 0 and baked["cutters"] == ["Slot", "Hole"]
and {k: baked[k] for k in ("faces", "volume", "nonManifoldEdges")} == shown, [shown_slots, len(plate.data.materials), len(plate.material_slots), baked])
receipt, frozen = send("brokkr_kitbash.freeze", object_name="Plate")
check("freeze on a part with no material slot leaves the frozen mesh with none (Blender's Boolean shows it with one empty slot); a linked duplicate keeps the live mesh",
receipt["status"] == "accepted" and shown_slots == [None] and len(plate.data.materials) == 0 and len(plate.material_slots) == 0
and frozen["booleans"] == second["booleans"] and frozen["evaluated"] == shown
and twin.data.name == "Plate" and plate["kit_frozen"] == twin.data and all(m.show_viewport for m in twin.modifiers),
[shown_slots, len(plate.data.materials), len(plate.material_slots), frozen])
bpy.data.objects.remove(twin)
send("brokkr_kitbash.thaw", object_name="Plate")
send("assignMaterial", targetObjectName="Plate", materialName="Plate Paint", color=[0.35, 0.35, 0.35])
send("createObject", objectType="MESH", name="Boss", location=[0.0, -3.0, 0.1], size=0.06)
send("assignMaterial", targetObjectName="Boss", materialName="Boss Brass", color=[0.6, 0.5, 0.2])
send("setObjectTransform", targetObjectName="Boss", location=[0.0, -3.0, 0.02])
receipt, third = send("brokkr_kitbash.boolean", object_name="Plate", cutter="Boss", operation="UNION")
shown, shown_slots = evaluated(plate)
receipt, baked = send("brokkr_kitbash.apply", object_name="Plate")
receipt, frozen = send("brokkr_kitbash.freeze", object_name="Plate")
used = np.zeros(len(plate.data.polygons), dtype=np.int32)
plate.data.polygons.foreach_get("material_index", used)
check("a baked part is cut and baked again; a cutter that has a material brings it after the part's own slots, on the faces it made",
receipt["status"] == "accepted" and third["booleans"] == [{"cutter": "Boss", "operation": "UNION"}] and third["baked"] is True
check("a thawed part is cut and frozen again; a cutter that has a material brings it after the part's own slots, on the faces it made",
receipt["status"] == "accepted" and third["booleans"][-1] == {"cutter": "Boss", "operation": "UNION"} and third["frozen"] is False and frozen["frozen"] is True
and third["evaluated"]["volume"] > R["plate"]["slotAndHole"]["volume"] and shown_slots == ["Plate Paint", "Boss Brass"]
and [m and m.name for m in plate.data.materials] == ["Plate Paint", "Boss Brass"] and sorted(set(used.tolist())) == [0, 1]
and len(plate.modifiers) == 0, [third and third["evaluated"], shown_slots, [m and m.name for m in plate.data.materials], sorted(set(used.tolist()))])
and stack(plate) == ["Kit Difference", "Kit Union", "Kit Bevel"], [third and third["evaluated"], shown_slots, [m and m.name for m in plate.data.materials], sorted(set(used.tolist()))])
vent = place("Vent", "vent", "width=0.2; height=0.15")
receipt, report = send("brokkr_kitbash.attach", object_name="Vent", socket="back", parent_name="Plate", parent_socket="front")
check("a vent that fits attaches to the baked plate's front", receipt["status"] == "accepted" and held(report)
check("a vent that fits attaches to the frozen plate's front", receipt["status"] == "accepted" and held(report)
and reading("seated", seated(vent, "back", plate, "front", 0.0)) < SEATED, receipt["message"])
refused("a loop of two", "brokkr_kitbash.attach", {"object_name": "Plate", "socket": "back", "parent_name": "Vent", "parent_socket": "back"},
"'Vent' is below 'Plate'")
@ -686,14 +836,14 @@ try:
check("a tee with a box cut from it has no non-manifold edge: its branch hub is narrower than its run hub", receipt["status"] == "accepted" and cut
and cut["evaluated"]["nonManifoldEdges"] == 0 and 0.004 < cut["evaluated"]["volume"] < 0.008, [receipt["message"], cut and cut["evaluated"]])
# --- apply and empty material slots -----------------------------------------------------------------------------------------------
# --- freeze and empty material slots ----------------------------------------------------------------------------------------------
keeper = place("Keeper", "plate", location=[0.0, -9.0, 0.0])
send("assignMaterial", targetObjectName="Keeper", materialName="Plate Paint", color=[0.35, 0.35, 0.35])
keeper.data.materials.append(None) # an empty last slot the part was given
send("createObject", objectType="MESH", name="Bare", location=[0.1, -9.0, 0.0], size=0.1)
send("brokkr_kitbash.boolean", object_name="Keeper", cutter="Bare")
receipt, baked = send("brokkr_kitbash.apply", object_name="Keeper")
check("apply keeps a part's own empty last slot when the cutter has no material", receipt["status"] == "accepted"
receipt, frozen = send("brokkr_kitbash.freeze", object_name="Keeper")
check("freeze keeps a part's own empty last slot when the cutter has no material", receipt["status"] == "accepted" and keeper.data.name == "Keeper frozen"
and [m and m.name for m in keeper.data.materials] == ["Plate Paint", None] and len(keeper.material_slots) == 2,
[receipt["message"], [m and m.name for m in keeper.data.materials]])
gapped = place("Gapped", "plate", location=[0.0, -12.0, 0.0])
@ -704,10 +854,10 @@ try:
gap.data.materials.append(bpy.data.materials["Boss Brass"])
gap.data.polygons[0].material_index = gap.data.polygons[1].material_index = 1 # two of its faces are brass; the rest stay in the empty slot
send("brokkr_kitbash.boolean", object_name="Gapped", cutter="Gap")
receipt, baked = send("brokkr_kitbash.apply", object_name="Gapped")
receipt, frozen = send("brokkr_kitbash.freeze", object_name="Gapped")
used = np.zeros(len(gapped.data.polygons), dtype=np.int32)
gapped.data.polygons.foreach_get("material_index", used)
check("apply leaves no face outside the material slots when a cutter's first slot is empty", receipt["status"] == "accepted" and len(used) > 44
check("freeze leaves no face outside the material slots when a cutter's first slot is empty", receipt["status"] == "accepted" and len(used) > 44
and used.min() >= 0 and used.max() < len(gapped.data.materials) and not gapped.data.validate_material_indices() and not gapped.data.validate(verbose=False),
[receipt["message"], int(used.min()), int(used.max()), [m and m.name for m in gapped.data.materials]])
names = [m and m.name for m in gapped.data.materials]
@ -716,6 +866,54 @@ try:
check("and each face keeps its own slot: the cutter's brass faces are brass, the faces from its empty slot and the plate's own are the plate's paint",
names[0] == "Plate Paint" and 0 < len(brass) < len(used) and far and all(used[i] == 0 for i in far)
and all(abs((gapped.matrix_world @ gapped.data.polygons[i].center).x - 0.1) < 0.051 for i in brass), [names, len(brass), len(far), sorted(set(used.tolist()))])
# --- a frozen part is cheap -------------------------------------------------------------------------------------------------------
# Blender re-evaluates every live collection Boolean in the scene after any datablock is removed (docs/kitbash.md). Every
# other cut object is frozen first, so the update timed here evaluates the three tanks' Booleans or none.
for obj in [o for o in bpy.context.scene.objects if o.type == "MESH" and any(m.type == "BOOLEAN" and m.show_viewport for m in o.modifiers)]:
send("brokkr_kitbash.freeze", object_name=obj.name)
tanks = []
for n in range(3):
tanks.append(place(f"Cold{n}", "tank", location=[6.0, 3.0 * n, 0.0]))
send("createObject", objectType="MESH", name=f"ColdBox{n}", location=[6.3, 3.0 * n, 0.0], size=0.3)
send("brokkr_kitbash.boolean", object_name=f"Cold{n}", cutter=f"ColdBox{n}")
SEEN = []
def seen(scene, depsgraph):
SEEN.extend(u.id.original.name for u in depsgraph.updates if isinstance(u.id, bpy.types.Object) and u.is_updated_geometry
and u.id.original.type == "MESH" and any(m.type == "BOOLEAN" and m.show_viewport for m in u.id.original.modifiers))
def orphan_removed():
"""(seconds the scene's update takes after an orphan mesh is removed, the objects with a shown Boolean it re-evaluated)"""
mesh = bpy.data.meshes.new("Orphan")
bpy.context.view_layer.update()
SEEN.clear()
start = time.perf_counter()
bpy.data.meshes.remove(mesh)
bpy.context.view_layer.update()
return time.perf_counter() - start, sorted(set(SEEN))
bpy.app.handlers.depsgraph_update_post.append(seen)
costs = {"live": [], "frozen": []}
for _ in range(3):
bpy.context.view_layer.update()
costs["live"].append(orphan_removed())
for obj in tanks:
send("brokkr_kitbash.freeze", object_name=obj.name)
bpy.context.view_layer.update()
costs["frozen"].append(orphan_removed())
for obj in tanks:
send("brokkr_kitbash.thaw", object_name=obj.name)
bpy.app.handlers.depsgraph_update_post.remove(seen)
medians = {state: sorted(seconds for seconds, _ in rows)[1] for state, rows in costs.items()}
# wall time is this machine's: printed, and kept out of the result file, which carries what was re-evaluated
SECONDS = {"live": [round(s, 4) for s, _ in costs["live"]], "frozen": [round(s, 5) for s, _ in costs["frozen"]], "frozenOverLive": medians["frozen"] / medians["live"]}
print("SECONDS", SECONDS, flush=True)
R["frozenCost"] = {state: [names for _, names in rows] for state, rows in costs.items()}
check("removing an orphan mesh re-evaluates the three live cut tanks, and none of them frozen", all(names == ["Cold0", "Cold1", "Cold2"] for _, names in costs["live"])
and all(names == [] for _, names in costs["frozen"]), R["frozenCost"])
check("and the update with them frozen costs under the bound of what it costs with them live",
SECONDS["frozenOverLive"] < FROZEN_COST, SECONDS)
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()[-6:])

View file

@ -7,7 +7,7 @@
"detail": null
},
{
"name": "a part nobody attached reports connection null and baked false",
"name": "a part nobody attached reports connection null",
"ok": true,
"detail": null
},
@ -497,42 +497,217 @@
"detail": null
},
{
"name": "refused, scene unchanged: apply on a mesh that is not a kit part",
"name": "refused, scene unchanged: freeze on a mesh with no modifiers",
"ok": true,
"detail": null
},
{
"name": "apply makes the evaluated mesh the tank's mesh: the same faces and volume, no modifiers, one mesh datablock of the old name",
"name": "refused, scene unchanged: thaw on a live part",
"ok": true,
"detail": null
},
{
"name": "apply keeps the material slots exactly, and faces of both materials",
"name": "refused, scene unchanged: freeze on a part with a modifier already off names it",
"ok": true,
"detail": null
},
{
"name": "apply marks the part baked and keeps what it is",
"name": "freeze makes the evaluated mesh the tank's mesh: the same faces, volume and non-manifold edges, and the tank still evaluates to them",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: set_params on a baked part",
"name": "freeze holds the live mesh in kit_frozen and keeps the stack, off, with its collection and cutter",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: apply on a baked part with no modifiers left",
"name": "freeze keeps the material slots exactly, and faces of both materials",
"ok": true,
"detail": null
},
{
"name": "a baked part still reports its sockets where its params put them, and what is attached to it still holds",
"name": "a frozen part keeps what it is",
"ok": true,
"detail": null
},
{
"name": "a new part attaches to a baked one",
"name": "refused, scene unchanged: set_params on a frozen part",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: boolean on a frozen part",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: cut on a frozen part",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: cut_many on a frozen part",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: freeze on a frozen part",
"ok": true,
"detail": null
},
{
"name": "a frozen part still reports its sockets where its params put them, and what is attached to it still holds",
"ok": true,
"detail": null
},
{
"name": "a new part attaches to a frozen one",
"ok": true,
"detail": null
},
{
"name": "a frozen child rolls where it hangs on a frozen parent, and what hangs on it follows",
"ok": true,
"detail": null
},
{
"name": "the held live mesh survives a purge of orphans",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: setObjectCustomProperty on kit_frozen",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: setObjectCustomProperty on customProperties.kit_frozen",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: setObjectCustomProperty on kit_roll",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: setObjectCustomProperty on kit_anything",
"ok": true,
"detail": null
},
{
"name": "a frozen part with a modifier shown again reports dirty with the modifier, and not frozen",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: exportGltf applying modifiers over a dirty frozen part: the scene",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: exportGltf applying modifiers over a dirty frozen part: the part by name",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: set_params on a dirty frozen part, named dirty as its report names it",
"ok": true,
"detail": null
},
{
"name": "a frozen part with a modifier shown in renders only reports dirty",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: exportGltf applying modifiers over a frozen part dirty in renders only",
"ok": true,
"detail": null
},
{
"name": "with the modifier hidden again the part reports frozen; the refused exports wrote nothing",
"ok": true,
"detail": null
},
{
"name": "thaw puts the live mesh back, turns every modifier on and removes the frozen mesh",
"ok": true,
"detail": null
},
{
"name": "the thawed tank evaluates to what it did before freeze, and reports frozen false",
"ok": true,
"detail": null
},
{
"name": "a live mesh whose kit_frozen was overwritten by hand survives a purge of orphans",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: thaw on a frozen part whose kit_frozen was overwritten names the kept mesh",
"ok": true,
"detail": null
},
{
"name": "and with the kept mesh put back in kit_frozen it thaws",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: thaw on a frozen part whose held mesh was removed",
"ok": true,
"detail": null
},
{
"name": "thaw after an export that applied modifiers leaves no frozen mesh behind",
"ok": true,
"detail": null
},
{
"name": "freeze gives the live mesh a fake user and kit_kept, a pointer to the frozen mesh; a save writes both",
"ok": true,
"detail": null
},
{
"name": "deleteObject on a frozen object releases its live mesh: a purge takes it and the frozen mesh",
"ok": true,
"detail": null
},
{
"name": "importGltf drops the kit_* properties a file's extras carry, and says so: the imported object is not frozen and not a part",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: thaw on the imported object",
"ok": true,
"detail": null
},
{
"name": "a frozen object deleted in Blender, by no action: a save writes neither mesh, and a purge takes both",
"ok": true,
"detail": null
},
{
"name": "a kept mesh whose kit_kept was cleared by hand still gives its fake user back at thaw",
"ok": true,
"detail": null
},
{
"name": "a live mesh whose kit_frozen was deleted by hand stays kept through a purge and a save",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: thaw on a frozen part whose kit_frozen was deleted names the kept mesh",
"ok": true,
"detail": null
},
{
"name": "and with kit_frozen pointed back it thaws and the mesh is released",
"ok": true,
"detail": null
},
@ -542,22 +717,17 @@
"detail": null
},
{
"name": "refused, scene unchanged: apply on a mesh a linked duplicate shares",
"name": "freeze on a part with no material slot leaves the frozen mesh with none (Blender's Boolean shows it with one empty slot); a linked duplicate keeps the live mesh",
"ok": true,
"detail": null
},
{
"name": "apply on a part with no material slot leaves it with none (Blender's Boolean shows it with one empty slot)",
"name": "a thawed part is cut and frozen again; a cutter that has a material brings it after the part's own slots, on the faces it made",
"ok": true,
"detail": null
},
{
"name": "a baked part is cut and baked again; a cutter that has a material brings it after the part's own slots, on the faces it made",
"ok": true,
"detail": null
},
{
"name": "a vent that fits attaches to the baked plate's front",
"name": "a vent that fits attaches to the frozen plate's front",
"ok": true,
"detail": null
},
@ -577,12 +747,12 @@
"detail": null
},
{
"name": "apply keeps a part's own empty last slot when the cutter has no material",
"name": "freeze keeps a part's own empty last slot when the cutter has no material",
"ok": true,
"detail": null
},
{
"name": "apply leaves no face outside the material slots when a cutter's first slot is empty",
"name": "freeze leaves no face outside the material slots when a cutter's first slot is empty",
"ok": true,
"detail": null
},
@ -590,6 +760,16 @@
"name": "and each face keeps its own slot: the cutter's brass faces are brass, the faces from its empty slot and the plate's own are the plate's paint",
"ok": true,
"detail": null
},
{
"name": "removing an orphan mesh re-evaluates the three live cut tanks, and none of them frozen",
"ok": true,
"detail": null
},
{
"name": "and the update with them frozen costs under the bound of what it costs with them live",
"ok": true,
"detail": null
}
],
"hostErrors": [],
@ -637,5 +817,29 @@
"volume": 0.006031088,
"nonManifoldEdges": 0
},
"frozenCost": {
"live": [
[
"Cold0",
"Cold1",
"Cold2"
],
[
"Cold0",
"Cold1",
"Cold2"
],
[
"Cold0",
"Cold1",
"Cold2"
]
],
"frozen": [
[],
[],
[]
]
},
"ok": true
}

View file

@ -0,0 +1,340 @@
"""Live proof, in a background Blender, of brokkr_kitbash.shell's free cage through run_intent: a cage of triangles
and quads with declared poles becomes a shell whose subdivided face count is the reported one at each level, takes a
wall, counts folds and is cut; a mirrored cage closes over its seam; a loft shell is rebuilt in place as a free cage
under its cutters; the pole gate refuses without writing; tools/cage_export.py reads a cage back, an open one
included, as its maker's Subdivision draws it; and tools/cage_score.py ranks a near copy, a moved vertex, an
over-creased and a creaseless cage in that order. Not part of the unittest run: it needs Blender.
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_cage.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 reading and
its mutant's, both written beside it, and is compared as it stands; an order between two readings asks 1.2
between them; the result file carries the readings. The checks run inside
one try: an uncaught error is a failed check that names its section, and the result file is always written.
"""
import importlib.util
import json
import math
import os
import sys
import tempfile
import traceback
import types
from pathlib import Path
import bmesh
import bpy
import numpy as np
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
import cage_export # noqa: E402
import cage_score # noqa: E402
core = cage_export.load_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-cage-"))
target.configure_action_dirs("", str(WORK))
target.reload_host_actions()
R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], "readings": {}}
COUNT, SECTION = [0], ["setup"]
# Degrees: the largest dihedral angle across an edge of the tent's subdivided surface off its boundary; it is on the
# creased ridge. Shipped 71; least claimed mutant 16 (K1, the free form's creases not written to crease_edge: the
# ridge subdivides smooth), read here by clearing the attribute; the geometric mean, separation 2.1 each side.
CRISP = 34.0
# Per cent of the reference's extent: cage_score's Hausdorff distance. Shipped (the tent against itself) 0, read as
# 5e-5 (the reading is rounded to 1e-4); the mutant is one stated move, the apex lifted 5% of the extent, 3.3; the
# geometric mean, separation 260 each side. A smaller move is not claimed.
SAME = 1.3e-2
# Per cent of extent: the worst distance, both ways, between an open plate as Blender's Subdivision at Boundary Smooth
# All draws it and as shell builds cage_export's document of it. Shipped 1.7e-5; mutant B1 (the shell's Kit Subsurf at
# Keep Corners, read here by setting it) 7.7; the geometric mean, separation 670 each side. A closed cage does not tell
# the two apart, and a hand-modelled hull's own round trip is 0.28 (its seam snap): the open plate stands inside that.
OPEN = 1.1e-2
# A tent: four triangles round an apex of valence 4 with two ridges creased, and a quad hung under one edge: 7
# vertices, vertices 1 and 2 boundary poles of valence 4.
TENT = {"verts": [[0.0, 0.0, 0.5], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [-1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [1.0, 0.0, -1.0], [0.0, 1.0, -1.0]],
"faces": [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [2, 1, 5, 6]], "creases": [[0, 1, 1.0], [0, 3, 1.0]], "poles": [1, 2], "rim": 0.0}
# Half a lozenge hull, mirrored: seam vertices 0 to 3 (one 4 mm off the plane), a nose and tail triangle each side.
HULL = {"verts": [[0.0, -1.0, 0.0], [0.004, 0.0, 0.3], [0.0, 1.0, 0.0], [0.0, 0.0, -0.3], [0.6, 0.0, 0.0]],
"faces": [[0, 4, 1], [1, 4, 2], [2, 4, 3], [3, 4, 0]], "creases": [[0, 4, 1.0], [4, 2, 1.0]], "mirror": True}
LOFT = {"rings": [[[0.3 * j - 0.45, 0.02 * j * j, 0.3 * i] for j in range(4)] for i in range(3)], "flip": True}
CUTS = [{"name": "TentLine", "part": "slab", "params": "gap=0.02; length=0.4; depth=0.03", "origin": [0.3, -0.35, 3.0], "direction": [0, 0, -1]}]
def check(name, ok, detail=None):
R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else json.loads(json.dumps(detail, default=str))})
def section(name):
SECTION[0] = name
def send(action, **fields):
COUNT[0] += 1
receipt = target.run_intent(bpy.context, {"commandId": f"live-{COUNT[0]}", "requestedBy": "nibu/hands", "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"])[:300], flush=True)
return receipt, result
def evaluated(obj, only=None):
"""An object as Blender evaluates it, as a bmesh; with `only`, with just the modifiers of those names shown."""
hidden = [m for m in obj.modifiers if only is not None and m.name not in only and m.show_viewport]
for m in hidden:
m.show_viewport = False
try:
bpy.context.view_layer.update()
owner = obj.evaluated_get(bpy.context.evaluated_depsgraph_get())
bm = bmesh.new()
bm.from_mesh(owner.to_mesh())
owner.to_mesh_clear()
finally:
for m in hidden:
m.show_viewport = True
bpy.context.view_layer.update()
bm.normal_update()
return bm
def sharpest(obj):
bm = evaluated(obj, only=("Kit Subsurf",))
worst = max(math.degrees(e.link_faces[0].normal.angle(e.link_faces[1].normal, 0.0)) for e in bm.edges if len(e.link_faces) == 2)
bm.free()
return worst
def state():
return {o.name: (sorted(k for k in o.keys() if k.startswith("kit_")), len(o.data.vertices) if o.type == "MESH" else None, [m.name for m in o.modifiers]) for o in bpy.data.objects}, sorted(m.name for m in bpy.data.meshes)
try:
# --- live-free-cage-shell: counts at each level ----------------------------------------------------------------
section("free-cage-triangle-counts")
for levels in (1, 2, 3):
receipt, report = send("brokkr_kitbash.shell", object_name="Tent", sheet=json.dumps(TENT), thickness=0.04, levels=levels, count_folds=True)
tent = bpy.data.objects.get("Tent")
expected = 1 * 4 ** levels + 4 * 3 * 4 ** (levels - 1)
bm = evaluated(tent, only=("Kit Subsurf",))
faces, sides = len(bm.faces), {len(f.verts) for f in bm.faces}
bm.free()
wall = evaluated(tent, only=("Kit Subsurf", "Kit Solidify"))
closed, walled = all(e.is_manifold for e in wall.edges), len(wall.faces)
wall.free()
check(f"a cage of 4 triangles and a quad at {levels} levels: subdividedFaces is 4^L + 4 * 3 * 4^(L-1) and the evaluated surface has that many faces, all quads",
receipt["status"] == "accepted" and report["subdividedFaces"] == expected == faces and sides == {4}, [receipt["message"], expected, faces, sides])
check(f"at {levels} levels the wall is closed, twice the surface and a rim, and count_folds counts none folded",
closed and walled == 2 * expected + 6 * 2 ** levels and report["folded"] == 0, [closed, walled, report and report["folded"]]) # the tent's boundary is 6 cage edges
built = core.sheet(TENT)
check("the report carries the cage's facts: 7 vertices, 5 faces of which 4 triangles, 2 creases, two poles of valence 4, open; rings and points null",
report and {k: report[k] for k in ("rings", "points", "cageVerts", "cageFaces", "triangles", "creases", "corners", "poles", "closed")}
== {"rings": None, "points": None, "cageVerts": 7, "cageFaces": 5, "triangles": 4, "creases": 2, "corners": 0, "poles": {"4": 2}, "closed": False}, report)
check("the cage mesh is core.sheet's, face for face, and kit_shell is the request",
[tuple(p.vertices) for p in tent.data.polygons] == [tuple(f) for f in TENT["faces"]] and np.abs(np.array([v.co[:] for v in tent.data.vertices]) - built.V).max() < 1e-6
and json.loads(tent["kit_shell"])["sheet"] == TENT, tent["kit_shell"])
# --- the creases reach the surface -----------------------------------------------------------------------------------
section("free-cage-crisp")
crisp = sharpest(tent)
attribute = tent.data.attributes["crease_edge"]
kept = [d.value for d in attribute.data]
attribute.data.foreach_set("value", [0.0] * len(kept)) # K1: what the surface is when the creases are not written
tent.data.update()
soft = sharpest(tent)
attribute.data.foreach_set("value", kept)
tent.data.update()
R["readings"].update({"crispDegrees": crisp, "crispDegreesK1": soft})
check(f"the creased ridge stays an edge under subdivision: over {CRISP} degrees, and under it with crease_edge cleared", crisp > CRISP and soft < CRISP, [crisp, soft])
# --- cut -------------------------------------------------------------------------------------------------------------
section("live-free-cage-shell")
receipt, cut = send("brokkr_kitbash.cut_many", object_name="Tent", cuts=json.dumps(CUTS))
plate = evaluated(tent)
check("cut_many cuts a free-cage shell: the Boolean stands after the wall, the plate has more faces than the wall it was cut from (a Boolean that cut nothing leaves as many) and no non-manifold edge",
receipt["status"] == "accepted" and [m.name for m in tent.modifiers] == ["Kit Subsurf", "Kit Solidify", "Kit Difference"] and len(plate.faces) > walled
and sum(1 for e in plate.edges if not e.is_manifold) == 0, [receipt["message"], len(plate.faces), walled, sum(1 for e in plate.edges if not e.is_manifold)])
plate.free()
# --- mirror ----------------------------------------------------------------------------------------------------------
section("free-cage-mirror")
receipt, report = send("brokkr_kitbash.shell", object_name="Hull", sheet=json.dumps(HULL), thickness=0.01)
hull = bpy.data.objects.get("Hull")
bm = evaluated(hull, only=("Kit Subsurf",))
check("a mirrored cage closes over its seam: 6 vertices from 5, 8 triangles, the vertex 4 mm off the plane snapped onto it, no boundary edge on the cage or its surface, and its poles reported",
receipt["status"] == "accepted" and (report["cageVerts"], report["cageFaces"], report["triangles"], report["closed"], report["creases"], report["subdividedFaces"]) == (6, 8, 8, True, 4, 8 * 3 * 16)
and abs(hull.data.vertices[1].co.x) < 1e-9 and all(e.is_manifold for e in bm.edges) and len(bm.faces) == 384 and report["poles"] == {}, report)
bm.free()
# --- rebuild a loft as a free cage -------------------------------------------------------------------------------------
section("free-cage-rebuild")
receipt, _ = send("brokkr_kitbash.shell", object_name="Plate", sheet=json.dumps(LOFT), thickness=0.03)
plate_obj = bpy.data.objects["Plate"]
plate_obj.data.materials.append(bpy.data.materials.new("Khaki"))
receipt, _ = send("brokkr_kitbash.cut_many", object_name="Plate", cuts=json.dumps([{"name": "PlateLine", "part": "slab", "params": "gap=0.02; length=0.3; depth=0.02", "origin": [0.0, 3.0, 0.3], "direction": [0, -1, 0]}]))
before = (plate_obj.as_pointer(), plate_obj.data.as_pointer(), sorted(c.name for c in plate_obj.children), sorted(o.name for o in plate_obj.modifiers["Kit Difference"].collection.objects), [s.material.name for s in plate_obj.material_slots])
loft = core.sheet(LOFT)
quads = loft.faces.reshape(-1, 4).tolist()
FREE = {"verts": [[round(c, 6) for c in v] for v in loft.V.tolist()], "faces": quads[:5] + [quads[5][:3], [quads[5][0], quads[5][2], quads[5][3]]], "poles": [7, 10], "creases": [[5, 6, 1.0]]} # the last quad split along its diagonal: two boundary vertices of valence 4
receipt, report = send("brokkr_kitbash.shell", object_name="Plate", sheet=json.dumps(FREE), thickness=0.03)
again = bpy.data.objects.get("Plate")
after = (again.as_pointer(), again.data.as_pointer(), sorted(c.name for c in again.children), sorted(o.name for o in again.modifiers["Kit Difference"].collection.objects), [s.material.name for s in again.material_slots])
bm = evaluated(again)
check("a loft shell rebuilt in place as a free cage keeps its object, mesh datablock, cutter, Boolean and material slot; the report says rebuilt, 2 triangles and the cage's poles; the plate is still cut and closed",
receipt["status"] == "accepted" and before == after and before[2:] == (["PlateLine"], ["PlateLine"], ["Khaki"]) and report["rebuilt"] is True and (report["triangles"], report["rings"], report["cageFaces"]) == (2, None, 7)
and report["poles"] == {"4": 2} and report["children"] == ["PlateLine"] and sum(1 for e in bm.edges if not e.is_manifold) == 0 and len(bm.faces) > 2 * report["subdividedFaces"], [receipt["message"], report, before, after])
bm.free()
# --- the gate refuses before it writes -------------------------------------------------------------------------------
section("free-cage-refusals")
for label, name, sheet, expected in (
("an undeclared pole, on a shell", "Plate", {**FREE, "poles": [7]}, "sheet.poles lacks vertex 10 (valence 4, on the boundary)"),
("a declared vertex that is no pole, on a new name", "New", {**TENT, "poles": [1, 2, 0]}, "sheet.poles[2] names vertex 0 (valence 4), which is no pole"),
("rings with verts", "New", {**TENT, "rings": LOFT["rings"]}, "sheet states both rings and verts"),
("a face of five sides", "New", {**TENT, "faces": TENT["faces"][:4] + [[2, 1, 5, 6, 3]]}, "sheet.faces[4] must be 3 or 4 vertex indices, not 5"),
("two faces wound against each other", "Plate", {**FREE, "faces": FREE["faces"][:6] + [FREE["faces"][6][::-1]]}, "the two are wound against each other")):
held = state()
receipt, _ = send("brokkr_kitbash.shell", object_name=name, sheet=json.dumps(sheet))
check(f"refused, scene unchanged: {label}", receipt["status"] != "accepted" and expected in str(receipt["message"]) and state() == held, [receipt["status"], receipt["message"]])
check("no refusal made an object", "New" not in bpy.data.objects, None)
# --- export-score-roundtrip -----------------------------------------------------------------------------------------
section("export-score-roundtrip")
saved = str(WORK / "scratch.blend")
probe = bpy.data.objects.new("Probe Cage", bpy.data.meshes.new("Probe Cage")) # a cage as a person leaves one: a mesh, a Mirror, creases on edges; made here, no one's file
bpy.context.scene.collection.objects.link(probe)
probe.data.from_pydata(HULL["verts"], [], HULL["faces"])
probe.data.update(calc_edges=True)
weights = probe.data.attributes.new("crease_edge", "FLOAT", "EDGE")
for e in probe.data.edges:
weights.data[e.index].value = 1.0 if tuple(sorted(e.vertices)) in ((0, 4), (2, 4)) else 0.0
probe.modifiers.new("Mirror", "MIRROR")
probe.modifiers.new("Subdivision", "SUBSURF")
document = cage_export.export(probe, core)
exported = document["sheet"]
check("cage_export reads a mirrored, creased mesh as the free cage it is: the vertices as authored and the seam snapped when built, the creases by vertex pair, mirror set, rim 0, the poles computed, and core.sheet takes it",
exported["verts"][1] == [0.004, 0.0, 0.3] and core.sheet(exported).V[1].tolist() == [0.0, 0.0, 0.3] and exported["faces"] == HULL["faces"] and exported["creases"] == [[0, 4, 1.0], [2, 4, 1.0]] and exported["mirror"] is True
and exported["rim"] == 0.0 and exported["poles"] == [] and document["modifiers"] == [["MIRROR", "Mirror"], ["SUBSURF", "Subdivision"]]
and np.array_equal(core.sheet(exported).faces, core.sheet(HULL).faces), document)
bpy.data.objects.remove(probe)
# an open plate as a person leaves one: a bulge, one creased ridge, an uncreased outline, Subdivision at Boundary Smooth All
grid = [[i - 1.5, j - 1.5, 0.4 * math.cos(i - 1.5) * math.cos(j - 1.5)] for i in range(4) for j in range(4)]
open_plate = bpy.data.objects.new("Open Plate", bpy.data.meshes.new("Open Plate"))
bpy.context.scene.collection.objects.link(open_plate)
open_plate.data.from_pydata(grid, [], [[4 * i + j, 4 * i + 4 + j, 4 * i + 5 + j, 4 * i + 1 + j] for i in range(3) for j in range(3)])
open_plate.data.update(calc_edges=True)
weights = open_plate.data.attributes.new("crease_edge", "FLOAT", "EDGE")
for e in open_plate.data.edges:
weights.data[e.index].value = 1.0 if all(v // 4 == 1 for v in e.vertices) else 0.0
by_hand = open_plate.modifiers.new("Subdivision", "SUBSURF")
by_hand.levels, by_hand.boundary_smooth = 3, "ALL"
bm = evaluated(open_plate)
VH = np.array([v.co[:] for v in bm.verts])
TH = np.array([[f.verts[0].index, f.verts[k].index, f.verts[k + 1].index] for f in bm.faces for k in (1, 2)])
bm.free()
document = cage_export.export(open_plate, core)
receipt, report = send("brokkr_kitbash.shell", object_name="Open Shell", sheet=json.dumps(document["sheet"]), levels=3, thickness=0.001)
shell_obj = bpy.data.objects["Open Shell"]
worst = {}
for mode in ("ALL", "PRESERVE_CORNERS"): # the second is B1
kept, shell_obj.modifiers["Kit Subsurf"].boundary_smooth = shell_obj.modifiers["Kit Subsurf"].boundary_smooth, mode
VS, TS, _, _ = cage_score.surface(shell_obj)
worst[mode] = float(max(cage_score.nearest(VS, VH, TH).max(), cage_score.nearest(VH, VS, TS).max()) / np.ptp(VH, axis=0).max() * 100.0)
shell_obj.modifiers["Kit Subsurf"].boundary_smooth = kept
R["readings"].update({"openRoundTripPct": worst["ALL"], "openRoundTripPctB1": worst["PRESERVE_CORNERS"]})
check(f"an open cage round-trips: shell builds cage_export's document of a plate with an uncreased outline as its Subdivision (Boundary Smooth All) draws it, under {OPEN}% of extent, and over it at Keep Corners",
receipt["status"] == "accepted" and kept == "ALL" and report["closed"] is False and document["sheet"]["corners"] == [] and worst["ALL"] < OPEN < worst["PRESERVE_CORNERS"], [receipt["message"], worst])
by_hand.boundary_smooth = "PRESERVE_CORNERS"
try:
cage_export.export(open_plate, core)
said = None
except core.KitError as error:
said = str(error)
check("cage_export refuses a Subdivision at Keep Corners, saying how to state the corners", said is not None and "Boundary Smooth Keep Corners" in said and "vertex crease of 1" in said, said)
bpy.data.objects.remove(shell_obj)
bpy.data.objects.remove(open_plate)
# --- score-ranks ---------------------------------------------------------------------------------------------------
section("score-ranks")
tent_document = {**TENT, "rim": 1.0}
held = state()
same = cage_score.score(tent_document, tent_document, send)
check("cage_score of a cage against itself: equal counts, distance 0, every silhouette IoU 1, no sharp feature missed or spurious, the cost its complexity alone, and its two shells removed again",
same["agent"] == same["reference"] and same["agent"]["cageVerts"] == 7 and same["distance"]["hausdorffPct"] < SAME and set(same["silhouetteIoU"].values()) == {1.0}
and (same["crease"]["missPct"], same["crease"]["spurPct"]) == (0.0, 0.0) and same["crease"]["agentSharp"] == same["crease"]["referenceSharp"] > 0
and same["cost"]["complexity"] == round(7 * cage_score.C_REP + 8 * cage_score.C_SHARP, 4) and abs(same["cost"]["total"] - same["cost"]["complexity"]) < SAME and state() == held, same)
lifted = cage_score.score({**tent_document, "verts": [[0.0, 0.0, 0.5 + 0.05 * 2.0]] + TENT["verts"][1:]}, tent_document, send) # the apex lifted 5% of the 2 m extent
R["readings"].update({"scoreSameHausdorffPct": same["distance"]["hausdorffPct"], "scoreLiftedHausdorffPct": lifted["distance"]["hausdorffPct"]})
check("cage_score of the tent with its apex lifted 5% of the extent: Hausdorff distance above the bound, a silhouette under 1, the counts and the extent still the reference's",
lifted["distance"]["hausdorffPct"] > SAME and min(lifted["silhouetteIoU"].values()) < 1.0 and lifted["agent"] == lifted["reference"] and abs(lifted["extent"] - same["extent"]) < 1e-9, lifted)
# A box of 26 vertices and 24 quads, its lid's outline creased: the reference. Four agents against it.
points = [(x, y, z) for x in (-1, 0, 1) for y in (-1, 0, 1) for z in (-1, 0, 1) if (x, y, z) != (0, 0, 0)]
at = {point: k for k, point in enumerate(points)}
quads = []
for axis in range(3):
for side in (-1, 1):
for a in (-1, 0):
for b in (-1, 0):
quad = []
for da, db in ((0, 0), (1, 0), (1, 1), (0, 1)):
point = [0, 0, 0]
point[axis], point[(axis + 1) % 3], point[(axis + 2) % 3] = side, a + da, b + db
quad.append(at[tuple(point)])
quads.append(quad if side > 0 else quad[::-1])
cage_edges = sorted({tuple(sorted((q[k], q[k - 1]))) for q in quads for k in range(4)})
BOX = {"verts": [[0.6 * x, 1.0 * y, 0.4 * z] for x, y, z in points], "faces": quads,
"creases": [[a, b, 1.0] for a, b in cage_edges if points[a][2] == points[b][2] == 1 and (0, 0, 1) not in (points[a], points[b])]}
BOX["poles"] = core.poles(BOX)
shaken = (np.array(BOX["verts"]) + np.random.default_rng(7).normal(size=(26, 3)) * 0.005 * 2.0 / math.sqrt(3)).round(6).tolist()
agents = {"Self": BOX, "Near": {**BOX, "verts": shaken}, # every vertex off by 0.5% of the 2 m extent
"Moved": {**BOX, "verts": [[v[0], v[1] + 0.05 * 2.0, v[2]] if k == at[(1, 1, 1)] else v for k, v in enumerate(BOX["verts"])]}, # one vertex, 5% of the extent
"Over": {**BOX, "creases": [[a, b, 1.0] for a, b in cage_edges]}, # every edge creased: the box as a polyhedron
"Bare": {**BOX, "creases": []}} # no crease: a smooth blob
read = {label: cage_score.score(agent, BOX, send) for label, agent in agents.items()}
cost = {label: reading["cost"]["total"] for label, reading in read.items()}
R["readings"].update({f"cost{label}": value for label, value in cost.items()})
R["readings"].update({"costMovedHausdorffPct": read["Moved"]["distance"]["hausdorffPct"], "costBareMissPct": read["Bare"]["crease"]["missPct"], "costOverSpurPct": read["Over"]["crease"]["spurPct"]})
check("the cost ranks: the reference itself is cheapest, and a near copy (every vertex 0.5% off) beats a creaseless cage, each by 1.2 or more",
len(BOX["creases"]) == 8 and cost["Self"] * 1.2 < cost["Near"] and cost["Near"] * 1.2 < cost["Bare"] and read["Bare"]["crease"]["missPct"] > read["Near"]["crease"]["missPct"], [cost, read["Bare"]["crease"]])
check("one vertex moved 5% of the extent registers: its Hausdorff distance is over the bound and its cost 1.2 over the reference's own, though the median and the silhouettes barely see it",
read["Moved"]["distance"]["hausdorffPct"] > SAME and cost["Self"] * 1.2 < cost["Moved"], read["Moved"])
check("an over-creased cage costs more than the reference, by its spurious sharp features and its sharp edges' price",
cost["Self"] * 1.2 < cost["Over"] and read["Over"]["crease"]["spurPct"] > 0.0 and read["Over"]["cost"]["complexity"] > read["Self"]["cost"]["complexity"], read["Over"])
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,153 @@
{
"blender": "5.3.0",
"checks": [
{
"name": "a cage of 4 triangles and a quad at 1 levels: subdividedFaces is 4^L + 4 * 3 * 4^(L-1) and the evaluated surface has that many faces, all quads",
"ok": true,
"detail": null
},
{
"name": "at 1 levels the wall is closed, twice the surface and a rim, and count_folds counts none folded",
"ok": true,
"detail": null
},
{
"name": "a cage of 4 triangles and a quad at 2 levels: subdividedFaces is 4^L + 4 * 3 * 4^(L-1) and the evaluated surface has that many faces, all quads",
"ok": true,
"detail": null
},
{
"name": "at 2 levels the wall is closed, twice the surface and a rim, and count_folds counts none folded",
"ok": true,
"detail": null
},
{
"name": "a cage of 4 triangles and a quad at 3 levels: subdividedFaces is 4^L + 4 * 3 * 4^(L-1) and the evaluated surface has that many faces, all quads",
"ok": true,
"detail": null
},
{
"name": "at 3 levels the wall is closed, twice the surface and a rim, and count_folds counts none folded",
"ok": true,
"detail": null
},
{
"name": "the report carries the cage's facts: 7 vertices, 5 faces of which 4 triangles, 2 creases, two poles of valence 4, open; rings and points null",
"ok": true,
"detail": null
},
{
"name": "the cage mesh is core.sheet's, face for face, and kit_shell is the request",
"ok": true,
"detail": null
},
{
"name": "the creased ridge stays an edge under subdivision: over 34.0 degrees, and under it with crease_edge cleared",
"ok": true,
"detail": null
},
{
"name": "cut_many cuts a free-cage shell: the Boolean stands after the wall, the plate has more faces than the wall it was cut from (a Boolean that cut nothing leaves as many) and no non-manifold edge",
"ok": true,
"detail": null
},
{
"name": "a mirrored cage closes over its seam: 6 vertices from 5, 8 triangles, the vertex 4 mm off the plane snapped onto it, no boundary edge on the cage or its surface, and its poles reported",
"ok": true,
"detail": null
},
{
"name": "a loft shell rebuilt in place as a free cage keeps its object, mesh datablock, cutter, Boolean and material slot; the report says rebuilt, 2 triangles and the cage's poles; the plate is still cut and closed",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: an undeclared pole, on a shell",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a declared vertex that is no pole, on a new name",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: rings with verts",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a face of five sides",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: two faces wound against each other",
"ok": true,
"detail": null
},
{
"name": "no refusal made an object",
"ok": true,
"detail": null
},
{
"name": "cage_export reads a mirrored, creased mesh as the free cage it is: the vertices as authored and the seam snapped when built, the creases by vertex pair, mirror set, rim 0, the poles computed, and core.sheet takes it",
"ok": true,
"detail": null
},
{
"name": "an open cage round-trips: shell builds cage_export's document of a plate with an uncreased outline as its Subdivision (Boundary Smooth All) draws it, under 0.011% of extent, and over it at Keep Corners",
"ok": true,
"detail": null
},
{
"name": "cage_export refuses a Subdivision at Keep Corners, saying how to state the corners",
"ok": true,
"detail": null
},
{
"name": "cage_score of a cage against itself: equal counts, distance 0, every silhouette IoU 1, no sharp feature missed or spurious, the cost its complexity alone, and its two shells removed again",
"ok": true,
"detail": null
},
{
"name": "cage_score of the tent with its apex lifted 5% of the extent: Hausdorff distance above the bound, a silhouette under 1, the counts and the extent still the reference's",
"ok": true,
"detail": null
},
{
"name": "the cost ranks: the reference itself is cheapest, and a near copy (every vertex 0.5% off) beats a creaseless cage, each by 1.2 or more",
"ok": true,
"detail": null
},
{
"name": "one vertex moved 5% of the extent registers: its Hausdorff distance is over the bound and its cost 1.2 over the reference's own, though the median and the silhouettes barely see it",
"ok": true,
"detail": null
},
{
"name": "an over-creased cage costs more than the reference, by its spurious sharp features and its sharp edges' price",
"ok": true,
"detail": null
}
],
"hostErrors": [],
"readings": {
"costBare": 58.0,
"costBareMissPct": 100.0,
"costMoved": 3.4,
"costMovedHausdorffPct": 2.7,
"costNear": 1.2,
"costOver": 27.0,
"costOverSpurPct": 22.0,
"costSelf": 0.28,
"crispDegrees": 71.0,
"crispDegreesK1": 16.0,
"openRoundTripPct": 1.7e-05,
"openRoundTripPctB1": 7.7,
"scoreLiftedHausdorffPct": 3.3,
"scoreSameHausdorffPct": 0.0
},
"ok": true
}

View file

@ -214,7 +214,8 @@ try:
and sorted(stored) == ["bevel", "levels", "offset", "sheet", "thickness"] and stored["sheet"] == PAULDRON
and (stored["levels"], stored["offset"]) == (3, -1.0) and abs(stored["thickness"] - WALL) < 1e-7, [receipt["message"], stored])
check("shell reports cage facts: rings, points, quads, creased edges, the subdivided count, an upward facing, no children",
report and sorted(report) == ["cageFaces", "children", "corners", "creases", "facing", "folded", "levels", "object", "offset", "points", "rebuilt", "rings", "subdividedFaces", "thickness"]
report and sorted(report) == ["cageFaces", "cageVerts", "children", "closed", "corners", "creases", "facing", "folded", "levels", "object", "offset", "points", "poles", "rebuilt", "rings", "subdividedFaces", "thickness", "triangles"]
and (report["cageVerts"], report["triangles"], report["poles"], report["closed"]) == (36, 0, {}, False)
and (report["object"], report["rebuilt"], report["rings"], report["points"], report["cageFaces"], report["creases"], report["corners"], report["subdividedFaces"], report["levels"],
report["thickness"], report["offset"], report["children"]) == ("Pauldron", False, 6, 6, 25, 25, 0, 1600, 3, 0.06, -1.0, [])
and report["facing"][2] > 0.5 and abs(np.linalg.norm(report["facing"]) - 1.0) < 1e-5, report)
@ -445,8 +446,10 @@ except Exception: # noqa: BLE001 whatever it was, it is a failed check with a
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())}
costs = R.pop("costs", None) # wall time is this machine's: printed, and kept out of the result file
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"], R["costs"], flush=True)
print("READINGS", R["readings"], flush=True)
print("SECONDS", costs, flush=True)
sys.exit(0 if R["ok"] else 1)

View file

@ -183,14 +183,6 @@
"soft": 5.8,
"solid": 0.027
},
"costs": {
"shell": 0.0059,
"shellCountingFolds": 0.0091,
"evaluation": 0.0022,
"rebuildUnderCuts": 1.7,
"rebuildCall": 1.6,
"rebuildCallCountingFolds": 1.6
},
"folds": {
"seeded": {
"5185 offset -1": [

View file

@ -0,0 +1,510 @@
"""Live proof, in a background Blender, of brokkr_kitbash.hose through run_intent: a bundle of three hoses from an actuator
on one strut to an actuator on the next, around an armour plate and through a point on the knee pin's axis; the pin's
roll range measured without posing anything, and a range that swings the hose into the plate refused by roll; a second
hose that keeps clear of the first; a rebuild in place; a hose from a tank's flange over two clamps to an actuator's
port; and the refusals. Not part of the unittest run: it needs Blender.
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_hose.py -- <out> [<blend>]
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. With <blend>, an
absolute path, the scene is saved there at the end.
Bounds follow lodur:ruling:deterministic-bound-margin; each is written beside its constant with the shipped reading
and the least claimed mutant's (cut kit-hose's H list). The checks run inside one try: an uncaught error is a failed
check that names its section, and the result file is always written.
"""
import importlib.util
import json
import math
import os
import sys
import tempfile
import traceback
import types
from pathlib import Path
import bpy
import numpy as np
from mathutils import Vector
from mathutils.bvhtree import BVHTree
SURFACE = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(SURFACE / "tools"))
import private_dirs # noqa: E402
_refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind))
if _refused:
raise SystemExit(_refused)
OUT = sys.argv[sys.argv.index("--") + 1]
if not Path(OUT).is_absolute():
raise SystemExit(f"{OUT!r} is not an absolute path")
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
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-hose-"))
target.configure_action_dirs("", str(WORK))
target.reload_host_actions()
R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], "readings": {}, "reports": {}, "seconds": {}}
COUNT, SECTION = [0], ["setup"]
kit = core.load_kit("mechanical")
RADIUS, CLEARANCE, COUNT_HOSES = 0.006, 0.005, 3
SPREAD = 2.6 * RADIUS
ENVELOPE = SPREAD + RADIUS # half the bundle's width
LEAD = 8.0 * RADIUS
FLOOR = 4.0 * 2.0 * RADIUS + SPREAD # of the centre line: the innermost hose keeps 4 outside diameters
BUNDLE = {"count": COUNT_HOSES, "radius": RADIUS, "clearance": CLEARANCE}
# Metres between a hose's surface and the nearest other mesh, read on the hose's own vertices further than the lead
# from both its ports (the least is the worst), over every hose this suite makes. Shipped worst 0.031. Least claimed
# mutant 0.0089: H4b (route.verify measures and refuses nothing) accepts the hose past the plate beside a port's
# straight, section "verify", and the ring of it nearest the plate reads that; shipped refuses it and makes no hose.
# The geometric mean, separation 1.8 and 1.9.
CLEAR = 0.017
# Metres a clamped hose's ring vertices stand off the radius about its own line over a clamp (the line through the
# clamp point along the socket's y, offset across the bundle), over the 24 nearest; 1 when a hose has no 24 vertices
# there. Shipped worst 4.6e-08 (float32 meshes); least claimed mutant 1 (C2, the straight laid along the socket's x:
# the route is refused, or no ring stands on the line); the geometric mean, separation 4700 each side.
CLAMPED = 2.1e-4
# Metres along a clamped hose's line from a clamp point to the nearest ring of a bend. Shipped 0.028; least claimed
# mutant 0.013 (C1, no straight kept at a clamp); the geometric mean, separation 1.47 each side.
KEPT = 0.019
def check(name, ok, detail=None):
R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail})
def reading(name, value, least=False):
"""The worst of a metric: the largest, or with `least` the smallest."""
R["readings"][name] = (min if least else max)(R["readings"].get(name, float(value)), float(value))
return float(value)
def section(name):
SECTION[0] = name
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, np.round(np.array(o.matrix_basis), 6).tolist(), {k: repr(o[k]) for k in sorted(o.keys()) if k.startswith("kit_")},
[(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,
np.round(np.array([v.co for v in o.data.vertices[: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.hose", **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="", location=None, rotation=None, parent=None):
send("brokkr_kitbash.place_part", part=part, object_name=name, params=params)
if location is not None:
send("setObjectTransform", targetObjectName=name, location=location, rotationEuler=rotation or [0.0, 0.0, 0.0])
made = bpy.data.objects[name]
if parent is not None: # carried rigidly: a plain parent, which states no connection
bpy.context.view_layer.update()
made.parent = parent
made.matrix_parent_inverse = parent.matrix_world.inverted()
return made
def box(name, low, high, parent=None):
(x0, y0, z0), (x1, y1, z1) = low, high
made = bpy.data.objects.new(name, bpy.data.meshes.new(name))
made.data.from_pydata([(x0, y0, z0), (x1, y0, z0), (x1, y1, z0), (x0, y1, z0), (x0, y0, z1), (x1, y0, z1), (x1, y1, z1), (x0, y1, z1)], [],
[(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)])
bpy.context.scene.collection.objects.link(made)
if parent is not None:
bpy.context.view_layer.update()
made.parent = parent
made.matrix_parent_inverse = parent.matrix_world.inverted()
return made
def frame(obj, name):
"""A socket's world frame, from the object's matrix_world and core's build of its stored params."""
built = core.build(core.part(kit, obj["kit_part"]), json.loads(obj["kit_params"]))
return np.array(obj.matrix_world, dtype=np.float64) @ next(s for s in built.sockets if s["name"] == name)["matrix"]
def world_points(obj):
points = np.zeros(3 * len(obj.data.vertices))
obj.data.vertices.foreach_get("co", points)
world = np.array(obj.matrix_world)
return points.reshape(-1, 3) @ world[:3, :3].T + world[:3, 3]
def others(hose):
"""A tree of every other mesh object's evaluated mesh in the world: this test's own reading of the obstacles."""
depsgraph, points, faces = bpy.context.evaluated_depsgraph_get(), [], []
for obj in bpy.context.scene.objects:
if obj.type != "MESH" or obj == hose:
continue
evaluated = obj.evaluated_get(depsgraph)
mesh, start = evaluated.to_mesh(), sum(len(p) for p in points)
points.append(np.array([evaluated.matrix_world @ v.co for v in mesh.vertices]).reshape(-1, 3))
faces += [[start + i for i in polygon.vertices] for polygon in mesh.polygons]
evaluated.to_mesh_clear()
return BVHTree.FromPolygons(np.vstack(points).tolist(), faces)
def surface_clearance(hose, ports):
"""The least distance from the hose's vertices to any other mesh, over the vertices further than the lead and the
bundle's half width from both ports."""
bpy.context.view_layer.update()
tree, points = others(hose), world_points(hose)
far = np.all([np.linalg.norm(points - port, axis=1) > LEAD + ENVELOPE + CLEARANCE for port in ports], axis=0)
return min(tree.find_nearest(Vector(p))[3] for p in points[far])
def shells(obj):
"""(closed shells, edges that do not join two faces) of a mesh object."""
edges = {}
for polygon in obj.data.polygons:
for a, b in polygon.edge_keys:
edges[(a, b)] = edges.get((a, b), 0) + 1
root = list(range(len(obj.data.vertices)))
def find(i):
while root[i] != i:
root[i] = root[root[i]]
i = root[i]
return i
for a, b in edges:
root[find(a)] = find(b)
return len({find(i) for i in range(len(root))}), sum(1 for n in edges.values() if n != 2)
def timed(fields):
"""Median wall seconds of three rebuilds of a hose, each after one report action."""
import time
taken = []
for _ in range(3):
send("brokkr_kitbash.report", object_name="Thigh")
started = time.perf_counter()
send("brokkr_kitbash.hose", **fields)
taken.append(time.perf_counter() - started)
return sorted(taken)[1]
try:
section("knee")
STRUT = "length=0.8;width=0.08;thickness=0.05"
RAM = "body_r=0.12;body_len=0.2;extension=0"
thigh = place("Thigh", "strut", STRUT)
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)
shin = bpy.data.objects["Shin"]
upper = place("ActT", "actuator", RAM, [-0.674, -0.2, -0.2], parent=thigh)
lower = place("ActS", "actuator", RAM, [-0.674, -0.2, 0.89], parent=shin)
plate = box("Armour", (-0.21, -0.45, 0.15), (-0.19, 0.05, 0.7), parent=thigh)
bpy.context.view_layer.update()
ports = [frame(upper, "port_cap")[:3, 3], frame(lower, "port_cap")[:3, 3]]
check("the actuator's ports sit on its boss faces, facing out", np.allclose(ports[0], [-0.5, -0.2, 0.01], atol=1e-6) and np.allclose(frame(upper, "port_cap")[:3, 2], [1, 0, 0], atol=1e-6)
and others(None).find_nearest(Vector(ports[0]))[3] < 1e-6 and np.allclose(frame(upper, "port_rod")[:3, 3], [-0.5, -0.2, 0.27], atol=1e-6), ports[0].tolist())
JOINT = {"socket": "Shin:end_a_back", "standoff": 0.08}
def limits(lo, hi):
"""State the knee's limits: the roll range a hose across it is proven over is the pin's own."""
receipt, _ = send("brokkr_kitbash.joint", object_name="Shin", record=json.dumps({"limits": None if lo is None else [lo, hi]}))
return receipt
refused("hose-range-from-pin: a pin with no limits, naming the action that states them", {"object_name": "Feed", "start": "ActT:port_cap", "end": "ActS:port_cap", **BUNDLE, "joint": json.dumps(JOINT)},
"'Shin' on 'Thigh': the pin the hose crosses states no limits: brokkr_kitbash.joint gives it the roll range the hose is proven over")
check("the knee takes its limits", limits(-20, 20)["status"] == "accepted" and (shin["kit_min"], shin["kit_max"]) == (-20.0, 20.0), dict(shin.items()))
FEED = {"object_name": "Feed", "start": "ActT:port_cap", "end": "ActS:port_cap", **BUNDLE, "joint": json.dumps(JOINT)}
state = scene_state()
receipt, report = send("brokkr_kitbash.hose", **FEED)
R["reports"]["feed"] = report
check("hose-behind-armour: three hoses route from the thigh's ram to the shin's, round the plate and through the pin point",
receipt["status"] == "accepted" and report["hoses"] == 3 and not report["rebuilt"] and report["nonManifoldEdges"] == 0 and report["rolls"] >= 9
and report["clearance"] >= CLEARANCE and report["worstClearance"] >= CLEARANCE and report["radii"]["least"] >= FLOOR * (1 - 1e-6) and len(report["voxels"]) == 2,
[receipt["status"], receipt["message"], report])
feed = bpy.data.objects["Feed"]
check("the hose is one object, the start's child under an identity parent inverse, and carries its request",
feed.parent == upper and np.allclose(np.array(feed.matrix_parent_inverse), np.eye(4)) and np.allclose(np.array(feed.matrix_basis), np.eye(4))
and json.loads(feed["kit_hose"])["joint"] == JOINT and len(feed.data.materials) == 0 and len(feed.vertex_groups) == 0, feed.get("kit_hose"))
check("every hose and collar is a closed shell", shells(feed) == (3 + 3 * 4, 0), shells(feed))
points = world_points(feed)
check("each hose starts on the port's face, side by side across it",
min(np.linalg.norm(points - ports[0], axis=1)) < RADIUS * 1.5 and abs(float(((points - ports[0]) @ [1.0, 0, 0]).min())) < 1e-5, None)
line_blocked = others(feed).ray_cast(Vector(ports[0] + [0.12, 0, 0]), Vector((np.array([0, -0.2075, 0.764]) - ports[0] - [0.12, 0, 0])))[0] is not None
check("the straight way from the port to the pin point is through the plate", line_blocked, None)
check("hose-behind-armour: the hose's surface keeps the clearance from every other mesh outside its leads",
reading("clear", surface_clearance(feed, ports), least=True) >= CLEAR, R["readings"])
check("the hose passes the pin's axis: its vertices come within the bundle of the point 0.08 beyond the shin's pin face",
float(np.linalg.norm(points - [0.0, -0.2075, 0.764], axis=1).min()) < 0.08, float(np.linalg.norm(points - [0.0, -0.2075, 0.764], axis=1).min()))
check("the report states sag for both legs, no more than the sag asked for", len(report["sag"]) == 2 and all(0.0 <= s <= 2 * RADIUS + 1e-9 for s in report["sag"]) and any(s > 0 for s in report["sag"]), report["sag"])
_, taut = send("brokkr_kitbash.hose", **{**FEED, "sag": 0.0})
check("sag 0 routes taut and no longer than the sagged hose", taut["sag"] == [0.0, 0.0] and taut["rebuilt"] and taut["length"] < report["length"], [taut["length"], report["length"]])
reading("slack", report["length"] - taut["length"])
section("range")
_, again = send("brokkr_kitbash.hose", **FEED)
check("a rebuild at the same pose reports what the first call did", {**again, "rebuilt": False} == report and len(bpy.data.meshes) == len(state[1]) + 1, again)
check("hose-through-range: the range passes and reports the length's change", report["lengthChange"] is not None and report["lengthChange"] >= 0 and report["worstRoll"] is not None, report)
limits(-20, 90)
refused("a range that swings the shin's hose into the thigh's parts, naming the sagged attempt and the taut one", FEED,
"sagged: roll 48.59: the hose's child's side reads 0.0269 m from the parts about the pin at [-0.2144, -0.2042, 0.7271], counting the 0.0005933 m it can move against the other side's "
"through the 0.156 degrees either side of it: too near the 0.0266 m the bundle needs to prove it of what stands between two readings; taut: roll 50.78: the hose's child's side reads 0.0264 m")
receipt, _ = send("brokkr_kitbash.hose", **FEED)
check("the refusal names both attempts, each by its roll and its side", "sagged: roll " in str(receipt["message"]) and "; taut: roll " in str(receipt["message"])
and str(receipt["message"]).count("the hose's child's side reads") == 2, receipt["message"])
limits(-20, 20)
section("thin plate")
# A plate 1 mm thick, 4 cm square, on the thigh, where a point of the shin's side of a single hose stands at roll
# -17.5: between two of the rolls 5 degrees apart. At -20 and at -15 the hose keeps its need from it.
SINGLE = {**FEED, "object_name": "Single", "start": "ActT:port_rod", "end": "ActS:port_rod", "count": 1, "joint": json.dumps({**JOINT, "standoff": 0.24})}
_, single = send("brokkr_kitbash.hose", **SINGLE)
line = world_points(bpy.data.objects["Single"])
pivot = frame(shin, "end_a_back")
origin, axis = pivot[:3, 3], pivot[:3, 2]
beyond = line[(line[:, 2] > origin[2] + 0.1) & (np.linalg.norm(line - frame(lower, "port_rod")[:3, 3], axis=1) > 0.15)]
far_point = beyond[np.argmax(np.linalg.norm(np.cross(beyond - origin, axis), axis=1))]
turn = math.radians(-17.5)
rel = far_point - origin
at = origin + rel * math.cos(turn) + np.cross(axis, rel) * math.sin(turn) + axis * float(rel @ axis) * (1.0 - math.cos(turn))
way = np.cross(axis, at - origin)
way /= np.linalg.norm(way)
out = np.cross(way, axis)
corners = [at + axis * a * 0.02 + out * b * 0.02 + way * c * 0.0005 for c in (-1, 1) for a in (-1, 1) for b in (-1, 1)]
thin = bpy.data.objects.new("Thin", bpy.data.meshes.new("Thin"))
thin.data.from_pydata([tuple(v) for v in corners], [], [(0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (1, 5, 7, 3), (3, 7, 6, 2), (2, 6, 4, 0)])
bpy.context.scene.collection.objects.link(thin)
bpy.context.view_layer.update()
thin.parent = thigh
thin.matrix_parent_inverse = thigh.matrix_world.inverted()
bpy.context.view_layer.update()
check("the plate stands in the single hose's swing, over 0.03 from where it stands now", single is not None and float(np.linalg.norm(line - at, axis=1).min()) > 0.03, float(np.linalg.norm(line - at, axis=1).min()))
refused("range-sampled-not-swept: a 1 mm plate the hose crosses between two rolls 5 degrees apart", SINGLE, "roll -1")
receipt, _ = send("brokkr_kitbash.hose", **SINGLE)
named = [float(part.split(":")[0]) for part in str(receipt["message"]).split("roll ")[1:]]
check("the refusal names a roll between -20 and -15 for each attempt", len(named) >= 1 and all(-20.0 < roll < -15.0 for roll in named), receipt["message"])
limits(-10, 20)
receipt, narrow = send("brokkr_kitbash.hose", **SINGLE)
check("short of the plate the same hose passes its range", receipt["status"] == "accepted" and narrow["rolls"] >= 7, receipt["message"])
limits(-20, 20)
for name in ("Thin", "Single"):
gone = bpy.data.objects[name]
mesh = gone.data
bpy.data.objects.remove(gone)
bpy.data.meshes.remove(mesh)
bpy.context.view_layer.update()
section("coarse step")
# coarse-step-cuts-thin-plate: no measurement of a hose depends on the search's step. At the coarsest step the
# single taut hose of the finding and the bundle both keep the clearance from the 2 cm armour plate.
for label, extra in (("one taut hose", {"count": 1, "sag": 0.0}), ("the bundle", {})):
receipt, coarse = send("brokkr_kitbash.hose", **{**FEED, "step": 0.2, **extra})
check(f"at step 0.2 {label} routes and keeps the clearance from every other mesh", receipt["status"] == "accepted" and coarse["rebuilt"] and coarse["clearance"] >= CLEARANCE
and reading("clear", surface_clearance(feed, ports), least=True) >= CLEAR, [receipt["message"], R["readings"]])
section("range")
send("brokkr_kitbash.roll", object_name="Shin", roll=10.0)
bpy.context.view_layer.update()
receipt, rolled = send("brokkr_kitbash.hose", **FEED)
check("after a roll the hose rebuilds in place on its name", receipt["status"] == "accepted" and rolled["rebuilt"] and bpy.data.objects["Feed"] == feed and rolled["rolls"] >= 9, receipt["message"])
check("the rebuilt hose keeps the clearance at the new pose", reading("clear", surface_clearance(feed, [frame(upper, "port_cap")[:3, 3], frame(lower, "port_cap")[:3, 3]]), least=True) >= CLEAR, R["readings"])
mesh = feed.data
bpy.data.objects.remove(feed)
bpy.data.meshes.remove(mesh)
bpy.context.view_layer.update()
receipt, fresh = send("brokkr_kitbash.hose", **FEED)
feed = bpy.data.objects["Feed"]
check("hose-through-range: roll then rebuild gives the same report as a fresh hose", receipt["status"] == "accepted" and {**rolled, "rebuilt": False} == fresh, [rolled, fresh])
R["seconds"]["hose on the knee, median of 3"] = round(timed(FEED), 3)
section("second hose")
RETURN = {"object_name": "Return", "start": "ActT:port_rod", "end": "ActS:port_rod", **BUNDLE, "joint": json.dumps({**JOINT, "standoff": 0.24})} # the pin point further out than the first hose's, at the default step
receipt, back = send("brokkr_kitbash.hose", **RETURN)
R["reports"]["return"] = back
check("second-bundle: a second hose routes through the same knee at the default step, its range measured against the parts and not against where the first hose stood",
receipt["status"] == "accepted" and back["nonManifoldEdges"] == 0 and back["rolls"] >= 9 and abs(json.loads(bpy.data.objects["Return"]["kit_hose"])["step"] - 0.02) < 1e-6, [receipt["status"], receipt["message"]])
for step in (0.0125, 0.03, 0.04): # feasibility does not turn on the step: a leg is searched with room for its bends
receipt, _ = send("brokkr_kitbash.hose", **{**FEED, "step": step})
check(f"the first hose's route also stands at step {step}, beside the second", receipt["status"] == "accepted", receipt["message"])
# bend-room-not-monotone-in-step: a search's polyline is a seed. These are steps whose seeds were refused before
# seeds were refined and searched on other grid origins (0.1275 of the first bundle, the rest of the second).
seeds = []
for base, step in [(FEED, 0.1275)] + [(RETURN, step) for step in (0.0225, 0.04, 0.115, 0.1425, 0.155, 0.2)]:
receipt, swept = send("brokkr_kitbash.hose", **{**base, "step": step})
ok = receipt["status"] == "accepted"
check(f"{base['object_name']} routes at step {step}: no bend under the floor, the clearance kept", ok and swept["radii"]["least"] >= FLOOR * (1 - 1e-6) and swept["clearance"] >= CLEARANCE
and swept["worstClearance"] >= CLEARANCE and reading("clear", surface_clearance(bpy.data.objects[base["object_name"]], [frame(ram, "port_cap" if base is FEED else "port_rod")[:3, 3] for ram in (upper, lower)]), least=True) >= CLEAR,
[receipt["message"], swept, R["readings"]])
seeds.append(swept["seed"] if ok else None)
R["reports"]["seeds"] = seeds
check("some of those routes come from a refined seed and some from another grid origin, and the report says which",
any(seed and seed["refined"] for seed in seeds) and any(seed and seed["offset"] != [0.0, 0.0, 0.0] for seed in seeds), seeds)
send("brokkr_kitbash.hose", **FEED)
send("brokkr_kitbash.hose", **RETURN)
refused("a bend the search finds no route for on the knee, by what its first seed lacked", {**FEED, "bend": 16.0}, "under the floor 0.2076: ")
rod_ports = [frame(upper, "port_rod")[:3, 3], frame(lower, "port_rod")[:3, 3]]
check("hose-behind-armour: the second hose keeps the clearance from the first", reading("clear", surface_clearance(bpy.data.objects["Return"], rod_ports), least=True) >= CLEAR, R["readings"])
refused("a pin point another hose already passes", {**RETURN, "object_name": "Third"}, "from an obstacle")
section("too stiff")
# too stiff is said where it is proven: a wall 0.08 above a port leaves the centre line 0.021 beyond its lead to
# turn aside in, and a curve of the floor radius 0.048 cannot; one of 0.012 can, and routes.
for name, x in (("Nozzle", 10.0), ("Drain", 10.6)):
empty = bpy.data.objects.new(name, None)
empty.location = (x, 0.0, 0.0)
bpy.context.scene.collection.objects.link(empty)
box("Lid", (9.0, -1.0, 0.08), (11.6, 1.0, 0.1))
bpy.context.view_layer.update()
LOOP = {"object_name": "Loop", "start": "Nozzle", "end": "Drain", "count": 1, "radius": RADIUS, "clearance": CLEARANCE}
refused("a bundle proven too stiff to leave its port under a wall", LOOP, "the bundle is too stiff to leave its start: from the end of its lead at [10, 0, 0.048] no curve that bends at the floor radius 0.048 m or wider")
receipt, loop = send("brokkr_kitbash.hose", **{**LOOP, "bend": 1.0})
check("the same hose at bend 1 routes under the wall", receipt["status"] == "accepted" and loop["radii"]["least"] >= 0.012 * (1 - 1e-6) and loop["clearance"] >= CLEARANCE, [receipt["message"], loop])
section("clamps")
tank = place("Tank", "tank", "radius=0.22;length=0.9", [3.0, 0.0, 0.0])
seats = [place(name, "plate", "width=0.1;height=0.1", [x, 0.0, 1.25], [0.0, 0.0, math.pi / 2]) for name, x in (("SeatA", 3.45), ("SeatB", 4.05))]
ram = place("Ram", "actuator", RAM, [5.074, 0.0, 1.07], [0.0, 0.0, math.pi])
bpy.context.view_layer.update()
LINE = {"object_name": "Line", "start": "Tank:port_b", "end": "Ram:port_cap", **BUNDLE, "clamps": json.dumps([{"socket": "SeatA:front"}, {"socket": "SeatB:front"}])}
receipt, line = send("brokkr_kitbash.hose", **LINE)
R["reports"]["line"] = line
check("hose-clamps-ports: a hose runs from the tank's flange over two clamps to the ram's port", receipt["status"] == "accepted" and line["nonManifoldEdges"] == 0 and len(line["voxels"]) == 3
and line["rolls"] is None and line["lengthChange"] is None, [receipt["status"], receipt["message"]])
hose = bpy.data.objects["Line"]
check("three hoses with four collars each, two straps and two pads", shells(hose) == (3 + 12 + 4, 0), shells(hose))
points = world_points(hose)
stand, held = ENVELOPE + CLEARANCE + RADIUS, 4.0 * RADIUS + FLOOR
for seat in seats:
at = frame(seat, "front")
centre, y, x = at[:3, 3] + at[:3, 2] * stand, at[:3, 1], at[:3, 0]
for k in range(COUNT_HOSES):
origin = centre + x * (k - 1) * SPREAD
rel = points - origin
along = rel @ y
off = np.abs(np.linalg.norm(rel - np.outer(along, y), axis=1) - RADIUS)
near = np.sort(off[np.abs(along) <= held + 1e-6])[:24] # the two rings where the kept straight ends, twelve vertices each
reading("clamped", near.max() if len(near) == 24 else 1.0)
reading("kept", np.abs(along[off < 1e-5]).min() if (off < 1e-5).any() else 0.0, least=True)
check("hose-clamps-ports: each hose passes each clamp point straight along the socket's y", R["readings"]["clamped"] <= CLAMPED, R["readings"])
check("the bundle runs straight for two outside diameters each side of a clamp point: no ring of a bend stands nearer", R["readings"]["kept"] >= KEPT, R["readings"])
check("the clamped hose reports the clearance it keeps (its pads stand on their seats)", line["clearance"] >= CLEARANCE and surface_clearance(hose, [frame(tank, "port_b")[:3, 3], frame(ram, "port_cap")[:3, 3]]) < 1e-6,
line["clearance"])
refused("a bundle wider than the port", {**LINE, "object_name": "Wide", "count": 5}, "a bundle of 5 hoses is 0.0744 m wide, over socket 'Ram:port_cap' (hose, size 0.048)")
tip = bpy.data.objects.new("Tip", None)
bpy.context.scene.collection.objects.link(tip)
tip.location, tip.rotation_euler = (3.5, 0.0, -1.3), (0.0, -math.pi / 6, 0.0) # under the tank's lower port, its z up toward it
bpy.context.view_layer.update()
receipt, loose = send("brokkr_kitbash.hose", object_name="Loose", start="Tank:port_a", end="Tip", radius=0.02)
check("a hose runs from a flange to an empty", receipt["status"] == "accepted" and loose["hoses"] == 1 and shells(bpy.data.objects["Loose"]) == (5, 0), [receipt["status"], receipt["message"]])
section("verify")
# h4-claimable-live: a straight hose from a ram's port to an empty in line with it has no corner and no pin, and
# its leg starts beyond the plate that stands 0.008 under its first straight: route.verify is the only thing that
# measures that straight, and refuses it. With verify refusing nothing (H4b) the hose is made and reads under CLEAR.
solo = place("Solo", "actuator", RAM, [10.0, 0.0, 0.0])
bpy.context.view_layer.update()
mouth = frame(solo, "port_cap")[:3, 3]
stub = bpy.data.objects.new("Stub", None)
bpy.context.scene.collection.objects.link(stub)
stub.location, stub.rotation_euler = (float(mouth[0]) + 0.5, float(mouth[1]), float(mouth[2])), (0.0, -math.pi / 2, 0.0) # its z back along the line toward the port
box("Beside", (mouth[0] + 0.06, mouth[1] - 0.05, mouth[2] - 0.06), (mouth[0] + 0.08, mouth[1] + 0.05, mouth[2] - 0.008))
bpy.context.view_layer.update()
PAST = {"object_name": "Past", "start": "Solo:port_cap", "end": "Stub", "radius": RADIUS, "clearance": CLEARANCE, "sag": 0.0}
state = scene_state()
receipt, _ = send("brokkr_kitbash.hose", **PAST)
past = bpy.data.objects.get("Past")
if past is not None:
reading("clear", surface_clearance(past, [mouth, np.array(stub.location)]), least=True)
check("h4: the straight past the plate is refused by route.verify, naming the point; nothing changed",
receipt["status"] != "accepted" and "the hose stands 0.008 m from an obstacle at [" in str(receipt["message"]) and "under the 0.011 m the bundle needs" in str(receipt["message"])
and scene_state() == state, [receipt["status"], receipt["message"]])
check("h4: no hose this suite made stands nearer another mesh than CLEAR", R["readings"]["clear"] >= CLEAR, R["readings"])
bpy.data.objects["Beside"].location = (0.0, 0.0, -0.01) # 0.018 under the straight: the same call routes
bpy.context.view_layer.update()
receipt, past = send("brokkr_kitbash.hose", **PAST)
check("with the plate 0.018 under it the same straight is made", receipt["status"] == "accepted" and (past["radii"]["least"] is None or past["radii"]["least"] > 1e3) and abs(past["clearance"] - 0.012) < 1e-4, [receipt["message"], past])
section("refusals")
refused("a name taken by a mesh that is no hose", {**FEED, "object_name": "Thigh"}, "An object named 'Thigh' exists and is no hose")
refused("a socket the part does not have", {**FEED, "start": "ActT:nope"}, "start: 'ActT' (a actuator) has no socket 'nope'; its sockets: base, base_back, rod_end, rod_end_back, port_cap, port_rod")
refused("an object that does not exist", {**FEED, "end": "Nobody:port_cap"}, "end: no object named 'Nobody'")
refused("a pivot as an end", {**FEED, "start": "Thigh:end_a"}, "start: socket 'end_a' of 'Thigh' is a pivot socket; this takes a hose or flange socket")
refused("a mesh that is no empty as an end", {**FEED, "end": "Armour"}, "end 'Armour' names no socket")
refused("a clamp on a pivot", {**FEED, "clamps": json.dumps([{"socket": "Thigh:end_a"}])}, "clamps[0]: socket 'end_a' of 'Thigh' is a pivot socket; this takes a mount socket")
refused("clamps that are not rows of socket", {**FEED, "clamps": json.dumps([{"at": [0, 0, 0]}])}, "clamps[0] must be an object of socket")
refused("nine clamps", {**FEED, "clamps": json.dumps([{"socket": "SeatA:front"}] * 9)}, "clamps must be a JSON array of 0 to 8 objects")
refused("a pin crossed with no joint", {k: v for k, v in FEED.items() if k != "joint"}, "The hose crosses the pin of 'Shin' on 'Thigh' (socket 'end_b_back'): give joint")
refused("a joint where no pin is crossed", {**LINE, "object_name": "New", "joint": json.dumps(JOINT)}, "joint is given and the hose crosses no pin")
feed.modifiers.new("Smooth", "SUBSURF") # by hand: a hose has no modifiers of its own, and freeze takes any mesh that has one
receipt, chilled = send("brokkr_kitbash.freeze", object_name="Feed")
check("a hose given a modifier freezes", receipt["status"] == "accepted" and chilled and chilled["frozen"] is True and feed.data.name == "Feed frozen", receipt["message"])
refused("a rebuild of a frozen hose", FEED, "'Feed' is frozen, and rebuilding it needs its live mesh and modifiers: thaw it first")
send("brokkr_kitbash.thaw", object_name="Feed")
feed.modifiers.remove(feed.modifiers["Smooth"])
receipt, thawed = send("brokkr_kitbash.hose", **FEED)
check("the thawed hose rebuilds", receipt["status"] == "accepted" and "Feed frozen" not in bpy.data.meshes and thawed["nonManifoldEdges"] == 0, receipt["message"])
place("Jack", "actuator", "body_r=0.0534;body_len=0.2;extension=0")
send("brokkr_kitbash.attach", object_name="Jack", socket="base", parent_name="Shin", parent_socket="end_b", roll=90.0)
bpy.context.view_layer.update()
refused("two pins crossed", {**FEED, "object_name": "New", "end": "Jack:port_cap", "count": 1, "radius": 0.004}, "The hose crosses 2 pins ('Jack' on 'Shin', 'Shin' on 'Thigh'): a hose crosses one")
refused("a joint socket off the crossed pin's axis", {**FEED, "joint": json.dumps({**JOINT, "socket": "Shin:end_b_back"})}, "joint.socket 'Shin:end_b_back' is not on the axis of the pin the hose crosses ('Shin' on 'Thigh', socket 'end_b_back')")
state = scene_state()
receipt = limits(30, 60)
check("limits that exclude the roll the knee stands at are the joint action's to refuse", receipt["status"] != "accepted" and "'Shin' on 'Thigh': its roll 10 is outside the joint's limits 30 to 60" in str(receipt["message"])
and scene_state() == state, receipt["message"])
receipt = limits(-200, 200)
check("and limits over a full turn", receipt["status"] != "accepted" and "a revolute joint's span at most 360 degrees" in str(receipt["message"]) and scene_state() == state, receipt["message"])
shin["kit_min"], shin["kit_max"] = 30.0, 60.0 # by hand: the hose reads the pin's limits and finds the roll outside them
refused("the current roll outside limits written by hand", FEED, "'Shin' stands at roll 10, outside its joint's limits 30 to 60")
shin["kit_min"], shin["kit_max"] = -20.0, 20.0
refused("a joint that states a range of its own", {**FEED, "joint": json.dumps({**JOINT, "range": [-20, 20]})}, "joint must be an object of socket (an 'Object:socket' text) and standoff (0 to 10)")
place("Barrel", "ram_barrel", "body_r=0.0534")
place("Rod", "ram_rod", "body_r=0.0534")
send("brokkr_kitbash.attach", object_name="Barrel", socket="base", parent_name="Shin", parent_socket="end_b_back", roll=90.0)
send("brokkr_kitbash.attach", object_name="Rod", socket="piston", parent_name="Barrel", parent_socket="bore")
rod_tip = bpy.data.objects.new("RodTip", None)
bpy.context.scene.collection.objects.link(rod_tip)
rod_tip.parent = bpy.data.objects["Rod"]
bpy.context.view_layer.update()
refused("hose-range-from-pin: a hose across a slide", {**FEED, "object_name": "New", "start": "Barrel:port_cap", "end": "RodTip", "count": 1, "radius": 0.004, "joint": ""},
"The hose crosses the slide of 'Rod' on 'Barrel' (socket 'bore'): a hose across a prismatic connection is not routed")
refused("a grid past the voxel limit", {**FEED, "step": 0.005}, "voxels at step 0.005, over 524288: a step of ")
lower.scale = (1.0, 1.0, 1.01)
bpy.context.view_layer.update()
refused("a scaled part", FEED, "'ActS' is scaled, mirrored or sheared in the world")
lower.scale = (1.0, 1.0, 1.0)
tip.hide_viewport = True
bpy.context.view_layer.update()
refused("a hidden end", {"object_name": "Loose", "start": "Tank:port_a", "end": "Tip", "radius": 0.02}, "Blender does not evaluate 'Tip' in this view layer")
tip.hide_viewport = False
bpy.context.view_layer.update()
if len(sys.argv) > sys.argv.index("--") + 2:
bpy.ops.wm.save_as_mainfile(filepath=sys.argv[sys.argv.index("--") + 2])
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())}
seconds = R.pop("seconds") # wall time is this machine's: printed, and kept out of the result file
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)
print("SECONDS", seconds, flush=True)
sys.exit(0 if R["ok"] else 1)

View file

@ -0,0 +1,593 @@
{
"blender": "5.3.0",
"checks": [
{
"name": "the actuator's ports sit on its boss faces, facing out",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: hose-range-from-pin: a pin with no limits, naming the action that states them",
"ok": true,
"detail": null
},
{
"name": "the knee takes its limits",
"ok": true,
"detail": null
},
{
"name": "hose-behind-armour: three hoses route from the thigh's ram to the shin's, round the plate and through the pin point",
"ok": true,
"detail": null
},
{
"name": "the hose is one object, the start's child under an identity parent inverse, and carries its request",
"ok": true,
"detail": null
},
{
"name": "every hose and collar is a closed shell",
"ok": true,
"detail": null
},
{
"name": "each hose starts on the port's face, side by side across it",
"ok": true,
"detail": null
},
{
"name": "the straight way from the port to the pin point is through the plate",
"ok": true,
"detail": null
},
{
"name": "hose-behind-armour: the hose's surface keeps the clearance from every other mesh outside its leads",
"ok": true,
"detail": null
},
{
"name": "the hose passes the pin's axis: its vertices come within the bundle of the point 0.08 beyond the shin's pin face",
"ok": true,
"detail": null
},
{
"name": "the report states sag for both legs, no more than the sag asked for",
"ok": true,
"detail": null
},
{
"name": "sag 0 routes taut and no longer than the sagged hose",
"ok": true,
"detail": null
},
{
"name": "a rebuild at the same pose reports what the first call did",
"ok": true,
"detail": null
},
{
"name": "hose-through-range: the range passes and reports the length's change",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a range that swings the shin's hose into the thigh's parts, naming the sagged attempt and the taut one",
"ok": true,
"detail": null
},
{
"name": "the refusal names both attempts, each by its roll and its side",
"ok": true,
"detail": null
},
{
"name": "the plate stands in the single hose's swing, over 0.03 from where it stands now",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: range-sampled-not-swept: a 1 mm plate the hose crosses between two rolls 5 degrees apart",
"ok": true,
"detail": null
},
{
"name": "the refusal names a roll between -20 and -15 for each attempt",
"ok": true,
"detail": null
},
{
"name": "short of the plate the same hose passes its range",
"ok": true,
"detail": null
},
{
"name": "at step 0.2 one taut hose routes and keeps the clearance from every other mesh",
"ok": true,
"detail": null
},
{
"name": "at step 0.2 the bundle routes and keeps the clearance from every other mesh",
"ok": true,
"detail": null
},
{
"name": "after a roll the hose rebuilds in place on its name",
"ok": true,
"detail": null
},
{
"name": "the rebuilt hose keeps the clearance at the new pose",
"ok": true,
"detail": null
},
{
"name": "hose-through-range: roll then rebuild gives the same report as a fresh hose",
"ok": true,
"detail": null
},
{
"name": "second-bundle: a second hose routes through the same knee at the default step, its range measured against the parts and not against where the first hose stood",
"ok": true,
"detail": null
},
{
"name": "the first hose's route also stands at step 0.0125, beside the second",
"ok": true,
"detail": null
},
{
"name": "the first hose's route also stands at step 0.03, beside the second",
"ok": true,
"detail": null
},
{
"name": "the first hose's route also stands at step 0.04, beside the second",
"ok": true,
"detail": null
},
{
"name": "Feed routes at step 0.1275: no bend under the floor, the clearance kept",
"ok": true,
"detail": null
},
{
"name": "Return routes at step 0.0225: no bend under the floor, the clearance kept",
"ok": true,
"detail": null
},
{
"name": "Return routes at step 0.04: no bend under the floor, the clearance kept",
"ok": true,
"detail": null
},
{
"name": "Return routes at step 0.115: no bend under the floor, the clearance kept",
"ok": true,
"detail": null
},
{
"name": "Return routes at step 0.1425: no bend under the floor, the clearance kept",
"ok": true,
"detail": null
},
{
"name": "Return routes at step 0.155: no bend under the floor, the clearance kept",
"ok": true,
"detail": null
},
{
"name": "Return routes at step 0.2: no bend under the floor, the clearance kept",
"ok": true,
"detail": null
},
{
"name": "some of those routes come from a refined seed and some from another grid origin, and the report says which",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a bend the search finds no route for on the knee, by what its first seed lacked",
"ok": true,
"detail": null
},
{
"name": "hose-behind-armour: the second hose keeps the clearance from the first",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a pin point another hose already passes",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a bundle proven too stiff to leave its port under a wall",
"ok": true,
"detail": null
},
{
"name": "the same hose at bend 1 routes under the wall",
"ok": true,
"detail": null
},
{
"name": "hose-clamps-ports: a hose runs from the tank's flange over two clamps to the ram's port",
"ok": true,
"detail": null
},
{
"name": "three hoses with four collars each, two straps and two pads",
"ok": true,
"detail": null
},
{
"name": "hose-clamps-ports: each hose passes each clamp point straight along the socket's y",
"ok": true,
"detail": null
},
{
"name": "the bundle runs straight for two outside diameters each side of a clamp point: no ring of a bend stands nearer",
"ok": true,
"detail": null
},
{
"name": "the clamped hose reports the clearance it keeps (its pads stand on their seats)",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a bundle wider than the port",
"ok": true,
"detail": null
},
{
"name": "a hose runs from a flange to an empty",
"ok": true,
"detail": null
},
{
"name": "h4: the straight past the plate is refused by route.verify, naming the point; nothing changed",
"ok": true,
"detail": null
},
{
"name": "h4: no hose this suite made stands nearer another mesh than CLEAR",
"ok": true,
"detail": null
},
{
"name": "with the plate 0.018 under it the same straight is made",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a name taken by a mesh that is no hose",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a socket the part does not have",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: an object that does not exist",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a pivot as an end",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a mesh that is no empty as an end",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a clamp on a pivot",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: clamps that are not rows of socket",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: nine clamps",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a pin crossed with no joint",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a joint where no pin is crossed",
"ok": true,
"detail": null
},
{
"name": "a hose given a modifier freezes",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a rebuild of a frozen hose",
"ok": true,
"detail": null
},
{
"name": "the thawed hose rebuilds",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: two pins crossed",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a joint socket off the crossed pin's axis",
"ok": true,
"detail": null
},
{
"name": "limits that exclude the roll the knee stands at are the joint action's to refuse",
"ok": true,
"detail": null
},
{
"name": "and limits over a full turn",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: the current roll outside limits written by hand",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a joint that states a range of its own",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: hose-range-from-pin: a hose across a slide",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a grid past the voxel limit",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a scaled part",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a hidden end",
"ok": true,
"detail": null
}
],
"hostErrors": [],
"readings": {
"clamped": 4.6e-08,
"clear": 0.031,
"kept": 0.028,
"slack": 0.017
},
"reports": {
"feed": {
"object": "Feed",
"rebuilt": false,
"hoses": 3,
"length": 1.642855,
"lengthChange": 0.034539,
"floor": 0.0636,
"clearance": 0.024995,
"capped": 0.1522,
"voxels": [
79488,
53406
],
"seed": {
"step": 0.02,
"offset": [
0.0,
0.0,
0.0
],
"refined": false
},
"sag": [
0.001879,
0.009076
],
"rolls": 9,
"worstRoll": -20.0,
"worstClearance": 0.025166,
"faces": 3378,
"volume": 0.000577468,
"nonManifoldEdges": 0,
"radii": {
"least": 0.134032,
"corners": [
0.297307,
0.134032,
28.760693,
0.232497,
3.487729,
0.140588
]
}
},
"return": {
"object": "Return",
"rebuilt": false,
"hoses": 3,
"length": 1.679265,
"lengthChange": 0.032203,
"floor": 0.0636,
"clearance": 0.026679,
"capped": 0.1522,
"voxels": [
82110,
92820
],
"seed": {
"step": 0.02,
"offset": [
0.0,
0.0,
0.0
],
"refined": false
},
"sag": [
0.008745,
0.00844
],
"rolls": 9,
"worstRoll": -20.0,
"worstClearance": 0.027159,
"faces": 5466,
"volume": 0.000589265,
"nonManifoldEdges": 0,
"radii": {
"least": 0.082543,
"corners": [
0.082543,
4.587721,
0.136709,
0.183407,
0.094636,
9.943722,
0.104249
]
}
},
"seeds": [
{
"step": 0.1275,
"offset": [
0.0,
0.0,
0.0
],
"refined": false
},
{
"step": 0.0225,
"offset": [
0.0,
0.0,
0.0
],
"refined": false
},
{
"step": 0.04,
"offset": [
0.0,
0.0,
0.0
],
"refined": true
},
{
"step": 0.115,
"offset": [
0.0,
0.0,
0.0
],
"refined": true
},
{
"step": 0.1425,
"offset": [
0.31,
0.67,
0.13
],
"refined": false
},
{
"step": 0.155,
"offset": [
0.0,
0.0,
0.0
],
"refined": true
},
{
"step": 0.1,
"offset": [
0.0,
0.0,
0.0
],
"refined": false
}
],
"line": {
"object": "Line",
"rebuilt": false,
"hoses": 3,
"length": 2.100069,
"lengthChange": null,
"floor": 0.0636,
"clearance": 0.010959,
"capped": 0.1522,
"voxels": [
49815,
34992,
43011
],
"seed": {
"step": 0.02,
"offset": [
0.0,
0.0,
0.0
],
"refined": false
},
"sag": [
0.00942,
0.012,
0.011996
],
"rolls": null,
"worstRoll": null,
"worstClearance": null,
"faces": 2510,
"volume": 0.000777105,
"nonManifoldEdges": 0,
"radii": {
"least": 0.100091,
"corners": [
0.109706,
4.289628,
0.100091,
1.739264,
2.896538,
1.739264,
1.672436,
7.389576,
10.858347
]
}
}
},
"ok": true
}

View file

@ -84,6 +84,14 @@ NEARER = 0.0
# Metres past the top of its circle a reach may ask (core.REACH_EDGE, a rule: HELD). A height typed back from a
# refusal's range overshoots by at most 3.2e-07 here and is taken; PAST is refused. The two sit sqrt(10) either side.
EDGE, PAST = 1e-5, 3.2e-5
# The largest difference between a joints row's axis or origin and the parent socket's z or origin read from the scene
# in the root's frame. Shipped worst 4.9e-07 (rows carry 6 decimals); least claimed mutant 3.1 (J11, the rows in the
# world's frame); separation 6.3e6.
JOINT_FRAME = 1.2e-3
# The joint-record readings below use the bounds above: "slid", metres between the rod's piston and the point its slide
# states along the bore's z, against SEATED (shipped 1.4e-07; least claimed mutant J1, the slide applied after FLIP, reads 0.6);
# "limit roll", degrees between a roll solved inside limits and the one expected, against ROLL (shipped
# 2e-05; its mutants J2, J3 and J4 die in test_kitbash's JointRecordTests, where their readings are).
def check(name, ok, detail=None):
@ -309,6 +317,166 @@ try:
refused("reach along no direction", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_b", "height": 0.0, "direction_z": 0.0}, "The direction is zero")
refused("a roll past a turn, by the action table", "brokkr_kitbash.roll", {"object_name": "Strut", "roll": 361.0}, "roll")
refused("an axis that is not one of the six, by the action table", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "x", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0}, "axis")
# --- joint records ------------------------------------------------------------------------------------------------------
# Below the strut: a barrel on its other pin with a rod in its bore, and a bracket hung by its own pin that carries a
# second bracket rigidly, which carries a strut on its pin. Tank > Mount (rigid) > Strut > {Barrel > Rod, Hinge > Foot (rigid) > Toe, Ram}.
rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")]
check("joint, slide and joints load as host actions after reach", rows[rows.index("brokkr_kitbash.reach") + 1:][:3] == ["brokkr_kitbash.joint", "brokkr_kitbash.slide", "brokkr_kitbash.joints"], rows)
barrel, rod = place("Barrel", "ram_barrel"), place("Rod", "ram_rod")
hinge, foot, toe = place("Hinge", "bracket"), place("Foot", "bracket"), place("Toe", "strut", "width=0.09")
send("brokkr_kitbash.attach", object_name="Barrel", socket="base", parent_name="Strut", parent_socket="end_b_back", roll=25.0)
receipt, report = send("brokkr_kitbash.attach", object_name="Rod", socket="piston", parent_name="Barrel", parent_socket="bore")
send("brokkr_kitbash.attach", object_name="Hinge", socket="pivot", parent_name="Strut", parent_socket="end_a_back", roll=-15.0)
send("brokkr_kitbash.attach", object_name="Foot", socket="mount", parent_name="Hinge", parent_socket="mount", roll=90.0)
send("brokkr_kitbash.attach", object_name="Toe", socket="end_a", parent_name="Foot", parent_socket="pivot", roll=40.0)
found = report and report["connection"]
check("a rod attaches in its barrel's bore: a prismatic connection at slide 0 with no joint record, and no record key written",
receipt["status"] == "accepted" and holds(found, "Barrel", "piston", "bore", 0.0) and found == {**found, "dof": "prismatic", "slide": 0.0, "limits": None, "mechanism": None, "compliance": None, "within": True}
and sorted(k for k in rod.keys() if k.startswith("kit_")) == ["kit_kit", "kit_params", "kit_parent_socket", "kit_part", "kit_roll", "kit_slide", "kit_socket"]
and connection("Strut")["dof"] == "revolute" and connection("Mount")["dof"] is None and "kit_slide" not in strut.keys() and "kit_slide" not in mount.keys(),
[receipt["message"], found, sorted(rod.keys()), connection("Strut"), connection("Mount")])
def slid(amount):
"""How far the rod's piston stands from the point `amount` along the bore's z, and how far its normal is from opposed."""
a, b = frame(barrel, "bore"), frame(rod, "piston")
return max(float(np.linalg.norm(b[:3, 3] - a[:3, 3] - amount * a[:3, 2])), float(np.abs(a[:3, 2] + b[:3, 2]).max()))
# the record: stated by joint, kept key by key
spring = {"hertz": 4.0, "damping_ratio": 0.7}
receipt, report = send("brokkr_kitbash.joint", object_name="Rod", record=json.dumps({"limits": [0.0, 0.3], "mechanism": "shock", "compliance": spring}))
found = report and report["connection"]
check("joint states a slide's limits, mechanism and compliance, and moves nothing", receipt["status"] == "accepted" and found == {**found, "dof": "prismatic", "slide": 0.0, "limits": [0.0, 0.3],
"mechanism": "shock", "compliance": spring, "within": True, "holds": True} and (rod["kit_min"], rod["kit_max"], rod["kit_mechanism"], json.loads(rod["kit_compliance"])) == (0.0, 0.3, "shock", spring)
and reading("slid", slid(0.0)) < SEATED, [receipt["message"], found, dict(rod.items())])
receipt, report = send("brokkr_kitbash.joint", object_name="Rod", record=json.dumps({"mechanism": None}))
found = report and report["connection"]
check("a key left out keeps what is stated and null clears it", receipt["status"] == "accepted" and found == {**found, "limits": [0.0, 0.3], "mechanism": None, "compliance": spring}
and "kit_mechanism" not in rod.keys(), [receipt["message"], found])
send("brokkr_kitbash.joint", object_name="Rod", record=json.dumps({"mechanism": "shock"}))
# slide
for amount in (0.12, 0.3, 0.0, 0.12):
was, pin = stated(rod), frame(rod, "rod_end")[:3, 3].copy()
receipt, report = send("brokkr_kitbash.slide", object_name="Rod", slide=amount)
off, moved = reading("slid", slid(amount)), float(np.linalg.norm(frame(rod, "rod_end")[:3, 3] - pin))
found = report and report["connection"]
check(f"slide {amount:g} moves the rod along the bore's z where it hangs: its parent, sockets, roll and record as they were, the slide stated and seated",
receipt["status"] == "accepted" and off < SEATED and abs(rod["kit_slide"] - amount) < 1e-6 and found["holds"] is True and found["slide"] == round(rod["kit_slide"], 6)
and {k: v for k, v in stated(rod)[1].items() if k != "kit_slide"} == {k: v for k, v in was[1].items() if k != "kit_slide"} and stated(rod)[0] == "Barrel"
and abs(moved - abs(amount - was[1]["kit_slide"])) < SEATED, [receipt["message"], found, off, moved, dict(rod.items())])
receipt, report = send("brokkr_kitbash.roll", object_name="Rod", roll=90.0)
check("a roll on a prismatic connection is a build angle: it turns the rod in the bore and the slide stays", receipt["status"] == "accepted" and rod["kit_roll"] == 90.0
and abs(rod["kit_slide"] - 0.12) < 1e-6 and reading("slid", slid(0.12)) < SEATED and holds(report["connection"], "Barrel", "piston", "bore", 90.0), [receipt["message"], report and report["connection"]])
receipt, report = send("brokkr_kitbash.set_params", object_name="Barrel", params="body_len=0.5")
check("set_params of the barrel moves its bore and reseats the rod at its slide", receipt["status"] == "accepted" and reading("slid", slid(0.12)) < SEATED
and connection("Rod") == {**connection("Rod"), "holds": True, "slide": 0.12}, [receipt["message"], connection("Rod")])
refused("a slide past the joint's limits, naming value and limits", "brokkr_kitbash.slide", {"object_name": "Rod", "slide": 0.31}, "'Rod' on 'Barrel': its slide 0.31 is outside the joint's limits 0 to 0.3")
refused("a slide under them", "brokkr_kitbash.slide", {"object_name": "Rod", "slide": -0.01}, "its slide -0.01 is outside the joint's limits 0 to 0.3")
refused("a slide of a pin, naming its type", "brokkr_kitbash.slide", {"object_name": "Strut", "slide": 0.1}, "'Strut' on 'Mount': socket type 'pivot' is revolute: slide poses a prismatic connection")
refused("a slide of a rigid connection, naming its type", "brokkr_kitbash.slide", {"object_name": "Mount", "slide": 0.1}, "'Mount' on 'Tank': socket type 'mount' is rigid: slide poses a prismatic connection")
refused("a joint record on a rigid connection, naming its type", "brokkr_kitbash.joint", {"object_name": "Mount", "record": '{"limits": [0, 10]}'},
"'Mount' on 'Tank': socket type 'mount' states no dof: the connection is rigid")
refused("limits that exclude the slide the joint has", "brokkr_kitbash.joint", {"object_name": "Rod", "record": '{"limits": [0.2, 0.3]}'}, "its slide 0.12 is outside the joint's limits 0.2 to 0.3")
refused("prismatic limits past 10 m", "brokkr_kitbash.joint", {"object_name": "Rod", "record": '{"limits": [0, 11]}'}, "a prismatic joint's stand within 10 m of 0")
refused("limits cleared under a compliance", "brokkr_kitbash.joint", {"object_name": "Rod", "record": '{"limits": null}'}, "compliance needs limits")
refused("a compliance out of range", "brokkr_kitbash.joint", {"object_name": "Rod", "record": '{"compliance": {"hertz": 0, "damping_ratio": 0.7}}'}, "hertz is over 0 and at most 30")
refused("a compliance on a pin", "brokkr_kitbash.joint", {"object_name": "Strut", "record": '{"limits": [-180, 180], "compliance": {"hertz": 4, "damping_ratio": 0.7}}'},
"compliance is a prismatic joint's (a slide that settles under load): socket type 'pivot' is revolute")
refused("revolute limits spanning over a turn", "brokkr_kitbash.joint", {"object_name": "Strut", "record": '{"limits": [-200, 200]}'}, "a revolute joint's span at most 360 degrees")
refused("a revolute limit past 360", "brokkr_kitbash.joint", {"object_name": "Strut", "record": '{"limits": [300, 400]}'}, "each end within 360 of 0")
refused("a record that is not the shape", "brokkr_kitbash.joint", {"object_name": "Strut", "record": '{"limits": [10, -10]}'}, "record must be a JSON object of any of limits")
refused("a record with a key it does not have", "brokkr_kitbash.joint", {"object_name": "Strut", "record": '{"axis": [0, 0, 1]}'}, "record must be a JSON object of any of limits")
refused("a mechanism that is no label", "brokkr_kitbash.joint", {"object_name": "Strut", "record": '{"mechanism": "Knee Ram"}'}, "record must be a JSON object of any of limits")
refused("a record that is not JSON", "brokkr_kitbash.joint", {"object_name": "Strut", "record": "{limits}"}, "record must be JSON")
refused("a joint record on a part nobody attached", "brokkr_kitbash.joint", {"object_name": "Spare", "record": "{}"}, "'Spare' is not attached")
# limits on a pin: roll, aim and reach stay inside them
world, z = np.array(mount.matrix_world, dtype=np.float64), np.array([0.0, 0.0, 1.0])
pointing = lambda roll: (world @ core.mate(socket(mount, "pivot"), socket(strut, "end_a"), roll))[:3, :3] @ z # noqa: E731 where the strut's z points at a roll
send("brokkr_kitbash.roll", object_name="Strut", roll=180.0)
refused("limits that exclude the roll the joint has", "brokkr_kitbash.joint", {"object_name": "Strut", "record": '{"limits": [190, 210]}'}, "'Strut' on 'Mount': its roll 180 is outside the joint's limits 190 to 210")
receipt, report = send("brokkr_kitbash.joint", object_name="Strut", record='{"limits": [150, 210], "mechanism": "knee"}')
check("joint states a pin's limits about the roll it has", receipt["status"] == "accepted" and report["connection"] == {**report["connection"], "roll": 180.0, "limits": [150.0, 210.0], "mechanism": "knee", "within": True}
and (strut["kit_min"], strut["kit_max"]) == (150.0, 210.0) and "kit_slide" not in strut.keys(), [receipt["message"], report and report["connection"]])
refused("a roll with no turn of itself inside the limits, naming value and limits", "brokkr_kitbash.roll", {"object_name": "Strut", "roll": 100.0}, "'Strut' on 'Mount': its roll 100 is outside the joint's limits 150 to 210")
receipt, report = send("brokkr_kitbash.roll", object_name="Strut", roll=-170.0)
check("a roll a turn away from the limits is written as its representative inside them: -170 as 190", receipt["status"] == "accepted" and strut["kit_roll"] == 190.0
and holds(report["connection"], "Mount", "end_a", "pivot", 190.0) and reading("seated", seated(strut, "end_a", mount, "pivot", 190.0)) < SEATED, [receipt["message"], report and report["connection"]])
send("brokkr_kitbash.roll", object_name="Strut", roll=160.0)
d = pointing(-170.0)
receipt, report = send("brokkr_kitbash.aim", object_name="Strut", axis="+z", direction_x=float(d[0]), direction_y=float(d[1]), direction_z=float(d[2]))
aimed = (report or {}).get("aimed") or {"roll": 1e9, "dot": 1e9}
check("aim solving -170 inside limits 150..210 writes 190", receipt["status"] == "accepted" and reading("limit roll", abs(aimed["roll"] - 190.0)) < ROLL and abs(strut["kit_roll"] - 190.0) < ROLL
and reading("aimed", abs(aimed["dot"] - 1.0)) < AIMED and holds(report["connection"], "Mount", "end_a", "pivot", aimed["roll"]), [receipt["message"], aimed, strut["kit_roll"]])
for free, end in ((100.0, 150.0), (-110.0, 210.0), (127.0, 150.0)):
d = pointing(free)
receipt, report = send("brokkr_kitbash.aim", object_name="Strut", axis="+z", direction_x=float(d[0]), direction_y=float(d[1]), direction_z=float(d[2]))
aimed = (report or {}).get("aimed") or {"roll": 1e9, "dot": 1e9}
read = float(np.array(strut.matrix_world, dtype=np.float64)[:3, :3] @ z @ d)
grid = max(float(pointing(float(r)) @ d) for r in np.arange(150.0, 210.25, 0.25))
check(f"aim at where roll {free:g} points, outside the limits, takes the end that points nearer ({end:g}): no roll inside the limits passes it",
receipt["status"] == "accepted" and aimed["roll"] == end and strut["kit_roll"] == end and reading("aimed", abs(aimed["dot"] - read)) < AIMED
and reading("aimed short", max(grid - read, 0.0)) < AIMED and reading("aimed", abs(read - math.cos(math.radians(free - end)))) < AIMED, [receipt["message"], aimed, read, grid])
A, B, C = core.roll_terms(world, socket(mount, "pivot"), socket(strut, "end_a"), socket(strut, "end_b")["matrix"][:3, 3], 1.0, z)
middle, swing = math.degrees(math.atan2(B, A)), math.hypot(A, B)
near, far, height = middle - 40.0, middle + 40.0, C + math.cos(math.radians(40.0)) * swing # the two rolls that reach this height
send("brokkr_kitbash.joint", object_name="Strut", record='{"limits": null}')
send("brokkr_kitbash.roll", object_name="Strut", roll=round(near + 5.0, 3))
send("brokkr_kitbash.joint", object_name="Strut", record=json.dumps({"limits": [round(near + 2.0, 3), round(far + 10.0, 3)]}))
receipt, report = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=height)
reached = (report or {}).get("reached") or {"roll": 1e9, "residual": 1e9}
check("reach inside limits that hold only the farther of its two rolls takes that one", receipt["status"] == "accepted" and reading("limit roll", abs(reached["roll"] - far)) < ROLL
and reading("reached", abs(float(frame(strut, "end_b")[:3, 3] @ z) - height)) < REACHED and report["connection"]["within"] is True, [receipt["message"], reached, near, far])
send("brokkr_kitbash.roll", object_name="Strut", roll=round(near + 5.0, 3))
send("brokkr_kitbash.joint", object_name="Strut", record=json.dumps({"limits": [round(near + 2.0, 3), round(far - 2.0, 3)]}))
refused("reach with neither roll inside the limits, naming both and the limits", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_b", "height": height},
f"are outside the joint's limits {round(near + 2.0, 3):.6g} to {round(far - 2.0, 3):.6g}")
rod["kit_slide"] = 0.5 # by hand, past the limits: every report says so and the next pose is refused
found = connection("Rod")
check("a slide written by hand outside the limits reads within false and does not hold", found == {**found, "slide": 0.5, "within": False, "holds": False}, found)
refused("and a roll of it is refused by the limits", "brokkr_kitbash.roll", {"object_name": "Rod", "roll": 0.0}, "its slide 0.5 is outside the joint's limits 0 to 0.3")
rod["kit_slide"] = 0.12
check("put back, it holds", connection("Rod") == {**connection("Rod"), "slide": 0.12, "within": True, "holds": True}, connection("Rod"))
# --- the joints report --------------------------------------------------------------------------------------------------
send("brokkr_kitbash.joint", object_name="Hinge", record='{"limits": [-90, 20], "mechanism": "ankle"}')
receipt, joints = send("brokkr_kitbash.joints", object_name="Tank")
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}
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,
{name: row["parent"] for name, row in table.items()})
check("each row names its part, its parent socket and its kind", {name: (row["part"], row["socket"], row["kind"]) for name, row in table.items()} == {
"Strut": ("strut", "Mount:pivot", "revolute"), "Barrel": ("ram_barrel", "Strut:end_b_back", "revolute"), "Rod": ("ram_rod", "Barrel:bore", "prismatic"),
"Hinge": ("bracket", "Strut:end_a_back", "revolute"), "Toe": ("strut", "Foot:pivot", "revolute"), "Ram": ("actuator", "Strut:end_b", "revolute")}, table)
inverse = np.linalg.inv(np.array(tank.matrix_world, dtype=np.float64))
for name, row in table.items():
owner, _, parent_socket = row["socket"].partition(":")
at = inverse @ frame(bpy.data.objects[owner], parent_socket)
reading("joint frame", max(float(np.abs(at[:3, 2] - row["axis"]).max()), float(np.abs(at[:3, 3] - row["origin"]).max())))
check("axis and origin are the parent socket's z and origin in the root's frame, read from the scene", len(table) == 6 and R["readings"]["joint frame"] < JOINT_FRAME, R["readings"])
value = strut["kit_roll"]
check("value is the roll or slide now, limits are as stated, and min and max are the limits less the value: the travel either way",
table["Rod"] == {**table["Rod"], "value": 0.12, "limits": [0.0, 0.3], "min": -0.12, "max": 0.18, "mechanism": "shock", "compliance": spring}
and table["Hinge"] == {**table["Hinge"], "value": -15.0, "limits": [-90.0, 20.0], "min": -75.0, "max": 35.0, "mechanism": "ankle", "compliance": None}
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)
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 -------------------------------------------------------------------------------------------
receipt, report = send("brokkr_kitbash.detach", object_name="Rod")
check("detach leaves none of the eight connection keys", receipt["status"] == "accepted" and report["connection"] is None and rod.parent is None
and sorted(k for k in rod.keys() if k.startswith("kit_")) == ["kit_kit", "kit_params", "kit_part"], [receipt["message"], sorted(rod.keys())])
receipt, report = send("brokkr_kitbash.attach", object_name="Rod", socket="piston", parent_name="Barrel", parent_socket="bore")
check("and attached again it states no record", receipt["status"] == "accepted" and report["connection"] == {**report["connection"], "slide": 0.0, "limits": None, "mechanism": None, "compliance": None},
[receipt["message"], report and report["connection"]])
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()[-6:])

View file

@ -230,6 +230,251 @@
"name": "refused, scene unchanged: an axis that is not one of the six, by the action table",
"ok": true,
"detail": null
},
{
"name": "joint, slide and joints load as host actions after reach",
"ok": true,
"detail": null
},
{
"name": "a rod attaches in its barrel's bore: a prismatic connection at slide 0 with no joint record, and no record key written",
"ok": true,
"detail": null
},
{
"name": "joint states a slide's limits, mechanism and compliance, and moves nothing",
"ok": true,
"detail": null
},
{
"name": "a key left out keeps what is stated and null clears it",
"ok": true,
"detail": null
},
{
"name": "slide 0.12 moves the rod along the bore's z where it hangs: its parent, sockets, roll and record as they were, the slide stated and seated",
"ok": true,
"detail": null
},
{
"name": "slide 0.3 moves the rod along the bore's z where it hangs: its parent, sockets, roll and record as they were, the slide stated and seated",
"ok": true,
"detail": null
},
{
"name": "slide 0 moves the rod along the bore's z where it hangs: its parent, sockets, roll and record as they were, the slide stated and seated",
"ok": true,
"detail": null
},
{
"name": "slide 0.12 moves the rod along the bore's z where it hangs: its parent, sockets, roll and record as they were, the slide stated and seated",
"ok": true,
"detail": null
},
{
"name": "a roll on a prismatic connection is a build angle: it turns the rod in the bore and the slide stays",
"ok": true,
"detail": null
},
{
"name": "set_params of the barrel moves its bore and reseats the rod at its slide",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a slide past the joint's limits, naming value and limits",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a slide under them",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a slide of a pin, naming its type",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a slide of a rigid connection, naming its type",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a joint record on a rigid connection, naming its type",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: limits that exclude the slide the joint has",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: prismatic limits past 10 m",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: limits cleared under a compliance",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a compliance out of range",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a compliance on a pin",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: revolute limits spanning over a turn",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a revolute limit past 360",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a record that is not the shape",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a record with a key it does not have",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a mechanism that is no label",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a record that is not JSON",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a joint record on a part nobody attached",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: limits that exclude the roll the joint has",
"ok": true,
"detail": null
},
{
"name": "joint states a pin's limits about the roll it has",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a roll with no turn of itself inside the limits, naming value and limits",
"ok": true,
"detail": null
},
{
"name": "a roll a turn away from the limits is written as its representative inside them: -170 as 190",
"ok": true,
"detail": null
},
{
"name": "aim solving -170 inside limits 150..210 writes 190",
"ok": true,
"detail": null
},
{
"name": "aim at where roll 100 points, outside the limits, takes the end that points nearer (150): no roll inside the limits passes it",
"ok": true,
"detail": null
},
{
"name": "aim at where roll -110 points, outside the limits, takes the end that points nearer (210): no roll inside the limits passes it",
"ok": true,
"detail": null
},
{
"name": "aim at where roll 127 points, outside the limits, takes the end that points nearer (150): no roll inside the limits passes it",
"ok": true,
"detail": null
},
{
"name": "reach inside limits that hold only the farther of its two rolls takes that one",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: reach with neither roll inside the limits, naming both and the limits",
"ok": true,
"detail": null
},
{
"name": "a slide written by hand outside the limits reads within false and does not hold",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: and a roll of it is refused by the limits",
"ok": true,
"detail": null
},
{
"name": "put back, it holds",
"ok": true,
"detail": null
},
{
"name": "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",
"ok": true,
"detail": null
},
{
"name": "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",
"ok": true,
"detail": null
},
{
"name": "each row names its part, its parent socket and its kind",
"ok": true,
"detail": null
},
{
"name": "axis and origin are the parent socket's z and origin in the root's frame, read from the scene",
"ok": true,
"detail": null
},
{
"name": "value is the roll or slide now, limits are as stated, and min and max are the limits less the value: the travel either way",
"ok": true,
"detail": null
},
{
"name": "under another root the rows are in its frame and begin below it",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: joints of a mesh that is not a kit part",
"ok": true,
"detail": null
},
{
"name": "detach leaves none of the eight connection keys",
"ok": true,
"detail": null
},
{
"name": "and attached again it states no record",
"ok": true,
"detail": null
}
],
"hostErrors": [],
@ -238,11 +483,173 @@
"aimed short": 0.0,
"edge reached": 2.6e-08,
"edge typed past": 3.2e-07,
"joint frame": 4e-07,
"limit roll": 2e-05,
"reach other root": 74.0,
"reached": 2.1e-07,
"reached": 2.4e-07,
"roll": 8.4e-06,
"seated": 1.1e-06,
"slid": 1.4e-07,
"turned": 0.55
},
"joints": {
"schema": "brokkr.joints",
"version": 1,
"root": "Tank",
"frame": "the root object's: Blender axes (+Z up), metres",
"rigid": 2,
"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
},
{
"id": "Barrel",
"parent": "Strut",
"part": "ram_barrel",
"socket": "Strut:end_b_back",
"kind": "revolute",
"axis": [
-0.0,
1.0,
0.0
],
"origin": [
0.154833,
0.085,
1.515425
],
"value": 25.0,
"limits": null,
"min": null,
"max": null,
"mechanism": null,
"compliance": null
},
{
"id": "Rod",
"parent": "Barrel",
"part": "ram_rod",
"socket": "Barrel:bore",
"kind": "prismatic",
"axis": [
0.034551,
-0.0,
0.999403
],
"origin": [
0.157321,
0.124,
1.587382
],
"value": 0.12,
"limits": [
0.0,
0.3
],
"min": -0.12,
"max": 0.18,
"mechanism": "shock",
"compliance": {
"damping_ratio": 0.7,
"hertz": 4.0
}
},
{
"id": "Hinge",
"parent": "Strut",
"part": "bracket",
"socket": "Strut:end_a_back",
"kind": "revolute",
"axis": [
-0.0,
1.0,
0.0
],
"origin": [
0.436,
0.085,
0.85368
],
"value": -15.0,
"limits": [
-90.0,
20.0
],
"min": -75.0,
"max": 35.0,
"mechanism": "ankle",
"compliance": null
},
{
"id": "Toe",
"parent": "Hinge",
"part": "strut",
"socket": "Foot:pivot",
"kind": "revolute",
"axis": [
0.787796,
0.0,
0.615936
],
"origin": [
0.559187,
0.085,
0.696121
],
"value": 40.0,
"limits": null,
"min": null,
"max": null,
"mechanism": null,
"compliance": null
},
{
"id": "Ram",
"parent": "Strut",
"part": "actuator",
"socket": "Strut:end_b",
"kind": "revolute",
"axis": [
0.0,
-1.0,
-0.0
],
"origin": [
0.154833,
-0.0,
1.515425
],
"value": -36.0,
"limits": null,
"min": null,
"max": null,
"mechanism": null,
"compliance": null
}
]
},
"ok": true
}

View file

@ -259,7 +259,7 @@ try:
check("the evaluated cage stays a closed wall and loses volume with each cut", all(falls) and len(falls) == 4, R["cage"])
receipt, report = send("brokkr_kitbash.report", object_name="")
check("report lists the cutters as kit parts and not the cage", report and [p["object"] for p in report["parts"]] == sorted(c[0] for c in CUTS)
and all(p["connection"] is None and p["baked"] is False for p in report["parts"]), report and [p["object"] for p in report["parts"]])
and all(p["connection"] is None for p in report["parts"]), report and [p["object"] for p in report["parts"]])
# --- cut-casts-the-uncut-surface --------------------------------------------------------------------------------------------
section('cut-casts-the-uncut-surface')
@ -398,22 +398,56 @@ try:
receipt["status"] == "accepted" and stack(plate) == ["Kit Difference", "Kit Union", "Kit Intersect", "Kit Bevel"]
and report["booleans"] == [{"cutter": "Hole", "operation": "DIFFERENCE"}, {"cutter": "Boss", "operation": "UNION"}, {"cutter": "Keep", "operation": "INTERSECT"}]
and report["evaluated"]["nonManifoldEdges"] == 0 and report["kit"] == "mechanical", [stack(plate), report and report["booleans"]])
collections = len(bpy.data.collections)
receipt, baked = send("brokkr_kitbash.apply", object_name="Plate")
check("apply removes the three collections its modifiers held and leaves every cutter in the scene", receipt["status"] == "accepted"
and baked["cutters"] == ["Hole", "Boss", "Keep"] and len(bpy.data.collections) == collections - 3 and len(plate.modifiers) == 0
and all(name in bpy.context.scene.objects for name in ("Hole", "Boss", "Keep")), [receipt["message"], [c.name for c in bpy.data.collections]])
refused("apply on the cage, which is not a kit part", "brokkr_kitbash.apply", {"object_name": "Cage"}, "'Cage' is not a kit part")
THAW = "thaw it first"
shown, cage_shown, collections = evaluated(plate)[0], evaluated(cage)[0], len(bpy.data.collections)
receipt, frozen = send("brokkr_kitbash.freeze", object_name="Plate")
check("freeze keeps the three modifiers, off, the three collections they read and every cutter in the scene", receipt["status"] == "accepted"
and frozen["booleans"] == report["booleans"] and len(bpy.data.collections) == collections and frozen["modifiers"] == stack(plate) == ["Kit Difference", "Kit Union", "Kit Intersect", "Kit Bevel"]
and not any(m.show_viewport or m.show_render for m in plate.modifiers) and frozen["evaluated"] == shown == evaluated(plate)[0]
and all(name in bpy.context.scene.objects for name in ("Hole", "Boss", "Keep")), [receipt["message"], frozen, shown])
cage_stack, cage_mesh = stack(cage), cage.data.name
receipt, frozen = send("brokkr_kitbash.freeze", object_name="Cage")
check("freeze takes the cage, which is not a kit part: its evaluated wall, its stack off, its cutters still its children", receipt["status"] == "accepted" and frozen["object"] == "Cage"
and "kit" not in frozen and frozen["frozen"] is True and frozen["evaluated"] == cage_shown == evaluated(cage)[0]
and frozen["modifiers"] == stack(cage) == cage_stack and not any(m.show_viewport or m.show_render for m in cage.modifiers) and cage.data.name == "Cage frozen"
and bpy.data.objects["Bay"].parent == cage and len(bpy.data.collections) == collections, [receipt["message"], frozen and frozen["modifiers"], cage_shown])
refused("ribs from a frozen cage", "brokkr_kitbash.ribs", {"object_name": "Cage", "ribs_name": "ColdRibs", "planes": json.dumps([{"origin": [0.0, 0.0, 0.5], "normal": [0.0, 0.0, 1.0]}])}, THAW)
refused("cut on a frozen cage", "brokkr_kitbash.cut", {"object_name": "Cage", "cutter_name": "Late", "part": "box", "origin_x": 3.0, "origin_y": 0.0, "origin_z": 0.1,
"direction_x": -1.0, "direction_y": 0.0, "direction_z": 0.0}, THAW)
refused("cut_many on a frozen cage", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{"name": "Late", "part": "box", "origin": [3.0, 0.0, 0.1], "direction": [-1.0, 0.0, 0.0]}])}, THAW)
refused("boolean on a frozen cage", "brokkr_kitbash.boolean", {"object_name": "Cage", "cutter": "Hole"}, THAW)
for name in ("Plate", "Cage"):
receipt, thawed = send("brokkr_kitbash.thaw", object_name=name)
check("thaw gives both back: the live meshes, every modifier on, the frozen meshes gone, and the same evaluated shapes", receipt["status"] == "accepted"
and thawed == {"object": "Cage", "frozen": False, "modifiers": cage_stack, "faces": len(cage.data.polygons)} and cage.data.name == cage_mesh
and all(m.show_viewport and m.show_render for o in (plate, cage) for m in o.modifiers) and not any(n in bpy.data.meshes for n in ("Cage frozen", "Plate frozen"))
and "kit_frozen" not in cage and "kit_frozen" not in plate and evaluated(plate)[0] == shown and evaluated(cage)[0] == cage_shown,
[receipt["message"], thawed, sorted(m.name for m in bpy.data.meshes)])
twin = place("Twin", "plate", location=[0.0, -15.0, 0.0])
send("createObject", objectType="MESH", name="TwinHole", location=[0.0, -15.0, 0.0], size=0.05)
send("brokkr_kitbash.boolean", object_name="Twin", cutter="TwinHole")
copied = twin.copy() # a copied part: its own mesh, and a Kit Difference modifier that reads the same collection
copied.data = twin.data.copy()
bpy.context.scene.collection.objects.link(copied)
receipt, baked = send("brokkr_kitbash.apply", object_name="Twin")
receipt, frozen = send("brokkr_kitbash.freeze", object_name="Twin")
kept = bpy.data.collections.get("Twin difference")
check("M6: apply keeps a collection a copied part's modifier still reads", receipt["status"] == "accepted" and len(twin.modifiers) == 0 and kept is not None
and copied.modifiers["Kit Difference"].collection == kept and [o.name for o in kept.objects] == ["TwinHole"], [receipt["message"], [c.name for c in bpy.data.collections]])
check("M6: a frozen part and its copy still read the one collection, and the copy stays live", receipt["status"] == "accepted" and kept is not None
and twin.modifiers["Kit Difference"].collection == kept == copied.modifiers["Kit Difference"].collection and [o.name for o in kept.objects] == ["TwinHole"]
and "kit_frozen" in twin and all(m.show_viewport for m in copied.modifiers), [receipt["message"], [c.name for c in bpy.data.collections]])
send("brokkr_kitbash.thaw", object_name="Twin")
RINGS = [[[x, y, 0.1 - x * x] for x in (-0.3, -0.1, 0.1, 0.3)] for y in (0.0, 0.2, 0.4)]
lid = {"object_name": "Lid", "sheet": json.dumps({"rings": RINGS}), "thickness": 0.02, "levels": 2}
send("brokkr_kitbash.shell", **lid)
send("setObjectTransform", targetObjectName="Lid", location=[0.0, -30.0, 0.0])
wall = evaluated(bpy.data.objects["Lid"])[0]
receipt, frozen = send("brokkr_kitbash.freeze", object_name="Lid")
check("freeze takes a shell: the wall its Kit Subsurf and Kit Solidify make", receipt["status"] == "accepted" and frozen["modifiers"] == ["Kit Subsurf", "Kit Solidify"]
and frozen["evaluated"] == wall and wall["faces"] > 2 * 6 * 16, [receipt["message"], frozen, wall])
refused("a rebuild of a frozen shell", "brokkr_kitbash.shell", lid, THAW)
refused("a rebuild of a frozen shell that counts folds", "brokkr_kitbash.shell", {**lid, "count_folds": True}, THAW)
send("brokkr_kitbash.thaw", object_name="Lid")
receipt, rebuilt = send("brokkr_kitbash.shell", **lid)
check("and thawed, the shell rebuilds", receipt["status"] == "accepted" and rebuilt["rebuilt"] is True and evaluated(bpy.data.objects["Lid"])[0] == wall, [receipt["message"], rebuilt])
# --- cut-refusals -----------------------------------------------------------------------------------------------------------
section('cut-refusals')
@ -471,8 +505,8 @@ try:
refused(f"cut_many on a target {why}", "brokkr_kitbash.cut_many",
{"object_name": name, "cuts": json.dumps([{"name": "Unseen", "part": "box", "origin": [0.1, 0.1, 3.0], "direction": [0.0, 0.0, -1.0], "up": [0.0, 1.0, 0.0]}])}, NOT)
refused(f"boolean on a target {why}", "brokkr_kitbash.boolean", {"object_name": name, "cutter": "Sheet"}, NOT)
refused("apply on a part disabled in viewports", "brokkr_kitbash.apply", {"object_name": "Plate"}, "Blender does not evaluate 'Plate' in this view layer")
refused("apply on a part in a collection outside the view layer", "brokkr_kitbash.apply", {"object_name": "Loose"}, "Blender does not evaluate 'Loose' in this view layer")
refused("freeze on a part disabled in viewports", "brokkr_kitbash.freeze", {"object_name": "Plate"}, "Blender does not evaluate 'Plate' in this view layer")
refused("freeze on a part in a collection outside the view layer", "brokkr_kitbash.freeze", {"object_name": "Loose"}, "Blender does not evaluate 'Loose' in this view layer")
veil.hide_viewport = plate.hide_viewport = False
bpy.context.view_layer.update()

View file

@ -222,17 +222,62 @@
"detail": null
},
{
"name": "apply removes the three collections its modifiers held and leaves every cutter in the scene",
"name": "freeze keeps the three modifiers, off, the three collections they read and every cutter in the scene",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: apply on the cage, which is not a kit part",
"name": "freeze takes the cage, which is not a kit part: its evaluated wall, its stack off, its cutters still its children",
"ok": true,
"detail": null
},
{
"name": "M6: apply keeps a collection a copied part's modifier still reads",
"name": "refused, scene unchanged: ribs from a frozen cage",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: cut on a frozen cage",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: cut_many on a frozen cage",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: boolean on a frozen cage",
"ok": true,
"detail": null
},
{
"name": "thaw gives both back: the live meshes, every modifier on, the frozen meshes gone, and the same evaluated shapes",
"ok": true,
"detail": null
},
{
"name": "M6: a frozen part and its copy still read the one collection, and the copy stays live",
"ok": true,
"detail": null
},
{
"name": "freeze takes a shell: the wall its Kit Subsurf and Kit Solidify make",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a rebuild of a frozen shell",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a rebuild of a frozen shell that counts folds",
"ok": true,
"detail": null
},
{
"name": "and thawed, the shell rebuilds",
"ok": true,
"detail": null
},
@ -327,12 +372,12 @@
"detail": null
},
{
"name": "refused, scene unchanged: apply on a part disabled in viewports",
"name": "refused, scene unchanged: freeze on a part disabled in viewports",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: apply on a part in a collection outside the view layer",
"name": "refused, scene unchanged: freeze on a part in a collection outside the view layer",
"ok": true,
"detail": null
},

View file

@ -0,0 +1,435 @@
"""Live proof, in a background Blender, of brokkr_kitbash/ram.py's clearance gate on meshes: the R-3 knee (thigh,
shin, the bracket and horn, a bell crank's or a four-bar's plates, pins and clevises), every piece a closed mesh this
file generates, each a named part of a body, and the gate answered by the package's signed BVH oracle (ram.Signed)
over them. Not part of the unittest run: it needs Blender (mathutils' BVHTree).
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/ram_knee.py -- <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 <out>.r3_<angle>.png (the bell crank at 0,
-62.5 and -125) and exits 1 when a check failed.
The oracle is ram.Signed, three rays by majority. Its ray count is held by tests/fixtures/ram_rays.json: the rocker
plates as Imagination's jointlib builds them and points between the plates that stand on the first ray short of an
edge or a vertex. One ray reads them inside a plate they stand clear of; the oracle as it is made reads none inside.
A clearance verdict is a sign, the gate's own. FLAT follows lodur:ruling:deterministic-bound-margin. The checks run
inside one try: an uncaught error is a failed check that names its section, and the result file is always written.
"""
import importlib.util
import json
import math
import os
import sys
import time
import traceback
from dataclasses import replace
from pathlib import Path
import bmesh
import bpy
import numpy as np
from mathutils import Matrix, Vector
SURFACE = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(SURFACE / "tools"))
import private_dirs # noqa: E402
_refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind))
if _refused:
raise SystemExit(_refused)
OUT = sys.argv[sys.argv.index("--") + 1]
if not Path(OUT).is_absolute():
raise SystemExit(f"{OUT!r} is not an absolute path")
spec = importlib.util.spec_from_file_location("brokkr_kitbash_ram", SURFACE / "brokkr_kitbash" / "ram.py")
R = importlib.util.module_from_spec(spec) # ram.py as the unit tests load it
sys.modules[spec.name] = R
spec.loader.exec_module(R)
Signed = R.Signed
RES = {"blender": bpy.app.version_string, "checks": [], "readings": {}}
SECTION = ["setup"]
# Metres between the oracle's reading and 0.0225, on a grid a plate's thickness off a rocker plate's face. Shipped
# worst 1.3e-08 (float32 faces); least claimed mutant 0.045 (a sample signed inside reads -0.0225); the geometric mean.
FLAT = 2.4e-5
BORE, PIN, AXLE = 0.042, 0.026, 0.028
SLAB_C, SLAB_R = (0.31, 0.345), (0.35, 0.385) # the twin link plates along the axis: the coupler's inside the rocker's
X_C, X_R = 0.5 * sum(SLAB_C), 0.5 * sum(SLAB_R)
HALF = 0.5 * (SLAB_R[1] - SLAB_R[0]) # half a plate's thickness
W_ROCKER, W_COUPLER, W_ARM, W_HORN, W_BRACKET, COLLAR = 0.045, 0.04, 0.04, 0.05, 0.055, 0.05
CHEEK = (0.03, 0.05) # a clevis's cheeks, either side of the ram's eye
SLACK = 0.001 # a zone's depth over the burial it lets: a float32 face reads a burial to 1e-8
# P2's seats, (y, z): the deep four-bar behind the knee and the bell crank in front of it
DEEP = {"a": (-0.45, 1.15), "rocker": (-0.2320142211320173, 0.4604939911625098), "p": (-0.43650046730511183, -0.017951928782268284),
"c": (0.06881023105761902, -0.3143743967236484), "d": (-0.43650046730511183, -0.017951928782268284)}
CRANK = {"a": (0.45, 1.15), "rocker": (0.3171126791600819, 0.3216537818398838), "p": (0.7282866960904424, 0.43261578669776135),
"c": (0.34929485118682846, 0.14862538079826304), "d": (0.48651463351122515, 0.49166254003196397)}
ROOTS = {"bell_crank": {"horn": (0.10, -0.40), "bracket": (0.10, 0.55)}, "four_bar": {"horn": (0.0, -0.42), "bracket": (-0.10, 0.55)}}
THIGH_FRONT, EMBED = 0.14, 0.01 # the thigh core's faces stand at y +-0.14; a foot runs this far into it
def check(name, ok, detail=None):
RES["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail})
def prism(outline, x0, x1):
"""A closed shell: the convex (y, z) outline, counter-clockwise seen from +x, run from x0 to x1."""
x0, x1 = min(x0, x1), max(x0, x1)
n = len(outline)
verts = [(x, y, z) for x in (x0, x1) for y, z in outline]
faces = [tuple(range(n - 1, -1, -1)), tuple(range(n, 2 * n))] + [(k, (k + 1) % n, n + (k + 1) % n, n + k) for k in range(n)]
return np.array(verts, dtype=float), faces
def box(centre, size):
(cx, cy, cz), (sx, sy, sz) = centre, size
return prism([(cy - sy / 2, cz - sz / 2), (cy + sy / 2, cz - sz / 2), (cy + sy / 2, cz + sz / 2), (cy - sy / 2, cz + sz / 2)], cx - sx / 2, cx + sx / 2)
def disc(at, r, x0, x1, n=32):
return prism([(at[0] + r * math.cos(2 * math.pi * k / n), at[1] + r * math.sin(2 * math.pi * k / n)) for k in range(n)], x0, x1)
def bar(p, q, w, x0, x1, n=10):
"""A link plate: the stadium of half width w about the segment p -> q."""
p, q = np.array(p, float), np.array(q, float)
base = math.atan2(*((q - p) / np.linalg.norm(q - p))[::-1])
pts = [(c[0] + w * math.cos(a0 + math.pi * k / n), c[1] + w * math.sin(a0 + math.pi * k / n)) for c, a0 in ((q, base - math.pi / 2), (p, base + math.pi / 2)) for k in range(n + 1)]
return prism(pts, x0, x1)
def knee(kind, pn, links=True):
"""part -> [shell], part -> body: the knee at rest (angle 0, every frame the parent's)."""
shells, front = {}, kind == "bell_crank"
def add(part, *made):
shells.setdefault(part, []).extend(made)
r, gap, cheek = 0.25, 0.22, 0.07
half = gap / 2 + cheek
add("parent.body", box((0, 0, 0.725), (0.26, 2 * THIGH_FRONT, 0.85)), box((0, 0.185, 0.725), (0.34, 0.06, 0.77)), box((0, 0, 0.2), (gap - 0.03, 0.24, 0.4)),
disc((0, 0), 0.9 * r, -(gap - 0.03) / 2, (gap - 0.03) / 2))
outline = [(r * math.cos(math.radians(a)), r * math.sin(math.radians(a))) for a in range(0, 181, 15)] + [(-0.12, -0.95), (0.12, -0.95)]
add("child.body", box((0, 0, -0.72), (gap, 0.22, 0.46)), box((0, 0.15, -0.62), (2 * half + 0.06, 0.06, 0.58)))
Rk, P, C, A, D = (pn[k] for k in ("rocker", "p", "c", "a", "d"))
for s in (-1, 1):
add("child.body", prism(outline, s * gap / 2, s * half), disc((0, 0), 0.19, s * half, s * (half + 0.025)), box((s * (half + 0.03), 0.0, -0.62), (0.045, 0.2, 0.5)))
add("child.horn", bar(ROOTS[kind]["horn"], C, W_HORN, s * (half + 0.05), s * SLAB_C[0]))
add("parent.bracket", bar(ROOTS[kind]["bracket"], Rk, W_BRACKET, s * 0.13, s * SLAB_R[0]))
# the base clevis: cheeks about the pin and a foot that runs into the thigh's core, toward it
toward = -1.0 if front else 1.0
foot = (A[0] + toward * 0.2, A[1])
add("parent.seat", bar(A, foot, 1.7 * BORE, s * CHEEK[0], s * CHEEK[1]))
if links:
add("rocker.plate", bar(Rk, P, W_ROCKER, s * SLAB_R[0], s * SLAB_R[1]))
add("coupler.plate", bar(P, C, W_COUPLER, s * SLAB_C[0], s * SLAB_C[1]))
add("rocker.seat", disc(D, COLLAR, s * CHEEK[0], s * CHEEK[1])) # the eye's collars on its pin
if front:
add("rocker.plate", bar(Rk, D, W_ARM, s * SLAB_R[0], s * SLAB_R[1]))
face = toward * (THIGH_FRONT - EMBED)
add("parent.seat", box((0, 0.5 * (face + foot[0]), A[1]), (2 * CHEEK[1], abs(foot[0] - face), 3.4 * BORE)))
if links:
add("rocker.pin.R", disc(Rk, AXLE, -SLAB_R[1] - 0.015, SLAB_R[1] + 0.015))
add("rocker.pin.p", disc(P, PIN, -SLAB_R[1] - 0.015, SLAB_R[1] + 0.015))
add("coupler.pin.c", disc(C, PIN, -SLAB_C[1] - 0.015, SLAB_C[1] + 0.015))
if front:
add("rocker.pin.d", disc(D, PIN, -SLAB_R[1] - 0.015, SLAB_R[1] + 0.015))
return shells, {part: {"parent": "parent", "child": "child", "rocker": "rocker", "coupler": "coupler"}[part.split(".")[0]] for part in shells}
def near(ram, member):
return {"barrel": ram.barrel_r, "rod": ram.rod}.get(member, ram.link_r) + ram.gap + ram.spacing() / 2
def parting(ram, w, degrees):
"""How far from a pin a link parts from a plate of half width w that stands beside it on the pin, a plate's
thickness off along the axis, the two crossing at `degrees` at the least: where the link's axis is what a link
keeps from the plate's edge, and never less than the plate's round end."""
lateral = math.sqrt(near(ram, "rocker") ** 2 - HALF ** 2)
return max((w + lateral) / math.sin(math.radians(min(degrees, 90.0))), w + near(ram, "rocker"))
def crossing(m, kind):
"""The least angle, over the range, at which the rocker, the rocker arm and the coupler cross what stands beside
them: the bracket's bar at the pivot, the horn's at c (seen from the shin), each other at p."""
p, n = R.pose(m, np.linspace(m.lo, m.hi, 126)), m.axis
def least(a, b):
a, b = R._flat(a, n), R._flat(np.broadcast_to(b, a.shape), n)
return float(np.degrees(np.arccos(np.clip((a * b).sum(axis=1) / (np.linalg.norm(a, axis=1) * np.linalg.norm(b, axis=1)), -1.0, 1.0))).min())
root = {key: np.array((0.0, *value)) for key, value in ROOTS[kind].items()}
seen = R._into(m, p, "child", p.P[:, None, :])[:, 0, :]
return {"rocker": least(p.P - m.rocker, root["bracket"] - m.rocker), "rocker arm": least(p.eye - m.rocker, root["bracket"] - m.rocker),
"coupler": least(seen - m.c, root["horn"] - m.c), "p": float(p.mu_p.min())}
def zones(m, ram, parts):
"""Each member's zones. About a pin: the pin's, collar's or cheek's radius plus what the member keeps, as deep as
the pin where it runs through the member's eye and 0 beside a collar, a cheek, the bracket or the horn; a link's
own plate about both its pins, each a little over half its length (a zone is no wider than its member), half
the plate's thickness deep; a plate beside a link as far as the two part. A depth that is not 0 is stated SLACK
over the burial."""
kind, link, at = m.kind, near(ram, "rocker"), crossing(m, m.kind)
PIN, AXLE, HALF = (value + SLACK for value in (globals()["PIN"], globals()["AXLE"], globals()["HALF"]))
reach = {"pin": globals()["PIN"] + link, "axle": globals()["AXLE"] + link}
eye = "rocker.pin.d" if kind == "bell_crank" else "rocker.pin.p"
def own(part, a, b, span):
return [(part, a, 0.51 * span, HALF), (part, b, 0.51 * span, HALF)]
def parts_at(member, w, degrees): # never wider than the member: two that cross at a few degrees part beyond its length
return min(parting(ram, w, degrees), R._span(m, member))
touch = {member: [("parent.seat", "a", 1.7 * BORE + near(ram, member), 0.0), ("rocker.seat", "d", COLLAR + near(ram, member), 0.0),
(eye, "d", globals()["PIN"] + near(ram, member), PIN if member == "rod" else 0.0)] for member in ("barrel", "rod")}
pivot = [("parent.bracket", "rocker", None, 0.0), ("rocker.pin.R", "rocker", reach["axle"], AXLE)]
touch["rocker"] = pivot + [("rocker.pin.p", "p", reach["pin"], PIN), *own("rocker.plate", "rocker", "p", m.lr), ("coupler.plate", "p", parts_at("rocker", W_COUPLER, at["p"]), 0.0)]
touch["coupler"] = [("child.horn", "c", parts_at("coupler", W_HORN, at["coupler"]), 0.0), ("coupler.pin.c", "c", reach["pin"], PIN), ("rocker.pin.p", "p", reach["pin"], PIN),
*own("coupler.plate", "p", "c", m.lc), ("rocker.plate", "p", parts_at("coupler", W_ROCKER, at["p"]), 0.0)]
if kind == "bell_crank":
touch["rocker arm"] = pivot + [("rocker.pin.d", "d", reach["pin"], PIN), *own("rocker.plate", "rocker", "d", R._span(m, "rocker arm"))]
for member in ("rocker", "rocker arm"):
if member in touch:
touch[member][0] = ("parent.bracket", "rocker", parts_at(member, W_BRACKET, at[member]), 0.0)
return {member: [zone for zone in given if zone[0] in parts] for member, given in touch.items()}
def pins3(pn, side=1.0, **moved):
at = {"a": 0.0, "p": 0.0, "d": 0.0, "rocker": side * X_R, "c": side * X_C, **moved}
return {k: (at[k], float(pn[k][0]), float(pn[k][1])) for k in pn}
def needs(m, ram, parts, distance, steps=49):
"""(member, part) -> (pin, radius, depth): for every pair refused with nothing let, the least zone that lets it."""
p = R.pose(m, np.linspace(m.lo, m.hi, steps))
at = {"a": p.base, R.EYE[m.kind]: p.eye, "rocker": m.rocker, "p": p.P, "c": p.C}
step, out = ram.spacing(), {}
for member, label, start, end, radius, pins in R._members(m, ram, R.barrel_length(m, ram), p):
count = max(int(math.ceil(float(np.linalg.norm(end - start, axis=1).max()) / step)) + 1, 2)
pts = start[:, None, :] + (end - start)[:, None, :] * np.linspace(0.0, 1.0, count)[None, :, None]
for part, body in parts.items():
got = distance(part, R._into(m, p, body, pts).reshape(-1, 3)).reshape(len(p.degrees), count)
bad = got < radius + ram.gap + step / 2
if bad.any():
best = None
for pin in pins:
across = np.linalg.norm(R._flat(pts - np.broadcast_to(at[pin], start.shape)[:, None, :], m.axis), axis=2)
reach = float(across[bad].max())
if best is None or reach < best[1]:
best = (pin, reach, max(-float(got[across <= reach].min()), 0.0))
out[(label, part)] = best
return out
def refused(f):
return sorted((pair, round(reading[0], 4), reading[1]) for pair, reading in f.pairs.items() if reading[0] < 0.0)
def label(member):
return member + "[0]" if member in ("barrel", "rod") else member
def hinge4(pivot, degrees):
return Matrix.Translation(Vector(pivot)) @ Matrix.Rotation(math.radians(degrees), 4, "X") @ Matrix.Translation(-Vector(pivot))
def render(m, ram, f, shells, parts):
"""The bell crank at 0, -62.5 and -125, each piece coloured by its part, the ram as the gate holds it."""
scene = bpy.context.scene
colour = {"horn": (0.95, 0.45, 0.1, 1), "bracket": (0.15, 0.45, 0.9, 1), "plate": (0.75, 0.75, 0.78, 1), "seat": (0.55, 0.3, 0.6, 1), "pin": (0.9, 0.9, 0.3, 1)}
objects = []
for part, made in shells.items():
for k, (verts, faces) in enumerate(made):
me = bpy.data.meshes.new(f"{part}.{k}")
me.from_pydata(verts.tolist(), [], faces)
o = bpy.data.objects.new(me.name, me)
scene.collection.objects.link(o)
o.color = colour.get(part.split(".")[1], (0.33, 0.38, 0.24, 1) if parts[part] == "child" else (0.3, 0.32, 0.36, 1))
objects.append((o, parts[part]))
def tube(name, r, col):
me, bm = bpy.data.meshes.new(name), bmesh.new()
bmesh.ops.create_cone(bm, cap_ends=True, segments=24, radius1=r, radius2=r, depth=1.0)
bmesh.ops.translate(bm, verts=bm.verts[:], vec=(0, 0, 0.5))
bm.to_mesh(me)
bm.free()
o = bpy.data.objects.new(name, me)
scene.collection.objects.link(o)
o.color = col
return o
barrel, rod = tube("ram.barrel", ram.barrel_r, (0.85, 0.15, 0.12, 1)), tube("ram.rod", ram.rod, (0.95, 0.95, 0.95, 1))
scene.render.engine = "BLENDER_WORKBENCH"
scene.display.shading.light, scene.display.shading.color_type = "STUDIO", "OBJECT"
scene.display.shading.show_shadows = scene.display.shading.show_cavity = True
scene.render.resolution_x, scene.render.resolution_y, scene.render.film_transparent = 1400, 1500, False
scene.world = bpy.data.worlds.new("w")
scene.world.color = (0.82, 0.83, 0.85)
cam = bpy.data.objects.new("cam", bpy.data.cameras.new("cam"))
scene.collection.objects.link(cam)
cam.data.type, cam.data.ortho_scale = "ORTHO", 2.75
target = Vector((0.0, 0.1, 0.12))
cam.location = target + Vector((0.72, 0.62, 0.22)).normalized() * 8.0
cam.rotation_euler = (target - cam.location).to_track_quat("-Z", "Y").to_euler()
scene.camera = cam
made = []
for angle in (0.0, -62.5, -125.0):
p = R.pose(m, angle)
T = {"parent": Matrix.Identity(4), "child": hinge4((0, 0, 0), angle), "rocker": hinge4(m.rocker, math.degrees(p.phi[0])),
"coupler": Matrix.Translation(Vector(p.P[0] - m.p)) @ hinge4(m.p, math.degrees(p.psi[0]))}
for o, body in objects:
o.matrix_world = T[body]
u, base = Vector(p.u[0]), Vector(p.base[0])
frame = u.to_track_quat("Z", "Y").to_matrix().to_4x4()
barrel.matrix_world = Matrix.Translation(base + u * ram.back) @ frame @ Matrix.Diagonal((1, 1, f.barrel, 1))
rod.matrix_world = Matrix.Translation(base + u * (ram.back + f.barrel)) @ frame @ Matrix.Diagonal((1, 1, float(p.L[0]) - ram.back - f.barrel, 1))
scene.render.filepath = f"{OUT}.r3_{abs(angle):g}".replace(".5", "p5") + ".png"
bpy.ops.render.render(write_still=True)
made.append(scene.render.filepath)
return made
try:
bpy.ops.wm.read_factory_settings(use_empty=True)
ram = R.Ram(BORE)
HINGE = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), -125.0, 0.0)
SECTION[0] = "oracle"
shells, parts = knee("bell_crank", CRANK)
rows = []
for name, part, point, depth in (("the thigh core's centre", "parent.body", (0.0, 0.0, 0.7), -0.13), ("0.02 inside the thigh's wall", "parent.body", (0.11, 0.0, 0.7), -0.02),
("the shin's leg centre", "child.body", (0.0, 0.0, -0.7), -0.11), ("0.125 off the thigh's plate", "parent.body", (0.0, 0.34, 0.7), 0.125)):
capped, free = (float(Signed(shells, cap)(part, np.array([point]))[0]) for cap in (ram.reach(), None))
rows.append((name, capped, free, abs(free - depth) < FLAT and capped == (free if depth < 0 else min(free, ram.reach()))))
check("inside-is-negative: a point inside a part reads its depth, negative, capped or not; a cap changes only what is outside", all(row[3] for row in rows), rows)
# a grid a plate's thickness off the rocker plates' inner face, over the knee: every point is 0.0225 or more from the
# plates and none is inside; where the plate is under the point the reading is the 0.0225
ys, zs = np.meshgrid(np.linspace(0.1, 0.9, 96), np.linspace(0.1, 0.7, 72))
plane = np.stack([np.full(ys.size, X_C), ys.ravel(), zs.ravel()], axis=1)
three, one = Signed(shells)("rocker.plate", plane), Signed(shells, rays=1)("rocker.plate", plane)
def off(a, b): # each grid point's distance from the segment a -> b, across the axis
a, b = np.array(a), np.array(b)
t = np.clip(((plane[:, 1:] - a) @ (b - a)) / ((b - a) @ (b - a)), 0.0, 1.0)
return np.linalg.norm(plane[:, 1:] - a - t[:, None] * (b - a), axis=1)
under = (off(CRANK["rocker"], CRANK["p"]) < W_ROCKER - 0.005) | (off(CRANK["rocker"], CRANK["d"]) < W_ARM - 0.005)
RES["readings"]["FLAT"] = float(np.abs(three[under] - (SLAB_R[0] - X_C)).max())
RES["readings"]["one ray: samples signed inside, of %d" % len(plane)] = int((one < 0).sum())
check("three-rays: on a plane 0.0225 off the rocker plates no sample reads inside or nearer, and under a plate each reads the 0.0225",
(three >= SLAB_R[0] - X_C - FLAT).all() and under.sum() > 500 and RES["readings"]["FLAT"] < FLAT, [float(three.min()), int(under.sum()), RES["readings"]["FLAT"]])
# against shells whose inside is known in closed form: a box and a disc, random points, each ray's edges and vertices among them
rng = np.random.default_rng(7)
cloud = rng.uniform((-0.2, -0.2, 0.2), (0.2, 0.2, 1.25), (4000, 3))
core = Signed({"core": [box((0, 0, 0.725), (0.26, 0.28, 0.85))]})("core", cloud)
exact = np.maximum.reduce([np.abs(cloud[:, 0]) - 0.13, np.abs(cloud[:, 1]) - 0.14, np.abs(cloud[:, 2] - 0.725) - 0.425])
check("three-rays: 4000 random points about a box are signed as the box signs them", ((core < 0) == (exact < 0)).all(), int(((core < 0) != (exact < 0)).sum()))
# the ray count: the jointlib rocker plates, and points between them aimed along the first ray at an edge or a vertex
fixture = json.loads((SURFACE / "tests" / "fixtures" / "ram_rays.json").read_text(encoding="utf-8"))
plates, aimed = {"plates": [(np.array(fixture["verts"]), fixture["faces"])]}, np.array(fixture["points"])
made, single = Signed(plates)("plates", aimed), Signed(plates, rays=1)("plates", aimed)
RES["readings"]["jointlib plates: points one ray signs inside, of %d" % len(aimed)] = int((single < 0).sum())
RES["readings"]["jointlib plates: points the oracle signs inside"] = int((made < 0).sum())
# one ray reads all 24 inside; the oracle as made reads none. The bound on one ray's count is the geometric mean of 1 and 24
check("ray-count: between the jointlib rocker plates, points on the first ray short of an edge or a vertex read outside by the oracle as it is made, inside by one ray",
(np.abs(aimed[:, 0]) < 0.349).all() and (made > 0).all() and (single < 0).sum() >= 5, [int((made < 0).sum()), int((single < 0).sum())])
SECTION[0] = "seat"
seat = np.concatenate([v for v, _ in shells["parent.seat"]])
deepest = float(Signed(shells)("parent.body", seat).min())
RES["readings"]["the base clevis's foot inside the thigh"] = deepest
check("the base clevis is seated: its foot runs 0.01 into the thigh's core, through the front plate", abs(deepest + EMBED) < FLAT, deepest)
SECTION[0] = "bell crank"
winner = None
for side in (1.0, -1.0):
m = R.Mechanism("bell_crank", *HINGE, **pins3(CRANK, side), parts=parts)
touch = zones(m, ram, parts)
m = replace(m, touch=touch)
zoned = {(label(member), zone[0]) for member, given in touch.items() for zone in given}
t0 = time.perf_counter()
f = R._fit(m, ram, steps=49, distance=Signed(shells, ram.reach()))
seconds = time.perf_counter() - t0
check(f"bell-crank-clears-on-meshes (side {side:+.0f}): over 0..-125 at 49 steps every member is clear of every part, 5 x {len(parts)} pairs, beside its pins by the record's zones",
f.ok and len(f.pairs) == 5 * len(parts) and set(f.allowed) == zoned, [f.report(), refused(f)])
fine = R._fit(m, ram, steps=251, distance=Signed(shells))
check(f"bell-crank-clears-on-meshes (side {side:+.0f}): and at 251 steps with the oracle uncapped", fine.ok, [fine.report(), refused(fine)])
bare = R._fit(replace(m, touch={}), ram, steps=49, distance=Signed(shells, ram.reach()))
need = needs(m, ram, parts, Signed(shells))
stated = {}
for member, given in touch.items():
for zone in given:
stated.setdefault((label(member), zone[0]), []).append(zone)
def takes(given, pin, radius, depth): # one zone about the pin, or zones about both of the member's pins that meet
return all(zone[3] >= depth for zone in given) and (any(zone[1] == pin and zone[2] >= radius for zone in given)
or (len({zone[1] for zone in given}) == 2 and sum(zone[2] for zone in given) >= radius))
slack = {pair: takes(stated[pair], *least) for pair, least in need.items() if pair in stated}
check(f"zones (side {side:+.0f}): with nothing let the gate refuses, and only pairs the record zones; each stated zone takes in the least that lets its pair",
{pair for pair, _, _ in refused(bare)} == set(need) and set(need) <= zoned and all(slack.values()), [refused(bare), sorted(set(need) - zoned), [k for k, v in slack.items() if not v]])
if side > 0:
winner = (m, f)
def free(fit): # the least margin of the pairs no zone lets: a zoned pair's is its depth's slack at the pin
return min(reading[0] for pair, reading in fit.pairs.items() if pair not in zoned)
RES["readings"].update({"bell crank: least margin of a pair with no zone, 251 steps uncapped": free(fine),
"bell crank: least margin of a zoned pair, 251 steps uncapped": min(reading[0] for pair, reading in fine.pairs.items() if pair in zoned),
"bell crank: pairs": len(f.pairs), "bell crank: zoned pairs": len(f.allowed), "bell crank: pairs refused with nothing let": len(refused(bare)),
"bell crank: seconds, 49 steps capped": seconds})
RES["zones"] = {f"{pair[0]} | {pair[1]}": {"stated": [list(zone[1:]) for zone in stated[pair]], "least": [pin, round(radius, 4), round(depth, 4)]} for pair, (pin, radius, depth) in sorted(need.items()) if pair in stated}
RES["least pairs"] = sorted((round(v[0], 4), v[1], k[0], k[1]) for k, v in fine.pairs.items() if k not in zoned)[:8]
SECTION[0] = "zones end"
m, f = winner
for member, part in (("rocker", "parent.bracket"), ("coupler", "child.horn"), ("rod", "rocker.pin.d")):
short = {**m.touch, member: tuple((p_, pin, 0.5 * radius, depth) if p_ == part else (p_, pin, radius, depth) for p_, pin, radius, depth in m.touch[member])}
got = R._fit(replace(m, touch=short), ram, steps=49, distance=Signed(shells, ram.reach()))
check(f"a zone ends at its radius: {member}'s about {part} cut to half, that pair alone is refused", [pair for pair, _, _ in refused(got)] == [(label(member), part)], refused(got))
SECTION[0] = "moved x"
# Soul's let_hide probes: a link's place along the axis moved from beside the bracket or horn into it
for name, moved, expect in (("the rocker at x 0.25, inside the bracket's 0.13..0.35", {"rocker": 0.25}, {("rocker", "parent.bracket"), ("rocker arm", "parent.bracket")}),
("the coupler at x 0.25, inside the horn's 0.23..0.31", {"c": 0.25}, {("coupler", "child.horn")}),
("both", {"rocker": 0.25, "c": 0.25}, {("rocker", "parent.bracket"), ("rocker arm", "parent.bracket"), ("coupler", "child.horn")})):
mm = R.Mechanism("bell_crank", *HINGE, **pins3(CRANK, 1.0, **moved), parts=parts, touch=m.touch)
got = R._fit(mm, ram, steps=49, distance=Signed(shells, ram.reach()))
inside = {pair: reading for pair, reading, _ in refused(got)}
RES["readings"]["moved x: " + name] = min(inside.values()) if inside else 0.0
check(f"a pin stood inside what it stands beside is refused: {name}", not got.ok and expect <= set(inside) and all(inside[pair] < -0.015 for pair in expect), refused(got))
SECTION[0] = "four bar"
shells4, parts4 = knee("four_bar", DEEP)
m4 = R.Mechanism("four_bar", *HINGE, **pins3(DEEP), parts=parts4)
m4 = replace(m4, touch=zones(m4, ram, parts4))
f4 = R._fit(m4, ram, steps=49, distance=Signed(shells4, ram.reach()))
hit = {pair: reading for pair, reading, _ in refused(f4)}
RES["readings"]["four bar: barrel inside the shin's clearance"] = hit.get(("barrel[0]", "child.body"), 0.0)
check("third-body: the deep four-bar's ram is refused on the shin, which folds into it", not f4.ok and {("barrel[0]", "child.body"), ("rod[0]", "child.body")} <= set(hit) and f4.clear_at[2] == "child.body", refused(f4))
SECTION[0] = "search"
seats = {"rocker": [(X_R, *CRANK["rocker"]), (X_R, CRANK["rocker"][0] - 0.07, CRANK["rocker"][1] + 0.03)], "c": [(X_C, *CRANK["c"]), (X_C, CRANK["c"][0] - 0.05, CRANK["c"][1] + 0.03)],
"a": [(0.0, *CRANK["a"]), (0.0, 0.4, 1.0)], "link": (0.35, 0.5, 3), "d": (0.2, 0.26, 2)}
built = []
def world(mech):
made, bodies = knee("bell_crank", {k: (float(getattr(mech, k)[1]), float(getattr(mech, k)[2])) for k in CRANK})
built.append(mech)
return bodies, zones(mech, ram, bodies), Signed(made, ram.reach())
t0 = time.perf_counter()
s = R.search("bell_crank", {"pivot": HINGE[0], "axis": HINGE[1], "lo": -125, "hi": 0}, ram, seats, world=world, steps=49)
RES["readings"].update({"search: seconds": time.perf_counter() - t0, "search: candidates": s.tried, "search: pass the gates before clearance": s.fits,
"search: worlds built": len(built), "search: refused on their own parts": s.tally.get("clash", 0)})
RES["search"] = {"report": s.report(), "seat": {k: np.round(v, 4).tolist() for k, v in (s.seat or {}).items()}, "tally": s.tally}
again = R._fit(s.best.m, ram, steps=251, distance=world(s.best.m)[2]) if s.found else None
check("search-holds-candidate-links: a seat grid about the probe's bell crank, each candidate met with the meshes its own pins place, runs to a fit that holds at 251 steps",
s.found and s.best.ok and len(built) - 1 == s.tally.get("clash", 0) + 1 and again.ok and len(s.best.pairs) == 5 * len(parts), [s.report(), refused(again) if again else None])
SECTION[0] = "render"
RES["renders"] = render(winner[0], ram, winner[1], shells, parts)
check("the bell crank is drawn at 0, -62.5 and -125", all(Path(path).is_file() for path in RES["renders"]), RES["renders"])
except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, not a missing result file
check(f"no uncaught error in section: {SECTION[0]}", False, traceback.format_exc().splitlines()[-8:])
finally:
RES["ok"] = all(c["ok"] for c in RES["checks"])
RES["readings"] = {name: (float(f"{value:.3g}") if isinstance(value, float) else value) for name, value in sorted(RES["readings"].items())}
Path(OUT + ".result.json").write_text(json.dumps(RES, indent=1, default=str), encoding="utf-8")
for c in RES["checks"]:
print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True)
print("READINGS", RES["readings"], flush=True)
sys.exit(0 if RES["ok"] else 1)

View file

@ -0,0 +1,504 @@
{
"blender": "5.3.0",
"checks": [
{
"name": "inside-is-negative: a point inside a part reads its depth, negative, capped or not; a cap changes only what is outside",
"ok": true,
"detail": null
},
{
"name": "three-rays: on a plane 0.0225 off the rocker plates no sample reads inside or nearer, and under a plate each reads the 0.0225",
"ok": true,
"detail": null
},
{
"name": "three-rays: 4000 random points about a box are signed as the box signs them",
"ok": true,
"detail": null
},
{
"name": "ray-count: between the jointlib rocker plates, points on the first ray short of an edge or a vertex read outside by the oracle as it is made, inside by one ray",
"ok": true,
"detail": null
},
{
"name": "the base clevis is seated: its foot runs 0.01 into the thigh's core, through the front plate",
"ok": true,
"detail": null
},
{
"name": "bell-crank-clears-on-meshes (side +1): over 0..-125 at 49 steps every member is clear of every part, 5 x 12 pairs, beside its pins by the record's zones",
"ok": true,
"detail": null
},
{
"name": "bell-crank-clears-on-meshes (side +1): and at 251 steps with the oracle uncapped",
"ok": true,
"detail": null
},
{
"name": "zones (side +1): with nothing let the gate refuses, and only pairs the record zones; each stated zone takes in the least that lets its pair",
"ok": true,
"detail": null
},
{
"name": "bell-crank-clears-on-meshes (side -1): over 0..-125 at 49 steps every member is clear of every part, 5 x 12 pairs, beside its pins by the record's zones",
"ok": true,
"detail": null
},
{
"name": "bell-crank-clears-on-meshes (side -1): and at 251 steps with the oracle uncapped",
"ok": true,
"detail": null
},
{
"name": "zones (side -1): with nothing let the gate refuses, and only pairs the record zones; each stated zone takes in the least that lets its pair",
"ok": true,
"detail": null
},
{
"name": "a zone ends at its radius: rocker's about parent.bracket cut to half, that pair alone is refused",
"ok": true,
"detail": null
},
{
"name": "a zone ends at its radius: coupler's about child.horn cut to half, that pair alone is refused",
"ok": true,
"detail": null
},
{
"name": "a zone ends at its radius: rod's about rocker.pin.d cut to half, that pair alone is refused",
"ok": true,
"detail": null
},
{
"name": "a pin stood inside what it stands beside is refused: the rocker at x 0.25, inside the bracket's 0.13..0.35",
"ok": true,
"detail": null
},
{
"name": "a pin stood inside what it stands beside is refused: the coupler at x 0.25, inside the horn's 0.23..0.31",
"ok": true,
"detail": null
},
{
"name": "a pin stood inside what it stands beside is refused: both",
"ok": true,
"detail": null
},
{
"name": "third-body: the deep four-bar's ram is refused on the shin, which folds into it",
"ok": true,
"detail": null
},
{
"name": "search-holds-candidate-links: a seat grid about the probe's bell crank, each candidate met with the meshes its own pins place, runs to a fit that holds at 251 steps",
"ok": true,
"detail": null
},
{
"name": "the bell crank is drawn at 0, -62.5 and -125",
"ok": true,
"detail": null
}
],
"readings": {
"FLAT": 8.34e-09,
"bell crank: least margin of a pair with no zone, 251 steps uncapped": 0.0336,
"bell crank: least margin of a zoned pair, 251 steps uncapped": 0.000118,
"bell crank: pairs": 60,
"bell crank: pairs refused with nothing let": 19,
"bell crank: seconds, 49 steps capped": 2.12,
"bell crank: zoned pairs": 20,
"four bar: barrel inside the shin's clearance": -0.122,
"jointlib plates: points one ray signs inside, of 24": 24,
"jointlib plates: points the oracle signs inside": 0,
"moved x: both": -0.0543,
"moved x: the coupler at x 0.25, inside the horn's 0.23..0.31": -0.02,
"moved x: the rocker at x 0.25, inside the bracket's 0.13..0.35": -0.0543,
"one ray: samples signed inside, of 6912": 0,
"search: candidates": 13824,
"search: pass the gates before clearance": 78,
"search: refused on their own parts": 21,
"search: seconds": 43.3,
"search: worlds built": 22,
"the base clevis's foot inside the thigh": -0.01
},
"zones": {
"barrel[0] | parent.seat": {
"stated": [
[
"a",
0.15645000000000003,
0.0
]
],
"least": [
"a",
0.1222,
0.0
]
},
"barrel[0] | rocker.pin.d": {
"stated": [
[
"d",
0.11105000000000001,
0.0
]
],
"least": [
"d",
0.1108,
0.0
]
},
"barrel[0] | rocker.seat": {
"stated": [
[
"d",
0.13505,
0.0
]
],
"least": [
"d",
0.1263,
0.0
]
},
"coupler | child.horn": {
"stated": [
[
"c",
0.11195,
0.0
]
],
"least": [
"c",
0.0947,
0.0
]
},
"coupler | coupler.pin.c": {
"stated": [
[
"c",
0.08795,
0.027
]
],
"least": [
"c",
0.0474,
0.0259
]
},
"coupler | coupler.plate": {
"stated": [
[
"p",
0.24152975906703586,
0.018500000000000016
],
[
"c",
0.24152975906703586,
0.018500000000000016
]
],
"least": [
"p",
0.4736,
0.0175
]
},
"coupler | rocker.pin.p": {
"stated": [
[
"p",
0.08795,
0.027
]
],
"least": [
"p",
0.0474,
0.0259
]
},
"coupler | rocker.plate": {
"stated": [
[
"p",
0.2818973893266964,
0.0
]
],
"least": [
"p",
0.2368,
0.0
]
},
"rocker | coupler.plate": {
"stated": [
[
"p",
0.26840002998268986,
0.0
]
],
"least": [
"p",
0.2366,
0.0
]
},
"rocker | parent.bracket": {
"stated": [
[
"rocker",
0.11695,
0.0
]
],
"least": [
"rocker",
0.0946,
0.0
]
},
"rocker | rocker.pin.R": {
"stated": [
[
"rocker",
0.08995,
0.029
]
],
"least": [
"rocker",
0.0473,
0.0279
]
},
"rocker | rocker.pin.p": {
"stated": [
[
"p",
0.08795,
0.027
]
],
"least": [
"p",
0.0473,
0.0259
]
},
"rocker | rocker.plate": {
"stated": [
[
"rocker",
0.2172005150345214,
0.018500000000000016
],
[
"p",
0.2172005150345214,
0.018500000000000016
]
],
"least": [
"rocker",
0.4259,
0.0175
]
},
"rocker arm | parent.bracket": {
"stated": [
[
"rocker",
0.11695,
0.0
]
],
"least": [
"rocker",
0.096,
0.0
]
},
"rocker arm | rocker.pin.R": {
"stated": [
[
"rocker",
0.08995,
0.029
]
],
"least": [
"rocker",
0.048,
0.0279
]
},
"rocker arm | rocker.pin.d": {
"stated": [
[
"d",
0.08795,
0.027
]
],
"least": [
"d",
0.048,
0.0259
]
},
"rocker arm | rocker.plate": {
"stated": [
[
"rocker",
0.12240000000000001,
0.018500000000000016
],
[
"d",
0.12240000000000001,
0.018500000000000016
]
],
"least": [
"rocker",
0.24,
0.0175
]
},
"rod[0] | rocker.pin.d": {
"stated": [
[
"d",
0.07955,
0.027
]
],
"least": [
"d",
0.0794,
0.0259
]
},
"rod[0] | rocker.seat": {
"stated": [
[
"d",
0.10355,
0.0
]
],
"least": [
"d",
0.0938,
0.0
]
}
},
"least pairs": [
[
0.0336,
-125.0,
"rocker",
"rocker.pin.d"
],
[
0.0393,
-125.0,
"rod[0]",
"rocker.pin.R"
],
[
0.0417,
0.0,
"coupler",
"parent.bracket"
],
[
0.0579,
0.0,
"rocker arm",
"coupler.plate"
],
[
0.0687,
0.0,
"coupler",
"rocker.pin.R"
],
[
0.0766,
0.0,
"rocker",
"child.horn"
],
[
0.0766,
0.0,
"rocker arm",
"child.horn"
],
[
0.0808,
-125.0,
"coupler",
"child.body"
]
],
"search": {
"report": "78 of 13824 candidates pass the gates before clearance (failed: arm 1406, assembly 4800, clash 21, load 1355, stroke 1160, toggle 7352); best: OK: L 0.664..0.968, barrel 0.513, stroke 0.458 for travel 0.304 (spare +0.137), arm >= 0.090, rocker swing 99.9, pin load <= 0.73, transmission >= 17.3 deg, clear +0.000",
"seat": {
"a": [
0.0,
0.45,
1.15
],
"rocker": [
0.3675,
0.3171,
0.3217
],
"p": [
0.3675,
0.7683,
0.5372
],
"c": [
0.3275,
0.3493,
0.1486
],
"d": [
0.0,
0.4303,
0.4866
]
},
"tally": {
"assembly": 4800,
"toggle": 7352,
"arm": 1406,
"stroke": 1160,
"load": 1355,
"clash": 21
}
},
"renders": [
"F:/aeth-wt/fable-ramcore/scratch/h4/out/live_h4.r3_0.png",
"F:/aeth-wt/fable-ramcore/scratch/h4/out/live_h4.r3_62p5.png",
"F:/aeth-wt/fable-ramcore/scratch/h4/out/live_h4.r3_125.png"
],
"ok": true
}

View file

@ -12,7 +12,8 @@
"brokkr_mesh_polish.scrub_markings",
"brokkr_mesh_polish.cut_parts",
"brokkr_mesh_polish.pick",
"brokkr_reference.solve_camera"
"brokkr_reference.solve_camera",
"brokkr_reference.flow_score"
]
},
{
@ -119,13 +120,14 @@
"brokkr_mesh_polish.scrub_markings",
"brokkr_mesh_polish.cut_parts",
"brokkr_mesh_polish.pick",
"brokkr_reference.solve_camera"
"brokkr_reference.solve_camera",
"brokkr_reference.flow_score"
],
"record": {
"lens": 50.02266319807241,
"lens_band": [
50.02266319807241,
50.02266319807241
45.26237741142627,
61.09781880064287
],
"lens_at_bound": null,
"rms": 0.03555833513434369,

View file

@ -0,0 +1,276 @@
"""Live proof, in a background Blender, of brokkr_reference.flow_score through run_intent, and of core.crease_run
against Blender's own subdivision.
crease_run a strip of quads with its middle column creased hard, subdivided once by Blender: the built crease
is where core.crease_run says (the numbers printed as BUILT are test_reference.py's fixture)
flow_score a box and, beside it, a folded sheet seen from behind: the box's front edge scores 1, its back edge 0
(it faces away, so it is never read), and the sheet's fold 0, since neither of its faces is toward
the camera (mutant N5, which counts such creases, reads 1 and four creases). Then the box alone at
scales 0.01, 1 and 100, its front edge seen, and hidden by a strip standing in front of it by
0.316% of the box's diagonal (mutants O1, nothing hides; O2, a margin of 0.03 units; O3, HIDE ten
times over: each reads the hidden edge as seen. O4, no margin at all, loses seen edges to their
own faces here and at the first box). The margin is the objects' own: a box over a ground 20 and
40 times its size, a small box over a ground behind a long strip (O7, a share of the largest mesh
read), two chips before a large box (O9, no second cast); a box, a ground and a strip joined
into one mesh, where the margin is the box's own connected piece's (O10, the whole mesh's).
Cameras 30 and 144 diagonals off still read every edge (O5, HIDE at 1e-6, loses four contours
at 144)
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/reference_flow.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: it writes <out>.result.json and exits 1 when a check failed. Not part
of the unittest run: it needs Blender.
"""
import json
import math
import os
import sys
import tempfile
import time
import traceback
import types
from pathlib import Path
import bmesh
import bpy
import numpy as np
from bpy_extras.object_utils import world_to_camera_view
from mathutils import Euler, Matrix, Vector
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 os.path.isabs(OUT):
raise SystemExit(f"<out> must be an absolute path, not {OUT!r}: a relative one lands in Blender's start directory")
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
sys.path.append(str(SURFACE))
bpy.ops.wm.read_factory_settings(use_empty=True)
for module in ("brokkr_mesh_polish", "brokkr_reference"):
addon_utils.enable(module, default_set=True)
from brokkr_reference import core # noqa: E402
target = bt.BrokkrBlenderTarget(bpy)
target.configure_action_dirs("", tempfile.mkdtemp(prefix="brokkr-reference-flow-live-"))
target.reload_host_actions()
R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1],
"hostRows": [row["name"] for row in target.host_actions()[0]]}
COUNT = [0]
T0 = time.time()
WIDTH, HEIGHT = 800, 600
COLUMN = [[0.5, 0.0, 0.0], [0.6, 0.2, 1.0], [0.4, 0.1, 2.0], [0.7, -0.2, 3.0], [0.5, 0.0, 4.0]]
def check(name, ok, detail=None):
R["checks"].append({"name": name, "ok": bool(ok), "detail": detail})
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 = json.loads(receipt["hostResult"]) if receipt.get("hostResult") else None
print("SEND", f"{time.time() - T0:.1f}s", action, receipt["status"], str(receipt["message"])[:300], flush=True)
return receipt, result
def mesh_object(name, verts, faces):
mesh = bpy.data.meshes.new(name)
mesh.from_pydata(verts, [], faces)
obj = bpy.data.objects.new(name, mesh)
bpy.context.scene.collection.objects.link(obj)
return obj
def traced(camera, points, scale=1.0, corner=(0.0, 0.0)):
"""'u,v u,v ...' where Blender's own projection draws world points, in an image whose pixels are the frame's
times `scale` from `corner`."""
out = []
for p in points:
x, y, _ = world_to_camera_view(bpy.context.scene, camera, Vector(p))
out.append(f"{corner[0] + scale * x * WIDTH:.3f},{corner[1] + scale * (1.0 - y) * HEIGHT:.3f}")
return " ".join(out)
try:
check("host file admitted", not R["hostErrors"] and "brokkr_reference.flow_score" in R["hostRows"], R["hostRows"])
scene = bpy.context.scene
scene.render.resolution_x, scene.render.resolution_y, scene.render.resolution_percentage = WIDTH, HEIGHT, 100
# --- crease_run is Blender's level-1 subdivision of a hard crease -------------------------------------------------
col = np.array(COLUMN)
verts = [tuple(p + d) for p in col for d in ((-0.5, 0.3, 0.0), (0.0, 0.0, 0.0), (0.5, -0.3, 0.1))]
strip = mesh_object("Strip", verts, [(3 * i + j, 3 * i + j + 1, 3 * i + j + 4, 3 * i + j + 3) for i in range(4) for j in range(2)])
sharp = strip.data.attributes.new("crease_edge", "FLOAT", "EDGE")
for edge in strip.data.edges:
sharp.data[edge.index].value = 1.0 if all(v % 3 == 1 for v in edge.vertices) else 0.0
modifier = strip.modifiers.new("Subdivision", "SUBSURF")
modifier.levels, modifier.subdivision_type, modifier.use_creases = 1, "CATMULL_CLARK", True
bpy.context.view_layer.update()
evaluated = strip.evaluated_get(bpy.context.evaluated_depsgraph_get())
built_all = np.array([v.co for v in evaluated.data.vertices])
run = core.crease_run(COLUMN)
nearest = [built_all[np.linalg.norm(built_all - p, axis=1).argmin()] for p in run]
R["BUILT"] = [[round(float(v), 6) for v in p] for p in nearest]
print("BUILT", json.dumps(R["BUILT"]), flush=True)
worst = float(np.abs(np.array(nearest) - run).max())
# Shipped 4.8e-7 m (Blender's single floats); without the limit step (N3) 0.0208: the bound is their geometric mean.
check("crease_run stands where Blender builds the creased column, within 1e-4 m", len(built_all) == 45 and worst < 1e-4, worst)
strip.hide_render = True
strip.hide_viewport = True
# --- the camera every flow_score check below is seen through -------------------------------------------------------
truth = bpy.data.objects.new("Truth", bpy.data.cameras.new("Truth"))
scene.collection.objects.link(truth)
truth.data.lens, truth.data.sensor_width, truth.data.sensor_fit = 50.0, 36.0, "HORIZONTAL"
truth.matrix_world = Matrix.Translation((-6.5, -8.0, 4.6)) @ Euler((1.2, 0.03, -0.72), "XYZ").to_matrix().to_4x4()
bpy.context.view_layer.update()
box = "100,50,1700,1250" # the same view as an image twice the frame's size, its corner at 100, 50
# --- flow_score: the edges the camera sees on a box and on a folded sheet seen from behind ------------------------
bm = bmesh.new()
bmesh.ops.create_cube(bm, size=2.0, matrix=Matrix.Translation((0.0, 0.0, 1.0)))
mesh = bpy.data.meshes.new("Box")
bm.to_mesh(mesh)
bm.free()
scene.collection.objects.link(bpy.data.objects.new("Box", mesh))
# a valley fold running toward the camera in plan, its faces rising 45 degrees to either side: seen from above, both look down and away
fold, wing = [(2.176, -1.734, 0.5), (2.824, -1.266, 0.5)], np.array([0.1755, -0.2433, 0.3])
sheet = mesh_object("Sheet", [fold[0], fold[1], tuple(fold[1] - wing * [1, 1, -1]), tuple(fold[0] - wing * [1, 1, -1]), tuple(fold[1] + wing), tuple(fold[0] + wing)], [(0, 1, 2, 3), (1, 0, 5, 4)])
for polygon in sheet.data.polygons:
if polygon.normal.z > 0:
polygon.flip()
sheet.data.update()
bpy.context.view_layer.update()
eye = np.array(truth.matrix_world.translation)
check("fixture: both of the sheet's faces look away from the camera, and their fold is 90 degrees or so",
all((eye - np.array(p.center)) @ np.array(p.normal) < 0 for p in sheet.data.polygons) and abs(sheet.data.polygons[0].normal @ sheet.data.polygons[1].normal) < 0.5,
[list(p.normal) for p in sheet.data.polygons])
front, back = [(-1.0, -1.0, 0.0), (-1.0, -1.0, 2.0)], [(1.0, 1.0, 0.0), (1.0, 1.0, 2.0)]
lines = f"front: {traced(truth, front)}; back: {traced(truth, back)}; fold: {traced(truth, fold)}; top: {traced(truth, [(-1.0, -1.0, 2.0), (1.0, -1.0, 2.0), (1.0, 1.0, 2.0)])}"
receipt, flow = send("brokkr_reference.flow_score", camera_name="Truth", lines=lines)
R["flow"] = flow
check("flow_score: accepted; the box shows 3 creases and 6 contours, the sheet 6 borders and no crease", receipt["status"] == "accepted"
and flow["edges"] == {"crease": 3, "contour": 6, "border": 6} and flow["objects"] == ["Box", "Sheet"] and flow["height"] == HEIGHT, [receipt["message"], flow and flow["edges"]])
check("the box's front edge and the top's two edges score on 1, run 1", flow and flow["lines"]["front"]["on"] == 1.0 and flow["lines"]["front"]["run"] == 1.0
and flow["lines"]["top"]["on"] > 0.95, flow and flow["lines"])
check("the box's back edge, both its faces turned away, is not read: on 0", flow and flow["lines"]["back"] == {"on": 0.0, "off": 5.0, "run": 0.0}, flow and flow["lines"]["back"])
check("the sheet's fold, both faces turned away, scores on 0 (N5 reads 1)", flow and flow["lines"]["fold"]["on"] == 0.0, flow and flow["lines"]["fold"])
receipt, only = send("brokkr_reference.flow_score", camera_name="Truth", lines=lines, objects="Box", box=box, height=600)
check("objects names the meshes read: the box alone has no border; lines in the frame's pixels miss a box twice its size",
receipt["status"] == "accepted" and only["edges"] == {"crease": 3, "contour": 6, "border": 0} and only["objects"] == ["Box"] and only["lines"]["front"]["on"] == 0.0, [receipt["message"], only])
for fields, said in (({"objects": "Nobody"}, "not a mesh object"), ({"objects": "Truth"}, "not a mesh object"), ({"lines": "1,2 3,4"}, "no tag"), ({"camera_name": "Box"}, "not a camera")):
receipt, _ = send("brokkr_reference.flow_score", **{"camera_name": "Truth", "lines": lines, **fields})
check(f"flow_score refuses {next(iter(fields))}: failed, saying '{said}'", receipt["status"] == "failed" and said in receipt["message"], receipt["message"])
# --- flow_score: an edge the camera would see, hidden by a nearer surface; the margin is the objects' own ----------
def stage(half, ground=0.0, far=0.0):
"""A box of half-width `half` standing on z = 0, alone or over a square ground `ground` across, and a camera:
the first box's, scaled with the box, or one `far` box diagonals off with the lens grown to match. Returns
the camera, the box's front edge, and its line as the camera draws it."""
for obj in [o for o in bpy.data.objects if o.type == "MESH"]:
bpy.data.objects.remove(obj)
name = f"Staged {half:g} {ground:g} {far:g}"
staged = bpy.data.objects.new(name, bpy.data.cameras.new(name))
scene.collection.objects.link(staged)
staged.data.lens, staged.data.sensor_width, staged.data.sensor_fit, staged.data.clip_start, staged.data.clip_end = 50.0 * max(1.0, far / 5.0), 36.0, "HORIZONTAL", 0.01 * half, 1e9
if far:
centre = Vector((0.0, 0.0, half))
place = centre + Vector((-0.55, -0.7, 0.4)).normalized() * far * 2.0 * half * math.sqrt(3.0)
staged.matrix_world = Matrix.Translation(place) @ (centre - place).to_track_quat("-Z", "Y").to_matrix().to_4x4()
else:
staged.matrix_world = Matrix.Translation(truth.matrix_world.translation * half) @ truth.matrix_world.to_3x3().to_4x4()
bm = bmesh.new()
bmesh.ops.create_cube(bm, size=2.0 * half, matrix=Matrix.Translation((0.0, 0.0, half)))
mesh = bpy.data.meshes.new("Box")
bm.to_mesh(mesh)
bm.free()
scene.collection.objects.link(bpy.data.objects.new("Box", mesh))
if ground:
g = ground / 2.0
mesh_object("Ground", [(-g, -g, -4.0 * half), (g, -g, -4.0 * half), (g, g, -4.0 * half), (-g, g, -4.0 * half)], [(0, 1, 2, 3)])
bpy.context.view_layer.update()
edge = np.array([(-1.0, -1.0, 0.0), (-1.0, -1.0, 2.0)]) * half
return staged, edge, f"front: {traced(staged, edge)}"
def screen(staged, name, point, gap, wide, tall):
"""An upright quad `wide` by `tall` that every sight line to `point` meets `gap` before it."""
toward = np.array(staged.matrix_world.translation) - point
toward /= np.linalg.norm(toward)
level = np.array([toward[0], toward[1], 0.0]) / np.hypot(toward[0], toward[1])
side = np.cross([0.0, 0.0, 1.0], level)
at = point + level * gap * float(toward @ level)
mesh_object(name, [tuple(at + side * a * wide / 2.0 + np.array([0.0, 0.0, b * tall / 2.0])) for a, b in ((-1, -1), (1, -1), (1, 1), (-1, 1))], [(0, 1, 2, 3)])
bpy.context.view_layer.update()
def front(staged, line, objects):
receipt, flow = send("brokkr_reference.flow_score", camera_name=staged.name, lines=line, **objects)
return (flow["lines"]["front"]["on"], flow["edges"]["crease"], flow["edges"]["contour"]) if receipt["status"] == "accepted" else receipt["message"]
DIAGONAL = 2.0 * math.sqrt(3.0) # of a box, in its half-widths
for s in (0.01, 1.0, 100.0):
staged, edge, line = stage(s)
bare = front(staged, line, {"objects": "Box"})
gap = 3.16e-3 * DIAGONAL * s # of the box's diagonal: the geometric mean of the shipped HIDE, 1e-3, and one ten times it (mutant O3), 3.16 from each
screen(staged, "Wall", edge.mean(0), gap, 0.4 * s, 3.0 * s)
walled = front(staged, line, {"objects": "Box"})
check(f"at scale {s:g} the box's front edge is a crease the camera sees (on 1); a strip 0.316% of the box's diagonal in front of it hides it (on 0, one crease fewer): O1 (nothing hides), "
"O2 (the ray stops 0.03 units short) and O3 (ten times HIDE) read on 1", bare == (1.0, 3, 6) and walled == (0.0, 2, 6), [bare, walled, gap])
# a larger mesh in the scene and among the meshes read: the margin stays the box's
for half, ground in ((0.5, 20.0), (0.05, 4.0)):
staged, edge, line = stage(half, ground)
bare = front(staged, line, {})
screen(staged, "Wall", edge.mean(0), 0.01 * DIAGONAL * half, 0.4 * half, 3.0 * half)
walled = front(staged, line, {})
check(f"a box {2 * half:g} across over a ground {ground:g} across, every mesh read: its front edge is seen, and a strip 1% of the box's diagonal in front hides it "
f"(a margin of the ground's is {1e-3 * ground * math.sqrt(2.0) / (0.01 * DIAGONAL * half):.1f} times the gap)", bare == (1.0, 3, 6) and walled == (0.0, 2, 6), [bare, walled])
# the box, the ground and the strip joined into one mesh: the margin is the box's own piece's (O10, the whole mesh's diagonal, reads on 1: the ground's margin is 16 times the gap)
staged, edge, line = stage(0.05, 20.0)
screen(staged, "Wall", edge.mean(0), 0.01 * DIAGONAL * 0.05, 0.02, 0.15)
bm = bmesh.new()
for obj in [o for o in bpy.data.objects if o.type == "MESH"]:
bm.from_mesh(obj.data)
bpy.data.objects.remove(obj)
mesh = bpy.data.meshes.new("Joined")
bm.to_mesh(mesh)
bm.free()
scene.collection.objects.link(bpy.data.objects.new("Joined", mesh))
bpy.context.view_layer.update()
walled = front(staged, line, {})
check("a box 0.1 across, a ground 20 across and a strip 1% of the box's diagonal in front of the box's edge, all one mesh: hidden, the margin is the edge's own connected piece's (O10 reads on 1)", walled[0] == 0.0, walled)
# a small box's edge behind a strip far longer than the box, over a ground: the margin is the box's, not the strip's or the ground's (O7, a share of the largest mesh read, reads on 1)
staged, edge, line = stage(0.05, 4.0)
gap = math.sqrt(1e-3 * DIAGONAL * 0.05 * 1e-3 * math.hypot(0.02, 4.0)) # the geometric mean of the box's margin and the strip's, 4.8 from each
screen(staged, "Wall", edge.mean(0), gap, 0.02, 4.0)
walled = front(staged, line, {})
check("a box 0.1 across over a ground 4 across, with a strip 4 long standing between the two margins in front of its edge: hidden, the margin is the smaller object's (O7 reads on 1)", walled == (0.0, 2, 6), [walled, gap])
# two chips far smaller than the box, in front of two of the edge's three read points: the margin is the chips' (O9, no second cast, reads on 1)
staged, edge, line = stage(1.0)
gap = math.sqrt(1e-3 * DIAGONAL * 1e-3 * 0.05 * math.sqrt(2.0)) # the geometric mean of the box's margin and a chip's, 7 from each
for t in (0.2, 0.5):
screen(staged, f"Chip {t}", edge[0] + t * (edge[1] - edge[0]), gap, 0.05, 0.05)
chipped = front(staged, line, {"objects": "Box"})
check("a box 2 across with two chips 0.05 across standing between the two margins in front of its edge: hidden, the margin is the chips' (O9 reads on 1)", chipped == (0.0, 2, 6), [chipped, gap])
# far cameras: the margin's floor is the ray's rounding (O5, HIDE 1e-6, loses four contours to their own faces at 144 diagonals; at 30 it reads true here)
for far in (30.0, 144.0):
staged, edge, line = stage(1.0, far=far)
bare = front(staged, line, {"objects": "Box"})
check(f"a camera {far:g} box diagonals off still reads the box's 3 creases and 6 contours and its front edge on 1" + (" (O5 reads 2 contours)" if far == 144.0 else ""), bare == (1.0, 3, 6), bare)
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()[-6:])
R["ok"] = all(c["ok"] for c in R["checks"])
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")
sys.exit(0 if R["ok"] else 1)

View file

@ -0,0 +1,385 @@
{
"blender": "5.3.0",
"checks": [
{
"name": "host file admitted",
"ok": true,
"detail": [
"brokkr_mesh_polish.audit",
"brokkr_mesh_polish.repair",
"brokkr_mesh_polish.orient",
"brokkr_mesh_polish.delight",
"brokkr_mesh_polish.scrub_markings",
"brokkr_mesh_polish.cut_parts",
"brokkr_mesh_polish.pick",
"brokkr_reference.solve_camera",
"brokkr_reference.flow_score"
]
},
{
"name": "crease_run stands where Blender builds the creased column, within 1e-4 m",
"ok": true,
"detail": 4.76837158203125e-07
},
{
"name": "fixture: both of the sheet's faces look away from the camera, and their fold is 90 degrees or so",
"ok": true,
"detail": [
[
-0.4140099287033081,
0.5732445120811462,
-0.7070971727371216
],
[
0.4140099287033081,
-0.5732445120811462,
-0.7070971727371216
]
]
},
{
"name": "flow_score: accepted; the box shows 3 creases and 6 contours, the sheet 6 borders and no crease",
"ok": true,
"detail": [
"Operator brokkr_reference.flow_score finished.",
{
"crease": 3,
"contour": 6,
"border": 6
}
]
},
{
"name": "the box's front edge and the top's two edges score on 1, run 1",
"ok": true,
"detail": {
"front": {
"on": 1.0,
"off": 0.0,
"run": 1.0
},
"back": {
"on": 0.0,
"off": 5.0,
"run": 0.0
},
"fold": {
"on": 0.0,
"off": 5.0,
"run": 0.0
},
"top": {
"on": 0.988,
"off": 0.06,
"run": 0.537
}
}
},
{
"name": "the box's back edge, both its faces turned away, is not read: on 0",
"ok": true,
"detail": {
"on": 0.0,
"off": 5.0,
"run": 0.0
}
},
{
"name": "the sheet's fold, both faces turned away, scores on 0 (N5 reads 1)",
"ok": true,
"detail": {
"on": 0.0,
"off": 5.0,
"run": 0.0
}
},
{
"name": "objects names the meshes read: the box alone has no border; lines in the frame's pixels miss a box twice its size",
"ok": true,
"detail": [
"Operator brokkr_reference.flow_score finished.",
{
"lines": {
"front": {
"on": 0.0,
"off": 5.0,
"run": 0.0
},
"back": {
"on": 0.0,
"off": 5.0,
"run": 0.0
},
"fold": {
"on": 0.0,
"off": 5.0,
"run": 0.0
},
"top": {
"on": 0.0,
"off": 5.0,
"run": 0.0
}
},
"edges": {
"crease": 3,
"contour": 6,
"border": 0
},
"objects": [
"Box"
],
"height": 600.0
}
]
},
{
"name": "flow_score refuses objects: failed, saying 'not a mesh object'",
"ok": true,
"detail": "Error: 'Nobody' is not a mesh object of this scene."
},
{
"name": "flow_score refuses objects: failed, saying 'not a mesh object'",
"ok": true,
"detail": "Error: 'Truth' is not a mesh object of this scene."
},
{
"name": "flow_score refuses lines: failed, saying 'no tag'",
"ok": true,
"detail": "Error: lines entry '1,2 3,4' has no tag; it is 'tag: u,v u,v ...'"
},
{
"name": "flow_score refuses camera_name: failed, saying 'not a camera'",
"ok": true,
"detail": "Error: 'Box' is not a camera object."
},
{
"name": "at scale 0.01 the box's front edge is a crease the camera sees (on 1); a strip 0.316% of the box's diagonal in front of it hides it (on 0, one crease fewer): O1 (nothing hides), O2 (the ray stops 0.03 units short) and O3 (ten times HIDE) read on 1",
"ok": true,
"detail": [
[
1.0,
3,
6
],
[
0.0,
2,
6
],
0.00010946561103835304
]
},
{
"name": "at scale 1 the box's front edge is a crease the camera sees (on 1); a strip 0.316% of the box's diagonal in front of it hides it (on 0, one crease fewer): O1 (nothing hides), O2 (the ray stops 0.03 units short) and O3 (ten times HIDE) read on 1",
"ok": true,
"detail": [
[
1.0,
3,
6
],
[
0.0,
2,
6
],
0.010946561103835304
]
},
{
"name": "at scale 100 the box's front edge is a crease the camera sees (on 1); a strip 0.316% of the box's diagonal in front of it hides it (on 0, one crease fewer): O1 (nothing hides), O2 (the ray stops 0.03 units short) and O3 (ten times HIDE) read on 1",
"ok": true,
"detail": [
[
1.0,
3,
6
],
[
0.0,
2,
6
],
1.0946561103835304
]
},
{
"name": "a box 1 across over a ground 20 across, every mesh read: its front edge is seen, and a strip 1% of the box's diagonal in front hides it (a margin of the ground's is 1.6 times the gap)",
"ok": true,
"detail": [
[
1.0,
3,
6
],
[
0.0,
2,
6
]
]
},
{
"name": "a box 0.1 across over a ground 4 across, every mesh read: its front edge is seen, and a strip 1% of the box's diagonal in front hides it (a margin of the ground's is 3.3 times the gap)",
"ok": true,
"detail": [
[
1.0,
3,
6
],
[
0.0,
2,
6
]
]
},
{
"name": "a box 0.1 across, a ground 20 across and a strip 1% of the box's diagonal in front of the box's edge, all one mesh: hidden, the margin is the edge's own connected piece's (O10 reads on 1)",
"ok": true,
"detail": [
0.0,
2,
6
]
},
{
"name": "a box 0.1 across over a ground 4 across, with a strip 4 long standing between the two margins in front of its edge: hidden, the margin is the smaller object's (O7 reads on 1)",
"ok": true,
"detail": [
[
0.0,
2,
6
],
0.000832363492248106
]
},
{
"name": "a box 2 across with two chips 0.05 across standing between the two margins in front of its edge: hidden, the margin is the chips' (O9 reads on 1)",
"ok": true,
"detail": [
[
0.0,
2,
6
],
0.0004949232003839765
]
},
{
"name": "a camera 30 box diagonals off still reads the box's 3 creases and 6 contours and its front edge on 1",
"ok": true,
"detail": [
1.0,
3,
6
]
},
{
"name": "a camera 144 box diagonals off still reads the box's 3 creases and 6 contours and its front edge on 1 (O5 reads 2 contours)",
"ok": true,
"detail": [
1.0,
3,
6
]
}
],
"hostErrors": [],
"hostRows": [
"brokkr_mesh_polish.audit",
"brokkr_mesh_polish.repair",
"brokkr_mesh_polish.orient",
"brokkr_mesh_polish.delight",
"brokkr_mesh_polish.scrub_markings",
"brokkr_mesh_polish.cut_parts",
"brokkr_mesh_polish.pick",
"brokkr_reference.solve_camera",
"brokkr_reference.flow_score"
],
"BUILT": [
[
0.5,
0.0,
0.0
],
[
0.54375,
0.09375,
0.5
],
[
0.55,
0.15,
1.0
],
[
0.504167,
0.139583,
1.5
],
[
0.483333,
0.066667,
2.0
],
[
0.55,
-0.04375,
2.5
],
[
0.616667,
-0.116667,
3.0
],
[
0.589583,
-0.089583,
3.5
],
[
0.5,
0.0,
4.0
]
],
"flow": {
"lines": {
"front": {
"on": 1.0,
"off": 0.0,
"run": 1.0
},
"back": {
"on": 0.0,
"off": 5.0,
"run": 0.0
},
"fold": {
"on": 0.0,
"off": 5.0,
"run": 0.0
},
"top": {
"on": 0.988,
"off": 0.06,
"run": 0.537
}
},
"edges": {
"crease": 3,
"contour": 6,
"border": 6
},
"objects": [
"Box",
"Sheet"
],
"height": 600.0
},
"ok": true
}

View file

@ -559,21 +559,24 @@ class ParamTests(unittest.TestCase):
@unittest.skipIf(np is None, "numpy is not installed")
class MechanicalKitTests(unittest.TestCase):
PARTS = ["nozzle", "tank", "ribbed_cylinder", "strut", "actuator", "pipe_fitting", "radiator_stack", "vent", "plate", "reducer", "bracket"]
PARTS = ["nozzle", "tank", "ribbed_cylinder", "strut", "actuator", "ram_barrel", "ram_rod", "pipe_fitting", "radiator_stack", "vent", "plate", "reducer", "bracket"]
@classmethod
def setUpClass(cls):
cls.kit = core.load_kit("mechanical")
def test_the_kit_is_the_eleven_parts_and_three_socket_types(self):
def test_the_kit_is_the_thirteen_parts_and_five_socket_types(self):
self.assertEqual(list(self.kit["parts"]), self.PARTS)
self.assertEqual({k: v["match"] for k, v in self.kit["socketTypes"].items()}, {"flange": "equal", "mount": "fits", "pivot": "equal"})
self.assertEqual({k: (v["match"], v.get("dof")) for k, v in self.kit["socketTypes"].items()},
{"flange": ("equal", None), "mount": ("fits", None), "pivot": ("equal", "revolute"), "slide": ("equal", "prismatic"), "hose": ("fits", None)})
self.assertEqual({name: [(s["name"], s["type"]) for s in part["sockets"]] for name, part in self.kit["parts"].items()}, {
"nozzle": [("mount", "flange")],
"tank": [("port_a", "flange"), ("port_b", "flange"), ("saddle", "mount"), ("lug_a", "mount"), ("lug_b", "mount"), ("lug_a_back", "mount"), ("lug_b_back", "mount")],
"ribbed_cylinder": [("end_a", "flange"), ("end_b", "flange")],
"strut": [("end_a", "pivot"), ("end_a_back", "pivot"), ("end_b", "pivot"), ("end_b_back", "pivot")],
"actuator": [("base", "pivot"), ("base_back", "pivot"), ("rod_end", "pivot"), ("rod_end_back", "pivot")],
"actuator": [("base", "pivot"), ("base_back", "pivot"), ("rod_end", "pivot"), ("rod_end_back", "pivot"), ("port_cap", "hose"), ("port_rod", "hose")],
"ram_barrel": [("base", "pivot"), ("base_back", "pivot"), ("bore", "slide"), ("port_cap", "hose"), ("port_rod", "hose")],
"ram_rod": [("piston", "slide"), ("rod_end", "pivot"), ("rod_end_back", "pivot")],
"pipe_fitting": [("a", "flange"), ("b", "flange"), ("c", "flange")],
"radiator_stack": [("base", "mount")], "vent": [("back", "mount")], "plate": [("back", "mount"), ("front", "mount")],
"reducer": [("big", "flange"), ("small", "flange")], "bracket": [("mount", "mount"), ("pivot", "pivot"), ("pivot_back", "pivot")]})
@ -811,8 +814,6 @@ class FrameKitTests(unittest.TestCase):
"""frame-kit-holds. Mutant E10 (frame's mount declared 'equal'): the types differ from mechanical's."""
self.assertEqual(list(self.kit["parts"]), self.PARTS)
self.assertEqual(self.kit["socketTypes"], {name: self.mechanical["socketTypes"][name] for name in ("mount", "pivot")})
lines = lambda name: [line for line in (core.KITS / f"{name}.v0.json").read_text(encoding="utf-8").split("\n") if line.startswith((' "mount"', ' "pivot"'))] # noqa: E731
self.assertEqual((lines("frame"), len(lines("frame"))), (lines("mechanical"), 2)) # byte for byte
ends = [("end_a", "mount"), ("end_b", "mount")]
self.assertEqual({name: [(s["name"], s["type"]) for s in part["sockets"]] for name, part in self.kit["parts"].items()}, {
"beam_i": ends, "channel": ends, "tee": ends, "angle": ends, "box_beam": ends, "truss": ends,
@ -1411,6 +1412,189 @@ class PoseTests(unittest.TestCase):
core.reach_roll(world, sp, sc, [rng.uniform(-1, 1) for _ in range(3)], (world @ sp["matrix"])[:3, 2], 0.0, 0.0)
@unittest.skipIf(np is None, "numpy is not installed")
class JointRecordTests(unittest.TestCase):
"""What a connection's joint record rests on in core: the socket type's dof, mate and residual with a slide,
within, and aim_roll and reach_roll inside limits. Bounds sit at the geometric mean of the shipped worst reading
and the least claimed mutant's (lodur:ruling:deterministic-bound-margin); a reading that is exact is asserted
equal."""
PAIRS = MateTests.PAIRS
SLIDES = (-0.04, 0.025, 0.3)
SLID = 2.4e-8 # metres from the point `slide` along the parent socket's z. shipped 9.7e-16; least mutant 0.6 (J1); separation 6.2e14
RAM = 1.9e-8 # a socket of barrel and rod against the actuator's. shipped 0, taken as one float step; least mutant 1.6 (J1); separation 7.2e15
BEATEN = 1.2e-8 # how far a roll inside the limits may pass the dot aim reports. shipped 1.1e-16; least mutant 1.26 (J2), J3 reads 1.99; separation 1.1e16
@classmethod
def setUpClass(cls):
cls.kit = core.load_kit("mechanical")
def slide_readings(self):
"""Read from the two world frames, not through core.residual: how far the child socket's origin stands from
the point `slide` along the parent socket's z, the normals, and the residual at the stated slide."""
rng, parts, worst = random.Random("slide"), self.kit["parts"], {"slid": 0.0, "normal": 0.0, "residual": 0.0}
for parent, parent_params, parent_socket, child, child_params, child_socket in self.PAIRS:
sp, sc = core.joint(parts[parent], core.build(parts[parent], parent_params), parent_socket,
parts[child], core.build(parts[child], child_params), child_socket)
world = np.eye(4)
world[:3, :3] = core._rotation([rng.uniform(-180, 180) for _ in range(3)])
world[:3, 3] = [rng.uniform(-5, 5) for _ in range(3)]
for roll in (0.0, 30.0, -115.0):
self.assertEqual(core.mate(sp, sc, roll, 0.0).tolist(), core.mate(sp, sc, roll).tolist()) # slide 0 is the mate there was
for slide in self.SLIDES:
placed = world @ core.mate(sp, sc, roll, slide)
a, b = world @ sp["matrix"], placed @ sc["matrix"]
worst["slid"] = max(worst["slid"], float(np.linalg.norm(b[:3, 3] - a[:3, 3] - slide * a[:3, 2])))
worst["normal"] = max(worst["normal"], float(np.abs(a[:3, 2] + b[:3, 2]).max()))
worst["residual"] = max(worst["residual"], core.residual(world, sp, placed, sc, roll, slide))
self.assertAlmostEqual(core.residual(world, sp, placed, sc, roll, 0.0), abs(slide) * float(np.abs(a[:3, 2]).max()), places=12) # read at another slide it stands that far off
return worst
def test_a_slide_stands_the_child_along_the_parent_socket_z(self):
"""slide-mates. Mutant J1 (the slide applied after FLIP, so along the child's side of the joint: the child
stands -slide along the parent socket's z)."""
worst = self.slide_readings()
self.assertLess(worst["slid"], self.SLID)
self.assertLess(worst["normal"], MateTests.NORMAL)
self.assertLess(worst["residual"], MateTests.RESIDUAL)
def ram_reading(self):
parts, worst = self.kit["parts"], 0.0
for body_r, body_len, extension in ((0.06, 0.4, 0.0), (0.05, 0.2, 0.15), (0.12, 1.0, 0.8), (0.09, 0.55, 0.31)):
barrel = core.build(parts["ram_barrel"], {"body_r": body_r, "body_len": body_len})
rod = core.build(parts["ram_rod"], {"body_r": body_r, "length": body_len + 1.1 * body_r})
whole = {s["name"]: s["matrix"] for s in core.build(parts["actuator"], {"body_r": body_r, "body_len": body_len, "extension": extension}).sockets}
sp, sc = core.joint(parts["ram_barrel"], barrel, "bore", parts["ram_rod"], rod, "piston")
self.assertIsNone(core.mate_refusal(self.kit["socketTypes"], sp, sc))
placed = core.mate(sp, sc, 0.0, extension)
for socket in barrel.sockets:
if socket["name"] != "bore":
worst = max(worst, float(np.abs(socket["matrix"] - whole[socket["name"]]).max()))
for socket in rod.sockets[1:]:
worst = max(worst, float(np.abs(placed @ socket["matrix"] - whole[socket["name"]]).max()))
return worst
def test_a_rod_in_its_barrel_is_the_actuator_at_that_extension(self):
"""slide-mates, on the kit: ram_rod's piston on ram_barrel's bore at slide e puts every socket where the
actuator has it at extension e. Slide 0 is closed. Mutant J1."""
self.assertEqual([(s["name"], s["type"]) for s in core.build(self.kit["parts"]["ram_barrel"]).sockets],
[("base", "pivot"), ("base_back", "pivot"), ("bore", "slide"), ("port_cap", "hose"), ("port_rod", "hose")])
self.assertEqual([(s["name"], s["type"]) for s in core.build(self.kit["parts"]["ram_rod"]).sockets],
[("piston", "slide"), ("rod_end", "pivot"), ("rod_end_back", "pivot")])
self.assertLess(self.ram_reading(), self.RAM)
def test_a_socket_type_states_its_dof(self):
"""dof-by-type, the format. A type states revolute or prismatic or nothing (rigid); anything else is refused
naming the type."""
doc = document()
doc["socketTypes"] = {"mount": {"match": "fits", "doc": ""}, "pin": {"match": "equal", "doc": "", "dof": "revolute"}, "bore": {"match": "equal", "dof": "prismatic", "doc": ""}}
self.assertEqual({name: entry.get("dof") for name, entry in core.check_kit(doc)["socketTypes"].items()}, {"mount": None, "pin": "revolute", "bore": "prismatic"})
self.assertNotIn("dof", core.check_kit(doc)["socketTypes"]["mount"])
for odd in ("hinge", "", None, ["revolute"], "rigid"):
doc["socketTypes"]["pin"]["dof"] = odd
with self.assertRaisesRegex(core.KitError, r"kit 't' socket type 'pin': dof must be 'revolute' or 'prismatic'"):
core.check_kit(doc)
doc["socketTypes"]["pin"] = {"match": "equal", "doc": "", "axis": "z"}
with self.assertRaisesRegex(core.KitError, r"socket type 'pin' has no key 'axis'"):
core.check_kit(doc)
types = {kit: core.load_kit(kit)["socketTypes"] for kit in ("mechanical", "frame", "cutters")}
self.assertEqual({(kit, name): entry["dof"] for kit, found in types.items() for name, entry in found.items() if "dof" in entry},
{("mechanical", "pivot"): "revolute", ("mechanical", "slide"): "prismatic", ("frame", "pivot"): "revolute"})
self.assertEqual(core.describe(self.kit, "ram_rod")["socketTypes"]["slide"]["dof"], "prismatic")
def test_two_kits_mate_a_type_only_when_its_dof_agrees(self):
"""dof-by-type, across kits. Mutant J6 (mate_refusal ignores dof across kits): a pivot another kit declares
without dof mates."""
types, frame = self.kit["socketTypes"], core.load_kit("frame")["socketTypes"]
socket = lambda name, kind, size: {"name": name, "type": kind, "size": size, "matrix": np.eye(4)} # noqa: E731
self.assertIsNone(core.mate_refusal(frame, socket("p", "pivot", 0.05), socket("c", "pivot", 0.05), types, ("frame", "mechanical")))
self.assertIsNone(core.mate_refusal(types, socket("p", "pivot", 0.05), socket("c", "pivot", 0.05), frame, ("mechanical", "frame")))
rigid = {**types, "pivot": {"match": "equal", "doc": ""}}
self.assertRegex(core.mate_refusal(types, socket("p", "pivot", 0.05), socket("c", "pivot", 0.05), rigid, ("mechanical", "odd")),
r"kit 'mechanical' declares socket type 'pivot' with dof revolute and kit 'odd' with dof none \(rigid\); parts of two kits mate by socket types both declare alike")
self.assertRegex(core.mate_refusal(rigid, socket("p", "pivot", 0.05), socket("c", "pivot", 0.05), types, ("odd", "mechanical")),
r"kit 'odd' declares socket type 'pivot' with dof none \(rigid\) and kit 'mechanical' with dof revolute")
sliding = {**types, "pivot": {"match": "equal", "doc": "", "dof": "prismatic"}}
self.assertIn("with dof revolute and kit 'odd' with dof prismatic", core.mate_refusal(types, socket("p", "pivot", 0.05), socket("c", "pivot", 0.05), sliding, ("mechanical", "odd")))
self.assertIsNone(core.mate_refusal(rigid, socket("p", "pivot", 0.05), socket("c", "pivot", 0.05), None)) # one kit: its own type
def test_within_is_the_value_s_representative_inside_the_limits(self):
"""limits-everywhere, the one rule. Mutant J2 (within without the 360 k shift): -170 has no representative in
150..210."""
self.assertEqual(core.within(190.0, 150.0, 210.0, True), 190.0)
self.assertEqual(core.within(-170.0, 150.0, 210.0, True), 190.0)
self.assertEqual(core.within(550.0, 150.0, 210.0, True), 190.0)
self.assertIsNone(core.within(-170.0, 150.0, 210.0, False))
self.assertIsNone(core.within(100.0, 150.0, 210.0, True))
self.assertIsNone(core.within(-100.0, 150.0, 210.0, True))
self.assertEqual(core.within(180.0, -180.0, 180.0, True), 180.0) # a value inside is itself
self.assertEqual(core.within(-180.0, -180.0, 180.0, True), -180.0)
self.assertEqual(core.within(270.0, -180.0, 180.0, True), -90.0)
self.assertEqual(core.within(-350.0, 0.0, 20.0, True), 10.0)
self.assertEqual(core.within(0.12, 0.0, 0.3, False), 0.12)
self.assertIsNone(core.within(0.31, 0.0, 0.3, False))
self.assertIsNone(core.within(-0.001, 0.0, 0.3, False))
self.assertEqual(core.within(float(np.float32(0.3)), 0.0, 0.3, False), 0.3) # a float32 field's 0.3 is 1.2e-08 over: the end
self.assertEqual(core.within(float(np.float32(-20.1)), -20.1, 90.0, True), -20.1)
self.assertEqual(core.within(-1e-7, 0.0, 0.3, False), 0.0)
self.assertIsNone(core.within(0.3 + 3e-6, 0.0, 0.3, False)) # 3 slacks over
def aim_readings(self):
"""Over PoseTests' joints, each under limits drawn about it: how far a roll on a quarter-degree grid inside
the limits passes the dot aim_roll reports there, and how far the reported dot is from the one read back."""
worst, pose = {"beaten": -math.inf, "read": 0.0, "ends": 0, "cases": 0}, PoseTests()
pose.kit = self.kit
for world, sp, sc, rng in pose.joints("aim-limits"):
for name, axis in core.AXES.items():
if abs(np.array(axis) @ sc["matrix"][:3, 2]) == 1.0:
continue
d, lo = pose.direction(rng), rng.uniform(-360.0, 300.0)
hi = lo + rng.uniform(5.0, min(360.0, 360.0 - lo))
roll, dot = core.aim_roll(world, sp, sc, axis, d, (lo, hi))
turned = lambda r: float(d @ (world @ core.mate(sp, sc, r))[:3, :3] @ np.array(axis)) # noqa: E731
self.assertTrue(lo <= roll <= hi, (roll, lo, hi))
worst["read"] = max(worst["read"], abs(dot - turned(roll)))
worst["beaten"] = max(worst["beaten"], max(turned(float(r)) for r in np.arange(lo, hi, 0.25)) - dot)
worst["ends"] += roll in (lo, hi)
worst["cases"] += 1
return worst
def test_aim_inside_limits_takes_the_best_roll_they_hold(self):
"""limits-everywhere, aim. The free roll's representative when the limits hold one (150..210 and a free roll
of -170: 190), else the end with the larger dot. Mutant J3 (the end nearer the free roll by angle, read along
the line and not round the circle: 100..185 and a free roll of -170 takes 100)."""
ident = {"name": "s", "matrix": np.eye(4)}
toward = lambda roll: (-math.sin(math.radians(roll)), math.cos(math.radians(roll)), 0.0) # noqa: E731 the child's y stands there at that roll
aim = lambda free, limits: tuple(round(v, 9) for v in core.aim_roll(np.eye(4), ident, ident, (0.0, 1.0, 0.0), toward(free), limits)) # noqa: E731
self.assertEqual(aim(-170.0, None), (-170.0, 1.0))
self.assertEqual(aim(-170.0, (150.0, 210.0)), (190.0, 1.0))
self.assertEqual(aim(-170.0, (100.0, 185.0)), (185.0, round(math.cos(math.radians(5.0)), 9)))
self.assertEqual(aim(-170.0, (-90.0, 20.0)), (-90.0, round(math.cos(math.radians(80.0)), 9)))
self.assertEqual(aim(90.0, (-20.0, 200.0)), (90.0, 1.0))
self.assertEqual(aim(0.0, (170.0, 190.0)), (170.0, round(math.cos(math.radians(170.0)), 9))) # a tie takes lo
with self.assertRaisesRegex(core.KitError, "lies along the pin"):
core.aim_roll(np.eye(4), ident, ident, (0.0, 0.0, 1.0), (1.0, 0.0, 0.0), (0.0, 90.0))
worst = self.aim_readings()
self.assertEqual(worst["cases"], 80)
self.assertGreater(worst["ends"], 20) # the limits bind in a share of the cases
self.assertLess(worst["read"], PoseTests.AIMED)
self.assertLess(worst["beaten"], self.BEATEN)
def test_reach_inside_limits_takes_a_root_they_hold(self):
"""limits-everywhere, reach. Mutant J4 (the nearer root whatever the limits)."""
ident = {"name": "s", "matrix": np.eye(4)}
reach = lambda current, limits: tuple(round(v, 9) for v in core.reach_roll(np.eye(4), ident, ident, (0.0, 1.0, 0.0), (1.0, 0.0, 0.0), 0.5, current, limits)) # noqa: E731
self.assertEqual(reach(0.0, None), (-30.0, 0.0)) # the roots are -30 and -150
self.assertEqual(reach(0.0, (-160.0, -100.0)), (-150.0, 0.0)) # the nearer root is outside
self.assertEqual(reach(0.0, (200.0, 220.0)), (210.0, 0.0)) # as its representative
self.assertEqual(reach(0.0, (-180.0, 180.0)), (-30.0, 0.0)) # both inside: the nearer
self.assertEqual(reach(-170.0, (-180.0, 180.0)), (-150.0, 0.0))
self.assertEqual(reach(300.0, (180.0, 360.0)), (330.0, 0.0))
with self.assertRaisesRegex(core.KitError, r"socket 's' on parent socket 's': the rolls that bring the point to 0\.500000 m, -150 and -30, are outside the joint's limits 0 to 90$"):
reach(0.0, (0.0, 90.0))
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))
@unittest.skipIf(np is None, "numpy is not installed")
class StructureTests(unittest.TestCase):
"""core's sweep, band, crossings, resample and spans: what brokkr_kitbash.ribs builds a frame from. Every reading is
@ -1813,9 +1997,147 @@ 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.close",
"brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.apply", "brokkr_kitbash.ribs",
"brokkr_kitbash.shell"]
"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"]
class CageTests(unittest.TestCase):
"""core.sheet's free form: a cage of vertices and faces of 3 or 4 sides. Exact arithmetic: each assertion is
the built value and names the mutant it kills."""
@staticmethod
def fan(quads: int, lift=0.2):
"""`quads` quads round vertex 0, counter-clockwise seen from +z (their outside): 0 has valence `quads`."""
ring = [[math.cos(k * math.pi / quads), math.sin(k * math.pi / quads), 0.0] for k in range(2 * quads)]
return [[0.0, 0.0, lift]] + ring, [[0, 2 * k + 1, 2 * k + 2, (2 * k + 2) % (2 * quads) + 1] for k in range(quads)]
PYRAMID = ([[0.0, 0.0, 0.5], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [-1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [1.0, 0.0, -1.0], [0.0, 1.0, -1.0]],
[[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [2, 1, 5, 6]]) # four triangles round an apex of valence 4, a quad hung under one edge
def refused(self, pattern, **sheet):
with self.assertRaisesRegex(core.KitError, pattern):
core.sheet(sheet)
def test_a_free_cage_stating_a_loft_is_the_loft(self):
"""free-cage-grid-equals-loft. C1 (a second path that orders, winds or creases differently): the same Sheet,
array for array, open and closed."""
for extra in ({"creases": [{"ring": 1, "from": 0, "to": 3, "weight": 0.5}, {"column": 2, "from": 0, "to": 2, "weight": 0.25}], "rim": 0.75},
{"closed": True, "creases": [{"ring": 1, "from": 0, "to": 4, "weight": 1.0}]}, {"flip": True, "rim": 0.0}):
loft = core.sheet({"rings": SheetTests.rings(3, 4), **extra})
runs = [[int(a), int(b), w] for (a, b), w in zip(loft.creases.tolist(), loft.weights.tolist())]
free = core.sheet({"verts": loft.V.tolist(), "faces": loft.faces.reshape(-1, 4).tolist(), "creases": runs, "rim": 0.0})
for field in ("V", "faces", "counts", "smooth", "creases", "weights", "corners", "corner_weights", "poles"):
self.assertEqual(getattr(free, field).tolist(), getattr(loft, field).tolist(), (field, extra))
self.assertEqual((free.rings, free.points, free.triangles, loft.triangles, len(loft.poles)), (None, None, 0, 0, 0))
self.assertEqual((free.boundary, loft.boundary), ("ALL", "PRESERVE_CORNERS")) # the one field the form decides: a free cage's boundary is smoothed as a hand-modelled cage's
self.assertEqual(core.cage_report(free), core.cage_report(loft))
plain = core.sheet({"rings": SheetTests.rings(3, 4)}) # rim defaults to 1 on the boundary edges of either form
free = core.sheet({"verts": plain.V.tolist(), "faces": plain.faces.reshape(-1, 4).tolist()})
self.assertEqual((free.creases.tolist(), free.weights.tolist()), (plain.creases.tolist(), plain.weights.tolist()))
self.assertEqual(core.cage_report(free), {"cageVerts": 12, "cageFaces": 6, "triangles": 0, "creases": 10, "corners": 0, "poles": {}, "closed": False})
def test_a_mirrored_cage_shares_its_seam(self):
"""free-cage-mirror. C2 (the seam duplicated: an open cage; the reflected faces not reversed): seam vertices
within SEAM_REL of the extent are snapped and shared, the rest reflected, and creases, corners and poles land
on both halves. S1 (the seam distance in metres, not of the extent): the same cage at 1% and at 100 times builds alike."""
verts = [[0.0, 0.0, 0.0], [0.004, 0.0, 1.0], [0.5, 0.0, 0.0], [0.5, 0.0, 1.0], [1.0, 0.2, 0.0], [1.0, 0.2, 1.0]]
faces = [[0, 1, 3, 2], [2, 3, 5, 4]] # outside is +y
built = core.sheet({"verts": verts, "faces": faces, "mirror": True, "creases": [[2, 3, 0.75]], "corners": [[4, 0.5], [0, 1.0]], "rim": 0.0})
self.assertEqual((len(built.V), built.counts.tolist()), (10, [4, 4, 4, 4]))
self.assertEqual(built.V[:2, 0].tolist(), [0.0, 0.0]) # 0.004 of an extent of 1 is inside SEAM_REL: snapped
for scale in (0.01, 100.0): # S1: at 1 cm an absolute 5 mm takes face 0 for the plane's; at 100 m it leaves vertex 1 off the seam
scaled = core.sheet({"verts": [[c * scale for c in v] for v in verts], "faces": faces, "mirror": True, "rim": 0.0})
self.assertEqual((len(scaled.V), scaled.V[:2, 0].tolist(), scaled.faces.tolist()), (10, [0.0, 0.0], built.faces.tolist()), scale)
turned = core.sheet({"verts": verts, "faces": faces, "mirror": True, "flip": True, "rim": 0.0}) # F1 (flip ignored on a free cage): every face reversed, the reflected ones too
self.assertEqual(turned.faces.reshape(-1, 4).tolist(), [[2, 3, 1, 0], [4, 5, 3, 2], [0, 1, 7, 6], [6, 7, 9, 8]])
self.assertEqual((turned.V.tolist(), SheetTests.weights(turned)), (built.V.tolist(), {}))
self.assertEqual(built.V[6:].tolist(), [[-0.5, 0.0, 0.0], [-0.5, 0.0, 1.0], [-1.0, 0.2, 0.0], [-1.0, 0.2, 1.0]])
self.assertEqual(built.faces.reshape(-1, 4).tolist(), [[0, 1, 3, 2], [2, 3, 5, 4], [6, 7, 1, 0], [8, 9, 7, 6]])
V = built.V[built.faces.reshape(-1, 4)]
self.assertTrue((np.cross(V[:, 1] - V[:, 0], V[:, 3] - V[:, 0])[:, 1] > 0).all()) # both halves face +y
self.assertEqual(SheetTests.weights(built), {(2, 3): 0.75, (6, 7): 0.75})
self.assertEqual((built.corners.tolist(), built.corner_weights.tolist()), ([0, 4, 8], [1.0, 0.5, 0.5]))
edges, boundary, _, _ = core._cage_facts(len(built.V), built.faces, built.counts)
self.assertEqual((edges[(0, 1)], (0, 1) in boundary, len(boundary)), (2, False, 10)) # the seam edge is interior
verts[1][0] = 0.006 # outside the seam: reflected, not shared, so face 0 and its reflection meet at vertex 0 alone
self.refused(r"sheet\.verts\[0\] is pinched: its faces meet only at it, in 2 fans \(faces 0 \| 0 mirrored\)", verts=verts, faces=faces, mirror=True, poles=[0])
verts[0][0] = 0.006 # both off the plane: two halves 12 mm apart, no vertex shared
apart = core.sheet({"verts": verts, "faces": faces, "mirror": True})
self.assertEqual((len(apart.V), apart.V[6:8].tolist(), apart.poles.tolist()), (12, [[-0.006, 0.0, 0.0], [-0.006, 0.0, 1.0]], []))
verts[0][0] = 0.0
fan_verts, fan_faces = self.fan(3)
aside = core.sheet({"verts": [[x + 2.0, y, z] for x, y, z in fan_verts], "faces": fan_faces, "mirror": True, "poles": [0]})
self.assertEqual((aside.poles.tolist(), core.cage_report(aside)["poles"]), ([0, 7], {"3": 2})) # a pole off the seam stands on both halves
left = core.sheet({"verts": [[-x, y, z] for x, y, z in verts[:1] + [[0.0, 0.0, 1.0]] + verts[2:]], "faces": [face[::-1] for face in faces], "mirror": True})
self.assertEqual(left.V[6:, 0].tolist(), [0.5, 0.5, 1.0, 1.0]) # authored on -x, reflected to +x
verts[5][0] = -1.0
self.refused(r"sheet\.verts\[5\] has x = -1: a mirrored cage is authored on one side", verts=verts, faces=faces, mirror=True)
def test_triangles_are_counted_as_three_quads(self):
"""free-cage-triangle-counts. C3 (every face counted as a quad): q quads and t triangles subdivide to
q * 4^L + t * 3 * 4^(L-1) faces."""
verts, faces = self.PYRAMID
built = core.sheet({"verts": verts, "faces": faces, "poles": [1, 2]})
self.assertEqual((built.counts.tolist(), built.triangles, len(built.faces)), ([3, 3, 3, 3, 4], 4, 16))
self.assertEqual([core.subdivided_faces(built, levels) for levels in (1, 2, 3)], [4 * 3 + 4, 4 * 12 + 16, 4 * 48 + 64])
self.assertEqual(core.cage_report(built), {"cageVerts": 7, "cageFaces": 5, "triangles": 4, "creases": 6, "corners": 0, "poles": {"4": 2}, "closed": False})
loft = core.sheet({"rings": SheetTests.rings(3, 4)})
self.assertEqual([core.subdivided_faces(loft, levels) for levels in (1, 3)], [24, 384])
def test_poles_are_declared_or_refused(self):
"""free-cage-pole-gate. C4 (a gate that compares counts, or skips the check): the declared set must be the
computed set, vertex for vertex."""
for quads in (3, 5):
verts, faces = self.fan(quads)
self.refused(rf"sheet\.poles lacks vertex 0 \(valence {quads}\)", verts=verts, faces=faces)
self.refused(rf"sheet\.poles lacks vertex 0 \(valence {quads}\)", verts=verts, faces=faces, poles=[1]) # one named, one computed: the count agrees, the set does not
built = core.sheet({"verts": verts, "faces": faces, "poles": [0]})
self.assertEqual((built.poles.tolist(), core.cage_report(built)["poles"]), ([0], {str(quads): 1}))
verts, faces = self.fan(4) # valence 4 at the centre; the rim has valence 2 and 3: no pole anywhere
self.assertEqual(core.sheet({"verts": verts, "faces": faces}).poles.tolist(), [])
self.refused(r"sheet\.poles\[0\] names vertex 0 \(valence 4\), which is no pole", verts=verts, faces=faces, poles=[0])
self.refused(r"sheet\.poles\[0\] names vertex 2 \(valence 2, on the boundary\), which is no pole", verts=verts, faces=faces, poles=[2])
self.refused(r"sheet\.poles\[1\] names vertex 0 twice", verts=self.fan(3)[0], faces=self.fan(3)[1], poles=[0, 0])
verts, faces = self.PYRAMID
self.refused(r"sheet\.poles lacks vertex 1 \(valence 4, on the boundary\), vertex 2 \(valence 4, on the boundary\)", verts=verts, faces=faces)
def test_a_bad_cage_is_refused_by_field_and_index(self):
"""free-cage-refusals. C5 (a check dropped): each fault is refused, naming where."""
verts, faces = self.fan(4)
ok = {"verts": verts, "faces": faces}
self.refused(r"sheet\.verts\[9\] is in no face", **{**ok, "verts": verts + [[5.0, 5.0, 5.0]]})
self.refused(r"sheet\.faces\[1\] must be 3 or 4 vertex indices, not 2", **{**ok, "faces": [faces[0], [0, 3]] + faces[1:]})
self.refused(r"sheet\.faces\[0\] must be 3 or 4 vertex indices, not 5", **{**ok, "faces": [[0, 1, 2, 3, 4]] + faces[1:]})
self.refused(r"sheet\.faces\[2\] names vertex 5 twice", **{**ok, "faces": faces[:2] + [[0, 5, 5, 7]] + faces[3:]})
self.refused(r"sheet\.faces\[3\]\[2\] must be a whole number from 0 to 8, not 9", **{**ok, "faces": faces[:3] + [[0, 7, 9, 1]]})
self.refused(r"sheet\.faces\[4\] has the vertices of sheet\.faces\[0\]: a duplicate face", **{**ok, "faces": faces + [[3, 2, 1, 0]]})
wing = [[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 1.0], [1.0, 0.0, 0.0], [-1.0, 0.0, 0.0], [-1.0, 0.0, 1.0], [0.0, 1.0, 0.0], [0.0, 1.0, 1.0]]
self.refused(r"the edge between vertices 0 and 1 is in 3 faces \(0, 1, 2\)", verts=wing, faces=[[0, 1, 2, 3], [1, 0, 4, 5], [0, 1, 7, 6]])
self.refused(r"sheet\.faces\[1\] crosses the edge between vertices 0 and 1 the same way as sheet\.faces\[0\]", verts=wing[:6], faces=[[0, 1, 2, 3], [0, 1, 5, 4]])
self.refused(r"sheet\.faces\[0\] and sheet\.faces\[1\] share the edge between vertices 0 and 1, which lies on the mirror plane",
verts=wing[:4] + [[1.0, 1.0, 0.0], [1.0, 1.0, 1.0]], faces=[[0, 1, 2, 3], [1, 0, 4, 5]], mirror=True)
self.refused(r"sheet\.faces\[0\] lies on the mirror plane", verts=[[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 1.0, 1.0], [1.0, 0.0, 0.0]], faces=[[0, 1, 2], [0, 3, 1]], mirror=True)
self.refused(r"sheet\.faces\[1\] has area 0 m2, under 1e-08: a collapsed face",
verts=[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [2.0, 0.0, 0.0], [3.0, 0.0, 0.0]], faces=[[0, 1, 2], [1, 3, 4]])
self.refused(r"sheet\.faces\[0\] has area 0 m2, under 1e-08: a collapsed face", verts=[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [2.0, 0.0, 0.0], [3.0, 0.0, 0.0]], faces=[[0, 1, 2, 3]])
dart = core.sheet({"verts": [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [-1.0, 0.0, 0.0]], "faces": [[0, 1, 2, 3]]}) # Q1 (a quad's area read from its first corner alone): vertex 0 stands on the line from 3 to 1, and the quad has area 1
self.assertEqual((dart.counts.tolist(), dart.poles.tolist()), ([4], []))
self.refused(r"sheet\.verts\[2\] is pinched: its faces meet only at it, in 2 fans \(faces 0 \| 1\)\. A vertex's faces are one fan", # P1 (the fan check dropped): its valence 4 declared, it was taken
verts=[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0], [2.0, 1.0, 0.0], [2.0, 2.0, 0.0], [1.0, 2.0, 0.0]], faces=[[0, 1, 2, 3], [2, 4, 5, 6]], poles=[2])
self.refused(r"sheet states both rings and verts", rings=SheetTests.rings(), **ok)
self.refused(r"sheet lacks 'rings' and 'verts'", creases=[])
self.refused(r"sheet\.verts must be 4 to 256 vertices, not 257", verts=[[0.0, 0.0, float(k)] for k in range(257)], faces=faces)
self.refused(r"sheet\.verts must be 4 to 256 vertices, not 3", verts=verts[:3], faces=[[0, 1, 2]])
self.refused(r"sheet\.verts\[2\] must be three finite numbers", **{**ok, "verts": verts[:2] + [[0.0, float("nan"), 0.0]] + verts[3:]})
self.refused(r"sheet has no key 'closed'", closed=True, **ok)
self.refused(r"sheet\.creases\[0\]: vertices 1 and 5 share no face's edge", creases=[[1, 5, 1.0]], **ok)
self.refused(r"sheet\.creases\[1\] gives an edge weight 0\.5 that sheet\.creases\[0\] gives 1", creases=[[0, 1, 1.0], [1, 0, 0.5]], **ok)
self.refused(r"sheet\.creases\[0\]\[2\] must be a number from 0 to 1, not 2", creases=[[0, 1, 2]], **ok)
self.refused(r"sheet\.corners\[0\] must be \[vertex, weight\]", corners=[[0]], **ok)
self.refused(r"sheet\.creases\[0\] must be \{ring, from, to, weight\}", rings=SheetTests.rings(), creases=[[0, 1, 1.0]]) # the loft keeps its own crease form
self.refused(r"sheet has no key 'poles'", rings=SheetTests.rings(), poles=[])
class HostFileTests(unittest.TestCase):
@ -1861,7 +2183,8 @@ class HostFileTests(unittest.TestCase):
self.assertEqual(at.validate(boolean, host)["operation"], "DIFFERENCE")
for bad in ({**attach, "roll": 360.5}, {**attach, "socket": "a b"}, {**attach, "parent_socket": ""}, {**attach, "matrix": [1, 0, 0]},
{**boolean, "operation": "SLICE"}, {**boolean, "solver": "EXACT"}, {**boolean, "cutter": ""},
{**envelope, "action": "brokkr_kitbash.apply"}, {**envelope, "action": "brokkr_kitbash.detach", "object_name": "x" * 64},
{**envelope, "action": "brokkr_kitbash.freeze"}, {**envelope, "action": "brokkr_kitbash.thaw", "object_name": ""},
{**envelope, "action": "brokkr_kitbash.detach", "object_name": "x" * 64},
{**close, "socket": "end b"}, {**close, "other_socket": "x" * 33}, {**close, "other_name": ""}, {**close, "roll": 10},
{k: v for k, v in close.items() if k != "other_socket"}):
with self.assertRaises(at.IntentInvalid, msg=str(bad)):
@ -1885,7 +2208,7 @@ 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.shell", "levels"), ("brokkr_kitbash.hose", "count")])
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])
@ -1935,7 +2258,8 @@ class OwnershipTests(unittest.TestCase):
r"hide_render|hide_viewport|display_type", # a cutter's visibility is setObjectVisibility's
r"kit_parent_name|kit_parent\b|matrix_world_stored", # obj.parent has no second owner
r"SCREW|\"ARRAY\"|spin\(", # core makes every vertex: no modifier or bmesh op makes kit geometry
r"Kit Boolean |operand_type\s*=\s*[\"']OBJECT") # cutters cut through one collection Boolean per operation, never a modifier each
r"Kit Boolean |operand_type\s*=\s*[\"']OBJECT", # cutters cut through one collection Boolean per operation, never a modifier each
r"kit_axis|kit_order|kit_parent_joint") # a joint's axis is its parent socket's z and its order the parent tree: neither is stored
CORE = r"^import bpy|^from bpy|^import bmesh"
SCHEMAS = r"brokkr\.kit\.v0"
@ -1943,7 +2267,7 @@ class OwnershipTests(unittest.TestCase):
return {p.name: p.read_text(encoding="utf-8") for p in sorted((SURFACE / "brokkr_kitbash").rglob("*")) if p.suffix in (".py", ".json")}
def test_no_pattern_matches(self):
self.assertEqual(sorted(self.sources()), ["__init__.py", "brokkr_actions.json", "core.py", "cutters.v0.json", "frame.v0.json", "mechanical.v0.json"])
self.assertEqual(sorted(self.sources()), ["__init__.py", "brokkr_actions.json", "core.py", "cutters.v0.json", "frame.v0.json", "mechanical.v0.json", "ram.py", "route.py"])
for pattern in self.PACKAGE:
for name, text in self.sources().items():
if pattern is self.PACKAGE[2] and name == "__init__.py":
@ -1960,25 +2284,40 @@ 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_only_cut_boolean_and_apply_evaluate_a_modifier_stack(self):
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."""
source = self.sources()["__init__.py"]
self.assertEqual(source.count("evaluated_get("), 1)
self.assertIn("evaluated_get(", source.split("def evaluated_of(")[1].split("\n\n\n")[0])
bodies = {body.split("(")[0]: body.split("\n\n\n")[0] for body in source.split("class BROKKR_KITBASH_OT_")[1:]}
self.assertEqual([name for name, body in bodies.items() if "evaluated_of(" in body], ["boolean", "apply", "ribs"])
self.assertEqual(source.count("evaluated_of("), 7) # its def, evaluable, boolean, apply, and ribs for the designed surface, for the plate's two faces and for its holes
self.assertEqual([name for name, body in bodies.items() if "evaluated_of(" in body], ["boolean", "ribs"])
self.assertEqual(source.count("evaluated_of("), 6) # its def, evaluable, boolean, and ribs for the designed surface, for the plate's two faces and for its holes
self.assertIn("evaluated_of(", source.split("def evaluable(")[1].split("\n\n\n")[0])
place = source.split("def place_cutters(")[1].split("\n\n\n")[0] # cut and cut_many place through it: one evaluation, with the Booleans off
self.assertEqual((place.count("evaluable("), place.count("evaluated_of(")), (1, 0))
self.assertLess(place.index("modifier.show_viewport = False"), place.index("evaluable("))
self.assertLess(place.index("evaluable("), place.index("modifier.show_viewport = True"))
# unevaluable-target: every action that evaluates refuses an object Blender does not evaluate before its first write
for body, first_write in ((place, "bpy.data.meshes.new("), (bodies["boolean"], ".objects.link("), (bodies["apply"], "bpy.data.meshes.new_from_object("),
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()")):
self.assertLess(body.index("evaluable("), body.index(first_write))
self.assertEqual([name for name, body in bodies.items() if "evaluable(" in body], ["boolean", "apply", "ribs", "shell"])
self.assertEqual([name for name, body in bodies.items() if "evaluable(" in body], ["boolean", "freeze", "ribs", "shell", "hose"])
# frozen: thaw evaluates nothing, and every action that writes a mesh or a modifier stack refuses a frozen object before its first write
for call in ("evaluable(", "evaluated_of(", "to_mesh(", "depsgraph", "view_layer.update"):
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(")):
self.assertLess(body.index("live("), body.index(first_write))
self.assertEqual(source.count("live("), 8) # its def and the seven callers above
# 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 = "
self.assertEqual(re.findall(writes, source), re.findall(writes, hold))
self.assertEqual(len(re.findall(writes, hold)), 6)
self.assertEqual(("hold(obj, frozen)" in bodies["freeze"], "hold(obj)" in bodies["thaw"], "obj.data =" in bodies["freeze"] + bodies["thaw"]), (True, True, False))
self.assertEqual(re.findall(r"handlers\.(\w+)", source.split("SETTLED_ON = ")[1].split("\n")[0]),["depsgraph_update_post", "save_pre"])
ribs = bodies["ribs"] # every refusal before the ribs object is written, and the cage's modifiers shown again whatever happened
self.assertLess(ribs.rindex("raise Refused("), ribs.index("mesh = bpy.data.meshes.new(self.ribs_name)"))
self.assertLess(ribs.index("finally:"), ribs.index("modifier.show_viewport = True"))
@ -1993,7 +2332,7 @@ class OwnershipTests(unittest.TestCase):
self.assertEqual((shell.count("evaluable("), shell.count("folded_faces("), shell.count("self.count_folds")), (1, 1, 2))
self.assertLess(shell.index("if self.count_folds:"), shell.index("with self.wall_alone(obj):"))
self.assertLess(shell.index("with self.wall_alone(obj):"), shell.index("evaluable("))
self.assertIn("self.folded_faces(context, obj, cage_faces * 4 ** self.levels) if self.count_folds else None", shell)
self.assertIn("self.folded_faces(context, obj, subdivided) if self.count_folds else None", shell)
self.assertLess(count.index("wall_alone(shell):"), count.index("evaluable("))
self.assertEqual((count.count("evaluable("), count.count("to_mesh("), source.count("folded_faces("), source.count("wall_alone(")), (1, 1, 2, 3))
self.assertLess(alone.index("finally:"), alone.index("modifier.show_viewport = True"))
@ -2026,18 +2365,78 @@ class OwnershipTests(unittest.TestCase):
self.assertEqual(len(re.findall(rf"(?<!['\"])\b{name}\b(?!['\"])" if name[0] != '"' else name, source.replace(body, ""))), 0 if name[0] == '"' else 1, name)
self.assertIn(name, body)
def test_only_hose_writes_kit_hose(self):
"""kit_hose is the request a hose was routed from: hose assigns it once, after its last refusal, and outside
hose it is named only by its constant's line. The path is route.py's, which needs no Blender; every tube is
core.sweep's: no curve object, no hide flag and no deleted object stand in for either (mutant H11: a write
before the range's refusal)."""
source = self.sources()["__init__.py"]
body = source.split("class BROKKR_KITBASH_OT_hose(")[1].split("class BROKKR_KITBASH_OT_")[0]
writes = re.findall(r'[^\n]*\[(?:HOSE|"kit_hose")\]\s*=(?!=)[^\n]*', source)
self.assertEqual(len(writes), 1)
self.assertIn(writes[0], body)
self.assertEqual(len(re.findall(r'\bHOSE\b|"kit_hose"', source.replace(body, ""))), 2) # outside hose: the constant's own line, its name and its value
self.assertEqual(re.findall(r"\[HOSE\]|HOSE not in hose|HOSE in \w+", body), ["HOSE not in hose", "[HOSE]"])
work = body.split(" @staticmethod")[0]
first = min(work.index(write) for write in ("clear_geometry()", "bpy.data.meshes.new(", "write_mesh(", ".parent =", "[HOSE] ="))
self.assertLess(work.rindex("raise Refused("), first) # every refusal before any write
for call in ("self.seed(", "self.routed(", "route.leaves(", "self.built(", "self.trees(", "self.crossed(", "self.rows()", "self.frame("):
self.assertLess(work.rindex(call), first, call)
for write in ("clear_geometry()", "bpy.data.meshes.new(", "write_mesh(", ".parent =", "[HOSE] ="): # what work calls to seed, refine and shape a route writes nothing
self.assertEqual(body.count(write), work.count(write), write)
for owner, call in (("seed", "route.leg("), ("routed", "route.relax("), ("routed", "self.shaped(")):
self.assertIn(call, body.split(f" def {owner}(")[1].split("\n def ")[0], call)
shaped = body.split(" def shaped(")[1].split(" def built(")[0]
self.assertLess(shaped.index("route.fillet("), shaped.index("route.verify("))
self.assertLess(shaped.index("route.verify("), shaped.index("route.passes("))
self.assertEqual((body.count("route.fillet("), body.count("route.verify("), body.count("route.passes("), body.count("route.leg(")), (1, 1, 1, 1)) # every leg and both sags through one path
for pattern in (r"bevel_depth|curves\.new|\"CURVE\"", r"objects\.remove|meshes\.remove|to_mesh\(", r"scene\.frame_set|view_layer\.update|write_connection\(|\[ROLL\]"):
self.assertIsNone(re.search(pattern, body), pattern) # no curve object, nothing deleted or baked, and no part posed to measure a roll
self.assertIsNone(re.search(r"bevel_depth|curves\.new|\"CURVE\"", source))
self.assertIsNone(re.search(r"^import bpy|^from bpy|^import bmesh|mathutils", self.sources()["route.py"], re.M))
self.assertEqual(len(re.findall(r"core\.sweep\(", body)), 5) # a hose, two collars, a strap and a pad
self.assertIsNone(re.search(r"def sweep|sweep\(", self.sources()["route.py"])) # route.py sweeps nothing
def test_the_hose_row_takes_its_bounds(self):
host = [{**row, "host": "brokkr_kitbash"} for row in json.loads((SURFACE / "brokkr_kitbash" / "brokkr_actions.json").read_text(encoding="utf-8"))["actions"]]
hose = {"schema": "brokkr.blender.command_intent.v0", "commandId": "t-1", "requestedBy": "test/driver", "action": "brokkr_kitbash.hose", "object_name": "Hose",
"start": "Ram:port_cap", "end": "Feed"}
admitted = at.validate(hose, host)
self.assertEqual([admitted[k] for k in ("count", "radius", "spread", "clearance", "bend", "step", "sag", "clamps", "joint")], [1, 0.01, 0, 0.01, 4, 0.02, 1, "[]", ""])
at.validate({**hose, "count": 8, "radius": 0.003, "step": 0.005, "sag": 0, "joint": '{"socket": "Shin:end_a_back", "standoff": 0.05, "range": [-120, 10]}'}, host)
for bad in ({**hose, "count": 9}, {**hose, "count": 1.5}, {**hose, "radius": 0.002}, {**hose, "step": 0.004}, {**hose, "bend": 0.5}, {**hose, "sag": 9}, {**hose, "clamps": ""},
{**hose, "clamps": "[" + " " * 4000}, {**hose, "joint": "{" + " " * 4000}, {k: v for k, v in hose.items() if k != "end"}, {**hose, "start": ""}, {**hose, "object_name": "x" * 64},
{**hose, "range": [0, 1]}):
with self.assertRaises(at.IntentInvalid, msg=str(bad)[:200]):
at.validate(bad, host)
def test_only_write_connection_writes_the_roll(self):
"""one-writer. kit_roll is the one statement of a connection's roll, and write_connection its one writer: attach
and pose (roll, aim and reach) call it; set_params and the reports read the roll and never write it back.
Mutant R7 (attach keeps its own inline write beside write_connection)."""
and pose (roll, aim, reach, slide and joint) call it; set_params and the reports read the roll and never write
it back. Mutant R7 (attach keeps its own inline write beside write_connection). The joint record (kit_slide,
kit_min, kit_max, kit_mechanism, kit_compliance) is written there too and nowhere else: its names are read by
link and joint_record, cleared by detach, and no other function names them; the hose keeps no roll range of
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] = stated"])
self.assertIn(writes[0], 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_connection(")[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)
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"])
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))
for name in ("roll", "aim", "reach"):
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"]))
@ -2056,8 +2455,8 @@ class OwnershipTests(unittest.TestCase):
assigned = re.findall(rf"[^\n]*\[{keys}\][^\n=]*=(?!=)[^\n]*", source)
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, 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, 1, True))
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(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"]))
@ -2067,7 +2466,7 @@ class OwnershipTests(unittest.TestCase):
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',
'obj.modifiers.new("Turn", "SCREW")', 'modifier.operand_type = "OBJECT"')
'obj.modifiers.new("Turn", "SCREW")', 'modifier.operand_type = "OBJECT"', 'child["kit_axis"] = list(axis)')
self.assertIsNotNone(re.search(self.PACKAGE[6], 'obj.modifiers.new("Kit Boolean " + cutter.name, "BOOLEAN")'))
for text in ('obj.modifiers.new("Bolts", "ARRAY")', "bmesh.ops.spin(bm, geom=geom)"):
self.assertIsNotNone(re.search(self.PACKAGE[5], text))

View file

@ -609,6 +609,16 @@ class NodeActionTests(unittest.TestCase):
self.assertIn("setModifierInput", receipt["message"])
self.assertFalse(hasattr(host, "custom"))
def test_custom_property_in_the_kit_namespace_is_refused(self):
self.group()
host = self.bpy.data.objects["Host"]
for name in ("kit_frozen", "customProperties.kit_frozen", "kit_roll", "kit_"):
receipt = self.refused(action="setObjectCustomProperty", targetObjectName="Host", propertyName=name, value=3)
self.assertIn("brokkr_kitbash's own state (kit_*)", receipt["message"])
self.assertFalse(hasattr(host, "custom"))
self.accepted(action="setObjectCustomProperty", targetObjectName="Host", propertyName="kitchen", value=3)
self.assertEqual(host.custom, ("kitchen", 3))
def test_custom_property_sharing_only_a_display_name_is_an_ordinary_property(self):
self.group()
host = self.bpy.data.objects["Host"]

File diff suppressed because it is too large Load diff

View file

@ -15,6 +15,8 @@ tolerances round a known truth that no mutant claims. The mutants, each run once
M6 the turned group is not turned test_a_turned_torso_is_recovered_as_twist
M7 square holds the yaw along y only test_square_solves_elevations_along_both_axes
M13 the walk stops after 20 steps each way test_a_wide_band_is_walked_to_its_end
G10, G01 core.EXACT ten times looser, ten tighter test_the_exact_gates_sit_at_a_billionth_of_the_marks_extent
PL1, PL3, PL4, PL5 the band and lens_determined test_a_plane_tilted_from_square_on_never_reports_a_lens_it_does_not_decide
"""
from __future__ import annotations
@ -117,19 +119,20 @@ class SolveTests(unittest.TestCase):
self.assertAlmostEqual(s["c"][0], 640.0, delta=5.0)
def test_the_band_is_an_equal_error_band(self):
"""band-is-equal-error: a build 4 cm off. Every lens in the band refits within BAND of the best rms, and one
step past each end does not."""
"""band-is-equal-error: a build 4 cm off. Every lens inside the band refits within BAND of the best rms; the
band's ends are the first lenses that do not (PL4, a band that stops at the last lens that fits, has ends
that fit)."""
world, pixels = marks(self.oblique, self.points, build=0.04)
s = core.solve(world, pixels, BOX, model="upright")
low, high = s["lens_band"]
self.assertLess(low, s["lens"] * 0.95)
self.assertGreater(high, s["lens"] * 1.05)
for lens in (low, math.sqrt(low * s["lens"]), math.sqrt(high * s["lens"]), high):
for lens in (low * math.exp(core.STEP), math.sqrt(low * s["lens"]), math.sqrt(high * s["lens"]), high * math.exp(-core.STEP)):
self.assertLessEqual(core.solve(world, pixels, BOX, model="upright", lens=lens)["rms"], core.BAND * s["rms"] + 1e-6, lens)
for lens in (low * math.exp(-core.STEP), high * math.exp(core.STEP)):
for lens in (low, high):
self.assertGreater(core.solve(world, pixels, BOX, model="upright", lens=lens)["rms"], core.BAND * s["rms"], lens)
held = core.solve(world, pixels, BOX, model="upright", lens=low)
self.assertEqual((held["lens"], held["lens_band"], held["lens_at_bound"]), (low, [low, low], None))
self.assertEqual((held["lens"], held["lens_band"], held["lens_at_bound"], held["lens_determined"]), (low, [low, low], None, None))
def test_the_band_is_walked_from_the_last_solve(self):
"""M3: each step of the walk is one solve started at the one before; restarting from the grid costs 16 per
@ -211,31 +214,172 @@ class SolveTests(unittest.TestCase):
self.assertTrue(issubclass(core.ReferenceFitError, ValueError))
def test_marks_that_decide_no_camera_are_refused(self):
"""refusals: marks with no extent, in a line or in a plane are refused by which they are before any solve
(one pixel for every name was a bare ValueError, one world point a record of NaN). A plane is enough once
the lens is held and the centre is not solved."""
"""refusals: marks with no extent or in a line and a plane asked for its centre are refused by which they
are before any solve (one pixel for every name was a bare ValueError, one world point a record of NaN)."""
solved, lm = [], core.lm
core.lm = lambda *args, **kwargs: solved.append(1) or lm(*args, **kwargs)
self.addCleanup(setattr, core, "lm", lm)
plane = np.c_[self.points[:, :2], np.zeros(13)]
on_plane = dict(zip(NAMES, plane.tolist())), dict(zip(NAMES, core.project(self.oblique, plane).tolist()))
in_plane = dict(zip(NAMES, plane.tolist())), dict(zip(NAMES, core.project(self.oblique, plane).tolist()))
square_on = in_plane[0], dict(zip(NAMES, core.project(camera(plane, 35, 90, 50), plane).tolist()))
line = dict(zip(NAMES, np.outer(np.arange(13.0), [1.0, 2.0, 0.5]).tolist()))
cases = (((self.world, {k: [500.0, 400.0] for k in NAMES}), {}, "1 different pixels"),
(({k: [1.0, 2.0, 3.0] for k in NAMES}, self.pixels), {}, "1 different world points"),
((self.world, {**self.pixels, **{k: self.pixels["p0"] for k in NAMES[:9]}}), {}, "5 different pixels are marked; six are needed ('p0' and 'p1'"),
((self.world, {k: [100.0 + 10 * i, 200.0 + 5 * i] for i, k in enumerate(NAMES)}), {}, "pixels lie on one line"),
((line, self.pixels), {}, "world points lie on one line"),
(on_plane, {}, "one plane"), (on_plane, {"model": "upright"}, "one plane"), (on_plane, {"model": "free", "lens": 50.0}, "one plane"))
(in_plane, {"model": "free"}, "one plane, which does not decide the centre"), (in_plane, {"model": "free", "lens": 50.0}, "does not decide the centre"))
for args, kwargs, said in cases:
with self.assertRaises(core.ReferenceFitError) as caught:
core.solve(*args, BOX, **kwargs)
self.assertIn(said, str(caught.exception))
self.assertEqual(solved, [])
held = core.solve(*on_plane, BOX, model="upright", lens=50.0)
held = core.solve(*square_on, BOX, model="upright", lens=50.0) # with the lens held a plane decides the rest, square-on too
self.assertLess(held["rms"], 1e-3)
self.assertAlmostEqual(held["azimuth"], 35.0, delta=0.01)
self.assertAlmostEqual(held["elevation"], 90.0, delta=0.01)
self.assertAlmostEqual(held["plane"], 0.0, delta=0.01)
self.assertNotIn("NaN", json.dumps(held))
def test_a_plane_seen_obliquely_decides_the_lens_and_says_it_is_a_plane(self):
"""plane-honest: world points in one plane are solved, not refused: the plane's foreshortening decides the
lens (Zhang's calibration from a plane), "plane" says how far from square-on the view is, and auto leaves
the free model untried, since a plane never decides the centre."""
plane = np.c_[self.points[:, :2], np.zeros(13)]
world = dict(zip(NAMES, plane.tolist()))
solved = core.solve(world, dict(zip(NAMES, core.project(self.oblique, plane).tolist())), BOX)
self.assertAlmostEqual(solved["lens"], 50.0, delta=0.01)
self.assertAlmostEqual(solved["plane"], 70.0, delta=0.01)
self.assertEqual(sorted(solved["tried"]), ["rolled", "upright"])
self.assertLess(place_error(solved, self.oblique), 1e-3)
self.assertEqual((solved["planarity"], solved["lens_determined"]), (0.0, True))
self.assertIsNone(self.auto["plane"])
self.assertGreater(self.auto["planarity"], core.PLANAR)
self.assertIs(self.auto["lens_determined"], True)
def test_a_plane_tilted_from_square_on_never_reports_a_lens_it_does_not_decide(self):
"""plane-sweep: a plane of thirteen marks seen through a 50 mm lens from square-on to 30 degrees off it,
each mark a pixel off (a second seed at 0 and 3 degrees), and from square-on and a hair off it with exact marks. At every tilt the
band holds 50 mm; where the lens is called determined the headline is within a quarter of 50 mm, and it is
never called determined within 3 degrees of square-on, where the headlines read 4 to 4000 mm; from 15
degrees on it is. Truth tolerances, no bound a mutant claims by a reading; the mutants die by which
assertion: PL1 (a band open at one end stays closed at the other) at square-on, seed 0, band [309, 4000];
PL3 (no FINE floor under the band's error) on the exact marks square-on, band [192, 2855]; PL4 (the band
stops at the last lens that fits) at 6 degrees, band [51, 69];
PL5 (DECIDED 10) at 3 degrees, seed 0, 90 mm called determined."""
plane = np.c_[self.points[:, :2], np.zeros(13)]
world = dict(zip(NAMES, plane.tolist()))
cases = [(tilt, 1.0, 0) for tilt in (0.0, 3.0, 6.0, 10.0, 15.0, 20.0, 30.0)] + [(0.0, 1.0, 1), (3.0, 1.0, 1), (0.0, 0.0, 0), (1e-5, 0.0, 0)]
for tilt, noise, seed in cases:
drawn = core.project(camera(plane, 35, 90.0 - tilt, 50), plane) + np.random.default_rng(seed).normal(0, noise, (13, 2))
s = core.solve(world, dict(zip(NAMES, drawn.tolist())), BOX)
said = f"tilt {tilt:g}, noise {noise:g}, seed {seed}: lens {s['lens']:.0f}, band {s['lens_band']}, determined {s['lens_determined']}"
self.assertTrue(s["lens_band"][0] <= 50.0 <= s["lens_band"][1], said)
self.assertNotIn("NaN", json.dumps(s))
if s["lens_determined"]:
self.assertAlmostEqual(math.log(s["lens"] / 50.0), 0.0, delta=math.log(1.25), msg=said)
self.assertAlmostEqual(s["plane"], tilt, delta=3.0, msg=said)
if tilt <= 3.0:
self.assertIs(s["lens_determined"], False, said)
if tilt < 1.0:
self.assertEqual(s["lens_band"], list(core.LENS_MM), said)
if tilt >= 15.0:
self.assertIs(s["lens_determined"], True, said)
def test_determined_and_planar_sit_between_readings_either_side(self):
"""lens_determined's two thresholds, each between two readings (lodur:ruling:deterministic-bound-margin).
DECIDED: a band spans a whole number of STEPs, so the readings are discrete. Marks with depth seen through
85 mm, 3 px off, read a band of four steps, 1.4918 times, the widest of 48 such solves, and are called
determined; the same marks 5 px off read five steps, 1.6487, and are not. DECIDED 1.57 is the geometric
mean, 1.05 from each: the readings are one step apart, 1.105, under the ruling's 1.2, and no nearer pair
exists: an exception to the ruling, recorded at core.DECIDED (a band moved one step by a host fails the span
assertion here, loudly). Mutants DECIDED 1.4 and 1.7 die here by which call flips; 2.5 too; 1.5 and 1.6 are
unclaimed, inside the step. PLANAR: a panel with relief (planarity 0.041) seen square-on through 85 mm,
3 px off, reads a band open at 4000 mm and so is reported open at both ends; marks with depth read 0.36.
PLANAR 0.12 is the geometric mean, 2.9 from each: PLANAR 0.03 leaves the panel's band at [84.4, 4000] and
dies here, as 0.001 and 0.008 do on the flatter panel (0.009); PLANAR 1.0 dies at the oblique view.
Unclaimed: PLANAR 0.3, which differs from shipped in none of 192 solves of panels 0.009 to 0.277 thick."""
for noise, span, determined in ((3.0, 1.4918, True), (5.0, 1.6487, False)):
drawn = core.project(camera(self.points, 35, 20, 85), self.points) + np.random.default_rng(3).normal(0, noise, (13, 2))
s = core.solve(dict(zip(NAMES, self.points.tolist())), dict(zip(NAMES, drawn.tolist())), BOX)
self.assertAlmostEqual(s["lens_band"][1] / s["lens_band"][0], span, delta=1e-3)
self.assertIs(s["lens_determined"], determined)
self.assertAlmostEqual(s["planarity"], 0.3615, delta=1e-3)
relief = np.random.default_rng(77).uniform(-1, 1, 13)
for depth, lens, noise, planarity in ((0.01, 50, 1.0, 0.009), (0.045, 85, 3.0, 0.041)):
panel = np.c_[self.points[:, :2], relief / np.ptp(relief) * depth * np.ptp(self.points[:, :2], axis=0).max()]
drawn = core.project(camera(panel, 35, 90.0, lens), panel) + np.random.default_rng(0).normal(0, noise, (13, 2))
s = core.solve(dict(zip(NAMES, panel.tolist())), dict(zip(NAMES, drawn.tolist())), BOX)
self.assertAlmostEqual(s["planarity"], planarity, delta=5e-4)
self.assertEqual((s["lens_band"], s["lens_determined"]), (list(core.LENS_MM), False))
def test_the_exact_gates_sit_at_a_billionth_of_the_marks_extent(self):
"""exact-gate: each of _decidable's three tests reads a ratio (the marks' thinnest extent over their
widest) against core.EXACT, 1e-9. Marks at 3.16e-10 are refused
and marks at 3.16e-9 pass: the geometric means of the shipped gate with a gate ten times tighter and ten
times looser, the least mutants claimed (separation 3.16 each side)."""
r = np.random.default_rng(7)
bump = r.normal(0, 1, 13)
plane = np.c_[self.points[:, :2], np.zeros(13)]
line = np.outer(np.linspace(-2, 2, 13), [1.0, 2.0, 0.5])
across = np.cross([1.0, 2.0, 0.5], [0.0, 0.0, 1.0])
flat_px, slope = np.c_[np.linspace(200, 900, 13), np.linspace(300, 500, 13)], np.array([-200.0, 700.0])
thin = lambda A: (lambda s: s[-1] / s[0])(np.linalg.svd(A - A.mean(0), compute_uv=False)) # noqa: E731
sites = (("pixels lie on one line", lambda t: (self.points, flat_px + t * np.outer(bump, slope)), lambda W, P: thin(P), {}),
("world points lie on one line", lambda t: (line + t * np.outer(bump, across), np.array(list(self.pixels.values()))), lambda W, P: (lambda s: s[1] / s[0])(np.linalg.svd(W - W.mean(0), compute_uv=False)), {}),
("does not decide the centre", lambda t: (plane + t * np.outer(bump, [0.0, 0.0, 1.0]), np.array(list(self.pixels.values()))), lambda W, P: thin(W), {"model": "free"}))
for said, make, reading, how in sites:
unit = reading(*make(1e-6)) / 1e-6 # the reading is the offset's size times this, the offset being small
for at, refused in ((3.16e-10, True), (3.16e-9, False)):
W, P = make(at / unit)
self.assertAlmostEqual(reading(W, P) / at, 1.0, delta=0.01, msg=said)
try:
core._decidable(NAMES, W, P, how.get("model", "auto"))
self.assertFalse(refused, f"{said}: marks at {at:g} passed")
except core.ReferenceFitError as refusal:
self.assertTrue(refused, f"{said}: marks at {at:g} were refused: {refusal}")
self.assertIn(said, str(refusal))
@unittest.skipIf(np is None, "numpy")
class FlowTests(unittest.TestCase):
"""The crease Blender builds from a cage column, the flow score and the line parsers. Mutants, each run once:
N3 crease_run without the limit step test_crease_run_is_one_level_of_subdivision
N3b its first step weighs (1, 4, 1) / 6 the same
N4 along without the direction test test_along_scores_edges_that_run_with_the_line
N5 (back-facing creases counted) is claimed by tests/live/reference_flow.py."""
COLUMN = [[0.5, 0.0, 0.0], [0.6, 0.2, 1.0], [0.4, 0.1, 2.0], [0.7, -0.2, 3.0], [0.5, 0.0, 4.0]]
BUILT = [[0.5, 0.0, 0.0], [0.54375, 0.09375, 0.5], [0.55, 0.15, 1.0], [0.504167, 0.139583, 1.5], [0.483333, 0.066667, 2.0], [0.55, -0.04375, 2.5],
[0.616667, -0.116667, 3.0], [0.589583, -0.089583, 3.5], [0.5, 0.0, 4.0]] # Blender 5.3's level-1 Subdivision of this column creased hard, as tests/live/reference_flow.py printed it
def test_crease_run_is_one_level_of_subdivision(self):
"""crease-run-and-through, N3: against Blender's own numbers, which are the limit curve's (the modifier's
Limit Surface is on unless turned off). Shipped reads 3.3e-7 m, the fixture's rounding; N3b 0.0139 and N3
0.0208: the bound is the geometric mean of 3.3e-7 and 0.0139, separation 205 each side."""
run = core.crease_run(self.COLUMN)
self.assertEqual(run.shape, (9, 3))
self.assertLess(np.abs(run - np.array(self.BUILT)).max(), 6.8e-5)
def test_along_scores_edges_that_run_with_the_line(self):
"""along-scores, N4: rungs 5 px apart cross the line square-on, each within the 10 px that counts as near."""
line = [[100.0, 200.0], [500.0, 200.0]]
self.assertEqual(core.along(line, [[80.0, 203.0, 520.0, 203.0]], 1000.0), {"on": 1.0, "off": 0.3, "run": 1.0})
rungs = [[float(u), 150.0, float(u), 250.0] for u in range(100, 501, 5)]
self.assertEqual(core.along(line, rungs, 1000.0), {"on": 0.0, "off": 5.0, "run": 0.0})
half = core.along(line, [[100.0, 200.0, 300.0, 200.0]], 1000.0)
self.assertAlmostEqual(half["on"], 0.5, delta=0.03)
self.assertEqual(half["run"], half["on"])
self.assertEqual(core.along(line, [], 1000.0), {"on": 0.0, "off": 5.0, "run": 0.0})
def test_line_parsers(self):
self.assertEqual(core.polyline("1,2 3,4.5", "line_a").tolist(), [[1.0, 2.0], [3.0, 4.5]])
self.assertEqual({k: v.tolist() for k, v in core.polylines("r: 1,2 3,4; l: 5,6 7,8;", "lines").items()}, {"r": [[1.0, 2.0], [3.0, 4.0]], "l": [[5.0, 6.0], [7.0, 8.0]]})
for call, text, said in ((core.polyline, "1,2", "no length"), (core.polyline, "1,2 1,2", "no length"), (core.polyline, "1,2 3", "point"),
(core.polylines, "1,2 3,4", "no tag"), (core.polylines, "r: 1,2 3,4; r: 1,2 3,4", "twice"), (core.polylines, " ; ", "no line")):
with self.assertRaises(core.ReferenceFitError) as caught:
call(text, "lines")
self.assertIn(said, str(caught.exception))
@unittest.skipIf(np is None, "numpy")
class CameraTests(unittest.TestCase):
@ -300,13 +444,15 @@ class HostFileTests(unittest.TestCase):
def test_the_row_names_the_operator_and_properties_the_add_on_defines(self):
source = (SURFACE / "brokkr_reference" / "__init__.py").read_text(encoding="utf-8")
(row,) = self.document["actions"]
self.assertIn(f'bl_idname = "{row["name"]}"', source)
self.assertEqual(row.get("result"), "brokkr_mesh_polish_result")
body = source.split(f'bl_idname = "{row["name"]}"')[1].split("def work")[0]
for field in row["fields"]:
self.assertIn(f" {field['name']}: bpy.props.", body, field["name"])
self.assertEqual(body.count(": bpy.props."), len(row["fields"]))
self.assertEqual([row["name"] for row in self.document["actions"]], ["brokkr_reference.solve_camera", "brokkr_reference.flow_score"])
self.assertEqual(source.count("bl_idname = "), 2)
for row in self.document["actions"]:
self.assertIn(f'bl_idname = "{row["name"]}"', source)
self.assertEqual(row.get("result"), "brokkr_mesh_polish_result")
body = source.split(f'bl_idname = "{row["name"]}"')[1].split("def work")[0]
for field in row["fields"]:
self.assertIn(f" {field['name']}: bpy.props.", body, field["name"])
self.assertEqual(body.count(": bpy.props."), len(row["fields"]), row["name"])
def test_a_valid_intent_is_admitted_and_a_bound_miss_is_refused(self):
fields = {"world": "a=0,0,0", "pixels": "a=1,2", "box": "0,0,10,10"}
@ -315,6 +461,11 @@ class HostFileTests(unittest.TestCase):
for bad in ({"lens": 4001}, {"model": "fisheye"}, {"width": 8}, {"world": ""}):
with self.assertRaises(at.IntentInvalid):
at.validate({**self.envelope, **fields, **bad}, self.host)
flow = {**self.envelope, "action": "brokkr_reference.flow_score", "camera_name": "Concept", "lines": "r: 1,2 3,4"}
self.assertEqual((at.validate(flow, self.host)["angle"], at.validate(flow, self.host)["height"]), (18, 0))
for intent, bad in ((flow, {"angle": 0}), (flow, {"lines": ""}), (flow, {"camera_name": "x" * 64})):
with self.assertRaises(at.IntentInvalid):
at.validate({**intent, **bad}, self.host)
class OwnershipTests(unittest.TestCase):
@ -325,9 +476,10 @@ class OwnershipTests(unittest.TestCase):
self.assertIsNone(re.search(r"import bpy|mathutils", (SURFACE / "brokkr_reference" / "core.py").read_text(encoding="utf-8")))
def test_the_package_reads_no_image_or_sheet(self):
"""Nor does it hold the harness's recipes: the centre plate, the outline descent and their masks stay there."""
for path in (SURFACE / "brokkr_reference").glob("*"):
if path.is_file():
self.assertIsNone(re.search(r"concepts\.json|PIL|Image\.open", path.read_text(encoding="utf-8")), path.name)
self.assertIsNone(re.search(r"concepts\.json|PIL|Image\.open|centre_plate|silhouette|polygon_mask|knotted", path.read_text(encoding="utf-8")), path.name)
def test_no_other_package_names_this_one(self):
for package in ("brokkr_kitbash", "brokkr_rig", "brokkr_bridge", "brokkr_mesh_polish"):

View file

@ -0,0 +1,471 @@
"""Route tests. No Blender: brokkr_kitbash/route.py against analytic distance fields.
Run: python3 -m unittest discover -s surfaces/blender/tests -v (needs numpy; skipped without it)
The hose action is exercised in a real Blender by tests/live/kitbash_hose.py.
Bounds follow lodur:ruling:deterministic-bound-margin: a deterministic reading is exact here, so each assertion is the
rule itself, and each names the mutant it kills (cut kit-hose's H list).
"""
from __future__ import annotations
import importlib.util
import math
import unittest
from pathlib import Path
SURFACE = Path(__file__).resolve().parents[1]
try:
import numpy as np
except ImportError: # pragma: no cover
np = None
if np is not None:
spec = importlib.util.spec_from_file_location("brokkr_kitbash_route", SURFACE / "brokkr_kitbash" / "route.py")
route = importlib.util.module_from_spec(spec)
spec.loader.exec_module(route)
NEED = 0.04
def wall(hole: float):
"""A wall 0.04 thick across x = 1 with a round hole of radius `hole` about the line y = z = 0.2."""
def distance(points):
points = np.asarray(points, dtype=np.float64)
out = np.maximum(np.abs(points[:, 0] - 1.0) - 0.02, 0.0)
inside = hole - np.hypot(points[:, 1] - 0.2, points[:, 2] - 0.2)
return np.where(inside > 0.0, np.hypot(out, inside), out)
return distance
def ball(centre, radius: float):
return lambda points: np.linalg.norm(np.asarray(points, dtype=np.float64) - np.asarray(centre), axis=1) - radius
def nothing(points):
return np.full(len(points), 10.0)
def room_of(distance, need: float):
return lambda a, b: route.room(a, b, distance, need)
def dense(a, b, spacing: float):
"""This test's own reading of a segment: points no further apart than spacing."""
a, b = np.asarray(a, dtype=np.float64), np.asarray(b, dtype=np.float64)
return a[None] + (b - a)[None] * np.linspace(0.0, 1.0, max(2, math.ceil(float(np.linalg.norm(b - a)) / spacing) + 1))[:, None]
def slab(x: float, half: float):
"""A plate across x, `half` thick each side of it."""
return lambda points: np.maximum(np.abs(np.asarray(points, dtype=np.float64)[:, 0] - x) - half, 0.0)
def length(points) -> float:
return float(np.linalg.norm(np.diff(np.asarray(points), axis=0), axis=1).sum())
@unittest.skipIf(np is None, "numpy is not installed")
class SearchTests(unittest.TestCase):
def test_a_leg_passes_the_hole_and_every_sight_line_keeps_need(self):
"""wavefront-and-pull. Mutant H12 (occupancy at need less a voxel): a kept point stands under need."""
distance = wall(0.12)
a, b = np.array([0.0, 0.0, 0.0]), np.array([2.0, 0.0, 0.0])
pulled, voxels = route.leg(a, b, distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 1")
self.assertEqual(voxels, 131 * 31 * 31)
self.assertTrue(np.allclose(pulled[0], a) and np.allclose(pulled[-1], b))
read = np.vstack([dense(p, q, 0.0025) for p, q in zip(pulled[:-1], pulled[1:])])
self.assertGreaterEqual(float(distance(read).min()), NEED - 1e-9)
through = read[np.abs(read[:, 0] - 1.0) < 0.02]
self.assertTrue(len(through) and (np.hypot(through[:, 1] - 0.2, through[:, 2] - 0.2) < 0.12 - NEED + 1e-9).all())
self.assertLess(length(pulled), 2.0 * math.hypot(1.0, 0.2 * math.sqrt(2.0)) + 0.05) # taut: near the two straights through the hole's middle
def test_two_neighbouring_free_voxels_keep_need_between_them(self):
"""The half diagonal a free voxel stands beyond need is what a step between two of them can lose: beside an
edge (a thin rod) every step between neighbouring free voxels keeps need, and without it some do not."""
rod = lambda points: np.hypot(np.asarray(points)[:, 0], np.asarray(points)[:, 1]) # noqa: E731
for reach, holds in ((route.REACH, True), (0.0, False)):
cells = route.grid([-0.1, -0.1, 0.0], [0.1, 0.1, 0.0], 0.02, rod, 0.043 + reach * 0.02)
free = [np.array(m) for m in zip(*np.nonzero(cells.free))]
least = min(float(rod(dense(cells.lo + 0.02 * p, cells.lo + 0.02 * q, 0.001)).min())
for p in free for q in free if 0 < np.abs(p - q).max() <= 1)
self.assertEqual(least >= 0.043, holds, least)
def test_a_measure_proves_what_stands_between_its_readings(self):
"""clearance-kept. Mutants M3 and M3b (verify and pull read at a spacing): a plate 1 mm thick stands between
two readings 0.1 apart, each of which keeps need, and the line through it is refused by measure, by pull and by
verify. The bound is a piece's reading less half its length: with the half length left out the first reading
of the whole segment would prove it."""
plate, a, b = slab(1.0, 0.0005), np.array([0.05, 0.0, 0.0]), np.array([1.85, 0.0, 0.0])
self.assertGreaterEqual(float(plate(dense(a, b, 0.1)).min()), 0.04) # readings 0.1 apart straddle it: the nearest stands 0.0495 off
swept = route.measure(a, b, plate, 0.01)
self.assertTrue(swept.short and swept.least < 0.01 and abs(float(swept.where[0]) - 1.0) < 0.0105, swept)
self.assertFalse(route.clear(a, b, plate, 0.01))
self.assertTrue(route.clear(a, [0.98, 0.0, 0.0], plate, 0.01))
over = np.array([a, [1.0, 0.0, 5.0], b]) # the plate ends nowhere: a pulled line keeps the point that leads round nothing, and is not shortened through it
self.assertEqual(len(route.pull(over, lambda points: np.where(np.asarray(points)[:, 2] > 4.0, 10.0, plate(points)), 0.01)), 3)
with self.assertRaisesRegex(route.RouteError, r"^the hose stands 0\.00\d+ m from an obstacle at \[(1|0\.99\d*|1\.00\d*), 0, 0\], under the 0\.01 m the bundle needs"):
route.verify(np.array([a, b]), plate, 0.01, 0.0)
ground = lambda points: np.asarray(points, dtype=np.float64)[:, 2] # noqa: E731
along_ = lambda z: (np.array([0.0, 0.0, z]), np.array([1.0, 0.0, z])) # noqa: E731
self.assertFalse(route.measure(*along_(0.01 + route.FINE), ground, 0.01).short) # a line that keeps need by FINE is proven
grazing = route.measure(*along_(0.01 + route.FINE / 4.0), ground, 0.01) # one that keeps it by less than half of FINE is not, and is refused as that
self.assertTrue(grazing.short and grazing.least >= 0.01)
self.assertIn("too near the 0.01 m the bundle needs to prove it", route.falls(grazing.least, 0.01))
slope = lambda points: 0.3 + np.abs(np.asarray(points, dtype=np.float64)[:, 0] - 0.7137) # noqa: E731
self.assertLess(route.measure([0.0, 0, 0], [1.0, 0, 0], slope, 0.01).least - 0.3, 0.3) # proven at need by a few readings
self.assertLess(route.measure([0.0, 0, 0], [1.0, 0, 0], slope, 0.01, within=route.FINE).least - 0.3, route.FINE) # the least itself, within the bound asked
self.assertTrue(np.allclose(route.span(np.array([[0.0, 0, 0], [1.0, 0, 0], [1.0, 1.0, 0]]), 0.5, 1.5), [[0.5, 0, 0], [1.0, 0, 0], [1.0, 0.5, 0]]))
self.assertEqual(len(route.span(np.array([[0.0, 0, 0], [1.0, 0, 0]]), 0.6, 0.4)), 0)
def test_a_leg_searched_with_room_keeps_it_where_it_wraps(self):
"""A line pulled at need grazes what it wraps, and the corner there has no room for an arc: with pad the
pulled line keeps need and pad of every point further than twice pad from its ends, and a corner's room is
the pad instead of what the pull happened to leave."""
distance, pad = ball([1.0, 0.0, 0.0], 0.3), 0.03
a, b = np.array([0.0, 0.0, 0.0]), np.array([2.0, 0.0, 0.0])
tight = route.leg(a, b, distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 1")[0]
roomy = route.leg(a, b, distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 1", pad)[0]
least = lambda line: float(distance(np.vstack([dense(p, q, 0.002) for p, q in zip(line[:-1], line[1:])])).min()) # noqa: E731
self.assertLess(least(tight), NEED + 0.2 * pad)
self.assertGreaterEqual(least(tight), NEED)
self.assertGreaterEqual(least(roomy), NEED + pad)
self.assertGreater(length(roomy), length(tight))
near = np.array([0.66, 0.0, 0.0]) # an end that stands need from the ball has no voxel with that room beside it: the caller searches such a leg without
with self.assertRaisesRegex(route.RouteError, r"^leg 1: no free voxel stands in sight of its start \[0\.66, 0, 0\]: an obstacle is nearer it than 0\.08732 m on every side"):
route.leg(near, [0.0, 0.0, 0.0], distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 1", pad)
self.assertEqual(len(route.leg(near, [0.0, 0.0, 0.0], distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 1")[0]), 2)
def test_a_closed_way_a_buried_end_and_a_box_too_fine_are_refused_by_name(self):
distance = wall(0.03) # a hole narrower than the bundle
ends = (np.array([0.0, 0.0, 0.0]), np.array([2.0, 0.0, 0.0]))
with self.assertRaisesRegex(route.RouteError, r"^leg 2: no free way joins its ends"):
route.leg(*ends, distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 2")
with self.assertRaisesRegex(route.RouteError, r"^leg 3: its end \[1, 0, 0\] stands 0 m from an obstacle, under the 0\.04 m"):
route.leg(ends[0], np.array([1.0, 0.0, 0.0]), distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 3")
with self.assertRaisesRegex(route.RouteError, r"^leg 4: its search box of \[2\.6, 0\.6, 0\.6\] m is \d+ voxels at step 0\.005, over 524288: a step of 0\.0\d+ fits"):
route.leg(*ends, distance, distance, NEED, 0.005, 0.3, 2 ** 19, "leg 4")
try:
route.leg(*ends, distance, distance, NEED, 0.005, 0.3, 2 ** 19, "leg 4")
except route.RouteError as error:
fits = float(str(error).split("a step of ")[1].split(" ")[0])
self.assertLessEqual(int(np.prod(np.ceil(np.array([2.6, 0.6, 0.6]) / fits - 1e-9) + 1)), 2 ** 19)
with self.assertRaisesRegex(route.RouteError, "its start voxel is not free"):
route.wavefront(np.zeros((2, 2, 2), dtype=bool), (0, 0, 0), (1, 1, 1))
def test_a_wavefront_way_is_a_shortest_one(self):
free = np.ones((9, 9, 1), dtype=bool)
free[4, 1:, 0] = False # a wall with a gap at j = 0
way = route.wavefront(free, (0, 8, 0), (8, 8, 0))
self.assertEqual((way[0], way[-1], len(way)), ((0, 8, 0), (8, 8, 0), 17))
self.assertIn((4, 0, 0), way)
self.assertTrue(all(max(abs(p[i] - q[i]) for i in range(3)) == 1 for p, q in zip(way[:-1], way[1:])))
@unittest.skipIf(np is None, "numpy is not installed")
class FilletTests(unittest.TestCase):
ZIGZAG = np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.3, 0.0], [2.0, 0.3, 0.4], [2.0, 1.5, 0.4]])
def test_every_arc_is_tangent_and_two_corners_share_a_segment(self):
"""fillet-rule. Mutant H2 (arcs not tangent): the first chord of an arc leaves its segment at more than half a
step of the arc. Two corners on the 0.3 segment shrink until their tangents share it."""
made = route.fillet(self.ZIGZAG, None, 0.01, 0.2)
lengths, unit, turn = route._turns(self.ZIGZAG)
self.assertTrue((made.t[:-1] + made.t[1:] <= lengths[1:-1] + 1e-12).all())
self.assertAlmostEqual(float(made.t[0] + made.t[1]), 0.3, places=12)
self.assertAlmostEqual(float(made.t[0] / made.t[1]), min(0.8, 0.3) / min(0.3, float(lengths[2])), places=12) # in proportion to what each had alone
for c in range(3):
arc = made.curve[made.owner == c]
steps = max(2, math.ceil(turn[c] * route.ARC))
self.assertEqual(len(arc), steps + (c != 1)) # arcs 0 and 1 meet on the shared segment: the point where they meet is listed once, as arc 0's
for chord, tangent in ((arc[1] - arc[0], unit[c]), (arc[-1] - arc[-2], unit[c + 1]))[c == 1:]:
self.assertAlmostEqual(math.acos(min(1.0, float(chord @ tangent) / float(np.linalg.norm(chord)))), turn[c] / steps / 2.0, places=9)
self.assertAlmostEqual(float(np.linalg.norm(arc[-1] - self.ZIGZAG[c + 1])), float(made.t[c]), places=12)
self.assertAlmostEqual(float(made.radii[c]), float(made.t[c] / math.tan(turn[c] / 2.0)), places=12)
def test_the_leads_stay_straight(self):
"""Mutant H1 (lead ignored): the first corner's tangent takes the whole first segment and the bend starts at
the ferrule."""
made = route.fillet(np.array([[0.0, 0.0, 0.0], [0.3, 0.0, 0.0], [0.3, 2.0, 0.0], [0.3, 2.0, 0.5]]), None, 0.01, 0.2)
self.assertAlmostEqual(float(made.t[0]), 0.1, places=12)
self.assertAlmostEqual(float(made.t[1]), 0.3, places=12)
self.assertAlmostEqual(float(np.linalg.norm(made.curve[1] - made.curve[0])), 0.2, places=12)
self.assertAlmostEqual(float(np.linalg.norm(made.curve[-1] - made.curve[-2])), 0.2, places=12)
def test_a_kept_straight_stays_in_the_middle_of_a_centred_segment(self):
points = np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.5, 0.0], [3.0, 0.5, 1.0]])
made = route.fillet(points, None, 0.01, 0.0, keep=[0.0, 0.1, 0.0], centred=[False, True, False])
self.assertAlmostEqual(float(made.t[0]), 0.2, places=12)
self.assertAlmostEqual(float(made.t[1]), 0.2, places=12)
def test_a_corner_that_wraps_an_obstacle_gets_the_radius_its_room_allows(self):
"""Mutant H3 (the room cap off: radius by segments only): the arc cuts through the ball."""
distance = ball([-0.25, 0.25, 0.0], 0.17)
points = np.array([[-1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
room = room_of(distance, 0.05)
made = route.fillet(points, room, 0.05, 0.0)
radius, t = float(made.radii[0]), float(made.t[0])
depth = 1.0 - math.cos(math.pi / 4.0)
measured = min(room(points[1] - np.array([1.0, 0.0, 0.0]) * t, points[1]), room(points[1], points[1] + np.array([0.0, 1.0, 0.0]) * t))
self.assertLessEqual(radius * depth, measured + 1e-12)
self.assertGreater(radius, 0.03 / depth) # more than the room at the segments' nearest points allows: the room is measured along the tangent segments only
self.assertLess(radius, 0.25)
arc = made.curve[made.owner == 0]
self.assertGreaterEqual(float(distance(np.vstack([dense(p, q, 0.001) for p, q in zip(arc[:-1], arc[1:])])).min()), 0.05)
grown = route.arcs(points, np.array([t * 1.05]))[0] # the largest: 5 percent more breaks the rule
t2 = t * 1.05
self.assertGreater(t2 / math.tan(math.pi / 4.0) * depth, min(room(points[1] - np.array([1.0, 0.0, 0.0]) * t2, points[1]), room(points[1], points[1] + np.array([0.0, 1.0, 0.0]) * t2)))
self.assertEqual(len(grown), len(made.curve))
free = route.fillet(points, None, 0.05, 0.0)
self.assertAlmostEqual(float(free.radii[0]), 1.0, places=12)
self.assertLess(float(distance(free.curve).min()), 0.0)
self.assertGreaterEqual(route.verify(made.curve, distance, 0.05, 0.0), 0.05)
with self.assertRaisesRegex(route.RouteError, r"^the hose stands -0\.\d+ m from an obstacle at \[-0\.\d+, 0\.\d+, 0\], under the 0\.05 m"):
route.verify(free.curve, distance, 0.05, 0.0)
def test_a_corner_under_the_floor_is_refused_by_name(self):
with self.assertRaisesRegex(route.RouteError, r"^corner 1 at \[1, 0, 0\] turns 90\.0 degrees and gets a bend of radius 0\.15 m, under the floor 0\.5: "
r"the corner's segments leave 0\.3 m of straight for the 0\.5 m its tangent takes at the floor"):
route.fillet(self.ZIGZAG, None, 0.5, 0.2)
with self.assertRaisesRegex(route.RouteError, r"^corner 1 at \[0, 0, 0\] turns 90\.0 degrees and gets a bend of radius 0(\.00\d+)? m, under the floor 0\.05: the route passes too near an obstacle to bend here: "
r"its segments stand 0(\.00\d+)? m clear beyond what the bundle needs and the arc at the floor takes 0\.01464 "):
route.fillet(np.array([[-1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]]), room_of(ball([-0.05, 0.05, 0.0], 0.02), 0.05), 0.05, 0.0) # a ball in the corner
def test_a_corner_keeps_its_floor_s_tangent_before_its_neighbour_gets_more(self):
"""bend-room-searched. Two corners on a 0.5 segment ask 0.5 and 0.25 of it and need 0.22 each at the floor:
each keeps its need and the 0.06 left is shared by what each asked beyond it. Mutant T1 (shared in proportion
to what each asked, floor = 0 in tangents): the second corner gets 0.167 and the polyline is refused."""
points = np.array([[0.0, 0.0, 0.0], [3.0, 0.0, 0.0], [3.0, 0.5, 0.0], [3.25, 0.5, 0.0]])
made = route.fillet(points, None, 0.22, 0.0)
self.assertAlmostEqual(float(made.t.sum()), 0.5, places=12)
self.assertAlmostEqual(float((made.t[0] - 0.22) / (made.t[1] - 0.22)), 0.28 / 0.03, places=9)
self.assertAlmostEqual(float(route.tangents(points, None, 0.0)[1]), 0.5 / 3.0, places=12) # the share a corner got before its need counted
self.assertEqual(float(route.strain(points, 0.22, 0.0).sum()), 0.0)
self.assertAlmostEqual(float(route.strain(points, 0.3, 0.0)[1]), 0.1, places=12)
self.assertAlmostEqual(float(route.strain(points, 0.3, 0.0, keep=[0.0, 0.1, 0.0], centred=[False, True, False])[1]), 0.2, places=12)
held = route.fillet(points, None, 0.1, 0.0, least=[0.4, 0.0]) # a corner that will turn further holds the tangent that takes
self.assertAlmostEqual(float(held.t[0]), 0.4, places=12)
self.assertAlmostEqual(float(held.t[1]), 0.1, places=12)
def test_a_seed_without_the_straight_for_its_bends_is_refined_where_the_oracle_allows(self):
"""bend-room-searched. A seed's vertex stands 0.18 from a held corner and their two tangents at the floor take
0.25; a ball closes the straight way past it. relax moves the vertex until every segment has its straight,
each moved segment proven clear. Mutant X1 (relax returns its seed): strain stays and fillet refuses."""
distance, need, floor = ball([1.0, 0.7, 0.0], 0.05), 0.05, 0.3
seed, tags = np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.15, 0.1, 0.0], [1.15, 1.5, 0.0]]), ["P", "E", None, "P"]
self.assertFalse(route.clear(seed[1], seed[3], distance, need))
self.assertGreater(float(route.strain(seed, floor, 0.0).sum()), 0.05)
with self.assertRaisesRegex(route.RouteError, "under the floor 0.3: it shares a segment with the corner beside it"):
route.fillet(seed, room_of(distance, need), floor, 0.0)
tried = []
def sure(a, b):
tried.append((a, b))
return route.clear(a, b, distance, need)
points, kept = route.relax(seed, tags, lambda p, g: route.strain(p, floor, 0.0), sure, floor)
self.assertTrue(tried)
self.assertEqual(float(route.strain(points, floor, 0.0).sum()), 0.0)
self.assertEqual([tag for tag in kept if tag is not None], ["P", "E", "P"])
for index in (0, 1, -1):
self.assertTrue((points[index] == seed[index]).all())
self.assertGreaterEqual(float(distance(np.vstack([dense(p, q, 0.001) for p, q in zip(points[:-1], points[1:])])).min()), need)
made = route.fillet(points, room_of(distance, need), floor, 0.0)
self.assertGreaterEqual(float(made.radii.min()), floor * (1 - 1e-9))
open_points, open_tags = route.relax(seed, tags, lambda p, g: route.strain(p, floor, 0.0), lambda a, b: True, floor)
self.assertEqual(open_tags, ["P", "E", "P"]) # with nothing in the way the vertex is dropped
same, _ = route.relax(seed, tags, lambda p, g: route.strain(p, floor, 0.0), lambda a, b: False, floor)
self.assertTrue((same == seed).all()) # nothing the oracle does not prove is kept
def test_too_stiff_is_proven_of_a_pocket_and_of_nothing_else(self):
"""bend-room-searched. A wall 0.08 ahead of a point a hose leaves along x: no curve of radius 0.2 turns
aside in the 0.06 its centre line has, and one of radius 0.04 does. Mutant S1 (the balls a curve cannot
enter left out of leaves): the stiff bundle is said to leave."""
wall = lambda at: (lambda p: at - np.asarray(p)[:, 0]) # noqa: E731
origin, ahead = np.zeros(3), np.array([1.0, 0.0, 0.0])
self.assertFalse(route.leaves(origin, ahead, 0.2, wall(0.08), 0.02))
self.assertTrue(route.leaves(origin, ahead, 0.04, wall(0.08), 0.02))
self.assertTrue(route.leaves(origin, ahead, 0.2, wall(0.5), 0.02))
slit = lambda p: np.where(np.abs(np.asarray(p)[:, 1]) < 0.03, 1.0, wall(0.08)(p)) # noqa: E731 the wall, open along a slit 0.06 wide straight ahead
self.assertTrue(route.leaves(origin, ahead, 0.2, slit, 0.02))
def test_the_sharpest_turn_of_a_range_is_exact(self):
"""range-measured-unposed. The turn at a pin over a range of rolls, against the turn at 4001 rolls of it."""
rng = np.random.default_rng(7)
for low, high in ((-20.0, 20.0), (-170.0, 5.0), (30.0, 31.0), (-360.0, 360.0), (4.0, 4.0)):
before, after, axis = (v / np.linalg.norm(v) for v in rng.normal(size=(3, 3)))
turns = [math.acos(max(-1.0, min(1.0, float(before @ route.turned(after[None], np.zeros(3), axis, float(roll))[0])))) for roll in np.linspace(low, high, 4001)]
found = route.sharpest_turn(before, after, axis, low, high)
self.assertGreaterEqual(found, max(turns) - 1e-12)
self.assertLess(found - max(turns), 1e-5)
def test_the_floor_is_the_innermost_hose_s(self):
"""Mutant H8 (the floor taken at the centre line): the innermost of three hoses bends tighter than bend
outside diameters."""
sizes = route.bundle(3, 0.014, 0.0, 0.01, 4.0)
self.assertAlmostEqual(sizes["spread"], 0.0364, places=12)
self.assertAlmostEqual(sizes["floor"] - sizes["spread"], 4.0 * 0.028, places=12)
self.assertAlmostEqual(sizes["need"], 0.0364 + 0.014 + 0.01, places=12)
self.assertAlmostEqual(sizes["width"], 2 * 0.0364 + 0.028, places=12)
self.assertAlmostEqual(sizes["lead"], 5 * 0.014 + 1.5 * 0.028, places=12)
self.assertEqual(route.bundle(1, 0.01, 0.0, 0.0, 4.0)["floor"], 0.08)
def test_a_span_sags_by_no_more_than_half_its_room(self):
"""ruling hose-slack-and-skinned. Mutant S1 (the sag not bounded by the room): the span hangs into the floor
under it."""
ground = lambda points: np.asarray(points, dtype=np.float64)[:, 2] # noqa: E731
span = np.array([[0.0, 0.0, 0.1], [1.0, 0.0, 0.1]])
hung, drop = route.sag(span, 0.1, room_of(ground, 0.05))
self.assertAlmostEqual(drop, 0.025 - 0.75 * route.FINE, places=12) # half the room: what the span stands beyond need, less what a measure cannot tell apart
self.assertTrue(np.allclose(hung[1], [0.5, 0.0, 0.1 - drop]))
made = route.fillet(np.vstack([[[0.0, 0.0, 0.5]], hung, [[1.0, 0.0, 0.5]]]), room_of(ground, 0.05), 0.01, 0.1)
self.assertGreaterEqual(route.verify(made.curve, ground, 0.05, 0.1), 0.05)
self.assertGreater(float(made.radii[1]), 1.0) # a gentle arc, not a kink
high, drop = route.sag(span + [0.0, 0.0, 1.0], 0.1, room_of(ground, 0.05))
self.assertEqual((drop, len(high)), (0.1, 3))
self.assertEqual(route.sag(np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 1.0]]), 0.1, None)[1], 0.0) # a vertical span does not sag
self.assertEqual(route.sag(span, 0.0, None)[1], 0.0)
leaning, drop = route.sag(np.array([[0.0, 0.0, 1.0], [1.0, 0.0, 2.0]]), 0.1, None) # across the span, by how far it runs from vertical
self.assertAlmostEqual(drop, 0.1 * math.sqrt(0.5), places=12)
self.assertAlmostEqual(float((leaning[1] - [0.5, 0.0, 1.5]) @ [1.0, 0.0, 1.0]), 0.0, places=12)
self.assertEqual(route.sag(np.array([[0.0, 0.0, 1.0], [0.5, 0.0, 1.0]]), 0.1, None)[1], 0.0) # too short for the drop
@unittest.skipIf(np is None, "numpy is not installed")
class FrameTests(unittest.TestCase):
@staticmethod
def reference(curve, tangent, up):
"""The double reflection method as Wang et al. 2008 state it, a point at a time."""
ups = [up]
for i in range(len(curve) - 1):
v1 = [curve[i + 1][k] - curve[i][k] for k in range(3)]
c1 = sum(v * v for v in v1)
dot = lambda a, b: sum(x * y for x, y in zip(a, b)) # noqa: E731
r_left = [ups[-1][k] - 2.0 / c1 * dot(v1, ups[-1]) * v1[k] for k in range(3)]
t_left = [tangent[i][k] - 2.0 / c1 * dot(v1, tangent[i]) * v1[k] for k in range(3)]
v2 = [tangent[i + 1][k] - t_left[k] for k in range(3)]
c2 = dot(v2, v2)
ups.append([r_left[k] - 2.0 / c2 * dot(v2, r_left) * v2[k] for k in range(3)])
return np.array(ups)
@staticmethod
def tangents(curve):
steps = np.diff(curve, axis=0)
steps /= np.linalg.norm(steps, axis=1)[:, None]
tangent = np.vstack([steps[:1], steps[:-1] + steps[1:], steps[-1:]])
return tangent / np.linalg.norm(tangent, axis=1)[:, None]
def test_ups_are_rotation_minimising(self):
"""frames-rmf. Mutant H7 (Frenet frames for ups): on a planar S the up leaves the plane's normal."""
s = np.linspace(0.0, 2.0 * math.pi, 200)
planar = np.stack([s, np.sin(s), np.zeros_like(s)], axis=1)
ups = route.frames(planar, [0.0, 0.0, 1.0])
self.assertLess(float(np.abs(ups - [0.0, 0.0, 1.0]).max()), 1e-12)
helix = np.stack([np.cos(s * 2.0), np.sin(s * 2.0), 0.3 * s], axis=1)
ups, tangent = route.frames(helix, [0.0, 0.0, 1.0]), self.tangents(helix)
self.assertLess(float(np.abs(np.einsum("ij,ij->i", ups, tangent)).max()), 1e-12)
self.assertLess(float(np.abs(np.linalg.norm(ups, axis=1) - 1.0).max()), 1e-12)
first = np.array([0.0, 0.0, 1.0]) - tangent[0] * tangent[0][2]
self.assertLess(float(np.abs(ups - self.reference(helix.tolist(), tangent.tolist(), (first / np.linalg.norm(first)).tolist())).max()), 1e-9)
with self.assertRaisesRegex(route.RouteError, "runs along the curve's first tangent"):
route.frames(planar, planar[1] - planar[0])
def test_a_short_straight_between_two_arcs_is_dropped(self):
curve = np.array([[0.0, 0, 0], [1.0, 0, 0], [1.0 + 1e-6, 0, 0], [2.0, 1, 0], [2.0, 1 + 1e-6, 0]])
self.assertEqual(route.thinned(curve, 1e-3).tolist(), curve[[0, 1, 4]].tolist()) # the ends stay, the last in place of a point beside it
self.assertEqual(route.thinned(curve, 1e-9).tolist(), curve.tolist())
self.assertEqual(route.thinned(curve[:2], 10.0).tolist(), curve[:2].tolist())
@unittest.skipIf(np is None, "numpy is not installed")
class JointTests(unittest.TestCase):
P = np.array([[0.5, 0.0, 1.0], [0.2, 0.0, 0.0], [0.5, 0.0, -1.0]]) # through a point on the x axis
AXIS = (np.zeros(3), np.array([1.0, 0.0, 0.0]))
SIZES = {"need": 0.05, "floor": 0.05, "lead": 0.1}
FINEST = 0.3
def test_a_polyline_through_the_axis_keeps_its_length_at_every_roll(self):
"""joint-passage."""
rolls = route.rolls_of(-120.0, 10.0, 5.0)
self.assertEqual((len(rolls), rolls[0], rolls[-2], rolls[-1]), (27, -120.0, 5.0, 10.0))
self.assertEqual(route.rolls_of(0.0, 12.0, 5.0), [0.0, 5.0, 10.0, 12.0])
for roll in rolls:
posed = np.vstack([self.P[:2], route.turned(self.P[2:], *self.AXIS, roll)])
self.assertAlmostEqual(length(posed), length(self.P), places=12)
self.assertTrue(np.allclose(route.turned(np.array([[0.3, 1.0, 0.0]]), *self.AXIS, 90.0), [[0.3, 0.0, 1.0]])) # right-handed about +x
t = route.fillet(self.P, None, 0.05, 0.1).t
found = route.passes(self.P, t, 1, *self.AXIS, rolls, self.FINEST, 0.0, nothing, nothing, **self.SIZES)
self.assertEqual(found["rolls"], 27)
self.assertTrue(10.0 - 1.2 * math.radians(2.5) < found["least"] < 10.0, found) # a reading counts for less by what its point moves in half a step of the rolls
hung = np.vstack([route.sag(self.P[:2], 0.05, None)[0], route.sag(self.P[1:], 0.05, None)[0][1:]]) # sag-with-joint: each side hangs, and the pin point is still the one turned about
self.assertEqual(len(hung), 5)
sagged = route.passes(hung, route.fillet(hung, None, 0.05, 0.1).t, 2, *self.AXIS, rolls, self.FINEST, 0.0, nothing, nothing, **self.SIZES)
self.assertEqual(sagged["rolls"], 27)
self.assertLess(sagged["lengthChange"], found["lengthChange"]) # the hanging spans turn with their sides: only the bend at the pin changes, and its segments are shorter
with self.assertRaisesRegex(route.RouteError, r"^point 1 \[\S+, 0, \S+\] of the hose stands 0\.\d+ m off the pin's axis"):
route.passes(hung, route.fillet(hung, None, 0.05, 0.1).t, 1, *self.AXIS, rolls, self.FINEST, 0.0, nothing, nothing, **self.SIZES)
self.assertGreater(found["lengthChange"], 0.01) # the bend at the pin is what changes: each roll's is the largest arc its segments give
self.assertLess(found["lengthChange"], length(self.P) * (1.0 - math.pi / 4.0) * 2.0) # no more than every corner's shortcut
def test_a_hairpin_roll_is_refused_by_name(self):
t = route.fillet(self.P, None, 0.05, 0.1).t
with self.assertRaisesRegex(route.RouteError, r"^roll 1[67]\d(\.\d+)?: the bend at the pin turns up to 1\d\d\.\d degrees and its segments leave room for a radius of \S+ m, under the floor 0\.05 "
r"through the 0\.\d+ degrees either side of it$"):
route.passes(self.P, t, 1, *self.AXIS, [0.0, 90.0, 180.0], self.FINEST, 0.0, nothing, nothing, **self.SIZES)
def test_each_side_is_measured_against_the_other_where_the_roll_puts_it(self):
"""Mutants H5 (the child's obstacles not turned with the roll) and H6 (the range checked at its ends only): a
part of the child that the roll carries into the parent's side of the hose, between the ends of the range."""
middle = (self.P[0] + self.P[1]) / 2.0
child = ball(route.turned(middle[None], *self.AXIS, -45.0)[0], 0.05) # where it stands at roll 0
t = route.fillet(self.P, None, 0.05, 0.1).t
self.assertEqual(route.passes(self.P, t, 1, *self.AXIS, [0.0], self.FINEST, 0.0, nothing, child, **self.SIZES)["rolls"], 1)
for rolls in ([-90.0, 90.0], route.rolls_of(-90.0, 90.0, 5.0)): # the rolls given are where measuring starts, not all that is measured: the two ends find it as the 5 degree steps do
with self.assertRaisesRegex(route.RouteError, r"^roll 3[34](\.\d+)?: the hose's parent's side reads 0\.0\d+ m from the parts about the pin at \[\S+, \S+, \S+\], counting the 0\.00\d+ m it can move "
r"against the other side's through the 0\.\d+ degrees either side of it: "):
route.passes(self.P, t, 1, *self.AXIS, rolls, self.FINEST, 0.0, nothing, child, **self.SIZES)
seen = []
route.passes(self.P, t, 1, *self.AXIS, [30.0], self.FINEST, 10.0, nothing, lambda points: seen.append(np.array(points)) or nothing(points), **self.SIZES)
line = (self.P[1] - self.P[0]) / np.linalg.norm(self.P[1] - self.P[0])
on = [points for points in seen if np.abs(np.cross(route.turned(points, *self.AXIS, 20.0) - self.P[0], line)).max() < 1e-12]
self.assertTrue(on) # the parent's side was read turned back by roll - current: turned forward again it lies on its own segment
self.assertTrue(any(np.linalg.norm(np.cross(points - self.P[0], line), axis=1).min() > 0.01 for points in on)) # and as read it lay off it
parent = ball(route.turned(((self.P[1] + self.P[2]) / 2.0)[None], *self.AXIS, 45.0)[0], 0.05) # a part of the parent the child's side swings into
with self.assertRaisesRegex(route.RouteError, r"^roll 3[34](\.\d+)?: the hose's child's side reads"):
route.passes(self.P, t, 1, *self.AXIS, route.rolls_of(-90.0, 90.0, 5.0), self.FINEST, 0.0, parent, nothing, **self.SIZES)
def test_the_bend_at_the_pin_is_no_larger_than_its_room(self):
"""A ball inside the bend at the pin that both of the corner's segments clear: the arc there takes the radius
whose dip the segments' room allows, not the largest its segments give. Mutant R3 (the bend's tangent segments
measured for need alone) rounds the corner under need of the ball."""
inside = ball([0.28, 0.0, 0.0], 0.01)
t = route.fillet(self.P, None, 0.05, 0.1).t
self.assertGreater(float(inside(np.vstack([dense(self.P[0], self.P[1], 0.001), dense(self.P[1], self.P[2], 0.001)])).min()), 0.06)
free = route.passes(self.P, t, 1, *self.AXIS, [0.0], self.FINEST, 0.0, nothing, nothing, **self.SIZES)["radius"]
found = route.passes(self.P, t, 1, *self.AXIS, [0.0], self.FINEST, 0.0, inside, nothing, **self.SIZES)["radius"]
self.assertGreater(free, 2.0)
self.assertTrue(0.05 <= found < 0.5, found)
turn = float(route._turns(self.P)[2][0])
arc = route.arcs(self.P, np.array([found * math.tan(turn / 2.0)]))[0]
self.assertGreaterEqual(float(inside(np.vstack([dense(p, q, 0.001) for p, q in zip(arc[:-1], arc[1:])])).min()), 0.05)
self.assertLess(float(inside(route.arcs(self.P, np.array([free * math.tan(turn / 2.0)]))[0]).min()), 0.05) # the largest arc its segments give stands under need of the ball
def test_a_plate_between_two_rolls_is_found(self):
"""range-sampled-not-swept. A part of the child 2 mm across that crosses the parent's side of the hose at roll
17.5, half way between two rolls 5 degrees apart: at 15 and at 20 the hose reads 0.02 from it and keeps its
need of 0.01, and the range is refused at a roll between them. Mutant R1 (a reading not lessened by what its
point moves within its bin) accepts the range."""
middle = (self.P[0] + self.P[1]) / 2.0
child = ball(route.turned(middle[None], *self.AXIS, -17.5)[0], 0.001)
t, sizes = route.fillet(self.P, None, 0.05, 0.1).t, {**self.SIZES, "need": 0.01}
for roll in (15.0, 20.0):
self.assertGreater(float(child(route.turned(dense(self.P[0], self.P[1], 0.0005), *self.AXIS, -roll)).min()), 0.02)
self.assertEqual(route.passes(self.P, t, 1, *self.AXIS, [15.0], self.FINEST, 0.0, nothing, child, **sizes)["rolls"], 1) # one roll answers for itself alone
with self.assertRaisesRegex(route.RouteError, r"^roll 1[5-9]\.\d+: the hose's parent's side reads"):
route.passes(self.P, t, 1, *self.AXIS, route.rolls_of(-20.0, 20.0, 5.0), self.FINEST, 0.0, nothing, child, **sizes)
clear_of = route.passes(self.P, t, 1, *self.AXIS, route.rolls_of(-20.0, 10.0, 5.0), self.FINEST, 0.0, nothing, child, **sizes)
self.assertGreaterEqual(clear_of["rolls"], 7) # short of the plate the same range passes, with more rolls measured where the 5 degree bins fell short
if __name__ == "__main__":
unittest.main()

View file

@ -67,6 +67,15 @@ def fake_render():
return FakeRender()
class Extras(dict):
"""An ID with custom properties: a mapping, and the attributes it is given."""
def __init__(self, properties=(), **attributes):
super().__init__(properties)
self.__dict__.update(attributes)
__hash__ = object.__hash__
class Objects(dict):
"""bpy.data.objects: a mapping with keys() and get(); like bpy_prop_collection, iterating it yields the objects."""
@ -89,7 +98,7 @@ class FakeUndo:
class FakeBpy:
def __init__(self):
self.imported = []
self.imported, self.import_extras, self.import_mesh_extras = [], {}, {}
self.rendered = []
self.scene = NS(name="Scene", camera=None, world=None, render=fake_render())
self.camera_data = NS(lens=50.0, type="PERSP", ortho_scale=6.0, clip_start=0.1, clip_end=100.0,
@ -114,6 +123,7 @@ class FakeBpy:
for o in self.data.objects.values():
o.selected = o is self.mesh
o.select_get = (lambda o=o: o.selected)
o.modifiers, o.get = [], (lambda key, default=None: default) # no modifier, no custom property
o.select_set = (lambda state, o=o: setattr(o, "selected", state))
add = lambda kind: (lambda mode, undo, **kw: self.add_object(kind, kw, (mode, undo)))
self.ops = NS(import_scene=NS(gltf=self.import_gltf), render=NS(render=self.render_still),
@ -140,7 +150,7 @@ class FakeBpy:
def import_gltf(self, mode, undo, filepath):
assert (mode, undo) == ("EXEC_DEFAULT", False)
self.imported.append(filepath)
self.data.objects["Imported"] = NS(name="Imported", type="MESH", data=None)
self.data.objects["Imported"] = Extras(self.import_extras, name="Imported", type="MESH", data=Extras(self.import_mesh_extras))
def export_gltf(self, mode, undo, **kwargs):
assert (mode, undo) == ("EXEC_DEFAULT", False)
@ -192,6 +202,18 @@ class ActionTests(unittest.TestCase):
self.assertEqual(receipt["status"], "accepted")
self.assertEqual(self.bpy.imported, [str(self.root / "in" / "model.glb")])
self.assertEqual(receipt["objectName"], "Imported")
self.assertEqual(receipt["message"], "Imported 1 object(s) from model.glb.")
def test_import_drops_the_kit_properties_a_file_carries(self):
"""kit_* is brokkr_kitbash's own state: what setObjectCustomProperty refuses, importGltf does not bring in from extras."""
self.bpy.import_extras = {"kit_frozen": None, "kit_part": "tank", "kit_params": "{}", "note": "kept", "kitchen": 1}
self.bpy.import_mesh_extras = {"kit_kept": True, "source": "scan"}
receipt = self.run_action(action="importGltf", filepath="model.glb")
imported = self.bpy.data.objects["Imported"]
self.assertEqual((receipt["status"], dict(imported), dict(imported.data)), ("accepted", {"note": "kept", "kitchen": 1}, {"source": "scan"}))
self.assertIn("Dropped the file's kit_* properties from Imported", receipt["message"])
self.assertEqual(bt.kit_owned("kit_frozen") and bt.kit_owned("kit_anything"), True)
self.assertEqual(bt.kit_owned("kitchen") or bt.kit_owned("akit_x"), False)
def test_import_outside_the_import_dir_is_refused_before_bpy(self):
for path in ("../secret.glb", str(self.root / "secret.glb"), "/etc/passwd.glb", "sub/../../secret.glb"):
@ -291,6 +313,24 @@ class ActionTests(unittest.TestCase):
self.assertEqual(call["selected_at_call"], ["Cam", "Lamp"])
self.assertEqual([o.name for o in self.bpy.data.objects.values() if o.selected], ["Cube"])
def test_export_applying_modifiers_refuses_a_frozen_object_with_a_modifier_shown(self):
mesh = self.bpy.data.objects["Cube"]
mesh.get = lambda key, default=None: "live mesh" if key == "kit_frozen" else default
mesh.modifiers = [NS(show_viewport=False, show_render=False), NS(show_viewport=True, show_render=False)]
for fields in ({}, {"selection": ["Cube"]}):
receipt = self.run_action(action="exportGltf", filepath="dirty.glb", **fields)
self.assertEqual(receipt["status"], "failed", receipt)
self.assertIn("Cube: frozen (brokkr_kitbash.freeze) with a modifier shown again", receipt["message"])
self.assertEqual((self.bpy.exported, list((self.root / "out").iterdir())), ([], []))
for fields in ({"applyModifiers": False}, {"selection": ["Cam"]}): # nothing applied, or the object not exported
receipt = self.run_action(action="exportGltf", filepath=f"ok{len(self.bpy.exported)}.glb", **fields)
self.assertEqual(receipt["status"], "accepted", receipt)
mesh.modifiers[1].show_viewport = False
mesh.modifiers[0].show_render = True # shown in renders only: dirty by the rule brokkr_kitbash's report uses
self.assertIn("with a modifier shown again", self.run_action(action="exportGltf", filepath="render.glb")["message"])
mesh.modifiers[0].show_render = False
self.assertEqual(self.run_action(action="exportGltf", filepath="frozen.glb")["status"], "accepted")
def test_export_without_a_selection_never_touches_selection(self):
def explode(*a, **k):
raise AssertionError("selection touched")

View file

@ -0,0 +1,88 @@
"""Write one object of a .blend as a free cage document, the form brokkr_kitbash.shell's sheet takes.
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tools/cage_export.py -- <copy.blend> <object> <out.json>
For reading a cage a person modelled by hand: its vertex budget, faces, creases and poles, and as the reference
of tools/cage_score.py. <copy.blend> is a COPY of the file, made by whoever runs this: the script opens it, reads
one mesh, writes <out.json> (an absolute path) and nothing else, and never saves a .blend. It refuses to start
unless BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS are private (tools/private_dirs.py).
The document: {"object", "modifiers" (type and name, as stacked), "matrixWorld", "sheet"}. sheet is the cage in
the object's own frame, before any modifier: verts as authored (core.sheet snaps the seam when it builds), faces,
creases from the crease_edge attribute, corners from crease_vert, mirror true when the object carries a Mirror
across x (any other Mirror is refused), rim 0 (a boundary edge carries the crease it was given and no more), and
poles as the faces make them (core.poles). The sheet is what core.sheet accepts: a cage it would refuse (a face of
five sides, a fin on the mirror plane) is refused here with its reason.
A free cage's boundary is smoothed as Blender's Boundary Smooth: All smooths it (core.Sheet.boundary), the setting
of the hand-modelled cages this was made to read. A Subdivision set to Keep Corners draws another surface from the
same cage, so an object carrying one is refused, saying how to state its corners.
"""
import importlib.util
import json
import os
import sys
from pathlib import Path
import bpy
SURFACE = Path(__file__).resolve().parents[1]
def load_core():
spec = importlib.util.spec_from_file_location("brokkr_kitbash_core_tool", SURFACE / "brokkr_kitbash" / "core.py")
core = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = core
spec.loader.exec_module(core)
return core
def export(obj, core) -> dict:
"""The document of a mesh object's cage. Raises core.KitError when the cage is none core.sheet takes."""
if obj.type != "MESH":
raise core.KitError(f"{obj.name!r} is a {obj.type}, not a mesh")
mirrors = [m for m in obj.modifiers if m.type == "MIRROR"]
if len(mirrors) > 1 or mirrors and (tuple(mirrors[0].use_axis) != (True, False, False) or mirrors[0].mirror_object is not None):
raise core.KitError(f"{obj.name!r} is mirrored otherwise than once across its own x: a free cage mirrors across x = 0 only")
kept = [m.name for m in obj.modifiers if m.type == "SUBSURF" and m.boundary_smooth != "ALL"]
if kept:
raise core.KitError(f"{obj.name!r} has its Subdivision {kept[0]!r} at Boundary Smooth Keep Corners, and a free cage smooths its boundary through every vertex: "
"set it to All and give each corner a vertex crease of 1, which draws the same surface")
mesh = obj.data
verts = [[round(float(c), 6) for c in v.co] for v in mesh.vertices]
creases, corners = mesh.attributes.get("crease_edge"), mesh.attributes.get("crease_vert")
sheet = {"verts": verts, "faces": [list(p.vertices) for p in mesh.polygons],
"creases": sorted([*sorted(e.vertices), round(float(creases.data[e.index].value), 4)] for e in mesh.edges if creases.data[e.index].value > 0) if creases else [],
"corners": [[v.index, round(float(corners.data[v.index].value), 4)] for v in mesh.vertices if corners.data[v.index].value > 0] if corners else [],
"mirror": bool(mirrors), "rim": 0.0}
sheet["poles"] = core.poles(sheet)
core.sheet(sheet)
return {"object": obj.name, "modifiers": [[m.type, m.name] for m in obj.modifiers], "matrixWorld": core.rows(obj.matrix_world), "sheet": sheet}
def main() -> int:
sys.path.insert(0, str(Path(__file__).resolve().parent))
import private_dirs
refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind))
if refused:
raise SystemExit(f"cage_export: {refused}")
arguments = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
if len(arguments) != 3 or not Path(arguments[2]).is_absolute():
raise SystemExit("usage: blender --background --factory-startup --python cage_export.py -- <copy.blend> <object> <absolute out.json>")
blend, name, out = arguments
core = load_core()
bpy.ops.wm.open_mainfile(filepath=str(Path(blend).resolve()), load_ui=False, use_scripts=False)
obj = bpy.data.objects.get(name)
if obj is None:
raise SystemExit(f"cage_export: {blend} has no object {name!r}; its meshes: {', '.join(sorted(o.name for o in bpy.data.objects if o.type == 'MESH'))}")
try:
document = export(obj, core)
except core.KitError as error:
raise SystemExit(f"cage_export: {name!r} is no free cage: {error}") from None
Path(out).write_text(json.dumps(document, indent=1), encoding="utf-8")
print("cage_export:", json.dumps({key: core.cage_report(core.sheet(document["sheet"]))[key] for key in ("cageVerts", "cageFaces", "triangles", "creases", "poles", "closed")}), flush=True)
return 0
if __name__ == "__main__":
sys.exit(main())

View file

@ -0,0 +1,210 @@
"""Read how close one free cage comes to another, and what it spends to get there: an agent's cage against a
reference, both in one frame.
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tools/cage_score.py -- <agent.json> <reference.json> <out.json>
Each input is a sheet (either form of brokkr_kitbash.shell's) or a cage_export.py document holding one. Both are
built by brokkr_kitbash.shell through the add-on's own agent turn, at three levels, and read with their Kit
Subsurf alone: the tool measures what the tool builds. <out.json> is an absolute path and the one file written;
no .blend is saved. It refuses to start unless BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and
BLENDER_USER_SCRIPTS are private (tools/private_dirs.py).
The result is a reading with no pass bar. Every percentage is of the reference surface's largest extent.
agent, reference each cage's counts as shell reports them: cageVerts, cageFaces, triangles, creases, corners, poles, closed
extent the reference surface's largest extent, metres
distance between the two level-3 surfaces, whose vertices lie on the limit surface. Each one's vertices
to the nearest point of the other: agentToReference and referenceToAgent {meanPct, maxPct},
the mean weighted by each vertex's share of its surface's area. meanPct is the mean of the two
means, hausdorffPct the larger of the two maxima (one moved vertex shows here), medianPct and
p95Pct the pooled centiles.
silhouetteIoU orthographic silhouettes seen along x, y and z, 512 px across the two surfaces' common box:
intersection over union
crease where each surface is sharp, read off the surface and not off the cage's crease weights: the
level-3 edges between two faces that turn SHARP degrees or more, sampled every 1% of extent.
missPct is the mean distance from the reference's sharp samples to the agent's (a feature the
agent lacks), spurPct the reverse (a feature the reference lacks). A side with sharp samples
against one with none reads 100; two with none read 0. agentSharp and referenceSharp count the
sharp edges.
cost the headline, lower is better, after the energy of Hoppe et al., "Piecewise Smooth Surface
Reconstruction" (SIGGRAPH 1994), E = E_dist + c_rep * vertices + c_sharp * sharp edges: fit is
distance.meanPct + distance.hausdorffPct + the mean of crease.missPct and crease.spurPct;
complexity is C_REP per cage vertex and C_SHARP per creased cage edge of the agent, a sharp
edge a fifth of a vertex as in that paper; total is their sum. C_REP is the fit, in per cent
of extent, that one more cage vertex must buy.
"""
import importlib.util
import json
import math
import os
import sys
import types
from pathlib import Path
import bmesh
import bpy
import numpy as np
from mathutils import Vector
from mathutils.bvhtree import BVHTree
from mathutils.kdtree import KDTree
SURFACE = Path(__file__).resolve().parents[1]
LEVELS, PIXELS, SPACING = 3, 512, 0.01
SHARP = 30.0 # degrees between two level-3 faces at which their edge is a sharp feature
C_REP, C_SHARP = 0.01, 0.002 # per cent of extent: the price of a cage vertex, and of a creased cage edge
COUNTS = ("cageVerts", "cageFaces", "triangles", "creases", "corners", "poles", "closed")
def surface(obj):
"""(V, triangles, area, sharp) of a shell read with its Kit Subsurf alone: area (len(V),) is each vertex's share
of the surface, sharp the (S, 2, 3) end points of the edges between two faces that turn SHARP degrees or more."""
hidden = [m for m in obj.modifiers if m.name != "Kit Subsurf" and m.show_viewport]
for m in hidden:
m.show_viewport = False
try:
bpy.context.view_layer.update()
owner = obj.evaluated_get(bpy.context.evaluated_depsgraph_get())
bm = bmesh.new()
bm.from_mesh(owner.to_mesh())
owner.to_mesh_clear()
finally:
for m in hidden:
m.show_viewport = True
bpy.context.view_layer.update()
bm.normal_update()
V = np.array([v.co[:] for v in bm.verts], dtype=np.float64)
triangles = np.array([[f.verts[0].index, f.verts[k].index, f.verts[k + 1].index] for f in bm.faces for k in range(1, len(f.verts) - 1)], dtype=np.int64)
area = np.zeros(len(V))
for f in bm.faces:
for v in f.verts:
area[v.index] += f.calc_area() / len(f.verts)
sharp = np.array([[e.verts[0].co[:], e.verts[1].co[:]] for e in bm.edges if len(e.link_faces) == 2 and math.degrees(e.calc_face_angle()) >= SHARP], dtype=np.float64).reshape(-1, 2, 3)
bm.free()
return V, triangles, area, sharp
def nearest(points, V, triangles):
tree = BVHTree.FromPolygons([Vector(v) for v in V], [tuple(int(i) for i in t) for t in triangles])
return np.array([tree.find_nearest(Vector(p))[3] for p in points])
def silhouette(V, triangles, axis, low, scale):
"""A PIXELS-square mask of the triangles seen along `axis`, in the frame (low, scale) both surfaces share."""
keep = [k for k in range(3) if k != axis]
P = (V[:, keep] - low[keep]) * scale
mask = np.zeros((PIXELS, PIXELS), dtype=bool)
for a, b, c in P[triangles]:
x0, y0 = np.floor(np.minimum(np.minimum(a, b), c)).astype(int).clip(0, PIXELS - 1)
x1, y1 = np.ceil(np.maximum(np.maximum(a, b), c)).astype(int).clip(0, PIXELS - 1)
area = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
if abs(area) < 1e-12:
continue
X, Y = np.meshgrid(np.arange(x0, x1 + 1) + 0.5, np.arange(y0, y1 + 1) + 0.5)
u = ((b[0] - X) * (c[1] - Y) - (b[1] - Y) * (c[0] - X)) / area
v = ((c[0] - X) * (a[1] - Y) - (c[1] - Y) * (a[0] - X)) / area
mask[y0:y1 + 1, x0:x1 + 1] |= (u >= 0) & (v >= 0) & (u + v <= 1)
return mask
def sampled(segments, step):
"""Points along each segment, its ends included, no further apart than step."""
points = [a + (b - a) * np.linspace(0.0, 1.0, max(2, int(np.ceil(np.linalg.norm(b - a) / step)) + 1))[:, None] for a, b in segments]
return np.concatenate(points) if points else np.zeros((0, 3))
def apart(P, Q, extent):
"""The mean distance from P's points to the nearest of Q's, per cent of extent: 0 for no P, 100 for a P against no Q."""
if not len(P) or not len(Q):
return 100.0 if len(P) else 0.0
tree = KDTree(len(Q))
for k, q in enumerate(Q):
tree.insert(q, k)
tree.balance()
return float(np.mean([tree.find(p)[2] for p in P])) / extent * 100.0
def score(agent: dict, reference: dict, send) -> dict:
"""The reading of two sheets. send(action, **fields) -> (receipt, report) runs an intent; the two shells it
builds (Cage Score Agent, Cage Score Reference) are removed again."""
built, reports = {}, {}
try:
for role, sheet in (("agent", agent), ("reference", reference)):
name = f"Cage Score {role.title()}"
receipt, report = send("brokkr_kitbash.shell", object_name=name, sheet=json.dumps(sheet), levels=LEVELS, thickness=0.001)
if receipt["status"] != "accepted":
raise SystemExit(f"cage_score: the {role} cage was refused: {receipt['message']}")
reports[role] = {key: report[key] for key in COUNTS}
built[role] = surface(bpy.data.objects[name])
finally:
for role in ("agent", "reference"):
obj = bpy.data.objects.get(f"Cage Score {role.title()}")
if obj is not None:
mesh = obj.data
bpy.data.objects.remove(obj)
bpy.data.meshes.remove(mesh)
(VA, TA, WA, SA), (VB, TB, WB, SB) = built["agent"], built["reference"]
extent = float(np.ptp(VB, axis=0).max())
to_reference, to_agent = nearest(VA, VB, TB) / extent * 100.0, nearest(VB, VA, TA) / extent * 100.0
pooled = np.concatenate([to_reference, to_agent])
means = float(np.average(to_reference, weights=WA)), float(np.average(to_agent, weights=WB))
mean, hausdorff = 0.5 * (means[0] + means[1]), float(pooled.max())
both = np.concatenate([VA, VB])
low = both.min(axis=0)
scale = (PIXELS - 1) / float(np.ptp(both, axis=0).max())
overlap = {}
for axis, label in enumerate("xyz"):
a, b = silhouette(VA, TA, axis, low, scale), silhouette(VB, TB, axis, low, scale)
overlap[label] = round(float((a & b).sum() / max(1, (a | b).sum())), 4)
PA, PB = sampled(SA, SPACING * extent), sampled(SB, SPACING * extent)
miss, spur = apart(PB, PA, extent), apart(PA, PB, extent)
fit = mean + hausdorff + 0.5 * (miss + spur)
complexity = C_REP * reports["agent"]["cageVerts"] + C_SHARP * reports["agent"]["creases"]
return {"levels": LEVELS, "agent": reports["agent"], "reference": reports["reference"], "extent": round(extent, 6),
"distance": {"meanPct": round(mean, 4), "hausdorffPct": round(hausdorff, 4), "medianPct": round(float(np.median(pooled)), 4), "p95Pct": round(float(np.percentile(pooled, 95)), 4),
"agentToReference": {"meanPct": round(means[0], 4), "maxPct": round(float(to_reference.max()), 4)},
"referenceToAgent": {"meanPct": round(means[1], 4), "maxPct": round(float(to_agent.max()), 4)}},
"silhouetteIoU": overlap,
"crease": {"sharpDegrees": SHARP, "missPct": round(miss, 4), "spurPct": round(spur, 4), "agentSharp": len(SA), "referenceSharp": len(SB)},
"cost": {"fit": round(fit, 4), "complexity": round(complexity, 4), "total": round(fit + complexity, 4), "cRep": C_REP, "cSharp": C_SHARP}}
def main() -> int:
sys.path.insert(0, str(Path(__file__).resolve().parent))
import private_dirs
refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind))
if refused:
raise SystemExit(f"cage_score: {refused}")
arguments = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
if len(arguments) != 3 or not Path(arguments[2]).is_absolute():
raise SystemExit("usage: blender --background --factory-startup --python cage_score.py -- <agent.json> <reference.json> <absolute out.json>")
sheets = []
for path in arguments[:2]:
document = json.loads(Path(path).read_text(encoding="utf-8"))
sheets.append(document["sheet"] if "sheet" in document else document)
package = types.ModuleType("brokkr_bridge")
package.__path__ = [str(SURFACE / "brokkr_bridge")]
sys.modules["brokkr_bridge"] = package
blender_target = importlib.import_module("brokkr_bridge.blender_target")
import addon_utils
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 = blender_target.BrokkrBlenderTarget(bpy)
target.configure_action_dirs("", str(Path(arguments[2]).parent))
target.reload_host_actions()
count = [0]
def send(action, **fields):
count[0] += 1
receipt = target.run_intent(bpy.context, {"commandId": f"cage-score-{count[0]}", "requestedBy": "tools/cage_score", "action": action, **fields})
return receipt, json.loads(receipt["hostResult"]) if receipt.get("hostResult") else None
result = score(sheets[0], sheets[1], send)
Path(arguments[2]).write_text(json.dumps(result, indent=1), encoding="utf-8")
print("cage_score:", json.dumps(result), flush=True)
return 0
if __name__ == "__main__":
sys.exit(main())