23 KiB
Brokkr Blender Adapter
Install surfaces/blender/brokkr_bridge as a Blender add-on directory during
local development.
The add-on adds a Brokkr panel to the 3D View sidebar and exposes a Blender target surface for host snapshots, admitted command intents, and command receipts.
The adapter writes its mirror documents through CultLib's Python CultMesh node.
If cultcache-py, cultnet-py and cultmesh-py are not installed into
Blender's Python, point CultLib Python Source at the CultLib packages
directory; the add-on puts each package's src on sys.path:
F:/Projects/CultLib/packages
That CultLib checkout must carry cultcache-py's MessagePack payload default
(CultLib main after the py-msgpack-default merge); the add-on refuses an older
one. A .brokkr/blender-editor.ccmp written under the JSON default is
converted into a new file, never in place: close Blender, stop the daemon,
convert, check the new file opens, then swap it in for the original:
py -3 -c "import sys; sys.path.insert(0, r'<brokkr>/surfaces/blender/brokkr_bridge'); import blender_target as t; print(t.convert_store(r'<dir>/blender-editor.ccmp', r'<dir>/blender-editor.mp.ccmp'))"
The command prints the record count and leaves the source unwritten. Records a new daemon already appended (MessagePack) are carried into the new file.
msgpack for a stock Blender
CultLib's cultnet-py and cultcache-py import msgpack, and Blender's Python does
not ship it. Install Brokkr as an extension so Blender installs it for you:
surfaces/blender/brokkr_bridge/blender_manifest.toml lists the bundled wheel
wheels/msgpack-1.2.2-py3-none-any.whl, which Blender unpacks into the extension's own
site-packages when the extension is enabled. Build and install it:
blender --command extension build --source-dir surfaces/blender/brokkr_bridge --output-dir <dist>
blender --command extension install-file --repo user_default --enable <dist>/brokkr_bridge-0.2.0.zip
To try a build without touching your own Blender, run both commands (and any live test) with private
BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories set. Blender 5.3 ignores
BLENDER_USER_RESOURCE_PATH, so install-file under it replaces the user_default copy in your own extensions
folder. The live tests refuse to start without the three variables.
The wheel is one pure-Python msgpack, so the extension carries no platform restriction (Blender 5.3 or
newer, any OS). msgpack then runs its pure-Python fallback, which CultLib 9fc4bdda (PR #180) decodes.
Wheel provenance: msgpack 1.2.2 as installed on the build host (CPython 3.13, the PyPI release; nothing
was downloaded), repacked by tools/build-msgpack-wheel.py from its msgpack/__init__.py, exceptions.py,
ext.py and fallback.py (the _cmsgpack C extension is left out) with the package's METADATA (read as bytes, so its hash is the one PyPI's RECORD lists) and
Apache-2.0 COPYING. The repack is deterministic; rebuild and compare:
python tools/build-msgpack-wheel.py <out-dir>
sha256 91d288892c9622ffe1b3f1430a66956f93ae5964b4dcacf00c4eb93f3f4f65af msgpack-1.2.2-py3-none-any.whl
In a plain add-on directory install the wheel is not unpacked: put msgpack into Blender's Python
yourself. A CultLib package missing a module is reported by that module's name, not as a missing
CultLib package.
The default node cache is:
.brokkr/blender-editor.ccmp
The panel can also serve that node through CultMesh Python. Leave Serve Port
at 0 to bind a free local port, or set a fixed port when another runtime needs
a stable endpoint. The panel reports the active cultnet://host:port endpoint
after Start Server.
Stop and the Agents panel
Stop agents sits at the top of the Brokkr panel. It turns Auto Drain Commands (the command sink) off, then gives
every pending intent a stopped receipt without running it: the same path as Start Server and Stop Server.
Only the operator turns the sink on; no intent writes add-on preferences. The timer runs one intent per tick, so
Stop lands between two intents; an action already running finishes as one undo step, and Ctrl+Z takes it back.
A stopped intent's id is spent. While the sink is off the add-on answers every intent that arrives with a
stopped receipt ("agent commands are off") at once, so brokkr-ctl wait exits 3 and nothing queues to fire when
the operator turns the sink back on. The answer needs a node the add-on has opened (a running server or a published
snapshot).
The Agents section sits directly under Stop agents and lists the agents active in the last five minutes (distinct requestedBy among receipts),
the number of pending intents, and the last eight receipts as <requestedBy> <action> <status> with their note and
undo label. It is a display cache of the node's receipts, rebuilt from the node on first draw. The host snapshot
carries agentCommandsEnabled, which brokkr-ctl blender status prints.
Server Safety
Always on:
Start ServerandStop Serverstop queued command intents: eachbrokkr.blender.command_intent.v0record in the node gets a receipt with statusstoppedthat names the reason, then leaves the queue unrun. Intents queued before a start never run under the new session, and the sender (brokkr-ctl wait, exit 3) learns they were stopped.- After
Start Serverthe panel shows the bind address, port and the filecultmesh_pywas actually loaded from (its__file__, not the preference). - A
Serve Hostthat is not loopback (0.0.0.0, a LAN address, a hostname other thanlocalhost) is refused untilAllow Non-Loopback Bindis ticked in the add-on preferences by hand. While such a server runs the panel shows a warning, and unticking the allow stops it.
Opt-in, default off: Require Session Token. This is internal infrastructure
and the machine's owner judged per-write access control not worth the friction
by default. When ticked, Start Server generates a random token (secrets),
the panel offers Copy Session Token (the token is never drawn on screen), and the server rejects every document put and delete whose
message lacks it in a top-level sessionToken field. It is checked on every
write, not only at connect. Reads stay open. Stop Server, quitting, or
disabling the add-on revokes it; it is held in memory only and never saved to
preferences or the cache.
Peer write scope: CultLib's cultmesh_py refuses peer writes unless an authority grants them, and the add-on
passes CultMeshGrantAllWrites(). A peer that gets past the session token (or any peer, when the token is off) can
therefore put or delete any registered document on the served node, not only command intents. That is acceptable
on loopback, the default; a grant scoped to command intents is future work. Do not combine Allow Non-Loopback Bind
with the token off.
Run the tests (no Blender needed; CULTLIB_PACKAGES adds the real-server tests):
CULTLIB_PACKAGES=F:/Projects/CultLib/packages python -m unittest discover -s surfaces/blender/tests -v
Debug Export Root may still emit readable JSON snapshot and receipt files under
.brokkr/blender-editor-debug. They are export only: nothing reads them back, and
a JSON file placed there is never an intent. CultMesh owns the mirror state, and
intents enter only through the node (brokkr-ctl blender send, a served peer, the
sync organ).
Local Smoke
- Install and enable
brokkr_bridge. - Open
View3D > Sidebar > Brokkr. - Click
Capture Snapshot. - Inspect
.brokkr/blender-editor.ccmp. - Send an intent into the node:
brokkr-ctl blender send createObject --set objectType='"EMPTY"' --agent <name> --no-wait(needsEUREKA_INSTANCEand--store <abs path to .brokkr/blender-editor.ccmp>). - Click
Drain Commands, or enableAuto Drain Commandsto poll command intents once per second while the add-on is loaded. - Read the receipt with
brokkr-ctl blender wait <commandId> --store <path>, or inspect.brokkr/blender-editor.ccmpor the optional debug export at.brokkr/blender-editor-debug/blender/receipts/{commandId}.json. - Click
Start Server. - Use the reported
cultnet://host:portendpoint from a CultMesh/CultNet client to read snapshots or write command intents. - In the
Object Syncsection, set the Unity object id/path and lane toggles, select a Blender object, then clickObject Syncto publish abrokkr.sync.object_binding.v0plus per-lanebrokkr.sync.var.v0records for transform, parent, visibility, material, and custom property sync. - In the
Timeline / Cinemachinesection, set the Unity Timeline and Cinemachine targets, then clickTimeline Syncto publish abrokkr.sync.timeline_binding.v0for Blender frame/action data and Unity Timeline/Cinemachine lanes. - After running
brokkr-daemon sync-onceorsync-loop, clickRefresh Sync Receiptto show the latest daemon sync pass observed in the Blender mirror. KeepAuto Drain Commandsenabled whilesync-loopis running if Blender should continuously consume daemon command intents. - To publish an ad hoc sync variable, fill the
Ad Hoc Sync Varfields in the sidebar or add-on preferences and clickPublish Sync Var.
Command actions and their fields are one table, brokkr_bridge/actions.json (schema
brokkr.blender.actions.v0): each action's fields with their types, enums, bounds, defaults and which
are required, and whether the action changes the scene (one undo step) and is safe in Edit Mode.
brokkr-ctl blender send --help prints it. The add-on admits every intent through that table and
nothing else: an unknown action, an unknown field (a name no action declares), a wrong type, an enum
that is not matched exactly (Blender's identifiers, case included), a number outside its bounds or a
missing required field is refused with a denied receipt that names the field and the rule; nothing
ran and no undo step was pushed. null counts as absent. brokkr-ctl send applies the same table
first and writes nothing for an intent it refuses. What only the scene can judge stays with the action
and answers failed (the object is not found or not the right type, a path escapes its directory, the
engine is not available in this Blender); a failed action that wrote part of its work is one labelled
undo step. Targets are named targetObjectName for the scene actions and objectName for the node
actions; there are no other spellings.
Behaviour the table does not say, per action:
-
createObject: aMESHis a cube ofsize.lightType,emptyDisplayTypeandmeshTypeapply only to their ownobjectType. -
setObjectParent: an empty or absentparentObjectNameclears the parent. Before it writes, each enabled add-on that definesbrokkr_parent_refusal(object, parent)is asked, and a reason it answers refuses the intent with nothing changed (brokkr_kitbashanswers its one-driver rule over the loops the object is part of or stands above,docs/kitbash.md; an object no loop hangs from is never refused by it). -
importGltf:filepath,.gltfor.glb, relative to the add-on preferenceImport Directory(absolute paths,..and symlinks that resolve outside it are refused). EmptyImport Directorydisables the action. Needs Blender's glTF add-on. Custom properties namedkit_*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 preferenceRender Output Directory(the renderStill rules: no.., no links, and an existing name is refused; there is no overwrite).extrasmakes custom properties nodeextras; aselectionnames objects, any name not found, or not in the active view layer, refuses the export; the selection is touched only when one is given, and restored afterwards. The exporter writes into a staging folder beside the target and Brokkr then moves each file into place (the.glb, or the.gltfwith its.binand texture files), refusing the whole export, naming the file, if any of those names is taken: nothing existing is overwritten. A refused or failed export leaves no file and no new folder, so the same name can be retried. Each export holds an OS lock on its staging folder; the next export removes any.brokkr-export-*folder under the output directory whose lock is free (its Blender died), and a rollback that itself fails is refused naming the files left, which that same sweep removes. Not checked: a link or swap made between the check and the move (the same residual as renderStill). The receipt message carries the written path and byte size. Needs Blender's glTF add-on. -
setCamera:targetObjectNamemust be a camera object.panoramaTypeis a property of the camera (Blender 4.2 and newer). Panoramic cameras render in Cycles.cameraTypeleaves outCUSTOM: it runs a script. -
setLight:targetObjectNamemust be a light object.coloris linear. -
setWorld: withoutworldName, the scene's world, created if there is none. Edits the world's Background node. -
assignMaterial:targetObjectNamemust be an object with material slots, such as a mesh. An existing material of that name is reused.coloris linear[r, g, b]or[r, g, b, a], alpha 1 when absent; it sets the Principled BSDF Base Color (the node tree is created if the material has none) anddiffuse_color; a malformedcoloris refused and nothing is created or changed. Withoutcoloran existing material's colour is left as it is. Idempotent per (object, material): if the object already has a slot with that material no second slot is added. -
renderStill:outputPathrelative to the preferenceRender Output Directory, ending.png,.jpgor.exr(same containment rules as import).engineis an engine identifier of the running Blender, matched exactly (Blender is asked by assignment; one it does not have is afailedreceipt). Resolutions are whole numbers of 4 or more: Blender stores 1 to 3 as 4 without a word, so they are refused. Engine, resolution, camera, file path and format are restored after the render. The render blocks Blender's UI until it finishes. In a background (-b) Blender on Linux, the GL enginesBLENDER_WORKBENCH,BLENDER_EEVEEandBLENDER_EEVEE_NEXTare refused with afailedreceipt when a one-pixel test render of that engine does not finish in a child process of the same Blender binary (it aborts, hangs past 120 s, or the binary is unknown). The probe runs once per engine and is cached for the life of the process, so the first GL render after startup waits for it. Rendering would otherwise abort the whole process with no receipt;CYCLESrenders on the CPU. The check applies to the scene's engine whenengineis omitted. A foreground Blender is not probed. -
look: no fields. Captures the 3D view she is looking at (the largest 3D view across the windows, its main region) to<Render Output Directory>/look/<commandId>.pngand puts the absolute path in the receipt'slookPath; refused when the output directory is unset or no 3D view is open. It reads Blender's own framebuffer for that one region, so her desktop and other applications are never in the picture; a menu, popup or the splash Blender draws over the view is, as she sees it. It is a read: no undo step, and it runs in Edit Mode. The capture blocks her UI for about 70 ms.captureSourcesays how it was taken:region, oroffscreenwhen every Blender window is minimised (Windows only; a minimised window stops redrawing, so its framebuffer is a stale frame) and the view's own viewpoint is drawn offscreen at the region's size instead, with her popups and menus not drawn; an offscreen failure is a refusal, never a stale picture.sceneUpdateSeqis the count of depsgraph updates, hers and the agent's, that the picture reflects. The look directory keeps the newest 20 PNGs (scratch, never read back). The receipt also carriessessionId,humanEditSeq,humanEditsSinceLookandeditedSinceLook(object names), counted for the sendingrequestedBysince its previous look in this session, andeditSelection: for each object in Edit Mode its selected vertex, edge and face indices (each list capped at 4096, the true count beside it asverticesTotaland so on; non-mesh objects sayunsupported). The host snapshot carries the samesessionId,humanEditSeq,editSelectionand each object'slastHumanEditSeq. The sequences come from depsgraph updates outside an agent turn, counted per flagged object (transform, geometry or shading) and from undo and redo; opening a file starts a new session. An update also flags objects that only depend on what she changed (a constrained follower), and adding or linking an object flags all of them, soeditedSinceLookcan name more than she touched; the receipt then says so:editedSinceLookCoarseis true, with the reason ineditedSinceLookNote(an update that flagged every object, or an undo or redo). Selection totals are the mesh's own counts and the index scan stops at the cap. They are observations: no intent is refused because of them.
Host add-on actions
A host add-on (Aetheria's aetheria_ships, say) lets agents run some of its own operators by putting a file
brokkr_actions.json beside its __init__.py: {"schema": "brokkr.blender.host_actions.v0", "actions": [row]}.
The add-on imports nothing from Brokkr and registers nothing; the file is the whole contract.
surfaces/blender/tests/fixtures/brokkr_host_fixture/ is a worked example.
A row is a built-in row (name, doc, changesScene, editModeSafe, fields) plus an optional result.
name is the bl_idname of an operator the same add-on registers (addon.operator, lower case, one dot, so
it never equals a built-in name). Fields are scalar only: string (with enum, minLength, maxLength,
chars, prefixes, forbid), number or integer (both with minimum and maximum) and boolean,
with required and default as for built-ins; no arrays, objects or free JSON, and no envelope or
charsets keys. The messages are the built-in ones.
Brokkr admits a file whole or not at all, and reads it only when a human asks: once shortly after Brokkr
registers, and whenever she presses Reload Host Actions in the Brokkr panel. No intent, snapshot or agent
turn re-reads a file (the operator refuses inside a turn), so rewriting brokkr_actions.json to list
another operator admits nothing until she reloads; press it after enabling a host add-on or editing its
file. A file is checked when it is read, and the live checks below run at every intent and snapshot, so a
disabled add-on's actions are unknown at its next intent. A field may not be named like an envelope key
(schema, commandId, action, requestedBy, note): Brokkr writes those itself, so the operator would
never receive the agent's value. The live checks: each named operator exists and is a Python class defined by
that add-on's module (the module itself or under it: aetheria_ships is not aetheria's), every field is a
property of the operator of the matching type (a string with an enum is an enum property with the same
identifiers), the operator's RNA hard limits contain the row's bounds, a row with changesScene false names
no operator whose bl_options has UNDO, and result names a writable StringProperty on
bpy.types.WindowManager. A refused file is reported in the host snapshot as hostActionErrors
(brokkr-ctl blender status prints each) and none of its rows runs.
changesScene and editModeSafe are the host's word: Brokkr cannot see what an operator writes. A row that
claims to change nothing but writes gets no undo step and no Edit Mode refusal, so keep the flags honest. An
operator that calls bpy.ops.ed.undo_push itself adds that step to Brokkr's own (two for one action), or
one with changesScene false; that is a documented limit, not checked. A poll that fails, or a result
property that cannot be cleared, refuses before anything runs and pushes no undo step.
An admitted action goes through the same agent turn as a built-in: Edit Mode refusal for rows that are not
editModeSafe, one labelled undo step when changesScene, a receipt. The operator is called with
'EXEC_DEFAULT' and exactly the declared fields. It runs on Blender's main thread, so a long operator
blocks the interface for as long as her own button would. FINISHED is accepted; CANCELLED is failed
with nothing pushed; an argument Blender will not convert, or an ERROR report or exception, is failed
(with the first line of the error). result is how an operator returns text (a dry-run's change lines): the
agent turn clears that WindowManager property before the call and copies it, up to 16000 characters and then
[truncated], into the receipt's hostResult (empty for every other action).
surfaces/blender/brokkr_mesh_polish is a host add-on that ships with Brokkr (mesh-polish.md), and
surfaces/blender/tools/run_intents.py runs a list of intents, host rows included, in a background Blender.
The admitted rows are published in the host snapshot as hostActions (each with its host module).
brokkr-ctl blender send --help --store <path> lists them after the built-ins, send refuses an intent
they refuse before writing anything, and the add-on still decides. Human-only is absence: an operator only a
person may run (one that applies a change to a game's data) is left out of the file, so an intent naming it
is Unsupported Blender command action, as runPython is; the person still presses her own button.
The scene actions were run against Blender 5.2.3 LTS headless with
surfaces/blender/tests/live/headless_smoke.py (usage in its docstring). One real
failure it found: Blender's engine enum is dynamic, so bl_rna lists only
BLENDER_EEVEE; renderStill now asks Blender by assignment instead. tests/live/export_gltf.py and
tests/live/refusals.py (Blender 5.3.0 headless, usage in their docstrings) run exportGltf against the
real exporter and the render probe and meshType refusal against real bpy.
Path rules and the residual race
Both directories take plain relative names only, judged as text the same on every OS:
no drive (C:, C:foo), UNC or \\?\ form, leading separator, .., NUL, : anywhere
(also NTFS streams), trailing dot or space, or Windows device name. No existing component
may be a symlink or junction (Windows' "untrusted mount point" error on a junction counts
as one). renderStill refuses any output name that already exists, including symlinks
(even dangling) and hardlinks. importGltf parses the .gltf JSON (or a .glb's first
chunk) and refuses every buffers[].uri / images[].uri that is not data: or a
relative path inside the import directory; .gltf files from the same folder tree work.
Residual TOCTOU. The checks run in the add-on, and the path is re-checked (resolved name, plus size and modification time of the file and its references) immediately before use, but Blender's own importer and renderer then open the files themselves. Someone who can write to the import or output directory in that last gap can still swap a file or link in. The add-on cannot close that window from Python: make both directories writable only by trusted users, and treat the checks as protection against a malicious intent, not against a hostile local writer. A same-size, same-mtime content swap is also not detected by the re-check.