From a371056f04ad5daee879cb5dc915f6b07132090b Mon Sep 17 00:00:00 2001 From: Eureka Date: Fri, 27 Nov 2026 18:59:16 +0000 Subject: [PATCH 01/63] Brokkr on MessagePack payloads: strict reads through cultcache-rs, pins at CultLib baf4ecf7 (#11) --- Cargo.lock | 134 +++++++++- brokkr-daemon/Cargo.toml | 2 +- brokkr-daemon/src/main.rs | 237 +++++++++++++----- .../blender/brokkr_bridge/blender_target.py | 51 +++- surfaces/blender/docs/install.md | 12 + surfaces/blender/tests/test_store_convert.py | 129 ++++++++++ tools/check.ps1 | 3 + 7 files changed, 486 insertions(+), 82 deletions(-) create mode 100644 surfaces/blender/tests/test_store_convert.py diff --git a/Cargo.lock b/Cargo.lock index 6736cc7..dabf833 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -17,6 +17,15 @@ version = "1.0.102" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" +[[package]] +name = "ar_archive_writer" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec" +dependencies = [ + "object", +] + [[package]] name = "autocfg" version = "1.5.1" @@ -29,6 +38,15 @@ version = "2.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "brokkr-daemon" version = "0.1.0" @@ -83,10 +101,29 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "cultcache-rs" -version = "0.1.0" -source = "git+https://github.com/GameCult/CultLib.git?rev=c2a9a6e526390808ef195759056fda0b9a55d8a3#c2a9a6e526390808ef195759056fda0b9a55d8a3" +version = "0.3.1" +source = "git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb#baf4ecf78fae634fafef956d3b85420162c074bb" dependencies = [ "anyhow", "chrono", @@ -97,20 +134,33 @@ dependencies = [ "serde", "serde_bytes", "serde_json", + "serde_stacker", + "sha2", + "stacker", "uuid", "windows-sys 0.59.0", ] [[package]] name = "cultcache-rs-derive" -version = "0.1.0" -source = "git+https://github.com/GameCult/CultLib.git?rev=c2a9a6e526390808ef195759056fda0b9a55d8a3#c2a9a6e526390808ef195759056fda0b9a55d8a3" +version = "0.2.0" +source = "git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb#baf4ecf78fae634fafef956d3b85420162c074bb" dependencies = [ "proc-macro2", "quote", "syn", ] +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + [[package]] name = "equivalent" version = "1.0.2" @@ -179,6 +229,16 @@ dependencies = [ "slab", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "getrandom" version = "0.4.2" @@ -311,6 +371,15 @@ dependencies = [ "autocfg", ] +[[package]] +name = "object" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +dependencies = [ + "memchr", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -342,6 +411,16 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "psm" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" +dependencies = [ + "ar_archive_writer", + "cc", +] + [[package]] name = "quote" version = "1.0.45" @@ -463,6 +542,28 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_stacker" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4936375d50c4be7eff22293a9344f8e46f323ed2b3c243e52f89138d9bb0f4a" +dependencies = [ + "serde", + "serde_core", + "stacker", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "shlex" version = "2.0.1" @@ -475,6 +576,19 @@ version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" +[[package]] +name = "stacker" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys 0.61.2", +] + [[package]] name = "syn" version = "2.0.117" @@ -499,6 +613,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "unicode-ident" version = "1.0.24" @@ -522,6 +642,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + [[package]] name = "wasip2" version = "1.0.4+wasi-0.2.12" diff --git a/brokkr-daemon/Cargo.toml b/brokkr-daemon/Cargo.toml index 5839b77..58bbccf 100644 --- a/brokkr-daemon/Cargo.toml +++ b/brokkr-daemon/Cargo.toml @@ -6,7 +6,7 @@ publish = false [dependencies] anyhow = "1" -cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c2a9a6e526390808ef195759056fda0b9a55d8a3", package = "cultcache-rs" } +cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "baf4ecf78fae634fafef956d3b85420162c074bb", package = "cultcache-rs" } rmp-serde = "1.3" serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/brokkr-daemon/src/main.rs b/brokkr-daemon/src/main.rs index 48600c5..f83e29b 100644 --- a/brokkr-daemon/src/main.rs +++ b/brokkr-daemon/src/main.rs @@ -767,7 +767,7 @@ fn run_sync_once(args: &SyncArgs) -> Result { &source.local_position, ); if !args.dry_run { - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.command_intent.v0", &format!("blender/commands/{command_id}"), &command, @@ -843,7 +843,7 @@ fn run_sync_once(args: &SyncArgs) -> Result { "scale": source.local_scale, }); if !args.dry_run { - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.command_intent.v0", &format!( "blender/commands/{}", @@ -874,7 +874,7 @@ fn run_sync_once(args: &SyncArgs) -> Result { "visible": source.active_self, }); if !args.dry_run { - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.command_intent.v0", &format!( "blender/commands/{}", @@ -924,7 +924,7 @@ fn run_sync_once(args: &SyncArgs) -> Result { &parent_name, ); if !args.dry_run { - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.command_intent.v0", &format!("blender/commands/{command_id}"), &command, @@ -961,7 +961,7 @@ fn run_sync_once(args: &SyncArgs) -> Result { material, ); if !args.dry_run { - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.command_intent.v0", &format!("blender/commands/{command_id}"), &command, @@ -1013,7 +1013,7 @@ fn run_sync_once(args: &SyncArgs) -> Result { "value": property.value, }); if !args.dry_run { - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.command_intent.v0", &format!( "blender/commands/{}", @@ -1368,8 +1368,8 @@ fn run_sync_once(args: &SyncArgs) -> Result { "sync/receipts/{}", receipt["receiptId"].as_str().unwrap_or("sync-receipt") ); - unity_store.put_json_document("brokkr.sync.receipt.v0", &receipt_key, &receipt)?; - blender_store.put_json_document("brokkr.sync.receipt.v0", &receipt_key, &receipt)?; + unity_store.put_messagepack_document("brokkr.sync.receipt.v0", &receipt_key, &receipt)?; + blender_store.put_messagepack_document("brokkr.sync.receipt.v0", &receipt_key, &receipt)?; report.receipts_written += 2; } @@ -1390,9 +1390,10 @@ impl MirrorStore { fn documents(&mut self) -> Result> { let mut documents = Vec::new(); for envelope in self.store.pull_all()? { - let value = decode_payload(&envelope).with_context(|| { - format!("failed to decode {} at {}", envelope.r#type, envelope.key) - })?; + let value = + cultcache_rs::decode_payload::(&envelope.payload).with_context(|| { + format!("failed to decode {} at {}", envelope.r#type, envelope.key) + })?; documents.push(CacheDocument { key: envelope.key, value, @@ -1401,17 +1402,6 @@ impl MirrorStore { Ok(documents) } - fn put_json_document(&mut self, schema: &str, key: &str, value: &Value) -> Result<()> { - let payload = serde_json::to_vec(value)?; - self.store.push(&CultCacheEnvelope { - key: key.to_string(), - r#type: schema.to_string(), - payload, - stored_at: chrono_like_now(), - schema_id: Some(schema.to_string()), - }) - } - fn put_messagepack_document(&mut self, schema: &str, key: &str, value: &Value) -> Result<()> { let payload = rmp_serde::to_vec(value)?; self.store.push(&CultCacheEnvelope { @@ -1420,21 +1410,11 @@ impl MirrorStore { payload, stored_at: chrono_like_now(), schema_id: Some(schema.to_string()), - }) + })?; + Ok(()) } } -fn decode_payload(envelope: &CultCacheEnvelope) -> Result { - serde_json::from_slice(&envelope.payload) - .or_else(|_| rmp_serde::from_slice(&envelope.payload)) - .with_context(|| { - format!( - "payload is neither MessagePack nor JSON for {}", - envelope.key - ) - }) -} - fn parse_object_binding(value: &Value) -> Option { Some(ObjectBinding { binding_id: field_string(value, 1, "bindingId")?, @@ -2699,7 +2679,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ @@ -2714,7 +2694,7 @@ mod tests { }] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -2729,7 +2709,7 @@ mod tests { "authority": authority }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.var.v0", "sync/vars/var-cube-transform", &json!({ @@ -2746,7 +2726,7 @@ mod tests { }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -2772,7 +2752,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ @@ -2787,7 +2767,7 @@ mod tests { }] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -2802,7 +2782,7 @@ mod tests { "authority": "unity-to-blender" }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ "objects": [] }), @@ -2815,12 +2795,12 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ "sceneObjects": [] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -2834,7 +2814,7 @@ mod tests { "authority": "blender-to-unity" }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -2856,7 +2836,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ @@ -2883,7 +2863,7 @@ mod tests { ] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-rig", &json!({ @@ -2898,7 +2878,7 @@ mod tests { "authority": authority }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -2913,7 +2893,7 @@ mod tests { "authority": authority }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.var.v0", "sync/vars/var-cube-parent", &json!({ @@ -2929,7 +2909,7 @@ mod tests { "enabled": true }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -2963,7 +2943,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ @@ -2979,7 +2959,7 @@ mod tests { }] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -2994,7 +2974,7 @@ mod tests { "authority": authority }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.var.v0", "sync/vars/var-cube-material", &json!({ @@ -3010,7 +2990,7 @@ mod tests { "enabled": true }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -3033,7 +3013,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ @@ -3048,7 +3028,7 @@ mod tests { }] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -3063,7 +3043,7 @@ mod tests { "authority": "blender-to-unity" }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.var.v0", "sync/vars/var-cube-active", &json!({ @@ -3079,7 +3059,7 @@ mod tests { "enabled": true }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -3106,7 +3086,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ @@ -3131,7 +3111,7 @@ mod tests { }] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -3146,7 +3126,7 @@ mod tests { "authority": "unity-to-blender" }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.var.v0", "sync/vars/var-cube-component-speed", &json!({ @@ -3162,7 +3142,7 @@ mod tests { "enabled": true }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -3189,7 +3169,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ @@ -3204,7 +3184,7 @@ mod tests { }] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -3219,7 +3199,7 @@ mod tests { "authority": "blender-to-unity" }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.var.v0", "sync/vars/var-cube-custom-intensity", &json!({ @@ -3235,7 +3215,7 @@ mod tests { "enabled": true }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -3261,7 +3241,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.timeline_binding.v0", "sync/bindings/timelines/timeline-camera", &json!({ @@ -3280,7 +3260,7 @@ mod tests { "enabled": true }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -3329,4 +3309,127 @@ mod tests { ); Ok(()) } + + fn raw_envelope(key: &str, payload: Vec) -> CultCacheEnvelope { + CultCacheEnvelope { + key: key.to_string(), + r#type: "brokkr.sync.receipt.v0".to_string(), + payload, + stored_at: chrono_like_now(), + schema_id: Some("brokkr.sync.receipt.v0".to_string()), + } + } + + #[test] + fn store_read_refuses_trailing_bytes() -> Result<()> { + let temp = tempfile::tempdir()?; + let path = temp.path().join("store.ccmp"); + let mut raw = SingleFileMessagePackBackingStore::new(&path); + let clean = rmp_serde::to_vec(&json!({"a": 1}))?; + raw.push(&raw_envelope("k/clean", clean.clone()))?; + let documents = MirrorStore::open(&path)?.documents()?; + assert_eq!(documents.len(), 1); + assert_eq!(documents[0].value, json!({"a": 1})); + + let mut dirty = clean; + dirty.push(0xc0); + raw.push(&raw_envelope("k/dirty", dirty))?; + let message = format!("{:#}", MirrorStore::open(&path)?.documents().unwrap_err()); + assert!(message.contains("k/dirty"), "{message}"); + assert!(!message.to_lowercase().contains("c0"), "{message}"); + Ok(()) + } + + #[test] + fn store_read_refuses_json_payload() -> Result<()> { + let temp = tempfile::tempdir()?; + let path = temp.path().join("store.ccmp"); + let receipt = json!({"schema": "brokkr.sync.receipt.v0", "status": "ok"}); + SingleFileMessagePackBackingStore::new(&path).push(&raw_envelope( + "sync/receipts/json", + serde_json::to_vec(&receipt)?, + ))?; + let message = format!("{:#}", MirrorStore::open(&path)?.documents().unwrap_err()); + assert!(message.contains("sync/receipts/json"), "{message}"); + Ok(()) + } + + #[test] + fn sync_once_writes_unity_active_state_to_blender_visibility_command() -> Result<()> { + let temp = tempfile::tempdir()?; + let unity_path = temp.path().join("unity.ccmp"); + let blender_path = temp.path().join("blender.ccmp"); + seed_component_property_stores(&unity_path, &blender_path, "active-state")?; + + let report = run_sync_once(&SyncArgs { + unity_cache: unity_path, + blender_cache: blender_path.clone(), + dry_run: false, + })?; + + assert_eq!(report.blender_commands_written, 1, "{report:#?}"); + let command = MirrorStore::open(&blender_path)? + .documents()? + .into_iter() + .find(|document| document.key.starts_with("blender/commands/")) + .expect("Brokkr should emit a Blender visibility command"); + assert_eq!(command.value["action"], "setObjectVisibility"); + assert_eq!(command.value["targetObjectName"], "Cube"); + assert_eq!(command.value["visible"], true); + Ok(()) + } + + #[test] + fn dry_run_counts_active_state_command_but_writes_none() -> Result<()> { + let temp = tempfile::tempdir()?; + let unity_path = temp.path().join("unity.ccmp"); + let blender_path = temp.path().join("blender.ccmp"); + seed_component_property_stores(&unity_path, &blender_path, "active-state")?; + + let report = run_sync_once(&SyncArgs { + unity_cache: unity_path, + blender_cache: blender_path.clone(), + dry_run: true, + })?; + + assert_eq!(report.blender_commands_written, 1, "{report:#?}"); + assert!( + MirrorStore::open(&blender_path)? + .documents()? + .iter() + .all(|document| !document.key.starts_with("blender/commands/")), + "a dry run must not write a command intent" + ); + Ok(()) + } + + #[test] + fn sync_once_writes_messagepack_receipts() -> Result<()> { + let temp = tempfile::tempdir()?; + let unity_path = temp.path().join("unity.ccmp"); + let blender_path = temp.path().join("blender.ccmp"); + seed_sync_stores(&unity_path, &blender_path, "unity-to-blender")?; + run_sync_once(&SyncArgs { + unity_cache: unity_path.clone(), + blender_cache: blender_path.clone(), + dry_run: false, + })?; + + for path in [&unity_path, &blender_path] { + let store = SingleFileMessagePackBackingStore::new(path); + let envelopes = store.pull_all()?; + let receipt = envelopes + .iter() + .find(|envelope| envelope.r#type == "brokkr.sync.receipt.v0") + .expect("store should hold the daemon sync receipt"); + let lead = receipt.payload.first().copied().unwrap_or(0); + assert!( + (0x80..=0x8f).contains(&lead) || lead == 0xde || lead == 0xdf, + "receipt payload should be a MessagePack map, led by {lead:#04x}" + ); + assert!(serde_json::from_slice::(&receipt.payload).is_err()); + assert!(cultcache_rs::decode_payload::(&receipt.payload)?.is_object()); + } + Ok(()) + } } diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 0c49412..677f03d 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -1026,16 +1026,7 @@ class BrokkrBlenderTarget: return self._node, self._documents cultmesh, cultcache = _load_cultmesh(cultlib_py_src) - documents = { - "host_snapshot": cultcache.define_document_type(HOST_SNAPSHOT_SCHEMA), - "command_intent": cultcache.define_document_type(COMMAND_INTENT_SCHEMA), - "command_receipt": cultcache.define_document_type(COMMAND_RECEIPT_SCHEMA), - "sync_session": cultcache.define_document_type(SYNC_SESSION_SCHEMA), - "sync_object_binding": cultcache.define_document_type(SYNC_OBJECT_BINDING_SCHEMA), - "sync_var": cultcache.define_document_type(SYNC_VAR_SCHEMA), - "sync_timeline_binding": cultcache.define_document_type(SYNC_TIMELINE_BINDING_SCHEMA), - "sync_receipt": cultcache.define_document_type(SYNC_RECEIPT_SCHEMA), - } + documents = bridge_documents(cultcache) node = cultmesh.CultMesh.start_node(path, runtime_id=runtime_id) for document in documents.values(): node.database.register_document(document) @@ -1095,6 +1086,41 @@ class BrokkrBlenderTarget: }) +def bridge_documents(cultcache: Any) -> dict[str, Any]: + """The bridge's eight document definitions, under cultcache-py's default (MessagePack) payload codec.""" + return { + "host_snapshot": cultcache.define_document_type(HOST_SNAPSHOT_SCHEMA), + "command_intent": cultcache.define_document_type(COMMAND_INTENT_SCHEMA), + "command_receipt": cultcache.define_document_type(COMMAND_RECEIPT_SCHEMA), + "sync_session": cultcache.define_document_type(SYNC_SESSION_SCHEMA), + "sync_object_binding": cultcache.define_document_type(SYNC_OBJECT_BINDING_SCHEMA), + "sync_var": cultcache.define_document_type(SYNC_VAR_SCHEMA), + "sync_timeline_binding": cultcache.define_document_type(SYNC_TIMELINE_BINDING_SCHEMA), + "sync_receipt": cultcache.define_document_type(SYNC_RECEIPT_SCHEMA), + } + + +def convert_store(source: str, destination: str, cultlib_py_src: str = "") -> int: + """Write the records of a bridge store to a new MessagePack file and return the count converted. + JSON payloads (the old default) are converted; MessagePack payloads, such as records the new daemon already + appended to the old store, are carried through. The destination must not exist and the source is never written: + stop every writer, convert, then swap the files.""" + _cultmesh, cultcache = _load_cultmesh(cultlib_py_src) + json_codec, msgpack_codec = cultcache.JSON_PAYLOAD_CODEC, cultcache.MESSAGEPACK_PAYLOAD_CODEC + + def decode_either(payload: bytes) -> Any: + # A JSON object or array never starts like a MessagePack map or array, so a payload JSON refuses is MessagePack. + try: + return json_codec.decode(payload) + except Exception: + return msgpack_codec.decode(payload) + + either = cultcache.PayloadCodec("JSON or MessagePack", json_codec.encode, decode_either) + return cultcache.convert( + cultcache.SingleFileMessagePackBackingStore(source), destination, bridge_documents(cultcache).values(), + source_codec=either) + + def _load_cultmesh(cultlib_py_src: str) -> tuple[Any, Any]: packages = Path(cultlib_py_src or DEFAULT_CULTLIB_PY_SRC) for name in CULTLIB_PY_PACKAGES: @@ -1111,6 +1137,11 @@ def _load_cultmesh(cultlib_py_src: str) -> tuple[Any, Any]: "Brokkr Blender target requires CultLib's Python packages. Set CultLib Python Source " "to the CultLib packages directory or install cultcache-py, cultnet-py and cultmesh-py into Blender's Python." ) from exc + if not hasattr(cultcache_py, "convert"): + raise RuntimeError( + "Brokkr Blender target requires CultLib's cultcache-py with the MessagePack payload default " + "(CultLib main after the py-msgpack-default merge); the cultcache-py found here predates it. " + "Update the CultLib checkout named by CultLib Python Source.") return cultmesh_py, cultcache_py diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index f27093b..3b3a93d 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -16,6 +16,18 @@ 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: + +```text +py -3 -c "import sys; sys.path.insert(0, r'/surfaces/blender/brokkr_bridge'); import blender_target as t; print(t.convert_store(r'/blender-editor.ccmp', r'/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. + The default node cache is: ```text diff --git a/surfaces/blender/tests/test_store_convert.py b/surfaces/blender/tests/test_store_convert.py new file mode 100644 index 0000000..17d6506 --- /dev/null +++ b/surfaces/blender/tests/test_store_convert.py @@ -0,0 +1,129 @@ +"""convert_store and the CultLib guard. No Blender, no bpy. + +Run: CULTLIB_PACKAGES= python3 -m unittest discover -s surfaces/blender/tests -v +Needs the msgpack package and CultLib main with cultcache-py's MessagePack payload default. +""" +from __future__ import annotations + +import hashlib +import os +import sys +import tempfile +import types +import unittest +from pathlib import Path + +ADDON = Path(__file__).resolve().parents[1] / "brokkr_bridge" +package = types.ModuleType("brokkr_bridge") +package.__path__ = [str(ADDON)] +sys.modules.setdefault("brokkr_bridge", package) + +from brokkr_bridge import blender_target as bt # noqa: E402 + +PACKAGES = os.environ.get("CULTLIB_PACKAGES", "") + + +def sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +@unittest.skipUnless(PACKAGES and Path(PACKAGES).is_dir(), "set CULTLIB_PACKAGES to CultLib's packages directory") +class ConvertStoreTests(unittest.TestCase): + def setUp(self): + self.cultmesh, self.cultcache = bt._load_cultmesh(PACKAGES) + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.dir = Path(self.temp.name) + self.source = self.dir / "blender-editor.ccmp" + self.records = {} + old_definitions = [ + self.cultcache.define_document_type(d.type, payload_codec=self.cultcache.JSON_PAYLOAD_CODEC) + for d in bt.bridge_documents(self.cultcache).values() + ] + node = self.cultmesh.CultMesh.start_node(str(self.source), runtime_id="brokkr-test") + for definition in old_definitions: + node.database.register_document(definition) + key = f"test/{definition.type}" + value = {"schema": definition.type, "id": key, "n": 7, "nested": {"a": [1, 2, "é"]}} + node.database.put(definition, key, value) + self.records[(definition.type, key)] = value + # What the old daemon wrote: a raw JSON receipt envelope. + receipt = {"schema": bt.SYNC_RECEIPT_SCHEMA, "receiptId": "r1", "status": "ok"} + store = self.cultcache.SingleFileMessagePackBackingStore(self.source) + import json + store.push(self.cultcache.CultCacheEnvelope( + key="sync/receipts/r1", type=bt.SYNC_RECEIPT_SCHEMA, payload=json.dumps(receipt).encode(), + stored_at="2026-11-27T00:00:00Z", schema_id=bt.SYNC_RECEIPT_SCHEMA)) + self.records[(bt.SYNC_RECEIPT_SCHEMA, "sync/receipts/r1")] = receipt + + def test_converted_store_opens_under_default(self): + import msgpack + before = sha256(self.source) + destination = self.dir / "blender-editor.mp.ccmp" + count = bt.convert_store(str(self.source), str(destination), PACKAGES) + self.assertEqual(count, len(self.records)) + self.assertEqual(sha256(self.source), before) + + node = self.cultmesh.CultMesh.start_node(str(destination), runtime_id="brokkr-test-new") + documents = bt.bridge_documents(self.cultcache) + for document in documents.values(): + node.database.register_document(document) + node.database.pull() + snapshot = node.database.snapshot() + for (schema, key), value in self.records.items(): + self.assertEqual(snapshot[schema][key], value, (schema, key)) + for envelope in self.cultcache.SingleFileMessagePackBackingStore(destination).pull_all(): + decoded = msgpack.unpackb(envelope.payload, raw=False) # raises ExtraData on a trailing byte + self.assertIsInstance(decoded, dict, envelope.key) + + def test_mixed_store_converts_json_and_carries_messagepack(self): + import msgpack + # What the new daemon appends to an old store before the operator converts it. + appended = {"schema": bt.SYNC_RECEIPT_SCHEMA, "receiptId": "r2", "status": "ok"} + self.cultcache.SingleFileMessagePackBackingStore(self.source).push(self.cultcache.CultCacheEnvelope( + key="sync/receipts/r2", type=bt.SYNC_RECEIPT_SCHEMA, payload=msgpack.packb(appended), + stored_at="2026-11-27T01:00:00Z", schema_id=bt.SYNC_RECEIPT_SCHEMA)) + before = sha256(self.source) + destination = self.dir / "mixed.mp.ccmp" + self.assertEqual(bt.convert_store(str(self.source), str(destination), PACKAGES), len(self.records) + 1) + self.assertEqual(sha256(self.source), before) + node = self.cultmesh.CultMesh.start_node(str(destination), runtime_id="brokkr-test-mixed") + for document in bt.bridge_documents(self.cultcache).values(): + node.database.register_document(document) + node.database.pull() + snapshot = node.database.snapshot() + self.assertEqual(snapshot[bt.SYNC_RECEIPT_SCHEMA]["sync/receipts/r2"], appended) + for (schema, key), value in self.records.items(): + self.assertEqual(snapshot[schema][key], value, (schema, key)) + + def test_convert_store_writes_only_a_new_file(self): + destination = self.dir / "new.ccmp" + bt.convert_store(str(self.source), str(destination), PACKAGES) + source_bytes, destination_bytes = self.source.read_bytes(), destination.read_bytes() + with self.assertRaises(Exception) as caught: + bt.convert_store(str(self.source), str(destination), PACKAGES) + self.assertIn("destination_exists", str(caught.exception)) + self.assertEqual(self.source.read_bytes(), source_bytes) + self.assertEqual(destination.read_bytes(), destination_bytes) + + +class LoadGuardTests(unittest.TestCase): + def test_load_cultmesh_refuses_json_default_cultcache(self): + names = ("cultcache_py", "cultmesh_py") + saved = {name: sys.modules.get(name) for name in names} + try: + sys.modules["cultcache_py"] = types.ModuleType("cultcache_py") # no convert + sys.modules["cultmesh_py"] = types.ModuleType("cultmesh_py") + with self.assertRaises(RuntimeError) as caught: + bt._load_cultmesh("") + self.assertIn("MessagePack payload default", str(caught.exception)) + finally: + for name, module in saved.items(): + if module is None: + sys.modules.pop(name, None) + else: + sys.modules[name] = module + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/check.ps1 b/tools/check.ps1 index c5d8dbb..e0aba41 100644 --- a/tools/check.ps1 +++ b/tools/check.ps1 @@ -88,6 +88,9 @@ try { } & $pythonExe -c "import sys, tempfile; sys.path.insert(0, r'surfaces\blender\brokkr_bridge'); import blender_target; cultmesh, cultcache = blender_target._load_cultmesh(r'$cultLibPackages'); doc = cultcache.define_document_type('brokkr.check.v0'); node = cultmesh.CultMesh.start_node(tempfile.NamedTemporaryFile(suffix='.ccmp').name, runtime_id='brokkr-check'); node.database.register_document(doc); node.database.put(doc, 'check', {'ok': True}); assert node.database.snapshot()['brokkr.check.v0']['check']['ok'] is True; server = cultmesh.CultMesh.serve_node(node, host='127.0.0.1', port=0); assert server.port > 0; server.stop()" Assert-NativeSuccess "Blender adapter CultMesh import" + $env:CULTLIB_PACKAGES = $cultLibPackages + & $pythonExe -m unittest discover -s surfaceslender ests + Assert-NativeSuccess "Blender adapter unit tests" } finally { Pop-Location From 04954c05006d6adcefb6db5a51f88cec036ac14e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 18:02:26 +0100 Subject: [PATCH 02/63] Live collaboration target: invariants, probes, identity table Target document for the brokkr-live campaign: the agent works in the same live Blender scene the operator is looking at. Records the Blender 5.3 timer-undo and viewport-capture probes the invariants stand on, and the identity, lifecycle and authority table for every kind the layer adds. Co-Authored-By: Claude Opus 5.5 --- docs/live-collab-target.md | 203 ++++++++++++++++++ docs/research/live-collab/probe_look.py | 68 ++++++ docs/research/live-collab/probe_timer_undo.py | 146 +++++++++++++ 3 files changed, 417 insertions(+) create mode 100644 docs/live-collab-target.md create mode 100644 docs/research/live-collab/probe_look.py create mode 100644 docs/research/live-collab/probe_timer_undo.py diff --git a/docs/live-collab-target.md b/docs/live-collab-target.md new file mode 100644 index 0000000..acbdb07 --- /dev/null +++ b/docs/live-collab-target.md @@ -0,0 +1,203 @@ +# Brokkr live collaboration: target + +Campaign `brokkr-live` (Nibu's mind). Working branch `nibu/live-collab-target`, base +`origin/main` 5e279b2. This document holds the rationale, the design truths the +campaign produces, and the identity, lifecycle and authority table. The typed +`target` in the mind holds the labelled invariants and the not-in-scope list; the +text below is their source. + +## Why + +Operator, 2026-11-27: Brokkr "is meant to give an agent hands into the same Blender +scene I'm looking at, enabling live collaboration work". Brokkr already runs inside +her live Blender: a `depsgraph_update_post` handler publishes a host snapshot and a +persistent 1 s `bpy.app.timers` callback drains command intents +(`surfaces/blender/brokkr_bridge/__init__.py:610-647`, `:668-671`). What it lacks is +everything that makes two people in one scene a collaboration rather than a remote +control: + +- an agent edit is not an undo step (research `nibu-body:research:blender-live-collab.brokkr-undo`); +- nobody can tell who made an edit: the Blender side reads no `requestedBy` + (`.brokkr-attribution-gate`); +- the human cannot stop an agent except by unticking a preference, and a queued intent + still runs if she ticks it back; +- the agent sees names and counts, not the viewport and not the Edit Mode selection + (`.brokkr-perception`); +- nothing stops an agent intent planned against an old scene from overwriting what she + did since; +- the agent has no hands: `brokkr-ctl` has no source (`.brokkr-no-agent-surface`). + +Its strengths stay: typed, validated actions with no free-form Python, path +confinement, loopback bind and an optional session token (`.brokkr-security`). + +## Prior art the design stands on + +- **mcp-for-blender's `UserEditRecorder`** (`.mcp4b-human-edits`): buffers human + operator and undo/redo events with `undo_post`/`redo_post` handlers, attributes events + during an agent command to the agent, and hands the agent the human's activity before + its next action. We take the idea (the agent learns what the human did) and drop the + trajectory log: the snapshot carries per-object human-edit sequence numbers instead. +- **blender-copilot** (`.copilot-undo-cancel`): one undo step per agent turn, a Stop + button, visible turns and an undo receipt, no approval gate. Its Stop cannot interrupt + a blocking native call. We take all four and accept the same limit. +- **Multi-User** (`.humans-multiuser`) and the paid collab add-ons (`.humans-others`): + presence of the other party in the 3D view, rights and object locks. We take presence + as a panel, derived from intents and receipts; human-to-human replication is theirs, + not ours. +- **Blender Lab MCP and mcp-for-blender** (`.lab-official`, `.mcp4b-perception-safe`): + viewport screenshots as perception; arbitrary code with a weak or default-off + sandbox, and no undo. The perception we copy; the code path is fork Q1. +- **ceeyang/blender_mcp** (`.ceeyang-159`): 159 typed tools, every write undoable. The + existence proof that a typed vocabulary can be wide. +- The brush-tree campaign's `one-commit-primitive` (Libby's mind): a stale base is + refused, never merged. The conflict rule below is the same rule applied to a live scene. + +## What probing established (Blender 5.3.0, Starfire, GUI, `--factory-startup`) + +Probe scripts: `docs/research/live-collab/probe_timer_undo.py` and `probe_look.py`. +Each step runs in its own timer tick, as Brokkr's drain does. + +1. **A write from a timer with no undo push is not a step, and it survives undo.** The + cube moved to x=1 with no push; one `ed.undo` left it at x=1. The next push captured + it, so the agent's write became part of the next step, whoever made it (case A). The + vendor warning (`.undo-timer-warning`) is real for unpushed writes, and the failure is + worse than "not undoable": the edit is misattributed. +2. **An explicit `ed.undo_push` from a timer makes a correct step.** x=2 pushed, x=3 + pushed; undo gave 2, undo gave 1 (the earlier step), redo gave 2 (case B). +3. **An UNDO-flagged operator called from a timer pushes its own step.** A sphere added + by `primitive_uv_sphere_add` vanished on one undo with no explicit push (case C). An + action that calls two operators therefore makes two steps unless told otherwise. +4. **Operators called with `undo=False` push nothing; one explicit push then covers + them.** Cube and cone added with `("EXEC_DEFAULT", False)`, one push, one undo removed + both, a second undo changed nothing (case E). This is the mechanism for "one intent, + one step". +5. **Edit Mode:** a bmesh write plus push in Edit Mode is reverted by one undo, and that + undo also left Edit Mode (the agent had entered it in the same probe); the mesh kept + its original vertex (case D). Mode entry and the agent step are not cleanly separable + when the agent itself changed mode. Not yet probed: the human in Edit Mode and the + agent writing. +6. **Driving `ed.undo`/`ed.redo` programmatically from timers crashed Blender 2 of 2 + times** in the long sequence (A through E in one session), with + `EXCEPTION_ACCESS_VIOLATION` in UI draw code after a memfile undo + (`outliner_draw_restrictbuts`, then `psys_get_current` from the properties editor). The + short sequences (C alone, D alone, E alone) did not crash. Cause not isolated; the + probe's own `temp_override` with a captured region is a suspect. +7. **The agent can see what the human sees.** `bpy.ops.screen.screenshot_area` on the + 3D view from a timer: 7 of 7 `FINISHED`, median 72.5 ms over runs 2-7 at 1574x888, + about 609 KB PNG, and it captured the splash screen over the viewport, so it is the + human's view, overlays and popups included. Each capture stalls her UI for that long. +8. **Edit Mode selection reads live** through `bmesh.from_edit_mesh` without leaving Edit + Mode: selected vertices `[0, 3]`, 0.013 ms, mode still `EDIT_MESH`. + +Not yet probed, and owed before the cut that depends on it: whether depsgraph updates +caused by an agent intent arrive inside the timer callback or after it returns (this +decides how human edits are told from agent edits); and whether a human Ctrl+Z inside a +pending agent intent's base window can be detected reliably by `undo_post`. + +## Design truths + +**One agent turn primitive.** Every agent mutation in Blender goes through one function +in the add-on: admit (sink enabled, `requestedBy` present, id unused, base fresh), run +the action with every operator called `undo=False`, push exactly one undo step labelled +`Brokkr : `, write the receipt. A refusal or a +failure pushes nothing and leaves the scene as it was. Typed actions, the node actions, +and `run` if Q1 keeps it, all use it; there is no second writer. + +**Undo belongs to the human.** Blender's one linear stack is the shared history. The +agent's steps sit in it, labelled, between hers; she undoes them with Ctrl+Z like her +own. The agent never calls `ed.undo` or `ed.redo` (probe 6); an agent that wants to back +out sends a new compensating intent, which is one more step. Undoing an agent step that +sits under later human steps is not offered: Blender's stack is linear and per-user undo +is out of scope. + +**Stop is one control, and only the human holds it.** The Brokkr panel's Stop turns the +command sink off and gives every pending intent a `stopped` receipt without running it. +An action already running finishes (a blocking native call cannot be interrupted, as in +blender-copilot); it is one undo step, so Stop plus Ctrl+Z always returns her scene. No +intent can turn the sink on. Re-enabling is a fresh decision, and intents queued before +Stop never run. + +**The agent sees her view and her edits.** `look` is a read intent: it captures her 3D +view to a scratch PNG named by command id (ruling `brush-tree:ruling:look-files-are-scratch`) +and returns the path; it pushes no undo step. The snapshot gains the Edit Mode selection +and a Blender session id plus human-edit sequence numbers: one counter for the session, +the last sequence at which the human touched each object, and the last sequence at which +she undid or redid. The agent reads "what changed since I last looked" from those. + +**A human edit is never silently overwritten.** Every mutating intent names the base +sequence it was planned against. If the human touched any datablock the intent targets +since that base, or undid or redid since it, or the session id changed, the intent is +refused with a `conflict` receipt naming what changed, and nothing is applied. The +agent looks again and re-plans. Granularity is fork Q3. + +**Presence is derived.** The panel shows which agents have intents or receipts in the +last minutes, the running or last intent with its one-line `note`, and the recent +receipts with their undo labels. It reads the intent and receipt documents; it owns no +state of its own. + +**Hands are a CLI.** `brokkr-ctl blender` (Rust, ruling `brush-tree:ruling:fitting-home-ruled`) +writes intents and reads receipts and snapshots through the Blender mirror store +(`brush-tree:ruling:blender-transport-ruled`), prints plain text or paths, and its +`--help` is the schema (`brush-tree:ruling:cli-not-mcp`, `:help-is-the-schema`). It owns +no state, policy or ledger (brush-tree target invariant `brokkr-authority-holds`). + +## Authority map + +- **Owner.** The add-on's agent turn primitive owns whether and how an agent intent + changes the live scene. Blender owns scene truth and the undo stack. The human owns + the sink toggle, Stop, and undo. +- **Inputs.** Intent documents; the snapshot's human-edit sequences; the sink toggle. +- **Outputs.** One undo step per accepted mutating intent; one receipt per intent; + the refreshed snapshot; look PNG paths. +- **Derived state.** Presence (from intents and receipts). Human-edit sequences + (from depsgraph and undo handlers, observations only). Look PNGs (telemetry). +- **Forbidden writers.** `execute_command` called outside the primitive; operators + called with undo on inside an agent action; any raw RNA write by an agent without the + closing push; `ed.undo`/`ed.redo` from add-on code; the debug-mirror JSON import + (`blender_target.py` `_import_debug_command_files`) as a second door for intents; + `brokkr-ctl` opening the store to decide anything. +- **Shared paths.** brokkr-ctl intents, panel buttons that act on the scene, sync-organ + intents from `brokkr-daemon sync-once`, and replayed intents use the one primitive. +- **Deletion line.** The debug-mirror intent import goes before the primitive lands; + `drain_commands` stops calling `execute_command` directly. + +## Identity, lifecycle and authority + +| Persistent kind | What names it | What happens to it over time | Who decides | +|---|---|---|---| +| Blender command intent `brokkr.blender.command_intent.v0` (gains `requestedBy`, `baseSeq`, `note`) | `blender/commands/{commandId}`; ids single-use, minted by the writer (Unity F6 A, `brush-tree:ruling:blender-sink-mirrors-unity`) | Written once by a caller. Executed at most once or refused. Removed when its receipt is written, as today. Never rewritten. | Callers write. The agent turn primitive alone decides admission and execution. | +| Blender command receipt `brokkr.blender.command_receipt.v0` (gains `requestedBy`, `outcome` in accepted, denied, conflict, stopped, failed, `undoLabel`, `lookPath`, and for `run` the script text and SHA-256) | `blender/receipts/{commandId}`, one per intent | Written once, after the primitive decides. Pruned by count with Unity's cap and prune rule. The only proof an intent ran. | The primitive alone. Callers and the panel read. | +| Agent identity `requestedBy` | `/` stated by the caller (brokkr-ctl takes it from `EUREKA_INSTANCE` and a flag) | Carried on each intent into its receipt and undo label; not stored on its own. | The caller states it; the primitive refuses an intent without it. The session token proves admission, not identity. | +| Agent undo step | Blender undo stack entry labelled `Brokkr : ` | Pushed once per accepted mutating intent; lives as Blender's stack does (step limit, file load); never persisted by Brokkr. | Blender owns the stack. The primitive pushes. Only the human undoes or redoes. | +| Blender session id | uuid minted at add-on register and on each `load_post` | Replaced when Blender restarts or a file loads; every older base is then stale. | The add-on alone. | +| Human-edit sequences (snapshot fields: `humanEditSeq`, per-object `lastHumanEditSeq`, `lastUndoSeq`) | Integers within a session id | Monotonic within a session; reset with it. Observations, never scene truth. | The add-on's depsgraph and undo handlers alone. | +| Host snapshot `brokkr.blender.host_snapshot.v0` (gains Edit Mode selection, session id, the sequences above, sink state) | `blender/host/current`, overwritten | Refreshed on depsgraph update and after each intent. | The add-on alone. | +| Command sink toggle (the existing `auto_drain_commands` preference) | Add-on preference, echoed in the snapshot | Off by default. Stop turns it off; only the human turns it on. | The human only. No intent writes it. | +| Script toggle (only if Q1 = b) | A second add-on preference, echoed in the snapshot | Off by default, independent of the sink. | The human only. | +| Look PNG | `/look/{commandId}.png` | Pruned by count; never read back as truth. | The primitive writes; `brush-tree:ruling:look-files-are-scratch` governs. | + +## Not in scope + +Human-to-human replication or several Blender instances in one session (Multi-User's +domain). Agents on another host reaching the operator's Blender: the transport is not +widened beyond what the add-on serves today. Per-user or selective undo. An approval gate +before each agent action (unless Q2 rules otherwise). A 3D-view overlay of the agent's +presence; the panel carries presence in this revision. The Unity surface and +`brokkr-command`. The brush-tree vocabulary, Geometry.Csg and OpenSCAD text (brush-tree +owns them). Agent-initiated save and quit (`brush-tree:ruling:run-admitted-when-enabled` +keeps them off the allowed list). Asset libraries and generators. An MCP server. + +## Open forks (draft questions; Self admits) + +- **Q1. Free-form Python.** Today the Blender add-on has no script action. Libby's + Defaulted ruling `brush-tree:ruling:run-admitted-when-enabled` would add `run`, admitted + whenever agent commands are on. Options: (a) typed actions only; (b) `run` behind its + own off-by-default toggle, one undo step, script text in the receipt; (c) the Defaulted + ruling as written. Recommend (b). +- **Q2. Act then undo, or approve first.** Recommend act then undo, with Stop. +- **Q3. Conflict granularity.** (a) any human edit since the base refuses; (b) only edits to + the intent's targets, plus any undo or redo. Recommend (b), after the depsgraph + attribution probe. +- **Q4. Who builds `brokkr-ctl blender`.** Recommend this campaign builds the session + subcommands in Rust per Libby's rulings, and brush-tree adds its tree commands to the + same binary later. diff --git a/docs/research/live-collab/probe_look.py b/docs/research/live-collab/probe_look.py new file mode 100644 index 0000000..1e8851c --- /dev/null +++ b/docs/research/live-collab/probe_look.py @@ -0,0 +1,68 @@ +"""Probe: can a timer callback capture the 3D viewport the human sees, and read Edit Mode selection? + +blender --factory-startup --python probe_look.py -- +""" +import json +import os +import statistics +import sys +import time +import traceback + +import bmesh +import bpy + +args = sys.argv[sys.argv.index("--") + 1:] +OUT, PNG_DIR = args[0], args[1] +log = {"blender": bpy.app.version_string} + + +def ctx(): + win = bpy.context.window_manager.windows[0] + area = next(a for a in win.screen.areas if a.type == "VIEW_3D") + region = next(r for r in area.regions if r.type == "WINDOW") + return win, area, region + + +def run(): + win, area, region = ctx() + log["view3d_px"] = [region.width, region.height] + times = [] + for n in range(7): + path = os.path.join(PNG_DIR, f"look-{n}.png") + t = time.perf_counter() + with bpy.context.temp_override(window=win, area=area, region=region): + r = bpy.ops.screen.screenshot_area(filepath=path) + times.append((time.perf_counter() - t) * 1000) + log.setdefault("results", []).append(list(r)) + log["screenshot_ms"] = [round(x, 1) for x in times] + log["screenshot_ms_median"] = round(statistics.median(times[1:]), 1) + log["png_bytes"] = os.path.getsize(os.path.join(PNG_DIR, "look-6.png")) + # Edit Mode selection read, live, without leaving Edit Mode. + with bpy.context.temp_override(window=win, area=area, region=region): + bpy.ops.object.mode_set(mode="EDIT") + bpy.ops.mesh.select_all(action="DESELECT") + bm = bmesh.from_edit_mesh(bpy.data.objects["Cube"].data) + bm.verts.ensure_lookup_table() + bm.verts[0].select = True + bm.verts[3].select = True + bm.select_flush_mode() + t = time.perf_counter() + sel = [v.index for v in bmesh.from_edit_mesh(bpy.data.objects["Cube"].data).verts if v.select] + log["edit_selection_read_ms"] = round((time.perf_counter() - t) * 1000, 3) + log["edit_selected_verts"] = sel + log["mode_after_read"] = bpy.context.mode + + +def tick(): + try: + run() + except Exception: + log["error"] = traceback.format_exc() + with open(OUT, "w") as f: + json.dump(log, f, indent=1) + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(tick, first_interval=3.0) diff --git a/docs/research/live-collab/probe_timer_undo.py b/docs/research/live-collab/probe_timer_undo.py new file mode 100644 index 0000000..57886fb --- /dev/null +++ b/docs/research/live-collab/probe_timer_undo.py @@ -0,0 +1,146 @@ +"""Probe: do edits made from a bpy.app.timers callback land on Blender's undo stack? + +Run in GUI Blender: blender --factory-startup --python probe_timer_undo.py -- [cases, e.g. AB] +Each step is its own timer tick so the event loop runs between steps, as it does +for Brokkr's 1 s drain. Results are written to the JSON path, then Blender quits. +""" +import json +import sys +import traceback + +import bmesh +import bpy + +OUT = sys.argv[sys.argv.index("--") + 1] +log = {"blender": bpy.app.version_string, "background": bpy.app.background, "steps": []} + + +def win_ctx(): + win = bpy.context.window_manager.windows[0] + area = next(a for a in win.screen.areas if a.type == "VIEW_3D") + return bpy.context.temp_override(window=win, area=area, region=area.regions[-1]) + + +def cube(): + return bpy.data.objects.get("Cube") + + +def state(tag): + c = cube() + s = { + "tag": tag, + "cube_x": round(c.location.x, 3) if c else None, + "objects": sorted(o.name for o in bpy.data.objects), + "mode": bpy.context.mode, + "mesh_v0_z": round(c.data.vertices[0].co.z, 3) if c else None, + } + if c and c.mode == "EDIT": + bm = bmesh.from_edit_mesh(c.data) + bm.verts.ensure_lookup_table() + s["edit_v0_z"] = round(bm.verts[0].co.z if bm.verts else 0, 3) + log["steps"].append(s) + return s + + +def push(msg): + with win_ctx(): + r = bpy.ops.ed.undo_push(message=msg) + log["steps"].append({"tag": f"undo_push:{msg}", "result": list(r)}) + + +def undo(): + with win_ctx(): + r = bpy.ops.ed.undo() + log["steps"].append({"tag": "undo", "result": list(r)}) + + +def redo(): + with win_ctx(): + r = bpy.ops.ed.redo() + log["steps"].append({"tag": "redo", "result": list(r)}) + + +# Case A: raw RNA write from a timer, no push. Does Ctrl+Z see it as its own step? +# Case B: RNA write then an explicit undo_push from the timer. +# Case C: an UNDO-flagged operator called from a timer, no explicit push. +# Case D: Edit Mode bmesh write from a timer then undo_push. +# Case E: two operators called with undo=False, then one explicit undo_push. +ONLY = sys.argv[sys.argv.index("--") + 2] if len(sys.argv) > sys.argv.index("--") + 2 else "ABCDE" +steps = [ + lambda: (push("baseline"), state("A0 baseline")), + lambda: (setattr(cube().location, "x", 1.0), state("A1 raw write x=1, no push")), + lambda: (undo(), state("A2 after one undo")), + lambda: (push("rebase-B"), state("B0")), + lambda: (setattr(cube().location, "x", 2.0), push("agent: x=2"), state("B1 x=2 pushed")), + lambda: (setattr(cube().location, "x", 3.0), push("agent: x=3"), state("B2 x=3 pushed")), + lambda: (undo(), state("B3 after undo (expect x=2)")), + lambda: (undo(), state("B4 after second undo (expect x=0)")), + lambda: (redo(), state("B5 after redo (expect x=2)")), + lambda: (push("rebase-C"), state("C0")), + lambda: (_add_sphere(), state("C1 op add sphere, no push")), + lambda: (undo(), state("C2 after undo (sphere gone?)")), + lambda: (bpy.context.view_layer.objects.__setattr__("active", cube()), cube().select_set(True), push("rebase-D"), state("D0")), + lambda: (_edit_enter(), state("D1 edit mode")), + lambda: (_edit_write(), push("agent: edit v0"), state("D2 v0 moved, pushed")), + lambda: (undo(), state("D3 after undo (expect v0 back)")), + lambda: (undo(), state("D4 after second undo")), + lambda: (_edit_exit(), push("rebase-E"), state("E0")), + lambda: (_two_ops_one_step(), push("agent: two ops"), state("E1 two ops undo=False + one push")), + lambda: (undo(), state("E2 after one undo (expect both gone)")), + lambda: (undo(), state("E3 after second undo (expect no change)")), +] + + +def _add_sphere(): + with win_ctx(): + bpy.ops.mesh.primitive_uv_sphere_add(location=(5, 0, 0)) + + +def _edit_exit(): + if bpy.context.mode != "OBJECT": + with win_ctx(): + bpy.ops.object.mode_set(mode="OBJECT") + + +def _two_ops_one_step(): + with win_ctx(): + bpy.ops.mesh.primitive_cube_add("EXEC_DEFAULT", False, location=(0, 4, 0)) + bpy.ops.mesh.primitive_cone_add("EXEC_DEFAULT", False, location=(0, -4, 0)) + + +def _edit_enter(): + with win_ctx(): + bpy.ops.object.mode_set(mode="EDIT") + + +def _edit_write(): + c = cube() + bm = bmesh.from_edit_mesh(c.data) + bm.verts.ensure_lookup_table() + bm.verts[0].co.z += 5.0 + bmesh.update_edit_mesh(c.data) + + +i = 0 +_all = steps +steps = [f for f, c in zip(_all, "AAABBBBBBCCCDDDDDEEEE") if c in ONLY] + + +def tick(): + global i + if i < len(steps): + try: + steps[i]() + except Exception: + log["steps"].append({"tag": f"step {i} error", "error": traceback.format_exc()}) + i += 1 + with open(OUT, "w") as f: + json.dump(log, f, indent=1) + return 0.3 + with open(OUT, "w") as f: + json.dump(log, f, indent=1) + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(tick, first_interval=2.0) From 48c0aeee6d702c28da79fd275042d95455eb557e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 18:07:37 +0100 Subject: [PATCH 03/63] Live collab: depsgraph timing probe Records when depsgraph updates from an agent edit in a timer arrive and which ids they name, for the human-edit detection fork (Q3). Co-Authored-By: Claude Opus 5.5 --- .../live-collab/probe_depsgraph_timing.py | 134 ++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 docs/research/live-collab/probe_depsgraph_timing.py diff --git a/docs/research/live-collab/probe_depsgraph_timing.py b/docs/research/live-collab/probe_depsgraph_timing.py new file mode 100644 index 0000000..d763e07 --- /dev/null +++ b/docs/research/live-collab/probe_depsgraph_timing.py @@ -0,0 +1,134 @@ +"""Probe: when do depsgraph updates caused by an agent edit in a timer arrive, and what do they name? + +blender --factory-startup --python probe_depsgraph_timing.py -- + +Each case runs in its own timer tick. AGENT is True only while the timer callback +runs the edit. depsgraph_update_post and undo_post log every call with AGENT's value, +the tick that was current, and the ids depsgraph.updates names. +""" +import json +import sys +import time +import traceback + +import bpy + +OUT = sys.argv[sys.argv.index("--") + 1] +log = {"blender": bpy.app.version_string, "events": []} +AGENT = False +TICK = "setup" +T0 = time.perf_counter() + + +def ev(kind, **kw): + log["events"].append({"kind": kind, "tick": TICK, "agent": AGENT, + "ms": round((time.perf_counter() - T0) * 1000, 1), **kw}) + + +@bpy.app.handlers.persistent +def on_depsgraph(scene, depsgraph): + ups = [] + for u in depsgraph.updates: + ups.append(f"{type(u.id).__name__}:{u.id.name}" + f"{'/T' if u.is_updated_transform else ''}{'/G' if u.is_updated_geometry else ''}") + ev("depsgraph", updates=ups) + + +@bpy.app.handlers.persistent +def on_undo(scene, *_): + ev("undo_post") + + +@bpy.app.handlers.persistent +def on_redo(scene, *_): + ev("redo_post") + + +def win_ctx(): + win = bpy.context.window_manager.windows[0] + area = next(a for a in win.screen.areas if a.type == "VIEW_3D") + region = next(r for r in area.regions if r.type == "WINDOW") + return bpy.context.temp_override(window=win, area=area, region=region) + + +def setup(): + # B follows A through a Copy Location constraint: an indirect dependent of A. + a = bpy.data.objects["Cube"] + with win_ctx(): + bpy.ops.mesh.primitive_cone_add("EXEC_DEFAULT", False, location=(0, 3, 0)) + b = bpy.context.active_object + b.name = "Follower" + c = b.constraints.new("COPY_LOCATION") + c.target = a + c.use_y = False + with win_ctx(): + bpy.ops.ed.undo_push(message="setup") + + +def agent(fn, flush): + global AGENT + AGENT = True + ev("turn_begin", flush=flush) + fn() + with win_ctx(): + bpy.ops.ed.undo_push(message=f"agent {TICK}") + if flush: + bpy.context.view_layer.update() + ev("turn_end") + AGENT = False + + +def move_a(x): + return lambda: setattr(bpy.data.objects["Cube"].location, "x", x) + + +def add_op(): + with win_ctx(): + bpy.ops.mesh.primitive_uv_sphere_add("EXEC_DEFAULT", False, location=(-4, 0, 0)) + + +def undo_once(): + with win_ctx(): + bpy.ops.ed.undo() + + +cases = [ + ("setup", setup), + ("idle1", lambda: None), + ("rna-noflush", lambda: agent(move_a(1.0), False)), + ("idle2", lambda: None), + ("rna-flush", lambda: agent(move_a(2.0), True)), + ("idle3", lambda: None), + ("op-noflush", lambda: agent(add_op, False)), + ("idle4", lambda: None), + ("op-flush", lambda: agent(add_op, True)), + ("idle5", lambda: None), + ("undo", undo_once), # stands in for a human Ctrl+Z (not an agent turn) + ("idle6", lambda: None), +] +i = 0 + + +def tick(): + global i, TICK + if i < len(cases): + TICK, fn = cases[i] + try: + fn() + except Exception: + ev("error", error=traceback.format_exc()) + TICK = f"after:{TICK}" + i += 1 + with open(OUT, "w") as f: + json.dump(log, f, indent=1) + return 0.5 + with open(OUT, "w") as f: + json.dump(log, f, indent=1) + bpy.ops.wm.quit_blender() + return None + + +bpy.app.handlers.depsgraph_update_post.append(on_depsgraph) +bpy.app.handlers.undo_post.append(on_undo) +bpy.app.handlers.redo_post.append(on_redo) +bpy.app.timers.register(tick, first_interval=2.0) From 714ae214788e8a1a28e3a2f43af417590a7daacb Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 18:18:59 +0100 Subject: [PATCH 04/63] Live collab target r2: rulings in, phase two authoring surface Takes in the operator's 2026-11-27 rulings (no free-form Python, act then undo, last writer wins in the scene, brokkr-ctl blender built here) and adds phase two: scene collections as an authoring surface over a ship's .cc, opened at known record versions and pushed through AetherDb with a dry-run default and stale-version refusal. Records why neither variants' deltas nor CultNet carry the push today. Co-Authored-By: Claude Opus 5.5 --- docs/live-collab-target.md | 399 ++++++++++++++++++++++--------------- 1 file changed, 243 insertions(+), 156 deletions(-) diff --git a/docs/live-collab-target.md b/docs/live-collab-target.md index acbdb07..228ae83 100644 --- a/docs/live-collab-target.md +++ b/docs/live-collab-target.md @@ -4,200 +4,287 @@ Campaign `brokkr-live` (Nibu's mind). Working branch `nibu/live-collab-target`, `origin/main` 5e279b2. This document holds the rationale, the design truths the campaign produces, and the identity, lifecycle and authority table. The typed `target` in the mind holds the labelled invariants and the not-in-scope list; the -text below is their source. +text below is their source. Revision 2 adds phase two (the authoring surface) and +takes in the operator's rulings of 2026-11-27. + +Rulings in force: `brokkr-live:ruling:no-free-form-python`, `:act-then-undo`, +`:scene-last-writer-wins`, `:brokkr-ctl-blender-built-here`, +`:cc-is-hull-authority-scene-pushes-deltas`. ## Why Operator, 2026-11-27: Brokkr "is meant to give an agent hands into the same Blender -scene I'm looking at, enabling live collaboration work". Brokkr already runs inside -her live Blender: a `depsgraph_update_post` handler publishes a host snapshot and a -persistent 1 s `bpy.app.timers` callback drains command intents -(`surfaces/blender/brokkr_bridge/__init__.py:610-647`, `:668-671`). What it lacks is -everything that makes two people in one scene a collaboration rather than a remote -control: +scene I'm looking at, enabling live collaboration work". Her original vision for it: +"use Blender as an authoring environment, since it exposes typed access to all of the +assets we need over CultMesh. Certain collections within the Blender scene would +mirror their data into the exact documents Aetheria needs for its ships." -- an agent edit is not an undo step (research `nibu-body:research:blender-live-collab.brokkr-undo`); -- nobody can tell who made an edit: the Blender side reads no `requestedBy` - (`.brokkr-attribution-gate`); -- the human cannot stop an agent except by unticking a preference, and a queued intent - still runs if she ticks it back; -- the agent sees names and counts, not the viewport and not the Edit Mode selection - (`.brokkr-perception`); -- nothing stops an agent intent planned against an old scene from overwriting what she - did since; -- the agent has no hands: `brokkr-ctl` has no source (`.brokkr-no-agent-surface`). +So the campaign has two phases. **Phase one** makes the live session a collaboration: +the agent's edits are undoable and attributed, she can stop it, and it sees what she +sees. **Phase two** makes the scene an authoring surface over a ship's `.cc`: scene +collections map to the ship's records, the scene opens from the `.cc` at a known +revision, and pushes go back through AetherDb. -Its strengths stay: typed, validated actions with no free-form Python, path -confinement, loopback bind and an optional session token (`.brokkr-security`). +Brokkr already runs inside her live Blender: a `depsgraph_update_post` handler +publishes a host snapshot and a persistent 1 s `bpy.app.timers` callback drains +command intents (`surfaces/blender/brokkr_bridge/__init__.py:610-647`, `:668-671`). +What it lacks: an agent edit is not an undo step (`nibu-body:research:blender-live-collab.brokkr-undo`); +nobody can tell who made an edit (`.brokkr-attribution-gate`); the human can stop an +agent only by unticking a preference; the agent sees names and counts, not the viewport +or the Edit Mode selection (`.brokkr-perception`); and the agent has no hands, since +`brokkr-ctl` has no source (`.brokkr-no-agent-surface`). Its strengths stay: typed, +validated actions with no free-form Python, path confinement, loopback bind and an +optional session token (`.brokkr-security`). ## Prior art the design stands on -- **mcp-for-blender's `UserEditRecorder`** (`.mcp4b-human-edits`): buffers human - operator and undo/redo events with `undo_post`/`redo_post` handlers, attributes events - during an agent command to the agent, and hands the agent the human's activity before - its next action. We take the idea (the agent learns what the human did) and drop the - trajectory log: the snapshot carries per-object human-edit sequence numbers instead. +- **mcp-for-blender's `UserEditRecorder`** (`.mcp4b-human-edits`): the agent learns what + the human did between its actions. We keep the idea as snapshot fields, without a + trajectory log. - **blender-copilot** (`.copilot-undo-cancel`): one undo step per agent turn, a Stop - button, visible turns and an undo receipt, no approval gate. Its Stop cannot interrupt - a blocking native call. We take all four and accept the same limit. -- **Multi-User** (`.humans-multiuser`) and the paid collab add-ons (`.humans-others`): - presence of the other party in the 3D view, rights and object locks. We take presence - as a panel, derived from intents and receipts; human-to-human replication is theirs, - not ours. + button, visible turns and an undo receipt, no approval gate. Its Stop cannot + interrupt a blocking native call; ours cannot either. +- **Multi-User** (`.humans-multiuser`, `.humans-others`): presence of the other party. + We show presence in a panel; human-to-human replication is theirs. - **Blender Lab MCP and mcp-for-blender** (`.lab-official`, `.mcp4b-perception-safe`): - viewport screenshots as perception; arbitrary code with a weak or default-off - sandbox, and no undo. The perception we copy; the code path is fork Q1. -- **ceeyang/blender_mcp** (`.ceeyang-159`): 159 typed tools, every write undoable. The - existence proof that a typed vocabulary can be wide. -- The brush-tree campaign's `one-commit-primitive` (Libby's mind): a stale base is - refused, never merged. The conflict rule below is the same rule applied to a live scene. + viewport screenshots as perception. Their arbitrary-code path is refused here + (`no-free-form-python`). +- **ceeyang/blender_mcp** (`.ceeyang-159`): 159 typed tools, every write undoable; a + typed vocabulary can be wide. +- **Aetheria's ship package path** (Aetheria origin/master 6702b01bf, packager on + `nibu/hull-packager` 7101b5cec): `AetherDb ship-authoring` (create, stats, price, + product, regenerate with a dry-run default, validate, inspect) loads a `ship.cc` + through the game's own types; `tools/blender/package_hull.py` drives the + `aetheria_ships` add-on and AetherDb from a manifest; `tools/blender/aetheria_ships/ship_cc.py` + reads and writes `ship.cc` envelopes directly, with a layout revision hash for its + layout write. +- **CultCache compare-exchange and element ids** (CultLib origin/main baf4ecf7, + `src/GameCult.Caching/CultCache.cs:2228-2235` `Expect`/`ExpectUnchanged`; + `CultElementIds.cs`). `HardpointData.Id` is a `[CultElementId]` (Aetheria + `Assets/Scripts/ServerShared/ItemData.cs:648`). -## What probing established (Blender 5.3.0, Starfire, GUI, `--factory-startup`) +## What probing established -Probe scripts: `docs/research/live-collab/probe_timer_undo.py` and `probe_look.py`. -Each step runs in its own timer tick, as Brokkr's drain does. +Blender 5.3.0, Starfire, GUI, `--factory-startup`, each step in its own timer tick. +Scripts in `docs/research/live-collab/`. Research notes +`brokkr-live:research:live-collab-probes.*`. -1. **A write from a timer with no undo push is not a step, and it survives undo.** The - cube moved to x=1 with no push; one `ed.undo` left it at x=1. The next push captured - it, so the agent's write became part of the next step, whoever made it (case A). The - vendor warning (`.undo-timer-warning`) is real for unpushed writes, and the failure is - worse than "not undoable": the edit is misattributed. -2. **An explicit `ed.undo_push` from a timer makes a correct step.** x=2 pushed, x=3 - pushed; undo gave 2, undo gave 1 (the earlier step), redo gave 2 (case B). -3. **An UNDO-flagged operator called from a timer pushes its own step.** A sphere added - by `primitive_uv_sphere_add` vanished on one undo with no explicit push (case C). An - action that calls two operators therefore makes two steps unless told otherwise. -4. **Operators called with `undo=False` push nothing; one explicit push then covers - them.** Cube and cone added with `("EXEC_DEFAULT", False)`, one push, one undo removed - both, a second undo changed nothing (case E). This is the mechanism for "one intent, - one step". -5. **Edit Mode:** a bmesh write plus push in Edit Mode is reverted by one undo, and that - undo also left Edit Mode (the agent had entered it in the same probe); the mesh kept - its original vertex (case D). Mode entry and the agent step are not cleanly separable - when the agent itself changed mode. Not yet probed: the human in Edit Mode and the - agent writing. -6. **Driving `ed.undo`/`ed.redo` programmatically from timers crashed Blender 2 of 2 - times** in the long sequence (A through E in one session), with - `EXCEPTION_ACCESS_VIOLATION` in UI draw code after a memfile undo - (`outliner_draw_restrictbuts`, then `psys_get_current` from the properties editor). The - short sequences (C alone, D alone, E alone) did not crash. Cause not isolated; the - probe's own `temp_override` with a captured region is a suspect. -7. **The agent can see what the human sees.** `bpy.ops.screen.screenshot_area` on the - 3D view from a timer: 7 of 7 `FINISHED`, median 72.5 ms over runs 2-7 at 1574x888, - about 609 KB PNG, and it captured the splash screen over the viewport, so it is the - human's view, overlays and popups included. Each capture stalls her UI for that long. -8. **Edit Mode selection reads live** through `bmesh.from_edit_mesh` without leaving Edit - Mode: selected vertices `[0, 3]`, 0.013 ms, mode still `EDIT_MESH`. +1. **An unpushed write from a timer is not an undo step and survives undo**; the next + push absorbs it, so it is misattributed (`.timer-undo`, case A). +2. **An explicit `ed.undo_push` from a timer makes a correct step**, and undo and redo + walk it (case B). +3. **UNDO-flagged operators push their own step**; called `("EXEC_DEFAULT", False)` they + push none, and one explicit push covers several (cases C, E). This is how one intent + becomes one step. +4. **Edit Mode**: an agent bmesh write plus push is reverted by one undo, which also + left the Edit Mode the agent had entered (case D). +5. **Driving `ed.undo`/`ed.redo` from code crashed Blender 2 of 2 times** in the long + sequence, in UI draw after a memfile undo (`.programmatic-undo-crash`). +6. **The agent can see her view**: `screenshot_area` on her 3D view, median 72.5 ms at + 1574x888, about 609 KB, popups included; Edit Mode selection reads live without + leaving Edit Mode (`.look-capture`). +7. **Depsgraph updates from an agent edit arrive inside the timer turn** and name + indirect dependents; after an undo every object is listed and only the transform and + geometry flags show what changed (`.depsgraph-timing`). +8. **cultcache-rs writes the add-on's single-file `.ccmp` under the shared lock, and a + live cultmesh-py node pulls Rust writes**; no runtime has a directory store + (`.rust-store-writer`). -Not yet probed, and owed before the cut that depends on it: whether depsgraph updates -caused by an agent intent arrive inside the timer callback or after it returns (this -decides how human edits are told from agent edits); and whether a human Ctrl+Z inside a -pending agent intent's base window can be detected reliably by `undo_post`. +Not yet probed, owed before the cut that depends on it: the latency of one AetherDb +`ship-authoring` call on Starfire (phase two decides between a CLI call per push and a +resident service on that number); reading a record's stored version through AetherDb. -## Design truths +## Phase one: the live session **One agent turn primitive.** Every agent mutation in Blender goes through one function -in the add-on: admit (sink enabled, `requestedBy` present, id unused, base fresh), run -the action with every operator called `undo=False`, push exactly one undo step labelled -`Brokkr : `, write the receipt. A refusal or a -failure pushes nothing and leaves the scene as it was. Typed actions, the node actions, -and `run` if Q1 keeps it, all use it; there is no second writer. +in the add-on: admit (sink enabled, `requestedBy` present, id unused, action typed and +valid), run the action with every operator called `undo=False`, push exactly one undo +step labelled `Brokkr : `, write the receipt. A +refusal or a failure pushes nothing and leaves the scene unchanged. There is no second +writer and no script action (`no-free-form-python`): what the typed actions do not +cover waits for a new typed action. -**Undo belongs to the human.** Blender's one linear stack is the shared history. The -agent's steps sit in it, labelled, between hers; she undoes them with Ctrl+Z like her -own. The agent never calls `ed.undo` or `ed.redo` (probe 6); an agent that wants to back -out sends a new compensating intent, which is one more step. Undoing an agent step that -sits under later human steps is not offered: Blender's stack is linear and per-user undo -is out of scope. +**The agent acts; the human undoes** (`act-then-undo`). Admitted intents apply without +asking. Blender's one linear undo stack is the shared history; agent steps sit in it, +labelled, between hers, and she takes them back with Ctrl+Z. The agent never calls +`ed.undo` or `ed.redo` (probe 5); it backs out by sending a compensating intent. -**Stop is one control, and only the human holds it.** The Brokkr panel's Stop turns the -command sink off and gives every pending intent a `stopped` receipt without running it. -An action already running finishes (a blocking native call cannot be interrupted, as in -blender-copilot); it is one undo step, so Stop plus Ctrl+Z always returns her scene. No -intent can turn the sink on. Re-enabling is a fresh decision, and intents queued before -Stop never run. +**Last writer wins in the scene** (`scene-last-writer-wins`). An agent intent applies +even if she changed the scene since the agent looked. Her edit is never lost: it stays +in the undo history below the agent's step, and one Ctrl+Z takes the agent's step back. +This is scene-level only; the `.cc` keeps its revision refusal (phase two). + +**Stop is one control, and only the human holds it.** Stop turns the command sink off +and gives every pending intent a `stopped` receipt without running it. An action +already running finishes as one undo step, so Stop plus Ctrl+Z always returns her +scene. No intent can turn the sink on; intents queued before Stop never run. **The agent sees her view and her edits.** `look` is a read intent: it captures her 3D -view to a scratch PNG named by command id (ruling `brush-tree:ruling:look-files-are-scratch`) -and returns the path; it pushes no undo step. The snapshot gains the Edit Mode selection -and a Blender session id plus human-edit sequence numbers: one counter for the session, -the last sequence at which the human touched each object, and the last sequence at which -she undid or redid. The agent reads "what changed since I last looked" from those. +view to a scratch PNG named by command id (`brush-tree:ruling:look-files-are-scratch`) +and returns the path. The snapshot gains the Edit Mode selection, a Blender session id, +and human-edit sequence numbers (a session counter and, per object, the last sequence +at which she changed it, from depsgraph updates outside agent turns and flagged +transform, geometry or shading). These tell the agent what she did since it last +looked; they gate nothing. -**A human edit is never silently overwritten.** Every mutating intent names the base -sequence it was planned against. If the human touched any datablock the intent targets -since that base, or undid or redid since it, or the session id changed, the intent is -refused with a `conflict` receipt naming what changed, and nothing is applied. The -agent looks again and re-plans. Granularity is fork Q3. +**Presence is derived.** The panel shows active agents, the running or last intent with +its one-line `note`, and recent receipts with their undo labels, read from the intent +and receipt documents. -**Presence is derived.** The panel shows which agents have intents or receipts in the -last minutes, the running or last intent with its one-line `note`, and the recent -receipts with their undo labels. It reads the intent and receipt documents; it owns no -state of its own. +**Hands are a CLI** (`brokkr-ctl-blender-built-here`). `brokkr-ctl blender` is a Rust +binary in this repo (`brush-tree:ruling:fitting-home-ruled`) that writes intents and +reads receipts and snapshots in the add-on's single-file store (probe 8), prints plain +text or paths, and whose `--help` is the schema (`brush-tree:ruling:cli-not-mcp`, +`:help-is-the-schema`). It owns no state, policy or ledger. Libby's brush-tree adds its +tree commands to the same binary later. -**Hands are a CLI.** `brokkr-ctl blender` (Rust, ruling `brush-tree:ruling:fitting-home-ruled`) -writes intents and reads receipts and snapshots through the Blender mirror store -(`brush-tree:ruling:blender-transport-ruled`), prints plain text or paths, and its -`--help` is the schema (`brush-tree:ruling:cli-not-mcp`, `:help-is-the-schema`). It owns -no state, policy or ledger (brush-tree target invariant `brokkr-authority-holds`). +## Phase two: the authoring surface + +**The `.cc` is the authority; the scene is a surface over it** +(`cc-is-hull-authority-scene-pushes-deltas`). A ship's records live in its `ship.cc`: +`HullData`, `ShipAuthoring` (model asset, anchors, schematic lines) and its product +records (`ShipAuthoringStore.Load` returns exactly these three). A Blender scene may be +bound to one `ship.cc` as its authoring surface. The scene never becomes truth: it is an +edit buffer that opens from the store and pushes back to it. + +**Collections carry roles.** Scene collections are tagged with the role they author: +hull shape (the hull source and its raster), hardpoint rows (one object per row, +carrying `aetheria.id`, the `HardpointData` element id, and its kind, cell, footprint, +rotation, armor and arc), schematic lines, and anchors. Stats, price and product live on +the binding. These are the fields the packager manifest already names +(`tools/blender/package_hull.md`), so the manifest and a push describe a ship in one +vocabulary. + +**Open reads through the game's code.** Opening runs `AetherDb ship-authoring` to read +the three records and their stored versions, builds the tagged collections, and records +on the binding the version of each record it read. Nothing reads a `.cc` by scraping +envelopes (operator 2026-11-17). + +**A push is one AetherDb call, dry-run then apply.** The surface writes the authoring +state of its tagged collections (the manifest vocabulary, plus the record versions it +opened at) to a scratch request file and calls `AetherDb ship-authoring push +`. Without `apply` AetherDb loads the store, derives the records the request +describes, validates them, and prints the per-record, per-field changes; nothing is +written. With `apply` it does the same and writes under compare-exchange on each +record's stored version (`Expect`). One CLI call per push is the starting shape; a +resident service is built only if the measured latency of that call demands it. + +**A stale revision is refused, never merged.** If any record changed in the store since +the scene opened it (another push, a CLI `stats` call, a packager `--replace`), the push +is refused with the records named; the surface reopens and the author re-applies. On a +successful apply the binding takes the new versions. + +**One owner turns a hull into records.** AetherDb's ship-authoring code (C#, the game's +own types) is the only code that derives `HullData`, `ShipAuthoring` and product records +from authoring input, and the only writer of `.cc` stores. The packager and the +authoring surface both call it. The direct envelope writes in +`aetheria_ships/ship_cc.py` (`replace_lines`, `replace_visual`, `replace_layout`, and +the first Save Layout that creates `ship.cc`) and its `layout_revision` hash are +demoted: `ship_cc.py` keeps no write path and no revision of its own, and +`package_hull.py`'s Save Layout steps become push calls. Whether the request is +the delta of the ruling, or a whole-record replace, is fork Q5 below. + +**The agent's hands reach the surface through typed actions.** Open, push dry-run and +push apply are typed Brokkr actions like any other, admitted by the same primitive; a +push changes no scene state and so pushes no undo step. Whether an agent may apply, +not only dry-run, is fork Q7. + +### Variants and CultNet deltas: not the push primitive today + +The coordinator asked whether Libby's `variants` delta records, or CultNet's deltas, +are the primitive for the push. + +- **Variants** (`variants` target, Libby's mind): a variant is a persisted record stored + as a base reference plus sparse overrides (`CultVariantDelta`, `CultVariantOverride` + with `Set`/`Insert`/`Remove` at slot plus element-id paths, + `src/GameCult.Caching/CultVariants.cs:56-112`), resolved by the cache at load, and a + plain upsert at a variant's key is refused (`variants:ruling:q1-refuse-plain-upsert`). + It describes a second document defined against a base, not a change to the base. Its + nested paths and `Insert`/`Remove` are unbuilt (`variants:follow_up:remaining-variant-cuts`, + C2b), C# alone resolves it, and Aetheria catalog content is out of its scope. +- **CultNet** (`contracts/cultnet/`): the wire has whole-document `document-put` and + `document-put-raw`, `document-delete`, and `database-change-raw` (added, updated, + removed, with the whole document and a commit id). There is no delta message. The + "delta" in `cultnet-rs/src/replication.rs:97,789-829` and `cultmesh-py/node.py:1649-1660` + is a client-side reconciliation diff (predicted minus canonical, per top-level slot, + numeric subtraction) handed to the caller to smooth a prediction; it is never sent. +- **One mechanism?** Not today. They are two unrelated things that share a word. The + operator's recollection matches the plan, not the code: variants' fork ruling 4 + (`cultnet-deltas`) says variants travel on CultNet as deltas, and + `variants:ruling:hop-subscriptions-refuse-variants` holds CultNet off variants until + that cut (C5) lands. When it does, the override vocabulary will be both the stored + variant and the wire delta. +- **Consequence for the push.** The push invents no delta format. Its addressing is the + variants override vocabulary (slot plus element id; `HardpointData.Id` is already a + `[CultElementId]`) when CultLib can apply overrides to a record in place; until then + it is a whole-record replace of the records that changed, guarded by `Expect`. Fork Q5. ## Authority map -- **Owner.** The add-on's agent turn primitive owns whether and how an agent intent - changes the live scene. Blender owns scene truth and the undo stack. The human owns - the sink toggle, Stop, and undo. -- **Inputs.** Intent documents; the snapshot's human-edit sequences; the sink toggle. -- **Outputs.** One undo step per accepted mutating intent; one receipt per intent; - the refreshed snapshot; look PNG paths. -- **Derived state.** Presence (from intents and receipts). Human-edit sequences - (from depsgraph and undo handlers, observations only). Look PNGs (telemetry). -- **Forbidden writers.** `execute_command` called outside the primitive; operators - called with undo on inside an agent action; any raw RNA write by an agent without the - closing push; `ed.undo`/`ed.redo` from add-on code; the debug-mirror JSON import - (`blender_target.py` `_import_debug_command_files`) as a second door for intents; - `brokkr-ctl` opening the store to decide anything. +- **Owner.** Phase one: the add-on's agent turn primitive owns whether and how an agent + intent changes the live scene; Blender owns scene truth and the undo stack; the human + owns the sink toggle, Stop and undo. Phase two: the `ship.cc` owns the ship; + AetherDb's ship-authoring code alone derives and writes its records. +- **Inputs.** Intent documents and the sink toggle (phase one). The tagged collections, + the binding's opened versions and the request file (phase two). +- **Outputs.** One undo step per accepted mutating intent; one receipt per intent; the + refreshed snapshot; look PNG paths; AetherDb's dry-run diff or its write. +- **Derived state.** Presence; human-edit sequences; look PNGs; the scene's mapped + collections (an edit buffer over the `.cc`); the request file. +- **Forbidden writers.** `execute_command` called around the primitive; operators run + with undo on inside an agent action; unpushed agent writes; `ed.undo`/`ed.redo` from + add-on code; any agent-sent Python; the debug-mirror JSON import as a door for intents + (`blender_target.py` `_import_debug_command_files`); `brokkr-ctl` deciding anything; + `ship_cc.py`'s envelope writes and any other direct `.cc` writer; `layout_revision` + as a revision. - **Shared paths.** brokkr-ctl intents, panel buttons that act on the scene, sync-organ - intents from `brokkr-daemon sync-once`, and replayed intents use the one primitive. + intents and replayed intents use the one primitive. The packager, the authoring + surface's buttons and an agent's push intent use the one AetherDb push. - **Deletion line.** The debug-mirror intent import goes before the primitive lands; - `drain_commands` stops calling `execute_command` directly. + `drain_commands` stops calling `execute_command` directly. `ship_cc.py`'s write + functions and `layout_revision` go when the push lands. ## Identity, lifecycle and authority | Persistent kind | What names it | What happens to it over time | Who decides | |---|---|---|---| -| Blender command intent `brokkr.blender.command_intent.v0` (gains `requestedBy`, `baseSeq`, `note`) | `blender/commands/{commandId}`; ids single-use, minted by the writer (Unity F6 A, `brush-tree:ruling:blender-sink-mirrors-unity`) | Written once by a caller. Executed at most once or refused. Removed when its receipt is written, as today. Never rewritten. | Callers write. The agent turn primitive alone decides admission and execution. | -| Blender command receipt `brokkr.blender.command_receipt.v0` (gains `requestedBy`, `outcome` in accepted, denied, conflict, stopped, failed, `undoLabel`, `lookPath`, and for `run` the script text and SHA-256) | `blender/receipts/{commandId}`, one per intent | Written once, after the primitive decides. Pruned by count with Unity's cap and prune rule. The only proof an intent ran. | The primitive alone. Callers and the panel read. | -| Agent identity `requestedBy` | `/` stated by the caller (brokkr-ctl takes it from `EUREKA_INSTANCE` and a flag) | Carried on each intent into its receipt and undo label; not stored on its own. | The caller states it; the primitive refuses an intent without it. The session token proves admission, not identity. | -| Agent undo step | Blender undo stack entry labelled `Brokkr : ` | Pushed once per accepted mutating intent; lives as Blender's stack does (step limit, file load); never persisted by Brokkr. | Blender owns the stack. The primitive pushes. Only the human undoes or redoes. | -| Blender session id | uuid minted at add-on register and on each `load_post` | Replaced when Blender restarts or a file loads; every older base is then stale. | The add-on alone. | -| Human-edit sequences (snapshot fields: `humanEditSeq`, per-object `lastHumanEditSeq`, `lastUndoSeq`) | Integers within a session id | Monotonic within a session; reset with it. Observations, never scene truth. | The add-on's depsgraph and undo handlers alone. | -| Host snapshot `brokkr.blender.host_snapshot.v0` (gains Edit Mode selection, session id, the sequences above, sink state) | `blender/host/current`, overwritten | Refreshed on depsgraph update and after each intent. | The add-on alone. | -| Command sink toggle (the existing `auto_drain_commands` preference) | Add-on preference, echoed in the snapshot | Off by default. Stop turns it off; only the human turns it on. | The human only. No intent writes it. | -| Script toggle (only if Q1 = b) | A second add-on preference, echoed in the snapshot | Off by default, independent of the sink. | The human only. | -| Look PNG | `/look/{commandId}.png` | Pruned by count; never read back as truth. | The primitive writes; `brush-tree:ruling:look-files-are-scratch` governs. | +| Blender command intent `brokkr.blender.command_intent.v0` (gains `requestedBy`, `note`) | `blender/commands/{commandId}`; ids single-use, minted by the writer (`brush-tree:ruling:blender-sink-mirrors-unity`) | Written once by a caller. Executed at most once or refused. Removed when its receipt is written. Never rewritten. | Callers write. The agent turn primitive alone decides admission and execution. | +| Blender command receipt `brokkr.blender.command_receipt.v0` (gains `requestedBy`, `outcome` in accepted, denied, stopped, failed, `undoLabel`, `lookPath`) | `blender/receipts/{commandId}`, one per intent | Written once, after the primitive decides. Pruned by count with Unity's cap and prune rule. | The primitive alone. Callers and the panel read. | +| Agent identity `requestedBy` | `/` stated by the caller | Carried on each intent into its receipt and undo label; not stored on its own. | The caller states it; the primitive refuses an intent without it. The session token proves admission, not identity. | +| Agent undo step | Blender undo entry `Brokkr : ` | One per accepted mutating intent; lives as Blender's stack does; never persisted by Brokkr. | Blender owns the stack; the primitive pushes; only the human undoes or redoes. | +| Blender session id | uuid minted at add-on register and on each `load_post` | Replaced when Blender restarts or a file loads. | The add-on alone. | +| Human-edit sequences (snapshot: `humanEditSeq`, per-object `lastHumanEditSeq`) | Integers within a session id | Monotonic within a session; reset with it. Information for the agent; they gate nothing. | The add-on's depsgraph and undo handlers alone. | +| Host snapshot `brokkr.blender.host_snapshot.v0` (gains Edit Mode selection, session id, sequences, sink state, authoring binding summary) | `blender/host/current`, overwritten | Refreshed on depsgraph update and after each intent. | The add-on alone. | +| Command sink toggle (`auto_drain_commands`) | Add-on preference, echoed in the snapshot | Off by default. Stop turns it off; only the human turns it on. | The human only. | +| Look PNG | `/look/{commandId}.png` | Pruned by count; never read back as truth. | The primitive writes; `look-files-are-scratch` governs. | +| Ship package store `ship.cc` (`HullData`, `ShipAuthoring`, product records) | Its path, `GameData/Mods//ship.cc`; records by their keys | Created by `ship-authoring create`; changed only by AetherDb commands, each write minting new stored versions (`variants:ruling:storedat-on-change`); replaced whole only by packager `--replace`. | AetherDb's ship-authoring code is the only writer. | +| Record version | The version CultCache's compare-exchange tests for each record key | Changes on every write that changes the record's bytes. | CultCache mints it; AetherDb reports it on open and tests it on apply. | +| Authoring binding | A custom property on the Blender scene: the `ship.cc` path relative to the `.blend`, the ship id, and the record versions opened at | Set on Open; versions replaced after each successful apply; cleared on Detach or reopen. Lives in the `.blend`. | Open, apply and Detach (human buttons or agent actions through the primitive) alone write it. | +| Collection role | A custom property on a collection: hull, hardpoints, lines or anchors | Set when the surface builds or the author tags a collection; removed on Detach. | The author; the surface's Open builds the defaults. | +| Hardpoint row identity | `aetheria.id` on the row's object, equal to `HardpointData.Id` (`[CultElementId]`) | Minted when the row is created; survives renames and moves; removing the object removes the row on the next push. | AetherDb mints for a new row; the surface carries it. | +| Push request | `/authoring/{commandId}.json`, manifest vocabulary plus opened versions | Written per push; pruned by count; never read back as state. | The surface writes; AetherDb alone interprets it. | ## Not in scope -Human-to-human replication or several Blender instances in one session (Multi-User's -domain). Agents on another host reaching the operator's Blender: the transport is not -widened beyond what the add-on serves today. Per-user or selective undo. An approval gate -before each agent action (unless Q2 rules otherwise). A 3D-view overlay of the agent's -presence; the panel carries presence in this revision. The Unity surface and -`brokkr-command`. The brush-tree vocabulary, Geometry.Csg and OpenSCAD text (brush-tree -owns them). Agent-initiated save and quit (`brush-tree:ruling:run-admitted-when-enabled` -keeps them off the allowed list). Asset libraries and generators. An MCP server. +Human-to-human replication or several Blender instances in one session. Agents on +another host reaching the operator's Blender. Per-user or selective undo. An approval +gate (`act-then-undo`). Stale-action refusal inside the live scene +(`scene-last-writer-wins`). Any agent-sent Python (`no-free-form-python`). A 3D-view +presence overlay. The Unity surface and `brokkr-command`. The brush-tree vocabulary, +Geometry.Csg and OpenSCAD text (brush-tree owns them). Agent-initiated save and quit. +Asset libraries and generators. An MCP server. Records outside a ship package +(catalog loadouts, factions) unless Q6 rules them in. A new delta wire format. ## Open forks (draft questions; Self admits) -- **Q1. Free-form Python.** Today the Blender add-on has no script action. Libby's - Defaulted ruling `brush-tree:ruling:run-admitted-when-enabled` would add `run`, admitted - whenever agent commands are on. Options: (a) typed actions only; (b) `run` behind its - own off-by-default toggle, one undo step, script text in the receipt; (c) the Defaulted - ruling as written. Recommend (b). -- **Q2. Act then undo, or approve first.** Recommend act then undo, with Stop. -- **Q3. Conflict granularity.** (a) any human edit since the base refuses; (b) only edits to - the intent's targets, plus any undo or redo. Recommend (b), after the depsgraph - attribution probe. -- **Q4. Who builds `brokkr-ctl blender`.** Recommend this campaign builds the session - subcommands in Rust per Libby's rulings, and brush-tree adds its tree commands to the - same binary later. +- **Q5. What a push carries.** (a) whole records that changed, under `Expect`, now; (b) + variants override paths applied in place, after CultLib builds in-place apply and + C2b; (c) (a) now with the request shaped so (b) replaces it without changing the + surface. Recommend (c). +- **Q6. Does a ship's loadout belong in its package?** A package holds hull, authoring + and products today; loadouts are catalog records. Recommend not in r2. +- **Q7. May an agent apply a push, or only dry-run?** A `.cc` write has no Ctrl+Z. + Recommend dry-run for agents, apply by her button. +- **Q8. Where the authoring surface lives.** (a) the `aetheria_ships` add-on in Aetheria, + with Brokkr giving the agent typed actions that call it; (b) Brokkr's add-on gains + Aetheria vocabulary. Recommend (a). From 847c28714bc58d37b2e8f30ae1cc1f6088121828 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 18:20:10 +0100 Subject: [PATCH 05/63] Live collab target r2: the push request is a stdin dump, as the material path Co-Authored-By: Claude Opus 5.5 --- docs/live-collab-target.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/live-collab-target.md b/docs/live-collab-target.md index 228ae83..13592ad 100644 --- a/docs/live-collab-target.md +++ b/docs/live-collab-target.md @@ -160,10 +160,11 @@ the three records and their stored versions, builds the tagged collections, and on the binding the version of each record it read. Nothing reads a `.cc` by scraping envelopes (operator 2026-11-17). -**A push is one AetherDb call, dry-run then apply.** The surface writes the authoring +**A push is one AetherDb call, dry-run then apply.** The surface pipes the authoring state of its tagged collections (the manifest vocabulary, plus the record versions it -opened at) to a scratch request file and calls `AetherDb ship-authoring push -`. Without `apply` AetherDb loads the store, derives the records the request +opened at) as a structural JSON dump on stdin to `AetherDb ship-authoring push `, +as the material path does (`aetheria-release:ruling:blender-dump-stdin`): never written +to disk, parsed and judged only in C#, so the schema exists once. Without `apply` AetherDb loads the store, derives the records the request describes, validates them, and prints the per-record, per-field changes; nothing is written. With `apply` it does the same and writes under compare-exchange on each record's stored version (`Expect`). One CLI call per push is the starting shape; a @@ -226,11 +227,11 @@ are the primitive for the push. owns the sink toggle, Stop and undo. Phase two: the `ship.cc` owns the ship; AetherDb's ship-authoring code alone derives and writes its records. - **Inputs.** Intent documents and the sink toggle (phase one). The tagged collections, - the binding's opened versions and the request file (phase two). + the binding's opened versions and the stdin dump (phase two). - **Outputs.** One undo step per accepted mutating intent; one receipt per intent; the refreshed snapshot; look PNG paths; AetherDb's dry-run diff or its write. - **Derived state.** Presence; human-edit sequences; look PNGs; the scene's mapped - collections (an edit buffer over the `.cc`); the request file. + collections (an edit buffer over the `.cc`); the stdin dump (a pipe, not state). - **Forbidden writers.** `execute_command` called around the primitive; operators run with undo on inside an agent action; unpushed agent writes; `ed.undo`/`ed.redo` from add-on code; any agent-sent Python; the debug-mirror JSON import as a door for intents @@ -262,7 +263,6 @@ are the primitive for the push. | Authoring binding | A custom property on the Blender scene: the `ship.cc` path relative to the `.blend`, the ship id, and the record versions opened at | Set on Open; versions replaced after each successful apply; cleared on Detach or reopen. Lives in the `.blend`. | Open, apply and Detach (human buttons or agent actions through the primitive) alone write it. | | Collection role | A custom property on a collection: hull, hardpoints, lines or anchors | Set when the surface builds or the author tags a collection; removed on Detach. | The author; the surface's Open builds the defaults. | | Hardpoint row identity | `aetheria.id` on the row's object, equal to `HardpointData.Id` (`[CultElementId]`) | Minted when the row is created; survives renames and moves; removing the object removes the row on the next push. | AetherDb mints for a new row; the surface carries it. | -| Push request | `/authoring/{commandId}.json`, manifest vocabulary plus opened versions | Written per push; pruned by count; never read back as state. | The surface writes; AetherDb alone interprets it. | ## Not in scope From bebc004f09fcfdb32937dd19553ca7383e7daee7 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 18:32:47 +0100 Subject: [PATCH 06/63] Blender: one agent turn primitive, run_intent (live-2) Every intent is admitted (commandId unused, requestedBy /, typed action), run with operator undo off, pushed as one labelled undo step, and receipted with requestedBy, note and undoLabel. execute_command becomes the private _dispatch. A refusal before any write pushes nothing; a raise after one pushes a '(failed)' step. Live GUI test: Edit Mode object-level write is not reverted by one undo (reported). Co-Authored-By: Claude Sonnet 5.5 --- docs/live-collab-target.md | 4 +- .../blender/brokkr_bridge/blender_target.py | 152 +++++++++++----- .../blender/tests/live/agent_turn_undo.py | 170 ++++++++++++++++++ .../tests/live/agent_turn_undo.result.json | 167 +++++++++++++++++ surfaces/blender/tests/live/gn_actions.py | 4 +- surfaces/blender/tests/live/gn_recreation.py | 4 +- surfaces/blender/tests/live/headless_smoke.py | 2 +- .../blender/tests/live/material_colour.py | 2 +- surfaces/blender/tests/test_agent_turn.py | 90 ++++++++++ .../blender/tests/test_material_actions.py | 21 ++- surfaces/blender/tests/test_node_actions.py | 16 +- surfaces/blender/tests/test_scene_actions.py | 36 +++- 12 files changed, 604 insertions(+), 64 deletions(-) create mode 100644 surfaces/blender/tests/live/agent_turn_undo.py create mode 100644 surfaces/blender/tests/live/agent_turn_undo.result.json create mode 100644 surfaces/blender/tests/test_agent_turn.py diff --git a/docs/live-collab-target.md b/docs/live-collab-target.md index 13592ad..aee7181 100644 --- a/docs/live-collab-target.md +++ b/docs/live-collab-target.md @@ -100,7 +100,9 @@ resident service on that number); reading a record's stored version through Aeth in the add-on: admit (sink enabled, `requestedBy` present, id unused, action typed and valid), run the action with every operator called `undo=False`, push exactly one undo step labelled `Brokkr : `, write the receipt. A -refusal or a failure pushes nothing and leaves the scene unchanged. There is no second +refusal caught before any write pushes nothing and leaves the scene unchanged; an action +that fails after writing pushes one step labelled `(failed)`, so the partial write is one +undoable step. There is no second writer and no script action (`no-free-form-python`): what the typed actions do not cover waits for a new typed action. diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 677f03d..a3156c0 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -5,6 +5,7 @@ import functools import json import math import os +import re import sys import uuid from array import array @@ -43,6 +44,16 @@ CREATABLE_OBJECT_TYPES = ("MESH", "LIGHT", "CAMERA", "EMPTY") GL_RENDER_ENGINES = ("BLENDER_WORKBENCH", "BLENDER_EEVEE", "BLENDER_EEVEE_NEXT") GL_RUNTIME_LIBRARY = "libEGL.so.1" +# Actions that only read the scene and so push no undo step (live-5 adds look). +READ_ACTIONS: tuple[str, ...] = () +MUTATING_ACTIONS = ( + "createObject", "deleteObject", "setObjectTransform", "setObjectVisibility", "setObjectParent", + "setObjectCustomProperty", "selectObject", "assignMaterial", "importGltf", "exportGltf", + "setCamera", "setLight", "setWorld", "renderStill", +) +REQUESTED_BY_SHAPE = re.compile(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$") +NOTE_LIMIT = 200 + EVALUATED_POSITION_CAP = 256 EVALUATED_VERTEX_LIMIT = 1_000_000 EVALUATED_INSTANCE_SCAN_LIMIT = 100_000 # depsgraph items visited per capture; iterating one in Python costs ~5 us @@ -92,6 +103,8 @@ class BrokkrBlenderTarget: self.import_dir: str = "" self.output_dir: str = "" self.nodes = na.NodeActions(bpy_module) + self.agent_turn = False # true only inside run_intent + self._receipted: set[str] = set() def configure_action_dirs(self, import_dir: str, output_dir: str) -> None: """The directories importGltf and renderStill may touch; empty leaves that action disabled.""" @@ -133,9 +146,11 @@ class BrokkrBlenderTarget: snapshot = node.database.snapshot() commands = snapshot.get(COMMAND_INTENT_SCHEMA, {}) receipts: list[dict[str, Any]] = [] + self._receipted.update( + r.get("commandId", "") for r in snapshot.get(COMMAND_RECEIPT_SCHEMA, {}).values()) for command_key, command in sorted(commands.items()): - receipt = self.execute_command(context, command) + receipt = self.run_intent(context, command) self.publish_receipt(cache_path, cultlib_py_src, receipt, debug_mirror_root) node.database.delete(documents["command_intent"], command_key) receipts.append(receipt) @@ -488,45 +503,89 @@ class BrokkrBlenderTarget: "collections": [self._collection_snapshot(collection) for collection in bpy.data.collections], } - def execute_command(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def run_intent(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + """The one agent turn: admit, run with operator undo off, push one labelled undo step, receipt.""" + command_id = command.get("commandId") + requested_by = command.get("requestedBy") action = command.get("action", "") + denial = "" + if not isinstance(command_id, str) or not command_id: + denial = "Intent has no commandId." + elif command_id in self._receipted: + denial = f"commandId {command_id!r} was already receipted; ids are single-use." + elif not isinstance(requested_by, str) or not REQUESTED_BY_SHAPE.match(requested_by): + denial = "Intent has no requestedBy of the form '/'." + elif action not in MUTATING_ACTIONS and action not in READ_ACTIONS and action not in na.NodeActions.ACTIONS: + denial = f"Unsupported Blender command action: {action}" + if denial: + if isinstance(command_id, str) and command_id: + self._receipted.add(command_id) + return self._receipt(command, "denied", denial, "") + + label = f"Brokkr {requested_by}: {action} {command_id[:8]}" + push = action not in READ_ACTIONS + self.agent_turn = True try: - if action == "createObject": - return self._create_object(context, command) - if action == "deleteObject": - return self._delete_object(context, command) - if action == "setObjectTransform": - return self._set_object_transform(context, command) - if action == "setObjectVisibility": - return self._set_object_visibility(context, command) - if action == "setObjectParent": - return self._set_object_parent(context, command) - if action == "setObjectCustomProperty": - return self._set_object_custom_property(context, command) - if action == "selectObject": - return self._select_object(context, command) - if action == "assignMaterial": - return self._assign_material(context, command) - if action == "importGltf": - return self._import_gltf(context, command) - if action == "exportGltf": - return self._export_gltf(context, command) - if action == "setCamera": - return self._set_camera(context, command) - if action == "setLight": - return self._set_light(context, command) - if action == "setWorld": - return self._set_world(context, command) - if action == "renderStill": - return self._render_still(context, command) - if action in na.NodeActions.ACTIONS: - message, name = self.nodes.execute(action, command) - return self._receipt(command, "accepted", message, name) - return self._receipt(command, "failed", f"Unsupported Blender command action: {action}", "") - except sa.ActionRefused as error: - return self._receipt(command, "failed", str(error), "") - except Exception as error: - return self._receipt(command, "failed", str(error), "") + try: + receipt = self._dispatch(context, command) + if receipt["status"] != "accepted": + push = False # returned a refusal: it wrote nothing + except sa.ActionRefused as error: # raised before any write: nothing to push + receipt, push = self._receipt(command, "failed", str(error), ""), False + except Exception as error: # a partial write is one undoable step, not part of her next action + label += " (failed)" + receipt = self._receipt(command, "failed", str(error), "") + if push: + self._push_undo(label) + receipt["undoLabel"] = label + finally: + self.agent_turn = False + self._receipted.add(command_id) + return receipt + + def _push_undo(self, label: str) -> None: + windows = self.bpy.context.window_manager.windows + if windows: + with self.bpy.context.temp_override(window=windows[0]): + self.bpy.ops.ed.undo_push(message=label) + else: + self.bpy.ops.ed.undo_push(message=label) + + def _dispatch(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + """The action table. Only run_intent calls it; it owns refusal, failure and the undo step.""" + action = command.get("action", "") + if action == "createObject": + return self._create_object(context, command) + if action == "deleteObject": + return self._delete_object(context, command) + if action == "setObjectTransform": + return self._set_object_transform(context, command) + if action == "setObjectVisibility": + return self._set_object_visibility(context, command) + if action == "setObjectParent": + return self._set_object_parent(context, command) + if action == "setObjectCustomProperty": + return self._set_object_custom_property(context, command) + if action == "selectObject": + return self._select_object(context, command) + if action == "assignMaterial": + return self._assign_material(context, command) + if action == "importGltf": + return self._import_gltf(context, command) + if action == "exportGltf": + return self._export_gltf(context, command) + if action == "setCamera": + return self._set_camera(context, command) + if action == "setLight": + return self._set_light(context, command) + if action == "setWorld": + return self._set_world(context, command) + if action == "renderStill": + return self._render_still(context, command) + if action in na.NodeActions.ACTIONS: + message, name = self.nodes.execute(action, command) + return self._receipt(command, "accepted", message, name) + return self._receipt(command, "failed", f"Unsupported Blender command action: {action}", "") def _create_object(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: object_type = command.get("objectType", "EMPTY") @@ -542,13 +601,13 @@ class BrokkrBlenderTarget: location = _vector(command.get("location"), 3, (0.0, 0.0, 0.0)) if object_type == "MESH": - self.bpy.ops.mesh.primitive_cube_add(size=float(command.get("size", 1.0)), location=location) + self.bpy.ops.mesh.primitive_cube_add("EXEC_DEFAULT", False, size=float(command.get("size", 1.0)), location=location) elif object_type == "LIGHT": - self.bpy.ops.object.light_add(type=command.get("lightType", "POINT"), location=location) + self.bpy.ops.object.light_add("EXEC_DEFAULT", False, type=command.get("lightType", "POINT"), location=location) elif object_type == "CAMERA": - self.bpy.ops.object.camera_add(location=location) + self.bpy.ops.object.camera_add("EXEC_DEFAULT", False, location=location) else: # EMPTY - self.bpy.ops.object.empty_add(type=command.get("emptyDisplayType", "PLAIN_AXES"), location=location) + self.bpy.ops.object.empty_add("EXEC_DEFAULT", False, type=command.get("emptyDisplayType", "PLAIN_AXES"), location=location) obj = context.object obj.name = name @@ -662,7 +721,7 @@ class BrokkrBlenderTarget: (sa.fingerprint([path]), sa.fingerprint(existing)) != checked: raise sa.ActionRefused("Import file changed while it was being checked.") before = set(self.bpy.data.objects.keys()) - self.bpy.ops.import_scene.gltf(filepath=str(path)) + 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 "") @@ -708,7 +767,7 @@ class BrokkrBlenderTarget: try: for obj in objects: obj.select_set(obj in chosen) - result = self.bpy.ops.export_scene.gltf( + result = self.bpy.ops.export_scene.gltf("EXEC_DEFAULT", False, filepath=str(path), export_format="GLB" if suffix == ".glb" else "GLTF_SEPARATE", use_selection=bool(chosen), **options) finally: @@ -848,7 +907,7 @@ class BrokkrBlenderTarget: path.parent.mkdir(parents=True, exist_ok=True) if sa.resolve_inside(self.output_dir, name, "output", new_file=True) != path: raise sa.ActionRefused("Output path changed while it was being checked.") - self.bpy.ops.render.render(write_still=True) + self.bpy.ops.render.render("EXEC_DEFAULT", False, write_still=True) finally: (render.engine, render.resolution_x, render.resolution_y, render.filepath, render.image_settings.file_format, scene.camera) = saved @@ -1013,6 +1072,9 @@ class BrokkrBlenderTarget: "status": status, "message": message, "objectName": object_name, + "requestedBy": command["requestedBy"] if isinstance(command.get("requestedBy"), str) else "", + "note": command["note"][:NOTE_LIMIT] if isinstance(command.get("note"), str) else "", + "undoLabel": "", "observedAt": _now(), } diff --git a/surfaces/blender/tests/live/agent_turn_undo.py b/surfaces/blender/tests/live/agent_turn_undo.py new file mode 100644 index 0000000..c41ca89 --- /dev/null +++ b/surfaces/blender/tests/live/agent_turn_undo.py @@ -0,0 +1,170 @@ +"""Live proof, in GUI Blender, that every agent intent is one undo step. + + BROKKR_ADDON= \ + blender --factory-startup --python agent_turn_undo.py -- + +Writes .result.json beside , then quits Blender. Each step is its own timer tick so the +event loop runs between steps, as it does for Brokkr's 1 s drain (probe_timer_undo.py pattern). +Undo is read only here, by this driver; the add-on never calls ed.undo or ed.redo. +Exit status is not meaningful in a GUI session: read the "ok" fields of the result. +""" +import json +import os +import sys +import traceback +import types +from pathlib import Path + +import bpy + +ADDON = Path(os.environ["BROKKR_ADDON"]).resolve() +pkg = types.ModuleType("brokkr_bridge"); pkg.__path__ = [str(ADDON)] +sys.modules["brokkr_bridge"] = pkg +from brokkr_bridge import blender_target as bt + +OUT = sys.argv[sys.argv.index("--") + 1] +R = {"blender": bpy.app.version_string, "background": bpy.app.background, "checks": [], "steps": []} +target = bt.BrokkrBlenderTarget(bpy) +N = [0] + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def win(): + w = bpy.context.window_manager.windows[0] + return bpy.context.temp_override(window=w) + + +def intent(**cmd): + N[0] += 1 + cmd.setdefault("commandId", "%08d-live-agent-turn" % N[0]) + cmd.setdefault("requestedBy", "nibu/hands") + r = target.run_intent(bpy.context, cmd) + R["steps"].append({"intent": cmd["action"], "status": r["status"], "undoLabel": r["undoLabel"], "message": r["message"]}) + return r + + +def undo(): + with win(): + bpy.ops.ed.undo() + + +def push(msg): + with win(): + bpy.ops.ed.undo_push(message=msg) + + +def loc(name): + o = bpy.data.objects.get(name) + return None if o is None else [round(v, 3) for v in o.location] + + +def names(): + return sorted(o.name for o in bpy.data.objects) + + +S = {} + + +def s_baseline(): + push("driver baseline") + S["objects0"] = names() + + +def s_create(): + r = intent(action="createObject", objectType="MESH", name="AgentCube", location=[3, 0, 0]) + check("createObject accepted with undoLabel", r["status"] == "accepted" and r["undoLabel"].startswith("Brokkr nibu/hands: createObject "), r["undoLabel"]) + + +def s_transform(): + intent(action="setObjectTransform", objectName="AgentCube", location=[3, 2, 0]) + check("transform applied", loc("AgentCube") == [3.0, 2.0, 0.0], loc("AgentCube")) + + +def s_undo_transform(): + undo() + check("one undo reverts only the transform step", "AgentCube" in names() and loc("AgentCube") == [3.0, 0.0, 0.0], + {"objects": names(), "loc": loc("AgentCube")}) + + +def s_undo_create(): + undo() + check("one undo reverts createObject (cube_add, rename, location) together", names() == S["objects0"], names()) + + +def s_denied_setup(): + intent(action="createObject", objectType="MESH", name="AgentCube2", location=[0, 5, 0]) + r = intent(action="createObject", objectType="MESH", requestedBy="", name="Intruder") + check("denied intent: status denied, scene unchanged", r["status"] == "denied" and "Intruder" not in names(), r["status"]) + check("denied intent: no undoLabel", r["undoLabel"] == "", r["undoLabel"]) + + +def s_denied_undo(): + undo() + check("denied intent pushed nothing: one undo removes the preceding accepted intent", names() == S["objects0"], names()) + + +def s_edit_enter(): + cube = bpy.data.objects["Cube"] + bpy.context.view_layer.objects.active = cube + cube.select_set(True) + with win(): + bpy.ops.object.mode_set(mode="EDIT") + S["loc0"] = loc("Cube") + push("driver edit-mode baseline") + R["editMode"] = {"mode_before": bpy.context.mode, "loc_before": S["loc0"]} + + +def s_edit_agent(): + r = intent(action="setObjectTransform", objectName="Cube", location=[0, 0, 5]) + R["editMode"].update(mode_after_intent=bpy.context.mode, loc_after_intent=loc("Cube"), receipt=r["status"], undoLabel=r["undoLabel"]) + check("edit mode: agent transform applied", loc("Cube") == [0.0, 0.0, 5.0], loc("Cube")) + + +def s_edit_undo(): + undo() + R["editMode"].update(mode_after_undo=bpy.context.mode, loc_after_undo=loc("Cube")) + check("edit mode: one undo reverts the agent transform", loc("Cube") == S["loc0"], R["editMode"]) + + +def s_edit_undo_again(): + """Diagnostic, not a check: where does the object-level write sit relative to Edit Mode steps?""" + undo() + R["editMode"].update(mode_after_second_undo=bpy.context.mode, loc_after_second_undo=loc("Cube")) + + +def s_exit(): + if bpy.context.mode != "OBJECT": + with win(): + bpy.ops.object.mode_set(mode="OBJECT") + + +steps = [s_baseline, s_create, s_transform, s_undo_transform, s_undo_create, s_denied_setup, s_denied_undo, + s_edit_enter, s_edit_agent, s_edit_undo, s_edit_undo_again, s_exit] +i = 0 + + +def write(): + R["ok"] = bool(R["checks"]) and all(c["ok"] for c in R["checks"]) and not any("error" in s for s in R["steps"]) + with open(OUT + ".result.json", "w") as f: + json.dump(R, f, indent=1) + + +def tick(): + global i + if i < len(steps): + try: + steps[i]() + except Exception: + R["steps"].append({"step": steps[i].__name__, "error": traceback.format_exc()}) + i += 1 + write() + return 0.5 + write() + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(tick, first_interval=2.0) diff --git a/surfaces/blender/tests/live/agent_turn_undo.result.json b/surfaces/blender/tests/live/agent_turn_undo.result.json new file mode 100644 index 0000000..5ae93a7 --- /dev/null +++ b/surfaces/blender/tests/live/agent_turn_undo.result.json @@ -0,0 +1,167 @@ +{ + "blender": "5.3.0", + "background": false, + "checks": [ + { + "name": "createObject accepted with undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: createObject 00000001" + }, + { + "name": "transform applied", + "ok": true, + "detail": [ + 3.0, + 2.0, + 0.0 + ] + }, + { + "name": "one undo reverts only the transform step", + "ok": true, + "detail": { + "objects": [ + "AgentCube", + "Camera", + "Cube", + "Light" + ], + "loc": [ + 3.0, + 0.0, + 0.0 + ] + } + }, + { + "name": "one undo reverts createObject (cube_add, rename, location) together", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light" + ] + }, + { + "name": "denied intent: status denied, scene unchanged", + "ok": true, + "detail": "denied" + }, + { + "name": "denied intent: no undoLabel", + "ok": true, + "detail": "" + }, + { + "name": "denied intent pushed nothing: one undo removes the preceding accepted intent", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light" + ] + }, + { + "name": "edit mode: agent transform applied", + "ok": true, + "detail": [ + 0.0, + 0.0, + 5.0 + ] + }, + { + "name": "edit mode: one undo reverts the agent transform", + "ok": false, + "detail": { + "mode_before": "EDIT_MESH", + "loc_before": [ + 0.0, + 0.0, + 0.0 + ], + "mode_after_intent": "EDIT_MESH", + "loc_after_intent": [ + 0.0, + 0.0, + 5.0 + ], + "receipt": "accepted", + "undoLabel": "Brokkr nibu/hands: setObjectTransform 00000005", + "mode_after_undo": "EDIT_MESH", + "loc_after_undo": [ + 0.0, + 0.0, + 5.0 + ], + "mode_after_second_undo": "OBJECT", + "loc_after_second_undo": [ + 0.0, + 0.0, + 0.0 + ] + } + } + ], + "steps": [ + { + "intent": "createObject", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: createObject 00000001", + "message": "Blender object created." + }, + { + "intent": "setObjectTransform", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: setObjectTransform 00000002", + "message": "Blender object transform updated." + }, + { + "intent": "createObject", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: createObject 00000003", + "message": "Blender object created." + }, + { + "intent": "createObject", + "status": "denied", + "undoLabel": "", + "message": "Intent has no requestedBy of the form '/'." + }, + { + "intent": "setObjectTransform", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: setObjectTransform 00000005", + "message": "Blender object transform updated." + } + ], + "ok": false, + "editMode": { + "mode_before": "EDIT_MESH", + "loc_before": [ + 0.0, + 0.0, + 0.0 + ], + "mode_after_intent": "EDIT_MESH", + "loc_after_intent": [ + 0.0, + 0.0, + 5.0 + ], + "receipt": "accepted", + "undoLabel": "Brokkr nibu/hands: setObjectTransform 00000005", + "mode_after_undo": "EDIT_MESH", + "loc_after_undo": [ + 0.0, + 0.0, + 5.0 + ], + "mode_after_second_undo": "OBJECT", + "loc_after_second_undo": [ + 0.0, + 0.0, + 0.0 + ] + } +} \ No newline at end of file diff --git a/surfaces/blender/tests/live/gn_actions.py b/surfaces/blender/tests/live/gn_actions.py index 1d9e329..62df949 100644 --- a/surfaces/blender/tests/live/gn_actions.py +++ b/surfaces/blender/tests/live/gn_actions.py @@ -4,7 +4,7 @@ blender -b --factory-startup --python gn_actions.py -- result.json Each native tree is built with bpy as the reference and evaluated with the depsgraph. The Brokkr side -uses BrokkrBlenderTarget.execute_command for every build step and capture_snapshot().objects[].evaluated +uses BrokkrBlenderTarget.run_intent for every build step and capture_snapshot().objects[].evaluated for every read: no bpy call touches the Brokkr-built scene except the harness's own reference trees. Exit status is non-zero if any check fails. """ @@ -29,7 +29,7 @@ def fresh(): N = [0] def act(t, **cmd): N[0] += 1; cmd.setdefault("commandId", "c%d" % N[0]) - r = t.execute_command(bpy.context, cmd) + r = t.run_intent(bpy.context, dict(cmd, requestedBy="test/driver")) if r["status"] != "accepted": print("REFUSED", cmd["action"], r["message"], flush=True) return r diff --git a/surfaces/blender/tests/live/gn_recreation.py b/surfaces/blender/tests/live/gn_recreation.py index 6ef8036..f8127d9 100644 --- a/surfaces/blender/tests/live/gn_recreation.py +++ b/surfaces/blender/tests/live/gn_recreation.py @@ -4,7 +4,7 @@ blender -b --factory-startup --python gn_recreation.py -- result.json Each setup is built twice: natively (geometry-nodes tree via bpy, evaluated) and through -BrokkrBlenderTarget.execute_command using only the actions that exist. Prints GAP lines where an +BrokkrBlenderTarget.run_intent using only the actions that exist. Prints GAP lines where an action that would be needed is refused or has no effect. Not part of the unittest run (needs Blender). """ import bpy, sys, os, json, types, math, random @@ -25,7 +25,7 @@ def reset(): def act(t, **cmd): cmd.setdefault("commandId", "c%d" % act.n); act.n += 1 - return t.execute_command(bpy.context, cmd) + return t.run_intent(bpy.context, dict(cmd, requestedBy="test/driver")) act.n = 0 def gap(key, **detail): diff --git a/surfaces/blender/tests/live/headless_smoke.py b/surfaces/blender/tests/live/headless_smoke.py index 085df0c..1d21601 100644 --- a/surfaces/blender/tests/live/headless_smoke.py +++ b/surfaces/blender/tests/live/headless_smoke.py @@ -43,7 +43,7 @@ results = [] def run(label, **cmd): cmd.setdefault("commandId", label) try: - r = target.execute_command(bpy.context, cmd) + r = target.run_intent(bpy.context, dict(cmd, requestedBy="test/driver")) except Exception: r = {"status": "EXCEPTION", "message": traceback.format_exc()} print("RESULT", label, r["status"], r.get("message", "").replace("\n", " | ")[:400], flush=True) diff --git a/surfaces/blender/tests/live/material_colour.py b/surfaces/blender/tests/live/material_colour.py index 4b43135..07c2f4d 100644 --- a/surfaces/blender/tests/live/material_colour.py +++ b/surfaces/blender/tests/live/material_colour.py @@ -26,7 +26,7 @@ cube = bpy.context.active_object N = [0] def act(**cmd): N[0] += 1; cmd.setdefault("commandId", "c%d" % N[0]); cmd["action"] = "assignMaterial"; cmd["targetObjectName"] = cube.name - return t.execute_command(bpy.context, cmd) + return t.run_intent(bpy.context, dict(cmd, requestedBy="test/driver")) def base(): return tuple(round(c, 6) for c in bpy.data.materials["oxide red"].node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value) diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py new file mode 100644 index 0000000..353f709 --- /dev/null +++ b/surfaces/blender/tests/test_agent_turn.py @@ -0,0 +1,90 @@ +"""run_intent: admission, one labelled undo step, receipts. A fake bpy records ops calls.""" +from __future__ import annotations + +import re +import unittest +import unittest.mock +from pathlib import Path + +import test_scene_actions as ts + +bt = ts.bt +SOURCE = Path(bt.__file__) + + +class AgentTurnTests(unittest.TestCase): + """Reuses the scene fixture (fake bpy, temp import/output dirs).""" + setUp = ts.ActionTests.setUp + run_action = ts.ActionTests.run_action + + def test_intent_without_requested_by_is_denied(self): + receipt = self.run_action(action="createObject", objectType="EMPTY", requestedBy="") + self.assertEqual(receipt["status"], "denied") + self.assertEqual(self.bpy.created, []) + self.assertEqual(self.bpy.undo.pushes, []) + receipt = self.run_action(action="createObject", objectType="EMPTY", requestedBy="nibu") + self.assertEqual(receipt["status"], "denied") + self.assertEqual(self.bpy.created, []) + + def test_unknown_action_is_denied(self): + self.assertEqual(self.run_action(action="runPython")["status"], "denied") + self.assertEqual(self.bpy.undo.pushes, []) + + def test_reused_command_id_is_denied(self): + first = self.run_action(action="createObject", objectType="EMPTY", commandId="same-id-1") + self.assertEqual(first["status"], "accepted") + second = self.run_action(action="createObject", objectType="EMPTY", commandId="same-id-1") + self.assertEqual(second["status"], "denied") + self.assertEqual(len(self.bpy.created), 1) + self.assertEqual(len(self.bpy.undo.pushes), 1) + + def test_accepted_receipt_carries_undo_label(self): + receipt = self.run_action(action="createObject", objectType="EMPTY", + commandId="abcdef0123456789", requestedBy="nibu/hands", note="x" * 300) + label = "Brokkr nibu/hands: createObject abcdef01" + self.assertEqual(self.bpy.undo.pushes, [label]) + self.assertEqual(receipt["undoLabel"], label) + self.assertEqual(receipt["requestedBy"], "nibu/hands") + self.assertEqual(len(receipt["note"]), 200) + + def test_refusal_pushes_nothing(self): + receipt = self.run_action(action="createObject", objectType="BOGUS") + self.assertEqual(receipt["status"], "failed") + self.assertEqual(receipt["undoLabel"], "") + self.assertEqual(self.bpy.undo.pushes, []) + + def test_read_action_pushes_nothing(self): + with unittest.mock.patch.object(bt, "READ_ACTIONS", ("createObject",)): + self.run_action(action="createObject", objectType="EMPTY") + self.assertEqual(self.bpy.undo.pushes, []) + + def test_raise_after_admission_pushes_failed_step(self): + def boom(*a, **kw): + raise RuntimeError("half done") + self.bpy.ops.object.empty_add = boom + receipt = self.run_action(action="createObject", objectType="EMPTY", commandId="deadbeef99") + self.assertEqual(receipt["status"], "failed") + self.assertEqual(self.bpy.undo.pushes, ["Brokkr nibu/hands: createObject deadbeef (failed)"]) + + def test_agent_turn_flag_is_scoped(self): + seen = [] + original = self.bpy.ops.object.empty_add + self.bpy.ops.object.empty_add = lambda *a, **kw: (seen.append(self.target.agent_turn), original(*a, **kw))[1] + self.run_action(action="createObject", objectType="EMPTY") + self.assertEqual(seen, [True]) + self.assertFalse(self.target.agent_turn) + + def test_operators_called_with_undo_false(self): + self.assertEqual(self.run_action(action="exportGltf", filepath="o.glb")["status"], "accepted") + self.assertEqual(self.run_action(action="importGltf", filepath="model.glb")["status"], "accepted") + self.assertEqual(self.run_action(action="renderStill", outputPath="r.png", engine="CYCLES")["status"], "accepted") + for kind in ("MESH", "LIGHT", "CAMERA", "EMPTY"): + self.assertEqual(self.run_action(action="createObject", objectType=kind)["status"], "accepted") + # the fake ops assert ("EXEC_DEFAULT", False); the source pattern pins the spelling too + bad = re.findall(r'bpy\.ops\.(?:mesh|object|import_scene|export_scene|render)\.[a-z_]+\((?!"EXEC_DEFAULT", False)', + SOURCE.read_text(encoding="utf-8")) + self.assertEqual(bad, []) + + +if __name__ == "__main__": + unittest.main() diff --git a/surfaces/blender/tests/test_material_actions.py b/surfaces/blender/tests/test_material_actions.py index 9ecc2ec..0caa663 100644 --- a/surfaces/blender/tests/test_material_actions.py +++ b/surfaces/blender/tests/test_material_actions.py @@ -5,6 +5,9 @@ The real API is exercised by tests/live/material_colour.py. """ from __future__ import annotations +import contextlib +import itertools + import sys import types import unittest @@ -50,11 +53,25 @@ class Materials(dict): return self[name] +IDS = itertools.count() + + +class FakeUndo: + """What run_intent needs of bpy: a window to override and ed.undo_push, recorded.""" + def __init__(self, bpy): + self.pushes = [] + bpy.context = NS(window_manager=NS(windows=[object()]), temp_override=lambda **kw: contextlib.nullcontext()) + ops = getattr(bpy, "ops", None) or NS() + ops.ed = NS(undo_push=lambda message: self.pushes.append(message)) + bpy.ops = ops + + class FakeBpy: def __init__(self): self.mesh = NS(name="Cube", type="MESH", data=NS(materials=[])) self.empty = NS(name="Empty", type="EMPTY", data=None) self.data = NS(objects={"Cube": self.mesh, "Empty": self.empty}, materials=Materials()) + self.undo = FakeUndo(self) class MaterialTests(unittest.TestCase): @@ -63,7 +80,7 @@ class MaterialTests(unittest.TestCase): self.target = bt.BrokkrBlenderTarget(self.bpy) def assign(self, **fields): - return self.target.execute_command(NS(), {"commandId": "c1", "action": "assignMaterial", + return self.target.run_intent(NS(), {"commandId": f"c{next(IDS)}", "requestedBy": "nibu/hands", "action": "assignMaterial", "targetObjectName": "Cube", **fields}) def base_color(self, name="oxide red"): @@ -137,7 +154,7 @@ class MaterialTests(unittest.TestCase): self.assertEqual(self.base_color("bare"), (0.2, 0.3, 0.4, 1.0)) def test_object_without_material_slots_is_refused(self): - receipt = self.target.execute_command(NS(), {"commandId": "c", "action": "assignMaterial", + receipt = self.target.run_intent(NS(), {"commandId": f"c{next(IDS)}", "requestedBy": "nibu/hands", "action": "assignMaterial", "targetObjectName": "Empty", "color": [1, 0, 0]}) self.assertEqual(receipt["status"], "failed") self.assertEqual(dict(self.bpy.data.materials), {}) diff --git a/surfaces/blender/tests/test_node_actions.py b/surfaces/blender/tests/test_node_actions.py index 4c333f1..eac602f 100644 --- a/surfaces/blender/tests/test_node_actions.py +++ b/surfaces/blender/tests/test_node_actions.py @@ -5,6 +5,8 @@ The real API is exercised by tests/live/gn_actions.py. """ from __future__ import annotations +import contextlib + import sys import types import unittest @@ -168,9 +170,20 @@ class Obj: self.custom = (key, value) +class FakeUndo: + """What run_intent needs of bpy: a window to override and ed.undo_push, recorded.""" + def __init__(self, bpy): + self.pushes = [] + bpy.context = NS(window_manager=NS(windows=[object()]), temp_override=lambda **kw: contextlib.nullcontext()) + ops = getattr(bpy, "ops", None) or NS() + ops.ed = NS(undo_push=lambda message: self.pushes.append(message)) + bpy.ops = ops + + class FakeBpy: def __init__(self): self.data = NS(node_groups=Groups(), objects={"Host": Obj("Host")}) + self.undo = FakeUndo(self) class NodeActionTests(unittest.TestCase): @@ -182,7 +195,8 @@ class NodeActionTests(unittest.TestCase): def run_action(self, **command): self.n += 1 command.setdefault("commandId", f"c{self.n}") - return self.target.execute_command(None, command) + command.setdefault("requestedBy", "nibu/hands") + return self.target.run_intent(None, command) def accepted(self, **command): receipt = self.run_action(**command) diff --git a/surfaces/blender/tests/test_scene_actions.py b/surfaces/blender/tests/test_scene_actions.py index bb3a292..c60b657 100644 --- a/surfaces/blender/tests/test_scene_actions.py +++ b/surfaces/blender/tests/test_scene_actions.py @@ -4,6 +4,7 @@ Run: python3 -m unittest discover -s surfaces/blender/tests -v """ from __future__ import annotations +import contextlib import json import os import struct @@ -69,6 +70,16 @@ class Objects(dict): """bpy.data.objects: a mapping with keys() and get().""" +class FakeUndo: + """What run_intent needs of bpy: a window to override and ed.undo_push, recorded.""" + def __init__(self, bpy): + self.pushes = [] + bpy.context = NS(window_manager=NS(windows=[object()]), temp_override=lambda **kw: contextlib.nullcontext()) + ops = getattr(bpy, "ops", None) or NS() + ops.ed = NS(undo_push=lambda message: self.pushes.append(message)) + bpy.ops = ops + + class FakeBpy: def __init__(self): self.imported = [] @@ -95,14 +106,16 @@ class FakeBpy: o.selected = o is self.mesh o.select_get = (lambda o=o: o.selected) o.select_set = (lambda state, o=o: setattr(o, "selected", state)) - add = lambda kind: (lambda **kw: self.add_object(kind, kw)) + 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), export_scene=NS(gltf=self.export_gltf), mesh=NS(primitive_cube_add=add("MESH")), object=NS(light_add=add("LIGHT"), camera_add=add("CAMERA"), empty_add=add("EMPTY"))) self.on_add = lambda obj: None + self.undo = FakeUndo(self) - def add_object(self, kind, kwargs): + def add_object(self, kind, kwargs, call=("EXEC_DEFAULT", False)): + assert call == ("EXEC_DEFAULT", False), call # operators run with undo off self.created.append((kind, kwargs)) obj = NS(name=kind.title(), type=kind) self.data.objects[obj.name] = obj @@ -115,18 +128,21 @@ class FakeBpy: world.background = background return world - def import_gltf(self, filepath): + 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) - def export_gltf(self, **kwargs): + def export_gltf(self, mode, undo, **kwargs): + assert (mode, undo) == ("EXEC_DEFAULT", False) kwargs["selected_at_call"] = sorted(o.name for o in self.data.objects.values() if o.selected) self.exported.append(kwargs) if self.export_writes: Path(kwargs["filepath"]).write_bytes(b"x" * 10) return self.export_result - def render_still(self, write_still): + def render_still(self, mode, undo, write_still): + assert (mode, undo) == ("EXEC_DEFAULT", False) r = self.scene.render self.rendered.append((r.engine, r.resolution_x, r.resolution_y, r.filepath, r.image_settings.file_format, self.scene.camera)) @@ -149,8 +165,10 @@ class ActionTests(unittest.TestCase): self.bpy.on_add = lambda obj: setattr(self.context, "object", obj) def run_action(self, **command): - command.setdefault("commandId", "c1") - return self.target.execute_command(self.context, command) + self.n = getattr(self, "n", 0) + 1 + command.setdefault("commandId", f"c{self.n:07d}") + command.setdefault("requestedBy", "nibu/hands") + return self.target.run_intent(self.context, command) # importGltf def test_import_inside_the_import_dir_runs(self): @@ -289,7 +307,7 @@ class ActionTests(unittest.TestCase): self.assertFalse((self.root / "out" / "b.glb").exists()) def test_export_selection_restored_when_the_exporter_raises(self): - def boom(**kw): + def boom(*a, **kw): raise RuntimeError("exporter blew up") self.bpy.ops.export_scene.gltf = boom receipt = self.run_action(action="exportGltf", filepath="a.glb", selection=["Cam"]) @@ -362,7 +380,7 @@ class ActionTests(unittest.TestCase): self.assertIsNone(self.bpy.scene.camera) def test_render_still_restores_settings_when_the_render_fails(self): - def boom(write_still): + def boom(*a, **kw): raise RuntimeError("render failed") self.bpy.ops.render.render = boom self.assertEqual(self.run_action(action="renderStill", outputPath="a.png", engine="CYCLES")["status"], "failed") From 6464915fa42e5eb3dee1114bb7a7f7aeed0202e2 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 18:35:25 +0100 Subject: [PATCH 07/63] Blender: refuse object-level intents while an object is in Edit Mode Ruling brokkr-live:ruling:object-intents-refused-in-edit-mode. The guard denies before any write, so nothing is pushed and her mode is untouched. Live check measured in Blender 5.3.0: refused, scene and undo stack unchanged. Co-Authored-By: Claude Sonnet 5.5 --- .../blender/brokkr_bridge/blender_target.py | 12 +++ .../blender/tests/live/agent_turn_undo.py | 31 +++++--- .../tests/live/agent_turn_undo.result.json | 76 +++++++++++-------- surfaces/blender/tests/test_agent_turn.py | 13 ++++ 4 files changed, 90 insertions(+), 42 deletions(-) diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index a3156c0..3b9a81a 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -51,6 +51,9 @@ MUTATING_ACTIONS = ( "setObjectCustomProperty", "selectObject", "assignMaterial", "importGltf", "exportGltf", "setCamera", "setLight", "setWorld", "renderStill", ) +# While an object is in Edit Mode, undo steps are edit-mesh steps and an object-level write is not +# reverted by one undo (brokkr-live:ruling:object-intents-refused-in-edit-mode). These touch no object. +EDIT_MODE_SAFE_ACTIONS = ("setWorld", "exportGltf", "renderStill") REQUESTED_BY_SHAPE = re.compile(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$") NOTE_LIMIT = 200 @@ -517,6 +520,9 @@ class BrokkrBlenderTarget: denial = "Intent has no requestedBy of the form '/'." elif action not in MUTATING_ACTIONS and action not in READ_ACTIONS and action not in na.NodeActions.ACTIONS: denial = f"Unsupported Blender command action: {action}" + elif action not in EDIT_MODE_SAFE_ACTIONS and self._edit_mode_object() is not None: + denial = (f"Object {self._edit_mode_object()!r} is in Edit Mode: object-level intents are refused " + "until she leaves it; nothing was changed.") if denial: if isinstance(command_id, str) and command_id: self._receipted.add(command_id) @@ -543,6 +549,12 @@ class BrokkrBlenderTarget: self._receipted.add(command_id) return receipt + def _edit_mode_object(self) -> str | None: + for obj in self.bpy.data.objects.values(): + if getattr(obj, "mode", "OBJECT") == "EDIT": + return obj.name + return None + def _push_undo(self, label: str) -> None: windows = self.bpy.context.window_manager.windows if windows: diff --git a/surfaces/blender/tests/live/agent_turn_undo.py b/surfaces/blender/tests/live/agent_turn_undo.py index c41ca89..75716ee 100644 --- a/surfaces/blender/tests/live/agent_turn_undo.py +++ b/surfaces/blender/tests/live/agent_turn_undo.py @@ -15,6 +15,7 @@ import traceback import types from pathlib import Path +import bmesh import bpy ADDON = Path(os.environ["BROKKR_ADDON"]).resolve() @@ -68,6 +69,11 @@ def names(): S = {} +def vz(): + bm = bmesh.from_edit_mesh(bpy.data.objects["Cube"].data); bm.verts.ensure_lookup_table() + return round(bm.verts[0].co.z, 3) + + def s_baseline(): push("driver baseline") S["objects0"] = names() @@ -114,25 +120,28 @@ def s_edit_enter(): bpy.ops.object.mode_set(mode="EDIT") S["loc0"] = loc("Cube") push("driver edit-mode baseline") + S["z0"] = vz() + bm = bmesh.from_edit_mesh(cube.data); bm.verts.ensure_lookup_table(); bm.verts[0].co.z += 5.0 + bmesh.update_edit_mesh(cube.data) + push("her edit-mesh edit") R["editMode"] = {"mode_before": bpy.context.mode, "loc_before": S["loc0"]} def s_edit_agent(): r = intent(action="setObjectTransform", objectName="Cube", location=[0, 0, 5]) - R["editMode"].update(mode_after_intent=bpy.context.mode, loc_after_intent=loc("Cube"), receipt=r["status"], undoLabel=r["undoLabel"]) - check("edit mode: agent transform applied", loc("Cube") == [0.0, 0.0, 5.0], loc("Cube")) + R["editMode"].update(mode_after_intent=bpy.context.mode, loc_after_intent=loc("Cube"), receipt=r["status"], + message=r["message"], undoLabel=r["undoLabel"]) + check("edit mode: object-level intent refused, scene and her mode unchanged", + r["status"] == "denied" and "Edit Mode" in r["message"] and r["undoLabel"] == "" + and loc("Cube") == S["loc0"] and bpy.context.mode == "EDIT_MESH", R["editMode"]) def s_edit_undo(): + """One undo must revert her edit-mesh step: a step pushed by the refused intent would have taken it.""" undo() - R["editMode"].update(mode_after_undo=bpy.context.mode, loc_after_undo=loc("Cube")) - check("edit mode: one undo reverts the agent transform", loc("Cube") == S["loc0"], R["editMode"]) - - -def s_edit_undo_again(): - """Diagnostic, not a check: where does the object-level write sit relative to Edit Mode steps?""" - undo() - R["editMode"].update(mode_after_second_undo=bpy.context.mode, loc_after_second_undo=loc("Cube")) + R["editMode"].update(mode_after_undo=bpy.context.mode, loc_after_undo=loc("Cube"), z_before=S["z0"] + 5.0, z_after_undo=vz()) + check("edit mode: undo stack unchanged by the refused intent (one undo reverts her edit-mesh step)", + vz() == S["z0"] and loc("Cube") == S["loc0"], R["editMode"]) def s_exit(): @@ -142,7 +151,7 @@ def s_exit(): steps = [s_baseline, s_create, s_transform, s_undo_transform, s_undo_create, s_denied_setup, s_denied_undo, - s_edit_enter, s_edit_agent, s_edit_undo, s_edit_undo_again, s_exit] + s_edit_enter, s_edit_agent, s_edit_undo, s_exit] i = 0 diff --git a/surfaces/blender/tests/live/agent_turn_undo.result.json b/surfaces/blender/tests/live/agent_turn_undo.result.json index 5ae93a7..455335f 100644 --- a/surfaces/blender/tests/live/agent_turn_undo.result.json +++ b/surfaces/blender/tests/live/agent_turn_undo.result.json @@ -62,17 +62,8 @@ ] }, { - "name": "edit mode: agent transform applied", + "name": "edit mode: object-level intent refused, scene and her mode unchanged", "ok": true, - "detail": [ - 0.0, - 0.0, - 5.0 - ] - }, - { - "name": "edit mode: one undo reverts the agent transform", - "ok": false, "detail": { "mode_before": "EDIT_MESH", "loc_before": [ @@ -84,22 +75,48 @@ "loc_after_intent": [ 0.0, 0.0, - 5.0 + 0.0 ], - "receipt": "accepted", - "undoLabel": "Brokkr nibu/hands: setObjectTransform 00000005", + "receipt": "denied", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "undoLabel": "", "mode_after_undo": "EDIT_MESH", "loc_after_undo": [ 0.0, 0.0, - 5.0 + 0.0 ], - "mode_after_second_undo": "OBJECT", - "loc_after_second_undo": [ + "z_before": 6.0, + "z_after_undo": 1.0 + } + }, + { + "name": "edit mode: undo stack unchanged by the refused intent (one undo reverts her edit-mesh step)", + "ok": true, + "detail": { + "mode_before": "EDIT_MESH", + "loc_before": [ 0.0, 0.0, 0.0 - ] + ], + "mode_after_intent": "EDIT_MESH", + "loc_after_intent": [ + 0.0, + 0.0, + 0.0 + ], + "receipt": "denied", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "undoLabel": "", + "mode_after_undo": "EDIT_MESH", + "loc_after_undo": [ + 0.0, + 0.0, + 0.0 + ], + "z_before": 6.0, + "z_after_undo": 1.0 } } ], @@ -130,12 +147,12 @@ }, { "intent": "setObjectTransform", - "status": "accepted", - "undoLabel": "Brokkr nibu/hands: setObjectTransform 00000005", - "message": "Blender object transform updated." + "status": "denied", + "undoLabel": "", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed." } ], - "ok": false, + "ok": true, "editMode": { "mode_before": "EDIT_MESH", "loc_before": [ @@ -147,21 +164,18 @@ "loc_after_intent": [ 0.0, 0.0, - 5.0 + 0.0 ], - "receipt": "accepted", - "undoLabel": "Brokkr nibu/hands: setObjectTransform 00000005", + "receipt": "denied", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "undoLabel": "", "mode_after_undo": "EDIT_MESH", "loc_after_undo": [ - 0.0, - 0.0, - 5.0 - ], - "mode_after_second_undo": "OBJECT", - "loc_after_second_undo": [ 0.0, 0.0, 0.0 - ] + ], + "z_before": 6.0, + "z_after_undo": 1.0 } } \ No newline at end of file diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index 353f709..db950a6 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -26,6 +26,19 @@ class AgentTurnTests(unittest.TestCase): self.assertEqual(receipt["status"], "denied") self.assertEqual(self.bpy.created, []) + def test_object_intent_is_refused_while_an_object_is_in_edit_mode(self): + self.bpy.mesh.mode = "EDIT" + receipt = self.run_action(action="setObjectTransform", objectName="Cube", location=[0, 0, 5]) + self.assertEqual(receipt["status"], "denied") + self.assertIn("Edit Mode", receipt["message"]) + self.assertEqual(receipt["undoLabel"], "") + self.assertEqual(self.bpy.undo.pushes, []) + self.assertEqual(self.bpy.created, []) + self.assertEqual(self.bpy.mesh.mode, "EDIT") # the agent never changes her mode + self.assertEqual(self.run_action(action="renderStill", outputPath="r.png", engine="CYCLES")["status"], "accepted") + self.bpy.mesh.mode = "OBJECT" + self.assertEqual(self.run_action(action="createObject", objectType="EMPTY")["status"], "accepted") + def test_unknown_action_is_denied(self): self.assertEqual(self.run_action(action="runPython")["status"], "denied") self.assertEqual(self.bpy.undo.pushes, []) From 8f8c92e7c906286532d7e31f4849920166195e5a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 19:09:48 +0100 Subject: [PATCH 08/63] Blender agent turn: Soul s1 fixes Edit Mode refuses setWorld and exportGltf too (only renderStill stays); exportGltf and renderStill push no undo step; receipts are write-once (a reused id's denial goes under .denied); a raise in the undo push is a failed receipt and never re-runs; pin the four surviving branches; queue-level live harness through the node and the add-on timer. Co-Authored-By: Claude Sonnet 5.5 --- .../blender/brokkr_bridge/blender_target.py | 31 ++- .../blender/tests/live/agent_turn_queue.py | 225 ++++++++++++++++++ .../tests/live/agent_turn_queue.result.json | 196 +++++++++++++++ .../blender/tests/live/agent_turn_undo.py | 34 ++- .../tests/live/agent_turn_undo.result.json | 131 ++++++++++ surfaces/blender/tests/test_agent_turn.py | 96 ++++++++ surfaces/blender/tests/test_scene_actions.py | 5 +- 7 files changed, 708 insertions(+), 10 deletions(-) create mode 100644 surfaces/blender/tests/live/agent_turn_queue.py create mode 100644 surfaces/blender/tests/live/agent_turn_queue.result.json diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 3b9a81a..2528bbc 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -51,9 +51,13 @@ MUTATING_ACTIONS = ( "setObjectCustomProperty", "selectObject", "assignMaterial", "importGltf", "exportGltf", "setCamera", "setLight", "setWorld", "renderStill", ) -# While an object is in Edit Mode, undo steps are edit-mesh steps and an object-level write is not -# reverted by one undo (brokkr-live:ruling:object-intents-refused-in-edit-mode). These touch no object. -EDIT_MODE_SAFE_ACTIONS = ("setWorld", "exportGltf", "renderStill") +# Actions that change no scene state: they push no undo step (exportGltf restores its selection; +# renderStill restores its settings). +NO_SCENE_CHANGE_ACTIONS = ("exportGltf", "renderStill") +# While an object is in Edit Mode, undo steps are edit-mesh steps, so a scene write is not reverted by +# one undo, and some operators leave Edit Mode (brokkr-live:ruling:object-intents-refused-in-edit-mode). +# Anything that writes scene state or changes her mode is refused; renderStill does neither. +EDIT_MODE_SAFE_ACTIONS = ("renderStill",) REQUESTED_BY_SHAPE = re.compile(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$") NOTE_LIMIT = 200 @@ -153,8 +157,12 @@ class BrokkrBlenderTarget: r.get("commandId", "") for r in snapshot.get(COMMAND_RECEIPT_SCHEMA, {}).values()) for command_key, command in sorted(commands.items()): + reused = command.get("commandId") in self._receipted receipt = self.run_intent(context, command) - self.publish_receipt(cache_path, cultlib_py_src, receipt, debug_mirror_root) + # Receipts are write-once: a reused id's denial goes under '.denied', never over the + # original. The sender learns of it by reading that key (and the drain's returned list). + self.publish_receipt(cache_path, cultlib_py_src, receipt, debug_mirror_root, + key_suffix=".denied" if reused else "") node.database.delete(documents["command_intent"], command_key) receipts.append(receipt) @@ -166,8 +174,9 @@ class BrokkrBlenderTarget: cultlib_py_src: str, receipt: dict[str, Any], debug_mirror_root: str = "", + key_suffix: str = "", ) -> None: - command_id = receipt.get("commandId") or uuid.uuid4().hex + command_id = (receipt.get("commandId") or uuid.uuid4().hex) + key_suffix node, documents = self._open_node(cache_path, cultlib_py_src) node.database.put(documents["command_receipt"], f"blender/receipts/{command_id}", receipt) if debug_mirror_root: @@ -529,7 +538,7 @@ class BrokkrBlenderTarget: return self._receipt(command, "denied", denial, "") label = f"Brokkr {requested_by}: {action} {command_id[:8]}" - push = action not in READ_ACTIONS + push = action not in READ_ACTIONS and action not in NO_SCENE_CHANGE_ACTIONS self.agent_turn = True try: try: @@ -542,8 +551,14 @@ class BrokkrBlenderTarget: label += " (failed)" receipt = self._receipt(command, "failed", str(error), "") if push: - self._push_undo(label) - receipt["undoLabel"] = label + try: + self._push_undo(label) + receipt["undoLabel"] = label + except Exception as error: # the write stands; the intent is receipted, never re-run + receipt = self._receipt( + command, "failed", + f"{receipt['message']} The undo step could not be pushed ({error}); the change stands " + "but is not one undo step.", receipt["objectName"]) finally: self.agent_turn = False self._receipted.add(command_id) diff --git a/surfaces/blender/tests/live/agent_turn_queue.py b/surfaces/blender/tests/live/agent_turn_queue.py new file mode 100644 index 0000000..e44669a --- /dev/null +++ b/surfaces/blender/tests/live/agent_turn_queue.py @@ -0,0 +1,225 @@ +"""Live proof, in GUI Blender with the add-on enabled, that intents arriving through the node queue +are drained by the add-on's own 1 s timer as one undo step each, with write-once receipts. + + BROKKR_USER_SCRIPTS= (also BLENDER_USER_SCRIPTS) + BROKKR_SCRATCH= + BROKKR_PYLIBS= + blender --factory-startup --python agent_turn_queue.py -- + +Intents are put into the node database as brokkr-ctl does (no debug-mirror files). Writes +.result.json, then quits Blender. Undo is read only here, by this driver. +""" +import json +import os +import sys +import traceback +from pathlib import Path + +import bpy + +if os.environ.get("BROKKR_PYLIBS"): + sys.path.insert(0, os.environ["BROKKR_PYLIBS"]) +SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() +SCRATCH.mkdir(parents=True, exist_ok=True) +OUT = sys.argv[sys.argv.index("--") + 1] +R = {"blender": bpy.app.version_string, "checks": [], "receipts": {}} + +bpy.ops.preferences.addon_enable(module="brokkr_bridge") +import brokkr_bridge as addon # noqa: E402 +from brokkr_bridge import blender_target as bt # noqa: E402 + +prefs = bpy.context.preferences.addons["brokkr_bridge"].preferences +CACHE = str(SCRATCH / "queue.ccmp") +prefs.cultmesh_cache_path = CACHE +prefs.debug_mirror_root = "" # the debug-mirror door is not used here +prefs.output_dir = str(SCRATCH / "out") +prefs.import_dir = "" +prefs.auto_drain_commands = True +(SCRATCH / "out").mkdir(exist_ok=True) +adapter = addon.target() + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def win(): + return bpy.context.temp_override(window=bpy.context.window_manager.windows[0]) + + +def undo(): + with win(): + bpy.ops.ed.undo() + + +def push(msg): + with win(): + bpy.ops.ed.undo_push(message=msg) + + +def node(): + return adapter._open_node(CACHE, prefs.cultlib_py_src) + + +def queue(cid, **cmd): + n, docs = node() + cmd.update(commandId=cid, schema=bt.COMMAND_INTENT_SCHEMA) + n.database.put(docs["command_intent"], f"blender/commands/{cid}", cmd) + + +def receipt(key): + n, _ = node() + return n.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}).get(f"blender/receipts/{key}") + + +def pending(): + n, _ = node() + return n.database.snapshot().get(bt.COMMAND_INTENT_SCHEMA, {}) + + +def names(): + return sorted(o.name for o in bpy.data.objects) + + +S = {} +WAIT = {"ticks": 0} + + +def until(pred, limit=24): + """A step that repeats each tick until pred() holds (the add-on's timer drains meanwhile).""" + def step(): + WAIT["ticks"] += 1 + if pred(): + WAIT["ticks"] = 0 + return True + if WAIT["ticks"] > limit: + raise TimeoutError("drain did not receipt in time") + return False + return step + + +def once(fn): + def step(): + fn() + return True + return step + + +def drained(*ids): + return lambda: all(receipt(i) for i in ids) + + +def q1(): + push("driver baseline") + queue("aaaaaaaa-0001", action="createObject", objectType="MESH", name="QCube", location=[4, 0, 0], + requestedBy="nibu/hands", note="queue test") + + +def q1_check(): + r = receipt("aaaaaaaa-0001") + R["receipts"]["q1"] = r + S["q1_label"] = r and r.get("undoLabel") + check("queue: createObject drained by the add-on timer, accepted, labelled, attributed", + r and r["status"] == "accepted" and r["undoLabel"] == "Brokkr nibu/hands: createObject aaaaaaaa" + and r["requestedBy"] == "nibu/hands" and r["note"] == "queue test" and "QCube" in names(), r) + check("queue: intent removed from the queue after the drain", "blender/commands/aaaaaaaa-0001" not in pending(), list(pending())) + + +def q2(): + queue("aaaaaaaa-0001", action="createObject", objectType="MESH", name="QReuse", requestedBy="nibu/hands") + + +def q2_check(): + orig = receipt("aaaaaaaa-0001") + denial = receipt("aaaaaaaa-0001.denied") + R["receipts"]["q2_original"], R["receipts"]["q2_denial"] = orig, denial + check("queue: reused id leaves the original receipt untouched (write-once)", + orig["status"] == "accepted" and orig["undoLabel"] == S["q1_label"], orig) + check("queue: reused id reported under .denied, nothing created", + denial and denial["status"] == "denied" and "QReuse" not in names(), denial) + + +def q3(): + queue("aaaaaaaa-0003", action="createObject", objectType="MESH", name="QNoOwner") + + +def q3_check(): + r = receipt("aaaaaaaa-0003") + R["receipts"]["q3"] = r + check("queue: intent without requestedBy denied, scene unchanged", r["status"] == "denied" and "QNoOwner" not in names(), r) + + +def q4(): + queue("aaaaaaaa-0004", action="createObject", objectType="MESH", name="QOne", location=[0, 6, 0], requestedBy="nibu/hands") + queue("aaaaaaaa-0005", action="createObject", objectType="MESH", name="QTwo", location=[0, 8, 0], requestedBy="nibu/imagination") + + +def q4_undo_two(): + undo() + after_one = names() + undo() + after_two = names() + check("queue: two intents drained together are two undo steps, last first", + "QTwo" not in after_one and "QOne" in after_one and "QOne" not in after_two, [after_one, after_two]) + + +def q5_edit(): + cube = bpy.data.objects["Cube"] + bpy.context.view_layer.objects.active = cube + cube.select_set(True) + with win(): + bpy.ops.object.mode_set(mode="EDIT") + push("driver edit baseline") + queue("aaaaaaaa-0006", action="setWorld", color=[1, 0, 0], requestedBy="nibu/hands") + queue("aaaaaaaa-0007", action="exportGltf", filepath="edit.glb", requestedBy="nibu/hands") + queue("aaaaaaaa-0008", action="setObjectTransform", objectName="Cube", location=[0, 0, 9], requestedBy="nibu/hands") + + +def q5_check(): + rs = [receipt(k) for k in ("aaaaaaaa-0006", "aaaaaaaa-0007", "aaaaaaaa-0008")] + R["receipts"]["q5"] = rs + check("queue: in Edit Mode setWorld, exportGltf and an object write are all denied, her mode kept", + all(r["status"] == "denied" and r["undoLabel"] == "" for r in rs) and bpy.context.mode == "EDIT_MESH" + and not (SCRATCH / "out" / "edit.glb").exists(), [r["message"] for r in rs]) + + +def q5_exit(): + with win(): + bpy.ops.object.mode_set(mode="OBJECT") + check("queue: add-on drain reports no error", adapter.last_auto_drain_error == "", adapter.last_auto_drain_error) + + +steps = [ + once(q1), until(drained("aaaaaaaa-0001")), once(q1_check), + once(q2), until(lambda: receipt("aaaaaaaa-0001.denied")), once(q2_check), + once(q3), until(drained("aaaaaaaa-0003")), once(q3_check), + once(q4), until(drained("aaaaaaaa-0004", "aaaaaaaa-0005")), once(q4_undo_two), + once(q5_edit), until(drained("aaaaaaaa-0006", "aaaaaaaa-0007", "aaaaaaaa-0008")), once(q5_check), once(q5_exit), +] +i = 0 + + +def write(): + R["ok"] = bool(R["checks"]) and all(c["ok"] for c in R["checks"]) and not R.get("errors") + with open(OUT + ".result.json", "w") as f: + json.dump(R, f, indent=1, default=str) + + +def tick(): + global i + if i < len(steps): + try: + if steps[i](): + i += 1 + except Exception: + R.setdefault("errors", []).append({"step": i, "error": traceback.format_exc()}) + i = len(steps) + write() + return 0.5 + write() + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(tick, first_interval=3.0) diff --git a/surfaces/blender/tests/live/agent_turn_queue.result.json b/surfaces/blender/tests/live/agent_turn_queue.result.json new file mode 100644 index 0000000..a040d56 --- /dev/null +++ b/surfaces/blender/tests/live/agent_turn_queue.result.json @@ -0,0 +1,196 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "queue: createObject drained by the add-on timer, accepted, labelled, attributed", + "ok": true, + "detail": { + "action": "createObject", + "commandId": "aaaaaaaa-0001", + "message": "Blender object created.", + "note": "queue test", + "objectName": "QCube", + "observedAt": "2026-11-27T18:07:31.682454+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa" + } + }, + { + "name": "queue: intent removed from the queue after the drain", + "ok": true, + "detail": [] + }, + { + "name": "queue: reused id leaves the original receipt untouched (write-once)", + "ok": true, + "detail": { + "action": "createObject", + "commandId": "aaaaaaaa-0001", + "message": "Blender object created.", + "note": "queue test", + "objectName": "QCube", + "observedAt": "2026-11-27T18:07:31.682454+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa" + } + }, + { + "name": "queue: reused id reported under .denied, nothing created", + "ok": true, + "detail": { + "action": "createObject", + "commandId": "aaaaaaaa-0001", + "message": "commandId 'aaaaaaaa-0001' was already receipted; ids are single-use.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T18:07:33.680885+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "denied", + "undoLabel": "" + } + }, + { + "name": "queue: intent without requestedBy denied, scene unchanged", + "ok": true, + "detail": { + "action": "createObject", + "commandId": "aaaaaaaa-0003", + "message": "Intent has no requestedBy of the form '/'.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T18:07:35.693748+00:00", + "requestedBy": "", + "schema": "brokkr.blender.command_receipt.v0", + "status": "denied", + "undoLabel": "" + } + }, + { + "name": "queue: two intents drained together are two undo steps, last first", + "ok": true, + "detail": [ + [ + "Camera", + "Cube", + "Light", + "QCube", + "QOne" + ], + [ + "Camera", + "Cube", + "Light", + "QCube" + ] + ] + }, + { + "name": "queue: in Edit Mode setWorld, exportGltf and an object write are all denied, her mode kept", + "ok": true, + "detail": [ + "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed." + ] + }, + { + "name": "queue: add-on drain reports no error", + "ok": true, + "detail": "" + } + ], + "receipts": { + "q1": { + "action": "createObject", + "commandId": "aaaaaaaa-0001", + "message": "Blender object created.", + "note": "queue test", + "objectName": "QCube", + "observedAt": "2026-11-27T18:07:31.682454+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa" + }, + "q2_original": { + "action": "createObject", + "commandId": "aaaaaaaa-0001", + "message": "Blender object created.", + "note": "queue test", + "objectName": "QCube", + "observedAt": "2026-11-27T18:07:31.682454+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa" + }, + "q2_denial": { + "action": "createObject", + "commandId": "aaaaaaaa-0001", + "message": "commandId 'aaaaaaaa-0001' was already receipted; ids are single-use.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T18:07:33.680885+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "denied", + "undoLabel": "" + }, + "q3": { + "action": "createObject", + "commandId": "aaaaaaaa-0003", + "message": "Intent has no requestedBy of the form '/'.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T18:07:35.693748+00:00", + "requestedBy": "", + "schema": "brokkr.blender.command_receipt.v0", + "status": "denied", + "undoLabel": "" + }, + "q5": [ + { + "action": "setWorld", + "commandId": "aaaaaaaa-0006", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T18:07:39.773004+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "denied", + "undoLabel": "" + }, + { + "action": "exportGltf", + "commandId": "aaaaaaaa-0007", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T18:07:39.867526+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "denied", + "undoLabel": "" + }, + { + "action": "setObjectTransform", + "commandId": "aaaaaaaa-0008", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T18:07:39.950112+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "denied", + "undoLabel": "" + } + ] + }, + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/live/agent_turn_undo.py b/surfaces/blender/tests/live/agent_turn_undo.py index 75716ee..9a9dc1b 100644 --- a/surfaces/blender/tests/live/agent_turn_undo.py +++ b/surfaces/blender/tests/live/agent_turn_undo.py @@ -11,6 +11,7 @@ Exit status is not meaningful in a GUI session: read the "ok" fields of the resu import json import os import sys +import tempfile import traceback import types from pathlib import Path @@ -27,6 +28,8 @@ OUT = sys.argv[sys.argv.index("--") + 1] R = {"blender": bpy.app.version_string, "background": bpy.app.background, "checks": [], "steps": []} target = bt.BrokkrBlenderTarget(bpy) N = [0] +OUTDIR = tempfile.mkdtemp(prefix="brokkr-live2-") +target.configure_action_dirs("", OUTDIR) def check(name, ok, detail=None): @@ -136,6 +139,21 @@ def s_edit_agent(): and loc("Cube") == S["loc0"] and bpy.context.mode == "EDIT_MESH", R["editMode"]) +def s_edit_others(): + """Anything that writes scene state or changes her mode is refused in Edit Mode; renderStill does neither.""" + world0 = bpy.context.scene.world + rw = intent(action="setWorld", color=[1, 0, 0], strength=2.0) + rx = intent(action="exportGltf", filepath="edit.glb") + rr = intent(action="renderStill", outputPath="edit.png", engine="CYCLES", resolutionX=8, resolutionY=8) + R["editMode"].update(setWorld=rw["status"], exportGltf=rx["status"], renderStill=rr["status"], + mode_after_others=bpy.context.mode) + check("edit mode: setWorld and exportGltf denied, world untouched, no file written", + rw["status"] == "denied" and rx["status"] == "denied" and bpy.context.scene.world == world0 + and "edit.glb" not in os.listdir(OUTDIR), R["editMode"]) + check("edit mode: renderStill accepted, pushes nothing, her mode kept", + rr["status"] == "accepted" and rr["undoLabel"] == "" and bpy.context.mode == "EDIT_MESH", R["editMode"]) + + def s_edit_undo(): """One undo must revert her edit-mesh step: a step pushed by the refused intent would have taken it.""" undo() @@ -150,8 +168,22 @@ def s_exit(): bpy.ops.object.mode_set(mode="OBJECT") +def s_noop_setup(): + intent(action="createObject", objectType="MESH", name="AgentCube3", location=[0, -5, 0]) + rx = intent(action="exportGltf", filepath="object.glb") + rr = intent(action="renderStill", outputPath="object.png", engine="CYCLES", resolutionX=8, resolutionY=8) + check("exportGltf and renderStill accepted with no undoLabel", + rx["status"] == "accepted" and rr["status"] == "accepted" and rx["undoLabel"] == "" and rr["undoLabel"] == "", + [rx["message"], rr["message"]]) + + +def s_noop_undo(): + undo() + check("no-op actions pushed no step: one undo removes the preceding createObject", "AgentCube3" not in names(), names()) + + steps = [s_baseline, s_create, s_transform, s_undo_transform, s_undo_create, s_denied_setup, s_denied_undo, - s_edit_enter, s_edit_agent, s_edit_undo, s_exit] + s_edit_enter, s_edit_agent, s_edit_others, s_edit_undo, s_exit, s_noop_setup, s_noop_undo] i = 0 diff --git a/surfaces/blender/tests/live/agent_turn_undo.result.json b/surfaces/blender/tests/live/agent_turn_undo.result.json index 455335f..7e8e590 100644 --- a/surfaces/blender/tests/live/agent_turn_undo.result.json +++ b/surfaces/blender/tests/live/agent_turn_undo.result.json @@ -80,6 +80,76 @@ "receipt": "denied", "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", "undoLabel": "", + "setWorld": "denied", + "exportGltf": "denied", + "renderStill": "accepted", + "mode_after_others": "EDIT_MESH", + "mode_after_undo": "EDIT_MESH", + "loc_after_undo": [ + 0.0, + 0.0, + 0.0 + ], + "z_before": 6.0, + "z_after_undo": 1.0 + } + }, + { + "name": "edit mode: setWorld and exportGltf denied, world untouched, no file written", + "ok": true, + "detail": { + "mode_before": "EDIT_MESH", + "loc_before": [ + 0.0, + 0.0, + 0.0 + ], + "mode_after_intent": "EDIT_MESH", + "loc_after_intent": [ + 0.0, + 0.0, + 0.0 + ], + "receipt": "denied", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "undoLabel": "", + "setWorld": "denied", + "exportGltf": "denied", + "renderStill": "accepted", + "mode_after_others": "EDIT_MESH", + "mode_after_undo": "EDIT_MESH", + "loc_after_undo": [ + 0.0, + 0.0, + 0.0 + ], + "z_before": 6.0, + "z_after_undo": 1.0 + } + }, + { + "name": "edit mode: renderStill accepted, pushes nothing, her mode kept", + "ok": true, + "detail": { + "mode_before": "EDIT_MESH", + "loc_before": [ + 0.0, + 0.0, + 0.0 + ], + "mode_after_intent": "EDIT_MESH", + "loc_after_intent": [ + 0.0, + 0.0, + 0.0 + ], + "receipt": "denied", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "undoLabel": "", + "setWorld": "denied", + "exportGltf": "denied", + "renderStill": "accepted", + "mode_after_others": "EDIT_MESH", "mode_after_undo": "EDIT_MESH", "loc_after_undo": [ 0.0, @@ -109,6 +179,10 @@ "receipt": "denied", "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", "undoLabel": "", + "setWorld": "denied", + "exportGltf": "denied", + "renderStill": "accepted", + "mode_after_others": "EDIT_MESH", "mode_after_undo": "EDIT_MESH", "loc_after_undo": [ 0.0, @@ -118,6 +192,23 @@ "z_before": 6.0, "z_after_undo": 1.0 } + }, + { + "name": "exportGltf and renderStill accepted with no undoLabel", + "ok": true, + "detail": [ + "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-yk0g4dyg\\object.glb (3484 bytes).", + "Rendered still to object.png." + ] + }, + { + "name": "no-op actions pushed no step: one undo removes the preceding createObject", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light" + ] } ], "steps": [ @@ -150,6 +241,42 @@ "status": "denied", "undoLabel": "", "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed." + }, + { + "intent": "setWorld", + "status": "denied", + "undoLabel": "", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed." + }, + { + "intent": "exportGltf", + "status": "denied", + "undoLabel": "", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed." + }, + { + "intent": "renderStill", + "status": "accepted", + "undoLabel": "", + "message": "Rendered still to edit.png." + }, + { + "intent": "createObject", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: createObject 00000009", + "message": "Blender object created." + }, + { + "intent": "exportGltf", + "status": "accepted", + "undoLabel": "", + "message": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-yk0g4dyg\\object.glb (3484 bytes)." + }, + { + "intent": "renderStill", + "status": "accepted", + "undoLabel": "", + "message": "Rendered still to object.png." } ], "ok": true, @@ -169,6 +296,10 @@ "receipt": "denied", "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", "undoLabel": "", + "setWorld": "denied", + "exportGltf": "denied", + "renderStill": "accepted", + "mode_after_others": "EDIT_MESH", "mode_after_undo": "EDIT_MESH", "loc_after_undo": [ 0.0, diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index db950a6..4874644 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -98,6 +98,102 @@ class AgentTurnTests(unittest.TestCase): SOURCE.read_text(encoding="utf-8")) self.assertEqual(bad, []) + # fix batch s1 + def test_world_and_export_are_refused_in_edit_mode_render_is_not(self): + self.bpy.mesh.mode = "EDIT" + for action, fields in (("setWorld", {}), ("exportGltf", {"filepath": "o.glb"})): + receipt = self.run_action(action=action, **fields) + self.assertEqual(receipt["status"], "denied", action) + self.assertIn("Edit Mode", receipt["message"]) + self.assertEqual(self.bpy.exported, []) + self.assertEqual(self.bpy.undo.pushes, []) + self.assertEqual(self.run_action(action="renderStill", outputPath="r.png", engine="CYCLES")["status"], "accepted") + + def test_export_and_render_push_no_undo_step(self): + self.assertEqual(self.run_action(action="exportGltf", filepath="o.glb")["status"], "accepted") + receipt = self.run_action(action="renderStill", outputPath="r.png", engine="CYCLES") + self.assertEqual(receipt["status"], "accepted") + self.assertEqual(receipt["undoLabel"], "") + self.assertEqual(self.bpy.undo.pushes, []) + + def test_returned_failed_receipt_pushes_nothing(self): + receipt = self.run_action(action="setObjectTransform", objectName="NoSuchObject", location=[1, 2, 3]) + self.assertEqual(receipt["status"], "failed") + self.assertEqual(self.bpy.undo.pushes, []) + + def test_denied_id_is_recorded_as_receipted(self): + self.bpy.mesh.mode = "EDIT" + self.assertEqual(self.run_action(action="createObject", objectType="EMPTY", commandId="denied-1")["status"], "denied") + self.bpy.mesh.mode = "OBJECT" + again = self.run_action(action="createObject", objectType="EMPTY", commandId="denied-1") + self.assertEqual(again["status"], "denied") + self.assertIn("single-use", again["message"]) + self.assertEqual(self.bpy.created, []) + + def test_undo_push_runs_under_the_first_window(self): + self.run_action(action="createObject", objectType="EMPTY") + self.assertEqual(self.bpy.undo.overrides, [{"window": self.bpy.undo.window}]) + + def test_push_failure_is_a_failed_receipt_and_never_reruns(self): + def broken(message): + raise RuntimeError("no undo stack") + self.bpy.ops.ed.undo_push = broken + receipt = self.run_action(action="createObject", objectType="EMPTY", commandId="push-fail-1") + self.assertEqual(receipt["status"], "failed") + self.assertIn("no undo stack", receipt["message"]) + self.assertEqual(receipt["undoLabel"], "") + again = self.run_action(action="createObject", objectType="EMPTY", commandId="push-fail-1") + self.assertEqual(again["status"], "denied") + self.assertEqual(len(self.bpy.created), 1) + + +class FakeNode: + """The node database drain_commands reads: intents, receipts, and what it puts and deletes.""" + def __init__(self, intents, receipts=()): + self.docs = {bt.COMMAND_INTENT_SCHEMA: dict(intents), bt.COMMAND_RECEIPT_SCHEMA: dict(receipts)} + self.puts = [] + self.deleted = [] + self.database = self + + def snapshot(self): + return {k: dict(v) for k, v in self.docs.items()} + + def put(self, document, key, value): + self.puts.append((key, value)) + + def delete(self, document, key): + self.deleted.append(key) + + +class DrainTests(unittest.TestCase): + setUp = ts.ActionTests.setUp + run_action = ts.ActionTests.run_action + + def drain(self, node): + docs = {"command_intent": "i", "command_receipt": "r"} + with unittest.mock.patch.object(self.target, "_open_node", return_value=(node, docs)): + return self.target.drain_commands(self.context, "cache", "src") + + def intent(self, cid, **fields): + return {"commandId": cid, "requestedBy": "nibu/hands", "action": "createObject", "objectType": "EMPTY", **fields} + + def test_drain_seeds_receipted_from_persisted_receipts(self): + old = {"blender/receipts/old-1": {"commandId": "old-1", "status": "accepted"}} + node = FakeNode({"blender/commands/old-1": self.intent("old-1")}, old) + receipts = self.drain(node) + self.assertEqual(receipts[0]["status"], "denied") + self.assertEqual(self.bpy.created, []) + + def test_reused_id_never_overwrites_the_original_receipt(self): + node = FakeNode({"blender/commands/a": self.intent("dup-1"), "blender/commands/b": self.intent("dup-1")}) + self.drain(node) + keys = [k for k, _ in node.puts] + self.assertEqual(keys.count("blender/receipts/dup-1"), 1) + self.assertEqual(dict(node.puts)["blender/receipts/dup-1"]["status"], "accepted") + denial = dict(node.puts)["blender/receipts/dup-1.denied"] + self.assertEqual(denial["status"], "denied") + self.assertEqual(sorted(node.deleted), ["blender/commands/a", "blender/commands/b"]) + if __name__ == "__main__": unittest.main() diff --git a/surfaces/blender/tests/test_scene_actions.py b/surfaces/blender/tests/test_scene_actions.py index c60b657..6c73c67 100644 --- a/surfaces/blender/tests/test_scene_actions.py +++ b/surfaces/blender/tests/test_scene_actions.py @@ -74,7 +74,10 @@ class FakeUndo: """What run_intent needs of bpy: a window to override and ed.undo_push, recorded.""" def __init__(self, bpy): self.pushes = [] - bpy.context = NS(window_manager=NS(windows=[object()]), temp_override=lambda **kw: contextlib.nullcontext()) + self.overrides = [] + self.window = object() + bpy.context = NS(window_manager=NS(windows=[self.window]), + temp_override=lambda **kw: (self.overrides.append(kw), contextlib.nullcontext())[1]) ops = getattr(bpy, "ops", None) or NS() ops.ed = NS(undo_push=lambda message: self.pushes.append(message)) bpy.ops = ops From a975f99a907f7832fa15cdb81b319285a4ef1c93 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 18:02:26 +0100 Subject: [PATCH 09/63] Live collaboration target: invariants, probes, identity table Target document for the brokkr-live campaign: the agent works in the same live Blender scene the operator is looking at. Records the Blender 5.3 timer-undo and viewport-capture probes the invariants stand on, and the identity, lifecycle and authority table for every kind the layer adds. Co-Authored-By: Claude Opus 5.5 --- docs/live-collab-target.md | 203 ++++++++++++++++++ docs/research/live-collab/probe_look.py | 68 ++++++ docs/research/live-collab/probe_timer_undo.py | 146 +++++++++++++ 3 files changed, 417 insertions(+) create mode 100644 docs/live-collab-target.md create mode 100644 docs/research/live-collab/probe_look.py create mode 100644 docs/research/live-collab/probe_timer_undo.py diff --git a/docs/live-collab-target.md b/docs/live-collab-target.md new file mode 100644 index 0000000..acbdb07 --- /dev/null +++ b/docs/live-collab-target.md @@ -0,0 +1,203 @@ +# Brokkr live collaboration: target + +Campaign `brokkr-live` (Nibu's mind). Working branch `nibu/live-collab-target`, base +`origin/main` 5e279b2. This document holds the rationale, the design truths the +campaign produces, and the identity, lifecycle and authority table. The typed +`target` in the mind holds the labelled invariants and the not-in-scope list; the +text below is their source. + +## Why + +Operator, 2026-11-27: Brokkr "is meant to give an agent hands into the same Blender +scene I'm looking at, enabling live collaboration work". Brokkr already runs inside +her live Blender: a `depsgraph_update_post` handler publishes a host snapshot and a +persistent 1 s `bpy.app.timers` callback drains command intents +(`surfaces/blender/brokkr_bridge/__init__.py:610-647`, `:668-671`). What it lacks is +everything that makes two people in one scene a collaboration rather than a remote +control: + +- an agent edit is not an undo step (research `nibu-body:research:blender-live-collab.brokkr-undo`); +- nobody can tell who made an edit: the Blender side reads no `requestedBy` + (`.brokkr-attribution-gate`); +- the human cannot stop an agent except by unticking a preference, and a queued intent + still runs if she ticks it back; +- the agent sees names and counts, not the viewport and not the Edit Mode selection + (`.brokkr-perception`); +- nothing stops an agent intent planned against an old scene from overwriting what she + did since; +- the agent has no hands: `brokkr-ctl` has no source (`.brokkr-no-agent-surface`). + +Its strengths stay: typed, validated actions with no free-form Python, path +confinement, loopback bind and an optional session token (`.brokkr-security`). + +## Prior art the design stands on + +- **mcp-for-blender's `UserEditRecorder`** (`.mcp4b-human-edits`): buffers human + operator and undo/redo events with `undo_post`/`redo_post` handlers, attributes events + during an agent command to the agent, and hands the agent the human's activity before + its next action. We take the idea (the agent learns what the human did) and drop the + trajectory log: the snapshot carries per-object human-edit sequence numbers instead. +- **blender-copilot** (`.copilot-undo-cancel`): one undo step per agent turn, a Stop + button, visible turns and an undo receipt, no approval gate. Its Stop cannot interrupt + a blocking native call. We take all four and accept the same limit. +- **Multi-User** (`.humans-multiuser`) and the paid collab add-ons (`.humans-others`): + presence of the other party in the 3D view, rights and object locks. We take presence + as a panel, derived from intents and receipts; human-to-human replication is theirs, + not ours. +- **Blender Lab MCP and mcp-for-blender** (`.lab-official`, `.mcp4b-perception-safe`): + viewport screenshots as perception; arbitrary code with a weak or default-off + sandbox, and no undo. The perception we copy; the code path is fork Q1. +- **ceeyang/blender_mcp** (`.ceeyang-159`): 159 typed tools, every write undoable. The + existence proof that a typed vocabulary can be wide. +- The brush-tree campaign's `one-commit-primitive` (Libby's mind): a stale base is + refused, never merged. The conflict rule below is the same rule applied to a live scene. + +## What probing established (Blender 5.3.0, Starfire, GUI, `--factory-startup`) + +Probe scripts: `docs/research/live-collab/probe_timer_undo.py` and `probe_look.py`. +Each step runs in its own timer tick, as Brokkr's drain does. + +1. **A write from a timer with no undo push is not a step, and it survives undo.** The + cube moved to x=1 with no push; one `ed.undo` left it at x=1. The next push captured + it, so the agent's write became part of the next step, whoever made it (case A). The + vendor warning (`.undo-timer-warning`) is real for unpushed writes, and the failure is + worse than "not undoable": the edit is misattributed. +2. **An explicit `ed.undo_push` from a timer makes a correct step.** x=2 pushed, x=3 + pushed; undo gave 2, undo gave 1 (the earlier step), redo gave 2 (case B). +3. **An UNDO-flagged operator called from a timer pushes its own step.** A sphere added + by `primitive_uv_sphere_add` vanished on one undo with no explicit push (case C). An + action that calls two operators therefore makes two steps unless told otherwise. +4. **Operators called with `undo=False` push nothing; one explicit push then covers + them.** Cube and cone added with `("EXEC_DEFAULT", False)`, one push, one undo removed + both, a second undo changed nothing (case E). This is the mechanism for "one intent, + one step". +5. **Edit Mode:** a bmesh write plus push in Edit Mode is reverted by one undo, and that + undo also left Edit Mode (the agent had entered it in the same probe); the mesh kept + its original vertex (case D). Mode entry and the agent step are not cleanly separable + when the agent itself changed mode. Not yet probed: the human in Edit Mode and the + agent writing. +6. **Driving `ed.undo`/`ed.redo` programmatically from timers crashed Blender 2 of 2 + times** in the long sequence (A through E in one session), with + `EXCEPTION_ACCESS_VIOLATION` in UI draw code after a memfile undo + (`outliner_draw_restrictbuts`, then `psys_get_current` from the properties editor). The + short sequences (C alone, D alone, E alone) did not crash. Cause not isolated; the + probe's own `temp_override` with a captured region is a suspect. +7. **The agent can see what the human sees.** `bpy.ops.screen.screenshot_area` on the + 3D view from a timer: 7 of 7 `FINISHED`, median 72.5 ms over runs 2-7 at 1574x888, + about 609 KB PNG, and it captured the splash screen over the viewport, so it is the + human's view, overlays and popups included. Each capture stalls her UI for that long. +8. **Edit Mode selection reads live** through `bmesh.from_edit_mesh` without leaving Edit + Mode: selected vertices `[0, 3]`, 0.013 ms, mode still `EDIT_MESH`. + +Not yet probed, and owed before the cut that depends on it: whether depsgraph updates +caused by an agent intent arrive inside the timer callback or after it returns (this +decides how human edits are told from agent edits); and whether a human Ctrl+Z inside a +pending agent intent's base window can be detected reliably by `undo_post`. + +## Design truths + +**One agent turn primitive.** Every agent mutation in Blender goes through one function +in the add-on: admit (sink enabled, `requestedBy` present, id unused, base fresh), run +the action with every operator called `undo=False`, push exactly one undo step labelled +`Brokkr : `, write the receipt. A refusal or a +failure pushes nothing and leaves the scene as it was. Typed actions, the node actions, +and `run` if Q1 keeps it, all use it; there is no second writer. + +**Undo belongs to the human.** Blender's one linear stack is the shared history. The +agent's steps sit in it, labelled, between hers; she undoes them with Ctrl+Z like her +own. The agent never calls `ed.undo` or `ed.redo` (probe 6); an agent that wants to back +out sends a new compensating intent, which is one more step. Undoing an agent step that +sits under later human steps is not offered: Blender's stack is linear and per-user undo +is out of scope. + +**Stop is one control, and only the human holds it.** The Brokkr panel's Stop turns the +command sink off and gives every pending intent a `stopped` receipt without running it. +An action already running finishes (a blocking native call cannot be interrupted, as in +blender-copilot); it is one undo step, so Stop plus Ctrl+Z always returns her scene. No +intent can turn the sink on. Re-enabling is a fresh decision, and intents queued before +Stop never run. + +**The agent sees her view and her edits.** `look` is a read intent: it captures her 3D +view to a scratch PNG named by command id (ruling `brush-tree:ruling:look-files-are-scratch`) +and returns the path; it pushes no undo step. The snapshot gains the Edit Mode selection +and a Blender session id plus human-edit sequence numbers: one counter for the session, +the last sequence at which the human touched each object, and the last sequence at which +she undid or redid. The agent reads "what changed since I last looked" from those. + +**A human edit is never silently overwritten.** Every mutating intent names the base +sequence it was planned against. If the human touched any datablock the intent targets +since that base, or undid or redid since it, or the session id changed, the intent is +refused with a `conflict` receipt naming what changed, and nothing is applied. The +agent looks again and re-plans. Granularity is fork Q3. + +**Presence is derived.** The panel shows which agents have intents or receipts in the +last minutes, the running or last intent with its one-line `note`, and the recent +receipts with their undo labels. It reads the intent and receipt documents; it owns no +state of its own. + +**Hands are a CLI.** `brokkr-ctl blender` (Rust, ruling `brush-tree:ruling:fitting-home-ruled`) +writes intents and reads receipts and snapshots through the Blender mirror store +(`brush-tree:ruling:blender-transport-ruled`), prints plain text or paths, and its +`--help` is the schema (`brush-tree:ruling:cli-not-mcp`, `:help-is-the-schema`). It owns +no state, policy or ledger (brush-tree target invariant `brokkr-authority-holds`). + +## Authority map + +- **Owner.** The add-on's agent turn primitive owns whether and how an agent intent + changes the live scene. Blender owns scene truth and the undo stack. The human owns + the sink toggle, Stop, and undo. +- **Inputs.** Intent documents; the snapshot's human-edit sequences; the sink toggle. +- **Outputs.** One undo step per accepted mutating intent; one receipt per intent; + the refreshed snapshot; look PNG paths. +- **Derived state.** Presence (from intents and receipts). Human-edit sequences + (from depsgraph and undo handlers, observations only). Look PNGs (telemetry). +- **Forbidden writers.** `execute_command` called outside the primitive; operators + called with undo on inside an agent action; any raw RNA write by an agent without the + closing push; `ed.undo`/`ed.redo` from add-on code; the debug-mirror JSON import + (`blender_target.py` `_import_debug_command_files`) as a second door for intents; + `brokkr-ctl` opening the store to decide anything. +- **Shared paths.** brokkr-ctl intents, panel buttons that act on the scene, sync-organ + intents from `brokkr-daemon sync-once`, and replayed intents use the one primitive. +- **Deletion line.** The debug-mirror intent import goes before the primitive lands; + `drain_commands` stops calling `execute_command` directly. + +## Identity, lifecycle and authority + +| Persistent kind | What names it | What happens to it over time | Who decides | +|---|---|---|---| +| Blender command intent `brokkr.blender.command_intent.v0` (gains `requestedBy`, `baseSeq`, `note`) | `blender/commands/{commandId}`; ids single-use, minted by the writer (Unity F6 A, `brush-tree:ruling:blender-sink-mirrors-unity`) | Written once by a caller. Executed at most once or refused. Removed when its receipt is written, as today. Never rewritten. | Callers write. The agent turn primitive alone decides admission and execution. | +| Blender command receipt `brokkr.blender.command_receipt.v0` (gains `requestedBy`, `outcome` in accepted, denied, conflict, stopped, failed, `undoLabel`, `lookPath`, and for `run` the script text and SHA-256) | `blender/receipts/{commandId}`, one per intent | Written once, after the primitive decides. Pruned by count with Unity's cap and prune rule. The only proof an intent ran. | The primitive alone. Callers and the panel read. | +| Agent identity `requestedBy` | `/` stated by the caller (brokkr-ctl takes it from `EUREKA_INSTANCE` and a flag) | Carried on each intent into its receipt and undo label; not stored on its own. | The caller states it; the primitive refuses an intent without it. The session token proves admission, not identity. | +| Agent undo step | Blender undo stack entry labelled `Brokkr : ` | Pushed once per accepted mutating intent; lives as Blender's stack does (step limit, file load); never persisted by Brokkr. | Blender owns the stack. The primitive pushes. Only the human undoes or redoes. | +| Blender session id | uuid minted at add-on register and on each `load_post` | Replaced when Blender restarts or a file loads; every older base is then stale. | The add-on alone. | +| Human-edit sequences (snapshot fields: `humanEditSeq`, per-object `lastHumanEditSeq`, `lastUndoSeq`) | Integers within a session id | Monotonic within a session; reset with it. Observations, never scene truth. | The add-on's depsgraph and undo handlers alone. | +| Host snapshot `brokkr.blender.host_snapshot.v0` (gains Edit Mode selection, session id, the sequences above, sink state) | `blender/host/current`, overwritten | Refreshed on depsgraph update and after each intent. | The add-on alone. | +| Command sink toggle (the existing `auto_drain_commands` preference) | Add-on preference, echoed in the snapshot | Off by default. Stop turns it off; only the human turns it on. | The human only. No intent writes it. | +| Script toggle (only if Q1 = b) | A second add-on preference, echoed in the snapshot | Off by default, independent of the sink. | The human only. | +| Look PNG | `/look/{commandId}.png` | Pruned by count; never read back as truth. | The primitive writes; `brush-tree:ruling:look-files-are-scratch` governs. | + +## Not in scope + +Human-to-human replication or several Blender instances in one session (Multi-User's +domain). Agents on another host reaching the operator's Blender: the transport is not +widened beyond what the add-on serves today. Per-user or selective undo. An approval gate +before each agent action (unless Q2 rules otherwise). A 3D-view overlay of the agent's +presence; the panel carries presence in this revision. The Unity surface and +`brokkr-command`. The brush-tree vocabulary, Geometry.Csg and OpenSCAD text (brush-tree +owns them). Agent-initiated save and quit (`brush-tree:ruling:run-admitted-when-enabled` +keeps them off the allowed list). Asset libraries and generators. An MCP server. + +## Open forks (draft questions; Self admits) + +- **Q1. Free-form Python.** Today the Blender add-on has no script action. Libby's + Defaulted ruling `brush-tree:ruling:run-admitted-when-enabled` would add `run`, admitted + whenever agent commands are on. Options: (a) typed actions only; (b) `run` behind its + own off-by-default toggle, one undo step, script text in the receipt; (c) the Defaulted + ruling as written. Recommend (b). +- **Q2. Act then undo, or approve first.** Recommend act then undo, with Stop. +- **Q3. Conflict granularity.** (a) any human edit since the base refuses; (b) only edits to + the intent's targets, plus any undo or redo. Recommend (b), after the depsgraph + attribution probe. +- **Q4. Who builds `brokkr-ctl blender`.** Recommend this campaign builds the session + subcommands in Rust per Libby's rulings, and brush-tree adds its tree commands to the + same binary later. diff --git a/docs/research/live-collab/probe_look.py b/docs/research/live-collab/probe_look.py new file mode 100644 index 0000000..1e8851c --- /dev/null +++ b/docs/research/live-collab/probe_look.py @@ -0,0 +1,68 @@ +"""Probe: can a timer callback capture the 3D viewport the human sees, and read Edit Mode selection? + +blender --factory-startup --python probe_look.py -- +""" +import json +import os +import statistics +import sys +import time +import traceback + +import bmesh +import bpy + +args = sys.argv[sys.argv.index("--") + 1:] +OUT, PNG_DIR = args[0], args[1] +log = {"blender": bpy.app.version_string} + + +def ctx(): + win = bpy.context.window_manager.windows[0] + area = next(a for a in win.screen.areas if a.type == "VIEW_3D") + region = next(r for r in area.regions if r.type == "WINDOW") + return win, area, region + + +def run(): + win, area, region = ctx() + log["view3d_px"] = [region.width, region.height] + times = [] + for n in range(7): + path = os.path.join(PNG_DIR, f"look-{n}.png") + t = time.perf_counter() + with bpy.context.temp_override(window=win, area=area, region=region): + r = bpy.ops.screen.screenshot_area(filepath=path) + times.append((time.perf_counter() - t) * 1000) + log.setdefault("results", []).append(list(r)) + log["screenshot_ms"] = [round(x, 1) for x in times] + log["screenshot_ms_median"] = round(statistics.median(times[1:]), 1) + log["png_bytes"] = os.path.getsize(os.path.join(PNG_DIR, "look-6.png")) + # Edit Mode selection read, live, without leaving Edit Mode. + with bpy.context.temp_override(window=win, area=area, region=region): + bpy.ops.object.mode_set(mode="EDIT") + bpy.ops.mesh.select_all(action="DESELECT") + bm = bmesh.from_edit_mesh(bpy.data.objects["Cube"].data) + bm.verts.ensure_lookup_table() + bm.verts[0].select = True + bm.verts[3].select = True + bm.select_flush_mode() + t = time.perf_counter() + sel = [v.index for v in bmesh.from_edit_mesh(bpy.data.objects["Cube"].data).verts if v.select] + log["edit_selection_read_ms"] = round((time.perf_counter() - t) * 1000, 3) + log["edit_selected_verts"] = sel + log["mode_after_read"] = bpy.context.mode + + +def tick(): + try: + run() + except Exception: + log["error"] = traceback.format_exc() + with open(OUT, "w") as f: + json.dump(log, f, indent=1) + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(tick, first_interval=3.0) diff --git a/docs/research/live-collab/probe_timer_undo.py b/docs/research/live-collab/probe_timer_undo.py new file mode 100644 index 0000000..57886fb --- /dev/null +++ b/docs/research/live-collab/probe_timer_undo.py @@ -0,0 +1,146 @@ +"""Probe: do edits made from a bpy.app.timers callback land on Blender's undo stack? + +Run in GUI Blender: blender --factory-startup --python probe_timer_undo.py -- [cases, e.g. AB] +Each step is its own timer tick so the event loop runs between steps, as it does +for Brokkr's 1 s drain. Results are written to the JSON path, then Blender quits. +""" +import json +import sys +import traceback + +import bmesh +import bpy + +OUT = sys.argv[sys.argv.index("--") + 1] +log = {"blender": bpy.app.version_string, "background": bpy.app.background, "steps": []} + + +def win_ctx(): + win = bpy.context.window_manager.windows[0] + area = next(a for a in win.screen.areas if a.type == "VIEW_3D") + return bpy.context.temp_override(window=win, area=area, region=area.regions[-1]) + + +def cube(): + return bpy.data.objects.get("Cube") + + +def state(tag): + c = cube() + s = { + "tag": tag, + "cube_x": round(c.location.x, 3) if c else None, + "objects": sorted(o.name for o in bpy.data.objects), + "mode": bpy.context.mode, + "mesh_v0_z": round(c.data.vertices[0].co.z, 3) if c else None, + } + if c and c.mode == "EDIT": + bm = bmesh.from_edit_mesh(c.data) + bm.verts.ensure_lookup_table() + s["edit_v0_z"] = round(bm.verts[0].co.z if bm.verts else 0, 3) + log["steps"].append(s) + return s + + +def push(msg): + with win_ctx(): + r = bpy.ops.ed.undo_push(message=msg) + log["steps"].append({"tag": f"undo_push:{msg}", "result": list(r)}) + + +def undo(): + with win_ctx(): + r = bpy.ops.ed.undo() + log["steps"].append({"tag": "undo", "result": list(r)}) + + +def redo(): + with win_ctx(): + r = bpy.ops.ed.redo() + log["steps"].append({"tag": "redo", "result": list(r)}) + + +# Case A: raw RNA write from a timer, no push. Does Ctrl+Z see it as its own step? +# Case B: RNA write then an explicit undo_push from the timer. +# Case C: an UNDO-flagged operator called from a timer, no explicit push. +# Case D: Edit Mode bmesh write from a timer then undo_push. +# Case E: two operators called with undo=False, then one explicit undo_push. +ONLY = sys.argv[sys.argv.index("--") + 2] if len(sys.argv) > sys.argv.index("--") + 2 else "ABCDE" +steps = [ + lambda: (push("baseline"), state("A0 baseline")), + lambda: (setattr(cube().location, "x", 1.0), state("A1 raw write x=1, no push")), + lambda: (undo(), state("A2 after one undo")), + lambda: (push("rebase-B"), state("B0")), + lambda: (setattr(cube().location, "x", 2.0), push("agent: x=2"), state("B1 x=2 pushed")), + lambda: (setattr(cube().location, "x", 3.0), push("agent: x=3"), state("B2 x=3 pushed")), + lambda: (undo(), state("B3 after undo (expect x=2)")), + lambda: (undo(), state("B4 after second undo (expect x=0)")), + lambda: (redo(), state("B5 after redo (expect x=2)")), + lambda: (push("rebase-C"), state("C0")), + lambda: (_add_sphere(), state("C1 op add sphere, no push")), + lambda: (undo(), state("C2 after undo (sphere gone?)")), + lambda: (bpy.context.view_layer.objects.__setattr__("active", cube()), cube().select_set(True), push("rebase-D"), state("D0")), + lambda: (_edit_enter(), state("D1 edit mode")), + lambda: (_edit_write(), push("agent: edit v0"), state("D2 v0 moved, pushed")), + lambda: (undo(), state("D3 after undo (expect v0 back)")), + lambda: (undo(), state("D4 after second undo")), + lambda: (_edit_exit(), push("rebase-E"), state("E0")), + lambda: (_two_ops_one_step(), push("agent: two ops"), state("E1 two ops undo=False + one push")), + lambda: (undo(), state("E2 after one undo (expect both gone)")), + lambda: (undo(), state("E3 after second undo (expect no change)")), +] + + +def _add_sphere(): + with win_ctx(): + bpy.ops.mesh.primitive_uv_sphere_add(location=(5, 0, 0)) + + +def _edit_exit(): + if bpy.context.mode != "OBJECT": + with win_ctx(): + bpy.ops.object.mode_set(mode="OBJECT") + + +def _two_ops_one_step(): + with win_ctx(): + bpy.ops.mesh.primitive_cube_add("EXEC_DEFAULT", False, location=(0, 4, 0)) + bpy.ops.mesh.primitive_cone_add("EXEC_DEFAULT", False, location=(0, -4, 0)) + + +def _edit_enter(): + with win_ctx(): + bpy.ops.object.mode_set(mode="EDIT") + + +def _edit_write(): + c = cube() + bm = bmesh.from_edit_mesh(c.data) + bm.verts.ensure_lookup_table() + bm.verts[0].co.z += 5.0 + bmesh.update_edit_mesh(c.data) + + +i = 0 +_all = steps +steps = [f for f, c in zip(_all, "AAABBBBBBCCCDDDDDEEEE") if c in ONLY] + + +def tick(): + global i + if i < len(steps): + try: + steps[i]() + except Exception: + log["steps"].append({"tag": f"step {i} error", "error": traceback.format_exc()}) + i += 1 + with open(OUT, "w") as f: + json.dump(log, f, indent=1) + return 0.3 + with open(OUT, "w") as f: + json.dump(log, f, indent=1) + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(tick, first_interval=2.0) From 3213ee3d864e5f46afaf2ac79e15943a1801d41f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 18:07:37 +0100 Subject: [PATCH 10/63] Live collab: depsgraph timing probe Records when depsgraph updates from an agent edit in a timer arrive and which ids they name, for the human-edit detection fork (Q3). Co-Authored-By: Claude Opus 5.5 --- .../live-collab/probe_depsgraph_timing.py | 134 ++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 docs/research/live-collab/probe_depsgraph_timing.py diff --git a/docs/research/live-collab/probe_depsgraph_timing.py b/docs/research/live-collab/probe_depsgraph_timing.py new file mode 100644 index 0000000..d763e07 --- /dev/null +++ b/docs/research/live-collab/probe_depsgraph_timing.py @@ -0,0 +1,134 @@ +"""Probe: when do depsgraph updates caused by an agent edit in a timer arrive, and what do they name? + +blender --factory-startup --python probe_depsgraph_timing.py -- + +Each case runs in its own timer tick. AGENT is True only while the timer callback +runs the edit. depsgraph_update_post and undo_post log every call with AGENT's value, +the tick that was current, and the ids depsgraph.updates names. +""" +import json +import sys +import time +import traceback + +import bpy + +OUT = sys.argv[sys.argv.index("--") + 1] +log = {"blender": bpy.app.version_string, "events": []} +AGENT = False +TICK = "setup" +T0 = time.perf_counter() + + +def ev(kind, **kw): + log["events"].append({"kind": kind, "tick": TICK, "agent": AGENT, + "ms": round((time.perf_counter() - T0) * 1000, 1), **kw}) + + +@bpy.app.handlers.persistent +def on_depsgraph(scene, depsgraph): + ups = [] + for u in depsgraph.updates: + ups.append(f"{type(u.id).__name__}:{u.id.name}" + f"{'/T' if u.is_updated_transform else ''}{'/G' if u.is_updated_geometry else ''}") + ev("depsgraph", updates=ups) + + +@bpy.app.handlers.persistent +def on_undo(scene, *_): + ev("undo_post") + + +@bpy.app.handlers.persistent +def on_redo(scene, *_): + ev("redo_post") + + +def win_ctx(): + win = bpy.context.window_manager.windows[0] + area = next(a for a in win.screen.areas if a.type == "VIEW_3D") + region = next(r for r in area.regions if r.type == "WINDOW") + return bpy.context.temp_override(window=win, area=area, region=region) + + +def setup(): + # B follows A through a Copy Location constraint: an indirect dependent of A. + a = bpy.data.objects["Cube"] + with win_ctx(): + bpy.ops.mesh.primitive_cone_add("EXEC_DEFAULT", False, location=(0, 3, 0)) + b = bpy.context.active_object + b.name = "Follower" + c = b.constraints.new("COPY_LOCATION") + c.target = a + c.use_y = False + with win_ctx(): + bpy.ops.ed.undo_push(message="setup") + + +def agent(fn, flush): + global AGENT + AGENT = True + ev("turn_begin", flush=flush) + fn() + with win_ctx(): + bpy.ops.ed.undo_push(message=f"agent {TICK}") + if flush: + bpy.context.view_layer.update() + ev("turn_end") + AGENT = False + + +def move_a(x): + return lambda: setattr(bpy.data.objects["Cube"].location, "x", x) + + +def add_op(): + with win_ctx(): + bpy.ops.mesh.primitive_uv_sphere_add("EXEC_DEFAULT", False, location=(-4, 0, 0)) + + +def undo_once(): + with win_ctx(): + bpy.ops.ed.undo() + + +cases = [ + ("setup", setup), + ("idle1", lambda: None), + ("rna-noflush", lambda: agent(move_a(1.0), False)), + ("idle2", lambda: None), + ("rna-flush", lambda: agent(move_a(2.0), True)), + ("idle3", lambda: None), + ("op-noflush", lambda: agent(add_op, False)), + ("idle4", lambda: None), + ("op-flush", lambda: agent(add_op, True)), + ("idle5", lambda: None), + ("undo", undo_once), # stands in for a human Ctrl+Z (not an agent turn) + ("idle6", lambda: None), +] +i = 0 + + +def tick(): + global i, TICK + if i < len(cases): + TICK, fn = cases[i] + try: + fn() + except Exception: + ev("error", error=traceback.format_exc()) + TICK = f"after:{TICK}" + i += 1 + with open(OUT, "w") as f: + json.dump(log, f, indent=1) + return 0.5 + with open(OUT, "w") as f: + json.dump(log, f, indent=1) + bpy.ops.wm.quit_blender() + return None + + +bpy.app.handlers.depsgraph_update_post.append(on_depsgraph) +bpy.app.handlers.undo_post.append(on_undo) +bpy.app.handlers.redo_post.append(on_redo) +bpy.app.timers.register(tick, first_interval=2.0) From e271dcc9cf6e8ff5fa61a34694a28d6c9eef7d0e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 18:18:59 +0100 Subject: [PATCH 11/63] Live collab target r2: rulings in, phase two authoring surface Takes in the operator's 2026-11-27 rulings (no free-form Python, act then undo, last writer wins in the scene, brokkr-ctl blender built here) and adds phase two: scene collections as an authoring surface over a ship's .cc, opened at known record versions and pushed through AetherDb with a dry-run default and stale-version refusal. Records why neither variants' deltas nor CultNet carry the push today. Co-Authored-By: Claude Opus 5.5 --- docs/live-collab-target.md | 399 ++++++++++++++++++++++--------------- 1 file changed, 243 insertions(+), 156 deletions(-) diff --git a/docs/live-collab-target.md b/docs/live-collab-target.md index acbdb07..228ae83 100644 --- a/docs/live-collab-target.md +++ b/docs/live-collab-target.md @@ -4,200 +4,287 @@ Campaign `brokkr-live` (Nibu's mind). Working branch `nibu/live-collab-target`, `origin/main` 5e279b2. This document holds the rationale, the design truths the campaign produces, and the identity, lifecycle and authority table. The typed `target` in the mind holds the labelled invariants and the not-in-scope list; the -text below is their source. +text below is their source. Revision 2 adds phase two (the authoring surface) and +takes in the operator's rulings of 2026-11-27. + +Rulings in force: `brokkr-live:ruling:no-free-form-python`, `:act-then-undo`, +`:scene-last-writer-wins`, `:brokkr-ctl-blender-built-here`, +`:cc-is-hull-authority-scene-pushes-deltas`. ## Why Operator, 2026-11-27: Brokkr "is meant to give an agent hands into the same Blender -scene I'm looking at, enabling live collaboration work". Brokkr already runs inside -her live Blender: a `depsgraph_update_post` handler publishes a host snapshot and a -persistent 1 s `bpy.app.timers` callback drains command intents -(`surfaces/blender/brokkr_bridge/__init__.py:610-647`, `:668-671`). What it lacks is -everything that makes two people in one scene a collaboration rather than a remote -control: +scene I'm looking at, enabling live collaboration work". Her original vision for it: +"use Blender as an authoring environment, since it exposes typed access to all of the +assets we need over CultMesh. Certain collections within the Blender scene would +mirror their data into the exact documents Aetheria needs for its ships." -- an agent edit is not an undo step (research `nibu-body:research:blender-live-collab.brokkr-undo`); -- nobody can tell who made an edit: the Blender side reads no `requestedBy` - (`.brokkr-attribution-gate`); -- the human cannot stop an agent except by unticking a preference, and a queued intent - still runs if she ticks it back; -- the agent sees names and counts, not the viewport and not the Edit Mode selection - (`.brokkr-perception`); -- nothing stops an agent intent planned against an old scene from overwriting what she - did since; -- the agent has no hands: `brokkr-ctl` has no source (`.brokkr-no-agent-surface`). +So the campaign has two phases. **Phase one** makes the live session a collaboration: +the agent's edits are undoable and attributed, she can stop it, and it sees what she +sees. **Phase two** makes the scene an authoring surface over a ship's `.cc`: scene +collections map to the ship's records, the scene opens from the `.cc` at a known +revision, and pushes go back through AetherDb. -Its strengths stay: typed, validated actions with no free-form Python, path -confinement, loopback bind and an optional session token (`.brokkr-security`). +Brokkr already runs inside her live Blender: a `depsgraph_update_post` handler +publishes a host snapshot and a persistent 1 s `bpy.app.timers` callback drains +command intents (`surfaces/blender/brokkr_bridge/__init__.py:610-647`, `:668-671`). +What it lacks: an agent edit is not an undo step (`nibu-body:research:blender-live-collab.brokkr-undo`); +nobody can tell who made an edit (`.brokkr-attribution-gate`); the human can stop an +agent only by unticking a preference; the agent sees names and counts, not the viewport +or the Edit Mode selection (`.brokkr-perception`); and the agent has no hands, since +`brokkr-ctl` has no source (`.brokkr-no-agent-surface`). Its strengths stay: typed, +validated actions with no free-form Python, path confinement, loopback bind and an +optional session token (`.brokkr-security`). ## Prior art the design stands on -- **mcp-for-blender's `UserEditRecorder`** (`.mcp4b-human-edits`): buffers human - operator and undo/redo events with `undo_post`/`redo_post` handlers, attributes events - during an agent command to the agent, and hands the agent the human's activity before - its next action. We take the idea (the agent learns what the human did) and drop the - trajectory log: the snapshot carries per-object human-edit sequence numbers instead. +- **mcp-for-blender's `UserEditRecorder`** (`.mcp4b-human-edits`): the agent learns what + the human did between its actions. We keep the idea as snapshot fields, without a + trajectory log. - **blender-copilot** (`.copilot-undo-cancel`): one undo step per agent turn, a Stop - button, visible turns and an undo receipt, no approval gate. Its Stop cannot interrupt - a blocking native call. We take all four and accept the same limit. -- **Multi-User** (`.humans-multiuser`) and the paid collab add-ons (`.humans-others`): - presence of the other party in the 3D view, rights and object locks. We take presence - as a panel, derived from intents and receipts; human-to-human replication is theirs, - not ours. + button, visible turns and an undo receipt, no approval gate. Its Stop cannot + interrupt a blocking native call; ours cannot either. +- **Multi-User** (`.humans-multiuser`, `.humans-others`): presence of the other party. + We show presence in a panel; human-to-human replication is theirs. - **Blender Lab MCP and mcp-for-blender** (`.lab-official`, `.mcp4b-perception-safe`): - viewport screenshots as perception; arbitrary code with a weak or default-off - sandbox, and no undo. The perception we copy; the code path is fork Q1. -- **ceeyang/blender_mcp** (`.ceeyang-159`): 159 typed tools, every write undoable. The - existence proof that a typed vocabulary can be wide. -- The brush-tree campaign's `one-commit-primitive` (Libby's mind): a stale base is - refused, never merged. The conflict rule below is the same rule applied to a live scene. + viewport screenshots as perception. Their arbitrary-code path is refused here + (`no-free-form-python`). +- **ceeyang/blender_mcp** (`.ceeyang-159`): 159 typed tools, every write undoable; a + typed vocabulary can be wide. +- **Aetheria's ship package path** (Aetheria origin/master 6702b01bf, packager on + `nibu/hull-packager` 7101b5cec): `AetherDb ship-authoring` (create, stats, price, + product, regenerate with a dry-run default, validate, inspect) loads a `ship.cc` + through the game's own types; `tools/blender/package_hull.py` drives the + `aetheria_ships` add-on and AetherDb from a manifest; `tools/blender/aetheria_ships/ship_cc.py` + reads and writes `ship.cc` envelopes directly, with a layout revision hash for its + layout write. +- **CultCache compare-exchange and element ids** (CultLib origin/main baf4ecf7, + `src/GameCult.Caching/CultCache.cs:2228-2235` `Expect`/`ExpectUnchanged`; + `CultElementIds.cs`). `HardpointData.Id` is a `[CultElementId]` (Aetheria + `Assets/Scripts/ServerShared/ItemData.cs:648`). -## What probing established (Blender 5.3.0, Starfire, GUI, `--factory-startup`) +## What probing established -Probe scripts: `docs/research/live-collab/probe_timer_undo.py` and `probe_look.py`. -Each step runs in its own timer tick, as Brokkr's drain does. +Blender 5.3.0, Starfire, GUI, `--factory-startup`, each step in its own timer tick. +Scripts in `docs/research/live-collab/`. Research notes +`brokkr-live:research:live-collab-probes.*`. -1. **A write from a timer with no undo push is not a step, and it survives undo.** The - cube moved to x=1 with no push; one `ed.undo` left it at x=1. The next push captured - it, so the agent's write became part of the next step, whoever made it (case A). The - vendor warning (`.undo-timer-warning`) is real for unpushed writes, and the failure is - worse than "not undoable": the edit is misattributed. -2. **An explicit `ed.undo_push` from a timer makes a correct step.** x=2 pushed, x=3 - pushed; undo gave 2, undo gave 1 (the earlier step), redo gave 2 (case B). -3. **An UNDO-flagged operator called from a timer pushes its own step.** A sphere added - by `primitive_uv_sphere_add` vanished on one undo with no explicit push (case C). An - action that calls two operators therefore makes two steps unless told otherwise. -4. **Operators called with `undo=False` push nothing; one explicit push then covers - them.** Cube and cone added with `("EXEC_DEFAULT", False)`, one push, one undo removed - both, a second undo changed nothing (case E). This is the mechanism for "one intent, - one step". -5. **Edit Mode:** a bmesh write plus push in Edit Mode is reverted by one undo, and that - undo also left Edit Mode (the agent had entered it in the same probe); the mesh kept - its original vertex (case D). Mode entry and the agent step are not cleanly separable - when the agent itself changed mode. Not yet probed: the human in Edit Mode and the - agent writing. -6. **Driving `ed.undo`/`ed.redo` programmatically from timers crashed Blender 2 of 2 - times** in the long sequence (A through E in one session), with - `EXCEPTION_ACCESS_VIOLATION` in UI draw code after a memfile undo - (`outliner_draw_restrictbuts`, then `psys_get_current` from the properties editor). The - short sequences (C alone, D alone, E alone) did not crash. Cause not isolated; the - probe's own `temp_override` with a captured region is a suspect. -7. **The agent can see what the human sees.** `bpy.ops.screen.screenshot_area` on the - 3D view from a timer: 7 of 7 `FINISHED`, median 72.5 ms over runs 2-7 at 1574x888, - about 609 KB PNG, and it captured the splash screen over the viewport, so it is the - human's view, overlays and popups included. Each capture stalls her UI for that long. -8. **Edit Mode selection reads live** through `bmesh.from_edit_mesh` without leaving Edit - Mode: selected vertices `[0, 3]`, 0.013 ms, mode still `EDIT_MESH`. +1. **An unpushed write from a timer is not an undo step and survives undo**; the next + push absorbs it, so it is misattributed (`.timer-undo`, case A). +2. **An explicit `ed.undo_push` from a timer makes a correct step**, and undo and redo + walk it (case B). +3. **UNDO-flagged operators push their own step**; called `("EXEC_DEFAULT", False)` they + push none, and one explicit push covers several (cases C, E). This is how one intent + becomes one step. +4. **Edit Mode**: an agent bmesh write plus push is reverted by one undo, which also + left the Edit Mode the agent had entered (case D). +5. **Driving `ed.undo`/`ed.redo` from code crashed Blender 2 of 2 times** in the long + sequence, in UI draw after a memfile undo (`.programmatic-undo-crash`). +6. **The agent can see her view**: `screenshot_area` on her 3D view, median 72.5 ms at + 1574x888, about 609 KB, popups included; Edit Mode selection reads live without + leaving Edit Mode (`.look-capture`). +7. **Depsgraph updates from an agent edit arrive inside the timer turn** and name + indirect dependents; after an undo every object is listed and only the transform and + geometry flags show what changed (`.depsgraph-timing`). +8. **cultcache-rs writes the add-on's single-file `.ccmp` under the shared lock, and a + live cultmesh-py node pulls Rust writes**; no runtime has a directory store + (`.rust-store-writer`). -Not yet probed, and owed before the cut that depends on it: whether depsgraph updates -caused by an agent intent arrive inside the timer callback or after it returns (this -decides how human edits are told from agent edits); and whether a human Ctrl+Z inside a -pending agent intent's base window can be detected reliably by `undo_post`. +Not yet probed, owed before the cut that depends on it: the latency of one AetherDb +`ship-authoring` call on Starfire (phase two decides between a CLI call per push and a +resident service on that number); reading a record's stored version through AetherDb. -## Design truths +## Phase one: the live session **One agent turn primitive.** Every agent mutation in Blender goes through one function -in the add-on: admit (sink enabled, `requestedBy` present, id unused, base fresh), run -the action with every operator called `undo=False`, push exactly one undo step labelled -`Brokkr : `, write the receipt. A refusal or a -failure pushes nothing and leaves the scene as it was. Typed actions, the node actions, -and `run` if Q1 keeps it, all use it; there is no second writer. +in the add-on: admit (sink enabled, `requestedBy` present, id unused, action typed and +valid), run the action with every operator called `undo=False`, push exactly one undo +step labelled `Brokkr : `, write the receipt. A +refusal or a failure pushes nothing and leaves the scene unchanged. There is no second +writer and no script action (`no-free-form-python`): what the typed actions do not +cover waits for a new typed action. -**Undo belongs to the human.** Blender's one linear stack is the shared history. The -agent's steps sit in it, labelled, between hers; she undoes them with Ctrl+Z like her -own. The agent never calls `ed.undo` or `ed.redo` (probe 6); an agent that wants to back -out sends a new compensating intent, which is one more step. Undoing an agent step that -sits under later human steps is not offered: Blender's stack is linear and per-user undo -is out of scope. +**The agent acts; the human undoes** (`act-then-undo`). Admitted intents apply without +asking. Blender's one linear undo stack is the shared history; agent steps sit in it, +labelled, between hers, and she takes them back with Ctrl+Z. The agent never calls +`ed.undo` or `ed.redo` (probe 5); it backs out by sending a compensating intent. -**Stop is one control, and only the human holds it.** The Brokkr panel's Stop turns the -command sink off and gives every pending intent a `stopped` receipt without running it. -An action already running finishes (a blocking native call cannot be interrupted, as in -blender-copilot); it is one undo step, so Stop plus Ctrl+Z always returns her scene. No -intent can turn the sink on. Re-enabling is a fresh decision, and intents queued before -Stop never run. +**Last writer wins in the scene** (`scene-last-writer-wins`). An agent intent applies +even if she changed the scene since the agent looked. Her edit is never lost: it stays +in the undo history below the agent's step, and one Ctrl+Z takes the agent's step back. +This is scene-level only; the `.cc` keeps its revision refusal (phase two). + +**Stop is one control, and only the human holds it.** Stop turns the command sink off +and gives every pending intent a `stopped` receipt without running it. An action +already running finishes as one undo step, so Stop plus Ctrl+Z always returns her +scene. No intent can turn the sink on; intents queued before Stop never run. **The agent sees her view and her edits.** `look` is a read intent: it captures her 3D -view to a scratch PNG named by command id (ruling `brush-tree:ruling:look-files-are-scratch`) -and returns the path; it pushes no undo step. The snapshot gains the Edit Mode selection -and a Blender session id plus human-edit sequence numbers: one counter for the session, -the last sequence at which the human touched each object, and the last sequence at which -she undid or redid. The agent reads "what changed since I last looked" from those. +view to a scratch PNG named by command id (`brush-tree:ruling:look-files-are-scratch`) +and returns the path. The snapshot gains the Edit Mode selection, a Blender session id, +and human-edit sequence numbers (a session counter and, per object, the last sequence +at which she changed it, from depsgraph updates outside agent turns and flagged +transform, geometry or shading). These tell the agent what she did since it last +looked; they gate nothing. -**A human edit is never silently overwritten.** Every mutating intent names the base -sequence it was planned against. If the human touched any datablock the intent targets -since that base, or undid or redid since it, or the session id changed, the intent is -refused with a `conflict` receipt naming what changed, and nothing is applied. The -agent looks again and re-plans. Granularity is fork Q3. +**Presence is derived.** The panel shows active agents, the running or last intent with +its one-line `note`, and recent receipts with their undo labels, read from the intent +and receipt documents. -**Presence is derived.** The panel shows which agents have intents or receipts in the -last minutes, the running or last intent with its one-line `note`, and the recent -receipts with their undo labels. It reads the intent and receipt documents; it owns no -state of its own. +**Hands are a CLI** (`brokkr-ctl-blender-built-here`). `brokkr-ctl blender` is a Rust +binary in this repo (`brush-tree:ruling:fitting-home-ruled`) that writes intents and +reads receipts and snapshots in the add-on's single-file store (probe 8), prints plain +text or paths, and whose `--help` is the schema (`brush-tree:ruling:cli-not-mcp`, +`:help-is-the-schema`). It owns no state, policy or ledger. Libby's brush-tree adds its +tree commands to the same binary later. -**Hands are a CLI.** `brokkr-ctl blender` (Rust, ruling `brush-tree:ruling:fitting-home-ruled`) -writes intents and reads receipts and snapshots through the Blender mirror store -(`brush-tree:ruling:blender-transport-ruled`), prints plain text or paths, and its -`--help` is the schema (`brush-tree:ruling:cli-not-mcp`, `:help-is-the-schema`). It owns -no state, policy or ledger (brush-tree target invariant `brokkr-authority-holds`). +## Phase two: the authoring surface + +**The `.cc` is the authority; the scene is a surface over it** +(`cc-is-hull-authority-scene-pushes-deltas`). A ship's records live in its `ship.cc`: +`HullData`, `ShipAuthoring` (model asset, anchors, schematic lines) and its product +records (`ShipAuthoringStore.Load` returns exactly these three). A Blender scene may be +bound to one `ship.cc` as its authoring surface. The scene never becomes truth: it is an +edit buffer that opens from the store and pushes back to it. + +**Collections carry roles.** Scene collections are tagged with the role they author: +hull shape (the hull source and its raster), hardpoint rows (one object per row, +carrying `aetheria.id`, the `HardpointData` element id, and its kind, cell, footprint, +rotation, armor and arc), schematic lines, and anchors. Stats, price and product live on +the binding. These are the fields the packager manifest already names +(`tools/blender/package_hull.md`), so the manifest and a push describe a ship in one +vocabulary. + +**Open reads through the game's code.** Opening runs `AetherDb ship-authoring` to read +the three records and their stored versions, builds the tagged collections, and records +on the binding the version of each record it read. Nothing reads a `.cc` by scraping +envelopes (operator 2026-11-17). + +**A push is one AetherDb call, dry-run then apply.** The surface writes the authoring +state of its tagged collections (the manifest vocabulary, plus the record versions it +opened at) to a scratch request file and calls `AetherDb ship-authoring push +`. Without `apply` AetherDb loads the store, derives the records the request +describes, validates them, and prints the per-record, per-field changes; nothing is +written. With `apply` it does the same and writes under compare-exchange on each +record's stored version (`Expect`). One CLI call per push is the starting shape; a +resident service is built only if the measured latency of that call demands it. + +**A stale revision is refused, never merged.** If any record changed in the store since +the scene opened it (another push, a CLI `stats` call, a packager `--replace`), the push +is refused with the records named; the surface reopens and the author re-applies. On a +successful apply the binding takes the new versions. + +**One owner turns a hull into records.** AetherDb's ship-authoring code (C#, the game's +own types) is the only code that derives `HullData`, `ShipAuthoring` and product records +from authoring input, and the only writer of `.cc` stores. The packager and the +authoring surface both call it. The direct envelope writes in +`aetheria_ships/ship_cc.py` (`replace_lines`, `replace_visual`, `replace_layout`, and +the first Save Layout that creates `ship.cc`) and its `layout_revision` hash are +demoted: `ship_cc.py` keeps no write path and no revision of its own, and +`package_hull.py`'s Save Layout steps become push calls. Whether the request is +the delta of the ruling, or a whole-record replace, is fork Q5 below. + +**The agent's hands reach the surface through typed actions.** Open, push dry-run and +push apply are typed Brokkr actions like any other, admitted by the same primitive; a +push changes no scene state and so pushes no undo step. Whether an agent may apply, +not only dry-run, is fork Q7. + +### Variants and CultNet deltas: not the push primitive today + +The coordinator asked whether Libby's `variants` delta records, or CultNet's deltas, +are the primitive for the push. + +- **Variants** (`variants` target, Libby's mind): a variant is a persisted record stored + as a base reference plus sparse overrides (`CultVariantDelta`, `CultVariantOverride` + with `Set`/`Insert`/`Remove` at slot plus element-id paths, + `src/GameCult.Caching/CultVariants.cs:56-112`), resolved by the cache at load, and a + plain upsert at a variant's key is refused (`variants:ruling:q1-refuse-plain-upsert`). + It describes a second document defined against a base, not a change to the base. Its + nested paths and `Insert`/`Remove` are unbuilt (`variants:follow_up:remaining-variant-cuts`, + C2b), C# alone resolves it, and Aetheria catalog content is out of its scope. +- **CultNet** (`contracts/cultnet/`): the wire has whole-document `document-put` and + `document-put-raw`, `document-delete`, and `database-change-raw` (added, updated, + removed, with the whole document and a commit id). There is no delta message. The + "delta" in `cultnet-rs/src/replication.rs:97,789-829` and `cultmesh-py/node.py:1649-1660` + is a client-side reconciliation diff (predicted minus canonical, per top-level slot, + numeric subtraction) handed to the caller to smooth a prediction; it is never sent. +- **One mechanism?** Not today. They are two unrelated things that share a word. The + operator's recollection matches the plan, not the code: variants' fork ruling 4 + (`cultnet-deltas`) says variants travel on CultNet as deltas, and + `variants:ruling:hop-subscriptions-refuse-variants` holds CultNet off variants until + that cut (C5) lands. When it does, the override vocabulary will be both the stored + variant and the wire delta. +- **Consequence for the push.** The push invents no delta format. Its addressing is the + variants override vocabulary (slot plus element id; `HardpointData.Id` is already a + `[CultElementId]`) when CultLib can apply overrides to a record in place; until then + it is a whole-record replace of the records that changed, guarded by `Expect`. Fork Q5. ## Authority map -- **Owner.** The add-on's agent turn primitive owns whether and how an agent intent - changes the live scene. Blender owns scene truth and the undo stack. The human owns - the sink toggle, Stop, and undo. -- **Inputs.** Intent documents; the snapshot's human-edit sequences; the sink toggle. -- **Outputs.** One undo step per accepted mutating intent; one receipt per intent; - the refreshed snapshot; look PNG paths. -- **Derived state.** Presence (from intents and receipts). Human-edit sequences - (from depsgraph and undo handlers, observations only). Look PNGs (telemetry). -- **Forbidden writers.** `execute_command` called outside the primitive; operators - called with undo on inside an agent action; any raw RNA write by an agent without the - closing push; `ed.undo`/`ed.redo` from add-on code; the debug-mirror JSON import - (`blender_target.py` `_import_debug_command_files`) as a second door for intents; - `brokkr-ctl` opening the store to decide anything. +- **Owner.** Phase one: the add-on's agent turn primitive owns whether and how an agent + intent changes the live scene; Blender owns scene truth and the undo stack; the human + owns the sink toggle, Stop and undo. Phase two: the `ship.cc` owns the ship; + AetherDb's ship-authoring code alone derives and writes its records. +- **Inputs.** Intent documents and the sink toggle (phase one). The tagged collections, + the binding's opened versions and the request file (phase two). +- **Outputs.** One undo step per accepted mutating intent; one receipt per intent; the + refreshed snapshot; look PNG paths; AetherDb's dry-run diff or its write. +- **Derived state.** Presence; human-edit sequences; look PNGs; the scene's mapped + collections (an edit buffer over the `.cc`); the request file. +- **Forbidden writers.** `execute_command` called around the primitive; operators run + with undo on inside an agent action; unpushed agent writes; `ed.undo`/`ed.redo` from + add-on code; any agent-sent Python; the debug-mirror JSON import as a door for intents + (`blender_target.py` `_import_debug_command_files`); `brokkr-ctl` deciding anything; + `ship_cc.py`'s envelope writes and any other direct `.cc` writer; `layout_revision` + as a revision. - **Shared paths.** brokkr-ctl intents, panel buttons that act on the scene, sync-organ - intents from `brokkr-daemon sync-once`, and replayed intents use the one primitive. + intents and replayed intents use the one primitive. The packager, the authoring + surface's buttons and an agent's push intent use the one AetherDb push. - **Deletion line.** The debug-mirror intent import goes before the primitive lands; - `drain_commands` stops calling `execute_command` directly. + `drain_commands` stops calling `execute_command` directly. `ship_cc.py`'s write + functions and `layout_revision` go when the push lands. ## Identity, lifecycle and authority | Persistent kind | What names it | What happens to it over time | Who decides | |---|---|---|---| -| Blender command intent `brokkr.blender.command_intent.v0` (gains `requestedBy`, `baseSeq`, `note`) | `blender/commands/{commandId}`; ids single-use, minted by the writer (Unity F6 A, `brush-tree:ruling:blender-sink-mirrors-unity`) | Written once by a caller. Executed at most once or refused. Removed when its receipt is written, as today. Never rewritten. | Callers write. The agent turn primitive alone decides admission and execution. | -| Blender command receipt `brokkr.blender.command_receipt.v0` (gains `requestedBy`, `outcome` in accepted, denied, conflict, stopped, failed, `undoLabel`, `lookPath`, and for `run` the script text and SHA-256) | `blender/receipts/{commandId}`, one per intent | Written once, after the primitive decides. Pruned by count with Unity's cap and prune rule. The only proof an intent ran. | The primitive alone. Callers and the panel read. | -| Agent identity `requestedBy` | `/` stated by the caller (brokkr-ctl takes it from `EUREKA_INSTANCE` and a flag) | Carried on each intent into its receipt and undo label; not stored on its own. | The caller states it; the primitive refuses an intent without it. The session token proves admission, not identity. | -| Agent undo step | Blender undo stack entry labelled `Brokkr : ` | Pushed once per accepted mutating intent; lives as Blender's stack does (step limit, file load); never persisted by Brokkr. | Blender owns the stack. The primitive pushes. Only the human undoes or redoes. | -| Blender session id | uuid minted at add-on register and on each `load_post` | Replaced when Blender restarts or a file loads; every older base is then stale. | The add-on alone. | -| Human-edit sequences (snapshot fields: `humanEditSeq`, per-object `lastHumanEditSeq`, `lastUndoSeq`) | Integers within a session id | Monotonic within a session; reset with it. Observations, never scene truth. | The add-on's depsgraph and undo handlers alone. | -| Host snapshot `brokkr.blender.host_snapshot.v0` (gains Edit Mode selection, session id, the sequences above, sink state) | `blender/host/current`, overwritten | Refreshed on depsgraph update and after each intent. | The add-on alone. | -| Command sink toggle (the existing `auto_drain_commands` preference) | Add-on preference, echoed in the snapshot | Off by default. Stop turns it off; only the human turns it on. | The human only. No intent writes it. | -| Script toggle (only if Q1 = b) | A second add-on preference, echoed in the snapshot | Off by default, independent of the sink. | The human only. | -| Look PNG | `/look/{commandId}.png` | Pruned by count; never read back as truth. | The primitive writes; `brush-tree:ruling:look-files-are-scratch` governs. | +| Blender command intent `brokkr.blender.command_intent.v0` (gains `requestedBy`, `note`) | `blender/commands/{commandId}`; ids single-use, minted by the writer (`brush-tree:ruling:blender-sink-mirrors-unity`) | Written once by a caller. Executed at most once or refused. Removed when its receipt is written. Never rewritten. | Callers write. The agent turn primitive alone decides admission and execution. | +| Blender command receipt `brokkr.blender.command_receipt.v0` (gains `requestedBy`, `outcome` in accepted, denied, stopped, failed, `undoLabel`, `lookPath`) | `blender/receipts/{commandId}`, one per intent | Written once, after the primitive decides. Pruned by count with Unity's cap and prune rule. | The primitive alone. Callers and the panel read. | +| Agent identity `requestedBy` | `/` stated by the caller | Carried on each intent into its receipt and undo label; not stored on its own. | The caller states it; the primitive refuses an intent without it. The session token proves admission, not identity. | +| Agent undo step | Blender undo entry `Brokkr : ` | One per accepted mutating intent; lives as Blender's stack does; never persisted by Brokkr. | Blender owns the stack; the primitive pushes; only the human undoes or redoes. | +| Blender session id | uuid minted at add-on register and on each `load_post` | Replaced when Blender restarts or a file loads. | The add-on alone. | +| Human-edit sequences (snapshot: `humanEditSeq`, per-object `lastHumanEditSeq`) | Integers within a session id | Monotonic within a session; reset with it. Information for the agent; they gate nothing. | The add-on's depsgraph and undo handlers alone. | +| Host snapshot `brokkr.blender.host_snapshot.v0` (gains Edit Mode selection, session id, sequences, sink state, authoring binding summary) | `blender/host/current`, overwritten | Refreshed on depsgraph update and after each intent. | The add-on alone. | +| Command sink toggle (`auto_drain_commands`) | Add-on preference, echoed in the snapshot | Off by default. Stop turns it off; only the human turns it on. | The human only. | +| Look PNG | `/look/{commandId}.png` | Pruned by count; never read back as truth. | The primitive writes; `look-files-are-scratch` governs. | +| Ship package store `ship.cc` (`HullData`, `ShipAuthoring`, product records) | Its path, `GameData/Mods//ship.cc`; records by their keys | Created by `ship-authoring create`; changed only by AetherDb commands, each write minting new stored versions (`variants:ruling:storedat-on-change`); replaced whole only by packager `--replace`. | AetherDb's ship-authoring code is the only writer. | +| Record version | The version CultCache's compare-exchange tests for each record key | Changes on every write that changes the record's bytes. | CultCache mints it; AetherDb reports it on open and tests it on apply. | +| Authoring binding | A custom property on the Blender scene: the `ship.cc` path relative to the `.blend`, the ship id, and the record versions opened at | Set on Open; versions replaced after each successful apply; cleared on Detach or reopen. Lives in the `.blend`. | Open, apply and Detach (human buttons or agent actions through the primitive) alone write it. | +| Collection role | A custom property on a collection: hull, hardpoints, lines or anchors | Set when the surface builds or the author tags a collection; removed on Detach. | The author; the surface's Open builds the defaults. | +| Hardpoint row identity | `aetheria.id` on the row's object, equal to `HardpointData.Id` (`[CultElementId]`) | Minted when the row is created; survives renames and moves; removing the object removes the row on the next push. | AetherDb mints for a new row; the surface carries it. | +| Push request | `/authoring/{commandId}.json`, manifest vocabulary plus opened versions | Written per push; pruned by count; never read back as state. | The surface writes; AetherDb alone interprets it. | ## Not in scope -Human-to-human replication or several Blender instances in one session (Multi-User's -domain). Agents on another host reaching the operator's Blender: the transport is not -widened beyond what the add-on serves today. Per-user or selective undo. An approval gate -before each agent action (unless Q2 rules otherwise). A 3D-view overlay of the agent's -presence; the panel carries presence in this revision. The Unity surface and -`brokkr-command`. The brush-tree vocabulary, Geometry.Csg and OpenSCAD text (brush-tree -owns them). Agent-initiated save and quit (`brush-tree:ruling:run-admitted-when-enabled` -keeps them off the allowed list). Asset libraries and generators. An MCP server. +Human-to-human replication or several Blender instances in one session. Agents on +another host reaching the operator's Blender. Per-user or selective undo. An approval +gate (`act-then-undo`). Stale-action refusal inside the live scene +(`scene-last-writer-wins`). Any agent-sent Python (`no-free-form-python`). A 3D-view +presence overlay. The Unity surface and `brokkr-command`. The brush-tree vocabulary, +Geometry.Csg and OpenSCAD text (brush-tree owns them). Agent-initiated save and quit. +Asset libraries and generators. An MCP server. Records outside a ship package +(catalog loadouts, factions) unless Q6 rules them in. A new delta wire format. ## Open forks (draft questions; Self admits) -- **Q1. Free-form Python.** Today the Blender add-on has no script action. Libby's - Defaulted ruling `brush-tree:ruling:run-admitted-when-enabled` would add `run`, admitted - whenever agent commands are on. Options: (a) typed actions only; (b) `run` behind its - own off-by-default toggle, one undo step, script text in the receipt; (c) the Defaulted - ruling as written. Recommend (b). -- **Q2. Act then undo, or approve first.** Recommend act then undo, with Stop. -- **Q3. Conflict granularity.** (a) any human edit since the base refuses; (b) only edits to - the intent's targets, plus any undo or redo. Recommend (b), after the depsgraph - attribution probe. -- **Q4. Who builds `brokkr-ctl blender`.** Recommend this campaign builds the session - subcommands in Rust per Libby's rulings, and brush-tree adds its tree commands to the - same binary later. +- **Q5. What a push carries.** (a) whole records that changed, under `Expect`, now; (b) + variants override paths applied in place, after CultLib builds in-place apply and + C2b; (c) (a) now with the request shaped so (b) replaces it without changing the + surface. Recommend (c). +- **Q6. Does a ship's loadout belong in its package?** A package holds hull, authoring + and products today; loadouts are catalog records. Recommend not in r2. +- **Q7. May an agent apply a push, or only dry-run?** A `.cc` write has no Ctrl+Z. + Recommend dry-run for agents, apply by her button. +- **Q8. Where the authoring surface lives.** (a) the `aetheria_ships` add-on in Aetheria, + with Brokkr giving the agent typed actions that call it; (b) Brokkr's add-on gains + Aetheria vocabulary. Recommend (a). From 561562626f4f69867fbefd3d9a2ed74b8f26ae4c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 18:20:10 +0100 Subject: [PATCH 12/63] Live collab target r2: the push request is a stdin dump, as the material path Co-Authored-By: Claude Opus 5.5 --- docs/live-collab-target.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/live-collab-target.md b/docs/live-collab-target.md index 228ae83..13592ad 100644 --- a/docs/live-collab-target.md +++ b/docs/live-collab-target.md @@ -160,10 +160,11 @@ the three records and their stored versions, builds the tagged collections, and on the binding the version of each record it read. Nothing reads a `.cc` by scraping envelopes (operator 2026-11-17). -**A push is one AetherDb call, dry-run then apply.** The surface writes the authoring +**A push is one AetherDb call, dry-run then apply.** The surface pipes the authoring state of its tagged collections (the manifest vocabulary, plus the record versions it -opened at) to a scratch request file and calls `AetherDb ship-authoring push -`. Without `apply` AetherDb loads the store, derives the records the request +opened at) as a structural JSON dump on stdin to `AetherDb ship-authoring push `, +as the material path does (`aetheria-release:ruling:blender-dump-stdin`): never written +to disk, parsed and judged only in C#, so the schema exists once. Without `apply` AetherDb loads the store, derives the records the request describes, validates them, and prints the per-record, per-field changes; nothing is written. With `apply` it does the same and writes under compare-exchange on each record's stored version (`Expect`). One CLI call per push is the starting shape; a @@ -226,11 +227,11 @@ are the primitive for the push. owns the sink toggle, Stop and undo. Phase two: the `ship.cc` owns the ship; AetherDb's ship-authoring code alone derives and writes its records. - **Inputs.** Intent documents and the sink toggle (phase one). The tagged collections, - the binding's opened versions and the request file (phase two). + the binding's opened versions and the stdin dump (phase two). - **Outputs.** One undo step per accepted mutating intent; one receipt per intent; the refreshed snapshot; look PNG paths; AetherDb's dry-run diff or its write. - **Derived state.** Presence; human-edit sequences; look PNGs; the scene's mapped - collections (an edit buffer over the `.cc`); the request file. + collections (an edit buffer over the `.cc`); the stdin dump (a pipe, not state). - **Forbidden writers.** `execute_command` called around the primitive; operators run with undo on inside an agent action; unpushed agent writes; `ed.undo`/`ed.redo` from add-on code; any agent-sent Python; the debug-mirror JSON import as a door for intents @@ -262,7 +263,6 @@ are the primitive for the push. | Authoring binding | A custom property on the Blender scene: the `ship.cc` path relative to the `.blend`, the ship id, and the record versions opened at | Set on Open; versions replaced after each successful apply; cleared on Detach or reopen. Lives in the `.blend`. | Open, apply and Detach (human buttons or agent actions through the primitive) alone write it. | | Collection role | A custom property on a collection: hull, hardpoints, lines or anchors | Set when the surface builds or the author tags a collection; removed on Detach. | The author; the surface's Open builds the defaults. | | Hardpoint row identity | `aetheria.id` on the row's object, equal to `HardpointData.Id` (`[CultElementId]`) | Minted when the row is created; survives renames and moves; removing the object removes the row on the next push. | AetherDb mints for a new row; the surface carries it. | -| Push request | `/authoring/{commandId}.json`, manifest vocabulary plus opened versions | Written per push; pruned by count; never read back as state. | The surface writes; AetherDb alone interprets it. | ## Not in scope From a6184b61582f5d1d94bdafe6b13fda15102d2d91 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 19:34:27 +0100 Subject: [PATCH 13/63] Blender agent turn: Soul s2 fixes and a stock-Blender install commandId is validated (short key-safe string) before the reused check and any receipt key; a bad id is denied under a fresh key naming the queue key and leaves the queue. The add-on ships as an extension with a bundled msgpack wheel; _load_cultmesh names the module it lacks; NO_SCENE_CHANGE_ACTIONS is pinned; the queue harness runs in a stock Blender without PYLIBS. Co-Authored-By: Claude Sonnet 5.5 --- .../brokkr_bridge/blender_manifest.toml | 15 +++++ .../blender/brokkr_bridge/blender_target.py | 36 ++++++++--- .../msgpack-1.2.2-cp313-cp313-win_amd64.whl | Bin 0 -> 72206 bytes surfaces/blender/docs/install.md | 21 +++++++ .../blender/tests/live/agent_turn_queue.py | 54 +++++++++++++--- .../tests/live/agent_turn_queue.result.json | 59 ++++++++++++++---- surfaces/blender/tests/test_agent_turn.py | 47 ++++++++++++++ 7 files changed, 206 insertions(+), 26 deletions(-) create mode 100644 surfaces/blender/brokkr_bridge/blender_manifest.toml create mode 100644 surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-cp313-cp313-win_amd64.whl diff --git a/surfaces/blender/brokkr_bridge/blender_manifest.toml b/surfaces/blender/brokkr_bridge/blender_manifest.toml new file mode 100644 index 0000000..ec5feed --- /dev/null +++ b/surfaces/blender/brokkr_bridge/blender_manifest.toml @@ -0,0 +1,15 @@ +schema_version = "1.0.0" +id = "brokkr_bridge" +version = "0.2.0" +name = "Brokkr Bridge" +tagline = "Brokkr command intents, receipts and snapshots over CultMesh" +maintainer = "GameCult " +type = "add-on" +blender_version_min = "5.3.0" +platforms = ["windows-x64"] +license = ["SPDX:GPL-3.0-or-later"] +# CultLib's cultnet-py and cultcache-py import msgpack; Blender's Python does not ship it. The wheel is +# the installed msgpack 1.2.2 CPython 3.13 Windows build (Blender 5.3 runs Python 3.13). The C extension +# matters: CultLib at baf4ecf7 fails on msgpack's pure-Python fallback (object_pairs_hook gets a generator). +# Linux and macOS wheels are not bundled yet. +wheels = ["./wheels/msgpack-1.2.2-cp313-cp313-win_amd64.whl"] diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 2528bbc..3ed2dcf 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -59,6 +59,9 @@ NO_SCENE_CHANGE_ACTIONS = ("exportGltf", "renderStill") # Anything that writes scene state or changes her mode is refused; renderStill does neither. EDIT_MODE_SAFE_ACTIONS = ("renderStill",) REQUESTED_BY_SHAPE = re.compile(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$") +# A commandId becomes part of a receipt key, so it is a short string of key-safe characters ('.' is left +# out: it separates the '.denied' suffix). +COMMAND_ID_SHAPE = re.compile(r"^[A-Za-z0-9_-]{1,128}$") NOTE_LIMIT = 200 EVALUATED_POSITION_CAP = 256 @@ -154,11 +157,18 @@ class BrokkrBlenderTarget: commands = snapshot.get(COMMAND_INTENT_SCHEMA, {}) receipts: list[dict[str, Any]] = [] self._receipted.update( - r.get("commandId", "") for r in snapshot.get(COMMAND_RECEIPT_SCHEMA, {}).values()) + r["commandId"] for r in snapshot.get(COMMAND_RECEIPT_SCHEMA, {}).values() + if isinstance(r.get("commandId"), str)) for command_key, command in sorted(commands.items()): - reused = command.get("commandId") in self._receipted + command_id = command.get("commandId") + valid = _valid_command_id(command_id) + reused = valid and command_id in self._receipted receipt = self.run_intent(context, command) + if not valid: + # No safe key exists for this id: the denial is receipted under a fresh key and names the + # queue key, so the intent leaves the queue and its sender can still find the refusal. + receipt["message"] += f" (queue key {command_key})" # Receipts are write-once: a reused id's denial goes under '.denied', never over the # original. The sender learns of it by reading that key (and the drain's returned list). self.publish_receipt(cache_path, cultlib_py_src, receipt, debug_mirror_root, @@ -521,8 +531,8 @@ class BrokkrBlenderTarget: requested_by = command.get("requestedBy") action = command.get("action", "") denial = "" - if not isinstance(command_id, str) or not command_id: - denial = "Intent has no commandId." + if not _valid_command_id(command_id): + denial = "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'." elif command_id in self._receipted: denial = f"commandId {command_id!r} was already receipted; ids are single-use." elif not isinstance(requested_by, str) or not REQUESTED_BY_SHAPE.match(requested_by): @@ -533,7 +543,7 @@ class BrokkrBlenderTarget: denial = (f"Object {self._edit_mode_object()!r} is in Edit Mode: object-level intents are refused " "until she leaves it; nothing was changed.") if denial: - if isinstance(command_id, str) and command_id: + if _valid_command_id(command_id): self._receipted.add(command_id) return self._receipt(command, "denied", denial, "") @@ -1094,7 +1104,7 @@ class BrokkrBlenderTarget: def _receipt(self, command: dict[str, Any], status: str, message: str, object_name: str) -> dict[str, Any]: return { "schema": COMMAND_RECEIPT_SCHEMA, - "commandId": command.get("commandId") or uuid.uuid4().hex, + "commandId": command["commandId"] if _valid_command_id(command.get("commandId")) else uuid.uuid4().hex, "action": command.get("action", ""), "status": status, "message": message, @@ -1222,9 +1232,15 @@ def _load_cultmesh(cultlib_py_src: str) -> tuple[Any, Any]: import cultmesh_py # type: ignore import cultcache_py # type: ignore except ModuleNotFoundError as exc: + own = {name.replace("-", "_") for name in CULTLIB_PY_PACKAGES} + if exc.name in own: + raise RuntimeError( + "Brokkr Blender target requires CultLib's Python packages. Set CultLib Python Source " + "to the CultLib packages directory or install cultcache-py, cultnet-py and cultmesh-py into Blender's Python." + ) from exc raise RuntimeError( - "Brokkr Blender target requires CultLib's Python packages. Set CultLib Python Source " - "to the CultLib packages directory or install cultcache-py, cultnet-py and cultmesh-py into Blender's Python." + f"A CultLib Python package needs the module {exc.name!r}, which Blender's Python does not have. " + "Install the add-on as an extension (it bundles msgpack) or install that module into Blender's Python." ) from exc if not hasattr(cultcache_py, "convert"): raise RuntimeError( @@ -1255,6 +1271,10 @@ def _to_list(value: Any) -> list[float]: return [float(item) for item in value] +def _valid_command_id(value: Any) -> bool: + return isinstance(value, str) and COMMAND_ID_SHAPE.match(value) is not None + + def _vector(value: Any, size: int, fallback: Any) -> tuple[float, ...]: if value is None: return tuple(float(item) for item in fallback) diff --git a/surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-cp313-cp313-win_amd64.whl b/surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-cp313-cp313-win_amd64.whl new file mode 100644 index 0000000000000000000000000000000000000000..83a8682553e2b936e0c3cb72ecf267cd6ec8b371 GIT binary patch literal 72206 zcmY&;Q;aT58{|8-ZCht->x^yNwmoykwr$(CZQHi?+hi~Hzvxb<(|OWKRq~)pUJ3*h z6#xK0{k-&0blszJo zLxj-!IE-womWg+OYMwKHl6azUFXfs1yV%AHB%T_PGBCc;yraN@8< zK~4VkOyFTt@?>Xl%%8t;5r?*^LGa0m$&g`U zX#ZoLXWtugLeO>$hHG2L4V15#eLV1OaE5dg&)do|Jx(CA60`ekarMt@+2LXAhr_5I z;^!oKYt~ zAn(#=vy(yjH5`js%?BX=KjaufT=r=Fj~o{Nkpu1jBZrB*k%_&tg`KU_fAmOJlCdlN zfAm;~iEnrZiuWv+EYf95&UnIZch|0Bbv=qLdVl2}0m4;{cjffI@A7zb_hpITgn;ld zoWA|&>`zP;Q#-V5r-I3|s#oV>4x4+jH=yNMB--klVrCQSVs-Yp1>J!LdxS)BPz1RI|D!vnf8V zfh%&yM%9kWMI1~JPkX`(IOD{b4o7gBF0%tn=XStP!k<>%GbYU2_!G0O5a;mVfl0t%d*qmaqT-`2RuL`9Fw@HEirQ#gKn&`+f~%`_Ym} z>KlyOk`XZ=IL=u`FH1O1HS;LP(3%@wByXss4>251(_76< z&DaapDi-=8uxv&8<>Z3B@?!egfWtEE-!_kgIGh-7B zkWHhg^I_HShf7;&8PhQN^9H4^uF!mV_}&i_p7Cqw!fkMWB1F8Ek+G{#394!7iXFP^ zU41F<7{ttX8g@!4e~!r|uitHJO5&zsL#;~bC3fbrX%93Yw+A2$Snr*TTPJ0)T;?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0)JHg#JSK{FlDNaNoTWDgZz@>Ua6q@qYESw{mf@M#j+o3*ag`s/surfaces/blender/brokkr_brid 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-cp313-cp313-win_amd64.whl`, which Blender unpacks into the extension's own +site-packages when the extension is enabled. Build and install it: + +```text +blender --command extension build --source-dir surfaces/blender/brokkr_bridge --output-dir +blender --command extension install-file --repo user_default --enable /brokkr_bridge-0.2.0.zip +``` + +The bundled wheel is msgpack 1.2.2 for CPython 3.13 on Windows x64 (Blender 5.3's Python), +repacked from the installed package with its Apache-2.0 licence; the extension is therefore +declared `windows-x64`, Blender 5.3 or newer. The C extension matters: CultLib at `baf4ecf7` +fails on msgpack's pure-Python fallback. Linux and macOS wheels are not bundled yet: there, +or in a plain add-on directory install, 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: ```text diff --git a/surfaces/blender/tests/live/agent_turn_queue.py b/surfaces/blender/tests/live/agent_turn_queue.py index e44669a..18fc00a 100644 --- a/surfaces/blender/tests/live/agent_turn_queue.py +++ b/surfaces/blender/tests/live/agent_turn_queue.py @@ -3,13 +3,17 @@ are drained by the add-on's own 1 s timer as one undo step each, with write-once BROKKR_USER_SCRIPTS= (also BLENDER_USER_SCRIPTS) BROKKR_SCRATCH= - BROKKR_PYLIBS= + BROKKR_ADDON_MODULE= + BROKKR_CULTLIB= + BROKKR_PYLIBS= blender --factory-startup --python agent_turn_queue.py -- Intents are put into the node database as brokkr-ctl does (no debug-mirror files). Writes .result.json, then quits Blender. Undo is read only here, by this driver. """ +import importlib import json import os import sys @@ -23,19 +27,28 @@ if os.environ.get("BROKKR_PYLIBS"): SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() SCRATCH.mkdir(parents=True, exist_ok=True) OUT = sys.argv[sys.argv.index("--") + 1] -R = {"blender": bpy.app.version_string, "checks": [], "receipts": {}} +R = {"blender": bpy.app.version_string, "module": os.environ.get("BROKKR_ADDON_MODULE", "brokkr_bridge"), + "pylibs": bool(os.environ.get("BROKKR_PYLIBS")), "checks": [], "receipts": {}} -bpy.ops.preferences.addon_enable(module="brokkr_bridge") -import brokkr_bridge as addon # noqa: E402 -from brokkr_bridge import blender_target as bt # noqa: E402 +MODULE = os.environ.get("BROKKR_ADDON_MODULE", "brokkr_bridge") +bpy.ops.preferences.addon_enable(module=MODULE) +addon = importlib.import_module(MODULE) +bt = importlib.import_module(MODULE + ".blender_target") -prefs = bpy.context.preferences.addons["brokkr_bridge"].preferences +try: + import msgpack + R["msgpack"] = msgpack.__file__ +except ImportError: + R["msgpack"] = None +prefs = bpy.context.preferences.addons[MODULE].preferences CACHE = str(SCRATCH / "queue.ccmp") prefs.cultmesh_cache_path = CACHE prefs.debug_mirror_root = "" # the debug-mirror door is not used here prefs.output_dir = str(SCRATCH / "out") prefs.import_dir = "" prefs.auto_drain_commands = True +if os.environ.get("BROKKR_CULTLIB"): + prefs.cultlib_py_src = os.environ["BROKKR_CULTLIB"] (SCRATCH / "out").mkdir(exist_ok=True) adapter = addon.target() @@ -73,6 +86,11 @@ def receipt(key): return n.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}).get(f"blender/receipts/{key}") +def all_receipts(): + n, _ = node() + return n.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}) + + def pending(): n, _ = node() return n.database.snapshot().get(bt.COMMAND_INTENT_SCHEMA, {}) @@ -190,11 +208,33 @@ def q5_exit(): check("queue: add-on drain reports no error", adapter.last_auto_drain_error == "", adapter.last_auto_drain_error) +def q6(): + queue("bad-list", action="createObject", objectType="MESH", name="QBadList", requestedBy="nibu/hands") + queue("bad-int", action="createObject", objectType="MESH", name="QBadInt", requestedBy="nibu/hands") + n, docs = node() + for key in ("bad-list", "bad-int"): # overwrite the id with a non-string, as a hand-written put could + doc = dict(n.database.snapshot()[bt.COMMAND_INTENT_SCHEMA][f"blender/commands/{key}"]) + doc["commandId"] = ["x"] if key == "bad-list" else 7 + n.database.put(docs["command_intent"], f"blender/commands/{key}", doc) + queue("zzzzzzzz-good", action="createObject", objectType="MESH", name="QAfterBad", requestedBy="nibu/hands") + + +def q6_check(): + denials = [r for k, r in all_receipts().items() if "queue key blender/commands/bad-" in r.get("message", "")] + R["receipts"]["q6"] = denials + check("queue: a list id and an int id are denied under fresh keys, removed from the queue, drain not wedged", + len(denials) == 2 and all(r["status"] == "denied" and isinstance(r["commandId"], str) for r in denials) + and not pending() and "QBadList" not in names() and "QBadInt" not in names() + and receipt("zzzzzzzz-good")["status"] == "accepted" and "QAfterBad" in names() + and adapter.last_auto_drain_error == "", [adapter.last_auto_drain_error, list(pending())]) + + steps = [ once(q1), until(drained("aaaaaaaa-0001")), once(q1_check), once(q2), until(lambda: receipt("aaaaaaaa-0001.denied")), once(q2_check), once(q3), until(drained("aaaaaaaa-0003")), once(q3_check), once(q4), until(drained("aaaaaaaa-0004", "aaaaaaaa-0005")), once(q4_undo_two), + once(q6), until(drained("zzzzzzzz-good")), once(q6_check), once(q5_edit), until(drained("aaaaaaaa-0006", "aaaaaaaa-0007", "aaaaaaaa-0008")), once(q5_check), once(q5_exit), ] i = 0 diff --git a/surfaces/blender/tests/live/agent_turn_queue.result.json b/surfaces/blender/tests/live/agent_turn_queue.result.json index a040d56..cbd7ce5 100644 --- a/surfaces/blender/tests/live/agent_turn_queue.result.json +++ b/surfaces/blender/tests/live/agent_turn_queue.result.json @@ -1,5 +1,7 @@ { "blender": "5.3.0", + "module": "bl_ext.user_default.brokkr_bridge", + "pylibs": false, "checks": [ { "name": "queue: createObject drained by the add-on timer, accepted, labelled, attributed", @@ -10,7 +12,7 @@ "message": "Blender object created.", "note": "queue test", "objectName": "QCube", - "observedAt": "2026-11-27T18:07:31.682454+00:00", + "observedAt": "2026-11-27T18:33:33.859109+00:00", "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", "status": "accepted", @@ -31,7 +33,7 @@ "message": "Blender object created.", "note": "queue test", "objectName": "QCube", - "observedAt": "2026-11-27T18:07:31.682454+00:00", + "observedAt": "2026-11-27T18:33:33.859109+00:00", "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", "status": "accepted", @@ -47,7 +49,7 @@ "message": "commandId 'aaaaaaaa-0001' was already receipted; ids are single-use.", "note": "", "objectName": "", - "observedAt": "2026-11-27T18:07:33.680885+00:00", + "observedAt": "2026-11-27T18:33:35.854629+00:00", "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", "status": "denied", @@ -63,7 +65,7 @@ "message": "Intent has no requestedBy of the form '/'.", "note": "", "objectName": "", - "observedAt": "2026-11-27T18:07:35.693748+00:00", + "observedAt": "2026-11-27T18:33:37.862020+00:00", "requestedBy": "", "schema": "brokkr.blender.command_receipt.v0", "status": "denied", @@ -89,6 +91,14 @@ ] ] }, + { + "name": "queue: a list id and an int id are denied under fresh keys, removed from the queue, drain not wedged", + "ok": true, + "detail": [ + "", + [] + ] + }, { "name": "queue: in Edit Mode setWorld, exportGltf and an object write are all denied, her mode kept", "ok": true, @@ -111,7 +121,7 @@ "message": "Blender object created.", "note": "queue test", "objectName": "QCube", - "observedAt": "2026-11-27T18:07:31.682454+00:00", + "observedAt": "2026-11-27T18:33:33.859109+00:00", "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", "status": "accepted", @@ -123,7 +133,7 @@ "message": "Blender object created.", "note": "queue test", "objectName": "QCube", - "observedAt": "2026-11-27T18:07:31.682454+00:00", + "observedAt": "2026-11-27T18:33:33.859109+00:00", "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", "status": "accepted", @@ -135,7 +145,7 @@ "message": "commandId 'aaaaaaaa-0001' was already receipted; ids are single-use.", "note": "", "objectName": "", - "observedAt": "2026-11-27T18:07:33.680885+00:00", + "observedAt": "2026-11-27T18:33:35.854629+00:00", "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", "status": "denied", @@ -147,12 +157,38 @@ "message": "Intent has no requestedBy of the form '/'.", "note": "", "objectName": "", - "observedAt": "2026-11-27T18:07:35.693748+00:00", + "observedAt": "2026-11-27T18:33:37.862020+00:00", "requestedBy": "", "schema": "brokkr.blender.command_receipt.v0", "status": "denied", "undoLabel": "" }, + "q6": [ + { + "action": "createObject", + "commandId": "8cdf6298074845bfa652d7136ec176f0", + "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-int)", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T18:33:41.872393+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "denied", + "undoLabel": "" + }, + { + "action": "createObject", + "commandId": "cfdfef85da3a4c0398901d7ffef109af", + "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-list)", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T18:33:41.884756+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "denied", + "undoLabel": "" + } + ], "q5": [ { "action": "setWorld", @@ -160,7 +196,7 @@ "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", "note": "", "objectName": "", - "observedAt": "2026-11-27T18:07:39.773004+00:00", + "observedAt": "2026-11-27T18:33:43.881906+00:00", "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", "status": "denied", @@ -172,7 +208,7 @@ "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", "note": "", "objectName": "", - "observedAt": "2026-11-27T18:07:39.867526+00:00", + "observedAt": "2026-11-27T18:33:43.894611+00:00", "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", "status": "denied", @@ -184,7 +220,7 @@ "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", "note": "", "objectName": "", - "observedAt": "2026-11-27T18:07:39.950112+00:00", + "observedAt": "2026-11-27T18:33:43.916685+00:00", "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", "status": "denied", @@ -192,5 +228,6 @@ } ] }, + "msgpack": "F:\\aeth-wt\\brokkr-live-2.res\\extensions\\.local\\lib\\python3.13\\site-packages\\msgpack\\__init__.py", "ok": true } \ No newline at end of file diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index 4874644..69e83fc 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -2,6 +2,8 @@ from __future__ import annotations import re +import sys +import tempfile import unittest import unittest.mock from pathlib import Path @@ -146,6 +148,36 @@ class AgentTurnTests(unittest.TestCase): self.assertEqual(again["status"], "denied") self.assertEqual(len(self.bpy.created), 1) + # fix batch s2 + def test_no_scene_change_set_is_exactly_export_and_render(self): + self.assertEqual(bt.NO_SCENE_CHANGE_ACTIONS, ("exportGltf", "renderStill")) + receipt = self.run_action(action="setWorld", color=[0.1, 0.2, 0.3]) + self.assertEqual(receipt["status"], "accepted") + self.assertEqual(len(self.bpy.undo.pushes), 1) + + def test_malformed_command_ids_are_denied_without_raising(self): + for bad in (["x"], 7, 1.5, {"a": 1}, "", "a/b", "x.denied", "has space", "a" * 200, None, True): + receipt = self.run_action(action="createObject", objectType="EMPTY", commandId=bad) + self.assertEqual(receipt["status"], "denied", repr(bad)) + self.assertIsInstance(receipt["commandId"], str) + self.assertRegex(receipt["commandId"], bt.COMMAND_ID_SHAPE.pattern, repr(bad)) + self.assertEqual(self.bpy.created, []) + self.assertEqual(self.bpy.undo.pushes, []) + + def test_load_cultmesh_names_the_missing_module(self): + root = Path(tempfile.mkdtemp()) + self.addCleanup(lambda: __import__("shutil").rmtree(root, ignore_errors=True)) + src = root / "cultmesh-py" / "src" / "cultmesh_py" + src.mkdir(parents=True) + (src / "__init__.py").write_text("import brokkr_no_such_dependency_xyz") + saved = {k: sys.modules.pop(k) for k in ("cultmesh_py", "cultcache_py") if k in sys.modules} + saved_path = list(sys.path) + self.addCleanup(lambda: (sys.modules.update(saved), sys.path[:] == saved_path or sys.path.__setitem__(slice(None), saved_path))) + with self.assertRaises(RuntimeError) as caught: + bt._load_cultmesh(str(root)) + self.assertIn("brokkr_no_such_dependency_xyz", str(caught.exception)) + self.assertNotIn("requires CultLib's Python packages", str(caught.exception)) + class FakeNode: """The node database drain_commands reads: intents, receipts, and what it puts and deletes.""" @@ -177,6 +209,21 @@ class DrainTests(unittest.TestCase): def intent(self, cid, **fields): return {"commandId": cid, "requestedBy": "nibu/hands", "action": "createObject", "objectType": "EMPTY", **fields} + def test_malformed_ids_in_the_queue_never_wedge_the_drain(self): + node = FakeNode({ + "blender/commands/a-list": self.intent(["x"]), + "blender/commands/b-int": self.intent(7), + "blender/commands/c-good": self.intent("good-1"), + }) + receipts = self.drain(node) # must not raise + self.assertEqual(sorted(node.deleted), sorted(node.docs[bt.COMMAND_INTENT_SCHEMA])) + self.assertEqual([r["status"] for r in receipts], ["denied", "denied", "accepted"]) + keys = [k for k, _ in node.puts] + self.assertTrue(all(isinstance(k, str) and "[" not in k for k in keys), keys) + self.assertIn("blender/receipts/good-1", keys) + bad = [v for k, v in node.puts if k != "blender/receipts/good-1"] + self.assertTrue(all("blender/commands/" in v["message"] for v in bad), [v["message"] for v in bad]) + def test_drain_seeds_receipted_from_persisted_receipts(self): old = {"blender/receipts/old-1": {"commandId": "old-1", "status": "accepted"}} node = FakeNode({"blender/commands/old-1": self.intent("old-1")}, old) From 57ca88ed381aa19a495564acd537a5fc5e32102b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 20:02:50 +0100 Subject: [PATCH 14/63] Blender agent turn: live harness results rerun on main a371056f (CultLib baf4ecf7 pins) Co-Authored-By: Claude Sonnet 5.5 --- .../tests/live/agent_turn_queue.result.json | 208 +++++++++--------- .../tests/live/agent_turn_undo.result.json | 4 +- 2 files changed, 106 insertions(+), 106 deletions(-) diff --git a/surfaces/blender/tests/live/agent_turn_queue.result.json b/surfaces/blender/tests/live/agent_turn_queue.result.json index cbd7ce5..9d8a289 100644 --- a/surfaces/blender/tests/live/agent_turn_queue.result.json +++ b/surfaces/blender/tests/live/agent_turn_queue.result.json @@ -7,16 +7,16 @@ "name": "queue: createObject drained by the add-on timer, accepted, labelled, attributed", "ok": true, "detail": { - "action": "createObject", - "commandId": "aaaaaaaa-0001", - "message": "Blender object created.", - "note": "queue test", - "objectName": "QCube", - "observedAt": "2026-11-27T18:33:33.859109+00:00", - "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0001", + "action": "createObject", "status": "accepted", - "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa" + "message": "Blender object created.", + "objectName": "QCube", + "requestedBy": "nibu/hands", + "note": "queue test", + "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa", + "observedAt": "2026-11-27T19:01:35.205337+00:00" } }, { @@ -28,48 +28,48 @@ "name": "queue: reused id leaves the original receipt untouched (write-once)", "ok": true, "detail": { - "action": "createObject", - "commandId": "aaaaaaaa-0001", - "message": "Blender object created.", - "note": "queue test", - "objectName": "QCube", - "observedAt": "2026-11-27T18:33:33.859109+00:00", - "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0001", + "action": "createObject", "status": "accepted", - "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa" + "message": "Blender object created.", + "objectName": "QCube", + "requestedBy": "nibu/hands", + "note": "queue test", + "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa", + "observedAt": "2026-11-27T19:01:35.205337+00:00" } }, { "name": "queue: reused id reported under .denied, nothing created", "ok": true, "detail": { - "action": "createObject", - "commandId": "aaaaaaaa-0001", - "message": "commandId 'aaaaaaaa-0001' was already receipted; ids are single-use.", - "note": "", - "objectName": "", - "observedAt": "2026-11-27T18:33:35.854629+00:00", - "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0001", + "action": "createObject", "status": "denied", - "undoLabel": "" + "message": "commandId 'aaaaaaaa-0001' was already receipted; ids are single-use.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "observedAt": "2026-11-27T19:01:37.202231+00:00" } }, { "name": "queue: intent without requestedBy denied, scene unchanged", "ok": true, "detail": { - "action": "createObject", - "commandId": "aaaaaaaa-0003", - "message": "Intent has no requestedBy of the form '/'.", - "note": "", - "objectName": "", - "observedAt": "2026-11-27T18:33:37.862020+00:00", - "requestedBy": "", "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0003", + "action": "createObject", "status": "denied", - "undoLabel": "" + "message": "Intent has no requestedBy of the form '/'.", + "objectName": "", + "requestedBy": "", + "note": "", + "undoLabel": "", + "observedAt": "2026-11-27T19:01:39.207926+00:00" } }, { @@ -116,115 +116,115 @@ ], "receipts": { "q1": { - "action": "createObject", - "commandId": "aaaaaaaa-0001", - "message": "Blender object created.", - "note": "queue test", - "objectName": "QCube", - "observedAt": "2026-11-27T18:33:33.859109+00:00", - "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0001", + "action": "createObject", "status": "accepted", - "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa" + "message": "Blender object created.", + "objectName": "QCube", + "requestedBy": "nibu/hands", + "note": "queue test", + "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa", + "observedAt": "2026-11-27T19:01:35.205337+00:00" }, "q2_original": { - "action": "createObject", - "commandId": "aaaaaaaa-0001", - "message": "Blender object created.", - "note": "queue test", - "objectName": "QCube", - "observedAt": "2026-11-27T18:33:33.859109+00:00", - "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0001", + "action": "createObject", "status": "accepted", - "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa" + "message": "Blender object created.", + "objectName": "QCube", + "requestedBy": "nibu/hands", + "note": "queue test", + "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa", + "observedAt": "2026-11-27T19:01:35.205337+00:00" }, "q2_denial": { - "action": "createObject", - "commandId": "aaaaaaaa-0001", - "message": "commandId 'aaaaaaaa-0001' was already receipted; ids are single-use.", - "note": "", - "objectName": "", - "observedAt": "2026-11-27T18:33:35.854629+00:00", - "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0001", + "action": "createObject", "status": "denied", - "undoLabel": "" + "message": "commandId 'aaaaaaaa-0001' was already receipted; ids are single-use.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "observedAt": "2026-11-27T19:01:37.202231+00:00" }, "q3": { - "action": "createObject", - "commandId": "aaaaaaaa-0003", - "message": "Intent has no requestedBy of the form '/'.", - "note": "", - "objectName": "", - "observedAt": "2026-11-27T18:33:37.862020+00:00", - "requestedBy": "", "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0003", + "action": "createObject", "status": "denied", - "undoLabel": "" + "message": "Intent has no requestedBy of the form '/'.", + "objectName": "", + "requestedBy": "", + "note": "", + "undoLabel": "", + "observedAt": "2026-11-27T19:01:39.207926+00:00" }, "q6": [ { - "action": "createObject", - "commandId": "8cdf6298074845bfa652d7136ec176f0", - "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-int)", - "note": "", - "objectName": "", - "observedAt": "2026-11-27T18:33:41.872393+00:00", - "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", + "commandId": "ae0a53d8d0584e54b1ce518cf7e8cf9d", + "action": "createObject", "status": "denied", - "undoLabel": "" + "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-int)", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "observedAt": "2026-11-27T19:01:43.220315+00:00" }, { - "action": "createObject", - "commandId": "cfdfef85da3a4c0398901d7ffef109af", - "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-list)", - "note": "", - "objectName": "", - "observedAt": "2026-11-27T18:33:41.884756+00:00", - "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", + "commandId": "f5ce147da5e0466ab0771ac13135f4be", + "action": "createObject", "status": "denied", - "undoLabel": "" + "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-list)", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "observedAt": "2026-11-27T19:01:43.242934+00:00" } ], "q5": [ { - "action": "setWorld", + "schema": "brokkr.blender.command_receipt.v0", "commandId": "aaaaaaaa-0006", - "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", - "note": "", - "objectName": "", - "observedAt": "2026-11-27T18:33:43.881906+00:00", - "requestedBy": "nibu/hands", - "schema": "brokkr.blender.command_receipt.v0", + "action": "setWorld", "status": "denied", - "undoLabel": "" + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "observedAt": "2026-11-27T19:01:45.227825+00:00" }, { - "action": "exportGltf", + "schema": "brokkr.blender.command_receipt.v0", "commandId": "aaaaaaaa-0007", - "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", - "note": "", - "objectName": "", - "observedAt": "2026-11-27T18:33:43.894611+00:00", - "requestedBy": "nibu/hands", - "schema": "brokkr.blender.command_receipt.v0", + "action": "exportGltf", "status": "denied", - "undoLabel": "" + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "observedAt": "2026-11-27T19:01:45.250025+00:00" }, { - "action": "setObjectTransform", - "commandId": "aaaaaaaa-0008", - "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", - "note": "", - "objectName": "", - "observedAt": "2026-11-27T18:33:43.916685+00:00", - "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0008", + "action": "setObjectTransform", "status": "denied", - "undoLabel": "" + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "observedAt": "2026-11-27T19:01:45.281467+00:00" } ] }, diff --git a/surfaces/blender/tests/live/agent_turn_undo.result.json b/surfaces/blender/tests/live/agent_turn_undo.result.json index 7e8e590..5468ce0 100644 --- a/surfaces/blender/tests/live/agent_turn_undo.result.json +++ b/surfaces/blender/tests/live/agent_turn_undo.result.json @@ -197,7 +197,7 @@ "name": "exportGltf and renderStill accepted with no undoLabel", "ok": true, "detail": [ - "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-yk0g4dyg\\object.glb (3484 bytes).", + "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-a4ak7h0p\\object.glb (3484 bytes).", "Rendered still to object.png." ] }, @@ -270,7 +270,7 @@ "intent": "exportGltf", "status": "accepted", "undoLabel": "", - "message": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-yk0g4dyg\\object.glb (3484 bytes)." + "message": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-a4ak7h0p\\object.glb (3484 bytes)." }, { "intent": "renderStill", From 68e1b654dda7384a417677d94b7bbe5d258a6398 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 18:35:30 +0100 Subject: [PATCH 15/63] brokkr-ctl blender: a Rust CLI that sends typed intents to the live add-on's store and reads receipts and the snapshot Workspace member brokkr-ctl; cultcache-rs moves to [workspace.dependencies] at the daemon's existing rev. Writes only blender/commands/; intents are attributed or refused; exit code derives from the receipt. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.toml | 6 +- brokkr-ctl/Cargo.toml | 14 + brokkr-ctl/src/blender.rs | 588 ++++++++++++++++++ brokkr-ctl/src/main.rs | 24 + brokkr-ctl/tests/cli.rs | 154 +++++ brokkr-daemon/Cargo.toml | 2 +- .../blender/tests/test_brokkr_ctl_interop.py | 73 +++ 7 files changed, 859 insertions(+), 2 deletions(-) create mode 100644 brokkr-ctl/Cargo.toml create mode 100644 brokkr-ctl/src/blender.rs create mode 100644 brokkr-ctl/src/main.rs create mode 100644 brokkr-ctl/tests/cli.rs create mode 100644 surfaces/blender/tests/test_brokkr_ctl_interop.py diff --git a/Cargo.toml b/Cargo.toml index 37f910c..c469605 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,10 @@ [workspace] resolver = "2" members = [ - "brokkr-daemon" + "brokkr-daemon", + "brokkr-ctl", ] +[workspace.dependencies] +cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "baf4ecf78fae634fafef956d3b85420162c074bb", package = "cultcache-rs" } + diff --git a/brokkr-ctl/Cargo.toml b/brokkr-ctl/Cargo.toml new file mode 100644 index 0000000..cff9015 --- /dev/null +++ b/brokkr-ctl/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "brokkr-ctl" +version = "0.1.0" +edition = "2024" +publish = false + +[dependencies] +anyhow = "1" +cultcache-rs = { workspace = true } +serde_json = "1" +uuid = { version = "1", features = ["v4"] } + +[dev-dependencies] +tempfile = "3" diff --git a/brokkr-ctl/src/blender.rs b/brokkr-ctl/src/blender.rs new file mode 100644 index 0000000..d054357 --- /dev/null +++ b/brokkr-ctl/src/blender.rs @@ -0,0 +1,588 @@ +//! `brokkr-ctl blender`: a caller of the Blender add-on's store. It writes one intent +//! document per `send` and reads receipts and the host snapshot. The add-on decides. + +use anyhow::{Context, Result, anyhow, bail}; +use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, SingleFileMessagePackBackingStore}; +use serde_json::{Map, Value}; +use std::path::PathBuf; +use std::thread; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +pub const INTENT_SCHEMA: &str = "brokkr.blender.command_intent.v0"; +pub const RECEIPT_SCHEMA: &str = "brokkr.blender.command_receipt.v0"; +pub const SNAPSHOT_SCHEMA: &str = "brokkr.blender.host_snapshot.v0"; +const INTENT_PREFIX: &str = "blender/commands/"; +const RECEIPT_PREFIX: &str = "blender/receipts/"; +const SNAPSHOT_KEY: &str = "blender/host/current"; +const RESERVED: [&str; 5] = ["schema", "commandId", "action", "requestedBy", "note"]; +const DEFAULT_TIMEOUT_SECS: f64 = 60.0; +const POLL: Duration = Duration::from_millis(200); + +/// What a receipt (or its absence) says; the exit code derives from it and from nothing else. +pub enum Outcome { + Accepted, + Failed, + Stopped, + Timeout, +} + +impl Outcome { + pub fn code(&self) -> i32 { + match self { + Outcome::Accepted => 0, + Outcome::Failed => 2, + Outcome::Stopped => 3, + Outcome::Timeout => 4, + } + } + + pub fn from_status(status: &str) -> Outcome { + match status { + "accepted" => Outcome::Accepted, + "stopped" => Outcome::Stopped, + _ => Outcome::Failed, // denied, failed, and any status this tool does not know + } + } +} + +#[derive(Default)] +struct Options { + store: Option, + agent: Option, + note: String, + sets: Vec, + no_wait: bool, + timeout: Option, + last: Option, + positional: Vec, +} + +fn parse(args: &[String]) -> Result { + let mut options = Options::default(); + let mut iter = args.iter(); + while let Some(arg) = iter.next() { + let mut value = |name: &str| { + iter.next() + .cloned() + .ok_or_else(|| anyhow!("{name} needs a value")) + }; + match arg.as_str() { + "--store" => options.store = Some(PathBuf::from(value("--store")?)), + "--agent" => options.agent = Some(value("--agent")?), + "--note" => options.note = value("--note")?, + "--set" => options.sets.push(value("--set")?), + "--no-wait" => options.no_wait = true, + "--timeout" => { + let raw = value("--timeout")?; + let secs: f64 = raw + .parse() + .map_err(|_| anyhow!("--timeout wants seconds, got {raw:?}"))?; + if !secs.is_finite() || secs < 0.0 { + bail!("--timeout wants a non-negative number of seconds"); + } + options.timeout = Some(secs); + } + "--last" => { + let raw = value("--last")?; + options.last = Some( + raw.parse() + .map_err(|_| anyhow!("--last wants a count, got {raw:?}"))?, + ); + } + flag if flag.starts_with("--") => bail!("unknown option {flag}"), + _ => options.positional.push(arg.clone()), + } + } + Ok(options) +} + +/// Runs one `blender` subcommand and returns the process exit code. +pub fn run(args: &[String]) -> Result { + let Some((sub, rest)) = args.split_first() else { + print!("{}", group_help()); + return Ok(1); + }; + if matches!(sub.as_str(), "--help" | "-h" | "help") { + print!("{}", group_help()); + return Ok(0); + } + if rest.iter().any(|arg| arg == "--help" || arg == "-h") { + print!("{}", if sub == "send" { send_help() } else { group_help() }); + return Ok(0); + } + let options = parse(rest)?; + match sub.as_str() { + "send" => send(&options), + "wait" => { + let id = one_positional(&options, "wait ")?; + let store = open_store(&options)?; + wait_for_receipt(&store, id, timeout(&options)) + } + "receipts" => receipts(&open_store(&options)?, options.last), + "status" => status(&open_store(&options)?), + other => bail!("unknown subcommand {other:?}; try `brokkr-ctl blender --help`"), + } +} + +fn one_positional<'a>(options: &'a Options, usage: &str) -> Result<&'a str> { + match options.positional.as_slice() { + [one] => Ok(one), + _ => bail!("usage: brokkr-ctl blender {usage}"), + } +} + +fn timeout(options: &Options) -> Duration { + Duration::from_secs_f64(options.timeout.unwrap_or(DEFAULT_TIMEOUT_SECS)) +} + +/// The add-on creates its store; naming a path that is not there is a typo, not a request +/// to make a second store. +fn open_store(options: &Options) -> Result { + let path = options + .store + .clone() + .or_else(|| std::env::var_os("BROKKR_BLENDER_STORE").map(PathBuf::from)) + .ok_or_else(|| anyhow!("no store: pass --store or set BROKKR_BLENDER_STORE"))?; + if !path.is_file() { + bail!("store {} does not exist; the add-on creates it", path.display()); + } + // The store library stages writes beside the file and fails on a bare file name. + Ok(SingleFileMessagePackBackingStore::new(std::path::absolute(path)?)) +} + +fn requested_by(options: &Options) -> Result { + let instance = std::env::var("EUREKA_INSTANCE").unwrap_or_default(); + let agent = options + .agent + .clone() + .or_else(|| std::env::var("BROKKR_AGENT").ok()) + .unwrap_or_default(); + if instance.trim().is_empty() || agent.trim().is_empty() { + bail!("an intent must be attributed: set EUREKA_INSTANCE and pass --agent or set BROKKR_AGENT"); + } + Ok(format!("{}/{}", instance.trim(), agent.trim())) +} + +fn build_intent( + action: &str, + command_id: &str, + requested_by: &str, + note: &str, + sets: &[String], +) -> Result { + if action.is_empty() || !action.chars().all(|c| c.is_ascii_alphanumeric()) { + bail!("action must be letters and digits, e.g. createObject"); + } + let mut map = Map::new(); + for set in sets { + let (key, raw) = set + .split_once('=') + .ok_or_else(|| anyhow!("--set wants key=json, got {set:?}"))?; + if key.is_empty() || RESERVED.contains(&key) { + bail!("--set cannot name {key:?}: it is written by brokkr-ctl"); + } + let value: Value = serde_json::from_str(raw) + .with_context(|| format!("--set {key}: {raw:?} is not JSON (strings need quotes)"))?; + map.insert(key.to_string(), value); + } + map.insert("schema".into(), INTENT_SCHEMA.into()); + map.insert("commandId".into(), command_id.into()); + map.insert("action".into(), action.into()); + map.insert("requestedBy".into(), requested_by.into()); + map.insert("note".into(), note.into()); + Ok(Value::Object(map)) +} + +fn send(options: &Options) -> Result { + let action = one_positional(options, "send [--set key=json]...")?; + let requested_by = requested_by(options)?; + let mut store = open_store(options)?; + let command_id = uuid::Uuid::new_v4().simple().to_string(); + let intent = build_intent(action, &command_id, &requested_by, &options.note, &options.sets)?; + store.push(&CultCacheEnvelope { + key: format!("{INTENT_PREFIX}{command_id}"), + r#type: INTENT_SCHEMA.to_string(), + payload: serde_json::to_vec(&intent)?, + stored_at: iso_now(), + schema_id: Some(INTENT_SCHEMA.to_string()), + })?; + println!("commandId: {command_id}"); + if options.no_wait { + return Ok(0); + } + wait_for_receipt(&store, &command_id, timeout(options)) +} + +fn read_receipt(store: &SingleFileMessagePackBackingStore, id: &str) -> Result> { + let key = format!("{RECEIPT_PREFIX}{id}"); + for envelope in store.pull_all()? { + if envelope.key == key && envelope.r#type == RECEIPT_SCHEMA { + return Ok(Some(decode(&envelope)?)); + } + } + Ok(None) +} + +fn wait_for_receipt( + store: &SingleFileMessagePackBackingStore, + id: &str, + limit: Duration, +) -> Result { + let started = Instant::now(); + loop { + if let Some(receipt) = read_receipt(store, id)? { + print_fields(&receipt); + let status = receipt.get("status").and_then(Value::as_str).unwrap_or(""); + return Ok(Outcome::from_status(status).code()); + } + if started.elapsed() >= limit { + println!("status: timeout"); + return Ok(Outcome::Timeout.code()); + } + thread::sleep(POLL); + } +} + +fn receipts(store: &SingleFileMessagePackBackingStore, last: Option) -> Result { + let mut found = Vec::new(); + for envelope in store.pull_all()? { + if envelope.key.starts_with(RECEIPT_PREFIX) && envelope.r#type == RECEIPT_SCHEMA { + found.push(decode(&envelope)?); + } + } + found.sort_by_key(|receipt| { + receipt + .get("observedAt") + .and_then(Value::as_str) + .unwrap_or("") + .to_string() + }); + let skip = last.map_or(0, |n| found.len().saturating_sub(n)); + for (index, receipt) in found.iter().skip(skip).enumerate() { + if index > 0 { + println!(); + } + print_fields(receipt); + } + Ok(0) +} + +fn status(store: &SingleFileMessagePackBackingStore) -> Result { + for envelope in store.pull_all()? { + if envelope.key == SNAPSHOT_KEY && envelope.r#type == SNAPSHOT_SCHEMA { + let snapshot = decode(&envelope)?; + for key in [ + "observedAt", + "blenderVersion", + "projectPath", + "mode", + "activeScene", + "activeObjectName", + "selectedObjectNames", + "objectCount", + "sink", + ] { + if let Some(value) = snapshot.get(key) { + print_field(key, value); + } + } + return Ok(0); + } + } + bail!("the store holds no host snapshot yet; is the add-on's server running?") +} + +fn decode(envelope: &CultCacheEnvelope) -> Result { + serde_json::from_slice(&envelope.payload) + .with_context(|| format!("{} is not a JSON map payload", envelope.key)) +} + +fn print_fields(value: &Value) { + match value.as_object() { + Some(map) => map.iter().for_each(|(key, value)| print_field(key, value)), + None => println!("value: {value}"), + } +} + +fn print_field(key: &str, value: &Value) { + match value { + Value::String(text) => println!("{key}: {text}"), + other => println!("{key}: {other}"), + } +} + +/// UTC, microseconds, `+00:00`: the form the Python node stamps. +fn iso_now() -> String { + let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default(); + iso_from(now.as_secs() as i64, now.subsec_micros()) +} + +fn iso_from(secs: i64, micros: u32) -> String { + let days = secs.div_euclid(86_400); + let rem = secs.rem_euclid(86_400); + // Howard Hinnant's civil_from_days. + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + i64::from(month <= 2); + format!( + "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{micros:06}+00:00", + rem / 3_600, + rem % 3_600 / 60, + rem % 60 + ) +} + +pub fn group_help() -> String { + "\ +brokkr-ctl blender: send typed intents to the live Blender add-on and read what it did. + + send [--set key=json]... [--note text] [--agent name] [--no-wait] [--timeout secs] + Write one intent, then wait for its receipt and print it. `send --help` lists actions. + wait [--timeout secs] Wait for a receipt and print it. + receipts [--last n] Print stored receipts, oldest first. + status Print the host snapshot summary. + +Every command needs --store or $BROKKR_BLENDER_STORE (the add-on's .ccmp). +send needs $EUREKA_INSTANCE and --agent or $BROKKR_AGENT; requestedBy is '/'. +Output is 'key: value' lines. Exit: 0 accepted, 2 denied or failed, 3 stopped, 4 timeout, +1 usage or store error. brokkr-ctl validates nothing about an action: the add-on does, and +its refusal comes back in the receipt. +" + .to_string() +} + +pub fn send_help() -> String { + let mut text = String::from( + "\ +brokkr-ctl blender send [--set key=json]... [--note text] [--agent name] [--no-wait] [--timeout secs] + +--set takes JSON: --set objectType='\"MESH\"' --set location='[0,0,1]'. brokkr-ctl writes schema, +commandId, action, requestedBy and note itself; --set cannot name them. Fields below are what the +add-on reads; it validates them and refuses in the receipt. Targets also accept objectName. + +actions: +", + ); + for (action, fields) in ACTIONS { + text.push_str(&format!(" {action}\n")); + for (name, kind, note) in *fields { + text.push_str(&format!(" {name}: {kind} {note}\n")); + } + } + text +} + +type Field = (&'static str, &'static str, &'static str); + +/// Help text only: what the add-on's `execute_command` dispatches and reads at the base commit. +const ACTIONS: &[(&str, &[Field])] = &[ + ( + "createObject", + &[ + ("objectType", "string", "MESH | LIGHT | CAMERA | EMPTY (default EMPTY)"), + ("name", "string", ""), + ("location", "[x,y,z]", ""), + ("size", "number", "MESH"), + ("meshType", "string", "CUBE"), + ("lightType", "string", "LIGHT"), + ("emptyDisplayType", "string", "EMPTY"), + ], + ), + ("deleteObject", &[("targetObjectName", "string", "")]), + ( + "setObjectTransform", + &[ + ("targetObjectName", "string", ""), + ("location", "[x,y,z]", ""), + ("rotationEuler", "[x,y,z]", "radians"), + ("scale", "[x,y,z]", ""), + ], + ), + ( + "setObjectVisibility", + &[("targetObjectName", "string", ""), ("visible", "bool", "")], + ), + ( + "setObjectParent", + &[ + ("targetObjectName", "string", ""), + ("parentObjectName", "string", "empty clears the parent"), + ], + ), + ( + "setObjectCustomProperty", + &[ + ("targetObjectName", "string", ""), + ("propertyName", "string", ""), + ("value", "json", ""), + ], + ), + ( + "selectObject", + &[("targetObjectName", "string", ""), ("clearSelection", "bool", "default true")], + ), + ( + "assignMaterial", + &[ + ("targetObjectName", "string", ""), + ("materialName", "string", ""), + ("color", "[r,g,b] or [r,g,b,a]", "linear, 0..1"), + ], + ), + ( + "importGltf", + &[("filepath", "string", "inside the add-on's import directory")], + ), + ( + "exportGltf", + &[ + ("filepath", "string", ".glb or .gltf inside the add-on's output directory"), + ("extras", "bool", ""), + ("yUp", "bool", ""), + ("applyModifiers", "bool", ""), + ("selection", "[string]", "object names"), + ], + ), + ( + "setCamera", + &[ + ("targetObjectName", "string", ""), + ("lens", "number", "mm"), + ("cameraType", "string", ""), + ("orthoScale", "number", ""), + ("clipStart", "number", ""), + ("clipEnd", "number", ""), + ("panoramaType", "string", ""), + ("active", "bool", "make it the scene camera"), + ], + ), + ( + "setLight", + &[ + ("targetObjectName", "string", ""), + ("energy", "number", ""), + ("color", "[r,g,b]", "linear, 0..1"), + ("lightType", "string", ""), + ], + ), + ( + "setWorld", + &[ + ("worldName", "string", ""), + ("color", "[r,g,b]", "linear, 0..1"), + ("strength", "number", ""), + ], + ), + ( + "renderStill", + &[ + ("outputPath", "string", "inside the add-on's output directory"), + ("engine", "string", ""), + ("resolutionX", "integer", ""), + ("resolutionY", "integer", ""), + ("cameraName", "string", ""), + ], + ), + ( + "createNodeGroup", + &[ + ("treeKey", "string", ""), + ("interface", "[{inOut,name,type,default?}]", "types: Geometry Float Int Bool Vector"), + ], + ), + ( + "addNode", + &[ + ("treeKey", "string", ""), + ("id", "string", "brokkr's key for the node"), + ("blIdname", "string", "GeometryNode*, FunctionNode* or ShaderNode*"), + ("location", "[x,y]", ""), + ("label", "string", ""), + ("properties", "object", "enum, bool, int or float node settings"), + ("inputs", "object", "unlinked input defaults"), + ], + ), + ("removeNode", &[("treeKey", "string", ""), ("id", "string", "")]), + ( + "linkSockets", + &[ + ("treeKey", "string", ""), + ("fromNode", "string", ""), + ("fromSocket", "string", ""), + ("toNode", "string", ""), + ("toSocket", "string", ""), + ], + ), + ( + "unlinkSockets", + &[ + ("treeKey", "string", ""), + ("toNode", "string", ""), + ("toSocket", "string", ""), + ("fromNode", "string", "optional"), + ("fromSocket", "string", "optional"), + ], + ), + ( + "addModifier", + &[ + ("objectName", "string", ""), + ("treeKey", "string", ""), + ("modifierName", "string", "default Brokkr GeoNodes"), + ], + ), + ( + "removeModifier", + &[("objectName", "string", ""), ("modifierName", "string", "")], + ), + ( + "setModifierInput", + &[ + ("objectName", "string", ""), + ("modifierName", "string", ""), + ("socket", "string", "identifier or unique interface name"), + ("value", "json", "Float, Int, Bool or Vector"), + ], + ), +]; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn iso_matches_the_python_form() { + assert_eq!(iso_from(0, 0), "1970-01-01T00:00:00.000000+00:00"); + assert_eq!(iso_from(1_795_800_558, 813_099), "2026-11-27T17:29:18.813099+00:00"); + } + + #[test] + fn intent_carries_reserved_fields_and_refuses_overrides() { + let sets = vec!["objectType=\"MESH\"".to_string(), "location=[0,0,1]".to_string()]; + let intent = build_intent("createObject", "abc", "nibu/hands", "n", &sets).unwrap(); + assert_eq!(intent["requestedBy"], "nibu/hands"); + assert_eq!(intent["objectType"], "MESH"); + assert_eq!(intent["location"][2], 1); + for bad in ["requestedBy=\"x\"", "commandId=\"x\"", "action=\"x\"", "novalue", "k=notjson"] { + assert!( + build_intent("createObject", "abc", "a/b", "", &[bad.to_string()]).is_err(), + "{bad}" + ); + } + assert!(build_intent("../x", "abc", "a/b", "", &[]).is_err()); + } + + #[test] + fn statuses_map_to_exit_codes() { + for (status, code) in [("accepted", 0), ("denied", 2), ("failed", 2), ("stopped", 3), ("weird", 2)] { + assert_eq!(Outcome::from_status(status).code(), code, "{status}"); + } + assert_eq!(Outcome::Timeout.code(), 4); + } +} diff --git a/brokkr-ctl/src/main.rs b/brokkr-ctl/src/main.rs new file mode 100644 index 0000000..1fc3dd8 --- /dev/null +++ b/brokkr-ctl/src/main.rs @@ -0,0 +1,24 @@ +//! brokkr-ctl: command-line hands for Brokkr's creative-tool surfaces. + +mod blender; + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + let code = match args.split_first() { + Some((group, rest)) if group == "blender" => blender::run(rest), + Some((flag, _)) if matches!(flag.as_str(), "--help" | "-h" | "help") => { + print!( + "brokkr-ctl ...\n\ngroups:\n blender send intents to the live Blender add-on (`brokkr-ctl blender --help`)\n" + ); + Ok(0) + } + _ => Err(anyhow::anyhow!("usage: brokkr-ctl blender ...")), + }; + match code { + Ok(code) => std::process::exit(code), + Err(error) => { + eprintln!("error: {error:#}"); + std::process::exit(1); + } + } +} diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs new file mode 100644 index 0000000..a9cee07 --- /dev/null +++ b/brokkr-ctl/tests/cli.rs @@ -0,0 +1,154 @@ +//! brokkr-ctl against a real single-file store, read back through cultcache-rs. + +use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, SingleFileMessagePackBackingStore}; +use serde_json::{Value, json}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; + +const INTENT: &str = "brokkr.blender.command_intent.v0"; +const RECEIPT: &str = "brokkr.blender.command_receipt.v0"; + +fn envelope(schema: &str, key: &str, payload: &Value) -> CultCacheEnvelope { + CultCacheEnvelope { + key: key.to_string(), + r#type: schema.to_string(), + payload: serde_json::to_vec(payload).unwrap(), + stored_at: "2026-11-27T00:00:00.000000+00:00".to_string(), + schema_id: Some(schema.to_string()), + } +} + +/// A store the way the add-on leaves it: a file that already exists, holding other records. +fn store_with_receipts(dir: &Path, statuses: &[(&str, &str)]) -> PathBuf { + let path = dir.join("blender-editor.ccmp"); + let mut store = SingleFileMessagePackBackingStore::new(&path); + for (id, status) in statuses { + let receipt = json!({"schema": RECEIPT, "commandId": id, "status": status, "observedAt": "2026-11-27T00:00:00+00:00"}); + store + .push(&envelope(RECEIPT, &format!("blender/receipts/{id}"), &receipt)) + .unwrap(); + } + path +} + +fn ctl(store: &Path, args: &[&str], instance: Option<&str>) -> Output { + let mut command = Command::new(env!("CARGO_BIN_EXE_brokkr-ctl")); + command + .arg("blender") + .args(args) + .arg("--store") + .arg(store) + .env_remove("BROKKR_AGENT") + .env_remove("BROKKR_BLENDER_STORE") + .env_remove("EUREKA_INSTANCE"); + if let Some(instance) = instance { + command.env("EUREKA_INSTANCE", instance); + } + command.output().unwrap() +} + +fn stdout(output: &Output) -> String { + String::from_utf8_lossy(&output.stdout).into_owned() +} + +#[test] +fn send_writes_a_pullable_intent() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("seed", "accepted")]); + let output = ctl( + &path, + &["send", "createObject", "--set", "objectType=\"MESH\"", "--set", "location=[0,0,1]", "--note", "a cube", "--agent", "hands", "--no-wait"], + Some("nibu"), + ); + assert_eq!(output.status.code(), Some(0), "{}", String::from_utf8_lossy(&output.stderr)); + let id = stdout(&output).trim().strip_prefix("commandId: ").unwrap().to_string(); + assert_eq!(id.len(), 32); + + let envelopes = SingleFileMessagePackBackingStore::new(&path).pull_all().unwrap(); + let intent = envelopes + .iter() + .find(|e| e.key == format!("blender/commands/{id}")) + .expect("intent key"); + assert_eq!(intent.r#type, INTENT); + assert_eq!(intent.schema_id.as_deref(), Some(INTENT)); + let payload: Value = serde_json::from_slice(&intent.payload).unwrap(); + assert_eq!( + payload, + json!({"schema": INTENT, "commandId": id, "action": "createObject", "requestedBy": "nibu/hands", + "note": "a cube", "objectType": "MESH", "location": [0, 0, 1]}) + ); + assert!(envelopes.iter().any(|e| e.key == "blender/receipts/seed"), "other records survive the write"); +} + +#[test] +fn an_intent_without_instance_or_agent_is_refused_and_writes_nothing() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("seed", "accepted")]); + let before = std::fs::read(&path).unwrap(); + for (instance, agent) in [(None, Some("hands")), (Some("nibu"), None), (None, None), (Some(" "), Some("hands"))] { + let mut args = vec!["send", "createObject", "--no-wait"]; + if let Some(agent) = agent { + args.extend(["--agent", agent]); + } + let output = ctl(&path, &args, instance); + assert_eq!(output.status.code(), Some(1), "{instance:?} {agent:?}"); + } + assert_eq!(std::fs::read(&path).unwrap(), before); +} + +#[test] +fn a_missing_store_is_not_created() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("nope.ccmp"); + let output = ctl(&path, &["send", "createObject", "--agent", "hands", "--no-wait"], Some("nibu")); + assert_eq!(output.status.code(), Some(1)); + assert!(!path.exists()); +} + +#[test] +fn exit_code_follows_the_receipt() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts( + dir.path(), + &[("a", "accepted"), ("d", "denied"), ("f", "failed"), ("s", "stopped")], + ); + for (id, code) in [("a", 0), ("d", 2), ("f", 2), ("s", 3)] { + let output = ctl(&path, &["wait", id, "--timeout", "5"], None); + assert_eq!(output.status.code(), Some(code), "{id}"); + assert!(stdout(&output).contains(&format!("commandId: {id}"))); + } + let output = ctl(&path, &["wait", "missing", "--timeout", "0.3"], None); + assert_eq!(output.status.code(), Some(4)); + assert!(stdout(&output).contains("status: timeout")); +} + +#[test] +fn receipts_lists_the_last_n_oldest_first() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("a", "accepted"), ("b", "failed")]); + let output = ctl(&path, &["receipts"], None); + assert_eq!(output.status.code(), Some(0)); + let text = stdout(&output); + assert!(text.contains("commandId: a") && text.contains("commandId: b")); + let one = ctl(&path, &["receipts", "--last", "1"], None); + assert!(!stdout(&one).contains("commandId: a")); +} + +#[test] +fn status_without_a_snapshot_is_a_store_error() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("a", "accepted")]); + assert_eq!(ctl(&path, &["status"], None).status.code(), Some(1)); +} + +#[test] +fn send_help_lists_the_actions() { + let output = Command::new(env!("CARGO_BIN_EXE_brokkr-ctl")) + .args(["blender", "send", "--help"]) + .output() + .unwrap(); + let text = stdout(&output); + for action in ["createObject", "renderStill", "setModifierInput", "exportGltf"] { + assert!(text.contains(action), "{action}"); + } +} diff --git a/brokkr-daemon/Cargo.toml b/brokkr-daemon/Cargo.toml index 58bbccf..77fce12 100644 --- a/brokkr-daemon/Cargo.toml +++ b/brokkr-daemon/Cargo.toml @@ -6,7 +6,7 @@ publish = false [dependencies] anyhow = "1" -cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "baf4ecf78fae634fafef956d3b85420162c074bb", package = "cultcache-rs" } +cultcache-rs = { workspace = true } rmp-serde = "1.3" serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/surfaces/blender/tests/test_brokkr_ctl_interop.py b/surfaces/blender/tests/test_brokkr_ctl_interop.py new file mode 100644 index 0000000..92bef5a --- /dev/null +++ b/surfaces/blender/tests/test_brokkr_ctl_interop.py @@ -0,0 +1,73 @@ +"""brokkr-ctl writes an intent a cultmesh-py node pulls as the same dict, and reads a node's receipt. + +No Blender. Needs CultLib's Python packages (CULTLIB_PACKAGES, the packages directory) and the built +binary (BROKKR_CTL, the path to brokkr-ctl or brokkr-ctl.exe); skipped when either is missing. +""" +from __future__ import annotations + +import os +import subprocess +import sys +import tempfile +import types +import unittest +from pathlib import Path + +ADDON = Path(__file__).resolve().parents[1] / "brokkr_bridge" +package = types.ModuleType("brokkr_bridge") +package.__path__ = [str(ADDON)] +sys.modules.setdefault("brokkr_bridge", package) + +from brokkr_bridge import blender_target as bt # noqa: E402 + +PACKAGES = os.environ.get("CULTLIB_PACKAGES", "") +CTL = os.environ.get("BROKKR_CTL", "") + + +@unittest.skipUnless(PACKAGES and Path(PACKAGES).is_dir(), "set CULTLIB_PACKAGES to CultLib's packages directory") +@unittest.skipUnless(CTL and Path(CTL).is_file(), "set BROKKR_CTL to the built brokkr-ctl binary") +class BrokkrCtlInterop(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.store = str(Path(self.tmp.name) / "blender-editor.ccmp") + self.cultmesh, self.cultcache = bt._load_cultmesh(PACKAGES) + self.node = self.cultmesh.CultMesh.start_node(self.store, runtime_id="addon") + self.intent = self.cultcache.define_document_type(bt.COMMAND_INTENT_SCHEMA) + self.receipt = self.cultcache.define_document_type(bt.COMMAND_RECEIPT_SCHEMA) + self.node.database.register_document(self.intent) + self.node.database.register_document(self.receipt) + # The add-on's own first write is what creates its store file. + self.node.database.put(self.receipt, "blender/receipts/seed", { + "schema": bt.COMMAND_RECEIPT_SCHEMA, "commandId": "seed", "status": "accepted"}) + + def ctl(self, *args): + env = dict(os.environ, EUREKA_INSTANCE="nibu") + env.pop("BROKKR_AGENT", None) + return subprocess.run([CTL, "blender", *args, "--store", self.store], env=env, + capture_output=True, text=True, timeout=60) + + def test_a_node_pulls_the_intent_as_the_dict_ctl_wrote(self): + sent = self.ctl("send", "createObject", "--set", 'objectType="MESH"', "--set", "location=[0,0,1]", + "--note", "a cube", "--agent", "hands", "--no-wait") + self.assertEqual(sent.returncode, 0, sent.stderr) + command_id = sent.stdout.split("commandId:")[1].split()[0] + self.node.database.pull() + got = self.node.database.snapshot()[bt.COMMAND_INTENT_SCHEMA][f"blender/commands/{command_id}"] + self.assertEqual(got, { + "schema": bt.COMMAND_INTENT_SCHEMA, "commandId": command_id, "action": "createObject", + "requestedBy": "nibu/hands", "note": "a cube", "objectType": "MESH", "location": [0, 0, 1]}) + # The node's own earlier record is still there after the Rust whole-store write. + self.assertIn("blender/receipts/seed", self.node.database.snapshot()[bt.COMMAND_RECEIPT_SCHEMA]) + + def test_ctl_reads_a_receipt_the_node_wrote(self): + self.node.database.put(self.receipt, "blender/receipts/r1", { + "schema": bt.COMMAND_RECEIPT_SCHEMA, "commandId": "r1", "action": "createObject", + "status": "failed", "message": "refused"}) + waited = self.ctl("wait", "r1", "--timeout", "5") + self.assertEqual(waited.returncode, 2, waited.stderr) + self.assertIn("message: refused", waited.stdout) + + +if __name__ == "__main__": + unittest.main() From ef7086971c268e6e3e0f4958e07ac012e17ca761 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 18:54:21 +0100 Subject: [PATCH 16/63] brokkr-ctl: time-ordered ids, stat-gated polling, parsed help flag, bounded timeout, absolute unlinked store, pinned survivors Co-Authored-By: Claude Sonnet 5.5 --- brokkr-ctl/Cargo.toml | 2 +- brokkr-ctl/src/blender.rs | 94 +++++++++++++++++---- brokkr-ctl/tests/cli.rs | 168 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 249 insertions(+), 15 deletions(-) diff --git a/brokkr-ctl/Cargo.toml b/brokkr-ctl/Cargo.toml index cff9015..ce74ab3 100644 --- a/brokkr-ctl/Cargo.toml +++ b/brokkr-ctl/Cargo.toml @@ -8,7 +8,7 @@ publish = false anyhow = "1" cultcache-rs = { workspace = true } serde_json = "1" -uuid = { version = "1", features = ["v4"] } +uuid = { version = "1", features = ["v7"] } [dev-dependencies] tempfile = "3" diff --git a/brokkr-ctl/src/blender.rs b/brokkr-ctl/src/blender.rs index d054357..c35148b 100644 --- a/brokkr-ctl/src/blender.rs +++ b/brokkr-ctl/src/blender.rs @@ -15,8 +15,11 @@ const INTENT_PREFIX: &str = "blender/commands/"; const RECEIPT_PREFIX: &str = "blender/receipts/"; const SNAPSHOT_KEY: &str = "blender/host/current"; const RESERVED: [&str; 5] = ["schema", "commandId", "action", "requestedBy", "note"]; -const DEFAULT_TIMEOUT_SECS: f64 = 60.0; +const DEFAULT_TIMEOUT_SECS: u64 = 60; const POLL: Duration = Duration::from_millis(200); +const MAX_TIMEOUT: Duration = Duration::from_secs(24 * 3600); +/// Even when the file looks unchanged, read it again this often. +const RECHECK: Duration = Duration::from_secs(5); /// What a receipt (or its absence) says; the exit code derives from it and from nothing else. pub enum Outcome { @@ -52,7 +55,8 @@ struct Options { note: String, sets: Vec, no_wait: bool, - timeout: Option, + timeout: Option, + help: bool, last: Option, positional: Vec, } @@ -72,15 +76,20 @@ fn parse(args: &[String]) -> Result { "--note" => options.note = value("--note")?, "--set" => options.sets.push(value("--set")?), "--no-wait" => options.no_wait = true, + "--help" | "-h" => options.help = true, "--timeout" => { let raw = value("--timeout")?; let secs: f64 = raw .parse() .map_err(|_| anyhow!("--timeout wants seconds, got {raw:?}"))?; - if !secs.is_finite() || secs < 0.0 { - bail!("--timeout wants a non-negative number of seconds"); - } - options.timeout = Some(secs); + options.timeout = Some( + Duration::try_from_secs_f64(secs) + .ok() + .filter(|limit| *limit <= MAX_TIMEOUT) + .ok_or_else(|| { + anyhow!("--timeout wants seconds between 0 and {}", MAX_TIMEOUT.as_secs()) + })?, + ); } "--last" => { let raw = value("--last")?; @@ -106,11 +115,11 @@ pub fn run(args: &[String]) -> Result { print!("{}", group_help()); return Ok(0); } - if rest.iter().any(|arg| arg == "--help" || arg == "-h") { + let options = parse(rest)?; + if options.help { print!("{}", if sub == "send" { send_help() } else { group_help() }); return Ok(0); } - let options = parse(rest)?; match sub.as_str() { "send" => send(&options), "wait" => { @@ -132,7 +141,7 @@ fn one_positional<'a>(options: &'a Options, usage: &str) -> Result<&'a str> { } fn timeout(options: &Options) -> Duration { - Duration::from_secs_f64(options.timeout.unwrap_or(DEFAULT_TIMEOUT_SECS)) + options.timeout.unwrap_or(Duration::from_secs(DEFAULT_TIMEOUT_SECS)) } /// The add-on creates its store; naming a path that is not there is a typo, not a request @@ -143,11 +152,17 @@ fn open_store(options: &Options) -> Result { .clone() .or_else(|| std::env::var_os("BROKKR_BLENDER_STORE").map(PathBuf::from)) .ok_or_else(|| anyhow!("no store: pass --store or set BROKKR_BLENDER_STORE"))?; - if !path.is_file() { - bail!("store {} does not exist; the add-on creates it", path.display()); + // The add-on resolves its store against the blend file; ctl cannot know that, so it takes none. + if !path.is_absolute() { + bail!("store {} must be an absolute path", path.display()); } - // The store library stages writes beside the file and fails on a bare file name. - Ok(SingleFileMessagePackBackingStore::new(std::path::absolute(path)?)) + // A staged replace swaps the path itself, which would turn a link into a diverged copy. + let meta = std::fs::symlink_metadata(&path) + .map_err(|_| anyhow!("store {} does not exist; the add-on creates it", path.display()))?; + if meta.file_type().is_symlink() || !meta.is_file() { + bail!("store {} must be the add-on's regular file, not a link", path.display()); + } + Ok(SingleFileMessagePackBackingStore::new(path)) } fn requested_by(options: &Options) -> Result { @@ -197,7 +212,7 @@ fn send(options: &Options) -> Result { let action = one_positional(options, "send [--set key=json]...")?; let requested_by = requested_by(options)?; let mut store = open_store(options)?; - let command_id = uuid::Uuid::new_v4().simple().to_string(); + let command_id = uuid::Uuid::now_v7().simple().to_string(); let intent = build_intent(action, &command_id, &requested_by, &options.note, &options.sets)?; store.push(&CultCacheEnvelope { key: format!("{INTENT_PREFIX}{command_id}"), @@ -229,7 +244,16 @@ fn wait_for_receipt( limit: Duration, ) -> Result { let started = Instant::now(); + let mut gate = ChangeGate::new(store.path()); loop { + if !gate.should_read() { + if started.elapsed() >= limit { + println!("status: timeout"); + return Ok(Outcome::Timeout.code()); + } + thread::sleep(POLL); + continue; + } if let Some(receipt) = read_receipt(store, id)? { print_fields(&receipt); let status = receipt.get("status").and_then(Value::as_str).unwrap_or(""); @@ -243,6 +267,32 @@ fn wait_for_receipt( } } +/// Polling must not hold the store: a read takes the shared lock and an open handle, and on +/// Windows that can make the add-on's replace fail. So the file's stat is polled and the store +/// is read only after it changed (and every RECHECK as a backstop). +pub struct ChangeGate { + path: PathBuf, + seen: Option<(u64, Option)>, + last_read: Option, +} + +impl ChangeGate { + pub fn new(path: &std::path::Path) -> Self { + Self { path: path.to_path_buf(), seen: None, last_read: None } + } + + pub fn should_read(&mut self) -> bool { + let stamp = std::fs::metadata(&self.path).ok().map(|m| (m.len(), m.modified().ok())); + let stale = self.last_read.is_none_or(|at| at.elapsed() >= RECHECK); + if self.seen.is_none() || stamp != self.seen || stale { + self.seen = stamp; + self.last_read = Some(Instant::now()); + return true; + } + false + } +} + fn receipts(store: &SingleFileMessagePackBackingStore, last: Option) -> Result { let mut found = Vec::new(); for envelope in store.pull_all()? { @@ -578,6 +628,22 @@ mod tests { assert!(build_intent("../x", "abc", "a/b", "", &[]).is_err()); } + #[test] + fn the_gate_reads_first_then_only_after_the_file_changes() { + let dir = std::env::temp_dir().join(format!("brokkr-gate-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("s.ccmp"); + std::fs::write(&file, b"one").unwrap(); + let mut gate = ChangeGate::new(&file); + assert!(gate.should_read()); + assert!(!gate.should_read()); + assert!(!gate.should_read()); + std::fs::write(&file, b"three").unwrap(); + assert!(gate.should_read()); + assert!(!gate.should_read()); + std::fs::remove_dir_all(&dir).unwrap(); + } + #[test] fn statuses_map_to_exit_codes() { for (status, code) in [("accepted", 0), ("denied", 2), ("failed", 2), ("stopped", 3), ("weird", 2)] { diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs index a9cee07..a6e2ced 100644 --- a/brokkr-ctl/tests/cli.rs +++ b/brokkr-ctl/tests/cli.rs @@ -152,3 +152,171 @@ fn send_help_lists_the_actions() { assert!(text.contains(action), "{action}"); } } + +fn envelope_at(schema: &str, key: &str, payload: &Value) -> CultCacheEnvelope { + envelope(schema, key, payload) +} + +fn push(path: &Path, entries: &[CultCacheEnvelope]) { + let mut store = SingleFileMessagePackBackingStore::new(path); + for entry in entries { + store.push(entry).unwrap(); + } +} + +#[test] +fn intents_sent_in_order_sort_in_send_order() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("seed", "accepted")]); + let mut sent = Vec::new(); + for _ in 0..8 { + let output = ctl(&path, &["send", "createObject", "--agent", "hands", "--no-wait"], Some("nibu")); + assert_eq!(output.status.code(), Some(0)); + sent.push(format!("blender/commands/{}", stdout(&output).trim().strip_prefix("commandId: ").unwrap())); + } + let mut sorted = sent.clone(); + sorted.sort(); + assert_eq!(sent, sorted, "the add-on drains by sorted key"); +} + +#[test] +fn an_absurd_timeout_is_a_usage_error_not_a_panic() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("a", "accepted")]); + for value in ["1e300", "inf", "nan", "-1", "abc"] { + let output = ctl(&path, &["wait", "x", "--timeout", value], None); + assert_eq!(output.status.code(), Some(1), "{value}"); + } +} + +#[test] +fn help_words_as_option_values_do_not_swallow_the_command() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("a", "accepted")]); + let output = ctl( + &path, + &["send", "createObject", "--note", "-h", "--agent", "--help", "--no-wait"], + Some("nibu"), + ); + assert_eq!(output.status.code(), Some(0), "{}", String::from_utf8_lossy(&output.stderr)); + let id = stdout(&output).trim().strip_prefix("commandId: ").unwrap().to_string(); + let found = SingleFileMessagePackBackingStore::new(&path).pull_all().unwrap(); + let intent = found.iter().find(|e| e.key == format!("blender/commands/{id}")).unwrap(); + let payload: Value = serde_json::from_slice(&intent.payload).unwrap(); + assert_eq!(payload["note"], "-h"); + assert_eq!(payload["requestedBy"], "nibu/--help"); + // a real help flag still prints help and sends nothing + let help = ctl(&path, &["send", "createObject", "--help"], Some("nibu")); + assert_eq!(help.status.code(), Some(0)); + assert!(stdout(&help).contains("actions:")); +} + +#[test] +fn a_relative_store_path_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("a", "accepted")]); + let output = Command::new(env!("CARGO_BIN_EXE_brokkr-ctl")) + .current_dir(dir.path()) + .args(["blender", "receipts", "--store", path.file_name().unwrap().to_str().unwrap()]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&output.stderr).contains("absolute")); +} + +#[test] +fn a_symlinked_store_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("a", "accepted")]); + let link = dir.path().join("link.ccmp"); + #[cfg(windows)] + let made = std::os::windows::fs::symlink_file(&path, &link); + #[cfg(unix)] + let made = std::os::unix::fs::symlink(&path, &link); + if made.is_err() { + eprintln!("skipped: no symlink privilege"); + return; + } + assert_eq!(ctl(&link, &["receipts"], None).status.code(), Some(1)); +} + +#[test] +fn receipts_only_come_from_the_receipt_keys_and_type() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("real", "accepted")]); + let fake = json!({"commandId": "fake", "status": "accepted"}); + push( + &path, + &[ + envelope_at(RECEIPT, "elsewhere/fake", &fake), + envelope_at(INTENT, "blender/receipts/wrongtype", &fake), + ], + ); + let listed = stdout(&ctl(&path, &["receipts"], None)); + assert!(listed.contains("commandId: real")); + assert!(!listed.contains("fake"), "{listed}"); + let waited = ctl(&path, &["wait", "wrongtype", "--timeout", "0.3"], None); + assert_eq!(waited.status.code(), Some(4)); +} + +#[test] +fn receipts_sort_by_observed_time_not_by_key() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[]); + push( + &path, + &[ + envelope_at(RECEIPT, "blender/receipts/a", &json!({"commandId": "a", "observedAt": "2026-11-27T10:00:02+00:00"})), + envelope_at(RECEIPT, "blender/receipts/b", &json!({"commandId": "b", "observedAt": "2026-11-27T10:00:01+00:00"})), + ], + ); + let text = stdout(&ctl(&path, &["receipts"], None)); + assert!(text.find("commandId: b").unwrap() < text.find("commandId: a").unwrap(), "{text}"); +} + +#[test] +fn status_prints_the_snapshot_summary() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[]); + let snapshot = json!({"mode": "OBJECT", "activeScene": "Scene", "objectCount": 3, "selectedObjectNames": ["Cube"], "sink": {"enabled": true}}); + push(&path, &[envelope_at("brokkr.blender.host_snapshot.v0", "blender/host/current", &snapshot)]); + let output = ctl(&path, &["status"], None); + assert_eq!(output.status.code(), Some(0)); + let text = stdout(&output); + for line in ["mode: OBJECT", "activeScene: Scene", "objectCount: 3", "selectedObjectNames: [\"Cube\"]", "sink: {\"enabled\":true}"] { + assert!(text.contains(line), "{line} in {text}"); + } +} + +/// A pin, not a copy: every action the add-on dispatches is in `send --help`, and every help field +/// name is a string the add-on source mentions. The add-on has no machine-readable action table. +#[test] +fn help_names_every_dispatched_action_and_only_fields_the_addon_mentions() { + let addon = Path::new(env!("CARGO_MANIFEST_DIR")).join("../surfaces/blender/brokkr_bridge"); + let source: String = ["blender_target.py", "node_actions.py", "scene_actions.py"] + .iter() + .map(|file| std::fs::read_to_string(addon.join(file)).unwrap()) + .collect(); + let help = stdout( + &Command::new(env!("CARGO_BIN_EXE_brokkr-ctl")).args(["blender", "send", "--help"]).output().unwrap(), + ); + let mut dispatched: Vec = source + .lines() + .filter_map(|line| line.trim().strip_prefix("if action == \"")) + .filter_map(|rest| rest.split('"').next()) + .map(String::from) + .collect(); + let actions_line = source.lines().find(|l| l.contains("ACTIONS = (\"")).unwrap(); + dispatched.extend(actions_line.split('"').skip(1).step_by(2).map(String::from)); + assert!(dispatched.len() >= 20, "{dispatched:?}"); + let listed: Vec<&str> = help.lines().filter_map(|l| l.strip_prefix(" ")).filter(|l| !l.starts_with(' ')).collect(); + for action in &dispatched { + assert!(listed.contains(&action.as_str()), "help lacks {action}"); + } + for action in &listed { + assert!(dispatched.iter().any(|d| d == action) || *action == "actions:", "help lists unknown {action}"); + } + for field in help.lines().filter_map(|l| l.strip_prefix(" ")).filter_map(|l| l.split(':').next()) { + assert!(source.contains(&format!("\"{field}\"")), "add-on never mentions {field}"); + } +} From 0f4ab2d0d95b3beca52c4c38858f1ce0aeb80edb Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 20:08:02 +0100 Subject: [PATCH 17/63] brokkr-ctl on MessagePack payloads: reads through cultcache_rs::decode_payload, one MessagePack value per write, tests off JSON Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 12 ++++++++++++ brokkr-ctl/Cargo.toml | 1 + brokkr-ctl/src/blender.rs | 6 +++--- brokkr-ctl/tests/cli.rs | 17 ++++++++++++++--- 4 files changed, 30 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index dabf833..f01e20a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -47,6 +47,18 @@ dependencies = [ "generic-array", ] +[[package]] +name = "brokkr-ctl" +version = "0.1.0" +dependencies = [ + "anyhow", + "cultcache-rs", + "rmp-serde", + "serde_json", + "tempfile", + "uuid", +] + [[package]] name = "brokkr-daemon" version = "0.1.0" diff --git a/brokkr-ctl/Cargo.toml b/brokkr-ctl/Cargo.toml index ce74ab3..4470cd6 100644 --- a/brokkr-ctl/Cargo.toml +++ b/brokkr-ctl/Cargo.toml @@ -7,6 +7,7 @@ publish = false [dependencies] anyhow = "1" cultcache-rs = { workspace = true } +rmp-serde = "1.3" serde_json = "1" uuid = { version = "1", features = ["v7"] } diff --git a/brokkr-ctl/src/blender.rs b/brokkr-ctl/src/blender.rs index c35148b..c342e91 100644 --- a/brokkr-ctl/src/blender.rs +++ b/brokkr-ctl/src/blender.rs @@ -217,7 +217,7 @@ fn send(options: &Options) -> Result { store.push(&CultCacheEnvelope { key: format!("{INTENT_PREFIX}{command_id}"), r#type: INTENT_SCHEMA.to_string(), - payload: serde_json::to_vec(&intent)?, + payload: rmp_serde::to_vec(&intent)?, stored_at: iso_now(), schema_id: Some(INTENT_SCHEMA.to_string()), })?; @@ -343,8 +343,8 @@ fn status(store: &SingleFileMessagePackBackingStore) -> Result { } fn decode(envelope: &CultCacheEnvelope) -> Result { - serde_json::from_slice(&envelope.payload) - .with_context(|| format!("{} is not a JSON map payload", envelope.key)) + cultcache_rs::decode_payload::(&envelope.payload) + .with_context(|| format!("{} is not one MessagePack value", envelope.key)) } fn print_fields(value: &Value) { diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs index a6e2ced..072ae2a 100644 --- a/brokkr-ctl/tests/cli.rs +++ b/brokkr-ctl/tests/cli.rs @@ -12,7 +12,7 @@ fn envelope(schema: &str, key: &str, payload: &Value) -> CultCacheEnvelope { CultCacheEnvelope { key: key.to_string(), r#type: schema.to_string(), - payload: serde_json::to_vec(payload).unwrap(), + payload: rmp_serde::to_vec(payload).unwrap(), stored_at: "2026-11-27T00:00:00.000000+00:00".to_string(), schema_id: Some(schema.to_string()), } @@ -71,7 +71,7 @@ fn send_writes_a_pullable_intent() { .expect("intent key"); assert_eq!(intent.r#type, INTENT); assert_eq!(intent.schema_id.as_deref(), Some(INTENT)); - let payload: Value = serde_json::from_slice(&intent.payload).unwrap(); + let payload: Value = cultcache_rs::decode_payload(&intent.payload).unwrap(); assert_eq!( payload, json!({"schema": INTENT, "commandId": id, "action": "createObject", "requestedBy": "nibu/hands", @@ -202,7 +202,7 @@ fn help_words_as_option_values_do_not_swallow_the_command() { let id = stdout(&output).trim().strip_prefix("commandId: ").unwrap().to_string(); let found = SingleFileMessagePackBackingStore::new(&path).pull_all().unwrap(); let intent = found.iter().find(|e| e.key == format!("blender/commands/{id}")).unwrap(); - let payload: Value = serde_json::from_slice(&intent.payload).unwrap(); + let payload: Value = cultcache_rs::decode_payload(&intent.payload).unwrap(); assert_eq!(payload["note"], "-h"); assert_eq!(payload["requestedBy"], "nibu/--help"); // a real help flag still prints help and sends nothing @@ -320,3 +320,14 @@ fn help_names_every_dispatched_action_and_only_fields_the_addon_mentions() { assert!(source.contains(&format!("\"{field}\"")), "add-on never mentions {field}"); } } + +#[test] +fn a_json_payload_is_refused_not_guessed() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[]); + let mut json_receipt = envelope(RECEIPT, "blender/receipts/j", &json!({"commandId": "j", "status": "accepted"})); + json_receipt.payload = serde_json::to_vec(&json!({"commandId": "j", "status": "accepted"})).unwrap(); + push(&path, &[json_receipt]); + let output = ctl(&path, &["wait", "j", "--timeout", "1"], None); + assert_eq!(output.status.code(), Some(1)); +} From 741e186c5a643b600c563d21eaf9a7d92b6fdb54 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 20:30:20 +0100 Subject: [PATCH 18/63] Blender: cut the debug-mirror JSON intent door; one admission shape fix Intents now enter only through the node (brokkr-ctl, a served peer, the sync organ). _import_debug_command_files, the debug-root glob in purge_command_intents and start_server's debug-root parameter are deleted; Debug Export Root stays export-only. Also live-2-lows: COMMAND_ID_SHAPE and REQUESTED_BY_SHAPE use fullmatch (a trailing newline passed), and _load_cultmesh's own-package set is pinned. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 2 +- docs/live-collab-target.md | 4 +- surfaces/blender/brokkr_bridge/__init__.py | 3 +- .../blender/brokkr_bridge/blender_target.py | 32 +++----- .../blender/brokkr_bridge/server_guard.py | 10 +-- surfaces/blender/docs/install.md | 19 +++-- .../blender/tests/live/agent_turn_queue.py | 13 +++- surfaces/blender/tests/test_agent_turn.py | 38 ++++++++++ surfaces/blender/tests/test_server_guard.py | 76 +++++++------------ 9 files changed, 101 insertions(+), 96 deletions(-) diff --git a/README.md b/README.md index c42f6ea..e0be8d0 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ broker. - `surfaces/unity/Packages/com.gamecult.brokkr`: Unity editor package scaffold. - `surfaces/blender/brokkr_bridge`: Blender add-on target backed by - CultLib's Python CultMesh node/server, with optional debug export/import + CultLib's Python CultMesh node/server, with an optional debug export probes. - `brokkr-command`: .NET CLI that writes one Unity command intent through the project's directory store and reports the editor's receipt (`docs/provider-contract.md`). diff --git a/docs/live-collab-target.md b/docs/live-collab-target.md index aee7181..fcfedaa 100644 --- a/docs/live-collab-target.md +++ b/docs/live-collab-target.md @@ -236,8 +236,8 @@ are the primitive for the push. collections (an edit buffer over the `.cc`); the stdin dump (a pipe, not state). - **Forbidden writers.** `execute_command` called around the primitive; operators run with undo on inside an agent action; unpushed agent writes; `ed.undo`/`ed.redo` from - add-on code; any agent-sent Python; the debug-mirror JSON import as a door for intents - (`blender_target.py` `_import_debug_command_files`); `brokkr-ctl` deciding anything; + add-on code; any agent-sent Python; any reader that turns a file under + the debug-mirror root into an intent (removed in cut-live-1); `brokkr-ctl` deciding anything; `ship_cc.py`'s envelope writes and any other direct `.cc` writer; `layout_revision` as a revision. - **Shared paths.** brokkr-ctl intents, panel buttons that act on the scene, sync-organ diff --git a/surfaces/blender/brokkr_bridge/__init__.py b/surfaces/blender/brokkr_bridge/__init__.py index e2bcbe8..8a81707 100644 --- a/surfaces/blender/brokkr_bridge/__init__.py +++ b/surfaces/blender/brokkr_bridge/__init__.py @@ -58,7 +58,7 @@ class BrokkrPreferences(bpy.types.AddonPreferences): name="Debug Export Root", subtype="DIR_PATH", default=DEFAULT_DEBUG_MIRROR_ROOT, - description="Optional JSON debug export/import root; CultMesh remains the mirror owner", + description="Optional JSON debug export root (export only); CultMesh remains the mirror owner", ) import_dir: bpy.props.StringProperty( @@ -476,7 +476,6 @@ class BROKKR_OT_start_server(bpy.types.Operator): prefs.serve_port, prefs.max_snapshot_documents, prefs.max_snapshot_bytes, - prefs.debug_mirror_root, prefs.allow_non_loopback, prefs.require_session_token, ) diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 3ed2dcf..8684e8e 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -109,11 +109,11 @@ class BrokkrBlenderTarget: self._server: Any | None = None self._guard: SessionGuard | None = None self._cultmesh_module: str = "" - self._debug_mirror_root: str = "" self.import_dir: str = "" self.output_dir: str = "" self.nodes = na.NodeActions(bpy_module) self.agent_turn = False # true only inside run_intent + self._wrote = True # run_intent: false when an accepted action changed nothing self._receipted: set[str] = set() def configure_action_dirs(self, import_dir: str, output_dir: str) -> None: @@ -150,9 +150,6 @@ class BrokkrBlenderTarget: debug_mirror_root: str = "", ) -> list[dict[str, Any]]: node, documents = self._open_node(cache_path, cultlib_py_src) - if debug_mirror_root: - self._import_debug_command_files(node, documents["command_intent"], debug_mirror_root) - snapshot = node.database.snapshot() commands = snapshot.get(COMMAND_INTENT_SCHEMA, {}) receipts: list[dict[str, Any]] = [] @@ -365,7 +362,6 @@ class BrokkrBlenderTarget: port: int, max_snapshot_documents: int, max_snapshot_bytes: int, - debug_mirror_root: str = "", allow_non_loopback: bool = False, require_token: bool = False, ) -> dict[str, Any]: @@ -391,8 +387,7 @@ class BrokkrBlenderTarget: self.stop_server() self._cultmesh_module = "" - self._debug_mirror_root = self.resolve_debug_mirror_root(debug_mirror_root) if debug_mirror_root else "" - purge_command_intents(node, documents["command_intent"], COMMAND_INTENT_SCHEMA, self._debug_mirror_root) + purge_command_intents(node, documents["command_intent"], COMMAND_INTENT_SCHEMA) cultmesh, _cultcache = _load_cultmesh(cultlib_py_src) self._cultmesh_module = str(getattr(cultmesh, "__file__", "") or "") verse_catalog = cultmesh.CultMesh.create_verse_catalog() @@ -463,7 +458,7 @@ class BrokkrBlenderTarget: finally: try: if was_running and self._node is not None: - purge_command_intents(self._node, self._documents["command_intent"], COMMAND_INTENT_SCHEMA, self._debug_mirror_root) + purge_command_intents(self._node, self._documents["command_intent"], COMMAND_INTENT_SCHEMA) finally: self._server = None self._server_key = None @@ -535,7 +530,7 @@ class BrokkrBlenderTarget: denial = "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'." elif command_id in self._receipted: denial = f"commandId {command_id!r} was already receipted; ids are single-use." - elif not isinstance(requested_by, str) or not REQUESTED_BY_SHAPE.match(requested_by): + elif not isinstance(requested_by, str) or not REQUESTED_BY_SHAPE.fullmatch(requested_by): denial = "Intent has no requestedBy of the form '/'." elif action not in MUTATING_ACTIONS and action not in READ_ACTIONS and action not in na.NodeActions.ACTIONS: denial = f"Unsupported Blender command action: {action}" @@ -550,11 +545,12 @@ class BrokkrBlenderTarget: label = f"Brokkr {requested_by}: {action} {command_id[:8]}" push = action not in READ_ACTIONS and action not in NO_SCENE_CHANGE_ACTIONS self.agent_turn = True + self._wrote = True try: try: receipt = self._dispatch(context, command) - if receipt["status"] != "accepted": - push = False # returned a refusal: it wrote nothing + if receipt["status"] != "accepted" or not self._wrote: + push = False # a refusal, or an accepted no-op: it wrote nothing except sa.ActionRefused as error: # raised before any write: nothing to push receipt, push = self._receipt(command, "failed", str(error), ""), False except Exception as error: # a partial write is one undoable step, not part of her next action @@ -621,6 +617,7 @@ class BrokkrBlenderTarget: return self._render_still(context, command) if action in na.NodeActions.ACTIONS: message, name = self.nodes.execute(action, command) + self._wrote = self.nodes.changed return self._receipt(command, "accepted", message, name) return self._receipt(command, "failed", f"Unsupported Blender command action: {action}", "") @@ -1136,17 +1133,6 @@ class BrokkrBlenderTarget: self._documents = documents return node, documents - def _import_debug_command_files(self, node: Any, command_document: Any, debug_mirror_root: str) -> None: - commands_root = Path(self.resolve_debug_mirror_root(debug_mirror_root)) / "blender" / "commands" - for command_path in sorted(commands_root.glob("*.json")): - with command_path.open("r", encoding="utf-8") as handle: - command = json.load(handle) - command_id = command.get("commandId") or command_path.stem - command["schema"] = command.get("schema") or COMMAND_INTENT_SCHEMA - command["commandId"] = command_id - node.database.put(command_document, f"blender/commands/{command_id}", command) - command_path.unlink(missing_ok=True) - def _write_debug_document(self, debug_mirror_root: str, relative_path: str, document: dict[str, Any]) -> None: path = Path(self.resolve_debug_mirror_root(debug_mirror_root)) / relative_path path.parent.mkdir(parents=True, exist_ok=True) @@ -1272,7 +1258,7 @@ def _to_list(value: Any) -> list[float]: def _valid_command_id(value: Any) -> bool: - return isinstance(value, str) and COMMAND_ID_SHAPE.match(value) is not None + return isinstance(value, str) and COMMAND_ID_SHAPE.fullmatch(value) is not None def _vector(value: Any, size: int, fallback: Any) -> tuple[float, ...]: diff --git a/surfaces/blender/brokkr_bridge/server_guard.py b/surfaces/blender/brokkr_bridge/server_guard.py index 0e9d111..0dbba80 100644 --- a/surfaces/blender/brokkr_bridge/server_guard.py +++ b/surfaces/blender/brokkr_bridge/server_guard.py @@ -12,7 +12,6 @@ from __future__ import annotations import hmac import ipaddress import secrets -from pathlib import Path from typing import Any PUT_SCHEMA_VERSIONS = ("cultnet.document_put_raw.v0", "cultnet.document_delete.v0") @@ -91,17 +90,12 @@ def guarded_server_class(base: type, guard: SessionGuard) -> type: return GuardedServer -def purge_command_intents(node: Any, command_document: Any, command_schema: str, debug_mirror_root: str) -> int: - """Delete every queued command intent from the node and every command JSON under - /blender/commands. Returns how many were removed.""" +def purge_command_intents(node: Any, command_document: Any, command_schema: str) -> int: + """Delete every queued command intent from the node. Returns how many were removed.""" removed = 0 if node is not None: node.database.pull() for key in list(node.database.snapshot().get(command_schema, {})): node.database.delete(command_document, key) removed += 1 - if debug_mirror_root: - for path in (Path(debug_mirror_root) / "blender" / "commands").glob("*.json"): - path.unlink(missing_ok=True) - removed += 1 return removed diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 29b1242..f29c195 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -65,8 +65,7 @@ after `Start Server`. Always on: - `Start Server` and `Stop Server` purge queued command intents: every - `brokkr.blender.command_intent.v0` record in the node and every - `blender/commands/*.json` under `Debug Export Root`. Intents queued before a + `brokkr.blender.command_intent.v0` record in the node. Intents queued before a start never run under the new session. - After `Start Server` the panel shows the bind address, port and the file `cultmesh_py` was actually loaded from (its `__file__`, not the preference). @@ -96,9 +95,11 @@ 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 probe files under -`.brokkr/blender-editor-debug`, but those files are debug/import glue. CultMesh -owns the mirror state. +`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 @@ -106,11 +107,13 @@ owns the mirror state. 2. Open `View3D > Sidebar > Brokkr`. 3. Click `Capture Snapshot`. 4. Inspect `.brokkr/blender-editor.ccmp`. -5. Drop a command intent JSON file into - `.brokkr/blender-editor-debug/blender/commands/{commandId}.json`. +5. Send an intent into the node: + `brokkr-ctl blender send createObject --set objectType='"EMPTY"' --agent --no-wait` + (needs `EUREKA_INSTANCE` and `--store `). 6. Click `Drain Commands`, or enable `Auto Drain Commands` to poll command intents once per second while the add-on is loaded. -7. Inspect `.brokkr/blender-editor.ccmp` or the optional debug export +7. Read the receipt with `brokkr-ctl blender wait --store `, or + inspect `.brokkr/blender-editor.ccmp` or the optional debug export at `.brokkr/blender-editor-debug/blender/receipts/{commandId}.json`. 8. Click `Start Server`. 9. Use the reported `cultnet://host:port` endpoint from a CultMesh/CultNet diff --git a/surfaces/blender/tests/live/agent_turn_queue.py b/surfaces/blender/tests/live/agent_turn_queue.py index 18fc00a..f2b2d3c 100644 --- a/surfaces/blender/tests/live/agent_turn_queue.py +++ b/surfaces/blender/tests/live/agent_turn_queue.py @@ -10,7 +10,8 @@ are drained by the add-on's own 1 s timer as one undo step each, with write-once leave unset to prove a stock install> blender --factory-startup --python agent_turn_queue.py -- -Intents are put into the node database as brokkr-ctl does (no debug-mirror files). Writes +Intents are put into the node database as brokkr-ctl does; a command JSON dropped under the debug +root is never an intent. Writes .result.json, then quits Blender. Undo is read only here, by this driver. """ import importlib @@ -43,7 +44,7 @@ except ImportError: prefs = bpy.context.preferences.addons[MODULE].preferences CACHE = str(SCRATCH / "queue.ccmp") prefs.cultmesh_cache_path = CACHE -prefs.debug_mirror_root = "" # the debug-mirror door is not used here +prefs.debug_mirror_root = str(SCRATCH / "debug") # export only: q1 drops a command file there and it must stay inert prefs.output_dir = str(SCRATCH / "out") prefs.import_dir = "" prefs.auto_drain_commands = True @@ -130,6 +131,10 @@ def drained(*ids): def q1(): push("driver baseline") + door = SCRATCH / "debug" / "blender" / "commands" + door.mkdir(parents=True, exist_ok=True) + (door / "door-0001.json").write_text(json.dumps( + {"commandId": "door-0001", "requestedBy": "nibu/hands", "action": "createObject", "objectType": "MESH", "name": "QDoor"})) queue("aaaaaaaa-0001", action="createObject", objectType="MESH", name="QCube", location=[4, 0, 0], requestedBy="nibu/hands", note="queue test") @@ -141,6 +146,10 @@ def q1_check(): check("queue: createObject drained by the add-on timer, accepted, labelled, attributed", r and r["status"] == "accepted" and r["undoLabel"] == "Brokkr nibu/hands: createObject aaaaaaaa" and r["requestedBy"] == "nibu/hands" and r["note"] == "queue test" and "QCube" in names(), r) + check("queue: a command JSON under the debug root is inert (kept, never run, never receipted); the receipt export still lands", + (SCRATCH / "debug" / "blender" / "commands" / "door-0001.json").exists() and "QDoor" not in names() + and receipt("door-0001") is None and (SCRATCH / "debug" / "blender" / "receipts" / "aaaaaaaa-0001.json").exists(), + names()) check("queue: intent removed from the queue after the drain", "blender/commands/aaaaaaaa-0001" not in pending(), list(pending())) diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index 69e83fc..02706de 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -164,6 +164,44 @@ class AgentTurnTests(unittest.TestCase): self.assertEqual(self.bpy.created, []) self.assertEqual(self.bpy.undo.pushes, []) + def test_trailing_newline_does_not_pass_the_id_shapes(self): + self.assertFalse(bt._valid_command_id("okid\n")) + receipt = self.run_action(action="createObject", objectType="EMPTY", commandId="okid\n") + self.assertEqual(receipt["status"], "denied") + receipt = self.run_action(action="createObject", objectType="EMPTY", requestedBy="nibu/hands\n") + self.assertEqual(receipt["status"], "denied") + self.assertEqual(self.bpy.created, []) + + def test_load_cultmesh_pins_its_own_package_set(self): + # an unrelated module named like a CultLib package is a missing dependency, not "CultLib is absent" + self.assertEqual(bt.CULTLIB_PY_PACKAGES, ("cultcache-py", "cultnet-py", "cultmesh-py")) + root = Path(tempfile.mkdtemp()) + self.addCleanup(lambda: __import__("shutil").rmtree(root, ignore_errors=True)) + src = root / "cultmesh-py" / "src" / "cultmesh_py" + src.mkdir(parents=True) + (src / "__init__.py").write_text("import cultnet_py") # an own package that is absent here + saved = {k: sys.modules.pop(k) for k in ("cultmesh_py", "cultcache_py", "cultnet_py") if k in sys.modules} + saved_path = list(sys.path) + self.addCleanup(lambda: (sys.modules.update(saved), sys.path.__setitem__(slice(None), saved_path))) + with self.assertRaises(RuntimeError) as caught: + bt._load_cultmesh(str(root)) + self.assertIn("requires CultLib's Python packages", str(caught.exception)) + + def test_debug_command_file_is_not_executed(self): + with tempfile.TemporaryDirectory() as tmp: + commands = Path(tmp) / "blender" / "commands" + commands.mkdir(parents=True) + door = commands / "door-1.json" + door.write_text('{"commandId": "door-1", "requestedBy": "nibu/hands", "action": "createObject", "objectType": "EMPTY"}') + node = FakeNode({}) + docs = {"command_intent": "i", "command_receipt": "r"} + with unittest.mock.patch.object(self.target, "_open_node", return_value=(node, docs)): + receipts = self.target.drain_commands(self.context, "cache", "src", tmp) + self.assertEqual(receipts, []) + self.assertEqual(node.puts, []) + self.assertEqual(self.bpy.created, []) + self.assertTrue(door.exists()) + def test_load_cultmesh_names_the_missing_module(self): root = Path(tempfile.mkdtemp()) self.addCleanup(lambda: __import__("shutil").rmtree(root, ignore_errors=True)) diff --git a/surfaces/blender/tests/test_server_guard.py b/surfaces/blender/tests/test_server_guard.py index 439cfe0..d726162 100644 --- a/surfaces/blender/tests/test_server_guard.py +++ b/surfaces/blender/tests/test_server_guard.py @@ -144,48 +144,29 @@ class FakeNode: class PurgeTests(unittest.TestCase): - def make_debug_root(self, tmp): - commands = Path(tmp) / "blender" / "commands" - commands.mkdir(parents=True) - (commands / "a.json").write_text("{}") - (commands / "b.json").write_text("{}") - (commands / "note.txt").write_text("keep") - receipts = Path(tmp) / "blender" / "receipts" - receipts.mkdir() - (receipts / "r.json").write_text("{}") - return commands, receipts + def test_purge_removes_queued_intents(self): + node = FakeNode(["c1", "c2"]) + removed = sg.purge_command_intents(node, "DOC", bt.COMMAND_INTENT_SCHEMA) + self.assertEqual(removed, 2) + self.assertEqual(node.database.deleted, [("DOC", "c1"), ("DOC", "c2")]) - def test_purge_removes_queued_intents_and_debug_command_files_only(self): - with tempfile.TemporaryDirectory() as tmp: - commands, receipts = self.make_debug_root(tmp) - node = FakeNode(["c1", "c2"]) - removed = sg.purge_command_intents(node, "DOC", bt.COMMAND_INTENT_SCHEMA, tmp) - self.assertEqual(removed, 4) - self.assertEqual(node.database.deleted, [("DOC", "c1"), ("DOC", "c2")]) - self.assertEqual(sorted(p.name for p in commands.iterdir()), ["note.txt"]) - self.assertTrue((receipts / "r.json").exists()) - - def test_purge_without_a_debug_root_or_node_is_quiet(self): - self.assertEqual(sg.purge_command_intents(None, "DOC", bt.COMMAND_INTENT_SCHEMA, ""), 0) + def test_purge_without_a_node_is_quiet(self): + self.assertEqual(sg.purge_command_intents(None, "DOC", bt.COMMAND_INTENT_SCHEMA), 0) def test_stop_server_purges_and_revokes(self): - with tempfile.TemporaryDirectory() as tmp: - commands, _ = self.make_debug_root(tmp) - target = bt.BrokkrBlenderTarget(types.SimpleNamespace()) - stopped = [] - target._server = types.SimpleNamespace(stop=lambda: stopped.append(True)) - target._guard = sg.SessionGuard() - guard = target._guard - old = guard.token - target._node = FakeNode(["c1"]) - target._documents = {"command_intent": "DOC"} - target._debug_mirror_root = tmp - target.stop_server() - self.assertEqual(stopped, [True]) - self.assertEqual(target._node.database.keys, []) - self.assertEqual(sorted(p.name for p in commands.iterdir()), ["note.txt"]) - self.assertFalse(guard.admits({sg.TOKEN_FIELD: old})) - self.assertEqual(target.session_token, "") + target = bt.BrokkrBlenderTarget(types.SimpleNamespace()) + stopped = [] + target._server = types.SimpleNamespace(stop=lambda: stopped.append(True)) + target._guard = sg.SessionGuard() + guard = target._guard + old = guard.token + target._node = FakeNode(["c1"]) + target._documents = {"command_intent": "DOC"} + target.stop_server() + self.assertEqual(stopped, [True]) + self.assertEqual(target._node.database.keys, []) + self.assertFalse(guard.admits({sg.TOKEN_FIELD: old})) + self.assertEqual(target.session_token, "") def test_stop_server_revokes_and_purges_even_when_the_socket_stop_raises(self): target = bt.BrokkrBlenderTarget(types.SimpleNamespace()) @@ -229,24 +210,19 @@ class RealServerTests(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() self.addCleanup(self.tmp.cleanup) - self.debug = str(Path(self.tmp.name) / "debug") - commands = Path(self.debug) / "blender" / "commands" - commands.mkdir(parents=True) - (commands / "stale.json").write_text("{}") self.cache = str(Path(self.tmp.name) / "node.ccmp") self.target = bt.BrokkrBlenderTarget(types.SimpleNamespace( path=types.SimpleNamespace(abspath=lambda p: p))) self.addCleanup(self.target.stop_server) def start(self, **kwargs): - return self.target.start_server(self.cache, PACKAGES, "127.0.0.1", 0, 100, 1 << 20, self.debug, **kwargs) + return self.target.start_server(self.cache, PACKAGES, "127.0.0.1", 0, 100, 1 << 20, **kwargs) - def test_default_start_has_no_token_and_purges_stale_debug_commands(self): + def test_default_start_has_no_token(self): status = self.start() self.assertTrue(status["running"]) self.assertFalse(status["tokenRequired"]) self.assertEqual(self.target.session_token, "") - self.assertEqual(list((Path(self.debug) / "blender" / "commands").glob("*.json")), []) self.assertTrue(status["cultmeshModule"].endswith("__init__.py")) self.assertIn("cultmesh_py", status["cultmeshModule"]) self.assertTrue(status["loopback"]) @@ -311,17 +287,17 @@ class RealServerTests(unittest.TestCase): self.assertEqual(self.queued(self.cache), []) def test_allow_true_goes_through_start_server_and_unticking_stops_it(self): - status = self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, self.debug, + status = self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, allow_non_loopback=True) self.assertTrue(status["running"]) self.assertFalse(status["loopback"]) with self.assertRaises(sg.BindRefused): - self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, self.debug, + self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, allow_non_loopback=False) self.assertFalse(self.target.server_status()["running"]) def test_unticking_the_allow_stops_a_running_non_loopback_server(self): - self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, self.debug, + self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, allow_non_loopback=True) self.target.enforce_bind_policy(False) self.assertFalse(self.target.server_status()["running"]) @@ -378,7 +354,7 @@ class RealServerTests(unittest.TestCase): def test_non_loopback_bind_is_refused_before_anything_starts(self): with self.assertRaises(sg.BindRefused): - self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, self.debug) + self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20) self.assertFalse(self.target.server_status()["running"]) From 8f5a660964d92fe9d4611ff0af8dae539db5d7e9 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 20:30:27 +0100 Subject: [PATCH 19/63] Blender: removeNode and removeModifier on an absent target push no undo step NodeActions.changed says whether the last action wrote; run_intent pushes the labelled step only when it did (the run_intent half rode in the previous commit's blender_target.py). Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/brokkr_bridge/node_actions.py | 4 ++++ surfaces/blender/tests/test_node_actions.py | 9 ++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/surfaces/blender/brokkr_bridge/node_actions.py b/surfaces/blender/brokkr_bridge/node_actions.py index 5210b86..aba236d 100644 --- a/surfaces/blender/brokkr_bridge/node_actions.py +++ b/surfaces/blender/brokkr_bridge/node_actions.py @@ -121,8 +121,10 @@ class NodeActions: def __init__(self, bpy_module: Any): self.bpy = bpy_module + self.changed = False # whether the last execute wrote anything: an absent-target removal does not def execute(self, action: str, command: dict[str, Any]) -> tuple[str, str]: + self.changed = True return getattr(self, "_" + action)(command) # tree and node lookup @@ -236,6 +238,7 @@ class NodeActions: raise ActionRefused(f"{node_id!r} is the group's own input/output node and stays.") node = next((n for n in tree.nodes if n.get("brokkr_id") == node_id), None) if node is None: + self.changed = False return f"Node {node_id!r} was already absent.", node_id tree.nodes.remove(node) # Blender drops the node's links with it return "Node removed.", node_id @@ -305,6 +308,7 @@ class NodeActions: raise ActionRefused("modifierName must be a string of at most 255 characters.") modifier = obj.modifiers.get(name) if modifier is None: + self.changed = False return f"Modifier {name!r} was already absent.", obj.name if modifier.type != "NODES": raise ActionRefused(f"{name!r} is not a Geometry Nodes modifier; only those are removed here.") diff --git a/surfaces/blender/tests/test_node_actions.py b/surfaces/blender/tests/test_node_actions.py index eac602f..6aeee39 100644 --- a/surfaces/blender/tests/test_node_actions.py +++ b/surfaces/blender/tests/test_node_actions.py @@ -544,8 +544,11 @@ class NodeActionTests(unittest.TestCase): tree = self.chain() self.accepted(action="removeNode", treeKey="G", id="b") self.assertEqual([n.get("brokkr_id") for n in tree.nodes], ["gin", "gout", "a", "c"]) + pushes = len(self.bpy.undo.pushes) again = self.accepted(action="removeNode", treeKey="G", id="b") self.assertIn("already absent", again["message"]) + self.assertEqual(len(self.bpy.undo.pushes), pushes) # nothing changed: no undo step + self.assertEqual(again["undoLabel"], "") for keep in ("gin", "gout"): self.refused(action="removeNode", treeKey="G", id=keep) self.refused(action="removeNode", treeKey="Nope", id="a") @@ -575,7 +578,11 @@ class NodeActionTests(unittest.TestCase): self.accepted(action="removeModifier", objectName="Host", modifierName="GN") self.assertEqual([m.name for m in host.modifiers], ["Sub"]) self.assertEqual(host.tagged, tags + 1) - self.assertIn("already absent", self.accepted(action="removeModifier", objectName="Host", modifierName="GN")["message"]) + pushes = len(self.bpy.undo.pushes) + again = self.accepted(action="removeModifier", objectName="Host", modifierName="GN") + self.assertIn("already absent", again["message"]) + self.assertEqual(len(self.bpy.undo.pushes), pushes) + self.assertEqual(again["undoLabel"], "") self.refused(action="removeModifier", objectName="Nope", modifierName="GN") for bad in (["x"], "x" * 256, "a\0b", 5): self.refused(action="removeModifier", objectName="Host", modifierName=bad) From 4510dcc45be5fbee8a27883b5237cd4270c88812 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 20:30:28 +0100 Subject: [PATCH 20/63] brokkr-ctl: delete ChangeGate, refuse hard-linked stores, pin the survivors The store lock removed the failure the stat gate compensated, so wait reads each poll. A store with more than one hard link is refused (unix nlink; windows via GetFileInformationByHandle, windows-sys already in the lock). Tests pin the 86400 s cap, the receipt-key prefix and -h as a flag; the help test finds the dispatch table by its own line after live-2 added other *ACTIONS tuples. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 1 + brokkr-ctl/Cargo.toml | 3 ++ brokkr-ctl/src/blender.rs | 79 +++++++++++++-------------------------- brokkr-ctl/tests/cli.rs | 40 +++++++++++++++++++- 4 files changed, 69 insertions(+), 54 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f01e20a..cedd285 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -57,6 +57,7 @@ dependencies = [ "serde_json", "tempfile", "uuid", + "windows-sys 0.61.2", ] [[package]] diff --git a/brokkr-ctl/Cargo.toml b/brokkr-ctl/Cargo.toml index 4470cd6..b74147e 100644 --- a/brokkr-ctl/Cargo.toml +++ b/brokkr-ctl/Cargo.toml @@ -11,5 +11,8 @@ rmp-serde = "1.3" serde_json = "1" uuid = { version = "1", features = ["v7"] } +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_Storage_FileSystem"] } + [dev-dependencies] tempfile = "3" diff --git a/brokkr-ctl/src/blender.rs b/brokkr-ctl/src/blender.rs index c342e91..e2a7a40 100644 --- a/brokkr-ctl/src/blender.rs +++ b/brokkr-ctl/src/blender.rs @@ -18,8 +18,6 @@ const RESERVED: [&str; 5] = ["schema", "commandId", "action", "requestedBy", "no const DEFAULT_TIMEOUT_SECS: u64 = 60; const POLL: Duration = Duration::from_millis(200); const MAX_TIMEOUT: Duration = Duration::from_secs(24 * 3600); -/// Even when the file looks unchanged, read it again this often. -const RECHECK: Duration = Duration::from_secs(5); /// What a receipt (or its absence) says; the exit code derives from it and from nothing else. pub enum Outcome { @@ -162,9 +160,35 @@ fn open_store(options: &Options) -> Result { if meta.file_type().is_symlink() || !meta.is_file() { bail!("store {} must be the add-on's regular file, not a link", path.display()); } + // The same swap would leave a second name on the old bytes. + if link_count(&path)? > 1 { + bail!("store {} has more than one hard link; it must be the add-on's only name for the file", path.display()); + } Ok(SingleFileMessagePackBackingStore::new(path)) } +#[cfg(unix)] +fn link_count(path: &std::path::Path) -> Result { + use std::os::unix::fs::MetadataExt; + Ok(std::fs::metadata(path)?.nlink()) +} + +/// std's `number_of_links` is unstable, so ask the handle. +#[cfg(windows)] +fn link_count(path: &std::path::Path) -> Result { + use std::os::windows::io::AsRawHandle; + use windows_sys::Win32::Storage::FileSystem::{BY_HANDLE_FILE_INFORMATION, GetFileInformationByHandle}; + let file = std::fs::File::open(path)?; + let mut info = std::mem::MaybeUninit::::zeroed(); + // SAFETY: the handle is live for the call and `info` is a writable BY_HANDLE_FILE_INFORMATION. + let ok = unsafe { GetFileInformationByHandle(file.as_raw_handle() as _, info.as_mut_ptr()) }; + if ok == 0 { + return Err(std::io::Error::last_os_error().into()); + } + // SAFETY: the call succeeded, so it filled the struct. + Ok(u64::from(unsafe { info.assume_init() }.nNumberOfLinks)) +} + fn requested_by(options: &Options) -> Result { let instance = std::env::var("EUREKA_INSTANCE").unwrap_or_default(); let agent = options @@ -244,16 +268,7 @@ fn wait_for_receipt( limit: Duration, ) -> Result { let started = Instant::now(); - let mut gate = ChangeGate::new(store.path()); loop { - if !gate.should_read() { - if started.elapsed() >= limit { - println!("status: timeout"); - return Ok(Outcome::Timeout.code()); - } - thread::sleep(POLL); - continue; - } if let Some(receipt) = read_receipt(store, id)? { print_fields(&receipt); let status = receipt.get("status").and_then(Value::as_str).unwrap_or(""); @@ -267,32 +282,6 @@ fn wait_for_receipt( } } -/// Polling must not hold the store: a read takes the shared lock and an open handle, and on -/// Windows that can make the add-on's replace fail. So the file's stat is polled and the store -/// is read only after it changed (and every RECHECK as a backstop). -pub struct ChangeGate { - path: PathBuf, - seen: Option<(u64, Option)>, - last_read: Option, -} - -impl ChangeGate { - pub fn new(path: &std::path::Path) -> Self { - Self { path: path.to_path_buf(), seen: None, last_read: None } - } - - pub fn should_read(&mut self) -> bool { - let stamp = std::fs::metadata(&self.path).ok().map(|m| (m.len(), m.modified().ok())); - let stale = self.last_read.is_none_or(|at| at.elapsed() >= RECHECK); - if self.seen.is_none() || stamp != self.seen || stale { - self.seen = stamp; - self.last_read = Some(Instant::now()); - return true; - } - false - } -} - fn receipts(store: &SingleFileMessagePackBackingStore, last: Option) -> Result { let mut found = Vec::new(); for envelope in store.pull_all()? { @@ -628,22 +617,6 @@ mod tests { assert!(build_intent("../x", "abc", "a/b", "", &[]).is_err()); } - #[test] - fn the_gate_reads_first_then_only_after_the_file_changes() { - let dir = std::env::temp_dir().join(format!("brokkr-gate-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let file = dir.join("s.ccmp"); - std::fs::write(&file, b"one").unwrap(); - let mut gate = ChangeGate::new(&file); - assert!(gate.should_read()); - assert!(!gate.should_read()); - assert!(!gate.should_read()); - std::fs::write(&file, b"three").unwrap(); - assert!(gate.should_read()); - assert!(!gate.should_read()); - std::fs::remove_dir_all(&dir).unwrap(); - } - #[test] fn statuses_map_to_exit_codes() { for (status, code) in [("accepted", 0), ("denied", 2), ("failed", 2), ("stopped", 3), ("weird", 2)] { diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs index 072ae2a..c3df5a6 100644 --- a/brokkr-ctl/tests/cli.rs +++ b/brokkr-ctl/tests/cli.rs @@ -240,6 +240,43 @@ fn a_symlinked_store_is_refused() { assert_eq!(ctl(&link, &["receipts"], None).status.code(), Some(1)); } +#[test] +fn a_hard_linked_store_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("a", "accepted")]); + let link = dir.path().join("second-name.ccmp"); + std::fs::hard_link(&path, &link).unwrap(); + let before = std::fs::read(&path).unwrap(); + for name in [&path, &link] { + let output = ctl(name, &["send", "createObject", "--agent", "hands", "--no-wait"], Some("nibu")); + assert_eq!(output.status.code(), Some(1), "{}", name.display()); + assert!(String::from_utf8_lossy(&output.stderr).contains("hard link")); + } + assert_eq!(std::fs::read(&path).unwrap(), before); +} + +#[test] +fn the_timeout_cap_is_one_day_inclusive() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[]); + // --help returns after parsing, so a legal timeout does not wait + let at_cap = ctl(&path, &["send", "createObject", "--help", "--timeout", "86400"], None); + assert_eq!(at_cap.status.code(), Some(0)); + let over = ctl(&path, &["send", "createObject", "--help", "--timeout", "86400.5"], None); + assert_eq!(over.status.code(), Some(1)); +} + +#[test] +fn short_help_is_a_flag() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[]); + let output = ctl(&path, &["send", "createObject", "-h"], Some("nibu")); + assert_eq!(output.status.code(), Some(0)); + assert!(stdout(&output).contains("actions:")); + let group = ctl(&path, &["receipts", "-h"], None); + assert!(stdout(&group).contains("brokkr-ctl blender:")); +} + #[test] fn receipts_only_come_from_the_receipt_keys_and_type() { let dir = tempfile::tempdir().unwrap(); @@ -250,6 +287,7 @@ fn receipts_only_come_from_the_receipt_keys_and_type() { &[ envelope_at(RECEIPT, "elsewhere/fake", &fake), envelope_at(INTENT, "blender/receipts/wrongtype", &fake), + envelope_at(RECEIPT, "nested/blender/receipts/fake2", &fake), ], ); let listed = stdout(&ctl(&path, &["receipts"], None)); @@ -306,7 +344,7 @@ fn help_names_every_dispatched_action_and_only_fields_the_addon_mentions() { .filter_map(|rest| rest.split('"').next()) .map(String::from) .collect(); - let actions_line = source.lines().find(|l| l.contains("ACTIONS = (\"")).unwrap(); + let actions_line = source.lines().find(|l| l.trim_start().starts_with("ACTIONS = (\"")).unwrap(); dispatched.extend(actions_line.split('"').skip(1).step_by(2).map(String::from)); assert!(dispatched.len() >= 20, "{dispatched:?}"); let listed: Vec<&str> = help.lines().filter_map(|l| l.strip_prefix(" ")).filter(|l| !l.starts_with(' ')).collect(); From c723754ea6a9fe7b79f74cb766f088c179346e96 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 20:36:58 +0100 Subject: [PATCH 21/63] Blender live harness results rerun on the extension build (stock Blender 5.3, no PYLIBS) agent_turn_queue now also drops a command JSON under the debug root and checks it stays inert. Co-Authored-By: Claude Sonnet 5.5 --- .../tests/live/agent_turn_queue.result.json | 42 ++++++++++++------- .../tests/live/agent_turn_undo.result.json | 4 +- 2 files changed, 28 insertions(+), 18 deletions(-) diff --git a/surfaces/blender/tests/live/agent_turn_queue.result.json b/surfaces/blender/tests/live/agent_turn_queue.result.json index 9d8a289..e76bb3f 100644 --- a/surfaces/blender/tests/live/agent_turn_queue.result.json +++ b/surfaces/blender/tests/live/agent_turn_queue.result.json @@ -16,9 +16,19 @@ "requestedBy": "nibu/hands", "note": "queue test", "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa", - "observedAt": "2026-11-27T19:01:35.205337+00:00" + "observedAt": "2026-11-27T19:32:00.583673+00:00" } }, + { + "name": "queue: a command JSON under the debug root is inert (kept, never run, never receipted); the receipt export still lands", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light", + "QCube" + ] + }, { "name": "queue: intent removed from the queue after the drain", "ok": true, @@ -37,7 +47,7 @@ "requestedBy": "nibu/hands", "note": "queue test", "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa", - "observedAt": "2026-11-27T19:01:35.205337+00:00" + "observedAt": "2026-11-27T19:32:00.583673+00:00" } }, { @@ -53,7 +63,7 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:01:37.202231+00:00" + "observedAt": "2026-11-27T19:32:02.587784+00:00" } }, { @@ -69,7 +79,7 @@ "requestedBy": "", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:01:39.207926+00:00" + "observedAt": "2026-11-27T19:32:04.590532+00:00" } }, { @@ -125,7 +135,7 @@ "requestedBy": "nibu/hands", "note": "queue test", "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa", - "observedAt": "2026-11-27T19:01:35.205337+00:00" + "observedAt": "2026-11-27T19:32:00.583673+00:00" }, "q2_original": { "schema": "brokkr.blender.command_receipt.v0", @@ -137,7 +147,7 @@ "requestedBy": "nibu/hands", "note": "queue test", "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa", - "observedAt": "2026-11-27T19:01:35.205337+00:00" + "observedAt": "2026-11-27T19:32:00.583673+00:00" }, "q2_denial": { "schema": "brokkr.blender.command_receipt.v0", @@ -149,7 +159,7 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:01:37.202231+00:00" + "observedAt": "2026-11-27T19:32:02.587784+00:00" }, "q3": { "schema": "brokkr.blender.command_receipt.v0", @@ -161,12 +171,12 @@ "requestedBy": "", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:01:39.207926+00:00" + "observedAt": "2026-11-27T19:32:04.590532+00:00" }, "q6": [ { "schema": "brokkr.blender.command_receipt.v0", - "commandId": "ae0a53d8d0584e54b1ce518cf7e8cf9d", + "commandId": "8fe2e26fece047bcaca1b9938f1a030c", "action": "createObject", "status": "denied", "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-int)", @@ -174,11 +184,11 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:01:43.220315+00:00" + "observedAt": "2026-11-27T19:32:08.599229+00:00" }, { "schema": "brokkr.blender.command_receipt.v0", - "commandId": "f5ce147da5e0466ab0771ac13135f4be", + "commandId": "b1a5c7e22158468bb06f6b500c4fa2a7", "action": "createObject", "status": "denied", "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-list)", @@ -186,7 +196,7 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:01:43.242934+00:00" + "observedAt": "2026-11-27T19:32:08.621069+00:00" } ], "q5": [ @@ -200,7 +210,7 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:01:45.227825+00:00" + "observedAt": "2026-11-27T19:32:10.606424+00:00" }, { "schema": "brokkr.blender.command_receipt.v0", @@ -212,7 +222,7 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:01:45.250025+00:00" + "observedAt": "2026-11-27T19:32:10.629698+00:00" }, { "schema": "brokkr.blender.command_receipt.v0", @@ -224,10 +234,10 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:01:45.281467+00:00" + "observedAt": "2026-11-27T19:32:10.665150+00:00" } ] }, - "msgpack": "F:\\aeth-wt\\brokkr-live-2.res\\extensions\\.local\\lib\\python3.13\\site-packages\\msgpack\\__init__.py", + "msgpack": "F:\\aeth-wt\\brokkr-live-1.e2e\\res\\extensions\\.local\\lib\\python3.13\\site-packages\\msgpack\\__init__.py", "ok": true } \ No newline at end of file diff --git a/surfaces/blender/tests/live/agent_turn_undo.result.json b/surfaces/blender/tests/live/agent_turn_undo.result.json index 5468ce0..0437128 100644 --- a/surfaces/blender/tests/live/agent_turn_undo.result.json +++ b/surfaces/blender/tests/live/agent_turn_undo.result.json @@ -197,7 +197,7 @@ "name": "exportGltf and renderStill accepted with no undoLabel", "ok": true, "detail": [ - "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-a4ak7h0p\\object.glb (3484 bytes).", + "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-_y_dg6ko\\object.glb (3484 bytes).", "Rendered still to object.png." ] }, @@ -270,7 +270,7 @@ "intent": "exportGltf", "status": "accepted", "undoLabel": "", - "message": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-a4ak7h0p\\object.glb (3484 bytes)." + "message": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-_y_dg6ko\\object.glb (3484 bytes)." }, { "intent": "renderStill", From 1f469c47218b8207a6160eda0c3a46011dbcbad9 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 21:04:46 +0100 Subject: [PATCH 22/63] CultLib pins to 9fc4bdda; one pure-Python msgpack wheel, no platform restriction cultcache-rs moves to 9fc4bdda (PR #180: cultcache-py decodes under msgpack's pure-Python fallback). The Windows-only C wheel is replaced by msgpack 1.2.2 repacked deterministically from the installed package; source, version and sha256 are in install.md. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 4 +- Cargo.toml | 2 +- .../brokkr_bridge/blender_manifest.toml | 10 ++-- .../msgpack-1.2.2-cp313-cp313-win_amd64.whl | Bin 72206 -> 0 bytes .../wheels/msgpack-1.2.2-py3-none-any.whl | Bin 0 -> 15448 bytes surfaces/blender/docs/install.md | 23 +++++++--- .../tests/live/agent_turn_undo.result.json | 14 +++--- .../blender/tests/test_extension_wheel.py | 43 ++++++++++++++++++ tools/build-msgpack-wheel.py | 27 +++++++++++ 9 files changed, 100 insertions(+), 23 deletions(-) delete mode 100644 surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-cp313-cp313-win_amd64.whl create mode 100644 surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-py3-none-any.whl create mode 100644 surfaces/blender/tests/test_extension_wheel.py create mode 100644 tools/build-msgpack-wheel.py diff --git a/Cargo.lock b/Cargo.lock index cedd285..1c9d7f7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -136,7 +136,7 @@ dependencies = [ [[package]] name = "cultcache-rs" version = "0.3.1" -source = "git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb#baf4ecf78fae634fafef956d3b85420162c074bb" +source = "git+https://github.com/GameCult/CultLib.git?rev=9fc4bdda6a8620f846b58e89ddf476f4676d3e89#9fc4bdda6a8620f846b58e89ddf476f4676d3e89" dependencies = [ "anyhow", "chrono", @@ -157,7 +157,7 @@ dependencies = [ [[package]] name = "cultcache-rs-derive" version = "0.2.0" -source = "git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb#baf4ecf78fae634fafef956d3b85420162c074bb" +source = "git+https://github.com/GameCult/CultLib.git?rev=9fc4bdda6a8620f846b58e89ddf476f4676d3e89#9fc4bdda6a8620f846b58e89ddf476f4676d3e89" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index c469605..5645f78 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,5 +6,5 @@ members = [ ] [workspace.dependencies] -cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "baf4ecf78fae634fafef956d3b85420162c074bb", package = "cultcache-rs" } +cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "9fc4bdda6a8620f846b58e89ddf476f4676d3e89", package = "cultcache-rs" } diff --git a/surfaces/blender/brokkr_bridge/blender_manifest.toml b/surfaces/blender/brokkr_bridge/blender_manifest.toml index ec5feed..cbdf1d8 100644 --- a/surfaces/blender/brokkr_bridge/blender_manifest.toml +++ b/surfaces/blender/brokkr_bridge/blender_manifest.toml @@ -6,10 +6,8 @@ tagline = "Brokkr command intents, receipts and snapshots over CultMesh" maintainer = "GameCult " type = "add-on" blender_version_min = "5.3.0" -platforms = ["windows-x64"] license = ["SPDX:GPL-3.0-or-later"] -# CultLib's cultnet-py and cultcache-py import msgpack; Blender's Python does not ship it. The wheel is -# the installed msgpack 1.2.2 CPython 3.13 Windows build (Blender 5.3 runs Python 3.13). The C extension -# matters: CultLib at baf4ecf7 fails on msgpack's pure-Python fallback (object_pairs_hook gets a generator). -# Linux and macOS wheels are not bundled yet. -wheels = ["./wheels/msgpack-1.2.2-cp313-cp313-win_amd64.whl"] +# CultLib's cultnet-py and cultcache-py import msgpack; Blender's Python does not ship it. The wheel is one +# pure-Python msgpack 1.2.2 (no C extension), so the extension is platform-independent; CultLib 9fc4bdda +# (PR #180) decodes under msgpack's pure-Python fallback. Source and hash: docs/install.md. +wheels = ["./wheels/msgpack-1.2.2-py3-none-any.whl"] diff --git a/surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-cp313-cp313-win_amd64.whl b/surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-cp313-cp313-win_amd64.whl deleted file mode 100644 index 83a8682553e2b936e0c3cb72ecf267cd6ec8b371..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 72206 zcmY&;Q;aT58{|8-ZCht->x^yNwmoykwr$(CZQHi?+hi~Hzvxb<(|OWKRq~)pUJ3*h z6#xK0{k-&0blszJo zLxj-!IE-womWg+OYMwKHl6azUFXfs1yV%AHB%T_PGBCc;yraN@8< zK~4VkOyFTt@?>Xl%%8t;5r?*^LGa0m$&g`U zX#ZoLXWtugLeO>$hHG2L4V15#eLV1OaE5dg&)do|Jx(CA60`ekarMt@+2LXAhr_5I z;^!oKYt~ zAn(#=vy(yjH5`js%?BX=KjaufT=r=Fj~o{Nkpu1jBZrB*k%_&tg`KU_fAmOJlCdlN z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IStpfBrM63lQ&@Ut4$_uF`|iIOYiOpw1^TfU>4dZt!PC9Nq#5Nzy$>|a z3+PlY1zzjs5ccO2{XEglwj@$E zStwL#_sR=bvQGb4?Awzmw3FWaAsjW;Bbk-s{K8yS2Vbo6JxCq=w>kG9-FM|pRMe25 zIEY?pSNcB*xJ!c$hoxUPyPj0Z{KdlLl9Ck-Rclie4Sq_OJyrVt+m>4vA!Whc0QoyA zF9Q)?b{u!-lr>0sN5o=kRe?9KvjYPfg=?2%E>9|G zsY|LW%haZ5icya|L;%HA3gm4`Jn%4;rtu$x3Ta43Hm2^|6%j{8}YYe?B588 zKW@Q)BmU(d`+Mx)i_-r+b_eF)WB~GrNmEhmBSJwYb z`$t{)8~JxV_%~9V?LQ;`t`2`w|ISJOrebmYXX^jXP=BNTP9Oh9wf`5?|4AnDQefc! Rx*zJ#7W+ppja>ga`(GeE=H37R literal 0 HcmV?d00001 diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index f29c195..6452905 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -33,7 +33,7 @@ The command prints the record count and leaves the source unwritten. Records a n 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-cp313-cp313-win_amd64.whl`, which Blender unpacks into the extension's own +`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: ```text @@ -41,12 +41,21 @@ blender --command extension build --source-dir surfaces/blender/brokkr_bridge -- blender --command extension install-file --repo user_default --enable /brokkr_bridge-0.2.0.zip ``` -The bundled wheel is msgpack 1.2.2 for CPython 3.13 on Windows x64 (Blender 5.3's Python), -repacked from the installed package with its Apache-2.0 licence; the extension is therefore -declared `windows-x64`, Blender 5.3 or newer. The C extension matters: CultLib at `baf4ecf7` -fails on msgpack's pure-Python fallback. Linux and macOS wheels are not bundled yet: there, -or in a plain add-on directory install, put `msgpack` into Blender's Python yourself. A -CultLib package missing a module is reported by that module's name, not as a missing +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 and +Apache-2.0 `COPYING`. The repack is deterministic; rebuild and compare: + +```text +python tools/build-msgpack-wheel.py +sha256 0b53d2ea2e21782a670fc152bb104d97623cfa337940518016a6b7ded369af42 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: diff --git a/surfaces/blender/tests/live/agent_turn_undo.result.json b/surfaces/blender/tests/live/agent_turn_undo.result.json index 0437128..248b79b 100644 --- a/surfaces/blender/tests/live/agent_turn_undo.result.json +++ b/surfaces/blender/tests/live/agent_turn_undo.result.json @@ -5,7 +5,7 @@ { "name": "createObject accepted with undoLabel", "ok": true, - "detail": "Brokkr nibu/hands: createObject 00000001" + "detail": "Brokkr nibu/hands: createObject ent-turn" }, { "name": "transform applied", @@ -197,7 +197,7 @@ "name": "exportGltf and renderStill accepted with no undoLabel", "ok": true, "detail": [ - "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-_y_dg6ko\\object.glb (3484 bytes).", + "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-0ge72kvx\\object.glb (3484 bytes).", "Rendered still to object.png." ] }, @@ -215,19 +215,19 @@ { "intent": "createObject", "status": "accepted", - "undoLabel": "Brokkr nibu/hands: createObject 00000001", + "undoLabel": "Brokkr nibu/hands: createObject ent-turn", "message": "Blender object created." }, { "intent": "setObjectTransform", "status": "accepted", - "undoLabel": "Brokkr nibu/hands: setObjectTransform 00000002", + "undoLabel": "Brokkr nibu/hands: setObjectTransform ent-turn", "message": "Blender object transform updated." }, { "intent": "createObject", "status": "accepted", - "undoLabel": "Brokkr nibu/hands: createObject 00000003", + "undoLabel": "Brokkr nibu/hands: createObject ent-turn", "message": "Blender object created." }, { @@ -263,14 +263,14 @@ { "intent": "createObject", "status": "accepted", - "undoLabel": "Brokkr nibu/hands: createObject 00000009", + "undoLabel": "Brokkr nibu/hands: createObject ent-turn", "message": "Blender object created." }, { "intent": "exportGltf", "status": "accepted", "undoLabel": "", - "message": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-_y_dg6ko\\object.glb (3484 bytes)." + "message": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-0ge72kvx\\object.glb (3484 bytes)." }, { "intent": "renderStill", diff --git a/surfaces/blender/tests/test_extension_wheel.py b/surfaces/blender/tests/test_extension_wheel.py new file mode 100644 index 0000000..36c3b0d --- /dev/null +++ b/surfaces/blender/tests/test_extension_wheel.py @@ -0,0 +1,43 @@ +"""The extension's one bundled wheel is pure Python, matches its recorded hash, and the manifest does not pin a platform.""" +from __future__ import annotations + +import base64 +import hashlib +import re +import tomllib +import unittest +import zipfile +from pathlib import Path + +ADDON = Path(__file__).resolve().parents[1] / "brokkr_bridge" +INSTALL = Path(__file__).resolve().parents[1] / "docs" / "install.md" + + +class ExtensionWheelTests(unittest.TestCase): + def setUp(self): + self.manifest = tomllib.loads((ADDON / "blender_manifest.toml").read_text(encoding="utf-8")) + + def test_one_pure_python_wheel_and_no_platform_restriction(self): + self.assertEqual(len(self.manifest["wheels"]), 1) + wheel = ADDON / self.manifest["wheels"][0] + self.assertTrue(wheel.name.endswith("-py3-none-any.whl"), wheel.name) + self.assertNotIn("platforms", self.manifest) + with zipfile.ZipFile(wheel) as z: + names = z.namelist() + self.assertEqual([n for n in names if n.endswith((".pyd", ".so", ".dylib"))], []) + self.assertIn("Root-Is-Purelib: true", z.read("msgpack-1.2.2.dist-info/WHEEL").decode()) + for line in z.read("msgpack-1.2.2.dist-info/RECORD").decode().splitlines(): + name, digest, size = line.split(",") + if digest: + data = z.read(name) + self.assertEqual(digest, "sha256=" + base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode(), name) + self.assertEqual(int(size), len(data), name) + + def test_install_doc_records_the_wheel_hash(self): + wheel = ADDON / self.manifest["wheels"][0] + recorded = re.findall(r"\b[0-9a-f]{64}\b", INSTALL.read_text(encoding="utf-8")) + self.assertIn(hashlib.sha256(wheel.read_bytes()).hexdigest(), recorded) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/build-msgpack-wheel.py b/tools/build-msgpack-wheel.py new file mode 100644 index 0000000..a6d67af --- /dev/null +++ b/tools/build-msgpack-wheel.py @@ -0,0 +1,27 @@ +"""Repack the installed msgpack's pure-Python modules as one py3-none-any wheel (no download, no C extension). + +usage: python tools/build-msgpack-wheel.py +Deterministic: the same installed msgpack gives the same bytes, so the sha256 in install.md is checkable. +""" +import base64, hashlib, importlib.metadata as md, pathlib, sys, zipfile + +PURE = ("__init__.py", "exceptions.py", "ext.py", "fallback.py") # _cmsgpack is the C extension: left out +dist = md.distribution("msgpack") +version = dist.version +site = pathlib.Path(dist.locate_file("")) +files = {f"msgpack/{name}": (site / "msgpack" / name).read_bytes() for name in PURE} +info = f"msgpack-{version}.dist-info" +files[f"{info}/METADATA"] = dist.read_text("METADATA").encode() +files[f"{info}/top_level.txt"] = b"msgpack\n" +files[f"{info}/licenses/COPYING"] = (site / info / "licenses" / "COPYING").read_bytes() +files[f"{info}/WHEEL"] = b"Wheel-Version: 1.0\nGenerator: brokkr tools/build-msgpack-wheel.py\nRoot-Is-Purelib: true\nTag: py3-none-any\n" +digest = lambda data: "sha256=" + base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode() +files[f"{info}/RECORD"] = ("".join(f"{n},{digest(d)},{len(d)}\n" for n, d in files.items()) + f"{info}/RECORD,,\n").encode() + +out = pathlib.Path(sys.argv[1]) / f"msgpack-{version}-py3-none-any.whl" +with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as z: + for name, data in files.items(): + entry = zipfile.ZipInfo(name, (1980, 1, 1, 0, 0, 0)) + entry.compress_type, entry.external_attr = zipfile.ZIP_DEFLATED, 0o644 << 16 + z.writestr(entry, data) +print(out, hashlib.sha256(out.read_bytes()).hexdigest()) From fe76ac45c470e195336b6485dd2e77dd514b0f3a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 21:04:47 +0100 Subject: [PATCH 23/63] live-1 Lows: undo label from the id tail, empty unlink pushes no step, wait pins exact key and poll sleep, architecture wording Each has a test that failed first; the ctl mutants (ends_with key, sleep removed) now fail. Co-Authored-By: Claude Sonnet 5.5 --- brokkr-ctl/src/blender.rs | 49 ++++++++++++++++--- brokkr-ctl/tests/cli.rs | 10 ++++ docs/architecture.md | 2 +- docs/live-collab-target.md | 4 +- .../blender/brokkr_bridge/blender_target.py | 2 +- .../blender/brokkr_bridge/node_actions.py | 1 + .../blender/tests/live/agent_turn_queue.py | 4 +- .../tests/live/agent_turn_queue.result.json | 42 ++++++++-------- surfaces/blender/tests/test_agent_turn.py | 16 +++++- surfaces/blender/tests/test_node_actions.py | 6 ++- 10 files changed, 101 insertions(+), 35 deletions(-) diff --git a/brokkr-ctl/src/blender.rs b/brokkr-ctl/src/blender.rs index e2a7a40..36e7245 100644 --- a/brokkr-ctl/src/blender.rs +++ b/brokkr-ctl/src/blender.rs @@ -267,18 +267,34 @@ fn wait_for_receipt( id: &str, limit: Duration, ) -> Result { - let started = Instant::now(); - loop { - if let Some(receipt) = read_receipt(store, id)? { + match poll_until(limit, POLL, || read_receipt(store, id))? { + Some(receipt) => { print_fields(&receipt); let status = receipt.get("status").and_then(Value::as_str).unwrap_or(""); - return Ok(Outcome::from_status(status).code()); + Ok(Outcome::from_status(status).code()) + } + None => { + println!("status: timeout"); + Ok(Outcome::Timeout.code()) + } + } +} + +/// Reads until `read` yields a value or `limit` passes, sleeping `poll` between reads. +fn poll_until( + limit: Duration, + poll: Duration, + mut read: impl FnMut() -> Result>, +) -> Result> { + let started = Instant::now(); + loop { + if let Some(found) = read()? { + return Ok(Some(found)); } if started.elapsed() >= limit { - println!("status: timeout"); - return Ok(Outcome::Timeout.code()); + return Ok(None); } - thread::sleep(POLL); + thread::sleep(poll); } } @@ -617,6 +633,25 @@ mod tests { assert!(build_intent("../x", "abc", "a/b", "", &[]).is_err()); } + #[test] + fn polling_sleeps_between_reads_and_stops_at_the_limit() { + let mut reads = 0; + let found: Option = poll_until(Duration::from_millis(400), Duration::from_millis(100), || { + reads += 1; + Ok(None) + }) + .unwrap(); + assert_eq!(found, None); + assert!((2..=6).contains(&reads), "{reads} reads: the sleep paces them"); + let mut reads = 0; + let found = poll_until(Duration::from_secs(5), Duration::from_millis(100), || { + reads += 1; + Ok((reads == 3).then_some("receipt")) + }) + .unwrap(); + assert_eq!((found, reads), (Some("receipt"), 3)); + } + #[test] fn statuses_map_to_exit_codes() { for (status, code) in [("accepted", 0), ("denied", 2), ("failed", 2), ("stopped", 3), ("weird", 2)] { diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs index c3df5a6..6161f6b 100644 --- a/brokkr-ctl/tests/cli.rs +++ b/brokkr-ctl/tests/cli.rs @@ -105,6 +105,16 @@ fn a_missing_store_is_not_created() { assert!(!path.exists()); } +#[test] +fn wait_matches_the_exact_receipt_key() { + let dir = tempfile::tempdir().unwrap(); + // receipts whose keys merely end with, or start with, the waited id are other commands' receipts + let path = store_with_receipts(dir.path(), &[("xr1", "accepted"), ("r1x", "accepted")]); + let output = ctl(&path, &["wait", "r1", "--timeout", "0.3"], None); + assert_eq!(output.status.code(), Some(4), "{}", stdout(&output)); + assert!(stdout(&output).contains("status: timeout")); +} + #[test] fn exit_code_follows_the_receipt() { let dir = tempfile::tempdir().unwrap(); diff --git a/docs/architecture.md b/docs/architecture.md index 9b102a9..843dbeb 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -100,7 +100,7 @@ Derived State: - Unity package settings are adapter configuration, not Verse authority. - Blender add-on preferences are adapter configuration, not Verse authority. -- Blender JSON debug exports are inspection/import probes, not mirror authority. +- Blender JSON debug exports are export-only inspection output, not mirror authority and never read back as intents. - Unity and Blender sync UI fields are command/edit affordances; the `brokkr.sync.*` documents are the shared sync policy surface. - Ad hoc syncvar editors write `brokkr.sync.var.v0` policy records only; they diff --git a/docs/live-collab-target.md b/docs/live-collab-target.md index fcfedaa..2853e5a 100644 --- a/docs/live-collab-target.md +++ b/docs/live-collab-target.md @@ -99,7 +99,7 @@ resident service on that number); reading a record's stored version through Aeth **One agent turn primitive.** Every agent mutation in Blender goes through one function in the add-on: admit (sink enabled, `requestedBy` present, id unused, action typed and valid), run the action with every operator called `undo=False`, push exactly one undo -step labelled `Brokkr : `, write the receipt. A +step labelled `Brokkr : `, write the receipt. A refusal caught before any write pushes nothing and leaves the scene unchanged; an action that fails after writing pushes one step labelled `(failed)`, so the partial write is one undoable step. There is no second @@ -254,7 +254,7 @@ are the primitive for the push. | Blender command intent `brokkr.blender.command_intent.v0` (gains `requestedBy`, `note`) | `blender/commands/{commandId}`; ids single-use, minted by the writer (`brush-tree:ruling:blender-sink-mirrors-unity`) | Written once by a caller. Executed at most once or refused. Removed when its receipt is written. Never rewritten. | Callers write. The agent turn primitive alone decides admission and execution. | | Blender command receipt `brokkr.blender.command_receipt.v0` (gains `requestedBy`, `outcome` in accepted, denied, stopped, failed, `undoLabel`, `lookPath`) | `blender/receipts/{commandId}`, one per intent | Written once, after the primitive decides. Pruned by count with Unity's cap and prune rule. | The primitive alone. Callers and the panel read. | | Agent identity `requestedBy` | `/` stated by the caller | Carried on each intent into its receipt and undo label; not stored on its own. | The caller states it; the primitive refuses an intent without it. The session token proves admission, not identity. | -| Agent undo step | Blender undo entry `Brokkr : ` | One per accepted mutating intent; lives as Blender's stack does; never persisted by Brokkr. | Blender owns the stack; the primitive pushes; only the human undoes or redoes. | +| Agent undo step | Blender undo entry `Brokkr : ` | One per accepted mutating intent; lives as Blender's stack does; never persisted by Brokkr. | Blender owns the stack; the primitive pushes; only the human undoes or redoes. | | Blender session id | uuid minted at add-on register and on each `load_post` | Replaced when Blender restarts or a file loads. | The add-on alone. | | Human-edit sequences (snapshot: `humanEditSeq`, per-object `lastHumanEditSeq`) | Integers within a session id | Monotonic within a session; reset with it. Information for the agent; they gate nothing. | The add-on's depsgraph and undo handlers alone. | | Host snapshot `brokkr.blender.host_snapshot.v0` (gains Edit Mode selection, session id, sequences, sink state, authoring binding summary) | `blender/host/current`, overwritten | Refreshed on depsgraph update and after each intent. | The add-on alone. | diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 8684e8e..8302a69 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -542,7 +542,7 @@ class BrokkrBlenderTarget: self._receipted.add(command_id) return self._receipt(command, "denied", denial, "") - label = f"Brokkr {requested_by}: {action} {command_id[:8]}" + label = f"Brokkr {requested_by}: {action} {command_id[-8:]}" # the tail: uuid v7 ids lead with a timestamp, one value per minute push = action not in READ_ACTIONS and action not in NO_SCENE_CHANGE_ACTIONS self.agent_turn = True self._wrote = True diff --git a/surfaces/blender/brokkr_bridge/node_actions.py b/surfaces/blender/brokkr_bridge/node_actions.py index aba236d..389a536 100644 --- a/surfaces/blender/brokkr_bridge/node_actions.py +++ b/surfaces/blender/brokkr_bridge/node_actions.py @@ -254,6 +254,7 @@ class NodeActions: doomed = [l for l in tree.links if l.to_socket == into and (out is None or l.from_socket == out)] for link in doomed: tree.links.remove(link) + self.changed = bool(doomed) # no link matched: no undo step return f"Removed {len(doomed)} link(s).", tree.name def _linkSockets(self, command: dict[str, Any]) -> tuple[str, str]: diff --git a/surfaces/blender/tests/live/agent_turn_queue.py b/surfaces/blender/tests/live/agent_turn_queue.py index f2b2d3c..1521ba0 100644 --- a/surfaces/blender/tests/live/agent_turn_queue.py +++ b/surfaces/blender/tests/live/agent_turn_queue.py @@ -39,6 +39,8 @@ bt = importlib.import_module(MODULE + ".blender_target") try: import msgpack R["msgpack"] = msgpack.__file__ + R["msgpack_packer"] = msgpack.Packer.__module__ # msgpack.fallback: the pure-Python codec, no C extension + R["msgpack_purepython_env"] = os.environ.get("MSGPACK_PUREPYTHON", "") except ImportError: R["msgpack"] = None prefs = bpy.context.preferences.addons[MODULE].preferences @@ -144,7 +146,7 @@ def q1_check(): R["receipts"]["q1"] = r S["q1_label"] = r and r.get("undoLabel") check("queue: createObject drained by the add-on timer, accepted, labelled, attributed", - r and r["status"] == "accepted" and r["undoLabel"] == "Brokkr nibu/hands: createObject aaaaaaaa" + r and r["status"] == "accepted" and r["undoLabel"] == "Brokkr nibu/hands: createObject aaa-0001" # the id's last 8 characters and r["requestedBy"] == "nibu/hands" and r["note"] == "queue test" and "QCube" in names(), r) check("queue: a command JSON under the debug root is inert (kept, never run, never receipted); the receipt export still lands", (SCRATCH / "debug" / "blender" / "commands" / "door-0001.json").exists() and "QDoor" not in names() diff --git a/surfaces/blender/tests/live/agent_turn_queue.result.json b/surfaces/blender/tests/live/agent_turn_queue.result.json index e76bb3f..e1c803e 100644 --- a/surfaces/blender/tests/live/agent_turn_queue.result.json +++ b/surfaces/blender/tests/live/agent_turn_queue.result.json @@ -15,8 +15,8 @@ "objectName": "QCube", "requestedBy": "nibu/hands", "note": "queue test", - "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa", - "observedAt": "2026-11-27T19:32:00.583673+00:00" + "undoLabel": "Brokkr nibu/hands: createObject aaa-0001", + "observedAt": "2026-11-27T20:02:43.826604+00:00" } }, { @@ -46,8 +46,8 @@ "objectName": "QCube", "requestedBy": "nibu/hands", "note": "queue test", - "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa", - "observedAt": "2026-11-27T19:32:00.583673+00:00" + "undoLabel": "Brokkr nibu/hands: createObject aaa-0001", + "observedAt": "2026-11-27T20:02:43.826604+00:00" } }, { @@ -63,7 +63,7 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:32:02.587784+00:00" + "observedAt": "2026-11-27T20:02:45.831074+00:00" } }, { @@ -79,7 +79,7 @@ "requestedBy": "", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:32:04.590532+00:00" + "observedAt": "2026-11-27T20:02:47.837505+00:00" } }, { @@ -134,8 +134,8 @@ "objectName": "QCube", "requestedBy": "nibu/hands", "note": "queue test", - "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa", - "observedAt": "2026-11-27T19:32:00.583673+00:00" + "undoLabel": "Brokkr nibu/hands: createObject aaa-0001", + "observedAt": "2026-11-27T20:02:43.826604+00:00" }, "q2_original": { "schema": "brokkr.blender.command_receipt.v0", @@ -146,8 +146,8 @@ "objectName": "QCube", "requestedBy": "nibu/hands", "note": "queue test", - "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa", - "observedAt": "2026-11-27T19:32:00.583673+00:00" + "undoLabel": "Brokkr nibu/hands: createObject aaa-0001", + "observedAt": "2026-11-27T20:02:43.826604+00:00" }, "q2_denial": { "schema": "brokkr.blender.command_receipt.v0", @@ -159,7 +159,7 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:32:02.587784+00:00" + "observedAt": "2026-11-27T20:02:45.831074+00:00" }, "q3": { "schema": "brokkr.blender.command_receipt.v0", @@ -171,12 +171,12 @@ "requestedBy": "", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:32:04.590532+00:00" + "observedAt": "2026-11-27T20:02:47.837505+00:00" }, "q6": [ { "schema": "brokkr.blender.command_receipt.v0", - "commandId": "8fe2e26fece047bcaca1b9938f1a030c", + "commandId": "3414cf427aa549ea9e9a52c4cfc61908", "action": "createObject", "status": "denied", "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-int)", @@ -184,11 +184,11 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:32:08.599229+00:00" + "observedAt": "2026-11-27T20:02:51.875508+00:00" }, { "schema": "brokkr.blender.command_receipt.v0", - "commandId": "b1a5c7e22158468bb06f6b500c4fa2a7", + "commandId": "3c53313e68aa4d07ab6e3e330396567d", "action": "createObject", "status": "denied", "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-list)", @@ -196,7 +196,7 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:32:08.621069+00:00" + "observedAt": "2026-11-27T20:02:51.901697+00:00" } ], "q5": [ @@ -210,7 +210,7 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:32:10.606424+00:00" + "observedAt": "2026-11-27T20:02:53.881094+00:00" }, { "schema": "brokkr.blender.command_receipt.v0", @@ -222,7 +222,7 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:32:10.629698+00:00" + "observedAt": "2026-11-27T20:02:53.905589+00:00" }, { "schema": "brokkr.blender.command_receipt.v0", @@ -234,10 +234,12 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:32:10.665150+00:00" + "observedAt": "2026-11-27T20:02:53.944684+00:00" } ] }, - "msgpack": "F:\\aeth-wt\\brokkr-live-1.e2e\\res\\extensions\\.local\\lib\\python3.13\\site-packages\\msgpack\\__init__.py", + "msgpack": "F:\\aeth-wt\\brokkr-live-pins.e2e\\res\\extensions\\.local\\lib\\python3.13\\site-packages\\msgpack\\__init__.py", + "msgpack_packer": "msgpack.fallback", + "msgpack_purepython_env": "", "ok": true } \ No newline at end of file diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index 02706de..cf78e9b 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -56,12 +56,24 @@ class AgentTurnTests(unittest.TestCase): def test_accepted_receipt_carries_undo_label(self): receipt = self.run_action(action="createObject", objectType="EMPTY", commandId="abcdef0123456789", requestedBy="nibu/hands", note="x" * 300) - label = "Brokkr nibu/hands: createObject abcdef01" + label = "Brokkr nibu/hands: createObject 23456789" # the id's tail: uuid v7 ids lead with a timestamp self.assertEqual(self.bpy.undo.pushes, [label]) self.assertEqual(receipt["undoLabel"], label) self.assertEqual(receipt["requestedBy"], "nibu/hands") self.assertEqual(len(receipt["note"]), 200) + def test_two_sends_a_minute_apart_get_distinct_labels(self): + # brokkr-ctl ids are uuid v7: the first 8 hex are one value per 65 seconds, the tail is random + self.run_action(action="createObject", objectType="EMPTY", commandId="01a21e88" + "0" * 16 + "aaaa1111") + self.run_action(action="createObject", objectType="EMPTY", commandId="01a21e88" + "0" * 16 + "bbbb2222") + self.assertEqual(len(set(self.bpy.undo.pushes)), 2, self.bpy.undo.pushes) + + def test_architecture_page_does_not_call_the_debug_json_an_import_path(self): + page = (SOURCE.parents[3] / "docs" / "architecture.md").read_text(encoding="utf-8") + for line in page.splitlines(): + if "debug" in line.lower() and "json" in line.lower(): + self.assertNotRegex(line.lower(), r"import", line) + def test_refusal_pushes_nothing(self): receipt = self.run_action(action="createObject", objectType="BOGUS") self.assertEqual(receipt["status"], "failed") @@ -79,7 +91,7 @@ class AgentTurnTests(unittest.TestCase): self.bpy.ops.object.empty_add = boom receipt = self.run_action(action="createObject", objectType="EMPTY", commandId="deadbeef99") self.assertEqual(receipt["status"], "failed") - self.assertEqual(self.bpy.undo.pushes, ["Brokkr nibu/hands: createObject deadbeef (failed)"]) + self.assertEqual(self.bpy.undo.pushes, ["Brokkr nibu/hands: createObject adbeef99 (failed)"]) def test_agent_turn_flag_is_scoped(self): seen = [] diff --git a/surfaces/blender/tests/test_node_actions.py b/surfaces/blender/tests/test_node_actions.py index 6aeee39..f69cc07 100644 --- a/surfaces/blender/tests/test_node_actions.py +++ b/surfaces/blender/tests/test_node_actions.py @@ -559,7 +559,11 @@ class NodeActionTests(unittest.TestCase): self.accepted(action="linkSockets", treeKey="G", fromNode="a", fromSocket="Out", toNode="c", toSocket="A") self.accepted(action="linkSockets", treeKey="G", fromNode="b", fromSocket="Out", toNode="c", toSocket="Size") self.refused(action="unlinkSockets", treeKey="G", fromNode="zzz", fromSocket="Out", toNode="c", toSocket="A") - self.assertIn("Removed 0", self.accepted(action="unlinkSockets", treeKey="G", fromNode="b", fromSocket="Out", toNode="c", toSocket="A")["message"]) + pushes = len(self.bpy.undo.pushes) + empty = self.accepted(action="unlinkSockets", treeKey="G", fromNode="b", fromSocket="Out", toNode="c", toSocket="A") + self.assertIn("Removed 0", empty["message"]) + self.assertEqual(len(self.bpy.undo.pushes), pushes) # nothing changed: no undo step + self.assertEqual(empty["undoLabel"], "") self.assertEqual(len(tree.links), 2) self.assertIn("Removed 1", self.accepted(action="unlinkSockets", treeKey="G", fromNode="a", fromSocket="Out", toNode="c", toSocket="A")["message"]) self.assertEqual(len(tree.links), 1) From 17584e40f967e0d489d63b2f56c45c4e5ead0677 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 21:31:22 +0100 Subject: [PATCH 24/63] Wheel METADATA is the published file's bytes (rebuild, new sha256); a real unlinkSockets removal pins one undo step build-msgpack-wheel.py read METADATA through read_text, which folded CRLF and changed the hash PyPI's RECORD lists. The test compares the wheel's METADATA hash with the installed distribution's RECORD and failed first; the unlink test fails against a mutant that never reports a change. Co-Authored-By: Claude Sonnet 5.5 --- .../wheels/msgpack-1.2.2-py3-none-any.whl | Bin 15448 -> 15493 bytes surfaces/blender/docs/install.md | 4 ++-- .../blender/tests/test_extension_wheel.py | 16 ++++++++++++++++ surfaces/blender/tests/test_node_actions.py | 6 +++++- tools/build-msgpack-wheel.py | 2 +- 5 files changed, 24 insertions(+), 4 deletions(-) diff --git a/surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-py3-none-any.whl b/surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-py3-none-any.whl index 832d5453b3cd50d71b8902c0428d829b228c0c84..641dbcd4defc52d93da2caa7c3dbd742c463e507 100644 GIT binary patch delta 3977 zcmV;44|ed_c!hbe!6y#jkEuF04FCXMApig%0F!|`8k6ZK5Pw}W`X5mDe3Cp8{YZMf z)1A_DoR_bO?TPJXGHFJHL`XtS5-dPkRyzIP?^`@5N_H~ow4Ej)3G8B@-|j+hM9C9g z^1)9+8>#XkJBl8+TW35ILzbC&!KXLvR=s!_9Ysg&)@7AtT(5@gjWCAK#RYaTBedkH z{3LX{bzGGTrGEz^<1!tx(;R28Gp=qV`;SriT+R5D=gI27bJ`G1RraLadM&3SH)8Po zuFzm>&pXEX3o$r~4%)2?t$q>Ha&Z0j^^m<%nJ92_pDoI=FvIt4hDq*(xoGf@g7pa>65l)j-P4;2$eE;Ot@!8Agug_mbS<-I(C{|0Q6I1)UpEphlNi`+HeJo5;u}OGd z2o1LRoPS-eOer!VJHJHWB%%=bD=#;k>yS;>|VBGLqmmY+FHn+J9k9M^C3&k%~Hq=*x*){PT=1Ru{12Tk&fp5%>eQ zb;zEK9z}nAU{iSSAW8z`X*7!e4RjK6NqDVK9>BN54Qi2kVE zIxSf$O2byFV&ZOUF@h1eGoAr-SyrW`MDVfH2c|(t+z9r+%kwjkKdm5O*)eR!k%Ag0 zC(L9#O@+ql735|l8U-{gcqG2LGLnzbh>3_`n z3?;EsvdRb?;60s4Q))S>T;ZZkxd5be(S452Z#7`gg=iun|~DEblovQ zVxX%t=Ph#5dYRw~Aq9hziIgoXrV*BxCDPZHuiE@p@@xAhbZkM1?U=27LhnQj2;|<( z8f={U#@R*Xh!980x;Wo{oU8zp!LuZ#R@Hm~EP|J32=|y}0^`ANq?ZA2_d_O2M4`jyTus8&WHd@bT{1~d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|}h@DpJc18l6yHW@mQl(dFV9RVU@H33rFS7=~-!rxuL*!zcv z)rDAk>p5X#FYLvQZ$aR;9X*MO+64U(9^lDp2&3ynvWg~NQKWSv@st9~|jd0tRx z2dfc>-n&xKVn0HWe^=|vD)F@xU$sVET+Ora+YsK9$t;Pjmutlw;t%|le{K3JOGXg# z9W6rTetAZ!X#zSXb;AfKZZr~6Xx-47k?cP+{$=i`HvhD53nb8#yJ zT8kd zmdX`5UuR2ge4YItvnVyq0tFxEjJm#)`ZqOyK4_r9U;_k1Rsq2l#Dvo3)gvH6JJ9_4 zHCU%itec$Zt5c_L)#c3@UuSVlYC_|9+Ayvw&Om~HHl$sJwxkX%{0o?4o{ap$w9-Q0 zX4Q6+ZC$HkR$9!BImh!*{Hp$2>44LQl3U%qX&}=m9$SL%UY;Pqp&`WRUY%+oRAtkD zqgAjLp7EoSt;~GOVx;rBz6SSO)lLI>RkURNWL5g@cd> zzf5*6%gZyoSuGng!CsxQBvWYlX=UvwG!+zE-9;4+&0aQ_O!GkAcbp(7qVmEf{1iMd zAswBNI=jtm1F5=-)R(NHd?>~M4S|<`UL`$pLU?e+W>{@nJa$JnKOcmC({IBcn^S-+ ze1z$(iOcjSEvIy#zf)3n-A8tF%rRz+QklY5PbGE!?j^- zU#K__f{Ex$3&YR706wCdagp{|HVe1z`JvZro~`5WWNAKsX%0W4zM;9k&T(J=0JGpZ z5djJt-4{s-4FCX9Ad~w#UIO|wlaVzVlU_9qlY%=c0!KBIku@rl*gGl$88?%WH5!v1 xJQW-t=Zw0(0RRBF0ssIW00000000000001_0l7Dmku@5VX*?DNvpE0&007=;mJ9#@ diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 6452905..d85ab16 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -46,12 +46,12 @@ newer, any OS). msgpack then runs its pure-Python fallback, which CultLib `9fc4b 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 and +`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: ```text python tools/build-msgpack-wheel.py -sha256 0b53d2ea2e21782a670fc152bb104d97623cfa337940518016a6b7ded369af42 msgpack-1.2.2-py3-none-any.whl +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 diff --git a/surfaces/blender/tests/test_extension_wheel.py b/surfaces/blender/tests/test_extension_wheel.py index 36c3b0d..362e32f 100644 --- a/surfaces/blender/tests/test_extension_wheel.py +++ b/surfaces/blender/tests/test_extension_wheel.py @@ -3,6 +3,7 @@ from __future__ import annotations import base64 import hashlib +import importlib.metadata import re import tomllib import unittest @@ -33,6 +34,21 @@ class ExtensionWheelTests(unittest.TestCase): self.assertEqual(digest, "sha256=" + base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode(), name) self.assertEqual(int(size), len(data), name) + def test_wheel_metadata_is_the_published_files_bytes(self): + """RECORD in the installed (PyPI) msgpack hashes its METADATA byte for byte; the wheel must carry the same bytes.""" + try: + dist = importlib.metadata.distribution("msgpack") + except importlib.metadata.PackageNotFoundError: + self.skipTest("msgpack is not installed here") + wheel = ADDON / self.manifest["wheels"][0] + if dist.version != "1.2.2": + self.skipTest(f"installed msgpack is {dist.version}") + expected = next(f for f in dist.files if f.name == "METADATA" and f.parent.name.endswith(".dist-info")).hash + with zipfile.ZipFile(wheel) as z: + data = z.read("msgpack-1.2.2.dist-info/METADATA") + digest = "sha256=" + base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode() + self.assertEqual(digest, f"{expected.mode}={expected.value}") + def test_install_doc_records_the_wheel_hash(self): wheel = ADDON / self.manifest["wheels"][0] recorded = re.findall(r"\b[0-9a-f]{64}\b", INSTALL.read_text(encoding="utf-8")) diff --git a/surfaces/blender/tests/test_node_actions.py b/surfaces/blender/tests/test_node_actions.py index f69cc07..eff659b 100644 --- a/surfaces/blender/tests/test_node_actions.py +++ b/surfaces/blender/tests/test_node_actions.py @@ -565,7 +565,11 @@ class NodeActionTests(unittest.TestCase): self.assertEqual(len(self.bpy.undo.pushes), pushes) # nothing changed: no undo step self.assertEqual(empty["undoLabel"], "") self.assertEqual(len(tree.links), 2) - self.assertIn("Removed 1", self.accepted(action="unlinkSockets", treeKey="G", fromNode="a", fromSocket="Out", toNode="c", toSocket="A")["message"]) + pushes = len(self.bpy.undo.pushes) + removal = self.accepted(action="unlinkSockets", treeKey="G", fromNode="a", fromSocket="Out", toNode="c", toSocket="A") + self.assertIn("Removed 1", removal["message"]) + self.assertEqual(len(self.bpy.undo.pushes), pushes + 1) # a real removal is one undo step + self.assertEqual(removal["undoLabel"], self.bpy.undo.pushes[-1]) self.assertEqual(len(tree.links), 1) self.accepted(action="unlinkSockets", treeKey="G", toNode="c", toSocket="Size") self.assertEqual(len(tree.links), 0) diff --git a/tools/build-msgpack-wheel.py b/tools/build-msgpack-wheel.py index a6d67af..6dbf28e 100644 --- a/tools/build-msgpack-wheel.py +++ b/tools/build-msgpack-wheel.py @@ -11,7 +11,7 @@ version = dist.version site = pathlib.Path(dist.locate_file("")) files = {f"msgpack/{name}": (site / "msgpack" / name).read_bytes() for name in PURE} info = f"msgpack-{version}.dist-info" -files[f"{info}/METADATA"] = dist.read_text("METADATA").encode() +files[f"{info}/METADATA"] = (site / info / "METADATA").read_bytes() # bytes: read_text would fold CRLF and change the hash PyPI's RECORD lists files[f"{info}/top_level.txt"] = b"msgpack\n" files[f"{info}/licenses/COPYING"] = (site / info / "licenses" / "COPYING").read_bytes() files[f"{info}/WHEEL"] = b"Wheel-Version: 1.0\nGenerator: brokkr tools/build-msgpack-wheel.py\nRoot-Is-Purelib: true\nTag: py3-none-any\n" From 044ac094b5ca6c036c6dec7e5283bea60d4b557e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 21:38:17 +0100 Subject: [PATCH 25/63] Stop agents: one human control turns the sink off and receipts every pending intent as stopped; presence in the panel purge_command_intents becomes stop_pending: a stopped receipt per intent, written before the intent is deleted. Stop agents, server start and server stop share that path. The timer runs one intent per tick so Stop lands between two. The panel's Agents section (active agents, pending count, last eight receipts) reads a display cache filled where receipts are written; the host snapshot carries agentCommandsEnabled, which brokkr-ctl status prints. Live proof on stock Blender 5.3 with real brokkr-ctl sends: tests/live/stop_presence.py. Co-Authored-By: Claude Sonnet 5.5 --- brokkr-ctl/src/blender.rs | 4 +- brokkr-ctl/tests/cli.rs | 4 +- surfaces/blender/brokkr_bridge/__init__.py | 98 +++++- .../blender/brokkr_bridge/blender_target.py | 116 ++++++- .../blender/brokkr_bridge/server_guard.py | 21 +- surfaces/blender/docs/install.md | 20 +- surfaces/blender/tests/live/gn_actions.py | 4 +- surfaces/blender/tests/live/gn_recreation.py | 4 +- surfaces/blender/tests/live/stop_presence.py | 254 ++++++++++++++ .../tests/live/stop_presence.result.json | 280 ++++++++++++++++ surfaces/blender/tests/test_agent_turn.py | 4 + surfaces/blender/tests/test_server_guard.py | 55 ++- surfaces/blender/tests/test_stop_presence.py | 313 ++++++++++++++++++ 13 files changed, 1118 insertions(+), 59 deletions(-) create mode 100644 surfaces/blender/tests/live/stop_presence.py create mode 100644 surfaces/blender/tests/live/stop_presence.result.json create mode 100644 surfaces/blender/tests/test_stop_presence.py diff --git a/brokkr-ctl/src/blender.rs b/brokkr-ctl/src/blender.rs index 36e7245..be25999 100644 --- a/brokkr-ctl/src/blender.rs +++ b/brokkr-ctl/src/blender.rs @@ -335,7 +335,7 @@ fn status(store: &SingleFileMessagePackBackingStore) -> Result { "activeObjectName", "selectedObjectNames", "objectCount", - "sink", + "agentCommandsEnabled", ] { if let Some(value) = snapshot.get(key) { print_field(key, value); @@ -401,7 +401,7 @@ brokkr-ctl blender: send typed intents to the live Blender add-on and read what Write one intent, then wait for its receipt and print it. `send --help` lists actions. wait [--timeout secs] Wait for a receipt and print it. receipts [--last n] Print stored receipts, oldest first. - status Print the host snapshot summary. + status Print the host snapshot summary, agentCommandsEnabled included. Every command needs --store or $BROKKR_BLENDER_STORE (the add-on's .ccmp). send needs $EUREKA_INSTANCE and --agent or $BROKKR_AGENT; requestedBy is '/'. diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs index 6161f6b..4ea7f24 100644 --- a/brokkr-ctl/tests/cli.rs +++ b/brokkr-ctl/tests/cli.rs @@ -326,12 +326,12 @@ fn receipts_sort_by_observed_time_not_by_key() { fn status_prints_the_snapshot_summary() { let dir = tempfile::tempdir().unwrap(); let path = store_with_receipts(dir.path(), &[]); - let snapshot = json!({"mode": "OBJECT", "activeScene": "Scene", "objectCount": 3, "selectedObjectNames": ["Cube"], "sink": {"enabled": true}}); + let snapshot = json!({"mode": "OBJECT", "activeScene": "Scene", "objectCount": 3, "selectedObjectNames": ["Cube"], "agentCommandsEnabled": false}); push(&path, &[envelope_at("brokkr.blender.host_snapshot.v0", "blender/host/current", &snapshot)]); let output = ctl(&path, &["status"], None); assert_eq!(output.status.code(), Some(0)); let text = stdout(&output); - for line in ["mode: OBJECT", "activeScene: Scene", "objectCount: 3", "selectedObjectNames: [\"Cube\"]", "sink: {\"enabled\":true}"] { + for line in ["mode: OBJECT", "activeScene: Scene", "objectCount: 3", "selectedObjectNames: [\"Cube\"]", "agentCommandsEnabled: false"] { assert!(text.contains(line), "{line} in {text}"); } } diff --git a/surfaces/blender/brokkr_bridge/__init__.py b/surfaces/blender/brokkr_bridge/__init__.py index 8a81707..1a4b5d2 100644 --- a/surfaces/blender/brokkr_bridge/__init__.py +++ b/surfaces/blender/brokkr_bridge/__init__.py @@ -31,6 +31,22 @@ def target(): return _target +def _sink_changed(prefs): + """The sink toggle moved: the stored host snapshot says so, so brokkr-ctl status never reads a stale toggle. + A node nothing has opened yet holds no snapshot to correct.""" + adapter = target() + if adapter.node_open: + adapter.publish_snapshot(bpy.context, prefs.cultmesh_cache_path, prefs.cultlib_py_src, + prefs.debug_mirror_root, prefs.auto_drain_commands) + + +def _redraw(): + for window in bpy.context.window_manager.windows: + for area in window.screen.areas: + if area.type == "VIEW_3D": + area.tag_redraw() + + class BrokkrPreferences(bpy.types.AddonPreferences): bl_idname = __name__ @@ -84,7 +100,9 @@ class BrokkrPreferences(bpy.types.AddonPreferences): auto_drain_commands: bpy.props.BoolProperty( name="Auto Drain Commands", default=False, - description="Poll and execute pending Brokkr Blender command intents on a timer", + update=lambda self, context: _sink_changed(self), + description="The command sink: poll and run queued agent intents on a timer. Only the operator turns it on, " + "and Stop agents turns it off; no agent intent can write it", ) serve_host: bpy.props.StringProperty( @@ -333,6 +351,10 @@ class BROKKR_PT_status(bpy.types.Panel): prefs = context.preferences.addons[__name__].preferences adapter = target() + stop = layout.row() + stop.scale_y = 1.6 + stop.operator("brokkr.stop_agents", icon="CANCEL") + layout.label(text=f"Provider: {PROVIDER_ID}") layout.label(text=f"Tool: {TOOL_KIND}") layout.label(text=f"Broker: {prefs.broker_uri}") @@ -409,10 +431,20 @@ class BROKKR_PT_status(bpy.types.Panel): layout.label(text=f"Materials: {adapter.last_snapshot.get('materialCount', 0)}") layout.label(text=f"Selected: {len(adapter.last_snapshot.get('selectedObjectNames', []))}") - if adapter.last_receipt: - layout.separator() - layout.label(text=f"Last receipt: {adapter.last_receipt.get('status', '')}") - layout.label(text=adapter.last_receipt.get("message", "")) + if adapter.node_open and not adapter.receipts_loaded: + adapter.load_recent_receipts(prefs.cultmesh_cache_path, prefs.cultlib_py_src) + agents_box = layout.box() + agents_box.label(text="Agents") + agents_box.label(text=f"Agent commands: {'on' if prefs.auto_drain_commands else 'off'}") + active = adapter.active_agents() + agents_box.label(text=f"Active: {', '.join(active)}" if active else "Active: none in the last 5 minutes") + agents_box.label(text=f"Pending: {adapter.pending_count}") + for item in adapter.recent_receipts(): + agents_box.label(text=f"{item.get('requestedBy') or '?'} {item.get('action', '')} {item.get('status', '')}") + if item.get("note"): + agents_box.label(text=f" {item['note']}") + if item.get("undoLabel"): + agents_box.label(text=f" {item['undoLabel']}") if adapter.last_auto_drain_error: layout.separator() @@ -438,11 +470,31 @@ class BROKKR_OT_capture_snapshot(bpy.types.Operator): prefs.cultmesh_cache_path, prefs.cultlib_py_src, prefs.debug_mirror_root, + prefs.auto_drain_commands, ) self.report({"INFO"}, f"Brokkr mirrored Blender snapshot: {snapshot['observedAt']}") return {"FINISHED"} +class BROKKR_OT_stop_agents(bpy.types.Operator): + bl_idname = "brokkr.stop_agents" + bl_label = "Stop agents" + bl_description = ("Turn agent commands off and give every pending intent a 'stopped' receipt without running it. " + "An action already running finishes as one undo step; Ctrl+Z takes it back") + + def execute(self, context): + prefs = context.preferences.addons[__name__].preferences + prefs.auto_drain_commands = False + try: + stopped = target().stop_pending("stopped by the operator", prefs.cultmesh_cache_path, + prefs.cultlib_py_src, prefs.debug_mirror_root) + except Exception as exc: + self.report({"ERROR"}, f"Agent commands are off, but pending intents could not be stopped: {exc}") + return {"CANCELLED"} + self.report({"INFO"}, f"Agent commands off; {stopped} pending intent(s) stopped.") + return {"FINISHED"} + + class BROKKR_OT_drain_commands(bpy.types.Operator): bl_idname = "brokkr.drain_commands" bl_label = "Drain Commands" @@ -616,39 +668,49 @@ def _auto_capture(scene, depsgraph): prefs.preferences.cultmesh_cache_path, prefs.preferences.cultlib_py_src, prefs.preferences.debug_mirror_root, + prefs.preferences.auto_drain_commands, ) +BUSY_INTERVAL = 0.05 # one intent per tick: Stop is a UI event, and it lands between two intents +IDLE_INTERVAL = 1.0 + + def _auto_drain_commands(): context = bpy.context addon = context.preferences.addons.get(__name__) adapter = target() if not addon: - return 1.0 + return IDLE_INTERVAL prefs = addon.preferences - if not prefs.auto_drain_commands: - adapter.last_auto_drain_error = "" - return 1.0 - + ran = 0 + pending_before = adapter.pending_count try: - adapter.configure_action_dirs(prefs.import_dir, prefs.output_dir) - adapter.drain_commands( - context, - prefs.cultmesh_cache_path, - prefs.cultlib_py_src, - prefs.debug_mirror_root, - ) + if adapter.node_open: + adapter.count_pending(prefs.cultmesh_cache_path, prefs.cultlib_py_src) + if prefs.auto_drain_commands: + adapter.configure_action_dirs(prefs.import_dir, prefs.output_dir) + ran = len(adapter.drain_commands( + context, + prefs.cultmesh_cache_path, + prefs.cultlib_py_src, + prefs.debug_mirror_root, + limit=1, + )) adapter.last_auto_drain_error = "" except Exception as exc: adapter.last_auto_drain_error = str(exc) - return 1.0 + if ran or adapter.pending_count != pending_before: + _redraw() + return BUSY_INTERVAL if ran else IDLE_INTERVAL classes = ( BrokkrPreferences, BROKKR_PT_status, + BROKKR_OT_stop_agents, BROKKR_OT_capture_snapshot, BROKKR_OT_drain_commands, BROKKR_OT_start_server, diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 8302a69..33a332a 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -9,13 +9,14 @@ import re import sys import uuid from array import array -from datetime import datetime, timezone +from collections import deque +from datetime import datetime, timedelta, timezone from pathlib import Path from typing import Any, Iterable from . import node_actions as na from . import scene_actions as sa -from .server_guard import BindRefused, SessionGuard, check_bind, guarded_server_class, is_loopback_host, purge_command_intents +from .server_guard import BindRefused, SessionGuard, check_bind, guarded_server_class, is_loopback_host, stop_pending PROVIDER_ID = "brokkr.blender_editor" TOOL_KIND = "blender-editor" @@ -63,6 +64,9 @@ REQUESTED_BY_SHAPE = re.compile(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$") # out: it separates the '.denied' suffix). COMMAND_ID_SHAPE = re.compile(r"^[A-Za-z0-9_-]{1,128}$") NOTE_LIMIT = 200 +ACTIVE_AGENT_WINDOW = timedelta(minutes=5) # an agent is active when a receipt of its own is this recent +RECEIPTS_SHOWN = 8 +RECEIPTS_KEPT = 64 # the display cache; the node holds the receipts EVALUATED_POSITION_CAP = 256 EVALUATED_VERTEX_LIMIT = 1_000_000 @@ -99,7 +103,6 @@ class BrokkrBlenderTarget: def __init__(self, bpy_module: Any): self.bpy = bpy_module self.last_snapshot: dict[str, Any] | None = None - self.last_receipt: dict[str, Any] | None = None self.last_sync_receipt: dict[str, Any] | None = None self.last_auto_drain_error: str = "" self._node_key: tuple[str, str, str] | None = None @@ -115,6 +118,9 @@ class BrokkrBlenderTarget: self.agent_turn = False # true only inside run_intent self._wrote = True # run_intent: false when an accepted action changed nothing self._receipted: set[str] = set() + self._recent: deque[dict[str, Any]] = deque(maxlen=RECEIPTS_KEPT) # display cache of the node's receipts + self._receipts_loaded = False + self.pending_count = 0 # display cache: intents queued in the node def configure_action_dirs(self, import_dir: str, output_dir: str) -> None: """The directories importGltf and renderStill may touch; empty leaves that action disabled.""" @@ -133,8 +139,9 @@ class BrokkrBlenderTarget: cache_path: str, cultlib_py_src: str, debug_mirror_root: str = "", + agent_commands_enabled: bool = False, ) -> dict[str, Any]: - snapshot = self.capture_snapshot(context) + snapshot = self.capture_snapshot(context, agent_commands_enabled) node, documents = self._open_node(cache_path, cultlib_py_src) node.database.put(documents["host_snapshot"], "blender/host/current", snapshot) if debug_mirror_root: @@ -148,16 +155,16 @@ class BrokkrBlenderTarget: cache_path: str, cultlib_py_src: str, debug_mirror_root: str = "", + limit: int | None = None, ) -> list[dict[str, Any]]: + """Run queued intents, oldest key first: all of them, or at most `limit`, the rest staying queued.""" node, documents = self._open_node(cache_path, cultlib_py_src) snapshot = node.database.snapshot() commands = snapshot.get(COMMAND_INTENT_SCHEMA, {}) receipts: list[dict[str, Any]] = [] - self._receipted.update( - r["commandId"] for r in snapshot.get(COMMAND_RECEIPT_SCHEMA, {}).values() - if isinstance(r.get("commandId"), str)) + self._seed_receipted(snapshot) - for command_key, command in sorted(commands.items()): + for command_key, command in sorted(commands.items())[:limit]: command_id = command.get("commandId") valid = _valid_command_id(command_id) reused = valid and command_id in self._receipted @@ -183,12 +190,86 @@ class BrokkrBlenderTarget: debug_mirror_root: str = "", key_suffix: str = "", ) -> None: - command_id = (receipt.get("commandId") or uuid.uuid4().hex) + key_suffix node, documents = self._open_node(cache_path, cultlib_py_src) + self._put_receipt(node, documents, receipt, debug_mirror_root, key_suffix) + + def _put_receipt(self, node: Any, documents: dict[str, Any], receipt: dict[str, Any], + debug_mirror_root: str = "", key_suffix: str = "") -> None: + """The one place a receipt is written: the node, the debug export, and the panel's display cache.""" + command_id = (receipt.get("commandId") or uuid.uuid4().hex) + key_suffix node.database.put(documents["command_receipt"], f"blender/receipts/{command_id}", receipt) if debug_mirror_root: self._write_debug_document(debug_mirror_root, f"blender/receipts/{command_id}.json", receipt) - self.last_receipt = receipt + self.note_receipt(receipt) + + def _seed_receipted(self, snapshot: dict[str, Any]) -> None: + self._receipted.update( + r["commandId"] for r in snapshot.get(COMMAND_RECEIPT_SCHEMA, {}).values() + if isinstance(r.get("commandId"), str)) + + def stop_pending(self, reason: str, cache_path: str, cultlib_py_src: str, debug_mirror_root: str = "") -> int: + """The Stop button's path: every queued intent gets a 'stopped' receipt and leaves the queue unrun.""" + node, documents = self._open_node(cache_path, cultlib_py_src) + return self._stop_pending(node, documents, reason, debug_mirror_root) + + def _stop_pending(self, node: Any, documents: dict[str, Any], reason: str, debug_mirror_root: str = "") -> int: + """Stop, server start and server stop all take intents off the queue here and nowhere else.""" + if node is None: + return 0 + self._seed_receipted(node.database.snapshot()) + + def write(queue_key: str, intent: dict[str, Any], why: str) -> None: + valid = _valid_command_id(intent.get("commandId")) + reused = valid and intent["commandId"] in self._receipted + receipt = self._receipt(intent, "stopped", f"Stopped ({why}); the intent was not run and nothing was changed.", "") + if not valid: + receipt["message"] += f" (queue key {queue_key})" + self._put_receipt(node, documents, receipt, debug_mirror_root, ".stopped" if reused else "") + if valid: + self._receipted.add(intent["commandId"]) # the id is spent: the sender resends under a new one + + return stop_pending(node, documents["command_intent"], COMMAND_INTENT_SCHEMA, write, reason) + + def note_receipt(self, receipt: dict[str, Any]) -> None: + self._recent.append(receipt) + + def recent_receipts(self) -> list[dict[str, Any]]: + """The last few receipts, newest first.""" + return list(self._recent)[::-1][:RECEIPTS_SHOWN] + + def active_agents(self) -> list[str]: + """Distinct requestedBy among receipts from the last five minutes, in order of first appearance.""" + cutoff = datetime.now(timezone.utc) - ACTIVE_AGENT_WINDOW + agents: dict[str, None] = {} + for item in self._recent: + who, seen = item.get("requestedBy"), _parse_time(item.get("observedAt")) + if who and seen is not None and seen >= cutoff: + agents[who] = None + return list(agents) + + def load_recent_receipts(self, cache_path: str, cultlib_py_src: str) -> None: + """Rebuild the display cache from the node's receipts, once: it replaces what this session noted, since each of those was written to the node.""" + if self._receipts_loaded: + return + node, _documents = self._open_node(cache_path, cultlib_py_src) + stored = sorted(node.database.snapshot().get(COMMAND_RECEIPT_SCHEMA, {}).values(), + key=lambda r: str(r.get("observedAt", ""))) + self._recent = deque(stored, maxlen=RECEIPTS_KEPT) # the node holds every receipt this session noted + self._receipts_loaded = True + + def count_pending(self, cache_path: str, cultlib_py_src: str) -> int: + node, _documents = self._open_node(cache_path, cultlib_py_src) + node.database.pull() + self.pending_count = len(node.database.snapshot().get(COMMAND_INTENT_SCHEMA, {})) + return self.pending_count + + @property + def receipts_loaded(self) -> bool: + return self._receipts_loaded + + @property + def node_open(self) -> bool: + return self._node is not None def refresh_sync_receipt( self, @@ -387,7 +468,7 @@ class BrokkrBlenderTarget: self.stop_server() self._cultmesh_module = "" - purge_command_intents(node, documents["command_intent"], COMMAND_INTENT_SCHEMA) + self._stop_pending(node, documents, "server started") cultmesh, _cultcache = _load_cultmesh(cultlib_py_src) self._cultmesh_module = str(getattr(cultmesh, "__file__", "") or "") verse_catalog = cultmesh.CultMesh.create_verse_catalog() @@ -458,7 +539,7 @@ class BrokkrBlenderTarget: finally: try: if was_running and self._node is not None: - purge_command_intents(self._node, self._documents["command_intent"], COMMAND_INTENT_SCHEMA) + self._stop_pending(self._node, self._documents, "server stopped") finally: self._server = None self._server_key = None @@ -490,7 +571,7 @@ class BrokkrBlenderTarget: "cultmeshModule": self._cultmesh_module, } - def capture_snapshot(self, context: Any) -> dict[str, Any]: + def capture_snapshot(self, context: Any, agent_commands_enabled: bool) -> dict[str, Any]: bpy = self.bpy scan = self._instance_scan() if any(o.type == "MESH" and len(o.modifiers) for o in bpy.data.objects) else None selected = [item.name for item in context.selected_objects if item is not None] @@ -513,6 +594,7 @@ class BrokkrBlenderTarget: "collectionCount": len(bpy.data.collections), "materialCount": len(bpy.data.materials), "imageCount": len(bpy.data.images), + "agentCommandsEnabled": bool(agent_commands_enabled), "capabilities": list(CAPABILITIES), "scenes": [self._scene_snapshot(scene) for scene in bpy.data.scenes], "objects": [self._object_snapshot(obj, scan) for obj in bpy.data.objects], @@ -1249,6 +1331,14 @@ def missing_gl_library() -> str | None: return None +def _parse_time(value: Any) -> datetime | None: + try: + parsed = datetime.fromisoformat(value) + except (TypeError, ValueError): + return None + return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc) + + def _now() -> str: return datetime.now(timezone.utc).isoformat() diff --git a/surfaces/blender/brokkr_bridge/server_guard.py b/surfaces/blender/brokkr_bridge/server_guard.py index 0dbba80..ff91c12 100644 --- a/surfaces/blender/brokkr_bridge/server_guard.py +++ b/surfaces/blender/brokkr_bridge/server_guard.py @@ -3,7 +3,7 @@ Stdlib only, no bpy: everything here is unit-testable without Blender. Always on: a non-loopback bind needs an explicit allow (check_bind), and command -intents queued before a start or stop are purged (purge_command_intents). +intents queued before a start or stop are stopped with a receipt each (stop_pending). Opt-in: a per-session token, checked on every document put and delete when the user turns it on in the add-on preferences (SessionGuard, guarded_server_class). """ @@ -12,7 +12,7 @@ from __future__ import annotations import hmac import ipaddress import secrets -from typing import Any +from typing import Any, Callable PUT_SCHEMA_VERSIONS = ("cultnet.document_put_raw.v0", "cultnet.document_delete.v0") TOKEN_FIELD = "sessionToken" @@ -90,12 +90,17 @@ def guarded_server_class(base: type, guard: SessionGuard) -> type: return GuardedServer -def purge_command_intents(node: Any, command_document: Any, command_schema: str) -> int: - """Delete every queued command intent from the node. Returns how many were removed.""" - removed = 0 +def stop_pending(node: Any, command_document: Any, command_schema: str, + write_receipt: Callable[[str, dict[str, Any], str], None], reason: str) -> int: + """Take every queued command intent off the node without running it: write_receipt(queue key, intent, reason) + first, then delete the intent. An intent whose receipt cannot be written stays queued and the error + propagates, so nothing leaves the queue unreceipted. Returns how many were stopped. Stop, server start + and server stop all come through here; `reason` says why, for the receipt.""" + stopped = 0 if node is not None: node.database.pull() - for key in list(node.database.snapshot().get(command_schema, {})): + for key, intent in list(node.database.snapshot().get(command_schema, {}).items()): + write_receipt(key, intent, reason) node.database.delete(command_document, key) - removed += 1 - return removed + stopped += 1 + return stopped diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index d85ab16..c04ad92 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -69,13 +69,27 @@ 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: the agent resends under a new id once the operator turns the sink back on. + +The `Agents` section lists the agents active in the last five minutes (distinct `requestedBy` among receipts), +the number of pending intents, and the last eight receipts as ` ` 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 Server` and `Stop Server` purge queued command intents: every - `brokkr.blender.command_intent.v0` record in the node. Intents queued before a - start never run under the new session. +- `Start Server` and `Stop Server` stop queued command intents: each + `brokkr.blender.command_intent.v0` record in the node gets a receipt with status `stopped` that 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 Server` the panel shows the bind address, port and the file `cultmesh_py` was actually loaded from (its `__file__`, not the preference). - A `Serve Host` that is not loopback (`0.0.0.0`, a LAN address, a hostname diff --git a/surfaces/blender/tests/live/gn_actions.py b/surfaces/blender/tests/live/gn_actions.py index 62df949..9d86395 100644 --- a/surfaces/blender/tests/live/gn_actions.py +++ b/surfaces/blender/tests/live/gn_actions.py @@ -37,7 +37,7 @@ def ok(t, **cmd): r = act(t, **cmd); check("%s %s" % (cmd["action"], cmd.get("id") or cmd.get("treeKey") or cmd.get("objectName") or ""), r["status"] == "accepted", r["message"]); return r def evaluated(t, name): - snap = t.capture_snapshot(bpy.context) + snap = t.capture_snapshot(bpy.context, False) return [o for o in snap["objects"] if o["name"] == name][0]["evaluated"] def native_tree(build): @@ -254,7 +254,7 @@ def heavy(n, instanced): else: links = [("grid", "Mesh", "gout", "Geometry")] graph(tt, "Heavy", GEO_OUT, nodes, links); host(tt, "HeavyHost", "Heavy") - t0 = time.time(); snap = tt.capture_snapshot(bpy.context); dt = time.time() - t0 + t0 = time.time(); snap = tt.capture_snapshot(bpy.context, False); dt = time.time() - t0 return dt, [o for o in snap["objects"] if o["name"] == "HeavyHost"][0]["evaluated"] dt, ev = heavy(2000, True) R["capture_2000_grid_instanced_seconds"] = round(dt, 3) diff --git a/surfaces/blender/tests/live/gn_recreation.py b/surfaces/blender/tests/live/gn_recreation.py index f8127d9..c7dc47d 100644 --- a/surfaces/blender/tests/live/gn_recreation.py +++ b/surfaces/blender/tests/live/gn_recreation.py @@ -104,7 +104,7 @@ getattr(hob.modifiers["GN"].properties.inputs, ident).__setattr__("value", 5) before = len(evaluated_verts(hob)) r = act(t, action="setObjectCustomProperty", targetObjectName="ParamHost", propertyName=ident, value=12) after = len(evaluated_verts(hob)) -snap = t.capture_snapshot(bpy.context) +snap = t.capture_snapshot(bpy.context, False) ho = [o for o in snap["objects"] if o["name"] == "ParamHost"][0] gap("custom_property_does_not_drive_modifier", receipt=r["status"], verts_before=before, verts_after=after, identifier=ident, snapshot_modifier=ho["modifiers"], snapshot_mesh=ho["mesh"], @@ -153,7 +153,7 @@ g.links.new(grid.outputs["Mesh"], dis.inputs["Mesh"]); g.links.new(dis.outputs[" g.links.new(cone.outputs["Mesh"], iop.inputs["Instance"]); g.links.new(iop.outputs["Instances"], gout.inputs["Geometry"]) ob = host("ScatterHost", g); native = sorted(evaluated_instances(ob)) # what Brokkr can see of that object -snap = t.capture_snapshot(bpy.context); so = [o for o in snap["objects"] if o["name"] == "ScatterHost"][0] +snap = t.capture_snapshot(bpy.context, False); so = [o for o in snap["objects"] if o["name"] == "ScatterHost"][0] gap("snapshot_not_evaluated", brokkr_sees=so["mesh"], modifiers=so["modifiers"], evaluated_instances=len(native), repro="host object with Distribute->InstanceOnPoints: snapshot mesh.vertexCount=0, no instance count, no positions") # (a) replay the native points through actions (needs a side channel that is not Brokkr) diff --git a/surfaces/blender/tests/live/stop_presence.py b/surfaces/blender/tests/live/stop_presence.py new file mode 100644 index 0000000..e23f990 --- /dev/null +++ b/surfaces/blender/tests/live/stop_presence.py @@ -0,0 +1,254 @@ +"""Live proof, in GUI Blender with the add-on enabled, of Stop and presence, with real brokkr-ctl sends. + + BROKKR_SCRATCH= + BROKKR_CTL= + BROKKR_ADDON_MODULE= + BROKKR_CULTLIB= + blender --factory-startup --python stop_presence.py -- + +The driver stands in for the operator's hands only: it ticks the sink preference on and runs the add-on's own +"Stop agents" operator. Every intent is sent by brokkr-ctl; the add-on's timer drains them. Undo is read only here. +Writes .result.json, then quits Blender. +""" +import importlib +import json +import os +import re +import subprocess +import sys +import traceback +from pathlib import Path + +import bpy + +SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() +SCRATCH.mkdir(parents=True, exist_ok=True) +CTL = os.environ["BROKKR_CTL"] +OUT = sys.argv[sys.argv.index("--") + 1] +MODULE = os.environ.get("BROKKR_ADDON_MODULE", "bl_ext.user_default.brokkr_bridge") +R = {"blender": bpy.app.version_string, "module": MODULE, "checks": [], "notes": {}} + +bpy.ops.preferences.addon_enable(module=MODULE) +addon = importlib.import_module(MODULE) +bt = importlib.import_module(MODULE + ".blender_target") +prefs = bpy.context.preferences.addons[MODULE].preferences +CACHE = str(SCRATCH / "stop.ccmp") +prefs.cultmesh_cache_path = CACHE +prefs.cultlib_py_src = os.environ.get("BROKKR_CULTLIB", prefs.cultlib_py_src) +prefs.auto_drain_commands = False +adapter = addon.target() +ENV = dict(os.environ, EUREKA_INSTANCE="nibu", BROKKR_BLENDER_STORE=CACHE, BROKKR_AGENT="hands") +S = {"ids": []} + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def ctl(*args): + done = subprocess.run([CTL, "blender", *args], env=ENV, capture_output=True, text=True, timeout=30) + return done.returncode, done.stdout + + +def send(name, note): + code, out = ctl("send", "createObject", "--set", 'objectType="EMPTY"', "--set", f'name="{name}"', + "--note", note, "--no-wait") + match = re.search(r"commandId:\s*(\S+)", out) + assert code == 0 and match, (code, out) + return match.group(1) + + +def receipts(): + node, _ = adapter._open_node(CACHE, prefs.cultlib_py_src) + return {r["commandId"]: r for r in node.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}).values()} + + +def pending(): + node, _ = adapter._open_node(CACHE, prefs.cultlib_py_src) + return list(node.database.snapshot().get(bt.COMMAND_INTENT_SCHEMA, {})) + + +def empties(prefix): + return sorted(o.name for o in bpy.data.objects if o.name.startswith(prefix)) + + +def win(): + return bpy.context.temp_override(window=bpy.context.window_manager.windows[0]) + + +class Recorder: + """A layout that records the panel's labels and operators; the real BROKKR_PT_status.draw runs against it.""" + def __init__(self): + self.labels, self.operators = [], [] + + def __getattr__(self, name): + if name == "label": + return lambda text="", **kw: self.labels.append(text) + if name == "operator": + return lambda idname, **kw: self.operators.append(idname) + return lambda *a, **kw: self + + +def panel(): + layout = Recorder() + addon.BROKKR_PT_status.draw(type("Drawn", (), {"layout": layout})(), bpy.context) + return layout + + +# ---- steps ------------------------------------------------------------------------------------------------- + +def s_setup(): + with win(): + bpy.ops.brokkr.start_server() + bpy.ops.brokkr.capture_snapshot() + code, out = ctl("status") + check("setup: server up, sink off, brokkr-ctl status shows agentCommandsEnabled: false", + adapter.server_status()["running"] and code == 0 and "agentCommandsEnabled: false" in out, out) + + +def s_burst(): + S["ids"] = [send(f"B{n:02d}", "burst") for n in range(12)] + adapter.count_pending(CACHE, prefs.cultlib_py_src) + check("burst: 12 brokkr-ctl sends queue while the sink is off; nothing ran", + len(pending()) == 12 and not empties("B") and adapter.pending_count == 12, [len(pending()), empties("B")]) + + +def s_sink_on(): + prefs.auto_drain_commands = True # the operator ticks the sink + code, out = ctl("status") + check("sink on: the stored snapshot follows the toggle (agentCommandsEnabled: true)", "agentCommandsEnabled: true" in out, out) + + +def started(): + return len(receipts()) >= 2 + + +def s_stop(): + S["at_stop"] = sorted(receipts()) + S["panel_before"] = panel().labels # what she sees the moment before she presses Stop, mid-burst + with win(): + S["stop_result"] = bpy.ops.brokkr.stop_agents() + S["after_stop_pending"] = pending() + + +def s_after_stop(): + rs = receipts() + ours = {i: rs.get(i) for i in S["ids"]} + states = {i: (r or {}).get("status") for i, r in ours.items()} + accepted = [i for i, s in states.items() if s == "accepted"] + stopped = [i for i, s in states.items() if s == "stopped"] + R["notes"]["states"] = states + R["notes"]["at_stop_receipted"] = len(S["at_stop"]) + check("stop: every one of the 12 intents has a receipt, each accepted or stopped, none missing", + len(accepted) + len(stopped) == 12 and len(stopped) >= 1 and len(accepted) >= 2, states) + check("stop: the queue is empty and the sink is off", pending() == [] and prefs.auto_drain_commands is False + and S["stop_result"] == {"FINISHED"}, [pending(), S["stop_result"]]) + check("stop: exactly the accepted intents ran, in key order, and the stopped ones left no object", + len(empties("B")) == len(accepted), [empties("B"), len(accepted)]) + check("stop: each accepted intent is one labelled undo step the receipt names", + all(rs[i]["undoLabel"].startswith("Brokkr nibu/hands: createObject ") for i in accepted), + [rs[i]["undoLabel"] for i in accepted][:3]) + check("stop: stopped receipts say who, what and why, and were never given an undo label", + all(rs[i]["requestedBy"] == "nibu/hands" and rs[i]["action"] == "createObject" and rs[i]["undoLabel"] == "" + and "stopped by the operator" in rs[i]["message"] for i in stopped), [rs[i]["message"] for i in stopped][:1]) + exits = {} + for i in S["ids"]: + code, out = ctl("wait", i, "--timeout", "5") + exits[i] = (states[i], code) + R["notes"]["wait_exits"] = exits + check("stop: brokkr-ctl wait exits 0 for accepted and the distinct 3 for stopped", + all(code == (0 if st == "accepted" else 3) for st, code in exits.values()), sorted(set(exits.values()))) + code, out = ctl("status") + check("stop: brokkr-ctl status now reads agentCommandsEnabled: false", "agentCommandsEnabled: false" in out, out) + S["accepted"], S["stopped"] = accepted, stopped + + +def s_undo(): + before = len(empties("B")) + with win(): + bpy.ops.ed.undo() + after = len(empties("B")) + check("stop + Ctrl+Z: one undo takes back the last agent step, nothing else", before - after == 1, [before, after]) + + +def s_panel(): + before = "\n".join(S["panel_before"]) + R["notes"]["panel_before_stop"] = S["panel_before"] + check("panel mid-burst: the agent is active, intents are pending, accepted receipts show note and undo label", + "Active: nibu/hands" in before and "Agent commands: on" in before and re.search(r"Pending: [1-9]", before) + and "nibu/hands createObject accepted" in before and "burst" in before + and "Brokkr nibu/hands: createObject" in before + and before.count("createObject accepted") == len(S["at_stop"]), before) # each receipt listed once + layout = panel() + text = "\n".join(layout.labels) + R["notes"]["panel_labels"] = layout.labels + check("panel after Stop: Stop agents is the first operator drawn", layout.operators[:1] == ["brokkr.stop_agents"], layout.operators[:3]) + check("panel after Stop: commands off, pending 0, the stopped receipts listed with who and what", + "Agent commands: off" in text and "Pending: 0" in text and "nibu/hands createObject stopped" in text, text) + + +def s_server_stop(): + S["ids2"] = [send(f"S{n}", "server-stop") for n in range(3)] + check("server stop: three intents queued behind a running server, sink off", len(pending()) == 3) + with win(): + bpy.ops.brokkr.stop_server() + rs = receipts() + check("server stop: the same path gives each a stopped receipt naming 'server stopped'", + pending() == [] and all(rs[i]["status"] == "stopped" and "server stopped" in rs[i]["message"] for i in S["ids2"]) + and not empties("S"), [rs[i]["message"] for i in S["ids2"]][:1]) + + +def s_server_start(): + S["ids3"] = [send(f"T{n}", "server-start") for n in range(2)] + with win(): + bpy.ops.brokkr.start_server() + rs = receipts() + exits = [ctl("wait", i, "--timeout", "5")[0] for i in S["ids3"]] + check("server start: intents queued while stopped get stopped receipts naming 'server started', wait exits 3", + pending() == [] and all(rs[i]["status"] == "stopped" and "server started" in rs[i]["message"] for i in S["ids3"]) + and exits == [3, 3] and not empties("T"), [exits, [rs[i]["message"] for i in S["ids3"]][:1]]) + + +def s_final(): + check("no add-on drain error", adapter.last_auto_drain_error == "", adapter.last_auto_drain_error) + with win(): + bpy.ops.brokkr.stop_server() + + +i = 0 + + +def write(): + R["ok"] = bool(R["checks"]) and all(c["ok"] for c in R["checks"]) and not R.get("errors") + with open(OUT + ".result.json", "w") as f: + json.dump(R, f, indent=1, default=str) + + +# The add-on's own timer drains between our ticks. Stop is pressed as soon as two receipts exist, so the burst +# is cut in the middle. +def runner(): + global i + try: + if i >= len(steps): + write() + bpy.ops.wm.quit_blender() + return None + step = steps[i] + if step == "wait-two": + if started(): + s_stop() + i += 1 + return 0.005 + step() + i += 1 + write() + return 0.5 if step is not s_sink_on else 0.005 + except Exception: + R.setdefault("errors", []).append({"step": i, "error": traceback.format_exc()}) + write() + bpy.ops.wm.quit_blender() + return None + + +steps = [s_setup, s_burst, s_sink_on, "wait-two", s_after_stop, s_undo, s_panel, s_server_stop, s_server_start, s_final] +bpy.app.timers.register(runner, first_interval=3.0) diff --git a/surfaces/blender/tests/live/stop_presence.result.json b/surfaces/blender/tests/live/stop_presence.result.json new file mode 100644 index 0000000..6bbb5cb --- /dev/null +++ b/surfaces/blender/tests/live/stop_presence.result.json @@ -0,0 +1,280 @@ +{ + "blender": "5.3.0", + "module": "bl_ext.user_default.brokkr_bridge", + "checks": [ + { + "name": "setup: server up, sink off, brokkr-ctl status shows agentCommandsEnabled: false", + "ok": true, + "detail": "observedAt: 2026-11-27T20:37:49.797904+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: Cube\nselectedObjectNames: [\"Cube\"]\nobjectCount: 3\nagentCommandsEnabled: false\n" + }, + { + "name": "burst: 12 brokkr-ctl sends queue while the sink is off; nothing ran", + "ok": true, + "detail": [ + 12, + [] + ] + }, + { + "name": "sink on: the stored snapshot follows the toggle (agentCommandsEnabled: true)", + "ok": true, + "detail": "observedAt: 2026-11-27T20:37:51.169335+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: Cube\nselectedObjectNames: [\"Cube\"]\nobjectCount: 3\nagentCommandsEnabled: true\n" + }, + { + "name": "stop: every one of the 12 intents has a receipt, each accepted or stopped, none missing", + "ok": true, + "detail": { + "01a21eba859d7b21aa7e23791e640a17": "accepted", + "01a21eba85d175a083c1e8e542bbed1d": "accepted", + "01a21eba860f74f1b73c707054d48792": "stopped", + "01a21eba864b7881ba64c540fc461d4d": "stopped", + "01a21eba86a97292a71e1ca6d8acb2d8": "stopped", + "01a21eba86f2722093b458840f45af3a": "stopped", + "01a21eba87577fc1b50a0de908986e13": "stopped", + "01a21eba87b87f919b2dfac978be3b57": "stopped", + "01a21eba881c7a9286a621369083ac7b": "stopped", + "01a21eba886a7833ae7ff3224cdc4e29": "stopped", + "01a21eba88d978f3b5db769bb462f99b": "stopped", + "01a21eba897772009d540695cd6453cc": "stopped" + } + }, + { + "name": "stop: the queue is empty and the sink is off", + "ok": true, + "detail": [ + [], + "{'FINISHED'}" + ] + }, + { + "name": "stop: exactly the accepted intents ran, in key order, and the stopped ones left no object", + "ok": true, + "detail": [ + [ + "B00", + "B01" + ], + 2 + ] + }, + { + "name": "stop: each accepted intent is one labelled undo step the receipt names", + "ok": true, + "detail": [ + "Brokkr nibu/hands: createObject 1e640a17", + "Brokkr nibu/hands: createObject 42bbed1d" + ] + }, + { + "name": "stop: stopped receipts say who, what and why, and were never given an undo label", + "ok": true, + "detail": [ + "Stopped (stopped by the operator); the intent was not run and nothing was changed." + ] + }, + { + "name": "stop: brokkr-ctl wait exits 0 for accepted and the distinct 3 for stopped", + "ok": true, + "detail": [ + [ + "accepted", + 0 + ], + [ + "stopped", + 3 + ] + ] + }, + { + "name": "stop: brokkr-ctl status now reads agentCommandsEnabled: false", + "ok": true, + "detail": "observedAt: 2026-11-27T20:37:52.309838+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: B01\nselectedObjectNames: [\"B01\"]\nobjectCount: 5\nagentCommandsEnabled: false\n" + }, + { + "name": "stop + Ctrl+Z: one undo takes back the last agent step, nothing else", + "ok": true, + "detail": [ + 2, + 1 + ] + }, + { + "name": "panel mid-burst: the agent is active, intents are pending, accepted receipts show note and undo label", + "ok": true, + "detail": "Provider: brokkr.blender_editor\nTool: blender-editor\nBroker: cultmesh://brokkr\nNode: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp\nServer: cultnet://127.0.0.1:53223\nBind: 127.0.0.1:53223\ncultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py\nObject Sync\nTimeline / Cinemachine\nAd Hoc Sync Var\nObjects: 3\nMaterials: 2\nSelected: 1\nAgents\nAgent commands: on\nActive: nibu/hands\nPending: 11\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject 42bbed1d\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject 1e640a17" + }, + { + "name": "panel after Stop: Stop agents is the first operator drawn", + "ok": true, + "detail": [ + "brokkr.stop_agents", + "brokkr.capture_snapshot", + "brokkr.drain_commands" + ] + }, + { + "name": "panel after Stop: commands off, pending 0, the stopped receipts listed with who and what", + "ok": true, + "detail": "Provider: brokkr.blender_editor\nTool: blender-editor\nBroker: cultmesh://brokkr\nNode: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp\nServer: cultnet://127.0.0.1:53223\nBind: 127.0.0.1:53223\ncultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py\nObject Sync\nTimeline / Cinemachine\nAd Hoc Sync Var\nObjects: 5\nMaterials: 2\nSelected: 1\nAgents\nAgent commands: off\nActive: nibu/hands\nPending: 0\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst" + }, + { + "name": "server stop: three intents queued behind a running server, sink off", + "ok": true, + "detail": null + }, + { + "name": "server stop: the same path gives each a stopped receipt naming 'server stopped'", + "ok": true, + "detail": [ + "Stopped (server stopped); the intent was not run and nothing was changed." + ] + }, + { + "name": "server start: intents queued while stopped get stopped receipts naming 'server started', wait exits 3", + "ok": true, + "detail": [ + [ + 3, + 3 + ], + [ + "Stopped (server started); the intent was not run and nothing was changed." + ] + ] + }, + { + "name": "no add-on drain error", + "ok": true, + "detail": "" + } + ], + "notes": { + "states": { + "01a21eba859d7b21aa7e23791e640a17": "accepted", + "01a21eba85d175a083c1e8e542bbed1d": "accepted", + "01a21eba860f74f1b73c707054d48792": "stopped", + "01a21eba864b7881ba64c540fc461d4d": "stopped", + "01a21eba86a97292a71e1ca6d8acb2d8": "stopped", + "01a21eba86f2722093b458840f45af3a": "stopped", + "01a21eba87577fc1b50a0de908986e13": "stopped", + "01a21eba87b87f919b2dfac978be3b57": "stopped", + "01a21eba881c7a9286a621369083ac7b": "stopped", + "01a21eba886a7833ae7ff3224cdc4e29": "stopped", + "01a21eba88d978f3b5db769bb462f99b": "stopped", + "01a21eba897772009d540695cd6453cc": "stopped" + }, + "at_stop_receipted": 2, + "wait_exits": { + "01a21eba859d7b21aa7e23791e640a17": [ + "accepted", + 0 + ], + "01a21eba85d175a083c1e8e542bbed1d": [ + "accepted", + 0 + ], + "01a21eba860f74f1b73c707054d48792": [ + "stopped", + 3 + ], + "01a21eba864b7881ba64c540fc461d4d": [ + "stopped", + 3 + ], + "01a21eba86a97292a71e1ca6d8acb2d8": [ + "stopped", + 3 + ], + "01a21eba86f2722093b458840f45af3a": [ + "stopped", + 3 + ], + "01a21eba87577fc1b50a0de908986e13": [ + "stopped", + 3 + ], + "01a21eba87b87f919b2dfac978be3b57": [ + "stopped", + 3 + ], + "01a21eba881c7a9286a621369083ac7b": [ + "stopped", + 3 + ], + "01a21eba886a7833ae7ff3224cdc4e29": [ + "stopped", + 3 + ], + "01a21eba88d978f3b5db769bb462f99b": [ + "stopped", + 3 + ], + "01a21eba897772009d540695cd6453cc": [ + "stopped", + 3 + ] + }, + "panel_before_stop": [ + "Provider: brokkr.blender_editor", + "Tool: blender-editor", + "Broker: cultmesh://brokkr", + "Node: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp", + "Server: cultnet://127.0.0.1:53223", + "Bind: 127.0.0.1:53223", + "cultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py", + "Object Sync", + "Timeline / Cinemachine", + "Ad Hoc Sync Var", + "Objects: 3", + "Materials: 2", + "Selected: 1", + "Agents", + "Agent commands: on", + "Active: nibu/hands", + "Pending: 11", + "nibu/hands createObject accepted", + " burst", + " Brokkr nibu/hands: createObject 42bbed1d", + "nibu/hands createObject accepted", + " burst", + " Brokkr nibu/hands: createObject 1e640a17" + ], + "panel_labels": [ + "Provider: brokkr.blender_editor", + "Tool: blender-editor", + "Broker: cultmesh://brokkr", + "Node: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp", + "Server: cultnet://127.0.0.1:53223", + "Bind: 127.0.0.1:53223", + "cultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py", + "Object Sync", + "Timeline / Cinemachine", + "Ad Hoc Sync Var", + "Objects: 5", + "Materials: 2", + "Selected: 1", + "Agents", + "Agent commands: off", + "Active: nibu/hands", + "Pending: 0", + "nibu/hands createObject stopped", + " burst", + "nibu/hands createObject stopped", + " burst", + "nibu/hands createObject stopped", + " burst", + "nibu/hands createObject stopped", + " burst", + "nibu/hands createObject stopped", + " burst", + "nibu/hands createObject stopped", + " burst", + "nibu/hands createObject stopped", + " burst", + "nibu/hands createObject stopped", + " burst" + ] + }, + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index cf78e9b..b052cc9 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -236,6 +236,10 @@ class FakeNode: self.puts = [] self.deleted = [] self.database = self + self.runtime_id = "fake" + + def pull(self): + pass def snapshot(self): return {k: dict(v) for k, v in self.docs.items()} diff --git a/surfaces/blender/tests/test_server_guard.py b/surfaces/blender/tests/test_server_guard.py index d726162..e4490fa 100644 --- a/surfaces/blender/tests/test_server_guard.py +++ b/surfaces/blender/tests/test_server_guard.py @@ -131,7 +131,10 @@ class FakeDatabase: self.pulls += 1 def snapshot(self): - return {self.schema: {k: {} for k in self.keys}, "other.v0": {"keep": {}}} + return {self.schema: {k: {"commandId": k} for k in self.keys}, "other.v0": {"keep": {}}} + + def put(self, document, key, value): + pass def delete(self, document, key): self.deleted.append((document, key)) @@ -143,16 +146,32 @@ class FakeNode: self.database = FakeDatabase(bt.COMMAND_INTENT_SCHEMA, keys) -class PurgeTests(unittest.TestCase): - def test_purge_removes_queued_intents(self): +class StopPendingTests(unittest.TestCase): + def test_stop_pending_receipts_each_intent_then_deletes_it(self): node = FakeNode(["c1", "c2"]) - removed = sg.purge_command_intents(node, "DOC", bt.COMMAND_INTENT_SCHEMA) + events = [] + removed = sg.stop_pending(node, "DOC", bt.COMMAND_INTENT_SCHEMA, + lambda key, intent, reason: events.append(("receipt", key, intent["commandId"], reason)), + "why") self.assertEqual(removed, 2) self.assertEqual(node.database.deleted, [("DOC", "c1"), ("DOC", "c2")]) + self.assertEqual(events, [("receipt", "c1", "c1", "why"), ("receipt", "c2", "c2", "why")]) - def test_purge_without_a_node_is_quiet(self): - self.assertEqual(sg.purge_command_intents(None, "DOC", bt.COMMAND_INTENT_SCHEMA), 0) + def test_an_intent_whose_receipt_cannot_be_written_is_not_deleted(self): + node = FakeNode(["c1", "c2"]) + def writer(key, intent, reason): + if key == "c2": + raise OSError("disk full") + with self.assertRaises(OSError): + sg.stop_pending(node, "DOC", bt.COMMAND_INTENT_SCHEMA, writer, "why") + self.assertEqual(node.database.deleted, [("DOC", "c1")]) + self.assertEqual(node.database.keys, ["c2"]) + + def test_stop_pending_without_a_node_is_quiet(self): + self.assertEqual(sg.stop_pending(None, "DOC", bt.COMMAND_INTENT_SCHEMA, lambda k, i, r: 1 / 0, "why"), 0) + +class StopServerTests(unittest.TestCase): def test_stop_server_purges_and_revokes(self): target = bt.BrokkrBlenderTarget(types.SimpleNamespace()) stopped = [] @@ -161,7 +180,7 @@ class PurgeTests(unittest.TestCase): guard = target._guard old = guard.token target._node = FakeNode(["c1"]) - target._documents = {"command_intent": "DOC"} + target._documents = {"command_intent": "DOC", "command_receipt": "RDOC"} target.stop_server() self.assertEqual(stopped, [True]) self.assertEqual(target._node.database.keys, []) @@ -178,7 +197,7 @@ class PurgeTests(unittest.TestCase): guard = target._guard old = guard.token target._node = FakeNode(["c1"]) - target._documents = {"command_intent": "DOC"} + target._documents = {"command_intent": "DOC", "command_receipt": "RDOC"} with self.assertRaises(OSError): target.stop_server() self.assertFalse(guard.admits({sg.TOKEN_FIELD: old})) @@ -195,7 +214,7 @@ class PurgeTests(unittest.TestCase): def test_stop_server_with_no_server_running_purges_nothing(self): target = bt.BrokkrBlenderTarget(types.SimpleNamespace()) target._node = FakeNode(["c1"]) - target._documents = {"command_intent": "DOC"} + target._documents = {"command_intent": "DOC", "command_receipt": "RDOC"} target.stop_server() self.assertEqual(target._node.database.keys, ["c1"]) @@ -272,6 +291,22 @@ class RealServerTests(unittest.TestCase): fresh.database.pull() return list(fresh.database.snapshot().get(bt.COMMAND_INTENT_SCHEMA, {})) + def receipt_states(self): + """commandId -> (status, reason) of the receipts a fresh node reads from disk.""" + cultmesh, cultcache = bt._load_cultmesh(PACKAGES) + fresh = cultmesh.CultMesh.start_node(self.cache, runtime_id="receipt-reader") + fresh.database.register_document(cultcache.define_document_type(bt.COMMAND_RECEIPT_SCHEMA)) + fresh.database.pull() + found = fresh.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}).values() + return {r["commandId"]: (r["status"], r["message"]) for r in found} + + def assertStopped(self, reason): + states = self.receipt_states() + self.assertEqual(list(states), ["q1"]) + status, message = states["q1"] + self.assertEqual(status, "stopped") + self.assertIn(reason, message) + def test_start_purges_intents_queued_in_the_node_and_they_stay_gone_after_reopening(self): self.queue_intent() self.assertEqual(len(self.queued(self.cache)), 1) @@ -279,12 +314,14 @@ class RealServerTests(unittest.TestCase): node, _ = self.target._open_node(self.cache, PACKAGES) self.assertEqual(list(node.database.snapshot().get(bt.COMMAND_INTENT_SCHEMA, {})), []) self.assertEqual(self.queued(self.cache), []) + self.assertStopped("server started") def test_stop_purges_intents_queued_while_running_and_they_stay_gone_after_reopening(self): self.start() self.queue_intent() self.target.stop_server() self.assertEqual(self.queued(self.cache), []) + self.assertStopped("server stopped") def test_allow_true_goes_through_start_server_and_unticking_stops_it(self): status = self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, diff --git a/surfaces/blender/tests/test_stop_presence.py b/surfaces/blender/tests/test_stop_presence.py new file mode 100644 index 0000000..6e77f68 --- /dev/null +++ b/surfaces/blender/tests/test_stop_presence.py @@ -0,0 +1,313 @@ +"""Stop and presence: one human control turns the sink off and receipts every pending intent as stopped; +the panel's agent activity is derived from receipts. A fake bpy and a fake node database; no Blender. +""" +from __future__ import annotations + +import re +import types +import unittest +import unittest.mock +from collections import deque +from datetime import datetime, timedelta, timezone +from pathlib import Path + +import test_agent_turn as tat +import test_scene_actions as ts +import test_addon_ui as ui + +bt = ts.bt +NS = types.SimpleNamespace +addon = ui.addon +BRIDGE = Path(bt.__file__).parent +DOCS = {"command_intent": "i", "command_receipt": "r"} + + +class StopFixture(unittest.TestCase): + setUp = ts.ActionTests.setUp + run_action = ts.ActionTests.run_action + intent = tat.DrainTests.intent + + def patched(self, node): + patch = unittest.mock.patch.object(self.target, "_open_node", return_value=(node, DOCS)) + patch.start() + self.addCleanup(patch.stop) + + +class StopPendingTests(StopFixture): + def queue(self): + return tat.FakeNode({f"blender/commands/{n}": self.intent(n, requestedBy=who) + for n, who in (("q-1", "nibu/hands"), ("q-2", "nibu/hands"), ("q-3", "nibu/soul"))}) + + def test_stop_receipts_every_pending_intent(self): + node = self.queue() + self.patched(node) + stopped = self.target.stop_pending("stopped by the operator", "cache", "src") + self.assertEqual(stopped, 3) + receipts = dict(node.puts) + self.assertEqual(sorted(receipts), [f"blender/receipts/q-{n}" for n in (1, 2, 3)]) + for key, receipt in receipts.items(): + self.assertEqual(receipt["status"], "stopped", key) + self.assertIn("stopped by the operator", receipt["message"]) + self.assertEqual(receipt["undoLabel"], "") + self.assertEqual(receipt["action"], "createObject") + self.assertEqual(receipts["blender/receipts/q-3"]["requestedBy"], "nibu/soul") + self.assertEqual(sorted(node.deleted), sorted(node.docs[bt.COMMAND_INTENT_SCHEMA])) + self.assertEqual(self.bpy.created, []) # none dispatched + self.assertEqual(self.bpy.undo.pushes, []) + + def test_every_intent_is_receipted_before_it_is_deleted(self): + node = self.queue() + events = [] + node.put = lambda document, key, value: events.append(("put", key)) + node.delete = lambda document, key: events.append(("delete", key)) + self.patched(node) + self.target.stop_pending("stopped by the operator", "cache", "src") + for n in (1, 2, 3): + self.assertLess(events.index(("put", f"blender/receipts/q-{n}")), + events.index(("delete", f"blender/commands/q-{n}"))) + + def test_a_failed_receipt_write_leaves_the_intent_queued(self): + node = self.queue() + + def put(document, key, value): + raise OSError("disk full") + node.put = put + self.patched(node) + with self.assertRaises(OSError): + self.target.stop_pending("stopped by the operator", "cache", "src") + self.assertEqual(node.deleted, []) # no silent delete + + def test_a_stopped_id_is_spent_and_a_reused_id_keeps_its_original_receipt(self): + old = {"blender/receipts/q-1": {"commandId": "q-1", "status": "accepted"}} + node = tat.FakeNode({"blender/commands/a": self.intent("q-1"), "blender/commands/b": self.intent("q-2")}, old) + self.patched(node) + self.target.stop_pending("stopped by the operator", "cache", "src") + keys = [k for k, _ in node.puts] + self.assertNotIn("blender/receipts/q-1", keys) # write-once: the accepted receipt stands + self.assertIn("blender/receipts/q-1.stopped", keys) + self.assertIn("blender/receipts/q-2", keys) + later = self.run_action(action="createObject", objectType="EMPTY", commandId="q-2") + self.assertEqual(later["status"], "denied") # the sender resends under a new id + self.assertEqual(self.bpy.created, []) + + def test_a_malformed_id_is_receipted_under_a_fresh_key_naming_the_queue_key(self): + node = tat.FakeNode({"blender/commands/odd": self.intent(["x"])}) + self.patched(node) + self.target.stop_pending("stopped by the operator", "cache", "src") + ((key, receipt),) = node.puts + self.assertNotIn("[", key) + self.assertEqual(receipt["status"], "stopped") + self.assertIn("blender/commands/odd", receipt["message"]) + self.assertEqual(node.deleted, ["blender/commands/odd"]) + + def test_stop_with_nothing_pending_writes_nothing(self): + node = tat.FakeNode({}) + self.patched(node) + self.assertEqual(self.target.stop_pending("stopped by the operator", "cache", "src"), 0) + self.assertEqual((node.puts, node.deleted), ([], [])) + + def test_server_stop_and_start_receipt_with_their_own_reasons(self): + node = self.queue() + self.target._node, self.target._documents = node, DOCS + self.target._server = NS(stop=lambda: None) + self.target.stop_server() + self.assertEqual({v["status"] for _, v in node.puts}, {"stopped"}) + self.assertTrue(all("server stopped" in v["message"] for _, v in node.puts)) + self.assertEqual(len(node.deleted), 3) + + def test_start_server_receipts_stale_intents(self): + node = self.queue() + self.patched(node) + with unittest.mock.patch.object(bt, "_load_cultmesh", side_effect=RuntimeError("stop here")): + with self.assertRaises(RuntimeError): + self.target.start_server("cache", "src", "127.0.0.1", 0, 10, 1 << 20) + self.assertEqual({v["status"] for _, v in node.puts}, {"stopped"}) + self.assertTrue(all("server started" in v["message"] for _, v in node.puts)) + self.assertEqual(len(node.deleted), 3) + + +class DrainLimitTests(StopFixture): + def test_a_limited_drain_runs_that_many_and_leaves_the_rest_queued_for_stop(self): + node = tat.FakeNode({f"blender/commands/{n}": self.intent(n) for n in ("b-1", "b-2", "b-3")}) + node.delete = lambda document, key: (node.deleted.append(key), node.docs[bt.COMMAND_INTENT_SCHEMA].pop(key)) + self.patched(node) + receipts = self.target.drain_commands(self.context, "cache", "src", limit=1) + self.assertEqual([r["commandId"] for r in receipts], ["b-1"]) + self.assertEqual(node.deleted, ["blender/commands/b-1"]) + self.target.stop_pending("stopped by the operator", "cache", "src") + stopped = {v["commandId"]: v["status"] for _, v in node.puts} + self.assertEqual(stopped, {"b-1": "accepted", "b-2": "stopped", "b-3": "stopped"}) + self.assertEqual(len(self.bpy.created), 1) + + +class SnapshotTests(StopFixture): + def test_the_snapshot_carries_the_sink_toggle(self): + self.bpy.data = NS(objects=[], scenes=[], materials=[], images=[], collections=[], filepath="") + self.bpy.app = NS(version=(5, 3, 0)) + context = NS(selected_objects=[], active_object=None, scene=self.bpy.scene, mode="OBJECT") + for enabled in (True, False): + self.assertIs(self.target.capture_snapshot(context, enabled)["agentCommandsEnabled"], enabled) + + +def receipt(agent, action, status, minutes_ago=0, note="", undo="", key="k"): + when = datetime.now(timezone.utc) - timedelta(minutes=minutes_ago) + return {"commandId": key, "requestedBy": agent, "action": action, "status": status, "note": note, + "undoLabel": undo, "observedAt": when.isoformat(), "message": ""} + + +class PresenceTests(StopFixture): + def test_active_agents_are_distinct_requesters_in_the_last_five_minutes(self): + self.target.note_receipt(receipt("nibu/hands", "createObject", "accepted", 1)) + self.target.note_receipt(receipt("nibu/hands", "addNode", "accepted", 2)) + self.target.note_receipt(receipt("nibu/soul", "selectObject", "stopped", 4)) + self.target.note_receipt(receipt("nibu/eyes", "selectObject", "accepted", 6)) + self.assertEqual(self.target.active_agents(), ["nibu/hands", "nibu/soul"]) + + def test_recent_receipts_are_the_last_eight_newest_first(self): + for n in range(12): + self.target.note_receipt(receipt("nibu/hands", f"a{n}", "accepted", key=f"k{n}")) + self.assertEqual([r["action"] for r in self.target.recent_receipts()], [f"a{n}" for n in range(11, 3, -1)]) + + def test_publish_receipt_and_stop_both_fill_the_display_cache(self): + node = tat.FakeNode({"blender/commands/s-1": self.intent("s-1")}) + self.patched(node) + self.target.publish_receipt("cache", "src", receipt("nibu/hands", "createObject", "accepted", key="p-1")) + self.target.stop_pending("stopped by the operator", "cache", "src") + self.assertEqual({r["commandId"]: r["status"] for r in self.target.recent_receipts()}, + {"p-1": "accepted", "s-1": "stopped"}) + + def test_first_load_rebuilds_the_cache_from_the_node_once(self): + stored = {f"blender/receipts/{n}": receipt("nibu/hands", "createObject", "accepted", n, key=f"n{n}") + for n in range(1, 4)} + node = tat.FakeNode({}, stored) + self.patched(node) + self.target.load_recent_receipts("cache", "src") + self.assertEqual([r["commandId"] for r in self.target.recent_receipts()], ["n1", "n2", "n3"]) + node.docs[bt.COMMAND_RECEIPT_SCHEMA]["blender/receipts/x"] = receipt("a/b", "x", "accepted", key="x") + self.target.load_recent_receipts("cache", "src") + self.assertEqual(len(self.target.recent_receipts()), 3) # loaded once + + def test_loading_after_receipts_were_noted_lists_each_receipt_once(self): + stored = {"blender/receipts/n1": receipt("nibu/hands", "createObject", "accepted", 1, key="n1")} + node = tat.FakeNode({}, stored) + self.patched(node) + self.target.note_receipt(stored["blender/receipts/n1"]) # written by this session before the first draw + self.target.load_recent_receipts("cache", "src") + self.assertEqual([r["commandId"] for r in self.target.recent_receipts()], ["n1"]) + + def test_pending_count_comes_from_the_node(self): + node = tat.FakeNode({"blender/commands/a": self.intent("a"), "blender/commands/b": self.intent("b")}) + self.patched(node) + self.assertEqual(self.target.count_pending("cache", "src"), 2) + + +class PanelAndOperatorTests(unittest.TestCase): + def setUp(self): + self.target = bt.BrokkrBlenderTarget(NS(path=NS(abspath=lambda p: p))) + addon._target = self.target + self.addCleanup(lambda: setattr(addon, "_target", None)) + self.prefs = unittest.mock.MagicMock(auto_drain_commands=True, cultmesh_cache_path="cache", + cultlib_py_src="src", debug_mirror_root="", broker_uri="b") + self.context = NS(preferences=NS(addons={"brokkr_addon": NS(preferences=self.prefs)})) + + def test_stop_agents_turns_the_sink_off_and_receipts_the_queue(self): + node = tat.FakeNode({"blender/commands/a": {"commandId": "a-1", "requestedBy": "x/y", "action": "createObject"}}) + with unittest.mock.patch.object(self.target, "_open_node", return_value=(node, DOCS)): + operator = addon.BROKKR_OT_stop_agents() + result = operator.execute(self.context) + self.assertEqual(result, {"FINISHED"}) + self.assertFalse(self.prefs.auto_drain_commands) + self.assertEqual([v["status"] for _, v in node.puts], ["stopped"]) + self.assertIn("stopped by the operator", node.puts[0][1]["message"]) + + def test_stop_agents_is_registered_and_first_in_the_panel(self): + self.assertIn(addon.BROKKR_OT_stop_agents, addon.classes) + layout = unittest.mock.MagicMock() + panel = addon.BROKKR_PT_status() + panel.layout = layout + panel.draw(self.context) + first = [c for c in layout.mock_calls if c[0] == "operator" or c[0].endswith(".operator")][0] + self.assertEqual(first.args[0], "brokkr.stop_agents") + + def test_the_sink_preference_defaults_off_and_says_only_the_operator_turns_it_on(self): + prop = addon.BrokkrPreferences.__annotations__["auto_drain_commands"] + self.assertIs(prop.kwargs["default"], False) + self.assertIn("operator", prop.kwargs["description"].lower()) + self.assertTrue(callable(prop.kwargs.get("update"))) # the stored snapshot follows the toggle + + def test_toggling_the_sink_republishes_the_stored_snapshot_once_a_node_is_open(self): + update = addon.BrokkrPreferences.__annotations__["auto_drain_commands"].kwargs["update"] + addon.bpy.context = NS() + with unittest.mock.patch.object(self.target, "publish_snapshot") as publish: + update(self.prefs, None) + publish.assert_not_called() # nothing has opened a node: no snapshot to correct + self.target._node = object() + self.prefs.auto_drain_commands = False + update(self.prefs, None) + self.assertEqual(publish.call_args.args[-1], False) + + def test_the_agents_section_lists_agents_pending_and_receipts(self): + self.target.note_receipt(receipt("nibu/hands", "createObject", "accepted", 1, note="a cube", + undo="Brokkr nibu/hands: createObject abcd1234")) + self.target.note_receipt(receipt("nibu/soul", "setLight", "stopped", 2)) + self.target.pending_count = 3 + self.target._receipts_loaded = True + layout = unittest.mock.MagicMock() + panel = addon.BROKKR_PT_status() + panel.layout = layout + panel.draw(self.context) + texts = [str(c.kwargs.get("text", "")) for c in layout.mock_calls if c.kwargs] + joined = "\n".join(texts) + self.assertIn("Agents", joined) + self.assertIn("nibu/hands", joined) + self.assertIn("nibu/soul setLight stopped", joined) + self.assertIn("nibu/hands createObject accepted", joined) + self.assertIn("a cube", joined) + self.assertIn("Brokkr nibu/hands: createObject abcd1234", joined) + self.assertRegex(joined, r"Pending: 3") + self.assertNotIn("Last receipt", joined) + + +class TimerTests(unittest.TestCase): + def setUp(self): + self.target = bt.BrokkrBlenderTarget(NS(path=NS(abspath=lambda p: p))) + addon._target = self.target + self.addCleanup(lambda: setattr(addon, "_target", None)) + self.prefs = NS(auto_drain_commands=True, cultmesh_cache_path="c", cultlib_py_src="s", debug_mirror_root="", + import_dir="", output_dir="") + patch = unittest.mock.patch.object(addon, "_redraw") + self.redraws = patch.start() + self.addCleanup(patch.stop) + addon.bpy.context = NS(preferences=NS(addons=NS(get=lambda name: NS(preferences=self.prefs)))) + self.drains = [] + self.target.drain_commands = lambda *a, **k: self.drains.append(k) or [1] * self.ran + self.target.count_pending = lambda *a: 0 + self.target.configure_action_dirs = lambda *a: None + + def test_the_timer_drains_one_intent_per_tick_so_stop_lands_between_them(self): + self.ran = 1 + interval = addon._auto_drain_commands() + self.assertEqual(self.drains[0].get("limit"), 1) + self.assertLess(interval, 0.22) # more may be queued: come back soon (bound: geometric mean of the 0.05 shipped and the 1.0 idle reading) + + def test_an_empty_tick_goes_back_to_the_idle_interval(self): + self.ran = 0 + self.assertEqual(addon._auto_drain_commands(), 1.0) + + def test_with_the_sink_off_the_timer_runs_nothing(self): + self.prefs.auto_drain_commands = False + self.ran = 1 + self.assertEqual(addon._auto_drain_commands(), 1.0) + self.assertEqual(self.drains, []) + + +class NoPreferenceWritesTests(unittest.TestCase): + def test_no_action_writes_preferences(self): + # the sink toggle is the human's: no intent or action code reaches add-on preferences + for name in ("scene_actions.py", "node_actions.py", "blender_target.py"): + source = (BRIDGE / name).read_text(encoding="utf-8") + self.assertEqual(re.findall(r"[.]preferences\b|\bprefs\b", source), [], name) + + +if __name__ == "__main__": + unittest.main() From 861edd3195a95ce68fa60d72320379570d0c2e75 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 21:53:10 +0100 Subject: [PATCH 26/63] Stop: a sink-off add-on answers arriving intents stopped; Agents under Stop; pending zero after Stop; survivors pinned Soul s1: post-stop-queue-runs (ruling sink-off-answers-stopped), agents-section-buried, pending-stale-after-stop, stop-survivors-unpinned. The live harness now sends a concurrent burst with the sink on, cuts it with Stop, and shows a later send answered stopped at once (wait exit 3) with nothing firing on re-enable. Co-Authored-By: Claude Sonnet 5.5 --- docs/live-collab-target.md | 4 +- surfaces/blender/brokkr_bridge/__init__.py | 53 ++-- .../blender/brokkr_bridge/blender_target.py | 4 +- surfaces/blender/docs/install.md | 7 +- surfaces/blender/tests/live/stop_presence.py | 125 ++++++--- .../tests/live/stop_presence.result.json | 249 +++++++++++------- surfaces/blender/tests/test_stop_presence.py | 43 ++- 7 files changed, 320 insertions(+), 165 deletions(-) diff --git a/docs/live-collab-target.md b/docs/live-collab-target.md index 2853e5a..545df3d 100644 --- a/docs/live-collab-target.md +++ b/docs/live-collab-target.md @@ -119,7 +119,9 @@ This is scene-level only; the `.cc` keeps its revision refusal (phase two). **Stop is one control, and only the human holds it.** Stop turns the command sink off and gives every pending intent a `stopped` receipt without running it. An action already running finishes as one undo step, so Stop plus Ctrl+Z always returns her -scene. No intent can turn the sink on; intents queued before Stop never run. +scene. No intent can turn the sink on; intents queued before Stop never run, and an intent that +arrives while the sink is off gets a `stopped` receipt at once (`brokkr-live:ruling:sink-off-answers-stopped`), +so nothing queues to fire on re-enable. **The agent sees her view and her edits.** `look` is a read intent: it captures her 3D view to a scratch PNG named by command id (`brush-tree:ruling:look-files-are-scratch`) diff --git a/surfaces/blender/brokkr_bridge/__init__.py b/surfaces/blender/brokkr_bridge/__init__.py index 1a4b5d2..5495956 100644 --- a/surfaces/blender/brokkr_bridge/__init__.py +++ b/surfaces/blender/brokkr_bridge/__init__.py @@ -355,6 +355,21 @@ class BROKKR_PT_status(bpy.types.Panel): stop.scale_y = 1.6 stop.operator("brokkr.stop_agents", icon="CANCEL") + if adapter.node_open and not adapter.receipts_loaded: + adapter.load_recent_receipts(prefs.cultmesh_cache_path, prefs.cultlib_py_src) + agents_box = layout.box() + agents_box.label(text="Agents") + agents_box.label(text=f"Agent commands: {'on' if prefs.auto_drain_commands else 'off'}") + active = adapter.active_agents() + agents_box.label(text=f"Active: {', '.join(active)}" if active else "Active: none in the last 5 minutes") + agents_box.label(text=f"Pending: {adapter.pending_count}") + for item in adapter.recent_receipts(): + agents_box.label(text=f"{item.get('requestedBy') or '?'} {item.get('action', '')} {item.get('status', '')}") + if item.get("note"): + agents_box.label(text=f" {item['note']}") + if item.get("undoLabel"): + agents_box.label(text=f" {item['undoLabel']}") + layout.label(text=f"Provider: {PROVIDER_ID}") layout.label(text=f"Tool: {TOOL_KIND}") layout.label(text=f"Broker: {prefs.broker_uri}") @@ -431,21 +446,6 @@ class BROKKR_PT_status(bpy.types.Panel): layout.label(text=f"Materials: {adapter.last_snapshot.get('materialCount', 0)}") layout.label(text=f"Selected: {len(adapter.last_snapshot.get('selectedObjectNames', []))}") - if adapter.node_open and not adapter.receipts_loaded: - adapter.load_recent_receipts(prefs.cultmesh_cache_path, prefs.cultlib_py_src) - agents_box = layout.box() - agents_box.label(text="Agents") - agents_box.label(text=f"Agent commands: {'on' if prefs.auto_drain_commands else 'off'}") - active = adapter.active_agents() - agents_box.label(text=f"Active: {', '.join(active)}" if active else "Active: none in the last 5 minutes") - agents_box.label(text=f"Pending: {adapter.pending_count}") - for item in adapter.recent_receipts(): - agents_box.label(text=f"{item.get('requestedBy') or '?'} {item.get('action', '')} {item.get('status', '')}") - if item.get("note"): - agents_box.label(text=f" {item['note']}") - if item.get("undoLabel"): - agents_box.label(text=f" {item['undoLabel']}") - if adapter.last_auto_drain_error: layout.separator() layout.label(text="Auto drain error:") @@ -688,16 +688,19 @@ def _auto_drain_commands(): pending_before = adapter.pending_count try: if adapter.node_open: - adapter.count_pending(prefs.cultmesh_cache_path, prefs.cultlib_py_src) - if prefs.auto_drain_commands: - adapter.configure_action_dirs(prefs.import_dir, prefs.output_dir) - ran = len(adapter.drain_commands( - context, - prefs.cultmesh_cache_path, - prefs.cultlib_py_src, - prefs.debug_mirror_root, - limit=1, - )) + if prefs.auto_drain_commands: + adapter.configure_action_dirs(prefs.import_dir, prefs.output_dir) + ran = len(adapter.drain_commands( + context, + prefs.cultmesh_cache_path, + prefs.cultlib_py_src, + prefs.debug_mirror_root, + limit=1, + )) + adapter.count_pending(prefs.cultmesh_cache_path, prefs.cultlib_py_src) + else: # the add-on owns the sink, so it answers: nothing queues to fire on re-enable + adapter.stop_pending("agent commands are off", prefs.cultmesh_cache_path, + prefs.cultlib_py_src, prefs.debug_mirror_root) adapter.last_auto_drain_error = "" except Exception as exc: adapter.last_auto_drain_error = str(exc) diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 33a332a..82be6e2 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -228,7 +228,9 @@ class BrokkrBlenderTarget: if valid: self._receipted.add(intent["commandId"]) # the id is spent: the sender resends under a new one - return stop_pending(node, documents["command_intent"], COMMAND_INTENT_SCHEMA, write, reason) + stopped = stop_pending(node, documents["command_intent"], COMMAND_INTENT_SCHEMA, write, reason) + self.pending_count = 0 + return stopped def note_receipt(self, receipt: dict[str, Any]) -> None: self._recent.append(receipt) diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index c04ad92..0b5917c 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -75,9 +75,12 @@ after `Start Server`. 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: the agent resends under a new id once the operator turns the sink back on. +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 lists the agents active in the last five minutes (distinct `requestedBy` among receipts), +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 ` ` 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. diff --git a/surfaces/blender/tests/live/stop_presence.py b/surfaces/blender/tests/live/stop_presence.py index e23f990..a9b176d 100644 --- a/surfaces/blender/tests/live/stop_presence.py +++ b/surfaces/blender/tests/live/stop_presence.py @@ -16,6 +16,7 @@ import os import re import subprocess import sys +import time import traceback from pathlib import Path @@ -50,14 +51,22 @@ def ctl(*args): return done.returncode, done.stdout +SEND = ["send", "createObject", "--set", 'objectType="EMPTY"'] + + def send(name, note): - code, out = ctl("send", "createObject", "--set", 'objectType="EMPTY"', "--set", f'name="{name}"', - "--note", note, "--no-wait") + code, out = ctl(*SEND, "--set", f'name="{name}"', "--note", note, "--no-wait") match = re.search(r"commandId:\s*(\S+)", out) assert code == 0 and match, (code, out) return match.group(1) +def spawn(name, note): + """A brokkr-ctl send that runs beside Blender's timers: the sender is another process, as an agent is.""" + return subprocess.Popen([CTL, "blender", *SEND, "--set", f'name="{name}"', "--note", note, "--no-wait"], + env=ENV, stdout=subprocess.PIPE, text=True) + + def receipts(): node, _ = adapter._open_node(CACHE, prefs.cultlib_py_src) return {r["commandId"]: r for r in node.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}).values()} @@ -96,6 +105,8 @@ def panel(): # ---- steps ------------------------------------------------------------------------------------------------- +BURST = 20 + def s_setup(): with win(): @@ -107,16 +118,10 @@ def s_setup(): def s_burst(): - S["ids"] = [send(f"B{n:02d}", "burst") for n in range(12)] - adapter.count_pending(CACHE, prefs.cultlib_py_src) - check("burst: 12 brokkr-ctl sends queue while the sink is off; nothing ran", - len(pending()) == 12 and not empties("B") and adapter.pending_count == 12, [len(pending()), empties("B")]) - - -def s_sink_on(): prefs.auto_drain_commands = True # the operator ticks the sink code, out = ctl("status") check("sink on: the stored snapshot follows the toggle (agentCommandsEnabled: true)", "agentCommandsEnabled: true" in out, out) + S["procs"] = [spawn(f"B{n:02d}", "burst") for n in range(BURST)] def started(): @@ -128,68 +133,103 @@ def s_stop(): S["panel_before"] = panel().labels # what she sees the moment before she presses Stop, mid-burst with win(): S["stop_result"] = bpy.ops.brokkr.stop_agents() - S["after_stop_pending"] = pending() - + S["pending_after_stop"] = adapter.pending_count + + +def finished(): + return all(p.poll() is not None for p in S["procs"]) and pending() == [] + def s_after_stop(): + ids = [] + for proc in S["procs"]: + match = re.search(r"commandId:\s*(\S+)", proc.stdout.read()) + ids.append(match.group(1)) + S["ids"] = ids rs = receipts() - ours = {i: rs.get(i) for i in S["ids"]} - states = {i: (r or {}).get("status") for i, r in ours.items()} - accepted = [i for i, s in states.items() if s == "accepted"] - stopped = [i for i, s in states.items() if s == "stopped"] + states = {i: (rs.get(i) or {}).get("status") for i in ids} + accepted = [i for i, st in states.items() if st == "accepted"] + stopped = [i for i, st in states.items() if st == "stopped"] R["notes"]["states"] = states - R["notes"]["at_stop_receipted"] = len(S["at_stop"]) - check("stop: every one of the 12 intents has a receipt, each accepted or stopped, none missing", - len(accepted) + len(stopped) == 12 and len(stopped) >= 1 and len(accepted) >= 2, states) - check("stop: the queue is empty and the sink is off", pending() == [] and prefs.auto_drain_commands is False - and S["stop_result"] == {"FINISHED"}, [pending(), S["stop_result"]]) - check("stop: exactly the accepted intents ran, in key order, and the stopped ones left no object", - len(empties("B")) == len(accepted), [empties("B"), len(accepted)]) + check("stop: every one of the 20 intents has a receipt, each accepted or stopped, none missing", + len(accepted) + len(stopped) == BURST and len(stopped) >= 1 and len(accepted) >= 2, states) + check("stop: the queue is empty, the sink is off, Pending read 0 the moment Stop returned", + pending() == [] and prefs.auto_drain_commands is False and S["stop_result"] == {"FINISHED"} + and S["pending_after_stop"] == 0, [pending(), S["stop_result"], S["pending_after_stop"]]) + check("stop: exactly the accepted intents ran and the stopped ones left no object", + len(empties("B")) == len(accepted), [len(empties("B")), len(accepted)]) check("stop: each accepted intent is one labelled undo step the receipt names", all(rs[i]["undoLabel"].startswith("Brokkr nibu/hands: createObject ") for i in accepted), [rs[i]["undoLabel"] for i in accepted][:3]) - check("stop: stopped receipts say who, what and why, and were never given an undo label", + check("stop: stopped receipts say who, what and why, and never carry an undo label", all(rs[i]["requestedBy"] == "nibu/hands" and rs[i]["action"] == "createObject" and rs[i]["undoLabel"] == "" - and "stopped by the operator" in rs[i]["message"] for i in stopped), [rs[i]["message"] for i in stopped][:1]) - exits = {} - for i in S["ids"]: - code, out = ctl("wait", i, "--timeout", "5") - exits[i] = (states[i], code) + and ("stopped by the operator" in rs[i]["message"] or "agent commands are off" in rs[i]["message"]) + for i in stopped), sorted({rs[i]["message"][:50] for i in stopped})) + R["notes"]["stop_reasons"] = sorted({rs[i]["message"][:48] for i in stopped}) + exits = {i: (states[i], ctl("wait", i, "--timeout", "5")[0]) for i in ids} R["notes"]["wait_exits"] = exits check("stop: brokkr-ctl wait exits 0 for accepted and the distinct 3 for stopped", all(code == (0 if st == "accepted" else 3) for st, code in exits.values()), sorted(set(exits.values()))) code, out = ctl("status") check("stop: brokkr-ctl status now reads agentCommandsEnabled: false", "agentCommandsEnabled: false" in out, out) - S["accepted"], S["stopped"] = accepted, stopped -def s_undo(): +def s_late(): + """An agent that never saw Stop sends again and waits: the add-on's timer answers at once, nothing queues.""" + S["late_began"] = time.time() + S["late"] = subprocess.Popen([CTL, "blender", *SEND, "--set", 'name="Late"', "--note", "late", "--timeout", "10"], + env=ENV, stdout=subprocess.PIPE, text=True) + + +def late_done(): + return S["late"].poll() is not None + + +def s_late_check(): + took = time.time() - S["late_began"] + out = S["late"].stdout.read() + code = S["late"].returncode + R["notes"]["late"] = {"exit": code, "seconds": round(took, 2), "out": out} + check("sink off: a send after Stop is answered stopped at once (wait exit 3, 'agent commands are off'), nothing queued", + code == 3 and took < 5 and "agent commands are off" in out and pending() == [] and not empties("Late"), + [code, took, out]) + S["receipt_count"] = len(receipts()) + prefs.auto_drain_commands = True # she turns the sink back on + + +def s_reenabled(): + check("re-enable: nothing queued fires; the late intent never runs", + pending() == [] and not empties("Late") and len(receipts()) == S["receipt_count"], + [pending(), empties("Late"), len(receipts()) - S["receipt_count"]]) before = len(empties("B")) with win(): bpy.ops.ed.undo() - after = len(empties("B")) - check("stop + Ctrl+Z: one undo takes back the last agent step, nothing else", before - after == 1, [before, after]) + check("stop + Ctrl+Z: one undo takes back the last agent step, nothing else", before - len(empties("B")) == 1, + [before, len(empties("B"))]) def s_panel(): before = "\n".join(S["panel_before"]) R["notes"]["panel_before_stop"] = S["panel_before"] - check("panel mid-burst: the agent is active, intents are pending, accepted receipts show note and undo label", - "Active: nibu/hands" in before and "Agent commands: on" in before and re.search(r"Pending: [1-9]", before) + check("panel mid-burst: Agents is first under Stop, the agent is active, accepted receipts show note and undo label, each once", + S["panel_before"].index("Agents") < S["panel_before"].index("Provider: brokkr.blender_editor") + and "Active: nibu/hands" in before and "Agent commands: on" in before and "nibu/hands createObject accepted" in before and "burst" in before and "Brokkr nibu/hands: createObject" in before - and before.count("createObject accepted") == len(S["at_stop"]), before) # each receipt listed once + and before.count("createObject accepted") == len(S["at_stop"]), before) + prefs.auto_drain_commands = False layout = panel() text = "\n".join(layout.labels) R["notes"]["panel_labels"] = layout.labels check("panel after Stop: Stop agents is the first operator drawn", layout.operators[:1] == ["brokkr.stop_agents"], layout.operators[:3]) check("panel after Stop: commands off, pending 0, the stopped receipts listed with who and what", "Agent commands: off" in text and "Pending: 0" in text and "nibu/hands createObject stopped" in text, text) + prefs.auto_drain_commands = True def s_server_stop(): - S["ids2"] = [send(f"S{n}", "server-stop") for n in range(3)] - check("server stop: three intents queued behind a running server, sink off", len(pending()) == 3) + S["ids2"] = [send(f"S{n}", "server-stop") for n in range(3)] # the sender blocks Blender's thread: they cannot drain yet + check("server stop: three intents queued behind a running server, sink on", len(pending()) == 3, len(pending())) with win(): bpy.ops.brokkr.stop_server() rs = receipts() @@ -225,7 +265,7 @@ def write(): # The add-on's own timer drains between our ticks. Stop is pressed as soon as two receipts exist, so the burst -# is cut in the middle. +# is cut in the middle; sends that arrive after it meet a sink that is off. def runner(): global i try: @@ -239,10 +279,14 @@ def runner(): s_stop() i += 1 return 0.005 + if step in ("wait-done", "wait-late"): + if (finished if step == "wait-done" else late_done)(): + i += 1 + return 0.1 step() i += 1 write() - return 0.5 if step is not s_sink_on else 0.005 + return 0.005 if step is s_burst else 0.5 except Exception: R.setdefault("errors", []).append({"step": i, "error": traceback.format_exc()}) write() @@ -250,5 +294,6 @@ def runner(): return None -steps = [s_setup, s_burst, s_sink_on, "wait-two", s_after_stop, s_undo, s_panel, s_server_stop, s_server_start, s_final] +steps = [s_setup, s_burst, "wait-two", "wait-done", s_after_stop, s_late, "wait-late", s_late_check, s_reenabled, s_panel, + s_server_stop, s_server_start, s_final] bpy.app.timers.register(runner, first_interval=3.0) diff --git a/surfaces/blender/tests/live/stop_presence.result.json b/surfaces/blender/tests/live/stop_presence.result.json index 6bbb5cb..bb6f00b 100644 --- a/surfaces/blender/tests/live/stop_presence.result.json +++ b/surfaces/blender/tests/live/stop_presence.result.json @@ -5,55 +5,53 @@ { "name": "setup: server up, sink off, brokkr-ctl status shows agentCommandsEnabled: false", "ok": true, - "detail": "observedAt: 2026-11-27T20:37:49.797904+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: Cube\nselectedObjectNames: [\"Cube\"]\nobjectCount: 3\nagentCommandsEnabled: false\n" - }, - { - "name": "burst: 12 brokkr-ctl sends queue while the sink is off; nothing ran", - "ok": true, - "detail": [ - 12, - [] - ] + "detail": "observedAt: 2026-11-27T20:52:54.171327+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: Cube\nselectedObjectNames: [\"Cube\"]\nobjectCount: 3\nagentCommandsEnabled: false\n" }, { "name": "sink on: the stored snapshot follows the toggle (agentCommandsEnabled: true)", "ok": true, - "detail": "observedAt: 2026-11-27T20:37:51.169335+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: Cube\nselectedObjectNames: [\"Cube\"]\nobjectCount: 3\nagentCommandsEnabled: true\n" + "detail": "observedAt: 2026-11-27T20:52:54.505375+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: Cube\nselectedObjectNames: [\"Cube\"]\nobjectCount: 3\nagentCommandsEnabled: true\n" }, { - "name": "stop: every one of the 12 intents has a receipt, each accepted or stopped, none missing", + "name": "stop: every one of the 20 intents has a receipt, each accepted or stopped, none missing", "ok": true, "detail": { - "01a21eba859d7b21aa7e23791e640a17": "accepted", - "01a21eba85d175a083c1e8e542bbed1d": "accepted", - "01a21eba860f74f1b73c707054d48792": "stopped", - "01a21eba864b7881ba64c540fc461d4d": "stopped", - "01a21eba86a97292a71e1ca6d8acb2d8": "stopped", - "01a21eba86f2722093b458840f45af3a": "stopped", - "01a21eba87577fc1b50a0de908986e13": "stopped", - "01a21eba87b87f919b2dfac978be3b57": "stopped", - "01a21eba881c7a9286a621369083ac7b": "stopped", - "01a21eba886a7833ae7ff3224cdc4e29": "stopped", - "01a21eba88d978f3b5db769bb462f99b": "stopped", - "01a21eba897772009d540695cd6453cc": "stopped" + "01a21ec852a07e139e33eba7c8c21251": "accepted", + "01a21ec852b27442b17daac0eef61b81": "accepted", + "01a21ec852b47ae08561010021792ee2": "stopped", + "01a21ec852b77eb393c0f081d680b1d3": "stopped", + "01a21ec852ce78c0b66a2c2ce666f185": "stopped", + "01a21ec852cd7d30b8ec875ee4a9272e": "stopped", + "01a21ec852ce7582bff08d6a81921ee4": "stopped", + "01a21ec852e57a009ad0e186af6f0cfa": "stopped", + "01a21ec852e57cb3859bf2d738ef586a": "stopped", + "01a21ec852ec72c0bfd939a5bb39fde3": "stopped", + "01a21ec852ec78c28d7e16c9edc4cc07": "stopped", + "01a21ec8530772339db47b279044d6f5": "stopped", + "01a21ec853237550b1855dd0f0f27269": "stopped", + "01a21ec853347ac1b822f5d61ae8afcb": "stopped", + "01a21ec853457d418b3bd09272666916": "stopped", + "01a21ec853447c328eac215160e935d8": "stopped", + "01a21ec8535375309be1eec02df779f4": "stopped", + "01a21ec853577ba393761e10d99a14d5": "stopped", + "01a21ec853617913965abb873a2228b9": "stopped", + "01a21ec853617d41884613d8831720fe": "stopped" } }, { - "name": "stop: the queue is empty and the sink is off", + "name": "stop: the queue is empty, the sink is off, Pending read 0 the moment Stop returned", "ok": true, "detail": [ [], - "{'FINISHED'}" + "{'FINISHED'}", + 0 ] }, { - "name": "stop: exactly the accepted intents ran, in key order, and the stopped ones left no object", + "name": "stop: exactly the accepted intents ran and the stopped ones left no object", "ok": true, "detail": [ - [ - "B00", - "B01" - ], + 2, 2 ] }, @@ -61,15 +59,15 @@ "name": "stop: each accepted intent is one labelled undo step the receipt names", "ok": true, "detail": [ - "Brokkr nibu/hands: createObject 1e640a17", - "Brokkr nibu/hands: createObject 42bbed1d" + "Brokkr nibu/hands: createObject c8c21251", + "Brokkr nibu/hands: createObject eef61b81" ] }, { - "name": "stop: stopped receipts say who, what and why, and were never given an undo label", + "name": "stop: stopped receipts say who, what and why, and never carry an undo label", "ok": true, "detail": [ - "Stopped (stopped by the operator); the intent was not run and nothing was changed." + "Stopped (stopped by the operator); the intent was " ] }, { @@ -89,7 +87,25 @@ { "name": "stop: brokkr-ctl status now reads agentCommandsEnabled: false", "ok": true, - "detail": "observedAt: 2026-11-27T20:37:52.309838+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: B01\nselectedObjectNames: [\"B01\"]\nobjectCount: 5\nagentCommandsEnabled: false\n" + "detail": "observedAt: 2026-11-27T20:52:55.144050+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: B01\nselectedObjectNames: [\"B01\"]\nobjectCount: 5\nagentCommandsEnabled: false\n" + }, + { + "name": "sink off: a send after Stop is answered stopped at once (wait exit 3, 'agent commands are off'), nothing queued", + "ok": true, + "detail": [ + 3, + 0.6096086502075195, + "commandId: 01a21ec8598f754383d402238c3af85d\naction: createObject\ncommandId: 01a21ec8598f754383d402238c3af85d\nmessage: Stopped (agent commands are off); the intent was not run and nothing was changed.\nnote: late\nobjectName: \nobservedAt: 2026-11-27T20:52:56.732437+00:00\nrequestedBy: nibu/hands\nschema: brokkr.blender.command_receipt.v0\nstatus: stopped\nundoLabel: \n" + ] + }, + { + "name": "re-enable: nothing queued fires; the late intent never runs", + "ok": true, + "detail": [ + [], + [], + 0 + ] }, { "name": "stop + Ctrl+Z: one undo takes back the last agent step, nothing else", @@ -100,9 +116,9 @@ ] }, { - "name": "panel mid-burst: the agent is active, intents are pending, accepted receipts show note and undo label", + "name": "panel mid-burst: Agents is first under Stop, the agent is active, accepted receipts show note and undo label, each once", "ok": true, - "detail": "Provider: brokkr.blender_editor\nTool: blender-editor\nBroker: cultmesh://brokkr\nNode: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp\nServer: cultnet://127.0.0.1:53223\nBind: 127.0.0.1:53223\ncultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py\nObject Sync\nTimeline / Cinemachine\nAd Hoc Sync Var\nObjects: 3\nMaterials: 2\nSelected: 1\nAgents\nAgent commands: on\nActive: nibu/hands\nPending: 11\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject 42bbed1d\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject 1e640a17" + "detail": "Agents\nAgent commands: on\nActive: nibu/hands\nPending: 18\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject eef61b81\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject c8c21251\nProvider: brokkr.blender_editor\nTool: blender-editor\nBroker: cultmesh://brokkr\nNode: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp\nServer: cultnet://127.0.0.1:55445\nBind: 127.0.0.1:55445\ncultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py\nObject Sync\nTimeline / Cinemachine\nAd Hoc Sync Var\nObjects: 3\nMaterials: 2\nSelected: 1" }, { "name": "panel after Stop: Stop agents is the first operator drawn", @@ -116,12 +132,12 @@ { "name": "panel after Stop: commands off, pending 0, the stopped receipts listed with who and what", "ok": true, - "detail": "Provider: brokkr.blender_editor\nTool: blender-editor\nBroker: cultmesh://brokkr\nNode: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp\nServer: cultnet://127.0.0.1:53223\nBind: 127.0.0.1:53223\ncultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py\nObject Sync\nTimeline / Cinemachine\nAd Hoc Sync Var\nObjects: 5\nMaterials: 2\nSelected: 1\nAgents\nAgent commands: off\nActive: nibu/hands\nPending: 0\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst" + "detail": "Agents\nAgent commands: off\nActive: nibu/hands\nPending: 0\nnibu/hands createObject stopped\n late\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nProvider: brokkr.blender_editor\nTool: blender-editor\nBroker: cultmesh://brokkr\nNode: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp\nServer: cultnet://127.0.0.1:55445\nBind: 127.0.0.1:55445\ncultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py\nObject Sync\nTimeline / Cinemachine\nAd Hoc Sync Var\nObjects: 4\nMaterials: 2\nSelected: 1" }, { - "name": "server stop: three intents queued behind a running server, sink off", + "name": "server stop: three intents queued behind a running server, sink on", "ok": true, - "detail": null + "detail": 3 }, { "name": "server stop: the same path gives each a stopped receipt naming 'server stopped'", @@ -151,115 +167,149 @@ ], "notes": { "states": { - "01a21eba859d7b21aa7e23791e640a17": "accepted", - "01a21eba85d175a083c1e8e542bbed1d": "accepted", - "01a21eba860f74f1b73c707054d48792": "stopped", - "01a21eba864b7881ba64c540fc461d4d": "stopped", - "01a21eba86a97292a71e1ca6d8acb2d8": "stopped", - "01a21eba86f2722093b458840f45af3a": "stopped", - "01a21eba87577fc1b50a0de908986e13": "stopped", - "01a21eba87b87f919b2dfac978be3b57": "stopped", - "01a21eba881c7a9286a621369083ac7b": "stopped", - "01a21eba886a7833ae7ff3224cdc4e29": "stopped", - "01a21eba88d978f3b5db769bb462f99b": "stopped", - "01a21eba897772009d540695cd6453cc": "stopped" + "01a21ec852a07e139e33eba7c8c21251": "accepted", + "01a21ec852b27442b17daac0eef61b81": "accepted", + "01a21ec852b47ae08561010021792ee2": "stopped", + "01a21ec852b77eb393c0f081d680b1d3": "stopped", + "01a21ec852ce78c0b66a2c2ce666f185": "stopped", + "01a21ec852cd7d30b8ec875ee4a9272e": "stopped", + "01a21ec852ce7582bff08d6a81921ee4": "stopped", + "01a21ec852e57a009ad0e186af6f0cfa": "stopped", + "01a21ec852e57cb3859bf2d738ef586a": "stopped", + "01a21ec852ec72c0bfd939a5bb39fde3": "stopped", + "01a21ec852ec78c28d7e16c9edc4cc07": "stopped", + "01a21ec8530772339db47b279044d6f5": "stopped", + "01a21ec853237550b1855dd0f0f27269": "stopped", + "01a21ec853347ac1b822f5d61ae8afcb": "stopped", + "01a21ec853457d418b3bd09272666916": "stopped", + "01a21ec853447c328eac215160e935d8": "stopped", + "01a21ec8535375309be1eec02df779f4": "stopped", + "01a21ec853577ba393761e10d99a14d5": "stopped", + "01a21ec853617913965abb873a2228b9": "stopped", + "01a21ec853617d41884613d8831720fe": "stopped" }, - "at_stop_receipted": 2, + "stop_reasons": [ + "Stopped (stopped by the operator); the intent wa" + ], "wait_exits": { - "01a21eba859d7b21aa7e23791e640a17": [ + "01a21ec852a07e139e33eba7c8c21251": [ "accepted", 0 ], - "01a21eba85d175a083c1e8e542bbed1d": [ + "01a21ec852b27442b17daac0eef61b81": [ "accepted", 0 ], - "01a21eba860f74f1b73c707054d48792": [ + "01a21ec852b47ae08561010021792ee2": [ "stopped", 3 ], - "01a21eba864b7881ba64c540fc461d4d": [ + "01a21ec852b77eb393c0f081d680b1d3": [ "stopped", 3 ], - "01a21eba86a97292a71e1ca6d8acb2d8": [ + "01a21ec852ce78c0b66a2c2ce666f185": [ "stopped", 3 ], - "01a21eba86f2722093b458840f45af3a": [ + "01a21ec852cd7d30b8ec875ee4a9272e": [ "stopped", 3 ], - "01a21eba87577fc1b50a0de908986e13": [ + "01a21ec852ce7582bff08d6a81921ee4": [ "stopped", 3 ], - "01a21eba87b87f919b2dfac978be3b57": [ + "01a21ec852e57a009ad0e186af6f0cfa": [ "stopped", 3 ], - "01a21eba881c7a9286a621369083ac7b": [ + "01a21ec852e57cb3859bf2d738ef586a": [ "stopped", 3 ], - "01a21eba886a7833ae7ff3224cdc4e29": [ + "01a21ec852ec72c0bfd939a5bb39fde3": [ "stopped", 3 ], - "01a21eba88d978f3b5db769bb462f99b": [ + "01a21ec852ec78c28d7e16c9edc4cc07": [ "stopped", 3 ], - "01a21eba897772009d540695cd6453cc": [ + "01a21ec8530772339db47b279044d6f5": [ + "stopped", + 3 + ], + "01a21ec853237550b1855dd0f0f27269": [ + "stopped", + 3 + ], + "01a21ec853347ac1b822f5d61ae8afcb": [ + "stopped", + 3 + ], + "01a21ec853457d418b3bd09272666916": [ + "stopped", + 3 + ], + "01a21ec853447c328eac215160e935d8": [ + "stopped", + 3 + ], + "01a21ec8535375309be1eec02df779f4": [ + "stopped", + 3 + ], + "01a21ec853577ba393761e10d99a14d5": [ + "stopped", + 3 + ], + "01a21ec853617913965abb873a2228b9": [ + "stopped", + 3 + ], + "01a21ec853617d41884613d8831720fe": [ "stopped", 3 ] }, + "late": { + "exit": 3, + "seconds": 0.61, + "out": "commandId: 01a21ec8598f754383d402238c3af85d\naction: createObject\ncommandId: 01a21ec8598f754383d402238c3af85d\nmessage: Stopped (agent commands are off); the intent was not run and nothing was changed.\nnote: late\nobjectName: \nobservedAt: 2026-11-27T20:52:56.732437+00:00\nrequestedBy: nibu/hands\nschema: brokkr.blender.command_receipt.v0\nstatus: stopped\nundoLabel: \n" + }, "panel_before_stop": [ + "Agents", + "Agent commands: on", + "Active: nibu/hands", + "Pending: 18", + "nibu/hands createObject accepted", + " burst", + " Brokkr nibu/hands: createObject eef61b81", + "nibu/hands createObject accepted", + " burst", + " Brokkr nibu/hands: createObject c8c21251", "Provider: brokkr.blender_editor", "Tool: blender-editor", "Broker: cultmesh://brokkr", "Node: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp", - "Server: cultnet://127.0.0.1:53223", - "Bind: 127.0.0.1:53223", + "Server: cultnet://127.0.0.1:55445", + "Bind: 127.0.0.1:55445", "cultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py", "Object Sync", "Timeline / Cinemachine", "Ad Hoc Sync Var", "Objects: 3", "Materials: 2", - "Selected: 1", - "Agents", - "Agent commands: on", - "Active: nibu/hands", - "Pending: 11", - "nibu/hands createObject accepted", - " burst", - " Brokkr nibu/hands: createObject 42bbed1d", - "nibu/hands createObject accepted", - " burst", - " Brokkr nibu/hands: createObject 1e640a17" + "Selected: 1" ], "panel_labels": [ - "Provider: brokkr.blender_editor", - "Tool: blender-editor", - "Broker: cultmesh://brokkr", - "Node: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp", - "Server: cultnet://127.0.0.1:53223", - "Bind: 127.0.0.1:53223", - "cultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py", - "Object Sync", - "Timeline / Cinemachine", - "Ad Hoc Sync Var", - "Objects: 5", - "Materials: 2", - "Selected: 1", "Agents", "Agent commands: off", "Active: nibu/hands", "Pending: 0", "nibu/hands createObject stopped", - " burst", + " late", "nibu/hands createObject stopped", " burst", "nibu/hands createObject stopped", @@ -273,7 +323,20 @@ "nibu/hands createObject stopped", " burst", "nibu/hands createObject stopped", - " burst" + " burst", + "Provider: brokkr.blender_editor", + "Tool: blender-editor", + "Broker: cultmesh://brokkr", + "Node: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp", + "Server: cultnet://127.0.0.1:55445", + "Bind: 127.0.0.1:55445", + "cultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py", + "Object Sync", + "Timeline / Cinemachine", + "Ad Hoc Sync Var", + "Objects: 4", + "Materials: 2", + "Selected: 1" ] }, "ok": true diff --git a/surfaces/blender/tests/test_stop_presence.py b/surfaces/blender/tests/test_stop_presence.py index 6e77f68..1126a2a 100644 --- a/surfaces/blender/tests/test_stop_presence.py +++ b/surfaces/blender/tests/test_stop_presence.py @@ -195,6 +195,24 @@ class PresenceTests(StopFixture): self.target.load_recent_receipts("cache", "src") self.assertEqual([r["commandId"] for r in self.target.recent_receipts()], ["n1"]) + def test_many_agents_inside_the_window_are_all_active_beyond_eight_receipts(self): + for n in range(20): + self.target.note_receipt(receipt(f"nibu/a{n}", "createObject", "accepted", 1, key=f"m{n}")) + self.assertEqual(len(self.target.active_agents()), 20) + + def test_a_receipt_time_without_a_zone_is_read_as_utc(self): + fresh = receipt("nibu/naive", "createObject", "accepted", 1) + fresh["observedAt"] = datetime.now(timezone.utc).replace(tzinfo=None).isoformat() + self.target.note_receipt(fresh) + self.assertEqual(self.target.active_agents(), ["nibu/naive"]) + + def test_pending_reads_zero_the_moment_stop_returns(self): + node = tat.FakeNode({"blender/commands/a": self.intent("a-1"), "blender/commands/b": self.intent("b-1")}) + self.patched(node) + self.assertEqual(self.target.count_pending("cache", "src"), 2) + self.target.stop_pending("stopped by the operator", "cache", "src") + self.assertEqual(self.target.pending_count, 0) + def test_pending_count_comes_from_the_node(self): node = tat.FakeNode({"blender/commands/a": self.intent("a"), "blender/commands/b": self.intent("b")}) self.patched(node) @@ -259,6 +277,11 @@ class PanelAndOperatorTests(unittest.TestCase): texts = [str(c.kwargs.get("text", "")) for c in layout.mock_calls if c.kwargs] joined = "\n".join(texts) self.assertIn("Agents", joined) + agents_at = [i for i, c in enumerate(layout.mock_calls) if c.kwargs.get("text") == "Agents"][0] + first_sync = [i for i, c in enumerate(layout.mock_calls) if c.args[:1] == ("brokkr.publish_object_sync",)][0] + first_other = [i for i, c in enumerate(layout.mock_calls) if str(c.kwargs.get("text", "")).startswith("Provider")][0] + self.assertLess(agents_at, first_other) # directly under Stop agents, above everything else + self.assertLess(agents_at, first_sync) self.assertIn("nibu/hands", joined) self.assertIn("nibu/soul setLight stopped", joined) self.assertIn("nibu/hands createObject accepted", joined) @@ -279,10 +302,13 @@ class TimerTests(unittest.TestCase): self.redraws = patch.start() self.addCleanup(patch.stop) addon.bpy.context = NS(preferences=NS(addons=NS(get=lambda name: NS(preferences=self.prefs)))) - self.drains = [] + self.drains, self.counts, self.stops = [], [], [] + self.ran = 0 self.target.drain_commands = lambda *a, **k: self.drains.append(k) or [1] * self.ran - self.target.count_pending = lambda *a: 0 + self.target.count_pending = lambda *a: self.counts.append(a) or 0 + self.target.stop_pending = lambda *a: self.stops.append(a) or 0 self.target.configure_action_dirs = lambda *a: None + self.target._node = object() def test_the_timer_drains_one_intent_per_tick_so_stop_lands_between_them(self): self.ran = 1 @@ -294,11 +320,22 @@ class TimerTests(unittest.TestCase): self.ran = 0 self.assertEqual(addon._auto_drain_commands(), 1.0) - def test_with_the_sink_off_the_timer_runs_nothing(self): + def test_with_the_sink_on_the_timer_keeps_the_pending_count_moving(self): + addon._auto_drain_commands() + self.assertEqual(len(self.counts), 1) + + def test_with_the_sink_off_every_arriving_intent_is_answered_stopped_not_queued(self): self.prefs.auto_drain_commands = False self.ran = 1 self.assertEqual(addon._auto_drain_commands(), 1.0) self.assertEqual(self.drains, []) + self.assertEqual([call[0] for call in self.stops], ["agent commands are off"]) + + def test_with_the_sink_off_and_no_node_open_the_timer_opens_nothing(self): + self.prefs.auto_drain_commands = False + self.target._node = None + addon._auto_drain_commands() + self.assertEqual((self.stops, self.drains, self.counts), ([], [], [])) class NoPreferenceWritesTests(unittest.TestCase): From 6c2da2f5343c9af4fc279880efdf4a1c5af0f71e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 22:04:33 +0100 Subject: [PATCH 27/63] Stop: the timer opens the node when the sink is on or a store already exists; an idle session makes no store Soul s2 node-gate-unpinned-sink-on: in a default install nothing opened the node, so the sink-on drain never started and a sink-off send got no answer. Live harness now starts from a default install with no snapshot published, and a second Blender on the same store proves the sink-off, node-closed answer. Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/brokkr_bridge/__init__.py | 4 +- .../blender/brokkr_bridge/blender_target.py | 3 + .../live/stop_presence.closed.result.json | 28 +++ surfaces/blender/tests/live/stop_presence.py | 60 ++++-- .../tests/live/stop_presence.result.json | 172 ++++++++++-------- surfaces/blender/tests/test_stop_presence.py | 25 ++- 6 files changed, 198 insertions(+), 94 deletions(-) create mode 100644 surfaces/blender/tests/live/stop_presence.closed.result.json diff --git a/surfaces/blender/brokkr_bridge/__init__.py b/surfaces/blender/brokkr_bridge/__init__.py index 5495956..4926385 100644 --- a/surfaces/blender/brokkr_bridge/__init__.py +++ b/surfaces/blender/brokkr_bridge/__init__.py @@ -687,7 +687,9 @@ def _auto_drain_commands(): ran = 0 pending_before = adapter.pending_count try: - if adapter.node_open: + # The sink on, a node open, or a store already on disk: any running Blender answers within a tick, and + # an idle session never creates a store. + if prefs.auto_drain_commands or adapter.node_open or adapter.store_exists(prefs.cultmesh_cache_path): if prefs.auto_drain_commands: adapter.configure_action_dirs(prefs.import_dir, prefs.output_dir) ran = len(adapter.drain_commands( diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 82be6e2..363e017 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -265,6 +265,9 @@ class BrokkrBlenderTarget: self.pending_count = len(node.database.snapshot().get(COMMAND_INTENT_SCHEMA, {})) return self.pending_count + def store_exists(self, cache_path: str) -> bool: + return Path(self.resolve_cache_path(cache_path)).is_file() + @property def receipts_loaded(self) -> bool: return self._receipts_loaded diff --git a/surfaces/blender/tests/live/stop_presence.closed.result.json b/surfaces/blender/tests/live/stop_presence.closed.result.json new file mode 100644 index 0000000..2fa8684 --- /dev/null +++ b/surfaces/blender/tests/live/stop_presence.closed.result.json @@ -0,0 +1,28 @@ +{ + "blender": "5.3.0", + "module": "bl_ext.user_default.brokkr_bridge", + "checks": [ + { + "name": "phase two: a store on disk from phase one, sink off, no snapshot published this session", + "ok": true, + "detail": null + }, + { + "name": "phase two: a send to a sink-off Blender with a closed node is answered stopped at once (exit 3)", + "ok": true, + "detail": [ + 3, + 1.2883892059326172, + "commandId: 01a21ed2b9747d53bc380f32f2057a09\naction: createObject\ncommandId: 01a21ed2b9747d53bc380f32f2057a09\nmessage: Stopped (agent commands are off); the intent was not run and nothing was changed.\nnote: closed\nobjectName: \nobservedAt: 2026-11-27T21:04:17.259806+00:00\nrequestedBy: nibu/hands\nschema: brokkr.blender.command_receipt.v0\nstatus: stopped\nundoLabel: \n" + ] + } + ], + "notes": { + "closed": { + "exit": 3, + "seconds": 1.29, + "out": "commandId: 01a21ed2b9747d53bc380f32f2057a09\naction: createObject\ncommandId: 01a21ed2b9747d53bc380f32f2057a09\nmessage: Stopped (agent commands are off); the intent was not run and nothing was changed.\nnote: closed\nobjectName: \nobservedAt: 2026-11-27T21:04:17.259806+00:00\nrequestedBy: nibu/hands\nschema: brokkr.blender.command_receipt.v0\nstatus: stopped\nundoLabel: \n" + } + }, + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/live/stop_presence.py b/surfaces/blender/tests/live/stop_presence.py index a9b176d..b1889f8 100644 --- a/surfaces/blender/tests/live/stop_presence.py +++ b/surfaces/blender/tests/live/stop_presence.py @@ -5,6 +5,7 @@ BROKKR_ADDON_MODULE= BROKKR_CULTLIB= blender --factory-startup --python stop_presence.py -- + Run a second Blender on the same store with BROKKR_PHASE=closed for the sink-off, node-closed answer. The driver stands in for the operator's hands only: it ticks the sink preference on and runs the add-on's own "Stop agents" operator. Every intent is sent by brokkr-ctl; the add-on's timer drains them. Undo is read only here. @@ -109,18 +110,30 @@ BURST = 20 def s_setup(): + """A default install: no server, no snapshot, Auto Capture off, sink off. An idle session makes no store.""" + check("setup: default install, no node open and no store file", not adapter.node_open and not Path(CACHE).exists(), + [adapter.node_open, Path(CACHE).exists()]) + + +def s_idle_check(): + check("idle: with the sink off and no store, the timer has still opened no node and made no store", + not adapter.node_open and not Path(CACHE).exists(), [adapter.node_open, Path(CACHE).exists()]) + prefs.auto_drain_commands = True # the operator ticks the sink + + +def node_opened(): + return adapter.node_open + + +def s_open(): + check("sink on with the node closed: the timer opened the node itself (an empty node writes no file until something is put)", adapter.node_open, None) with win(): - bpy.ops.brokkr.start_server() - bpy.ops.brokkr.capture_snapshot() + bpy.ops.brokkr.capture_snapshot() # she presses Capture, so brokkr-ctl status has a snapshot to read code, out = ctl("status") - check("setup: server up, sink off, brokkr-ctl status shows agentCommandsEnabled: false", - adapter.server_status()["running"] and code == 0 and "agentCommandsEnabled: false" in out, out) + check("the stored snapshot says agentCommandsEnabled: true", code == 0 and "agentCommandsEnabled: true" in out, out) def s_burst(): - prefs.auto_drain_commands = True # the operator ticks the sink - code, out = ctl("status") - check("sink on: the stored snapshot follows the toggle (agentCommandsEnabled: true)", "agentCommandsEnabled: true" in out, out) S["procs"] = [spawn(f"B{n:02d}", "burst") for n in range(BURST)] @@ -227,6 +240,11 @@ def s_panel(): prefs.auto_drain_commands = True +def s_server_up(): + with win(): + bpy.ops.brokkr.start_server() + + def s_server_stop(): S["ids2"] = [send(f"S{n}", "server-stop") for n in range(3)] # the sender blocks Blender's thread: they cannot drain yet check("server stop: three intents queued behind a running server, sink on", len(pending()) == 3, len(pending())) @@ -279,8 +297,11 @@ def runner(): s_stop() i += 1 return 0.005 - if step in ("wait-done", "wait-late"): - if (finished if step == "wait-done" else late_done)(): + if step in ("wait-done", "wait-late", "wait-store", "wait-idle"): + if step == "wait-idle": + S["idle"] = S.get("idle", 0) + 1 + if {"wait-done": finished, "wait-late": late_done, "wait-store": node_opened, + "wait-idle": lambda: S.get("idle", 0) >= 15}[step](): i += 1 return 0.1 step() @@ -294,6 +315,23 @@ def runner(): return None -steps = [s_setup, s_burst, "wait-two", "wait-done", s_after_stop, s_late, "wait-late", s_late_check, s_reenabled, s_panel, - s_server_stop, s_server_start, s_final] +if os.environ.get("BROKKR_PHASE") == "closed": + # Phase two, a fresh Blender on the phase-one store: sink off, no node opened, a store on disk. A send must + # be answered stopped within a tick. + def s_closed(): + check("phase two: a store on disk from phase one, sink off, no snapshot published this session", + Path(CACHE).exists() and not prefs.auto_drain_commands and adapter.last_snapshot is None, None) + S["late_began"] = time.time() + S["late"] = subprocess.Popen([CTL, "blender", *SEND, "--set", 'name="Closed"', "--note", "closed", "--timeout", "10"], + env=ENV, stdout=subprocess.PIPE, text=True) + + def s_closed_check(): + out, code, took = S["late"].stdout.read(), S["late"].returncode, time.time() - S["late_began"] + R["notes"]["closed"] = {"exit": code, "seconds": round(took, 2), "out": out} + check("phase two: a send to a sink-off Blender with a closed node is answered stopped at once (exit 3)", + code == 3 and took < 5 and "agent commands are off" in out and not empties("Closed"), [code, took, out]) + steps = [s_closed, "wait-late", s_closed_check] +else: + steps = [s_setup, "wait-idle", s_idle_check, "wait-store", s_open, s_burst, "wait-two", "wait-done", s_after_stop, s_late, "wait-late", s_late_check, s_reenabled, s_panel, + s_server_up, s_server_stop, s_server_start, s_final] bpy.app.timers.register(runner, first_interval=3.0) diff --git a/surfaces/blender/tests/live/stop_presence.result.json b/surfaces/blender/tests/live/stop_presence.result.json index bb6f00b..ab9f8ee 100644 --- a/surfaces/blender/tests/live/stop_presence.result.json +++ b/surfaces/blender/tests/live/stop_presence.result.json @@ -3,39 +3,55 @@ "module": "bl_ext.user_default.brokkr_bridge", "checks": [ { - "name": "setup: server up, sink off, brokkr-ctl status shows agentCommandsEnabled: false", + "name": "setup: default install, no node open and no store file", "ok": true, - "detail": "observedAt: 2026-11-27T20:52:54.171327+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: Cube\nselectedObjectNames: [\"Cube\"]\nobjectCount: 3\nagentCommandsEnabled: false\n" + "detail": [ + false, + false + ] }, { - "name": "sink on: the stored snapshot follows the toggle (agentCommandsEnabled: true)", + "name": "idle: with the sink off and no store, the timer has still opened no node and made no store", "ok": true, - "detail": "observedAt: 2026-11-27T20:52:54.505375+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: Cube\nselectedObjectNames: [\"Cube\"]\nobjectCount: 3\nagentCommandsEnabled: true\n" + "detail": [ + false, + false + ] + }, + { + "name": "sink on with the node closed: the timer opened the node itself (an empty node writes no file until something is put)", + "ok": true, + "detail": null + }, + { + "name": "the stored snapshot says agentCommandsEnabled: true", + "ok": true, + "detail": "observedAt: 2026-11-27T21:04:00.546944+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: Cube\nselectedObjectNames: [\"Cube\"]\nobjectCount: 3\nagentCommandsEnabled: true\n" }, { "name": "stop: every one of the 20 intents has a receipt, each accepted or stopped, none missing", "ok": true, "detail": { - "01a21ec852a07e139e33eba7c8c21251": "accepted", - "01a21ec852b27442b17daac0eef61b81": "accepted", - "01a21ec852b47ae08561010021792ee2": "stopped", - "01a21ec852b77eb393c0f081d680b1d3": "stopped", - "01a21ec852ce78c0b66a2c2ce666f185": "stopped", - "01a21ec852cd7d30b8ec875ee4a9272e": "stopped", - "01a21ec852ce7582bff08d6a81921ee4": "stopped", - "01a21ec852e57a009ad0e186af6f0cfa": "stopped", - "01a21ec852e57cb3859bf2d738ef586a": "stopped", - "01a21ec852ec72c0bfd939a5bb39fde3": "stopped", - "01a21ec852ec78c28d7e16c9edc4cc07": "stopped", - "01a21ec8530772339db47b279044d6f5": "stopped", - "01a21ec853237550b1855dd0f0f27269": "stopped", - "01a21ec853347ac1b822f5d61ae8afcb": "stopped", - "01a21ec853457d418b3bd09272666916": "stopped", - "01a21ec853447c328eac215160e935d8": "stopped", - "01a21ec8535375309be1eec02df779f4": "stopped", - "01a21ec853577ba393761e10d99a14d5": "stopped", - "01a21ec853617913965abb873a2228b9": "stopped", - "01a21ec853617d41884613d8831720fe": "stopped" + "01a21ed27e2e74e1b8e725800116e4e8": "accepted", + "01a21ed27e347fc1a9335eece58a845e": "accepted", + "01a21ed27e51773392985e0e1859abec": "stopped", + "01a21ed27e6d7b53a39ad7e8d7316c8b": "stopped", + "01a21ed27e6f78c1a05ed37723e2b309": "stopped", + "01a21ed27e6d76f1bb533bed0a748a13": "stopped", + "01a21ed27e6d7c1092c429ea773c8fc1": "stopped", + "01a21ed27e6f7d33a2055b67edc92f18": "stopped", + "01a21ed27e8272e195d68ac7f7fdf699": "stopped", + "01a21ed27e897ba19eba4c3b3093126d": "stopped", + "01a21ed27e9379e3831640c51caf5f7a": "stopped", + "01a21ed27ea270008ef42324ca91b333": "stopped", + "01a21ed27e9472d3930a123edde8b2fd": "stopped", + "01a21ed27ed57222bce4b3537264e29c": "stopped", + "01a21ed27ea674d1bb4f93ccf3f84df2": "stopped", + "01a21ed27ed07ea180078e4a1d81fc24": "stopped", + "01a21ed27eb37ea3ac2277d337e6fad9": "stopped", + "01a21ed27ed07f63aa4a193a340243bd": "stopped", + "01a21ed27ed070408f8bd458009ab441": "stopped", + "01a21ed27ed27ba1ae1e97b2320d6264": "stopped" } }, { @@ -59,8 +75,8 @@ "name": "stop: each accepted intent is one labelled undo step the receipt names", "ok": true, "detail": [ - "Brokkr nibu/hands: createObject c8c21251", - "Brokkr nibu/hands: createObject eef61b81" + "Brokkr nibu/hands: createObject 0116e4e8", + "Brokkr nibu/hands: createObject e58a845e" ] }, { @@ -87,15 +103,15 @@ { "name": "stop: brokkr-ctl status now reads agentCommandsEnabled: false", "ok": true, - "detail": "observedAt: 2026-11-27T20:52:55.144050+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: B01\nselectedObjectNames: [\"B01\"]\nobjectCount: 5\nagentCommandsEnabled: false\n" + "detail": "observedAt: 2026-11-27T21:04:01.582528+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: B01\nselectedObjectNames: [\"B01\"]\nobjectCount: 5\nagentCommandsEnabled: false\n" }, { "name": "sink off: a send after Stop is answered stopped at once (wait exit 3, 'agent commands are off'), nothing queued", "ok": true, "detail": [ 3, - 0.6096086502075195, - "commandId: 01a21ec8598f754383d402238c3af85d\naction: createObject\ncommandId: 01a21ec8598f754383d402238c3af85d\nmessage: Stopped (agent commands are off); the intent was not run and nothing was changed.\nnote: late\nobjectName: \nobservedAt: 2026-11-27T20:52:56.732437+00:00\nrequestedBy: nibu/hands\nschema: brokkr.blender.command_receipt.v0\nstatus: stopped\nundoLabel: \n" + 0.6054728031158447, + "commandId: 01a21ed2867e7733982b0eaf93547dcc\naction: createObject\ncommandId: 01a21ed2867e7733982b0eaf93547dcc\nmessage: Stopped (agent commands are off); the intent was not run and nothing was changed.\nnote: late\nobjectName: \nobservedAt: 2026-11-27T21:04:03.327292+00:00\nrequestedBy: nibu/hands\nschema: brokkr.blender.command_receipt.v0\nstatus: stopped\nundoLabel: \n" ] }, { @@ -118,7 +134,7 @@ { "name": "panel mid-burst: Agents is first under Stop, the agent is active, accepted receipts show note and undo label, each once", "ok": true, - "detail": "Agents\nAgent commands: on\nActive: nibu/hands\nPending: 18\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject eef61b81\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject c8c21251\nProvider: brokkr.blender_editor\nTool: blender-editor\nBroker: cultmesh://brokkr\nNode: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp\nServer: cultnet://127.0.0.1:55445\nBind: 127.0.0.1:55445\ncultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py\nObject Sync\nTimeline / Cinemachine\nAd Hoc Sync Var\nObjects: 3\nMaterials: 2\nSelected: 1" + "detail": "Agents\nAgent commands: on\nActive: nibu/hands\nPending: 18\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject e58a845e\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject 0116e4e8\nProvider: brokkr.blender_editor\nTool: blender-editor\nBroker: cultmesh://brokkr\nNode: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp\nServer: stopped\nObject Sync\nTimeline / Cinemachine\nAd Hoc Sync Var\nObjects: 3\nMaterials: 2\nSelected: 1" }, { "name": "panel after Stop: Stop agents is the first operator drawn", @@ -132,7 +148,7 @@ { "name": "panel after Stop: commands off, pending 0, the stopped receipts listed with who and what", "ok": true, - "detail": "Agents\nAgent commands: off\nActive: nibu/hands\nPending: 0\nnibu/hands createObject stopped\n late\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nProvider: brokkr.blender_editor\nTool: blender-editor\nBroker: cultmesh://brokkr\nNode: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp\nServer: cultnet://127.0.0.1:55445\nBind: 127.0.0.1:55445\ncultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py\nObject Sync\nTimeline / Cinemachine\nAd Hoc Sync Var\nObjects: 4\nMaterials: 2\nSelected: 1" + "detail": "Agents\nAgent commands: off\nActive: nibu/hands\nPending: 0\nnibu/hands createObject stopped\n late\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nProvider: brokkr.blender_editor\nTool: blender-editor\nBroker: cultmesh://brokkr\nNode: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp\nServer: stopped\nObject Sync\nTimeline / Cinemachine\nAd Hoc Sync Var\nObjects: 4\nMaterials: 2\nSelected: 1" }, { "name": "server stop: three intents queued behind a running server, sink on", @@ -167,108 +183,108 @@ ], "notes": { "states": { - "01a21ec852a07e139e33eba7c8c21251": "accepted", - "01a21ec852b27442b17daac0eef61b81": "accepted", - "01a21ec852b47ae08561010021792ee2": "stopped", - "01a21ec852b77eb393c0f081d680b1d3": "stopped", - "01a21ec852ce78c0b66a2c2ce666f185": "stopped", - "01a21ec852cd7d30b8ec875ee4a9272e": "stopped", - "01a21ec852ce7582bff08d6a81921ee4": "stopped", - "01a21ec852e57a009ad0e186af6f0cfa": "stopped", - "01a21ec852e57cb3859bf2d738ef586a": "stopped", - "01a21ec852ec72c0bfd939a5bb39fde3": "stopped", - "01a21ec852ec78c28d7e16c9edc4cc07": "stopped", - "01a21ec8530772339db47b279044d6f5": "stopped", - "01a21ec853237550b1855dd0f0f27269": "stopped", - "01a21ec853347ac1b822f5d61ae8afcb": "stopped", - "01a21ec853457d418b3bd09272666916": "stopped", - "01a21ec853447c328eac215160e935d8": "stopped", - "01a21ec8535375309be1eec02df779f4": "stopped", - "01a21ec853577ba393761e10d99a14d5": "stopped", - "01a21ec853617913965abb873a2228b9": "stopped", - "01a21ec853617d41884613d8831720fe": "stopped" + "01a21ed27e2e74e1b8e725800116e4e8": "accepted", + "01a21ed27e347fc1a9335eece58a845e": "accepted", + "01a21ed27e51773392985e0e1859abec": "stopped", + "01a21ed27e6d7b53a39ad7e8d7316c8b": "stopped", + "01a21ed27e6f78c1a05ed37723e2b309": "stopped", + "01a21ed27e6d76f1bb533bed0a748a13": "stopped", + "01a21ed27e6d7c1092c429ea773c8fc1": "stopped", + "01a21ed27e6f7d33a2055b67edc92f18": "stopped", + "01a21ed27e8272e195d68ac7f7fdf699": "stopped", + "01a21ed27e897ba19eba4c3b3093126d": "stopped", + "01a21ed27e9379e3831640c51caf5f7a": "stopped", + "01a21ed27ea270008ef42324ca91b333": "stopped", + "01a21ed27e9472d3930a123edde8b2fd": "stopped", + "01a21ed27ed57222bce4b3537264e29c": "stopped", + "01a21ed27ea674d1bb4f93ccf3f84df2": "stopped", + "01a21ed27ed07ea180078e4a1d81fc24": "stopped", + "01a21ed27eb37ea3ac2277d337e6fad9": "stopped", + "01a21ed27ed07f63aa4a193a340243bd": "stopped", + "01a21ed27ed070408f8bd458009ab441": "stopped", + "01a21ed27ed27ba1ae1e97b2320d6264": "stopped" }, "stop_reasons": [ "Stopped (stopped by the operator); the intent wa" ], "wait_exits": { - "01a21ec852a07e139e33eba7c8c21251": [ + "01a21ed27e2e74e1b8e725800116e4e8": [ "accepted", 0 ], - "01a21ec852b27442b17daac0eef61b81": [ + "01a21ed27e347fc1a9335eece58a845e": [ "accepted", 0 ], - "01a21ec852b47ae08561010021792ee2": [ + "01a21ed27e51773392985e0e1859abec": [ "stopped", 3 ], - "01a21ec852b77eb393c0f081d680b1d3": [ + "01a21ed27e6d7b53a39ad7e8d7316c8b": [ "stopped", 3 ], - "01a21ec852ce78c0b66a2c2ce666f185": [ + "01a21ed27e6f78c1a05ed37723e2b309": [ "stopped", 3 ], - "01a21ec852cd7d30b8ec875ee4a9272e": [ + "01a21ed27e6d76f1bb533bed0a748a13": [ "stopped", 3 ], - "01a21ec852ce7582bff08d6a81921ee4": [ + "01a21ed27e6d7c1092c429ea773c8fc1": [ "stopped", 3 ], - "01a21ec852e57a009ad0e186af6f0cfa": [ + "01a21ed27e6f7d33a2055b67edc92f18": [ "stopped", 3 ], - "01a21ec852e57cb3859bf2d738ef586a": [ + "01a21ed27e8272e195d68ac7f7fdf699": [ "stopped", 3 ], - "01a21ec852ec72c0bfd939a5bb39fde3": [ + "01a21ed27e897ba19eba4c3b3093126d": [ "stopped", 3 ], - "01a21ec852ec78c28d7e16c9edc4cc07": [ + "01a21ed27e9379e3831640c51caf5f7a": [ "stopped", 3 ], - "01a21ec8530772339db47b279044d6f5": [ + "01a21ed27ea270008ef42324ca91b333": [ "stopped", 3 ], - "01a21ec853237550b1855dd0f0f27269": [ + "01a21ed27e9472d3930a123edde8b2fd": [ "stopped", 3 ], - "01a21ec853347ac1b822f5d61ae8afcb": [ + "01a21ed27ed57222bce4b3537264e29c": [ "stopped", 3 ], - "01a21ec853457d418b3bd09272666916": [ + "01a21ed27ea674d1bb4f93ccf3f84df2": [ "stopped", 3 ], - "01a21ec853447c328eac215160e935d8": [ + "01a21ed27ed07ea180078e4a1d81fc24": [ "stopped", 3 ], - "01a21ec8535375309be1eec02df779f4": [ + "01a21ed27eb37ea3ac2277d337e6fad9": [ "stopped", 3 ], - "01a21ec853577ba393761e10d99a14d5": [ + "01a21ed27ed07f63aa4a193a340243bd": [ "stopped", 3 ], - "01a21ec853617913965abb873a2228b9": [ + "01a21ed27ed070408f8bd458009ab441": [ "stopped", 3 ], - "01a21ec853617d41884613d8831720fe": [ + "01a21ed27ed27ba1ae1e97b2320d6264": [ "stopped", 3 ] @@ -276,7 +292,7 @@ "late": { "exit": 3, "seconds": 0.61, - "out": "commandId: 01a21ec8598f754383d402238c3af85d\naction: createObject\ncommandId: 01a21ec8598f754383d402238c3af85d\nmessage: Stopped (agent commands are off); the intent was not run and nothing was changed.\nnote: late\nobjectName: \nobservedAt: 2026-11-27T20:52:56.732437+00:00\nrequestedBy: nibu/hands\nschema: brokkr.blender.command_receipt.v0\nstatus: stopped\nundoLabel: \n" + "out": "commandId: 01a21ed2867e7733982b0eaf93547dcc\naction: createObject\ncommandId: 01a21ed2867e7733982b0eaf93547dcc\nmessage: Stopped (agent commands are off); the intent was not run and nothing was changed.\nnote: late\nobjectName: \nobservedAt: 2026-11-27T21:04:03.327292+00:00\nrequestedBy: nibu/hands\nschema: brokkr.blender.command_receipt.v0\nstatus: stopped\nundoLabel: \n" }, "panel_before_stop": [ "Agents", @@ -285,17 +301,15 @@ "Pending: 18", "nibu/hands createObject accepted", " burst", - " Brokkr nibu/hands: createObject eef61b81", + " Brokkr nibu/hands: createObject e58a845e", "nibu/hands createObject accepted", " burst", - " Brokkr nibu/hands: createObject c8c21251", + " Brokkr nibu/hands: createObject 0116e4e8", "Provider: brokkr.blender_editor", "Tool: blender-editor", "Broker: cultmesh://brokkr", "Node: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp", - "Server: cultnet://127.0.0.1:55445", - "Bind: 127.0.0.1:55445", - "cultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py", + "Server: stopped", "Object Sync", "Timeline / Cinemachine", "Ad Hoc Sync Var", @@ -328,9 +342,7 @@ "Tool: blender-editor", "Broker: cultmesh://brokkr", "Node: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp", - "Server: cultnet://127.0.0.1:55445", - "Bind: 127.0.0.1:55445", - "cultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py", + "Server: stopped", "Object Sync", "Timeline / Cinemachine", "Ad Hoc Sync Var", diff --git a/surfaces/blender/tests/test_stop_presence.py b/surfaces/blender/tests/test_stop_presence.py index 1126a2a..4583ce0 100644 --- a/surfaces/blender/tests/test_stop_presence.py +++ b/surfaces/blender/tests/test_stop_presence.py @@ -4,6 +4,7 @@ the panel's agent activity is derived from receipts. A fake bpy and a fake node from __future__ import annotations import re +import tempfile import types import unittest import unittest.mock @@ -331,10 +332,30 @@ class TimerTests(unittest.TestCase): self.assertEqual(self.drains, []) self.assertEqual([call[0] for call in self.stops], ["agent commands are off"]) - def test_with_the_sink_off_and_no_node_open_the_timer_opens_nothing(self): + def test_with_the_sink_on_and_no_node_open_the_timer_still_drains(self): + self.target._node = None + self.ran = 1 + addon._auto_drain_commands() + self.assertEqual(len(self.drains), 1) + + def test_with_the_sink_off_and_an_existing_store_a_closed_node_still_answers_stopped(self): self.prefs.auto_drain_commands = False self.target._node = None - addon._auto_drain_commands() + with tempfile.TemporaryDirectory() as tmp: + store = Path(tmp) / "node.ccmp" + store.write_bytes(b"") + self.prefs.cultmesh_cache_path = str(store) + addon._auto_drain_commands() + self.assertEqual([call[0] for call in self.stops], ["agent commands are off"]) + + def test_an_idle_session_creates_no_store_and_answers_nothing(self): + self.prefs.auto_drain_commands = False + self.target._node = None + with tempfile.TemporaryDirectory() as tmp: + store = Path(tmp) / "node.ccmp" + self.prefs.cultmesh_cache_path = str(store) + addon._auto_drain_commands() + self.assertFalse(store.exists()) self.assertEqual((self.stops, self.drains, self.counts), ([], [], [])) From 54478cd0ad1715c056fa2be9b52b49c00cdd0095 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 22:19:53 +0100 Subject: [PATCH 28/63] Perception: look captures her 3D view to a scratch PNG; the snapshot carries Edit Mode selection, a session id and human-edit sequences look is a read action under run_intent (no undo step, allowed in Edit Mode). It overrides screenshot_area to the largest VIEW_3D area's WINDOW region, writes /look/.png and prunes to the newest 20. Human-edit tracking is always on and separate from auto_capture; nothing admits or refuses an intent on it. Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/brokkr_bridge/__init__.py | 30 ++ .../blender/brokkr_bridge/blender_target.py | 125 ++++- surfaces/blender/tests/test_addon_ui.py | 2 +- surfaces/blender/tests/test_perception.py | 483 ++++++++++++++++++ surfaces/blender/tests/test_scene_actions.py | 5 +- 5 files changed, 639 insertions(+), 6 deletions(-) create mode 100644 surfaces/blender/tests/test_perception.py diff --git a/surfaces/blender/brokkr_bridge/__init__.py b/surfaces/blender/brokkr_bridge/__init__.py index 4926385..58fd75b 100644 --- a/surfaces/blender/brokkr_bridge/__init__.py +++ b/surfaces/blender/brokkr_bridge/__init__.py @@ -672,6 +672,30 @@ def _auto_capture(scene, depsgraph): ) +# Human-edit tracking is always on and reads no preference: it must not depend on auto_capture. Persistent, so +# opening another file does not drop them. +@bpy.app.handlers.persistent +def _track_human_edits(scene, depsgraph): + target().track_human_edits(depsgraph) + + +@bpy.app.handlers.persistent +def _track_undo_redo(scene, *_): + target().note_undo_redo() + + +@bpy.app.handlers.persistent +def _new_session(*_): + target().renew_session() + + +_PERCEPTION_HANDLERS = ( + ("depsgraph_update_post", _track_human_edits), + ("undo_post", _track_undo_redo), + ("redo_post", _track_undo_redo), + ("load_post", _new_session), +) + BUSY_INTERVAL = 0.05 # one intent per tick: Stop is a UI event, and it lands between two intents IDLE_INTERVAL = 1.0 @@ -733,6 +757,9 @@ def register(): bpy.utils.register_class(cls) if _auto_capture not in bpy.app.handlers.depsgraph_update_post: bpy.app.handlers.depsgraph_update_post.append(_auto_capture) + for name, handler in _PERCEPTION_HANDLERS: + if handler not in getattr(bpy.app.handlers, name): + getattr(bpy.app.handlers, name).append(handler) if not bpy.app.timers.is_registered(_auto_drain_commands): bpy.app.timers.register(_auto_drain_commands, first_interval=1.0, persistent=True) @@ -740,6 +767,9 @@ def register(): def unregister(): if _auto_capture in bpy.app.handlers.depsgraph_update_post: bpy.app.handlers.depsgraph_update_post.remove(_auto_capture) + for name, handler in _PERCEPTION_HANDLERS: + if handler in getattr(bpy.app.handlers, name): + getattr(bpy.app.handlers, name).remove(handler) if bpy.app.timers.is_registered(_auto_drain_commands): bpy.app.timers.unregister(_auto_drain_commands) global _target diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 363e017..c69a493 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -45,8 +45,8 @@ CREATABLE_OBJECT_TYPES = ("MESH", "LIGHT", "CAMERA", "EMPTY") GL_RENDER_ENGINES = ("BLENDER_WORKBENCH", "BLENDER_EEVEE", "BLENDER_EEVEE_NEXT") GL_RUNTIME_LIBRARY = "libEGL.so.1" -# Actions that only read the scene and so push no undo step (live-5 adds look). -READ_ACTIONS: tuple[str, ...] = () +# Actions that only read the scene and so push no undo step. +READ_ACTIONS = ("look",) MUTATING_ACTIONS = ( "createObject", "deleteObject", "setObjectTransform", "setObjectVisibility", "setObjectParent", "setObjectCustomProperty", "selectObject", "assignMaterial", "importGltf", "exportGltf", @@ -57,8 +57,11 @@ MUTATING_ACTIONS = ( NO_SCENE_CHANGE_ACTIONS = ("exportGltf", "renderStill") # While an object is in Edit Mode, undo steps are edit-mesh steps, so a scene write is not reverted by # one undo, and some operators leave Edit Mode (brokkr-live:ruling:object-intents-refused-in-edit-mode). -# Anything that writes scene state or changes her mode is refused; renderStill does neither. -EDIT_MODE_SAFE_ACTIONS = ("renderStill",) +# Anything that writes scene state or changes her mode is refused; renderStill and look do neither. +EDIT_MODE_SAFE_ACTIONS = ("renderStill", "look") +LOOK_DIR = "look" # under the output directory: scratch captures named by command id (brush-tree:ruling:look-files-are-scratch) +LOOK_KEPT = 20 # the newest captures that stay after each look +EDIT_SELECTION_CAP = 4096 # indices listed per element kind and object; the total stays true beside the list REQUESTED_BY_SHAPE = re.compile(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$") # A commandId becomes part of a receipt key, so it is a short string of key-safe characters ('.' is left # out: it separates the '.denied' suffix). @@ -121,6 +124,11 @@ class BrokkrBlenderTarget: self._recent: deque[dict[str, Any]] = deque(maxlen=RECEIPTS_KEPT) # display cache of the node's receipts self._receipts_loaded = False self.pending_count = 0 # display cache: intents queued in the node + # What she did, as observed: nothing reads these back to admit or refuse an intent (scene-last-writer-wins). + self.session_id = uuid.uuid4().hex + self.human_edit_seq = 0 + self._last_human_edit: dict[str, int] = {} # object name -> human_edit_seq when she last changed it + self._looked: dict[str, int] = {} # requestedBy -> human_edit_seq at that agent's last look def configure_action_dirs(self, import_dir: str, output_dir: str) -> None: """The directories importGltf and renderStill may touch; empty leaves that action disabled.""" @@ -593,6 +601,9 @@ class BrokkrBlenderTarget: "activeScene": active_scene, "activeObjectName": active_object, "mode": context.mode, + "sessionId": self.session_id, + "humanEditSeq": self.human_edit_seq, + "editSelection": self.edit_selection(), "selectedObjectNames": selected, "sceneCount": len(bpy.data.scenes), "objectCount": len(bpy.data.objects), @@ -702,6 +713,8 @@ class BrokkrBlenderTarget: return self._set_world(context, command) if action == "renderStill": return self._render_still(context, command) + if action == "look": + return self._look(context, command) if action in na.NodeActions.ACTIONS: message, name = self.nodes.execute(action, command) self._wrote = self.nodes.changed @@ -1034,6 +1047,108 @@ class BrokkrBlenderTarget: render.image_settings.file_format, scene.camera) = saved return self._receipt(command, "accepted", f"Rendered still to {path.name}.", scene.name) + # ---- perception: what she sees and what she did ---------------------------------------------------------- + + def renew_session(self) -> None: + """A new session id and zeroed counters: names mean something else in a freshly loaded file.""" + self.session_id = uuid.uuid4().hex + self.human_edit_seq = 0 + self._last_human_edit.clear() + self._looked.clear() + + def track_human_edits(self, depsgraph: Any) -> None: + """A depsgraph update outside an agent turn is hers. What changed is read from each update's flags, never + from presence in the list: an update also names what only depends on the change.""" + if self.agent_turn: + return + changed = [u.id.name for u in depsgraph.updates + if u.id.id_type == "OBJECT" and (u.is_updated_transform or u.is_updated_geometry or u.is_updated_shading)] + if not changed: + return + self.human_edit_seq += 1 + for name in changed: + self._last_human_edit[name] = self.human_edit_seq + + def note_undo_redo(self) -> None: + """An undo or redo cannot be narrowed to objects from its updates, so it moves the session counter only.""" + self.human_edit_seq += 1 + + def last_human_edit_seq(self, name: str) -> int: + return self._last_human_edit.get(name, 0) + + def edit_selection(self) -> list[dict[str, Any]]: + """Her selection in every object in Edit Mode, read live from the edit mesh without leaving the mode.""" + editing = [obj for obj in self.bpy.data.objects if getattr(obj, "mode", "OBJECT") == "EDIT"] + entries: list[dict[str, Any]] = [] + if not editing: + return entries + import bmesh # exists only inside Blender; nothing is imported when no object is being edited + for obj in editing: + if obj.type != "MESH": + entries.append({"name": obj.name, "type": obj.type, "unsupported": True}) + continue + mesh = bmesh.from_edit_mesh(obj.data) + entry: dict[str, Any] = {"name": obj.name, "type": obj.type} + for key, elements in (("vertices", mesh.verts), ("edges", mesh.edges), ("faces", mesh.faces)): + chosen = [index for index, element in enumerate(elements) if element.select] + entry[key] = chosen[:EDIT_SELECTION_CAP] + entry[key + "Total"] = len(chosen) + entries.append(entry) + return entries + + def _viewport(self) -> tuple[Any, Any, Any]: + """The window, area and WINDOW region of the largest 3D view: the only pixels look may read.""" + best = None + for window in self.bpy.context.window_manager.windows: + for area in window.screen.areas: + if area.type == "VIEW_3D" and (best is None or area.width * area.height > best[1].width * best[1].height): + best = (window, area) + region = next((r for r in best[1].regions if r.type == "WINDOW"), None) if best else None + if region is None: + raise sa.ActionRefused("No 3D viewport is open to look at.") + return best[0], best[1], region + + def _look(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + """Capture her 3D view to /look/.png. screenshot_area reads Blender's own framebuffer + for the area it is overridden to, so the desktop and other applications are never in the picture; a menu or + popup Blender draws over the view is, as she sees it.""" + name = f"{LOOK_DIR}/{command['commandId']}.png" + path = sa.resolve_inside(self.output_dir, name, "output", new_file=True) + window, area, region = self._viewport() + path.parent.mkdir(parents=True, exist_ok=True) + if sa.resolve_inside(self.output_dir, name, "output", new_file=True) != path: + raise sa.ActionRefused("Output path changed while it was being checked.") + with self.bpy.context.temp_override(window=window, area=area, region=region): + result = self.bpy.ops.screen.screenshot_area("EXEC_DEFAULT", False, filepath=str(path)) + if "FINISHED" not in result or not path.is_file(): + raise sa.ActionRefused("Blender did not write the capture.") + self._prune_looks(path.parent) + requested_by = command["requestedBy"] + since = self._looked.get(requested_by, 0) + self._looked[requested_by] = self.human_edit_seq + receipt = self._receipt(command, "accepted", f"Captured the 3D view to {LOOK_DIR}/{path.name}.", "") + receipt.update({ + "lookPath": str(path), + "sessionId": self.session_id, + "humanEditSeq": self.human_edit_seq, + "humanEditsSinceLook": self.human_edit_seq - since, + "editedSinceLook": sorted(n for n, seq in self._last_human_edit.items() if seq > since), + "editSelection": self.edit_selection(), + }) + self._wrote = False + return receipt + + @staticmethod + def _prune_looks(directory: Path) -> None: + """Keep the newest LOOK_KEPT captures: plain .png files directly in the look directory, nothing else.""" + found = [] + with os.scandir(directory) as entries: + for entry in entries: + if entry.name.lower().endswith(".png") and entry.is_file(follow_symlinks=False): + found.append((entry.stat(follow_symlinks=False).st_mtime_ns, entry.name, entry.path)) + for _mtime, _name, old in sorted(found)[:-LOOK_KEPT]: + os.unlink(old) + def _resolve_object(self, command: dict[str, Any]) -> Any: name = command.get("targetObjectName") or command.get("objectName") return self.bpy.data.objects.get(name) if name else None @@ -1061,6 +1176,7 @@ class BrokkrBlenderTarget: "scale": _to_list(obj.scale), "visible": bool(obj.visible_get()), "selected": bool(obj.select_get()), + "lastHumanEditSeq": self.last_human_edit_seq(obj.name), "parentName": obj.parent.name if obj.parent else "", "collections": [collection.name for collection in obj.users_collection], "materials": [slot.material.name for slot in obj.material_slots if slot.material], @@ -1196,6 +1312,7 @@ class BrokkrBlenderTarget: "requestedBy": command["requestedBy"] if isinstance(command.get("requestedBy"), str) else "", "note": command["note"][:NOTE_LIMIT] if isinstance(command.get("note"), str) else "", "undoLabel": "", + "lookPath": "", "observedAt": _now(), } diff --git a/surfaces/blender/tests/test_addon_ui.py b/surfaces/blender/tests/test_addon_ui.py index 04e97d3..74c8a24 100644 --- a/surfaces/blender/tests/test_addon_ui.py +++ b/surfaces/blender/tests/test_addon_ui.py @@ -32,7 +32,7 @@ def load_addon(): fake = types.ModuleType("bpy") fake.types = NS(AddonPreferences=Base, Panel=Base, Operator=Base) fake.props = props - fake.app = NS(handlers=NS(depsgraph_update_post=[]), timers=NS(is_registered=lambda f: False)) + fake.app = NS(handlers=NS(depsgraph_update_post=[], persistent=lambda f: setattr(f, "persistent", True) or f), timers=NS(is_registered=lambda f: False)) fake.utils = NS() previous = sys.modules.get("bpy") sys.modules["bpy"] = fake diff --git a/surfaces/blender/tests/test_perception.py b/surfaces/blender/tests/test_perception.py new file mode 100644 index 0000000..ee793e8 --- /dev/null +++ b/surfaces/blender/tests/test_perception.py @@ -0,0 +1,483 @@ +"""Perception: look captures her 3D view, the snapshot carries her Edit Mode selection, a session id and +human-edit sequences. A fake bpy, a fake bmesh and fake depsgraphs; no Blender. +""" +from __future__ import annotations + +import contextlib +import inspect +import os +import re +import sys +import types +import unittest +import unittest.mock +from pathlib import Path + +import test_scene_actions as ts +import test_addon_ui as ui + +bt = ts.bt +NS = types.SimpleNamespace +addon = ui.addon +BRIDGE = Path(bt.__file__).parent +PNG = b"\x89PNG\r\n\x1a\n" + b"x" * 32 + + +def area(kind, width, height, name=None): + return NS(type=kind, width=width, height=height, name=name or kind, + regions=[NS(type="HEADER"), NS(type="WINDOW", width=width, height=height)]) + + +def window(*areas): + return NS(screen=NS(areas=list(areas))) + + +class Element: + def __init__(self, selected): + self.select = selected + + +class FakeBmesh: + """bmesh.from_edit_mesh(mesh) -> a mesh with verts, edges and faces that carry .select.""" + def __init__(self, meshes): + self.meshes = meshes + self.reads = 0 + + def from_edit_mesh(self, mesh): + self.reads += 1 + verts, edges, faces = self.meshes[id(mesh)] + return NS(verts=[Element(s) for s in verts], edges=[Element(s) for s in edges], + faces=[Element(s) for s in faces]) + + +class PerceptionFixture(unittest.TestCase): + """The scene fixture plus a window with a 3D view, a screenshot operator and a bmesh.""" + run_action = ts.ActionTests.run_action + + def setUp(self): + ts.ActionTests.setUp(self) + self.view = area("VIEW_3D", 1574, 888) + self.windows = [window(area("PROPERTIES", 300, 900), self.view, area("TIMELINE", 1600, 100))] + self.stack, self.shots, self.shot_result, self.shot_writes = [], [], {"FINISHED"}, True + bpy = self.bpy + bpy.context.window_manager.windows = self.windows + bpy.context.temp_override = self.override + bpy.ops.screen = NS(screenshot_area=self.screenshot) + bpy.mesh_data = NS(name="CubeMesh", vertices=[], edges=[], polygons=[], uv_layers=[], shape_keys=None) + bpy.mesh.data = bpy.mesh_data + bpy.mesh.mode = "OBJECT" + self.bmesh = FakeBmesh({id(bpy.mesh_data): ([True, False, True], [False, True], [False])}) + patch = unittest.mock.patch.dict(sys.modules, {"bmesh": self.bmesh}) + patch.start() + self.addCleanup(patch.stop) + bpy.data.scenes = [bpy.scene] + + @contextlib.contextmanager + def override(self, **kw): + self.stack.append(kw) + try: + yield + finally: + self.stack.pop() + + def screenshot(self, mode, undo, filepath): + assert (mode, undo) == ("EXEC_DEFAULT", False) # operators run with undo off + self.shots.append((dict(self.stack[-1]) if self.stack else None, filepath)) + if self.shot_writes: + Path(filepath).write_bytes(PNG) + return self.shot_result + + def look(self, **command): + return self.run_action(action="look", **command) + + def look_dir(self): + return self.root / "out" / "look" + + +class LookTests(PerceptionFixture): + def test_look_is_a_read_action(self): + receipt = self.look(commandId="look-0001") + self.assertEqual(receipt["status"], "accepted", receipt["message"]) + self.assertEqual(self.bpy.undo.pushes, []) # reads push no undo step + self.assertEqual(receipt["undoLabel"], "") + self.assertEqual(Path(receipt["lookPath"]), self.look_dir() / "look-0001.png") + self.assertEqual((self.look_dir() / "look-0001.png").read_bytes(), PNG) + self.assertEqual(self.bpy.created, []) + + def test_other_receipts_carry_an_empty_look_path(self): + self.assertEqual(self.run_action(action="createObject", objectType="EMPTY")["lookPath"], "") + + def test_look_captures_only_the_largest_3d_view_and_its_window_region(self): + # the capture is scoped to one area's WINDOW region: that is what keeps the desktop and every + # other Blender area out of the picture + small = area("VIEW_3D", 400, 300) + big = area("VIEW_3D", 1600, 900) + second = window(area("OUTLINER", 3000, 3000), small) + self.windows.append(second) + self.windows[0].screen.areas.append(big) + self.look() + override, path = self.shots[0] + self.assertIs(override["area"], big) + self.assertIs(override["window"], self.windows[0]) + self.assertEqual((override["region"].type, override["region"].width), ("WINDOW", 1600)) + self.assertEqual(len(self.shots), 1) + + def test_look_in_a_second_window_uses_that_window(self): + only = area("VIEW_3D", 800, 600) + self.windows[0].screen.areas.remove(self.view) + self.windows.append(window(only)) + self.look() + self.assertIs(self.shots[0][0]["window"], self.windows[1]) + self.assertIs(self.shots[0][0]["area"], only) + + def test_look_without_a_3d_view_is_refused_and_captures_nothing(self): + self.windows[0].screen.areas.remove(self.view) + receipt = self.look() + self.assertEqual(receipt["status"], "failed") + self.assertIn("3D", receipt["message"]) + self.assertEqual((self.shots, receipt["lookPath"]), ([], "")) + self.assertFalse(self.look_dir().exists()) + self.assertEqual(self.bpy.undo.pushes, []) + + def test_look_without_an_output_directory_is_refused(self): + self.target.configure_action_dirs(str(self.root / "in"), "") + receipt = self.look() + self.assertEqual(receipt["status"], "failed") + self.assertIn("output", receipt["message"]) + self.assertEqual(self.shots, []) + + def test_a_cancelled_or_unwritten_capture_is_a_failed_receipt_with_no_path(self): + self.shot_result = {"CANCELLED"} + receipt = self.look(commandId="look-c1") + self.assertEqual((receipt["status"], receipt["lookPath"]), ("failed", "")) + self.shot_result, self.shot_writes = {"FINISHED"}, False + receipt = self.look(commandId="look-c2") + self.assertEqual((receipt["status"], receipt["lookPath"]), ("failed", "")) + + def test_look_works_in_edit_mode_and_leaves_her_mode_alone(self): + self.bpy.mesh.mode = "EDIT" + receipt = self.look() + self.assertEqual(receipt["status"], "accepted", receipt["message"]) + self.assertEqual(self.bpy.mesh.mode, "EDIT") + self.assertEqual(self.run_action(action="createObject", objectType="EMPTY")["status"], "denied") + + def test_look_prunes_to_twenty(self): + # look-files-are-scratch: the newest twenty files stay, the capture just taken among them + self.look_dir().mkdir(parents=True) + for n in range(30): + old = self.look_dir() / f"old-{n:02d}.png" + old.write_bytes(PNG) + os.utime(old, (1_000_000 + n, 1_000_000 + n)) + receipt = self.look(commandId="look-new") + kept = sorted(p.name for p in self.look_dir().iterdir()) + self.assertEqual(len(kept), 20, kept) + self.assertIn("look-new.png", kept) + self.assertEqual([k for k in kept if k != "look-new.png"], [f"old-{n:02d}.png" for n in range(11, 30)]) # the newest 19 of the old + self.assertTrue(Path(receipt["lookPath"]).is_file()) + + def test_the_pruning_below_the_cap_removes_nothing(self): + for n in range(19): + self.look(commandId=f"look-{n:03d}") + self.assertEqual(len(list(self.look_dir().iterdir())), 19) + self.look(commandId="look-last") + self.assertEqual(len(list(self.look_dir().iterdir())), 20) + + def test_pruning_touches_only_png_files_directly_inside_look(self): + self.look_dir().mkdir(parents=True) + (self.root / "out" / "keep.png").write_bytes(PNG) + (self.look_dir() / "notes.txt").write_text("x") + (self.look_dir() / "dir.png").mkdir() + for n in range(25): + f = self.look_dir() / f"old-{n:02d}.png" + f.write_bytes(PNG) + os.utime(f, (1_000_000 + n, 1_000_000 + n)) + self.look() + self.assertTrue((self.root / "out" / "keep.png").exists()) + self.assertTrue((self.look_dir() / "notes.txt").exists()) + self.assertTrue((self.look_dir() / "dir.png").is_dir()) + self.assertEqual(len([p for p in self.look_dir().iterdir() if p.suffix == ".png" and p.is_file()]), 20) + + def test_a_refused_look_prunes_nothing(self): + self.look_dir().mkdir(parents=True) + for n in range(30): + (self.look_dir() / f"old-{n:02d}.png").write_bytes(PNG) + self.windows[0].screen.areas.remove(self.view) + self.look() + self.assertEqual(len(list(self.look_dir().iterdir())), 30) + + def test_a_refusal_does_not_echo_the_output_path(self): + self.windows[0].screen.areas.remove(self.view) + self.assertNotIn(str(self.root), self.look()["message"]) + + +def rich(obj): + """What the real _object_snapshot reads of an object.""" + for key, value in dict(library=None, location=(0.0, 0.0, 0.0), rotation_euler=(0.0, 0.0, 0.0), scale=(1.0, 1.0, 1.0), + parent=None, users_collection=[], material_slots=[], modifiers=[], constraints=[]).items(): + setattr(obj, key, value) + obj.visible_get = lambda: True + obj.items = lambda: [] + obj.mode = getattr(obj, "mode", "OBJECT") + return obj + + +class EditSelectionTests(PerceptionFixture): + def snapshot(self): + for obj in self.bpy.data.objects: + rich(obj) + self.bpy.camera_data.name, self.bpy.light_data.name, self.bpy.camera_data.angle = "CamData", "LightData", 0.6 + self.bpy.app.version = (5, 3, 0) + self.bpy.data.filepath = "" + for name in ("collections", "materials", "images"): + setattr(self.bpy.data, name, []) + self.bpy.scene.frame_current = self.bpy.scene.frame_start = self.bpy.scene.frame_end = 1 + self.bpy.scene.collection = None + context = NS(selected_objects=[], active_object=None, scene=self.bpy.scene, mode="EDIT_MESH") + with unittest.mock.patch.object(self.target, "_evaluated_snapshot", return_value=None): + return self.target.capture_snapshot(context, False) + + def test_selection_is_read_from_the_edit_mesh_without_leaving_edit_mode(self): + self.bpy.mesh.mode = "EDIT" + selection = self.target.edit_selection() + self.assertEqual(selection, [{"name": "Cube", "type": "MESH", + "vertices": [0, 2], "verticesTotal": 2, + "edges": [1], "edgesTotal": 1, + "faces": [], "facesTotal": 0}]) + self.assertEqual(self.bpy.mesh.mode, "EDIT") + self.assertEqual(self.bmesh.reads, 1) + + def test_nothing_in_edit_mode_is_an_empty_list_and_reads_no_mesh(self): + self.assertEqual(self.target.edit_selection(), []) + self.assertEqual(self.bmesh.reads, 0) + + def test_each_list_is_capped_at_4096_with_the_true_total_beside_it(self): + self.bpy.mesh.mode = "EDIT" + self.bmesh.meshes[id(self.bpy.mesh_data)] = ([True] * 5000, [False] * 5000 + [True], [True] * 4096) + entry = self.target.edit_selection()[0] + self.assertEqual((len(entry["vertices"]), entry["verticesTotal"]), (4096, 5000)) + self.assertEqual(entry["vertices"][:3], [0, 1, 2]) + self.assertEqual((entry["edges"], entry["edgesTotal"]), ([5000], 1)) + self.assertEqual((len(entry["faces"]), entry["facesTotal"]), (4096, 4096)) + + def test_every_object_in_edit_mode_is_listed_and_a_non_mesh_says_unsupported(self): + self.bpy.mesh.mode = "EDIT" + self.bpy.cam.mode = "EDIT" + names = {e["name"]: e for e in self.target.edit_selection()} + self.assertEqual(sorted(names), ["Cam", "Cube"]) + self.assertEqual(names["Cam"], {"name": "Cam", "type": "CAMERA", "unsupported": True}) + + def test_the_snapshot_carries_selection_session_and_sequences(self): + self.bpy.mesh.mode = "EDIT" + snap = self.snapshot() + self.assertEqual(snap["editSelection"][0]["vertices"], [0, 2]) + self.assertEqual(snap["sessionId"], self.target.session_id) + self.assertEqual(snap["humanEditSeq"], 0) + self.assertTrue(all(o["lastHumanEditSeq"] == 0 for o in snap["objects"])) + self.assertEqual(self.snapshot()["sessionId"], snap["sessionId"]) + + def test_the_object_snapshot_carries_the_last_human_edit_sequence(self): + self.target._last_human_edit["Cube"] = 7 + objects = {o["name"]: o["lastHumanEditSeq"] for o in self.snapshot()["objects"]} + self.assertEqual(objects, {"Cam": 0, "Lamp": 0, "Cube": 7}) + + +def update(name, *, kind="OBJECT", transform=False, geometry=False, shading=False): + return NS(id=NS(name=name, id_type=kind), is_updated_transform=transform, is_updated_geometry=geometry, + is_updated_shading=shading) + + +def depsgraph(*updates): + return NS(updates=list(updates)) + + +class HumanEditTests(PerceptionFixture): + def test_an_update_outside_an_agent_turn_bumps_the_sequence_and_stamps_the_object(self): + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.assertEqual(self.target.human_edit_seq, 1) + self.assertEqual(self.target.last_human_edit_seq("Cube"), 1) + self.target.track_human_edits(depsgraph(update("Lamp", geometry=True))) + self.assertEqual((self.target.human_edit_seq, self.target.last_human_edit_seq("Lamp")), (2, 2)) + self.assertEqual(self.target.last_human_edit_seq("Cube"), 1) + + def test_a_constrained_follower_moves_with_its_target(self): + # the update names both objects, the follower's carrying the transform flag only because of its constraint + self.target.track_human_edits(depsgraph(update("Cube", transform=True), update("Follower", transform=True))) + self.assertEqual(self.target.last_human_edit_seq("Follower"), self.target.last_human_edit_seq("Cube")) + self.assertEqual(self.target.human_edit_seq, 1) + + def test_geometry_and_shading_count_and_an_unflagged_presence_does_not(self): + self.target.track_human_edits(depsgraph(update("Cube", shading=True))) + self.assertEqual(self.target.last_human_edit_seq("Cube"), 1) + self.target.track_human_edits(depsgraph(update("Lamp"), update("Cam"))) # named, not changed + self.assertEqual((self.target.human_edit_seq, self.target.last_human_edit_seq("Lamp")), (1, 0)) + + def test_only_objects_are_stamped(self): + self.target.track_human_edits(depsgraph(update("Mesh", kind="MESH", geometry=True))) + self.assertEqual(self.target.human_edit_seq, 0) + + def test_agent_turn_updates_do_not_count_as_human(self): + # the update arrives inside the turn (probe depsgraph-timing), so the in-turn flag attributes it + original = self.bpy.ops.object.empty_add + + def add_and_update(*a, **kw): + original(*a, **kw) + self.target.track_human_edits(depsgraph(update("Empty", transform=True, geometry=True))) + + self.bpy.ops.object.empty_add = add_and_update + self.assertEqual(self.run_action(action="createObject", objectType="EMPTY")["status"], "accepted") + self.assertEqual(self.target.human_edit_seq, 0) + self.assertEqual(self.target.last_human_edit_seq("Empty"), 0) + self.target.track_human_edits(depsgraph(update("Empty", transform=True))) # after the turn: hers + self.assertEqual(self.target.human_edit_seq, 1) + + def test_a_failed_turn_still_ends_the_turn_for_attribution(self): + def boom(*a, **kw): + raise RuntimeError("half done") + self.bpy.ops.object.empty_add = boom + self.run_action(action="createObject", objectType="EMPTY") + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.assertEqual(self.target.human_edit_seq, 1) + + def test_undo_and_redo_bump_the_sequence_without_naming_an_object(self): + self.target.note_undo_redo() + self.target.note_undo_redo() + self.assertEqual(self.target.human_edit_seq, 2) + self.assertEqual(self.target._last_human_edit, {}) + + def test_human_edit_seq_never_refuses(self): + # scene-last-writer-wins: an intent after her edit is accepted, and so is one that targets what she edited + rich(self.bpy.mesh) + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + receipt = self.run_action(action="setObjectTransform", objectName="Cube", location=[0, 0, 5]) + self.assertEqual(receipt["status"], "accepted", receipt["message"]) + self.assertEqual(self.run_action(action="createObject", objectType="EMPTY")["status"], "accepted") + self.assertEqual(len(self.bpy.undo.pushes), 2) + + def test_the_admission_code_never_reads_the_sequences(self): + source = inspect.getsource(bt.BrokkrBlenderTarget.run_intent) + self.assertEqual(re.findall(r"humanEditSeq|lastHumanEditSeq|human_edit", source), []) + self.assertEqual(re.findall(r"human_edit|session_id", inspect.getsource(bt.BrokkrBlenderTarget._dispatch)), []) + + def test_a_new_session_resets_the_counters_and_mints_a_new_id(self): + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + before = self.target.session_id + self.target.renew_session() + self.assertNotEqual(self.target.session_id, before) + self.assertEqual((self.target.human_edit_seq, self.target.last_human_edit_seq("Cube")), (0, 0)) + + def test_two_targets_mint_different_session_ids(self): + self.assertNotEqual(bt.BrokkrBlenderTarget(self.bpy).session_id, self.target.session_id) + + +class LookReportsHerEditsTests(PerceptionFixture): + def test_the_receipt_carries_the_session_the_selection_and_the_edits_since_the_last_look(self): + self.bpy.mesh.mode = "EDIT" + first = self.look(requestedBy="nibu/hands") + self.assertEqual(first["sessionId"], self.target.session_id) + self.assertEqual((first["humanEditSeq"], first["humanEditsSinceLook"], first["editedSinceLook"]), (0, 0, [])) + self.assertEqual(first["editSelection"][0]["vertices"], [0, 2]) + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.target.track_human_edits(depsgraph(update("Lamp", geometry=True))) + second = self.look(requestedBy="nibu/hands") + self.assertEqual((second["humanEditSeq"], second["humanEditsSinceLook"]), (2, 2)) + self.assertEqual(second["editedSinceLook"], ["Cube", "Lamp"]) + third = self.look(requestedBy="nibu/hands") + self.assertEqual((third["humanEditsSinceLook"], third["editedSinceLook"]), (0, [])) + + def test_each_agent_has_its_own_last_look(self): + self.look(requestedBy="nibu/hands") + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.assertEqual(self.look(requestedBy="nibu/hands")["humanEditsSinceLook"], 1) + self.assertEqual(self.look(requestedBy="nibu/soul")["humanEditsSinceLook"], 1) # soul's first look: all of it + + def test_a_new_session_forgets_the_last_look(self): + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.look(requestedBy="nibu/hands") # her edit number 1 is now seen + self.target.renew_session() + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) # number 1 again, in the new session + receipt = self.look(requestedBy="nibu/hands") + self.assertEqual((receipt["humanEditSeq"], receipt["humanEditsSinceLook"], receipt["editedSinceLook"]), (1, 1, ["Cube"])) + + def test_a_refused_look_does_not_move_the_last_look(self): + self.look(requestedBy="nibu/hands") + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.windows[0].screen.areas.remove(self.view) + self.look(requestedBy="nibu/hands") + self.windows[0].screen.areas.append(self.view) + self.assertEqual(self.look(requestedBy="nibu/hands")["humanEditsSinceLook"], 1) + + +class StorePathTests(unittest.TestCase): + def test_the_default_blend_relative_store_is_found_where_the_blend_file_is(self): + # live-3 Low: store_exists must resolve the default '//.brokkr/...' against the blend file, as the add-on does + import tempfile + with tempfile.TemporaryDirectory() as tmp: + blend = Path(tmp).resolve() + (blend / ".brokkr").mkdir() + (blend / ".brokkr" / "blender-editor.ccmp").write_bytes(b"") + + def abspath(p): + return str(blend / p[2:]) if p.startswith("//") else p + + target = bt.BrokkrBlenderTarget(NS(path=NS(abspath=abspath))) + self.assertTrue(target.store_exists(bt.DEFAULT_CULTMESH_CACHE_PATH)) + self.assertTrue(target.store_exists("")) # an empty preference means the default + self.assertEqual(Path(target.resolve_cache_path(bt.DEFAULT_CULTMESH_CACHE_PATH)), + blend / ".brokkr" / "blender-editor.ccmp") + (blend / ".brokkr" / "blender-editor.ccmp").unlink() + self.assertFalse(target.store_exists(bt.DEFAULT_CULTMESH_CACHE_PATH)) + + def test_the_preference_default_is_the_blend_relative_path_the_target_resolves(self): + prop = addon.BrokkrPreferences.__annotations__["cultmesh_cache_path"] + self.assertEqual(prop.kwargs["default"], "//.brokkr/blender-editor.ccmp") + self.assertEqual(bt.DEFAULT_CULTMESH_CACHE_PATH, prop.kwargs["default"]) + + +class HandlerWiringTests(unittest.TestCase): + def setUp(self): + self.lists = {name: [] for name in ("depsgraph_update_post", "undo_post", "redo_post", "load_post")} + handlers = NS(persistent=lambda f: setattr(f, "persistent", True) or f, **self.lists) + self.fake = NS(app=NS(handlers=handlers, timers=NS(is_registered=lambda f: False, register=lambda *a, **k: None, + unregister=lambda f: None)), + utils=NS(register_class=lambda c: None, unregister_class=lambda c: None)) + patch = unittest.mock.patch.multiple(addon.bpy, app=self.fake.app, utils=self.fake.utils) + patch.start() + self.addCleanup(patch.stop) + self.target = bt.BrokkrBlenderTarget(NS(path=NS(abspath=lambda p: p))) + addon._target = self.target + self.addCleanup(lambda: setattr(addon, "_target", None)) + + def test_register_adds_persistent_human_edit_handlers_and_unregister_removes_them(self): + addon.register() + for name in ("depsgraph_update_post", "undo_post", "redo_post", "load_post"): + ours = [h for h in self.lists[name] if getattr(h, "persistent", False)] + self.assertEqual(len(ours), 1, name) + self.assertIn(addon._auto_capture, self.lists["depsgraph_update_post"]) # the snapshot handler stays + self.assertEqual(len(self.lists["depsgraph_update_post"]), 2) + addon.register() # twice adds nothing + self.assertEqual(len(self.lists["depsgraph_update_post"]), 2) + addon.unregister() + self.assertEqual([len(v) for v in self.lists.values()], [0, 0, 0, 0]) + + def test_the_handlers_feed_the_target(self): + addon.register() + addon._target = self.target + track = next(h for h in self.lists["depsgraph_update_post"] if getattr(h, "persistent", False)) + track(None, depsgraph(update("Cube", transform=True))) + self.assertEqual(self.target.human_edit_seq, 1) + self.lists["undo_post"][0](None) + self.lists["redo_post"][0](None) + self.assertEqual(self.target.human_edit_seq, 3) + before = self.target.session_id + self.lists["load_post"][0](None) + self.assertNotEqual(self.target.session_id, before) + self.assertEqual(self.target.human_edit_seq, 0) + + def test_the_human_edit_tracker_does_not_depend_on_auto_capture(self): + # always on: it reads no preference at all + source = inspect.getsource(addon._track_human_edits) + self.assertNotRegex(source, r"auto_capture|preferences") + + +if __name__ == "__main__": + unittest.main() diff --git a/surfaces/blender/tests/test_scene_actions.py b/surfaces/blender/tests/test_scene_actions.py index 6c73c67..fcc2b64 100644 --- a/surfaces/blender/tests/test_scene_actions.py +++ b/surfaces/blender/tests/test_scene_actions.py @@ -67,7 +67,10 @@ def fake_render(): class Objects(dict): - """bpy.data.objects: a mapping with keys() and get().""" + """bpy.data.objects: a mapping with keys() and get(); like bpy_prop_collection, iterating it yields the objects.""" + + def __iter__(self): + return iter(self.values()) class FakeUndo: From 5fcc8900215625ca44af58a7eb075775f9e3fdbc Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 22:19:53 +0100 Subject: [PATCH 29/63] brokkr-ctl blender look: send look, print the receipt's lookPath, selection and edits since the last look Co-Authored-By: Claude Sonnet 5.5 --- brokkr-ctl/src/blender.rs | 15 ++++++++++--- brokkr-ctl/tests/cli.rs | 47 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/brokkr-ctl/src/blender.rs b/brokkr-ctl/src/blender.rs index be25999..9bb89d1 100644 --- a/brokkr-ctl/src/blender.rs +++ b/brokkr-ctl/src/blender.rs @@ -119,7 +119,13 @@ pub fn run(args: &[String]) -> Result { return Ok(0); } match sub.as_str() { - "send" => send(&options), + "send" => send(&options, one_positional(&options, "send [--set key=json]...")?), + "look" => { + if !options.positional.is_empty() || !options.sets.is_empty() { + bail!("usage: brokkr-ctl blender look [--note text] [--agent name] [--no-wait] [--timeout secs]"); + } + send(&options, "look") + } "wait" => { let id = one_positional(&options, "wait ")?; let store = open_store(&options)?; @@ -232,8 +238,7 @@ fn build_intent( Ok(Value::Object(map)) } -fn send(options: &Options) -> Result { - let action = one_positional(options, "send [--set key=json]...")?; +fn send(options: &Options, action: &str) -> Result { let requested_by = requested_by(options)?; let mut store = open_store(options)?; let command_id = uuid::Uuid::now_v7().simple().to_string(); @@ -399,6 +404,9 @@ brokkr-ctl blender: send typed intents to the live Blender add-on and read what send [--set key=json]... [--note text] [--agent name] [--no-wait] [--timeout secs] Write one intent, then wait for its receipt and print it. `send --help` lists actions. + look [--note text] [--agent name] [--no-wait] [--timeout secs] + `send look`: capture the 3D view she is looking at. The receipt prints lookPath (a PNG), her + Edit Mode selection, and how many edits she made since this agent last looked. wait [--timeout secs] Wait for a receipt and print it. receipts [--last n] Print stored receipts, oldest first. status Print the host snapshot summary, agentCommandsEnabled included. @@ -544,6 +552,7 @@ const ACTIONS: &[(&str, &[Field])] = &[ ("cameraName", "string", ""), ], ), + ("look", &[]), ( "createNodeGroup", &[ diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs index 4ea7f24..a7293e1 100644 --- a/brokkr-ctl/tests/cli.rs +++ b/brokkr-ctl/tests/cli.rs @@ -80,6 +80,53 @@ fn send_writes_a_pullable_intent() { assert!(envelopes.iter().any(|e| e.key == "blender/receipts/seed"), "other records survive the write"); } +/// `look` is `send look`: one intent, no fields, the same receipt wait. +#[test] +fn look_sends_the_look_action_and_prints_the_receipts_look_path() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("seed", "accepted")]); + let output = ctl(&path, &["look", "--agent", "hands", "--note", "checking the view", "--no-wait"], Some("nibu")); + assert_eq!(output.status.code(), Some(0), "{}", String::from_utf8_lossy(&output.stderr)); + let id = stdout(&output).trim().strip_prefix("commandId: ").unwrap().to_string(); + let envelopes = SingleFileMessagePackBackingStore::new(&path).pull_all().unwrap(); + let intent = envelopes.iter().find(|e| e.key == format!("blender/commands/{id}")).expect("intent key"); + let payload: Value = cultcache_rs::decode_payload(&intent.payload).unwrap(); + assert_eq!( + payload, + json!({"schema": INTENT, "commandId": id, "action": "look", "requestedBy": "nibu/hands", + "note": "checking the view"}) + ); + // the add-on's receipt for it prints like any other: lookPath and the perception fields are plain lines + let mut store = SingleFileMessagePackBackingStore::new(&path); + let receipt = json!({"schema": RECEIPT, "commandId": id, "status": "accepted", "lookPath": "C:/out/look/x.png", + "humanEditSeq": 3, "editSelection": [{"name": "Cube", "vertices": [0, 2]}]}); + store.push(&envelope(RECEIPT, &format!("blender/receipts/{id}"), &receipt)).unwrap(); + let waited = ctl(&path, &["wait", &id, "--timeout", "5"], None); + assert_eq!(waited.status.code(), Some(0)); + let text = stdout(&waited); + assert!(text.contains("lookPath: C:/out/look/x.png"), "{text}"); + assert!(text.contains("humanEditSeq: 3") && text.contains("\"vertices\":[0,2]"), "{text}"); +} + +#[test] +fn look_takes_no_fields_and_no_second_action() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("seed", "accepted")]); + for extra in [vec!["--set", "x=1"], vec!["createObject"]] { + let mut args = vec!["look", "--agent", "hands", "--no-wait"]; + args.extend(extra.iter()); + assert_eq!(ctl(&path, &args, Some("nibu")).status.code(), Some(1), "{extra:?}"); + } + let store = SingleFileMessagePackBackingStore::new(&path).pull_all().unwrap(); + assert!(!store.iter().any(|e| e.key.starts_with("blender/commands/")), "a refused look writes nothing"); +} + +#[test] +fn the_group_help_names_look() { + let output = Command::new(env!("CARGO_BIN_EXE_brokkr-ctl")).args(["blender", "--help"]).output().unwrap(); + assert!(stdout(&output).contains("look")); +} + #[test] fn an_intent_without_instance_or_agent_is_refused_and_writes_nothing() { let dir = tempfile::tempdir().unwrap(); From bbe5176ca248d5847d0f450751c7510266c55a8b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 22:25:50 +0100 Subject: [PATCH 30/63] Perception: live proof in a stock Blender 5.3 through brokkr-ctl, and the look contract in the docs Co-Authored-By: Claude Sonnet 5.5 --- docs/provider-contract.md | 1 + surfaces/blender/docs/install.md | 18 + surfaces/blender/tests/live/perception.py | 275 +++++++++++ .../blender/tests/live/perception.result.json | 437 ++++++++++++++++++ 4 files changed, 731 insertions(+) create mode 100644 surfaces/blender/tests/live/perception.py create mode 100644 surfaces/blender/tests/live/perception.result.json diff --git a/docs/provider-contract.md b/docs/provider-contract.md index 8c1132f..cda8707 100644 --- a/docs/provider-contract.md +++ b/docs/provider-contract.md @@ -220,6 +220,7 @@ All Blender writes use `brokkr.blender.command_intent.v0` and receive - `setLight` - `setWorld` - `renderStill` +- `look` (a read: a PNG of her 3D view under the output directory's `look/`, her Edit Mode selection and her edit counters in the receipt) - `createNodeGroup`, `addNode`, `removeNode`, `linkSockets`, `unlinkSockets`, `addModifier`, `removeModifier`, `setModifierInput` (Geometry Nodes graphs; fields in `surfaces/blender/docs/node-actions.md`) diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 0b5917c..0eb7d40 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -175,6 +175,7 @@ Admitted command actions: - `setLight` - `setWorld` - `renderStill` +- `look` Scene action fields (all other keys are ignored; a refused intent changes nothing and gets a `failed` receipt whose message names the rule): @@ -227,6 +228,23 @@ gets a `failed` receipt whose message names the rule): CPU. The check applies to the scene's engine when `engine` is omitted. No such check runs on Windows or macOS. +- `look`: no fields. Captures the 3D view she is looking at (the largest 3D view across the windows, its + main region) to `/look/.png` and puts the absolute path in the receipt's + `lookPath`; 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. The look directory keeps the newest 20 PNGs (scratch, + never read back). The receipt also carries `sessionId`, `humanEditSeq`, `humanEditsSinceLook` and + `editedSinceLook` (object names), counted for the sending `requestedBy` since its previous look in this + session, and `editSelection`: for each object in Edit Mode its selected vertex, edge and face indices (each + list capped at 4096, the true count beside it as `verticesTotal` and so on; non-mesh objects say + `unsupported`). The host snapshot carries the same `sessionId`, `humanEditSeq`, `editSelection` and each + object's `lastHumanEditSeq`. 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, so `editedSinceLook` can name more than she touched. They are + observations: no intent is refused because of them. + 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 diff --git a/surfaces/blender/tests/live/perception.py b/surfaces/blender/tests/live/perception.py new file mode 100644 index 0000000..a62aeb8 --- /dev/null +++ b/surfaces/blender/tests/live/perception.py @@ -0,0 +1,275 @@ +"""Live proof, in GUI Blender with the add-on installed as an extension, of perception, with real brokkr-ctl sends. + + BROKKR_SCRATCH= + BROKKR_CTL= + BROKKR_ADDON_MODULE= + BROKKR_CULTLIB= + blender --python perception.py -- + +Run it in a Blender whose resource path is fresh (BLENDER_USER_RESOURCE_PATH) so the add-on's preferences are the +defaults. The driver stands in for the operator's hands only: it saves the blend, ticks the sink and sets the render +output directory (the two preferences an operator sets), enters Edit Mode, selects, moves objects and presses undo. +Every intent is sent by brokkr-ctl and answered by the add-on's own timer. Writes .result.json, then quits. +""" +import importlib +import json +import os +import shutil +import struct +import subprocess +import sys +import time +import traceback +from pathlib import Path + +import bmesh +import bpy + +SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() +SCRATCH.mkdir(parents=True, exist_ok=True) +CTL = os.environ["BROKKR_CTL"] +OUT = sys.argv[sys.argv.index("--") + 1] +MODULE = os.environ.get("BROKKR_ADDON_MODULE", "bl_ext.user_default.brokkr_bridge") +R = {"blender": bpy.app.version_string, "module": MODULE, "checks": [], "notes": {}} + +bpy.ops.preferences.addon_enable(module=MODULE) +addon = importlib.import_module(MODULE) +prefs = bpy.context.preferences.addons[MODULE].preferences +prefs.cultlib_py_src = os.environ.get("BROKKR_CULTLIB", prefs.cultlib_py_src) +adapter = addon.target() +STORE = SCRATCH / ".brokkr" / "blender-editor.ccmp" # what the default blend-relative preference resolves to +ENV = dict(os.environ, EUREKA_INSTANCE="nibu", BROKKR_BLENDER_STORE=str(STORE), BROKKR_AGENT="hands") + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def fields(text): + out = {} + for line in text.splitlines(): + key, _, value = line.partition(": ") + try: + out[key] = json.loads(value) if value[:1] in "[{0123456789" else value + except ValueError: + out[key] = value + return out + + +def ctl(*args): + """A brokkr-ctl run beside Blender's timers (it blocks until the receipt, and the add-on's timer answers it).""" + proc = subprocess.Popen([CTL, "blender", *args], env=ENV, stdout=subprocess.PIPE, text=True) + began = time.perf_counter() + while proc.poll() is None: + yield + out = proc.stdout.read() + return proc.returncode, fields(out), round((time.perf_counter() - began) * 1000) + + +def png_size(path): + data = Path(path).read_bytes() + assert data[:8] == b"\x89PNG\r\n\x1a\n", "not a PNG" + return struct.unpack(">II", data[16:24]) + + +def view3d(): + for window in bpy.context.window_manager.windows: + for area in window.screen.areas: + if area.type == "VIEW_3D": + return window, area, next(r for r in area.regions if r.type == "WINDOW") + + +def snapshot(): + with bpy.context.temp_override(window=bpy.context.window_manager.windows[0]): + bpy.ops.brokkr.capture_snapshot() + return adapter.last_snapshot + + +def objects_named(prefix): + return sorted(o.name for o in bpy.data.objects if o.name.startswith(prefix)) + + +def mode_edit(on): + window, area, region = view3d() + cube = bpy.data.objects["Cube"] + bpy.context.view_layer.objects.active = cube # she clicks it first + cube.select_set(True) + with bpy.context.temp_override(window=window, area=area, region=region, active_object=cube, object=cube): + bpy.ops.object.mode_set(mode="EDIT" if on else "OBJECT") + + +def flow(): + cube = bpy.data.objects["Cube"] + window, area, region = view3d() + R["notes"]["window_px"] = [window.width, window.height] + R["notes"]["region_px"] = [region.width, region.height] + R["notes"]["area_px"] = [area.width, area.height] + + # ---- a default install: the preferences are untouched except what the operator sets ---- + check("default install: the store preference is the blend-relative default", + prefs.cultmesh_cache_path == "//.brokkr/blender-editor.ccmp", prefs.cultmesh_cache_path) + bpy.ops.wm.save_as_mainfile(filepath=str(SCRATCH / "perception.blend")) + prefs.output_dir = str(SCRATCH / "out") + prefs.auto_drain_commands = True # the operator ticks the sink + yield 1.0 + snap = snapshot() + check("the default blend-relative store was created beside the saved blend", STORE.is_file(), str(STORE)) + check("the snapshot carries sessionId, humanEditSeq 0, editSelection [] and per-object lastHumanEditSeq", + snap["sessionId"] == adapter.session_id and snap["humanEditSeq"] == 0 and snap["editSelection"] == [] + and all(o["lastHumanEditSeq"] == 0 for o in snap["objects"]), [snap["sessionId"], snap["humanEditSeq"]]) + session = snap["sessionId"] + + # ---- look: her 3D view, scoped to the viewport ---- + code, r, ms = yield from ctl("look", "--note", "first look") + R["notes"]["first_look"] = r + R["notes"]["first_look_round_trip_ms"] = ms + path = r.get("lookPath", "") + size = png_size(path) if path and Path(path).is_file() else None + check("look: exit 0, accepted, a lookPath PNG under /look/.png", + code == 0 and r.get("status") == "accepted" and size is not None + and Path(path).parent == (SCRATCH / "out" / "look") and Path(path).name == r["commandId"] + ".png", [code, r]) + check("look: the PNG is the 3D view's WINDOW region, not the Blender window and not the desktop", + list(size) == R["notes"]["region_px"] and list(size) != R["notes"]["window_px"], [size, R["notes"]]) + check("look: no undo step, receipt names the session, edits so far 0, none edited since", + r.get("undoLabel", "") == "" and r.get("sessionId") == session and r.get("humanEditSeq") == 0 + and r.get("humanEditsSinceLook") == 0 and r.get("editedSinceLook") == [], r) + + # ---- the agent's own edits are not hers ---- + seq_before = adapter.human_edit_seq + code, r, _ = yield from ctl("send", "createObject", "--set", 'objectType="EMPTY"', "--set", 'name="AgentEmpty"') + code2, r2, _ = yield from ctl("send", "setObjectTransform", "--set", 'targetObjectName="Cube"', "--set", "location=[0,0,0.5]") + for _ in range(12): # a deferred depsgraph update, if the turn left one behind, arrives within a few ticks + yield 0.1 + check("agent turns (createObject, setObjectTransform) leave humanEditSeq unmoved, also after idle ticks", + code == 0 and code2 == 0 and adapter.human_edit_seq == seq_before == 0 + and adapter.last_human_edit_seq("AgentEmpty") == 0 and adapter.last_human_edit_seq("Cube") == 0, + [code, code2, adapter.human_edit_seq, adapter._last_human_edit]) + + # ---- Edit Mode selection, read live, without leaving Edit Mode ---- + mode_edit(True) + yield 0.3 + bm = bmesh.from_edit_mesh(cube.data) + for v in bm.verts: + v.select = False + bm.verts.ensure_lookup_table() + bm.verts[0].select = True + bm.verts[3].select = True + bm.select_flush_mode() + bmesh.update_edit_mesh(cube.data) + yield 0.3 + code, r, _ = yield from ctl("look") + if r.get("lookPath"): + shutil.copy(r["lookPath"], SCRATCH / "edit-look.png") + sel = (r.get("editSelection") or [{}])[0] + check("edit selection: look reads her two selected vertices live; the mode stays Edit Mode", + code == 0 and sel.get("name") == "Cube" and sel.get("vertices") == [0, 3] and sel.get("verticesTotal") == 2 + and bpy.context.mode == "EDIT_MESH", [r.get("editSelection"), bpy.context.mode]) + code, r2, _ = yield from ctl("send", "setObjectTransform", "--set", 'targetObjectName="Cube"', "--set", "location=[0,0,3]") + check("an object intent is refused while she is in Edit Mode (ruling in force); look was not", code == 2 and r2.get("status") == "denied", + r2.get("message")) + snap = snapshot() + check("the snapshot's editSelection matches", snap["editSelection"][0]["vertices"] == [0, 3], snap["editSelection"]) + mode_edit(False) + yield 0.3 + + # ---- her edits: counters, and a follower that moves with its target ---- + follower = bpy.data.objects.new("Follower", bpy.data.meshes.new("FollowerMesh")) + bpy.context.scene.collection.objects.link(follower) + constraint = follower.constraints.new("COPY_LOCATION") + constraint.target = cube + constraint.use_y = False + yield 0.5 + # Linking an object rebuilds the depsgraph relations and Blender flags other objects in that update: collateral + # of her adding an object, recorded, not attributed to a move. + R["notes"]["after_adding_follower"] = dict(adapter._last_human_edit) + code, r, _ = yield from ctl("look") # the marker: what she does next is "since this look" + marker = r["humanEditSeq"] + cube.location.x = 2.0 # her move + yield 0.5 + cube.location.x = 4.0 + yield 0.5 + snap = snapshot() + by = {o["name"]: o["lastHumanEditSeq"] for o in snap["objects"]} + R["notes"]["after_moving_cube"] = {"marker": marker, "humanEditSeq": snap["humanEditSeq"], "last": by} + check("her moves bump humanEditSeq; Cube and its constrained Follower carry the same last sequence, the untouched Light and Camera do not", + snap["humanEditSeq"] > marker and by["Cube"] == by["Follower"] == snap["humanEditSeq"] + and by["Light"] <= marker and by["Camera"] <= marker, [marker, snap["humanEditSeq"], by]) + code, r, _ = yield from ctl("look") + check("the next look says what changed since the last one: exactly the moved Cube and its Follower", + r["humanEditsSinceLook"] >= 2 and r["editedSinceLook"] == ["Cube", "Follower"], r) + code, r, _ = yield from ctl("look") + check("and a look right after it says nothing changed since", r["humanEditsSinceLook"] == 0 and r["editedSinceLook"] == [], r) + + # ---- scene-last-writer-wins and act-then-undo ---- + seq = adapter.human_edit_seq + code, r, _ = yield from ctl("send", "setObjectTransform", "--set", 'targetObjectName="Cube"', "--set", "location=[9,9,9]") + check("after her edit, the agent's action on the same object is accepted (last writer wins)", code == 0 and r.get("status") == "accepted" + and tuple(round(c, 3) for c in bpy.data.objects["Cube"].location) == (9.0, 9.0, 9.0), r) + check("and still did not count as hers", adapter.human_edit_seq == seq, [seq, adapter.human_edit_seq]) + with bpy.context.temp_override(window=bpy.context.window_manager.windows[0]): + bpy.ops.ed.undo() # her Ctrl+Z + yield 0.5 + check("her Ctrl+Z takes the agent's step back and counts as hers", + bpy.data.objects["Cube"].location.x != 9.0 and adapter.human_edit_seq > seq, + [bpy.data.objects["Cube"].location.x, seq, adapter.human_edit_seq]) + + # ---- a popup open over the view is in the picture, as she sees it ---- + window, area, region = view3d() + with bpy.context.temp_override(window=window, area=area, region=region): + bpy.ops.wm.call_menu("INVOKE_DEFAULT", name="VIEW3D_MT_add") + yield 0.8 + code, r, _ = yield from ctl("look", "--note", "with the Add menu open") + R["notes"]["popup_look"] = r.get("lookPath") + if r.get("lookPath"): + shutil.copy(r["lookPath"], SCRATCH / "popup-look.png") # the look directory is pruned; this copy is for a human to see + check("look with a popup open: accepted, a PNG of the same region size", code == 0 and r.get("lookPath") + and list(png_size(r["lookPath"])) == R["notes"]["region_px"], r) + + # ---- prune to twenty ---- + for _ in range(24): + yield from ctl("look") + kept = sorted((SCRATCH / "out" / "look").glob("*.png")) + check("after 30 looks the look directory holds exactly the newest 20 PNGs", len(kept) == 20, len(kept)) + + # ---- refusals ---- + area.type = "OUTLINER" + yield 0.3 + code, r, _ = yield from ctl("look") + area.type = "VIEW_3D" + check("no 3D view open: look is refused naming why, with no path", code == 2 and "3D" in r.get("message", "") and r.get("lookPath", "") == "", r) + prefs.output_dir = "" + code, r, _ = yield from ctl("look") + prefs.output_dir = str(SCRATCH / "out") + check("no output directory set: look is refused naming why", code == 2 and "output" in r.get("message", ""), r) + code, r, _ = yield from ctl("look") + check("the next look works again", code == 0, r) + check("no add-on drain error", adapter.last_auto_drain_error == "", adapter.last_auto_drain_error) + + +gen = flow() +wait_until = 0.0 + + +def write(): + R["ok"] = bool(R["checks"]) and all(c["ok"] for c in R["checks"]) and not R.get("errors") + with open(OUT + ".result.json", "w") as f: + json.dump(R, f, indent=1, default=str) + + +def runner(): + global wait_until + try: + delay = next(gen) + return delay if isinstance(delay, (int, float)) and delay else 0.05 + except StopIteration: + write() + bpy.ops.wm.quit_blender() + return None + except Exception: + R.setdefault("errors", []).append(traceback.format_exc()) + write() + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(runner, first_interval=3.0) diff --git a/surfaces/blender/tests/live/perception.result.json b/surfaces/blender/tests/live/perception.result.json new file mode 100644 index 0000000..ac8afdb --- /dev/null +++ b/surfaces/blender/tests/live/perception.result.json @@ -0,0 +1,437 @@ +{ + "blender": "5.3.0", + "module": "bl_ext.user_default.brokkr_bridge", + "checks": [ + { + "name": "default install: the store preference is the blend-relative default", + "ok": true, + "detail": "//.brokkr/blender-editor.ccmp" + }, + { + "name": "the default blend-relative store was created beside the saved blend", + "ok": true, + "detail": "F:\\aeth-wt\\brokkr-live-5.scratch\\.brokkr\\blender-editor.ccmp" + }, + { + "name": "the snapshot carries sessionId, humanEditSeq 0, editSelection [] and per-object lastHumanEditSeq", + "ok": true, + "detail": [ + "3e3712b94e944cb9ad4a74aafdc699bd", + 0 + ] + }, + { + "name": "look: exit 0, accepted, a lookPath PNG under /look/.png", + "ok": true, + "detail": [ + 0, + { + "commandId": "01a21ee5507774d293ea4186f58a4689", + "action": "look", + "editSelection": [], + "editedSinceLook": [], + "humanEditSeq": 0, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee5507774d293ea4186f58a4689.png", + "message": "Captured the 3D view to look/01a21ee5507774d293ea4186f58a4689.png.", + "note": "first look", + "objectName": "", + "observedAt": "2026-11-27T21:24:34.894575+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + } + ] + }, + { + "name": "look: the PNG is the 3D view's WINDOW region, not the Blender window and not the desktop", + "ok": true, + "detail": [ + [ + 1574, + 888 + ], + { + "window_px": [ + 1920, + 1009 + ], + "region_px": [ + 1574, + 888 + ], + "area_px": [ + 1574, + 888 + ], + "first_look": { + "commandId": "01a21ee5507774d293ea4186f58a4689", + "action": "look", + "editSelection": [], + "editedSinceLook": [], + "humanEditSeq": 0, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee5507774d293ea4186f58a4689.png", + "message": "Captured the 3D view to look/01a21ee5507774d293ea4186f58a4689.png.", + "note": "first look", + "objectName": "", + "observedAt": "2026-11-27T21:24:34.894575+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + }, + "first_look_round_trip_ms": 456, + "after_adding_follower": { + "Cube": 4, + "Light": 4, + "Camera": 4, + "AgentEmpty": 4, + "Follower": 4 + }, + "after_moving_cube": { + "marker": 4, + "humanEditSeq": 6, + "last": { + "AgentEmpty": 4, + "Camera": 4, + "Cube": 6, + "Follower": 6, + "Light": 4 + } + }, + "popup_look": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee581c771d2b3b688dfce3996f3.png" + } + ] + }, + { + "name": "look: no undo step, receipt names the session, edits so far 0, none edited since", + "ok": true, + "detail": { + "commandId": "01a21ee5507774d293ea4186f58a4689", + "action": "look", + "editSelection": [], + "editedSinceLook": [], + "humanEditSeq": 0, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee5507774d293ea4186f58a4689.png", + "message": "Captured the 3D view to look/01a21ee5507774d293ea4186f58a4689.png.", + "note": "first look", + "objectName": "", + "observedAt": "2026-11-27T21:24:34.894575+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "agent turns (createObject, setObjectTransform) leave humanEditSeq unmoved, also after idle ticks", + "ok": true, + "detail": [ + 0, + 0, + 0, + { + "Cube": 8, + "Light": 8, + "Camera": 8, + "AgentEmpty": 8, + "Follower": 6 + } + ] + }, + { + "name": "edit selection: look reads her two selected vertices live; the mode stays Edit Mode", + "ok": true, + "detail": [ + [ + { + "edges": [], + "edgesTotal": 0, + "faces": [], + "facesTotal": 0, + "name": "Cube", + "type": "MESH", + "vertices": [ + 0, + 3 + ], + "verticesTotal": 2 + } + ], + "EDIT_MESH" + ] + }, + { + "name": "an object intent is refused while she is in Edit Mode (ruling in force); look was not", + "ok": true, + "detail": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed." + }, + { + "name": "the snapshot's editSelection matches", + "ok": true, + "detail": [ + { + "name": "Cube", + "type": "MESH", + "vertices": [ + 0, + 3 + ], + "verticesTotal": 2, + "edges": [], + "edgesTotal": 0, + "faces": [], + "facesTotal": 0 + } + ] + }, + { + "name": "her moves bump humanEditSeq; Cube and its constrained Follower carry the same last sequence, the untouched Light and Camera do not", + "ok": true, + "detail": [ + 4, + 6, + { + "AgentEmpty": 4, + "Camera": 4, + "Cube": 6, + "Follower": 6, + "Light": 4 + } + ] + }, + { + "name": "the next look says what changed since the last one: exactly the moved Cube and its Follower", + "ok": true, + "detail": { + "commandId": "01a21ee56f787012b0f2312b77c478b4", + "action": "look", + "editSelection": [], + "editedSinceLook": [ + "Cube", + "Follower" + ], + "humanEditSeq": 6, + "humanEditsSinceLook": 2, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee56f787012b0f2312b77c478b4.png", + "message": "Captured the 3D view to look/01a21ee56f787012b0f2312b77c478b4.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:24:43.509761+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "and a look right after it says nothing changed since", + "ok": true, + "detail": { + "commandId": "01a21ee574627220a1ed3e104667b73c", + "action": "look", + "editSelection": [], + "editedSinceLook": [], + "humanEditSeq": 6, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee574627220a1ed3e104667b73c.png", + "message": "Captured the 3D view to look/01a21ee574627220a1ed3e104667b73c.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:24:44.677117+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "after her edit, the agent's action on the same object is accepted (last writer wins)", + "ok": true, + "detail": { + "commandId": "01a21ee5788978c1b7f353ca2e2147be", + "action": "setObjectTransform", + "lookPath": "", + "message": "Blender object transform updated.", + "note": "", + "objectName": "Cube", + "observedAt": "2026-11-27T21:24:45.745214+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: setObjectTransform 2e2147be" + } + }, + { + "name": "and still did not count as hers", + "ok": true, + "detail": [ + 6, + 6 + ] + }, + { + "name": "her Ctrl+Z takes the agent's step back and counts as hers", + "ok": true, + "detail": [ + 0.0, + 6, + 8 + ] + }, + { + "name": "look with a popup open: accepted, a PNG of the same region size", + "ok": true, + "detail": { + "commandId": "01a21ee581c771d2b3b688dfce3996f3", + "action": "look", + "editSelection": [], + "editedSinceLook": [ + "AgentEmpty", + "Camera", + "Cube", + "Light" + ], + "humanEditSeq": 8, + "humanEditsSinceLook": 2, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee581c771d2b3b688dfce3996f3.png", + "message": "Captured the 3D view to look/01a21ee581c771d2b3b688dfce3996f3.png.", + "note": "with the Add menu open", + "objectName": "", + "observedAt": "2026-11-27T21:24:47.877250+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "after 30 looks the look directory holds exactly the newest 20 PNGs", + "ok": true, + "detail": 20 + }, + { + "name": "no 3D view open: look is refused naming why, with no path", + "ok": true, + "detail": { + "commandId": "01a21ee5f6b27cc2ae9dd61ee3a5bdef", + "action": "look", + "lookPath": "", + "message": "No 3D viewport is open to look at.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:25:17.807716+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "failed", + "undoLabel": "" + } + }, + { + "name": "no output directory set: look is refused naming why", + "ok": true, + "detail": { + "commandId": "01a21ee5fa117271abc6c3536e2194d3", + "action": "look", + "lookPath": "", + "message": "output directory is not configured in the add-on preferences.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:25:18.920883+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "failed", + "undoLabel": "" + } + }, + { + "name": "the next look works again", + "ok": true, + "detail": { + "commandId": "01a21ee5fe627fc3ad7ae77850c6e812", + "action": "look", + "editSelection": [], + "editedSinceLook": [], + "humanEditSeq": 8, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee5fe627fc3ad7ae77850c6e812.png", + "message": "Captured the 3D view to look/01a21ee5fe627fc3ad7ae77850c6e812.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:25:20.088455+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "no add-on drain error", + "ok": true, + "detail": "" + } + ], + "notes": { + "window_px": [ + 1920, + 1009 + ], + "region_px": [ + 1574, + 888 + ], + "area_px": [ + 1574, + 888 + ], + "first_look": { + "commandId": "01a21ee5507774d293ea4186f58a4689", + "action": "look", + "editSelection": [], + "editedSinceLook": [], + "humanEditSeq": 0, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee5507774d293ea4186f58a4689.png", + "message": "Captured the 3D view to look/01a21ee5507774d293ea4186f58a4689.png.", + "note": "first look", + "objectName": "", + "observedAt": "2026-11-27T21:24:34.894575+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + }, + "first_look_round_trip_ms": 456, + "after_adding_follower": { + "Cube": 4, + "Light": 4, + "Camera": 4, + "AgentEmpty": 4, + "Follower": 4 + }, + "after_moving_cube": { + "marker": 4, + "humanEditSeq": 6, + "last": { + "AgentEmpty": 4, + "Camera": 4, + "Cube": 6, + "Follower": 6, + "Light": 4 + } + }, + "popup_look": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee581c771d2b3b688dfce3996f3.png" + }, + "ok": true +} \ No newline at end of file From 1286ad8fc4fffa27b7f53ce691b9936c0690389d Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 22:54:35 +0100 Subject: [PATCH 31/63] Perception fixes: offscreen look when Blender is not drawing, scene update sequence and capture source in the receipt, selection totals from the mesh and a capped scan, coarse attribution flagged, path re-check and prune pinned Co-Authored-By: Claude Sonnet 5.5 --- .../blender/brokkr_bridge/blender_target.py | 103 ++++++- surfaces/blender/tests/test_perception.py | 255 +++++++++++++++++- 2 files changed, 345 insertions(+), 13 deletions(-) diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index c69a493..93a9fb5 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -6,8 +6,10 @@ import json import math import os import re +import struct import sys import uuid +import zlib from array import array from collections import deque from datetime import datetime, timedelta, timezone @@ -129,6 +131,8 @@ class BrokkrBlenderTarget: self.human_edit_seq = 0 self._last_human_edit: dict[str, int] = {} # object name -> human_edit_seq when she last changed it self._looked: dict[str, int] = {} # requestedBy -> human_edit_seq at that agent's last look + self.scene_update_seq = 0 # every depsgraph update, hers or the agent's: what a capture reflects + self._coarse = {"seq": 0, "why": ""} # the latest human edit whose per-object stamps are not precise def configure_action_dirs(self, import_dir: str, output_dir: str) -> None: """The directories importGltf and renderStill may touch; empty leaves that action disabled.""" @@ -1055,10 +1059,13 @@ class BrokkrBlenderTarget: self.human_edit_seq = 0 self._last_human_edit.clear() self._looked.clear() + self.scene_update_seq = 0 + self._coarse = {"seq": 0, "why": ""} def track_human_edits(self, depsgraph: Any) -> None: """A depsgraph update outside an agent turn is hers. What changed is read from each update's flags, never from presence in the list: an update also names what only depends on the change.""" + self.scene_update_seq += 1 if self.agent_turn: return changed = [u.id.name for u in depsgraph.updates @@ -1068,10 +1075,13 @@ class BrokkrBlenderTarget: self.human_edit_seq += 1 for name in changed: self._last_human_edit[name] = self.human_edit_seq + if len(changed) >= 2 and len(changed) == len(self.bpy.data.objects): + self._coarse = {"seq": self.human_edit_seq, "why": "all objects flagged"} # an add or a link does this def note_undo_redo(self) -> None: """An undo or redo cannot be narrowed to objects from its updates, so it moves the session counter only.""" self.human_edit_seq += 1 + self._coarse = {"seq": self.human_edit_seq, "why": "undo or redo flags all objects"} def last_human_edit_seq(self, name: str) -> int: return self._last_human_edit.get(name, 0) @@ -1089,10 +1099,20 @@ class BrokkrBlenderTarget: continue mesh = bmesh.from_edit_mesh(obj.data) entry: dict[str, Any] = {"name": obj.name, "type": obj.type} - for key, elements in (("vertices", mesh.verts), ("edges", mesh.edges), ("faces", mesh.faces)): - chosen = [index for index, element in enumerate(elements) if element.select] - entry[key] = chosen[:EDIT_SELECTION_CAP] - entry[key + "Total"] = len(chosen) + # The totals are the mesh's own counts; the scan stops at the cap or when every selected one is found. + for key, elements, total in (("vertices", mesh.verts, obj.data.total_vert_sel), + ("edges", mesh.edges, obj.data.total_edge_sel), + ("faces", mesh.faces, obj.data.total_face_sel)): + chosen: list[int] = [] + want = min(total, EDIT_SELECTION_CAP) + if want: + for index, element in enumerate(elements): + if element.select: + chosen.append(index) + if len(chosen) == want: + break + entry[key] = chosen + entry[key + "Total"] = total entries.append(entry) return entries @@ -1118,26 +1138,81 @@ class BrokkrBlenderTarget: path.parent.mkdir(parents=True, exist_ok=True) if sa.resolve_inside(self.output_dir, name, "output", new_file=True) != path: raise sa.ActionRefused("Output path changed while it was being checked.") - with self.bpy.context.temp_override(window=window, area=area, region=region): - result = self.bpy.ops.screen.screenshot_area("EXEC_DEFAULT", False, filepath=str(path)) - if "FINISHED" not in result or not path.is_file(): - raise sa.ActionRefused("Blender did not write the capture.") + source = "region" if self._windows_drawn() else "offscreen" + if source == "region": + with self.bpy.context.temp_override(window=window, area=area, region=region): + result = self.bpy.ops.screen.screenshot_area("EXEC_DEFAULT", False, filepath=str(path)) + if "FINISHED" not in result or not path.is_file(): + raise sa.ActionRefused("Blender did not write the capture.") + else: # a minimised window stops redrawing, so its framebuffer is a stale frame: draw the view itself + try: + width, height, rgba = self._render_view_offscreen(window, area, region) + path.write_bytes(_png_bytes(width, height, rgba)) + except Exception: + path.unlink(missing_ok=True) + raise sa.ActionRefused("Blender is not drawing its window and the view could not be rendered offscreen.") from None self._prune_looks(path.parent) requested_by = command["requestedBy"] since = self._looked.get(requested_by, 0) self._looked[requested_by] = self.human_edit_seq + coarse = self._coarse["seq"] > since receipt = self._receipt(command, "accepted", f"Captured the 3D view to {LOOK_DIR}/{path.name}.", "") receipt.update({ "lookPath": str(path), + "captureSource": source, + "sceneUpdateSeq": self.scene_update_seq, "sessionId": self.session_id, "humanEditSeq": self.human_edit_seq, "humanEditsSinceLook": self.human_edit_seq - since, "editedSinceLook": sorted(n for n, seq in self._last_human_edit.items() if seq > since), + "editedSinceLookCoarse": coarse, + "editedSinceLookNote": (f"Coarse: {self._coarse['why']}; editedSinceLook may name objects she did not touch." + if coarse else ""), "editSelection": self.edit_selection(), }) self._wrote = False return receipt + def _windows_drawn(self) -> bool: + """False when every Blender window of this process is minimised, so none is redrawing. Only Windows can + say; elsewhere a window is taken as drawn.""" + if sys.platform != "win32": + return True + from ctypes import wintypes + user32 = ctypes.windll.user32 + iconic: list[bool] = [] + + @ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM) + def visit(hwnd, _lparam): + owner = wintypes.DWORD() + user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner)) + name = ctypes.create_unicode_buffer(64) + user32.GetClassNameW(hwnd, name, 64) + if owner.value == os.getpid() and name.value == "GHOST_WindowClass" and user32.IsWindowVisible(hwnd): + iconic.append(bool(user32.IsIconic(hwnd))) + return True + + user32.EnumWindows(visit, 0) + return not iconic or not all(iconic) + + def _render_view_offscreen(self, window: Any, area: Any, region: Any) -> tuple[int, int, bytes]: + """The 3D view's own viewpoint drawn into an offscreen buffer of the region's size: RGBA bytes, bottom row + first. Overlays and popups are not drawn.""" + import gpu # only inside Blender + space = area.spaces.active + rv3d = space.region_3d + width, height = region.width, region.height + context = self.bpy.context + offscreen = gpu.types.GPUOffScreen(width, height) + try: + offscreen.draw_view3d(context.scene, context.view_layer, space, region, rv3d.view_matrix, + rv3d.window_matrix, do_color_management=True) + with offscreen.bind(): + buffer = gpu.state.active_framebuffer_get().read_color(0, 0, width, height, 4, 0, "UBYTE") + return width, height, bytes(buffer) + finally: + offscreen.free() + @staticmethod def _prune_looks(directory: Path) -> None: """Keep the newest LOOK_KEPT captures: plain .png files directly in the look directory, nothing else.""" @@ -1461,6 +1536,18 @@ def _parse_time(value: Any) -> datetime | None: return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc) +def _png_bytes(width: int, height: int, rgba: bytes) -> bytes: + """An 8-bit RGBA PNG of bottom-row-first pixels, written top row first.""" + stride = width * 4 + rows = b"".join(b"\x00" + rgba[y * stride:(y + 1) * stride] for y in range(height - 1, -1, -1)) + + def chunk(kind: bytes, data: bytes) -> bytes: + return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data)) + + return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(rows, 1)) + chunk(b"IEND", b"")) + + def _now() -> str: return datetime.now(timezone.utc).isoformat() diff --git a/surfaces/blender/tests/test_perception.py b/surfaces/blender/tests/test_perception.py index ee793e8..48ba6fb 100644 --- a/surfaces/blender/tests/test_perception.py +++ b/surfaces/blender/tests/test_perception.py @@ -33,21 +33,40 @@ def window(*areas): class Element: - def __init__(self, selected): - self.select = selected + def __init__(self, selected, fake): + self._select, self._fake = selected, fake + + @property + def select(self): + self._fake.touched += 1 # every look at an element's flag costs a Python call in the real thing + return self._select + + +class Elements: + """A lazy sequence: a million of them without a million objects.""" + def __init__(self, fake, flags): + self.fake, self.flags = fake, flags + + def __iter__(self): + for flag in self.flags: + yield Element(flag, self.fake) class FakeBmesh: - """bmesh.from_edit_mesh(mesh) -> a mesh with verts, edges and faces that carry .select.""" + """bmesh.from_edit_mesh(mesh) -> verts, edges, faces that carry .select. The mesh carries + total_vert_sel and friends, as Mesh does in Edit Mode; a test may set them apart from the flags.""" def __init__(self, meshes): self.meshes = meshes self.reads = 0 + self.touched = 0 + self.totals = None # override: (verts, edges, faces) the mesh claims def from_edit_mesh(self, mesh): self.reads += 1 verts, edges, faces = self.meshes[id(mesh)] - return NS(verts=[Element(s) for s in verts], edges=[Element(s) for s in edges], - faces=[Element(s) for s in faces]) + counts = self.totals or tuple(sum(1 for f in kind if f) for kind in (verts, edges, faces)) + mesh.total_vert_sel, mesh.total_edge_sel, mesh.total_face_sel = counts + return NS(verts=Elements(self, verts), edges=Elements(self, edges), faces=Elements(self, faces)) class PerceptionFixture(unittest.TestCase): @@ -221,6 +240,215 @@ def rich(obj): return obj +class _All: + """Endless selected flags: a scan that does not stop at the cap would never return.""" + def __iter__(self): + return iter([True] * 5_000_000) + + +class _First: + """A huge mesh whose first n elements are selected: reading past them would show in the touches.""" + def __init__(self, n): + self.n = n + + def __iter__(self): + for i in range(10_000_000): + yield i < self.n + + +class LookFreshnessTests(PerceptionFixture): + """A minimised Blender stops redrawing, so a region capture is a stale frame. Then the view is drawn offscreen.""" + + def setUp(self): + super().setUp() + self.drawn = True + self.target._windows_drawn = lambda: self.drawn + self.offscreen_calls = [] + self.pixels = bytes([10, 20, 30, 255, 40, 50, 60, 255, # bottom row first, as GL reads it + 70, 80, 90, 255, 100, 110, 120, 255]) + + def render(window, area, region): + self.offscreen_calls.append((window, area, region)) + return 2, 2, self.pixels + + self.target._render_view_offscreen = render + + def test_a_drawn_window_is_captured_from_the_region_and_says_so(self): + receipt = self.look() + self.assertEqual((receipt["captureSource"], len(self.shots), self.offscreen_calls), ("region", 1, [])) + + def test_a_window_that_is_not_drawn_is_rendered_offscreen_and_says_so(self): + self.drawn = False + receipt = self.look(commandId="look-off") + self.assertEqual(receipt["status"], "accepted", receipt["message"]) + self.assertEqual(receipt["captureSource"], "offscreen") + self.assertEqual(self.shots, []) # the stale framebuffer is never read + window, area, region = self.offscreen_calls[0] + self.assertIs(window, self.windows[0]) + self.assertIs(area, self.view) + self.assertEqual(region.type, "WINDOW") + self.assertEqual(Path(receipt["lookPath"]), self.look_dir() / "look-off.png") + + def test_the_offscreen_file_is_a_png_of_the_pixels_top_row_first(self): + import struct + import zlib + self.drawn = False + data = Path(self.look()["lookPath"]).read_bytes() + self.assertEqual(data[:8], b"\x89PNG\r\n\x1a\n") + chunks, at = {}, 8 + while at < len(data): + size, kind = struct.unpack(">I4s", data[at:at + 8]) + chunks[kind] = data[at + 8:at + 8 + size] + at += 12 + size + self.assertEqual(struct.unpack(">IIBBBBB", chunks[b"IHDR"]), (2, 2, 8, 6, 0, 0, 0)) + raw = zlib.decompress(chunks[b"IDAT"]) + rows = [raw[i:i + 9] for i in range(0, len(raw), 9)] # a filter byte, then 2 RGBA pixels + self.assertEqual([r[0] for r in rows], [0, 0]) + self.assertEqual(rows[0][1:], self.pixels[8:]) # the top of the picture is the last row GL read + self.assertEqual(rows[1][1:], self.pixels[:8]) + + def test_an_offscreen_failure_is_a_refusal_never_a_stale_picture(self): + self.drawn = False + + def boom(*a): + raise RuntimeError("no gpu") + + self.target._render_view_offscreen = boom + receipt = self.look() + self.assertEqual((receipt["status"], receipt["lookPath"]), ("failed", "")) + self.assertEqual(self.shots, []) + self.assertEqual(list(self.look_dir().glob("*.png")) if self.look_dir().exists() else [], []) + + def test_the_receipt_names_the_scene_update_the_picture_reflects(self): + first = self.look()["sceneUpdateSeq"] + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.assertEqual(self.look()["sceneUpdateSeq"], first + 1) + + def test_agent_turn_updates_move_the_scene_update_sequence_too(self): + # it counts every update, hers or the agent's: what the capture reflects is the whole scene + before = self.target.scene_update_seq + self.target.agent_turn = True + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.target.agent_turn = False + self.assertEqual((self.target.scene_update_seq, self.target.human_edit_seq), (before + 1, 0)) + + def test_an_update_without_flags_still_counts_as_a_scene_update(self): + before = self.target.scene_update_seq + self.target.track_human_edits(depsgraph(update("Cube"))) + self.assertEqual(self.target.scene_update_seq, before + 1) + + def test_a_new_session_restarts_the_scene_update_sequence(self): + self.target.track_human_edits(depsgraph(update("Cube"))) + self.target.renew_session() + self.assertEqual(self.target.scene_update_seq, 0) + + def test_the_default_window_check_assumes_drawn_off_windows(self): + target = bt.BrokkrBlenderTarget(self.bpy) + with unittest.mock.patch.object(bt.sys, "platform", "linux"): + self.assertTrue(target._windows_drawn()) + + +class LookPathTests(PerceptionFixture): + def test_a_path_that_changes_after_the_directory_is_made_is_refused_and_nothing_is_captured(self): + # the second check is the guard for the gap between the first check and the capture + real = bt.sa.resolve_inside + calls = [] + + def swapped(root, candidate, label, **kw): + path = real(root, candidate, label, **kw) + calls.append(path) + return path if len(calls) == 1 else path.with_name("elsewhere.png") + + with unittest.mock.patch.object(bt.sa, "resolve_inside", swapped): + receipt = self.look() + self.assertEqual((receipt["status"], len(calls)), ("failed", 2)) + self.assertIn("changed", receipt["message"]) + self.assertEqual((self.shots, receipt["lookPath"]), ([], "")) + + def test_the_prune_does_not_follow_a_link_to_a_file(self): + # a link named *.png is not a plain file: it is never counted or removed through + removed = [] + + class Entry: + def __init__(self, name, mtime, link): + self.name, self.path, self._mtime, self._link = name, "dir/" + name, mtime, link + + def is_file(self, follow_symlinks=True): + return follow_symlinks or not self._link # a link is a file only when followed + + def stat(self, follow_symlinks=True): + return NS(st_mtime_ns=self._mtime) + + entries = [Entry(f"f{n:02d}.png", n, False) for n in range(21)] + [Entry("link.png", 0, True)] + + class Scan: + def __enter__(self): + return iter(entries) + + def __exit__(self, *a): + return False + + with unittest.mock.patch.object(bt.os, "scandir", lambda d: Scan()), \ + unittest.mock.patch.object(bt.os, "unlink", removed.append): + bt.BrokkrBlenderTarget._prune_looks(Path("dir")) + self.assertEqual(removed, ["dir/f00.png"]) + + +class CoarseAttributionTests(PerceptionFixture): + NOTE_WORDS = ("all objects flagged",) + + def edits(self, since_look="nibu/hands"): + return self.look(requestedBy=since_look) + + def test_a_precise_edit_is_not_marked_coarse(self): + self.edits() + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + receipt = self.edits() + self.assertEqual((receipt["editedSinceLookCoarse"], receipt["editedSinceLookNote"]), (False, "")) + + def test_an_update_that_flags_every_object_is_marked_coarse_and_says_why(self): + self.edits() + self.target.track_human_edits(depsgraph(*[update(n, transform=True, geometry=True) for n in ("Cube", "Lamp", "Cam")])) + receipt = self.edits() + self.assertTrue(receipt["editedSinceLookCoarse"]) + self.assertIn("all objects flagged", receipt["editedSinceLookNote"]) + self.assertEqual(receipt["editedSinceLook"], ["Cam", "Cube", "Lamp"]) # the semantics are unchanged + + def test_an_undo_or_redo_is_coarse(self): + self.edits() + self.target.note_undo_redo() + receipt = self.edits() + self.assertTrue(receipt["editedSinceLookCoarse"]) + self.assertIn("undo", receipt["editedSinceLookNote"]) + + def test_coarse_clears_with_the_next_look_and_comes_back_only_for_a_new_coarse_edit(self): + self.edits() + self.target.note_undo_redo() + self.assertTrue(self.edits()["editedSinceLookCoarse"]) + self.assertFalse(self.edits()["editedSinceLookCoarse"]) + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.assertFalse(self.edits()["editedSinceLookCoarse"]) + + def test_each_agent_has_its_own_coarse_since_its_last_look(self): + self.edits("nibu/hands") + self.target.note_undo_redo() + self.edits("nibu/hands") + self.assertTrue(self.edits("nibu/soul")["editedSinceLookCoarse"]) # soul has not looked since + + def test_a_new_session_forgets_coarse(self): + self.target.note_undo_redo() + self.target.renew_session() + self.assertFalse(self.edits()["editedSinceLookCoarse"]) + + def test_one_object_in_a_scene_of_one_is_not_coarse(self): + # nothing to over-attribute when there is only one object to name + for name in ("Cam", "Lamp"): + del self.bpy.data.objects[name] + self.edits() + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.assertFalse(self.edits()["editedSinceLookCoarse"]) + + class EditSelectionTests(PerceptionFixture): def snapshot(self): for obj in self.bpy.data.objects: @@ -259,6 +487,23 @@ class EditSelectionTests(PerceptionFixture): self.assertEqual((entry["edges"], entry["edgesTotal"]), ([5000], 1)) self.assertEqual((len(entry["faces"]), entry["facesTotal"]), (4096, 4096)) + def test_totals_come_from_the_mesh_and_the_scan_stops_at_the_cap(self): + # a million selected of each kind: the totals are the mesh's own counts, and each kind is read only up to the cap + self.bpy.mesh.mode = "EDIT" + self.bmesh.meshes[id(self.bpy.mesh_data)] = (_All(), _All(), _All()) + self.bmesh.totals = (1_000_000, 2_000_000, 3_000_000) + entry = self.target.edit_selection()[0] + self.assertEqual((entry["verticesTotal"], entry["edgesTotal"], entry["facesTotal"]), (1_000_000, 2_000_000, 3_000_000)) + self.assertEqual([len(entry[k]) for k in ("vertices", "edges", "faces")], [4096] * 3) + self.assertEqual(self.bmesh.touched, 3 * 4096) + + def test_a_small_selection_in_a_big_mesh_stops_when_every_selected_element_is_found(self): + self.bpy.mesh.mode = "EDIT" + self.bmesh.meshes[id(self.bpy.mesh_data)] = (_First(3), _First(2), _First(0)) + entry = self.target.edit_selection()[0] + self.assertEqual((entry["vertices"], entry["edges"], entry["faces"]), ([0, 1, 2], [0, 1], [])) + self.assertEqual(self.bmesh.touched, 3 + 2) # no scan past the last selected one, none at all when the total is zero + def test_every_object_in_edit_mode_is_listed_and_a_non_mesh_says_unsupported(self): self.bpy.mesh.mode = "EDIT" self.bpy.cam.mode = "EDIT" From 270b596f050354bcd7a7a7114969bed1582ce0e0 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 22:57:02 +0100 Subject: [PATCH 32/63] Perception fixes: live proof (minimised look, coarse flags, 1M-vertex read) and the contract in the docs Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/docs/install.md | 10 +- .../blender/tests/live/perception_fixes.py | 243 ++++++++++++++ .../tests/live/perception_fixes.result.json | 298 ++++++++++++++++++ 3 files changed, 549 insertions(+), 2 deletions(-) create mode 100644 surfaces/blender/tests/live/perception_fixes.py create mode 100644 surfaces/blender/tests/live/perception_fixes.result.json diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 0eb7d40..d3dec32 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -233,7 +233,11 @@ gets a `failed` receipt whose message names the rule): `lookPath`; 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. The look directory keeps the newest 20 PNGs (scratch, + Edit Mode. The capture blocks her UI for about 70 ms. `captureSource` says how it was taken: `region`, or + `offscreen` when 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. `sceneUpdateSeq` is 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 carries `sessionId`, `humanEditSeq`, `humanEditsSinceLook` and `editedSinceLook` (object names), counted for the sending `requestedBy` since its previous look in this session, and `editSelection`: for each object in Edit Mode its selected vertex, edge and face indices (each @@ -242,7 +246,9 @@ gets a `failed` receipt whose message names the rule): object's `lastHumanEditSeq`. 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, so `editedSinceLook` can name more than she touched. They are + linking an object flags all of them, so `editedSinceLook` can name more than she touched; the receipt then + says so: `editedSinceLookCoarse` is true, with the reason in `editedSinceLookNote` (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. The scene actions were run against Blender 5.2.3 LTS headless with diff --git a/surfaces/blender/tests/live/perception_fixes.py b/surfaces/blender/tests/live/perception_fixes.py new file mode 100644 index 0000000..7facba2 --- /dev/null +++ b/surfaces/blender/tests/live/perception_fixes.py @@ -0,0 +1,243 @@ +"""Live proof of the live-5 fix batch, in GUI Blender with the add-on installed as an extension, real brokkr-ctl looks. + +Same environment as perception.py (BROKKR_SCRATCH, BROKKR_CTL, BROKKR_CULTLIB; a fresh BLENDER_USER_RESOURCE_PATH). + blender --python perception_fixes.py -- +The driver stands in for the operator: it saves the blend, ticks the sink, sets the output directory, minimises and +restores the Blender window (Windows ShowWindow on this process's own window), moves objects, enters Edit Mode. +""" +import ctypes +import importlib +import json +import os +import statistics +import subprocess +import sys +import time +import traceback +from ctypes import wintypes +from pathlib import Path + +import bmesh +import bpy +import numpy + +SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() +CTL = os.environ["BROKKR_CTL"] +OUT = sys.argv[sys.argv.index("--") + 1] +MODULE = os.environ.get("BROKKR_ADDON_MODULE", "bl_ext.user_default.brokkr_bridge") +R = {"blender": bpy.app.version_string, "checks": [], "notes": {}} +bpy.ops.preferences.addon_enable(module=MODULE) +addon = importlib.import_module(MODULE) +prefs = bpy.context.preferences.addons[MODULE].preferences +prefs.cultlib_py_src = os.environ.get("BROKKR_CULTLIB", prefs.cultlib_py_src) +adapter = addon.target() +STORE = SCRATCH / ".brokkr" / "blender-editor.ccmp" +ENV = dict(os.environ, EUREKA_INSTANCE="nibu", BROKKR_BLENDER_STORE=str(STORE), BROKKR_AGENT="hands") +user32 = ctypes.windll.user32 + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def fields(text): + out = {} + for line in text.splitlines(): + key, _, value = line.partition(": ") + try: + out[key] = json.loads(value) if value[:1] in "[{0123456789tf" else value + except ValueError: + out[key] = value + return out + + +def ctl(*args): + proc = subprocess.Popen([CTL, "blender", *args], env=ENV, stdout=subprocess.PIPE, text=True) + while proc.poll() is None: + yield + return proc.returncode, fields(proc.stdout.read()) + + +def blender_windows(): + found = [] + + @ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM) + def visit(hwnd, _): + owner = wintypes.DWORD() + user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner)) + name = ctypes.create_unicode_buffer(64) + user32.GetClassNameW(hwnd, name, 64) + if owner.value == os.getpid() and name.value == "GHOST_WindowClass" and user32.IsWindowVisible(hwnd): + found.append(hwnd) + return True + + user32.EnumWindows(visit, 0) + return found + + +def show(cmd): # 6 minimise, 9 restore + for hwnd in blender_windows(): + user32.ShowWindow(hwnd, cmd) + + +def pixels(path): + image = bpy.data.images.load(str(path)) + try: + return numpy.array(image.pixels[:], dtype=numpy.float32).reshape(image.size[1], image.size[0], 4) + finally: + bpy.data.images.remove(image) + + +def diff_box(a, b): + mask = numpy.abs(a - b).max(axis=2) > 0.02 + if not mask.any(): + return None + ys, xs = numpy.where(mask) + return [int(xs.min()), int(ys.min()), int(xs.max()), int(ys.max())] + + +def old_scan(obj): + """The scan this fix replaces: every vertex, edge and face walked in Python.""" + mesh = bmesh.from_edit_mesh(obj.data) + out = [] + for elements in (mesh.verts, mesh.edges, mesh.faces): + chosen = [i for i, e in enumerate(elements) if e.select] + out.append((chosen[:4096], len(chosen))) + return out + + +def flow(): + bpy.ops.wm.save_as_mainfile(filepath=str(SCRATCH / "fixes.blend")) + prefs.output_dir = str(SCRATCH / "out") + prefs.auto_drain_commands = True + yield 1.0 + with bpy.context.temp_override(window=bpy.context.window_manager.windows[0]): + bpy.ops.brokkr.capture_snapshot() + cube = bpy.data.objects["Cube"] + # ---- minimised window: look must show the current scene ---- + code, a0 = yield from ctl("look") + check("window up: the region capture, source named", code == 0 and a0["captureSource"] == "region", a0) + show(6) + yield 1.0 + iconic = [bool(user32.IsIconic(h)) for h in blender_windows()] + R["notes"]["iconic_after_minimise"] = iconic + check("the Blender window is minimised (IsIconic)", iconic and all(iconic), iconic) + code, a = yield from ctl("look") + cube.location.x = 3.0 # her edit, while minimised + yield 0.5 + code, b = yield from ctl("look") + pa = pixels(a["lookPath"]) if a.get("lookPath") else None + pb = pixels(b["lookPath"]) if b.get("lookPath") else None + box = diff_box(pa, pb) if pa is not None and pb is not None else None + R["notes"]["minimised"] = {"a": a, "b": b, "diff_box": box} + check("minimised: both looks are accepted and say they were rendered offscreen", + code == 0 and a.get("captureSource") == "offscreen" and b.get("captureSource") == "offscreen", [a.get("captureSource"), b.get("captureSource")]) + check("minimised: the Cube moved by her shows in the next look (the pictures differ, in a box)", box is not None, box) + check("minimised: sceneUpdateSeq advanced between the two looks", b["sceneUpdateSeq"] > a["sceneUpdateSeq"], [a["sceneUpdateSeq"], b["sceneUpdateSeq"]]) + check("minimised: size equals the 3D region", [pb.shape[1], pb.shape[0]] == [1574, 888] if pb is not None else False, + None if pb is None else [pb.shape[1], pb.shape[0]]) + # the agent's own move while minimised, then look + code, m = yield from ctl("send", "setObjectTransform", "--set", 'targetObjectName="Cube"', "--set", "location=[-3,0,0]") + code, c = yield from ctl("look") + pc = pixels(c["lookPath"]) + check("minimised: the agent's own move is in its next look", diff_box(pb, pc) is not None and c["sceneUpdateSeq"] > b["sceneUpdateSeq"], diff_box(pb, pc)) + show(9) + yield 1.5 + code, d = yield from ctl("look") + check("restored: back to the region capture", code == 0 and d.get("captureSource") == "region", d.get("captureSource")) + + # ---- coarse attribution ---- + code, e0 = yield from ctl("look") + follower = bpy.data.objects.new("Follower", bpy.data.meshes.new("FM")) + bpy.context.scene.collection.objects.link(follower) + yield 0.5 + code, e1 = yield from ctl("look") + check("after her link of an object: the receipt says the attribution is coarse", + e1.get("editedSinceLookCoarse") is True and "all objects flagged" in e1.get("editedSinceLookNote", ""), e1) + code, e2 = yield from ctl("look") + cube.location.y = 1.0 + yield 0.5 + code, e3 = yield from ctl("look") + check("after a plain move: not coarse, only the Cube named", e3.get("editedSinceLookCoarse") is False and e3.get("editedSinceLook") == ["Cube"], e3) + with bpy.context.temp_override(window=bpy.context.window_manager.windows[0]): + bpy.ops.ed.undo() + yield 0.5 + code, e4 = yield from ctl("look") + check("after her undo: coarse", e4.get("editedSinceLookCoarse") is True, e4) + + # ---- one million vertices in Edit Mode ---- + mesh = bpy.data.meshes.new("Big") + bm = bmesh.new() + bmesh.ops.create_grid(bm, x_segments=1000, y_segments=1000, size=1.0) + bm.to_mesh(mesh) + bm.free() + big = bpy.data.objects.new("Big", mesh) + bpy.context.scene.collection.objects.link(big) + bpy.context.view_layer.objects.active = big + for o in bpy.context.view_layer.objects: + o.select_set(o is big) + yield 0.5 + window = bpy.context.window_manager.windows[0] + area = next(a for a in window.screen.areas if a.type == "VIEW_3D") + region = next(r for r in area.regions if r.type == "WINDOW") + with bpy.context.temp_override(window=window, area=area, region=region, active_object=big, object=big): + bpy.ops.object.mode_set(mode="EDIT") + bpy.ops.mesh.select_all(action="SELECT") + yield 0.5 + R["notes"]["verts"] = len(mesh.vertices) + new_ms, old_ms = [], [] + for _ in range(5): # paired, interleaved + t = time.perf_counter() + new = adapter.edit_selection() + new_ms.append((time.perf_counter() - t) * 1000) + t = time.perf_counter() + old = old_scan(big) + old_ms.append((time.perf_counter() - t) * 1000) + entry = new[0] + parts = {} + t = time.perf_counter(); bm2 = bmesh.from_edit_mesh(big.data); parts["from_edit_mesh"] = (time.perf_counter() - t) * 1000 + t = time.perf_counter(); totals = (big.data.total_vert_sel, big.data.total_edge_sel, big.data.total_face_sel); parts["totals"] = (time.perf_counter() - t) * 1000 + for name, seq in (("verts", bm2.verts), ("edges", bm2.edges), ("faces", bm2.faces)): + t = time.perf_counter(); n = 0 + for i, e in enumerate(seq): + if e.select: + n += 1 + if n == 4096: + break + parts[name] = (time.perf_counter() - t) * 1000 + R["notes"]["edit_selection_parts_ms"] = {k: round(v, 1) for k, v in parts.items()} + R["notes"]["edit_selection_ms"] = {"new": [round(x) for x in new_ms], "old": [round(x) for x in old_ms], + "new_median": round(statistics.median(new_ms)), "old_median": round(statistics.median(old_ms))} + check("1M vertices: the totals are the mesh's own and the lists are capped at 4096", + entry["verticesTotal"] == 1_002_001 and len(entry["vertices"]) == 4096 and entry["vertices"] == old[0][0] + and entry["edgesTotal"] == old[1][1] and entry["facesTotal"] == old[2][1], [entry["verticesTotal"], entry["edgesTotal"], entry["facesTotal"]]) + check("1M vertices: the read is several times faster than the full scan (medians in notes)", + statistics.median(old_ms) > 3 * statistics.median(new_ms), R["notes"]["edit_selection_ms"]) + with bpy.context.temp_override(window=window, area=area, region=region, active_object=big, object=big): + bpy.ops.object.mode_set(mode="OBJECT") + check("no add-on drain error", adapter.last_auto_drain_error == "", adapter.last_auto_drain_error) + + +gen = flow() + + +def write(): + R["ok"] = bool(R["checks"]) and all(c["ok"] for c in R["checks"]) and not R.get("errors") + with open(OUT + ".result.json", "w") as f: + json.dump(R, f, indent=1, default=str) + + +def runner(): + try: + delay = next(gen) + return delay if isinstance(delay, (int, float)) and delay else 0.05 + except StopIteration: + write() + bpy.ops.wm.quit_blender() + except Exception: + R.setdefault("errors", []).append(traceback.format_exc()) + write() + bpy.ops.wm.quit_blender() + + +bpy.app.timers.register(runner, first_interval=3.0) diff --git a/surfaces/blender/tests/live/perception_fixes.result.json b/surfaces/blender/tests/live/perception_fixes.result.json new file mode 100644 index 0000000..af2638c --- /dev/null +++ b/surfaces/blender/tests/live/perception_fixes.result.json @@ -0,0 +1,298 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "window up: the region capture, source named", + "ok": true, + "detail": { + "commandId": "01a21f023e60712180b8b5afee5b2621", + "action": "look", + "captureSource": "region", + "editSelection": [], + "editedSinceLook": [], + "editedSinceLookCoarse": false, + "editedSinceLookNote": "", + "humanEditSeq": 0, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f023e60712180b8b5afee5b2621.png", + "message": "Captured the 3D view to look/01a21f023e60712180b8b5afee5b2621.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:56:11.107854+00:00", + "requestedBy": "nibu/hands", + "sceneUpdateSeq": 0, + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "the Blender window is minimised (IsIconic)", + "ok": true, + "detail": [ + true + ] + }, + { + "name": "minimised: both looks are accepted and say they were rendered offscreen", + "ok": true, + "detail": [ + "offscreen", + "offscreen" + ] + }, + { + "name": "minimised: the Cube moved by her shows in the next look (the pictures differ, in a box)", + "ok": true, + "detail": [ + 711, + 248, + 975, + 529 + ] + }, + { + "name": "minimised: sceneUpdateSeq advanced between the two looks", + "ok": true, + "detail": [ + 0, + 1 + ] + }, + { + "name": "minimised: size equals the 3D region", + "ok": true, + "detail": [ + 1574, + 888 + ] + }, + { + "name": "minimised: the agent's own move is in its next look", + "ok": true, + "detail": [ + 656, + 248, + 975, + 581 + ] + }, + { + "name": "restored: back to the region capture", + "ok": true, + "detail": "region" + }, + { + "name": "after her link of an object: the receipt says the attribution is coarse", + "ok": true, + "detail": { + "commandId": "01a21f02711f7571991decbd06059938", + "action": "look", + "captureSource": "region", + "editSelection": [], + "editedSinceLook": [ + "Camera", + "Cube", + "Follower", + "Light" + ], + "editedSinceLookCoarse": true, + "editedSinceLookNote": "Coarse: all objects flagged; editedSinceLook may name objects she did not touch.", + "humanEditSeq": 4, + "humanEditsSinceLook": 1, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f02711f7571991decbd06059938.png", + "message": "Captured the 3D view to look/01a21f02711f7571991decbd06059938.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:56:23.908406+00:00", + "requestedBy": "nibu/hands", + "sceneUpdateSeq": 5, + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "after a plain move: not coarse, only the Cube named", + "ok": true, + "detail": { + "commandId": "01a21f027a1873a1a21df913136a4d49", + "action": "look", + "captureSource": "region", + "editSelection": [], + "editedSinceLook": [ + "Cube" + ], + "editedSinceLookCoarse": false, + "editedSinceLookNote": "", + "humanEditSeq": 5, + "humanEditsSinceLook": 1, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f027a1873a1a21df913136a4d49.png", + "message": "Captured the 3D view to look/01a21f027a1873a1a21df913136a4d49.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:56:26.306053+00:00", + "requestedBy": "nibu/hands", + "sceneUpdateSeq": 6, + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "after her undo: coarse", + "ok": true, + "detail": { + "commandId": "01a21f027ec27dd0bda5c62b0974531a", + "action": "look", + "captureSource": "region", + "editSelection": [], + "editedSinceLook": [ + "Camera", + "Cube", + "Light" + ], + "editedSinceLookCoarse": true, + "editedSinceLookNote": "Coarse: all objects flagged; editedSinceLook may name objects she did not touch.", + "humanEditSeq": 7, + "humanEditsSinceLook": 2, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f027ec27dd0bda5c62b0974531a.png", + "message": "Captured the 3D view to look/01a21f027ec27dd0bda5c62b0974531a.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:56:27.505456+00:00", + "requestedBy": "nibu/hands", + "sceneUpdateSeq": 7, + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "1M vertices: the totals are the mesh's own and the lists are capped at 4096", + "ok": true, + "detail": [ + 1002001, + 2002000, + 1000000 + ] + }, + { + "name": "1M vertices: the read is several times faster than the full scan (medians in notes)", + "ok": true, + "detail": { + "new": [ + 221, + 191, + 185, + 197, + 193 + ], + "old": [ + 977, + 950, + 974, + 1059, + 956 + ], + "new_median": 193, + "old_median": 974 + } + }, + { + "name": "no add-on drain error", + "ok": true, + "detail": "" + } + ], + "notes": { + "iconic_after_minimise": [ + true + ], + "minimised": { + "a": { + "commandId": "01a21f02458877a186fe6a31fe3b32d6", + "action": "look", + "captureSource": "offscreen", + "editSelection": [], + "editedSinceLook": [], + "editedSinceLookCoarse": false, + "editedSinceLookNote": "", + "humanEditSeq": 0, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f02458877a186fe6a31fe3b32d6.png", + "message": "Captured the 3D view to look/01a21f02458877a186fe6a31fe3b32d6.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:56:13.275722+00:00", + "requestedBy": "nibu/hands", + "sceneUpdateSeq": 0, + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "status": "accepted", + "undoLabel": "" + }, + "b": { + "commandId": "01a21f024b1876d0a4ec6281a49404a2", + "action": "look", + "captureSource": "offscreen", + "editSelection": [], + "editedSinceLook": [ + "Cube" + ], + "editedSinceLookCoarse": false, + "editedSinceLookNote": "", + "humanEditSeq": 1, + "humanEditsSinceLook": 1, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f024b1876d0a4ec6281a49404a2.png", + "message": "Captured the 3D view to look/01a21f024b1876d0a4ec6281a49404a2.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:56:14.485857+00:00", + "requestedBy": "nibu/hands", + "sceneUpdateSeq": 1, + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "status": "accepted", + "undoLabel": "" + }, + "diff_box": [ + 711, + 248, + 975, + 529 + ] + }, + "verts": 1002001, + "edit_selection_parts_ms": { + "from_edit_mesh": 0.0, + "totals": 0.0, + "verts": 24.7, + "edges": 79.6, + "faces": 33.2 + }, + "edit_selection_ms": { + "new": [ + 221, + 191, + 185, + 197, + 193 + ], + "old": [ + 977, + 950, + 974, + 1059, + 956 + ], + "new_median": 193, + "old_median": 974 + } + }, + "ok": true +} \ No newline at end of file From 282d9eff7a2901d1672c4bcb61106f22d8b791b4 Mon Sep 17 00:00:00 2001 From: Eureka Date: Sat, 28 Nov 2026 01:13:22 +0000 Subject: [PATCH 33/63] Blender add-on: glTF export checked against real Blender, atomic export, a render refusal that holds (#17) --- brokkr-daemon/src/main.rs | 36 +++ docs/provider-contract.md | 1 + surfaces/blender/brokkr_bridge/__init__.py | 2 +- .../blender/brokkr_bridge/blender_target.py | 264 +++++++++++++--- surfaces/blender/brokkr_bridge/gl_probe.py | 15 + surfaces/blender/docs/install.md | 27 +- surfaces/blender/tests/live/export_gltf.py | 102 ++++++ .../tests/live/export_gltf.result.json | 114 +++++++ surfaces/blender/tests/live/refusals.py | 74 +++++ .../blender/tests/live/refusals.result.json | 57 ++++ surfaces/blender/tests/test_scene_actions.py | 293 ++++++++++++++++-- 11 files changed, 904 insertions(+), 81 deletions(-) create mode 100644 surfaces/blender/brokkr_bridge/gl_probe.py create mode 100644 surfaces/blender/tests/live/export_gltf.py create mode 100644 surfaces/blender/tests/live/export_gltf.result.json create mode 100644 surfaces/blender/tests/live/refusals.py create mode 100644 surfaces/blender/tests/live/refusals.result.json diff --git a/brokkr-daemon/src/main.rs b/brokkr-daemon/src/main.rs index f83e29b..643cae9 100644 --- a/brokkr-daemon/src/main.rs +++ b/brokkr-daemon/src/main.rs @@ -3379,6 +3379,42 @@ mod tests { Ok(()) } + #[test] + fn sync_once_writes_an_inactive_unity_object_as_hidden_in_blender() -> Result<()> { + let temp = tempfile::tempdir()?; + let unity_path = temp.path().join("unity.ccmp"); + let blender_path = temp.path().join("blender.ccmp"); + seed_component_property_stores(&unity_path, &blender_path, "active-state")?; + MirrorStore::open(&unity_path)?.put_messagepack_document( + "brokkr.unity.host_snapshot.v0", + "unity/host/current", + &json!({ + "sceneObjects": [{ + "objectId": "unity-cube", + "name": "Cube", + "path": "/Cube", + "activeSelf": false + }] + }), + )?; + + let report = run_sync_once(&SyncArgs { + unity_cache: unity_path, + blender_cache: blender_path.clone(), + dry_run: false, + })?; + + assert_eq!(report.blender_commands_written, 1, "{report:#?}"); + let command = MirrorStore::open(&blender_path)? + .documents()? + .into_iter() + .find(|document| document.key.starts_with("blender/commands/")) + .expect("Brokkr should emit a Blender visibility command"); + assert_eq!(command.value["action"], "setObjectVisibility"); + assert_eq!(command.value["visible"], false); + Ok(()) + } + #[test] fn dry_run_counts_active_state_command_but_writes_none() -> Result<()> { let temp = tempfile::tempdir()?; diff --git a/docs/provider-contract.md b/docs/provider-contract.md index cda8707..6ccbb10 100644 --- a/docs/provider-contract.md +++ b/docs/provider-contract.md @@ -216,6 +216,7 @@ All Blender writes use `brokkr.blender.command_intent.v0` and receive - `selectObject` - `assignMaterial` - `importGltf` +- `exportGltf` (writes under the add-on preference Render Output Directory, never overwriting) - `setCamera` - `setLight` - `setWorld` diff --git a/surfaces/blender/brokkr_bridge/__init__.py b/surfaces/blender/brokkr_bridge/__init__.py index 58fd75b..c9db1ec 100644 --- a/surfaces/blender/brokkr_bridge/__init__.py +++ b/surfaces/blender/brokkr_bridge/__init__.py @@ -88,7 +88,7 @@ class BrokkrPreferences(bpy.types.AddonPreferences): name="Render Output Directory", subtype="DIR_PATH", default="", - description="renderStill may only write files inside this directory; empty disables renderStill", + description="renderStill and exportGltf may only write files inside this directory; empty disables both", ) auto_capture: bpy.props.BoolProperty( diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 93a9fb5..0bc72b3 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -6,8 +6,12 @@ import json import math import os import re +import shutil +import signal import struct +import subprocess import sys +import tempfile import uuid import zlib from array import array @@ -16,6 +20,11 @@ from datetime import datetime, timedelta, timezone from pathlib import Path from typing import Any, Iterable +if os.name == "nt": + import msvcrt +else: + import fcntl + from . import node_actions as na from . import scene_actions as sa from .server_guard import BindRefused, SessionGuard, check_bind, guarded_server_class, is_loopback_host, stop_pending @@ -42,10 +51,14 @@ SYNC_RECEIPT_SCHEMA = "brokkr.sync.receipt.v0" CREATABLE_OBJECT_TYPES = ("MESH", "LIGHT", "CAMERA", "EMPTY") -# Engines that draw through the GL stack. A headless Linux Blender without libEGL aborts the whole -# process inside bpy.ops.render.render for these (no receipt); CYCLES renders on the CPU. +# Engines that draw through the GL stack. A headless Blender with no usable GL device aborts the whole +# process inside bpy.ops.render.render for these (no receipt); CYCLES renders on the CPU. Whether it +# will is found by rendering one pixel in a child Blender (gl_render_failure), not by guessing at libraries. GL_RENDER_ENGINES = ("BLENDER_WORKBENCH", "BLENDER_EEVEE", "BLENDER_EEVEE_NEXT") -GL_RUNTIME_LIBRARY = "libEGL.so.1" +GL_PROBE_TIMEOUT_SECONDS = 120 +EXPORT_STAGE_PREFIX = ".brokkr-export-" +STAGE_LOCK = ".brokkr-lock" +STAGE_JOURNAL = ".brokkr-journal" # Actions that only read the scene and so push no undo step. READ_ACTIONS = ("look",) @@ -732,8 +745,9 @@ class BrokkrBlenderTarget: raise sa.ActionRefused( f"objectType {shown!r} cannot be created; allowed: {', '.join(CREATABLE_OBJECT_TYPES)}.") mesh_type = command.get("meshType") - if object_type == "MESH" and mesh_type is not None and ( - not isinstance(mesh_type, str) or mesh_type.upper() != "CUBE"): + if mesh_type is not None and object_type != "MESH": + raise sa.ActionRefused(f"meshType applies only to objectType MESH, not {object_type}.") + if mesh_type is not None and (not isinstance(mesh_type, str) or mesh_type.upper() != "CUBE"): raise sa.ActionRefused(f"meshType {mesh_type!r} is not available; a MESH is a CUBE.") name = command.get("name") or f"Brokkr {object_type.title()}" location = _vector(command.get("location"), 3, (0.0, 0.0, 0.0)) @@ -868,6 +882,8 @@ class BrokkrBlenderTarget: name = command.get("filepath") if not isinstance(name, str): raise sa.ActionRefused("filepath must be a string.") + if self.output_dir: + _sweep_stale_stages(Path(self.output_dir).resolve()) path = sa.resolve_inside(self.output_dir, name, "output", new_file=True) suffix = path.suffix.lower() if suffix not in sa.GLTF_EXTENSIONS: @@ -892,30 +908,90 @@ 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]}") - binary = path.with_suffix(".bin") - if suffix == ".gltf" and os.path.lexists(binary): - raise sa.ActionRefused("output path already exists; output actions never overwrite: " + binary.name) - path.parent.mkdir(parents=True, exist_ok=True) - # Re-check after the folders exist and just before use (residual TOCTOU as in renderStill). - if sa.resolve_inside(self.output_dir, name, "output", new_file=True) != path: - raise sa.ActionRefused("Output path changed while it was being checked.") - # The selection is touched only when one was asked for, and only on view-layer objects. - objects = list(context.view_layer.objects.values()) if chosen else [] - saved = [(obj, obj.select_get()) for obj in objects] + # 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 + # existing file is overwritten and a failed export leaves nothing behind (not even new folders). + made = [] + for folder in (path.parent, *path.parent.parents): + if folder.exists() or folder == Path(self.output_dir).resolve(): + break + made.append(folder) + stage = None + lock_fd = None + moved: list[tuple[Path, Path]] = [] + new_dirs: list[Path] = [] try: - for obj in objects: - obj.select_set(obj in chosen) - result = self.bpy.ops.export_scene.gltf("EXEC_DEFAULT", False, - filepath=str(path), export_format="GLB" if suffix == ".glb" else "GLTF_SEPARATE", - use_selection=bool(chosen), **options) - finally: - for obj, state in saved: - if obj.name in self.bpy.data.objects: - obj.select_set(state) - if "FINISHED" not in result: - raise sa.ActionRefused(f"glTF export did not finish: {sorted(result)}") - if not path.is_file(): - raise sa.ActionRefused("glTF export wrote no file.") + path.parent.mkdir(parents=True, exist_ok=True) + # Re-check after the folders exist and just before use (residual TOCTOU as in renderStill). + if sa.resolve_inside(self.output_dir, name, "output", new_file=True) != path: + raise sa.ActionRefused("Output path changed while it was being checked.") + stage, lock_fd = _open_stage(path.parent) + staged = stage / path.name + # The selection is touched only when one was asked for, and only on view-layer objects. + objects = list(context.view_layer.objects.values()) if chosen else [] + saved = [(obj, obj.select_get()) for obj in objects] + try: + for obj in objects: + obj.select_set(obj in chosen) + result = self.bpy.ops.export_scene.gltf("EXEC_DEFAULT", False, + filepath=str(staged), export_format="GLB" if suffix == ".glb" else "GLTF_SEPARATE", + use_selection=bool(chosen), **options) + finally: + for obj, state in saved: + if obj.name in self.bpy.data.objects: + obj.select_set(state) + if "FINISHED" not in result: + raise sa.ActionRefused(f"glTF export did not finish: {sorted(result)}") + if not staged.is_file(): + raise sa.ActionRefused("glTF export wrote no file.") + written = sorted(f.relative_to(stage) for f in stage.rglob("*") if f.is_file() and f != stage / STAGE_LOCK) + taken = [str(f) for f in written if os.path.lexists(path.parent / f)] + if taken: + raise sa.ActionRefused("output path already exists; output actions never overwrite: " + taken[0]) + for relative in written: + target = path.parent / relative + for folder in (target.parent, *target.parent.parents): + if folder.exists() or folder == path.parent: + break + new_dirs.append(folder) + target.parent.mkdir(parents=True, exist_ok=True) + os.rename(stage / relative, target) + moved.append((stage / relative, target)) + except BaseException as failure: + # A move that fails partway is rolled back: the target is the whole new export or untouched. + stuck = [] + for source, target in reversed(moved): + try: + os.rename(target, source) + except OSError: + stuck.append(target) + if lock_fd is not None: + os.close(lock_fd) + if stage is not None and stuck: + # The rollback itself failed: keep the stage with a journal of the files left in the + # target. Its lock is released, so the next export's sweep removes them and the retry works. + (stage / STAGE_JOURNAL).write_text( + "\n".join(t.relative_to(path.parent).as_posix() for t in stuck), encoding="utf-8") + raise sa.ActionRefused( + "glTF export failed and could not be rolled back; files left in the output directory: " + + ", ".join(t.relative_to(Path(self.output_dir).resolve()).as_posix() for t in stuck) + + ". The next export removes them.") from failure + if stage is not None: + shutil.rmtree(stage, ignore_errors=True) + for folder in sorted(set(new_dirs), key=lambda f: -len(f.parts)): + try: + folder.rmdir() + except OSError: + pass + for folder in made: # deepest first: only the folders this call made, only if still empty + try: + folder.rmdir() + except OSError: + pass + raise + os.close(lock_fd) + shutil.rmtree(stage, ignore_errors=True) return self._receipt(command, "accepted", f"Exported glTF to {path} ({path.stat().st_size} bytes).", "") def _resolve_typed(self, command: dict[str, Any], object_type: str) -> Any: @@ -1024,11 +1100,11 @@ class BrokkrBlenderTarget: except TypeError: raise sa.ActionRefused(f"engine {engine} is not available in this Blender.") from None if render.engine in GL_RENDER_ENGINES and getattr(getattr(self.bpy, "app", None), "background", False): - missing = missing_gl_library() - if missing: + failure = gl_render_failure(getattr(self.bpy.app, "binary_path", ""), render.engine) + if failure: raise sa.ActionRefused( - f"engine {render.engine} needs {missing}, which this headless Blender cannot load " - "(rendering would abort the process); use engine CYCLES.") + f"engine {render.engine} cannot render in this headless Blender ({failure}); " + "rendering would abort the process; use engine CYCLES.") if width is not None: render.resolution_x = width if height is not None: @@ -1515,17 +1591,123 @@ def _load_cultmesh(cultlib_py_src: str) -> tuple[Any, Any]: return cultmesh_py, cultcache_py -@functools.lru_cache(maxsize=None) -def missing_gl_library() -> str | None: - """The GL runtime library this host cannot load, or None. Probed once, on Linux only: on - Windows and macOS a failed GPU render is not a headless-EGL abort.""" - if not sys.platform.startswith("linux"): - return None +GL_PROBE_SCRIPT = Path(__file__).with_name("gl_probe.py") # runs inside the child Blender + + +def _try_lock(fd: int) -> bool: + """Take an exclusive lock on the file, without waiting; the OS drops it when the holder dies.""" try: - ctypes.CDLL(GL_RUNTIME_LIBRARY) + if os.name == "nt": + os.lseek(fd, 0, os.SEEK_SET) + msvcrt.locking(fd, msvcrt.LK_NBLCK, 1) + else: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) except OSError: - return GL_RUNTIME_LIBRARY - return None + return False + return True + + +def _open_stage(parent: Path) -> tuple[Path, int]: + """A fresh staging folder in parent whose lock file this export holds, locked, until it closes the + descriptor or dies: a held lock is how a sweep knows the stage is live.""" + stage = Path(tempfile.mkdtemp(prefix=EXPORT_STAGE_PREFIX, dir=parent)) + fd = os.open(stage / STAGE_LOCK, os.O_RDWR | os.O_CREAT) + if not _try_lock(fd): + os.close(fd) + raise OSError(f"could not lock staging folder {stage}") + return stage, fd + + +def _sweep_stale_stages(top: Path) -> None: + """Remove every staging folder under top whose lock can be taken: its export is over or its Blender + died. A held lock (an export running now, in any process) leaves the folder alone, and so does a + folder with no lock file yet (an export between creating it and locking it).""" + for root, dirs, _ in os.walk(top): + for name in [d for d in dirs if d.startswith(EXPORT_STAGE_PREFIX)]: + dirs.remove(name) + _sweep_stage(Path(root) / name) + + +def _sweep_stage(stage: Path) -> None: + try: + fd = os.open(stage / STAGE_LOCK, os.O_RDWR) + except OSError: + return + try: + if not _try_lock(fd): + return + journal = stage / STAGE_JOURNAL + if journal.is_file(): # a failed rollback's leftovers in the target + for line in journal.read_text(encoding="utf-8").splitlines(): + relative = Path(line) + if not line or relative.is_absolute() or ".." in relative.parts: + continue + target = stage.parent / relative + if target.is_file() and not target.is_symlink(): + target.unlink(missing_ok=True) + for folder in target.parents: + if folder == stage.parent: + break + try: + folder.rmdir() + except OSError: + break + finally: + os.close(fd) + shutil.rmtree(stage, ignore_errors=True) + + +def _kill_tree(process: "subprocess.Popen[str]") -> None: + """Kill process and everything it started, so none keeps its output pipe open.""" + if os.name == "nt": + subprocess.run(["taskkill", "/F", "/T", "/PID", str(process.pid)], capture_output=True, check=False) + else: + try: + os.killpg(process.pid, signal.SIGKILL) + except OSError: + pass + process.kill() + + +_GL_PROBES: dict[tuple[str, str], str | None] = {} + + +def gl_render_failure(binary: str, engine: str) -> str | None: + """Why a headless render with this engine would not survive on this host, or None when it does. + + Renders one pixel in a child process of the same Blender binary: the render aborts the process + it runs in, so only a child can find out. A definite outcome (it rendered, or it exited without + finishing) is cached per binary and engine for the life of the process; a hang, an unstartable + binary or an unknown binary is reported but not cached, so the next render probes again.""" + if not binary or not os.path.isfile(binary): + return "the Blender binary is unknown, so rendering could not be probed" + if (binary, engine) in _GL_PROBES: + return _GL_PROBES[(binary, engine)] + command = [binary, "--background", "--factory-startup", "--python-exit-code", "1", + "--python", str(GL_PROBE_SCRIPT), "--", engine] + group = {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP} if os.name == "nt" else {"start_new_session": True} + try: + process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, **group) + except OSError as exc: + return f"the one-pixel test render could not start: {exc}" + try: + stdout, _ = process.communicate(timeout=GL_PROBE_TIMEOUT_SECONDS) + except subprocess.TimeoutExpired: + _kill_tree(process) + try: + process.communicate(timeout=10) + except subprocess.TimeoutExpired: + pass + return f"a one-pixel test render did not finish in {GL_PROBE_TIMEOUT_SECONDS} s" + if process.returncode == 0 and "BROKKR_GL_PROBE_OK" in stdout: + outcome = None + else: + outcome = f"a one-pixel test render exited with status {process.returncode}" + _GL_PROBES[(binary, engine)] = outcome + return outcome + + +gl_render_failure.cache_clear = _GL_PROBES.clear def _parse_time(value: Any) -> datetime | None: diff --git a/surfaces/blender/brokkr_bridge/gl_probe.py b/surfaces/blender/brokkr_bridge/gl_probe.py new file mode 100644 index 0000000..6331daa --- /dev/null +++ b/surfaces/blender/brokkr_bridge/gl_probe.py @@ -0,0 +1,15 @@ +"""Run inside a child Blender by blender_target.gl_render_failure: render one pixel with the engine named +after `--`, and print the completion marker only if the render returned.""" +import sys + +import bpy + +bpy.ops.wm.read_factory_settings(use_empty=True) +scene = bpy.context.scene +scene.render.engine = sys.argv[-1] +scene.render.resolution_x = scene.render.resolution_y = 1 +camera = bpy.data.objects.new("probe", bpy.data.cameras.new("probe")) +scene.collection.objects.link(camera) +scene.camera = camera +bpy.ops.render.render(write_still=False) +print("BROKKR_GL_PROBE_OK") diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index d3dec32..cf2c3c2 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -184,19 +184,22 @@ gets a `failed` receipt whose message names the rule): `name`, `location`. Any other `objectType` (for example `TEXT` or `CURVE`) is refused with the allowed set named. A `MESH` is a cube (`size`); a `meshType` other than `CUBE` (case-insensitive, no surrounding whitespace) is refused rather than ignored. - `meshType` is checked only when `objectType` is `MESH`; an explicit `objectType: null` is refused. + `meshType` on any other `objectType` is refused too; an explicit `objectType: null` is refused. - `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. - `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, or an existing `.bin` beside a `.gltf`, is refused; there is no overwrite). + existing name is refused; there is no overwrite). Optional `extras` (custom properties become node `extras`), `yUp`, `applyModifiers` (each true by default, must be a boolean) and `selection` (a non-empty list of object names; 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). Not checked: texture - files a `.gltf` export writes beside it (only the `.bin` is), and a link or swap made between the - check and the write (the same residual as renderStill). + 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 `.gltf` + with its `.bin` and 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`: `targetObjectName` (a camera object); optional `lens` (mm), `cameraType` (`PERSP`, `ORTHO`, `PANO`), `panoramaType` (for example @@ -223,10 +226,12 @@ gets a `failed` receipt whose message names the rule): 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 engines `BLENDER_WORKBENCH`, `BLENDER_EEVEE` and `BLENDER_EEVEE_NEXT` are refused - with a `failed` receipt when `libEGL.so.1` cannot be loaded (probed once and cached for the life of the process), because - rendering would abort the whole process with no receipt; `CYCLES` renders on the - CPU. The check applies to the scene's engine when `engine` is omitted. No such - check runs on Windows or macOS. + with a `failed` receipt 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; + `CYCLES` renders on the CPU. The check applies to the scene's engine when `engine` is 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 `/look/.png` and puts the absolute path in the receipt's @@ -254,7 +259,9 @@ gets a `failed` receipt whose message names the rule): 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. +`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 diff --git a/surfaces/blender/tests/live/export_gltf.py b/surfaces/blender/tests/live/export_gltf.py new file mode 100644 index 0000000..ff9e0bc --- /dev/null +++ b/surfaces/blender/tests/live/export_gltf.py @@ -0,0 +1,102 @@ +"""Live proof of exportGltf on real bpy: the option names exist on the real exporter, extras reach the +file, selection filters, .gltf writes its .bin and textures without overwriting, a refused or failed +export leaves nothing behind. + + BROKKR_ADDON= \ + blender -b --factory-startup --python export_gltf.py -- result.json + +Exit status is non-zero if any check fails. +""" +import bpy, sys, os, json, types, tempfile +from pathlib import Path + +ADDON = Path(os.environ["BROKKR_ADDON"]).resolve() +pkg = types.ModuleType("brokkr_bridge"); pkg.__path__ = [str(ADDON)] +sys.modules["brokkr_bridge"] = pkg +from brokkr_bridge import blender_target as bt + +out = sys.argv[sys.argv.index("--") + 1] if "--" in sys.argv else "export_gltf_result.json" +R = {"blender": bpy.app.version_string, "checks": []} + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + print("CHECK", "ok " if ok else "FAIL", name, detail if not ok else "", flush=True) + + +# Every exporter keyword the add-on passes must be a property of the real operator. +props = {p.identifier for p in bpy.ops.export_scene.gltf.get_rna_type().properties} +passed = {"filepath", "export_format", "use_selection", "export_extras", "export_yup", "export_apply"} +check("exporter has every option the add-on passes", passed <= props, sorted(passed - props)) +work = Path(tempfile.mkdtemp(prefix="brokkr-export-live-")) +bpy.ops.wm.read_factory_settings(use_empty=True) +t = bt.BrokkrBlenderTarget(bpy) +t.configure_action_dirs("", str(work)) +bpy.ops.mesh.primitive_cube_add(); cube = bpy.context.active_object; cube.name = "Cube"; cube["brokkr_tag"] = "hello" +bpy.ops.mesh.primitive_uv_sphere_add(location=(3, 0, 0)); sphere = bpy.context.active_object; sphere.name = "Sphere" +image = bpy.data.images.new("brokkr_tex", 4, 4) +scratch = Path(tempfile.mkdtemp(prefix="brokkr-export-src-")) +image.filepath_raw = str(scratch / "brokkr_tex_src.png"); image.file_format = "PNG"; image.save() +mat = bpy.data.materials.new("Textured"); mat.use_nodes = True +node = mat.node_tree.nodes.new("ShaderNodeTexImage"); node.image = image +mat.node_tree.links.new(node.outputs["Color"], mat.node_tree.nodes["Principled BSDF"].inputs["Base Color"]) +cube.data.materials.append(mat) +N = [0] + + +def act(**cmd): + N[0] += 1; cmd.setdefault("commandId", "c%d" % N[0]); cmd["action"] = "exportGltf" + return t.run_intent(bpy.context, dict(cmd, requestedBy="test/driver")) + + +def listing(): + return sorted(str(p.relative_to(work)).replace("\\", "/") for p in work.rglob("*")) + + +r = act(filepath="all.glb") +check("glb accepted", r["status"] == "accepted", r["message"]) +check("glb written, no staging folder", listing() == ["all.glb"], listing()) +glb = (work / "all.glb").read_bytes() +check("glb carries extras", b"brokkr_tag" in glb and b"hello" in glb) +r = act(filepath="noextras.glb", extras=False) +check("extras=false leaves them out", b"brokkr_tag" not in (work / "noextras.glb").read_bytes(), r["message"]) +cube.select_set(True); sphere.select_set(False) +r = act(filepath="only.glb", selection=["Sphere"]) +data = (work / "only.glb").read_bytes() +check("selection exports only the sphere", b"Sphere" in data and b"Cube" not in data, r["message"]) +check("selection restored", cube.select_get() and not sphere.select_get(), (cube.select_get(), sphere.select_get())) + +r = act(filepath="sep/s.gltf") +check("gltf accepted", r["status"] == "accepted", r["message"]) +files = listing() +check("gltf writes its bin and the texture beside it", "sep/s.gltf" in files and "sep/s.bin" in files and any(f.startswith("sep/brokkr_tex") for f in files), files) +before = {f: (work / f).read_bytes() for f in listing() if (work / f).is_file()} +texture = next(f for f in files if f.startswith("sep/brokkr_tex")) +(work / texture).write_bytes(b"precious") +r = act(filepath="sep/s2.gltf") +check("a taken texture name refuses", r["status"] == "failed" and Path(texture).name in r["message"], r["message"]) +check("the taken texture is untouched", (work / texture).read_bytes() == b"precious") +check("the refused export leaves nothing", not any(f.startswith("sep/s2") for f in listing()) and not any(".brokkr-export" in f for f in listing()), listing()) + +r = act(filepath="fresh/deep/x.glb", selection=["Nope"]) +check("refused selection makes no folder", r["status"] == "failed" and not (work / "fresh").exists(), r["message"]) +orig = bpy.ops.export_scene.gltf +bt_target = t +class Boom: + def __call__(self, *a, **k): + Path(k["filepath"]).write_bytes(b"partial"); raise RuntimeError("died midway") + def get_rna_type(self): return orig.get_rna_type() +import types as _t +t.bpy = _t.SimpleNamespace(**{k: getattr(bpy, k) for k in ("data", "app", "path", "context")}) +t.bpy.ops = _t.SimpleNamespace(export_scene=_t.SimpleNamespace(gltf=Boom()), import_scene=bpy.ops.import_scene, render=bpy.ops.render) +r = act(filepath="fresh/deep/x.glb") +check("a failing exporter is a failed receipt", r["status"] == "failed", r["message"]) +check("and leaves no partial file or new folder", not (work / "fresh").exists(), listing()) +t.bpy = bpy +r = act(filepath="fresh/deep/x.glb") +check("the same name then exports", r["status"] == "accepted" and (work / "fresh" / "deep" / "x.glb").is_file(), r["message"]) + +import shutil +shutil.rmtree(work, ignore_errors=True); shutil.rmtree(scratch, ignore_errors=True) +json.dump(R, open(out, "w"), indent=1) +sys.exit(0 if all(c["ok"] for c in R["checks"]) else 1) diff --git a/surfaces/blender/tests/live/export_gltf.result.json b/surfaces/blender/tests/live/export_gltf.result.json new file mode 100644 index 0000000..ff10cae --- /dev/null +++ b/surfaces/blender/tests/live/export_gltf.result.json @@ -0,0 +1,114 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "exporter has every option the add-on passes", + "ok": true, + "detail": [] + }, + { + "name": "glb accepted", + "ok": true, + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\all.glb (72752 bytes)." + }, + { + "name": "glb written, no staging folder", + "ok": true, + "detail": [ + "all.glb" + ] + }, + { + "name": "glb carries extras", + "ok": true, + "detail": null + }, + { + "name": "extras=false leaves them out", + "ok": true, + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\noextras.glb (72720 bytes)." + }, + { + "name": "selection exports only the sphere", + "ok": true, + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\only.glb (70240 bytes)." + }, + { + "name": "selection restored", + "ok": true, + "detail": [ + true, + false + ] + }, + { + "name": "gltf accepted", + "ok": true, + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\sep\\s.gltf (2840 bytes)." + }, + { + "name": "gltf writes its bin and the texture beside it", + "ok": true, + "detail": [ + "all.glb", + "noextras.glb", + "only.glb", + "sep", + "sep/brokkr_tex_src.png", + "sep/s.bin", + "sep/s.gltf" + ] + }, + { + "name": "a taken texture name refuses", + "ok": true, + "detail": "output path already exists; output actions never overwrite: brokkr_tex_src.png" + }, + { + "name": "the taken texture is untouched", + "ok": true, + "detail": null + }, + { + "name": "the refused export leaves nothing", + "ok": true, + "detail": [ + "all.glb", + "noextras.glb", + "only.glb", + "sep", + "sep/brokkr_tex_src.png", + "sep/s.bin", + "sep/s.gltf" + ] + }, + { + "name": "refused selection makes no folder", + "ok": true, + "detail": "Selection object was not found: Nope" + }, + { + "name": "a failing exporter is a failed receipt", + "ok": true, + "detail": "died midway" + }, + { + "name": "and leaves no partial file or new folder", + "ok": true, + "detail": [ + "all.glb", + "noextras.glb", + "only.glb", + "sep", + "sep/brokkr_tex_src.png", + "sep/s.bin", + "sep/s.gltf" + ] + }, + { + "name": "the same name then exports", + "ok": true, + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\fresh\\deep\\x.glb (72752 bytes)." + } + ] +} \ No newline at end of file diff --git a/surfaces/blender/tests/live/refusals.py b/surfaces/blender/tests/live/refusals.py new file mode 100644 index 0000000..3abd794 --- /dev/null +++ b/surfaces/blender/tests/live/refusals.py @@ -0,0 +1,74 @@ +"""Live proof of the renderStill GL refusal and the createObject meshType refusal on real bpy. + + BROKKR_ADDON= \ + blender -b --factory-startup --python refusals.py -- result.json + +The pass outcome runs a real child Blender (a one-pixel Workbench and EEVEE render) and then a real +renderStill. The abort outcome needs a host whose headless GL fails (a container with libEGL and no +GPU), which this script cannot make: it runs the real probe against a stand-in binary that aborts, and +on such a host the first two checks fail instead of passing. Exit status is non-zero if any check fails. +""" +import bpy, sys, os, json, types, tempfile, stat, shutil +from pathlib import Path + +ADDON = Path(os.environ["BROKKR_ADDON"]).resolve() +pkg = types.ModuleType("brokkr_bridge"); pkg.__path__ = [str(ADDON)] +sys.modules["brokkr_bridge"] = pkg +from brokkr_bridge import blender_target as bt + +out = sys.argv[sys.argv.index("--") + 1] if "--" in sys.argv else "refusals_result.json" +R = {"blender": bpy.app.version_string, "background": bpy.app.background, "platform": sys.platform, "checks": []} + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + print("CHECK", "ok " if ok else "FAIL", name, detail if not ok else "", flush=True) + + +work = Path(tempfile.mkdtemp(prefix="brokkr-refusals-live-")) +bpy.ops.wm.read_factory_settings(use_empty=True) +t = bt.BrokkrBlenderTarget(bpy) +t.configure_action_dirs("", str(work)) +N = [0] + + +def act(action, **cmd): + N[0] += 1; cmd.setdefault("commandId", "c%d" % N[0]); cmd["action"] = action + return t.run_intent(bpy.context, dict(cmd, requestedBy="test/driver")) + + +for engine in ("BLENDER_WORKBENCH", "BLENDER_EEVEE_NEXT", "BLENDER_EEVEE"): + try: # the engine enum is dynamic: ask by assignment + bpy.context.scene.render.engine = engine + except TypeError: + continue + if True: + failure = bt.gl_render_failure(bpy.app.binary_path, engine) + check("real one-pixel %s render survives in a child Blender" % engine, failure is None, failure) + +bpy.ops.object.camera_add(); bpy.context.scene.camera = bpy.context.active_object +r = act("renderStill", outputPath="shot.png", engine="BLENDER_WORKBENCH", resolutionX=8, resolutionY=8) +check("renderStill Workbench headless renders after the probe", r["status"] == "accepted" and (work / "shot.png").is_file(), r["message"]) + +stand_in = work / ("abort.cmd" if os.name == "nt" else "abort.sh") +stand_in.write_text("@echo off\r\nexit /b 3\r\n" if os.name == "nt" else "#!/bin/sh\nkill -ABRT $$\n") +stand_in.chmod(stand_in.stat().st_mode | stat.S_IEXEC) +failure = bt.gl_render_failure(str(stand_in), "BLENDER_WORKBENCH") +check("a child that aborts is a refusal reason", failure is not None and "exited with status" in failure, failure) +t.bpy = types.SimpleNamespace(data=bpy.data, path=bpy.path, context=bpy.context, ops=bpy.ops, + app=types.SimpleNamespace(background=True, binary_path=str(stand_in))) +bpy.context.scene.render.engine = "BLENDER_WORKBENCH" +r = act("renderStill", outputPath="no.png", engine="BLENDER_WORKBENCH") +check("renderStill refuses and renders nothing", r["status"] == "failed" and "cannot render" in r["message"] and not (work / "no.png").exists(), r["message"]) +t.bpy = bpy + +for kind in ("LIGHT", "EMPTY", "CAMERA"): + r = act("createObject", objectType=kind, meshType="CYLINDER") + check("meshType on %s is refused" % kind, r["status"] == "failed" and "MESH" in r["message"], r["message"]) +check("and nothing was created for them", len([o for o in bpy.data.objects if o.type in ("LIGHT", "EMPTY")]) == 0) +r = act("createObject", objectType="MESH", meshType="cube") +check("meshType CUBE on a MESH still works", r["status"] == "accepted", r["message"]) + +shutil.rmtree(work, ignore_errors=True) +json.dump(R, open(out, "w"), indent=1) +sys.exit(0 if all(c["ok"] for c in R["checks"]) else 1) diff --git a/surfaces/blender/tests/live/refusals.result.json b/surfaces/blender/tests/live/refusals.result.json new file mode 100644 index 0000000..0047130 --- /dev/null +++ b/surfaces/blender/tests/live/refusals.result.json @@ -0,0 +1,57 @@ +{ + "blender": "5.3.0", + "background": true, + "platform": "win32", + "checks": [ + { + "name": "real one-pixel BLENDER_WORKBENCH render survives in a child Blender", + "ok": true, + "detail": null + }, + { + "name": "real one-pixel BLENDER_EEVEE render survives in a child Blender", + "ok": true, + "detail": null + }, + { + "name": "renderStill Workbench headless renders after the probe", + "ok": true, + "detail": "Rendered still to shot.png." + }, + { + "name": "a child that aborts is a refusal reason", + "ok": true, + "detail": "a one-pixel test render exited with status 3" + }, + { + "name": "renderStill refuses and renders nothing", + "ok": true, + "detail": "engine BLENDER_WORKBENCH cannot render in this headless Blender (a one-pixel test render exited with status 3); rendering would abort the process; use engine CYCLES." + }, + { + "name": "meshType on LIGHT is refused", + "ok": true, + "detail": "meshType applies only to objectType MESH, not LIGHT." + }, + { + "name": "meshType on EMPTY is refused", + "ok": true, + "detail": "meshType applies only to objectType MESH, not EMPTY." + }, + { + "name": "meshType on CAMERA is refused", + "ok": true, + "detail": "meshType applies only to objectType MESH, not CAMERA." + }, + { + "name": "and nothing was created for them", + "ok": true, + "detail": null + }, + { + "name": "meshType CUBE on a MESH still works", + "ok": true, + "detail": "Blender object created." + } + ] +} \ No newline at end of file diff --git a/surfaces/blender/tests/test_scene_actions.py b/surfaces/blender/tests/test_scene_actions.py index fcc2b64..a36df4a 100644 --- a/surfaces/blender/tests/test_scene_actions.py +++ b/surfaces/blender/tests/test_scene_actions.py @@ -108,6 +108,8 @@ class FakeBpy: self.exported = [] self.export_result = {"FINISHED"} self.export_writes = True + self.export_siblings = [] # extra files the exporter writes beside the target (textures) + self.export_raises_after_writing = None for o in self.data.objects.values(): o.selected = o is self.mesh o.select_get = (lambda o=o: o.selected) @@ -143,8 +145,15 @@ class FakeBpy: assert (mode, undo) == ("EXEC_DEFAULT", False) kwargs["selected_at_call"] = sorted(o.name for o in self.data.objects.values() if o.selected) self.exported.append(kwargs) + target = Path(kwargs["filepath"]) if self.export_writes: - Path(kwargs["filepath"]).write_bytes(b"x" * 10) + target.write_bytes(b"x" * 10) + if target.suffix == ".gltf": + target.with_suffix(".bin").write_bytes(b"b" * 4) + for name in self.export_siblings: + (target.parent / name).write_bytes(b"t" * 3) + if self.export_raises_after_writing: + raise RuntimeError(self.export_raises_after_writing) return self.export_result def render_still(self, mode, undo, write_still): @@ -267,8 +276,11 @@ class ActionTests(unittest.TestCase): self.assertIn(path, receipt["message"]) self.assertIn("10 bytes", receipt["message"]) call = self.bpy.exported[0] - self.assertEqual({k: v for k, v in call.items() if k != "selected_at_call"}, - {"filepath": path, "export_format": "GLB", "export_extras": True, + staged = Path(call["filepath"]) # the exporter writes into a staging folder, then Brokkr moves the file + self.assertEqual((staged.name, staged.parent.parent, staged.parent.name.startswith(".brokkr-export-")), + ("a.glb", self.root / "out" / "ship", True)) + self.assertEqual({k: v for k, v in call.items() if k not in ("selected_at_call", "filepath")}, + {"export_format": "GLB", "export_extras": True, "export_yup": True, "export_apply": True, "use_selection": False}) def test_export_gltf_suffix_is_separate_and_options_pass_through(self): @@ -343,13 +355,155 @@ class ActionTests(unittest.TestCase): self.assertEqual(sorted(p.name for p in (self.root / "out").iterdir()), ["taken.glb"]) self.assertIn("already exists", self.run_action(action="exportGltf", filepath="taken.glb")["message"]) - def test_export_gltf_refuses_an_existing_bin_sibling(self): + def test_export_gltf_writes_its_bin_and_textures_beside_it_and_nothing_else(self): + self.bpy.export_siblings = ["tex.png"] + receipt = self.run_action(action="exportGltf", filepath="sub/a.gltf") + self.assertEqual(receipt["status"], "accepted", receipt) + self.assertEqual(sorted(p.name for p in (self.root / "out" / "sub").iterdir()), ["a.bin", "a.gltf", "tex.png"]) + self.assertEqual(sorted(p.name for p in (self.root / "out").iterdir()), ["sub"]) # no staging folder left + + def test_export_gltf_refuses_an_existing_bin_sibling_and_keeps_it(self): (self.root / "out" / "a.bin").write_bytes(b"old") - self.assertEqual(self.run_action(action="exportGltf", filepath="a.gltf")["status"], "failed") - self.assertEqual(self.bpy.exported, []) + receipt = self.run_action(action="exportGltf", filepath="a.gltf") + self.assertEqual(receipt["status"], "failed") + self.assertIn("a.bin", receipt["message"]) + self.assertEqual((self.root / "out" / "a.bin").read_bytes(), b"old") + self.assertEqual(sorted(p.name for p in (self.root / "out").iterdir()), ["a.bin"]) + + def test_export_gltf_never_overwrites_a_texture_the_exporter_writes(self): + (self.root / "out" / "tex.png").write_bytes(b"old") + self.bpy.export_siblings = ["tex.png"] + receipt = self.run_action(action="exportGltf", filepath="a.gltf") + self.assertEqual(receipt["status"], "failed") + self.assertIn("tex.png", receipt["message"]) + self.assertEqual((self.root / "out" / "tex.png").read_bytes(), b"old") + self.assertEqual(sorted(p.name for p in (self.root / "out").iterdir()), ["tex.png"]) # no a.gltf, no a.bin + + def test_a_failed_export_leaves_no_file_no_folder_and_the_name_can_be_retried(self): + self.bpy.export_raises_after_writing = "exporter died midway" + receipt = self.run_action(action="exportGltf", filepath="new/deep/a.glb") + self.assertEqual(receipt["status"], "failed") + self.assertEqual(list((self.root / "out").iterdir()), []) + self.bpy.export_raises_after_writing = None + retry = self.run_action(action="exportGltf", filepath="new/deep/a.glb") + self.assertEqual(retry["status"], "accepted", retry) + self.assertTrue((self.root / "out" / "new" / "deep" / "a.glb").is_file()) + + def test_a_move_that_fails_partway_rolls_back_so_the_target_is_untouched_and_retry_works(self): + self.bpy.export_siblings = ["tex1.png", "tex2.png"] + real_rename = os.rename + calls = [] + + def fail_on_third(src, dst): + calls.append(dst) + if len(calls) == 3: + raise OSError("disk full") + return real_rename(src, dst) + + with mock.patch.object(bt.os, "rename", fail_on_third): + receipt = self.run_action(action="exportGltf", filepath="sub/a.gltf") + self.assertEqual(receipt["status"], "failed") + self.assertGreaterEqual(len(calls), 3) + self.assertEqual(list((self.root / "out").iterdir()), []) # nothing moved stays; no staging, no new folder + retry = self.run_action(action="exportGltf", filepath="sub/a.gltf") + self.assertEqual(retry["status"], "accepted", retry) + self.assertEqual(sorted(p.name for p in (self.root / "out" / "sub").iterdir()), + ["a.bin", "a.gltf", "tex1.png", "tex2.png"]) + + HOLD_STAGE = ( + "import sys\n" + "sys.path.insert(0, sys.argv[1])\n" + "import types\n" + "pkg = types.ModuleType('brokkr_bridge'); pkg.__path__ = [sys.argv[1] + '/brokkr_bridge']\n" + "sys.modules['brokkr_bridge'] = pkg\n" + "from brokkr_bridge import blender_target as bt\n" + "from pathlib import Path\n" + "stage, fd = bt._open_stage(Path(sys.argv[2]))\n" + "print(stage, flush=True)\n" + "sys.stdin.read()\n") + + def start_export_holding_a_stage(self): + import subprocess + child = subprocess.Popen([sys.executable, "-c", self.HOLD_STAGE, str(ADDON.parent), str(self.root / "out")], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) + self.addCleanup(child.kill) + self.addCleanup(child.wait) + self.addCleanup(child.stdout.close) + self.addCleanup(child.stdin.close) + return child, Path(child.stdout.readline().strip()) + + def test_a_sweep_spares_another_processs_live_stage_and_removes_a_killed_ones(self): + child, stage = self.start_export_holding_a_stage() + (stage / "a.glb").write_bytes(b"in flight") + os.utime(stage, (0, 0)) # old by any clock: only the lock decides + bt._sweep_stale_stages(self.root / "out") + self.assertTrue((stage / "a.glb").exists()) + self.assertEqual(self.run_action(action="exportGltf", filepath="b.glb")["status"], "accepted") + self.assertTrue((stage / "a.glb").exists()) # an export in this process swept too + child.kill() + child.wait() + bt._sweep_stale_stages(self.root / "out") + self.assertFalse(stage.exists()) + + def test_a_sweep_leaves_a_folder_whose_lock_is_not_made_yet(self): + early = self.root / "out" / ".brokkr-export-early" + early.mkdir() + bt._sweep_stale_stages(self.root / "out") + self.assertTrue(early.exists()) + + def test_a_failed_rollback_is_refused_loudly_naming_the_files_and_the_next_export_recovers(self): + self.bpy.export_siblings = ["tex1.png"] + real_rename = os.rename + calls = [] + + def fail_forever_from_third(src, dst): + calls.append(dst) + if len(calls) >= 3: + raise OSError("disk gone") + return real_rename(src, dst) + + with mock.patch.object(bt.os, "rename", fail_forever_from_third): + receipt = self.run_action(action="exportGltf", filepath="sub/a.gltf") + self.assertEqual(receipt["status"], "failed") + self.assertIn("could not be rolled back", receipt["message"]) + self.assertIn("sub/a.bin", receipt["message"]) + self.assertIn("sub/a.gltf", receipt["message"]) + self.assertTrue((self.root / "out" / "sub" / "a.bin").exists()) + retry = self.run_action(action="exportGltf", filepath="sub/a.gltf") + self.assertEqual(retry["status"], "accepted", retry) + self.assertEqual(sorted(p.name for p in (self.root / "out").rglob("*") if p.is_file()), + ["a.bin", "a.gltf", "tex1.png"]) + self.assertEqual([p.name for p in (self.root / "out").iterdir()], ["sub"]) # no stage left + + def test_a_failed_texture_subfolder_move_leaves_no_empty_folder(self): + self.bpy.export_siblings = [] + real_rename = os.rename + + def fail_the_texture(src, dst): + if "textures" in str(dst): + raise OSError("no") + return real_rename(src, dst) + + orig = self.bpy.export_gltf + + def with_subfolder(mode, undo, **kw): + result = orig(mode, undo, **kw) + target = Path(kw["filepath"]) + (target.parent / "textures").mkdir() + (target.parent / "textures" / "t.png").write_bytes(b"t") + return result + + self.bpy.ops.export_scene.gltf = with_subfolder + with mock.patch.object(bt.os, "rename", fail_the_texture): + receipt = self.run_action(action="exportGltf", filepath="a.gltf") + self.assertEqual(receipt["status"], "failed") + self.assertEqual(list((self.root / "out").iterdir()), []) def test_export_refuses_a_symlinked_folder(self): - os.symlink(self.root, self.root / "out" / "link") + try: + os.symlink(self.root, self.root / "out" / "link") + except OSError: + self.skipTest("the OS denies symlink creation to this user") self.assertEqual(self.run_action(action="exportGltf", filepath="link/a.glb")["status"], "failed") self.assertEqual(self.bpy.exported, []) @@ -427,29 +581,36 @@ class ActionTests(unittest.TestCase): self.assertIn("CUBE", receipt["message"]) self.assertEqual(self.bpy.created, []) - # renderStill: GPU engines without a GL runtime - def test_render_still_refuses_gpu_engines_headless_when_the_gl_library_is_missing(self): + def test_mesh_type_on_a_non_mesh_object_is_refused_not_ignored(self): + for object_type in ("LIGHT", "EMPTY", "CAMERA"): + receipt = self.run_action(action="createObject", objectType=object_type, meshType="CYLINDER") + self.assertEqual(receipt["status"], "failed", object_type) + self.assertIn("MESH", receipt["message"]) + self.assertEqual(self.bpy.created, []) + + # renderStill: GPU engines that would abort a headless Blender + def test_render_still_refuses_gpu_engines_headless_when_a_test_render_fails(self): self.bpy.app.background = True for engine in ("BLENDER_WORKBENCH", "BLENDER_EEVEE", "BLENDER_EEVEE_NEXT", "blender_workbench"): self.bpy.scene.render.ENGINES = FakeRender.ENGINES + ("BLENDER_EEVEE_NEXT",) - with mock.patch.object(bt, "missing_gl_library", return_value="libEGL.so.1"): + with mock.patch.object(bt, "gl_render_failure", return_value="a one-pixel test render exited with status 134"): receipt = self.run_action(action="renderStill", outputPath="a.png", engine=engine) self.assertEqual(receipt["status"], "failed", engine) - self.assertIn("libEGL.so.1", receipt["message"]) + self.assertIn("one-pixel test render", receipt["message"]) self.assertIn("CYCLES", receipt["message"]) self.assertEqual(self.bpy.rendered, []) self.assertEqual(self.bpy.scene.render.engine, "BLENDER_EEVEE") def test_render_still_refuses_the_scene_engine_too_and_leaves_no_folder(self): self.bpy.app.background = True # scene engine is BLENDER_EEVEE - with mock.patch.object(bt, "missing_gl_library", return_value="libEGL.so.1"): + with mock.patch.object(bt, "gl_render_failure", return_value="a one-pixel test render exited with status 134"): receipt = self.run_action(action="renderStill", outputPath="shots/a.png") self.assertEqual(receipt["status"], "failed") self.assertFalse((self.root / "out" / "shots").exists()) - def test_render_still_gl_check_spares_cycles_foreground_and_a_present_library(self): - probe = mock.Mock(return_value="libEGL.so.1") - with mock.patch.object(bt, "missing_gl_library", probe): + def test_render_still_gl_check_spares_cycles_foreground_and_a_working_test_render(self): + probe = mock.Mock(return_value="a one-pixel test render exited with status 134") + with mock.patch.object(bt, "gl_render_failure", probe): self.bpy.app.background = True self.assertEqual(self.run_action(action="renderStill", outputPath="a.png", engine="CYCLES")["status"], "accepted") probe.assert_not_called() @@ -460,20 +621,94 @@ class ActionTests(unittest.TestCase): probe.return_value = None self.assertEqual(self.run_action(action="renderStill", outputPath="c.png", engine="BLENDER_WORKBENCH")["status"], "accepted") - def test_missing_gl_library_probes_only_on_linux_and_only_once(self): - bt.missing_gl_library.cache_clear() - with mock.patch.object(bt.sys, "platform", "win32"), mock.patch.object(bt.ctypes, "CDLL", side_effect=OSError) as cdll: - self.assertIsNone(bt.missing_gl_library()) - cdll.assert_not_called() - bt.missing_gl_library.cache_clear() - with mock.patch.object(bt.sys, "platform", "linux"), mock.patch.object(bt.ctypes, "CDLL", side_effect=OSError) as cdll: - self.assertEqual(bt.missing_gl_library(), "libEGL.so.1") - self.assertEqual(bt.missing_gl_library(), "libEGL.so.1") - cdll.assert_called_once_with("libEGL.so.1") - bt.missing_gl_library.cache_clear() - with mock.patch.object(bt.sys, "platform", "linux"), mock.patch.object(bt.ctypes, "CDLL"): - self.assertIsNone(bt.missing_gl_library()) - bt.missing_gl_library.cache_clear() + def fake_blender(self, status, marker=True): + """A stand-in Blender binary: a script that ignores its arguments, prints the probe's completion + marker (or not) and exits with status.""" + if os.name == "nt": + path = self.root / "fake_blender.cmd" + path.write_text("@echo off\r\n" + ("echo BROKKR_GL_PROBE_OK\r\n" if marker else "") + f"exit /b {status}\r\n") + else: + path = self.root / "fake_blender.sh" + path.write_text("#!/bin/sh\n" + ("echo BROKKR_GL_PROBE_OK\n" if marker else "") + f"exit {status}\n") + path.chmod(0o755) + return str(path) + + def test_gl_probe_passes_when_the_test_render_finishes_and_says_so(self): + bt.gl_render_failure.cache_clear() + self.addCleanup(bt.gl_render_failure.cache_clear) + self.assertIsNone(bt.gl_render_failure(self.fake_blender(0), "BLENDER_EEVEE")) + + def test_gl_probe_fails_on_an_abort_a_missing_marker_a_hang_and_an_unknown_binary(self): + bt.gl_render_failure.cache_clear() + self.addCleanup(bt.gl_render_failure.cache_clear) + self.assertIn("status 3", bt.gl_render_failure(self.fake_blender(3), "BLENDER_EEVEE")) + self.assertIn("status 0", bt.gl_render_failure(self.fake_blender(0, marker=False), "BLENDER_WORKBENCH")) + with mock.patch.object(bt, "GL_PROBE_TIMEOUT_SECONDS", 0.001): + self.assertIn("did not finish", bt.gl_render_failure(self.fake_blender(0), "BLENDER_EEVEE_NEXT")) + self.assertIn("unknown", bt.gl_render_failure("", "BLENDER_EEVEE")) + self.assertIn("unknown", bt.gl_render_failure(str(self.root / "missing"), "BLENDER_EEVEE")) + + def slow_blender(self): + """A stand-in that starts a child which holds the output pipe for 30 s.""" + if os.name == "nt": + path = self.root / "slow_blender.cmd" + path.write_text("@echo off\r\nping -n 30 127.0.0.1 >nul\r\n") + else: + path = self.root / "slow_blender.sh" + path.write_text("#!/bin/sh\nsleep 30\necho BROKKR_GL_PROBE_OK\n") + path.chmod(0o755) + return path + + def test_gl_probe_timeout_returns_on_time_killing_the_childs_children_and_is_not_cached(self): + import time + bt.gl_render_failure.cache_clear() + self.addCleanup(bt.gl_render_failure.cache_clear) + slow = self.slow_blender() + with mock.patch.object(bt, "GL_PROBE_TIMEOUT_SECONDS", 1): + started = time.monotonic() + failure = bt.gl_render_failure(str(slow), "BLENDER_EEVEE") + took = time.monotonic() - started + self.assertIn("did not finish", failure) + self.assertLess(took, 10) + # the same binary and engine, now fast: a timeout was not remembered + slow.unlink() + fast = self.fake_blender(0) + os.replace(fast, str(slow.with_suffix(Path(fast).suffix))) + self.assertIsNone(bt.gl_render_failure(str(slow.with_suffix(Path(fast).suffix)), "BLENDER_EEVEE")) + + def test_gl_probe_caches_a_definite_abort_and_forgets_an_unstartable_binary(self): + bt.gl_render_failure.cache_clear() + self.addCleanup(bt.gl_render_failure.cache_clear) + binary = self.fake_blender(3) + self.assertIn("status 3", bt.gl_render_failure(binary, "BLENDER_EEVEE")) + self.fake_blender(0) # same path, now a working binary: the abort is still the answer + self.assertIn("status 3", bt.gl_render_failure(binary, "BLENDER_EEVEE")) + with mock.patch.object(bt.subprocess, "Popen", side_effect=OSError("denied")): + self.assertIn("could not start", bt.gl_render_failure(binary, "BLENDER_WORKBENCH")) + self.assertIsNone(bt.gl_render_failure(binary, "BLENDER_WORKBENCH")) + + def test_gl_probe_runs_once_per_binary_and_engine(self): + bt.gl_render_failure.cache_clear() + self.addCleanup(bt.gl_render_failure.cache_clear) + binary = self.fake_blender(0) + with mock.patch.object(bt.subprocess, "Popen", wraps=bt.subprocess.Popen) as run: + bt.gl_render_failure(binary, "BLENDER_EEVEE") + bt.gl_render_failure(binary, "BLENDER_EEVEE") + bt.gl_render_failure(binary, "BLENDER_WORKBENCH") + self.assertEqual(run.call_count, 2) + + def test_render_still_end_to_end_with_a_binary_that_aborts_and_one_that_renders(self): + bt.gl_render_failure.cache_clear() + self.addCleanup(bt.gl_render_failure.cache_clear) + self.bpy.app.background = True + self.bpy.app.binary_path = self.fake_blender(134) + refused = self.run_action(action="renderStill", outputPath="a.png") + self.assertEqual(refused["status"], "failed") + self.assertIn("status 134", refused["message"]) + self.assertEqual(self.bpy.rendered, []) + bt.gl_render_failure.cache_clear() + self.bpy.app.binary_path = self.fake_blender(0) + self.assertEqual(self.run_action(action="renderStill", outputPath="a.png")["status"], "accepted") # importGltf: names def test_import_refuses_drive_unc_extended_stream_and_device_names(self): From 00b38e8e09e79abb9f7b0db3de1459fef6a82186 Mon Sep 17 00:00:00 2001 From: Eureka Date: Sat, 28 Nov 2026 01:31:36 +0000 Subject: [PATCH 34/63] Brokkr C#: snapshot lists as whole values; C# pin to CultLib 9fc4bdda; snapshots reach disk again (#18) --- Directory.Build.props | 4 +- Directory.Build.targets | 4 +- brokkr-command/Program.cs | 8 ++- .../BrokkrHostSnapshotTests.cs | 60 +++++++++++++++++++ brokkr-contracts.Tests/EditorProbe.cs | 4 +- .../Editor/BrokkrCultMeshMirror.cs | 15 ++--- .../Editor/BrokkrUnitySnapshotBuilder.cs | 17 +++--- .../Runtime/BrokkrHostSnapshot.cs | 25 ++++++-- 8 files changed, 110 insertions(+), 27 deletions(-) create mode 100644 brokkr-contracts.Tests/BrokkrHostSnapshotTests.cs diff --git a/Directory.Build.props b/Directory.Build.props index c8a3c67..0b65fe5 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -2,8 +2,8 @@ $(CULTLIB_ROOT) $(MSBuildThisFileDirectory)..\CultLib - - 42dce3611a81adc5c5fac54cadbaa5637d6022d3 + + 9fc4bdda6a8620f846b58e89ddf476f4676d3e89 C:\Program Files\Git\cmd\git.exe git diff --git a/Directory.Build.targets b/Directory.Build.targets index 46d436a..624e78a 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -1,6 +1,6 @@ + worktree of that revision: git worktree add , detached (in CultLib). --> @@ -17,7 +17,7 @@ + Text="CultLib must be revision $(CultLibRevision); found $([System.String]::Copy($(ActualCultLibRevision)).Trim()). Set CultLibRoot to a clean worktree of that revision." /> - cache.TryGet(new CultRecordKey("unity/host/current"), out BrokkrHostSnapshot? host) ? host : null; + private static BrokkrHostSnapshot? ReadHostSnapshot(CultCache cache) + { + if (!cache.TryGet(new CultRecordKey("unity/host/current"), out BrokkrHostSnapshot? host)) return null; + host.RefuseDefaultLists(); + return host; + } private static Dictionary Parse(string[] args) { diff --git a/brokkr-contracts.Tests/BrokkrHostSnapshotTests.cs b/brokkr-contracts.Tests/BrokkrHostSnapshotTests.cs new file mode 100644 index 0000000..4a7fc06 --- /dev/null +++ b/brokkr-contracts.Tests/BrokkrHostSnapshotTests.cs @@ -0,0 +1,60 @@ +using System.Collections.Immutable; +using GameCult.Brokkr; +using MessagePack; + +namespace Brokkr.Contracts.Tests; + +public sealed class BrokkrHostSnapshotTests +{ + // Captured before the lists became ImmutableArray holders: the record payload must not change. + private const string PayloadHex = + "DC0013D92567616D6563756C742E62726F6B6B722E746F6F6C5F686F73745F736E617073686F742E7630B362726F6B6B722E756E6974795F656469746F72AC756E6974792D656469746F72A170A174A0A0A000900090919EA16FA0A0A0C2A00000A09195A163A0A0C29195A178A0A0A131C2A0A0A0909196A161A0A0C2C2A0C2C2C2C2C2"; + + private static BrokkrHostSnapshot Populated() => new() + { + projectPath = "p", + observedAt = "t", + sceneObjects = ImmutableArray.Create(new BrokkrGameObjectSnapshot + { + objectId = "o", + components = ImmutableArray.Create(new BrokkrComponentSnapshot + { + componentId = "c", + properties = ImmutableArray.Create(new BrokkrSerializedPropertySnapshot { path = "x", value = "1" }) + }) + }), + assets = ImmutableArray.Create(new BrokkrAssetSnapshot { path = "a" }) + }; + + [Fact] + public void ListsAreWholeValuesWithTheSameBytesAsArrays() => + Assert.Equal(PayloadHex, Convert.ToHexString(MessagePackSerializer.Serialize(Populated()))); + + [Fact] + public void PopulatedSnapshotIsAccepted() => Populated().RefuseDefaultLists(); + + [Theory] + [InlineData(12)] + [InlineData(13)] + public void NilListsDecodeToDefaultAndAreRefused(int key) + { + var fields = MessagePackSerializer.Deserialize(MessagePackSerializer.Serialize(Populated())); + fields[key] = null; + var snapshot = MessagePackSerializer.Deserialize(MessagePackSerializer.Serialize(fields)); + + var error = Assert.Throws(snapshot.RefuseDefaultLists); + Assert.Contains("default", error.Message); + } + + [Fact] + public void DefaultNestedListsAreRefused() + { + var snapshot = Populated(); + snapshot.sceneObjects[0].components = default; + Assert.Throws(snapshot.RefuseDefaultLists); + + snapshot = Populated(); + snapshot.sceneObjects[0].components[0].properties = default; + Assert.Throws(snapshot.RefuseDefaultLists); + } +} diff --git a/brokkr-contracts.Tests/EditorProbe.cs b/brokkr-contracts.Tests/EditorProbe.cs index 1445697..45fb41e 100644 --- a/brokkr-contracts.Tests/EditorProbe.cs +++ b/brokkr-contracts.Tests/EditorProbe.cs @@ -9,7 +9,7 @@ namespace Brokkr.Contracts.Tests; // The scenario harness: an editor without Unity. It opens the store exactly as BrokkrCultMeshMirror does (a CultMesh // node with StartServer=false over a directory store, no shard log) and runs one service tick in the // service order: pull, drain pending intents through BrokkrCommandDrain (the same class the service uses), host -// snapshot, soft flush. "Executing" an intent only records it, so the scenarios measure delivery and once-only +// snapshot, flush. "Executing" an intent only records it, so the scenarios measure delivery and once-only // execution, not Unity. It is also a thin IBrokkrCommandStore in front of the real BrokkrCommandStore, with knobs to // make writes fail and to land a writer between the enable's pull and its commit. internal sealed class EditorProbe : IDisposable, IBrokkrCommandStore @@ -132,7 +132,7 @@ internal sealed class EditorProbe : IDisposable, IBrokkrCommandStore projectPath = "probe", agentCommandsEnabled = AgentCommandsEnabled }); - await node.FlushAsync(soft: true); + await node.FlushAsync(); return handled; } diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrCultMeshMirror.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrCultMeshMirror.cs index fccfe07..1c46ed7 100644 --- a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrCultMeshMirror.cs +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrCultMeshMirror.cs @@ -77,8 +77,9 @@ namespace GameCult.Brokkr.Editor internal async Task PublishSnapshotAsync(BrokkrHostSnapshot snapshot) { RequireRunning(); + snapshot.RefuseDefaultLists(); await node.Database.PutAsync(new CultRecordKey("unity/host/current"), snapshot); - await node.FlushAsync(soft: true); + await node.FlushAsync(); } // Command ids are single-use: a caller with no id gets a fresh one, and reusing an answered id is a defect. @@ -91,42 +92,42 @@ namespace GameCult.Brokkr.Editor } await node.Database.PutAsync(BrokkrCommandLedger.CommandKey(command.commandId), command); - await node.FlushAsync(soft: true); + await node.FlushAsync(); } internal async Task PublishQuestRouteAsync(BrokkrQuestRoute route) { RequireRunning(); await node.Database.PutAsync(new CultRecordKey($"unity/quest-routes/{route.id}"), route); - await node.FlushAsync(soft: true); + await node.FlushAsync(); } internal async Task PublishSyncSessionAsync(BrokkrSyncSession session) { RequireRunning(); await node.Database.PutAsync(new CultRecordKey($"sync/sessions/{session.sessionId}"), session); - await node.FlushAsync(soft: true); + await node.FlushAsync(); } internal async Task PublishSyncObjectBindingAsync(BrokkrSyncObjectBinding binding) { RequireRunning(); await node.Database.PutAsync(new CultRecordKey($"sync/bindings/objects/{binding.bindingId}"), binding); - await node.FlushAsync(soft: true); + await node.FlushAsync(); } internal async Task PublishSyncVarAsync(BrokkrSyncVar syncVar) { RequireRunning(); await node.Database.PutAsync(new CultRecordKey($"sync/vars/{syncVar.syncVarId}"), syncVar); - await node.FlushAsync(soft: true); + await node.FlushAsync(); } internal async Task PublishTimelineBindingAsync(BrokkrSyncTimelineBinding binding) { RequireRunning(); await node.Database.PutAsync(new CultRecordKey($"sync/bindings/timelines/{binding.bindingId}"), binding); - await node.FlushAsync(soft: true); + await node.FlushAsync(); } internal bool TryDequeueSyncReceipt(out BrokkrSyncReceipt receipt) diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnitySnapshotBuilder.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnitySnapshotBuilder.cs index 45ae610..3536a50 100644 --- a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnitySnapshotBuilder.cs +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnitySnapshotBuilder.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.Globalization; using System.Linq; using System.Reflection; @@ -55,7 +56,7 @@ namespace GameCult.Brokkr.Editor }; } - private static BrokkrGameObjectSnapshot[] CaptureSceneObjects() + private static ImmutableArray CaptureSceneObjects() { var objects = new List(); @@ -73,7 +74,7 @@ namespace GameCult.Brokkr.Editor } } - return objects.ToArray(); + return objects.ToImmutableArray(); } private static void CaptureGameObject( @@ -109,7 +110,7 @@ namespace GameCult.Brokkr.Editor } } - private static BrokkrComponentSnapshot[] CaptureComponents(GameObject gameObject) + private static ImmutableArray CaptureComponents(GameObject gameObject) { return gameObject.GetComponents() .Where(component => component != null) @@ -121,7 +122,7 @@ namespace GameCult.Brokkr.Editor enabled = ReadEnabled(component), properties = CaptureProperties(component) }) - .ToArray(); + .ToImmutableArray(); } private static string[] CaptureMaterialNames(GameObject gameObject) @@ -135,7 +136,7 @@ namespace GameCult.Brokkr.Editor .ToArray(); } - private static BrokkrSerializedPropertySnapshot[] CaptureProperties(UnityEngine.Object target) + private static ImmutableArray CaptureProperties(UnityEngine.Object target) { var properties = new List(); using var serializedObject = new SerializedObject(target); @@ -165,10 +166,10 @@ namespace GameCult.Brokkr.Editor } } - return properties.ToArray(); + return properties.ToImmutableArray(); } - private static BrokkrAssetSnapshot[] CaptureAssets() + private static ImmutableArray CaptureAssets() { return AssetDatabase.GetAllAssetPaths() .Where(path => path.StartsWith("Assets/", StringComparison.Ordinal)) @@ -185,7 +186,7 @@ namespace GameCult.Brokkr.Editor name = System.IO.Path.GetFileNameWithoutExtension(path) }; }) - .ToArray(); + .ToImmutableArray(); } internal static string GetObjectId(UnityEngine.Object target) diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrHostSnapshot.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrHostSnapshot.cs index a33b9d2..f30466e 100644 --- a/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrHostSnapshot.cs +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrHostSnapshot.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Immutable; using GameCult.Caching; using MessagePack; @@ -21,14 +22,30 @@ namespace GameCult.Brokkr [Key(9)] public string[] selectedObjectNames = Array.Empty(); [Key(10)] public int assetCount; [Key(11)] public string[] capabilities = Array.Empty(); - [Key(12)] public BrokkrGameObjectSnapshot[] sceneObjects = Array.Empty(); - [Key(13)] public BrokkrAssetSnapshot[] assets = Array.Empty(); + [Key(12)] public ImmutableArray sceneObjects = ImmutableArray.Empty; + [Key(13)] public ImmutableArray assets = ImmutableArray.Empty; [Key(14)] public bool isPlaying; [Key(15)] public bool isPaused; [Key(16)] public bool isCompiling; [Key(17)] public bool isUpdating; // False means the editor executes no agent commands: the operator has not enabled the sink. [Key(18)] public bool agentCommandsEnabled; + + // The snapshot lists are whole values (ImmutableArray, no element ids): a store row from a writer that left + // one nil decodes to a default array, which this refuses instead of letting a reader throw later. + public void RefuseDefaultLists() + { + if (sceneObjects.IsDefault) throw new InvalidOperationException("Brokkr host snapshot sceneObjects is default, not a list."); + if (assets.IsDefault) throw new InvalidOperationException("Brokkr host snapshot assets is default, not a list."); + foreach (var sceneObject in sceneObjects) + { + if (sceneObject.components.IsDefault) + throw new InvalidOperationException($"Brokkr host snapshot object '{sceneObject.path}' components is default, not a list."); + foreach (var component in sceneObject.components) + if (component.properties.IsDefault) + throw new InvalidOperationException($"Brokkr host snapshot component '{component.typeName}' properties is default, not a list."); + } + } } // Written by the editor, into the store, when the operator enables the command sink. The token is also kept in @@ -73,7 +90,7 @@ namespace GameCult.Brokkr [Key(6)] public int layer; [Key(7)] public int childCount; [Key(8)] public string parentId = ""; - [Key(9)] public BrokkrComponentSnapshot[] components = Array.Empty(); + [Key(9)] public ImmutableArray components = ImmutableArray.Empty; [Key(10)] public string localPosition = ""; [Key(11)] public string localEulerAngles = ""; [Key(12)] public string localScale = ""; @@ -88,7 +105,7 @@ namespace GameCult.Brokkr [Key(1)] public string typeName = ""; [Key(2)] public string assemblyQualifiedName = ""; [Key(3)] public bool enabled; - [Key(4)] public BrokkrSerializedPropertySnapshot[] properties = Array.Empty(); + [Key(4)] public ImmutableArray properties = ImmutableArray.Empty; } [MessagePackObject] From 7c6092bc0a13a71d7586d3e14b3a5eea8a09bf53 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 02:47:07 +0100 Subject: [PATCH 35/63] Blender add-on: one action table (actions.json) decides every intent's fields and undo class run_intent admits through action_table.validate: unknown field, wrong type, enum miss, bound miss, missing required field are 'denied' (admission: nothing ran, no undo step). The entry's changesScene and editModeSafe replace READ_ACTIONS, MUTATING_ACTIONS, NO_SCENE_CHANGE_ACTIONS and EDIT_MODE_SAFE_ACTIONS; the handler is '_' + the action's name, so _dispatch's if-chain, the scene field helpers (number, integer, choice, color), node_actions' text/tree_key/check_idname and the cross-aliases (objectName on scene actions, targetObjectName on node actions, parentName) are gone. New bounds only where nothing was checked: createObject size, lightType/emptyDisplayType enums, resolution minimum 4 (Blender clamps 1..3 silently), the probed panoramaType items, node label 63. Handlers keep scene-dependent refusals (ActionRefused, 'failed'). Parity fixture surfaces/blender/tests/action_cases.json is for brokkr-ctl's validator, which follows. Co-Authored-By: Claude Sonnet 5.5 --- .../blender/brokkr_bridge/action_table.py | 213 +++++++++++++++ surfaces/blender/brokkr_bridge/actions.json | 144 ++++++++++ .../blender/brokkr_bridge/blender_target.py | 250 ++++++------------ .../blender/brokkr_bridge/node_actions.py | 135 +++------- .../blender/brokkr_bridge/scene_actions.py | 79 +----- surfaces/blender/tests/action_cases.json | 233 ++++++++++++++++ .../blender/tests/live/agent_turn_queue.py | 2 +- .../blender/tests/live/agent_turn_undo.py | 4 +- surfaces/blender/tests/test_action_table.py | 181 +++++++++++++ surfaces/blender/tests/test_agent_turn.py | 15 +- .../blender/tests/test_material_actions.py | 4 +- surfaces/blender/tests/test_node_actions.py | 3 +- surfaces/blender/tests/test_perception.py | 2 +- surfaces/blender/tests/test_scene_actions.py | 76 +++--- 14 files changed, 955 insertions(+), 386 deletions(-) create mode 100644 surfaces/blender/brokkr_bridge/action_table.py create mode 100644 surfaces/blender/brokkr_bridge/actions.json create mode 100644 surfaces/blender/tests/action_cases.json create mode 100644 surfaces/blender/tests/test_action_table.py diff --git a/surfaces/blender/brokkr_bridge/action_table.py b/surfaces/blender/brokkr_bridge/action_table.py new file mode 100644 index 0000000..dafbe9e --- /dev/null +++ b/surfaces/blender/brokkr_bridge/action_table.py @@ -0,0 +1,213 @@ +"""The action table: which Blender intents exist, what fields each may carry, and each action's undo class. + +actions.json (schema brokkr.blender.actions.v0) is the one owner. run_intent admits every intent through +validate(); brokkr-ctl embeds the same file for `send --help` and early refusal, with the same rules and +message text (surfaces/blender/tests/action_cases.json pins the two). Stdlib only, no bpy. + +Vocabulary: null means absent; a required field absent is refused; a field neither declared nor in the +envelope is refused; enums match exactly; number and integer are never bool and always within the declared +minimum and maximum, integer is whole; string may declare minLength, maxLength, chars (a named charset), +prefixes (starts with one and has at least one more character) and forbid (substrings); array declares +items, minItems, maxItems; object with properties is closed and recursive, without is a free map; any is +any non-null value; only {field, in} refuses a field present unless the sibling's value is in the list; +defaults fill absent top-level fields after validation. Scene-dependent rules stay in the handlers. +""" +from __future__ import annotations + +import functools +import json +import math +from pathlib import Path +from typing import Any + +TABLE_PATH = Path(__file__).with_name("actions.json") +SCHEMA = "brokkr.blender.actions.v0" +TYPES = ("string", "number", "integer", "boolean", "array", "object", "any") +TYPE_WORDS = {"string": "a string", "number": "a finite number", "integer": "a whole number", + "boolean": "true or false", "array": "an array", "object": "an object"} + + +class IntentInvalid(ValueError): + """The intent breaks a rule of the table; the message names the field path and the rule.""" + + +class TableInvalid(ValueError): + """actions.json itself is malformed.""" + + +def number_text(value: float) -> str: + """A bound as it is printed in messages: whole values without a fraction, others as the shortest digits.""" + return str(int(value)) if value == int(value) else repr(float(value)) + + +def _list(items: list) -> str: + return ", ".join(items) + + +@functools.lru_cache(maxsize=1) +def _raw() -> dict[str, Any]: + return json.loads(TABLE_PATH.read_text(encoding="utf-8")) + + +@functools.lru_cache(maxsize=1) +def table() -> dict[str, Any]: + """actions.json, loaded and checked once.""" + document = _raw() + check_table(document) + return document + + +def entry(action: Any) -> dict[str, Any] | None: + """The table row for an action name, or None.""" + return _by_name().get(action) if isinstance(action, str) else None + + +@functools.lru_cache(maxsize=1) +def _by_name() -> dict[str, dict[str, Any]]: + return {a["name"]: a for a in table()["actions"]} + + +def check_table(document: dict[str, Any]) -> None: + """Refuse a table with an unbounded number field, an 'only' naming a missing field, an unknown charset, + a default that breaks its own field's rules, or a bound that prints differently in Python and Rust.""" + if document.get("schema") != SCHEMA: + raise TableInvalid(f"table schema must be {SCHEMA}") + charsets = document.get("charsets", {}) + names = set() + for action in document["actions"]: + if action["name"] in names: + raise TableInvalid(f"action {action['name']} is listed twice") + names.add(action["name"]) + fields = {f["name"]: f for f in action["fields"]} + if len(fields) != len(action["fields"]): + raise TableInvalid(f"{action['name']} repeats a field") + for field in action["fields"]: + _check_spec(field, f"{action['name']}.{field['name']}", charsets, fields, top=True) + if "default" in field: + try: + _value(field, field["default"], field["name"]) + except IntentInvalid as error: + raise TableInvalid(f"{action['name']}.{field['name']} default: {error}") from None + + +def _check_spec(spec: dict[str, Any], where: str, charsets: dict, siblings: dict, top: bool) -> None: + kind = spec.get("type") + if kind not in TYPES: + raise TableInvalid(f"{where}: unknown type {kind!r}") + if kind in ("number", "integer"): + for bound in ("minimum", "maximum"): + value = spec.get(bound) + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise TableInvalid(f"{where}: a {kind} field declares {bound}") + if "e" in number_text(value): + raise TableInvalid(f"{where}: {bound} {value} does not print as plain digits") + if "chars" in spec and spec["chars"] not in charsets: + raise TableInvalid(f"{where}: charset {spec['chars']!r} is not defined") + if "only" in spec: + if not top or spec["only"]["field"] not in siblings: + raise TableInvalid(f"{where}: 'only' must name a field of the same action") + if "default" in spec and not top: + raise TableInvalid(f"{where}: only top-level fields have defaults") + if kind == "array": + _check_spec(spec["items"], where + "[]", charsets, siblings, top=False) + if kind == "object" and "properties" in spec: + inner = {p["name"]: p for p in spec["properties"]} + for prop in spec["properties"]: + _check_spec(prop, f"{where}.{prop['name']}", charsets, inner, top=False) + + +def validate(command: dict[str, Any]) -> dict[str, Any]: + """The normalized copy of an intent (nulls dropped, defaults filled), or IntentInvalid naming the rule.""" + action = command.get("action", "") + row = entry(action) + if row is None: + raise IntentInvalid(f"Unsupported Blender command action: {action}") + present = {k: v for k, v in command.items() if v is not None} + _fields(row["fields"], present, None, action, set(table()["envelope"])) + result = dict(present) + for field in row["fields"]: + if field["name"] not in result and "default" in field: + result[field["name"]] = field["default"] + return result + + +def _fields(specs: list[dict[str, Any]], values: dict[str, Any], parent: str | None, where: str, skip: set) -> None: + """The fields of an action (parent None) or of a closed object: unknown names first, sorted, then each + declared field in table order.""" + declared = [s["name"] for s in specs] + for key in sorted(k for k in values if k not in skip and k not in declared): + raise IntentInvalid(f"{where} has no field '{key}'; its fields: {_list(declared) or 'none'}.") + for spec in specs: + path = spec["name"] if parent is None else f"{parent}.{spec['name']}" + value = values.get(spec["name"]) + if value is None: + if spec.get("required"): + raise IntentInvalid(f"{path} is required.") + continue + only = spec.get("only") + if only is not None and values.get(only["field"]) not in only["in"]: + raise IntentInvalid(f"{path} applies only when {only['field']} is one of {_list(only['in'])}.") + _value(spec, value, path) + + +def _value(spec: dict[str, Any], value: Any, path: str) -> None: + kind = spec["type"] + if kind == "any": + return + if kind in ("number", "integer"): + _number(spec, value, path) + elif kind == "string": + if not isinstance(value, str): + raise IntentInvalid(f"{path} must be {TYPE_WORDS[kind]}.") + if "enum" in spec: + if value not in spec["enum"]: + raise IntentInvalid(f"{path} must be one of {_list(spec['enum'])}.") + else: + _string(spec, value, path) + elif kind == "boolean": + if not isinstance(value, bool): + raise IntentInvalid(f"{path} must be {TYPE_WORDS[kind]}.") + elif kind == "array": + if not isinstance(value, list): + raise IntentInvalid(f"{path} must be {TYPE_WORDS[kind]}.") + if "minItems" in spec and len(value) < spec["minItems"]: + raise IntentInvalid(f"{path} must have at least {spec['minItems']} items.") + if "maxItems" in spec and len(value) > spec["maxItems"]: + raise IntentInvalid(f"{path} must have at most {spec['maxItems']} items.") + for index, item in enumerate(value): + if item is None: + raise IntentInvalid(f"{path}[{index}] must be {TYPE_WORDS.get(spec['items']['type'], 'a value')}.") + _value(spec["items"], item, f"{path}[{index}]") + elif kind == "object": + if not isinstance(value, dict): + raise IntentInvalid(f"{path} must be {TYPE_WORDS[kind]}.") + if "properties" in spec: + _fields(spec["properties"], {k: v for k, v in value.items() if v is not None}, path, path, frozenset()) + + +def _string(spec: dict[str, Any], value: str, path: str) -> None: + if "minLength" in spec and len(value) < spec["minLength"]: + raise IntentInvalid(f"{path} must have at least {spec['minLength']} characters.") + if "maxLength" in spec and len(value) > spec["maxLength"]: + raise IntentInvalid(f"{path} must have at most {spec['maxLength']} characters.") + if "chars" in spec: + charset = _raw()["charsets"][spec["chars"]] + if any(c not in charset["allowed"] for c in value): + raise IntentInvalid(f"{path} may contain only {charset['text']}.") + if "prefixes" in spec and not any(value.startswith(p) and len(value) > len(p) for p in spec["prefixes"]): + raise IntentInvalid(f"{path} must start with one of {_list(spec['prefixes'])} and have at least one more character.") + for part in spec.get("forbid", ()): + if part in value: + raise IntentInvalid(f"{path} may not contain '{part}'.") + + +def _number(spec: dict[str, Any], value: Any, path: str) -> None: + kind = spec["type"] + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise IntentInvalid(f"{path} must be {TYPE_WORDS[kind]}.") + if isinstance(value, float) and not math.isfinite(value): + raise IntentInvalid(f"{path} must be {TYPE_WORDS[kind]}.") + if kind == "integer" and isinstance(value, float) and value != int(value): + raise IntentInvalid(f"{path} must be {TYPE_WORDS[kind]}.") + if not spec["minimum"] <= value <= spec["maximum"]: + raise IntentInvalid(f"{path} must be between {number_text(spec['minimum'])} and {number_text(spec['maximum'])}.") diff --git a/surfaces/blender/brokkr_bridge/actions.json b/surfaces/blender/brokkr_bridge/actions.json new file mode 100644 index 0000000..a605e01 --- /dev/null +++ b/surfaces/blender/brokkr_bridge/actions.json @@ -0,0 +1,144 @@ +{ + "schema": "brokkr.blender.actions.v0", + "envelope": ["schema", "commandId", "action", "requestedBy", "note"], + "charsets": { + "id": {"allowed": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-", "text": "letters, digits, '.', '_' or '-'"}, + "key": {"allowed": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ._-", "text": "letters, digits, space, '.', '_' or '-'"}, + "alnum": {"allowed": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "text": "letters and digits"} + }, + "actions": [ + {"name": "createObject", "doc": "Add an object at a location; a MESH is a cube.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "objectType", "type": "string", "enum": ["MESH", "LIGHT", "CAMERA", "EMPTY"], "default": "EMPTY"}, + {"name": "name", "type": "string"}, + {"name": "location", "type": "array", "items": {"type": "number", "minimum": -1000000000, "maximum": 1000000000}, "minItems": 3, "maxItems": 3, "doc": "[x,y,z]"}, + {"name": "size", "type": "number", "minimum": 0.001, "maximum": 1000000, "default": 1, "doc": "cube size, used by MESH"}, + {"name": "meshType", "type": "string", "enum": ["CUBE"], "only": {"field": "objectType", "in": ["MESH"]}}, + {"name": "lightType", "type": "string", "enum": ["POINT", "SUN", "SPOT", "AREA"], "default": "POINT", "only": {"field": "objectType", "in": ["LIGHT"]}}, + {"name": "emptyDisplayType", "type": "string", "enum": ["PLAIN_AXES", "ARROWS", "SINGLE_ARROW", "CIRCLE", "CUBE", "SPHERE", "CONE", "IMAGE"], "default": "PLAIN_AXES", "only": {"field": "objectType", "in": ["EMPTY"]}} + ]}, + {"name": "deleteObject", "doc": "Delete an object.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"} + ]}, + {"name": "setObjectTransform", "doc": "Set any of an object's location, rotation and scale.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "location", "type": "array", "items": {"type": "number", "minimum": -1000000000, "maximum": 1000000000}, "minItems": 3, "maxItems": 3, "doc": "[x,y,z]"}, + {"name": "rotationEuler", "type": "array", "items": {"type": "number", "minimum": -1000000000, "maximum": 1000000000}, "minItems": 3, "maxItems": 3, "doc": "[x,y,z] radians"}, + {"name": "scale", "type": "array", "items": {"type": "number", "minimum": -1000000000, "maximum": 1000000000}, "minItems": 3, "maxItems": 3, "doc": "[x,y,z]"} + ]}, + {"name": "setObjectVisibility", "doc": "Show or hide an object in the viewport and in renders.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "visible", "type": "boolean", "default": true} + ]}, + {"name": "setObjectParent", "doc": "Parent an object to another.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "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": "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"} + ]}, + {"name": "selectObject", "doc": "Select an object and make it active.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "clearSelection", "type": "boolean", "default": true} + ]}, + {"name": "assignMaterial", "doc": "Assign a material (created when new) to an object's slots.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "materialName", "type": "string", "default": "Brokkr Material"}, + {"name": "color", "type": "array", "items": {"type": "number", "minimum": 0, "maximum": 1}, "minItems": 3, "maxItems": 4, "doc": "[r,g,b] or [r,g,b,a], linear; alpha defaults to 1"} + ]}, + {"name": "importGltf", "doc": "Import a .gltf or .glb from the add-on's import directory.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "filepath", "type": "string", "required": true, "doc": "relative to the add-on's import directory"} + ]}, + {"name": "exportGltf", "doc": "Write the scene, or the named objects, as .glb or .gltf into the output directory.", "changesScene": false, "editModeSafe": false, "fields": [ + {"name": "filepath", "type": "string", "required": true, "doc": ".glb or .gltf relative to the add-on's output directory"}, + {"name": "extras", "type": "boolean", "default": true}, + {"name": "yUp", "type": "boolean", "default": true}, + {"name": "applyModifiers", "type": "boolean", "default": true}, + {"name": "selection", "type": "array", "items": {"type": "string", "minLength": 1}, "minItems": 1, "doc": "object names; the whole scene when absent"} + ]}, + {"name": "setCamera", "doc": "Change a camera's lens, projection and clipping.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "lens", "type": "number", "minimum": 1, "maximum": 5000, "doc": "mm"}, + {"name": "cameraType", "type": "string", "enum": ["PERSP", "ORTHO", "PANO"]}, + {"name": "orthoScale", "type": "number", "minimum": 0.001, "maximum": 100000}, + {"name": "clipStart", "type": "number", "minimum": 0.0001, "maximum": 1000000}, + {"name": "clipEnd", "type": "number", "minimum": 0.001, "maximum": 10000000}, + {"name": "panoramaType", "type": "string", "enum": ["EQUIRECTANGULAR", "EQUIANGULAR_CUBEMAP_FACE", "MIRRORBALL", "FISHEYE_EQUIDISTANT", "FISHEYE_EQUISOLID", "FISHEYE_LENS_POLYNOMIAL", "CENTRAL_CYLINDRICAL"]}, + {"name": "active", "type": "boolean", "doc": "true makes it the scene camera"} + ]}, + {"name": "setLight", "doc": "Change a light's energy, colour and type.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "energy", "type": "number", "minimum": 0, "maximum": 10000000}, + {"name": "color", "type": "array", "items": {"type": "number", "minimum": 0, "maximum": 1}, "minItems": 3, "maxItems": 3, "doc": "[r,g,b] linear"}, + {"name": "lightType", "type": "string", "enum": ["POINT", "SUN", "SPOT", "AREA"]} + ]}, + {"name": "setWorld", "doc": "Edit the world's Background node; a world is created when there is none.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "worldName", "type": "string", "doc": "default: the scene's world"}, + {"name": "color", "type": "array", "items": {"type": "number", "minimum": 0, "maximum": 1}, "minItems": 3, "maxItems": 3, "doc": "[r,g,b] linear"}, + {"name": "strength", "type": "number", "minimum": 0, "maximum": 1000000} + ]}, + {"name": "renderStill", "doc": "Render the scene to a still in the output directory; settings are restored afterwards.", "changesScene": false, "editModeSafe": true, "fields": [ + {"name": "outputPath", "type": "string", "required": true, "doc": ".png, .jpg or .exr relative to the add-on's output directory"}, + {"name": "engine", "type": "string", "minLength": 1, "doc": "a render engine identifier of the running Blender"}, + {"name": "resolutionX", "type": "integer", "minimum": 4, "maximum": 16384}, + {"name": "resolutionY", "type": "integer", "minimum": 4, "maximum": 16384}, + {"name": "cameraName", "type": "string"} + ]}, + {"name": "look", "doc": "Capture the 3D view she is looking at; the receipt carries lookPath.", "changesScene": false, "editModeSafe": true, "fields": [ + ]}, + {"name": "createNodeGroup", "doc": "Create a geometry node group with an interface.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "treeKind", "type": "string", "enum": ["geometry"], "default": "geometry"}, + {"name": "treeKey", "type": "string", "required": true, "chars": "key", "minLength": 1, "maxLength": 63, "doc": "the node group's name"}, + {"name": "interface", "type": "array", "required": true, "minItems": 1, "maxItems": 64, "items": {"type": "object", "properties": [{"name": "inOut", "type": "string", "required": true, "enum": ["INPUT", "OUTPUT"]}, {"name": "name", "type": "string", "required": true, "minLength": 1, "maxLength": 63}, {"name": "type", "type": "string", "required": true, "enum": ["Geometry", "Float", "Int", "Bool", "Vector"]}, {"name": "default", "type": "any", "doc": "a value of the socket's type"}]}, "doc": "sockets: {inOut, name, type, default?}"} + ]}, + {"name": "addNode", "doc": "Add a node to a geometry node group.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "treeKind", "type": "string", "enum": ["geometry"], "default": "geometry"}, + {"name": "treeKey", "type": "string", "required": true, "chars": "key", "minLength": 1, "maxLength": 63, "doc": "the node group's name"}, + {"name": "id", "type": "string", "chars": "id", "minLength": 1, "maxLength": 63, "required": true, "doc": "brokkr's key for the node"}, + {"name": "blIdname", "type": "string", "required": true, "chars": "alnum", "prefixes": ["GeometryNode", "FunctionNode", "ShaderNode"], "forbid": ["Import", "Export", "Script", "Bake", "Group", "Simulation", "Repeat", "Foreach", "Viewer", "TexImage", "TexEnvironment", "ImageTexture", "InputImage", "TexIES"], "doc": "Blender's node type; file, script, cache, group and image nodes are refused"}, + {"name": "location", "type": "array", "items": {"type": "number", "minimum": -1000000000, "maximum": 1000000000}, "minItems": 2, "maxItems": 2, "default": [0, 0], "doc": "[x,y]"}, + {"name": "label", "type": "string", "maxLength": 63}, + {"name": "properties", "type": "object", "doc": "enum, bool, int or float node settings"}, + {"name": "inputs", "type": "object", "doc": "unlinked input defaults"} + ]}, + {"name": "removeNode", "doc": "Remove a node and its links.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "treeKind", "type": "string", "enum": ["geometry"], "default": "geometry"}, + {"name": "treeKey", "type": "string", "required": true, "chars": "key", "minLength": 1, "maxLength": 63, "doc": "the node group's name"}, + {"name": "id", "type": "string", "chars": "id", "minLength": 1, "maxLength": 63, "required": true} + ]}, + {"name": "linkSockets", "doc": "Link one node's output socket to another's input.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "treeKind", "type": "string", "enum": ["geometry"], "default": "geometry"}, + {"name": "treeKey", "type": "string", "required": true, "chars": "key", "minLength": 1, "maxLength": 63, "doc": "the node group's name"}, + {"name": "fromNode", "type": "string", "chars": "id", "minLength": 1, "maxLength": 63, "required": true}, + {"name": "fromSocket", "type": "string", "required": true, "doc": "identifier or unique name"}, + {"name": "toNode", "type": "string", "chars": "id", "minLength": 1, "maxLength": 63, "required": true}, + {"name": "toSocket", "type": "string", "required": true, "doc": "identifier or unique name"} + ]}, + {"name": "unlinkSockets", "doc": "Remove the links into an input socket, or only the one from a named output.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "treeKind", "type": "string", "enum": ["geometry"], "default": "geometry"}, + {"name": "treeKey", "type": "string", "required": true, "chars": "key", "minLength": 1, "maxLength": 63, "doc": "the node group's name"}, + {"name": "toNode", "type": "string", "chars": "id", "minLength": 1, "maxLength": 63, "required": true}, + {"name": "toSocket", "type": "string", "required": true}, + {"name": "fromNode", "type": "string", "chars": "id", "minLength": 1, "maxLength": 63, "doc": "with fromSocket: remove only that link"}, + {"name": "fromSocket", "type": "string"} + ]}, + {"name": "addModifier", "doc": "Add or retarget a Geometry Nodes modifier on an object.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "objectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "modifierType", "type": "string", "enum": ["NODES"], "default": "NODES"}, + {"name": "treeKind", "type": "string", "enum": ["geometry"], "default": "geometry"}, + {"name": "treeKey", "type": "string", "required": true, "chars": "key", "minLength": 1, "maxLength": 63, "doc": "the node group's name"}, + {"name": "modifierName", "type": "string", "chars": "key", "minLength": 1, "maxLength": 63, "default": "Brokkr GeoNodes"} + ]}, + {"name": "removeModifier", "doc": "Remove a Geometry Nodes modifier from an object.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "objectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "modifierName", "type": "string", "minLength": 1, "maxLength": 255, "forbid": ["\u0000"], "default": "Brokkr GeoNodes"} + ]}, + {"name": "setModifierInput", "doc": "Set one exposed input of a Geometry Nodes modifier.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "objectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "modifierName", "type": "string", "default": "Brokkr GeoNodes"}, + {"name": "socket", "type": "string", "required": true, "doc": "identifier or unique interface name"}, + {"name": "value", "type": "any", "required": true, "doc": "Float, Int, Bool or Vector"} + ]} + ] +} diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 0bc72b3..fab5357 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -25,6 +25,7 @@ if os.name == "nt": else: import fcntl +from . import action_table as at from . import node_actions as na from . import scene_actions as sa from .server_guard import BindRefused, SessionGuard, check_bind, guarded_server_class, is_loopback_host, stop_pending @@ -49,8 +50,6 @@ SYNC_VAR_SCHEMA = "brokkr.sync.var.v0" SYNC_TIMELINE_BINDING_SCHEMA = "brokkr.sync.timeline_binding.v0" SYNC_RECEIPT_SCHEMA = "brokkr.sync.receipt.v0" -CREATABLE_OBJECT_TYPES = ("MESH", "LIGHT", "CAMERA", "EMPTY") - # Engines that draw through the GL stack. A headless Blender with no usable GL device aborts the whole # process inside bpy.ops.render.render for these (no receipt); CYCLES renders on the CPU. Whether it # will is found by rendering one pixel in a child Blender (gl_render_failure), not by guessing at libraries. @@ -60,20 +59,6 @@ EXPORT_STAGE_PREFIX = ".brokkr-export-" STAGE_LOCK = ".brokkr-lock" STAGE_JOURNAL = ".brokkr-journal" -# Actions that only read the scene and so push no undo step. -READ_ACTIONS = ("look",) -MUTATING_ACTIONS = ( - "createObject", "deleteObject", "setObjectTransform", "setObjectVisibility", "setObjectParent", - "setObjectCustomProperty", "selectObject", "assignMaterial", "importGltf", "exportGltf", - "setCamera", "setLight", "setWorld", "renderStill", -) -# Actions that change no scene state: they push no undo step (exportGltf restores its selection; -# renderStill restores its settings). -NO_SCENE_CHANGE_ACTIONS = ("exportGltf", "renderStill") -# While an object is in Edit Mode, undo steps are edit-mesh steps, so a scene write is not reverted by -# one undo, and some operators leave Edit Mode (brokkr-live:ruling:object-intents-refused-in-edit-mode). -# Anything that writes scene state or changes her mode is refused; renderStill and look do neither. -EDIT_MODE_SAFE_ACTIONS = ("renderStill", "look") LOOK_DIR = "look" # under the output directory: scratch captures named by command id (brush-tree:ruling:look-files-are-scratch) LOOK_KEPT = 20 # the newest captures that stay after each look EDIT_SELECTION_CAP = 4096 # indices listed per element kind and object; the total stays true beside the list @@ -636,29 +621,40 @@ class BrokkrBlenderTarget: } def run_intent(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: - """The one agent turn: admit, run with operator undo off, push one labelled undo step, receipt.""" + """The one agent turn: admit, run with operator undo off, push one labelled undo step, receipt. + + Admission order: commandId shape, id unused, requestedBy, then the action table (action known, fields + valid), then Edit Mode. While an object is in Edit Mode undo steps are edit-mesh steps, so a scene write + is not reverted by one undo and some operators leave Edit Mode + (brokkr-live:ruling:object-intents-refused-in-edit-mode); the table's editModeSafe actions write nothing + and change no mode. A refusal at admission is 'denied': nothing ran, no undo step.""" command_id = command.get("commandId") requested_by = command.get("requestedBy") action = command.get("action", "") denial = "" + row = None if not _valid_command_id(command_id): denial = "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'." elif command_id in self._receipted: denial = f"commandId {command_id!r} was already receipted; ids are single-use." elif not isinstance(requested_by, str) or not REQUESTED_BY_SHAPE.fullmatch(requested_by): denial = "Intent has no requestedBy of the form '/'." - elif action not in MUTATING_ACTIONS and action not in READ_ACTIONS and action not in na.NodeActions.ACTIONS: - denial = f"Unsupported Blender command action: {action}" - elif action not in EDIT_MODE_SAFE_ACTIONS and self._edit_mode_object() is not None: - denial = (f"Object {self._edit_mode_object()!r} is in Edit Mode: object-level intents are refused " - "until she leaves it; nothing was changed.") + else: + try: + command = at.validate(command) + row = at.entry(action) + except at.IntentInvalid as error: + denial = str(error) + if not denial and not row["editModeSafe"] and self._edit_mode_object() is not None: + denial = (f"Object {self._edit_mode_object()!r} is in Edit Mode: object-level intents are refused " + "until she leaves it; nothing was changed.") if denial: if _valid_command_id(command_id): self._receipted.add(command_id) return self._receipt(command, "denied", denial, "") label = f"Brokkr {requested_by}: {action} {command_id[-8:]}" # the tail: uuid v7 ids lead with a timestamp, one value per minute - push = action not in READ_ACTIONS and action not in NO_SCENE_CHANGE_ACTIONS + push = row["changesScene"] self.agent_turn = True self._wrote = True try: @@ -700,108 +696,70 @@ class BrokkrBlenderTarget: self.bpy.ops.ed.undo_push(message=label) def _dispatch(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: - """The action table. Only run_intent calls it; it owns refusal, failure and the undo step.""" - action = command.get("action", "") - if action == "createObject": - return self._create_object(context, command) - if action == "deleteObject": - return self._delete_object(context, command) - if action == "setObjectTransform": - return self._set_object_transform(context, command) - if action == "setObjectVisibility": - return self._set_object_visibility(context, command) - if action == "setObjectParent": - return self._set_object_parent(context, command) - if action == "setObjectCustomProperty": - return self._set_object_custom_property(context, command) - if action == "selectObject": - return self._select_object(context, command) - if action == "assignMaterial": - return self._assign_material(context, command) - if action == "importGltf": - return self._import_gltf(context, command) - if action == "exportGltf": - return self._export_gltf(context, command) - if action == "setCamera": - return self._set_camera(context, command) - if action == "setLight": - return self._set_light(context, command) - if action == "setWorld": - return self._set_world(context, command) - if action == "renderStill": - return self._render_still(context, command) - if action == "look": - return self._look(context, command) - if action in na.NodeActions.ACTIONS: + """Only run_intent calls it, with an intent the table admitted: the handler is '_' + the action's name, + on NodeActions for the node actions and on this target for the rest. It owns refusal, failure and the undo step.""" + action = command["action"] + if hasattr(self.nodes, "_" + action): message, name = self.nodes.execute(action, command) self._wrote = self.nodes.changed return self._receipt(command, "accepted", message, name) - return self._receipt(command, "failed", f"Unsupported Blender command action: {action}", "") + return getattr(self, "_" + action)(context, command) - def _create_object(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: - object_type = command.get("objectType", "EMPTY") - if not isinstance(object_type, str) or object_type not in CREATABLE_OBJECT_TYPES: - shown = object_type if isinstance(object_type, str) else repr(object_type) - raise sa.ActionRefused( - f"objectType {shown!r} cannot be created; allowed: {', '.join(CREATABLE_OBJECT_TYPES)}.") - mesh_type = command.get("meshType") - if mesh_type is not None and object_type != "MESH": - raise sa.ActionRefused(f"meshType applies only to objectType MESH, not {object_type}.") - if mesh_type is not None and (not isinstance(mesh_type, str) or mesh_type.upper() != "CUBE"): - raise sa.ActionRefused(f"meshType {mesh_type!r} is not available; a MESH is a CUBE.") + def _createObject(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + object_type = command["objectType"] name = command.get("name") or f"Brokkr {object_type.title()}" - location = _vector(command.get("location"), 3, (0.0, 0.0, 0.0)) + location = tuple(command.get("location") or (0.0, 0.0, 0.0)) if object_type == "MESH": - self.bpy.ops.mesh.primitive_cube_add("EXEC_DEFAULT", False, size=float(command.get("size", 1.0)), location=location) + self.bpy.ops.mesh.primitive_cube_add("EXEC_DEFAULT", False, size=float(command["size"]), location=location) elif object_type == "LIGHT": - self.bpy.ops.object.light_add("EXEC_DEFAULT", False, type=command.get("lightType", "POINT"), location=location) + self.bpy.ops.object.light_add("EXEC_DEFAULT", False, type=command["lightType"], location=location) elif object_type == "CAMERA": self.bpy.ops.object.camera_add("EXEC_DEFAULT", False, location=location) else: # EMPTY - self.bpy.ops.object.empty_add("EXEC_DEFAULT", False, type=command.get("emptyDisplayType", "PLAIN_AXES"), location=location) + self.bpy.ops.object.empty_add("EXEC_DEFAULT", False, type=command["emptyDisplayType"], location=location) obj = context.object obj.name = name return self._receipt(command, "accepted", "Blender object created.", obj.name) - def _delete_object(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _deleteObject(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: obj = self._resolve_object(command) if obj is None: return self._receipt(command, "failed", "Target Blender object was not found.", "") self.bpy.data.objects.remove(obj, do_unlink=True) return self._receipt(command, "accepted", "Blender object deleted.", command.get("targetObjectName", "")) - def _set_object_transform(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _setObjectTransform(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: obj = self._resolve_object(command) if obj is None: return self._receipt(command, "failed", "Target Blender object was not found.", "") if "location" in command: - obj.location = _vector(command["location"], 3, obj.location) + obj.location = tuple(command["location"]) if "rotationEuler" in command: - obj.rotation_euler = _vector(command["rotationEuler"], 3, obj.rotation_euler) + obj.rotation_euler = tuple(command["rotationEuler"]) if "scale" in command: - obj.scale = _vector(command["scale"], 3, obj.scale) + obj.scale = tuple(command["scale"]) return self._receipt(command, "accepted", "Blender object transform updated.", obj.name) - def _set_object_visibility(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _setObjectVisibility(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: obj = self._resolve_object(command) if obj is None: return self._receipt(command, "failed", "Target Blender object was not found.", "") - visible = bool(command.get("visible", True)) + visible = command["visible"] obj.hide_viewport = not visible obj.hide_render = not visible return self._receipt(command, "accepted", "Blender object visibility updated.", obj.name) - def _set_object_parent(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _setObjectParent(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: obj = self._resolve_object(command) if obj is None: return self._receipt(command, "failed", "Target Blender object was not found.", "") - parent_name = command.get("parentObjectName") or command.get("parentName") or "" + parent_name = command.get("parentObjectName") or "" parent = self.bpy.data.objects.get(parent_name) if parent_name else None if parent_name and parent is None: return self._receipt(command, "failed", f"Parent Blender object was not found: {parent_name}", obj.name) @@ -809,42 +767,43 @@ class BrokkrBlenderTarget: obj.parent = parent return self._receipt(command, "accepted", "Blender object parent updated.", obj.name) - def _set_object_custom_property(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _setObjectCustomProperty(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: obj = self._resolve_object(command) if obj is None: return self._receipt(command, "failed", "Target Blender object was not found.", "") - property_name = command.get("propertyName") or "brokkrValue" + property_name = command["propertyName"] if property_name.startswith("customProperties."): property_name = property_name[len("customProperties."):] 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}; " "a custom property does not drive it, use setModifierInput.", obj.name) - obj[property_name] = command.get("value") + obj[property_name] = command["value"] return self._receipt(command, "accepted", "Blender custom property updated.", obj.name) - def _select_object(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _selectObject(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: obj = self._resolve_object(command) if obj is None: return self._receipt(command, "failed", "Target Blender object was not found.", "") - if command.get("clearSelection", True): + if command["clearSelection"]: for existing in context.selected_objects: existing.select_set(False) obj.select_set(True) context.view_layer.objects.active = obj return self._receipt(command, "accepted", "Blender object selected.", obj.name) - def _assign_material(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _assignMaterial(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: obj = self._resolve_object(command) if obj is None: return self._receipt(command, "failed", "Target Blender object was not found.", "") if not (obj.data and hasattr(obj.data, "materials")): return self._receipt(command, "failed", "Target object cannot receive materials.", obj.name) - rgba = sa.color_rgba(command) # refused before anything is created or changed - material_name = command.get("materialName") or "Brokkr Material" + color = command.get("color") + rgba = (*color, 1.0)[:4] if color is not None else None # the table admits [r,g,b] or [r,g,b,a] + material_name = command["materialName"] material = self.bpy.data.materials.get(material_name) or self.bpy.data.materials.new(material_name) if rgba is not None: if not material.use_nodes or material.node_tree is None: @@ -858,8 +817,8 @@ class BrokkrBlenderTarget: obj.data.materials.append(material) return self._receipt(command, "accepted", "Blender material assigned.", obj.name) - def _import_gltf(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: - name = str(command.get("filepath") or "") + def _importGltf(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + name = command["filepath"] path = sa.resolve_inside(self.import_dir, name, "import") sa.require_gltf(path) stamped = sa.fingerprint([path]) # before the parse, so a swap during it shows @@ -877,28 +836,19 @@ class BrokkrBlenderTarget: 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 "") - def _export_gltf(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + 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.""" - name = command.get("filepath") - if not isinstance(name, str): - raise sa.ActionRefused("filepath must be a string.") + name = command["filepath"] if self.output_dir: _sweep_stale_stages(Path(self.output_dir).resolve()) path = sa.resolve_inside(self.output_dir, name, "output", new_file=True) suffix = path.suffix.lower() if suffix not in sa.GLTF_EXTENSIONS: raise sa.ActionRefused(f"Export path must end in {' or '.join(sa.GLTF_EXTENSIONS)}.") - options = {} - for field, key in (("extras", "export_extras"), ("yUp", "export_yup"), ("applyModifiers", "export_apply")): - value = command.get(field, True) - if not isinstance(value, bool): - raise sa.ActionRefused(f"{field} must be true or false.") - options[key] = value + options = {"export_extras": command["extras"], "export_yup": command["yUp"], "export_apply": command["applyModifiers"]} names = command.get("selection") chosen = [] if names is not None: - if not isinstance(names, list) or not names or not all(isinstance(n, str) and n for n in names): - raise sa.ActionRefused("selection must be a non-empty list of object names.") missing = [n for n in names if n not in self.bpy.data.objects] if missing: raise sa.ActionRefused(f"Selection object was not found: {missing[0]}") @@ -1002,58 +952,40 @@ class BrokkrBlenderTarget: raise sa.ActionRefused(f"Target Blender object is not a {object_type}.") return obj - def _set_camera(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _setCamera(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: obj = self._resolve_typed(command, "CAMERA") camera = obj.data - # Validate everything before changing anything, so a refused intent leaves the camera alone. - lens = sa.number(command, "lens", 1.0, sa.MAX_LENS_MM) - camera_type = sa.choice(command, "cameraType", sa.CAMERA_TYPES) - ortho_scale = sa.number(command, "orthoScale", 0.001, 100000.0) - clip_start = sa.number(command, "clipStart", 0.0001, 1.0e6) - clip_end = sa.number(command, "clipEnd", 0.001, 1.0e7) - panorama_type = sa.choice(command, "panoramaType", self._panorama_types(camera)) - if lens is not None: - camera.lens = lens - if camera_type is not None: - camera.type = camera_type - if ortho_scale is not None: - camera.ortho_scale = ortho_scale - if clip_start is not None: - camera.clip_start = clip_start - if clip_end is not None: - camera.clip_end = clip_end - if panorama_type is not None: - # Blender 4.2 moved panorama_type from camera.cycles to the camera itself. - holder = camera if hasattr(camera, "panorama_type") else camera.cycles - holder.panorama_type = panorama_type + # Nothing below can be refused: the table checked every value, so a camera is never half set. + if "lens" in command: + camera.lens = command["lens"] + if "cameraType" in command: + camera.type = command["cameraType"] + if "orthoScale" in command: + camera.ortho_scale = command["orthoScale"] + if "clipStart" in command: + camera.clip_start = command["clipStart"] + if "clipEnd" in command: + camera.clip_end = command["clipEnd"] + if "panoramaType" in command: + camera.panorama_type = command["panoramaType"] # on the camera since Blender 4.2 if command.get("active"): context.scene.camera = obj return self._receipt(command, "accepted", "Blender camera updated.", obj.name) - def _panorama_types(self, camera: Any) -> tuple[str, ...]: - holder = camera if hasattr(camera, "panorama_type") else getattr(camera, "cycles", camera) - try: - return tuple(item.identifier for item in holder.bl_rna.properties["panorama_type"].enum_items) - except (KeyError, AttributeError): - return ("EQUIRECTANGULAR", "EQUIDISTANT", "FISHEYE_EQUISOLID", "MIRRORBALL") - - def _set_light(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _setLight(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: obj = self._resolve_typed(command, "LIGHT") - energy = sa.number(command, "energy", 0.0, 1.0e7) - light_color = sa.color(command) - light_type = sa.choice(command, "lightType", sa.LIGHT_TYPES) - if energy is not None: - obj.data.energy = energy - if light_color is not None: - obj.data.color = light_color - if light_type is not None: - obj.data.type = light_type + if "energy" in command: + obj.data.energy = command["energy"] + if "color" in command: + obj.data.color = tuple(command["color"]) + if "lightType" in command: + obj.data.type = command["lightType"] return self._receipt(command, "accepted", "Blender light updated.", obj.name) - def _set_world(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: - world_color = sa.color(command) - strength = sa.number(command, "strength", 0.0, 1.0e6) - name = str(command.get("worldName") or "") + def _setWorld(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + world_color = command.get("color") + strength = command.get("strength") + name = command.get("worldName") or "" scene = context.scene world = self.bpy.data.worlds.get(name) if name else scene.world if world is None: @@ -1069,22 +1001,19 @@ class BrokkrBlenderTarget: background.inputs["Strength"].default_value = strength return self._receipt(command, "accepted", "Blender world updated.", world.name) - def _render_still(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _renderStill(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: scene = context.scene render = scene.render - name = str(command.get("outputPath") or "") + name = command["outputPath"] path = sa.resolve_inside(self.output_dir, name, "output", new_file=True) file_format = sa.still_format(path) # The engine enum is dynamic (Cycles and add-on engines register at runtime), and RNA's # enum_items on a dynamic enum lists only its static defaults, so the running Blender is # asked by assignment below and a TypeError there is the refusal. - engine = command.get("engine") - if engine is not None and (not isinstance(engine, str) or not engine.strip()): - raise sa.ActionRefused("engine must be a render engine identifier.") - engine = engine.strip().upper() if engine else None - width = sa.integer(command, "resolutionX", 1, sa.MAX_RESOLUTION) - height = sa.integer(command, "resolutionY", 1, sa.MAX_RESOLUTION) - camera_name = str(command.get("cameraName") or "") + engine = command.get("engine") # an identifier, exactly as given: a name Blender does not have is a TypeError below + width = command.get("resolutionX") + height = command.get("resolutionY") + camera_name = command.get("cameraName") or "" camera = None if camera_name: camera = self.bpy.data.objects.get(camera_name) @@ -1301,7 +1230,7 @@ class BrokkrBlenderTarget: os.unlink(old) def _resolve_object(self, command: dict[str, Any]) -> Any: - name = command.get("targetObjectName") or command.get("objectName") + name = command.get("targetObjectName") return self.bpy.data.objects.get(name) if name else None def _scene_snapshot(self, scene: Any) -> dict[str, Any]: @@ -1742,15 +1671,6 @@ def _valid_command_id(value: Any) -> bool: return isinstance(value, str) and COMMAND_ID_SHAPE.fullmatch(value) is not None -def _vector(value: Any, size: int, fallback: Any) -> tuple[float, ...]: - if value is None: - return tuple(float(item) for item in fallback) - result = [float(item) for item in value[:size]] - while len(result) < size: - result.append(0.0) - return tuple(result) - - def _jsonable(value: Any) -> Any: if value is None or isinstance(value, (str, int, float, bool)): if isinstance(value, float) and not math.isfinite(value): diff --git a/surfaces/blender/brokkr_bridge/node_actions.py b/surfaces/blender/brokkr_bridge/node_actions.py index 389a536..3d856bc 100644 --- a/surfaces/blender/brokkr_bridge/node_actions.py +++ b/surfaces/blender/brokkr_bridge/node_actions.py @@ -1,33 +1,23 @@ """Geometry node graph command actions: createNodeGroup, addNode, linkSockets, addModifier, setModifierInput. Owner of how an intent becomes a node group, a node, a link or a modifier input on Blender 5.2. -Validation is plain Python and runs before bpy is touched; apply steps that can still fail after +Field shape is action_table's and arrives validated; apply steps that can still fail after Blender has been asked (an unknown node type, an enum that is not offered) undo what they made, so a refused intent leaves the tree as it was. Docs: docs/node-actions.md. The design is PR #3 (branch libby/blender-node-graphs-design). """ from __future__ import annotations import math -import re from typing import Any from .scene_actions import ActionRefused -ID_PATTERN = re.compile(r"[A-Za-z0-9._-]{1,63}") -KEY_PATTERN = re.compile(r"[A-Za-z0-9 ._-]{1,63}") -# A geometry tree may hold geometry, function and shader math nodes. Nodes that read or write files, -# run code, write caches, nest groups or sample images are not part of this cut. -NODE_IDNAME = re.compile(r"(GeometryNode|FunctionNode|ShaderNode)[A-Za-z0-9]+") -NODE_DENIED = ("Import", "Export", "Script", "Bake", "Group", "Simulation", "Repeat", "Foreach", "Viewer", "TexImage", "TexEnvironment", - "ImageTexture", "InputImage", "TexIES") MAX_NODES = 500 -MAX_INTERFACE = 64 MAX_MODIFIERS = 8 MAX_VALUE = 1.0e9 MAX_INT = 4096 # counts, levels and sizes multiply: a 4096 x 4096 grid is the ceiling SOCKET_TYPES = {"Geometry": "NodeSocketGeometry", "Float": "NodeSocketFloat", "Int": "NodeSocketInt", "Bool": "NodeSocketBool", "Vector": "NodeSocketVector"} -IN_OUT = {"INPUT", "OUTPUT"} # Node properties that are not node settings, or that make a node reach outside the tree. NODE_PROPERTY_DENIED = frozenset({"name", "label", "location", "width", "height", "parent", "node_tree", "select", "mute", "hide", "show_options", "show_preview", "show_texture", "use_custom_color", @@ -37,24 +27,6 @@ NODE_PROPERTY_DENIED = frozenset({"name", "label", "location", "width", "height" SETTABLE_PROPERTY_TYPES = ("ENUM", "BOOLEAN", "INT", "FLOAT") -def text(command: dict[str, Any], key: str, pattern: re.Pattern, label: str, *, required: bool = True) -> str: - value = command.get(key) - if value is None or value == "": - if required: - raise ActionRefused(f"{label} is required.") - return "" - if not isinstance(value, str) or not pattern.fullmatch(value): - raise ActionRefused(f"{label} must be 1..63 characters of letters, digits, space, '.', '_' or '-'.") - return value - - -def tree_key(command: dict[str, Any]) -> str: - kind = command.get("treeKind", "geometry") - if kind != "geometry": - raise ActionRefused(f"treeKind {kind!r} is not supported; only 'geometry'.") - return text(command, "treeKey", KEY_PATTERN, "treeKey") - - def finite(value: Any, label: str) -> float: if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or abs(value) > MAX_VALUE: raise ActionRefused(f"{label} must be a finite number within +-{MAX_VALUE:g}.") @@ -82,34 +54,19 @@ def typed_value(value: Any, kind: str, label: str) -> Any: raise ActionRefused(f"{label}: socket type {kind} cannot be set by an intent.") -def check_idname(idname: Any) -> str: - if not isinstance(idname, str) or not NODE_IDNAME.fullmatch(idname): - raise ActionRefused("blIdname must be a GeometryNode*, FunctionNode* or ShaderNode* type.") - for denied in NODE_DENIED: - if denied in idname: - raise ActionRefused(f"node type {idname} is not allowed in this cut ({denied}).") - return idname - - -def check_interface(items: Any) -> list[dict[str, str]]: - if not isinstance(items, list) or not items or len(items) > MAX_INTERFACE: - raise ActionRefused(f"interface must be a list of 1..{MAX_INTERFACE} sockets.") +def check_interface(items: list[dict[str, Any]]) -> list[dict[str, Any]]: + """The interface as the table admitted it, minus what only a typed read can judge: a repeated (inOut, name) + and a default that does not fit its socket type.""" seen: set[tuple[str, str]] = set() result = [] for i, item in enumerate(items): - if not isinstance(item, dict): - raise ActionRefused(f"interface[{i}] must be an object.") - in_out = str(item.get("inOut", "")).upper() - name = item.get("name") - socket_type = item.get("type") - if in_out not in IN_OUT or not isinstance(name, str) or not name or len(name) > 63 or socket_type not in SOCKET_TYPES: - raise ActionRefused(f"interface[{i}] needs inOut INPUT|OUTPUT, a name and a type of {sorted(SOCKET_TYPES)}.") - if (in_out, name) in seen: - raise ActionRefused(f"interface[{i}] repeats {in_out} socket {name!r}.") - seen.add((in_out, name)) - entry = {"inOut": in_out, "name": name, "type": socket_type} + key = (item["inOut"], item["name"]) + if key in seen: + raise ActionRefused(f"interface[{i}] repeats {key[0]} socket {key[1]!r}.") + seen.add(key) + entry = dict(item) if "default" in item: - entry["default"] = typed_value(item["default"], socket_type, f"interface[{i}].default") + entry["default"] = typed_value(item["default"], item["type"], f"interface[{i}].default") result.append(entry) return result @@ -117,8 +74,6 @@ def check_interface(items: Any) -> list[dict[str, str]]: class NodeActions: """Applies the node-graph actions to a bpy module. Stateless: every lookup goes to bpy.data.""" - ACTIONS = ("createNodeGroup", "addNode", "removeNode", "linkSockets", "unlinkSockets", "addModifier", "removeModifier", "setModifierInput") - def __init__(self, bpy_module: Any): self.bpy = bpy_module self.changed = False # whether the last execute wrote anything: an absent-target removal does not @@ -159,8 +114,8 @@ class NodeActions: # actions def _createNodeGroup(self, command: dict[str, Any]) -> tuple[str, str]: - key = tree_key(command) - interface = check_interface(command.get("interface")) + key = command["treeKey"] + interface = check_interface(command["interface"]) existing = self.bpy.data.node_groups.get(key) if existing is not None: raise ActionRefused(f"Node group {key!r} already exists.") @@ -181,17 +136,12 @@ class NodeActions: return "Created node group; interface identifiers: " + ", ".join(made), tree.name def _addNode(self, command: dict[str, Any]) -> tuple[str, str]: - tree = self._tree(tree_key(command)) - node_id = text(command, "id", ID_PATTERN, "id") - idname = check_idname(command.get("blIdname")) - location = command.get("location", [0, 0]) - if not isinstance(location, (list, tuple)) or len(location) != 2: - raise ActionRefused("location must be two numbers.") - location = [finite(part, "location") for part in location] - properties = command.get("properties") or {} - inputs = command.get("inputs") or {} - if not isinstance(properties, dict) or not isinstance(inputs, dict): - raise ActionRefused("properties and inputs must be objects.") + tree = self._tree(command["treeKey"]) + node_id = command["id"] + idname = command["blIdname"] + location = list(command["location"]) + properties = command.get("properties", {}) + inputs = command.get("inputs", {}) if any(n.get("brokkr_id") == node_id for n in tree.nodes): raise ActionRefused(f"Node id {node_id!r} already exists in {tree.name!r}.") if len(tree.nodes) >= MAX_NODES: @@ -204,7 +154,7 @@ class NodeActions: node["brokkr_id"] = node_id node.location = location if command.get("label"): - node.label = str(command["label"])[:63] + node.label = command["label"] for name, value in properties.items(): # node settings first: they decide which sockets exist self._set_property(node, name, value) for name, value in inputs.items(): @@ -232,8 +182,8 @@ class NodeActions: raise ActionRefused(f"property {name!r} cannot be {value!r}: {error}") from None def _removeNode(self, command: dict[str, Any]) -> tuple[str, str]: - tree = self._tree(tree_key(command)) - node_id = text(command, "id", ID_PATTERN, "id") + tree = self._tree(command["treeKey"]) + node_id = command["id"] if node_id in ("gin", "gout"): raise ActionRefused(f"{node_id!r} is the group's own input/output node and stays.") node = next((n for n in tree.nodes if n.get("brokkr_id") == node_id), None) @@ -244,13 +194,15 @@ class NodeActions: return "Node removed.", node_id def _unlinkSockets(self, command: dict[str, Any]) -> tuple[str, str]: - tree = self._tree(tree_key(command)) - target = self._node(tree, text(command, "toNode", ID_PATTERN, "toNode")) - into = self._socket(target.inputs, str(command.get("toSocket", "")), "toSocket") + tree = self._tree(command["treeKey"]) + target = self._node(tree, command["toNode"]) + into = self._socket(target.inputs, command["toSocket"], "toSocket") source = out = None - if command.get("fromNode") or command.get("fromSocket"): - source = self._node(tree, text(command, "fromNode", ID_PATTERN, "fromNode")) - out = self._socket(source.outputs, str(command.get("fromSocket", "")), "fromSocket") + if ("fromNode" in command) != ("fromSocket" in command): + raise ActionRefused("fromNode and fromSocket are given together or not at all.") + if "fromNode" in command: + source = self._node(tree, command["fromNode"]) + out = self._socket(source.outputs, command["fromSocket"], "fromSocket") doomed = [l for l in tree.links if l.to_socket == into and (out is None or l.from_socket == out)] for link in doomed: tree.links.remove(link) @@ -258,11 +210,11 @@ class NodeActions: return f"Removed {len(doomed)} link(s).", tree.name def _linkSockets(self, command: dict[str, Any]) -> tuple[str, str]: - tree = self._tree(tree_key(command)) - source = self._node(tree, text(command, "fromNode", ID_PATTERN, "fromNode")) - target = self._node(tree, text(command, "toNode", ID_PATTERN, "toNode")) - out = self._socket(source.outputs, str(command.get("fromSocket", "")), "fromSocket") - into = self._socket(target.inputs, str(command.get("toSocket", "")), "toSocket") + tree = self._tree(command["treeKey"]) + source = self._node(tree, command["fromNode"]) + target = self._node(tree, command["toNode"]) + out = self._socket(source.outputs, command["fromSocket"], "fromSocket") + into = self._socket(target.inputs, command["toSocket"], "toSocket") if reaches(tree, target, source): # includes a self link raise ActionRefused(f"Link {source.get('brokkr_id')} -> {target.get('brokkr_id')} would make a cycle.") displaced = [(l.from_socket, l.is_muted) for l in tree.links if l.to_socket == into] if not getattr(into, "is_multi_input", False) else [] @@ -275,7 +227,7 @@ class NodeActions: return f"Linked {source.get('brokkr_id')}.{out.identifier} -> {target.get('brokkr_id')}.{into.identifier}.", tree.name def _object(self, command: dict[str, Any]) -> Any: - name = command.get("objectName") or command.get("targetObjectName") + name = command["objectName"] obj = self.bpy.data.objects.get(name) if name else None if obj is None: raise ActionRefused(f"Object {name!r} was not found.") @@ -283,11 +235,8 @@ class NodeActions: def _addModifier(self, command: dict[str, Any]) -> tuple[str, str]: obj = self._object(command) - kind = command.get("modifierType", "NODES") - if kind != "NODES": - raise ActionRefused("modifierType must be NODES; other modifiers are not part of this cut.") - tree = self._tree(tree_key(command)) - name = text(command, "modifierName", KEY_PATTERN, "modifierName", required=False) or "Brokkr GeoNodes" + tree = self._tree(command["treeKey"]) + name = command["modifierName"] modifier = obj.modifiers.get(name) if modifier is not None and modifier.type != "NODES": raise ActionRefused(f"{obj.name!r} already has a non-Geometry-Nodes modifier named {name!r}.") @@ -304,9 +253,7 @@ class NodeActions: def _removeModifier(self, command: dict[str, Any]) -> tuple[str, str]: obj = self._object(command) # A lookup, not a creation: a modifier made by hand may have any name Blender allows. - name = command.get("modifierName") or "Brokkr GeoNodes" - if not isinstance(name, str) or len(name) > 255 or "\0" in name: - raise ActionRefused("modifierName must be a string of at most 255 characters.") + name = command["modifierName"] modifier = obj.modifiers.get(name) if modifier is None: self.changed = False @@ -319,11 +266,11 @@ class NodeActions: def _setModifierInput(self, command: dict[str, Any]) -> tuple[str, str]: obj = self._object(command) - modifier = obj.modifiers.get(str(command.get("modifierName") or "Brokkr GeoNodes")) + modifier = obj.modifiers.get(command["modifierName"]) if modifier is None or modifier.type != "NODES" or modifier.node_group is None: raise ActionRefused(f"{obj.name!r} has no Geometry Nodes modifier with a node group of that name.") - item = modifier_input(modifier.node_group, str(command.get("socket", ""))) - value = typed_value(command.get("value"), item.socket_type.replace("NodeSocket", ""), f"input {item.name!r}") + item = modifier_input(modifier.node_group, command["socket"]) + value = typed_value(command["value"], item.socket_type.replace("NodeSocket", ""), f"input {item.name!r}") # modifier.properties.inputs[id] is a raw IDPropertyGroup on 5.2.3; attribute access reaches the struct. getattr(modifier.properties.inputs, item.identifier).value = value obj.update_tag() # without it a headless re-evaluation returned the previous result diff --git a/surfaces/blender/brokkr_bridge/scene_actions.py b/surfaces/blender/brokkr_bridge/scene_actions.py index 98dcb40..c2a0b3c 100644 --- a/surfaces/blender/brokkr_bridge/scene_actions.py +++ b/surfaces/blender/brokkr_bridge/scene_actions.py @@ -1,13 +1,12 @@ -"""Validation for the Blender scene command actions. Stdlib only, no bpy. +"""Path and file safety for the Blender scene command actions. Stdlib only, no bpy. -Everything an intent can say is checked here before bpy is touched, so the rules -are testable without Blender. Failures raise ActionRefused; the target turns the -message into a failed receipt. +What an intent's fields may hold (names, types, enums, bounds) is action_table's. What a path or a glTF +may reach is checked here before bpy is touched, so the rules are testable without Blender. Failures raise +ActionRefused; the target turns the message into a failed receipt. """ from __future__ import annotations import json -import math import os import struct from pathlib import Path @@ -16,10 +15,6 @@ from urllib.parse import unquote GLTF_EXTENSIONS = (".gltf", ".glb") STILL_FORMATS = {".png": "PNG", ".jpg": "JPEG", ".jpeg": "JPEG", ".exr": "OPEN_EXR"} -CAMERA_TYPES = ("PERSP", "ORTHO", "PANO") -LIGHT_TYPES = ("POINT", "SUN", "SPOT", "AREA") -MAX_RESOLUTION = 16384 -MAX_LENS_MM = 5000.0 class ActionRefused(ValueError): @@ -166,72 +161,6 @@ def _glb_json_chunk(path: Path) -> bytes: return data -def number(command: dict[str, Any], key: str, low: float, high: float) -> float | None: - """A finite number in [low, high], or None when the key is absent.""" - if key not in command or command[key] is None: - return None - value = command[key] - if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): - raise ActionRefused(f"{key} must be a finite number.") - if not low <= value <= high: - raise ActionRefused(f"{key} must be between {low} and {high}.") - return float(value) - - -def integer(command: dict[str, Any], key: str, low: int, high: int) -> int | None: - value = number(command, key, low, high) - if value is None: - return None - if value != int(value): - raise ActionRefused(f"{key} must be a whole number.") - return int(value) - - -def unit_component(key: str, item: Any) -> float: - """One colour component: a number in [0, 1]. The range test comes first: it also refuses nan and inf, - and a huge int (10**400) never reaches math.isfinite, which would raise OverflowError instead of - naming the field.""" - if isinstance(item, bool) or not isinstance(item, (int, float)) or not 0.0 <= item <= 1.0: - raise ActionRefused(f"{key} components must be numbers between 0 and 1.") - return float(item) - - -def color(command: dict[str, Any], key: str = "color") -> tuple[float, float, float] | None: - """Linear RGB, three finite numbers in [0, 1], or None when absent.""" - if key not in command or command[key] is None: - return None - value = command[key] - if not isinstance(value, (list, tuple)) or len(value) != 3: - raise ActionRefused(f"{key} must be three numbers [r, g, b].") - parts = [] - for item in value: - parts.append(unit_component(key, item)) - return (parts[0], parts[1], parts[2]) - - -def color_rgba(command: dict[str, Any], key: str = "color") -> tuple[float, float, float, float] | None: - """Linear RGB or RGBA, finite numbers in [0, 1] (RGB gets alpha 1), or None when absent.""" - if key not in command or command[key] is None: - return None - value = command[key] - if not isinstance(value, (list, tuple)) or len(value) not in (3, 4): - raise ActionRefused(f"{key} must be [r, g, b] or [r, g, b, a].") - parts = [] - for item in value: - parts.append(unit_component(key, item)) - return (parts[0], parts[1], parts[2], parts[3] if len(parts) == 4 else 1.0) - - -def choice(command: dict[str, Any], key: str, allowed: Iterable[str]) -> str | None: - if key not in command or command[key] is None: - return None - allowed = tuple(allowed) - value = command[key] - if not isinstance(value, str) or value.upper() not in allowed: - raise ActionRefused(f"{key} must be one of {', '.join(allowed)}.") - return value.upper() - - def still_format(path: Path) -> str: try: return STILL_FORMATS[path.suffix.lower()] diff --git a/surfaces/blender/tests/action_cases.json b/surfaces/blender/tests/action_cases.json new file mode 100644 index 0000000..fb5a8e0 --- /dev/null +++ b/surfaces/blender/tests/action_cases.json @@ -0,0 +1,233 @@ +[ + {"action": "createObject", "fields": {}, "expect": "ok"}, + {"action": "createObject", "fields": {"objectType": "MESH", "name": "N", "location": [0, 0, 1], "size": 2, "meshType": "CUBE"}, "expect": "ok"}, + {"action": "createObject", "fields": {"objectType": null, "name": null, "location": null}, "expect": "ok"}, + {"action": "createObject", "fields": {"note": "n", "requestedBy": "a/b", "commandId": "x", "schema": "s"}, "expect": "ok"}, + {"action": "look", "fields": {}, "expect": "ok"}, + {"action": "deleteObject", "fields": {"targetObjectName": "Cube"}, "expect": "ok"}, + {"action": "deleteObject", "fields": {}, "expect": "targetObjectName is required."}, + {"action": "deleteObject", "fields": {"targetObjectName": null}, "expect": "targetObjectName is required."}, + {"action": "createObject", "fields": {"bogus": 1}, "expect": "createObject has no field 'bogus'; its fields: objectType, name, location, size, meshType, lightType, emptyDisplayType."}, + {"action": "createObject", "fields": {"zeta": 1, "alpha": 2}, "expect": "createObject has no field 'alpha'; its fields: objectType, name, location, size, meshType, lightType, emptyDisplayType."}, + {"action": "setObjectTransform", "fields": {"objectName": "x"}, "expect": "setObjectTransform has no field 'objectName'; its fields: targetObjectName, location, rotationEuler, scale."}, + {"action": "addModifier", "fields": {"targetObjectName": "x"}, "expect": "addModifier has no field 'targetObjectName'; its fields: objectName, modifierType, treeKind, treeKey, modifierName."}, + {"action": "setObjectParent", "fields": {"targetObjectName": "x", "parentName": "p"}, "expect": "setObjectParent has no field 'parentName'; its fields: targetObjectName, parentObjectName."}, + {"action": "look", "fields": {"x": 1}, "expect": "look has no field 'x'; its fields: none."}, + {"action": "runPython", "fields": {}, "expect": "Unsupported Blender command action: runPython"}, + {"action": "createobject", "fields": {}, "expect": "Unsupported Blender command action: createobject"}, + {"action": "createObject", "fields": {"name": 5}, "expect": "name must be a string."}, + {"action": "createObject", "fields": {"size": "x"}, "expect": "size must be a finite number."}, + {"action": "createObject", "fields": {"size": true}, "expect": "size must be a finite number."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 1.5}, "expect": "resolutionX must be a whole number."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": true}, "expect": "resolutionX must be a whole number."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": "64"}, "expect": "resolutionX must be a whole number."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 640.0}, "expect": "ok"}, + {"action": "setObjectVisibility", "fields": {"targetObjectName": "c", "visible": 1}, "expect": "visible must be true or false."}, + {"action": "setObjectVisibility", "fields": {"targetObjectName": "c", "visible": false}, "expect": "ok"}, + {"action": "createObject", "fields": {"location": "x"}, "expect": "location must be an array."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "properties": []}, "expect": "properties must be an object."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "properties": {"x": null, "y": 1}, "inputs": {"a": [1, 2]}}, "expect": "ok"}, + {"action": "setObjectCustomProperty", "fields": {"targetObjectName": "c", "value": null}, "expect": "value is required."}, + {"action": "setObjectCustomProperty", "fields": {"targetObjectName": "c", "value": {"a": [1]}}, "expect": "ok"}, + {"action": "setObjectCustomProperty", "fields": {"targetObjectName": "c", "value": false}, "expect": "ok"}, + {"action": "createObject", "fields": {"objectType": "mesh"}, "expect": "objectType must be one of MESH, LIGHT, CAMERA, EMPTY."}, + {"action": "createObject", "fields": {"objectType": " MESH"}, "expect": "objectType must be one of MESH, LIGHT, CAMERA, EMPTY."}, + {"action": "createObject", "fields": {"objectType": 3}, "expect": "objectType must be a string."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "cameraType": "CUSTOM"}, "expect": "cameraType must be one of PERSP, ORTHO, PANO."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "cameraType": "ortho"}, "expect": "cameraType must be one of PERSP, ORTHO, PANO."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "EQUIDISTANT"}, "expect": "panoramaType must be one of EQUIRECTANGULAR, EQUIANGULAR_CUBEMAP_FACE, MIRRORBALL, FISHEYE_EQUIDISTANT, FISHEYE_EQUISOLID, FISHEYE_LENS_POLYNOMIAL, CENTRAL_CYLINDRICAL."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "CENTRAL_CYLINDRICAL", "cameraType": "PANO", "active": true}, "expect": "ok"}, + {"action": "addModifier", "fields": {"objectName": "o", "treeKey": "G", "modifierType": "SUBSURF"}, "expect": "modifierType must be one of NODES."}, + {"action": "addNode", "fields": {"treeKind": "shader", "treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath"}, "expect": "treeKind must be one of geometry."}, + {"action": "createObject", "fields": {"objectType": "MESH", "lightType": "POINT"}, "expect": "lightType applies only when objectType is one of LIGHT."}, + {"action": "createObject", "fields": {"lightType": "POINT"}, "expect": "lightType applies only when objectType is one of LIGHT."}, + {"action": "createObject", "fields": {"objectType": "LIGHT", "emptyDisplayType": "CUBE"}, "expect": "emptyDisplayType applies only when objectType is one of EMPTY."}, + {"action": "createObject", "fields": {"objectType": "LIGHT", "meshType": "CUBE"}, "expect": "meshType applies only when objectType is one of MESH."}, + {"action": "createObject", "fields": {"objectType": "LIGHT", "lightType": "SPOT"}, "expect": "ok"}, + {"action": "createObject", "fields": {"objectType": "EMPTY", "emptyDisplayType": "IMAGE"}, "expect": "ok"}, + {"action": "createObject", "fields": {"objectType": "LIGHT", "lightType": "LASER"}, "expect": "lightType must be one of POINT, SUN, SPOT, AREA."}, + {"action": "createObject", "fields": {"objectType": "EMPTY", "emptyDisplayType": "BOX"}, "expect": "emptyDisplayType must be one of PLAIN_AXES, ARROWS, SINGLE_ARROW, CIRCLE, CUBE, SPHERE, CONE, IMAGE."}, + {"action": "createNodeGroup", "fields": {"treeKey": "", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "treeKey must have at least 1 characters."}, + {"action": "createNodeGroup", "fields": {"treeKey": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "treeKey must have at most 63 characters."}, + {"action": "createNodeGroup", "fields": {"treeKey": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "ok"}, + {"action": "createNodeGroup", "fields": {"treeKey": "my group.1-x_y", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "ok"}, + {"action": "createNodeGroup", "fields": {"treeKey": "a/b", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "treeKey may contain only letters, digits, space, '.', '_' or '-'."}, + {"action": "removeNode", "fields": {"treeKey": "G", "id": "a b"}, "expect": "id may contain only letters, digits, '.', '_' or '-'."}, + {"action": "removeNode", "fields": {"treeKey": "G", "id": "a\n"}, "expect": "id may contain only letters, digits, '.', '_' or '-'."}, + {"action": "removeNode", "fields": {"treeKey": "G", "id": "\u00e9"}, "expect": "id may contain only letters, digits, '.', '_' or '-'."}, + {"action": "removeNode", "fields": {"treeKey": "G", "id": "gin"}, "expect": "ok"}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "Math"}, "expect": "blIdname must start with one of GeometryNode, FunctionNode, ShaderNode and have at least one more character."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "GeometryNode"}, "expect": "blIdname must start with one of GeometryNode, FunctionNode, ShaderNode and have at least one more character."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "Geometry Node"}, "expect": "blIdname may contain only letters and digits."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "GeometryNodeGroup"}, "expect": "blIdname may not contain 'Group'."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeTexImage"}, "expect": "blIdname may not contain 'TexImage'."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "FunctionNodeCompare"}, "expect": "ok"}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "label": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}, "expect": "label must have at most 63 characters."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "label": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}, "expect": "ok"}, + {"action": "removeModifier", "fields": {"objectName": "o", "modifierName": "a\u0000b"}, "expect": "modifierName may not contain '\u0000'."}, + {"action": "removeModifier", "fields": {"objectName": "o", "modifierName": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}, "expect": "modifierName must have at most 255 characters."}, + {"action": "removeModifier", "fields": {"objectName": "o", "modifierName": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}, "expect": "ok"}, + {"action": "removeModifier", "fields": {"objectName": "o", "modifierName": ""}, "expect": "modifierName must have at least 1 characters."}, + {"action": "removeModifier", "fields": {"objectName": "o", "modifierName": "G\u00e9 x/y"}, "expect": "ok"}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "engine": ""}, "expect": "engine must have at least 1 characters."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "engine": "CYCLES"}, "expect": "ok"}, + {"action": "exportGltf", "fields": {"filepath": "a.glb", "selection": []}, "expect": "selection must have at least 1 items."}, + {"action": "exportGltf", "fields": {"filepath": "a.glb", "selection": [3]}, "expect": "selection[0] must be a string."}, + {"action": "exportGltf", "fields": {"filepath": "a.glb", "selection": ["a", ""]}, "expect": "selection[1] must have at least 1 characters."}, + {"action": "exportGltf", "fields": {"filepath": "a.glb", "selection": ["a", null]}, "expect": "selection[1] must be a string."}, + {"action": "exportGltf", "fields": {"filepath": "a.glb", "selection": ["a"], "extras": "yes"}, "expect": "extras must be true or false."}, + {"action": "createObject", "fields": {"location": [1, 2]}, "expect": "location must have at least 3 items."}, + {"action": "createObject", "fields": {"location": [1, 2, 3, 4]}, "expect": "location must have at most 3 items."}, + {"action": "createObject", "fields": {"location": [1, "x", 3]}, "expect": "location[1] must be a finite number."}, + {"action": "createObject", "fields": {"location": [1, null, 3]}, "expect": "location[1] must be a finite number."}, + {"action": "createObject", "fields": {"location": [1, 2, true]}, "expect": "location[2] must be a finite number."}, + {"action": "assignMaterial", "fields": {"targetObjectName": "c", "color": [1, 0]}, "expect": "color must have at least 3 items."}, + {"action": "assignMaterial", "fields": {"targetObjectName": "c", "color": [1, 0, 0, 0, 0]}, "expect": "color must have at most 4 items."}, + {"action": "assignMaterial", "fields": {"targetObjectName": "c", "color": [1, 0, 0, 0.5]}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c", "color": [1, 0, 0, 1]}, "expect": "color must have at most 3 items."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "location": [1]}, "expect": "location must have at least 2 items."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G"}, "expect": "interface is required."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": []}, "expect": "interface must have at least 1 items."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "interface must have at most 64 items."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "ok"}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [1]}, "expect": "interface[0] must be an object."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "type": "Int"}]}, "expect": "interface[0].name is required."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": null, "type": "Int"}]}, "expect": "interface[1].name is required."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "input", "name": "a", "type": "Int"}]}, "expect": "interface[0].inOut must be one of INPUT, OUTPUT."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Mat"}]}, "expect": "interface[0].type must be one of Geometry, Float, Int, Bool, Vector."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "", "type": "Int"}]}, "expect": "interface[0].name must have at least 1 characters."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "type": "Int"}]}, "expect": "interface[0].name must have at most 63 characters."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int", "extra": 1}]}, "expect": "interface[0] has no field 'extra'; its fields: inOut, name, type, default."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int", "default": "anything"}]}, "expect": "ok"}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int", "default": null}]}, "expect": "ok"}, + {"action": "linkSockets", "fields": {"treeKey": "G", "fromNode": "a", "fromSocket": "o", "toNode": "b"}, "expect": "toSocket is required."}, + {"action": "unlinkSockets", "fields": {"treeKey": "G", "toNode": "b", "toSocket": "i"}, "expect": "ok"}, + {"action": "unlinkSockets", "fields": {"treeKey": "G", "toNode": "b", "toSocket": "i", "fromNode": "a"}, "expect": "ok"}, + {"action": "createObject", "fields": {"location": [-1000000000, -1000000000, -1000000000]}, "expect": "ok"}, + {"action": "createObject", "fields": {"location": [1000000000, 1000000000, 1000000000]}, "expect": "ok"}, + {"action": "createObject", "fields": {"location": [-1000000000, -1000000000, 1000000001]}, "expect": "location[2] must be between -1000000000 and 1000000000."}, + {"action": "createObject", "fields": {"location": [-1000000001, -1000000000, -1000000000]}, "expect": "location[0] must be between -1000000000 and 1000000000."}, + {"action": "createObject", "fields": {"size": 0.001}, "expect": "ok"}, + {"action": "createObject", "fields": {"size": 1000000}, "expect": "ok"}, + {"action": "createObject", "fields": {"size": 1000001}, "expect": "size must be between 0.001 and 1000000."}, + {"action": "createObject", "fields": {"size": -0.999}, "expect": "size must be between 0.001 and 1000000."}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "location": [-1000000000, -1000000000, -1000000000]}, "expect": "ok"}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "location": [1000000000, 1000000000, 1000000000]}, "expect": "ok"}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "location": [-1000000000, -1000000000, 1000000001]}, "expect": "location[2] must be between -1000000000 and 1000000000."}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "location": [-1000000001, -1000000000, -1000000000]}, "expect": "location[0] must be between -1000000000 and 1000000000."}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "rotationEuler": [-1000000000, -1000000000, -1000000000]}, "expect": "ok"}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "rotationEuler": [1000000000, 1000000000, 1000000000]}, "expect": "ok"}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "rotationEuler": [-1000000000, -1000000000, 1000000001]}, "expect": "rotationEuler[2] must be between -1000000000 and 1000000000."}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "rotationEuler": [-1000000001, -1000000000, -1000000000]}, "expect": "rotationEuler[0] must be between -1000000000 and 1000000000."}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "scale": [-1000000000, -1000000000, -1000000000]}, "expect": "ok"}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "scale": [1000000000, 1000000000, 1000000000]}, "expect": "ok"}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "scale": [-1000000000, -1000000000, 1000000001]}, "expect": "scale[2] must be between -1000000000 and 1000000000."}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "scale": [-1000000001, -1000000000, -1000000000]}, "expect": "scale[0] must be between -1000000000 and 1000000000."}, + {"action": "assignMaterial", "fields": {"targetObjectName": "c", "color": [0, 0, 0]}, "expect": "ok"}, + {"action": "assignMaterial", "fields": {"targetObjectName": "c", "color": [1, 1, 1]}, "expect": "ok"}, + {"action": "assignMaterial", "fields": {"targetObjectName": "c", "color": [0, 0, 2]}, "expect": "color[2] must be between 0 and 1."}, + {"action": "assignMaterial", "fields": {"targetObjectName": "c", "color": [-1, 0, 0]}, "expect": "color[0] must be between 0 and 1."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "lens": 1}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "lens": 5000}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "lens": 5001}, "expect": "lens must be between 1 and 5000."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "lens": 0}, "expect": "lens must be between 1 and 5000."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "orthoScale": 0.001}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "orthoScale": 100000}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "orthoScale": 100001}, "expect": "orthoScale must be between 0.001 and 100000."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "orthoScale": -0.999}, "expect": "orthoScale must be between 0.001 and 100000."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "clipStart": 0.0001}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "clipStart": 1000000}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "clipStart": 1000001}, "expect": "clipStart must be between 0.0001 and 1000000."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "clipStart": -0.9999}, "expect": "clipStart must be between 0.0001 and 1000000."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "clipEnd": 0.001}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "clipEnd": 10000000}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "clipEnd": 10000001}, "expect": "clipEnd must be between 0.001 and 10000000."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "clipEnd": -0.999}, "expect": "clipEnd must be between 0.001 and 10000000."}, + {"action": "setLight", "fields": {"targetObjectName": "c", "energy": 0}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c", "energy": 10000000}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c", "energy": 10000001}, "expect": "energy must be between 0 and 10000000."}, + {"action": "setLight", "fields": {"targetObjectName": "c", "energy": -1}, "expect": "energy must be between 0 and 10000000."}, + {"action": "setLight", "fields": {"targetObjectName": "c", "color": [0, 0, 0]}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c", "color": [1, 1, 1]}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c", "color": [0, 0, 2]}, "expect": "color[2] must be between 0 and 1."}, + {"action": "setLight", "fields": {"targetObjectName": "c", "color": [-1, 0, 0]}, "expect": "color[0] must be between 0 and 1."}, + {"action": "setWorld", "fields": {"color": [0, 0, 0]}, "expect": "ok"}, + {"action": "setWorld", "fields": {"color": [1, 1, 1]}, "expect": "ok"}, + {"action": "setWorld", "fields": {"color": [0, 0, 2]}, "expect": "color[2] must be between 0 and 1."}, + {"action": "setWorld", "fields": {"color": [-1, 0, 0]}, "expect": "color[0] must be between 0 and 1."}, + {"action": "setWorld", "fields": {"strength": 0}, "expect": "ok"}, + {"action": "setWorld", "fields": {"strength": 1000000}, "expect": "ok"}, + {"action": "setWorld", "fields": {"strength": 1000001}, "expect": "strength must be between 0 and 1000000."}, + {"action": "setWorld", "fields": {"strength": -1}, "expect": "strength must be between 0 and 1000000."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 4}, "expect": "ok"}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 16384}, "expect": "ok"}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 16385}, "expect": "resolutionX must be between 4 and 16384."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 3}, "expect": "resolutionX must be between 4 and 16384."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionY": 4}, "expect": "ok"}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionY": 16384}, "expect": "ok"}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionY": 16385}, "expect": "resolutionY must be between 4 and 16384."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionY": 3}, "expect": "resolutionY must be between 4 and 16384."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "location": [-1000000000, -1000000000]}, "expect": "ok"}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "location": [1000000000, 1000000000]}, "expect": "ok"}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "location": [-1000000000, 1000000001]}, "expect": "location[1] must be between -1000000000 and 1000000000."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "location": [-1000000001, -1000000000]}, "expect": "location[0] must be between -1000000000 and 1000000000."}, + {"action": "createObject", "fields": {"objectType": "MESH"}, "expect": "ok"}, + {"action": "createObject", "fields": {"objectType": "LIGHT"}, "expect": "ok"}, + {"action": "createObject", "fields": {"objectType": "CAMERA"}, "expect": "ok"}, + {"action": "createObject", "fields": {"objectType": "EMPTY"}, "expect": "ok"}, + {"action": "createObject", "fields": {"objectType": "mesh_"}, "expect": "objectType must be one of MESH, LIGHT, CAMERA, EMPTY."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "cameraType": "PERSP"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "cameraType": "ORTHO"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "cameraType": "PANO"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "cameraType": "persp_"}, "expect": "cameraType must be one of PERSP, ORTHO, PANO."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "EQUIRECTANGULAR"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "EQUIANGULAR_CUBEMAP_FACE"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "MIRRORBALL"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "FISHEYE_EQUIDISTANT"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "FISHEYE_EQUISOLID"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "FISHEYE_LENS_POLYNOMIAL"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "CENTRAL_CYLINDRICAL"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "equirectangular_"}, "expect": "panoramaType must be one of EQUIRECTANGULAR, EQUIANGULAR_CUBEMAP_FACE, MIRRORBALL, FISHEYE_EQUIDISTANT, FISHEYE_EQUISOLID, FISHEYE_LENS_POLYNOMIAL, CENTRAL_CYLINDRICAL."}, + {"action": "setLight", "fields": {"targetObjectName": "c", "lightType": "POINT"}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c", "lightType": "SUN"}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c", "lightType": "SPOT"}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c", "lightType": "AREA"}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c", "lightType": "point_"}, "expect": "lightType must be one of POINT, SUN, SPOT, AREA."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}], "treeKind": "geometry"}, "expect": "ok"}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}], "treeKind": "geometry_"}, "expect": "treeKind must be one of geometry."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "treeKind": "geometry"}, "expect": "ok"}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "treeKind": "geometry_"}, "expect": "treeKind must be one of geometry."}, + {"action": "removeNode", "fields": {"treeKey": "G", "id": "a", "treeKind": "geometry"}, "expect": "ok"}, + {"action": "removeNode", "fields": {"treeKey": "G", "id": "a", "treeKind": "geometry_"}, "expect": "treeKind must be one of geometry."}, + {"action": "linkSockets", "fields": {"treeKey": "G", "fromNode": "a", "fromSocket": "o", "toNode": "b", "toSocket": "i", "treeKind": "geometry"}, "expect": "ok"}, + {"action": "linkSockets", "fields": {"treeKey": "G", "fromNode": "a", "fromSocket": "o", "toNode": "b", "toSocket": "i", "treeKind": "geometry_"}, "expect": "treeKind must be one of geometry."}, + {"action": "unlinkSockets", "fields": {"treeKey": "G", "toNode": "b", "toSocket": "i", "treeKind": "geometry"}, "expect": "ok"}, + {"action": "unlinkSockets", "fields": {"treeKey": "G", "toNode": "b", "toSocket": "i", "treeKind": "geometry_"}, "expect": "treeKind must be one of geometry."}, + {"action": "addModifier", "fields": {"objectName": "o", "treeKey": "G", "modifierType": "NODES"}, "expect": "ok"}, + {"action": "addModifier", "fields": {"objectName": "o", "treeKey": "G", "modifierType": "nodes_"}, "expect": "modifierType must be one of NODES."}, + {"action": "addModifier", "fields": {"objectName": "o", "treeKey": "G", "treeKind": "geometry"}, "expect": "ok"}, + {"action": "addModifier", "fields": {"objectName": "o", "treeKey": "G", "treeKind": "geometry_"}, "expect": "treeKind must be one of geometry."}, + {"action": "createObject", "fields": {}, "expect": "ok"}, + {"action": "deleteObject", "fields": {"targetObjectName": "c"}, "expect": "ok"}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c"}, "expect": "ok"}, + {"action": "setObjectVisibility", "fields": {"targetObjectName": "c"}, "expect": "ok"}, + {"action": "setObjectParent", "fields": {"targetObjectName": "c"}, "expect": "ok"}, + {"action": "setObjectCustomProperty", "fields": {"targetObjectName": "c", "value": 1}, "expect": "ok"}, + {"action": "selectObject", "fields": {"targetObjectName": "c"}, "expect": "ok"}, + {"action": "assignMaterial", "fields": {"targetObjectName": "c"}, "expect": "ok"}, + {"action": "importGltf", "fields": {"filepath": "a.glb"}, "expect": "ok"}, + {"action": "exportGltf", "fields": {"filepath": "a.glb"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c"}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c"}, "expect": "ok"}, + {"action": "setWorld", "fields": {}, "expect": "ok"}, + {"action": "renderStill", "fields": {"outputPath": "a.png"}, "expect": "ok"}, + {"action": "look", "fields": {}, "expect": "ok"}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "ok"}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath"}, "expect": "ok"}, + {"action": "removeNode", "fields": {"treeKey": "G", "id": "a"}, "expect": "ok"}, + {"action": "linkSockets", "fields": {"treeKey": "G", "fromNode": "a", "fromSocket": "o", "toNode": "b", "toSocket": "i"}, "expect": "ok"}, + {"action": "unlinkSockets", "fields": {"treeKey": "G", "toNode": "b", "toSocket": "i"}, "expect": "ok"}, + {"action": "addModifier", "fields": {"objectName": "o", "treeKey": "G"}, "expect": "ok"}, + {"action": "removeModifier", "fields": {"objectName": "o"}, "expect": "ok"}, + {"action": "setModifierInput", "fields": {"objectName": "o", "socket": "s", "value": 1}, "expect": "ok"} +] diff --git a/surfaces/blender/tests/live/agent_turn_queue.py b/surfaces/blender/tests/live/agent_turn_queue.py index 1521ba0..5f8a68c 100644 --- a/surfaces/blender/tests/live/agent_turn_queue.py +++ b/surfaces/blender/tests/live/agent_turn_queue.py @@ -202,7 +202,7 @@ def q5_edit(): push("driver edit baseline") queue("aaaaaaaa-0006", action="setWorld", color=[1, 0, 0], requestedBy="nibu/hands") queue("aaaaaaaa-0007", action="exportGltf", filepath="edit.glb", requestedBy="nibu/hands") - queue("aaaaaaaa-0008", action="setObjectTransform", objectName="Cube", location=[0, 0, 9], requestedBy="nibu/hands") + queue("aaaaaaaa-0008", action="setObjectTransform", targetObjectName="Cube", location=[0, 0, 9], requestedBy="nibu/hands") def q5_check(): diff --git a/surfaces/blender/tests/live/agent_turn_undo.py b/surfaces/blender/tests/live/agent_turn_undo.py index 9a9dc1b..c8bec53 100644 --- a/surfaces/blender/tests/live/agent_turn_undo.py +++ b/surfaces/blender/tests/live/agent_turn_undo.py @@ -88,7 +88,7 @@ def s_create(): def s_transform(): - intent(action="setObjectTransform", objectName="AgentCube", location=[3, 2, 0]) + intent(action="setObjectTransform", targetObjectName="AgentCube", location=[3, 2, 0]) check("transform applied", loc("AgentCube") == [3.0, 2.0, 0.0], loc("AgentCube")) @@ -131,7 +131,7 @@ def s_edit_enter(): def s_edit_agent(): - r = intent(action="setObjectTransform", objectName="Cube", location=[0, 0, 5]) + r = intent(action="setObjectTransform", targetObjectName="Cube", location=[0, 0, 5]) R["editMode"].update(mode_after_intent=bpy.context.mode, loc_after_intent=loc("Cube"), receipt=r["status"], message=r["message"], undoLabel=r["undoLabel"]) check("edit mode: object-level intent refused, scene and her mode unchanged", diff --git a/surfaces/blender/tests/test_action_table.py b/surfaces/blender/tests/test_action_table.py new file mode 100644 index 0000000..d548b1b --- /dev/null +++ b/surfaces/blender/tests/test_action_table.py @@ -0,0 +1,181 @@ +"""The action table: the parity fixture, handler coverage, and the table's own load checks. No Blender.""" +from __future__ import annotations + +import copy +import json +import re +import unittest +from pathlib import Path +from unittest import mock + +import test_scene_actions as ts + +at = ts.at +bt = ts.bt +na = ts.bt.na +CASES = json.loads((Path(__file__).with_name("action_cases.json")).read_text(encoding="utf-8")) + + +def validate(action, fields): + try: + at.validate({"action": action, **fields}) + except at.IntentInvalid as error: + return str(error) + return "ok" + + +class ParityFixtureTests(unittest.TestCase): + """action_cases.json is also run by brokkr-ctl's actions.rs: one table, two interpreters, one set of messages.""" + + def test_every_case_yields_exactly_its_expected_message_or_ok(self): + wrong = [(c["action"], c["fields"], c["expect"], validate(c["action"], c["fields"])) + for c in CASES if validate(c["action"], c["fields"]) != c["expect"]] + self.assertEqual(wrong, []) + + def test_the_fixture_covers_every_rule_kind_and_every_number_field(self): + text = json.dumps(CASES) + for needle in ("is required.", "has no field", "must be one of", "must be between", "must have at least", "must have at most", + "may contain only", "must start with one of", "may not contain", "applies only when", "Unsupported Blender"): + self.assertIn(needle, text) + for action in at.table()["actions"]: + for field in action["fields"]: + if field["type"] in ("number", "integer") or field.get("items", {}).get("type") == "number": + pins = [c for c in CASES if c["action"] == action["name"] and field["name"] in c["fields"] + and c["expect"].startswith(f"{field['name']}") and "must be between" in c["expect"]] + self.assertGreaterEqual(len(pins), 2, f"{action['name']}.{field['name']}: both bounds") + self.assertTrue(any(c["action"] == action["name"] and c["expect"] == "ok" for c in CASES), action["name"]) + + def test_validate_normalizes_null_to_absent_and_fills_defaults(self): + normal = at.validate({"action": "createObject", "objectType": None, "location": None, "note": "n"}) + self.assertEqual(normal["objectType"], "EMPTY") + self.assertEqual((normal["size"], normal["lightType"], normal["emptyDisplayType"]), (1, "POINT", "PLAIN_AXES")) + self.assertNotIn("location", normal) + self.assertEqual(normal["note"], "n") + self.assertEqual(at.validate({"action": "setLight", "targetObjectName": "L"}).get("lightType"), None) # no default: absent stays absent + + def test_a_mutant_validator_fails_the_fixture(self): + """The fixture pins the rules: casefolding enums, widening a bound or letting bool pass as a number each break cases.""" + original = at._value + + def casefolded(spec, value, path): + if "enum" in spec and isinstance(value, str): + value = next((e for e in spec["enum"] if e.lower() == value.lower()), value) + return original(spec, value, path) + + for mutant in (casefolded,): + with mock.patch.object(at, "_value", mutant): + self.assertNotEqual([c for c in CASES if validate(c["action"], c["fields"]) != c["expect"]], []) + number = at._number + + def widened(spec, value, path): + return number({**spec, "maximum": spec["maximum"] * 10 + 10}, value, path) + + def boolish(spec, value, path): + return number(spec, int(value) if isinstance(value, bool) else value, path) + + for mutant in (widened, boolish): + with mock.patch.object(at, "_number", mutant): + self.assertNotEqual([c for c in CASES if validate(c["action"], c["fields"]) != c["expect"]], [], mutant.__name__) + + +class HandlerCoverageTests(unittest.TestCase): + def test_each_table_action_resolves_to_exactly_one_handler_and_each_handler_has_an_entry(self): + names = [a["name"] for a in at.table()["actions"]] + self.assertEqual(len(names), len(set(names))) + target = bt.BrokkrBlenderTarget + for name in names: + owners = [owner for owner in (target, na.NodeActions) if hasattr(owner, "_" + name)] + self.assertEqual(len(owners), 1, f"{name}: handlers {owners}") + camel = re.compile(r"_[a-z]+[A-Z][A-Za-z0-9]*") # every other private name of both classes is snake_case + handlers = {n[1:] for owner in (target, na.NodeActions) for n in vars(owner) if camel.fullmatch(n)} | {"look"} + self.assertEqual(sorted(handlers - set(names)), [], "a handler without a table entry") + self.assertEqual(sorted(set(names) - handlers), [], "a table entry without a handler") + + def test_node_socket_types_are_the_tables(self): + spec = next(a for a in at.table()["actions"] if a["name"] == "createNodeGroup") + interface = next(f for f in spec["fields"] if f["name"] == "interface") + kinds = next(p for p in interface["items"]["properties"] if p["name"] == "type")["enum"] + self.assertEqual(sorted(kinds), sorted(na.SOCKET_TYPES)) + + def test_removing_an_entry_makes_the_action_unsupported(self): + trimmed = copy.deepcopy(at.table()) + trimmed["actions"] = [a for a in trimmed["actions"] if a["name"] != "deleteObject"] + with mock.patch.object(at, "table", return_value=trimmed), mock.patch.object(at, "_by_name", return_value={a["name"]: a for a in trimmed["actions"]}): + self.assertEqual(validate("deleteObject", {"targetObjectName": "c"}), "Unsupported Blender command action: deleteObject") + + def test_undo_and_edit_mode_classes_are_the_tables(self): + rows = {a["name"]: a for a in at.table()["actions"]} + self.assertEqual(sorted(n for n, a in rows.items() if not a["changesScene"]), ["exportGltf", "look", "renderStill"]) + self.assertEqual(sorted(n for n, a in rows.items() if a["editModeSafe"]), ["look", "renderStill"]) + + +class TableCheckTests(unittest.TestCase): + def table(self): + return copy.deepcopy(at.table()) + + def test_an_unbounded_number_field_is_refused_at_load(self): + broken = self.table() + del next(f for a in broken["actions"] for f in a["fields"] if f["name"] == "lens")["maximum"] + with self.assertRaisesRegex(at.TableInvalid, "lens.*maximum"): + at.check_table(broken) + broken = self.table() + del next(f for a in broken["actions"] if a["name"] == "createObject" for f in a["fields"] if f["name"] == "location")["items"]["minimum"] + with self.assertRaisesRegex(at.TableInvalid, "minimum"): + at.check_table(broken) + + def test_an_only_naming_a_missing_field_is_refused(self): + broken = self.table() + next(f for a in broken["actions"] for f in a["fields"] if f["name"] == "lightType" and "only" in f)["only"]["field"] = "nope" + with self.assertRaisesRegex(at.TableInvalid, "only"): + at.check_table(broken) + + def test_an_unknown_charset_is_refused(self): + broken = self.table() + next(f for a in broken["actions"] for f in a["fields"] if f.get("chars") == "key")["chars"] = "nope" + with self.assertRaisesRegex(at.TableInvalid, "charset"): + at.check_table(broken) + + def test_a_default_that_breaks_its_own_field_is_refused(self): + broken = self.table() + next(f for a in broken["actions"] for f in a["fields"] if f["name"] == "objectType")["default"] = "TEXT" + with self.assertRaisesRegex(at.TableInvalid, "default"): + at.check_table(broken) + + def test_a_bound_that_prints_differently_in_python_and_rust_is_refused(self): + broken = self.table() + next(f for a in broken["actions"] for f in a["fields"] if f["name"] == "clipStart")["minimum"] = 1e-7 + with self.assertRaisesRegex(at.TableInvalid, "plain digits"): + at.check_table(broken) + + +class AdmissionTests(unittest.TestCase): + setUp = ts.ActionTests.setUp + run_action = ts.ActionTests.run_action + + def test_a_table_refusal_is_denied_pushes_no_undo_step_and_calls_no_operator(self): + for fields in ({"action": "createObject", "bogus": 1}, {"action": "createObject", "objectType": "mesh"}, + {"action": "renderStill", "outputPath": "a.png", "resolutionX": 2}, + {"action": "setObjectTransform", "objectName": "Cube", "location": [0, 0, 1]}): + receipt = self.run_action(**fields) + self.assertEqual(receipt["status"], "denied", fields) + self.assertEqual(receipt["undoLabel"], "") + self.assertEqual((self.bpy.created, self.bpy.undo.pushes, self.bpy.rendered), ([], [], [])) + self.assertEqual(self.bpy.mesh.__dict__.get("location"), None) + + def test_the_unknown_action_message_and_the_order_of_admission(self): + self.assertEqual(self.run_action(action="runPython")["message"], "Unsupported Blender command action: runPython") + self.bpy.mesh.mode = "EDIT" + receipt = self.run_action(action="createObject", objectType="mesh") # invalid fields are named before the mode + self.assertNotIn("Edit Mode", receipt["message"]) + receipt = self.run_action(action="createObject", objectType="EMPTY") + self.assertIn("Edit Mode", receipt["message"]) + + def test_defaults_reach_the_handler(self): + self.assertEqual(self.run_action(action="createObject", objectType="MESH")["status"], "accepted") + self.assertEqual(self.bpy.created[-1][1]["size"], 1.0) + self.assertEqual(self.run_action(action="createObject", objectType="LIGHT")["status"], "accepted") + self.assertEqual(self.bpy.created[-1][1]["type"], "POINT") + + +if __name__ == "__main__": + unittest.main() diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index b052cc9..523e0cb 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -11,6 +11,7 @@ from pathlib import Path import test_scene_actions as ts bt = ts.bt +at = ts.at SOURCE = Path(bt.__file__) @@ -30,7 +31,7 @@ class AgentTurnTests(unittest.TestCase): def test_object_intent_is_refused_while_an_object_is_in_edit_mode(self): self.bpy.mesh.mode = "EDIT" - receipt = self.run_action(action="setObjectTransform", objectName="Cube", location=[0, 0, 5]) + receipt = self.run_action(action="setObjectTransform", targetObjectName="Cube", location=[0, 0, 5]) self.assertEqual(receipt["status"], "denied") self.assertIn("Edit Mode", receipt["message"]) self.assertEqual(receipt["undoLabel"], "") @@ -76,13 +77,15 @@ class AgentTurnTests(unittest.TestCase): def test_refusal_pushes_nothing(self): receipt = self.run_action(action="createObject", objectType="BOGUS") - self.assertEqual(receipt["status"], "failed") + self.assertEqual(receipt["status"], "denied") self.assertEqual(receipt["undoLabel"], "") self.assertEqual(self.bpy.undo.pushes, []) + receipt = self.run_action(action="deleteObject", targetObjectName="Nope") # a scene refusal: ran, failed, no step + self.assertEqual(receipt["status"], "failed") + self.assertEqual(self.bpy.undo.pushes, []) def test_read_action_pushes_nothing(self): - with unittest.mock.patch.object(bt, "READ_ACTIONS", ("createObject",)): - self.run_action(action="createObject", objectType="EMPTY") + self.assertNotEqual(self.run_action(action="look")["status"], "denied") # admitted; the fake has no 3D view to capture self.assertEqual(self.bpy.undo.pushes, []) def test_raise_after_admission_pushes_failed_step(self): @@ -131,7 +134,7 @@ class AgentTurnTests(unittest.TestCase): self.assertEqual(self.bpy.undo.pushes, []) def test_returned_failed_receipt_pushes_nothing(self): - receipt = self.run_action(action="setObjectTransform", objectName="NoSuchObject", location=[1, 2, 3]) + receipt = self.run_action(action="setObjectTransform", targetObjectName="NoSuchObject", location=[1, 2, 3]) self.assertEqual(receipt["status"], "failed") self.assertEqual(self.bpy.undo.pushes, []) @@ -162,7 +165,7 @@ class AgentTurnTests(unittest.TestCase): # fix batch s2 def test_no_scene_change_set_is_exactly_export_and_render(self): - self.assertEqual(bt.NO_SCENE_CHANGE_ACTIONS, ("exportGltf", "renderStill")) + self.assertEqual([a["name"] for a in at.table()["actions"] if not a["changesScene"]], ["exportGltf", "renderStill", "look"]) receipt = self.run_action(action="setWorld", color=[0.1, 0.2, 0.3]) self.assertEqual(receipt["status"], "accepted") self.assertEqual(len(self.bpy.undo.pushes), 1) diff --git a/surfaces/blender/tests/test_material_actions.py b/surfaces/blender/tests/test_material_actions.py index 0caa663..884bca2 100644 --- a/surfaces/blender/tests/test_material_actions.py +++ b/surfaces/blender/tests/test_material_actions.py @@ -121,7 +121,7 @@ class MaterialTests(unittest.TestCase): [float("nan"), 0, 0], [float("inf"), 0, 0], [-0.1, 0, 0], [1.1, 0, 0], [0, 0, 0, 2], [1.0000001, 0, 0], [-1e-9, 0, 0], [0, 0, 0, 1.0000001], [10**400, 0, 0], [0, -10**400, 0]): receipt = self.assign(materialName="oxide red", color=bad) - self.assertEqual(receipt["status"], "failed", bad) + self.assertEqual(receipt["status"], "denied", bad) self.assertIn("color", receipt["message"], bad) self.assertEqual(dict(self.bpy.data.materials), {}) self.assertEqual(self.bpy.mesh.data.materials, []) @@ -143,7 +143,7 @@ class MaterialTests(unittest.TestCase): def test_refused_colour_on_an_existing_material_leaves_it_alone(self): self.assign(materialName="oxide red", color=[0.5, 0.1, 0.1]) - self.assertEqual(self.assign(materialName="oxide red", color=[2, 0, 0])["status"], "failed") + self.assertEqual(self.assign(materialName="oxide red", color=[2, 0, 0])["status"], "denied") self.assertEqual(self.base_color(), (0.5, 0.1, 0.1, 1.0)) def test_existing_tree_without_a_principled_node_gets_one(self): diff --git a/surfaces/blender/tests/test_node_actions.py b/surfaces/blender/tests/test_node_actions.py index eff659b..2a24752 100644 --- a/surfaces/blender/tests/test_node_actions.py +++ b/surfaces/blender/tests/test_node_actions.py @@ -204,8 +204,9 @@ class NodeActionTests(unittest.TestCase): return receipt def refused(self, **command): + """Refused either at admission by the table ('denied') or by the handler against the scene ('failed').""" receipt = self.run_action(**command) - self.assertEqual(receipt["status"], "failed", receipt["message"]) + self.assertIn(receipt["status"], ("denied", "failed"), receipt["message"]) return receipt def group(self, interface=None): diff --git a/surfaces/blender/tests/test_perception.py b/surfaces/blender/tests/test_perception.py index 48ba6fb..e2a2017 100644 --- a/surfaces/blender/tests/test_perception.py +++ b/surfaces/blender/tests/test_perception.py @@ -593,7 +593,7 @@ class HumanEditTests(PerceptionFixture): # scene-last-writer-wins: an intent after her edit is accepted, and so is one that targets what she edited rich(self.bpy.mesh) self.target.track_human_edits(depsgraph(update("Cube", transform=True))) - receipt = self.run_action(action="setObjectTransform", objectName="Cube", location=[0, 0, 5]) + receipt = self.run_action(action="setObjectTransform", targetObjectName="Cube", location=[0, 0, 5]) self.assertEqual(receipt["status"], "accepted", receipt["message"]) self.assertEqual(self.run_action(action="createObject", objectType="EMPTY")["status"], "accepted") self.assertEqual(len(self.bpy.undo.pushes), 2) diff --git a/surfaces/blender/tests/test_scene_actions.py b/surfaces/blender/tests/test_scene_actions.py index a36df4a..d9abebc 100644 --- a/surfaces/blender/tests/test_scene_actions.py +++ b/surfaces/blender/tests/test_scene_actions.py @@ -20,6 +20,7 @@ package = types.ModuleType("brokkr_bridge") package.__path__ = [str(ADDON)] sys.modules.setdefault("brokkr_bridge", package) +from brokkr_bridge import action_table as at # noqa: E402 from brokkr_bridge import blender_target as bt # noqa: E402 from brokkr_bridge import scene_actions as sa # noqa: E402 @@ -218,27 +219,18 @@ class ActionTests(unittest.TestCase): # setCamera def test_set_camera_sets_lens_type_panorama_and_active(self): - receipt = self.run_action(action="setCamera", targetObjectName="Cam", lens=35, cameraType="pano", + receipt = self.run_action(action="setCamera", targetObjectName="Cam", lens=35, cameraType="PANO", panoramaType="EQUIRECTANGULAR", active=True, clipEnd=500) self.assertEqual(receipt["status"], "accepted") d = self.bpy.camera_data self.assertEqual((d.lens, d.type, d.panorama_type, d.clip_end), (35.0, "PANO", "EQUIRECTANGULAR", 500.0)) self.assertIs(self.bpy.scene.camera, self.bpy.cam) - def test_set_camera_falls_back_to_the_cycles_panorama_property(self): - cycles = NS(panorama_type="FISHEYE_EQUISOLID", - bl_rna=NS(properties={"panorama_type": Enum("EQUIRECTANGULAR")})) - data = NS(lens=50.0, type="PERSP", cycles=cycles) - self.bpy.data.objects["Cam"] = NS(name="Cam", type="CAMERA", data=data) - receipt = self.run_action(action="setCamera", targetObjectName="Cam", panoramaType="EQUIRECTANGULAR") - self.assertEqual(receipt["status"], "accepted") - self.assertEqual(cycles.panorama_type, "EQUIRECTANGULAR") - def test_set_camera_refused_input_changes_nothing(self): for bad in ({"lens": -1}, {"lens": "wide"}, {"lens": float("nan")}, {"cameraType": "FISHEYE"}, {"panoramaType": "NOPE"}, {"lens": True}): receipt = self.run_action(action="setCamera", targetObjectName="Cam", clipEnd=9, **bad) - self.assertEqual(receipt["status"], "failed", bad) + self.assertEqual(receipt["status"], "denied", bad) # the table's refusal: admission, nothing ran self.assertEqual(self.bpy.camera_data.clip_end, 100.0) self.assertEqual(self.run_action(action="setCamera", targetObjectName="Lamp", lens=35)["status"], "failed") self.assertEqual(self.run_action(action="setCamera", targetObjectName="Nope", lens=35)["status"], "failed") @@ -251,7 +243,7 @@ class ActionTests(unittest.TestCase): def test_set_light_rejects_bad_values_whole(self): for bad in ({"energy": -5}, {"color": [2, 0, 0]}, {"color": [1, 0]}, {"color": "red"}, {"lightType": "LASER"}): - self.assertEqual(self.run_action(action="setLight", targetObjectName="Lamp", **bad)["status"], "failed", bad) + self.assertEqual(self.run_action(action="setLight", targetObjectName="Lamp", **bad)["status"], "denied", bad) self.assertEqual(self.bpy.light_data.energy, 1000.0) self.assertEqual(self.run_action(action="setLight", targetObjectName="Cam", energy=1)["status"], "failed") @@ -265,7 +257,7 @@ class ActionTests(unittest.TestCase): self.assertEqual(world.background.inputs["Strength"].default_value, 2.0) def test_set_world_refuses_bad_colour_before_creating_a_world(self): - self.assertEqual(self.run_action(action="setWorld", color=[9, 0, 0])["status"], "failed") + self.assertEqual(self.run_action(action="setWorld", color=[9, 0, 0])["status"], "denied") self.assertIsNone(self.bpy.scene.world) # exportGltf @@ -335,18 +327,16 @@ class ActionTests(unittest.TestCase): def test_export_refusals_never_reach_bpy_or_disk(self): (self.root / "out" / "taken.glb").write_bytes(b"old") + denied = [{"filepath": 5}, {"filepath": "a.glb", "selection": []}, {"filepath": "a.glb", "selection": "Cube"}, + {"filepath": "a.glb", "selection": [3]}, {"filepath": "a.glb", "extras": "yes"}, {"filepath": "a.glb", "yUp": 1}] + for case in denied: # the table refuses these at admission + self.assertEqual(self.run_action(action="exportGltf", **case)["status"], "denied", case) cases = [ - {"filepath": "a.obj"}, {"filepath": "a"}, {"filepath": ""}, {"filepath": 5}, + {"filepath": "a.obj"}, {"filepath": "a"}, {"filepath": ""}, {"filepath": "../a.glb"}, {"filepath": str(self.root / "a.glb")}, {"filepath": "taken.glb"}, {"filepath": "a.glb", "selection": ["Nope"]}, {"filepath": "a.glb", "selection": ["Cube", "Nope"]}, - {"filepath": "a.glb", "selection": []}, - {"filepath": "a.glb", "selection": "Cube"}, - {"filepath": "a.glb", "selection": [3]}, - {"filepath": "a.glb", "extras": "yes"}, - {"filepath": "a.glb", "yUp": 1}, - {"filepath": "a.glb", "applyModifiers": None}, ] for case in cases: self.assertEqual(self.run_action(action="exportGltf", **case)["status"], "failed", case) @@ -527,7 +517,7 @@ class ActionTests(unittest.TestCase): # renderStill def test_render_still_writes_inside_output_dir_and_restores_settings(self): - receipt = self.run_action(action="renderStill", outputPath="shots/a.png", engine="cycles", + receipt = self.run_action(action="renderStill", outputPath="shots/a.png", engine="CYCLES", resolutionX=640, resolutionY=360, cameraName="Cam") self.assertEqual(receipt["status"], "accepted") engine, x, y, filepath, fmt, camera = self.bpy.rendered[0] @@ -547,10 +537,13 @@ class ActionTests(unittest.TestCase): self.assertEqual(self.bpy.scene.render.engine, "BLENDER_EEVEE") def test_render_still_outside_the_output_dir_or_with_bad_input_never_renders(self): + for case in ({"outputPath": "a.png", "resolutionX": 0}, {"outputPath": "a.png", "resolutionX": 3}, + {"outputPath": "a.png", "resolutionX": 99999}, {"outputPath": "a.png", "resolutionX": 10.5}, + {"outputPath": "a.png", "engine": ""}, {"outputPath": "a.png", "resolutionY": "x"}): + self.assertEqual(self.run_action(action="renderStill", **case)["status"], "denied", case) cases = [{"outputPath": "../a.png"}, {"outputPath": str(self.root / "a.png")}, {"outputPath": "a.txt"}, - {"outputPath": ""}, {"outputPath": "a.png", "engine": "NOPE"}, - {"outputPath": "a.png", "resolutionX": 0}, {"outputPath": "a.png", "resolutionX": 99999}, - {"outputPath": "a.png", "resolutionX": 10.5}, {"outputPath": "a.png", "cameraName": "Lamp"}] + {"outputPath": ""}, {"outputPath": "a.png", "engine": "NOPE"}, {"outputPath": "a.png", "engine": "cycles"}, + {"outputPath": "a.png", "cameraName": "Lamp"}] for case in cases: self.assertEqual(self.run_action(action="renderStill", **case)["status"], "failed", case) self.assertEqual(self.bpy.rendered, []) @@ -563,35 +556,38 @@ class ActionTests(unittest.TestCase): receipt = self.run_action(action="createObject", objectType=kind, name="N") self.assertEqual(receipt["status"], "accepted", kind) self.assertEqual(self.bpy.created[-1][0], kind) - self.assertEqual(self.run_action(action="createObject", objectType="MESH", meshType="cube")["status"], "accepted") + self.assertEqual(self.run_action(action="createObject", objectType="MESH", meshType="CUBE")["status"], "accepted") - def test_create_object_refuses_other_types_naming_the_type_and_the_allowed_set(self): - for kind in ("TEXT", "CURVE", "mesh", "", None, 3): + def test_create_object_refuses_other_types_naming_the_field_and_the_allowed_set(self): + for kind in ("TEXT", "CURVE", "mesh", ""): receipt = self.run_action(action="createObject", objectType=kind) - self.assertEqual(receipt["status"], "failed", kind) - for allowed in ("MESH", "LIGHT", "CAMERA", "EMPTY"): - self.assertIn(allowed, receipt["message"]) - self.assertIn(repr(kind) if not isinstance(kind, str) else kind, receipt["message"]) + self.assertEqual(receipt["status"], "denied", kind) + self.assertEqual(receipt["message"], "objectType must be one of MESH, LIGHT, CAMERA, EMPTY.") + receipt = self.run_action(action="createObject", objectType=3) + self.assertEqual((receipt["status"], receipt["message"]), ("denied", "objectType must be a string.")) self.assertEqual(self.bpy.created, []) + self.assertEqual(self.run_action(action="createObject", objectType=None)["status"], "accepted") # null is absent: EMPTY + self.assertEqual(self.bpy.created[-1][0], "EMPTY") def test_create_object_refuses_a_mesh_type_other_than_cube(self): - for mesh_type in ("CYLINDER", "", 1, " CUBE", "CUBE "): + for mesh_type in ("CYLINDER", "", 1, " CUBE", "CUBE ", "cube"): receipt = self.run_action(action="createObject", objectType="MESH", meshType=mesh_type) - self.assertEqual(receipt["status"], "failed", mesh_type) - self.assertIn("CUBE", receipt["message"]) + self.assertEqual(receipt["status"], "denied", mesh_type) + self.assertIn("meshType must be", receipt["message"]) self.assertEqual(self.bpy.created, []) def test_mesh_type_on_a_non_mesh_object_is_refused_not_ignored(self): for object_type in ("LIGHT", "EMPTY", "CAMERA"): - receipt = self.run_action(action="createObject", objectType=object_type, meshType="CYLINDER") - self.assertEqual(receipt["status"], "failed", object_type) - self.assertIn("MESH", receipt["message"]) + receipt = self.run_action(action="createObject", objectType=object_type, meshType="CUBE") + self.assertEqual(receipt["status"], "denied", object_type) + self.assertEqual(receipt["message"], "meshType applies only when objectType is one of MESH.") + self.assertEqual(self.run_action(action="createObject", meshType="CUBE")["status"], "denied") # objectType absent is EMPTY self.assertEqual(self.bpy.created, []) # renderStill: GPU engines that would abort a headless Blender def test_render_still_refuses_gpu_engines_headless_when_a_test_render_fails(self): self.bpy.app.background = True - for engine in ("BLENDER_WORKBENCH", "BLENDER_EEVEE", "BLENDER_EEVEE_NEXT", "blender_workbench"): + for engine in ("BLENDER_WORKBENCH", "BLENDER_EEVEE", "BLENDER_EEVEE_NEXT"): self.bpy.scene.render.ENGINES = FakeRender.ENGINES + ("BLENDER_EEVEE_NEXT",) with mock.patch.object(bt, "gl_render_failure", return_value="a one-pixel test render exited with status 134"): receipt = self.run_action(action="renderStill", outputPath="a.png", engine=engine) @@ -844,10 +840,12 @@ class ActionTests(unittest.TestCase): def test_a_refused_render_leaves_no_folders_behind(self): (self.root / "out" / "taken").mkdir() (self.root / "out" / "taken" / "a.png").write_bytes(b"x") - for case in ({"outputPath": "new/deep/a.png", "resolutionX": 0}, {"outputPath": "new/deep/a.png", "engine": ""}, {"outputPath": "new/deep/a.png", "engine": "NOPE"}, + for case in ({"outputPath": "new/deep/a.png", "engine": "NOPE"}, {"outputPath": "new/deep/a.png", "cameraName": "Nope"}, {"outputPath": "new/deep/a.txt"}, {"outputPath": "taken/a.png"}): self.assertEqual(self.run_action(action="renderStill", **case)["status"], "failed", case) + for case in ({"outputPath": "new/deep/a.png", "resolutionX": 0}, {"outputPath": "new/deep/a.png", "engine": ""}): + self.assertEqual(self.run_action(action="renderStill", **case)["status"], "denied", case) self.assertIn("already exists", self.run_action(action="renderStill", outputPath="taken/a.png")["message"]) self.assertEqual(sorted(p.name for p in (self.root / "out").iterdir()), ["taken"]) self.assertEqual(self.bpy.rendered, []) From 90695765513b349537a260c4614bc2f295eab03a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 02:51:35 +0100 Subject: [PATCH 36/63] brokkr-ctl: embed the action table for send --help and pre-validation brokkr-ctl/src/actions.rs include_str!s the add-on's actions.json, reads entries as data (serde_json Value, no generated types) and implements the same vocabulary and message text as action_table.py. `send --help` is built from it; `send` refuses an intent the table refuses with exit 1 and writes nothing; --set refuses the table's envelope names. Deleted: the hand-written ACTIONS/Field help table, RESERVED, the letters-and-digits action check and the source-scraping drift test. The shared fixture action_cases.json (231 cases) is run by both validators. Co-Authored-By: Claude Sonnet 5.5 --- brokkr-ctl/src/actions.rs | 456 ++++++++++++++++++++++++++++++++++++++ brokkr-ctl/src/blender.rs | 198 +---------------- brokkr-ctl/src/main.rs | 1 + brokkr-ctl/tests/cli.rs | 103 +++++++-- 4 files changed, 544 insertions(+), 214 deletions(-) create mode 100644 brokkr-ctl/src/actions.rs diff --git a/brokkr-ctl/src/actions.rs b/brokkr-ctl/src/actions.rs new file mode 100644 index 0000000..590b29c --- /dev/null +++ b/brokkr-ctl/src/actions.rs @@ -0,0 +1,456 @@ +//! The Blender action table, embedded: `send --help` is built from it and `send` refuses an intent it +//! refuses. The owner is the add-on's `actions.json` (schema brokkr.blender.actions.v0); this module reads +//! it as data and implements the same vocabulary and message text as `action_table.py`, pinned to it by +//! the shared fixture `surfaces/blender/tests/action_cases.json`. Anything that reaches the store is still +//! decided by the add-on. + +use serde_json::{Map, Value}; +use std::sync::LazyLock; + +const TABLE_JSON: &str = include_str!("../../surfaces/blender/brokkr_bridge/actions.json"); + +static TABLE: LazyLock = + LazyLock::new(|| serde_json::from_str(TABLE_JSON).expect("actions.json is valid JSON")); + +pub fn table() -> &'static Value { + &TABLE +} + +fn actions() -> &'static [Value] { + table()["actions"].as_array().map_or(&[], Vec::as_slice) +} + +fn entry(name: &str) -> Option<&'static Value> { + actions().iter().find(|a| a["name"] == name) +} + +/// The names brokkr-ctl writes itself: `--set` cannot name them, and the table does not validate them. +pub fn envelope() -> Vec<&'static str> { + table()["envelope"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect() +} + +fn type_words(kind: &str) -> &'static str { + match kind { + "string" => "a string", + "number" => "a finite number", + "integer" => "a whole number", + "boolean" => "true or false", + "array" => "an array", + "object" => "an object", + _ => "a value", + } +} + +fn join(items: &Value) -> String { + items + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect::>() + .join(", ") +} + +/// A bound as messages and help print it: whole values without a fraction, others as the shortest digits. +pub fn number_text(value: f64) -> String { + if value == value.trunc() { + format!("{}", value as i128) + } else { + format!("{value}") + } +} + +/// Refuses an intent the table refuses, with the add-on's message; nothing is normalized (the add-on fills defaults). +pub fn validate(command: &Map) -> Result<(), String> { + let action = command.get("action").and_then(Value::as_str).unwrap_or(""); + let Some(row) = entry(action) else { + return Err(format!("Unsupported Blender command action: {action}")); + }; + let present: Map = command + .iter() + .filter(|(_, v)| !v.is_null()) + .map(|(k, v)| (k.clone(), v.clone())) + .collect(); + fields( + row["fields"].as_array().map_or(&[], Vec::as_slice), + &present, + None, + action, + &envelope(), + ) +} + +fn fields( + specs: &[Value], + values: &Map, + parent: Option<&str>, + whole: &str, + skip: &[&str], +) -> Result<(), String> { + let declared: Vec<&str> = specs.iter().filter_map(|s| s["name"].as_str()).collect(); + let mut unknown: Vec<&String> = values + .keys() + .filter(|k| !skip.contains(&k.as_str()) && !declared.contains(&k.as_str())) + .collect(); + unknown.sort(); + if let Some(key) = unknown.first() { + let listed = if declared.is_empty() { + "none".to_string() + } else { + declared.join(", ") + }; + return Err(format!( + "{whole} has no field '{key}'; its fields: {listed}." + )); + } + for spec in specs { + let name = spec["name"].as_str().unwrap_or(""); + let path = parent.map_or_else(|| name.to_string(), |p| format!("{p}.{name}")); + let Some(value) = values.get(name) else { + if spec["required"] == true { + return Err(format!("{path} is required.")); + } + continue; + }; + if let Some(only) = spec.get("only") { + let sibling = only["field"].as_str().and_then(|f| values.get(f)); + let allowed = only["in"].as_array().map_or(&[][..], Vec::as_slice); + if !sibling.is_some_and(|v| allowed.contains(v)) { + return Err(format!( + "{path} applies only when {} is one of {}.", + only["field"].as_str().unwrap_or(""), + join(&only["in"]) + )); + } + } + check_value(spec, value, &path)?; + } + Ok(()) +} + +fn check_value(spec: &Value, value: &Value, path: &str) -> Result<(), String> { + let kind = spec["type"].as_str().unwrap_or(""); + match kind { + "any" => {} + "number" | "integer" => check_number(spec, value, path, kind)?, + "string" => { + let Some(text) = value.as_str() else { + return Err(format!("{path} must be {}.", type_words(kind))); + }; + if let Some(allowed) = spec.get("enum") { + if !allowed + .as_array() + .is_some_and(|list| list.iter().any(|e| e.as_str() == Some(text))) + { + return Err(format!("{path} must be one of {}.", join(allowed))); + } + } else { + check_string(spec, text, path)?; + } + } + "boolean" => { + if !value.is_boolean() { + return Err(format!("{path} must be {}.", type_words(kind))); + } + } + "array" => { + let Some(items) = value.as_array() else { + return Err(format!("{path} must be {}.", type_words(kind))); + }; + if spec["minItems"] + .as_u64() + .is_some_and(|n| (items.len() as u64) < n) + { + return Err(format!( + "{path} must have at least {} items.", + spec["minItems"] + )); + } + if spec["maxItems"] + .as_u64() + .is_some_and(|n| (items.len() as u64) > n) + { + return Err(format!( + "{path} must have at most {} items.", + spec["maxItems"] + )); + } + let item_spec = &spec["items"]; + for (index, item) in items.iter().enumerate() { + if item.is_null() { + return Err(format!( + "{path}[{index}] must be {}.", + type_words(item_spec["type"].as_str().unwrap_or("")) + )); + } + check_value(item_spec, item, &format!("{path}[{index}]"))?; + } + } + "object" => { + let Some(map) = value.as_object() else { + return Err(format!("{path} must be {}.", type_words(kind))); + }; + if let Some(properties) = spec["properties"].as_array() { + let present: Map = map + .iter() + .filter(|(_, v)| !v.is_null()) + .map(|(k, v)| (k.clone(), v.clone())) + .collect(); + fields(properties, &present, Some(path), path, &[])?; + } + } + _ => {} + } + Ok(()) +} + +fn check_number(spec: &Value, value: &Value, path: &str, kind: &str) -> Result<(), String> { + let wrong = || format!("{path} must be {}.", type_words(kind)); + let Value::Number(number) = value else { + return Err(wrong()); + }; + let x = number + .as_f64() + .filter(|x| x.is_finite()) + .ok_or_else(wrong)?; + if kind == "integer" && !(number.is_i64() || number.is_u64() || x == x.trunc()) { + return Err(wrong()); + } + let (min, max) = ( + spec["minimum"].as_f64().unwrap_or(f64::MIN), + spec["maximum"].as_f64().unwrap_or(f64::MAX), + ); + if x < min || x > max { + return Err(format!( + "{path} must be between {} and {}.", + number_text(min), + number_text(max) + )); + } + Ok(()) +} + +fn check_string(spec: &Value, text: &str, path: &str) -> Result<(), String> { + let length = text.chars().count() as u64; + if spec["minLength"].as_u64().is_some_and(|n| length < n) { + return Err(format!( + "{path} must have at least {} characters.", + spec["minLength"] + )); + } + if spec["maxLength"].as_u64().is_some_and(|n| length > n) { + return Err(format!( + "{path} must have at most {} characters.", + spec["maxLength"] + )); + } + if let Some(name) = spec["chars"].as_str() { + let set = &table()["charsets"][name]; + let allowed = set["allowed"].as_str().unwrap_or(""); + if text.chars().any(|c| !allowed.contains(c)) { + return Err(format!( + "{path} may contain only {}.", + set["text"].as_str().unwrap_or("") + )); + } + } + if let Some(prefixes) = spec["prefixes"].as_array() { + let fits = prefixes + .iter() + .filter_map(Value::as_str) + .any(|p| text.starts_with(p) && text.chars().count() > p.chars().count()); + if !fits { + return Err(format!( + "{path} must start with one of {} and have at least one more character.", + join(&spec["prefixes"]) + )); + } + } + for part in spec["forbid"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + { + if text.contains(part) { + return Err(format!("{path} may not contain '{part}'.")); + } + } + Ok(()) +} + +/// The actions section of `send --help`: every action with its fields, built from the table. +pub fn help() -> String { + let mut text = String::new(); + for action in actions() { + text.push_str(&format!( + " {}: {}\n", + action["name"].as_str().unwrap_or(""), + action["doc"].as_str().unwrap_or("") + )); + field_lines( + &mut text, + action["fields"].as_array().map_or(&[], Vec::as_slice), + 6, + ); + } + text +} + +fn field_lines(text: &mut String, specs: &[Value], indent: usize) { + for spec in specs { + let mut line = format!( + "{}{}: {}", + " ".repeat(indent), + spec["name"].as_str().unwrap_or(""), + describe(spec) + ); + if spec["required"] == true { + line.push_str(", required"); + } + if let Some(default) = spec.get("default") { + line.push_str(&format!(", default {default}")); + } + if let Some(only) = spec.get("only") { + line.push_str(&format!( + ", only when {} is {}", + only["field"].as_str().unwrap_or(""), + join(&only["in"]).replace(", ", "|") + )); + } + if let Some(doc) = spec["doc"].as_str() { + line.push_str(&format!(" ({doc})")); + } + text.push_str(&line); + text.push('\n'); + if let Some(properties) = spec["items"]["properties"].as_array() { + field_lines(text, properties, indent + 4); + } + } +} + +fn describe(spec: &Value) -> String { + let kind = spec["type"].as_str().unwrap_or(""); + let mut parts = vec![match kind { + "any" => "json".to_string(), + "boolean" => "bool".to_string(), + other => other.to_string(), + }]; + if let Some(values) = spec.get("enum") { + parts.push(join(values).replace(", ", "|")); + } + if let (Some(min), Some(max)) = (spec["minimum"].as_f64(), spec["maximum"].as_f64()) { + parts.push(format!("{}..{}", number_text(min), number_text(max))); + } + if spec.get("minLength").is_some() || spec.get("maxLength").is_some() { + let min = spec["minLength"].as_u64().unwrap_or(0); + parts.push(match spec["maxLength"].as_u64() { + Some(max) => format!("{min}..{max} characters"), + None => format!("at least {min} characters"), + }); + } + if let Some(name) = spec["chars"].as_str() { + parts.push( + table()["charsets"][name]["text"] + .as_str() + .unwrap_or("") + .to_string(), + ); + } + if spec.get("prefixes").is_some() { + parts.push(format!( + "starts with {}", + join(&spec["prefixes"]).replace(", ", "|") + )); + } + if spec.get("forbid").is_some() { + parts.push(format!( + "without {}", + join(&spec["forbid"]).replace(", ", "|") + )); + } + if kind == "array" { + let (min, max) = (spec["minItems"].as_u64(), spec["maxItems"].as_u64()); + let count = match (min, max) { + (Some(a), Some(b)) if a == b => format!("{a} items"), + (Some(a), Some(b)) => format!("{a}..{b} items"), + (Some(a), None) => format!("at least {a} items"), + (None, Some(b)) => format!("at most {b} items"), + (None, None) => String::new(), + }; + parts.push(format!("[{}]", describe(&spec["items"]))); + if !count.is_empty() { + parts.push(count); + } + } + parts.join(" ") +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The same cases the add-on's test_action_table runs through action_table.py: one table, two + /// interpreters, one set of messages. + #[test] + fn the_parity_fixture_yields_the_add_ons_messages() { + let cases: Vec = serde_json::from_str(include_str!( + "../../surfaces/blender/tests/action_cases.json" + )) + .unwrap(); + assert!(cases.len() > 200, "{} cases", cases.len()); + let mut wrong = Vec::new(); + for case in &cases { + let mut command = case["fields"].as_object().unwrap().clone(); + command.insert("action".into(), case["action"].clone()); + let got = validate(&command).err().unwrap_or_else(|| "ok".to_string()); + if Some(got.as_str()) != case["expect"].as_str() { + wrong.push(format!( + "{} {} expected {} got {got}", + case["action"], case["fields"], case["expect"] + )); + } + } + assert!( + wrong.is_empty(), + "{} of {} differ:\n{}", + wrong.len(), + cases.len(), + wrong.join("\n") + ); + } + + #[test] + fn a_non_string_action_is_unsupported_and_the_envelope_is_the_tables() { + let mut command = Map::new(); + command.insert("action".into(), Value::from(3)); + assert_eq!( + validate(&command).unwrap_err(), + "Unsupported Blender command action: " + ); + assert_eq!( + envelope(), + ["schema", "commandId", "action", "requestedBy", "note"] + ); + } + + #[test] + fn numbers_print_the_way_the_add_on_prints_them() { + for (value, text) in [ + (0.0, "0"), + (4.0, "4"), + (1e7, "10000000"), + (0.001, "0.001"), + (0.0001, "0.0001"), + (1e9, "1000000000"), + (-1e9, "-1000000000"), + ] { + assert_eq!(number_text(value), text); + } + } +} diff --git a/brokkr-ctl/src/blender.rs b/brokkr-ctl/src/blender.rs index 9bb89d1..e404585 100644 --- a/brokkr-ctl/src/blender.rs +++ b/brokkr-ctl/src/blender.rs @@ -2,6 +2,7 @@ //! document per `send` and reads receipts and the host snapshot. The add-on decides. use anyhow::{Context, Result, anyhow, bail}; +use crate::actions; use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, SingleFileMessagePackBackingStore}; use serde_json::{Map, Value}; use std::path::PathBuf; @@ -14,7 +15,6 @@ pub const SNAPSHOT_SCHEMA: &str = "brokkr.blender.host_snapshot.v0"; const INTENT_PREFIX: &str = "blender/commands/"; const RECEIPT_PREFIX: &str = "blender/receipts/"; const SNAPSHOT_KEY: &str = "blender/host/current"; -const RESERVED: [&str; 5] = ["schema", "commandId", "action", "requestedBy", "note"]; const DEFAULT_TIMEOUT_SECS: u64 = 60; const POLL: Duration = Duration::from_millis(200); const MAX_TIMEOUT: Duration = Duration::from_secs(24 * 3600); @@ -215,15 +215,12 @@ fn build_intent( note: &str, sets: &[String], ) -> Result { - if action.is_empty() || !action.chars().all(|c| c.is_ascii_alphanumeric()) { - bail!("action must be letters and digits, e.g. createObject"); - } let mut map = Map::new(); for set in sets { let (key, raw) = set .split_once('=') .ok_or_else(|| anyhow!("--set wants key=json, got {set:?}"))?; - if key.is_empty() || RESERVED.contains(&key) { + if key.is_empty() || actions::envelope().contains(&key) { bail!("--set cannot name {key:?}: it is written by brokkr-ctl"); } let value: Value = serde_json::from_str(raw) @@ -235,6 +232,7 @@ fn build_intent( map.insert("action".into(), action.into()); map.insert("requestedBy".into(), requested_by.into()); map.insert("note".into(), note.into()); + actions::validate(&map).map_err(|message| anyhow!(message))?; Ok(Value::Object(map)) } @@ -414,8 +412,8 @@ brokkr-ctl blender: send typed intents to the live Blender add-on and read what Every command needs --store or $BROKKR_BLENDER_STORE (the add-on's .ccmp). send needs $EUREKA_INSTANCE and --agent or $BROKKR_AGENT; requestedBy is '/'. Output is 'key: value' lines. Exit: 0 accepted, 2 denied or failed, 3 stopped, 4 timeout, -1 usage or store error. brokkr-ctl validates nothing about an action: the add-on does, and -its refusal comes back in the receipt. +1 usage or store error. send refuses an intent the action table refuses (exit 1, nothing written); +the add-on decides the rest and its refusal comes back in the receipt. " .to_string() } @@ -426,196 +424,16 @@ pub fn send_help() -> String { brokkr-ctl blender send [--set key=json]... [--note text] [--agent name] [--no-wait] [--timeout secs] --set takes JSON: --set objectType='\"MESH\"' --set location='[0,0,1]'. brokkr-ctl writes schema, -commandId, action, requestedBy and note itself; --set cannot name them. Fields below are what the -add-on reads; it validates them and refuses in the receipt. Targets also accept objectName. +commandId, action, requestedBy and note itself; --set cannot name them. Below is the add-on's action +table (actions.json): every field an action reads; null means absent; a field not listed is refused. actions: ", ); - for (action, fields) in ACTIONS { - text.push_str(&format!(" {action}\n")); - for (name, kind, note) in *fields { - text.push_str(&format!(" {name}: {kind} {note}\n")); - } - } + text.push_str(&actions::help()); text } -type Field = (&'static str, &'static str, &'static str); - -/// Help text only: what the add-on's `execute_command` dispatches and reads at the base commit. -const ACTIONS: &[(&str, &[Field])] = &[ - ( - "createObject", - &[ - ("objectType", "string", "MESH | LIGHT | CAMERA | EMPTY (default EMPTY)"), - ("name", "string", ""), - ("location", "[x,y,z]", ""), - ("size", "number", "MESH"), - ("meshType", "string", "CUBE"), - ("lightType", "string", "LIGHT"), - ("emptyDisplayType", "string", "EMPTY"), - ], - ), - ("deleteObject", &[("targetObjectName", "string", "")]), - ( - "setObjectTransform", - &[ - ("targetObjectName", "string", ""), - ("location", "[x,y,z]", ""), - ("rotationEuler", "[x,y,z]", "radians"), - ("scale", "[x,y,z]", ""), - ], - ), - ( - "setObjectVisibility", - &[("targetObjectName", "string", ""), ("visible", "bool", "")], - ), - ( - "setObjectParent", - &[ - ("targetObjectName", "string", ""), - ("parentObjectName", "string", "empty clears the parent"), - ], - ), - ( - "setObjectCustomProperty", - &[ - ("targetObjectName", "string", ""), - ("propertyName", "string", ""), - ("value", "json", ""), - ], - ), - ( - "selectObject", - &[("targetObjectName", "string", ""), ("clearSelection", "bool", "default true")], - ), - ( - "assignMaterial", - &[ - ("targetObjectName", "string", ""), - ("materialName", "string", ""), - ("color", "[r,g,b] or [r,g,b,a]", "linear, 0..1"), - ], - ), - ( - "importGltf", - &[("filepath", "string", "inside the add-on's import directory")], - ), - ( - "exportGltf", - &[ - ("filepath", "string", ".glb or .gltf inside the add-on's output directory"), - ("extras", "bool", ""), - ("yUp", "bool", ""), - ("applyModifiers", "bool", ""), - ("selection", "[string]", "object names"), - ], - ), - ( - "setCamera", - &[ - ("targetObjectName", "string", ""), - ("lens", "number", "mm"), - ("cameraType", "string", ""), - ("orthoScale", "number", ""), - ("clipStart", "number", ""), - ("clipEnd", "number", ""), - ("panoramaType", "string", ""), - ("active", "bool", "make it the scene camera"), - ], - ), - ( - "setLight", - &[ - ("targetObjectName", "string", ""), - ("energy", "number", ""), - ("color", "[r,g,b]", "linear, 0..1"), - ("lightType", "string", ""), - ], - ), - ( - "setWorld", - &[ - ("worldName", "string", ""), - ("color", "[r,g,b]", "linear, 0..1"), - ("strength", "number", ""), - ], - ), - ( - "renderStill", - &[ - ("outputPath", "string", "inside the add-on's output directory"), - ("engine", "string", ""), - ("resolutionX", "integer", ""), - ("resolutionY", "integer", ""), - ("cameraName", "string", ""), - ], - ), - ("look", &[]), - ( - "createNodeGroup", - &[ - ("treeKey", "string", ""), - ("interface", "[{inOut,name,type,default?}]", "types: Geometry Float Int Bool Vector"), - ], - ), - ( - "addNode", - &[ - ("treeKey", "string", ""), - ("id", "string", "brokkr's key for the node"), - ("blIdname", "string", "GeometryNode*, FunctionNode* or ShaderNode*"), - ("location", "[x,y]", ""), - ("label", "string", ""), - ("properties", "object", "enum, bool, int or float node settings"), - ("inputs", "object", "unlinked input defaults"), - ], - ), - ("removeNode", &[("treeKey", "string", ""), ("id", "string", "")]), - ( - "linkSockets", - &[ - ("treeKey", "string", ""), - ("fromNode", "string", ""), - ("fromSocket", "string", ""), - ("toNode", "string", ""), - ("toSocket", "string", ""), - ], - ), - ( - "unlinkSockets", - &[ - ("treeKey", "string", ""), - ("toNode", "string", ""), - ("toSocket", "string", ""), - ("fromNode", "string", "optional"), - ("fromSocket", "string", "optional"), - ], - ), - ( - "addModifier", - &[ - ("objectName", "string", ""), - ("treeKey", "string", ""), - ("modifierName", "string", "default Brokkr GeoNodes"), - ], - ), - ( - "removeModifier", - &[("objectName", "string", ""), ("modifierName", "string", "")], - ), - ( - "setModifierInput", - &[ - ("objectName", "string", ""), - ("modifierName", "string", ""), - ("socket", "string", "identifier or unique interface name"), - ("value", "json", "Float, Int, Bool or Vector"), - ], - ), -]; - #[cfg(test)] mod tests { use super::*; diff --git a/brokkr-ctl/src/main.rs b/brokkr-ctl/src/main.rs index 1fc3dd8..41f1afc 100644 --- a/brokkr-ctl/src/main.rs +++ b/brokkr-ctl/src/main.rs @@ -1,5 +1,6 @@ //! brokkr-ctl: command-line hands for Brokkr's creative-tool surfaces. +mod actions; mod blender; fn main() { diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs index a7293e1..59d0444 100644 --- a/brokkr-ctl/tests/cli.rs +++ b/brokkr-ctl/tests/cli.rs @@ -383,36 +383,91 @@ fn status_prints_the_snapshot_summary() { } } -/// A pin, not a copy: every action the add-on dispatches is in `send --help`, and every help field -/// name is a string the add-on source mentions. The add-on has no machine-readable action table. +fn table() -> Value { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../surfaces/blender/brokkr_bridge/actions.json"); + serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap() +} + +fn bound(value: &Value) -> String { + let x = value.as_f64().unwrap(); + if x == x.trunc() { format!("{}", x as i64) } else { format!("{x}") } +} + +fn every_name(specs: &Value, out: &mut Vec) { + for spec in specs.as_array().unwrap() { + out.push(spec["name"].as_str().unwrap().to_string()); + if let Some(values) = spec["enum"].as_array() { + out.extend(values.iter().map(|v| v.as_str().unwrap().to_string())); + } + if let (Some(min), Some(max)) = (spec.get("minimum"), spec.get("maximum")) { + out.push(format!("{}..{}", bound(min), bound(max))); + } + if let Some(items) = spec.get("items") { + if let (Some(min), Some(max)) = (items.get("minimum"), items.get("maximum")) { + out.push(format!("{}..{}", bound(min), bound(max))); + } + if let Some(properties) = items.get("properties") { + every_name(properties, out); + } + } + } +} + +/// Help is the embedded table, not a copy: every action, field, enum value and bound in actions.json is +/// in `send --help`, and the help lists no action the table does not have. #[test] -fn help_names_every_dispatched_action_and_only_fields_the_addon_mentions() { - let addon = Path::new(env!("CARGO_MANIFEST_DIR")).join("../surfaces/blender/brokkr_bridge"); - let source: String = ["blender_target.py", "node_actions.py", "scene_actions.py"] - .iter() - .map(|file| std::fs::read_to_string(addon.join(file)).unwrap()) - .collect(); +fn help_names_every_action_field_enum_value_and_bound_of_the_table() { let help = stdout( &Command::new(env!("CARGO_BIN_EXE_brokkr-ctl")).args(["blender", "send", "--help"]).output().unwrap(), ); - let mut dispatched: Vec = source - .lines() - .filter_map(|line| line.trim().strip_prefix("if action == \"")) - .filter_map(|rest| rest.split('"').next()) - .map(String::from) - .collect(); - let actions_line = source.lines().find(|l| l.trim_start().starts_with("ACTIONS = (\"")).unwrap(); - dispatched.extend(actions_line.split('"').skip(1).step_by(2).map(String::from)); - assert!(dispatched.len() >= 20, "{dispatched:?}"); - let listed: Vec<&str> = help.lines().filter_map(|l| l.strip_prefix(" ")).filter(|l| !l.starts_with(' ')).collect(); - for action in &dispatched { - assert!(listed.contains(&action.as_str()), "help lacks {action}"); + let table = table(); + let mut listed = Vec::new(); + for action in table["actions"].as_array().unwrap() { + let name = action["name"].as_str().unwrap(); + assert!(help.lines().any(|l| l.starts_with(&format!(" {name}: "))), "help lacks {name}"); + let mut wanted = Vec::new(); + every_name(&action["fields"], &mut wanted); + let section: Vec<&str> = help + .lines() + .skip_while(|l| !l.starts_with(&format!(" {name}: "))) + .skip(1) + .take_while(|l| l.starts_with(" ")) + .collect(); + let section = section.join(" +"); + for word in wanted { + assert!(section.contains(&word), "{name}: help lacks {word} +{section}"); + } + listed.push(name.to_string()); } - for action in &listed { - assert!(dispatched.iter().any(|d| d == action) || *action == "actions:", "help lists unknown {action}"); + for line in help.lines().filter(|l| l.starts_with(" ") && !l.starts_with(" ")) { + let name = line.trim().split(':').next().unwrap(); + assert!(listed.iter().any(|a| a == name), "help lists unknown {name}"); } - for field in help.lines().filter_map(|l| l.strip_prefix(" ")).filter_map(|l| l.split(':').next()) { - assert!(source.contains(&format!("\"{field}\"")), "add-on never mentions {field}"); + assert!(help.contains("cameraType: string PERSP|ORTHO|PANO"), "{help}"); + assert!(help.contains("resolutionX: integer 4..16384"), "{help}"); +} + +#[test] +fn an_intent_the_table_refuses_exits_1_and_writes_nothing() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("seed", "accepted")]); + let before = std::fs::read(&path).unwrap(); + let cases: [(&[&str], &str); 5] = [ + (&["send", "setCamera", "--set", "targetObjectName=\"Cam\"", "--set", "cameraType=\"CUSTOM\""], "cameraType must be one of PERSP, ORTHO, PANO."), + (&["send", "renderStill", "--set", "outputPath=\"a.png\"", "--set", "resolutionX=2"], "resolutionX must be between 4 and 16384."), + (&["send", "createObject", "--set", "bogus=1"], "createObject has no field 'bogus'"), + (&["send", "runPython"], "Unsupported Blender command action: runPython"), + (&["send", "deleteObject"], "targetObjectName is required."), + ]; + for (args, message) in cases { + let mut args = args.to_vec(); + args.extend(["--agent", "hands", "--no-wait"]); + let output = ctl(&path, &args, Some("nibu")); + assert_eq!(output.status.code(), Some(1), "{args:?}"); + assert!(String::from_utf8_lossy(&output.stderr).contains(message), "{args:?}: {}", String::from_utf8_lossy(&output.stderr)); + assert_eq!(std::fs::read(&path).unwrap(), before, "{args:?} wrote to the store"); } } From caf4b343626127caa055934c77b490159eb066d2 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 02:53:03 +0100 Subject: [PATCH 37/63] Blender add-on: the drain claims an intent before it runs (at most once) drain_commands deleted the intent after writing its receipt, so a failed receipt write or a crash left an intent on the queue to run again. It now deletes the intent from the node first, then runs it, then writes the receipt; a receipt whose write raises is held (with its key suffix) and written first on the next drain, never read as truth. A delete that raises runs nothing and leaves the intent queued. Stop keeps receipt-then-delete: it runs nothing, so a re-stop cannot re-run an intent. A crash between claim and receipt loses the intent (the sender's wait times out, exit 4) rather than running it twice. Co-Authored-By: Claude Sonnet 5.5 --- .../blender/brokkr_bridge/blender_target.py | 20 ++++- surfaces/blender/tests/test_agent_turn.py | 73 ++++++++++++++++++- surfaces/blender/tests/test_stop_presence.py | 2 +- 3 files changed, 89 insertions(+), 6 deletions(-) diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index fab5357..4ab155d 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -121,6 +121,7 @@ class BrokkrBlenderTarget: self.agent_turn = False # true only inside run_intent self._wrote = True # run_intent: false when an accepted action changed nothing self._receipted: set[str] = set() + self._unsent: list[tuple[dict[str, Any], str]] = [] # receipts whose write failed: written first on the next drain, never read as truth self._recent: deque[dict[str, Any]] = deque(maxlen=RECEIPTS_KEPT) # display cache of the node's receipts self._receipts_loaded = False self.pending_count = 0 # display cache: intents queued in the node @@ -167,8 +168,15 @@ class BrokkrBlenderTarget: debug_mirror_root: str = "", limit: int | None = None, ) -> list[dict[str, Any]]: - """Run queued intents, oldest key first: all of them, or at most `limit`, the rest staying queued.""" + """Run queued intents, oldest key first: all of them, or at most `limit`, the rest staying queued. + + At most once: an intent is deleted from the node before it runs, so a failed receipt write or a + crash can never run it again. A receipt that could not be written is held and written first on + the next drain; the intent is not on the queue to be re-run.""" node, documents = self._open_node(cache_path, cultlib_py_src) + for receipt, suffix in list(self._unsent): + self.publish_receipt(cache_path, cultlib_py_src, receipt, debug_mirror_root, key_suffix=suffix) + self._unsent.pop(0) snapshot = node.database.snapshot() commands = snapshot.get(COMMAND_INTENT_SCHEMA, {}) receipts: list[dict[str, Any]] = [] @@ -178,6 +186,7 @@ class BrokkrBlenderTarget: command_id = command.get("commandId") valid = _valid_command_id(command_id) reused = valid and command_id in self._receipted + node.database.delete(documents["command_intent"], command_key) # claimed: nothing below can run it twice receipt = self.run_intent(context, command) if not valid: # No safe key exists for this id: the denial is receipted under a fresh key and names the @@ -185,10 +194,13 @@ class BrokkrBlenderTarget: receipt["message"] += f" (queue key {command_key})" # Receipts are write-once: a reused id's denial goes under '.denied', never over the # original. The sender learns of it by reading that key (and the drain's returned list). - self.publish_receipt(cache_path, cultlib_py_src, receipt, debug_mirror_root, - key_suffix=".denied" if reused else "") - node.database.delete(documents["command_intent"], command_key) + suffix = ".denied" if reused else "" receipts.append(receipt) + try: + self.publish_receipt(cache_path, cultlib_py_src, receipt, debug_mirror_root, key_suffix=suffix) + except Exception: + self._unsent.append((receipt, suffix)) + raise return receipts diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index 523e0cb..9f23465 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -236,8 +236,11 @@ class FakeNode: """The node database drain_commands reads: intents, receipts, and what it puts and deletes.""" def __init__(self, intents, receipts=()): self.docs = {bt.COMMAND_INTENT_SCHEMA: dict(intents), bt.COMMAND_RECEIPT_SCHEMA: dict(receipts)} + self.initial = sorted(intents) self.puts = [] self.deleted = [] + self.put_failures = 0 # the next n puts raise + self.delete_failures = 0 # the next n deletes raise self.database = self self.runtime_id = "fake" @@ -248,10 +251,19 @@ class FakeNode: return {k: dict(v) for k, v in self.docs.items()} def put(self, document, key, value): + if self.put_failures: + self.put_failures -= 1 + raise OSError("store write failed") self.puts.append((key, value)) + if key.startswith("blender/receipts/"): + self.docs[bt.COMMAND_RECEIPT_SCHEMA][key] = value def delete(self, document, key): + if self.delete_failures: + self.delete_failures -= 1 + raise OSError("store delete failed") self.deleted.append(key) + self.docs[bt.COMMAND_INTENT_SCHEMA].pop(key, None) class DrainTests(unittest.TestCase): @@ -273,7 +285,7 @@ class DrainTests(unittest.TestCase): "blender/commands/c-good": self.intent("good-1"), }) receipts = self.drain(node) # must not raise - self.assertEqual(sorted(node.deleted), sorted(node.docs[bt.COMMAND_INTENT_SCHEMA])) + self.assertEqual(sorted(node.deleted), node.initial) self.assertEqual([r["status"] for r in receipts], ["denied", "denied", "accepted"]) keys = [k for k, _ in node.puts] self.assertTrue(all(isinstance(k, str) and "[" not in k for k in keys), keys) @@ -298,6 +310,65 @@ class DrainTests(unittest.TestCase): self.assertEqual(denial["status"], "denied") self.assertEqual(sorted(node.deleted), ["blender/commands/a", "blender/commands/b"]) + # claim-first: an intent leaves the queue before it runs, so no failure can run it twice + def test_the_intent_is_deleted_before_its_handler_runs(self): + node = FakeNode({"blender/commands/a": self.intent("claim-1")}) + seen = [] + original = self.bpy.ops.object.empty_add + self.bpy.ops.object.empty_add = lambda *a, **kw: (seen.append(list(node.deleted)), original(*a, **kw))[1] + self.drain(node) + self.assertEqual(seen, [["blender/commands/a"]]) + self.assertEqual(node.puts[0][0], "blender/receipts/claim-1") + + def test_a_failed_receipt_write_is_held_and_written_next_drain_and_the_intent_never_reruns(self): + node = FakeNode({"blender/commands/a": self.intent("held-1")}) + node.put_failures = 1 + with self.assertRaises(OSError): + self.drain(node) + self.assertEqual(len(self.bpy.created), 1) + self.assertEqual(node.docs[bt.COMMAND_INTENT_SCHEMA], {}) + self.assertEqual(node.puts, []) + self.assertEqual(self.drain(node), []) # nothing queued: it runs nothing and writes the held receipt + self.assertEqual([k for k, _ in node.puts], ["blender/receipts/held-1"]) # not '.denied' + self.assertEqual(node.puts[0][1]["status"], "accepted") + self.assertEqual(len(self.bpy.created), 1) + self.assertEqual(self.drain(node), []) + self.assertEqual(len(node.puts), 1) # written once + + def test_a_held_receipt_survives_a_second_failed_write(self): + node = FakeNode({"blender/commands/a": self.intent("held-2")}) + node.put_failures = 2 + with self.assertRaises(OSError): + self.drain(node) + with self.assertRaises(OSError): + self.drain(node) + self.assertEqual(self.drain(node), []) + self.assertEqual([k for k, _ in node.puts], ["blender/receipts/held-2"]) + self.assertEqual(len(self.bpy.created), 1) + + def test_a_fresh_target_on_the_same_node_runs_nothing_after_a_failed_write(self): + node = FakeNode({"blender/commands/a": self.intent("fresh-1")}) + node.put_failures = 1 + with self.assertRaises(OSError): + self.drain(node) + fresh = bt.BrokkrBlenderTarget(self.bpy) + docs = {"command_intent": "i", "command_receipt": "r"} + with unittest.mock.patch.object(fresh, "_open_node", return_value=(node, docs)): + self.assertEqual(fresh.drain_commands(self.context, "cache", "src"), []) + self.assertEqual(len(self.bpy.created), 1) # the intent is gone from the queue: nothing re-ran it + + def test_a_delete_that_raises_runs_nothing_and_leaves_the_intent_queued(self): + node = FakeNode({"blender/commands/a": self.intent("keep-1")}) + node.delete_failures = 1 + with self.assertRaises(OSError): + self.drain(node) + self.assertEqual(self.bpy.created, []) + self.assertEqual(node.puts, []) + self.assertIn("blender/commands/a", node.docs[bt.COMMAND_INTENT_SCHEMA]) + receipts = self.drain(node) # the retry claims and runs it + self.assertEqual([r["status"] for r in receipts], ["accepted"]) + self.assertEqual(len(self.bpy.created), 1) + if __name__ == "__main__": unittest.main() diff --git a/surfaces/blender/tests/test_stop_presence.py b/surfaces/blender/tests/test_stop_presence.py index 4583ce0..5e732d9 100644 --- a/surfaces/blender/tests/test_stop_presence.py +++ b/surfaces/blender/tests/test_stop_presence.py @@ -52,7 +52,7 @@ class StopPendingTests(StopFixture): self.assertEqual(receipt["undoLabel"], "") self.assertEqual(receipt["action"], "createObject") self.assertEqual(receipts["blender/receipts/q-3"]["requestedBy"], "nibu/soul") - self.assertEqual(sorted(node.deleted), sorted(node.docs[bt.COMMAND_INTENT_SCHEMA])) + self.assertEqual(sorted(node.deleted), node.initial) self.assertEqual(self.bpy.created, []) # none dispatched self.assertEqual(self.bpy.undo.pushes, []) From 9d9c1178522b3463f62c68e84bcad3b0f393873f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 03:06:25 +0100 Subject: [PATCH 38/63] Action table: live proof in GUI Blender 5.3, live tests on the declared field names, docs point at the table tests/live/action_table.py (+ result): with the extension installed and the sink on, intents are queued as brokkr-ctl does and drained by the add-on's own timer. For all 23 actions of actions.json, 270 malformed intents generated from the table entries are each denied with no undo step and an unchanged scene (one undo reverts the canary before them); one valid intent per action is accepted and is exactly one undo step exactly when changesScene says so (undo restores, redo returns); one receipt write is held back and the intent still ran once. agent_turn_undo, agent_turn_queue, export_gltf, refusals, gn_actions and perception_fixes rerun on 5.3 with the declared field names and the denied/failed split; results refreshed. install.md, node-actions.md and provider-contract.md drop the field lists and point at actions.json and `send --help`. Co-Authored-By: Claude Sonnet 5.5 --- docs/provider-contract.md | 30 +- surfaces/blender/docs/install.md | 81 +- surfaces/blender/docs/node-actions.md | 27 +- surfaces/blender/tests/live/action_table.py | 388 +++ .../tests/live/action_table.result.json | 2543 +++++++++++++++++ .../tests/live/agent_turn_queue.result.json | 45 +- .../tests/live/agent_turn_undo.result.json | 4 +- .../tests/live/export_gltf.result.json | 10 +- surfaces/blender/tests/live/gn_actions.py | 4 +- .../blender/tests/live/gn_actions.result.json | 18 +- .../tests/live/perception_fixes.result.json | 114 +- surfaces/blender/tests/live/refusals.py | 4 +- .../blender/tests/live/refusals.result.json | 6 +- 13 files changed, 3098 insertions(+), 176 deletions(-) create mode 100644 surfaces/blender/tests/live/action_table.py create mode 100644 surfaces/blender/tests/live/action_table.result.json diff --git a/docs/provider-contract.md b/docs/provider-contract.md index 6ccbb10..e137bd7 100644 --- a/docs/provider-contract.md +++ b/docs/provider-contract.md @@ -207,30 +207,20 @@ id for each repetition. All Blender writes use `brokkr.blender.command_intent.v0` and receive `brokkr.blender.command_receipt.v0`. -- `createObject` -- `deleteObject` -- `setObjectTransform` -- `setObjectVisibility` -- `setObjectParent` -- `setObjectCustomProperty` -- `selectObject` -- `assignMaterial` -- `importGltf` -- `exportGltf` (writes under the add-on preference Render Output Directory, never overwriting) -- `setCamera` -- `setLight` -- `setWorld` -- `renderStill` -- `look` (a read: a PNG of her 3D view under the output directory's `look/`, her Edit Mode selection and her edit counters in the receipt) -- `createNodeGroup`, `addNode`, `removeNode`, `linkSockets`, `unlinkSockets`, `addModifier`, - `removeModifier`, `setModifierInput` (Geometry Nodes graphs; fields in - `surfaces/blender/docs/node-actions.md`) +The actions and their fields are one machine-readable table, +`surfaces/blender/brokkr_bridge/actions.json` (schema `brokkr.blender.actions.v0`): the add-on admits every +intent through it, and `brokkr-ctl blender send --help` prints it. It names each action's fields, types, enums, +bounds, defaults, whether the action changes the scene (one undo step), and whether it is safe in Edit Mode. An +intent the table refuses gets a `denied` receipt and changes nothing. Notes the table does not carry: +`exportGltf` writes under the add-on preference Render Output Directory, never overwriting; `look` is a read +(a PNG of her 3D view under the output directory's `look/`, her Edit Mode selection and her edit counters in the +receipt); the Geometry Nodes actions are described in `surfaces/blender/docs/node-actions.md`. Blender owns the mutation. Brokkr advertises the command surface; Verse clients write typed command intents; Blender executes recognized intents and publishes receipts. -`setObjectParent` uses `targetObjectName` and optional `parentObjectName`; an -empty parent reparents the object to the Blender scene root. +`setObjectParent` takes `targetObjectName` and an optional `parentObjectName`; an +empty or absent parent reparents the object to the Blender scene root. ## Operator Views diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index cf2c3c2..337b2e3 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -159,70 +159,55 @@ sync organ). 13. To publish an ad hoc sync variable, fill the `Ad Hoc Sync Var` fields in the sidebar or add-on preferences and click `Publish Sync Var`. -Admitted command actions: +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. -- `createObject` -- `deleteObject` -- `setObjectTransform` -- `setObjectVisibility` -- `setObjectParent` -- `setObjectCustomProperty` -- `selectObject` -- `assignMaterial` -- `importGltf` -- `exportGltf` -- `setCamera` -- `setLight` -- `setWorld` -- `renderStill` -- `look` +Behaviour the table does not say, per action: -Scene action fields (all other keys are ignored; a refused intent changes nothing and -gets a `failed` receipt whose message names the rule): - -- `createObject`: optional `objectType` (`MESH`, `LIGHT`, `CAMERA`, `EMPTY`; default `EMPTY`), - `name`, `location`. Any other `objectType` (for example `TEXT` or `CURVE`) is refused with - the allowed set named. A `MESH` is a cube (`size`); a `meshType` other than `CUBE` - (case-insensitive, no surrounding whitespace) is refused rather than ignored. - `meshType` on any other `objectType` is refused too; an explicit `objectType: null` is refused. +- `createObject`: a `MESH` is a cube of `size`. `lightType`, `emptyDisplayType` and `meshType` apply + only to their own `objectType`. +- `setObjectParent`: an empty or absent `parentObjectName` clears the parent. - `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. - `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). - Optional `extras` (custom properties become node `extras`), `yUp`, `applyModifiers` - (each true by default, must be a boolean) and `selection` (a non-empty list of object - names; 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 + `extras` makes custom properties node `extras`; a `selection` names 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 `.gltf` with its `.bin` and 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`: `targetObjectName` (a camera object); optional `lens` (mm), - `cameraType` (`PERSP`, `ORTHO`, `PANO`), `panoramaType` (for example - `EQUIRECTANGULAR`; read from the camera, or from `camera.cycles` before Blender 4.2), - `orthoScale`, `clipStart`, `clipEnd`, `active` (true makes it the scene camera). - Panoramic cameras render in Cycles. -- `setLight`: `targetObjectName` (a light object); optional `energy` (>= 0), - `color` (linear `[r, g, b]`, each 0 to 1), `lightType` (`POINT`, `SUN`, `SPOT`, `AREA`). -- `setWorld`: optional `worldName` (default: the scene's world, created if there is - none), `color` (`[r, g, b]`), `strength`. Edits the world's Background node. -- `assignMaterial`: `targetObjectName` (an object with material slots, such as a mesh); - optional `materialName` (default `Brokkr Material`; an existing material of that name - is reused) and `color` (linear `[r, g, b]` or `[r, g, b, a]`, each a finite number 0 - to 1; alpha defaults to 1). `color` sets the Principled BSDF Base Color (the node tree - is created if the material has none) and `diffuse_color`; a malformed `color` is - refused naming the field and nothing is created or changed (`"color": null` counts as absent). Without `color` an +- `setCamera`: `targetObjectName` must be a camera object. `panoramaType` is a property of the camera + (Blender 4.2 and newer). Panoramic cameras render in Cycles. `cameraType` leaves out `CUSTOM`: it runs a script. +- `setLight`: `targetObjectName` must be a light object. `color` is linear. +- `setWorld`: without `worldName`, the scene's world, created if there is none. Edits the world's Background node. +- `assignMaterial`: `targetObjectName` must be an object with material slots, such as a mesh. An existing + material of that name is reused. `color` is 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) and + `diffuse_color`; a malformed `color` is refused and nothing is created or changed. Without `color` an 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. Other keys are - ignored, as for every action. + object already has a slot with that material no second slot is added. - `renderStill`: `outputPath` relative to the preference `Render Output Directory`, - ending `.png`, `.jpg` or `.exr` (same containment rules as import); optional - `engine` (any engine of the running Blender, case-insensitive), `resolutionX`, - `resolutionY` (whole numbers, 1 to 16384), `cameraName`. Engine, resolution, + ending `.png`, `.jpg` or `.exr` (same containment rules as import). `engine` is an engine identifier of + the running Blender, matched exactly (Blender is asked by assignment; one it does not have is a `failed` + receipt). 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 engines `BLENDER_WORKBENCH`, `BLENDER_EEVEE` and `BLENDER_EEVEE_NEXT` are refused diff --git a/surfaces/blender/docs/node-actions.md b/surfaces/blender/docs/node-actions.md index cdbb556..b481c21 100644 --- a/surfaces/blender/docs/node-actions.md +++ b/surfaces/blender/docs/node-actions.md @@ -1,20 +1,23 @@ # Geometry node graph actions Command intents (`brokkr.blender.command_intent.v0`) that build and drive a Geometry Nodes graph. -Owner: `brokkr_bridge/node_actions.py`; the target only dispatches. Every field is validated before -`bpy` is touched; a refused intent is a `failed` receipt naming the rule and leaves the tree as it was. +Owner of how an intent becomes a graph: `brokkr_bridge/node_actions.py`; the target only dispatches. The +actions' fields, types and bounds are `brokkr_bridge/actions.json` (printed by `brokkr-ctl blender send --help`): +a field the table refuses is a `denied` receipt naming the rule, before `bpy` is touched. What only the scene +can judge (an absent group, a node type Blender does not offer, a socket that does not exist, a cycle) is a +`failed` receipt that leaves the tree as it was. Node actions name their object `objectName`. Design and the parts not built yet: the design lives at tag `parked/blender-node-graphs-design` (branch `libby/blender-node-graphs-design`, PR #3, closed unmerged), not in this tree. -| action | fields | rule | -|---|---|---| -| `createNodeGroup` | `treeKey`, `interface` `[{inOut, name, type, default?}]` | New geometry node group with `gin` and `gout` nodes. Types: Geometry, Float, Int, Bool, Vector. Refuses an existing group. The receipt lists the interface identifiers (`Socket_N`). | -| `addNode` | `treeKey`, `id`, `blIdname`, `location?`, `label?`, `properties?`, `inputs?` | `id` is Brokkr's key (stored as the node's `brokkr_id`). Type must be a `GeometryNode*`, `FunctionNode*` or `ShaderNode*` name that is not an importer, exporter, script, bake, group, zone, viewer or image-texture node. Properties are enum/bool/int/float node settings (set first, they decide which sockets exist); inputs are unlinked defaults (float, int, bool, vector, colour). At most 500 nodes per group. | -| `removeNode` | `treeKey`, `id` | Removes the node and its links. Absent id: accepted. `gin` and `gout` stay. | -| `linkSockets` | `treeKey`, `fromNode`, `fromSocket`, `toNode`, `toSocket` | Sockets by identifier, or by display name when exactly one available socket has it (Group Input/Output sockets are addressed by interface name). A link Blender calls invalid (field into a single value, type mismatch) is removed and refused, and the single link it displaced is put back. A valid link into a single-link input replaces the old one (Blender's behaviour); a link that would close a cycle, or link a node to itself, is refused before Blender is asked. | -| `unlinkSockets` | `treeKey`, `toNode`, `toSocket`, `fromNode?`, `fromSocket?` | Removes the links into an input, or only the one from the given source. None to remove: accepted. | -| `addModifier` | `objectName`, `treeKey`, `modifierName?` (default `Brokkr GeoNodes`) | `NODES` only. Reuses a modifier of that name; at most 8 per object. | -| `removeModifier` | `objectName`, `modifierName?` | Geometry Nodes modifiers only (a Subdivision or other modifier is refused). Absent: accepted. | -| `setModifierInput` | `objectName`, `modifierName?`, `socket` (identifier or unique interface name), `value` | Float, Int, Bool, Vector inputs. Written as `getattr(modifier.properties.inputs, id).value = v` (indexing `inputs[id]` yields a raw ID property group without `.value` on 5.2.3), then `object.update_tag()`. | +| action | rule | +|---|---| +| `createNodeGroup` | New geometry node group with `gin` and `gout` nodes. Types: Geometry, Float, Int, Bool, Vector. Refuses an existing group. The receipt lists the interface identifiers (`Socket_N`). | +| `addNode` | `id` is Brokkr's key (stored as the node's `brokkr_id`). Type must be a `GeometryNode*`, `FunctionNode*` or `ShaderNode*` name that is not an importer, exporter, script, bake, group, zone, viewer or image-texture node. Properties are enum/bool/int/float node settings (set first, they decide which sockets exist); inputs are unlinked defaults (float, int, bool, vector, colour). At most 500 nodes per group. | +| `removeNode` | Removes the node and its links. Absent id: accepted. `gin` and `gout` stay. | +| `linkSockets` | Sockets by identifier, or by display name when exactly one available socket has it (Group Input/Output sockets are addressed by interface name). A link Blender calls invalid (field into a single value, type mismatch) is removed and refused, and the single link it displaced is put back. A valid link into a single-link input replaces the old one (Blender's behaviour); a link that would close a cycle, or link a node to itself, is refused before Blender is asked. | +| `unlinkSockets` | Removes the links into an input, or only the one from the given source. None to remove: accepted. | +| `addModifier` | `NODES` only. Reuses a modifier of that name; at most 8 per object. | +| `removeModifier` | Geometry Nodes modifiers only (a Subdivision or other modifier is refused). Absent: accepted. | +| `setModifierInput` | Float, Int, Bool, Vector inputs. Written as `getattr(modifier.properties.inputs, id).value = v` (indexing `inputs[id]` yields a raw ID property group without `.value` on 5.2.3), then `object.update_tag()`. | `setObjectCustomProperty` refuses a property whose name is the identifier (`Socket_N`) of an input of a Geometry Nodes modifier on that object; a custom property never drives a modifier input. A name that only equals an diff --git a/surfaces/blender/tests/live/action_table.py b/surfaces/blender/tests/live/action_table.py new file mode 100644 index 0000000..98cbdf8 --- /dev/null +++ b/surfaces/blender/tests/live/action_table.py @@ -0,0 +1,388 @@ +"""Live proof, in GUI Blender with the add-on installed as an extension, that the action table is the one admission. + + BROKKR_SCRATCH= + BROKKR_ADDON_MODULE= + BROKKR_CULTLIB= + blender --python action_table.py -- + +Run it in a Blender whose resource path is fresh (BLENDER_USER_RESOURCE_PATH). Every intent is put into the node +database as brokkr-ctl does and answered by the add-on's own 1 s drain (the sink is on). For every action in actions.json: + + * malformed intents generated from its table entry (an unknown field, a wrong type, an enum miss, a bound miss, + a missing required field, a string or array rule broken, an 'only' broken) are each 'denied', add no undo step + and leave the scene unchanged: one undo after them reverts the canary step that preceded them; + * one valid intent is accepted and, when the entry's changesScene is true, is exactly one undo step (undo restores the + scene, redo brings it back); when false it pushes none. + +A final check holds a receipt write back once and proves the intent still ran exactly once (the drain claims first). +Undo and redo are read only here, by this driver. Writes .result.json, then quits Blender. +""" +import importlib +import json +import os +import sys +import traceback +from pathlib import Path + +import bpy + +SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() +SCRATCH.mkdir(parents=True, exist_ok=True) +OUT = sys.argv[sys.argv.index("--") + 1] +MODULE = os.environ.get("BROKKR_ADDON_MODULE", "bl_ext.user_default.brokkr_bridge") +R = {"blender": bpy.app.version_string, "module": MODULE, "checks": [], "actions": {}} + +bpy.ops.preferences.addon_enable(module=MODULE) +addon = importlib.import_module(MODULE) +bt = importlib.import_module(MODULE + ".blender_target") +at = importlib.import_module(MODULE + ".action_table") +prefs = bpy.context.preferences.addons[MODULE].preferences +bpy.ops.wm.save_as_mainfile(filepath=str(SCRATCH / "live.blend")) +CACHE = str(SCRATCH / "queue.ccmp") +prefs.cultmesh_cache_path = CACHE +prefs.debug_mirror_root = "" +prefs.output_dir = str(SCRATCH / "out") +prefs.import_dir = str(SCRATCH / "out") # importGltf reads what exportGltf wrote +prefs.auto_drain_commands = True # the sink +prefs.cultlib_py_src = os.environ.get("BROKKR_CULTLIB", prefs.cultlib_py_src) +(SCRATCH / "out").mkdir(exist_ok=True) +adapter = addon.target() +R["table_actions"] = [a["name"] for a in at.table()["actions"]] + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def win(): + return bpy.context.temp_override(window=bpy.context.window_manager.windows[0]) + + +def undo(): + with win(): + bpy.ops.ed.undo() + + +def redo(): + with win(): + bpy.ops.ed.redo() + + +def node(): + return adapter._open_node(CACHE, prefs.cultlib_py_src) + + +N = [0] + + +def queue(**cmd): + N[0] += 1 + cid = "live-%04d" % N[0] + n, docs = node() + cmd.update(commandId=cid, schema=bt.COMMAND_INTENT_SCHEMA, requestedBy="nibu/hands") + n.database.put(docs["command_intent"], f"blender/commands/{cid}", cmd) + return cid + + +def receipt(cid): + n, _ = node() + return n.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}).get(f"blender/receipts/{cid}") + + +def pending(): + n, _ = node() + return n.database.snapshot().get(bt.COMMAND_INTENT_SCHEMA, {}) + + +def names(): + return sorted(o.name for o in bpy.data.objects) + + +def r3(values): + return [round(float(v), 4) for v in values] + + +def sig(): + """What an agent intent can change, as one comparable value.""" + scene = bpy.context.scene + world = scene.world + background = world.node_tree.nodes.get("Background") if world and world.node_tree else None + return json.dumps({ + "objects": [[o.name, o.type, r3(o.location), r3(o.rotation_euler), r3(o.scale), o.hide_viewport, o.hide_render, + o.parent.name if o.parent else "", sorted(k for k in o.keys() if not k.startswith("_")), + [[m.name, m.type] for m in o.modifiers], o.select_get()] for o in bpy.data.objects], + "active": bpy.context.view_layer.objects.active.name if bpy.context.view_layer.objects.active else "", + "materials": [[m.name, r3(m.diffuse_color)] for m in bpy.data.materials], + "groups": [[g.name, len(g.nodes), len(g.links)] for g in bpy.data.node_groups], + "cameras": [[c.name, c.lens, c.type, c.panorama_type] for c in bpy.data.cameras], + "lights": [[l.name, l.energy, r3(l.color), l.type] for l in bpy.data.lights], + "world": [world.name, r3(background.inputs["Color"].default_value), round(background.inputs["Strength"].default_value, 4)] if background else None, + "camera": scene.camera.name if scene.camera else "", + "render": [scene.render.engine, scene.render.resolution_x, scene.render.resolution_y], + "counts": [len(bpy.data.objects), len(bpy.data.meshes), len(bpy.data.images)], + }, sort_keys=True) + + +# ---- table-generated intents ------------------------------------------------------------------------------------- + +SAMPLES = [ # (action, prep intents queued and run unmeasured first, the valid sample) + ("createObject", [], {"objectType": "MESH", "name": "LiveCube", "location": [2, 0, 0], "size": 2}), + ("deleteObject", [{"action": "createObject", "objectType": "EMPTY", "name": "LiveDoomed"}], {"targetObjectName": "LiveDoomed"}), + ("setObjectTransform", [], {"targetObjectName": "LiveCube", "location": [2, 3, 0], "rotationEuler": [0, 0, 0.5], "scale": [1, 2, 1]}), + ("setObjectVisibility", [], {"targetObjectName": "LiveCube", "visible": False}), + ("setObjectParent", [], {"targetObjectName": "LiveCube", "parentObjectName": "Cube"}), + ("setObjectCustomProperty", [], {"targetObjectName": "LiveCube", "propertyName": "liveProp", "value": 3}), + ("selectObject", [], {"targetObjectName": "Camera"}), + ("assignMaterial", [], {"targetObjectName": "LiveCube", "materialName": "LiveMat", "color": [0.1, 0.2, 0.3]}), + ("exportGltf", [], {"filepath": "live.glb"}), + ("importGltf", [], {"filepath": "live.glb"}), + ("setCamera", [], {"targetObjectName": "Camera", "lens": 35, "cameraType": "PANO", "panoramaType": "FISHEYE_EQUIDISTANT", "active": True}), + ("setLight", [], {"targetObjectName": "Light", "energy": 500, "color": [1, 0.5, 0], "lightType": "SUN"}), + ("setWorld", [], {"color": [0.1, 0.1, 0.2], "strength": 1.5}), + ("renderStill", [], {"outputPath": "live.png", "engine": "CYCLES", "resolutionX": 8, "resolutionY": 8}), + ("look", [], {}), + ("createNodeGroup", [], {"treeKey": "LiveG", "interface": [{"inOut": "INPUT", "name": "Geometry", "type": "Geometry"}, + {"inOut": "OUTPUT", "name": "Geometry", "type": "Geometry"}, + {"inOut": "INPUT", "name": "Count", "type": "Int", "default": 8}]}), + ("addNode", [], {"treeKey": "LiveG", "id": "m1", "blIdname": "ShaderNodeMath", "location": [100, 0], "label": "live"}), + ("linkSockets", [], {"treeKey": "LiveG", "fromNode": "gin", "fromSocket": "Geometry", "toNode": "gout", "toSocket": "Geometry"}), + ("unlinkSockets", [], {"treeKey": "LiveG", "toNode": "gout", "toSocket": "Geometry"}), + ("removeNode", [], {"treeKey": "LiveG", "id": "m1"}), + ("addModifier", [], {"objectName": "LiveCube", "treeKey": "LiveG", "modifierName": "LiveMod"}), + ("setModifierInput", [], {"objectName": "LiveCube", "modifierName": "LiveMod", "socket": "Count", "value": 4}), + ("removeModifier", [], {"objectName": "LiveCube", "modifierName": "LiveMod"}), +] +WRONG = {"string": 5, "number": "x", "integer": "x", "boolean": "x", "array": "x", "object": []} + + +def malformed(action, sample): + """Intents the table refuses, each derived from one rule of the action's entry. [(label, fields)]""" + row = at.entry(action) + out = [("unknown field", {**sample, "zzUnknown": 1})] + specs = {f["name"]: f for f in row["fields"]} + for name, spec in specs.items(): + def vary(label, value): + out.append((f"{name}: {label}", {**sample, name: value})) + kind = spec["type"] + if kind in WRONG: + vary("wrong type", WRONG[kind]) + if spec.get("required") and name in sample: + out.append((f"{name}: required missing", {k: v for k, v in sample.items() if k != name})) + if "enum" in spec: + vary("enum miss", "nope_") + if kind in ("number", "integer"): + vary("above maximum", spec["maximum"] + 1) + vary("below minimum", spec["minimum"] - 1) + if kind == "string" and "enum" not in spec: + if spec.get("minLength", 0) >= 1: + vary("below minLength", "") + if "maxLength" in spec: + vary("above maxLength", "x" * (spec["maxLength"] + 1)) + if "chars" in spec: + vary("outside charset", "a\n") + if "prefixes" in spec: + vary("no prefix", "Q") + if "forbid" in spec and isinstance(sample.get(name), str): + vary("forbidden part", sample[name] + spec["forbid"][0]) + if kind == "array": + item = spec["items"] + if spec.get("minItems", 0) >= 1: + vary("below minItems", [None][:0] if spec["minItems"] == 1 else [0] * (spec["minItems"] - 1)) + if "maxItems" in spec and item["type"] == "number": + vary("above maxItems", [0] * (spec["maxItems"] + 1)) + if item["type"] == "number": + low = [item["minimum"]] * spec.get("minItems", 1) + vary("item above maximum", [item["maximum"] + 1] + low[1:]) + vary("item below minimum", [item["minimum"] - 1] + low[1:]) + vary("item wrong type", [WRONG.get(item["type"], 5)] + [0] * (spec.get("minItems", 1) - 1)) + if item["type"] == "object": + vary("item missing a property", [{"inOut": "INPUT", "type": "Int"}]) + vary("item unknown property", [{"inOut": "INPUT", "name": "a", "type": "Int", "zzUnknown": 1}]) + if "only" in spec: + sibling = specs[spec["only"]["field"]] + other = next(v for v in sibling["enum"] if v not in spec["only"]["in"]) + out.append((f"{name}: only applies to {spec['only']['field']} in {spec['only']['in']}", + {**{k: v for k, v in sample.items() if k != name}, spec["only"]["field"]: other, name: spec["enum"][0]})) + return out + + +# ---- steps ------------------------------------------------------------------------------------------------------- + +S = {} +WAIT = {"ticks": 0} + + +def until(pred, limit=40): + def step(): + WAIT["ticks"] += 1 + if pred(): + WAIT["ticks"] = 0 + return True + if WAIT["ticks"] > limit: + raise TimeoutError("the drain did not receipt in time") + return False + return step + + +def once(fn): + def step(): + fn() + return True + return step + + +def drained(key): + return lambda: all(receipt(c) for c in S[key]) + + +def run_all(key, intents): + S[key] = [queue(**fields) for fields in intents] + + +def per_action(action, prep, sample): + row = at.entry(action) + key = action + info = R["actions"][action] = {"changesScene": row["changesScene"]} + scene_changing = row["changesScene"] + + def baseline(): + S[key + ":sig0"] = sig() + S[key + ":names0"] = names() + + def malformed_queue(): + bad = malformed(action, sample) + S[key + ":labels"] = [label for label, _ in bad] + run_all(key + ":bad", [{"action": action, **fields} for _, fields in bad]) + + def malformed_check(): + got = [receipt(c) for c in S[key + ":bad"]] + labels = S[key + ":labels"] + not_denied = [(l, r["status"], r["message"]) for l, r in zip(labels, got) if r["status"] != "denied"] + info["malformed"] = len(got) + info["messages"] = {l: r["message"] for l, r in zip(labels, got)} + steps_added = [l for l, r in zip(labels, got) if r["undoLabel"]] + check(f"{action}: {len(got)} table-generated malformed intents are each denied", got and not not_denied, not_denied[:5]) + check(f"{action}: a denied intent carries no undoLabel", not steps_added, steps_added[:5]) + check(f"{action}: the scene is unchanged by the malformed intents", sig() == S[key + ":sig1"], None) + undo() # one undo: if a malformed intent had pushed a step, the canary would survive + check(f"{action}: no malformed intent added an undo step (one undo reverts the canary before them)", + sig() == S[key + ":sig0"], {"names": names(), "was": S[key + ":names0"]}) + + def canary_queue(tag): + run_all(key + ":canary" + tag, [{"action": "createObject", "objectType": "MESH", "name": "Canary" + tag, "location": [0, 0, 9]}]) + + def canary_check(): + r = receipt(S[key + ":canary1"][0]) + S[key + ":sig1"] = sig() + check(f"{action}: the canary is accepted with one undoLabel", r["status"] == "accepted" and r["undoLabel"], r) + + def valid_queue(): + S[key + ":sigv0"] = sig() + run_all(key + ":valid", [{"action": action, **sample}]) + + def valid_check(): + r = receipt(S[key + ":valid"][0]) + info["valid"] = {"status": r["status"], "message": r["message"], "undoLabel": r["undoLabel"]} + after = sig() + S[key + ":sigv1"] = after + check(f"{action}: the valid intent is accepted", r["status"] == "accepted", r) + if scene_changing: + check(f"{action}: changesScene is true, so the receipt carries an undoLabel", r["undoLabel"].startswith(f"Brokkr nibu/hands: {action} "), r["undoLabel"]) + if after != S[key + ":sigv0"]: + undo() + check(f"{action}: one undo restores the scene to before the intent", sig() == S[key + ":sigv0"], None) + redo() + check(f"{action}: redo brings the intent's result back", sig() == after, None) + else: + info["note"] = "the intent changed nothing the signature reads (checked by label only)" + else: + check(f"{action}: changesScene is false, so no undoLabel", r["undoLabel"] == "", r["undoLabel"]) + + def noscene_check(): + # a canary, then the valid intent, then one undo: the canary goes, so the intent pushed no step + undo() + check(f"{action}: it pushed no undo step (one undo reverts the canary before it)", sig() == S[key + ":sigc0"], None) + + out = [] + for p in prep: + out += [once(lambda p=p: run_all(key + ":prep", [p])), until(drained(key + ":prep"))] + out += [once(baseline), once(lambda: canary_queue("1")), until(drained(key + ":canary1")), once(canary_check), + once(malformed_queue), until(drained(key + ":bad")), once(malformed_check)] + if scene_changing: + out += [once(valid_queue), until(drained(key + ":valid")), once(valid_check)] + else: + out += [once(lambda: S.__setitem__(key + ":sigc0", sig())), once(lambda: canary_queue("2")), until(drained(key + ":canary2")), + once(valid_queue), until(drained(key + ":valid")), once(valid_check), once(noscene_check)] + return out + + +def covered(): + missing = [a for a in R["table_actions"] if a not in {s[0] for s in SAMPLES}] + extra = [s[0] for s in SAMPLES if s[0] not in R["table_actions"]] + check("every action of actions.json has a live sample and no sample names an action the table lacks", not missing and not extra, [missing, extra]) + + +def flaky_setup(): + """Hold one receipt write back: the intent must still have run exactly once, and its receipt arrive next drain.""" + S["flaky:objects"] = len([o for o in bpy.data.objects if o.name.startswith("FlakyCube")]) + original = adapter.publish_receipt + state = {"raised": 0} + S["flaky:id"] = None + + def flaky(*args, **kwargs): + receipt_doc = args[2] if len(args) > 2 else kwargs.get("receipt") + if receipt_doc and receipt_doc.get("commandId") == S["flaky:id"] and not state["raised"]: + state["raised"] += 1 + raise OSError("injected receipt write failure") + return original(*args, **kwargs) + + adapter.publish_receipt = flaky + S["flaky:restore"] = lambda: setattr(adapter, "publish_receipt", original) + S["flaky:state"] = state + cid = queue(action="createObject", objectType="MESH", name="FlakyCube", location=[0, 0, 12]) + S["flaky:id"] = cid + S["flaky:ids"] = [cid] + + +def flaky_check(): + S["flaky:restore"]() + r = receipt(S["flaky:id"]) + flakies = [o.name for o in bpy.data.objects if o.name.startswith("FlakyCube")] + check("claim-first: with one receipt write failing, the intent ran exactly once and its receipt was written by the next drain", + S["flaky:state"]["raised"] == 1 and len(flakies) == 1 and r and r["status"] == "accepted" + and f"blender/receipts/{S['flaky:id']}.denied" not in node()[0].database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}) + and S["flaky:id"] not in str(pending()), {"raised": S["flaky:state"]["raised"], "objects": flakies, "receipt": r and r["status"]}) + check("the queue is empty and the add-on's drain reports no error", not pending() and adapter.last_auto_drain_error == "", + [list(pending()), adapter.last_auto_drain_error]) + + +steps = [once(covered)] +for action, prep, sample in SAMPLES: + steps += per_action(action, prep, sample) +steps += [once(flaky_setup), until(lambda: receipt(S["flaky:id"]) is not None), once(flaky_check)] +i = 0 + + +def write(): + R["ok"] = bool(R["checks"]) and all(c["ok"] for c in R["checks"]) and not R.get("errors") + with open(OUT + ".result.json", "w") as f: + json.dump(R, f, indent=1, default=str) + + +def tick(): + global i + if i < len(steps): + try: + if steps[i](): + i += 1 + except Exception: + R.setdefault("errors", []).append({"step": i, "error": traceback.format_exc()}) + i = len(steps) + write() + return 0.5 + write() + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(tick, first_interval=3.0) diff --git a/surfaces/blender/tests/live/action_table.result.json b/surfaces/blender/tests/live/action_table.result.json new file mode 100644 index 0000000..b21b4c1 --- /dev/null +++ b/surfaces/blender/tests/live/action_table.result.json @@ -0,0 +1,2543 @@ +{ + "blender": "5.3.0", + "module": "bl_ext.user_default.brokkr_bridge", + "checks": [ + { + "name": "every action of actions.json has a live sample and no sample names an action the table lacks", + "ok": true, + "detail": [ + [], + [] + ] + }, + { + "name": "createObject: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0001", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0001", + "lookPath": "", + "observedAt": "2026-11-28T01:56:40.145813+00:00" + } + }, + { + "name": "createObject: 22 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "createObject: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "createObject: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "createObject: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light" + ], + "was": [ + "Camera", + "Cube", + "Light" + ] + } + }, + { + "name": "createObject: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0024", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "LiveCube", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0024", + "lookPath": "", + "observedAt": "2026-11-28T01:56:45.785882+00:00" + } + }, + { + "name": "createObject: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: createObject ive-0024" + }, + { + "name": "createObject: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "createObject: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "deleteObject: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0026", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0026", + "lookPath": "", + "observedAt": "2026-11-28T01:56:49.944500+00:00" + } + }, + { + "name": "deleteObject: 3 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "deleteObject: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "deleteObject: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "deleteObject: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light", + "LiveCube", + "LiveDoomed" + ], + "was": [ + "Camera", + "Cube", + "Light", + "LiveCube", + "LiveDoomed" + ] + } + }, + { + "name": "deleteObject: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0030", + "action": "deleteObject", + "status": "accepted", + "message": "Blender object deleted.", + "objectName": "LiveDoomed", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: deleteObject ive-0030", + "lookPath": "", + "observedAt": "2026-11-28T01:56:54.485651+00:00" + } + }, + { + "name": "deleteObject: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: deleteObject ive-0030" + }, + { + "name": "deleteObject: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "deleteObject: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "setObjectTransform: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0031", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0031", + "lookPath": "", + "observedAt": "2026-11-28T01:56:56.566254+00:00" + } + }, + { + "name": "setObjectTransform: 21 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "setObjectTransform: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "setObjectTransform: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "setObjectTransform: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ], + "was": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ] + } + }, + { + "name": "setObjectTransform: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0053", + "action": "setObjectTransform", + "status": "accepted", + "message": "Blender object transform updated.", + "objectName": "LiveCube", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: setObjectTransform ive-0053", + "lookPath": "", + "observedAt": "2026-11-28T01:57:03.202116+00:00" + } + }, + { + "name": "setObjectTransform: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: setObjectTransform ive-0053" + }, + { + "name": "setObjectTransform: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "setObjectTransform: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "setObjectVisibility: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0054", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0054", + "lookPath": "", + "observedAt": "2026-11-28T01:57:05.306686+00:00" + } + }, + { + "name": "setObjectVisibility: 4 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "setObjectVisibility: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "setObjectVisibility: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "setObjectVisibility: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ], + "was": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ] + } + }, + { + "name": "setObjectVisibility: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0059", + "action": "setObjectVisibility", + "status": "accepted", + "message": "Blender object visibility updated.", + "objectName": "LiveCube", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: setObjectVisibility ive-0059", + "lookPath": "", + "observedAt": "2026-11-28T01:57:09.874099+00:00" + } + }, + { + "name": "setObjectVisibility: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: setObjectVisibility ive-0059" + }, + { + "name": "setObjectVisibility: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "setObjectVisibility: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "setObjectParent: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0060", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0060", + "lookPath": "", + "observedAt": "2026-11-28T01:57:11.974525+00:00" + } + }, + { + "name": "setObjectParent: 4 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "setObjectParent: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "setObjectParent: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "setObjectParent: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ], + "was": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ] + } + }, + { + "name": "setObjectParent: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0065", + "action": "setObjectParent", + "status": "accepted", + "message": "Blender object parent updated.", + "objectName": "LiveCube", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: setObjectParent ive-0065", + "lookPath": "", + "observedAt": "2026-11-28T01:57:16.563563+00:00" + } + }, + { + "name": "setObjectParent: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: setObjectParent ive-0065" + }, + { + "name": "setObjectParent: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "setObjectParent: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "setObjectCustomProperty: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0066", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0066", + "lookPath": "", + "observedAt": "2026-11-28T01:57:18.681337+00:00" + } + }, + { + "name": "setObjectCustomProperty: 5 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "setObjectCustomProperty: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "setObjectCustomProperty: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "setObjectCustomProperty: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ], + "was": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ] + } + }, + { + "name": "setObjectCustomProperty: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0072", + "action": "setObjectCustomProperty", + "status": "accepted", + "message": "Blender custom property updated.", + "objectName": "LiveCube", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: setObjectCustomProperty ive-0072", + "lookPath": "", + "observedAt": "2026-11-28T01:57:22.508309+00:00" + } + }, + { + "name": "setObjectCustomProperty: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: setObjectCustomProperty ive-0072" + }, + { + "name": "setObjectCustomProperty: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "setObjectCustomProperty: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "selectObject: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0073", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0073", + "lookPath": "", + "observedAt": "2026-11-28T01:57:24.630024+00:00" + } + }, + { + "name": "selectObject: 4 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "selectObject: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "selectObject: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "selectObject: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ], + "was": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ] + } + }, + { + "name": "selectObject: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0078", + "action": "selectObject", + "status": "accepted", + "message": "Blender object selected.", + "objectName": "Camera", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: selectObject ive-0078", + "lookPath": "", + "observedAt": "2026-11-28T01:57:29.310576+00:00" + } + }, + { + "name": "selectObject: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: selectObject ive-0078" + }, + { + "name": "selectObject: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "selectObject: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "assignMaterial: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0079", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0079", + "lookPath": "", + "observedAt": "2026-11-28T01:57:31.515585+00:00" + } + }, + { + "name": "assignMaterial: 10 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "assignMaterial: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "assignMaterial: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "assignMaterial: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ], + "was": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ] + } + }, + { + "name": "assignMaterial: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0090", + "action": "assignMaterial", + "status": "accepted", + "message": "Blender material assigned.", + "objectName": "LiveCube", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: assignMaterial ive-0090", + "lookPath": "", + "observedAt": "2026-11-28T01:57:37.550809+00:00" + } + }, + { + "name": "assignMaterial: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: assignMaterial ive-0090" + }, + { + "name": "assignMaterial: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "assignMaterial: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "exportGltf: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0091", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0091", + "lookPath": "", + "observedAt": "2026-11-28T01:57:39.704717+00:00" + } + }, + { + "name": "exportGltf: 9 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "exportGltf: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "exportGltf: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "exportGltf: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ], + "was": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ] + } + }, + { + "name": "exportGltf: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0102", + "action": "exportGltf", + "status": "accepted", + "message": "Exported glTF to F:\\aeth-wt\\brokkr-action-table-live\\scratch\\out\\live.glb (5028 bytes).", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "observedAt": "2026-11-28T01:57:48.919027+00:00" + } + }, + { + "name": "exportGltf: changesScene is false, so no undoLabel", + "ok": true, + "detail": "" + }, + { + "name": "exportGltf: it pushed no undo step (one undo reverts the canary before it)", + "ok": true, + "detail": null + }, + { + "name": "importGltf: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0103", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0103", + "lookPath": "", + "observedAt": "2026-11-28T01:57:51.228716+00:00" + } + }, + { + "name": "importGltf: 3 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "importGltf: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "importGltf: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "importGltf: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ], + "was": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ] + } + }, + { + "name": "importGltf: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0107", + "action": "importGltf", + "status": "accepted", + "message": "Imported 3 object(s) from live.glb.", + "objectName": "Canary2", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: importGltf ive-0107", + "lookPath": "", + "observedAt": "2026-11-28T01:57:56.255504+00:00" + } + }, + { + "name": "importGltf: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: importGltf ive-0107" + }, + { + "name": "importGltf: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "importGltf: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "setCamera: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0108", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0108", + "lookPath": "", + "observedAt": "2026-11-28T01:57:58.437908+00:00" + } + }, + { + "name": "setCamera: 20 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "setCamera: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "setCamera: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "setCamera: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "setCamera: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0129", + "action": "setCamera", + "status": "accepted", + "message": "Blender camera updated.", + "objectName": "Camera", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: setCamera ive-0129", + "lookPath": "", + "observedAt": "2026-11-28T01:58:11.054773+00:00" + } + }, + { + "name": "setCamera: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: setCamera ive-0129" + }, + { + "name": "setCamera: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "setCamera: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "setLight: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0130", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0130", + "lookPath": "", + "observedAt": "2026-11-28T01:58:13.248452+00:00" + } + }, + { + "name": "setLight: 14 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "setLight: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "setLight: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "setLight: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "setLight: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0145", + "action": "setLight", + "status": "accepted", + "message": "Blender light updated.", + "objectName": "Light", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: setLight ive-0145", + "lookPath": "", + "observedAt": "2026-11-28T01:58:22.382198+00:00" + } + }, + { + "name": "setLight: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: setLight ive-0145" + }, + { + "name": "setLight: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "setLight: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "setWorld: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0146", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0146", + "lookPath": "", + "observedAt": "2026-11-28T01:58:24.582227+00:00" + } + }, + { + "name": "setWorld: 11 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "setWorld: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "setWorld: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "setWorld: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "setWorld: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0158", + "action": "setWorld", + "status": "accepted", + "message": "Blender world updated.", + "objectName": "World", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: setWorld ive-0158", + "lookPath": "", + "observedAt": "2026-11-28T01:58:31.393393+00:00" + } + }, + { + "name": "setWorld: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: setWorld ive-0158" + }, + { + "name": "setWorld: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "setWorld: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "renderStill: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0159", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0159", + "lookPath": "", + "observedAt": "2026-11-28T01:58:33.598048+00:00" + } + }, + { + "name": "renderStill: 12 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "renderStill: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "renderStill: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "renderStill: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "renderStill: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0173", + "action": "renderStill", + "status": "accepted", + "message": "Rendered still to live.png.", + "objectName": "Scene", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "observedAt": "2026-11-28T01:58:44.631878+00:00" + } + }, + { + "name": "renderStill: changesScene is false, so no undoLabel", + "ok": true, + "detail": "" + }, + { + "name": "renderStill: it pushed no undo step (one undo reverts the canary before it)", + "ok": true, + "detail": null + }, + { + "name": "look: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0174", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0174", + "lookPath": "", + "observedAt": "2026-11-28T01:58:47.857036+00:00" + } + }, + { + "name": "look: 1 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "look: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "look: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "look: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "look: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0177", + "action": "look", + "status": "accepted", + "message": "Captured the 3D view to look/live-0177.png.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "F:\\aeth-wt\\brokkr-action-table-live\\scratch\\out\\look\\live-0177.png", + "observedAt": "2026-11-28T01:58:53.654873+00:00", + "captureSource": "region", + "sceneUpdateSeq": 95, + "sessionId": "3b3d62619afb43d0a8548fc3f2ce4a4f", + "humanEditSeq": 83, + "humanEditsSinceLook": 83, + "editedSinceLook": [ + "Camera", + "Canary2", + "Canary2.001", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001", + "LiveDoomed" + ], + "editedSinceLookCoarse": true, + "editedSinceLookNote": "Coarse: undo or redo flags all objects; editedSinceLook may name objects she did not touch.", + "editSelection": [] + } + }, + { + "name": "look: changesScene is false, so no undoLabel", + "ok": true, + "detail": "" + }, + { + "name": "look: it pushed no undo step (one undo reverts the canary before it)", + "ok": true, + "detail": null + }, + { + "name": "createNodeGroup: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0178", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0178", + "lookPath": "", + "observedAt": "2026-11-28T01:58:56.864241+00:00" + } + }, + { + "name": "createNodeGroup: 14 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "createNodeGroup: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "createNodeGroup: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "createNodeGroup: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "createNodeGroup: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0193", + "action": "createNodeGroup", + "status": "accepted", + "message": "Created node group; interface identifiers: input Geometry=Socket_0, output Geometry=Socket_1, input Count=Socket_2", + "objectName": "LiveG", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createNodeGroup ive-0193", + "lookPath": "", + "observedAt": "2026-11-28T01:59:10.270729+00:00" + } + }, + { + "name": "createNodeGroup: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: createNodeGroup ive-0193" + }, + { + "name": "createNodeGroup: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "createNodeGroup: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "addNode: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0194", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0194", + "lookPath": "", + "observedAt": "2026-11-28T01:59:12.510947+00:00" + } + }, + { + "name": "addNode: 28 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "addNode: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "addNode: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "addNode: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "addNode: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0223", + "action": "addNode", + "status": "accepted", + "message": "Node added.", + "objectName": "m1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: addNode ive-0223", + "lookPath": "", + "observedAt": "2026-11-28T01:59:47.731039+00:00" + } + }, + { + "name": "addNode: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: addNode ive-0223" + }, + { + "name": "addNode: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "addNode: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "linkSockets: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0224", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0224", + "lookPath": "", + "observedAt": "2026-11-28T01:59:49.993525+00:00" + } + }, + { + "name": "linkSockets: 22 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "linkSockets: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "linkSockets: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "linkSockets: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "linkSockets: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0247", + "action": "linkSockets", + "status": "accepted", + "message": "Linked gin.Socket_0 -> gout.Socket_1.", + "objectName": "LiveG", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: linkSockets ive-0247", + "lookPath": "", + "observedAt": "2026-11-28T02:00:17.375246+00:00" + } + }, + { + "name": "linkSockets: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: linkSockets ive-0247" + }, + { + "name": "linkSockets: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "linkSockets: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "unlinkSockets: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0248", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0248", + "lookPath": "", + "observedAt": "2026-11-28T02:00:19.737999+00:00" + } + }, + { + "name": "unlinkSockets: 20 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "unlinkSockets: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "unlinkSockets: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "unlinkSockets: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "unlinkSockets: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0269", + "action": "unlinkSockets", + "status": "accepted", + "message": "Removed 1 link(s).", + "objectName": "LiveG", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: unlinkSockets ive-0269", + "lookPath": "", + "observedAt": "2026-11-28T02:00:45.997967+00:00" + } + }, + { + "name": "unlinkSockets: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: unlinkSockets ive-0269" + }, + { + "name": "unlinkSockets: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "unlinkSockets: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "removeNode: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0270", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0270", + "lookPath": "", + "observedAt": "2026-11-28T02:00:48.315493+00:00" + } + }, + { + "name": "removeNode: 13 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "removeNode: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "removeNode: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "removeNode: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "removeNode: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0284", + "action": "removeNode", + "status": "accepted", + "message": "Node removed.", + "objectName": "m1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: removeNode ive-0284", + "lookPath": "", + "observedAt": "2026-11-28T02:01:03.364715+00:00" + } + }, + { + "name": "removeNode: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: removeNode ive-0284" + }, + { + "name": "removeNode: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "removeNode: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "addModifier: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0285", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0285", + "lookPath": "", + "observedAt": "2026-11-28T02:01:05.767376+00:00" + } + }, + { + "name": "addModifier: 16 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "addModifier: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "addModifier: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "addModifier: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "addModifier: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0302", + "action": "addModifier", + "status": "accepted", + "message": "Geometry Nodes modifier set.", + "objectName": "LiveCube", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: addModifier ive-0302", + "lookPath": "", + "observedAt": "2026-11-28T02:01:26.890644+00:00" + } + }, + { + "name": "addModifier: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: addModifier ive-0302" + }, + { + "name": "addModifier: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "addModifier: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "setModifierInput: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0303", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0303", + "lookPath": "", + "observedAt": "2026-11-28T02:01:29.307569+00:00" + } + }, + { + "name": "setModifierInput: 7 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "setModifierInput: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "setModifierInput: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "setModifierInput: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "setModifierInput: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0311", + "action": "setModifierInput", + "status": "accepted", + "message": "Modifier input Count set.", + "objectName": "LiveCube", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: setModifierInput ive-0311", + "lookPath": "", + "observedAt": "2026-11-28T02:01:37.160827+00:00" + } + }, + { + "name": "setModifierInput: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: setModifierInput ive-0311" + }, + { + "name": "removeModifier: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0312", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0312", + "lookPath": "", + "observedAt": "2026-11-28T02:01:39.514028+00:00" + } + }, + { + "name": "removeModifier: 7 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "removeModifier: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "removeModifier: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "removeModifier: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "removeModifier: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0320", + "action": "removeModifier", + "status": "accepted", + "message": "Modifier removed.", + "objectName": "LiveCube", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: removeModifier ive-0320", + "lookPath": "", + "observedAt": "2026-11-28T02:01:47.535687+00:00" + } + }, + { + "name": "removeModifier: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: removeModifier ive-0320" + }, + { + "name": "removeModifier: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "removeModifier: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "claim-first: with one receipt write failing, the intent ran exactly once and its receipt was written by the next drain", + "ok": true, + "detail": { + "raised": 1, + "objects": [ + "FlakyCube" + ], + "receipt": "accepted" + } + }, + { + "name": "the queue is empty and the add-on's drain reports no error", + "ok": true, + "detail": [ + [], + "" + ] + } + ], + "actions": { + "createObject": { + "changesScene": true, + "malformed": 22, + "messages": { + "unknown field": "createObject has no field 'zzUnknown'; its fields: objectType, name, location, size, meshType, lightType, emptyDisplayType.", + "objectType: wrong type": "objectType must be a string.", + "objectType: enum miss": "objectType must be one of MESH, LIGHT, CAMERA, EMPTY.", + "name: wrong type": "name must be a string.", + "location: wrong type": "location must be an array.", + "location: below minItems": "location must have at least 3 items.", + "location: above maxItems": "location must have at most 3 items.", + "location: item above maximum": "location[0] must be between -1000000000 and 1000000000.", + "location: item below minimum": "location[0] must be between -1000000000 and 1000000000.", + "location: item wrong type": "location[0] must be a finite number.", + "size: wrong type": "size must be a finite number.", + "size: above maximum": "size must be between 0.001 and 1000000.", + "size: below minimum": "size must be between 0.001 and 1000000.", + "meshType: wrong type": "meshType must be a string.", + "meshType: enum miss": "meshType must be one of CUBE.", + "meshType: only applies to objectType in ['MESH']": "meshType applies only when objectType is one of MESH.", + "lightType: wrong type": "lightType applies only when objectType is one of LIGHT.", + "lightType: enum miss": "lightType applies only when objectType is one of LIGHT.", + "lightType: only applies to objectType in ['LIGHT']": "lightType applies only when objectType is one of LIGHT.", + "emptyDisplayType: wrong type": "emptyDisplayType applies only when objectType is one of EMPTY.", + "emptyDisplayType: enum miss": "emptyDisplayType applies only when objectType is one of EMPTY.", + "emptyDisplayType: only applies to objectType in ['EMPTY']": "emptyDisplayType applies only when objectType is one of EMPTY." + }, + "valid": { + "status": "accepted", + "message": "Blender object created.", + "undoLabel": "Brokkr nibu/hands: createObject ive-0024" + } + }, + "deleteObject": { + "changesScene": true, + "malformed": 3, + "messages": { + "unknown field": "deleteObject has no field 'zzUnknown'; its fields: targetObjectName.", + "targetObjectName: wrong type": "targetObjectName must be a string.", + "targetObjectName: required missing": "targetObjectName is required." + }, + "valid": { + "status": "accepted", + "message": "Blender object deleted.", + "undoLabel": "Brokkr nibu/hands: deleteObject ive-0030" + } + }, + "setObjectTransform": { + "changesScene": true, + "malformed": 21, + "messages": { + "unknown field": "setObjectTransform has no field 'zzUnknown'; its fields: targetObjectName, location, rotationEuler, scale.", + "targetObjectName: wrong type": "targetObjectName must be a string.", + "targetObjectName: required missing": "targetObjectName is required.", + "location: wrong type": "location must be an array.", + "location: below minItems": "location must have at least 3 items.", + "location: above maxItems": "location must have at most 3 items.", + "location: item above maximum": "location[0] must be between -1000000000 and 1000000000.", + "location: item below minimum": "location[0] must be between -1000000000 and 1000000000.", + "location: item wrong type": "location[0] must be a finite number.", + "rotationEuler: wrong type": "rotationEuler must be an array.", + "rotationEuler: below minItems": "rotationEuler must have at least 3 items.", + "rotationEuler: above maxItems": "rotationEuler must have at most 3 items.", + "rotationEuler: item above maximum": "rotationEuler[0] must be between -1000000000 and 1000000000.", + "rotationEuler: item below minimum": "rotationEuler[0] must be between -1000000000 and 1000000000.", + "rotationEuler: item wrong type": "rotationEuler[0] must be a finite number.", + "scale: wrong type": "scale must be an array.", + "scale: below minItems": "scale must have at least 3 items.", + "scale: above maxItems": "scale must have at most 3 items.", + "scale: item above maximum": "scale[0] must be between -1000000000 and 1000000000.", + "scale: item below minimum": "scale[0] must be between -1000000000 and 1000000000.", + "scale: item wrong type": "scale[0] must be a finite number." + }, + "valid": { + "status": "accepted", + "message": "Blender object transform updated.", + "undoLabel": "Brokkr nibu/hands: setObjectTransform ive-0053" + } + }, + "setObjectVisibility": { + "changesScene": true, + "malformed": 4, + "messages": { + "unknown field": "setObjectVisibility has no field 'zzUnknown'; its fields: targetObjectName, visible.", + "targetObjectName: wrong type": "targetObjectName must be a string.", + "targetObjectName: required missing": "targetObjectName is required.", + "visible: wrong type": "visible must be true or false." + }, + "valid": { + "status": "accepted", + "message": "Blender object visibility updated.", + "undoLabel": "Brokkr nibu/hands: setObjectVisibility ive-0059" + } + }, + "setObjectParent": { + "changesScene": true, + "malformed": 4, + "messages": { + "unknown field": "setObjectParent has no field 'zzUnknown'; its fields: targetObjectName, parentObjectName.", + "targetObjectName: wrong type": "targetObjectName must be a string.", + "targetObjectName: required missing": "targetObjectName is required.", + "parentObjectName: wrong type": "parentObjectName must be a string." + }, + "valid": { + "status": "accepted", + "message": "Blender object parent updated.", + "undoLabel": "Brokkr nibu/hands: setObjectParent ive-0065" + } + }, + "setObjectCustomProperty": { + "changesScene": true, + "malformed": 5, + "messages": { + "unknown field": "setObjectCustomProperty has no field 'zzUnknown'; its fields: targetObjectName, propertyName, value.", + "targetObjectName: wrong type": "targetObjectName must be a string.", + "targetObjectName: required missing": "targetObjectName is required.", + "propertyName: wrong type": "propertyName must be a string.", + "value: required missing": "value is required." + }, + "valid": { + "status": "accepted", + "message": "Blender custom property updated.", + "undoLabel": "Brokkr nibu/hands: setObjectCustomProperty ive-0072" + } + }, + "selectObject": { + "changesScene": true, + "malformed": 4, + "messages": { + "unknown field": "selectObject has no field 'zzUnknown'; its fields: targetObjectName, clearSelection.", + "targetObjectName: wrong type": "targetObjectName must be a string.", + "targetObjectName: required missing": "targetObjectName is required.", + "clearSelection: wrong type": "clearSelection must be true or false." + }, + "valid": { + "status": "accepted", + "message": "Blender object selected.", + "undoLabel": "Brokkr nibu/hands: selectObject ive-0078" + } + }, + "assignMaterial": { + "changesScene": true, + "malformed": 10, + "messages": { + "unknown field": "assignMaterial has no field 'zzUnknown'; its fields: targetObjectName, materialName, color.", + "targetObjectName: wrong type": "targetObjectName must be a string.", + "targetObjectName: required missing": "targetObjectName is required.", + "materialName: wrong type": "materialName must be a string.", + "color: wrong type": "color must be an array.", + "color: below minItems": "color must have at least 3 items.", + "color: above maxItems": "color must have at most 4 items.", + "color: item above maximum": "color[0] must be between 0 and 1.", + "color: item below minimum": "color[0] must be between 0 and 1.", + "color: item wrong type": "color[0] must be a finite number." + }, + "valid": { + "status": "accepted", + "message": "Blender material assigned.", + "undoLabel": "Brokkr nibu/hands: assignMaterial ive-0090" + } + }, + "exportGltf": { + "changesScene": false, + "malformed": 9, + "messages": { + "unknown field": "exportGltf has no field 'zzUnknown'; its fields: filepath, extras, yUp, applyModifiers, selection.", + "filepath: wrong type": "filepath must be a string.", + "filepath: required missing": "filepath is required.", + "extras: wrong type": "extras must be true or false.", + "yUp: wrong type": "yUp must be true or false.", + "applyModifiers: wrong type": "applyModifiers must be true or false.", + "selection: wrong type": "selection must be an array.", + "selection: below minItems": "selection must have at least 1 items.", + "selection: item wrong type": "selection[0] must be a string." + }, + "valid": { + "status": "accepted", + "message": "Exported glTF to F:\\aeth-wt\\brokkr-action-table-live\\scratch\\out\\live.glb (5028 bytes).", + "undoLabel": "" + } + }, + "importGltf": { + "changesScene": true, + "malformed": 3, + "messages": { + "unknown field": "importGltf has no field 'zzUnknown'; its fields: filepath.", + "filepath: wrong type": "filepath must be a string.", + "filepath: required missing": "filepath is required." + }, + "valid": { + "status": "accepted", + "message": "Imported 3 object(s) from live.glb.", + "undoLabel": "Brokkr nibu/hands: importGltf ive-0107" + } + }, + "setCamera": { + "changesScene": true, + "malformed": 20, + "messages": { + "unknown field": "setCamera has no field 'zzUnknown'; its fields: targetObjectName, lens, cameraType, orthoScale, clipStart, clipEnd, panoramaType, active.", + "targetObjectName: wrong type": "targetObjectName must be a string.", + "targetObjectName: required missing": "targetObjectName is required.", + "lens: wrong type": "lens must be a finite number.", + "lens: above maximum": "lens must be between 1 and 5000.", + "lens: below minimum": "lens must be between 1 and 5000.", + "cameraType: wrong type": "cameraType must be a string.", + "cameraType: enum miss": "cameraType must be one of PERSP, ORTHO, PANO.", + "orthoScale: wrong type": "orthoScale must be a finite number.", + "orthoScale: above maximum": "orthoScale must be between 0.001 and 100000.", + "orthoScale: below minimum": "orthoScale must be between 0.001 and 100000.", + "clipStart: wrong type": "clipStart must be a finite number.", + "clipStart: above maximum": "clipStart must be between 0.0001 and 1000000.", + "clipStart: below minimum": "clipStart must be between 0.0001 and 1000000.", + "clipEnd: wrong type": "clipEnd must be a finite number.", + "clipEnd: above maximum": "clipEnd must be between 0.001 and 10000000.", + "clipEnd: below minimum": "clipEnd must be between 0.001 and 10000000.", + "panoramaType: wrong type": "panoramaType must be a string.", + "panoramaType: enum miss": "panoramaType must be one of EQUIRECTANGULAR, EQUIANGULAR_CUBEMAP_FACE, MIRRORBALL, FISHEYE_EQUIDISTANT, FISHEYE_EQUISOLID, FISHEYE_LENS_POLYNOMIAL, CENTRAL_CYLINDRICAL.", + "active: wrong type": "active must be true or false." + }, + "valid": { + "status": "accepted", + "message": "Blender camera updated.", + "undoLabel": "Brokkr nibu/hands: setCamera ive-0129" + } + }, + "setLight": { + "changesScene": true, + "malformed": 14, + "messages": { + "unknown field": "setLight has no field 'zzUnknown'; its fields: targetObjectName, energy, color, lightType.", + "targetObjectName: wrong type": "targetObjectName must be a string.", + "targetObjectName: required missing": "targetObjectName is required.", + "energy: wrong type": "energy must be a finite number.", + "energy: above maximum": "energy must be between 0 and 10000000.", + "energy: below minimum": "energy must be between 0 and 10000000.", + "color: wrong type": "color must be an array.", + "color: below minItems": "color must have at least 3 items.", + "color: above maxItems": "color must have at most 3 items.", + "color: item above maximum": "color[0] must be between 0 and 1.", + "color: item below minimum": "color[0] must be between 0 and 1.", + "color: item wrong type": "color[0] must be a finite number.", + "lightType: wrong type": "lightType must be a string.", + "lightType: enum miss": "lightType must be one of POINT, SUN, SPOT, AREA." + }, + "valid": { + "status": "accepted", + "message": "Blender light updated.", + "undoLabel": "Brokkr nibu/hands: setLight ive-0145" + } + }, + "setWorld": { + "changesScene": true, + "malformed": 11, + "messages": { + "unknown field": "setWorld has no field 'zzUnknown'; its fields: worldName, color, strength.", + "worldName: wrong type": "worldName must be a string.", + "color: wrong type": "color must be an array.", + "color: below minItems": "color must have at least 3 items.", + "color: above maxItems": "color must have at most 3 items.", + "color: item above maximum": "color[0] must be between 0 and 1.", + "color: item below minimum": "color[0] must be between 0 and 1.", + "color: item wrong type": "color[0] must be a finite number.", + "strength: wrong type": "strength must be a finite number.", + "strength: above maximum": "strength must be between 0 and 1000000.", + "strength: below minimum": "strength must be between 0 and 1000000." + }, + "valid": { + "status": "accepted", + "message": "Blender world updated.", + "undoLabel": "Brokkr nibu/hands: setWorld ive-0158" + } + }, + "renderStill": { + "changesScene": false, + "malformed": 12, + "messages": { + "unknown field": "renderStill has no field 'zzUnknown'; its fields: outputPath, engine, resolutionX, resolutionY, cameraName.", + "outputPath: wrong type": "outputPath must be a string.", + "outputPath: required missing": "outputPath is required.", + "engine: wrong type": "engine must be a string.", + "engine: below minLength": "engine must have at least 1 characters.", + "resolutionX: wrong type": "resolutionX must be a whole number.", + "resolutionX: above maximum": "resolutionX must be between 4 and 16384.", + "resolutionX: below minimum": "resolutionX must be between 4 and 16384.", + "resolutionY: wrong type": "resolutionY must be a whole number.", + "resolutionY: above maximum": "resolutionY must be between 4 and 16384.", + "resolutionY: below minimum": "resolutionY must be between 4 and 16384.", + "cameraName: wrong type": "cameraName must be a string." + }, + "valid": { + "status": "accepted", + "message": "Rendered still to live.png.", + "undoLabel": "" + } + }, + "look": { + "changesScene": false, + "malformed": 1, + "messages": { + "unknown field": "look has no field 'zzUnknown'; its fields: none." + }, + "valid": { + "status": "accepted", + "message": "Captured the 3D view to look/live-0177.png.", + "undoLabel": "" + } + }, + "createNodeGroup": { + "changesScene": true, + "malformed": 14, + "messages": { + "unknown field": "createNodeGroup has no field 'zzUnknown'; its fields: treeKind, treeKey, interface.", + "treeKind: wrong type": "treeKind must be a string.", + "treeKind: enum miss": "treeKind must be one of geometry.", + "treeKey: wrong type": "treeKey must be a string.", + "treeKey: required missing": "treeKey is required.", + "treeKey: below minLength": "treeKey must have at least 1 characters.", + "treeKey: above maxLength": "treeKey must have at most 63 characters.", + "treeKey: outside charset": "treeKey may contain only letters, digits, space, '.', '_' or '-'.", + "interface: wrong type": "interface must be an array.", + "interface: required missing": "interface is required.", + "interface: below minItems": "interface must have at least 1 items.", + "interface: item wrong type": "interface[0] must be an object.", + "interface: item missing a property": "interface[0].name is required.", + "interface: item unknown property": "interface[0] has no field 'zzUnknown'; its fields: inOut, name, type, default." + }, + "valid": { + "status": "accepted", + "message": "Created node group; interface identifiers: input Geometry=Socket_0, output Geometry=Socket_1, input Count=Socket_2", + "undoLabel": "Brokkr nibu/hands: createNodeGroup ive-0193" + } + }, + "addNode": { + "changesScene": true, + "malformed": 28, + "messages": { + "unknown field": "addNode has no field 'zzUnknown'; its fields: treeKind, treeKey, id, blIdname, location, label, properties, inputs.", + "treeKind: wrong type": "treeKind must be a string.", + "treeKind: enum miss": "treeKind must be one of geometry.", + "treeKey: wrong type": "treeKey must be a string.", + "treeKey: required missing": "treeKey is required.", + "treeKey: below minLength": "treeKey must have at least 1 characters.", + "treeKey: above maxLength": "treeKey must have at most 63 characters.", + "treeKey: outside charset": "treeKey may contain only letters, digits, space, '.', '_' or '-'.", + "id: wrong type": "id must be a string.", + "id: required missing": "id is required.", + "id: below minLength": "id must have at least 1 characters.", + "id: above maxLength": "id must have at most 63 characters.", + "id: outside charset": "id may contain only letters, digits, '.', '_' or '-'.", + "blIdname: wrong type": "blIdname must be a string.", + "blIdname: required missing": "blIdname is required.", + "blIdname: outside charset": "blIdname may contain only letters and digits.", + "blIdname: no prefix": "blIdname must start with one of GeometryNode, FunctionNode, ShaderNode and have at least one more character.", + "blIdname: forbidden part": "blIdname may not contain 'Import'.", + "location: wrong type": "location must be an array.", + "location: below minItems": "location must have at least 2 items.", + "location: above maxItems": "location must have at most 2 items.", + "location: item above maximum": "location[0] must be between -1000000000 and 1000000000.", + "location: item below minimum": "location[0] must be between -1000000000 and 1000000000.", + "location: item wrong type": "location[0] must be a finite number.", + "label: wrong type": "label must be a string.", + "label: above maxLength": "label must have at most 63 characters.", + "properties: wrong type": "properties must be an object.", + "inputs: wrong type": "inputs must be an object." + }, + "valid": { + "status": "accepted", + "message": "Node added.", + "undoLabel": "Brokkr nibu/hands: addNode ive-0223" + } + }, + "linkSockets": { + "changesScene": true, + "malformed": 22, + "messages": { + "unknown field": "linkSockets has no field 'zzUnknown'; its fields: treeKind, treeKey, fromNode, fromSocket, toNode, toSocket.", + "treeKind: wrong type": "treeKind must be a string.", + "treeKind: enum miss": "treeKind must be one of geometry.", + "treeKey: wrong type": "treeKey must be a string.", + "treeKey: required missing": "treeKey is required.", + "treeKey: below minLength": "treeKey must have at least 1 characters.", + "treeKey: above maxLength": "treeKey must have at most 63 characters.", + "treeKey: outside charset": "treeKey may contain only letters, digits, space, '.', '_' or '-'.", + "fromNode: wrong type": "fromNode must be a string.", + "fromNode: required missing": "fromNode is required.", + "fromNode: below minLength": "fromNode must have at least 1 characters.", + "fromNode: above maxLength": "fromNode must have at most 63 characters.", + "fromNode: outside charset": "fromNode may contain only letters, digits, '.', '_' or '-'.", + "fromSocket: wrong type": "fromSocket must be a string.", + "fromSocket: required missing": "fromSocket is required.", + "toNode: wrong type": "toNode must be a string.", + "toNode: required missing": "toNode is required.", + "toNode: below minLength": "toNode must have at least 1 characters.", + "toNode: above maxLength": "toNode must have at most 63 characters.", + "toNode: outside charset": "toNode may contain only letters, digits, '.', '_' or '-'.", + "toSocket: wrong type": "toSocket must be a string.", + "toSocket: required missing": "toSocket is required." + }, + "valid": { + "status": "accepted", + "message": "Linked gin.Socket_0 -> gout.Socket_1.", + "undoLabel": "Brokkr nibu/hands: linkSockets ive-0247" + } + }, + "unlinkSockets": { + "changesScene": true, + "malformed": 20, + "messages": { + "unknown field": "unlinkSockets has no field 'zzUnknown'; its fields: treeKind, treeKey, toNode, toSocket, fromNode, fromSocket.", + "treeKind: wrong type": "treeKind must be a string.", + "treeKind: enum miss": "treeKind must be one of geometry.", + "treeKey: wrong type": "treeKey must be a string.", + "treeKey: required missing": "treeKey is required.", + "treeKey: below minLength": "treeKey must have at least 1 characters.", + "treeKey: above maxLength": "treeKey must have at most 63 characters.", + "treeKey: outside charset": "treeKey may contain only letters, digits, space, '.', '_' or '-'.", + "toNode: wrong type": "toNode must be a string.", + "toNode: required missing": "toNode is required.", + "toNode: below minLength": "toNode must have at least 1 characters.", + "toNode: above maxLength": "toNode must have at most 63 characters.", + "toNode: outside charset": "toNode may contain only letters, digits, '.', '_' or '-'.", + "toSocket: wrong type": "toSocket must be a string.", + "toSocket: required missing": "toSocket is required.", + "fromNode: wrong type": "fromNode must be a string.", + "fromNode: below minLength": "fromNode must have at least 1 characters.", + "fromNode: above maxLength": "fromNode must have at most 63 characters.", + "fromNode: outside charset": "fromNode may contain only letters, digits, '.', '_' or '-'.", + "fromSocket: wrong type": "fromSocket must be a string." + }, + "valid": { + "status": "accepted", + "message": "Removed 1 link(s).", + "undoLabel": "Brokkr nibu/hands: unlinkSockets ive-0269" + } + }, + "removeNode": { + "changesScene": true, + "malformed": 13, + "messages": { + "unknown field": "removeNode has no field 'zzUnknown'; its fields: treeKind, treeKey, id.", + "treeKind: wrong type": "treeKind must be a string.", + "treeKind: enum miss": "treeKind must be one of geometry.", + "treeKey: wrong type": "treeKey must be a string.", + "treeKey: required missing": "treeKey is required.", + "treeKey: below minLength": "treeKey must have at least 1 characters.", + "treeKey: above maxLength": "treeKey must have at most 63 characters.", + "treeKey: outside charset": "treeKey may contain only letters, digits, space, '.', '_' or '-'.", + "id: wrong type": "id must be a string.", + "id: required missing": "id is required.", + "id: below minLength": "id must have at least 1 characters.", + "id: above maxLength": "id must have at most 63 characters.", + "id: outside charset": "id may contain only letters, digits, '.', '_' or '-'." + }, + "valid": { + "status": "accepted", + "message": "Node removed.", + "undoLabel": "Brokkr nibu/hands: removeNode ive-0284" + } + }, + "addModifier": { + "changesScene": true, + "malformed": 16, + "messages": { + "unknown field": "addModifier has no field 'zzUnknown'; its fields: objectName, modifierType, treeKind, treeKey, modifierName.", + "objectName: wrong type": "objectName must be a string.", + "objectName: required missing": "objectName is required.", + "modifierType: wrong type": "modifierType must be a string.", + "modifierType: enum miss": "modifierType must be one of NODES.", + "treeKind: wrong type": "treeKind must be a string.", + "treeKind: enum miss": "treeKind must be one of geometry.", + "treeKey: wrong type": "treeKey must be a string.", + "treeKey: required missing": "treeKey is required.", + "treeKey: below minLength": "treeKey must have at least 1 characters.", + "treeKey: above maxLength": "treeKey must have at most 63 characters.", + "treeKey: outside charset": "treeKey may contain only letters, digits, space, '.', '_' or '-'.", + "modifierName: wrong type": "modifierName must be a string.", + "modifierName: below minLength": "modifierName must have at least 1 characters.", + "modifierName: above maxLength": "modifierName must have at most 63 characters.", + "modifierName: outside charset": "modifierName may contain only letters, digits, space, '.', '_' or '-'." + }, + "valid": { + "status": "accepted", + "message": "Geometry Nodes modifier set.", + "undoLabel": "Brokkr nibu/hands: addModifier ive-0302" + } + }, + "setModifierInput": { + "changesScene": true, + "malformed": 7, + "messages": { + "unknown field": "setModifierInput has no field 'zzUnknown'; its fields: objectName, modifierName, socket, value.", + "objectName: wrong type": "objectName must be a string.", + "objectName: required missing": "objectName is required.", + "modifierName: wrong type": "modifierName must be a string.", + "socket: wrong type": "socket must be a string.", + "socket: required missing": "socket is required.", + "value: required missing": "value is required." + }, + "valid": { + "status": "accepted", + "message": "Modifier input Count set.", + "undoLabel": "Brokkr nibu/hands: setModifierInput ive-0311" + }, + "note": "the intent changed nothing the signature reads (checked by label only)" + }, + "removeModifier": { + "changesScene": true, + "malformed": 7, + "messages": { + "unknown field": "removeModifier has no field 'zzUnknown'; its fields: objectName, modifierName.", + "objectName: wrong type": "objectName must be a string.", + "objectName: required missing": "objectName is required.", + "modifierName: wrong type": "modifierName must be a string.", + "modifierName: below minLength": "modifierName must have at least 1 characters.", + "modifierName: above maxLength": "modifierName must have at most 255 characters.", + "modifierName: forbidden part": "modifierName may not contain '\u0000'." + }, + "valid": { + "status": "accepted", + "message": "Modifier removed.", + "undoLabel": "Brokkr nibu/hands: removeModifier ive-0320" + } + } + }, + "table_actions": [ + "createObject", + "deleteObject", + "setObjectTransform", + "setObjectVisibility", + "setObjectParent", + "setObjectCustomProperty", + "selectObject", + "assignMaterial", + "importGltf", + "exportGltf", + "setCamera", + "setLight", + "setWorld", + "renderStill", + "look", + "createNodeGroup", + "addNode", + "removeNode", + "linkSockets", + "unlinkSockets", + "addModifier", + "removeModifier", + "setModifierInput" + ], + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/live/agent_turn_queue.result.json b/surfaces/blender/tests/live/agent_turn_queue.result.json index e1c803e..ac8d776 100644 --- a/surfaces/blender/tests/live/agent_turn_queue.result.json +++ b/surfaces/blender/tests/live/agent_turn_queue.result.json @@ -16,7 +16,8 @@ "requestedBy": "nibu/hands", "note": "queue test", "undoLabel": "Brokkr nibu/hands: createObject aaa-0001", - "observedAt": "2026-11-27T20:02:43.826604+00:00" + "lookPath": "", + "observedAt": "2026-11-28T02:03:52.780549+00:00" } }, { @@ -47,7 +48,8 @@ "requestedBy": "nibu/hands", "note": "queue test", "undoLabel": "Brokkr nibu/hands: createObject aaa-0001", - "observedAt": "2026-11-27T20:02:43.826604+00:00" + "lookPath": "", + "observedAt": "2026-11-28T02:03:52.780549+00:00" } }, { @@ -63,7 +65,8 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T20:02:45.831074+00:00" + "lookPath": "", + "observedAt": "2026-11-28T02:03:54.875032+00:00" } }, { @@ -79,7 +82,8 @@ "requestedBy": "", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T20:02:47.837505+00:00" + "lookPath": "", + "observedAt": "2026-11-28T02:03:55.934781+00:00" } }, { @@ -135,7 +139,8 @@ "requestedBy": "nibu/hands", "note": "queue test", "undoLabel": "Brokkr nibu/hands: createObject aaa-0001", - "observedAt": "2026-11-27T20:02:43.826604+00:00" + "lookPath": "", + "observedAt": "2026-11-28T02:03:52.780549+00:00" }, "q2_original": { "schema": "brokkr.blender.command_receipt.v0", @@ -147,7 +152,8 @@ "requestedBy": "nibu/hands", "note": "queue test", "undoLabel": "Brokkr nibu/hands: createObject aaa-0001", - "observedAt": "2026-11-27T20:02:43.826604+00:00" + "lookPath": "", + "observedAt": "2026-11-28T02:03:52.780549+00:00" }, "q2_denial": { "schema": "brokkr.blender.command_receipt.v0", @@ -159,7 +165,8 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T20:02:45.831074+00:00" + "lookPath": "", + "observedAt": "2026-11-28T02:03:54.875032+00:00" }, "q3": { "schema": "brokkr.blender.command_receipt.v0", @@ -171,12 +178,13 @@ "requestedBy": "", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T20:02:47.837505+00:00" + "lookPath": "", + "observedAt": "2026-11-28T02:03:55.934781+00:00" }, "q6": [ { "schema": "brokkr.blender.command_receipt.v0", - "commandId": "3414cf427aa549ea9e9a52c4cfc61908", + "commandId": "01683c810bbd449484c96d5984efccd7", "action": "createObject", "status": "denied", "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-int)", @@ -184,11 +192,12 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T20:02:51.875508+00:00" + "lookPath": "", + "observedAt": "2026-11-28T02:04:00.170853+00:00" }, { "schema": "brokkr.blender.command_receipt.v0", - "commandId": "3c53313e68aa4d07ab6e3e330396567d", + "commandId": "bea34b7535da46188b741f55b3592707", "action": "createObject", "status": "denied", "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-list)", @@ -196,7 +205,8 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T20:02:51.901697+00:00" + "lookPath": "", + "observedAt": "2026-11-28T02:04:00.225976+00:00" } ], "q5": [ @@ -210,7 +220,8 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T20:02:53.881094+00:00" + "lookPath": "", + "observedAt": "2026-11-28T02:04:02.331449+00:00" }, { "schema": "brokkr.blender.command_receipt.v0", @@ -222,7 +233,8 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T20:02:53.905589+00:00" + "lookPath": "", + "observedAt": "2026-11-28T02:04:02.387296+00:00" }, { "schema": "brokkr.blender.command_receipt.v0", @@ -234,11 +246,12 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T20:02:53.944684+00:00" + "lookPath": "", + "observedAt": "2026-11-28T02:04:02.439331+00:00" } ] }, - "msgpack": "F:\\aeth-wt\\brokkr-live-pins.e2e\\res\\extensions\\.local\\lib\\python3.13\\site-packages\\msgpack\\__init__.py", + "msgpack": "F:\\aeth-wt\\brokkr-action-table-live\\ext\\.local\\lib\\python3.13\\site-packages\\msgpack\\__init__.py", "msgpack_packer": "msgpack.fallback", "msgpack_purepython_env": "", "ok": true diff --git a/surfaces/blender/tests/live/agent_turn_undo.result.json b/surfaces/blender/tests/live/agent_turn_undo.result.json index 248b79b..1f3ef58 100644 --- a/surfaces/blender/tests/live/agent_turn_undo.result.json +++ b/surfaces/blender/tests/live/agent_turn_undo.result.json @@ -197,7 +197,7 @@ "name": "exportGltf and renderStill accepted with no undoLabel", "ok": true, "detail": [ - "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-0ge72kvx\\object.glb (3484 bytes).", + "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-lmbbnbpa\\object.glb (3484 bytes).", "Rendered still to object.png." ] }, @@ -270,7 +270,7 @@ "intent": "exportGltf", "status": "accepted", "undoLabel": "", - "message": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-0ge72kvx\\object.glb (3484 bytes)." + "message": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-lmbbnbpa\\object.glb (3484 bytes)." }, { "intent": "renderStill", diff --git a/surfaces/blender/tests/live/export_gltf.result.json b/surfaces/blender/tests/live/export_gltf.result.json index ff10cae..5a154ee 100644 --- a/surfaces/blender/tests/live/export_gltf.result.json +++ b/surfaces/blender/tests/live/export_gltf.result.json @@ -9,7 +9,7 @@ { "name": "glb accepted", "ok": true, - "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\all.glb (72752 bytes)." + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-e1blbtu2\\all.glb (72752 bytes)." }, { "name": "glb written, no staging folder", @@ -26,12 +26,12 @@ { "name": "extras=false leaves them out", "ok": true, - "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\noextras.glb (72720 bytes)." + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-e1blbtu2\\noextras.glb (72720 bytes)." }, { "name": "selection exports only the sphere", "ok": true, - "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\only.glb (70240 bytes)." + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-e1blbtu2\\only.glb (70240 bytes)." }, { "name": "selection restored", @@ -44,7 +44,7 @@ { "name": "gltf accepted", "ok": true, - "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\sep\\s.gltf (2840 bytes)." + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-e1blbtu2\\sep\\s.gltf (2840 bytes)." }, { "name": "gltf writes its bin and the texture beside it", @@ -108,7 +108,7 @@ { "name": "the same name then exports", "ok": true, - "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\fresh\\deep\\x.glb (72752 bytes)." + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-e1blbtu2\\fresh\\deep\\x.glb (72752 bytes)." } ] } \ No newline at end of file diff --git a/surfaces/blender/tests/live/gn_actions.py b/surfaces/blender/tests/live/gn_actions.py index 9d86395..b5b2e0e 100644 --- a/surfaces/blender/tests/live/gn_actions.py +++ b/surfaces/blender/tests/live/gn_actions.py @@ -152,7 +152,7 @@ check("unwired exposed input leaves result", srt(evaluated(t, "ScatterHost")["in r = act(t, action="addNode", treeKey="Scatter", id="bad", blIdname="GeometryNodeMeshCube", inputs={"Nope": 1}); check("unknown input refused", r["status"] == "failed", r["message"]) check("refused addNode left no node", not any(n.get("brokkr_id") == "bad" for n in bpy.data.node_groups["Scatter"].nodes)) r = act(t, action="addNode", treeKey="Scatter", id="bad2", blIdname="GeometryNodeMeshCube", properties={"nope": 1}); check("unknown property refused", r["status"] == "failed", r["message"]) -r = act(t, action="addNode", treeKey="Scatter", id="bad3", blIdname="GeometryNodeImportOBJ"); check("file-reading node refused", r["status"] == "failed", r["message"]) +r = act(t, action="addNode", treeKey="Scatter", id="bad3", blIdname="GeometryNodeImportOBJ"); check("file-reading node refused", r["status"] == "denied", r["message"]) r = act(t, action="addNode", treeKey="Scatter", id="bad4", blIdname="GeometryNodeNoSuchThing"); check("unknown node type refused", r["status"] == "failed", r["message"]) r = act(t, action="linkSockets", treeKey="Scatter", fromNode="cone", fromSocket="Mesh", toNode="dist", toSocket="Density"); check("invalid link refused and removed", r["status"] == "failed" and not any(l.to_socket.name == "Density" for l in bpy.data.node_groups["Scatter"].links), r["message"]) r = act(t, action="setModifierInput", objectName="ScatterHost", modifierName="GN", socket="Seed", value="x"); check("wrong value type refused", r["status"] == "failed", r["message"]) @@ -167,7 +167,7 @@ after = [(l.from_node.get("brokkr_id"), l.to_socket.identifier) for l in bpy.dat check("refused link keeps the link it would have replaced", r["status"] == "failed" and before == after == [("cube", "Points")], (r["message"], before, after)) ok(t2, action="createObject", objectType="CAMERA", name="Cam") r = act(t2, action="addModifier", objectName="Cam", treeKey="L"); check("modifier on a camera refused clearly", r["status"] == "failed" and "CAMERA" in r["message"], r["message"]) -r = act(t2, action="addNode", treeKey="L", id="n\n", blIdname="ShaderNodeMath"); check("trailing newline in an id refused", r["status"] == "failed", r["message"]) +r = act(t2, action="addNode", treeKey="L", id="n\n", blIdname="ShaderNodeMath"); check("trailing newline in an id refused", r["status"] == "denied", r["message"]) # off-origin host: vertices are local, instances world, bounds kept apart t3 = fresh() graph(t3, "Off", GEO_OUT, [dict(id="circle", blIdname="GeometryNodeMeshCircle", inputs={"Vertices": 4, "Radius": 1.0}), dict(id="cube", blIdname="GeometryNodeMeshCube"), dict(id="iop", blIdname="GeometryNodeInstanceOnPoints"), dict(id="join", blIdname="GeometryNodeJoinGeometry")], diff --git a/surfaces/blender/tests/live/gn_actions.result.json b/surfaces/blender/tests/live/gn_actions.result.json index cdcc1f5..3253af1 100644 --- a/surfaces/blender/tests/live/gn_actions.result.json +++ b/surfaces/blender/tests/live/gn_actions.result.json @@ -1,5 +1,5 @@ { - "blender": "5.2.3 LTS", + "blender": "5.3.0", "checks": [ { "name": "createNodeGroup Ring", @@ -435,7 +435,7 @@ { "name": "file-reading node refused", "ok": true, - "detail": "node type GeometryNodeImportOBJ is not allowed in this cut (Import)." + "detail": "blIdname may not contain 'Import'." }, { "name": "unknown node type refused", @@ -514,7 +514,7 @@ { "name": "trailing newline in an id refused", "ok": true, - "detail": "id must be 1..63 characters of letters, digits, space, '.', '_' or '-'." + "detail": "id may contain only letters, digits, '.', '_' or '-'." }, { "name": "createNodeGroup Off", @@ -955,7 +955,7 @@ "detail": [ 59, 59, - 0.008 + 0.013 ] }, { @@ -1052,7 +1052,7 @@ "name": "2000x2000 instanced grid: capture is bounded", "ok": true, "detail": [ - 1.2, + 2.17, 99999, false ] @@ -1086,12 +1086,12 @@ "name": "2000x2000 mesh grid: counts only, bounded", "ok": true, "detail": [ - 0.05, + 0.0, 4000000 ] } ], - "cycle_probe_seconds": 0.008, - "capture_2000_grid_instanced_seconds": 1.198, - "capture_2000_grid_mesh_seconds": 0.045 + "cycle_probe_seconds": 0.013, + "capture_2000_grid_instanced_seconds": 2.173, + "capture_2000_grid_mesh_seconds": 0.002 } \ No newline at end of file diff --git a/surfaces/blender/tests/live/perception_fixes.result.json b/surfaces/blender/tests/live/perception_fixes.result.json index af2638c..11ca160 100644 --- a/surfaces/blender/tests/live/perception_fixes.result.json +++ b/surfaces/blender/tests/live/perception_fixes.result.json @@ -5,7 +5,7 @@ "name": "window up: the region capture, source named", "ok": true, "detail": { - "commandId": "01a21f023e60712180b8b5afee5b2621", + "commandId": "01a21fe56d007f03a2355733ee33a416", "action": "look", "captureSource": "region", "editSelection": [], @@ -14,15 +14,15 @@ "editedSinceLookNote": "", "humanEditSeq": 0, "humanEditsSinceLook": 0, - "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f023e60712180b8b5afee5b2621.png", - "message": "Captured the 3D view to look/01a21f023e60712180b8b5afee5b2621.png.", + "lookPath": "F:\\aeth-wt\\brokkr-action-table-live\\scratch3\\out\\look\\01a21fe56d007f03a2355733ee33a416.png", + "message": "Captured the 3D view to look/01a21fe56d007f03a2355733ee33a416.png.", "note": "", "objectName": "", - "observedAt": "2026-11-27T21:56:11.107854+00:00", + "observedAt": "2026-11-28T02:04:19.958143+00:00", "requestedBy": "nibu/hands", "sceneUpdateSeq": 0, "schema": "brokkr.blender.command_receipt.v0", - "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "sessionId": "f60fdb7ac4d04d6bbf6e2992d460d162", "status": "accepted", "undoLabel": "" } @@ -87,7 +87,7 @@ "name": "after her link of an object: the receipt says the attribution is coarse", "ok": true, "detail": { - "commandId": "01a21f02711f7571991decbd06059938", + "commandId": "01a21fe5a09b70728ba3f974ad47eecc", "action": "look", "captureSource": "region", "editSelection": [], @@ -101,15 +101,15 @@ "editedSinceLookNote": "Coarse: all objects flagged; editedSinceLook may name objects she did not touch.", "humanEditSeq": 4, "humanEditsSinceLook": 1, - "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f02711f7571991decbd06059938.png", - "message": "Captured the 3D view to look/01a21f02711f7571991decbd06059938.png.", + "lookPath": "F:\\aeth-wt\\brokkr-action-table-live\\scratch3\\out\\look\\01a21fe5a09b70728ba3f974ad47eecc.png", + "message": "Captured the 3D view to look/01a21fe5a09b70728ba3f974ad47eecc.png.", "note": "", "objectName": "", - "observedAt": "2026-11-27T21:56:23.908406+00:00", + "observedAt": "2026-11-28T02:04:32.629832+00:00", "requestedBy": "nibu/hands", "sceneUpdateSeq": 5, "schema": "brokkr.blender.command_receipt.v0", - "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "sessionId": "f60fdb7ac4d04d6bbf6e2992d460d162", "status": "accepted", "undoLabel": "" } @@ -118,7 +118,7 @@ "name": "after a plain move: not coarse, only the Cube named", "ok": true, "detail": { - "commandId": "01a21f027a1873a1a21df913136a4d49", + "commandId": "01a21fe5a8a677439cb3f76df5eed508", "action": "look", "captureSource": "region", "editSelection": [], @@ -129,15 +129,15 @@ "editedSinceLookNote": "", "humanEditSeq": 5, "humanEditsSinceLook": 1, - "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f027a1873a1a21df913136a4d49.png", - "message": "Captured the 3D view to look/01a21f027a1873a1a21df913136a4d49.png.", + "lookPath": "F:\\aeth-wt\\brokkr-action-table-live\\scratch3\\out\\look\\01a21fe5a8a677439cb3f76df5eed508.png", + "message": "Captured the 3D view to look/01a21fe5a8a677439cb3f76df5eed508.png.", "note": "", "objectName": "", - "observedAt": "2026-11-27T21:56:26.306053+00:00", + "observedAt": "2026-11-28T02:04:34.918968+00:00", "requestedBy": "nibu/hands", "sceneUpdateSeq": 6, "schema": "brokkr.blender.command_receipt.v0", - "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "sessionId": "f60fdb7ac4d04d6bbf6e2992d460d162", "status": "accepted", "undoLabel": "" } @@ -146,7 +146,7 @@ "name": "after her undo: coarse", "ok": true, "detail": { - "commandId": "01a21f027ec27dd0bda5c62b0974531a", + "commandId": "01a21fe5ad537f33846b930d41821f0e", "action": "look", "captureSource": "region", "editSelection": [], @@ -159,15 +159,15 @@ "editedSinceLookNote": "Coarse: all objects flagged; editedSinceLook may name objects she did not touch.", "humanEditSeq": 7, "humanEditsSinceLook": 2, - "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f027ec27dd0bda5c62b0974531a.png", - "message": "Captured the 3D view to look/01a21f027ec27dd0bda5c62b0974531a.png.", + "lookPath": "F:\\aeth-wt\\brokkr-action-table-live\\scratch3\\out\\look\\01a21fe5ad537f33846b930d41821f0e.png", + "message": "Captured the 3D view to look/01a21fe5ad537f33846b930d41821f0e.png.", "note": "", "objectName": "", - "observedAt": "2026-11-27T21:56:27.505456+00:00", + "observedAt": "2026-11-28T02:04:36.080195+00:00", "requestedBy": "nibu/hands", "sceneUpdateSeq": 7, "schema": "brokkr.blender.command_receipt.v0", - "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "sessionId": "f60fdb7ac4d04d6bbf6e2992d460d162", "status": "accepted", "undoLabel": "" } @@ -186,21 +186,21 @@ "ok": true, "detail": { "new": [ - 221, - 191, - 185, - 197, - 193 + 262, + 192, + 187, + 188, + 187 ], "old": [ - 977, - 950, - 974, - 1059, - 956 + 1044, + 1060, + 1010, + 1044, + 1313 ], - "new_median": 193, - "old_median": 974 + "new_median": 188, + "old_median": 1044 } }, { @@ -215,7 +215,7 @@ ], "minimised": { "a": { - "commandId": "01a21f02458877a186fe6a31fe3b32d6", + "commandId": "01a21fe575527fa0b4a36ecdbdd38ae6", "action": "look", "captureSource": "offscreen", "editSelection": [], @@ -224,20 +224,20 @@ "editedSinceLookNote": "", "humanEditSeq": 0, "humanEditsSinceLook": 0, - "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f02458877a186fe6a31fe3b32d6.png", - "message": "Captured the 3D view to look/01a21f02458877a186fe6a31fe3b32d6.png.", + "lookPath": "F:\\aeth-wt\\brokkr-action-table-live\\scratch3\\out\\look\\01a21fe575527fa0b4a36ecdbdd38ae6.png", + "message": "Captured the 3D view to look/01a21fe575527fa0b4a36ecdbdd38ae6.png.", "note": "", "objectName": "", - "observedAt": "2026-11-27T21:56:13.275722+00:00", + "observedAt": "2026-11-28T02:04:22.160175+00:00", "requestedBy": "nibu/hands", "sceneUpdateSeq": 0, "schema": "brokkr.blender.command_receipt.v0", - "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "sessionId": "f60fdb7ac4d04d6bbf6e2992d460d162", "status": "accepted", "undoLabel": "" }, "b": { - "commandId": "01a21f024b1876d0a4ec6281a49404a2", + "commandId": "01a21fe57bb173238bf0f2419a61ec46", "action": "look", "captureSource": "offscreen", "editSelection": [], @@ -248,15 +248,15 @@ "editedSinceLookNote": "", "humanEditSeq": 1, "humanEditsSinceLook": 1, - "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f024b1876d0a4ec6281a49404a2.png", - "message": "Captured the 3D view to look/01a21f024b1876d0a4ec6281a49404a2.png.", + "lookPath": "F:\\aeth-wt\\brokkr-action-table-live\\scratch3\\out\\look\\01a21fe57bb173238bf0f2419a61ec46.png", + "message": "Captured the 3D view to look/01a21fe57bb173238bf0f2419a61ec46.png.", "note": "", "objectName": "", - "observedAt": "2026-11-27T21:56:14.485857+00:00", + "observedAt": "2026-11-28T02:04:23.398210+00:00", "requestedBy": "nibu/hands", "sceneUpdateSeq": 1, "schema": "brokkr.blender.command_receipt.v0", - "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "sessionId": "f60fdb7ac4d04d6bbf6e2992d460d162", "status": "accepted", "undoLabel": "" }, @@ -271,27 +271,27 @@ "edit_selection_parts_ms": { "from_edit_mesh": 0.0, "totals": 0.0, - "verts": 24.7, - "edges": 79.6, - "faces": 33.2 + "verts": 27.4, + "edges": 70.9, + "faces": 27.4 }, "edit_selection_ms": { "new": [ - 221, - 191, - 185, - 197, - 193 + 262, + 192, + 187, + 188, + 187 ], "old": [ - 977, - 950, - 974, - 1059, - 956 + 1044, + 1060, + 1010, + 1044, + 1313 ], - "new_median": 193, - "old_median": 974 + "new_median": 188, + "old_median": 1044 } }, "ok": true diff --git a/surfaces/blender/tests/live/refusals.py b/surfaces/blender/tests/live/refusals.py index 3abd794..16823cb 100644 --- a/surfaces/blender/tests/live/refusals.py +++ b/surfaces/blender/tests/live/refusals.py @@ -64,9 +64,9 @@ t.bpy = bpy for kind in ("LIGHT", "EMPTY", "CAMERA"): r = act("createObject", objectType=kind, meshType="CYLINDER") - check("meshType on %s is refused" % kind, r["status"] == "failed" and "MESH" in r["message"], r["message"]) + check("meshType on %s is refused" % kind, r["status"] == "denied" and "MESH" in r["message"], r["message"]) check("and nothing was created for them", len([o for o in bpy.data.objects if o.type in ("LIGHT", "EMPTY")]) == 0) -r = act("createObject", objectType="MESH", meshType="cube") +r = act("createObject", objectType="MESH", meshType="CUBE") check("meshType CUBE on a MESH still works", r["status"] == "accepted", r["message"]) shutil.rmtree(work, ignore_errors=True) diff --git a/surfaces/blender/tests/live/refusals.result.json b/surfaces/blender/tests/live/refusals.result.json index 0047130..9c06d28 100644 --- a/surfaces/blender/tests/live/refusals.result.json +++ b/surfaces/blender/tests/live/refusals.result.json @@ -31,17 +31,17 @@ { "name": "meshType on LIGHT is refused", "ok": true, - "detail": "meshType applies only to objectType MESH, not LIGHT." + "detail": "meshType applies only when objectType is one of MESH." }, { "name": "meshType on EMPTY is refused", "ok": true, - "detail": "meshType applies only to objectType MESH, not EMPTY." + "detail": "meshType applies only when objectType is one of MESH." }, { "name": "meshType on CAMERA is refused", "ok": true, - "detail": "meshType applies only to objectType MESH, not CAMERA." + "detail": "meshType applies only when objectType is one of MESH." }, { "name": "and nothing was created for them", From c348e5d6342ffcd1cb0146e8daa64220ac6a1a70 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 03:09:32 +0100 Subject: [PATCH 39/63] live/action_table.py: name the environment variables that really isolate Blender's extensions Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/tests/live/action_table.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/surfaces/blender/tests/live/action_table.py b/surfaces/blender/tests/live/action_table.py index 98cbdf8..0c3967a 100644 --- a/surfaces/blender/tests/live/action_table.py +++ b/surfaces/blender/tests/live/action_table.py @@ -5,7 +5,10 @@ BROKKR_CULTLIB= blender --python action_table.py -- -Run it in a Blender whose resource path is fresh (BLENDER_USER_RESOURCE_PATH). Every intent is put into the node +Run it in a Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(this Blender build ignores BLENDER_USER_RESOURCE_PATH, so `extension install-file` would land in the operator's own +extensions folder), the extension installed there with `blender --command extension install-file --repo user_default +--enable ` under the same variables. Every intent is put into the node database as brokkr-ctl does and answered by the add-on's own 1 s drain (the sink is on). For every action in actions.json: * malformed intents generated from its table entry (an unknown field, a wrong type, an enum miss, a bound miss, From f7a43c19fd4d3871abac1114b66a7c4722de0533 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 03:44:05 +0100 Subject: [PATCH 40/63] Soul s1 fixes: private Blender env enforced, whole floats for integers, validate never raises, parent loops refused, timeout says queued or claimed - Every live script that installs or enables the extension refuses to run unless BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS are set and Blender's extensions folder is the one named (Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH); every other live script and install.md say so; the stale docstrings are corrected. - validate returns integer fields as int (1920.0 reaches Blender as 1920); five fixture cases added for both validators. - validate sorts unknown keys by str, so a document with mixed key types is a denied receipt, not a raise after the claim; pinned with hostile documents and through the drain. - setObjectParent refuses a parent that is the object or one of its own children before any undo step. - brokkr-ctl on timeout prints whether the intent is still queued (not run) or was claimed with no receipt (may or may not have run); group help says so. - live action_table re-run: 205 of 205, renderStill sample sends 8.0. Co-Authored-By: Claude Sonnet 5.5 --- brokkr-ctl/src/blender.rs | 17 +++- brokkr-ctl/tests/cli.rs | 21 +++++ .../blender/brokkr_bridge/action_table.py | 7 +- .../blender/brokkr_bridge/blender_target.py | 5 + surfaces/blender/docs/install.md | 5 + surfaces/blender/tests/action_cases.json | 7 +- surfaces/blender/tests/live/action_table.py | 17 +++- .../tests/live/action_table.result.json | 94 +++++++++---------- .../blender/tests/live/agent_turn_queue.py | 9 ++ .../blender/tests/live/agent_turn_undo.py | 2 + surfaces/blender/tests/live/export_gltf.py | 2 + surfaces/blender/tests/live/gn_actions.py | 2 + surfaces/blender/tests/live/gn_recreation.py | 2 + surfaces/blender/tests/live/headless_smoke.py | 2 + .../blender/tests/live/material_colour.py | 2 + surfaces/blender/tests/live/perception.py | 12 ++- .../blender/tests/live/perception_fixes.py | 10 +- surfaces/blender/tests/live/refusals.py | 2 + surfaces/blender/tests/live/stop_presence.py | 9 ++ surfaces/blender/tests/test_action_table.py | 31 ++++++ surfaces/blender/tests/test_agent_turn.py | 19 ++++ 21 files changed, 219 insertions(+), 58 deletions(-) diff --git a/brokkr-ctl/src/blender.rs b/brokkr-ctl/src/blender.rs index e404585..dc47866 100644 --- a/brokkr-ctl/src/blender.rs +++ b/brokkr-ctl/src/blender.rs @@ -278,6 +278,20 @@ fn wait_for_receipt( } None => { println!("status: timeout"); + // The add-on deletes an intent when it claims it, before it runs, so the queue says which timeout this is. + let key = format!("{INTENT_PREFIX}{id}"); + let queued = store + .pull_all()? + .iter() + .any(|e| e.key == key && e.r#type == INTENT_SCHEMA); + println!( + "message: {}", + if queued { + "the intent is still queued: Blender has not claimed it (is Agent Commands on and the add-on running?); it has not run" + } else { + "Blender claimed the intent but wrote no receipt: it may or may not have run; look at the scene before sending it again" + } + ); Ok(Outcome::Timeout.code()) } } @@ -412,7 +426,8 @@ brokkr-ctl blender: send typed intents to the live Blender add-on and read what Every command needs --store or $BROKKR_BLENDER_STORE (the add-on's .ccmp). send needs $EUREKA_INSTANCE and --agent or $BROKKR_AGENT; requestedBy is '/'. Output is 'key: value' lines. Exit: 0 accepted, 2 denied or failed, 3 stopped, 4 timeout, -1 usage or store error. send refuses an intent the action table refuses (exit 1, nothing written); +1 usage or store error. On timeout a message says whether the intent is still queued (not run) or was claimed by +Blender with no receipt (it may or may not have run). send refuses an intent the action table refuses (exit 1, nothing written); the add-on decides the rest and its refusal comes back in the receipt. " .to_string() diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs index 59d0444..9936d7f 100644 --- a/brokkr-ctl/tests/cli.rs +++ b/brokkr-ctl/tests/cli.rs @@ -162,6 +162,27 @@ fn wait_matches_the_exact_receipt_key() { assert!(stdout(&output).contains("status: timeout")); } +/// Exit 4 is two situations the sender must tell apart: the intent was never claimed (still in the queue, not run), +/// or Blender claimed it (deleted it from the queue) and no receipt landed (it may have run). +#[test] +fn a_timeout_says_whether_the_intent_is_still_queued_or_was_claimed() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("seed", "accepted")]); + let sent = ctl(&path, &["send", "createObject", "--agent", "hands", "--timeout", "0.3"], Some("nibu")); + assert_eq!(sent.status.code(), Some(4)); + let text = stdout(&sent); + assert!(text.contains("status: timeout") && text.contains("still queued") && text.contains("it has not run"), "{text}"); + let id = text.lines().find_map(|l| l.strip_prefix("commandId: ")).unwrap().to_string(); + // Blender claims it: the intent leaves the queue, and no receipt is written + let mut store = SingleFileMessagePackBackingStore::new(&path); + let queued = store.pull_all().unwrap().into_iter().find(|e| e.key == format!("blender/commands/{id}")).unwrap(); + store.delete(&queued).unwrap(); + let waited = ctl(&path, &["wait", &id, "--timeout", "0.3"], None); + assert_eq!(waited.status.code(), Some(4)); + let text = stdout(&waited); + assert!(text.contains("claimed the intent but wrote no receipt") && text.contains("may or may not have run"), "{text}"); +} + #[test] fn exit_code_follows_the_receipt() { let dir = tempfile::tempdir().unwrap(); diff --git a/surfaces/blender/brokkr_bridge/action_table.py b/surfaces/blender/brokkr_bridge/action_table.py index dafbe9e..3ecaa2f 100644 --- a/surfaces/blender/brokkr_bridge/action_table.py +++ b/surfaces/blender/brokkr_bridge/action_table.py @@ -117,7 +117,8 @@ def _check_spec(spec: dict[str, Any], where: str, charsets: dict, siblings: dict def validate(command: dict[str, Any]) -> dict[str, Any]: - """The normalized copy of an intent (nulls dropped, defaults filled), or IntentInvalid naming the rule.""" + """The normalized copy of an intent (nulls dropped, whole numbers of integer fields as int, defaults filled), or + IntentInvalid naming the rule. It raises nothing else, whatever the document holds.""" action = command.get("action", "") row = entry(action) if row is None: @@ -126,6 +127,8 @@ def validate(command: dict[str, Any]) -> dict[str, Any]: _fields(row["fields"], present, None, action, set(table()["envelope"])) result = dict(present) for field in row["fields"]: + if field["type"] == "integer" and field["name"] in result: + result[field["name"]] = int(result[field["name"]]) # a whole float (1920.0) is the same intent; Blender refuses a float for an int property if field["name"] not in result and "default" in field: result[field["name"]] = field["default"] return result @@ -135,7 +138,7 @@ def _fields(specs: list[dict[str, Any]], values: dict[str, Any], parent: str | N """The fields of an action (parent None) or of a closed object: unknown names first, sorted, then each declared field in table order.""" declared = [s["name"] for s in specs] - for key in sorted(k for k in values if k not in skip and k not in declared): + for key in sorted((k for k in values if k not in skip and k not in declared), key=str): # str: a store writer may mix key types raise IntentInvalid(f"{where} has no field '{key}'; its fields: {_list(declared) or 'none'}.") for spec in specs: path = spec["name"] if parent is None else f"{parent}.{spec['name']}" diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 4ab155d..f87da9c 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -775,6 +775,11 @@ class BrokkrBlenderTarget: parent = self.bpy.data.objects.get(parent_name) if parent_name else None if parent_name and parent is None: return self._receipt(command, "failed", f"Parent Blender object was not found: {parent_name}", obj.name) + ancestor = parent + while ancestor is not None: # Blender raises for a loop after the undo step is owed: refuse it before + if ancestor.name == obj.name: + raise sa.ActionRefused(f"{obj.name!r} cannot be parented to itself or to one of its own children.") + ancestor = getattr(ancestor, "parent", None) obj.parent = parent return self._receipt(command, "accepted", "Blender object parent updated.", obj.name) diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 337b2e3..1bd94b9 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -41,6 +41,11 @@ blender --command extension build --source-dir surfaces/blender/brokkr_bridge -- blender --command extension install-file --repo user_default --enable /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. diff --git a/surfaces/blender/tests/action_cases.json b/surfaces/blender/tests/action_cases.json index fb5a8e0..2c082f1 100644 --- a/surfaces/blender/tests/action_cases.json +++ b/surfaces/blender/tests/action_cases.json @@ -229,5 +229,10 @@ {"action": "unlinkSockets", "fields": {"treeKey": "G", "toNode": "b", "toSocket": "i"}, "expect": "ok"}, {"action": "addModifier", "fields": {"objectName": "o", "treeKey": "G"}, "expect": "ok"}, {"action": "removeModifier", "fields": {"objectName": "o"}, "expect": "ok"}, - {"action": "setModifierInput", "fields": {"objectName": "o", "socket": "s", "value": 1}, "expect": "ok"} + {"action": "setModifierInput", "fields": {"objectName": "o", "socket": "s", "value": 1}, "expect": "ok"}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 1920.0, "resolutionY": 1080.0}, "expect": "ok"}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionY": 4.0}, "expect": "ok"}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 3.0}, "expect": "resolutionX must be between 4 and 16384."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 1920.5}, "expect": "resolutionX must be a whole number."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionY": 16384.0}, "expect": "ok"} ] diff --git a/surfaces/blender/tests/live/action_table.py b/surfaces/blender/tests/live/action_table.py index 0c3967a..24db485 100644 --- a/surfaces/blender/tests/live/action_table.py +++ b/surfaces/blender/tests/live/action_table.py @@ -5,10 +5,9 @@ BROKKR_CULTLIB= blender --python action_table.py -- -Run it in a Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories -(this Blender build ignores BLENDER_USER_RESOURCE_PATH, so `extension install-file` would land in the operator's own -extensions folder), the extension installed there with `blender --command extension install-file --repo user_default ---enable ` under the same variables. Every intent is put into the node +Run it in Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH; without them the operator's own extensions folder is used). The script +refuses to run when they are unset. Every intent is put into the node database as brokkr-ctl does and answered by the add-on's own 1 s drain (the sink is on). For every action in actions.json: * malformed intents generated from its table entry (an unknown field, a wrong type, an enum miss, a bound miss, @@ -29,6 +28,14 @@ from pathlib import Path import bpy +import os as _os + +for _name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): + if not _os.environ.get(_name): # this Blender ignores BLENDER_USER_RESOURCE_PATH: without these, her own extensions folder is used + raise SystemExit(f"{_name} is not set: run this in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") +if _os.path.normcase(_os.path.abspath(bpy.utils.user_resource("EXTENSIONS"))) != _os.path.normcase(_os.path.abspath(_os.environ["BLENDER_USER_EXTENSIONS"])): + raise SystemExit("Blender's extensions folder is not BLENDER_USER_EXTENSIONS; refusing to touch it") + SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() SCRATCH.mkdir(parents=True, exist_ok=True) OUT = sys.argv[sys.argv.index("--") + 1] @@ -142,7 +149,7 @@ SAMPLES = [ # (action, prep intents queued and run unmeasured first, the valid ("setCamera", [], {"targetObjectName": "Camera", "lens": 35, "cameraType": "PANO", "panoramaType": "FISHEYE_EQUIDISTANT", "active": True}), ("setLight", [], {"targetObjectName": "Light", "energy": 500, "color": [1, 0.5, 0], "lightType": "SUN"}), ("setWorld", [], {"color": [0.1, 0.1, 0.2], "strength": 1.5}), - ("renderStill", [], {"outputPath": "live.png", "engine": "CYCLES", "resolutionX": 8, "resolutionY": 8}), + ("renderStill", [], {"outputPath": "live.png", "engine": "CYCLES", "resolutionX": 8.0, "resolutionY": 8}), # a whole float: the table hands Blender an int ("look", [], {}), ("createNodeGroup", [], {"treeKey": "LiveG", "interface": [{"inOut": "INPUT", "name": "Geometry", "type": "Geometry"}, {"inOut": "OUTPUT", "name": "Geometry", "type": "Geometry"}, diff --git a/surfaces/blender/tests/live/action_table.result.json b/surfaces/blender/tests/live/action_table.result.json index b21b4c1..981a3a6 100644 --- a/surfaces/blender/tests/live/action_table.result.json +++ b/surfaces/blender/tests/live/action_table.result.json @@ -24,7 +24,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0001", "lookPath": "", - "observedAt": "2026-11-28T01:56:40.145813+00:00" + "observedAt": "2026-11-28T02:36:27.076161+00:00" } }, { @@ -72,7 +72,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0024", "lookPath": "", - "observedAt": "2026-11-28T01:56:45.785882+00:00" + "observedAt": "2026-11-28T02:36:32.724431+00:00" } }, { @@ -104,7 +104,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0026", "lookPath": "", - "observedAt": "2026-11-28T01:56:49.944500+00:00" + "observedAt": "2026-11-28T02:36:36.860973+00:00" } }, { @@ -156,7 +156,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: deleteObject ive-0030", "lookPath": "", - "observedAt": "2026-11-28T01:56:54.485651+00:00" + "observedAt": "2026-11-28T02:36:41.174327+00:00" } }, { @@ -188,7 +188,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0031", "lookPath": "", - "observedAt": "2026-11-28T01:56:56.566254+00:00" + "observedAt": "2026-11-28T02:36:43.258961+00:00" } }, { @@ -238,7 +238,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: setObjectTransform ive-0053", "lookPath": "", - "observedAt": "2026-11-28T01:57:03.202116+00:00" + "observedAt": "2026-11-28T02:36:49.152690+00:00" } }, { @@ -270,7 +270,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0054", "lookPath": "", - "observedAt": "2026-11-28T01:57:05.306686+00:00" + "observedAt": "2026-11-28T02:36:51.255025+00:00" } }, { @@ -320,7 +320,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: setObjectVisibility ive-0059", "lookPath": "", - "observedAt": "2026-11-28T01:57:09.874099+00:00" + "observedAt": "2026-11-28T02:36:55.787695+00:00" } }, { @@ -352,7 +352,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0060", "lookPath": "", - "observedAt": "2026-11-28T01:57:11.974525+00:00" + "observedAt": "2026-11-28T02:36:57.891977+00:00" } }, { @@ -402,7 +402,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: setObjectParent ive-0065", "lookPath": "", - "observedAt": "2026-11-28T01:57:16.563563+00:00" + "observedAt": "2026-11-28T02:37:02.443984+00:00" } }, { @@ -434,7 +434,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0066", "lookPath": "", - "observedAt": "2026-11-28T01:57:18.681337+00:00" + "observedAt": "2026-11-28T02:37:04.556676+00:00" } }, { @@ -484,7 +484,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: setObjectCustomProperty ive-0072", "lookPath": "", - "observedAt": "2026-11-28T01:57:22.508309+00:00" + "observedAt": "2026-11-28T02:37:09.259197+00:00" } }, { @@ -516,7 +516,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0073", "lookPath": "", - "observedAt": "2026-11-28T01:57:24.630024+00:00" + "observedAt": "2026-11-28T02:37:11.382979+00:00" } }, { @@ -566,7 +566,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: selectObject ive-0078", "lookPath": "", - "observedAt": "2026-11-28T01:57:29.310576+00:00" + "observedAt": "2026-11-28T02:37:16.017922+00:00" } }, { @@ -598,7 +598,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0079", "lookPath": "", - "observedAt": "2026-11-28T01:57:31.515585+00:00" + "observedAt": "2026-11-28T02:37:18.151455+00:00" } }, { @@ -648,7 +648,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: assignMaterial ive-0090", "lookPath": "", - "observedAt": "2026-11-28T01:57:37.550809+00:00" + "observedAt": "2026-11-28T02:37:23.926592+00:00" } }, { @@ -680,7 +680,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0091", "lookPath": "", - "observedAt": "2026-11-28T01:57:39.704717+00:00" + "observedAt": "2026-11-28T02:37:26.063118+00:00" } }, { @@ -730,7 +730,7 @@ "note": "", "undoLabel": "", "lookPath": "", - "observedAt": "2026-11-28T01:57:48.919027+00:00" + "observedAt": "2026-11-28T02:37:33.358972+00:00" } }, { @@ -757,7 +757,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0103", "lookPath": "", - "observedAt": "2026-11-28T01:57:51.228716+00:00" + "observedAt": "2026-11-28T02:37:35.528127+00:00" } }, { @@ -807,7 +807,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: importGltf ive-0107", "lookPath": "", - "observedAt": "2026-11-28T01:57:56.255504+00:00" + "observedAt": "2026-11-28T02:37:40.218377+00:00" } }, { @@ -839,7 +839,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0108", "lookPath": "", - "observedAt": "2026-11-28T01:57:58.437908+00:00" + "observedAt": "2026-11-28T02:37:42.369543+00:00" } }, { @@ -895,7 +895,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: setCamera ive-0129", "lookPath": "", - "observedAt": "2026-11-28T01:58:11.054773+00:00" + "observedAt": "2026-11-28T02:37:54.650323+00:00" } }, { @@ -927,7 +927,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0130", "lookPath": "", - "observedAt": "2026-11-28T01:58:13.248452+00:00" + "observedAt": "2026-11-28T02:37:56.820173+00:00" } }, { @@ -983,7 +983,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: setLight ive-0145", "lookPath": "", - "observedAt": "2026-11-28T01:58:22.382198+00:00" + "observedAt": "2026-11-28T02:38:05.386213+00:00" } }, { @@ -1015,7 +1015,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0146", "lookPath": "", - "observedAt": "2026-11-28T01:58:24.582227+00:00" + "observedAt": "2026-11-28T02:38:07.578985+00:00" } }, { @@ -1071,7 +1071,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: setWorld ive-0158", "lookPath": "", - "observedAt": "2026-11-28T01:58:31.393393+00:00" + "observedAt": "2026-11-28T02:38:14.740238+00:00" } }, { @@ -1103,7 +1103,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0159", "lookPath": "", - "observedAt": "2026-11-28T01:58:33.598048+00:00" + "observedAt": "2026-11-28T02:38:16.953350+00:00" } }, { @@ -1159,7 +1159,7 @@ "note": "", "undoLabel": "", "lookPath": "", - "observedAt": "2026-11-28T01:58:44.631878+00:00" + "observedAt": "2026-11-28T02:38:28.064380+00:00" } }, { @@ -1186,7 +1186,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0174", "lookPath": "", - "observedAt": "2026-11-28T01:58:47.857036+00:00" + "observedAt": "2026-11-28T02:38:31.281935+00:00" } }, { @@ -1242,10 +1242,10 @@ "note": "", "undoLabel": "", "lookPath": "F:\\aeth-wt\\brokkr-action-table-live\\scratch\\out\\look\\live-0177.png", - "observedAt": "2026-11-28T01:58:53.654873+00:00", + "observedAt": "2026-11-28T02:38:37.045877+00:00", "captureSource": "region", "sceneUpdateSeq": 95, - "sessionId": "3b3d62619afb43d0a8548fc3f2ce4a4f", + "sessionId": "0cc3e9cdaf454a249a30cc24e617581c", "humanEditSeq": 83, "humanEditsSinceLook": 83, "editedSinceLook": [ @@ -1288,7 +1288,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0178", "lookPath": "", - "observedAt": "2026-11-28T01:58:56.864241+00:00" + "observedAt": "2026-11-28T02:38:39.309535+00:00" } }, { @@ -1344,7 +1344,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createNodeGroup ive-0193", "lookPath": "", - "observedAt": "2026-11-28T01:59:10.270729+00:00" + "observedAt": "2026-11-28T02:38:51.073058+00:00" } }, { @@ -1376,7 +1376,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0194", "lookPath": "", - "observedAt": "2026-11-28T01:59:12.510947+00:00" + "observedAt": "2026-11-28T02:38:53.324909+00:00" } }, { @@ -1432,7 +1432,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: addNode ive-0223", "lookPath": "", - "observedAt": "2026-11-28T01:59:47.731039+00:00" + "observedAt": "2026-11-28T02:39:29.096510+00:00" } }, { @@ -1464,7 +1464,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0224", "lookPath": "", - "observedAt": "2026-11-28T01:59:49.993525+00:00" + "observedAt": "2026-11-28T02:39:31.428197+00:00" } }, { @@ -1520,7 +1520,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: linkSockets ive-0247", "lookPath": "", - "observedAt": "2026-11-28T02:00:17.375246+00:00" + "observedAt": "2026-11-28T02:39:59.079008+00:00" } }, { @@ -1552,7 +1552,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0248", "lookPath": "", - "observedAt": "2026-11-28T02:00:19.737999+00:00" + "observedAt": "2026-11-28T02:40:01.374248+00:00" } }, { @@ -1608,7 +1608,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: unlinkSockets ive-0269", "lookPath": "", - "observedAt": "2026-11-28T02:00:45.997967+00:00" + "observedAt": "2026-11-28T02:40:29.839429+00:00" } }, { @@ -1640,7 +1640,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0270", "lookPath": "", - "observedAt": "2026-11-28T02:00:48.315493+00:00" + "observedAt": "2026-11-28T02:40:32.156639+00:00" } }, { @@ -1696,7 +1696,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: removeNode ive-0284", "lookPath": "", - "observedAt": "2026-11-28T02:01:03.364715+00:00" + "observedAt": "2026-11-28T02:40:48.986174+00:00" } }, { @@ -1728,7 +1728,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0285", "lookPath": "", - "observedAt": "2026-11-28T02:01:05.767376+00:00" + "observedAt": "2026-11-28T02:40:51.316429+00:00" } }, { @@ -1784,7 +1784,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: addModifier ive-0302", "lookPath": "", - "observedAt": "2026-11-28T02:01:26.890644+00:00" + "observedAt": "2026-11-28T02:41:12.934572+00:00" } }, { @@ -1816,7 +1816,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0303", "lookPath": "", - "observedAt": "2026-11-28T02:01:29.307569+00:00" + "observedAt": "2026-11-28T02:41:15.376364+00:00" } }, { @@ -1872,7 +1872,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: setModifierInput ive-0311", "lookPath": "", - "observedAt": "2026-11-28T02:01:37.160827+00:00" + "observedAt": "2026-11-28T02:41:23.279634+00:00" } }, { @@ -1894,7 +1894,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0312", "lookPath": "", - "observedAt": "2026-11-28T02:01:39.514028+00:00" + "observedAt": "2026-11-28T02:41:25.653006+00:00" } }, { @@ -1950,7 +1950,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: removeModifier ive-0320", "lookPath": "", - "observedAt": "2026-11-28T02:01:47.535687+00:00" + "observedAt": "2026-11-28T02:41:34.791771+00:00" } }, { diff --git a/surfaces/blender/tests/live/agent_turn_queue.py b/surfaces/blender/tests/live/agent_turn_queue.py index 5f8a68c..aa0204b 100644 --- a/surfaces/blender/tests/live/agent_turn_queue.py +++ b/surfaces/blender/tests/live/agent_turn_queue.py @@ -8,6 +8,7 @@ are drained by the add-on's own 1 s timer as one undo step each, with write-once BROKKR_CULTLIB= BROKKR_PYLIBS= + Private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS are required (refused otherwise). blender --factory-startup --python agent_turn_queue.py -- Intents are put into the node database as brokkr-ctl does; a command JSON dropped under the debug @@ -23,6 +24,14 @@ from pathlib import Path import bpy +import os as _os + +for _name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): + if not _os.environ.get(_name): # this Blender ignores BLENDER_USER_RESOURCE_PATH: without these, her own extensions folder is used + raise SystemExit(f"{_name} is not set: run this in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") +if _os.path.normcase(_os.path.abspath(bpy.utils.user_resource("EXTENSIONS"))) != _os.path.normcase(_os.path.abspath(_os.environ["BLENDER_USER_EXTENSIONS"])): + raise SystemExit("Blender's extensions folder is not BLENDER_USER_EXTENSIONS; refusing to touch it") + if os.environ.get("BROKKR_PYLIBS"): sys.path.insert(0, os.environ["BROKKR_PYLIBS"]) SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() diff --git a/surfaces/blender/tests/live/agent_turn_undo.py b/surfaces/blender/tests/live/agent_turn_undo.py index c8bec53..8347907 100644 --- a/surfaces/blender/tests/live/agent_turn_undo.py +++ b/surfaces/blender/tests/live/agent_turn_undo.py @@ -1,4 +1,6 @@ """Live proof, in GUI Blender, that every agent intent is one undo step. +Launch Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH); see docs/install.md. BROKKR_ADDON= \ blender --factory-startup --python agent_turn_undo.py -- diff --git a/surfaces/blender/tests/live/export_gltf.py b/surfaces/blender/tests/live/export_gltf.py index ff9e0bc..e133e7a 100644 --- a/surfaces/blender/tests/live/export_gltf.py +++ b/surfaces/blender/tests/live/export_gltf.py @@ -1,4 +1,6 @@ """Live proof of exportGltf on real bpy: the option names exist on the real exporter, extras reach the +Launch Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH); see docs/install.md. file, selection filters, .gltf writes its .bin and textures without overwriting, a refused or failed export leaves nothing behind. diff --git a/surfaces/blender/tests/live/gn_actions.py b/surfaces/blender/tests/live/gn_actions.py index b5b2e0e..87eda23 100644 --- a/surfaces/blender/tests/live/gn_actions.py +++ b/surfaces/blender/tests/live/gn_actions.py @@ -1,4 +1,6 @@ """Live proof of the node-graph actions: rebuild three geometry-node setups through Brokkr actions only. +Launch Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH); see docs/install.md. BROKKR_ADDON= \ blender -b --factory-startup --python gn_actions.py -- result.json diff --git a/surfaces/blender/tests/live/gn_recreation.py b/surfaces/blender/tests/live/gn_recreation.py index c7dc47d..2281812 100644 --- a/surfaces/blender/tests/live/gn_recreation.py +++ b/surfaces/blender/tests/live/gn_recreation.py @@ -1,4 +1,6 @@ """Recreate geometry-node setups through the Brokkr scene/object actions and compare with the native result. +Launch Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH); see docs/install.md. BROKKR_ADDON= \ blender -b --factory-startup --python gn_recreation.py -- result.json diff --git a/surfaces/blender/tests/live/headless_smoke.py b/surfaces/blender/tests/live/headless_smoke.py index 1d21601..40e6fff 100644 --- a/surfaces/blender/tests/live/headless_smoke.py +++ b/surfaces/blender/tests/live/headless_smoke.py @@ -1,4 +1,6 @@ """Live Blender smoke for the scene actions. Not part of the unittest run: it needs Blender. +Launch Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH); see docs/install.md. BROKKR_RUN= BROKKR_ADDON= \ blender --background --factory-startup --python surfaces/blender/tests/live/headless_smoke.py diff --git a/surfaces/blender/tests/live/material_colour.py b/surfaces/blender/tests/live/material_colour.py index 07c2f4d..d31533d 100644 --- a/surfaces/blender/tests/live/material_colour.py +++ b/surfaces/blender/tests/live/material_colour.py @@ -1,4 +1,6 @@ """Live proof of assignMaterial colour and idempotence on real bpy. +Launch Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH); see docs/install.md. BROKKR_ADDON= \ blender -b --factory-startup --python material_colour.py -- result.json diff --git a/surfaces/blender/tests/live/perception.py b/surfaces/blender/tests/live/perception.py index a62aeb8..7523763 100644 --- a/surfaces/blender/tests/live/perception.py +++ b/surfaces/blender/tests/live/perception.py @@ -6,7 +6,9 @@ BROKKR_CULTLIB= blender --python perception.py -- -Run it in a Blender whose resource path is fresh (BLENDER_USER_RESOURCE_PATH) so the add-on's preferences are the +Run it in Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH; without them the operator's own extensions folder is used). The script +refuses to run when they are unset. The add-on's preferences are then the defaults. The driver stands in for the operator's hands only: it saves the blend, ticks the sink and sets the render output directory (the two preferences an operator sets), enters Edit Mode, selects, moves objects and presses undo. Every intent is sent by brokkr-ctl and answered by the add-on's own timer. Writes .result.json, then quits. @@ -25,6 +27,14 @@ from pathlib import Path import bmesh import bpy +import os as _os + +for _name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): + if not _os.environ.get(_name): # this Blender ignores BLENDER_USER_RESOURCE_PATH: without these, her own extensions folder is used + raise SystemExit(f"{_name} is not set: run this in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") +if _os.path.normcase(_os.path.abspath(bpy.utils.user_resource("EXTENSIONS"))) != _os.path.normcase(_os.path.abspath(_os.environ["BLENDER_USER_EXTENSIONS"])): + raise SystemExit("Blender's extensions folder is not BLENDER_USER_EXTENSIONS; refusing to touch it") + SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() SCRATCH.mkdir(parents=True, exist_ok=True) CTL = os.environ["BROKKR_CTL"] diff --git a/surfaces/blender/tests/live/perception_fixes.py b/surfaces/blender/tests/live/perception_fixes.py index 7facba2..d535a51 100644 --- a/surfaces/blender/tests/live/perception_fixes.py +++ b/surfaces/blender/tests/live/perception_fixes.py @@ -1,6 +1,6 @@ """Live proof of the live-5 fix batch, in GUI Blender with the add-on installed as an extension, real brokkr-ctl looks. -Same environment as perception.py (BROKKR_SCRATCH, BROKKR_CTL, BROKKR_CULTLIB; a fresh BLENDER_USER_RESOURCE_PATH). +Same environment as perception.py (BROKKR_SCRATCH, BROKKR_CTL, BROKKR_CULTLIB; private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS; the script refuses to run without them). blender --python perception_fixes.py -- The driver stands in for the operator: it saves the blend, ticks the sink, sets the output directory, minimises and restores the Blender window (Windows ShowWindow on this process's own window), moves objects, enters Edit Mode. @@ -19,6 +19,14 @@ from pathlib import Path import bmesh import bpy + +import os as _os + +for _name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): + if not _os.environ.get(_name): # this Blender ignores BLENDER_USER_RESOURCE_PATH: without these, her own extensions folder is used + raise SystemExit(f"{_name} is not set: run this in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") +if _os.path.normcase(_os.path.abspath(bpy.utils.user_resource("EXTENSIONS"))) != _os.path.normcase(_os.path.abspath(_os.environ["BLENDER_USER_EXTENSIONS"])): + raise SystemExit("Blender's extensions folder is not BLENDER_USER_EXTENSIONS; refusing to touch it") import numpy SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() diff --git a/surfaces/blender/tests/live/refusals.py b/surfaces/blender/tests/live/refusals.py index 16823cb..a7292ad 100644 --- a/surfaces/blender/tests/live/refusals.py +++ b/surfaces/blender/tests/live/refusals.py @@ -1,4 +1,6 @@ """Live proof of the renderStill GL refusal and the createObject meshType refusal on real bpy. +Launch Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH); see docs/install.md. BROKKR_ADDON= \ blender -b --factory-startup --python refusals.py -- result.json diff --git a/surfaces/blender/tests/live/stop_presence.py b/surfaces/blender/tests/live/stop_presence.py index b1889f8..9e0c8a3 100644 --- a/surfaces/blender/tests/live/stop_presence.py +++ b/surfaces/blender/tests/live/stop_presence.py @@ -4,6 +4,7 @@ BROKKR_CTL= BROKKR_ADDON_MODULE= BROKKR_CULTLIB= + Private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS are required (refused otherwise). blender --factory-startup --python stop_presence.py -- Run a second Blender on the same store with BROKKR_PHASE=closed for the sink-off, node-closed answer. @@ -23,6 +24,14 @@ from pathlib import Path import bpy +import os as _os + +for _name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): + if not _os.environ.get(_name): # this Blender ignores BLENDER_USER_RESOURCE_PATH: without these, her own extensions folder is used + raise SystemExit(f"{_name} is not set: run this in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") +if _os.path.normcase(_os.path.abspath(bpy.utils.user_resource("EXTENSIONS"))) != _os.path.normcase(_os.path.abspath(_os.environ["BLENDER_USER_EXTENSIONS"])): + raise SystemExit("Blender's extensions folder is not BLENDER_USER_EXTENSIONS; refusing to touch it") + SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() SCRATCH.mkdir(parents=True, exist_ok=True) CTL = os.environ["BROKKR_CTL"] diff --git a/surfaces/blender/tests/test_action_table.py b/surfaces/blender/tests/test_action_table.py index d548b1b..858920a 100644 --- a/surfaces/blender/tests/test_action_table.py +++ b/surfaces/blender/tests/test_action_table.py @@ -78,6 +78,37 @@ class ParityFixtureTests(unittest.TestCase): self.assertNotEqual([c for c in CASES if validate(c["action"], c["fields"]) != c["expect"]], [], mutant.__name__) +class NormalizationTests(unittest.TestCase): + def test_a_whole_float_for_an_integer_field_reaches_the_handler_as_an_int(self): + normal = at.validate({"action": "renderStill", "outputPath": "a.png", "resolutionX": 1920.0, "resolutionY": 4.0}) + self.assertEqual((normal["resolutionX"], normal["resolutionY"]), (1920, 4)) + self.assertIs(type(normal["resolutionX"]), int) + + def test_validate_never_raises_whatever_the_document_holds(self): + """A store writer outside brokkr-ctl can put anything in an intent; the drain has already claimed it, so a raise + here would lose the intent without a receipt. Every hostile shape ends as ok or IntentInvalid.""" + hostile = [ + {"action": "createObject", 1: "a", "zz": "b"}, + {"action": "createObject", (1, 2): 1, None: 2, "zz": 3}, + {"action": "createNodeGroup", "treeKey": "G", "interface": [{1: "a", "name": "x", "inOut": "INPUT", "type": "Int"}]}, + {"action": "createNodeGroup", "treeKey": "G", "interface": [{"inOut": "INPUT", "name": "x", "type": "Int", 5: 6, None: 7}]}, + {"action": ["createObject"]}, {"action": {"a": 1}}, {"action": None}, {"action": 7}, {}, + {"action": "createObject", "location": [10 ** 400, float("nan"), float("inf")]}, + {"action": "renderStill", "outputPath": b"bytes", "resolutionX": 10 ** 400}, + {"action": "renderStill", "outputPath": "a.png", "resolutionX": float("inf")}, + {"action": "addNode", "treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "properties": {1: 2, (3,): 4}}, + {"action": "createObject", "objectType": ["MESH"]}, {"action": "createObject", "objectType": {"a": 1}}, + {"action": "setObjectCustomProperty", "targetObjectName": "c", "value": object()}, + ] + for command in hostile: + try: + at.validate(command) + except at.IntentInvalid: + pass + except Exception as error: # noqa: BLE001 + self.fail(f"{command!r} raised {error!r}") + + class HandlerCoverageTests(unittest.TestCase): def test_each_table_action_resolves_to_exactly_one_handler_and_each_handler_has_an_entry(self): names = [a["name"] for a in at.table()["actions"]] diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index 9f23465..b9fa12e 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -310,6 +310,25 @@ class DrainTests(unittest.TestCase): self.assertEqual(denial["status"], "denied") self.assertEqual(sorted(node.deleted), ["blender/commands/a", "blender/commands/b"]) + def test_a_mixed_key_intent_in_the_queue_ends_as_a_denied_receipt(self): + # a store writer can mix key types; the drain has claimed the intent, so validate must not raise + node = FakeNode({"blender/commands/a": {"commandId": "mixed-1", "requestedBy": "nibu/hands", "action": "createObject", 1: "a", "zz": "b"}}) + receipts = self.drain(node) + self.assertEqual([r["status"] for r in receipts], ["denied"]) + self.assertEqual(node.puts[0][0], "blender/receipts/mixed-1") + self.assertEqual(node.docs[bt.COMMAND_INTENT_SCHEMA], {}) + + def test_parenting_an_object_to_itself_or_its_own_child_is_refused_before_any_undo_step(self): + self.bpy.lamp.parent = self.bpy.mesh + for target, parent in (("Cube", "Cube"), ("Cube", "Lamp")): # Lamp is Cube's child + receipt = self.run_action(action="setObjectParent", targetObjectName=target, parentObjectName=parent) + self.assertEqual(receipt["status"], "failed", (target, parent)) + self.assertEqual(receipt["undoLabel"], "") + self.assertEqual(self.bpy.undo.pushes, []) + self.bpy.lamp.parent = None + self.assertEqual(self.run_action(action="setObjectParent", targetObjectName="Lamp", parentObjectName="Cube")["status"], "accepted") + self.assertEqual(len(self.bpy.undo.pushes), 1) + # claim-first: an intent leaves the queue before it runs, so no failure can run it twice def test_the_intent_is_deleted_before_its_handler_runs(self): node = FakeNode({"blender/commands/a": self.intent("claim-1")}) From 692606ba75ee048aa55507362ae784426fa8357f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 06:10:08 +0100 Subject: [PATCH 41/63] Blender add-on: host add-ons add rows to the action table through brokkr_actions.json check_host, host_actions discovery with ownership and RNA checks, _run_host_operator in the agent turn, hostActions and hostActionErrors in the snapshot, hostResult in receipts, fixture host add-on and cases. Co-Authored-By: Claude Sonnet 5.5 --- .../blender/brokkr_bridge/action_table.py | 74 +++++- .../blender/brokkr_bridge/blender_target.py | 154 +++++++++++- .../fixtures/brokkr_host_fixture/__init__.py | 72 ++++++ .../brokkr_host_fixture/brokkr_actions.json | 37 +++ surfaces/blender/tests/host_action_cases.json | 21 ++ surfaces/blender/tests/test_action_table.py | 68 ++++++ surfaces/blender/tests/test_agent_turn.py | 222 ++++++++++++++++++ .../blender/tests/test_material_actions.py | 2 +- surfaces/blender/tests/test_node_actions.py | 2 +- surfaces/blender/tests/test_scene_actions.py | 2 +- surfaces/blender/tests/test_stop_presence.py | 2 +- 11 files changed, 638 insertions(+), 18 deletions(-) create mode 100644 surfaces/blender/tests/fixtures/brokkr_host_fixture/__init__.py create mode 100644 surfaces/blender/tests/fixtures/brokkr_host_fixture/brokkr_actions.json create mode 100644 surfaces/blender/tests/host_action_cases.json diff --git a/surfaces/blender/brokkr_bridge/action_table.py b/surfaces/blender/brokkr_bridge/action_table.py index 3ecaa2f..48a888f 100644 --- a/surfaces/blender/brokkr_bridge/action_table.py +++ b/surfaces/blender/brokkr_bridge/action_table.py @@ -1,7 +1,9 @@ """The action table: which Blender intents exist, what fields each may carry, and each action's undo class. -actions.json (schema brokkr.blender.actions.v0) is the one owner. run_intent admits every intent through -validate(); brokkr-ctl embeds the same file for `send --help` and early refusal, with the same rules and +actions.json (schema brokkr.blender.actions.v0) owns the built-in rows; a host add-on adds rows of its own +operators in brokkr_actions.json (schema brokkr.blender.host_actions.v0: scalar fields only, no free JSON, +an optional result naming a WindowManager string property), checked by check_host and passed to validate() +and entry() as `host`. run_intent admits every intent through validate(); brokkr-ctl embeds the same file for `send --help` and early refusal, with the same rules and message text (surfaces/blender/tests/action_cases.json pins the two). Stdlib only, no bpy. Vocabulary: null means absent; a required field absent is refused; a field neither declared nor in the @@ -17,11 +19,15 @@ from __future__ import annotations import functools import json import math +import re from pathlib import Path from typing import Any TABLE_PATH = Path(__file__).with_name("actions.json") SCHEMA = "brokkr.blender.actions.v0" +HOST_SCHEMA = "brokkr.blender.host_actions.v0" +HOST_TYPES = ("string", "number", "integer", "boolean") +HOST_NAME = re.compile(r"^[a-z0-9_]+\.[a-z0-9_]+$") TYPES = ("string", "number", "integer", "boolean", "array", "object", "any") TYPE_WORDS = {"string": "a string", "number": "a finite number", "integer": "a whole number", "boolean": "true or false", "array": "an array", "object": "an object"} @@ -57,9 +63,14 @@ def table() -> dict[str, Any]: return document -def entry(action: Any) -> dict[str, Any] | None: - """The table row for an action name, or None.""" - return _by_name().get(action) if isinstance(action, str) else None +def entry(action: Any, host: Any = ()) -> dict[str, Any] | None: + """The row for an action name: the built-in row, else the first host row of that name, else None.""" + if not isinstance(action, str): + return None + row = _by_name().get(action) + if row is not None: + return row + return next((h for h in host if h.get("name") == action), None) @functools.lru_cache(maxsize=1) @@ -90,6 +101,55 @@ def check_table(document: dict[str, Any]) -> None: raise TableInvalid(f"{action['name']}.{field['name']} default: {error}") from None +def check_host(document: Any, charsets: dict[str, Any]) -> None: + """Refuse a host add-on's brokkr_actions.json unless its schema is the host schema, every name is a dotted + operator id and unique, every field is scalar and passes the built-in spec checks (and its default its own + rules), and result, if present, is an identifier. Raises TableInvalid naming the row and field.""" + if not isinstance(document, dict) or document.get("schema") != HOST_SCHEMA: + raise TableInvalid(f"host schema must be {HOST_SCHEMA}") + for key in document: + if key not in ("schema", "actions"): + raise TableInvalid(f"host file has no key '{key}'") + rows = document.get("actions") + if not isinstance(rows, list): + raise TableInvalid("host file actions must be an array") + names = set() + for row in rows: + name = row.get("name") if isinstance(row, dict) else None + if not isinstance(name, str) or not HOST_NAME.match(name): + raise TableInvalid(f"host action name {name!r} must look like addon.operator (a-z, 0-9, _)") + if name in names: + raise TableInvalid(f"host action {name} is listed twice") + names.add(name) + for key in ("doc", "changesScene", "editModeSafe", "fields"): + if key not in row: + raise TableInvalid(f"{name} lacks {key}") + if not isinstance(row["fields"], list): + raise TableInvalid(f"{name} fields must be an array") + for key in row: + if key not in ("name", "doc", "changesScene", "editModeSafe", "fields", "result"): + raise TableInvalid(f"{name} has no key '{key}'") + if "result" in row and not (isinstance(row["result"], str) and row["result"].isidentifier()): + raise TableInvalid(f"{name}.result must be an identifier") + fields = {} + for field in row["fields"]: + if not isinstance(field, dict) or not isinstance(field.get("name"), str) or field["name"] in fields: + raise TableInvalid(f"{name} has a missing or repeated field name") + fields[field["name"]] = field + for field in fields.values(): + where = f"{name}.{field['name']}" + if field.get("type") not in HOST_TYPES: + raise TableInvalid(f"{where}: a host field is one of {_list(list(HOST_TYPES))}") + if "only" in field: + raise TableInvalid(f"{where}: a host field has no 'only'") + _check_spec(field, where, charsets, fields, top=True) + if "default" in field: + try: + _value(field, field["default"], field["name"]) + except IntentInvalid as error: + raise TableInvalid(f"{where} default: {error}") from None + + def _check_spec(spec: dict[str, Any], where: str, charsets: dict, siblings: dict, top: bool) -> None: kind = spec.get("type") if kind not in TYPES: @@ -116,11 +176,11 @@ def _check_spec(spec: dict[str, Any], where: str, charsets: dict, siblings: dict _check_spec(prop, f"{where}.{prop['name']}", charsets, inner, top=False) -def validate(command: dict[str, Any]) -> dict[str, Any]: +def validate(command: dict[str, Any], host: Any = ()) -> dict[str, Any]: """The normalized copy of an intent (nulls dropped, whole numbers of integer fields as int, defaults filled), or IntentInvalid naming the rule. It raises nothing else, whatever the document holds.""" action = command.get("action", "") - row = entry(action) + row = entry(action, host) if row is None: raise IntentInvalid(f"Unsupported Blender command action: {action}") present = {k: v for k, v in command.items() if v is not None} diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index f87da9c..8bde4b0 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -42,6 +42,8 @@ CULTLIB_PY_PACKAGES = ("cultcache-py", "cultnet-py", "cultmesh-py") 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 COMMAND_INTENT_SCHEMA = "brokkr.blender.command_intent.v0" COMMAND_RECEIPT_SCHEMA = "brokkr.blender.command_receipt.v0" SYNC_SESSION_SCHEMA = "brokkr.sync.session.v0" @@ -100,6 +102,14 @@ CAPABILITIES = ( ) +class _NoHostFile(Exception): + """The add-on has no brokkr_actions.json: it is not a host.""" + + +def _first_line(text: str) -> str: + return text.strip().splitlines()[0] if text.strip() else "failed" + + class BrokkrBlenderTarget: """Blender-owned adapter target for Brokkr mirror documents.""" @@ -121,6 +131,7 @@ class BrokkrBlenderTarget: self.agent_turn = False # true only inside run_intent self._wrote = True # run_intent: false when an accepted action changed nothing self._receipted: set[str] = set() + self._host_files: dict[str, tuple[tuple, Any]] = {} # module -> (file stamp, parsed document or error text): a cache of reads, never truth self._unsent: list[tuple[dict[str, Any], str]] = [] # receipts whose write failed: written first on the next drain, never read as truth self._recent: deque[dict[str, Any]] = deque(maxlen=RECEIPTS_KEPT) # display cache of the node's receipts self._receipts_loaded = False @@ -600,6 +611,7 @@ class BrokkrBlenderTarget: def capture_snapshot(self, context: Any, agent_commands_enabled: bool) -> dict[str, Any]: bpy = self.bpy + host_rows, host_errors = self.host_actions() scan = self._instance_scan() if any(o.type == "MESH" and len(o.modifiers) for o in bpy.data.objects) else None selected = [item.name for item in context.selected_objects if item is not None] active_object = context.active_object.name if context.active_object else "" @@ -630,8 +642,90 @@ class BrokkrBlenderTarget: "objects": [self._object_snapshot(obj, scan) for obj in bpy.data.objects], "materials": [self._material_snapshot(material) for material in bpy.data.materials], "collections": [self._collection_snapshot(collection) for collection in bpy.data.collections], + "hostActions": host_rows, + "hostActionErrors": host_errors, } + def host_actions(self) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + """The one discovery of host rows: ([row + 'host' module], [{host, error}]). Each enabled add-on but this + one may carry brokkr_actions.json beside its __init__.py; the file is admitted whole or not at all. The + file is the add-on's word; what is checked here is what Brokkr can see: the operator exists and is a + Python class defined by that add-on, every field is a property of it of the matching type whose RNA hard + limits contain the row's bounds, and result is a WindowManager string property. Only the parse is cached + (on path, mtime and size); the live checks run each time, so a disabled add-on or an unregistered operator + is gone at the next intent. A name two files claim fails ownership in all but its owner.""" + rows: list[dict[str, Any]] = [] + errors: list[dict[str, Any]] = [] + own = __package__ or "" + modules = [m for m in self.bpy.context.preferences.addons.keys() if m != own] + for module in modules: + try: + document = self._host_document(module) + except _NoHostFile: + continue + except Exception as error: + errors.append({"host": module, "error": _first_line(f"{HOST_ACTIONS_FILE}: {error}")}) + continue + try: + for row in document["actions"]: + self._check_host_row(module, row) + except Exception as error: + errors.append({"host": module, "error": _first_line(f"{HOST_ACTIONS_FILE}: {error}")}) + continue + rows.extend({**row, "host": module} for row in document["actions"]) + return rows, errors + + def _host_document(self, module: str) -> dict[str, Any]: + loaded = sys.modules.get(module) + source = getattr(loaded, "__file__", None) + path = Path(source).with_name(HOST_ACTIONS_FILE) if source else None + if path is None or not path.is_file(): + self._host_files.pop(module, None) + raise _NoHostFile() + info = path.stat() + stamp = (str(path), info.st_mtime_ns, info.st_size) + cached = self._host_files.get(module) + if cached is None or cached[0] != stamp: + try: + document = json.loads(path.read_text(encoding="utf-8")) + at.check_host(document, at.table()["charsets"]) + cached = (stamp, document) + except Exception as error: + cached = (stamp, str(error)) + self._host_files[module] = cached + if isinstance(cached[1], str): + raise ValueError(cached[1]) + return cached[1] + + def _check_host_row(self, module: str, row: dict[str, Any]) -> None: + bpy = self.bpy + name = row["name"] + first, second = name.split(".") + operator = getattr(getattr(bpy.ops, first), second) + owner = getattr(bpy.types, operator.idname(), None) + owned = getattr(owner, "__module__", None) + if not isinstance(owner, type) or not isinstance(owned, str) or not (owned == module or owned.startswith(module + ".")): + raise ValueError(f"{name} is not an operator defined by {module}") + properties = {p.identifier: p for p in operator.get_rna_type().properties} + kinds = {"string": "STRING", "number": "FLOAT", "integer": "INT", "boolean": "BOOLEAN"} + for field in row["fields"]: + prop = properties.get(field["name"]) + where = f"{name}.{field['name']}" + if prop is None: + raise ValueError(f"{where} is not a property of the operator") + enum = field.get("enum") + if prop.type != ("ENUM" if enum is not None else kinds[field["type"]]): + raise ValueError(f"{where} is {prop.type} in the operator, not {field['type']}") + if enum is not None and {item.identifier for item in prop.enum_items} != set(enum): + raise ValueError(f"{where} enum differs from the operator's") + if field["type"] in ("number", "integer") and not (prop.hard_min <= field["minimum"] and field["maximum"] <= prop.hard_max): + raise ValueError(f"{where} bounds exceed the operator's own limits") + result = row.get("result") + if result is not None: + prop = bpy.types.WindowManager.bl_rna.properties.get(result) + if prop is None or prop.type != "STRING": + raise ValueError(f"{name} result {result} is not a string property of WindowManager") + def run_intent(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: """The one agent turn: admit, run with operator undo off, push one labelled undo step, receipt. @@ -639,7 +733,8 @@ class BrokkrBlenderTarget: valid), then Edit Mode. While an object is in Edit Mode undo steps are edit-mesh steps, so a scene write is not reverted by one undo and some operators leave Edit Mode (brokkr-live:ruling:object-intents-refused-in-edit-mode); the table's editModeSafe actions write nothing - and change no mode. A refusal at admission is 'denied': nothing ran, no undo step.""" + and change no mode. Host add-on rows (host_actions) are admitted by the same table check and run through + the same turn. A refusal at admission is 'denied': nothing ran, no undo step.""" command_id = command.get("commandId") requested_by = command.get("requestedBy") action = command.get("action", "") @@ -653,8 +748,9 @@ class BrokkrBlenderTarget: denial = "Intent has no requestedBy of the form '/'." else: try: - command = at.validate(command) - row = at.entry(action) + host, _ = self.host_actions() + command = at.validate(command, host) + row = at.entry(action, host) except at.IntentInvalid as error: denial = str(error) if not denial and not row["editModeSafe"] and self._edit_mode_object() is not None: @@ -671,7 +767,7 @@ class BrokkrBlenderTarget: self._wrote = True try: try: - receipt = self._dispatch(context, command) + receipt = self._dispatch(context, command, row) if receipt["status"] != "accepted" or not self._wrote: push = False # a refusal, or an accepted no-op: it wrote nothing except sa.ActionRefused as error: # raised before any write: nothing to push @@ -707,16 +803,59 @@ class BrokkrBlenderTarget: else: self.bpy.ops.ed.undo_push(message=label) - def _dispatch(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: - """Only run_intent calls it, with an intent the table admitted: the handler is '_' + the action's name, - on NodeActions for the node actions and on this target for the rest. It owns refusal, failure and the undo step.""" + def _dispatch(self, context: Any, command: dict[str, Any], row: dict[str, Any]) -> dict[str, Any]: + """Only run_intent calls it, with an intent the table admitted: a host row runs its operator; otherwise the + handler is '_' + the action's name, on NodeActions for the node actions and on this target for the rest. + It owns refusal, failure and the undo step.""" action = command["action"] + if "host" in row: + return self._run_host_operator(context, command, row) if hasattr(self.nodes, "_" + action): message, name = self.nodes.execute(action, command) self._wrote = self.nodes.changed return self._receipt(command, "accepted", message, name) return getattr(self, "_" + action)(context, command) + def _run_host_operator(self, context: Any, command: dict[str, Any], row: dict[str, Any]) -> dict[str, Any]: + """A host add-on's own operator, called with exactly the declared fields. FINISHED is accepted; CANCELLED + is failed and wrote nothing; an argument Blender will not convert raises ActionRefused before anything + ran; an ERROR report or exception is RuntimeError, failed (run_intent pushes '(failed)' for a changesScene + row). A row's result property is cleared before and copied, capped, into the receipt.""" + bpy = self.bpy + name = row["name"] + skip = set(at.table()["envelope"]) + kwargs = {k: v for k, v in command.items() if k not in skip} + result = row.get("result") + manager = bpy.context.window_manager + if result: + setattr(manager, result, "") + first, second = name.split(".") + operator = getattr(getattr(bpy.ops, first), second) + windows = manager.windows + try: + if windows: + with bpy.context.temp_override(window=windows[0]): + outcome = operator("EXEC_DEFAULT", False, **kwargs) + else: + outcome = operator("EXEC_DEFAULT", False, **kwargs) + except TypeError as error: + raise sa.ActionRefused(f"Operator {name} refused its arguments: {_first_line(str(error))}") from None + except RuntimeError as error: + raise RuntimeError(_first_line(str(error))) from None + text = "" + if result: + text = getattr(manager, result, "") or "" + if len(text) > HOST_RESULT_LIMIT: + text = text[:HOST_RESULT_LIMIT] + " [truncated]" + if "FINISHED" in outcome: + self._wrote = bool(row["changesScene"]) + receipt = self._receipt(command, "accepted", f"Operator {name} finished.", "") + else: + self._wrote = False + receipt = self._receipt(command, "failed", f"Operator {name} cancelled; nothing changed.", "") + receipt["hostResult"] = text + return receipt + def _createObject(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: object_type = command["objectType"] name = command.get("name") or f"Brokkr {object_type.title()}" @@ -1410,6 +1549,7 @@ class BrokkrBlenderTarget: "note": command["note"][:NOTE_LIMIT] if isinstance(command.get("note"), str) else "", "undoLabel": "", "lookPath": "", + "hostResult": "", "observedAt": _now(), } diff --git a/surfaces/blender/tests/fixtures/brokkr_host_fixture/__init__.py b/surfaces/blender/tests/fixtures/brokkr_host_fixture/__init__.py new file mode 100644 index 0000000..671d78c --- /dev/null +++ b/surfaces/blender/tests/fixtures/brokkr_host_fixture/__init__.py @@ -0,0 +1,72 @@ +"""A legacy host add-on for Brokkr's host-action tests. It knows nothing of Brokkr: its brokkr_actions.json is +the whole contract. apply is registered but left out of that file, the shape of an operator only a human runs.""" +bl_info = {"name": "Brokkr host fixture", "blender": (4, 2, 0), "category": "Development"} + +import bpy + + +class BROKKR_HOST_FIXTURE_OT_add_empty(bpy.types.Operator): + bl_idname = "brokkr_host_fixture.add_empty" + bl_label = "Fixture add empty" + bl_options = {"REGISTER", "UNDO"} + name: bpy.props.StringProperty(default="Fixture") + size: bpy.props.FloatProperty(default=1.0, min=0.0, max=100.0) + + def execute(self, context): + empty = bpy.data.objects.new(self.name, None) + empty.empty_display_size = self.size + context.scene.collection.objects.link(empty) + return {"FINISHED"} + + +class BROKKR_HOST_FIXTURE_OT_report(bpy.types.Operator): + bl_idname = "brokkr_host_fixture.report" + bl_label = "Fixture report" + bl_options = {"REGISTER"} + + def execute(self, context): + context.window_manager.brokkr_host_fixture_result = f"objects: {len(bpy.data.objects)}\nscenes: {len(bpy.data.scenes)}" + return {"FINISHED"} + + +class BROKKR_HOST_FIXTURE_OT_refuse(bpy.types.Operator): + bl_idname = "brokkr_host_fixture.refuse" + bl_label = "Fixture refuse" + + def execute(self, context): + self.report({"ERROR"}, "the fixture refuses") + return {"CANCELLED"} + + +class BROKKR_HOST_FIXTURE_OT_cancel(bpy.types.Operator): + bl_idname = "brokkr_host_fixture.cancel" + bl_label = "Fixture cancel" + + def execute(self, context): + return {"CANCELLED"} + + +class BROKKR_HOST_FIXTURE_OT_apply(bpy.types.Operator): + bl_idname = "brokkr_host_fixture.apply" + bl_label = "Fixture apply" + bl_options = {"REGISTER", "UNDO"} + + def execute(self, context): + bpy.data.objects.new("Applied", None) + return {"FINISHED"} + + +classes = (BROKKR_HOST_FIXTURE_OT_add_empty, BROKKR_HOST_FIXTURE_OT_report, BROKKR_HOST_FIXTURE_OT_refuse, + BROKKR_HOST_FIXTURE_OT_cancel, BROKKR_HOST_FIXTURE_OT_apply) + + +def register(): + bpy.types.WindowManager.brokkr_host_fixture_result = bpy.props.StringProperty() + for cls in classes: + bpy.utils.register_class(cls) + + +def unregister(): + for cls in reversed(classes): + bpy.utils.unregister_class(cls) + del bpy.types.WindowManager.brokkr_host_fixture_result diff --git a/surfaces/blender/tests/fixtures/brokkr_host_fixture/brokkr_actions.json b/surfaces/blender/tests/fixtures/brokkr_host_fixture/brokkr_actions.json new file mode 100644 index 0000000..160f67a --- /dev/null +++ b/surfaces/blender/tests/fixtures/brokkr_host_fixture/brokkr_actions.json @@ -0,0 +1,37 @@ +{ + "schema": "brokkr.blender.host_actions.v0", + "actions": [ + { + "name": "brokkr_host_fixture.add_empty", + "doc": "Add an empty named for the agent.", + "changesScene": true, + "editModeSafe": false, + "fields": [ + {"name": "name", "type": "string", "required": true, "minLength": 1, "maxLength": 63, "doc": "the empty's name"}, + {"name": "size", "type": "number", "minimum": 0.1, "maximum": 10, "default": 1, "doc": "display size"} + ] + }, + { + "name": "brokkr_host_fixture.report", + "doc": "Write a report of the scene without changing it.", + "changesScene": false, + "editModeSafe": true, + "result": "brokkr_host_fixture_result", + "fields": [] + }, + { + "name": "brokkr_host_fixture.refuse", + "doc": "Report an error and cancel.", + "changesScene": false, + "editModeSafe": true, + "fields": [] + }, + { + "name": "brokkr_host_fixture.cancel", + "doc": "Cancel without a report.", + "changesScene": false, + "editModeSafe": true, + "fields": [] + } + ] +} diff --git a/surfaces/blender/tests/host_action_cases.json b/surfaces/blender/tests/host_action_cases.json new file mode 100644 index 0000000..91836a9 --- /dev/null +++ b/surfaces/blender/tests/host_action_cases.json @@ -0,0 +1,21 @@ +[ + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E"}, "expect": "ok"}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E", "size": 0.1}, "expect": "ok"}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E", "size": 10}, "expect": "ok"}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E", "size": null, "note": "n", "requestedBy": "a/b", "commandId": "x"}, "expect": "ok"}, + {"action": "brokkr_host_fixture.add_empty", "fields": {}, "expect": "name is required."}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": ""}, "expect": "name must have at least 1 characters."}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}, "expect": "name must have at most 63 characters."}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": 5}, "expect": "name must be a string."}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E", "size": 0.05}, "expect": "size must be between 0.1 and 10."}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E", "size": 10.5}, "expect": "size must be between 0.1 and 10."}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E", "size": true}, "expect": "size must be a finite number."}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E", "bogus": 1}, "expect": "brokkr_host_fixture.add_empty has no field 'bogus'; its fields: name, size."}, + {"action": "brokkr_host_fixture.report", "fields": {}, "expect": "ok"}, + {"action": "brokkr_host_fixture.report", "fields": {"name": "E"}, "expect": "brokkr_host_fixture.report has no field 'name'; its fields: none."}, + {"action": "brokkr_host_fixture.refuse", "fields": {}, "expect": "ok"}, + {"action": "brokkr_host_fixture.cancel", "fields": {}, "expect": "ok"}, + {"action": "brokkr_host_fixture.apply", "fields": {}, "expect": "Unsupported Blender command action: brokkr_host_fixture.apply"}, + {"action": "wm.save_mainfile", "fields": {}, "expect": "Unsupported Blender command action: wm.save_mainfile"}, + {"action": "createObject", "fields": {}, "expect": "ok"} +] diff --git a/surfaces/blender/tests/test_action_table.py b/surfaces/blender/tests/test_action_table.py index 858920a..f3a5f6e 100644 --- a/surfaces/blender/tests/test_action_table.py +++ b/surfaces/blender/tests/test_action_table.py @@ -14,6 +14,8 @@ at = ts.at bt = ts.bt na = ts.bt.na CASES = json.loads((Path(__file__).with_name("action_cases.json")).read_text(encoding="utf-8")) +HOST_FILE = json.loads((Path(__file__).parent / "fixtures" / "brokkr_host_fixture" / "brokkr_actions.json").read_text(encoding="utf-8")) +HOST_CASES = json.loads((Path(__file__).with_name("host_action_cases.json")).read_text(encoding="utf-8")) def validate(action, fields): @@ -24,6 +26,72 @@ def validate(action, fields): return "ok" +class HostTableTests(unittest.TestCase): + """A host add-on's brokkr_actions.json adds rows; the same messages as for built-ins.""" + + def charsets(self): + return at.table()["charsets"] + + def host_file(self, **row): + base = copy.deepcopy(HOST_FILE) + base["actions"][0].update(row) + return base + + def test_the_fixture_file_is_admitted(self): + at.check_host(HOST_FILE, self.charsets()) + + def wrong_cases(self): + wrong = [] + for case in HOST_CASES: + try: + at.validate({"action": case["action"], **case["fields"]}, HOST_FILE["actions"]) + got = "ok" + except at.IntentInvalid as error: + got = str(error) + if got != case["expect"]: + wrong.append((case["action"], case["fields"], case["expect"], got)) + return wrong + + def test_every_host_case_yields_exactly_its_expected_message_or_ok(self): + self.assertEqual(self.wrong_cases(), []) + + def test_a_mutant_that_skips_host_rows_or_lets_an_undeclared_field_through_fails_a_case(self): + original = at.entry + with mock.patch.object(at, "entry", lambda action, host=(): original(action)): + self.assertTrue(self.wrong_cases()) + with mock.patch.object(at, "_fields", lambda *args: None): + self.assertTrue(self.wrong_cases()) + + def test_check_host_refuses_non_scalar_fields_bad_names_and_foreign_keys(self): + field = {"name": "f", "type": "array", "items": {"type": "number", "minimum": 0, "maximum": 1}} + for bad, why in ( + (self.host_file(fields=[field]), "array"), + (self.host_file(fields=[{"name": "f", "type": "object"}]), "object"), + (self.host_file(fields=[{"name": "f", "type": "any"}]), "any"), + (self.host_file(name="undotted"), "undotted"), + (self.host_file(name="Upper.case"), "uppercase"), + (self.host_file(fields=[{"name": "f", "type": "string", "chars": "nope"}]), "charset"), + (self.host_file(result="not an identifier"), "result"), + (self.host_file(fields=[{"name": "f", "type": "number"}]), "unbounded"), + ({**HOST_FILE, "envelope": []}, "envelope key"), + ({**HOST_FILE, "charsets": {}}, "charsets key"), + ({**HOST_FILE, "schema": at.SCHEMA}, "schema"), + ): + with self.assertRaises(at.TableInvalid, msg=why): + at.check_host(bad, self.charsets()) + twice = copy.deepcopy(HOST_FILE) + twice["actions"].append(copy.deepcopy(twice["actions"][0])) + with self.assertRaises(at.TableInvalid): + at.check_host(twice, self.charsets()) + + def test_a_host_row_never_shadows_a_built_in(self): + shadow = [{"name": "createObject", "doc": "", "changesScene": True, "editModeSafe": True, "fields": []}] + self.assertIs(at.entry("createObject", shadow), at.entry("createObject")) + self.assertEqual(at.entry("brokkr_host_fixture.report", HOST_FILE["actions"])["name"], "brokkr_host_fixture.report") + self.assertIsNone(at.entry("brokkr_host_fixture.report")) + self.assertTrue(all("." not in a["name"] for a in at.table()["actions"])) + + class ParityFixtureTests(unittest.TestCase): """action_cases.json is also run by brokkr-ctl's actions.rs: one table, two interpreters, one set of messages.""" diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index b9fa12e..6578b4b 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -232,6 +232,228 @@ class AgentTurnTests(unittest.TestCase): self.assertNotIn("requires CultLib's Python packages", str(caught.exception)) +FIXTURE = Path(__file__).parent / "fixtures" / "brokkr_host_fixture" +HOST = "brokkr_host_fixture" +NS = ts.NS + + +def types_module(name, file): + import types + module = types.ModuleType(name) + module.__file__ = str(file) + return module + + +class HostOp: + """bpy.ops..: callable with idname() and get_rna_type(), recording its calls.""" + + def __init__(self, name, props, behave): + self.cls = type(f"BROKKR_HOST_FIXTURE_OT_{name}", (), {"__module__": HOST}) + self.props = props + self.behave = behave + self.calls = [] + + def idname(self): + return self.cls.__name__ + + def get_rna_type(self): + return NS(properties=self.props) + + def __call__(self, mode, undo, **kwargs): + assert (mode, undo) == ("EXEC_DEFAULT", False) + self.calls.append(kwargs) + return self.behave(self, kwargs) + + +def prop(identifier, kind, lo=0.0, hi=1e30, enum=()): + return NS(identifier=identifier, type=kind, hard_min=lo, hard_max=hi, enum_items=[NS(identifier=e) for e in enum]) + + +def raising(error): + def behave(op, kwargs): + raise error + return behave + + +class HostActionTests(unittest.TestCase): + """Host rows from a host add-on's brokkr_actions.json, discovered through a fake bpy, run by run_intent.""" + + def setUp(self): + ts.ActionTests.setUp(self) + self.dir = Path(self.tmp.name) / HOST + self.dir.mkdir() + (self.dir / "brokkr_actions.json").write_bytes((FIXTURE / "brokkr_actions.json").read_bytes()) + patch = unittest.mock.patch.dict(sys.modules, {HOST: types_module(HOST, self.dir / "__init__.py")}) + patch.start() + self.addCleanup(patch.stop) + bpy = self.bpy + self.ops = { + "add_empty": HostOp("add_empty", [prop("name", "STRING"), prop("size", "FLOAT", 0.0, 100.0)], self.finish), + "report": HostOp("report", [], self.write_report), + "refuse": HostOp("refuse", [], raising(RuntimeError("Error: the fixture refuses"))), + "cancel": HostOp("cancel", [], lambda op, kw: {"CANCELLED"}), + "apply": HostOp("apply", [], self.finish), + } + bpy.ops.brokkr_host_fixture = NS(**self.ops) + bpy.types = NS(WindowManager=NS(bl_rna=NS(properties={"brokkr_host_fixture_result": NS(type="STRING")})), + **{op.idname(): op.cls for op in self.ops.values()}) + bpy.context.preferences.addons = {HOST: object(), "brokkr_bridge": object()} + bpy.context.window_manager.brokkr_host_fixture_result = "stale" + self.report_text = "objects: 3" + + def finish(self, op, kwargs): + return {"FINISHED"} + + def write_report(self, op, kwargs): + self.bpy.context.window_manager.brokkr_host_fixture_result = self.report_text + return {"FINISHED"} + + run_action = ts.ActionTests.run_action + + def send(self, operator, **fields): + return self.run_action(action=f"{HOST}.{operator}", **fields) + + def test_a_changing_host_operator_runs_with_exactly_its_declared_fields_and_is_one_undo_step(self): + receipt = self.send("add_empty", name="E", size=2) + self.assertEqual(receipt["status"], "accepted", receipt) + self.assertEqual(receipt["message"], f"Operator {HOST}.add_empty finished.") + self.assertEqual(receipt["hostResult"], "") + self.assertEqual(self.ops["add_empty"].calls, [{"name": "E", "size": 2}]) + self.assertEqual(len(self.bpy.undo.pushes), 1) + self.assertTrue(self.bpy.undo.pushes[0].startswith("Brokkr nibu/hands: brokkr_host_fixture.add_empty ")) + self.assertEqual(receipt["undoLabel"], self.bpy.undo.pushes[0]) + + def test_the_default_is_filled_and_an_undeclared_field_never_reaches_the_operator(self): + self.assertEqual(self.send("add_empty", name="E")["status"], "accepted") + self.assertEqual(self.ops["add_empty"].calls, [{"name": "E", "size": 1}]) + denied = self.send("add_empty", name="E", location=[1, 2, 3]) + self.assertEqual(denied["status"], "denied") + self.assertEqual(len(self.ops["add_empty"].calls), 1) + + def test_a_non_changing_operator_pushes_no_undo_step_and_returns_its_result(self): + receipt = self.send("report") + self.assertEqual((receipt["status"], receipt["hostResult"]), ("accepted", "objects: 3")) + self.assertEqual(self.bpy.undo.pushes, []) + self.assertEqual(self.run_action(action="createObject")["hostResult"], "") # a built-in's receipt carries the field empty + + def test_the_result_is_cleared_before_the_call_and_capped_after(self): + seen = [] + self.ops["report"].behave = lambda op, kw: (seen.append(self.bpy.context.window_manager.brokkr_host_fixture_result), {"CANCELLED"})[1] + self.assertEqual(self.send("report")["hostResult"], "") + self.assertEqual(seen, [""]) # 'stale' was cleared first + self.ops["report"].behave = self.write_report + self.report_text = "x" * (bt.HOST_RESULT_LIMIT + 50) + text = self.send("report")["hostResult"] + self.assertEqual(text, "x" * bt.HOST_RESULT_LIMIT + " [truncated]") + self.report_text = "y" * bt.HOST_RESULT_LIMIT + self.assertEqual(self.send("report")["hostResult"], "y" * bt.HOST_RESULT_LIMIT) + + def test_cancelled_is_failed_with_no_push(self): + receipt = self.send("cancel") + self.assertEqual((receipt["status"], receipt["message"]), ("failed", f"Operator {HOST}.cancel cancelled; nothing changed.")) + self.ops["add_empty"].behave = lambda op, kw: {"CANCELLED"} + self.assertEqual(self.send("add_empty", name="E")["status"], "failed") + self.assertEqual(self.bpy.undo.pushes, []) + + def test_a_conversion_error_is_failed_and_pushes_nothing(self): + self.ops["add_empty"].behave = raising(TypeError('keyword "size" could not be converted')) + receipt = self.send("add_empty", name="E") + self.assertEqual(receipt["status"], "failed") + self.assertIn("refused its arguments", receipt["message"]) + self.assertEqual(self.bpy.undo.pushes, []) + + def test_a_runtime_error_is_failed_with_its_first_line_and_pushes_failed_only_for_a_changing_row(self): + receipt = self.send("refuse") + self.assertEqual((receipt["status"], receipt["message"]), ("failed", "Error: the fixture refuses")) + self.assertEqual(self.bpy.undo.pushes, []) + self.ops["add_empty"].behave = raising(RuntimeError("Traceback...\nboom")) + receipt = self.send("add_empty", name="E") + self.assertEqual((receipt["status"], receipt["message"]), ("failed", "Traceback...")) + self.assertEqual(len(self.bpy.undo.pushes), 1) + self.assertTrue(self.bpy.undo.pushes[0].endswith("(failed)")) + + def test_a_human_only_operator_and_a_c_operator_are_unsupported_and_leave_no_trace(self): + for action in (f"{HOST}.apply", "wm.save_mainfile", "brokkr.stop_agents"): + receipt = self.run_action(action=action) + self.assertEqual(receipt["status"], "denied", action) + self.assertIn("Unsupported Blender command action", receipt["message"]) + self.assertEqual(self.ops["apply"].calls, []) + self.assertEqual(self.bpy.undo.pushes, []) + + def test_a_host_row_is_refused_in_edit_mode_unless_it_is_edit_mode_safe(self): + self.bpy.mesh.mode = "EDIT" + self.assertEqual(self.send("add_empty", name="E")["status"], "denied") + self.assertEqual(self.send("report")["status"], "accepted") + + def test_the_snapshot_lists_the_admitted_rows_with_their_host_and_no_human_only_row(self): + self.bpy.data = NS(objects=[], scenes=[], collections=[], materials=[], images=[], filepath="") + self.bpy.app = NS(version=(5, 3, 0), background=False) + context = NS(selected_objects=[], active_object=None, scene=None, mode="OBJECT") + snapshot = self.target.capture_snapshot(context, True) + names = [row["name"] for row in snapshot["hostActions"]] + self.assertEqual(names, [f"{HOST}.{n}" for n in ("add_empty", "report", "refuse", "cancel")]) + self.assertEqual({row["host"] for row in snapshot["hostActions"]}, {HOST}) + self.assertEqual(snapshot["hostActionErrors"], []) + + def refused(self): + rows, errors = self.target.host_actions() + self.assertEqual(rows, []) + self.assertEqual([e["host"] for e in errors], [HOST]) + self.assertIn("brokkr_actions.json", errors[0]["error"]) + self.assertEqual(self.send("report")["status"], "denied") # none of its rows is admitted + return errors[0]["error"] + + def test_a_row_naming_another_add_ons_operator_refuses_the_whole_file(self): + self.ops["report"].cls.__module__ = "other_addon" + self.assertIn("not an operator defined by", self.refused()) + self.ops["report"].cls.__module__ = HOST + ".sub" + self.assertEqual(len(self.target.host_actions()[0]), 4) # a submodule is its own + + def test_a_c_operator_refuses_the_whole_file(self): + self.bpy.types = NS(**{**vars(self.bpy.types), self.ops["cancel"].idname(): None}) + self.refused() + + def test_rna_disagreement_refuses_the_whole_file(self): + self.ops["add_empty"].props = [prop("name", "STRING")] # size missing + self.assertIn("size is not a property", self.refused()) + self.ops["add_empty"].props = [prop("name", "STRING"), prop("size", "INT", 0, 100)] + self.assertIn("is INT in the operator", self.refused()) + self.ops["add_empty"].props = [prop("name", "STRING"), prop("size", "FLOAT", 0.5, 100.0)] # hard min above the row's 0.1 + self.assertIn("bounds exceed", self.refused()) + self.ops["add_empty"].props = [prop("name", "STRING"), prop("size", "FLOAT", 0.0, 5.0)] # hard max below the row's 10 + self.assertIn("bounds exceed", self.refused()) + + def test_a_result_that_is_not_a_window_manager_string_refuses_the_whole_file(self): + self.bpy.types.WindowManager.bl_rna.properties["brokkr_host_fixture_result"] = NS(type="INT") + self.assertIn("not a string property", self.refused()) + self.bpy.types.WindowManager.bl_rna.properties.clear() + self.refused() + + def test_a_malformed_file_refuses_itself_and_a_changed_file_is_read_again(self): + path = self.dir / "brokkr_actions.json" + good = path.read_text(encoding="utf-8") + path.write_text(good.replace("host_actions.v0", "host_actions.v9"), encoding="utf-8") + self.assertIn("schema", self.refused()) + path.write_text(good, encoding="utf-8") + self.assertEqual(len(self.target.host_actions()[0]), 4) + path.write_text("not json", encoding="utf-8") + self.refused() + + def test_disabling_the_add_on_makes_its_action_unsupported_at_the_next_intent(self): + self.assertEqual(self.send("report")["status"], "accepted") + self.bpy.context.preferences.addons.pop(HOST) + receipt = self.send("report") + self.assertEqual(receipt["status"], "denied") + self.assertIn("Unsupported Blender command action", receipt["message"]) + self.assertEqual(self.target.host_actions(), ([], [])) + + def test_an_add_on_without_the_file_is_not_a_host_and_this_add_on_is_never_read(self): + (self.dir / "brokkr_actions.json").unlink() + self.assertEqual(self.target.host_actions(), ([], [])) + self.bpy.context.preferences.addons["brokkr_bridge"] = object() + self.assertEqual(self.target.host_actions(), ([], [])) + + class FakeNode: """The node database drain_commands reads: intents, receipts, and what it puts and deletes.""" def __init__(self, intents, receipts=()): diff --git a/surfaces/blender/tests/test_material_actions.py b/surfaces/blender/tests/test_material_actions.py index 884bca2..bf2baef 100644 --- a/surfaces/blender/tests/test_material_actions.py +++ b/surfaces/blender/tests/test_material_actions.py @@ -60,7 +60,7 @@ class FakeUndo: """What run_intent needs of bpy: a window to override and ed.undo_push, recorded.""" def __init__(self, bpy): self.pushes = [] - bpy.context = NS(window_manager=NS(windows=[object()]), temp_override=lambda **kw: contextlib.nullcontext()) + bpy.context = NS(window_manager=NS(windows=[object()]), preferences=NS(addons={}), temp_override=lambda **kw: contextlib.nullcontext()) ops = getattr(bpy, "ops", None) or NS() ops.ed = NS(undo_push=lambda message: self.pushes.append(message)) bpy.ops = ops diff --git a/surfaces/blender/tests/test_node_actions.py b/surfaces/blender/tests/test_node_actions.py index 2a24752..6d4a762 100644 --- a/surfaces/blender/tests/test_node_actions.py +++ b/surfaces/blender/tests/test_node_actions.py @@ -174,7 +174,7 @@ class FakeUndo: """What run_intent needs of bpy: a window to override and ed.undo_push, recorded.""" def __init__(self, bpy): self.pushes = [] - bpy.context = NS(window_manager=NS(windows=[object()]), temp_override=lambda **kw: contextlib.nullcontext()) + bpy.context = NS(window_manager=NS(windows=[object()]), preferences=NS(addons={}), temp_override=lambda **kw: contextlib.nullcontext()) ops = getattr(bpy, "ops", None) or NS() ops.ed = NS(undo_push=lambda message: self.pushes.append(message)) bpy.ops = ops diff --git a/surfaces/blender/tests/test_scene_actions.py b/surfaces/blender/tests/test_scene_actions.py index d9abebc..0281ba3 100644 --- a/surfaces/blender/tests/test_scene_actions.py +++ b/surfaces/blender/tests/test_scene_actions.py @@ -80,7 +80,7 @@ class FakeUndo: self.pushes = [] self.overrides = [] self.window = object() - bpy.context = NS(window_manager=NS(windows=[self.window]), + bpy.context = NS(window_manager=NS(windows=[self.window]), preferences=NS(addons={}), temp_override=lambda **kw: (self.overrides.append(kw), contextlib.nullcontext())[1]) ops = getattr(bpy, "ops", None) or NS() ops.ed = NS(undo_push=lambda message: self.pushes.append(message)) diff --git a/surfaces/blender/tests/test_stop_presence.py b/surfaces/blender/tests/test_stop_presence.py index 5e732d9..ea796b7 100644 --- a/surfaces/blender/tests/test_stop_presence.py +++ b/surfaces/blender/tests/test_stop_presence.py @@ -364,7 +364,7 @@ class NoPreferenceWritesTests(unittest.TestCase): # the sink toggle is the human's: no intent or action code reaches add-on preferences for name in ("scene_actions.py", "node_actions.py", "blender_target.py"): source = (BRIDGE / name).read_text(encoding="utf-8") - self.assertEqual(re.findall(r"[.]preferences\b|\bprefs\b", source), [], name) + self.assertEqual(re.findall(r"[.]preferences\b(?![.]addons[.]keys\(\))|\bprefs\b", source), [], name) if __name__ == "__main__": From 7b47fa5b8319f148e42353750283f5b5de5d26a6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 06:11:51 +0100 Subject: [PATCH 42/63] brokkr-ctl: host rows from the host snapshot in validate, send --help and status Co-Authored-By: Claude Sonnet 5.5 --- brokkr-ctl/src/actions.rs | 65 +++++++++++++++++++--- brokkr-ctl/src/blender.rs | 79 ++++++++++++++++++++++++--- brokkr-ctl/tests/cli.rs | 111 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 240 insertions(+), 15 deletions(-) diff --git a/brokkr-ctl/src/actions.rs b/brokkr-ctl/src/actions.rs index 590b29c..40a3d40 100644 --- a/brokkr-ctl/src/actions.rs +++ b/brokkr-ctl/src/actions.rs @@ -2,7 +2,9 @@ //! refuses. The owner is the add-on's `actions.json` (schema brokkr.blender.actions.v0); this module reads //! it as data and implements the same vocabulary and message text as `action_table.py`, pinned to it by //! the shared fixture `surfaces/blender/tests/action_cases.json`. Anything that reaches the store is still -//! decided by the add-on. +//! decided by the add-on. Host add-ons' rows (`brokkr.blender.host_actions.v0`) are not embedded: they come +//! from the add-on's host snapshot (`hostActions`), are searched after the built-ins, and are pinned by +//! `surfaces/blender/tests/host_action_cases.json`; a stale snapshot can only make ctl refuse early. use serde_json::{Map, Value}; use std::sync::LazyLock; @@ -20,8 +22,12 @@ fn actions() -> &'static [Value] { table()["actions"].as_array().map_or(&[], Vec::as_slice) } -fn entry(name: &str) -> Option<&'static Value> { - actions().iter().find(|a| a["name"] == name) +/// The built-in row of that name, else the first host row of that name. +fn entry<'a>(name: &str, host: &'a [Value]) -> Option<&'a Value> { + actions() + .iter() + .chain(host) + .find(|a| a["name"] == name) } /// The names brokkr-ctl writes itself: `--set` cannot name them, and the table does not validate them. @@ -66,9 +72,9 @@ pub fn number_text(value: f64) -> String { } /// Refuses an intent the table refuses, with the add-on's message; nothing is normalized (the add-on fills defaults). -pub fn validate(command: &Map) -> Result<(), String> { +pub fn validate(command: &Map, host: &[Value]) -> Result<(), String> { let action = command.get("action").and_then(Value::as_str).unwrap_or(""); - let Some(row) = entry(action) else { + let Some(row) = entry(action, host) else { return Err(format!("Unsupported Blender command action: {action}")); }; let present: Map = command @@ -286,8 +292,13 @@ fn check_string(spec: &Value, text: &str, path: &str) -> Result<(), String> { /// The actions section of `send --help`: every action with its fields, built from the table. pub fn help() -> String { + help_rows(actions()) +} + +/// The help body for any rows: the built-ins, or the host rows a snapshot carries. +pub fn help_rows(rows: &[Value]) -> String { let mut text = String::new(); - for action in actions() { + for action in rows { text.push_str(&format!( " {}: {}\n", action["name"].as_str().unwrap_or(""), @@ -408,7 +419,7 @@ mod tests { for case in &cases { let mut command = case["fields"].as_object().unwrap().clone(); command.insert("action".into(), case["action"].clone()); - let got = validate(&command).err().unwrap_or_else(|| "ok".to_string()); + let got = validate(&command, &[]).err().unwrap_or_else(|| "ok".to_string()); if Some(got.as_str()) != case["expect"].as_str() { wrong.push(format!( "{} {} expected {} got {got}", @@ -425,12 +436,50 @@ mod tests { ); } + /// The host rows a fixture add-on publishes, run through the same validator as the add-on's + /// HostTableTests: one set of messages for host rows too. + #[test] + fn the_host_parity_fixture_yields_the_add_ons_messages() { + let file: Value = serde_json::from_str(include_str!( + "../../surfaces/blender/tests/fixtures/brokkr_host_fixture/brokkr_actions.json" + )) + .unwrap(); + let host = file["actions"].as_array().unwrap().clone(); + let cases: Vec = serde_json::from_str(include_str!( + "../../surfaces/blender/tests/host_action_cases.json" + )) + .unwrap(); + assert!(cases.len() >= 15, "{} cases", cases.len()); + let mut wrong = Vec::new(); + for case in &cases { + let mut command = case["fields"].as_object().unwrap().clone(); + command.insert("action".into(), case["action"].clone()); + let got = validate(&command, &host) + .err() + .unwrap_or_else(|| "ok".to_string()); + if Some(got.as_str()) != case["expect"].as_str() { + wrong.push(format!( + "{} {} expected {} got {got}", + case["action"], case["fields"], case["expect"] + )); + } + } + assert!(wrong.is_empty(), "{}", wrong.join("\n")); + // Without the snapshot's rows the same host action is unsupported: ctl never invents rows. + let mut command = Map::new(); + command.insert("action".into(), "brokkr_host_fixture.report".into()); + assert_eq!( + validate(&command, &[]).unwrap_err(), + "Unsupported Blender command action: brokkr_host_fixture.report" + ); + } + #[test] fn a_non_string_action_is_unsupported_and_the_envelope_is_the_tables() { let mut command = Map::new(); command.insert("action".into(), Value::from(3)); assert_eq!( - validate(&command).unwrap_err(), + validate(&command, &[]).unwrap_err(), "Unsupported Blender command action: " ); assert_eq!( diff --git a/brokkr-ctl/src/blender.rs b/brokkr-ctl/src/blender.rs index dc47866..8a604ba 100644 --- a/brokkr-ctl/src/blender.rs +++ b/brokkr-ctl/src/blender.rs @@ -115,7 +115,7 @@ pub fn run(args: &[String]) -> Result { } let options = parse(rest)?; if options.help { - print!("{}", if sub == "send" { send_help() } else { group_help() }); + print!("{}", if sub == "send" { send_help(&options) } else { group_help() }); return Ok(0); } match sub.as_str() { @@ -214,6 +214,7 @@ fn build_intent( requested_by: &str, note: &str, sets: &[String], + host: &[Value], ) -> Result { let mut map = Map::new(); for set in sets { @@ -232,7 +233,7 @@ fn build_intent( map.insert("action".into(), action.into()); map.insert("requestedBy".into(), requested_by.into()); map.insert("note".into(), note.into()); - actions::validate(&map).map_err(|message| anyhow!(message))?; + actions::validate(&map, host).map_err(|message| anyhow!(message))?; Ok(Value::Object(map)) } @@ -240,7 +241,8 @@ fn send(options: &Options, action: &str) -> Result { let requested_by = requested_by(options)?; let mut store = open_store(options)?; let command_id = uuid::Uuid::now_v7().simple().to_string(); - let intent = build_intent(action, &command_id, &requested_by, &options.note, &options.sets)?; + let (host, _) = host_rows(&store)?; + let intent = build_intent(action, &command_id, &requested_by, &options.note, &options.sets, &host)?; store.push(&CultCacheEnvelope { key: format!("{INTENT_PREFIX}{command_id}"), r#type: INTENT_SCHEMA.to_string(), @@ -339,6 +341,27 @@ fn receipts(store: &SingleFileMessagePackBackingStore, last: Option) -> R Ok(0) } +/// The host snapshot as the add-on last published it, if any. +fn snapshot(store: &SingleFileMessagePackBackingStore) -> Result> { + for envelope in store.pull_all()? { + if envelope.key == SNAPSHOT_KEY && envelope.r#type == SNAPSHOT_SCHEMA { + return Ok(Some(decode(&envelope)?)); + } + } + Ok(None) +} + +/// The host rows the add-on published and when (`observedAt`); empty before any snapshot. A display and +/// early-refusal copy: the add-on admits or denies the intent itself. +fn host_rows(store: &SingleFileMessagePackBackingStore) -> Result<(Vec, String)> { + let Some(snapshot) = snapshot(store)? else { + return Ok((Vec::new(), String::new())); + }; + let rows = snapshot["hostActions"].as_array().cloned().unwrap_or_default(); + let observed = snapshot["observedAt"].as_str().unwrap_or("").to_string(); + Ok((rows, observed)) +} + fn status(store: &SingleFileMessagePackBackingStore) -> Result { for envelope in store.pull_all()? { if envelope.key == SNAPSHOT_KEY && envelope.r#type == SNAPSHOT_SCHEMA { @@ -358,6 +381,20 @@ fn status(store: &SingleFileMessagePackBackingStore) -> Result { print_field(key, value); } } + let names: Vec<&str> = snapshot["hostActions"] + .as_array() + .into_iter() + .flatten() + .filter_map(|row| row["name"].as_str()) + .collect(); + println!("hostActions: {}", names.join(", ")); + for error in snapshot["hostActionErrors"].as_array().into_iter().flatten() { + println!( + "hostActionErrors: {}: {}", + error["host"].as_str().unwrap_or(""), + error["error"].as_str().unwrap_or("") + ); + } return Ok(0); } } @@ -378,6 +415,10 @@ fn print_fields(value: &Value) { fn print_field(key: &str, value: &Value) { match value { + Value::String(text) if text.contains('\n') => { + println!("{key}:"); + text.lines().for_each(|line| println!(" {line}")); + } Value::String(text) => println!("{key}: {text}"), other => println!("{key}: {other}"), } @@ -433,7 +474,9 @@ the add-on decides the rest and its refusal comes back in the receipt. .to_string() } -pub fn send_help() -> String { +/// `send --help`: the built-ins, then, when a store is named (--store or $BROKKR_BLENDER_STORE), the host +/// rows its snapshot carries. It never fails for lack of a store. +fn send_help(options: &Options) -> String { let mut text = String::from( "\ brokkr-ctl blender send [--set key=json]... [--note text] [--agent name] [--no-wait] [--timeout secs] @@ -446,9 +489,31 @@ actions: ", ); text.push_str(&actions::help()); + text.push_str(&host_help(options)); text } +fn host_help(options: &Options) -> String { + let named = options.store.is_some() || std::env::var_os("BROKKR_BLENDER_STORE").is_some(); + if !named { + return "\nhost actions: add --store (or set BROKKR_BLENDER_STORE) to list the actions host add-ons publish.\n" + .to_string(); + } + match open_store(options).and_then(|store| host_rows(&store)) { + Err(error) => format!("\nhost actions: unavailable ({error}).\n"), + Ok((_, observed)) if observed.is_empty() => { + "\nhost actions: the store holds no host snapshot yet.\n".to_string() + } + Ok((rows, observed)) if rows.is_empty() => { + format!("\nhost actions (published by the add-on at {observed}): none.\n") + } + Ok((rows, observed)) => format!( + "\nhost actions (published by the add-on at {observed}):\n{}", + actions::help_rows(&rows) + ), + } +} + #[cfg(test)] mod tests { use super::*; @@ -462,17 +527,17 @@ mod tests { #[test] fn intent_carries_reserved_fields_and_refuses_overrides() { let sets = vec!["objectType=\"MESH\"".to_string(), "location=[0,0,1]".to_string()]; - let intent = build_intent("createObject", "abc", "nibu/hands", "n", &sets).unwrap(); + let intent = build_intent("createObject", "abc", "nibu/hands", "n", &sets, &[]).unwrap(); assert_eq!(intent["requestedBy"], "nibu/hands"); assert_eq!(intent["objectType"], "MESH"); assert_eq!(intent["location"][2], 1); for bad in ["requestedBy=\"x\"", "commandId=\"x\"", "action=\"x\"", "novalue", "k=notjson"] { assert!( - build_intent("createObject", "abc", "a/b", "", &[bad.to_string()]).is_err(), + build_intent("createObject", "abc", "a/b", "", &[bad.to_string()], &[]).is_err(), "{bad}" ); } - assert!(build_intent("../x", "abc", "a/b", "", &[]).is_err()); + assert!(build_intent("../x", "abc", "a/b", "", &[], &[]).is_err()); } #[test] diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs index 9936d7f..1cd8847 100644 --- a/brokkr-ctl/tests/cli.rs +++ b/brokkr-ctl/tests/cli.rs @@ -502,3 +502,114 @@ fn a_json_payload_is_refused_not_guessed() { let output = ctl(&path, &["wait", "j", "--timeout", "1"], None); assert_eq!(output.status.code(), Some(1)); } + +/// A store whose snapshot carries the fixture add-on's rows the way the add-on publishes them, plus one refused file. +fn host_store(dir: &Path) -> PathBuf { + let path = store_with_receipts(dir, &[("seed", "accepted")]); + let file: Value = serde_json::from_str(include_str!( + "../../surfaces/blender/tests/fixtures/brokkr_host_fixture/brokkr_actions.json" + )) + .unwrap(); + let rows: Vec = file["actions"] + .as_array() + .unwrap() + .iter() + .map(|row| { + let mut row = row.clone(); + row["host"] = json!("brokkr_host_fixture"); + row + }) + .collect(); + let snapshot = json!({ + "observedAt": "2026-11-28T10:00:00.000000+00:00", "mode": "OBJECT", + "hostActions": rows, + "hostActionErrors": [{"host": "broken_addon", "error": "brokkr_actions.json: host schema must be brokkr.blender.host_actions.v0"}], + }); + push(&path, &[envelope_at("brokkr.blender.host_snapshot.v0", "blender/host/current", &snapshot)]); + path +} + +fn help_text(args: &[&str], store: Option<&Path>) -> String { + let mut command = Command::new(env!("CARGO_BIN_EXE_brokkr-ctl")); + command.arg("blender").args(args).env_remove("BROKKR_BLENDER_STORE"); + if let Some(store) = store { + command.arg("--store").arg(store); + } + stdout(&command.output().unwrap()) +} + +#[test] +fn send_help_with_a_store_lists_the_host_rows_with_their_bounds() { + let dir = tempfile::tempdir().unwrap(); + let path = host_store(dir.path()); + let text = help_text(&["send", "--help"], Some(&path)); + assert!(text.contains("host actions (published by the add-on at 2026-11-28T10:00:00.000000+00:00):"), "{text}"); + for needle in ["brokkr_host_fixture.add_empty", "size: number 0.1..10", "name: string", "brokkr_host_fixture.report"] { + assert!(text.contains(needle), "{needle} in {text}"); + } + assert!(!text.contains("brokkr_host_fixture.apply"), "human-only is absence"); + assert!(text.contains("createObject"), "the built-ins are still listed"); +} + +#[test] +fn send_help_without_a_store_says_host_actions_need_one_and_with_no_snapshot_says_so() { + let text = help_text(&["send", "--help"], None); + assert!(text.contains("host actions: add --store"), "{text}"); + assert!(text.contains("createObject")); + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("seed", "accepted")]); + assert!(help_text(&["send", "--help"], Some(&path)).contains("the store holds no host snapshot yet")); +} + +#[test] +fn a_host_intent_out_of_bounds_exits_1_and_leaves_the_store_byte_identical() { + let dir = tempfile::tempdir().unwrap(); + let path = host_store(dir.path()); + let before = std::fs::read(&path).unwrap(); + let cases: [(&[&str], &str); 3] = [ + (&["send", "brokkr_host_fixture.add_empty", "--set", "name=\"E\"", "--set", "size=99"], "size must be between 0.1 and 10."), + (&["send", "brokkr_host_fixture.add_empty"], "name is required."), + (&["send", "brokkr_host_fixture.report", "--set", "x=1"], "has no field 'x'"), + ]; + for (args, message) in cases { + let mut args = args.to_vec(); + args.extend(["--agent", "hands", "--no-wait"]); + let output = ctl(&path, &args, Some("nibu")); + assert_eq!(output.status.code(), Some(1), "{args:?}"); + assert!(String::from_utf8_lossy(&output.stderr).contains(message), "{args:?}"); + assert_eq!(std::fs::read(&path).unwrap(), before, "{args:?} wrote to the store"); + } +} + +#[test] +fn a_human_only_operator_is_unsupported_and_a_published_host_action_is_written() { + let dir = tempfile::tempdir().unwrap(); + let path = host_store(dir.path()); + let before = std::fs::read(&path).unwrap(); + let output = ctl(&path, &["send", "brokkr_host_fixture.apply", "--agent", "hands", "--no-wait"], Some("nibu")); + assert_eq!(output.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&output.stderr).contains("Unsupported Blender command action: brokkr_host_fixture.apply")); + assert_eq!(std::fs::read(&path).unwrap(), before); + let sent = ctl(&path, &["send", "brokkr_host_fixture.add_empty", "--set", "name=\"E\"", "--set", "size=2", "--agent", "hands", "--no-wait"], Some("nibu")); + assert_eq!(sent.status.code(), Some(0), "{}", String::from_utf8_lossy(&sent.stderr)); + let id = stdout(&sent).trim().strip_prefix("commandId: ").unwrap().to_string(); + let store = SingleFileMessagePackBackingStore::new(&path); + let intent = store.pull_all().unwrap().into_iter().find(|e| e.key == format!("blender/commands/{id}")).unwrap(); + let value: Value = rmp_serde::from_slice(&intent.payload).unwrap(); + assert_eq!((value["action"].as_str(), value["size"].as_i64()), (Some("brokkr_host_fixture.add_empty"), Some(2))); +} + +#[test] +fn status_names_the_host_actions_and_each_refused_file_and_a_multiline_result_prints_indented() { + let dir = tempfile::tempdir().unwrap(); + let path = host_store(dir.path()); + let text = stdout(&ctl(&path, &["status"], None)); + assert!(text.contains("hostActions: brokkr_host_fixture.add_empty, brokkr_host_fixture.report"), "{text}"); + assert!(text.contains("hostActionErrors: broken_addon: brokkr_actions.json: host schema must be"), "{text}"); + push( + &path, + &[envelope_at(RECEIPT, "blender/receipts/h", &json!({"commandId": "h", "status": "accepted", "hostResult": "objects: 3\nscenes: 1", "observedAt": "2026-11-28T10:00:01+00:00"}))], + ); + let receipt = stdout(&ctl(&path, &["wait", "h"], None)); + assert!(receipt.contains("hostResult:\n objects: 3\n scenes: 1\n"), "{receipt}"); +} From 740a2c84c31b701cd693b13e9d0ecdd370b746d6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 06:12:09 +0100 Subject: [PATCH 43/63] install.md: host add-on actions Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/docs/install.md | 37 ++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 1bd94b9..cbb17fe 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -246,6 +246,43 @@ Behaviour the table does not say, per action: 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, at every intent and snapshot (a changed file is re-read; a +disabled add-on's actions are unknown at its next intent). Beyond the file's own shape it checks that each +named operator exists and is a Python class defined by that add-on's module, that 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), that the operator's RNA hard limits contain the row's bounds, and that `result` names a +`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. + +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). + +The admitted rows are published in the host snapshot as `hostActions` (each with its `host` module). +`brokkr-ctl blender send --help --store ` 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 From c1aacd9f7b2066c8ac7595ff2b7ec1659722b70b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 06:16:29 +0100 Subject: [PATCH 44/63] live/host_action.py: GUI Blender 5.3 proof of host rows, undo steps, results and human-only absence Co-Authored-By: Claude Sonnet 5.5 --- brokkr-ctl/tests/cli.rs | 2 +- surfaces/blender/tests/live/host_action.py | 241 ++++++++++++++++++ .../tests/live/host_action.result.json | 218 ++++++++++++++++ surfaces/blender/tests/test_agent_turn.py | 4 +- 4 files changed, 462 insertions(+), 3 deletions(-) create mode 100644 surfaces/blender/tests/live/host_action.py create mode 100644 surfaces/blender/tests/live/host_action.result.json diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs index 1cd8847..6e3d124 100644 --- a/brokkr-ctl/tests/cli.rs +++ b/brokkr-ctl/tests/cli.rs @@ -582,7 +582,7 @@ fn a_host_intent_out_of_bounds_exits_1_and_leaves_the_store_byte_identical() { } #[test] -fn a_human_only_operator_is_unsupported_and_a_published_host_action_is_written() { +fn an_operator_left_out_of_the_file_is_unsupported_and_a_published_host_action_is_written() { let dir = tempfile::tempdir().unwrap(); let path = host_store(dir.path()); let before = std::fs::read(&path).unwrap(); diff --git a/surfaces/blender/tests/live/host_action.py b/surfaces/blender/tests/live/host_action.py new file mode 100644 index 0000000..898137a --- /dev/null +++ b/surfaces/blender/tests/live/host_action.py @@ -0,0 +1,241 @@ +"""Live proof, in GUI Blender with the add-on installed as an extension, that a host add-on's brokkr_actions.json adds +rows the agent turn admits, runs and undoes like a built-in, and that an operator left out of the file stays human-only. + + BROKKR_SCRATCH= + BROKKR_ADDON_MODULE= + BROKKR_CULTLIB= + blender --python host_action.py -- + +Run it in Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH; without them the operator's own extensions folder is used). The script +refuses to run when they are unset. It copies tests/fixtures/brokkr_host_fixture into BLENDER_USER_SCRIPTS/addons and +enables it there; it writes nothing else outside BROKKR_SCRATCH. Every intent is put into the node database as +brokkr-ctl does and answered by the add-on's own 1 s drain (the sink is on). Proves, with wm.undo_stack as the counter: + + * the snapshot lists the fixture's four rows (host, no apply) and no hostActionErrors; + * add_empty is accepted as exactly one new undo step, undo removes the empty, redo brings it back; + * report is accepted with hostResult equal to what the operator wrote, no new step, humanEditSeq unchanged; + * refuse is failed with the operator's text and cancel is failed, each with no new step; + * apply (registered, left out of the file) and wm.save_mainfile are denied Unsupported with no step, the scene + unchanged and no 'Applied' object. + +Writes .result.json, then quits Blender. +""" +import importlib +import json +import os +import shutil +import sys +import traceback +from pathlib import Path + +import bpy + +for _name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): + if not os.environ.get(_name): # this Blender ignores BLENDER_USER_RESOURCE_PATH: without these, her own folders are used + raise SystemExit(f"{_name} is not set: run this in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") +if os.path.normcase(os.path.abspath(bpy.utils.user_resource("EXTENSIONS"))) != os.path.normcase(os.path.abspath(os.environ["BLENDER_USER_EXTENSIONS"])): + raise SystemExit("Blender's extensions folder is not BLENDER_USER_EXTENSIONS; refusing to touch it") +if os.path.normcase(os.path.abspath(bpy.utils.user_resource("SCRIPTS"))) != os.path.normcase(os.path.abspath(os.environ["BLENDER_USER_SCRIPTS"])): + raise SystemExit("Blender's scripts folder is not BLENDER_USER_SCRIPTS; refusing to touch it") + +SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() +SCRATCH.mkdir(parents=True, exist_ok=True) +OUT = sys.argv[sys.argv.index("--") + 1] +MODULE = os.environ.get("BROKKR_ADDON_MODULE", "bl_ext.user_default.brokkr_bridge") +HOST = "brokkr_host_fixture" +FIXTURE = Path(__file__).resolve().parents[1] / "fixtures" / HOST +R = {"blender": bpy.app.version_string, "module": MODULE, "checks": []} + +addons_dir = Path(os.environ["BLENDER_USER_SCRIPTS"]) / "addons" +addons_dir.mkdir(parents=True, exist_ok=True) +if (addons_dir / HOST).exists(): + shutil.rmtree(addons_dir / HOST) +shutil.copytree(FIXTURE, addons_dir / HOST, ignore=shutil.ignore_patterns("__pycache__")) +bpy.utils.refresh_script_paths() + +bpy.ops.preferences.addon_enable(module=MODULE) +bpy.ops.preferences.addon_enable(module=HOST) +addon = importlib.import_module(MODULE) +bt = importlib.import_module(MODULE + ".blender_target") +prefs = bpy.context.preferences.addons[MODULE].preferences +bpy.ops.wm.save_as_mainfile(filepath=str(SCRATCH / "live.blend")) +CACHE = str(SCRATCH / "queue.ccmp") +prefs.cultmesh_cache_path = CACHE +prefs.debug_mirror_root = "" +prefs.auto_drain_commands = True # the sink +prefs.cultlib_py_src = os.environ.get("BROKKR_CULTLIB", prefs.cultlib_py_src) +adapter = addon.target() + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def win(): + return bpy.context.temp_override(window=bpy.context.window_manager.windows[0]) + + +def steps_now(): + return [s.name for s in bpy.context.window_manager.undo_stack.steps] + + +def undo(): + with win(): + bpy.ops.ed.undo() + + +def redo(): + with win(): + bpy.ops.ed.redo() + + +def node(): + return adapter._open_node(CACHE, prefs.cultlib_py_src) + + +N = [0] + + +def queue(**cmd): + N[0] += 1 + cid = "host-%04d" % N[0] + n, docs = node() + cmd.update(commandId=cid, schema=bt.COMMAND_INTENT_SCHEMA, requestedBy="nibu/hands") + n.database.put(docs["command_intent"], f"blender/commands/{cid}", cmd) + return cid + + +def receipt(cid): + n, _ = node() + return n.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}).get(f"blender/receipts/{cid}") + + +def names(): + return sorted(o.name for o in bpy.data.objects) + + +S = {} +WAIT = {"ticks": 0} + + +def until(pred, limit=40): + def step(): + WAIT["ticks"] += 1 + if pred(): + WAIT["ticks"] = 0 + return True + if WAIT["ticks"] > limit: + raise TimeoutError("the drain did not receipt in time") + return False + return step + + +def once(fn): + def step(): + fn() + return True + return step + + +def send(key, **fields): + S[key + ":before"] = {"steps": steps_now(), "names": names(), "seq": adapter.human_edit_seq} + S[key] = queue(**fields) + + +def done(key): + return lambda: receipt(S[key]) is not None + + +def same_world(key): + before = S[key + ":before"] + return (steps_now() == before["steps"] and names() == before["names"] and adapter.human_edit_seq == before["seq"]) + + +def snapshot_check(): + snapshot = adapter.capture_snapshot(bpy.context, True) + rows = snapshot["hostActions"] + expect = [f"{HOST}.{n}" for n in ("add_empty", "report", "refuse", "cancel")] + check("the snapshot lists the fixture's four rows with their host and none other (apply is left out)", + sorted(r["name"] for r in rows) == sorted(expect) and {r["host"] for r in rows} == {HOST}, [r["name"] for r in rows]) + check("the snapshot carries no hostActionErrors", snapshot["hostActionErrors"] == [], snapshot["hostActionErrors"]) + check("the operators are registered by the legacy add-on, apply included", + all(hasattr(getattr(bpy.ops, HOST), n) for n in ("add_empty", "report", "refuse", "cancel", "apply"))) + + +def add_check(): + r = receipt(S["add"]) + before = S["add:before"] + after = steps_now() + check("add_empty is accepted", r["status"] == "accepted", r) + check("add_empty is exactly one new undo step carrying the receipt's label", + len(after) == len(before["steps"]) + 1 and after[-1] == r["undoLabel"] and r["undoLabel"].startswith(f"Brokkr nibu/hands: {HOST}.add_empty "), + {"before": before["steps"][-2:], "after": after[-2:], "label": r["undoLabel"]}) + check("add_empty made the empty with the declared name and size", + "LiveEmpty" in bpy.data.objects and abs(bpy.data.objects["LiveEmpty"].empty_display_size - 2.0) < 1e-6, names()) + check("add_empty is the agent's write: humanEditSeq did not move", adapter.human_edit_seq == before["seq"]) + S["add:names"] = names() + undo() + check("one undo removes the empty", "LiveEmpty" not in bpy.data.objects, names()) + redo() + check("redo brings it back", names() == S["add:names"], names()) + + +def report_check(): + r = receipt(S["report"]) + expect = f"objects: {len(bpy.data.objects)}\nscenes: {len(bpy.data.scenes)}" + check("report is accepted with hostResult equal to what the operator wrote", r["status"] == "accepted" and r["hostResult"] == expect, [r["status"], r["hostResult"], expect]) + check("report pushed no undo step, added no object and left humanEditSeq alone", same_world("report"), [steps_now()[-2:], S["report:before"]["steps"][-2:]]) + + +def failure_check(key, text): + def run(): + r = receipt(S[key]) + check(f"{key} is failed{' with ' + repr(text) if text else ''}", r["status"] == "failed" and text in r["message"], r) + check(f"{key} pushed no undo step and changed nothing", same_world(key) and r["undoLabel"] == "", r["undoLabel"]) + return run + + +def denied_check(key, action): + def run(): + r = receipt(S[key]) + check(f"{action} is denied Unsupported", r["status"] == "denied" and "Unsupported Blender command action" in r["message"], r) + check(f"{action} ran nothing: no step, no new object, no 'Applied'", same_world(key) and "Applied" not in bpy.data.objects, names()) + return run + + +steps = [ + once(snapshot_check), + once(lambda: send("add", action=f"{HOST}.add_empty", name="LiveEmpty", size=2)), until(done("add")), once(add_check), + once(lambda: send("report", action=f"{HOST}.report")), until(done("report")), once(report_check), + once(lambda: send("refuse", action=f"{HOST}.refuse")), until(done("refuse")), once(failure_check("refuse", "the fixture refuses")), + once(lambda: send("cancel", action=f"{HOST}.cancel")), until(done("cancel")), once(failure_check("cancel", "cancelled; nothing changed")), + once(lambda: send("apply", action=f"{HOST}.apply")), until(done("apply")), once(denied_check("apply", f"{HOST}.apply")), + once(lambda: send("save", action="wm.save_mainfile")), until(done("save")), once(denied_check("save", "wm.save_mainfile")), +] +i = 0 + + +def write(): + R["ok"] = bool(R["checks"]) and all(c["ok"] for c in R["checks"]) and not R.get("errors") + with open(OUT + ".result.json", "w") as f: + json.dump(R, f, indent=1, default=str) + + +def tick(): + global i + if i < len(steps): + try: + if steps[i](): + i += 1 + except Exception: + R.setdefault("errors", []).append({"step": i, "error": traceback.format_exc()}) + i = len(steps) + write() + return 0.5 + write() + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(tick, first_interval=3.0) diff --git a/surfaces/blender/tests/live/host_action.result.json b/surfaces/blender/tests/live/host_action.result.json new file mode 100644 index 0000000..a493c29 --- /dev/null +++ b/surfaces/blender/tests/live/host_action.result.json @@ -0,0 +1,218 @@ +{ + "blender": "5.3.0", + "module": "bl_ext.user_default.brokkr_bridge", + "checks": [ + { + "name": "the snapshot lists the fixture's four rows with their host and none other (apply is left out)", + "ok": true, + "detail": [ + "brokkr_host_fixture.add_empty", + "brokkr_host_fixture.report", + "brokkr_host_fixture.refuse", + "brokkr_host_fixture.cancel" + ] + }, + { + "name": "the snapshot carries no hostActionErrors", + "ok": true, + "detail": [] + }, + { + "name": "the operators are registered by the legacy add-on, apply included", + "ok": true, + "detail": null + }, + { + "name": "add_empty is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0001", + "action": "brokkr_host_fixture.add_empty", + "status": "accepted", + "message": "Operator brokkr_host_fixture.add_empty finished.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: brokkr_host_fixture.add_empty ost-0001", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T05:15:08.910684+00:00" + } + }, + { + "name": "add_empty is exactly one new undo step carrying the receipt's label", + "ok": true, + "detail": { + "before": [ + "Original" + ], + "after": [ + "Original", + "Brokkr nibu/hands: brokkr_host_fixture.add_empty ost-0001" + ], + "label": "Brokkr nibu/hands: brokkr_host_fixture.add_empty ost-0001" + } + }, + { + "name": "add_empty made the empty with the declared name and size", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light", + "LiveEmpty" + ] + }, + { + "name": "add_empty is the agent's write: humanEditSeq did not move", + "ok": true, + "detail": null + }, + { + "name": "one undo removes the empty", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light" + ] + }, + { + "name": "redo brings it back", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light", + "LiveEmpty" + ] + }, + { + "name": "report is accepted with hostResult equal to what the operator wrote", + "ok": true, + "detail": [ + "accepted", + "objects: 4\nscenes: 1", + "objects: 4\nscenes: 1" + ] + }, + { + "name": "report pushed no undo step, added no object and left humanEditSeq alone", + "ok": true, + "detail": [ + [ + "Original", + "Brokkr nibu/hands: brokkr_host_fixture.add_empty ost-0001" + ], + [ + "Original", + "Brokkr nibu/hands: brokkr_host_fixture.add_empty ost-0001" + ] + ] + }, + { + "name": "refuse is failed with 'the fixture refuses'", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0003", + "action": "brokkr_host_fixture.refuse", + "status": "failed", + "message": "Error: the fixture refuses", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T05:15:13.022948+00:00" + } + }, + { + "name": "refuse pushed no undo step and changed nothing", + "ok": true, + "detail": "" + }, + { + "name": "cancel is failed with 'cancelled; nothing changed'", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0004", + "action": "brokkr_host_fixture.cancel", + "status": "failed", + "message": "Operator brokkr_host_fixture.cancel cancelled; nothing changed.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T05:15:14.080400+00:00" + } + }, + { + "name": "cancel pushed no undo step and changed nothing", + "ok": true, + "detail": "" + }, + { + "name": "brokkr_host_fixture.apply is denied Unsupported", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0005", + "action": "brokkr_host_fixture.apply", + "status": "denied", + "message": "Unsupported Blender command action: brokkr_host_fixture.apply", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T05:15:16.137129+00:00" + } + }, + { + "name": "brokkr_host_fixture.apply ran nothing: no step, no new object, no 'Applied'", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light", + "LiveEmpty" + ] + }, + { + "name": "wm.save_mainfile is denied Unsupported", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0006", + "action": "wm.save_mainfile", + "status": "denied", + "message": "Unsupported Blender command action: wm.save_mainfile", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T05:15:18.194603+00:00" + } + }, + { + "name": "wm.save_mainfile ran nothing: no step, no new object, no 'Applied'", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light", + "LiveEmpty" + ] + } + ], + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index 6578b4b..60afb83 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -372,7 +372,7 @@ class HostActionTests(unittest.TestCase): self.assertEqual(len(self.bpy.undo.pushes), 1) self.assertTrue(self.bpy.undo.pushes[0].endswith("(failed)")) - def test_a_human_only_operator_and_a_c_operator_are_unsupported_and_leave_no_trace(self): + def test_an_operator_left_out_of_the_file_and_a_c_operator_are_unsupported_and_leave_no_trace(self): for action in (f"{HOST}.apply", "wm.save_mainfile", "brokkr.stop_agents"): receipt = self.run_action(action=action) self.assertEqual(receipt["status"], "denied", action) @@ -385,7 +385,7 @@ class HostActionTests(unittest.TestCase): self.assertEqual(self.send("add_empty", name="E")["status"], "denied") self.assertEqual(self.send("report")["status"], "accepted") - def test_the_snapshot_lists_the_admitted_rows_with_their_host_and_no_human_only_row(self): + def test_the_snapshot_lists_the_admitted_rows_with_their_host_and_no_left_out_row(self): self.bpy.data = NS(objects=[], scenes=[], collections=[], materials=[], images=[], filepath="") self.bpy.app = NS(version=(5, 3, 0), background=False) context = NS(selected_objects=[], active_object=None, scene=None, mode="OBJECT") From 26efb1b31a9814e5697ea7104785db8d3e64ee89 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 06:19:04 +0100 Subject: [PATCH 45/63] Host operator: drop the redundant _wrote writes; tests pin the envelope and the own add-on never read as a host Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/brokkr_bridge/blender_target.py | 4 +--- surfaces/blender/tests/test_agent_turn.py | 11 ++++++++++- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 8bde4b0..1c78e9b 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -847,11 +847,9 @@ class BrokkrBlenderTarget: text = getattr(manager, result, "") or "" if len(text) > HOST_RESULT_LIMIT: text = text[:HOST_RESULT_LIMIT] + " [truncated]" - if "FINISHED" in outcome: - self._wrote = bool(row["changesScene"]) + if "FINISHED" in outcome: # run_intent pushes an undo step for an accepted changesScene row only receipt = self._receipt(command, "accepted", f"Operator {name} finished.", "") else: - self._wrote = False receipt = self._receipt(command, "failed", f"Operator {name} cancelled; nothing changed.", "") receipt["hostResult"] = text return receipt diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index 60afb83..8b8174b 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -326,9 +326,14 @@ class HostActionTests(unittest.TestCase): def test_the_default_is_filled_and_an_undeclared_field_never_reaches_the_operator(self): self.assertEqual(self.send("add_empty", name="E")["status"], "accepted") self.assertEqual(self.ops["add_empty"].calls, [{"name": "E", "size": 1}]) + self.ops["add_empty"].calls.clear() + self.assertEqual(self.send("add_empty", name="E", note="why")["status"], "accepted") + self.assertEqual(self.ops["add_empty"].calls, [{"name": "E", "size": 1}]) # the envelope never reaches the operator + self.ops["add_empty"].calls.clear() + self.ops["add_empty"].calls.append({}) denied = self.send("add_empty", name="E", location=[1, 2, 3]) self.assertEqual(denied["status"], "denied") - self.assertEqual(len(self.ops["add_empty"].calls), 1) + self.assertEqual(len(self.ops["add_empty"].calls), 1) # only the seeded marker: the denied intent ran nothing def test_a_non_changing_operator_pushes_no_undo_step_and_returns_its_result(self): receipt = self.send("report") @@ -452,6 +457,10 @@ class HostActionTests(unittest.TestCase): self.assertEqual(self.target.host_actions(), ([], [])) self.bpy.context.preferences.addons["brokkr_bridge"] = object() self.assertEqual(self.target.host_actions(), ([], [])) + (self.dir / "brokkr_actions.json").write_bytes((FIXTURE / "brokkr_actions.json").read_bytes()) + with unittest.mock.patch.object(sys.modules["brokkr_bridge"], "__file__", str(self.dir / "__init__.py"), create=True): + self.bpy.context.preferences.addons.pop(HOST) # a file sits beside this add-on itself: still not read as a host's + self.assertEqual(self.target.host_actions(), ([], [])) class FakeNode: From fb9696b6394b794100ceb752fb787936cff62813 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 07:07:18 +0100 Subject: [PATCH 46/63] Host actions: files are read only by the human's reload, never on an intent Reload Host Actions operator (refuses inside an agent turn) and one startup read; envelope-named fields, unknown row keys, read-only results and UNDO operators on non-changing rows refuse the file; a failed poll or unclearable result refuses before any undo step; tests pin the ownership prefix, enum, snapshot errors and the guards; live proof extended; docs say the flags are the host's word. Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/brokkr_bridge/__init__.py | 29 ++++ .../blender/brokkr_bridge/action_table.py | 3 + .../blender/brokkr_bridge/blender_target.py | 115 ++++++++------- surfaces/blender/docs/install.md | 27 +++- surfaces/blender/tests/live/host_action.py | 47 +++++- .../tests/live/host_action.result.json | 110 +++++++++++++- surfaces/blender/tests/test_action_table.py | 7 + surfaces/blender/tests/test_addon_ui.py | 31 ++++ surfaces/blender/tests/test_agent_turn.py | 134 +++++++++++++++++- 9 files changed, 434 insertions(+), 69 deletions(-) diff --git a/surfaces/blender/brokkr_bridge/__init__.py b/surfaces/blender/brokkr_bridge/__init__.py index c9db1ec..0801c16 100644 --- a/surfaces/blender/brokkr_bridge/__init__.py +++ b/surfaces/blender/brokkr_bridge/__init__.py @@ -389,6 +389,7 @@ class BROKKR_PT_status(bpy.types.Panel): row = layout.row(align=True) row.operator("brokkr.capture_snapshot", icon="FILE_REFRESH") + layout.operator("brokkr.reload_host_actions", icon="FILE_REFRESH") row.operator("brokkr.drain_commands", icon="PLAY") layout.prop(prefs, "auto_drain_commands") @@ -495,6 +496,23 @@ class BROKKR_OT_stop_agents(bpy.types.Operator): return {"FINISHED"} +class BROKKR_OT_reload_host_actions(bpy.types.Operator): + bl_idname = "brokkr.reload_host_actions" + bl_label = "Reload Host Actions" + bl_description = ("Read each enabled add-on's brokkr_actions.json again. Only this button does: an agent cannot cause " + "a re-read, so an edited file admits nothing until you press it") + + def execute(self, context): + try: + found = target().reload_host_actions() + except PermissionError as exc: # inside an agent turn: a human acts here, never an agent + self.report({"ERROR"}, str(exc)) + return {"CANCELLED"} + rows, errors = target().host_actions() + self.report({"INFO"}, f"{found} host file(s) read; {len(rows)} host action(s) admitted, {len(errors)} file(s) refused.") + return {"FINISHED"} + + class BROKKR_OT_drain_commands(bpy.types.Operator): bl_idname = "brokkr.drain_commands" bl_label = "Drain Commands" @@ -741,6 +759,7 @@ classes = ( BROKKR_PT_status, BROKKR_OT_stop_agents, BROKKR_OT_capture_snapshot, + BROKKR_OT_reload_host_actions, BROKKR_OT_drain_commands, BROKKR_OT_start_server, BROKKR_OT_stop_server, @@ -752,6 +771,15 @@ classes = ( ) +def _load_host_actions_once(): + """One read of the host files shortly after startup, when the other add-ons are enabled (not an intent's doing).""" + try: + target().reload_host_actions() + except Exception: + pass + return None + + def register(): for cls in classes: bpy.utils.register_class(cls) @@ -762,6 +790,7 @@ def register(): getattr(bpy.app.handlers, name).append(handler) if not bpy.app.timers.is_registered(_auto_drain_commands): bpy.app.timers.register(_auto_drain_commands, first_interval=1.0, persistent=True) + bpy.app.timers.register(_load_host_actions_once, first_interval=3.0) def unregister(): diff --git a/surfaces/blender/brokkr_bridge/action_table.py b/surfaces/blender/brokkr_bridge/action_table.py index 48a888f..eba7e82 100644 --- a/surfaces/blender/brokkr_bridge/action_table.py +++ b/surfaces/blender/brokkr_bridge/action_table.py @@ -132,9 +132,12 @@ def check_host(document: Any, charsets: dict[str, Any]) -> None: if "result" in row and not (isinstance(row["result"], str) and row["result"].isidentifier()): raise TableInvalid(f"{name}.result must be an identifier") fields = {} + envelope = table()["envelope"] for field in row["fields"]: if not isinstance(field, dict) or not isinstance(field.get("name"), str) or field["name"] in fields: raise TableInvalid(f"{name} has a missing or repeated field name") + if field["name"] in envelope: + raise TableInvalid(f"{name}.{field['name']} is an envelope key; Brokkr writes it, so the operator would never receive the agent's value") fields[field["name"]] = field for field in fields.values(): where = f"{name}.{field['name']}" diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 1c78e9b..e030c89 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -1,5 +1,6 @@ from __future__ import annotations +import contextlib import ctypes import functools import json @@ -102,10 +103,6 @@ CAPABILITIES = ( ) -class _NoHostFile(Exception): - """The add-on has no brokkr_actions.json: it is not a host.""" - - def _first_line(text: str) -> str: return text.strip().splitlines()[0] if text.strip() else "failed" @@ -131,7 +128,7 @@ class BrokkrBlenderTarget: self.agent_turn = False # true only inside run_intent self._wrote = True # run_intent: false when an accepted action changed nothing self._receipted: set[str] = set() - self._host_files: dict[str, tuple[tuple, Any]] = {} # module -> (file stamp, parsed document or error text): a cache of reads, never truth + self._host_docs: dict[str, Any] = {} # module -> parsed host document or the error that refused it; written only by reload_host_actions self._unsent: list[tuple[dict[str, Any], str]] = [] # receipts whose write failed: written first on the next drain, never read as truth self._recent: deque[dict[str, Any]] = deque(maxlen=RECEIPTS_KEPT) # display cache of the node's receipts self._receipts_loaded = False @@ -646,25 +643,50 @@ class BrokkrBlenderTarget: "hostActionErrors": host_errors, } + def reload_host_actions(self) -> int: + """Read every enabled add-on's brokkr_actions.json (this add-on excepted) into the stored host documents, + replacing what was stored: the one place a host file is read. A human act: the panel's Reload Host Actions + button, and once shortly after this add-on registers. An intent never reaches it (an agent turn cannot + cause a re-read: this refuses inside one), so a file rewritten to list another operator admits nothing + until she reloads. A file is stored parsed and checked, or as the error that refused it; the live checks in + host_actions still run at every intent. Returns the number of host files found.""" + if self.agent_turn: + raise PermissionError("Host actions are reloaded by the human only, never inside an agent turn.") + own = __package__ or "" + docs: dict[str, Any] = {} + for module in self.bpy.context.preferences.addons.keys(): + if module == own: + continue + source = getattr(sys.modules.get(module), "__file__", None) + path = Path(source).with_name(HOST_ACTIONS_FILE) if source else None + if path is None or not path.is_file(): + continue + try: + document = json.loads(path.read_text(encoding="utf-8")) + at.check_host(document, at.table()["charsets"]) + docs[module] = document + except Exception as error: + docs[module] = str(error) + self._host_docs = docs + return len(docs) + def host_actions(self) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: - """The one discovery of host rows: ([row + 'host' module], [{host, error}]). Each enabled add-on but this - one may carry brokkr_actions.json beside its __init__.py; the file is admitted whole or not at all. The - file is the add-on's word; what is checked here is what Brokkr can see: the operator exists and is a - Python class defined by that add-on, every field is a property of it of the matching type whose RNA hard - limits contain the row's bounds, and result is a WindowManager string property. Only the parse is cached - (on path, mtime and size); the live checks run each time, so a disabled add-on or an unregistered operator - is gone at the next intent. A name two files claim fails ownership in all but its owner.""" + """The host rows admitted now: ([row + 'host' module], [{host, error}]), from the documents the last + reload stored (no file is read here). A document is admitted whole or not at all. The file is the add-on's + word; what is checked here, at every call, is what Brokkr can see: the add-on is still enabled, the operator + exists and is a Python class defined by that add-on (module equal to it or under it: 'aeth_ships' is not + under 'aeth'), every field is a property of it of the matching type whose RNA hard limits contain the row's + bounds, a row that changes nothing names no operator that pushes undo itself (bl_options UNDO), and result + is a writable WindowManager string property. A disabled add-on or an unregistered operator is gone at the + next intent. A name two files claim fails ownership in all but its owner.""" rows: list[dict[str, Any]] = [] errors: list[dict[str, Any]] = [] - own = __package__ or "" - modules = [m for m in self.bpy.context.preferences.addons.keys() if m != own] - for module in modules: - try: - document = self._host_document(module) - except _NoHostFile: + enabled = set(self.bpy.context.preferences.addons.keys()) + for module, document in self._host_docs.items(): + if module not in enabled: continue - except Exception as error: - errors.append({"host": module, "error": _first_line(f"{HOST_ACTIONS_FILE}: {error}")}) + if isinstance(document, str): + errors.append({"host": module, "error": _first_line(f"{HOST_ACTIONS_FILE}: {document}")}) continue try: for row in document["actions"]: @@ -675,28 +697,6 @@ class BrokkrBlenderTarget: rows.extend({**row, "host": module} for row in document["actions"]) return rows, errors - def _host_document(self, module: str) -> dict[str, Any]: - loaded = sys.modules.get(module) - source = getattr(loaded, "__file__", None) - path = Path(source).with_name(HOST_ACTIONS_FILE) if source else None - if path is None or not path.is_file(): - self._host_files.pop(module, None) - raise _NoHostFile() - info = path.stat() - stamp = (str(path), info.st_mtime_ns, info.st_size) - cached = self._host_files.get(module) - if cached is None or cached[0] != stamp: - try: - document = json.loads(path.read_text(encoding="utf-8")) - at.check_host(document, at.table()["charsets"]) - cached = (stamp, document) - except Exception as error: - cached = (stamp, str(error)) - self._host_files[module] = cached - if isinstance(cached[1], str): - raise ValueError(cached[1]) - return cached[1] - def _check_host_row(self, module: str, row: dict[str, Any]) -> None: bpy = self.bpy name = row["name"] @@ -706,6 +706,8 @@ class BrokkrBlenderTarget: owned = getattr(owner, "__module__", None) if not isinstance(owner, type) or not isinstance(owned, str) or not (owned == module or owned.startswith(module + ".")): raise ValueError(f"{name} is not an operator defined by {module}") + if "UNDO" in getattr(owner, "bl_options", ()) and not row["changesScene"]: + raise ValueError(f"{name} pushes undo itself (bl_options UNDO) but the row says changesScene is false") properties = {p.identifier: p for p in operator.get_rna_type().properties} kinds = {"string": "STRING", "number": "FLOAT", "integer": "INT", "boolean": "BOOLEAN"} for field in row["fields"]: @@ -723,8 +725,8 @@ class BrokkrBlenderTarget: result = row.get("result") if result is not None: prop = bpy.types.WindowManager.bl_rna.properties.get(result) - if prop is None or prop.type != "STRING": - raise ValueError(f"{name} result {result} is not a string property of WindowManager") + if prop is None or prop.type != "STRING" or prop.is_readonly: + raise ValueError(f"{name} result {result} is not a writable string property of WindowManager") def run_intent(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: """The one agent turn: admit, run with operator undo off, push one labelled undo step, receipt. @@ -827,21 +829,32 @@ class BrokkrBlenderTarget: kwargs = {k: v for k, v in command.items() if k not in skip} result = row.get("result") manager = bpy.context.window_manager - if result: - setattr(manager, result, "") first, second = name.split(".") operator = getattr(getattr(bpy.ops, first), second) windows = manager.windows + override = bpy.context.temp_override(window=windows[0]) if windows else contextlib.nullcontext() + # Everything that can refuse before the operator runs does so here, as ActionRefused: no undo step is pushed. try: - if windows: - with bpy.context.temp_override(window=windows[0]): - outcome = operator("EXEC_DEFAULT", False, **kwargs) - else: + with override: + runnable = operator.poll() + except Exception as error: + raise sa.ActionRefused(f"Operator {name} cannot run here: {_first_line(str(error))}") from None + if not runnable: + raise sa.ActionRefused(f"Operator {name} cannot run in this context (its poll failed); nothing changed.") + if result: + try: + setattr(manager, result, "") + except Exception as error: + raise sa.ActionRefused(f"Operator {name} result {result} cannot be cleared: {_first_line(str(error))}") from None + try: + with override: outcome = operator("EXEC_DEFAULT", False, **kwargs) except TypeError as error: raise sa.ActionRefused(f"Operator {name} refused its arguments: {_first_line(str(error))}") from None except RuntimeError as error: - raise RuntimeError(_first_line(str(error))) from None + lines = [line for line in str(error).splitlines() if line.strip()] + cause = lines[-1] if lines and "Traceback" in lines[0] else (lines[0] if lines else "failed") # a traceback's cause is its last line + raise RuntimeError(cause.strip()) from None text = "" if result: text = getattr(manager, result, "") or "" diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index cbb17fe..9ef449e 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -260,13 +260,26 @@ it never equals a built-in name). Fields are scalar only: `string` (with `enum`, 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, at every intent and snapshot (a changed file is re-read; a -disabled add-on's actions are unknown at its next intent). Beyond the file's own shape it checks that each -named operator exists and is a Python class defined by that add-on's module, that 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), that the operator's RNA hard limits contain the row's bounds, and that `result` names a -`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. +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 diff --git a/surfaces/blender/tests/live/host_action.py b/surfaces/blender/tests/live/host_action.py index 898137a..930a51a 100644 --- a/surfaces/blender/tests/live/host_action.py +++ b/surfaces/blender/tests/live/host_action.py @@ -17,7 +17,10 @@ brokkr-ctl does and answered by the add-on's own 1 s drain (the sink is on). Pro * report is accepted with hostResult equal to what the operator wrote, no new step, humanEditSeq unchanged; * refuse is failed with the operator's text and cancel is failed, each with no new step; * apply (registered, left out of the file) and wm.save_mainfile are denied Unsupported with no step, the scene - unchanged and no 'Applied' object. + unchanged and no 'Applied' object; + * the file is then rewritten to list apply: apply and the reload operator sent as intents are still denied (no + re-read on an intent), the operator refuses inside an agent turn, and only the human's reload (this driver + calling bpy.ops.brokkr.reload_host_actions outside a turn) admits apply, as one undo step. Writes .result.json, then quits Blender. """ @@ -66,6 +69,7 @@ prefs.debug_mirror_root = "" prefs.auto_drain_commands = True # the sink prefs.cultlib_py_src = os.environ.get("BROKKR_CULTLIB", prefs.cultlib_py_src) adapter = addon.target() +bpy.ops.brokkr.reload_host_actions() # the human's button: the host files are read here def check(name, ok, detail=None): @@ -204,6 +208,42 @@ def denied_check(key, action): return run +def rewrite_listing_apply(): + path = addons_dir / HOST / "brokkr_actions.json" + document = json.loads(path.read_text(encoding="utf-8")) + document["actions"].append({"name": f"{HOST}.apply", "doc": "applies", "changesScene": True, "editModeSafe": False, "fields": []}) + path.write_text(json.dumps(document), encoding="utf-8") + + +def reload_refused_in_a_turn(): + adapter.agent_turn = True + try: + try: + bpy.ops.brokkr.reload_host_actions() + refused = False + except RuntimeError as error: + refused = "human only" in str(error) + finally: + adapter.agent_turn = False + check("the Reload Host Actions operator refuses inside an agent turn", refused) + names_now = [r["name"] for r in adapter.host_actions()[0]] + check("and re-read nothing: the edited file's apply row is still not admitted", f"{HOST}.apply" not in names_now, names_now) + + +def human_reload_check(): + bpy.ops.brokkr.reload_host_actions() + names_now = [r["name"] for r in adapter.host_actions()[0]] + check("the human's reload admits the edited file's apply row", f"{HOST}.apply" in names_now, names_now) + + +def applied_check(): + r = receipt(S["apply2"]) + after = steps_now() + before = S["apply2:before"] + check("apply is accepted after the human's reload as one labelled undo step", + r["status"] == "accepted" and len(after) == len(before["steps"]) + 1 and after[-1] == r["undoLabel"] and "Applied" in bpy.data.objects, r) + + steps = [ once(snapshot_check), once(lambda: send("add", action=f"{HOST}.add_empty", name="LiveEmpty", size=2)), until(done("add")), once(add_check), @@ -212,6 +252,11 @@ steps = [ once(lambda: send("cancel", action=f"{HOST}.cancel")), until(done("cancel")), once(failure_check("cancel", "cancelled; nothing changed")), once(lambda: send("apply", action=f"{HOST}.apply")), until(done("apply")), once(denied_check("apply", f"{HOST}.apply")), once(lambda: send("save", action="wm.save_mainfile")), until(done("save")), once(denied_check("save", "wm.save_mainfile")), + once(rewrite_listing_apply), + once(lambda: send("apply1", action=f"{HOST}.apply")), until(done("apply1")), once(denied_check("apply1", f"{HOST}.apply after the file was edited")), + once(lambda: send("reload", action="brokkr.reload_host_actions")), until(done("reload")), once(denied_check("reload", "brokkr.reload_host_actions")), + once(reload_refused_in_a_turn), once(human_reload_check), + once(lambda: send("apply2", action=f"{HOST}.apply")), until(done("apply2")), once(applied_check), ] i = 0 diff --git a/surfaces/blender/tests/live/host_action.result.json b/surfaces/blender/tests/live/host_action.result.json index a493c29..5ef9544 100644 --- a/surfaces/blender/tests/live/host_action.result.json +++ b/surfaces/blender/tests/live/host_action.result.json @@ -37,7 +37,7 @@ "undoLabel": "Brokkr nibu/hands: brokkr_host_fixture.add_empty ost-0001", "lookPath": "", "hostResult": "", - "observedAt": "2026-11-28T05:15:08.910684+00:00" + "observedAt": "2026-11-28T06:03:04.276267+00:00" } }, { @@ -126,7 +126,7 @@ "undoLabel": "", "lookPath": "", "hostResult": "", - "observedAt": "2026-11-28T05:15:13.022948+00:00" + "observedAt": "2026-11-28T06:03:08.396168+00:00" } }, { @@ -149,7 +149,7 @@ "undoLabel": "", "lookPath": "", "hostResult": "", - "observedAt": "2026-11-28T05:15:14.080400+00:00" + "observedAt": "2026-11-28T06:03:10.456189+00:00" } }, { @@ -172,7 +172,7 @@ "undoLabel": "", "lookPath": "", "hostResult": "", - "observedAt": "2026-11-28T05:15:16.137129+00:00" + "observedAt": "2026-11-28T06:03:12.513224+00:00" } }, { @@ -200,7 +200,7 @@ "undoLabel": "", "lookPath": "", "hostResult": "", - "observedAt": "2026-11-28T05:15:18.194603+00:00" + "observedAt": "2026-11-28T06:03:14.572017+00:00" } }, { @@ -212,6 +212,106 @@ "Light", "LiveEmpty" ] + }, + { + "name": "brokkr_host_fixture.apply after the file was edited is denied Unsupported", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0007", + "action": "brokkr_host_fixture.apply", + "status": "denied", + "message": "Unsupported Blender command action: brokkr_host_fixture.apply", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T06:03:16.631534+00:00" + } + }, + { + "name": "brokkr_host_fixture.apply after the file was edited ran nothing: no step, no new object, no 'Applied'", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light", + "LiveEmpty" + ] + }, + { + "name": "brokkr.reload_host_actions is denied Unsupported", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0008", + "action": "brokkr.reload_host_actions", + "status": "denied", + "message": "Unsupported Blender command action: brokkr.reload_host_actions", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T06:03:18.693145+00:00" + } + }, + { + "name": "brokkr.reload_host_actions ran nothing: no step, no new object, no 'Applied'", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light", + "LiveEmpty" + ] + }, + { + "name": "the Reload Host Actions operator refuses inside an agent turn", + "ok": true, + "detail": null + }, + { + "name": "and re-read nothing: the edited file's apply row is still not admitted", + "ok": true, + "detail": [ + "brokkr_host_fixture.add_empty", + "brokkr_host_fixture.report", + "brokkr_host_fixture.refuse", + "brokkr_host_fixture.cancel" + ] + }, + { + "name": "the human's reload admits the edited file's apply row", + "ok": true, + "detail": [ + "brokkr_host_fixture.add_empty", + "brokkr_host_fixture.report", + "brokkr_host_fixture.refuse", + "brokkr_host_fixture.cancel", + "brokkr_host_fixture.apply" + ] + }, + { + "name": "apply is accepted after the human's reload as one labelled undo step", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0009", + "action": "brokkr_host_fixture.apply", + "status": "accepted", + "message": "Operator brokkr_host_fixture.apply finished.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: brokkr_host_fixture.apply ost-0009", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T06:03:21.755767+00:00" + } } ], "ok": true diff --git a/surfaces/blender/tests/test_action_table.py b/surfaces/blender/tests/test_action_table.py index f3a5f6e..af2938b 100644 --- a/surfaces/blender/tests/test_action_table.py +++ b/surfaces/blender/tests/test_action_table.py @@ -79,6 +79,13 @@ class HostTableTests(unittest.TestCase): ): with self.assertRaises(at.TableInvalid, msg=why): at.check_host(bad, self.charsets()) + for key in ("note", "action", "commandId", "requestedBy", "schema"): # Brokkr writes these: the operator would never receive the agent's value + with self.assertRaises(at.TableInvalid, msg=key): + at.check_host(self.host_file(fields=[{"name": key, "type": "string"}]), self.charsets()) + with self.assertRaises(at.TableInvalid): + at.check_host(self.host_file(unknown=1), self.charsets()) + with self.assertRaises(at.TableInvalid): + at.check_host(self.host_file(fields=[{"name": "a", "type": "string"}, {"name": "b", "type": "string", "only": {"field": "a", "in": ["x"]}}]), self.charsets()) twice = copy.deepcopy(HOST_FILE) twice["actions"].append(copy.deepcopy(twice["actions"][0])) with self.assertRaises(at.TableInvalid): diff --git a/surfaces/blender/tests/test_addon_ui.py b/surfaces/blender/tests/test_addon_ui.py index 74c8a24..2240371 100644 --- a/surfaces/blender/tests/test_addon_ui.py +++ b/surfaces/blender/tests/test_addon_ui.py @@ -113,6 +113,37 @@ class CopyOperatorTests(unittest.TestCase): self.assertIn(addon.BROKKR_OT_copy_session_token, addon.classes) +class ReloadHostActionsTests(unittest.TestCase): + """The panel's Reload Host Actions button is the human's: it reads the files; it refuses inside an agent turn.""" + + def press(self, target): + operator = addon.BROKKR_OT_reload_host_actions() + operator.reported = None + with mock.patch.object(addon, "_target", target): + return operator.execute(None), operator.reported + + def test_pressed_it_reloads_and_reports_the_counts(self): + target = bt.BrokkrBlenderTarget(NS()) + target.reload_host_actions = mock.Mock(return_value=2) + target.host_actions = mock.Mock(return_value=([{"name": "a.b"}], [])) + result, reported = self.press(target) + self.assertEqual(result, {"FINISHED"}) + target.reload_host_actions.assert_called_once_with() + self.assertIn("2 host file(s) read; 1 host action(s) admitted", reported[1]) + + def test_inside_an_agent_turn_it_refuses_and_reads_nothing(self): + target = bt.BrokkrBlenderTarget(NS()) + target.agent_turn = True + target._host_docs = {"kept": {}} + result, reported = self.press(target) + self.assertEqual((result, reported[0]), ({"CANCELLED"}, {"ERROR"})) + self.assertEqual(target._host_docs, {"kept": {}}) + + def test_it_is_registered_and_drawn_in_the_panel(self): + self.assertIn(addon.BROKKR_OT_reload_host_actions, addon.classes) + self.assertIn("brokkr.reload_host_actions", (ADDON / "__init__.py").read_text(encoding="utf-8")) + + class PanelTests(unittest.TestCase): def test_the_panel_never_draws_the_token(self): target = running_target() diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index 8b8174b..17b80e3 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -1,6 +1,7 @@ """run_intent: admission, one labelled undo step, receipts. A fake bpy records ops calls.""" from __future__ import annotations +import json import re import sys import tempfile @@ -252,6 +253,10 @@ class HostOp: self.props = props self.behave = behave self.calls = [] + self.pollable = True + + def poll(self): + return self.pollable def idname(self): return self.cls.__name__ @@ -266,7 +271,7 @@ class HostOp: def prop(identifier, kind, lo=0.0, hi=1e30, enum=()): - return NS(identifier=identifier, type=kind, hard_min=lo, hard_max=hi, enum_items=[NS(identifier=e) for e in enum]) + return NS(identifier=identifier, type=kind, hard_min=lo, hard_max=hi, enum_items=[NS(identifier=e) for e in enum], is_readonly=False) def raising(error): @@ -295,11 +300,12 @@ class HostActionTests(unittest.TestCase): "apply": HostOp("apply", [], self.finish), } bpy.ops.brokkr_host_fixture = NS(**self.ops) - bpy.types = NS(WindowManager=NS(bl_rna=NS(properties={"brokkr_host_fixture_result": NS(type="STRING")})), + bpy.types = NS(WindowManager=NS(bl_rna=NS(properties={"brokkr_host_fixture_result": NS(type="STRING", is_readonly=False)})), **{op.idname(): op.cls for op in self.ops.values()}) bpy.context.preferences.addons = {HOST: object(), "brokkr_bridge": object()} bpy.context.window_manager.brokkr_host_fixture_result = "stale" self.report_text = "objects: 3" + self.target.reload_host_actions() # the human's act: the files are read here and nowhere else def finish(self, op, kwargs): return {"FINISHED"} @@ -373,7 +379,7 @@ class HostActionTests(unittest.TestCase): self.assertEqual(self.bpy.undo.pushes, []) self.ops["add_empty"].behave = raising(RuntimeError("Traceback...\nboom")) receipt = self.send("add_empty", name="E") - self.assertEqual((receipt["status"], receipt["message"]), ("failed", "Traceback...")) + self.assertEqual((receipt["status"], receipt["message"]), ("failed", "boom")) self.assertEqual(len(self.bpy.undo.pushes), 1) self.assertTrue(self.bpy.undo.pushes[0].endswith("(failed)")) @@ -430,20 +436,65 @@ class HostActionTests(unittest.TestCase): def test_a_result_that_is_not_a_window_manager_string_refuses_the_whole_file(self): self.bpy.types.WindowManager.bl_rna.properties["brokkr_host_fixture_result"] = NS(type="INT") - self.assertIn("not a string property", self.refused()) + self.assertIn("not a writable string property", self.refused()) self.bpy.types.WindowManager.bl_rna.properties.clear() self.refused() - def test_a_malformed_file_refuses_itself_and_a_changed_file_is_read_again(self): + def test_a_malformed_file_refuses_itself_and_a_reload_reads_the_changed_file(self): path = self.dir / "brokkr_actions.json" good = path.read_text(encoding="utf-8") path.write_text(good.replace("host_actions.v0", "host_actions.v9"), encoding="utf-8") + self.target.reload_host_actions() self.assertIn("schema", self.refused()) path.write_text(good, encoding="utf-8") + self.target.reload_host_actions() self.assertEqual(len(self.target.host_actions()[0]), 4) path.write_text("not json", encoding="utf-8") + self.target.reload_host_actions() self.refused() + def listing_apply(self): + path = self.dir / "brokkr_actions.json" + document = json.loads(path.read_text(encoding="utf-8")) + document["actions"].append({"name": f"{HOST}.apply", "doc": "applies", "changesScene": True, "editModeSafe": False, "fields": []}) + path.write_text(json.dumps(document), encoding="utf-8") + + def test_an_edited_file_admits_nothing_until_a_human_reload(self): + self.assertEqual(self.send("apply")["status"], "denied") + self.listing_apply() + for _ in range(3): # the file changed; intents and snapshots come and go + receipt = self.send("apply") + self.assertEqual(receipt["status"], "denied", receipt) + self.assertIn("Unsupported Blender command action", receipt["message"]) + self.assertNotIn(f"{HOST}.apply", [r["name"] for r in self.target.host_actions()[0]]) + self.assertEqual(self.ops["apply"].calls, []) + self.assertEqual(self.bpy.undo.pushes, []) + self.target.reload_host_actions() # she presses the button + self.assertEqual(self.send("apply")["status"], "accepted") + self.assertEqual(len(self.ops["apply"].calls), 1) + + def test_a_reload_inside_an_agent_turn_is_refused_whatever_asks_for_it(self): + self.target.agent_turn = True + try: + with self.assertRaises(PermissionError): + self.target.reload_host_actions() + finally: + self.target.agent_turn = False + self.assertEqual(self.send("reload_host_actions")["status"], "denied") # not an action at all + self.assertEqual(self.run_action(action="brokkr.reload_host_actions")["status"], "denied") + self.listing_apply() + self.ops["add_empty"].behave = lambda op, kw: self.target.reload_host_actions() # a host operator that tries + receipt = self.send("add_empty", name="E") + self.assertEqual(receipt["status"], "failed") + self.assertIn("human only", receipt["message"]) + self.assertEqual(self.send("apply")["status"], "denied") # the attempt re-read nothing + + def test_a_reload_drops_what_the_files_no_longer_say(self): + (self.dir / "brokkr_actions.json").unlink() + self.assertEqual(len(self.target.host_actions()[0]), 4) # until she reloads + self.assertEqual(self.target.reload_host_actions(), 0) + self.assertEqual(self.target.host_actions(), ([], [])) + def test_disabling_the_add_on_makes_its_action_unsupported_at_the_next_intent(self): self.assertEqual(self.send("report")["status"], "accepted") self.bpy.context.preferences.addons.pop(HOST) @@ -454,14 +505,87 @@ class HostActionTests(unittest.TestCase): def test_an_add_on_without_the_file_is_not_a_host_and_this_add_on_is_never_read(self): (self.dir / "brokkr_actions.json").unlink() + self.target.reload_host_actions() self.assertEqual(self.target.host_actions(), ([], [])) self.bpy.context.preferences.addons["brokkr_bridge"] = object() + self.target.reload_host_actions() self.assertEqual(self.target.host_actions(), ([], [])) (self.dir / "brokkr_actions.json").write_bytes((FIXTURE / "brokkr_actions.json").read_bytes()) with unittest.mock.patch.object(sys.modules["brokkr_bridge"], "__file__", str(self.dir / "__init__.py"), create=True): self.bpy.context.preferences.addons.pop(HOST) # a file sits beside this add-on itself: still not read as a host's + self.assertEqual(self.target.reload_host_actions(), 0) self.assertEqual(self.target.host_actions(), ([], [])) + def test_a_sibling_add_on_whose_name_starts_with_the_hosts_is_not_the_host(self): + # aetheria_ships' operator is not aetheria's: the ownership guard is module equality or module + '.', never a bare prefix + self.ops["report"].cls.__module__ = HOST + "_ships" + self.assertIn("not an operator defined by", self.refused()) + self.ops["report"].cls.__module__ = HOST + "x.sub" + self.refused() + self.ops["report"].cls.__module__ = HOST + self.assertEqual(len(self.target.host_actions()[0]), 4) + + def rewrite_row(self, **changes): + path = self.dir / "brokkr_actions.json" + document = json.loads(path.read_text(encoding="utf-8")) + document["actions"][0].update(changes) + path.write_text(json.dumps(document), encoding="utf-8") + self.target.reload_host_actions() + + def test_a_file_with_an_unknown_row_key_or_an_only_is_refused_whole(self): + self.rewrite_row(unknown=1) + self.assertIn("no key", self.refused()) + self.rewrite_row(unknown=None) # restore: a null is still a key + path = self.dir / "brokkr_actions.json" + path.write_bytes((FIXTURE / "brokkr_actions.json").read_bytes()) + self.rewrite_row(fields=[{"name": "name", "type": "string"}, {"name": "size", "type": "number", "minimum": 0.1, "maximum": 10, + "only": {"field": "name", "in": ["a"]}}]) + self.assertIn("no 'only'", self.refused()) + + def test_an_enum_field_must_list_the_operators_identifiers(self): + field = {"name": "kind", "type": "string", "enum": ["A", "B"]} + self.ops["add_empty"].props = [prop("name", "STRING"), prop("size", "FLOAT", 0.0, 100.0), prop("kind", "ENUM", enum=("A", "B"))] + self.rewrite_row(fields=[{"name": "name", "type": "string"}, field]) + self.assertEqual(len(self.target.host_actions()[0]), 4) + self.ops["add_empty"].props = [prop("name", "STRING"), prop("kind", "ENUM", enum=("A", "C"))] + self.assertIn("enum differs", self.refused()) + + def test_a_refused_file_is_reported_in_the_snapshot(self): + self.ops["report"].cls.__module__ = "other_addon" + self.bpy.data = NS(objects=[], scenes=[], collections=[], materials=[], images=[], filepath="") + self.bpy.app = NS(version=(5, 3, 0), background=False) + snapshot = self.target.capture_snapshot(NS(selected_objects=[], active_object=None, scene=None, mode="OBJECT"), True) + self.assertEqual(snapshot["hostActions"], []) + self.assertEqual([e["host"] for e in snapshot["hostActionErrors"]], [HOST]) + self.assertIn("not an operator defined by", snapshot["hostActionErrors"][0]["error"]) + + def test_a_poll_that_fails_refuses_before_the_operator_and_before_any_undo_step(self): + self.ops["add_empty"].pollable = False + receipt = self.send("add_empty", name="E") + self.assertEqual(receipt["status"], "failed") + self.assertIn("poll failed", receipt["message"]) + self.assertEqual((self.ops["add_empty"].calls, self.bpy.undo.pushes), ([], [])) + + def test_a_poll_that_raises_refuses_too(self): + self.ops["add_empty"].poll = raising(RuntimeError("Operator bpy.ops.x.poll() failed, context is incorrect")) + receipt = self.send("add_empty", name="E") + self.assertEqual((receipt["status"], self.ops["add_empty"].calls, self.bpy.undo.pushes), ("failed", [], [])) + + def test_a_read_only_result_property_refuses_the_whole_file_at_load(self): + self.bpy.types.WindowManager.bl_rna.properties["brokkr_host_fixture_result"].is_readonly = True + self.assertIn("writable string property", self.refused()) + + def test_an_operator_that_pushes_undo_itself_may_not_be_a_row_that_changes_nothing(self): + self.ops["report"].cls.bl_options = {"REGISTER", "UNDO"} # report says changesScene false + self.assertIn("bl_options UNDO", self.refused()) + self.ops["report"].cls.bl_options = {"REGISTER"} + self.ops["add_empty"].cls.bl_options = {"REGISTER", "UNDO"} # a changing row may + self.assertEqual(len(self.target.host_actions()[0]), 4) + + def test_a_runtime_error_names_its_cause_not_the_traceback_header(self): + self.ops["add_empty"].behave = raising(RuntimeError("Error: Python: Traceback (most recent call last):" + chr(10) + " File x.py, line 1" + chr(10) + "ValueError: boom")) + self.assertEqual(self.send("add_empty", name="E")["message"], "ValueError: boom") + class FakeNode: """The node database drain_commands reads: intents, receipts, and what it puts and deletes.""" From 6667f523aa551cbc5673c2bd8c1c173ae09d00c1 Mon Sep 17 00:00:00 2001 From: Eureka Date: Sat, 28 Nov 2026 06:25:32 +0000 Subject: [PATCH 47/63] Blender add-on: glTF export error paths survive kills and concurrent sweeps (#21) --- .../blender/brokkr_bridge/blender_target.py | 98 ++++++++++++++----- surfaces/blender/tests/test_scene_actions.py | 90 ++++++++++++++++- 2 files changed, 160 insertions(+), 28 deletions(-) diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index e030c89..db3a939 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -13,6 +13,7 @@ import struct import subprocess import sys import tempfile +import time import uuid import zlib from array import array @@ -59,7 +60,8 @@ SYNC_RECEIPT_SCHEMA = "brokkr.sync.receipt.v0" GL_RENDER_ENGINES = ("BLENDER_WORKBENCH", "BLENDER_EEVEE", "BLENDER_EEVEE_NEXT") GL_PROBE_TIMEOUT_SECONDS = 120 EXPORT_STAGE_PREFIX = ".brokkr-export-" -STAGE_LOCK = ".brokkr-lock" +LEGACY_STAGE_LOCK = ".brokkr-lock" # older layout: the lock file inside the stage folder +STAGE_LOCK_SUFFIX = ".lock" # the lock file sits beside its stage folder: .lock STAGE_JOURNAL = ".brokkr-journal" LOOK_DIR = "look" # under the output directory: scratch captures named by command id (brush-tree:ruling:look-files-are-scratch) @@ -1062,7 +1064,7 @@ class BrokkrBlenderTarget: raise sa.ActionRefused(f"glTF export did not finish: {sorted(result)}") if not staged.is_file(): raise sa.ActionRefused("glTF export wrote no file.") - written = sorted(f.relative_to(stage) for f in stage.rglob("*") if f.is_file() and f != stage / STAGE_LOCK) + written = sorted(f.relative_to(stage) for f in stage.rglob("*") if f.is_file()) taken = [str(f) for f in written if os.path.lexists(path.parent / f)] if taken: raise sa.ActionRefused("output path already exists; output actions never overwrite: " + taken[0]) @@ -1083,19 +1085,21 @@ class BrokkrBlenderTarget: os.rename(target, source) except OSError: stuck.append(target) - if lock_fd is not None: - os.close(lock_fd) if stage is not None and stuck: # The rollback itself failed: keep the stage with a journal of the files left in the - # target. Its lock is released, so the next export's sweep removes them and the retry works. - (stage / STAGE_JOURNAL).write_text( - "\n".join(t.relative_to(path.parent).as_posix() for t in stuck), encoding="utf-8") + # target. The journal is written while the lock is held, so no sweep can take the stage + # first; once the lock is released the next export's sweep removes them and the retry works. + try: + (stage / STAGE_JOURNAL).write_text( + "\n".join(t.relative_to(path.parent).as_posix() for t in stuck), encoding="utf-8") + finally: + os.close(lock_fd) raise sa.ActionRefused( "glTF export failed and could not be rolled back; files left in the output directory: " + ", ".join(t.relative_to(Path(self.output_dir).resolve()).as_posix() for t in stuck) + ". The next export removes them.") from failure if stage is not None: - shutil.rmtree(stage, ignore_errors=True) + _close_stage(stage, lock_fd) for folder in sorted(set(new_dirs), key=lambda f: -len(f.parts)): try: folder.rmdir() @@ -1107,8 +1111,7 @@ class BrokkrBlenderTarget: except OSError: pass raise - os.close(lock_fd) - shutil.rmtree(stage, ignore_errors=True) + _close_stage(stage, lock_fd) return self._receipt(command, "accepted", f"Exported glTF to {path} ({path.stat().st_size} bytes).", "") def _resolve_typed(self, command: dict[str, Any], object_type: str) -> Any: @@ -1704,34 +1707,78 @@ def _try_lock(fd: int) -> bool: return True +def _stage_lock_path(stage: Path) -> Path: + return stage.with_name(stage.name + STAGE_LOCK_SUFFIX) + + def _open_stage(parent: Path) -> tuple[Path, int]: - """A fresh staging folder in parent whose lock file this export holds, locked, until it closes the - descriptor or dies: a held lock is how a sweep knows the stage is live.""" - stage = Path(tempfile.mkdtemp(prefix=EXPORT_STAGE_PREFIX, dir=parent)) - fd = os.open(stage / STAGE_LOCK, os.O_RDWR | os.O_CREAT) - if not _try_lock(fd): + """A fresh staging folder in parent, guarded by a lock file beside it that this export holds until it + closes the descriptor or dies. The lock file is created and locked first and the folder second, so + every stage on disk is either locked-live or sweepable: a kill at any step leaves a lock file a sweep + can take, never a folder no sweep can see.""" + while True: + stage = parent / (EXPORT_STAGE_PREFIX + uuid.uuid4().hex[:16]) + try: + fd = os.open(_stage_lock_path(stage), os.O_RDWR | os.O_CREAT | os.O_EXCL) + except FileExistsError: + continue + break + try: + for attempt in range(5): # a sweep may hold a fresh lock file for an instant + if _try_lock(fd): + break + time.sleep(0.02 * (attempt + 1)) + else: + raise OSError(f"could not lock staging folder {stage}") + stage.mkdir() + except BaseException: os.close(fd) - raise OSError(f"could not lock staging folder {stage}") + _unlink_quietly(_stage_lock_path(stage)) + raise return stage, fd +def _close_stage(stage: Path, fd: int) -> None: + """End a finished stage: remove the folder while the lock is held, then the lock file.""" + shutil.rmtree(stage, ignore_errors=True) + os.close(fd) + _unlink_quietly(_stage_lock_path(stage)) + + +def _unlink_quietly(path: Path) -> None: + """Remove a lock file; where the OS refuses (Windows, a sweeper holds it) the next sweep removes it.""" + try: + path.unlink(missing_ok=True) + except OSError: + pass + + def _sweep_stale_stages(top: Path) -> None: """Remove every staging folder under top whose lock can be taken: its export is over or its Blender - died. A held lock (an export running now, in any process) leaves the folder alone, and so does a - folder with no lock file yet (an export between creating it and locking it).""" - for root, dirs, _ in os.walk(top): + died. A held lock (an export running now, in any process) leaves the stage alone. A lock file with + no folder is a stage killed before its folder existed. A folder with no sibling lock file is the + older layout, locked by a file inside it, or never locked at all.""" + for root, dirs, files in os.walk(top): for name in [d for d in dirs if d.startswith(EXPORT_STAGE_PREFIX)]: dirs.remove(name) - _sweep_stage(Path(root) / name) + stage = Path(root) / name + if not _stage_lock_path(stage).exists(): + _sweep_stage(stage, stage / LEGACY_STAGE_LOCK) + for name in files: + if name.startswith(EXPORT_STAGE_PREFIX) and name.endswith(STAGE_LOCK_SUFFIX): + stage = Path(root) / name[:-len(STAGE_LOCK_SUFFIX)] + _sweep_stage(stage, Path(root) / name) -def _sweep_stage(stage: Path) -> None: +def _sweep_stage(stage: Path, lock_path: Path) -> None: try: - fd = os.open(stage / STAGE_LOCK, os.O_RDWR) + fd = os.open(lock_path, os.O_RDWR) + except FileNotFoundError: + fd = None # no lock was ever made for this folder: nothing can hold it except OSError: return try: - if not _try_lock(fd): + if fd is not None and not _try_lock(fd): return journal = stage / STAGE_JOURNAL if journal.is_file(): # a failed rollback's leftovers in the target @@ -1750,8 +1797,11 @@ def _sweep_stage(stage: Path) -> None: except OSError: break finally: - os.close(fd) + if fd is not None: + os.close(fd) shutil.rmtree(stage, ignore_errors=True) + if lock_path.parent != stage: + _unlink_quietly(lock_path) def _kill_tree(process: "subprocess.Popen[str]") -> None: diff --git a/surfaces/blender/tests/test_scene_actions.py b/surfaces/blender/tests/test_scene_actions.py index 0281ba3..ef3ae3b 100644 --- a/surfaces/blender/tests/test_scene_actions.py +++ b/surfaces/blender/tests/test_scene_actions.py @@ -435,11 +435,93 @@ class ActionTests(unittest.TestCase): bt._sweep_stale_stages(self.root / "out") self.assertFalse(stage.exists()) - def test_a_sweep_leaves_a_folder_whose_lock_is_not_made_yet(self): - early = self.root / "out" / ".brokkr-export-early" - early.mkdir() + def test_a_stage_killed_at_each_step_is_swept_by_the_next_export(self): + out = self.root / "out" + lock_only = out / ".brokkr-export-1.lock" # killed after taking the lock, before making the folder + lock_only.write_bytes(b"") + empty = out / ".brokkr-export-2" # killed after making the folder, before staging anything + empty.mkdir() + (out / ".brokkr-export-2.lock").write_bytes(b"") + mid = out / ".brokkr-export-3" # killed mid-export with files staged + mid.mkdir() + (mid / "a.glb").write_bytes(b"half") + (out / ".brokkr-export-3.lock").write_bytes(b"") + self.assertEqual(self.run_action(action="exportGltf", filepath="b.glb")["status"], "accepted") + self.assertEqual([p.name for p in out.iterdir()], ["b.glb"]) + + def test_a_stage_made_the_old_way_is_swept_with_its_journal_so_the_export_can_retry(self): + out = self.root / "out" + out.mkdir(exist_ok=True) + (out / "a.glb").write_bytes(b"left by a failed rollback") + old = out / ".brokkr-export-old" + old.mkdir() + (old / ".brokkr-lock").write_bytes(b"") + (old / ".brokkr-journal").write_text("a.glb", encoding="utf-8") + unlocked = out / ".brokkr-export-nolock" + unlocked.mkdir() + self.assertEqual(self.run_action(action="exportGltf", filepath="a.glb")["status"], "accepted") + self.assertEqual([p.name for p in out.iterdir()], ["a.glb"]) + self.assertNotEqual((out / "a.glb").read_bytes(), b"left by a failed rollback") + + def test_a_stage_whose_lock_a_sweep_briefly_holds_is_locked_after_a_short_wait(self): + calls = [] + real = bt._try_lock + + def busy_twice(fd): + calls.append(fd) + return len(calls) > 2 and real(fd) + + with mock.patch.object(bt, "_try_lock", busy_twice): + stage, fd = bt._open_stage(self.root / "out") + os.close(fd) + self.assertEqual(len(calls), 3) + + def test_a_lock_file_the_os_will_not_unlink_is_left_for_the_next_sweep(self): + stage, fd = bt._open_stage(self.root / "out") + with mock.patch.object(Path, "unlink", side_effect=PermissionError("held")): + bt._close_stage(stage, fd) # no error + self.assertTrue(bt._stage_lock_path(stage).exists()) bt._sweep_stale_stages(self.root / "out") - self.assertTrue(early.exists()) + self.assertEqual(list((self.root / "out").iterdir()), []) + + def test_every_stage_is_locked_before_its_folder_exists(self): + real_mkdir = Path.mkdir + seen = [] + + def watch(path, *args, **kw): + if path.name.startswith(bt.EXPORT_STAGE_PREFIX): + seen.append(bt._stage_lock_path(path).exists()) + return real_mkdir(path, *args, **kw) + + with mock.patch.object(Path, "mkdir", watch): + stage, fd = bt._open_stage(self.root / "out") + os.close(fd) + self.assertEqual(seen, [True]) + + def test_a_concurrent_sweep_during_a_failed_move_never_loses_the_journal(self): + self.bpy.export_siblings = ["tex1.png"] + real_rename = os.rename + real_write = Path.write_text + calls = [] + + def fail_forever_from_third(src, dst): + calls.append(dst) + if len(calls) >= 3: + raise OSError("disk gone") + return real_rename(src, dst) + + def sweep_then_write(path, *args, **kw): + if path.name == bt.STAGE_JOURNAL: + bt._sweep_stale_stages(self.root / "out") # another export's sweep, mid-failure + self.assertTrue(path.parent.is_dir()) + return real_write(path, *args, **kw) + + with mock.patch.object(bt.os, "rename", fail_forever_from_third), mock.patch.object(Path, "write_text", sweep_then_write): + receipt = self.run_action(action="exportGltf", filepath="sub/a.gltf") + self.assertIn("could not be rolled back", receipt["message"]) + journals = list((self.root / "out").glob("**/" + bt.STAGE_JOURNAL)) + self.assertEqual(len(journals), 1) + self.assertIn("a.bin", journals[0].read_text(encoding="utf-8")) def test_a_failed_rollback_is_refused_loudly_naming_the_files_and_the_next_export_recovers(self): self.bpy.export_siblings = ["tex1.png"] From 72258d9288475e15072bd4cd25622006d4ea6c9e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 01:08:04 +0100 Subject: [PATCH 48/63] Blender tools: run an intent recipe in a background Blender; write a turntable recipe run_intents.py sends a JSON list of intents through BrokkrBlenderTarget.run_intent in a background Blender (the action table admits or denies each, host rows included) and writes the receipts to a file. It refuses to start without private Blender user directories. turntable_recipe.py writes such a recipe from Brokkr's own scene actions, so a before and an after of one subject are framed identically. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tools/run_intents.py | 106 +++++++++++++++++++++ surfaces/blender/tools/turntable_recipe.py | 75 +++++++++++++++ 2 files changed, 181 insertions(+) create mode 100644 surfaces/blender/tools/run_intents.py create mode 100644 surfaces/blender/tools/turntable_recipe.py diff --git a/surfaces/blender/tools/run_intents.py b/surfaces/blender/tools/run_intents.py new file mode 100644 index 0000000..9c06c01 --- /dev/null +++ b/surfaces/blender/tools/run_intents.py @@ -0,0 +1,106 @@ +"""Run a list of Brokkr intents in a background Blender, through the add-on's own agent turn. + + blender --background --factory-startup --python surfaces/blender/tools/run_intents.py -- [] + +For batch work on files (polishing a generated mesh, rendering a turntable) where no person has a Blender open. +Every intent goes through BrokkrBlenderTarget.run_intent: the action table admits or denies it, host add-on +rows are checked as in a live session, and each gets a receipt. No CultMesh node is opened: the receipts are +written to (default: the recipe's name with .receipts.json) and nowhere else, so nothing here +shows in a person's Agents panel. This script is the human of its own Blender: it enables the host add-ons the +recipe names, reloads host actions once, and opens and saves the .blend. It refuses to start unless +BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS are set, so it never reads or writes a +person's own Blender folders (docs/install.md). + +The recipe: + + {"requestedBy": "/", + "importDir": "", "outputDir": "", + "hostAddons": ["brokkr_mesh_polish"], optional; modules found beside brokkr_bridge or in hostAddonDirs + "hostAddonDirs": [""], optional; extra directories holding host add-on packages + "openBlend": "", "saveBlend": "", optional; without openBlend the scene starts empty; saveBlend + is written after the last intent + "keepGoing": false, optional; true runs the rest after a refusal + "intents": [{"action": "importGltf", "filepath": "ship.glb"}, ...]} + +commandId defaults to -; requestedBy to the recipe's. Exit status: 0 when every intent was +accepted, 3 when one was not (the receipts file says which), 2 when the recipe could not be run at all. +""" +import importlib +import json +import os +import sys +import types +from pathlib import Path + +import bpy + + +def fail(message: str) -> None: + print(f"run_intents: {message}", file=sys.stderr, flush=True) + sys.exit(2) + + +def main() -> int: + for name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): + if not os.environ.get(name): + fail(f"{name} is not set: run in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") + arguments = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [] + if not arguments: + fail("usage: blender --background --factory-startup --python run_intents.py -- []") + recipe_path = Path(arguments[0]).resolve() + receipts_path = Path(arguments[1]).resolve() if len(arguments) > 1 else recipe_path.with_suffix(".receipts.json") + try: + recipe = json.loads(recipe_path.read_text(encoding="utf-8")) + except (OSError, ValueError) as error: + fail(f"cannot read {recipe_path}: {error}") + unknown = set(recipe) - {"requestedBy", "importDir", "outputDir", "hostAddons", "hostAddonDirs", "openBlend", + "saveBlend", "keepGoing", "intents"} + if unknown or not isinstance(recipe.get("intents"), list): + fail(f"recipe has unknown keys {sorted(unknown)} or no intents array") + + surface = Path(__file__).resolve().parents[1] + package = types.ModuleType("brokkr_bridge") # the add-on's modules without registering its panel or timers + package.__path__ = [str(surface / "brokkr_bridge")] + sys.modules["brokkr_bridge"] = package + target_module = importlib.import_module("brokkr_bridge.blender_target") + + if recipe.get("openBlend"): + bpy.ops.wm.open_mainfile(filepath=str(Path(recipe["openBlend"]).resolve())) + else: + bpy.ops.wm.read_factory_settings(use_empty=True) # no default cube, camera or light + import addon_utils + for directory in [str(surface)] + [str(Path(d).resolve()) for d in recipe.get("hostAddonDirs", [])]: + if directory not in sys.path: + sys.path.append(directory) + for module in recipe.get("hostAddons", []): + if addon_utils.enable(module, default_set=True) is None: + fail(f"host add-on {module!r} could not be enabled") + + target = target_module.BrokkrBlenderTarget(bpy) + target.configure_action_dirs(recipe.get("importDir", ""), recipe.get("outputDir", "")) + target.reload_host_actions() + _, errors = target.host_actions() + if errors: + fail(f"host actions refused: {errors}") + + receipts, status = [], 0 + for index, intent in enumerate(recipe["intents"]): + command = dict(intent) + command.setdefault("commandId", f"{recipe_path.stem}-{index}") + command.setdefault("requestedBy", recipe.get("requestedBy", "")) + receipt = target.run_intent(bpy.context, command) + receipts.append(receipt) + print("RECEIPT", command["commandId"], command.get("action"), receipt["status"], + str(receipt.get("message", "")).replace("\n", " | ")[:300], flush=True) + if receipt["status"] != "accepted": + status = 3 + if not recipe.get("keepGoing"): + break + receipts_path.write_text(json.dumps(receipts, indent=1, default=str), encoding="utf-8") + if recipe.get("saveBlend") and (status == 0 or recipe.get("keepGoing")): + bpy.ops.wm.save_as_mainfile(filepath=str(Path(recipe["saveBlend"]).resolve())) + return status + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/surfaces/blender/tools/turntable_recipe.py b/surfaces/blender/tools/turntable_recipe.py new file mode 100644 index 0000000..ccb2a59 --- /dev/null +++ b/surfaces/blender/tools/turntable_recipe.py @@ -0,0 +1,75 @@ +"""Write a run_intents recipe that renders a turntable of a .blend with Brokkr's own scene actions. + + python surfaces/blender/tools/turntable_recipe.py --blend ship.blend --output-dir renders --prefix ship_before \ + --radius 0.75 --requested-by nibu/hands > turntable.json + +The subject is assumed centred on the origin (brokkr_mesh_polish.orient leaves it there); --radius is half the +length the frame must hold. Each view is an orthographic still from a camera on a circle at --elevation degrees, +so two recipes with the same numbers frame two files identically: a before and an after can be compared view +by view. --look lit adds a sun over a dim grey world; --look flat lights with a uniform white world alone, which +shows a base colour texture as it is stored, baked shadows included. renderStill never overwrites, so a +recipe runs once per prefix. +""" +from __future__ import annotations + +import argparse +import json +import math +import sys + + +def camera_pose(azimuth_deg: float, elevation_deg: float, distance: float) -> tuple[list[float], list[float]]: + """(location, XYZ Euler radians) of a camera on the circle that looks at the origin with +Z up. Azimuth 0 + looks along +Y from behind the subject's -Y end; it grows counter-clockwise seen from above.""" + azimuth, elevation = math.radians(azimuth_deg), math.radians(elevation_deg) + x = distance * math.cos(elevation) * math.sin(azimuth) + y = -distance * math.cos(elevation) * math.cos(azimuth) + z = distance * math.sin(elevation) + return [x, y, z], [math.pi / 2 - elevation, 0.0, azimuth] + + +def recipe(blend: str, output_dir: str, prefix: str, radius: float, views: int, elevation: float, size: int, + engine: str, look: str, requested_by: str) -> dict: + distance = radius * 6 + intents: list[dict] = [ + {"action": "setWorld", "color": [1, 1, 1] if look == "flat" else [0.5, 0.5, 0.5], "strength": 1.0 if look == "flat" else 0.4}, + {"action": "createObject", "objectType": "CAMERA", "name": "TurntableCamera"}, + {"action": "setCamera", "targetObjectName": "TurntableCamera", "cameraType": "ORTHO", "orthoScale": radius * 2.1, + "clipStart": radius * 0.01, "clipEnd": radius * 20, "active": True}, + ] + if look == "lit": + intents += [ + {"action": "createObject", "objectType": "LIGHT", "lightType": "SUN", "name": "TurntableSun"}, + {"action": "setLight", "targetObjectName": "TurntableSun", "energy": 3.0, "color": [1, 1, 1]}, + {"action": "setObjectTransform", "targetObjectName": "TurntableSun", "rotationEuler": [math.radians(40), 0.0, math.radians(35)]}, + ] + poses = [(360.0 * i / views, elevation) for i in range(views)] + [(0.0, 90.0), (0.0, -90.0)] + names = [f"{round(a):03d}" for a, _ in poses[:views]] + ["top", "bottom"] + for name, (azimuth, tilt) in zip(names, poses): + location, rotation = camera_pose(azimuth, tilt, distance) + intents.append({"action": "setObjectTransform", "targetObjectName": "TurntableCamera", "location": location, "rotationEuler": rotation}) + intents.append({"action": "renderStill", "outputPath": f"{prefix}_{look}_{name}.png", "engine": engine, + "resolutionX": size, "resolutionY": size, "cameraName": "TurntableCamera"}) + return {"requestedBy": requested_by, "outputDir": output_dir, "openBlend": blend, "intents": intents} + + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--blend", required=True) + parser.add_argument("--output-dir", required=True) + parser.add_argument("--prefix", required=True) + parser.add_argument("--radius", type=float, required=True) + parser.add_argument("--views", type=int, default=8) + parser.add_argument("--elevation", type=float, default=25.0) + parser.add_argument("--size", type=int, default=1024) + parser.add_argument("--engine", default="BLENDER_EEVEE") + parser.add_argument("--look", choices=("lit", "flat"), default="lit") + parser.add_argument("--requested-by", required=True) + a = parser.parse_args(argv) + json.dump(recipe(a.blend, a.output_dir, a.prefix, a.radius, a.views, a.elevation, a.size, a.engine, a.look, + a.requested_by), sys.stdout, indent=1) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) From 6eb372525454d3de20ce02dfd7409d73bd110786 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 01:08:04 +0100 Subject: [PATCH 49/63] brokkr_mesh_polish: a host add-on that measures and polishes generated meshes Seven agent-callable operators for image-to-3D output (Tripo and its kin): audit (welded topology, UV overlap, texel density), repair, orient, delight (undo baked lighting that normals and occlusion explain), pick, scrub_markings (paint out baked lettering) and cut_parts (cut a fused skin into capped, rooted, parented parts from seeds). The arithmetic is core.py, numpy only, tested without Blender; the host file is tested against Brokkr's own checker; tests/live/mesh_polish.py proves every row through run_intent in Blender 5.3.0. Co-Authored-By: Claude Fable 5.2 --- .../blender/brokkr_mesh_polish/__init__.py | 698 ++++++++++++++++++ .../brokkr_mesh_polish/brokkr_actions.json | 102 +++ surfaces/blender/brokkr_mesh_polish/core.py | 414 +++++++++++ surfaces/blender/tests/live/mesh_polish.py | 234 ++++++ .../tests/live/mesh_polish.result.json | 471 ++++++++++++ surfaces/blender/tests/test_mesh_polish.py | 390 ++++++++++ 6 files changed, 2309 insertions(+) create mode 100644 surfaces/blender/brokkr_mesh_polish/__init__.py create mode 100644 surfaces/blender/brokkr_mesh_polish/brokkr_actions.json create mode 100644 surfaces/blender/brokkr_mesh_polish/core.py create mode 100644 surfaces/blender/tests/live/mesh_polish.py create mode 100644 surfaces/blender/tests/live/mesh_polish.result.json create mode 100644 surfaces/blender/tests/test_mesh_polish.py diff --git a/surfaces/blender/brokkr_mesh_polish/__init__.py b/surfaces/blender/brokkr_mesh_polish/__init__.py new file mode 100644 index 0000000..af1916c --- /dev/null +++ b/surfaces/blender/brokkr_mesh_polish/__init__.py @@ -0,0 +1,698 @@ +"""Mesh polish for generated meshes (Tripo and other image-to-3D output): measure, repair, orient, undo baked +lighting, scrub baked markings, cut a fused skin into articulated parts. + +A host add-on for Brokkr: it imports nothing from Brokkr, and brokkr_actions.json beside this file lists the +operators agents may run (docs/mesh-polish.md). The arithmetic is core.py (numpy, tested without Blender); +this file is the bpy around it. Every operator writes a JSON report to WindowManager.brokkr_mesh_polish_result. +""" +bl_info = {"name": "Brokkr Mesh Polish", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0), + "category": "Mesh", "description": "Measure and polish generated meshes; agent-callable through Brokkr."} + +import json +import math + +import bmesh +import bpy +import numpy as np +from mathutils import Matrix, Vector +from mathutils.bvhtree import BVHTree + +from . import core + +RESULT = "brokkr_mesh_polish_result" +CAP_MATERIAL = "Polish Cap" +CAP_COLOUR = (0.02, 0.02, 0.025, 1.0) + + +class Refused(Exception): + """The request cannot run on this scene; the message is the receipt.""" + + +def mesh_object(name: str): + obj = bpy.data.objects.get(name) + if obj is None or obj.type != "MESH": + raise Refused(f"No mesh object named {name!r}.") + return obj + + +def mesh_objects(name: str) -> list: + if name: + return [mesh_object(name)] + found = [o for o in bpy.context.scene.objects if o.type == "MESH"] + if not found: + raise Refused("The scene has no mesh objects.") + return found + + +def arrays(obj) -> dict: + """World-space triangle arrays of a mesh object: V, T, UV (per corner, or None), N (vertex normals), + polygon (the polygon each triangle came from).""" + mesh = obj.data + mesh.calc_loop_triangles() + count = len(mesh.loop_triangles) + V = np.empty(len(mesh.vertices) * 3, dtype=np.float32) + mesh.vertices.foreach_get("co", V) + N = np.empty(len(mesh.vertices) * 3, dtype=np.float32) + mesh.vertex_normals.foreach_get("vector", N) + T = np.empty(count * 3, dtype=np.int32) + mesh.loop_triangles.foreach_get("vertices", T) + L = np.empty(count * 3, dtype=np.int32) + mesh.loop_triangles.foreach_get("loops", L) + P = np.empty(count, dtype=np.int32) + mesh.loop_triangles.foreach_get("polygon_index", P) + world = np.array(obj.matrix_world, dtype=np.float64) + V = V.reshape(-1, 3).astype(np.float64) @ world[:3, :3].T + world[:3, 3] + N = N.reshape(-1, 3).astype(np.float64) @ np.linalg.inv(world[:3, :3]) + N /= np.maximum(np.linalg.norm(N, axis=1, keepdims=True), 1e-30) + UV = None + if mesh.uv_layers.active is not None: + flat = np.empty(len(mesh.loops) * 2, dtype=np.float32) + mesh.uv_layers.active.uv.foreach_get("vector", flat) + UV = flat.reshape(-1, 2).astype(np.float64)[L.reshape(-1, 3)] + return {"V": V, "T": T.reshape(-1, 3).astype(np.int64), "UV": UV, "N": N, "polygon": P} + + +def merged(objects: list) -> dict: + """The arrays of several objects as one mesh (vertex indices offset).""" + parts = [arrays(o) for o in objects] + offsets = np.cumsum([0] + [len(p["V"]) for p in parts[:-1]]) + uv = None if any(p["UV"] is None for p in parts) else np.concatenate([p["UV"] for p in parts]) + return {"V": np.concatenate([p["V"] for p in parts]), "N": np.concatenate([p["N"] for p in parts]), + "T": np.concatenate([p["T"] + o for p, o in zip(parts, offsets)]), "UV": uv} + + +def base_color_nodes(obj) -> list: + """Image Texture nodes feeding a Principled BSDF Base Color in the object's materials, nearest first.""" + found = [] + for slot in obj.material_slots: + material = slot.material + if material is None or material.node_tree is None: + continue + for node in material.node_tree.nodes: + if node.type != "BSDF_PRINCIPLED": + continue + queue = [link.from_node for link in node.inputs["Base Color"].links] + seen = set() + while queue: + upstream = queue.pop(0) + if upstream.name in seen: + continue + seen.add(upstream.name) + if upstream.type == "TEX_IMAGE" and upstream.image is not None: + found.append(upstream) + break + queue.extend(link.from_node for socket in upstream.inputs for link in socket.links) + return found + + +def base_color_image(obj): + nodes = base_color_nodes(obj) + if not nodes: + raise Refused(f"Object {obj.name!r} has no image texture on a Principled Base Color.") + return nodes[0].image + + +def image_users(image) -> list: + return [o for o in bpy.context.scene.objects + if o.type == "MESH" and any(n.image == image for n in base_color_nodes(o))] + + +def read_pixels(image) -> np.ndarray: + """(h, w, 4) float32, row 0 at v = 0, in the image's stored values (sRGB-encoded for an sRGB image).""" + width, height = image.size + if width == 0 or height == 0: + raise Refused(f"Image {image.name!r} has no pixels.") + flat = np.empty(width * height * 4, dtype=np.float32) + image.pixels.foreach_get(flat) + return flat.reshape(height, width, 4) + + +def replace_image(old, pixels: np.ndarray, suffix: str): + """A new packed image holding pixels, swapped in for old on every image texture node that used it. Nothing + is written to disk: the image lives in the .blend and in any glTF exported from it.""" + height, width = pixels.shape[:2] + stem = old.name.rsplit(".", 1)[0] if old.name.lower().endswith((".jpg", ".jpeg", ".png")) else old.name + ours = old.get("brokkr_mesh_polish", False) + name = old.name if ours and old.name.endswith("." + suffix) else f"{stem}.{suffix}" + image = bpy.data.images.new(name, width, height, alpha=False) + image["brokkr_mesh_polish"] = True + image.colorspace_settings.name = old.colorspace_settings.name + image.pixels.foreach_set(np.ascontiguousarray(pixels, dtype=np.float32).reshape(-1)) + image.pack() + for material in bpy.data.materials: + if material.node_tree is not None: + for node in material.node_tree.nodes: + if node.type == "TEX_IMAGE" and node.image == old: + node.image = image + if ours and old.users == 0: # an intermediate this add-on made: a chain of edits keeps one image, not one per step + bpy.data.images.remove(old) + image.name = name + return image + + +def ambient_occlusion(V: np.ndarray, T: np.ndarray, N: np.ndarray, rays: int, reach: float, seed: int = 0) -> np.ndarray: + """Open-sky share (0..1) at each vertex: cosine-weighted rays from just above it, against the mesh itself.""" + tree = BVHTree.FromPolygons([tuple(v) for v in V], [tuple(int(i) for i in t) for t in T]) + rng = np.random.default_rng(seed) + u, phi = rng.random(rays), rng.random(rays) * 2 * math.pi + local = np.stack([np.sqrt(u) * np.cos(phi), np.sqrt(u) * np.sin(phi), np.sqrt(1 - u)], axis=1) + helper = np.where(np.abs(N[:, [0]]) < 0.9, [[1.0, 0.0, 0.0]], [[0.0, 1.0, 0.0]]) + tangent = np.cross(N, helper) + tangent /= np.maximum(np.linalg.norm(tangent, axis=1, keepdims=True), 1e-30) + bitangent = np.cross(N, tangent) + open_sky = np.empty(len(V)) + offset = reach * 1e-3 + for i in range(len(V)): + directions = local[:, [0]] * tangent[i] + local[:, [1]] * bitangent[i] + local[:, [2]] * N[i] + origin = Vector(V[i] + N[i] * offset) + hits = sum(1 for d in directions if tree.ray_cast(origin, Vector(d), reach)[0] is not None) + open_sky[i] = 1.0 - hits / rays + return open_sky + + +def resample(pixels: np.ndarray, size: int) -> np.ndarray: + """pixels (h,w,c) at size x size: block mean when the sides divide evenly, nearest texel otherwise.""" + h, w = pixels.shape[:2] + if h == size and w == size: + return pixels + if h % size == 0 and w % size == 0: + return pixels.reshape(size, h // size, size, w // size, -1).mean(axis=(1, 3)) + rows = np.minimum(((np.arange(size) + 0.5) * h / size).astype(int), h - 1) + cols = np.minimum(((np.arange(size) + 0.5) * w / size).astype(int), w - 1) + return pixels[rows][:, cols] + + +def upsample(field: np.ndarray, height: int, width: int) -> np.ndarray: + """A (s,s) field bilinearly resampled to (height, width), texel centres aligned.""" + s = field.shape[0] + y = np.clip((np.arange(height) + 0.5) * s / height - 0.5, 0, s - 1) + x = np.clip((np.arange(width) + 0.5) * s / width - 0.5, 0, s - 1) + y0, x0 = np.floor(y).astype(int), np.floor(x).astype(int) + y1, x1 = np.minimum(y0 + 1, s - 1), np.minimum(x0 + 1, s - 1) + fy, fx = (y - y0)[:, None].astype(np.float32), (x - x0)[None, :].astype(np.float32) + top = field[y0][:, x0] * (1 - fx) + field[y0][:, x1] * fx + bottom = field[y1][:, x0] * (1 - fx) + field[y1][:, x1] * fx + return top * (1 - fy) + bottom * fy + + +def pin_uvs(bm, faces) -> None: + """Give each new face (a filled hole, a cap) one UV point, taken from an old face beside it, so it shows + that texel's colour and takes no area of the texture: a face made by filling has no place in the UV map, + and corners copied from several islands would smear the atlas across it and overlap everything.""" + layer = bm.loops.layers.uv.active + if layer is None: + return + fresh = set(faces) + for face in faces: + anchor = None + for loop in face.loops: + for other in loop.vert.link_loops: + if other.face not in fresh: + anchor = other[layer].uv.copy() + break + if anchor is not None: + break + if anchor is None: + anchor = face.loops[0][layer].uv.copy() + for loop in face.loops: + loop[layer].uv = anchor + + +def cap_surface(): + """The dark, rough material of cut faces and joints: what shows in the gap when a part swings away.""" + material = bpy.data.materials.get(CAP_MATERIAL) + if material is None: + material = bpy.data.materials.new(CAP_MATERIAL) + material.use_nodes = True + material.diffuse_color = CAP_COLOUR + shader = next((n for n in material.node_tree.nodes if n.type == "BSDF_PRINCIPLED"), None) + if shader is not None: + shader.inputs["Base Color"].default_value = CAP_COLOUR + shader.inputs["Roughness"].default_value = 0.7 + return material + + +class PolishOperator(bpy.types.Operator): + """Runs work(context) and stores its report; a Refused is an ERROR report (a failed receipt through Brokkr).""" + bl_options = {"REGISTER", "UNDO"} + + def execute(self, context): + try: + report = self.work(context) + except Refused as refusal: + self.report({"ERROR"}, str(refusal)) + return {"CANCELLED"} + setattr(context.window_manager, RESULT, json.dumps(report, separators=(",", ":"))) + return {"FINISHED"} + + +class BROKKR_MESH_POLISH_OT_audit(PolishOperator): + """Measure the meshes: triangles, welded topology (open and non-manifold edges, shells), UV overlap, UV + islands, texel density, and the size of the base colour texture""" + bl_idname = "brokkr_mesh_polish.audit" + bl_label = "Audit Mesh" + bl_options = {"REGISTER"} + object_name: bpy.props.StringProperty(name="Object", description="A mesh object; every mesh in the scene when empty") + raster: bpy.props.IntProperty(name="UV Raster", default=1024, min=64, max=4096) + + def work(self, context): + report = {} + for obj in mesh_objects(self.object_name): + data = arrays(obj) + nodes = base_color_nodes(obj) + size = max(nodes[0].image.size) if nodes else 0 + entry = core.audit(data["V"], data["T"], data["UV"], size, raster=self.raster) + entry["baseColorImage"] = nodes[0].image.name if nodes else "" + entry["baseColorSize"] = list(nodes[0].image.size) if nodes else [0, 0] + entry["customNormals"] = "custom_normal" in obj.data.attributes + report[obj.name] = entry + return report + + +class BROKKR_MESH_POLISH_OT_repair(PolishOperator): + """Weld coincident vertices (UV seams keep their UVs), drop degenerate and loose geometry, drop shells + below an area share, close small holes, make normals consistent and recompute shading from a sharp angle""" + bl_idname = "brokkr_mesh_polish.repair" + bl_label = "Repair Mesh" + object_name: bpy.props.StringProperty(name="Object") + weld_fraction: bpy.props.FloatProperty(name="Weld", default=1e-4, min=0.0, max=0.02, precision=6, + description="Weld distance as a share of the bounding diagonal") + min_shell_area: bpy.props.FloatProperty(name="Min Shell Area", default=0.0, min=0.0, max=0.5, precision=5, + description="Delete shells holding less than this share of the surface; 0 keeps all") + fill_holes_sides: bpy.props.IntProperty(name="Fill Holes", default=0, min=0, max=1000, + description="Close holes of up to this many edges; 0 leaves holes") + sharp_angle: bpy.props.FloatProperty(name="Sharp Angle", default=0.0, min=0.0, max=180.0, + description="Degrees; above 0, generated custom normals are dropped and edges sharper than this shade hard") + + def work(self, context): + obj = mesh_object(self.object_name) + mesh = obj.data + before = core.audit(arrays(obj)["V"], arrays(obj)["T"], None) + bm = bmesh.new() + bm.from_mesh(mesh) + diagonal = (Vector(obj.bound_box[6]) - Vector(obj.bound_box[0])).length + counts = {"vertices": len(bm.verts)} + if self.weld_fraction > 0: + bmesh.ops.remove_doubles(bm, verts=bm.verts[:], dist=diagonal * self.weld_fraction) + counts["welded"] = counts.pop("vertices") - len(bm.verts) + faces = len(bm.faces) + bmesh.ops.dissolve_degenerate(bm, edges=bm.edges[:], dist=diagonal * 1e-7) + counts["degenerateFacesRemoved"] = faces - len(bm.faces) + loose_edges = [e for e in bm.edges if not e.link_faces] + bmesh.ops.delete(bm, geom=loose_edges, context="EDGES") + loose_verts = [v for v in bm.verts if not v.link_edges] + bmesh.ops.delete(bm, geom=loose_verts, context="VERTS") + counts["looseEdgesRemoved"], counts["looseVertsRemoved"] = len(loose_edges), len(loose_verts) + counts["shellsRemoved"] = 0 + if self.min_shell_area > 0: + bm.verts.index_update() + pairs = np.array([[e.verts[0].index, e.verts[1].index] for e in bm.edges], dtype=np.int64).reshape(-1, 2) + labels = core.components(len(bm.verts), pairs) + face_label = np.array([f.verts[0].index for f in bm.faces], dtype=np.int64) + face_label = labels[face_label] if len(face_label) else face_label + area = np.array([f.calc_area() for f in bm.faces]) + shells, inverse = np.unique(face_label, return_inverse=True) + share = np.bincount(inverse, weights=area, minlength=len(shells)) / max(area.sum(), 1e-30) + small = share < self.min_shell_area + doomed = [f for f, s in zip(bm.faces[:], small[inverse]) if s] + bmesh.ops.delete(bm, geom=doomed, context="FACES") + counts["shellsRemoved"] = int(small.sum()) + counts["holesFilled"] = 0 + if self.fill_holes_sides > 0: + filled = bmesh.ops.holes_fill(bm, edges=[e for e in bm.edges if e.is_boundary], sides=self.fill_holes_sides) + counts["holesFilled"] = len(filled["faces"]) + pin_uvs(bm, filled["faces"]) + bmesh.ops.triangulate(bm, faces=[f for f in filled["faces"] if len(f.verts) > 3]) + bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:]) + bm.to_mesh(mesh) + bm.free() + if self.sharp_angle > 0: + if "custom_normal" in mesh.attributes: + mesh.attributes.remove(mesh.attributes["custom_normal"]) + mesh.polygons.foreach_set("use_smooth", [True] * len(mesh.polygons)) + mesh.set_sharp_from_angle(angle=math.radians(self.sharp_angle)) + mesh.update() + after = core.audit(arrays(obj)["V"], arrays(obj)["T"], None) + return {"object": obj.name, "changes": counts, + "before": {k: before[k] for k in ("triangles", "vertices", "boundaryEdges", "nonManifoldEdges", "shells")}, + "after": {k: after[k] for k in ("triangles", "vertices", "boundaryEdges", "nonManifoldEdges", "shells")}} + + +class BROKKR_MESH_POLISH_OT_orient(PolishOperator): + """Turn every mesh in the scene, as one rigid body, onto its principal axes (longest on Y, shortest on Z), + centre it at the origin, scale its longest side to a length, and bake that into the mesh data""" + bl_idname = "brokkr_mesh_polish.orient" + bl_label = "Orient Meshes" + length: bpy.props.FloatProperty(name="Length", default=0.0, min=0.0, max=1e6, + description="Longest side after scaling, in scene units; 0 keeps the size") + flip_forward: bpy.props.BoolProperty(name="Flip Forward", description="Turn half a turn about Z: swap bow and stern") + roll_quarter_turns: bpy.props.IntProperty(name="Roll", default=0, min=0, max=3, + description="Quarter turns about the long axis, to choose which side is up") + principal: bpy.props.BoolProperty(name="Principal Axes", default=True, + description="Off keeps the current axes and only applies the turns, centre and scale") + + def work(self, context): + objects = mesh_objects("") + data = merged(objects) + centre, rotation = core.principal_frame(data["V"], data["T"]) + if self.principal: + rotation = np.array([rotation[1], rotation[0], -rotation[2]]) # long on Y, middle on X, right-handed + if np.linalg.det(rotation) < 0: + rotation[2] *= -1 + else: + rotation = np.eye(3) + turn = Matrix.Rotation(math.radians(90 * self.roll_quarter_turns), 3, "Y") + if self.flip_forward: + turn = Matrix.Rotation(math.pi, 3, "Z") @ turn + rotation = np.array(turn) @ rotation + local = (data["V"] - centre) @ rotation.T + low, high = local.min(axis=0), local.max(axis=0) + scale = self.length / float((high - low).max()) if self.length > 0 else 1.0 + middle = (low + high) / 2.0 + frame = Matrix.Translation(Vector(-middle * scale)) @ Matrix.Diagonal((scale, scale, scale, 1.0)) \ + @ Matrix([list(row) + [0.0] for row in rotation] + [[0, 0, 0, 1]]) @ Matrix.Translation(Vector(-centre)) + originals = {o.name: frame @ o.matrix_world for o in objects} + for obj in objects: + if obj.data.users > 1: + obj.data = obj.data.copy() + obj.data.transform(originals[obj.name]) + obj.data.update() + for obj in objects: + obj.parent = None + obj.matrix_world = Matrix.Identity(4) + final = (local - middle) * scale + return {"objects": [o.name for o in objects], "scale": scale, + "extent": [round(float(x), 6) for x in (high - low) * scale], + "mirrorError": {axis: core.mirror_error(final, index) for index, axis in enumerate("XYZ")}} + + +class BROKKR_MESH_POLISH_OT_delight(PolishOperator): + """Undo lighting baked into a base colour texture: fit the light that the surface's own normals and ambient + occlusion explain, then raise shaded texels to the level of the lit ones. The result is a new packed image""" + bl_idname = "brokkr_mesh_polish.delight" + bl_label = "Delight Base Colour" + object_name: bpy.props.StringProperty(name="Object", description="Any object using the texture; all its users are treated together") + strength: bpy.props.FloatProperty(name="Strength", default=1.0, min=0.0, max=1.0) + max_gain: bpy.props.FloatProperty(name="Max Gain", default=3.0, min=1.0, max=8.0, + description="No texel is brightened or darkened by more than this factor") + clusters: bpy.props.IntProperty(name="Colour Clusters", default=3, min=1, max=8, + description="How many distinct paints the texture is assumed to hold") + fit_size: bpy.props.IntProperty(name="Fit Size", default=1024, min=128, max=2048) + occlusion_rays: bpy.props.IntProperty(name="Occlusion Rays", default=48, min=8, max=256) + + def work(self, context): + image = base_color_image(mesh_object(self.object_name)) + users = image_users(image) + data = merged(users) + if data["UV"] is None: + raise Refused("An object using the texture has no UV map.") + V, T, N = data["V"], data["T"], data["N"] + diagonal = float(np.linalg.norm(V.max(axis=0) - V.min(axis=0))) + occlusion = ambient_occlusion(V, T, N, self.occlusion_rays, 0.35 * diagonal) + owner, bary, _ = core.rasterize(data["UV"], self.fit_size) + covered = owner >= 0 + if covered.sum() < 64: + raise Refused("The UV map covers too little of the texture to fit lighting.") + normals = core.interpolate(owner, bary, N[T])[covered] + normals /= np.maximum(np.linalg.norm(normals, axis=1, keepdims=True), 1e-30) + sky = core.interpolate(owner, bary, occlusion[T][..., None])[covered][:, 0] + pixels = read_pixels(image) + encoded = image.colorspace_settings.name == "sRGB" + linear = core.srgb_to_linear(pixels[..., :3]) if encoded else pixels[..., :3] + small = resample(linear, self.fit_size)[covered].astype(np.float64) + log_l = np.log(core.luminance(small) + 1e-4) + basis = core.shading_basis(normals, sky) + # Texels below 4% of the white point are unpainted fill (what the generator never saw): no paint to judge. + judged = np.flatnonzero(core.luminance(small) > 0.04 * np.percentile(core.luminance(small), 95)) + if len(judged) < 64: + raise Refused("The texture is too dark to fit lighting.") + fit = np.random.default_rng(0).choice(judged, size=min(len(judged), 200000), replace=False) + labels = core.chroma_clusters(small[fit], min(self.clusters, len(fit))) + weights, explained = core.fit_shading(log_l[fit], basis[fit], labels) + gain = core.delight_gain(basis, weights, self.strength, self.max_gain) + after_log = np.log(core.luminance(small * gain[:, None]) + 1e-4) + _, explained_after = core.fit_shading(after_log[fit], basis[fit], labels) + field = np.ones((self.fit_size, self.fit_size, 1), dtype=np.float32) + field[covered] = gain[:, None] + field = core.push_pull(field, covered)[..., 0] + full = upsample(field, pixels.shape[0], pixels.shape[1]) + out = pixels.copy() + lit = linear * full[..., None] + out[..., :3] = core.linear_to_srgb(lit) if encoded else np.clip(lit, 0.0, None) + source = image.name + new = replace_image(image, out, "delit") # may remove image, when it was this add-on's own + return {"image": source, "newImage": new.name, "objects": [o.name for o in users], + "explainedByLight": {"before": explained, "after": explained_after}, + "before": core.lighting_signature(log_l[judged], normals[judged], sky[judged]), + "after": core.lighting_signature(after_log[judged], normals[judged], sky[judged]), + "gain": {"min": float(gain.min()), "median": float(np.median(gain)), "max": float(gain.max()), + "clamped": float(((gain >= self.max_gain * 0.999) | (gain <= 1.001 / self.max_gain)).mean())}} + + +class BROKKR_MESH_POLISH_OT_scrub_markings(PolishOperator): + """Paint out markings (garbled text, stray decals) on the base colour texture inside a sphere: texels far + from the sphere's median colour are replaced by a blend of their surroundings, with the surroundings' grain""" + bl_idname = "brokkr_mesh_polish.scrub_markings" + bl_label = "Scrub Markings" + object_name: bpy.props.StringProperty(name="Object") + x: bpy.props.FloatProperty(name="X", min=-1e6, max=1e6) + y: bpy.props.FloatProperty(name="Y", min=-1e6, max=1e6) + z: bpy.props.FloatProperty(name="Z", min=-1e6, max=1e6) + radius: bpy.props.FloatProperty(name="Radius", default=0.1, min=1e-4, max=1e6) + tolerance: bpy.props.FloatProperty(name="Tolerance", default=0.12, min=0.0, max=2.0, + description="Colour distance (0..1 texture values) from the region's median that counts as a marking") + grow: bpy.props.IntProperty(name="Grow", default=2, min=0, max=32, description="Texels to widen the marking mask by") + + def work(self, context): + obj = mesh_object(self.object_name) + image = base_color_image(obj) + data = arrays(obj) + if data["UV"] is None: + raise Refused(f"Object {obj.name!r} has no UV map.") + centre = np.array([self.x, self.y, self.z]) + corners = data["V"][data["T"]] + middle = corners.mean(axis=1) + reach = np.linalg.norm(corners - middle[:, None, :], axis=2).max(axis=1) + near = np.linalg.norm(middle - centre, axis=1) <= self.radius + reach + if not near.any(): + raise Refused("No surface lies inside the sphere.") + pixels = read_pixels(image) + height, width = pixels.shape[:2] + if height != width: + raise Refused("The base colour texture is not square.") + owner, bary, _ = core.rasterize(data["UV"][near], height) + position = core.interpolate(owner, bary, corners[near]) + region = (owner >= 0) & (np.linalg.norm(position - centre, axis=2) <= self.radius) + mask = core.marking_mask(pixels[..., :3], region, self.tolerance, self.grow) + if not mask.any(): + return {"object": obj.name, "image": image.name, "regionTexels": int(region.sum()), "scrubbedTexels": 0} + rows, cols = np.nonzero(mask) + pad = 24 + y0, y1 = max(rows.min() - pad, 0), min(rows.max() + pad + 1, height) + x0, x1 = max(cols.min() - pad, 0), min(cols.max() + pad + 1, width) + crop = pixels[y0:y1, x0:x1, :3].copy() + hole = mask[y0:y1, x0:x1] + source = region[y0:y1, x0:x1] & ~hole # fill from the same panel only, never from another UV island + if not source.any(): + raise Refused("The whole region counts as marking: raise the tolerance or the radius.") + filled = core.push_pull(crop, source) + grain = crop - core.box_blur(filled, 3) + donors = np.flatnonzero(source) + picks = np.random.default_rng(0).choice(donors, size=int(hole.sum())) + filled[hole] = np.clip(filled[hole] + grain.reshape(-1, 3)[picks], 0.0, 1.0) + out = pixels.copy() + out[y0:y1, x0:x1, :3][hole] = filled[hole] + source = image.name + new = replace_image(image, out, "scrubbed") # may remove image, when it was this add-on's own + return {"object": obj.name, "image": source, "newImage": new.name, + "regionTexels": int(region.sum()), "scrubbedTexels": int(mask.sum())} + + +class BROKKR_MESH_POLISH_OT_cut_parts(PolishOperator): + """Cut one fused skin into named parts grown from seed points along its concave creases, cap both sides of + every cut, and give each part an origin at the centre of its cut, parented to the first-named part""" + bl_idname = "brokkr_mesh_polish.cut_parts" + bl_label = "Cut Parts" + object_name: bpy.props.StringProperty(name="Object") + seeds: bpy.props.StringProperty(name="Seeds", maxlen=4000, + description="name=x,y,z; name=x,y,z ... world-space points on the surface; the first name is the body") + crease_cost: bpy.props.FloatProperty(name="Crease Cost", default=40.0, min=0.0, max=1000.0, + description="How strongly parts stop at concave creases; 0 splits by distance alone") + through: bpy.props.FloatProperty(name="Through", default=0.0, min=0.0, max=1.0, + description="Above 0, each seed off the body also seeds the far face of its part, found by a ray inward no longer than this share of the bounding diagonal: for thin shells") + joint_scale: bpy.props.FloatProperty(name="Joint Scale", default=0.0, min=0.0, max=10.0, + description="Above 0, a ball joint is added at each cut: radius = this x the cut's mean radius") + + def work(self, context): + obj = mesh_object(self.object_name) + try: + seeds = core.parse_seeds(self.seeds) + except ValueError as error: + raise Refused(str(error)) from None + names = list(dict.fromkeys(name for name, _ in seeds)) + if len(names) < 2: + raise Refused("Cutting needs seeds for at least two parts.") + mesh = obj.data + world = obj.matrix_world.copy() + bm = bmesh.new() + bm.from_mesh(mesh) + diagonal = (Vector(obj.bound_box[6]) - Vector(obj.bound_box[0])).length + bmesh.ops.remove_doubles(bm, verts=bm.verts[:], dist=diagonal * 1e-5) + bmesh.ops.triangulate(bm, faces=[f for f in bm.faces if len(f.verts) > 3]) + bm.verts.index_update() + bm.faces.index_update() + matrix = np.array(world) + V = np.array([v.co[:] for v in bm.verts]) @ matrix[:3, :3].T + matrix[:3, 3] + T = np.array([[v.index for v in f.verts] for f in bm.faces], dtype=np.int64) + pairs = core.face_adjacency(T) + costs = core.crease_costs(V, T, pairs, self.crease_cost) + centroid = V[T].mean(axis=1) + placed = [(int(np.argmin(((centroid - np.array(point)) ** 2).sum(axis=1))), names.index(name)) for name, point in seeds] + if self.through > 0: # a thin part's far face: where a ray from the seed, going inward, comes out again + tree = BVHTree.FromPolygons([tuple(v) for v in V], [tuple(int(i) for i in t) for t in T]) + for triangle, index in list(placed): + if index == 0: + continue + a, b, c = V[T[triangle]] + inward = -np.cross(b - a, c - a) + inward /= max(np.linalg.norm(inward), 1e-30) + hit = tree.ray_cast(Vector(centroid[triangle] + inward * diagonal * 1e-4), Vector(inward), self.through * diagonal) + if hit[0] is not None and hit[2] != triangle: + placed.append((int(hit[2]), index)) + part, _ = core.grow_parts(len(T), pairs, costs, placed) + part[part < 0] = 0 # shells no seed reaches stay with the body + label = bm.faces.layers.int.new("polish_part") + was_open = bm.edges.layers.int.new("polish_was_open") + for face, value in zip(bm.faces, part): + face[label] = int(value) + for edge in bm.edges: + edge[was_open] = int(edge.is_boundary) + cap_material = cap_surface() + cap_slot = len(mesh.materials) + materials = list(mesh.materials) + [cap_material] + collection = obj.users_collection[0] if obj.users_collection else context.scene.collection + made, report = [], [] + for index, name in enumerate(names): + piece = bm.copy() + piece_label = piece.faces.layers.int["polish_part"] + piece_open = piece.edges.layers.int["polish_was_open"] + bmesh.ops.delete(piece, geom=[f for f in piece.faces if f[piece_label] != index], context="FACES") + cut = [e for e in piece.edges if e.is_boundary and not e[piece_open]] + if not piece.faces: + piece.free() + raise Refused(f"Part {name!r} came out empty: move its seed onto the surface.") + lengths = np.array([e.calc_length() for e in cut]) + mids = np.array([((e.verts[0].co + e.verts[1].co) / 2)[:] for e in cut]).reshape(-1, 3) + root_local = (mids * lengths[:, None]).sum(axis=0) / lengths.sum() if len(cut) else np.zeros(3) + spread = mids - root_local + normal_local = np.linalg.eigh((spread * lengths[:, None]).T @ spread)[1][:, 0] if len(cut) >= 3 else np.array([0.0, 0.0, 1.0]) + mean_radius = float((np.linalg.norm(spread, axis=1) * lengths).sum() / lengths.sum()) if len(cut) else 0.0 + caps = bmesh.ops.holes_fill(piece, edges=cut, sides=0)["faces"] if cut else [] + pin_uvs(piece, caps) + caps = bmesh.ops.triangulate(piece, faces=caps)["faces"] if caps else [] + for face in caps: + face.material_index = cap_slot + face.smooth = False + bmesh.ops.recalc_face_normals(piece, faces=piece.faces[:]) + new_mesh = bpy.data.meshes.new(f"{obj.name}.{name}") + root_world = world @ Vector(root_local) if index else world.translation.copy() + piece.to_mesh(new_mesh) + piece.free() + for material in materials: + new_mesh.materials.append(material) + new_obj = bpy.data.objects.new(f"{obj.name}.{name}", new_mesh) + collection.objects.link(new_obj) + new_obj.matrix_world = world + if index: # move the origin to the cut centre without moving the surface + new_mesh.transform(Matrix.Translation(-Vector(root_local))) + new_obj.matrix_world = world @ Matrix.Translation(Vector(root_local)) + normal_world = (world.to_3x3() @ Vector(normal_local)).normalized() + new_obj["polish_cut_normal"] = [round(c, 6) for c in normal_world] + new_obj["polish_cut_radius"] = mean_radius + made.append(new_obj) + report.append({"name": new_obj.name, "triangles": len(new_mesh.polygons), "capTriangles": len(caps), + "cutEdges": len(cut), "root": [round(c, 6) for c in root_world], + "cutNormal": [round(c, 6) for c in normal_world], "cutRadius": mean_radius}) + bm.free() + body = made[0] + for child, entry in zip(made[1:], report[1:]): + child.parent = body + child.matrix_parent_inverse = body.matrix_world.inverted() + if self.joint_scale > 0 and entry["cutRadius"] > 0: + ball = bmesh.new() + bmesh.ops.create_uvsphere(ball, u_segments=16, v_segments=8, radius=entry["cutRadius"] * self.joint_scale) + joint_mesh = bpy.data.meshes.new(f"{child.name}.joint") + ball.to_mesh(joint_mesh) + ball.free() + joint_mesh.materials.append(cap_material) + joint_mesh.polygons.foreach_set("use_smooth", [True] * len(joint_mesh.polygons)) + joint = bpy.data.objects.new(f"{child.name}.joint", joint_mesh) + collection.objects.link(joint) + joint.matrix_world = Matrix.Translation(Vector(entry["root"])) + joint.parent = body + joint.matrix_parent_inverse = body.matrix_world.inverted() + entry["joint"] = joint.name + bpy.data.objects.remove(obj) + if mesh.users == 0: + bpy.data.meshes.remove(mesh) + return {"body": body.name, "parts": report} + + +class BROKKR_MESH_POLISH_OT_pick(PolishOperator): + """Name the surface point seen at a place in a camera's frame: where a render shows something, this says + where it is, so a region can be given to another action""" + bl_idname = "brokkr_mesh_polish.pick" + bl_label = "Pick Surface Point" + bl_options = {"REGISTER"} + camera_name: bpy.props.StringProperty(name="Camera") + u: bpy.props.FloatProperty(name="U", default=0.5, min=0.0, max=1.0, description="Across the frame, 0 left to 1 right") + v: bpy.props.FloatProperty(name="V", default=0.5, min=0.0, max=1.0, description="Up the frame, 0 bottom to 1 top") + resolution_x: bpy.props.IntProperty(name="Resolution X", default=0, min=0, max=16384, + description="Width of the picture (u, v) was read from; 0 is the scene's render width") + resolution_y: bpy.props.IntProperty(name="Resolution Y", default=0, min=0, max=16384, + description="Height of the picture (u, v) was read from; 0 is the scene's render height") + + def work(self, context): + camera = bpy.data.objects.get(self.camera_name) + if camera is None or camera.type != "CAMERA": + raise Refused(f"No camera named {self.camera_name!r}.") + scene = context.scene + context.view_layer.update() + render = scene.render + kept = (render.resolution_x, render.resolution_y) + try: # the frame's shape is the picture's: the same numbers the still was rendered with + render.resolution_x = self.resolution_x or kept[0] + render.resolution_y = self.resolution_y or kept[1] + top_right, bottom_right, bottom_left, top_left = camera.data.view_frame(scene=scene) + finally: + render.resolution_x, render.resolution_y = kept + on_frame = bottom_left + (bottom_right - bottom_left) * self.u + (top_left - bottom_left) * self.v + world = camera.matrix_world + if camera.data.type == "ORTHO": + origin = world @ Vector((on_frame.x, on_frame.y, 0.0)) + direction = (world.to_3x3() @ Vector((0.0, 0.0, -1.0))).normalized() + else: + origin = world.translation.copy() + direction = (world.to_3x3() @ on_frame).normalized() + hit, location, normal, _, obj, _ = scene.ray_cast(context.evaluated_depsgraph_get(), origin, direction) + if not hit: + return {"hit": False} + return {"hit": True, "object": obj.name, "point": [round(c, 6) for c in location], + "normal": [round(c, 6) for c in normal]} + + +classes = (BROKKR_MESH_POLISH_OT_audit, BROKKR_MESH_POLISH_OT_repair, BROKKR_MESH_POLISH_OT_orient, + BROKKR_MESH_POLISH_OT_delight, BROKKR_MESH_POLISH_OT_scrub_markings, BROKKR_MESH_POLISH_OT_cut_parts, + BROKKR_MESH_POLISH_OT_pick) + + +def register(): + setattr(bpy.types.WindowManager, RESULT, bpy.props.StringProperty()) + for cls in classes: + bpy.utils.register_class(cls) + + +def unregister(): + for cls in reversed(classes): + bpy.utils.unregister_class(cls) + delattr(bpy.types.WindowManager, RESULT) diff --git a/surfaces/blender/brokkr_mesh_polish/brokkr_actions.json b/surfaces/blender/brokkr_mesh_polish/brokkr_actions.json new file mode 100644 index 0000000..d2950b7 --- /dev/null +++ b/surfaces/blender/brokkr_mesh_polish/brokkr_actions.json @@ -0,0 +1,102 @@ +{ + "schema": "brokkr.blender.host_actions.v0", + "actions": [ + { + "name": "brokkr_mesh_polish.audit", + "doc": "Measure meshes: triangles, welded topology, shells, UV overlap and islands, texel density. Changes nothing.", + "changesScene": false, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + {"name": "object_name", "type": "string", "maxLength": 63, "doc": "a mesh object; every mesh in the scene when absent"}, + {"name": "raster", "type": "integer", "minimum": 64, "maximum": 4096, "default": 1024, "doc": "grid the UV overlap is counted on"} + ] + }, + { + "name": "brokkr_mesh_polish.repair", + "doc": "Weld coincident vertices, drop degenerate and loose geometry and small shells, close small holes, fix normals.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + {"name": "object_name", "type": "string", "required": true, "minLength": 1, "maxLength": 63}, + {"name": "weld_fraction", "type": "number", "minimum": 0, "maximum": 0.01, "default": 0.0001, "doc": "weld distance as a share of the bounding diagonal"}, + {"name": "min_shell_area", "type": "number", "minimum": 0, "maximum": 0.5, "default": 0, "doc": "delete shells below this share of the surface; 0 keeps all"}, + {"name": "fill_holes_sides", "type": "integer", "minimum": 0, "maximum": 1000, "default": 0, "doc": "close holes of up to this many edges"}, + {"name": "sharp_angle", "type": "number", "minimum": 0, "maximum": 180, "default": 0, "doc": "degrees; above 0 drops generated custom normals and shades edges sharper than this hard"} + ] + }, + { + "name": "brokkr_mesh_polish.orient", + "doc": "Turn all meshes as one body onto their principal axes (long on Y, short on Z), centre, scale, and bake it in.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + {"name": "length", "type": "number", "minimum": 0, "maximum": 1000000, "default": 0, "doc": "longest side after scaling; 0 keeps the size"}, + {"name": "flip_forward", "type": "boolean", "default": false, "doc": "half a turn about Z"}, + {"name": "roll_quarter_turns", "type": "integer", "minimum": 0, "maximum": 3, "default": 0, "doc": "quarter turns about the long axis"}, + {"name": "principal", "type": "boolean", "default": true, "doc": "false keeps the current axes and only turns, centres and scales"} + ] + }, + { + "name": "brokkr_mesh_polish.delight", + "doc": "Undo lighting baked into the base colour texture, as far as normals and ambient occlusion explain it.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + {"name": "object_name", "type": "string", "required": true, "minLength": 1, "maxLength": 63, "doc": "any object using the texture"}, + {"name": "strength", "type": "number", "minimum": 0, "maximum": 1, "default": 1}, + {"name": "max_gain", "type": "number", "minimum": 1, "maximum": 8, "default": 3, "doc": "largest brightening or darkening factor"}, + {"name": "clusters", "type": "integer", "minimum": 1, "maximum": 8, "default": 3, "doc": "distinct paints assumed"}, + {"name": "fit_size", "type": "integer", "minimum": 128, "maximum": 2048, "default": 1024}, + {"name": "occlusion_rays", "type": "integer", "minimum": 8, "maximum": 256, "default": 48} + ] + }, + { + "name": "brokkr_mesh_polish.scrub_markings", + "doc": "Paint out markings (garbled text, decals) on the base colour texture inside a world-space sphere.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + {"name": "object_name", "type": "string", "required": true, "minLength": 1, "maxLength": 63}, + {"name": "x", "type": "number", "minimum": -1000000, "maximum": 1000000, "required": true}, + {"name": "y", "type": "number", "minimum": -1000000, "maximum": 1000000, "required": true}, + {"name": "z", "type": "number", "minimum": -1000000, "maximum": 1000000, "required": true}, + {"name": "radius", "type": "number", "minimum": 0.0001, "maximum": 1000000, "required": true}, + {"name": "tolerance", "type": "number", "minimum": 0, "maximum": 2, "default": 0.12, "doc": "colour distance from the region's median that counts as a marking"}, + {"name": "grow", "type": "integer", "minimum": 0, "maximum": 32, "default": 2, "doc": "texels to widen the mask by"} + ] + }, + { + "name": "brokkr_mesh_polish.cut_parts", + "doc": "Cut one fused skin into named parts grown from seeds along concave creases; cap the cuts; root each part at its cut.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + {"name": "object_name", "type": "string", "required": true, "minLength": 1, "maxLength": 63}, + {"name": "seeds", "type": "string", "required": true, "minLength": 3, "maxLength": 4000, "doc": "name=x,y,z; name=x,y,z ... world-space; the first name is the body"}, + {"name": "crease_cost", "type": "number", "minimum": 0, "maximum": 1000, "default": 40, "doc": "how strongly parts stop at sharp concave creases; 0 splits by distance alone"}, + {"name": "through", "type": "number", "minimum": 0, "maximum": 1, "default": 0, "doc": "above 0, each seed off the body also seeds the far face of its part, by a ray inward no longer than this share of the bounding diagonal (thin shells)"}, + {"name": "joint_scale", "type": "number", "minimum": 0, "maximum": 10, "default": 0, "doc": "above 0 adds a ball joint at each cut, radius = this x the cut's mean radius"} + ] + }, + { + "name": "brokkr_mesh_polish.pick", + "doc": "The surface point seen at (u, v) of a camera's frame, so a place found in a render can be named to another action. Changes nothing.", + "changesScene": false, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + {"name": "camera_name", "type": "string", "required": true, "minLength": 1, "maxLength": 63}, + {"name": "u", "type": "number", "minimum": 0, "maximum": 1, "required": true, "doc": "across the frame, 0 left to 1 right"}, + {"name": "v", "type": "number", "minimum": 0, "maximum": 1, "required": true, "doc": "up the frame, 0 bottom to 1 top"}, + {"name": "resolution_x", "type": "integer", "minimum": 0, "maximum": 16384, "default": 0, "doc": "width of the picture (u, v) was read from; 0 is the scene's render width"}, + {"name": "resolution_y", "type": "integer", "minimum": 0, "maximum": 16384, "default": 0, "doc": "height of the picture; 0 is the scene's render height"} + ] + } + ] +} diff --git a/surfaces/blender/brokkr_mesh_polish/core.py b/surfaces/blender/brokkr_mesh_polish/core.py new file mode 100644 index 0000000..0ae197a --- /dev/null +++ b/surfaces/blender/brokkr_mesh_polish/core.py @@ -0,0 +1,414 @@ +"""The arithmetic of mesh polish: numpy only, no bpy, so every rule here is tested without Blender. + +A mesh is three arrays: V (n,3) positions, T (m,3) vertex indices of triangles, UV (m,3,2) per-corner texture +coordinates. Generated meshes (Tripo and its kin) and glTF imports split vertices at every UV seam, so topology +is always judged on welded positions (weld), never on the raw indices. +""" +from __future__ import annotations + +import numpy as np + + +def weld(V: np.ndarray, T: np.ndarray, tolerance: float) -> tuple[np.ndarray, np.ndarray]: + """(welded vertex id per vertex, T rewritten to welded ids): vertices in the same tolerance cell are one.""" + cells = np.round(np.asarray(V, dtype=np.float64) / max(tolerance, 1e-12)).astype(np.int64) + _, ids = np.unique(cells, axis=0, return_inverse=True) + ids = ids.reshape(-1) + return ids, ids[T] + + +def components(count: int, pairs: np.ndarray) -> np.ndarray: + """Connected-component label (the smallest member id) for each of count nodes joined by pairs (k,2).""" + parent = np.arange(count, dtype=np.int64) + if len(pairs) == 0: + return parent + a, b = pairs[:, 0], pairs[:, 1] + while True: + pa, pb = parent[a], parent[b] + if np.array_equal(pa, pb): + return parent + np.minimum.at(parent, np.maximum(pa, pb), np.minimum(pa, pb)) + while True: + hop = parent[parent] + if np.array_equal(hop, parent): + break + parent = hop + + +def triangle_areas(V: np.ndarray, T: np.ndarray) -> np.ndarray: + a, b, c = V[T[:, 0]], V[T[:, 1]], V[T[:, 2]] + return 0.5 * np.linalg.norm(np.cross(b - a, c - a), axis=1) + + +def edge_census(TW: np.ndarray) -> dict[str, int]: + """Edges of the welded triangles by how many triangles use them: 1 is an open boundary, 3 or more is + non-manifold. Triangles that collapsed in the weld (two corners equal) are left out.""" + live = (TW[:, 0] != TW[:, 1]) & (TW[:, 1] != TW[:, 2]) & (TW[:, 0] != TW[:, 2]) + tw = TW[live] + edges = np.sort(np.concatenate([tw[:, [0, 1]], tw[:, [1, 2]], tw[:, [2, 0]]]), axis=1) + _, counts = np.unique(edges, axis=0, return_counts=True) + return {"edges": int(len(counts)), "boundaryEdges": int((counts == 1).sum()), + "nonManifoldEdges": int((counts > 2).sum()), "collapsedTriangles": int((~live).sum())} + + +def triangle_components(TW: np.ndarray) -> np.ndarray: + """Component label per triangle: triangles sharing a welded vertex are one shell.""" + count = int(TW.max()) + 1 if len(TW) else 0 + labels = components(count, np.concatenate([TW[:, [0, 1]], TW[:, [1, 2]]])) + return labels[TW[:, 0]] + + +def rasterize(UV: np.ndarray, size: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Texel centres covered by the UV triangles, on a size x size grid with v up (row 0 is v = 0). + + Returns (owner, bary, cover): owner[y, x] is the last triangle covering the texel centre or -1, bary[y, x] + its barycentric weights there, cover[y, x] how many triangles cover it (2 or more is UV overlap).""" + owner = np.full((size, size), -1, dtype=np.int32) + bary = np.zeros((size, size, 3), dtype=np.float32) + cover = np.zeros((size, size), dtype=np.uint16) + P = np.asarray(UV, dtype=np.float64) * size - 0.5 # texel index space: centre of texel i is i + lo = np.clip(np.ceil(P.min(axis=1)).astype(np.int64), 0, size) + hi = np.clip(np.floor(P.max(axis=1)).astype(np.int64) + 1, 0, size) + det = ((P[:, 1, 0] - P[:, 0, 0]) * (P[:, 2, 1] - P[:, 0, 1]) - (P[:, 2, 0] - P[:, 0, 0]) * (P[:, 1, 1] - P[:, 0, 1])) + for t in np.nonzero((np.abs(det) > 1e-12) & (hi[:, 0] > lo[:, 0]) & (hi[:, 1] > lo[:, 1]))[0]: + x0, y0, x1, y1 = lo[t, 0], lo[t, 1], hi[t, 0], hi[t, 1] + xs = np.arange(x0, x1, dtype=np.float64)[None, :] + ys = np.arange(y0, y1, dtype=np.float64)[:, None] + a, b, c = P[t] + w1 = ((xs - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (ys - a[1])) / det[t] + w2 = ((b[0] - a[0]) * (ys - a[1]) - (xs - a[0]) * (b[1] - a[1])) / det[t] + w0 = 1.0 - w1 - w2 + inside = (w0 >= 0) & (w1 >= 0) & (w2 >= 0) + if not inside.any(): + continue + block = (slice(y0, y1), slice(x0, x1)) + cover[block] += inside + owner[block][inside] = t + bary[block][inside] = np.stack([w0, w1, w2], axis=-1)[inside] + return owner, bary, cover + + +def interpolate(owner: np.ndarray, bary: np.ndarray, corners: np.ndarray) -> np.ndarray: + """Per-texel value of a per-corner attribute corners (m,3,k); zero where no triangle covers.""" + out = np.zeros(owner.shape + (corners.shape[-1],), dtype=np.float32) + hit = owner >= 0 + out[hit] = np.einsum("pc,pck->pk", bary[hit], corners[owner[hit]]) + return out + + +def uv_islands(TW: np.ndarray, UV: np.ndarray) -> int: + """UV islands: triangles joined where they share a welded vertex at the same UV coordinate.""" + keys = np.concatenate([TW.reshape(-1, 1).astype(np.float64), np.round(UV.reshape(-1, 2) * 65536.0)], axis=1) + _, ids = np.unique(keys, axis=0, return_inverse=True) + ids = ids.reshape(-1, 3) + labels = components(int(ids.max()) + 1, np.concatenate([ids[:, [0, 1]], ids[:, [1, 2]]])) + return int(len(np.unique(labels[ids[:, 0]]))) + + +def weighted_quantile(values: np.ndarray, weights: np.ndarray, q: float) -> float: + order = np.argsort(values) + cumulative = np.cumsum(weights[order]) + return float(values[order][min(np.searchsorted(cumulative, q * cumulative[-1]), len(values) - 1)]) + + +def audit(V: np.ndarray, T: np.ndarray, UV: np.ndarray | None, texture_size: int = 0, + weld_fraction: float = 1e-5, raster: int = 1024) -> dict: + """The measurements a polish pass is judged by. Lengths are in the mesh's own units. + + Topology is counted after welding positions within weld_fraction of the bounding diagonal. UV overlap is + the share of covered texels (on a raster x raster grid) that more than one triangle covers. Texel density is + texels per unit length for a texture_size texture, area-weighted over triangles; its spread is p95 / p5.""" + V = np.asarray(V, dtype=np.float64) + T = np.asarray(T, dtype=np.int64) + extent = V.max(axis=0) - V.min(axis=0) if len(V) else np.zeros(3) + diagonal = float(np.linalg.norm(extent)) + areas = triangle_areas(V, T) + ids, TW = weld(V, T, diagonal * weld_fraction) + report = {"triangles": int(len(T)), "vertices": int(len(V)), "weldedVertices": int(ids.max()) + 1 if len(V) else 0, + "extent": [round(float(x), 6) for x in extent], "surfaceArea": float(areas.sum()), + "degenerateTriangles": int((areas <= 1e-14 * diagonal * diagonal).sum())} + report.update(edge_census(TW)) + shells = triangle_components(TW) + _, shell_sizes = np.unique(shells, return_counts=True) + report["shells"] = int(len(shell_sizes)) + report["shellTriangles"] = sorted((int(s) for s in shell_sizes), reverse=True)[:12] + if UV is None: + return report + UV = np.asarray(UV, dtype=np.float64) + signed = 0.5 * ((UV[:, 1, 0] - UV[:, 0, 0]) * (UV[:, 2, 1] - UV[:, 0, 1]) + - (UV[:, 2, 0] - UV[:, 0, 0]) * (UV[:, 1, 1] - UV[:, 0, 1])) + _, _, cover = rasterize(UV, raster) + covered = int((cover > 0).sum()) + report.update({ + "uvIslands": uv_islands(TW, UV), + "uvFlippedTriangles": int((signed < 0).sum()), + "uvZeroAreaTriangles": int((np.abs(signed) < 1e-12).sum()), + "uvOutsideUnitTriangles": int(((UV < -1e-6) | (UV > 1 + 1e-6)).any(axis=(1, 2)).sum()), + "uvCoverage": covered / float(raster * raster), + "uvOverlap": float((cover > 1).sum()) / covered if covered else 0.0, + }) + usable = (areas > 0) & (np.abs(signed) > 0) + if texture_size and usable.any(): + density = np.sqrt(np.abs(signed[usable]) * texture_size * texture_size / areas[usable]) + p5, p50, p95 = (weighted_quantile(density, areas[usable], q) for q in (0.05, 0.5, 0.95)) + report.update({"texelDensityMedian": p50, "texelDensityP5": p5, "texelDensityP95": p95, + "texelDensitySpread": p95 / p5 if p5 > 0 else float("inf")}) + return report + + +# --- orientation ----------------------------------------------------------------------------------------- + +def principal_frame(V: np.ndarray, T: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """(centre, R): the area-weighted centroid and a right-handed rotation whose rows are the principal axes, + longest first. R @ (p - centre) puts the longest axis on x, the shortest on z.""" + a, b, c = V[T[:, 0]], V[T[:, 1]], V[T[:, 2]] + areas = triangle_areas(V, T) + mids = (a + b + c) / 3.0 + centre = (mids * areas[:, None]).sum(axis=0) / areas.sum() + d = mids - centre + _, vectors = np.linalg.eigh((d * areas[:, None]).T @ d) + R = vectors[:, ::-1].T.copy() + if np.linalg.det(R) < 0: + R[2] *= -1 + return centre, R + + +def mirror_error(V: np.ndarray, axis: int, samples: int = 800, seed: int = 0) -> float: + """How far the point set is from mirror-symmetric across the plane axis = 0: the mean distance from a + mirrored sample to its nearest original, as a fraction of the bounding diagonal. 0 is a perfect mirror.""" + rng = np.random.default_rng(seed) + pick = V[rng.choice(len(V), size=min(samples, len(V)), replace=False)] + mirrored = pick.copy() + mirrored[:, axis] *= -1 + base = V[rng.choice(len(V), size=min(4 * samples, len(V)), replace=False)] + nearest = np.sqrt(((mirrored[:, None, :] - base[None, :, :]) ** 2).sum(axis=2).min(axis=1)) + return float(nearest.mean() / np.linalg.norm(V.max(axis=0) - V.min(axis=0))) + + +# --- parts ----------------------------------------------------------------------------------------------- + +def face_adjacency(TW: np.ndarray) -> np.ndarray: + """Pairs (k,2) of triangles that share a welded edge (each manifold edge once; an edge of three or more + triangles joins them in a chain).""" + count = len(TW) + edges = np.sort(np.concatenate([TW[:, [0, 1]], TW[:, [1, 2]], TW[:, [2, 0]]]), axis=1) + face = np.tile(np.arange(count), 3) + order = np.lexsort((edges[:, 1], edges[:, 0])) + edges, face = edges[order], face[order] + same = (edges[1:] == edges[:-1]).all(axis=1) + return np.stack([face[:-1][same], face[1:][same]], axis=1) + + +def crease_costs(V: np.ndarray, T: np.ndarray, pairs: np.ndarray, crease_cost: float) -> np.ndarray: + """Cost of stepping between two adjacent triangles: the distance between their centroids as a fraction of + the bounding diagonal, plus crease_cost times the square of how concave the fold between them is (0 flat + or convex, 1 a fold back on itself). A sharp concave crease is where one part of a fused skin meets another; + the square keeps the gentle concavity of a bowl, many small folds, far cheaper than one such crease.""" + a, b, c = V[T[:, 0]], V[T[:, 1]], V[T[:, 2]] + normal = np.cross(b - a, c - a) + normal /= np.maximum(np.linalg.norm(normal, axis=1, keepdims=True), 1e-30) + centre = (a + b + c) / 3.0 + diagonal = np.linalg.norm(V.max(axis=0) - V.min(axis=0)) + i, j = pairs[:, 0], pairs[:, 1] + step = centre[j] - centre[i] + angle = np.arccos(np.clip((normal[i] * normal[j]).sum(axis=1), -1.0, 1.0)) / np.pi + concave = ((step * normal[i]).sum(axis=1) - (step * normal[j]).sum(axis=1)) > 0 + return np.linalg.norm(step, axis=1) / diagonal + crease_cost * np.where(concave, angle * angle, 0.0) + + +def grow_parts(count: int, pairs: np.ndarray, costs: np.ndarray, seeds: list[tuple[int, int]]) -> tuple[np.ndarray, np.ndarray]: + """(part, cost) per triangle: each triangle joins the seed it is cheapest to walk to, at that cost; part is + -1 and cost infinite where no seed reaches. seeds are (triangle, part) and several seeds may name one part.""" + import heapq + + order = np.argsort(np.concatenate([pairs[:, 0], pairs[:, 1]]), kind="stable") + source = np.concatenate([pairs[:, 0], pairs[:, 1]])[order] + target = np.concatenate([pairs[:, 1], pairs[:, 0]])[order].tolist() + weight = np.concatenate([costs, costs])[order].tolist() + start = np.searchsorted(source, np.arange(count + 1)).tolist() + best = [float("inf")] * count + part = [-1] * count + heap = [] + for triangle, label in seeds: + best[triangle], part[triangle] = 0.0, label + heap.append((0.0, triangle, label)) + heapq.heapify(heap) + while heap: + cost, triangle, label = heapq.heappop(heap) + if cost > best[triangle] or part[triangle] != label: + continue + for k in range(start[triangle], start[triangle + 1]): + other, reach = target[k], cost + weight[k] + if reach < best[other]: + best[other], part[other] = reach, label + heapq.heappush(heap, (reach, other, label)) + return np.asarray(part, dtype=np.int64), np.asarray(best) + + +def parse_seeds(text: str) -> list[tuple[str, tuple[float, float, float]]]: + """'hull=0,0,0; pod1=1,0,0.5; pod1=1.2,0,0.4' as [(name, (x, y, z))]; ValueError names the bad entry.""" + seeds = [] + for entry in (piece.strip() for piece in text.split(";")): + if not entry: + continue + name, _, numbers = entry.partition("=") + values = numbers.split(",") + try: + point = tuple(float(v) for v in values) + except ValueError: + point = () + if not name.strip() or len(point) != 3: + raise ValueError(f"seed {entry!r} is not name=x,y,z") + seeds.append((name.strip(), point)) + if not seeds: + raise ValueError("no seeds given") + return seeds + + +# --- baked lighting -------------------------------------------------------------------------------------- + +def srgb_to_linear(c: np.ndarray) -> np.ndarray: + return np.where(c <= 0.04045, c / 12.92, ((np.maximum(c, 0.0) + 0.055) / 1.055) ** 2.4) + + +def linear_to_srgb(c: np.ndarray) -> np.ndarray: + c = np.clip(c, 0.0, 1.0) + return np.where(c <= 0.0031308, c * 12.92, 1.055 * c ** (1.0 / 2.4) - 0.055) + + +def luminance(rgb: np.ndarray) -> np.ndarray: + return rgb[..., 0] * 0.2126 + rgb[..., 1] * 0.7152 + rgb[..., 2] * 0.0722 + + +def shading_basis(normals: np.ndarray, occlusion: np.ndarray) -> np.ndarray: + """What baked light can depend on at a surface point: the eight non-constant order-2 spherical harmonics of + the unit normal (a smooth distant light) and the log of ambient occlusion (0..1, 1 is open sky).""" + x, y, z = normals[:, 0], normals[:, 1], normals[:, 2] + return np.stack([x, y, z, x * y, y * z, x * z, x * x - y * y, 3 * z * z - 1, + np.log(np.clip(occlusion, 0.02, 1.0))], axis=1) + + +def chroma_clusters(rgb: np.ndarray, count: int) -> np.ndarray: + """A cluster per sample by chromaticity alone (r and g as shares of the sum): paint of one hue stays one + cluster whether lit or shaded, so each cluster can stand for one family of paint.""" + return kmeans((rgb / (rgb.sum(axis=1, keepdims=True) + 1e-4))[:, :2], count) + + +def fit_shading(log_l: np.ndarray, basis: np.ndarray, clusters: np.ndarray, expectile: float = 0.85, + rounds: int = 12) -> tuple[np.ndarray, float]: + """(weights, explained): log luminance = an intercept per cluster + basis @ weights (the light). + + The fit follows the upper envelope of luminance (an expectile regression: samples above the fit weigh + expectile, samples below weigh 1 - expectile). Within one hue the brightest paint at a given normal and + occlusion shows how much light the bake put there; darker paint in the same place, such as machinery in a + crevice of a pale hull, is paint and must not be read as shadow. explained is the share of the + within-cluster variance of log luminance that the light accounts for: near 0, no baked light was found.""" + count = int(clusters.max()) + 1 + weight = np.ones(len(log_l)) + + def demean(values: np.ndarray) -> np.ndarray: + scaled = values * (weight[:, None] if values.ndim == 2 else weight) + sums = np.stack([np.bincount(clusters, weights=column, minlength=count) for column in scaled.reshape(len(values), -1).T], axis=1) + means = sums / np.maximum(np.bincount(clusters, weights=weight, minlength=count), 1e-12)[:, None] + return values - means[clusters].reshape(values.shape) + + w = np.zeros(basis.shape[1]) + for _ in range(rounds): + x, y = demean(basis), demean(log_l) + root = np.sqrt(weight) + w, *_ = np.linalg.lstsq(x * root[:, None], y * root, rcond=None) + weight = np.where(y - x @ w > 0, expectile, 1.0 - expectile) + weight = np.ones(len(log_l)) + x, y = demean(basis), demean(log_l) + total = float((y * y).sum()) + residual = demean(log_l - basis @ w) + return w, max(1.0 - float((residual * residual).sum()) / total, 0.0) if total > 0 else 0.0 + + +def lighting_signature(log_l: np.ndarray, normals: np.ndarray, occlusion: np.ndarray, up: int = 2) -> dict: + """Model-free signs of baked light: how much brighter up-facing surface is than down-facing (a ratio of + geometric-mean luminance, 1 is none) and how log luminance correlates with ambient occlusion (0 is none).""" + top, bottom = normals[:, up] > 0.5, normals[:, up] < -0.5 + ratio = float(np.exp(log_l[top].mean() - log_l[bottom].mean())) if top.any() and bottom.any() else 1.0 + spread = float(np.std(occlusion)) + correlation = float(np.corrcoef(log_l, occlusion)[0, 1]) if spread > 1e-6 and np.std(log_l) > 1e-9 else 0.0 + return {"upDownLuminanceRatio": ratio, "occlusionCorrelation": correlation} + + +def kmeans(features: np.ndarray, count: int, rounds: int = 12, seed: int = 0) -> np.ndarray: + rng = np.random.default_rng(seed) + centres = features[rng.choice(len(features), size=count, replace=False)].copy() + labels = np.zeros(len(features), dtype=np.int64) + for _ in range(rounds): + labels = np.argmin(((features[:, None, :] - centres[None, :, :]) ** 2).sum(axis=2), axis=1) + for k in range(count): + if (labels == k).any(): + centres[k] = features[labels == k].mean(axis=0) + return labels + + +def delight_gain(basis: np.ndarray, weights: np.ndarray, strength: float, max_gain: float) -> np.ndarray: + """The factor that undoes the fitted light at each sample. Surface the light favoured (the 90th percentile + of fitted light) is left as it is and shaded surface rises to meet it; nothing changes by more than + max_gain either way.""" + light = basis @ weights + return np.clip(np.exp(strength * (np.percentile(light, 90) - light)), 1.0 / max_gain, max_gain) + + +# --- texture filling ------------------------------------------------------------------------------------- + +def push_pull(image: np.ndarray, known: np.ndarray) -> np.ndarray: + """image (h,w,c) with the texels where known is False replaced by a smooth blend of the known texels around + them (push-pull: average down a pyramid, fill up from the coarser level). Known texels are returned as given.""" + h, w = known.shape + if known.all() or not known.any() or min(h, w) < 2: + return image.copy() + value = np.where(known[..., None], image, 0.0).astype(np.float32) + mass = known.astype(np.float32) + h2, w2 = (h + 1) // 2, (w + 1) // 2 + padded_v = np.zeros((h2 * 2, w2 * 2, image.shape[2]), dtype=np.float32) + padded_m = np.zeros((h2 * 2, w2 * 2), dtype=np.float32) + padded_v[:h, :w], padded_m[:h, :w] = value, mass + small_m = padded_m.reshape(h2, 2, w2, 2).sum(axis=(1, 3)) + small_v = padded_v.reshape(h2, 2, w2, 2, -1).sum(axis=(1, 3)) / np.maximum(small_m, 1e-9)[..., None] + filled = push_pull(small_v, small_m > 0) + up = np.repeat(np.repeat(filled, 2, axis=0), 2, axis=1)[:h, :w] + return np.where(known[..., None], image, up).astype(image.dtype) + + +def box_blur(image: np.ndarray, radius: int) -> np.ndarray: + """Mean over a (2 radius + 1) square, edges clamped; image is (h,w) or (h,w,c).""" + if radius <= 0: + return image.copy() + out = image.astype(np.float64) + for axis in (0, 1): + pad = [(0, 0)] * out.ndim + pad[axis] = (radius + 1, radius) + summed = np.cumsum(np.pad(out, pad, mode="edge"), axis=axis) + n = out.shape[axis] + upper = np.take(summed, np.arange(2 * radius + 1, 2 * radius + 1 + n), axis=axis) + lower = np.take(summed, np.arange(0, n), axis=axis) + out = (upper - lower) / (2 * radius + 1) + return out.astype(image.dtype) + + +def dilate(mask: np.ndarray, steps: int) -> np.ndarray: + out = mask.copy() + for _ in range(steps): + grown = out.copy() + grown[1:, :] |= out[:-1, :] + grown[:-1, :] |= out[1:, :] + grown[:, 1:] |= out[:, :-1] + grown[:, :-1] |= out[:, 1:] + out = grown + return out + + +def marking_mask(rgb: np.ndarray, region: np.ndarray, tolerance: float, grow: int) -> np.ndarray: + """Texels inside region whose colour is further than tolerance (Euclidean, in the image's own 0..1 values) + from the region's median colour, grown by grow texels within the region: the ink on a painted panel.""" + if not region.any(): + return np.zeros(region.shape, dtype=bool) + background = np.median(rgb[region], axis=0) + ink = region & (np.linalg.norm(rgb - background, axis=-1) > tolerance) + return dilate(ink, grow) & region diff --git a/surfaces/blender/tests/live/mesh_polish.py b/surfaces/blender/tests/live/mesh_polish.py new file mode 100644 index 0000000..4284585 --- /dev/null +++ b/surfaces/blender/tests/live/mesh_polish.py @@ -0,0 +1,234 @@ +"""Live proof, in a background Blender, that every brokkr_mesh_polish row is admitted by Brokkr as a host action +and does what its doc says to real bpy meshes and images. Not part of the unittest run: it needs Blender. + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/mesh_polish.py -- + +Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses +without them). Every action is sent through BrokkrBlenderTarget.run_intent, as tools/run_intents.py sends it. +Writes .result.json and exits 1 when a check failed. +""" +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 Matrix + +for _name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): + if not os.environ.get(_name): + raise SystemExit(f"{_name} is not set: run this in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") + +SURFACE = Path(__file__).resolve().parents[2] +OUT = sys.argv[sys.argv.index("--") + 1] +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) +addon_utils.enable("brokkr_mesh_polish", default_set=True) +target = bt.BrokkrBlenderTarget(bpy) +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] + + +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 + return receipt, result + + +def new_object(name, build, image=None): + mesh = bpy.data.meshes.new(name) + bm = bmesh.new() + bm.loops.layers.uv.new("UVMap") # calc_uvs fills a layer that exists + build(bm) + bm.to_mesh(mesh) + bm.free() + obj = bpy.data.objects.new(name, mesh) + bpy.context.scene.collection.objects.link(obj) + if image is not None: + material = bpy.data.materials.new(name) + material.use_nodes = True + node = material.node_tree.nodes.new("ShaderNodeTexImage") + node.image = image + shader = next(n for n in material.node_tree.nodes if n.type == "BSDF_PRINCIPLED") + material.node_tree.links.new(node.outputs["Color"], shader.inputs["Base Color"]) + mesh.materials.append(material) + return obj + + +def new_image(name, pixels): + height, width = pixels.shape[:2] + image = bpy.data.images.new(name, width, height, alpha=False) + image.colorspace_settings.name = "Non-Color" # stored values are the paint: the checks read them back as written + rgba = np.ones((height, width, 4), dtype=np.float32) + rgba[..., :3] = pixels + image.pixels.foreach_set(rgba.reshape(-1)) + return image + + +def pixels_of(obj): + image = obj.material_slots[0].material.node_tree.nodes["Image Texture"].image + flat = np.empty(image.size[0] * image.size[1] * 4, dtype=np.float32) + image.pixels.foreach_get(flat) + return flat.reshape(image.size[1], image.size[0], 4)[..., :3], image + + +check("host file admitted", not R["hostErrors"] and len(R["hostRows"]) == 7, R["hostErrors"] or R["hostRows"]) + +# --- audit and repair: a sphere torn into loose faces is welded back into one closed shell ----------------------- +size = 256 +rows = (np.arange(size) + 0.5) / size # v: 0 at the south pole, 1 at the north pole of Blender's UV sphere +baked = np.repeat((0.8 * (0.2 + 0.8 * rows))[:, None, None], size, axis=1) * np.ones((1, 1, 3)) +sphere = new_object("Ball", lambda bm: bmesh.ops.create_uvsphere(bm, u_segments=48, v_segments=24, radius=1.0, calc_uvs=True), + new_image("ball_bake", baked.astype(np.float32))) +sphere.data.polygons.foreach_set("use_smooth", [True] * len(sphere.data.polygons)) +torn = bmesh.new() +torn.from_mesh(sphere.data) +bmesh.ops.split_edges(torn, edges=torn.edges[:]) +torn.to_mesh(sphere.data) +torn.free() +receipt, before = send("brokkr_mesh_polish.audit", object_name="Ball") +check("audit: accepted, no undo step", receipt["status"] == "accepted" and not receipt.get("undoLabel"), receipt["message"]) +check("audit: welded topology sees one closed shell in the torn sphere", + before["Ball"]["shells"] == 1 and before["Ball"]["boundaryEdges"] == 0 and before["Ball"]["nonManifoldEdges"] == 0, before["Ball"]) +check("audit: texture and UV facts", before["Ball"]["baseColorSize"] == [size, size] and before["Ball"]["uvOverlap"] < 0.02 + and before["Ball"]["texelDensityMedian"] > 0, before["Ball"]) +torn_vertices = len(sphere.data.vertices) +receipt, repaired = send("brokkr_mesh_polish.repair", object_name="Ball", sharp_angle=30) +check("repair: accepted as one undo step", receipt["status"] == "accepted" and "repair" in receipt.get("undoLabel", ""), receipt) +check("repair: welds the torn vertices", repaired["changes"]["welded"] == torn_vertices - len(sphere.data.vertices) + and len(sphere.data.vertices) == 48 * 23 + 2, repaired) +edges = [e for e in sphere.data.edges] +check("repair: every edge has two faces again", sum(1 for _ in edges) == 48 * 23 + 48 * 24, len(edges)) + +# --- delight: a bake that darkens with latitude is levelled ------------------------------------------------------ +receipt, lit = send("brokkr_mesh_polish.delight", object_name="Ball", clusters=1, fit_size=256, occlusion_rays=8) +after_pixels, after_image = pixels_of(sphere) +column = after_pixels[:, size // 2, 0] +# top/bottom brightness of the stored texture, rows at v = 0.9 and v = 0.1 +ratio_before = float(baked[int(size * 0.9), 0, 0] / baked[int(size * 0.1), 0, 0]) +ratio_after = float(column[int(size * 0.9)] / column[int(size * 0.1)]) +R["delight"] = {"report": lit, "ratioBefore": ratio_before, "ratioAfter": ratio_after} +check("delight: accepted, new packed image on the material", receipt["status"] == "accepted" and after_image.name == "ball_bake.delit" + and after_image.packed_file is not None, receipt["message"]) +check("delight: finds the baked light", lit["explainedByLight"]["before"] > 0.5 and lit["before"]["upDownLuminanceRatio"] > 2.0, lit) +# bound: shipped ratioAfter 1.12, the no-op mutant leaves 3.29: sqrt(1.12 * 3.29) = 1.92 +check("delight: levels top against bottom", ratio_before > 1.92 * 1.2 and ratio_after < 1.92 / 1.2, [ratio_before, ratio_after]) + +# --- orient: a turned slab is laid along Y, thin on Z, centred, scaled ------------------------------------------ +slab = new_object("Slab", lambda bm: bmesh.ops.create_cube(bm, size=1.0, matrix=Matrix.Diagonal((3.0, 1.0, 0.5, 1.0)))) +slab.matrix_world = Matrix.Translation((4, 5, 6)) @ Matrix.Rotation(math.radians(37), 4, (0.3, 0.5, 0.8)) +sphere.hide_viewport = True +bpy.context.scene.collection.objects.unlink(sphere) # orient turns every mesh in the scene as one body +receipt, oriented = send("brokkr_mesh_polish.orient", length=12.0) +corners = np.array([slab.matrix_world @ v.co for v in slab.data.vertices]) +extent = corners.max(axis=0) - corners.min(axis=0) +check("orient: long on Y, thin on Z, scaled to the length, centred", + receipt["status"] == "accepted" and np.allclose(extent, [4.0, 12.0, 2.0], atol=1e-3) + and np.allclose((corners.max(axis=0) + corners.min(axis=0)) / 2, 0, atol=1e-4), [list(map(float, extent)), oriented]) +check("orient: reports the mirror error of a symmetric body as small", max(oriented["mirrorError"].values()) < 0.05, oriented["mirrorError"]) +bpy.data.objects.remove(slab) + +# --- cut_parts: a knob fused to a block is cut off at the crease, capped, and rooted at its cut ----------------- +def knobbed(bm): + bmesh.ops.create_cube(bm, size=2.0) + top = next(f for f in bm.faces if f.normal.z > 0.9) + bmesh.ops.inset_region(bm, faces=[top], thickness=0.6) + extruded = bmesh.ops.extrude_face_region(bm, geom=[top]) + bmesh.ops.translate(bm, verts=[g for g in extruded["geom"] if isinstance(g, bmesh.types.BMVert)], vec=(0, 0, 1.0)) + bmesh.ops.delete(bm, geom=[top], context="FACES") + bmesh.ops.triangulate(bm, faces=bm.faces[:]) + bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:]) + + +block = new_object("Block", knobbed) +receipt, single = send("brokkr_mesh_polish.audit", object_name="Block") +check("cut fixture is one closed skin", single["Block"]["shells"] == 1 and single["Block"]["boundaryEdges"] == 0, single["Block"]) +receipt, cut = send("brokkr_mesh_polish.cut_parts", object_name="Block", seeds="body=0,0,-1; knob=0,0,2", joint_scale=0.5) +R["cut"] = cut +check("cut_parts: accepted, one undo step, the fused object is replaced", receipt["status"] == "accepted" and bool(receipt.get("undoLabel")) + and "Block" not in bpy.data.objects and {"Block.body", "Block.knob"} <= set(bpy.data.objects.keys()), receipt["message"]) +if receipt["status"] == "accepted": + knob, body = bpy.data.objects["Block.knob"], bpy.data.objects["Block.body"] + part = {entry["name"]: entry for entry in cut["parts"]} + check("cut_parts: the knob is cut at the crease and rooted at the centre of the cut", + np.allclose(part["Block.knob"]["root"], [0, 0, 1], atol=1e-5) and np.allclose(knob.matrix_world.translation, [0, 0, 1], atol=1e-5) + and abs(abs(part["Block.knob"]["cutNormal"][2]) - 1) < 1e-5, part["Block.knob"]) + check("cut_parts: the knob hangs from the body and has not moved", knob.parent == body + and abs(max((knob.matrix_world @ v.co).z for v in knob.data.vertices) - 2.0) < 1e-5, None) + _, closed = send("brokkr_mesh_polish.audit") + check("cut_parts: both sides of the cut are capped (closed shells)", + all(closed[name]["boundaryEdges"] == 0 and closed[name]["shells"] == 1 for name in ("Block.body", "Block.knob")), + {name: [closed[name]["boundaryEdges"], closed[name]["shells"]] for name in ("Block.body", "Block.knob")}) + check("cut_parts: caps carry the cap material and a joint sits at the root", "Polish Cap" in [m.name for m in knob.data.materials] + and np.allclose(bpy.data.objects[part["Block.knob"]["joint"]].matrix_world.translation, [0, 0, 1], atol=1e-5), part["Block.knob"].get("joint")) +receipt, _ = send("brokkr_mesh_polish.cut_parts", object_name="Block.body", seeds="only=0,0,-1") +check("cut_parts: one part is refused with nothing changed", receipt["status"] == "failed" and "Block.body" in bpy.data.objects, receipt["message"]) + +# --- pick and scrub_markings: lettering on one panel is found from a camera and painted out ---------------------- +panel = np.full((128, 128, 3), [0.1, 0.35, 0.4], dtype=np.float32) +panel += np.random.default_rng(0).normal(0, 0.01, panel.shape).astype(np.float32) +for column_start in range(8, 120, 8): # yellow strokes over the whole texture + panel[:, column_start:column_start + 2] = [0.85, 0.75, 0.2] + + +def plate(bm): + bmesh.ops.create_grid(bm, x_segments=2, y_segments=1, size=1.0, matrix=Matrix.Diagonal((2.0, 1.0, 1.0, 1.0)), calc_uvs=True) + + +sign = new_object("Sign", plate, new_image("sign_paint", panel)) # 4 x 2, flat on z = 0, u along x +sign.location = (0, 0, 5) +bpy.context.view_layer.update() +camera = bpy.data.objects.new("Eye", bpy.data.cameras.new("Eye")) +bpy.context.scene.collection.objects.link(camera) +camera.data.type = "ORTHO" +camera.data.ortho_scale = 4.0 +camera.location = (0, 0, 9) +receipt, picked = send("brokkr_mesh_polish.pick", camera_name="Eye", u=0.25, v=0.5, resolution_x=400, resolution_y=200) +check("pick: names the surface point under (u, v) of a picture of that shape", receipt["status"] == "accepted" and picked["hit"] + and picked["object"] == "Sign" and np.allclose(picked["point"], [-1.0, 0.0, 5.0], atol=1e-4), picked) +receipt, missed = send("brokkr_mesh_polish.pick", camera_name="Eye", u=0.5, v=0.99, resolution_x=200, resolution_y=400) +check("pick: off the surface is a miss, not an error", receipt["status"] == "accepted" and missed == {"hit": False}, missed) + + +def ink(pixels): + return np.linalg.norm(pixels - [0.1, 0.35, 0.4], axis=-1) > 0.25 + + +receipt, scrubbed = send("brokkr_mesh_polish.scrub_markings", object_name="Sign", x=picked["point"][0], y=0.0, z=5.0, radius=0.5, tolerance=0.25) +after, image = pixels_of(sign) +inside = np.zeros((128, 128), dtype=bool) +inside[48:80, 20:44] = True # well within the sphere: u 0.25 +- 0.09, v 0.5 +- 0.12 +far = np.zeros((128, 128), dtype=bool) +far[:, 72:] = True # the other half of the sign +R["scrub"] = {"report": scrubbed, "inkInsideBefore": int(ink(panel)[inside].sum()), "inkInsideAfter": int(ink(after)[inside].sum())} +check("scrub_markings: accepted, the lettering inside the sphere is gone", receipt["status"] == "accepted" + and ink(panel)[inside].sum() > 100 and ink(after)[inside].sum() == 0, R["scrub"]) +check("scrub_markings: nothing outside the sphere is touched (to the 8 bits the image stores)", np.allclose(after[far], panel[far], atol=0.6 / 255) and image.name == "sign_paint.scrubbed", image.name) +receipt, _ = send("brokkr_mesh_polish.scrub_markings", object_name="Sign", x=50.0, y=0.0, z=0.0, radius=0.5) +check("scrub_markings: a sphere off the surface is refused", receipt["status"] == "failed", receipt["message"]) +receipt, _ = send("brokkr_mesh_polish.delight", object_name="Sign", max_gain=9) +check("a bound miss is denied by Brokkr's table before the operator runs", receipt["status"] == "denied", receipt["message"]) + +R["ok"] = all(c["ok"] for c in R["checks"]) +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) +sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/mesh_polish.result.json b/surfaces/blender/tests/live/mesh_polish.result.json new file mode 100644 index 0000000..9f3bae1 --- /dev/null +++ b/surfaces/blender/tests/live/mesh_polish.result.json @@ -0,0 +1,471 @@ +{ + "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" + ] + }, + { + "name": "audit: accepted, no undo step", + "ok": true, + "detail": "Operator brokkr_mesh_polish.audit finished." + }, + { + "name": "audit: welded topology sees one closed shell in the torn sphere", + "ok": true, + "detail": { + "triangles": 2208, + "vertices": 4512, + "weldedVertices": 1106, + "extent": [ + 2.000001, + 2.000002, + 2.0 + ], + "surfaceArea": 12.521572614010894, + "degenerateTriangles": 0, + "edges": 3312, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "collapsedTriangles": 0, + "shells": 1, + "shellTriangles": [ + 2208 + ], + "uvIslands": 1, + "uvFlippedTriangles": 0, + "uvZeroAreaTriangles": 0, + "uvOutsideUnitTriangles": 0, + "uvCoverage": 0.95831298828125, + "uvOverlap": 0.0, + "texelDensityMedian": 61.97425923665604, + "texelDensityP5": 57.66165269744736, + "texelDensityP95": 113.44982327717632, + "texelDensitySpread": 1.9675090457856172, + "baseColorImage": "ball_bake", + "baseColorSize": [ + 256, + 256 + ], + "customNormals": false + } + }, + { + "name": "audit: texture and UV facts", + "ok": true, + "detail": { + "triangles": 2208, + "vertices": 4512, + "weldedVertices": 1106, + "extent": [ + 2.000001, + 2.000002, + 2.0 + ], + "surfaceArea": 12.521572614010894, + "degenerateTriangles": 0, + "edges": 3312, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "collapsedTriangles": 0, + "shells": 1, + "shellTriangles": [ + 2208 + ], + "uvIslands": 1, + "uvFlippedTriangles": 0, + "uvZeroAreaTriangles": 0, + "uvOutsideUnitTriangles": 0, + "uvCoverage": 0.95831298828125, + "uvOverlap": 0.0, + "texelDensityMedian": 61.97425923665604, + "texelDensityP5": 57.66165269744736, + "texelDensityP95": 113.44982327717632, + "texelDensitySpread": 1.9675090457856172, + "baseColorImage": "ball_bake", + "baseColorSize": [ + 256, + 256 + ], + "customNormals": false + } + }, + { + "name": "repair: accepted as one undo step", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-2", + "action": "brokkr_mesh_polish.repair", + "status": "accepted", + "message": "Operator brokkr_mesh_polish.repair finished.", + "objectName": "", + "requestedBy": "test/driver", + "note": "", + "undoLabel": "Brokkr test/driver: brokkr_mesh_polish.repair live-2", + "lookPath": "", + "hostResult": "{\"object\":\"Ball\",\"changes\":{\"welded\":3406,\"degenerateFacesRemoved\":0,\"looseEdgesRemoved\":0,\"looseVertsRemoved\":0,\"shellsRemoved\":0,\"holesFilled\":0},\"before\":{\"triangles\":2208,\"vertices\":4512,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1},\"after\":{\"triangles\":2208,\"vertices\":1106,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1}}", + "observedAt": "2026-12-01T00:06:45.524772+00:00" + } + }, + { + "name": "repair: welds the torn vertices", + "ok": true, + "detail": { + "object": "Ball", + "changes": { + "welded": 3406, + "degenerateFacesRemoved": 0, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0 + }, + "before": { + "triangles": 2208, + "vertices": 4512, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "shells": 1 + }, + "after": { + "triangles": 2208, + "vertices": 1106, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "shells": 1 + } + } + }, + { + "name": "repair: every edge has two faces again", + "ok": true, + "detail": 2256 + }, + { + "name": "delight: accepted, new packed image on the material", + "ok": true, + "detail": "Operator brokkr_mesh_polish.delight finished." + }, + { + "name": "delight: finds the baked light", + "ok": true, + "detail": { + "image": "ball_bake", + "newImage": "ball_bake.delit", + "objects": [ + "Ball" + ], + "explainedByLight": { + "before": 0.9722586649734903, + "after": 0.005096664890544278 + }, + "before": { + "upDownLuminanceRatio": 2.5686425388668988, + "occlusionCorrelation": 0.0 + }, + "after": { + "upDownLuminanceRatio": 1.0190418174045521, + "occlusionCorrelation": 0.0 + }, + "gain": { + "min": 0.9849698054726783, + "median": 1.454503966956526, + "max": 3.0, + "clamped": 0.05147808358817533 + } + } + }, + { + "name": "delight: levels top against bottom", + "ok": true, + "detail": [ + 3.2905027932960893, + 1.119760513305664 + ] + }, + { + "name": "orient: long on Y, thin on Z, scaled to the length, centred", + "ok": true, + "detail": [ + [ + 4.0, + 12.0, + 2.000000476837158 + ], + { + "objects": [ + "Slab" + ], + "scale": 4.000000308302869, + "extent": [ + 4.0, + 12.0, + 2.0 + ], + "mirrorError": { + "X": 7.4458642458520986e-09, + "Y": 7.225481440456122e-09, + "Z": 1.962464589014781e-09 + } + } + ] + }, + { + "name": "orient: reports the mirror error of a symmetric body as small", + "ok": true, + "detail": { + "X": 7.4458642458520986e-09, + "Y": 7.225481440456122e-09, + "Z": 1.962464589014781e-09 + } + }, + { + "name": "cut fixture is one closed skin", + "ok": true, + "detail": { + "triangles": 28, + "vertices": 16, + "weldedVertices": 16, + "extent": [ + 2.0, + 2.0, + 3.0 + ], + "surfaceArea": 28.605887413024902, + "degenerateTriangles": 0, + "edges": 42, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "collapsedTriangles": 0, + "shells": 1, + "shellTriangles": [ + 28 + ], + "uvIslands": 1, + "uvFlippedTriangles": 0, + "uvZeroAreaTriangles": 28, + "uvOutsideUnitTriangles": 0, + "uvCoverage": 0.0, + "uvOverlap": 0.0, + "baseColorImage": "", + "baseColorSize": [ + 0, + 0 + ], + "customNormals": false + } + }, + { + "name": "cut_parts: accepted, one undo step, the fused object is replaced", + "ok": true, + "detail": "Operator brokkr_mesh_polish.cut_parts finished." + }, + { + "name": "cut_parts: the knob is cut at the crease and rooted at the centre of the cut", + "ok": true, + "detail": { + "name": "Block.knob", + "triangles": 12, + "capTriangles": 2, + "cutEdges": 4, + "root": [ + 0.0, + 0.0, + 1.0 + ], + "cutNormal": [ + 0.0, + 0.0, + 1.0 + ], + "cutRadius": 0.5757359266281128, + "joint": "Block.knob.joint" + } + }, + { + "name": "cut_parts: the knob hangs from the body and has not moved", + "ok": true, + "detail": null + }, + { + "name": "cut_parts: both sides of the cut are capped (closed shells)", + "ok": true, + "detail": { + "Block.body": [ + 0, + 1 + ], + "Block.knob": [ + 0, + 1 + ] + } + }, + { + "name": "cut_parts: caps carry the cap material and a joint sits at the root", + "ok": true, + "detail": "Block.knob.joint" + }, + { + "name": "cut_parts: one part is refused with nothing changed", + "ok": true, + "detail": "Error: Cutting needs seeds for at least two parts." + }, + { + "name": "pick: names the surface point under (u, v) of a picture of that shape", + "ok": true, + "detail": { + "hit": true, + "object": "Sign", + "point": [ + -1.0, + 0.0, + 5.0 + ], + "normal": [ + 0.0, + 0.0, + 1.0 + ] + } + }, + { + "name": "pick: off the surface is a miss, not an error", + "ok": true, + "detail": { + "hit": false + } + }, + { + "name": "scrub_markings: accepted, the lettering inside the sphere is gone", + "ok": true, + "detail": { + "report": { + "object": "Sign", + "image": "sign_paint", + "newImage": "sign_paint.scrubbed", + "regionTexels": 1612, + "scrubbedTexels": 1130 + }, + "inkInsideBefore": 192, + "inkInsideAfter": 0 + } + }, + { + "name": "scrub_markings: nothing outside the sphere is touched (to the 8 bits the image stores)", + "ok": true, + "detail": "sign_paint.scrubbed" + }, + { + "name": "scrub_markings: a sphere off the surface is refused", + "ok": true, + "detail": "Error: No surface lies inside the sphere." + }, + { + "name": "a bound miss is denied by Brokkr's table before the operator runs", + "ok": true, + "detail": "max_gain must be between 1 and 8." + } + ], + "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" + ], + "delight": { + "report": { + "image": "ball_bake", + "newImage": "ball_bake.delit", + "objects": [ + "Ball" + ], + "explainedByLight": { + "before": 0.9722586649734903, + "after": 0.005096664890544278 + }, + "before": { + "upDownLuminanceRatio": 2.5686425388668988, + "occlusionCorrelation": 0.0 + }, + "after": { + "upDownLuminanceRatio": 1.0190418174045521, + "occlusionCorrelation": 0.0 + }, + "gain": { + "min": 0.9849698054726783, + "median": 1.454503966956526, + "max": 3.0, + "clamped": 0.05147808358817533 + } + }, + "ratioBefore": 3.2905027932960893, + "ratioAfter": 1.119760513305664 + }, + "cut": { + "body": "Block.body", + "parts": [ + { + "name": "Block.body", + "triangles": 20, + "capTriangles": 2, + "cutEdges": 4, + "root": [ + 0.0, + 0.0, + 0.0 + ], + "cutNormal": [ + 0.0, + 0.0, + 1.0 + ], + "cutRadius": 0.5757359266281128 + }, + { + "name": "Block.knob", + "triangles": 12, + "capTriangles": 2, + "cutEdges": 4, + "root": [ + 0.0, + 0.0, + 1.0 + ], + "cutNormal": [ + 0.0, + 0.0, + 1.0 + ], + "cutRadius": 0.5757359266281128, + "joint": "Block.knob.joint" + } + ] + }, + "scrub": { + "report": { + "object": "Sign", + "image": "sign_paint", + "newImage": "sign_paint.scrubbed", + "regionTexels": 1612, + "scrubbedTexels": 1130 + }, + "inkInsideBefore": 192, + "inkInsideAfter": 0 + }, + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/test_mesh_polish.py b/surfaces/blender/tests/test_mesh_polish.py new file mode 100644 index 0000000..7205f81 --- /dev/null +++ b/surfaces/blender/tests/test_mesh_polish.py @@ -0,0 +1,390 @@ +"""Mesh polish tests. No Blender: the arithmetic in brokkr_mesh_polish/core.py on small hand-built meshes and +textures, the host action file against Brokkr's own checker, and the turntable recipe against the action table. + +Run: python3 -m unittest discover -s surfaces/blender/tests -v (needs numpy; skipped without it) +The operators around this arithmetic are exercised in a real Blender by tests/live/mesh_polish.py. + +Bounds follow lodur:ruling:deterministic-bound-margin: each sits at the geometric mean of the shipped reading +and the reading of the nearest mutant named beside it, and both are at least 1.2 away. +""" +from __future__ import annotations + +import importlib.util +import json +import math +import sys +import types +import unittest +from pathlib import Path + +SURFACE = Path(__file__).resolve().parents[1] +package = types.ModuleType("brokkr_bridge") +package.__path__ = [str(SURFACE / "brokkr_bridge")] +sys.modules.setdefault("brokkr_bridge", package) +from brokkr_bridge import action_table as at # noqa: E402 + +try: + import numpy as np +except ImportError: # pragma: no cover + np = None + + +def load(name: str, path: Path): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +turntable = load("turntable_recipe", SURFACE / "tools" / "turntable_recipe.py") +core = load("brokkr_mesh_polish_core", SURFACE / "brokkr_mesh_polish" / "core.py") if np is not None else None + + +def quad_strip(count: int, fold_after: int | None = None): + """count unit quads along x as 2 * count triangles, every triangle with its own three vertices (as a glTF + import leaves a seamed mesh). After fold_after quads the strip turns straight up: a 90 degree concave fold + seen from above.""" + V, T = [], [] + for i in range(count): + def at_station(s): + if fold_after is None or s <= fold_after: + return (float(s), 0.0) + return (float(fold_after), float(s - fold_after)) + (x0, z0), (x1, z1) = at_station(i), at_station(i + 1) + corners = [(x0, 0.0, z0), (x1, 0.0, z1), (x1, 1.0, z1), (x0, 1.0, z0)] + for tri in ((0, 1, 2), (0, 2, 3)): + T.append([len(V), len(V) + 1, len(V) + 2]) + V.extend(corners[k] for k in tri) + return np.array(V, dtype=float), np.array(T, dtype=np.int64) + + +@unittest.skipIf(np is None, "numpy is not installed") +class TopologyTests(unittest.TestCase): + def test_weld_joins_split_vertices_so_only_the_rim_is_open(self): + V, T = quad_strip(3) + _, TW = core.weld(V, T, 1e-6) + census = core.edge_census(TW) + self.assertEqual(census["boundaryEdges"], 8) # the rim of a 3 x 1 strip; unwelded, all 18 edges are open + self.assertEqual(census["nonManifoldEdges"], 0) + self.assertEqual(len(np.unique(core.triangle_components(TW))), 1) + + def test_three_triangles_on_one_edge_are_non_manifold(self): + V = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1]], dtype=float) + T = np.array([[0, 1, 2], [0, 1, 3], [0, 1, 4]]) + self.assertEqual(core.edge_census(T)["nonManifoldEdges"], 1) + report = core.audit(V, T, None) + self.assertEqual((report["nonManifoldEdges"], report["shells"], report["triangles"]), (1, 1, 3)) + + def test_separate_pieces_are_separate_shells(self): + V, T = quad_strip(2) + V2 = np.concatenate([V, V + [0, 5, 0]]) + T2 = np.concatenate([T, T + len(V)]) + report = core.audit(V2, T2, None) + self.assertEqual(report["shells"], 2) + self.assertEqual(report["shellTriangles"], [4, 4]) + + def test_components_follow_long_chains(self): + pairs = np.array([[i, i + 1] for i in range(999)]) + self.assertEqual(len(np.unique(core.components(1000, pairs[::-1]))), 1) + self.assertEqual(len(np.unique(core.components(1000, pairs[:500]))), 500) + + +@unittest.skipIf(np is None, "numpy is not installed") +class UvTests(unittest.TestCase): + SQUARE_V = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]], dtype=float) + SQUARE_T = np.array([[0, 1, 2], [0, 2, 3]]) + SQUARE_UV = np.array([[[0, 0], [1, 0], [1, 1]], [[0, 0], [1, 1], [0, 1]]], dtype=float) + + def test_a_square_filling_the_texture_has_full_coverage_no_overlap_and_density_of_the_texture_size(self): + report = core.audit(self.SQUARE_V, self.SQUARE_T, self.SQUARE_UV, texture_size=1024, raster=128) + self.assertAlmostEqual(report["uvCoverage"], 1.0, places=2) + self.assertLess(report["uvOverlap"], 0.02) # only texel centres exactly on the shared diagonal + self.assertAlmostEqual(report["texelDensityMedian"], 1024.0, places=3) + self.assertAlmostEqual(report["texelDensitySpread"], 1.0, places=6) + self.assertEqual((report["uvIslands"], report["uvFlippedTriangles"]), (1, 0)) + + def test_two_triangles_on_the_same_texels_overlap(self): + stacked = np.array([self.SQUARE_UV[0], self.SQUARE_UV[0]]) + report = core.audit(self.SQUARE_V, self.SQUARE_T, stacked, texture_size=1024, raster=128) + self.assertGreater(report["uvOverlap"], 0.98) + + def test_a_mirrored_island_counts_as_flipped_and_half_the_area_doubles_nothing_but_density(self): + mirrored = self.SQUARE_UV.copy() + mirrored[..., 0] = 1 - mirrored[..., 0] + self.assertEqual(core.audit(self.SQUARE_V, self.SQUARE_T, mirrored, 1024, raster=64)["uvFlippedTriangles"], 2) + half = core.audit(self.SQUARE_V, self.SQUARE_T, self.SQUARE_UV * 0.5, 1024, raster=64) + self.assertAlmostEqual(half["texelDensityMedian"], 512.0, places=3) + self.assertAlmostEqual(half["uvCoverage"], 0.25, places=2) + + def test_rasterize_gives_each_texel_its_triangle_and_weights(self): + owner, bary, cover = core.rasterize(self.SQUARE_UV, 8) + self.assertEqual(owner[0, 7], 0) # low v, high u: the first triangle + self.assertEqual(owner[7, 0], 1) + self.assertTrue(np.allclose(bary.sum(axis=2)[owner >= 0], 1.0, atol=1e-5)) + position = core.interpolate(owner, bary, self.SQUARE_V[self.SQUARE_T]) + self.assertTrue(np.allclose(position[2, 5, :2], [(5 + 0.5) / 8, (2 + 0.5) / 8], atol=1e-5)) + + +@unittest.skipIf(np is None, "numpy is not installed") +class OrientTests(unittest.TestCase): + def test_principal_frame_puts_the_long_side_on_x_and_the_thin_side_on_z(self): + V, T = quad_strip(6) # 6 x 1 x 0 + turn = np.array([[0.36, 0.48, -0.8], [-0.8, 0.6, 0.0], [0.48, 0.64, 0.6]]) # a rotation + centre, R = core.principal_frame(V @ turn.T + [3, -2, 5], T) + local = (V @ turn.T + [3, -2, 5] - centre) @ R.T + extent = local.max(axis=0) - local.min(axis=0) + # the diagonal split of each quad skews the area-weighted axes by under a degree + self.assertTrue(np.allclose(extent, [6, 1, 0], atol=0.08)) + self.assertLess(extent[2], 1e-9) + self.assertAlmostEqual(float(np.linalg.det(R)), 1.0, places=9) + + def test_mirror_error_tells_a_symmetric_cloud_from_a_lopsided_one(self): + rng = np.random.default_rng(1) + half = rng.random((400, 3)) + symmetric = np.concatenate([half, half * [-1, 1, 1]]) + lopsided = np.concatenate([half, half * [-0.3, 1, 1] - [0.4, 0, 0]]) + shipped, mutant = core.mirror_error(symmetric, 0), core.mirror_error(lopsided, 0) + # shipped 0.0 exactly (every mirrored sample is itself a point); the lopsided cloud reads 0.0426 + self.assertEqual(shipped, 0.0) + self.assertGreater(mutant, 0.0426 / 1.2) + + +@unittest.skipIf(np is None, "numpy is not installed") +class PartTests(unittest.TestCase): + def grown(self, crease_cost: float): + V, T = quad_strip(10, fold_after=7) + _, TW = core.weld(V, T, 1e-6) + pairs = core.face_adjacency(TW) + costs = core.crease_costs(V, T, pairs, crease_cost) + part, cost = core.grow_parts(len(T), pairs, costs, [(0, 0), (len(T) - 1, 1)]) + return part, cost + + def test_parts_stop_at_a_sharp_concave_crease(self): + part, _ = self.grown(40.0) + self.assertEqual(part.tolist(), [0] * 14 + [1] * 6) # the fold is after quad 7: 14 triangles before it + + def test_without_crease_cost_parts_split_by_distance_alone(self): + part, _ = self.grown(0.0) + self.assertEqual(part.tolist(), [0] * 10 + [1] * 10) + + def test_a_convex_fold_costs_nothing(self): + V, T = quad_strip(10, fold_after=7) + V[:, 2] *= -1 # the same strip folded down, normals unchanged: convex seen from the side they face + _, TW = core.weld(V, T, 1e-6) + pairs = core.face_adjacency(TW) + part, _ = core.grow_parts(len(T), pairs, core.crease_costs(V, T, pairs, 40.0), [(0, 0), (len(T) - 1, 1)]) + self.assertEqual(int((part == 0).sum()), 10) + + def test_a_bowl_of_gentle_folds_costs_far_less_than_one_sharp_crease_of_the_same_turn(self): + def crease_total(turns): # a strip of quads that turns upward by these degrees after each quad + V, T, x, z, heading = [], [], 0.0, 0.0, 0.0 + for turn in [0.0] + turns: + heading += math.radians(turn) + x1, z1 = x + math.cos(heading), z + math.sin(heading) + corners = [(x, 0.0, z), (x1, 0.0, z1), (x1, 1.0, z1), (x, 1.0, z)] + for tri in ((0, 1, 2), (0, 2, 3)): + T.append([len(V), len(V) + 1, len(V) + 2]) + V.extend(corners[k] for k in tri) + x, z = x1, z1 + V, T = np.array(V), np.array(T, dtype=np.int64) + _, TW = core.weld(V, T, 1e-6) + pairs = core.face_adjacency(TW) + return float((core.crease_costs(V, T, pairs, 1.0) - core.crease_costs(V, T, pairs, 0.0)).sum()) + + sharp, gentle = crease_total([90.0]), crease_total([10.0] * 9) + # shipped ratio 9.0 (the square: 0.5 ** 2 against 9 * (1 / 18) ** 2); a cost linear in the fold reads 1.0. Bound 3. + self.assertGreater(sharp / gentle, 3.0 * 1.2) + self.assertAlmostEqual(sharp, 0.25, places=9) + + def test_unseeded_shells_are_unreached_and_several_seeds_may_name_one_part(self): + V, T = quad_strip(2) + V2, T2 = np.concatenate([V, V + [0, 5, 0]]), np.concatenate([T, T + len(V)]) + _, TW = core.weld(V2, T2, 1e-6) + pairs = core.face_adjacency(TW) + part, cost = core.grow_parts(len(T2), pairs, core.crease_costs(V2, T2, pairs, 1.0), [(0, 0), (3, 0)]) + self.assertEqual(part.tolist(), [0, 0, 0, 0, -1, -1, -1, -1]) + self.assertTrue(np.isinf(cost[4:]).all()) + + def test_seed_text(self): + self.assertEqual(core.parse_seeds("hull=0,0,0; pod 1=1,-2.5,3e-1;"), [("hull", (0.0, 0.0, 0.0)), ("pod 1", (1.0, -2.5, 0.3))]) + for bad in ("", "hull", "hull=1,2", "=1,2,3", "hull=a,b,c"): + with self.assertRaises(ValueError): + core.parse_seeds(bad) + + +@unittest.skipIf(np is None, "numpy is not installed") +class DelightTests(unittest.TestCase): + """A synthetic bake: 40000 surface samples, pale paint with a tenth of it dark machinery (same hue), lit by + a sky brighter above than below and dimmed by occlusion.""" + + def setUp(self): + rng = np.random.default_rng(7) + count = 40000 + normals = rng.normal(size=(count, 3)) + self.normals = normals / np.linalg.norm(normals, axis=1, keepdims=True) + self.occlusion = rng.uniform(0.1, 1.0, count) + self.light = (0.55 + 0.45 * self.normals[:, 2]) * self.occlusion ** 0.7 + 0.05 + self.paint = np.where(rng.random(count) < 0.1, 0.08, 0.8) + self.rgb = (self.paint * self.light)[:, None] * np.array([1.0, 0.97, 0.9]) + self.basis = core.shading_basis(self.normals, self.occlusion) + self.log_l = np.log(core.luminance(self.rgb) + 1e-4) + self.clusters = core.chroma_clusters(self.rgb, 1) + + def delit(self, weights): + gain = core.delight_gain(self.basis, weights, 1.0, 8.0) + return np.log(core.luminance(self.rgb * gain[:, None]) + 1e-4) + + def test_the_fit_finds_the_light_and_dividing_it_out_levels_up_and_down(self): + weights, explained = core.fit_shading(self.log_l, self.basis, self.clusters) + before = core.lighting_signature(self.log_l, self.normals, self.occlusion) + after = core.lighting_signature(self.delit(weights), self.normals, self.occlusion) + self.assertGreater(explained, 0.2) + # up/down ratio: shipped 1.029; with no correction (a gain of 1) 3.323. Bound sqrt(1.029 * 3.323) = 1.849. + self.assertGreater(before["upDownLuminanceRatio"], 1.849 * 1.2) + self.assertLess(after["upDownLuminanceRatio"], 1.849 / 1.2) + # occlusion correlation: shipped 0.0032; uncorrected 0.356. Bound sqrt(0.0032 * 0.356) = 0.0337. + self.assertGreater(before["occlusionCorrelation"], 0.0337 * 1.2) + self.assertLess(abs(after["occlusionCorrelation"]), 0.0337 / 1.2) + + def test_dark_paint_in_crevices_is_not_read_as_shadow(self): + # All the dark machinery sits in the occluded third. A mean fit (expectile 0.5) reads it as shadow and + # overstates the occlusion weight; the envelope fit follows the pale paint. + crevice = self.occlusion < 0.4 + paint = np.where(crevice & (np.random.default_rng(3).random(len(crevice)) < 0.6), 0.08, 0.8) + rgb = (paint * self.light)[:, None] * np.array([1.0, 0.97, 0.9]) + log_l = np.log(core.luminance(rgb) + 1e-4) + true_weight = 0.7 # light ~ occlusion ** 0.7, up to the small ambient floor + envelope, _ = core.fit_shading(log_l, self.basis, self.clusters) + mean, _ = core.fit_shading(log_l, self.basis, self.clusters, expectile=0.5) + # occlusion weight: shipped 0.921, mean-fit mutant 1.502. Bound sqrt(0.921 * 1.502) = 1.176. + self.assertLess(envelope[-1], 1.176 / 1.2) + self.assertGreater(mean[-1], 1.176 * 1.2) + self.assertGreater(envelope[-1], true_weight * 0.8) + + def test_gain_leaves_the_lit_side_alone_and_respects_the_limit(self): + weights, _ = core.fit_shading(self.log_l, self.basis, self.clusters) + gain = core.delight_gain(self.basis, weights, 1.0, 3.0) + self.assertLessEqual(float(gain.max()), 3.0) + self.assertGreaterEqual(float(gain.min()), 1 / 3.0 - 1e-12) + light = self.basis @ weights + reference = np.abs(light - np.percentile(light, 90)) < 0.01 # the surface the light favoured + self.assertTrue(np.allclose(gain[reference], 1.0, atol=0.011)) + self.assertGreater(float(np.median(gain[self.occlusion < 0.3])), 1.5) # shaded surface is raised + self.assertTrue(np.allclose(core.delight_gain(self.basis, weights, 0.0, 3.0), 1.0)) + + def test_flat_paint_shows_no_light(self): + flat = np.tile([0.5, 0.4, 0.3], (len(self.normals), 1)) * np.random.default_rng(5).uniform(0.9, 1.1, (len(self.normals), 1)) + _, explained = core.fit_shading(np.log(core.luminance(flat)), self.basis, core.chroma_clusters(flat, 1)) + self.assertLess(explained, 0.01) + + def test_chroma_clusters_ignore_brightness(self): + teal, yellow = np.array([0.1, 0.4, 0.45]), np.array([0.8, 0.7, 0.1]) + shade = np.random.default_rng(2).uniform(0.1, 1.0, (200, 1)) + labels = core.chroma_clusters(np.concatenate([teal * shade, yellow * shade]), 2) + self.assertEqual(len(set(labels[:200])), 1) + self.assertEqual(len(set(labels[200:])), 1) + self.assertNotEqual(labels[0], labels[200]) + + def test_srgb_round_trip(self): + values = np.linspace(0, 1, 101) + self.assertTrue(np.allclose(core.linear_to_srgb(core.srgb_to_linear(values)), values, atol=1e-6)) + + +@unittest.skipIf(np is None, "numpy is not installed") +class TextureFillTests(unittest.TestCase): + def test_push_pull_fills_a_hole_from_its_surroundings_and_keeps_known_texels(self): + image = np.zeros((32, 32, 3), dtype=np.float32) + image[:, :16] = [0.2, 0.4, 0.6] + image[:, 16:] = [0.6, 0.4, 0.2] + known = np.ones((32, 32), dtype=bool) + known[10:20, 2:10] = False + holed = image.copy() + holed[~known] = 9.0 + filled = core.push_pull(holed, known) + self.assertTrue(np.array_equal(filled[known], image[known])) + self.assertTrue(np.allclose(filled[12:18, 3:8], [0.2, 0.4, 0.6], atol=0.05)) + + def test_push_pull_without_a_hole_or_without_anything_known_returns_the_image(self): + image = np.random.default_rng(0).random((8, 8, 3)).astype(np.float32) + self.assertTrue(np.array_equal(core.push_pull(image, np.ones((8, 8), dtype=bool)), image)) + self.assertTrue(np.array_equal(core.push_pull(image, np.zeros((8, 8), dtype=bool)), image)) + + def test_marking_mask_takes_the_ink_and_leaves_the_panel(self): + panel = np.full((40, 40, 3), [0.1, 0.35, 0.4], dtype=np.float32) + panel += np.random.default_rng(0).normal(0, 0.01, panel.shape).astype(np.float32) + panel[18:22, 8:30] = [0.85, 0.75, 0.2] # a stroke of yellow lettering + region = np.zeros((40, 40), dtype=bool) + region[5:35, 5:35] = True + mask = core.marking_mask(panel, region, 0.25, 1) + self.assertTrue(mask[18:22, 8:30].all()) + self.assertEqual(int(mask.sum()), 4 * 22 + 2 * 22 + 2 * 4) # the stroke grown by one texel edgewise, nothing else + outside = np.zeros((40, 40), dtype=bool) + self.assertFalse(core.marking_mask(panel, outside, 0.25, 1).any()) + + def test_box_blur_keeps_a_flat_field_and_spreads_a_point(self): + flat = np.full((9, 9), 0.5) + self.assertTrue(np.allclose(core.box_blur(flat, 2), 0.5)) + point = np.zeros((9, 9)) + point[4, 4] = 1.0 + blurred = core.box_blur(point, 1) + self.assertTrue(np.allclose(blurred[3:6, 3:6], 1 / 9)) + self.assertAlmostEqual(float(blurred.sum()), 1.0, places=9) + + +class HostFileTests(unittest.TestCase): + """brokkr_actions.json is the add-on's whole contract with Brokkr: it must pass Brokkr's own checker.""" + + def setUp(self): + self.document = json.loads((SURFACE / "brokkr_mesh_polish" / "brokkr_actions.json").read_text(encoding="utf-8")) + + def test_brokkr_admits_the_file(self): + at.check_host(self.document, at.table()["charsets"]) + + def test_every_row_names_an_operator_and_property_the_add_on_defines(self): + source = (SURFACE / "brokkr_mesh_polish" / "__init__.py").read_text(encoding="utf-8") + 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, f"{row['name']}.{field['name']}") + + def test_a_valid_intent_is_admitted_and_a_bound_miss_is_refused(self): + host = [{**row, "host": "brokkr_mesh_polish"} for row in self.document["actions"]] + envelope = {"schema": "brokkr.blender.command_intent.v0", "commandId": "t-1", "requestedBy": "test/driver"} + admitted = at.validate({**envelope, "action": "brokkr_mesh_polish.delight", "object_name": "Hull"}, host) + self.assertEqual(admitted["object_name"], "Hull") + with self.assertRaises(at.IntentInvalid): + at.validate({**envelope, "action": "brokkr_mesh_polish.delight", "object_name": "Hull", "max_gain": 9}, host) + with self.assertRaises(at.IntentInvalid): + at.validate({**envelope, "action": "brokkr_mesh_polish.cut_parts", "object_name": "Hull"}, host) # seeds required + + +class TurntableRecipeTests(unittest.TestCase): + def test_every_pose_looks_at_the_origin_with_z_up(self): + for azimuth in (0, 45, 90, 200, 315): + for elevation in (-90, -30, 0, 25, 90): + location, (rx, _, rz) = turntable.camera_pose(azimuth, elevation, 5.0) + forward = (-math.sin(rx) * math.sin(rz), math.sin(rx) * math.cos(rz), -math.cos(rx)) # camera -Z after XYZ Euler (rx, 0, rz) + for axis in range(3): + self.assertAlmostEqual(forward[axis], -location[axis] / 5.0, places=9) + + def test_every_intent_of_a_recipe_is_admitted_by_the_action_table(self): + for look in ("lit", "flat"): + recipe = turntable.recipe("ship.blend", "out", "ship", 0.7, 8, 25.0, 512, "BLENDER_EEVEE", look, "nibu/hands") + renders = [i for i in recipe["intents"] if i["action"] == "renderStill"] + self.assertEqual(len(renders), 10) # eight around, top, bottom + self.assertEqual(len({i["outputPath"] for i in renders}), 10) + for index, intent in enumerate(recipe["intents"]): + at.validate({"schema": "brokkr.blender.command_intent.v0", "commandId": f"t-{index}", + "requestedBy": recipe["requestedBy"], **intent}, []) + + def test_two_recipes_with_the_same_numbers_frame_identically(self): + a = turntable.recipe("a.blend", "out", "a", 0.7, 4, 25.0, 512, "CYCLES", "lit", "nibu/hands") + b = turntable.recipe("b.blend", "out", "b", 0.7, 4, 25.0, 512, "CYCLES", "lit", "nibu/hands") + moves = lambda r: [i for i in r["intents"] if i["action"] in ("setObjectTransform", "setCamera")] + self.assertEqual(moves(a), moves(b)) + + +if __name__ == "__main__": + unittest.main() From 0921bec89babe7ebb75e10ebf3235130b890a05b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 01:08:05 +0100 Subject: [PATCH 50/63] docs: mesh polish actions, the headless intent runner and the turntable recipe Co-Authored-By: Claude Fable 5.2 --- README.md | 3 + surfaces/blender/docs/install.md | 3 + surfaces/blender/docs/mesh-polish.md | 172 +++++++++++++++++++++++++++ 3 files changed, 178 insertions(+) create mode 100644 surfaces/blender/docs/mesh-polish.md diff --git a/README.md b/README.md index e0be8d0..90f7c57 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,9 @@ broker. - `surfaces/blender/brokkr_bridge`: Blender add-on target backed by CultLib's Python CultMesh node/server, with an optional debug export probes. +- `surfaces/blender/brokkr_mesh_polish`: Blender host add-on that measures and polishes generated meshes + (audit, repair, orient, delight, scrub markings, cut parts), agent-callable through Brokkr's host actions; + `surfaces/blender/tools` runs intent recipes in a background Blender (`surfaces/blender/docs/mesh-polish.md`). - `brokkr-command`: .NET CLI that writes one Unity command intent through the project's directory store and reports the editor's receipt (`docs/provider-contract.md`). - `brokkr-daemon`: Rust CLI that emits Brokkr's provider advertisement and diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 9ef449e..2659f4d 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -290,6 +290,9 @@ with nothing pushed; an argument Blender will not convert, or an `ERROR` report 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 ` 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 diff --git a/surfaces/blender/docs/mesh-polish.md b/surfaces/blender/docs/mesh-polish.md new file mode 100644 index 0000000..93b8fac --- /dev/null +++ b/surfaces/blender/docs/mesh-polish.md @@ -0,0 +1,172 @@ +# Mesh polish for generated meshes + +`surfaces/blender/brokkr_mesh_polish` is a Blender add-on that measures and polishes meshes made by image-to-3D +generators (Tripo and its kin): one fused or many-shelled skin, vertices split at every UV seam, an arbitrary +orientation, a unit-cube scale, and a base colour texture with the concept render's lighting and lettering baked in. + +It is a host add-on in Brokkr's sense (`install.md`, "Host add-on actions"): it imports nothing from Brokkr, and +`brokkr_actions.json` beside its `__init__.py` lists the operators agents may run. Every field, type, bound and +default is in that file; `brokkr-ctl blender send --help --store ` prints it for a live session. The +arithmetic is `core.py` (numpy only) and is tested without Blender. + +Every action writes a JSON report, returned in the receipt's `hostResult`. Actions that change the scene are one +undo step each. Lengths are in scene units; points and directions are world-space. + +## Running it + +In a person's Blender: enable the add-on beside Brokkr and press `Reload Host Actions` in the Brokkr panel; the +actions then arrive as intents like any other. + +With no Blender open, `surfaces/blender/tools/run_intents.py` runs a recipe (a JSON list of intents) in a +background Blender through the same agent turn, and writes the receipts to a file: + +```text +blender --background --factory-startup --python surfaces/blender/tools/run_intents.py -- polish.json +``` + +```json +{"requestedBy": "nibu/hands", "importDir": "work", "outputDir": "work", "hostAddons": ["brokkr_mesh_polish"], + "saveBlend": "work/ship.blend", + "intents": [ + {"action": "importGltf", "filepath": "ship_tripo.glb"}, + {"action": "brokkr_mesh_polish.audit"}, + {"action": "brokkr_mesh_polish.orient", "roll_quarter_turns": 2}, + {"action": "brokkr_mesh_polish.repair", "object_name": "tripo_ab12"}, + {"action": "brokkr_mesh_polish.delight", "object_name": "tripo_ab12", "clusters": 2}, + {"action": "brokkr_mesh_polish.audit"}, + {"action": "exportGltf", "filepath": "ship_polished.glb"}]} +``` + +The runner opens no CultMesh node: receipts go to `.receipts.json` only. It is the human of its own +Blender (it enables the host add-ons, reloads host actions once, opens and saves the `.blend`), and it refuses to +start without private `BLENDER_USER_CONFIG`, `BLENDER_USER_EXTENSIONS` and `BLENDER_USER_SCRIPTS`. Its exit status is +0 when every intent was accepted, 3 when one was not, 2 when the recipe could not run. + +`surfaces/blender/tools/turntable_recipe.py` writes a recipe of Brokkr's own scene actions (`setWorld`, +`createObject`, `setCamera`, `setObjectTransform`, `renderStill`) for an orthographic turntable of a `.blend` whose +subject is centred on the origin. Two recipes with the same numbers frame two files identically, so a before and +an after compare view by view. `--look flat` lights with a uniform white world alone and shows the texture as +stored, baked shadows included; `--look lit` adds a sun. + +A polish pass that works, in order: `audit`, `orient` (render a flat turntable and pick `roll_quarter_turns` and +`flip_forward` by eye), `repair`, `delight`, then `pick` and `scrub_markings` for each patch of lettering, then +`pick` and `cut_parts` when parts must move, `audit` again, `exportGltf`. + +## Actions + +### audit + +Measures one mesh object, or every mesh in the scene. Changes nothing. Topology is counted after welding positions +within 1e-5 of the bounding diagonal, because an imported mesh is split at every UV seam and would otherwise read +as all open edges. + +- `triangles`, `vertices`, `weldedVertices`, `extent`, `surfaceArea`, `degenerateTriangles`. +- `boundaryEdges` (one triangle on the edge: an open rim), `nonManifoldEdges` (three or more), `shells` and + the triangle count of the largest twelve. +- `uvIslands`, `uvFlippedTriangles` (mirrored in UV space), `uvZeroAreaTriangles`, `uvOutsideUnitTriangles`, + `uvCoverage` (share of the texture some triangle covers) and `uvOverlap` (share of covered texels that more + than one triangle covers), both counted at texel centres on a `raster` x `raster` grid. +- `texelDensityMedian`, `P5`, `P95` (texels per unit length for the base colour texture's size, area-weighted) and + `texelDensitySpread` (P95 / P5; 1 is uniform). +- `baseColorImage`, `baseColorSize`, `customNormals`. + +### repair + +Welds coincident vertices (UVs live on face corners, so seams keep their UVs), removes degenerate faces and loose +edges and vertices, optionally deletes shells below `min_shell_area` of the surface, optionally closes holes of up +to `fill_holes_sides` edges, and makes face normals consistent. With `sharp_angle` above 0 the generator's custom +normals are dropped and shading is recomputed: smooth, hard across edges sharper than the angle. + +A filled hole has no place in the UV map: each new face takes one UV point from the old face beside it, so it shows +that texel's colour and adds no UV overlap (it counts in `uvZeroAreaTriangles`). Making normals consistent flips the +winding of shells that faced inward, which mirrors their UVs; `uvFlippedTriangles` can rise. + +Welding does not join shells that merely touch or intersect. A mesh assembled from open, interpenetrating shells +stays one: its open edges and non-manifold edges are reported, not repaired. Closing such a mesh means remeshing it +and rebaking its texture, which this add-on does not do. + +### orient + +Turns every mesh in the scene, as one rigid body, onto its area-weighted principal axes: longest on Y, shortest on +Z, centred on the origin, the longest side scaled to `length` when given. The transform is baked into the mesh data +and the objects are left unparented at identity. Principal axes do not know bow from stern or up from down: +`flip_forward` and `roll_quarter_turns` choose, and `mirrorError` in the report (per axis, 0 is a perfect mirror) +says which plane the body is symmetric across. `principal: false` keeps the current axes and applies only the +turns, the centring and the scale. + +### delight + +Undoes lighting baked into the base colour texture, as far as the surface's own shape explains it. + +For each texel the add-on knows the surface normal and the ambient occlusion there (cosine-weighted rays against +the mesh, per vertex). It fits log luminance as an intercept per hue cluster (`clusters`: how many distinct paints +the texture holds) plus a light term: the order-2 spherical harmonics of the normal and the log of occlusion. The +fit follows the upper envelope of luminance (an expectile regression at 0.85), because within one hue the +brightest paint at a given normal and occlusion shows how much light the bake put there, while darker paint in the +same place, machinery in a crevice of a pale hull, is paint. Texels darker than 4% of the texture's white point are +left out of the fit: they are fill the generator never saw. Each texel is then multiplied by the factor that undoes +the fitted light, relative to the surface the light favoured (the 90th percentile), limited to `max_gain` either +way. The result is a new packed image (`.delit`) swapped into the material; nothing is written to disk. + +The report: `explainedByLight` (share of within-hue luminance variance the light term explains, before and +after), and two model-free readings before and after, over the texels that were judged: +`upDownLuminanceRatio` (up-facing over down-facing surface, 1 is none) and `occlusionCorrelation`. `gain.clamped` +is the share of texels that hit `max_gain`. + +What it cannot do. It removes smooth, shape-following light: sky-over-ground gradients and occlusion darkening. +It does not remove cast shadows, specular highlights, or light the shape does not explain. It cannot tell dark +paint from shadow where a hue has no bright paint at all in some range of occlusion. Texels the generator filled +with black stay black: there is no colour there to recover. It raises shaded paint by gain, so 8-bit noise and +JPEG blocks in dark areas are raised with it. + +### pick + +The surface point seen at `(u, v)` of a camera's frame (`u` across, `v` up, both 0 to 1), with the object and +normal there. `resolution_x` and `resolution_y` are the size of the picture the place was read from, since the +frame's shape follows the picture's. Changes nothing. It turns "the lettering at this place in this render" into a +point that `scrub_markings` or `cut_parts` can take. + +### scrub_markings + +Paints out markings on the base colour texture inside a world-space sphere. Texels of the object's surface inside +the sphere whose colour is further than `tolerance` from the sphere's median colour are the marking; the mask is +widened by `grow` texels, filled with a smooth blend of the unmasked texels of the same region (push-pull), and +given the surrounding texture's grain. The result is a new packed image (`.scrubbed`); successive scrubs +keep one image, not a chain. + +The median colour must be the panel, not the marking: keep the sphere wide enough that lettering is the minority. +Panel lines, rivets and rust inside the sphere that differ from the panel by more than `tolerance` go with the +lettering. The fill is a blend, not a reconstruction: a faint ghost of the removed strokes can remain where the +unmasked source was thin. + +### cut_parts + +Cuts one fused skin into named parts and makes each a separate object that can move. + +`seeds` is `name=x,y,z; name=x,y,z; ...`: points on the surface, several per name allowed; the first name is the +body. Every triangle joins the seed it is cheapest to walk to, where a step costs its length (as a share of the +bounding diagonal) plus `crease_cost` times the square of how concave the fold it crosses is. Parts therefore stop +at sharp concave creases, where one part of a fused skin meets another, and split by distance where there is no +crease. `through` above 0 also seeds the far face of each part off the body, found by a ray inward from each seed +no longer than that share of the diagonal: a thin shell (a petal, a fin) is then held from both faces. + +The mesh is welded and triangulated first. Each part becomes an object `.`; both sides of every cut +are capped with faces of a dark `Polish Cap` material (pinned to one UV point each, as in `repair`); each part off +the body gets its origin at the centre of its cut and is parented to the body without moving; custom properties +`polish_cut_normal` and `polish_cut_radius` record the cut's plane and mean radius. `joint_scale` above 0 adds a +ball of that share of the cut radius at each root, parented to the body. The original object is removed. + +The report gives each part's `triangles`, `capTriangles`, `cutEdges`, `root`, `cutNormal` and `cutRadius`. + +What it cannot do. Seeds decide the parts; a seed on the wrong surface gives a wrong part. Place them from a +render with `pick`, then check where they landed before cutting (a small cube at each seed, rendered, is enough). +Cuts follow triangle edges, so on a coarse mesh they are ragged. Caps are fans across the cut and can fold over on a +cut that is far from planar; they are meant to be hidden by the neighbouring part, not shown. The root is the +centre of the cut, not a designed hinge: it is a sensible pivot to start from. + +## Tests + +- `tests/test_mesh_polish.py`: the arithmetic on hand-built meshes and textures, `brokkr_actions.json` against + Brokkr's own host-file checker, and the turntable recipe against the action table. No Blender; needs numpy. +- `tests/live/mesh_polish.py`: every action through `run_intent` in a background Blender against real bpy + (`mesh_polish.result.json` is the last run, Blender 5.3.0). From 64ffc14e0abe72c039ba99e57738a1bc06a4e0f1 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 02:17:45 +0100 Subject: [PATCH 51/63] run_intents: refuse Blender user directories that are a person's own, or that Blender is not using The guard only checked that the three variables were non-empty. tools/private_dirs.py now refuses a variable set inside %APPDATA%/Blender Foundation, ~/.config/blender or the macOS folder, and a Blender whose own answer for CONFIG, EXTENSIONS or SCRIPTS is not under the variable. (Soul finding run-intents-guard-checks-non-empty, PR 22.) Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tools/private_dirs.py | 44 ++++++++++++++++++++++++++ surfaces/blender/tools/run_intents.py | 12 ++++--- 2 files changed, 51 insertions(+), 5 deletions(-) create mode 100644 surfaces/blender/tools/private_dirs.py diff --git a/surfaces/blender/tools/private_dirs.py b/surfaces/blender/tools/private_dirs.py new file mode 100644 index 0000000..014ef78 --- /dev/null +++ b/surfaces/blender/tools/private_dirs.py @@ -0,0 +1,44 @@ +"""Whether a Blender about to be driven by a script has user directories of its own. Stdlib only. + +A script that enables add-ons or saves preferences in a person's own Blender folders changes her Blender. The +three variables below point Blender at other folders; BLENDER_USER_RESOURCE_PATH does not (Blender 5.3 ignores it). +""" +from __future__ import annotations + +import os +from pathlib import Path +from typing import Callable, Mapping + +VARIABLES = {"BLENDER_USER_CONFIG": "CONFIG", "BLENDER_USER_EXTENSIONS": "EXTENSIONS", "BLENDER_USER_SCRIPTS": "SCRIPTS"} + + +def own_blender_roots(environ: Mapping[str, str], home: str) -> list[Path]: + """Where a person's own Blender keeps its folders on Windows, Linux and macOS, for this environment.""" + roots = [Path(home) / ".config" / "blender", Path(home) / "Library" / "Application Support" / "Blender"] + for variable in ("APPDATA", "XDG_CONFIG_HOME"): + if environ.get(variable): + roots.append(Path(environ[variable]) / ("Blender Foundation" if variable == "APPDATA" else "blender")) + return roots + + +def _inside(path: Path, root: Path) -> bool: + a, b = os.path.normcase(os.path.abspath(path)), os.path.normcase(os.path.abspath(root)) + return a == b or a.startswith(b + os.sep) + + +def refusal(environ: Mapping[str, str], home: str, resource: Callable[[str], str] | None = None) -> str | None: + """None when the three variables are set to folders outside every own-Blender root, and, given Blender's + own answer (resource('CONFIG') and so on, bpy.utils.user_resource), Blender is really using them; otherwise + the sentence to refuse with.""" + for variable, kind in VARIABLES.items(): + value = environ.get(variable) + if not value: + return f"{variable} is not set: run in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories" + for root in own_blender_roots(environ, home): + if _inside(Path(value), root): + return f"{variable} is {value}, inside a person's own Blender folder ({root}): point it at a scratch directory" + if resource is not None: + used = resource(kind) + if not used or not _inside(Path(used), Path(value)): + return f"Blender uses {used or 'no folder'} for {kind}, not {variable} ({value}): refusing to touch it" + return None diff --git a/surfaces/blender/tools/run_intents.py b/surfaces/blender/tools/run_intents.py index 9c06c01..eb09a64 100644 --- a/surfaces/blender/tools/run_intents.py +++ b/surfaces/blender/tools/run_intents.py @@ -8,8 +8,8 @@ rows are checked as in a live session, and each gets a receipt. No CultMesh node written to (default: the recipe's name with .receipts.json) and nowhere else, so nothing here shows in a person's Agents panel. This script is the human of its own Blender: it enables the host add-ons the recipe names, reloads host actions once, and opens and saves the .blend. It refuses to start unless -BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS are set, so it never reads or writes a -person's own Blender folders (docs/install.md). +BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS are set to folders outside a person's own +Blender folders and Blender is really using them (tools/private_dirs.py), so it never reads or writes hers. The recipe: @@ -41,9 +41,11 @@ def fail(message: str) -> None: def main() -> int: - for name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): - if not os.environ.get(name): - fail(f"{name} is not set: run in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") + 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: + fail(refused) arguments = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [] if not arguments: fail("usage: blender --background --factory-startup --python run_intents.py -- []") From 7de1e25e609f2ad41fae577cae33cdb7f229c93b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 02:17:45 +0100 Subject: [PATCH 52/63] brokkr_mesh_polish: repair and cut_parts turn no face; orient keeps the hierarchy; the tests pin the operators Soul falsified PR 22: repair's unconditional recalc_face_normals reversed 4,565 of 23,341 and 15,735 of 28,426 triangles on two further Tripo hulls, which a single-sided material culls. repair now leaves every winding alone; recalc_normals is opt-in and reports windingFlipped. cut_parts no longer recalculates either. Custom shading normals are carried through weld, fill and cut as plain directions and set back, new faces are shaded by their own direction, and delight reads those shading normals instead of winding-derived ones. audit: windingAgainstNormals, and uvMirroredTriangles (texture parity against the shading normals) in place of uvFlippedTriangles, which changed whenever a winding did. orient: object_name scopes it to a root and its descendants; parents and pivots are kept. cut_parts: a mesh with no material keeps a bare first slot, so only caps take the cap material. Tests: 13 more unit tests and 18 more live checks (43 with BROKKR_POLISH_HULLS). The live sphere is now torn, half inside out under outward custom normals. Soul's 26 mutants and 11 of this batch's own all die. Co-Authored-By: Claude Fable 5.2 --- .../blender/brokkr_mesh_polish/__init__.py | 148 ++++- .../brokkr_mesh_polish/brokkr_actions.json | 6 +- surfaces/blender/brokkr_mesh_polish/core.py | 20 +- surfaces/blender/tests/live/mesh_polish.py | 259 +++++++- .../tests/live/mesh_polish.result.json | 585 ++++++++++++++++-- surfaces/blender/tests/test_mesh_polish.py | 115 +++- 6 files changed, 1017 insertions(+), 116 deletions(-) diff --git a/surfaces/blender/brokkr_mesh_polish/__init__.py b/surfaces/blender/brokkr_mesh_polish/__init__.py index af1916c..473550d 100644 --- a/surfaces/blender/brokkr_mesh_polish/__init__.py +++ b/surfaces/blender/brokkr_mesh_polish/__init__.py @@ -45,15 +45,17 @@ def mesh_objects(name: str) -> list: def arrays(obj) -> dict: - """World-space triangle arrays of a mesh object: V, T, UV (per corner, or None), N (vertex normals), - polygon (the polygon each triangle came from).""" + """World-space triangle arrays of a mesh object: V, T, UV (per corner, or None), CN (per corner, the + normals the mesh is shaded with: its custom normals when it has them), N (per vertex, the mean of its + corners' CN) and polygon (the polygon each triangle came from). The normals never come from the winding + alone when the mesh carries custom normals, so a shell wound inside out still reads as it is drawn.""" mesh = obj.data mesh.calc_loop_triangles() count = len(mesh.loop_triangles) V = np.empty(len(mesh.vertices) * 3, dtype=np.float32) mesh.vertices.foreach_get("co", V) - N = np.empty(len(mesh.vertices) * 3, dtype=np.float32) - mesh.vertex_normals.foreach_get("vector", N) + corner = np.empty(len(mesh.loops) * 3, dtype=np.float32) + mesh.corner_normals.foreach_get("vector", corner) T = np.empty(count * 3, dtype=np.int32) mesh.loop_triangles.foreach_get("vertices", T) L = np.empty(count * 3, dtype=np.int32) @@ -62,14 +64,18 @@ def arrays(obj) -> dict: mesh.loop_triangles.foreach_get("polygon_index", P) world = np.array(obj.matrix_world, dtype=np.float64) V = V.reshape(-1, 3).astype(np.float64) @ world[:3, :3].T + world[:3, 3] - N = N.reshape(-1, 3).astype(np.float64) @ np.linalg.inv(world[:3, :3]) + corner = corner.reshape(-1, 3).astype(np.float64) @ np.linalg.inv(world[:3, :3]) + corner /= np.maximum(np.linalg.norm(corner, axis=1, keepdims=True), 1e-30) + CN = corner[L.reshape(-1, 3)] + N = np.zeros((len(V), 3)) + np.add.at(N, T.reshape(-1), CN.reshape(-1, 3)) N /= np.maximum(np.linalg.norm(N, axis=1, keepdims=True), 1e-30) UV = None if mesh.uv_layers.active is not None: flat = np.empty(len(mesh.loops) * 2, dtype=np.float32) mesh.uv_layers.active.uv.foreach_get("vector", flat) UV = flat.reshape(-1, 2).astype(np.float64)[L.reshape(-1, 3)] - return {"V": V, "T": T.reshape(-1, 3).astype(np.int64), "UV": UV, "N": N, "polygon": P} + return {"V": V, "T": T.reshape(-1, 3).astype(np.int64), "UV": UV, "N": N, "CN": CN, "polygon": P} def merged(objects: list) -> dict: @@ -78,6 +84,7 @@ def merged(objects: list) -> dict: offsets = np.cumsum([0] + [len(p["V"]) for p in parts[:-1]]) uv = None if any(p["UV"] is None for p in parts) else np.concatenate([p["UV"] for p in parts]) return {"V": np.concatenate([p["V"] for p in parts]), "N": np.concatenate([p["N"] for p in parts]), + "CN": np.concatenate([p["CN"] for p in parts]), "T": np.concatenate([p["T"] + o for p, o in zip(parts, offsets)]), "UV": uv} @@ -198,7 +205,14 @@ def upsample(field: np.ndarray, height: int, width: int) -> np.ndarray: def pin_uvs(bm, faces) -> None: """Give each new face (a filled hole, a cap) one UV point, taken from an old face beside it, so it shows that texel's colour and takes no area of the texture: a face made by filling has no place in the UV map, - and corners copied from several islands would smear the atlas across it and overlap everything.""" + and corners copied from several islands would smear the atlas across it and overlap everything. The fill + also copies its neighbours' stashed shading normals onto the new corners; those are cleared, so the new + face is shaded by its own direction.""" + kept = bm.loops.layers.float_vector.get(KEPT_NORMAL) + if kept is not None: + for face in faces: + for loop in face.loops: + loop[kept] = (0.0, 0.0, 0.0) layer = bm.loops.layers.uv.active if layer is None: return @@ -218,6 +232,41 @@ def pin_uvs(bm, faces) -> None: loop[layer].uv = anchor +KEPT_NORMAL = "polish_kept_normal" + + +def stash_normals(mesh, bm) -> bool: + """Copy the mesh's custom shading normals onto the bmesh's face corners, as plain vectors, so they survive + edits. Blender stores a custom normal against the automatic normal of its corner; welding or cutting + changes the automatic normals, and the stored ones would then be read as different directions.""" + if "custom_normal" not in mesh.attributes: + return False + flat = np.empty(len(mesh.loops) * 3, dtype=np.float32) + mesh.corner_normals.foreach_get("vector", flat) + normals = flat.reshape(-1, 3) + layer = bm.loops.layers.float_vector.new(KEPT_NORMAL) + for face in bm.faces: + for loop in face.loops: + loop[layer] = normals[loop.index] + return True + + +def restore_normals(mesh, keep: bool = True) -> None: + """Set the stashed vectors back as the mesh's custom normals (a new face's zero vector means automatic), + or with keep False only drop the stash.""" + attribute = mesh.attributes.get(KEPT_NORMAL) + if attribute is None: + return + flat = np.empty(len(mesh.loops) * 3, dtype=np.float32) + attribute.data.foreach_get("vector", flat) + mesh.attributes.remove(attribute) + if keep: + stale = mesh.attributes.get("custom_normal") + if stale is not None: # else a zero vector would keep the stale value instead of meaning automatic + mesh.attributes.remove(stale) + mesh.normals_split_custom_set(flat.reshape(-1, 3).tolist()) + + def cap_surface(): """The dark, rough material of cut faces and joints: what shows in the gap when a part swings away.""" material = bpy.data.materials.get(CAP_MATERIAL) @@ -261,7 +310,7 @@ class BROKKR_MESH_POLISH_OT_audit(PolishOperator): data = arrays(obj) nodes = base_color_nodes(obj) size = max(nodes[0].image.size) if nodes else 0 - entry = core.audit(data["V"], data["T"], data["UV"], size, raster=self.raster) + entry = core.audit(data["V"], data["T"], data["UV"], size, raster=self.raster, CN=data["CN"]) entry["baseColorImage"] = nodes[0].image.name if nodes else "" entry["baseColorSize"] = list(nodes[0].image.size) if nodes else [0, 0] entry["customNormals"] = "custom_normal" in obj.data.attributes @@ -271,7 +320,7 @@ class BROKKR_MESH_POLISH_OT_audit(PolishOperator): class BROKKR_MESH_POLISH_OT_repair(PolishOperator): """Weld coincident vertices (UV seams keep their UVs), drop degenerate and loose geometry, drop shells - below an area share, close small holes, make normals consistent and recompute shading from a sharp angle""" + below an area share, close small holes; on request rewind faces outward or recompute shading from a sharp angle""" bl_idname = "brokkr_mesh_polish.repair" bl_label = "Repair Mesh" object_name: bpy.props.StringProperty(name="Object") @@ -281,20 +330,26 @@ class BROKKR_MESH_POLISH_OT_repair(PolishOperator): description="Delete shells holding less than this share of the surface; 0 keeps all") fill_holes_sides: bpy.props.IntProperty(name="Fill Holes", default=0, min=0, max=1000, description="Close holes of up to this many edges; 0 leaves holes") + recalc_normals: bpy.props.BoolProperty(name="Recalculate Normals", default=False, + description="Rewind each shell so Blender judges it to face outward. Off leaves every face's winding as it is. On an open or intersecting shell the judgement can be wrong, and a face it turns is culled by a single-sided material: read windingFlipped in the report") sharp_angle: bpy.props.FloatProperty(name="Sharp Angle", default=0.0, min=0.0, max=180.0, description="Degrees; above 0, generated custom normals are dropped and edges sharper than this shade hard") def work(self, context): obj = mesh_object(self.object_name) mesh = obj.data - before = core.audit(arrays(obj)["V"], arrays(obj)["T"], None) + start = arrays(obj) + before = core.audit(start["V"], start["T"], None, CN=start["CN"]) bm = bmesh.new() bm.from_mesh(mesh) + stash_normals(mesh, bm) diagonal = (Vector(obj.bound_box[6]) - Vector(obj.bound_box[0])).length counts = {"vertices": len(bm.verts)} + faces = len(bm.faces) if self.weld_fraction > 0: bmesh.ops.remove_doubles(bm, verts=bm.verts[:], dist=diagonal * self.weld_fraction) counts["welded"] = counts.pop("vertices") - len(bm.verts) + counts["facesCollapsedByWeld"] = faces - len(bm.faces) faces = len(bm.faces) bmesh.ops.dissolve_degenerate(bm, edges=bm.edges[:], dist=diagonal * 1e-7) counts["degenerateFacesRemoved"] = faces - len(bm.faces) @@ -323,26 +378,39 @@ class BROKKR_MESH_POLISH_OT_repair(PolishOperator): counts["holesFilled"] = len(filled["faces"]) pin_uvs(bm, filled["faces"]) bmesh.ops.triangulate(bm, faces=[f for f in filled["faces"] if len(f.verts) > 3]) - bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:]) + counts["windingFlipped"] = 0 + if self.recalc_normals: + was = [face.normal.copy() for face in bm.faces] + bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:]) + bm.normal_update() + counts["windingFlipped"] = sum(1 for face, normal in zip(bm.faces, was) if face.normal.dot(normal) < 0) bm.to_mesh(mesh) bm.free() + # Custom normals are stored against each face's own normal: a face that was turned would carry its + # custom normal turned with it, so they cannot outlive a rewind. + drop_custom = self.sharp_angle > 0 or counts["windingFlipped"] > 0 + counts["customNormalsDropped"] = bool(drop_custom and "custom_normal" in mesh.attributes) + if drop_custom and "custom_normal" in mesh.attributes: + mesh.attributes.remove(mesh.attributes["custom_normal"]) + restore_normals(mesh, keep=not drop_custom) if self.sharp_angle > 0: - if "custom_normal" in mesh.attributes: - mesh.attributes.remove(mesh.attributes["custom_normal"]) mesh.polygons.foreach_set("use_smooth", [True] * len(mesh.polygons)) mesh.set_sharp_from_angle(angle=math.radians(self.sharp_angle)) mesh.update() - after = core.audit(arrays(obj)["V"], arrays(obj)["T"], None) + end = arrays(obj) + after = core.audit(end["V"], end["T"], None, CN=end["CN"]) + keys = ("triangles", "vertices", "boundaryEdges", "nonManifoldEdges", "shells", "windingAgainstNormals") return {"object": obj.name, "changes": counts, - "before": {k: before[k] for k in ("triangles", "vertices", "boundaryEdges", "nonManifoldEdges", "shells")}, - "after": {k: after[k] for k in ("triangles", "vertices", "boundaryEdges", "nonManifoldEdges", "shells")}} + "before": {k: before[k] for k in keys}, "after": {k: after[k] for k in keys}} class BROKKR_MESH_POLISH_OT_orient(PolishOperator): - """Turn every mesh in the scene, as one rigid body, onto its principal axes (longest on Y, shortest on Z), - centre it at the origin, scale its longest side to a length, and bake that into the mesh data""" + """Turn an object and everything parented under it (or the whole scene), as one rigid body, onto its + principal axes (longest on Y, shortest on Z), centre it at the origin and scale its longest side to a length. + Rotation and scale are baked into the mesh data; every object keeps its parent and its pivot point""" bl_idname = "brokkr_mesh_polish.orient" bl_label = "Orient Meshes" + object_name: bpy.props.StringProperty(name="Object", description="The root of what to turn: it and its descendants; every object in the scene when empty") length: bpy.props.FloatProperty(name="Length", default=0.0, min=0.0, max=1e6, description="Longest side after scaling, in scene units; 0 keeps the size") flip_forward: bpy.props.BoolProperty(name="Flip Forward", description="Turn half a turn about Z: swap bow and stern") @@ -352,7 +420,17 @@ class BROKKR_MESH_POLISH_OT_orient(PolishOperator): description="Off keeps the current axes and only applies the turns, centre and scale") def work(self, context): - objects = mesh_objects("") + if self.object_name: + top = bpy.data.objects.get(self.object_name) + if top is None: + raise Refused(f"No object named {self.object_name!r}.") + members = [top] + list(top.children_recursive) + else: + members = list(context.scene.objects) + objects = [o for o in members if o.type == "MESH"] + if not objects: + raise Refused("There is no mesh to orient.") + context.view_layer.update() data = merged(objects) centre, rotation = core.principal_frame(data["V"], data["T"]) if self.principal: @@ -371,15 +449,20 @@ class BROKKR_MESH_POLISH_OT_orient(PolishOperator): middle = (low + high) / 2.0 frame = Matrix.Translation(Vector(-middle * scale)) @ Matrix.Diagonal((scale, scale, scale, 1.0)) \ @ Matrix([list(row) + [0.0] for row in rotation] + [[0, 0, 0, 1]]) @ Matrix.Translation(Vector(-centre)) - originals = {o.name: frame @ o.matrix_world for o in objects} - for obj in objects: - if obj.data.users > 1: - obj.data = obj.data.copy() - obj.data.transform(originals[obj.name]) - obj.data.update() - for obj in objects: - obj.parent = None - obj.matrix_world = Matrix.Identity(4) + def depth(obj): + return 0 if obj.parent is None else 1 + depth(obj.parent) + + world = {o.name: o.matrix_world.copy() for o in members} + for obj in sorted(members, key=depth): # parents first: a child's new place is set against its parent's + target = frame @ world[obj.name] + pivot = Matrix.Translation(target.translation) + if obj.type == "MESH": + if obj.data.users > 1: + obj.data = obj.data.copy() + obj.data.transform(pivot.inverted() @ target) + obj.data.update() + obj.matrix_world = pivot if obj.type in ("MESH", "EMPTY") else target + context.view_layer.update() final = (local - middle) * scale return {"objects": [o.name for o in objects], "scale": scale, "extent": [round(float(x), 6) for x in (high - low) * scale], @@ -413,7 +496,7 @@ class BROKKR_MESH_POLISH_OT_delight(PolishOperator): covered = owner >= 0 if covered.sum() < 64: raise Refused("The UV map covers too little of the texture to fit lighting.") - normals = core.interpolate(owner, bary, N[T])[covered] + normals = core.interpolate(owner, bary, data["CN"])[covered] normals /= np.maximum(np.linalg.norm(normals, axis=1, keepdims=True), 1e-30) sky = core.interpolate(owner, bary, occlusion[T][..., None])[covered][:, 0] pixels = read_pixels(image) @@ -536,6 +619,7 @@ class BROKKR_MESH_POLISH_OT_cut_parts(PolishOperator): world = obj.matrix_world.copy() bm = bmesh.new() bm.from_mesh(mesh) + stash_normals(mesh, bm) diagonal = (Vector(obj.bound_box[6]) - Vector(obj.bound_box[0])).length bmesh.ops.remove_doubles(bm, verts=bm.verts[:], dist=diagonal * 1e-5) bmesh.ops.triangulate(bm, faces=[f for f in bm.faces if len(f.verts) > 3]) @@ -568,8 +652,8 @@ class BROKKR_MESH_POLISH_OT_cut_parts(PolishOperator): for edge in bm.edges: edge[was_open] = int(edge.is_boundary) cap_material = cap_surface() - cap_slot = len(mesh.materials) - materials = list(mesh.materials) + [cap_material] + materials = (list(mesh.materials) or [None]) + [cap_material] # a bare mesh keeps a bare first slot: only caps are dark + cap_slot = len(materials) - 1 collection = obj.users_collection[0] if obj.users_collection else context.scene.collection made, report = [], [] for index, name in enumerate(names): @@ -593,11 +677,11 @@ class BROKKR_MESH_POLISH_OT_cut_parts(PolishOperator): for face in caps: face.material_index = cap_slot face.smooth = False - bmesh.ops.recalc_face_normals(piece, faces=piece.faces[:]) new_mesh = bpy.data.meshes.new(f"{obj.name}.{name}") root_world = world @ Vector(root_local) if index else world.translation.copy() piece.to_mesh(new_mesh) piece.free() + restore_normals(new_mesh) for material in materials: new_mesh.materials.append(material) new_obj = bpy.data.objects.new(f"{obj.name}.{name}", new_mesh) diff --git a/surfaces/blender/brokkr_mesh_polish/brokkr_actions.json b/surfaces/blender/brokkr_mesh_polish/brokkr_actions.json index d2950b7..c161dcd 100644 --- a/surfaces/blender/brokkr_mesh_polish/brokkr_actions.json +++ b/surfaces/blender/brokkr_mesh_polish/brokkr_actions.json @@ -14,7 +14,7 @@ }, { "name": "brokkr_mesh_polish.repair", - "doc": "Weld coincident vertices, drop degenerate and loose geometry and small shells, close small holes, fix normals.", + "doc": "Weld coincident vertices, drop degenerate and loose geometry and small shells, close small holes; windings are left alone unless recalc_normals.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -23,16 +23,18 @@ {"name": "weld_fraction", "type": "number", "minimum": 0, "maximum": 0.01, "default": 0.0001, "doc": "weld distance as a share of the bounding diagonal"}, {"name": "min_shell_area", "type": "number", "minimum": 0, "maximum": 0.5, "default": 0, "doc": "delete shells below this share of the surface; 0 keeps all"}, {"name": "fill_holes_sides", "type": "integer", "minimum": 0, "maximum": 1000, "default": 0, "doc": "close holes of up to this many edges"}, + {"name": "recalc_normals", "type": "boolean", "default": false, "doc": "rewind each shell to face outward as Blender judges it; off leaves every winding as it is. Can turn faces wrongly on open shells: read windingFlipped"}, {"name": "sharp_angle", "type": "number", "minimum": 0, "maximum": 180, "default": 0, "doc": "degrees; above 0 drops generated custom normals and shades edges sharper than this hard"} ] }, { "name": "brokkr_mesh_polish.orient", - "doc": "Turn all meshes as one body onto their principal axes (long on Y, short on Z), centre, scale, and bake it in.", + "doc": "Turn an object and its descendants (or the scene) as one body onto its principal axes (long on Y, short on Z), centre, scale; parents and pivots are kept.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", "fields": [ + {"name": "object_name", "type": "string", "maxLength": 63, "doc": "the root of what to turn, with its descendants; every object in the scene when absent"}, {"name": "length", "type": "number", "minimum": 0, "maximum": 1000000, "default": 0, "doc": "longest side after scaling; 0 keeps the size"}, {"name": "flip_forward", "type": "boolean", "default": false, "doc": "half a turn about Z"}, {"name": "roll_quarter_turns", "type": "integer", "minimum": 0, "maximum": 3, "default": 0, "doc": "quarter turns about the long axis"}, diff --git a/surfaces/blender/brokkr_mesh_polish/core.py b/surfaces/blender/brokkr_mesh_polish/core.py index 0ae197a..9031425 100644 --- a/surfaces/blender/brokkr_mesh_polish/core.py +++ b/surfaces/blender/brokkr_mesh_polish/core.py @@ -111,13 +111,24 @@ def weighted_quantile(values: np.ndarray, weights: np.ndarray, q: float) -> floa return float(values[order][min(np.searchsorted(cumulative, q * cumulative[-1]), len(values) - 1)]) +def winding_against(V: np.ndarray, T: np.ndarray, CN: np.ndarray) -> np.ndarray: + """True for each triangle whose corner order faces away from its own shading normals CN (m,3,3): the + triangle is drawn from behind, and a single-sided material culls it.""" + a, b, c = V[T[:, 0]], V[T[:, 1]], V[T[:, 2]] + return (np.cross(b - a, c - a) * CN.sum(axis=1)).sum(axis=1) < 0 + + def audit(V: np.ndarray, T: np.ndarray, UV: np.ndarray | None, texture_size: int = 0, - weld_fraction: float = 1e-5, raster: int = 1024) -> dict: + weld_fraction: float = 1e-5, raster: int = 1024, CN: np.ndarray | None = None) -> dict: """The measurements a polish pass is judged by. Lengths are in the mesh's own units. Topology is counted after welding positions within weld_fraction of the bounding diagonal. UV overlap is the share of covered texels (on a raster x raster grid) that more than one triangle covers. Texel density is - texels per unit length for a texture_size texture, area-weighted over triangles; its spread is p95 / p5.""" + texels per unit length for a texture_size texture, area-weighted over triangles; its spread is p95 / p5. + With CN, the per-corner shading normals, windingAgainstNormals counts triangles wound away from them, and + uvMirroredTriangles counts triangles whose texture reads mirrored on the surface as shaded: negative UV + area on a triangle wound with its normals, or positive on one wound against them. Without CN the winding is + taken as right, so uvMirroredTriangles is the triangles of negative UV area.""" V = np.asarray(V, dtype=np.float64) T = np.asarray(T, dtype=np.int64) extent = V.max(axis=0) - V.min(axis=0) if len(V) else np.zeros(3) @@ -128,6 +139,9 @@ def audit(V: np.ndarray, T: np.ndarray, UV: np.ndarray | None, texture_size: int "extent": [round(float(x), 6) for x in extent], "surfaceArea": float(areas.sum()), "degenerateTriangles": int((areas <= 1e-14 * diagonal * diagonal).sum())} report.update(edge_census(TW)) + against = winding_against(V, T, np.asarray(CN, dtype=np.float64)) & (areas > 0) if CN is not None else np.zeros(len(T), dtype=bool) + if CN is not None: + report["windingAgainstNormals"] = int(against.sum()) shells = triangle_components(TW) _, shell_sizes = np.unique(shells, return_counts=True) report["shells"] = int(len(shell_sizes)) @@ -141,7 +155,7 @@ def audit(V: np.ndarray, T: np.ndarray, UV: np.ndarray | None, texture_size: int covered = int((cover > 0).sum()) report.update({ "uvIslands": uv_islands(TW, UV), - "uvFlippedTriangles": int((signed < 0).sum()), + "uvMirroredTriangles": int(((signed < 0) ^ against)[np.abs(signed) >= 1e-12].sum()), "uvZeroAreaTriangles": int((np.abs(signed) < 1e-12).sum()), "uvOutsideUnitTriangles": int(((UV < -1e-6) | (UV > 1 + 1e-6)).any(axis=(1, 2)).sum()), "uvCoverage": covered / float(raster * raster), diff --git a/surfaces/blender/tests/live/mesh_polish.py b/surfaces/blender/tests/live/mesh_polish.py index 4284585..5659698 100644 --- a/surfaces/blender/tests/live/mesh_polish.py +++ b/surfaces/blender/tests/live/mesh_polish.py @@ -5,7 +5,8 @@ and does what its doc says to real bpy meshes and images. Not part of the unitte Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses without them). Every action is sent through BrokkrBlenderTarget.run_intent, as tools/run_intents.py sends it. -Writes .result.json and exits 1 when a check failed. +With BROKKR_POLISH_HULLS= it also repairs each and checks that no face was +turned. Writes .result.json and exits 1 when a check failed. """ import json import math @@ -17,13 +18,15 @@ from pathlib import Path import bmesh import bpy import numpy as np -from mathutils import Matrix - -for _name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): - if not os.environ.get(_name): - raise SystemExit(f"{_name} is not set: run this in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") +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] package = types.ModuleType("brokkr_bridge") package.__path__ = [str(SURFACE / "brokkr_bridge")] @@ -40,6 +43,7 @@ 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] +RATIO_BOUND, DEFICIT_BOUND, SHADE_BOUND = 1.906, 0.136, 0.684 # each derived where it is used def check(name, ok, detail=None): @@ -92,58 +96,184 @@ def pixels_of(obj): check("host file admitted", not R["hostErrors"] and len(R["hostRows"]) == 7, R["hostErrors"] or R["hostRows"]) -# --- audit and repair: a sphere torn into loose faces is welded back into one closed shell ----------------------- +# --- audit and repair: a generator's sphere, torn at every edge, half its faces wound inside out under outward +# --- custom normals, is welded back into one closed shell with no face turned and its shading normals intact ------ size = 256 -rows = (np.arange(size) + 0.5) / size # v: 0 at the south pole, 1 at the north pole of Blender's UV sphere +rows = np.clip(((np.arange(size) + 0.5) / size - 0.1) / 0.8, 0.0, 1.0) # latitude: 0 at the south pole, 1 at the north baked = np.repeat((0.8 * (0.2 + 0.8 * rows))[:, None, None], size, axis=1) * np.ones((1, 1, 3)) -sphere = new_object("Ball", lambda bm: bmesh.ops.create_uvsphere(bm, u_segments=48, v_segments=24, radius=1.0, calc_uvs=True), - new_image("ball_bake", baked.astype(np.float32))) + + +def ball(bm): + bmesh.ops.create_uvsphere(bm, u_segments=48, v_segments=24, radius=1.0, calc_uvs=True) + layer = bm.loops.layers.uv.active + for face in bm.faces: # the island sits inside the texture with a margin, as a generator's atlas does + for loop in face.loops: + loop[layer].uv = loop[layer].uv * 0.8 + Vector((0.1, 0.1)) + + +sphere = new_object("Ball", ball, new_image("ball_bake", baked.astype(np.float32))) sphere.data.polygons.foreach_set("use_smooth", [True] * len(sphere.data.polygons)) torn = bmesh.new() torn.from_mesh(sphere.data) bmesh.ops.split_edges(torn, edges=torn.edges[:]) +inside_out = [f for f in torn.faces if f.calc_center_median().x > 0] +reversed_faces, reversed_triangles = len(inside_out), sum(len(f.verts) - 2 for f in inside_out) +bmesh.ops.reverse_faces(torn, faces=inside_out) torn.to_mesh(sphere.data) torn.free() +sphere.data.normals_split_custom_set([tuple(sphere.data.vertices[loop.vertex_index].co.normalized()) for loop in sphere.data.loops]) + + +def polygon_normals(mesh): + flat = np.empty(len(mesh.polygons) * 3, dtype=np.float32) + mesh.polygons.foreach_get("normal", flat) + return flat.reshape(-1, 3) + + +def shading_error(mesh): + """The worst angle, in degrees, between a corner's shading normal and the sphere's own outward direction.""" + flat = np.empty(len(mesh.loops) * 3, dtype=np.float32) + mesh.corner_normals.foreach_get("vector", flat) + outward = np.array([mesh.vertices[loop.vertex_index].co.normalized() for loop in mesh.loops]) + return float(np.degrees(np.arccos(np.clip((flat.reshape(-1, 3) * outward).sum(axis=1), -1, 1))).max()) + + receipt, before = send("brokkr_mesh_polish.audit", object_name="Ball") check("audit: accepted, no undo step", receipt["status"] == "accepted" and not receipt.get("undoLabel"), receipt["message"]) check("audit: welded topology sees one closed shell in the torn sphere", before["Ball"]["shells"] == 1 and before["Ball"]["boundaryEdges"] == 0 and before["Ball"]["nonManifoldEdges"] == 0, before["Ball"]) check("audit: texture and UV facts", before["Ball"]["baseColorSize"] == [size, size] and before["Ball"]["uvOverlap"] < 0.02 - and before["Ball"]["texelDensityMedian"] > 0, before["Ball"]) -torn_vertices = len(sphere.data.vertices) -receipt, repaired = send("brokkr_mesh_polish.repair", object_name="Ball", sharp_angle=30) + and before["Ball"]["texelDensityMedian"] > 0 and 0.55 < before["Ball"]["uvCoverage"] < 0.64, before["Ball"]) # an 0.8 x 0.8 island less the pole gaps +check("audit: counts the triangles wound against their shading normals, and none of them as a mirrored texture", + reversed_triangles > 1000 and before["Ball"]["windingAgainstNormals"] == reversed_triangles + and before["Ball"]["uvMirroredTriangles"] == 0, [reversed_triangles, before["Ball"].get("windingAgainstNormals"), before["Ball"].get("uvMirroredTriangles")]) +torn_vertices, normals_before = len(sphere.data.vertices), polygon_normals(sphere.data) +receipt, repaired = send("brokkr_mesh_polish.repair", object_name="Ball") check("repair: accepted as one undo step", receipt["status"] == "accepted" and "repair" in receipt.get("undoLabel", ""), receipt) check("repair: welds the torn vertices", repaired["changes"]["welded"] == torn_vertices - len(sphere.data.vertices) and len(sphere.data.vertices) == 48 * 23 + 2, repaired) -edges = [e for e in sphere.data.edges] -check("repair: every edge has two faces again", sum(1 for _ in edges) == 48 * 23 + 48 * 24, len(edges)) +check("repair: every edge has two faces again", len(sphere.data.edges) == 48 * 23 + 48 * 24, len(sphere.data.edges)) +normals_after = polygon_normals(sphere.data) +turned = int(((normals_before * normals_after).sum(axis=1) < 0).sum()) if len(normals_before) == len(normals_after) else -1 +R["winding"] = {"reversedTriangles": reversed_triangles, "turnedByDefaultRepair": turned, "shadingErrorDegrees": shading_error(sphere.data)} +check("repair: by default turns no face (a single-sided material would cull a turned one)", + turned == 0 and repaired["changes"]["windingFlipped"] == 0 + and repaired["after"]["windingAgainstNormals"] == repaired["before"]["windingAgainstNormals"] == reversed_triangles, [turned, repaired]) +check("repair: the shading normals survive the weld", "custom_normal" in sphere.data.attributes and R["winding"]["shadingErrorDegrees"] < 0.5 + and not repaired["changes"]["customNormalsDropped"], R["winding"]) -# --- delight: a bake that darkens with latitude is levelled ------------------------------------------------------ -receipt, lit = send("brokkr_mesh_polish.delight", object_name="Ball", clusters=1, fit_size=256, occlusion_rays=8) +# --- delight: a bake that darkens with latitude is levelled, reading the shading normals, not the windings -------- +receipt, lit = send("brokkr_mesh_polish.delight", object_name="Ball", clusters=1, fit_size=128, occlusion_rays=8, max_gain=8) after_pixels, after_image = pixels_of(sphere) column = after_pixels[:, size // 2, 0] -# top/bottom brightness of the stored texture, rows at v = 0.9 and v = 0.1 -ratio_before = float(baked[int(size * 0.9), 0, 0] / baked[int(size * 0.1), 0, 0]) -ratio_after = float(column[int(size * 0.9)] / column[int(size * 0.1)]) -R["delight"] = {"report": lit, "ratioBefore": ratio_before, "ratioAfter": ratio_after} -check("delight: accepted, new packed image on the material", receipt["status"] == "accepted" and after_image.name == "ball_bake.delit" - and after_image.packed_file is not None, receipt["message"]) +north, south = int(size * (0.1 + 0.8 * 0.9)), int(size * (0.1 + 0.8 * 0.1)) # rows at latitude 0.9 and 0.1 +ratio_before = float(baked[north, 0, 0] / baked[south, 0, 0]) +ratio_after = float(column[north] / column[south]) +# On the island's left border the gain field meets texels no triangle covers. With the field filled outward the +# border reads as the middle of the row does; left unfilled, the neutral gain of the uncovered texels bleeds in. +border = int(math.ceil(size * 0.1)) +deficit = float(np.median(1.0 - after_pixels[south - 8:south + 8, border, 0] / after_pixels[south - 8:south + 8, size // 2, 0])) +R["delight"] = {"report": lit, "ratioBefore": ratio_before, "ratioAfter": ratio_after, "borderDeficit": deficit} +check("delight: accepted, new packed image on the material, in the old image's colour space", receipt["status"] == "accepted" + and after_image.name == "ball_bake.delit" and after_image.packed_file is not None + and after_image.colorspace_settings.name == "Non-Color", [receipt["message"], after_image.colorspace_settings.name]) check("delight: finds the baked light", lit["explainedByLight"]["before"] > 0.5 and lit["before"]["upDownLuminanceRatio"] > 2.0, lit) -# bound: shipped ratioAfter 1.12, the no-op mutant leaves 3.29: sqrt(1.12 * 3.29) = 1.92 -check("delight: levels top against bottom", ratio_before > 1.92 * 1.2 and ratio_after < 1.92 / 1.2, [ratio_before, ratio_after]) +# bound: shipped ratioAfter 1.114; a no-op leaves 3.261 and so do normals taken from the windings (the inside-out half +# cancels the light the fit could find): sqrt(1.114 * 3.261) = 1.906 +check("delight: levels top against bottom", ratio_before > RATIO_BOUND * 1.2 and ratio_after < RATIO_BOUND / 1.2, [ratio_before, ratio_after]) +# bound: shipped deficit 0.000, an unfilled gain field leaves 0.164; the shipped reading being zero, the bound sits 1.2 under the mutant: 0.136 +check("delight: the gain reaches the island's border unweakened", abs(deficit) < DEFICIT_BOUND, deficit) -# --- orient: a turned slab is laid along Y, thin on Z, centred, scaled ------------------------------------------ +receipt, rewound = send("brokkr_mesh_polish.repair", object_name="Ball", recalc_normals=True, sharp_angle=30) +check("repair: recalc_normals rewinds the inside-out half and says how many faces it turned", + receipt["status"] == "accepted" and rewound["changes"]["windingFlipped"] == reversed_faces + and rewound["changes"]["customNormalsDropped"] and "custom_normal" not in sphere.data.attributes + and rewound["after"]["windingAgainstNormals"] == 0, rewound) + +# --- repair: only holes up to the size asked are filled, and only shells below the share asked are dropped ----- +def holey(bm): + bmesh.ops.create_grid(bm, x_segments=6, y_segments=6, size=3.0, calc_uvs=True) # 36 quads, each 1 x 1 + at = lambda face: (round(face.calc_center_median().x, 1), round(face.calc_center_median().y, 1)) + small = [f for f in bm.faces if at(f) == (1.5, 1.5)] # one quad inside: a 4-edge hole + large = [f for f in bm.faces if at(f)[0] in (-1.5, -0.5) and at(f)[1] in (-1.5, -0.5)] # a 2 x 2 block: an 8-edge hole + bmesh.ops.delete(bm, geom=small + large, context="FACES") + bm.faces.new([bm.verts.new(co) for co in ((9.0, 9.0, 0.0), (9.2, 9.0, 0.0), (9.0, 9.2, 0.0))]) # a far chip: 0.02 of area against 31 + + +sheet = new_object("Sheet", holey) +flipped_sheet = bmesh.new() # the generator's sheet faces down: a fill must follow it, whichever way Blender would guess +flipped_sheet.from_mesh(sheet.data) +bmesh.ops.reverse_faces(flipped_sheet, faces=flipped_sheet.faces[:]) +flipped_sheet.to_mesh(sheet.data) +flipped_sheet.free() +TILT = (0.6, 0.0, -0.8) # the generator's shading normals lean: the old faces must keep them, a fill must not borrow them +sheet.data.normals_split_custom_set([TILT] * len(sheet.data.loops)) +receipt, mended = send("brokkr_mesh_polish.repair", object_name="Sheet", fill_holes_sides=4, min_shell_area=0.01) +R["mend"] = mended +check("repair: fills the 4-edge hole, leaves the 8-edge hole and the rim, drops the chip", + receipt["status"] == "accepted" and mended["changes"]["holesFilled"] == 1 and mended["changes"]["shellsRemoved"] == 1 + and mended["after"]["shells"] == 1 and mended["after"]["boundaryEdges"] == 24 + 8, mended) +facing = polygon_normals(sheet.data)[:, 2] +check("repair: a filled hole is wound as the faces around it", len(facing) == 31 * 1 + 2 and bool((facing < -0.9).all()), [len(facing), float(facing.max())]) +shading = np.empty(len(sheet.data.loops) * 3, dtype=np.float32) +sheet.data.corner_normals.foreach_get("vector", shading) +shading = shading.reshape(-1, 3) +fill_loops = [i for polygon in sheet.data.polygons if abs(polygon.center.x - 1.5) < 0.4 and abs(polygon.center.y - 1.5) < 0.4 for i in polygon.loop_indices] +old_loops = [i for i in range(len(shading)) if i not in set(fill_loops)] +check("repair: old faces keep their shading normals through the weld and the fill; the fill is shaded by its own direction", + len(fill_loops) == 6 and np.allclose(shading[old_loops], TILT, atol=1e-3) and np.allclose(shading[fill_loops], (0.0, 0.0, -1.0), atol=1e-3), + [len(fill_loops), shading[fill_loops].tolist()[:2], shading[old_loops[0]].tolist()]) +bpy.data.objects.remove(sheet) + +# --- delight: darkness that follows occlusion is levelled --------------------------------------------------------- +def pair(bm): + layer = bm.loops.layers.uv.active + for side in (-1.0, 1.0): # two unit spheres 0.1 apart: their facing sides occlude each other + made = bmesh.ops.create_uvsphere(bm, u_segments=32, v_segments=16, radius=1.0, calc_uvs=True, matrix=Matrix.Translation((side * 1.05, 0, 0))) + for face in {f for v in made["verts"] for f in v.link_faces}: + for loop in face.loops: + loop[layer].uv = Vector((loop[layer].uv.x * 0.5 + (0.0 if side < 0 else 0.5), loop[layer].uv.y)) + + +import brokkr_mesh_polish as polish # noqa: E402 the fixture's bake uses the add-on's own occlusion, so the light is exactly what it can explain + +twins = new_object("Twins", pair, new_image("twins_bake", np.ones((size, size, 3), dtype=np.float32))) +twins.data.polygons.foreach_set("use_smooth", [True] * len(twins.data.polygons)) +twin = polish.arrays(twins) +twin_sky = polish.ambient_occlusion(twin["V"], twin["T"], twin["N"], 64, 0.35 * float(np.linalg.norm(twin["V"].max(axis=0) - twin["V"].min(axis=0)))) +owner, bary, _ = polish.core.rasterize(twin["UV"], size) +sky_map = polish.core.interpolate(owner, bary, twin_sky[twin["T"]][..., None])[..., 0] +occluded, open_sky = (owner >= 0) & (sky_map < 0.6), (owner >= 0) & (sky_map > 0.95) +twin_bake = np.where((owner >= 0)[..., None], 0.8 * np.clip(sky_map, 0.05, 1.0)[..., None], 0.5) * np.ones((1, 1, 3)) +flat = np.ones((size, size, 4), dtype=np.float32) +flat[..., :3] = twin_bake +bpy.data.images["twins_bake"].pixels.foreach_set(flat.reshape(-1)) +receipt, unshadowed = send("brokkr_mesh_polish.delight", object_name="Twins", clusters=1, fit_size=256, occlusion_rays=64, max_gain=8) +twin_after, _ = pixels_of(twins) +shade_before = float(np.median(twin_bake[..., 0][occluded]) / np.median(twin_bake[..., 0][open_sky])) +shade_after = float(np.median(twin_after[..., 0][occluded]) / np.median(twin_after[..., 0][open_sky])) +R["occlusion"] = {"report": unshadowed, "occludedTexels": int(occluded.sum()), "shadeBefore": shade_before, "shadeAfter": shade_after} +# bound: shipped shadeAfter 1.000; with occlusion ignored (a sky of 1 everywhere) it stays 0.468: sqrt(1.000 * 0.468) = 0.684 +check("delight: lifts occluded surface to the level of open surface", receipt["status"] == "accepted" and occluded.sum() > 500 + and shade_before < SHADE_BOUND / 1.2 and shade_after > SHADE_BOUND * 1.2, R["occlusion"]) +bpy.data.objects.remove(twins) + +# --- orient: a turned slab is laid along Y, thin on Z, centred, scaled; nothing outside it moves ----------------- slab = new_object("Slab", lambda bm: bmesh.ops.create_cube(bm, size=1.0, matrix=Matrix.Diagonal((3.0, 1.0, 0.5, 1.0)))) slab.matrix_world = Matrix.Translation((4, 5, 6)) @ Matrix.Rotation(math.radians(37), 4, (0.3, 0.5, 0.8)) -sphere.hide_viewport = True -bpy.context.scene.collection.objects.unlink(sphere) # orient turns every mesh in the scene as one body -receipt, oriented = send("brokkr_mesh_polish.orient", length=12.0) +sphere.location = (20, 0, 0) +bpy.context.view_layer.update() +receipt, oriented = send("brokkr_mesh_polish.orient", object_name="Slab", length=12.0) corners = np.array([slab.matrix_world @ v.co for v in slab.data.vertices]) extent = corners.max(axis=0) - corners.min(axis=0) check("orient: long on Y, thin on Z, scaled to the length, centred", receipt["status"] == "accepted" and np.allclose(extent, [4.0, 12.0, 2.0], atol=1e-3) and np.allclose((corners.max(axis=0) + corners.min(axis=0)) / 2, 0, atol=1e-4), [list(map(float, extent)), oriented]) check("orient: reports the mirror error of a symmetric body as small", max(oriented["mirrorError"].values()) < 0.05, oriented["mirrorError"]) +check("orient: an object outside the named root is not touched", oriented["objects"] == ["Slab"] + and np.allclose(sphere.matrix_world.translation, [20, 0, 0]) and abs(max(v.co.length for v in sphere.data.vertices) - 1.0) < 1e-5, oriented["objects"]) +receipt, _ = send("brokkr_mesh_polish.orient", object_name="Nobody") +check("orient: an unknown root is refused", receipt["status"] == "failed", receipt["message"]) bpy.data.objects.remove(slab) # --- cut_parts: a knob fused to a block is cut off at the crease, capped, and rooted at its cut ----------------- @@ -177,11 +307,54 @@ if receipt["status"] == "accepted": check("cut_parts: both sides of the cut are capped (closed shells)", all(closed[name]["boundaryEdges"] == 0 and closed[name]["shells"] == 1 for name in ("Block.body", "Block.knob")), {name: [closed[name]["boundaryEdges"], closed[name]["shells"]] for name in ("Block.body", "Block.knob")}) - check("cut_parts: caps carry the cap material and a joint sits at the root", "Polish Cap" in [m.name for m in knob.data.materials] + capped = {o.name: sum(1 for polygon in o.data.polygons if getattr(o.data.materials[polygon.material_index], "name", "") == "Polish Cap") for o in (body, knob)} + check("cut_parts: exactly the cap faces carry the cap material", capped["Block.knob"] == part["Block.knob"]["capTriangles"] > 0 + and capped["Block.body"] == part["Block.body"]["capTriangles"] > 0, capped) + cap_normals = {o.name: [polygon.normal.z for polygon in o.data.polygons + if getattr(o.data.materials[polygon.material_index], "name", "") == "Polish Cap"] for o in (body, knob)} + check("cut_parts: each cap faces out of its own part, and no old face was turned", + all(z < -0.9 for z in cap_normals["Block.knob"]) and all(z > 0.9 for z in cap_normals["Block.body"]) + and closed["Block.body"]["windingAgainstNormals"] == 0 and closed["Block.knob"]["windingAgainstNormals"] == 0, cap_normals) + check("cut_parts: a joint sits at the root", "Polish Cap" in [getattr(m, "name", "") for m in knob.data.materials] and np.allclose(bpy.data.objects[part["Block.knob"]["joint"]].matrix_world.translation, [0, 0, 1], atol=1e-5), part["Block.knob"].get("joint")) + # orient after the cut: the body and what hangs from it turn as one; the knob keeps its parent and its pivot + receipt, turned_parts = send("brokkr_mesh_polish.orient", object_name="Block.body", length=6.0) + pivot = knob.matrix_world.translation + reach = max(abs((knob.matrix_world @ v.co).y) for v in knob.data.vertices) + R["orientParts"] = {"report": turned_parts, "knobPivot": list(pivot), "knobReach": reach, "parent": knob.parent.name if knob.parent else None} + # the 2 x 2 x 3 body-and-knob is laid along Y and doubled: the cut centre (0, 0, 1), half a unit above the middle, lands 1 along Y + check("orient: after a cut the parts keep their parent and their pivot at the cut", receipt["status"] == "accepted" and knob.parent == body + and abs(abs(pivot.y) - 1.0) < 1e-4 and abs(pivot.x) < 1e-4 and abs(pivot.z) < 1e-4 and abs(reach - 3.0) < 1e-4 + and np.allclose(np.array(knob.matrix_world.to_3x3()), np.eye(3), atol=1e-6), R["orientParts"]) receipt, _ = send("brokkr_mesh_polish.cut_parts", object_name="Block.body", seeds="only=0,0,-1") check("cut_parts: one part is refused with nothing changed", receipt["status"] == "failed" and "Block.body" in bpy.data.objects, receipt["message"]) + +# --- cut_parts through: a seed on one face of a thin plate also holds the face behind it ----------------------- +def plate_body(bm): + bmesh.ops.create_cube(bm, size=2.0, matrix=Matrix.Diagonal((1.0, 1.0, 0.05, 1.0))) # 2 x 2 x 0.1 + bmesh.ops.subdivide_edges(bm, edges=bm.edges[:], cuts=7, use_grid_fill=True) + bmesh.ops.triangulate(bm, faces=bm.faces[:]) + + +def underside(name): + """Triangles of the part that face down and are surface, not cap.""" + part_object = bpy.data.objects[name] + return sum(1 for polygon in part_object.data.polygons + if polygon.normal.z < -0.9 and getattr(part_object.data.materials[polygon.material_index], "name", "") != "Polish Cap") + + +R["through"] = {} +for label, through in (("without", 0.0), ("with", 0.1)): + new_object("Plate", plate_body) + # by distance alone (no crease cost) the underside's middle is nearer the body's seed, at an underside corner, + # than the lid's seed on top, which must go round the rim; a ray inward from the lid's seed finds it at once + receipt, _ = send("brokkr_mesh_polish.cut_parts", object_name="Plate", seeds="body=-0.9,-0.9,-0.05; lid=0,0,0.05", crease_cost=0, through=through) + R["through"][label] = underside("Plate.lid") if receipt["status"] == "accepted" else None + for leftover in [o for o in bpy.data.objects if o.name.startswith("Plate")]: + bpy.data.objects.remove(leftover) +check("cut_parts: through seeds the far face of a thin part", R["through"]["without"] == 0 and (R["through"]["with"] or 0) >= 8, R["through"]) + # --- pick and scrub_markings: lettering on one panel is found from a camera and painted out ---------------------- panel = np.full((128, 128, 3), [0.1, 0.35, 0.4], dtype=np.float32) panel += np.random.default_rng(0).normal(0, 0.01, panel.shape).astype(np.float32) @@ -194,16 +367,16 @@ def plate(bm): sign = new_object("Sign", plate, new_image("sign_paint", panel)) # 4 x 2, flat on z = 0, u along x -sign.location = (0, 0, 5) +sign.location = (40, 0, 5) # clear of the block bpy.context.view_layer.update() camera = bpy.data.objects.new("Eye", bpy.data.cameras.new("Eye")) bpy.context.scene.collection.objects.link(camera) camera.data.type = "ORTHO" camera.data.ortho_scale = 4.0 -camera.location = (0, 0, 9) +camera.location = (40, 0, 9) receipt, picked = send("brokkr_mesh_polish.pick", camera_name="Eye", u=0.25, v=0.5, resolution_x=400, resolution_y=200) check("pick: names the surface point under (u, v) of a picture of that shape", receipt["status"] == "accepted" and picked["hit"] - and picked["object"] == "Sign" and np.allclose(picked["point"], [-1.0, 0.0, 5.0], atol=1e-4), picked) + and picked["object"] == "Sign" and np.allclose(picked["point"], [39.0, 0.0, 5.0], atol=1e-4), picked) receipt, missed = send("brokkr_mesh_polish.pick", camera_name="Eye", u=0.5, v=0.99, resolution_x=200, resolution_y=400) check("pick: off the surface is a miss, not an error", receipt["status"] == "accepted" and missed == {"hit": False}, missed) @@ -227,6 +400,26 @@ check("scrub_markings: a sphere off the surface is refused", receipt["status"] = receipt, _ = send("brokkr_mesh_polish.delight", object_name="Sign", max_gain=9) check("a bound miss is denied by Brokkr's table before the operator runs", receipt["status"] == "denied", receipt["message"]) +# --- real generated hulls, when a directory of .glb files is given: repair must turn none of their faces --------- +HULLS = os.environ.get("BROKKR_POLISH_HULLS", "") +R["hulls"] = {} +for path in sorted(Path(HULLS).glob("*.glb")) if HULLS else []: + known = set(bpy.data.objects.keys()) + bpy.ops.import_scene.gltf(filepath=str(path)) + for hull in [o for o in bpy.data.objects if o.name not in known and o.type == "MESH"]: + was = polygon_normals(hull.data) + _, raw = send("brokkr_mesh_polish.audit", object_name=hull.name) + against = raw[hull.name]["windingAgainstNormals"] + receipt, mended = send("brokkr_mesh_polish.repair", object_name=hull.name) + now = polygon_normals(hull.data) + turned = int(((was * now).sum(axis=1) < 0).sum()) if len(was) == len(now) else None + R["hulls"][path.name] = {"polygons": len(was), "polygonsAfter": len(now), "turned": turned, "againstBefore": against, + "againstAfter": mended["after"]["windingAgainstNormals"], "changes": mended["changes"]} + check(f"hull {path.name}: repair turns no face and keeps the shading normals' sides", receipt["status"] == "accepted" + and mended["changes"]["windingFlipped"] == 0 and turned in (0, None) # None: faces were removed, so indices no longer pair + and 0 <= against - mended["after"]["windingAgainstNormals"] <= len(was) - len(now), R["hulls"][path.name]) + bpy.data.objects.remove(hull) + R["ok"] = all(c["ok"] for c in R["checks"]) Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") for c in R["checks"]: diff --git a/surfaces/blender/tests/live/mesh_polish.result.json b/surfaces/blender/tests/live/mesh_polish.result.json index 9f3bae1..afe1e82 100644 --- a/surfaces/blender/tests/live/mesh_polish.result.json +++ b/surfaces/blender/tests/live/mesh_polish.result.json @@ -37,26 +37,27 @@ "boundaryEdges": 0, "nonManifoldEdges": 0, "collapsedTriangles": 0, + "windingAgainstNormals": 1104, "shells": 1, "shellTriangles": [ 2208 ], "uvIslands": 1, - "uvFlippedTriangles": 0, + "uvMirroredTriangles": 0, "uvZeroAreaTriangles": 0, "uvOutsideUnitTriangles": 0, - "uvCoverage": 0.95831298828125, + "uvCoverage": 0.6139068603515625, "uvOverlap": 0.0, - "texelDensityMedian": 61.97425923665604, - "texelDensityP5": 57.66165269744736, - "texelDensityP95": 113.44982327717632, - "texelDensitySpread": 1.9675090457856172, + "texelDensityMedian": 49.579448658498315, + "texelDensityP5": 46.12933107377486, + "texelDensityP95": 90.75985098993894, + "texelDensitySpread": 1.9675085000644446, "baseColorImage": "ball_bake", "baseColorSize": [ 256, 256 ], - "customNormals": false + "customNormals": true } }, { @@ -77,28 +78,38 @@ "boundaryEdges": 0, "nonManifoldEdges": 0, "collapsedTriangles": 0, + "windingAgainstNormals": 1104, "shells": 1, "shellTriangles": [ 2208 ], "uvIslands": 1, - "uvFlippedTriangles": 0, + "uvMirroredTriangles": 0, "uvZeroAreaTriangles": 0, "uvOutsideUnitTriangles": 0, - "uvCoverage": 0.95831298828125, + "uvCoverage": 0.6139068603515625, "uvOverlap": 0.0, - "texelDensityMedian": 61.97425923665604, - "texelDensityP5": 57.66165269744736, - "texelDensityP95": 113.44982327717632, - "texelDensitySpread": 1.9675090457856172, + "texelDensityMedian": 49.579448658498315, + "texelDensityP5": 46.12933107377486, + "texelDensityP95": 90.75985098993894, + "texelDensitySpread": 1.9675085000644446, "baseColorImage": "ball_bake", "baseColorSize": [ 256, 256 ], - "customNormals": false + "customNormals": true } }, + { + "name": "audit: counts the triangles wound against their shading normals, and none of them as a mirrored texture", + "ok": true, + "detail": [ + 1104, + 1104, + 0 + ] + }, { "name": "repair: accepted as one undo step", "ok": true, @@ -113,8 +124,8 @@ "note": "", "undoLabel": "Brokkr test/driver: brokkr_mesh_polish.repair live-2", "lookPath": "", - "hostResult": "{\"object\":\"Ball\",\"changes\":{\"welded\":3406,\"degenerateFacesRemoved\":0,\"looseEdgesRemoved\":0,\"looseVertsRemoved\":0,\"shellsRemoved\":0,\"holesFilled\":0},\"before\":{\"triangles\":2208,\"vertices\":4512,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1},\"after\":{\"triangles\":2208,\"vertices\":1106,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1}}", - "observedAt": "2026-12-01T00:06:45.524772+00:00" + "hostResult": "{\"object\":\"Ball\",\"changes\":{\"welded\":3406,\"facesCollapsedByWeld\":0,\"degenerateFacesRemoved\":0,\"looseEdgesRemoved\":0,\"looseVertsRemoved\":0,\"shellsRemoved\":0,\"holesFilled\":0,\"windingFlipped\":0,\"customNormalsDropped\":false},\"before\":{\"triangles\":2208,\"vertices\":4512,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1,\"windingAgainstNormals\":1104},\"after\":{\"triangles\":2208,\"vertices\":1106,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1,\"windingAgainstNormals\":1104}}", + "observedAt": "2026-12-01T01:10:29.202522+00:00" } }, { @@ -124,25 +135,30 @@ "object": "Ball", "changes": { "welded": 3406, + "facesCollapsedByWeld": 0, "degenerateFacesRemoved": 0, "looseEdgesRemoved": 0, "looseVertsRemoved": 0, "shellsRemoved": 0, - "holesFilled": 0 + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false }, "before": { "triangles": 2208, "vertices": 4512, "boundaryEdges": 0, "nonManifoldEdges": 0, - "shells": 1 + "shells": 1, + "windingAgainstNormals": 1104 }, "after": { "triangles": 2208, "vertices": 1106, "boundaryEdges": 0, "nonManifoldEdges": 0, - "shells": 1 + "shells": 1, + "windingAgainstNormals": 1104 } } }, @@ -152,9 +168,58 @@ "detail": 2256 }, { - "name": "delight: accepted, new packed image on the material", + "name": "repair: by default turns no face (a single-sided material would cull a turned one)", "ok": true, - "detail": "Operator brokkr_mesh_polish.delight finished." + "detail": [ + 0, + { + "object": "Ball", + "changes": { + "welded": 3406, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 0, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false + }, + "before": { + "triangles": 2208, + "vertices": 4512, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "shells": 1, + "windingAgainstNormals": 1104 + }, + "after": { + "triangles": 2208, + "vertices": 1106, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "shells": 1, + "windingAgainstNormals": 1104 + } + } + ] + }, + { + "name": "repair: the shading normals survive the weld", + "ok": true, + "detail": { + "reversedTriangles": 1104, + "turnedByDefaultRepair": 0, + "shadingErrorDegrees": 0.03426402062177658 + } + }, + { + "name": "delight: accepted, new packed image on the material, in the old image's colour space", + "ok": true, + "detail": [ + "Operator brokkr_mesh_polish.delight finished.", + "Non-Color" + ] }, { "name": "delight: finds the baked light", @@ -166,22 +231,22 @@ "Ball" ], "explainedByLight": { - "before": 0.9722586649734903, - "after": 0.005096664890544278 + "before": 0.9718638595466577, + "after": 0.0005166823179215685 }, "before": { - "upDownLuminanceRatio": 2.5686425388668988, + "upDownLuminanceRatio": 2.562451830544031, "occlusionCorrelation": 0.0 }, "after": { - "upDownLuminanceRatio": 1.0190418174045521, + "upDownLuminanceRatio": 1.0166067038538378, "occlusionCorrelation": 0.0 }, "gain": { - "min": 0.9849698054726783, - "median": 1.454503966956526, - "max": 3.0, - "clamped": 0.05147808358817533 + "min": 0.9857558709602762, + "median": 1.457103285957073, + "max": 3.0649151172981792, + "clamped": 0.0 } } }, @@ -189,10 +254,149 @@ "name": "delight: levels top against bottom", "ok": true, "detail": [ - 3.2905027932960893, - 1.119760513305664 + 3.2607489597780868, + 1.1137723922729492 ] }, + { + "name": "delight: the gain reaches the island's border unweakened", + "ok": true, + "detail": 0.0 + }, + { + "name": "repair: recalc_normals rewinds the inside-out half and says how many faces it turned", + "ok": true, + "detail": { + "object": "Ball", + "changes": { + "welded": 0, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 0, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 576, + "customNormalsDropped": true + }, + "before": { + "triangles": 2208, + "vertices": 1106, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "shells": 1, + "windingAgainstNormals": 1104 + }, + "after": { + "triangles": 2208, + "vertices": 1106, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "shells": 1, + "windingAgainstNormals": 0 + } + } + }, + { + "name": "repair: fills the 4-edge hole, leaves the 8-edge hole and the rim, drops the chip", + "ok": true, + "detail": { + "object": "Sheet", + "changes": { + "welded": 0, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 0, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 1, + "holesFilled": 1, + "windingFlipped": 0, + "customNormalsDropped": false + }, + "before": { + "triangles": 63, + "vertices": 51, + "boundaryEdges": 39, + "nonManifoldEdges": 0, + "shells": 2, + "windingAgainstNormals": 0 + }, + "after": { + "triangles": 64, + "vertices": 48, + "boundaryEdges": 32, + "nonManifoldEdges": 0, + "shells": 1, + "windingAgainstNormals": 0 + } + } + }, + { + "name": "repair: a filled hole is wound as the faces around it", + "ok": true, + "detail": [ + 33, + -1.0 + ] + }, + { + "name": "repair: old faces keep their shading normals through the weld and the fill; the fill is shaded by its own direction", + "ok": true, + "detail": [ + 6, + [ + [ + 0.0, + 0.0, + -1.0 + ], + [ + 0.0, + 0.0, + -1.0 + ] + ], + [ + 0.6000571846961975, + 7.155610326492479e-09, + -0.7999570965766907 + ] + ] + }, + { + "name": "delight: lifts occluded surface to the level of open surface", + "ok": true, + "detail": { + "report": { + "image": "twins_bake", + "newImage": "twins_bake.delit", + "objects": [ + "Twins" + ], + "explainedByLight": { + "before": 0.9999597575085393, + "after": 0.028075104342772272 + }, + "before": { + "upDownLuminanceRatio": 1.0000084632254227, + "occlusionCorrelation": 0.983967648279407 + }, + "after": { + "upDownLuminanceRatio": 0.9999964767503613, + "occlusionCorrelation": 0.40471079036691976 + }, + "gain": { + "min": 0.9999809983875252, + "median": 1.0000990920451596, + "max": 5.493916964800697, + "clamped": 0.0 + } + }, + "occludedTexels": 2209, + "shadeBefore": 0.42187492665834836, + "shadeAfter": 1.0 + } + }, { "name": "orient: long on Y, thin on Z, scaled to the length, centred", "ok": true, @@ -229,6 +433,18 @@ "Z": 1.962464589014781e-09 } }, + { + "name": "orient: an object outside the named root is not touched", + "ok": true, + "detail": [ + "Slab" + ] + }, + { + "name": "orient: an unknown root is refused", + "ok": true, + "detail": "Error: No object named 'Nobody'." + }, { "name": "cut fixture is one closed skin", "ok": true, @@ -247,12 +463,13 @@ "boundaryEdges": 0, "nonManifoldEdges": 0, "collapsedTriangles": 0, + "windingAgainstNormals": 0, "shells": 1, "shellTriangles": [ 28 ], "uvIslands": 1, - "uvFlippedTriangles": 0, + "uvMirroredTriangles": 0, "uvZeroAreaTriangles": 28, "uvOutsideUnitTriangles": 0, "uvCoverage": 0.0, @@ -312,15 +529,76 @@ } }, { - "name": "cut_parts: caps carry the cap material and a joint sits at the root", + "name": "cut_parts: exactly the cap faces carry the cap material", + "ok": true, + "detail": { + "Block.body": 2, + "Block.knob": 2 + } + }, + { + "name": "cut_parts: each cap faces out of its own part, and no old face was turned", + "ok": true, + "detail": { + "Block.body": [ + 1.0, + 1.0 + ], + "Block.knob": [ + -1.0, + -1.0 + ] + } + }, + { + "name": "cut_parts: a joint sits at the root", "ok": true, "detail": "Block.knob.joint" }, + { + "name": "orient: after a cut the parts keep their parent and their pivot at the cut", + "ok": true, + "detail": { + "report": { + "objects": [ + "Block.body", + "Block.knob", + "Block.knob.joint" + ], + "scale": 1.9999999986467376, + "extent": [ + 5.656854, + 6.0, + 5.656854 + ], + "mirrorError": { + "X": 1.8120748396336225e-08, + "Y": 0.1508370330678463, + "Z": 1.8363068583553207e-08 + } + }, + "knobPivot": [ + 1.407290284305418e-09, + 1.0, + -1.8218171415895767e-09 + ], + "knobReach": 3.0, + "parent": "Block.body" + } + }, { "name": "cut_parts: one part is refused with nothing changed", "ok": true, "detail": "Error: Cutting needs seeds for at least two parts." }, + { + "name": "cut_parts: through seeds the far face of a thin part", + "ok": true, + "detail": { + "without": 0, + "with": 93 + } + }, { "name": "pick: names the surface point under (u, v) of a picture of that shape", "ok": true, @@ -328,7 +606,7 @@ "hit": true, "object": "Sign", "point": [ - -1.0, + 39.0, 0.0, 5.0 ], @@ -375,6 +653,72 @@ "name": "a bound miss is denied by Brokkr's table before the operator runs", "ok": true, "detail": "max_gain must be between 1 and 8." + }, + { + "name": "hull fourth.glb: repair turns no face and keeps the shading normals' sides", + "ok": true, + "detail": { + "polygons": 28426, + "polygonsAfter": 28420, + "turned": null, + "againstBefore": 388, + "againstAfter": 387, + "changes": { + "welded": 6437, + "facesCollapsedByWeld": 2, + "degenerateFacesRemoved": 4, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false + } + } + }, + { + "name": "hull sub.glb: repair turns no face and keeps the shading normals' sides", + "ok": true, + "detail": { + "polygons": 10406, + "polygonsAfter": 10406, + "turned": 0, + "againstBefore": 64, + "againstAfter": 64, + "changes": { + "welded": 2454, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 0, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false + } + } + }, + { + "name": "hull third.glb: repair turns no face and keeps the shading normals' sides", + "ok": true, + "detail": { + "polygons": 23341, + "polygonsAfter": 23340, + "turned": null, + "againstBefore": 189, + "againstAfter": 189, + "changes": { + "welded": 3810, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 1, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false + } + } } ], "hostErrors": [], @@ -387,6 +731,11 @@ "brokkr_mesh_polish.cut_parts", "brokkr_mesh_polish.pick" ], + "winding": { + "reversedTriangles": 1104, + "turnedByDefaultRepair": 0, + "shadingErrorDegrees": 0.03426402062177658 + }, "delight": { "report": { "image": "ball_bake", @@ -395,26 +744,87 @@ "Ball" ], "explainedByLight": { - "before": 0.9722586649734903, - "after": 0.005096664890544278 + "before": 0.9718638595466577, + "after": 0.0005166823179215685 }, "before": { - "upDownLuminanceRatio": 2.5686425388668988, + "upDownLuminanceRatio": 2.562451830544031, "occlusionCorrelation": 0.0 }, "after": { - "upDownLuminanceRatio": 1.0190418174045521, + "upDownLuminanceRatio": 1.0166067038538378, "occlusionCorrelation": 0.0 }, "gain": { - "min": 0.9849698054726783, - "median": 1.454503966956526, - "max": 3.0, - "clamped": 0.05147808358817533 + "min": 0.9857558709602762, + "median": 1.457103285957073, + "max": 3.0649151172981792, + "clamped": 0.0 } }, - "ratioBefore": 3.2905027932960893, - "ratioAfter": 1.119760513305664 + "ratioBefore": 3.2607489597780868, + "ratioAfter": 1.1137723922729492, + "borderDeficit": 0.0 + }, + "mend": { + "object": "Sheet", + "changes": { + "welded": 0, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 0, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 1, + "holesFilled": 1, + "windingFlipped": 0, + "customNormalsDropped": false + }, + "before": { + "triangles": 63, + "vertices": 51, + "boundaryEdges": 39, + "nonManifoldEdges": 0, + "shells": 2, + "windingAgainstNormals": 0 + }, + "after": { + "triangles": 64, + "vertices": 48, + "boundaryEdges": 32, + "nonManifoldEdges": 0, + "shells": 1, + "windingAgainstNormals": 0 + } + }, + "occlusion": { + "report": { + "image": "twins_bake", + "newImage": "twins_bake.delit", + "objects": [ + "Twins" + ], + "explainedByLight": { + "before": 0.9999597575085393, + "after": 0.028075104342772272 + }, + "before": { + "upDownLuminanceRatio": 1.0000084632254227, + "occlusionCorrelation": 0.983967648279407 + }, + "after": { + "upDownLuminanceRatio": 0.9999964767503613, + "occlusionCorrelation": 0.40471079036691976 + }, + "gain": { + "min": 0.9999809983875252, + "median": 1.0000990920451596, + "max": 5.493916964800697, + "clamped": 0.0 + } + }, + "occludedTexels": 2209, + "shadeBefore": 0.42187492665834836, + "shadeAfter": 1.0 }, "cut": { "body": "Block.body", @@ -456,6 +866,37 @@ } ] }, + "orientParts": { + "report": { + "objects": [ + "Block.body", + "Block.knob", + "Block.knob.joint" + ], + "scale": 1.9999999986467376, + "extent": [ + 5.656854, + 6.0, + 5.656854 + ], + "mirrorError": { + "X": 1.8120748396336225e-08, + "Y": 0.1508370330678463, + "Z": 1.8363068583553207e-08 + } + }, + "knobPivot": [ + 1.407290284305418e-09, + 1.0, + -1.8218171415895767e-09 + ], + "knobReach": 3.0, + "parent": "Block.body" + }, + "through": { + "without": 0, + "with": 93 + }, "scrub": { "report": { "object": "Sign", @@ -467,5 +908,61 @@ "inkInsideBefore": 192, "inkInsideAfter": 0 }, + "hulls": { + "fourth.glb": { + "polygons": 28426, + "polygonsAfter": 28420, + "turned": null, + "againstBefore": 388, + "againstAfter": 387, + "changes": { + "welded": 6437, + "facesCollapsedByWeld": 2, + "degenerateFacesRemoved": 4, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false + } + }, + "sub.glb": { + "polygons": 10406, + "polygonsAfter": 10406, + "turned": 0, + "againstBefore": 64, + "againstAfter": 64, + "changes": { + "welded": 2454, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 0, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false + } + }, + "third.glb": { + "polygons": 23341, + "polygonsAfter": 23340, + "turned": null, + "againstBefore": 189, + "againstAfter": 189, + "changes": { + "welded": 3810, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 1, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false + } + } + }, "ok": true } \ No newline at end of file diff --git a/surfaces/blender/tests/test_mesh_polish.py b/surfaces/blender/tests/test_mesh_polish.py index 7205f81..9f0b4ef 100644 --- a/surfaces/blender/tests/test_mesh_polish.py +++ b/surfaces/blender/tests/test_mesh_polish.py @@ -37,6 +37,7 @@ def load(name: str, path: Path): turntable = load("turntable_recipe", SURFACE / "tools" / "turntable_recipe.py") +private_dirs = load("private_dirs", SURFACE / "tools" / "private_dirs.py") core = load("brokkr_mesh_polish_core", SURFACE / "brokkr_mesh_polish" / "core.py") if np is not None else None @@ -83,6 +84,23 @@ class TopologyTests(unittest.TestCase): self.assertEqual(report["shells"], 2) self.assertEqual(report["shellTriangles"], [4, 4]) + def test_a_triangle_the_weld_collapses_adds_no_edges(self): + V, T = quad_strip(3) + sliver = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1.0, 1.0, 0.0]]) # two corners weld into one + _, TW = core.weld(np.concatenate([V, sliver]), np.concatenate([T, [[len(V), len(V) + 1, len(V) + 2]]]), 1e-6) + census = core.edge_census(TW) + self.assertEqual((census["collapsedTriangles"], census["boundaryEdges"], census["nonManifoldEdges"]), (1, 8, 0)) + + def test_winding_against_shading_normals_is_counted_per_triangle(self): + V, T = quad_strip(3) # every triangle faces +z + up = np.tile([0.0, 0.0, 1.0], (len(T), 3, 1)) + self.assertEqual(int(core.winding_against(V, T, up).sum()), 0) + mixed = T.copy() + mixed[:2] = mixed[:2, ::-1] # two triangles wound the other way, their shading normals still up + self.assertEqual(core.winding_against(V, mixed, up).tolist(), [True, True, False, False, False, False]) + self.assertEqual(core.audit(V, mixed, None, CN=up)["windingAgainstNormals"], 2) + self.assertNotIn("windingAgainstNormals", core.audit(V, mixed, None)) + def test_components_follow_long_chains(self): pairs = np.array([[i, i + 1] for i in range(999)]) self.assertEqual(len(np.unique(core.components(1000, pairs[::-1]))), 1) @@ -101,7 +119,34 @@ class UvTests(unittest.TestCase): self.assertLess(report["uvOverlap"], 0.02) # only texel centres exactly on the shared diagonal self.assertAlmostEqual(report["texelDensityMedian"], 1024.0, places=3) self.assertAlmostEqual(report["texelDensitySpread"], 1.0, places=6) - self.assertEqual((report["uvIslands"], report["uvFlippedTriangles"]), (1, 0)) + self.assertEqual((report["uvIslands"], report["uvMirroredTriangles"]), (1, 0)) + + def test_a_seam_in_uv_space_makes_two_islands_of_one_surface(self): + apart = self.SQUARE_UV * 0.4 + apart[1] += 0.5 # the second triangle's UVs moved away: the 3D edge is shared, the UV edge is not + self.assertEqual(core.audit(self.SQUARE_V, self.SQUARE_T, apart, 1024, raster=64)["uvIslands"], 2) + self.assertEqual(core.audit(self.SQUARE_V, self.SQUARE_T, self.SQUARE_UV * 0.4, 1024, raster=64)["uvIslands"], 1) + + def test_texel_density_is_weighted_by_surface_area(self): + # one large triangle at 1024 texels per unit and four tiny ones at 4096: by count the median is 4096, by area 1024 + tiny = np.array([[0, 0, 0], [0.01, 0, 0], [0, 0.01, 0]], dtype=float) + V = np.concatenate([self.SQUARE_V[[0, 1, 2]] * 0.5] + [tiny + [2 + i, 0, 0] for i in range(4)]) + T = np.arange(15).reshape(5, 3) + UV = np.concatenate([self.SQUARE_UV[:1] * 0.5] + [tiny[None, :, :2] * 4 + [0.6 + 0.05 * i, 0.6] for i in range(4)]) + report = core.audit(V, T, UV, texture_size=1024, raster=64) + self.assertAlmostEqual(report["texelDensityMedian"], 1024.0, places=3) + self.assertAlmostEqual(report["texelDensityP95"], 1024.0, places=3) + + def test_mirrored_texture_is_judged_against_the_shading_normals_not_the_winding(self): + up = np.tile([0.0, 0.0, 1.0], (2, 3, 1)) + wound_back = self.SQUARE_T[:, ::-1] + uv_back = self.SQUARE_UV[:, ::-1] # the same texel at each vertex, listed in the reversed corner order + report = core.audit(self.SQUARE_V, wound_back, uv_back, 1024, raster=64, CN=up) + self.assertEqual((report["windingAgainstNormals"], report["uvMirroredTriangles"]), (2, 0)) # culled, but not mirrored + mirrored = self.SQUARE_UV.copy() + mirrored[..., 0] = 1 - mirrored[..., 0] + report = core.audit(self.SQUARE_V, self.SQUARE_T, mirrored, 1024, raster=64, CN=up) + self.assertEqual((report["windingAgainstNormals"], report["uvMirroredTriangles"]), (0, 2)) # drawn, and mirrored def test_two_triangles_on_the_same_texels_overlap(self): stacked = np.array([self.SQUARE_UV[0], self.SQUARE_UV[0]]) @@ -111,7 +156,7 @@ class UvTests(unittest.TestCase): def test_a_mirrored_island_counts_as_flipped_and_half_the_area_doubles_nothing_but_density(self): mirrored = self.SQUARE_UV.copy() mirrored[..., 0] = 1 - mirrored[..., 0] - self.assertEqual(core.audit(self.SQUARE_V, self.SQUARE_T, mirrored, 1024, raster=64)["uvFlippedTriangles"], 2) + self.assertEqual(core.audit(self.SQUARE_V, self.SQUARE_T, mirrored, 1024, raster=64)["uvMirroredTriangles"], 2) half = core.audit(self.SQUARE_V, self.SQUARE_T, self.SQUARE_UV * 0.5, 1024, raster=64) self.assertAlmostEqual(half["texelDensityMedian"], 512.0, places=3) self.assertAlmostEqual(half["uvCoverage"], 0.25, places=2) @@ -138,6 +183,22 @@ class OrientTests(unittest.TestCase): self.assertLess(extent[2], 1e-9) self.assertAlmostEqual(float(np.linalg.det(R)), 1.0, places=9) + def test_principal_frame_is_a_rotation_for_a_shape_and_for_its_mirror_image(self): + rng = np.random.default_rng(4) + V = rng.random((60, 3)) * [5.0, 2.0, 1.0] + T = rng.integers(0, 60, size=(40, 3)) + T = T[(T[:, 0] != T[:, 1]) & (T[:, 1] != T[:, 2]) & (T[:, 0] != T[:, 2])] + determinants = [float(np.linalg.det(core.principal_frame(V * flip, T)[1])) for flip in ([1, 1, 1], [-1, 1, 1], [1, -1, 1], [1, 1, -1])] + self.assertTrue(np.allclose(determinants, 1.0), determinants) # never a reflection: it would turn the mesh inside out + + def test_mirror_error_is_about_the_axis_asked(self): + rng = np.random.default_rng(1) + half = rng.random((400, 3)) + about_y = np.concatenate([half, half * [1, -1, 1]]) + [0.7, 0.0, 0.3] # a mirror across y = 0 only + self.assertEqual(core.mirror_error(about_y, 1), 0.0) + self.assertGreater(core.mirror_error(about_y, 0), 0.05) + self.assertGreater(core.mirror_error(about_y, 2), 0.05) + def test_mirror_error_tells_a_symmetric_cloud_from_a_lopsided_one(self): rng = np.random.default_rng(1) half = rng.random((400, 3)) @@ -321,6 +382,16 @@ class TextureFillTests(unittest.TestCase): outside = np.zeros((40, 40), dtype=bool) self.assertFalse(core.marking_mask(panel, outside, 0.25, 1).any()) + def test_marking_mask_judges_against_the_median_so_heavy_lettering_does_not_move_the_panel_colour(self): + panel = np.full((40, 40, 3), [0.1, 0.35, 0.4], dtype=np.float32) + panel[:, ::3] = [0.95, 0.9, 0.3] # a third of the region is lettering: the mean colour is 0.3 from the panel + region = np.ones((40, 40), dtype=bool) + mask = core.marking_mask(panel, region, 0.25, 0) + self.assertTrue(np.array_equal(mask, np.repeat((np.arange(40) % 3 == 0)[None, :], 40, axis=0))) + + def test_srgb_known_values(self): + self.assertTrue(np.allclose(core.srgb_to_linear(np.array([0.0, 0.04045, 0.5, 1.0])), [0.0, 0.0031308, 0.21404, 1.0], atol=2e-5)) + def test_box_blur_keeps_a_flat_field_and_spreads_a_point(self): flat = np.full((9, 9), 0.5) self.assertTrue(np.allclose(core.box_blur(flat, 2), 0.5)) @@ -360,6 +431,46 @@ class HostFileTests(unittest.TestCase): at.validate({**envelope, "action": "brokkr_mesh_polish.cut_parts", "object_name": "Hull"}, host) # seeds required +class PrivateDirsTests(unittest.TestCase): + """The guard a driver script runs before it touches Blender's user folders.""" + HOME = str(Path("/home/her")) + APPDATA = str(Path("/users/her/AppData/Roaming")) + + def environ(self, **changes): + base = {"BLENDER_USER_CONFIG": "/scratch/bl/cfg", "BLENDER_USER_EXTENSIONS": "/scratch/bl/ext", + "BLENDER_USER_SCRIPTS": "/scratch/bl/scripts", "APPDATA": self.APPDATA} + base.update(changes) + return {k: v for k, v in base.items() if v is not None} + + def test_scratch_directories_pass(self): + self.assertIsNone(private_dirs.refusal(self.environ(), self.HOME)) + used = {"CONFIG": "/scratch/bl/cfg", "EXTENSIONS": "/scratch/bl/ext", "SCRIPTS": "/scratch/bl/scripts"} + self.assertIsNone(private_dirs.refusal(self.environ(), self.HOME, lambda kind: used[kind])) + + def test_an_unset_or_empty_variable_is_refused(self): + for name in private_dirs.VARIABLES: + for value in (None, ""): + self.assertIn(name, private_dirs.refusal(self.environ(**{name: value}), self.HOME)) + + def test_a_variable_pointing_into_her_own_blender_folders_is_refused(self): + own = [str(Path(self.APPDATA) / "Blender Foundation" / "Blender" / "5.3" / "extensions"), + str(Path(self.APPDATA) / "Blender Foundation"), + str(Path(self.HOME) / ".config" / "blender" / "5.3" / "scripts"), + str(Path(self.HOME) / "Library" / "Application Support" / "Blender" / "5.3" / "config")] + for folder in own: + for name in private_dirs.VARIABLES: + refused = private_dirs.refusal(self.environ(**{name: folder}), self.HOME) + self.assertIsNotNone(refused, folder) + self.assertIn("own Blender folder", refused) + beside = str(Path(self.APPDATA) / "Blender Foundation Scratch") # a sibling that only shares a prefix + self.assertIsNone(private_dirs.refusal(self.environ(BLENDER_USER_EXTENSIONS=beside), self.HOME)) + + def test_a_blender_that_is_not_using_the_variables_is_refused(self): + hers = str(Path(self.APPDATA) / "Blender Foundation" / "Blender" / "5.3") + self.assertIn("refusing to touch it", private_dirs.refusal(self.environ(), self.HOME, lambda kind: hers)) + self.assertIn("refusing", private_dirs.refusal(self.environ(), self.HOME, lambda kind: "")) + + class TurntableRecipeTests(unittest.TestCase): def test_every_pose_looks_at_the_origin_with_z_up(self): for azimuth in (0, 45, 90, 200, 315): From 2e3ac798eab717d30e6b245049970735cebf4930 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 02:17:46 +0100 Subject: [PATCH 53/63] docs: mesh polish after Soul's pass: windings, shading normals, orient scope, delight's gradient limit, the guard Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/mesh-polish.md | 68 ++++++++++++++++++++-------- 1 file changed, 49 insertions(+), 19 deletions(-) diff --git a/surfaces/blender/docs/mesh-polish.md b/surfaces/blender/docs/mesh-polish.md index 93b8fac..914ed6a 100644 --- a/surfaces/blender/docs/mesh-polish.md +++ b/surfaces/blender/docs/mesh-polish.md @@ -38,9 +38,11 @@ blender --background --factory-startup --python surfaces/blender/tools/run_inten ``` The runner opens no CultMesh node: receipts go to `.receipts.json` only. It is the human of its own -Blender (it enables the host add-ons, reloads host actions once, opens and saves the `.blend`), and it refuses to -start without private `BLENDER_USER_CONFIG`, `BLENDER_USER_EXTENSIONS` and `BLENDER_USER_SCRIPTS`. Its exit status is -0 when every intent was accepted, 3 when one was not, 2 when the recipe could not run. +Blender (it enables the host add-ons, reloads host actions once, opens and saves the `.blend`). It refuses to +start unless `BLENDER_USER_CONFIG`, `BLENDER_USER_EXTENSIONS` and `BLENDER_USER_SCRIPTS` are each set to a folder +outside a person's own Blender folders (`%APPDATA%\Blender Foundation`, `~/.config/blender`, +`~/Library/Application Support/Blender`) and Blender reports that it is using them (`tools/private_dirs.py`). Its +exit status is 0 when every intent was accepted, 3 when one was not, 2 when the recipe could not run. `surfaces/blender/tools/turntable_recipe.py` writes a recipe of Brokkr's own scene actions (`setWorld`, `createObject`, `setCamera`, `setObjectTransform`, `renderStill`) for an orthographic turntable of a `.blend` whose @@ -49,7 +51,7 @@ an after compare view by view. `--look flat` lights with a uniform white world a stored, baked shadows included; `--look lit` adds a sun. A polish pass that works, in order: `audit`, `orient` (render a flat turntable and pick `roll_quarter_turns` and -`flip_forward` by eye), `repair`, `delight`, then `pick` and `scrub_markings` for each patch of lettering, then +`flip_forward` by eye; give `principal: false` on any later call, or the axes are found again), `repair`, `delight`, then `pick` and `scrub_markings` for each patch of lettering, then `pick` and `cut_parts` when parts must move, `audit` again, `exportGltf`. ## Actions @@ -63,7 +65,13 @@ as all open edges. - `triangles`, `vertices`, `weldedVertices`, `extent`, `surfaceArea`, `degenerateTriangles`. - `boundaryEdges` (one triangle on the edge: an open rim), `nonManifoldEdges` (three or more), `shells` and the triangle count of the largest twelve. -- `uvIslands`, `uvFlippedTriangles` (mirrored in UV space), `uvZeroAreaTriangles`, `uvOutsideUnitTriangles`, +- `windingAgainstNormals`: triangles whose corner order faces away from their own shading normals (the custom + normals a generated mesh carries). A single-sided material culls them. A mesh without custom normals is shaded + from its windings, so this reads 0 whatever its windings are. +- `uvMirroredTriangles`: triangles whose texture reads mirrored on the surface as shaded, that is negative UV area + on a triangle wound with its normals, or positive UV area on one wound against them. A triangle that is merely + wound backwards is not counted here. +- `uvIslands`, `uvZeroAreaTriangles`, `uvOutsideUnitTriangles`, `uvCoverage` (share of the texture some triangle covers) and `uvOverlap` (share of covered texels that more than one triangle covers), both counted at texel centres on a `raster` x `raster` grid. - `texelDensityMedian`, `P5`, `P95` (texels per unit length for the base colour texture's size, area-weighted) and @@ -73,13 +81,24 @@ as all open edges. ### repair Welds coincident vertices (UVs live on face corners, so seams keep their UVs), removes degenerate faces and loose -edges and vertices, optionally deletes shells below `min_shell_area` of the surface, optionally closes holes of up -to `fill_holes_sides` edges, and makes face normals consistent. With `sharp_angle` above 0 the generator's custom -normals are dropped and shading is recomputed: smooth, hard across edges sharper than the angle. +edges and vertices, optionally deletes shells below `min_shell_area` of the surface, and optionally closes holes of +up to `fill_holes_sides` edges. + +It turns no face. The winding of every face is left as the generator made it, and the mesh's custom shading normals +are carried through the weld as plain directions and set back afterwards (Blender stores a custom normal against +its corner's automatic normal, which welding changes). `windingFlipped` in the report is 0 and +`windingAgainstNormals` is the same before and after, less any triangle that was removed. + +`recalc_normals: true` asks Blender to rewind each shell to face outward. On a closed shell that is right. On the +open, intersecting shells generators make it is a guess: on three Tripo hulls it turned 83 of 10,406, 4,564 of +23,341 and 15,734 of 28,426 triangles, and a single-sided material then culls whatever was turned the wrong way. +The report says how many faces it turned (`windingFlipped`); the custom normals cannot outlive a rewind and are +dropped (`customNormalsDropped`). With `sharp_angle` above 0 the custom normals are also dropped and shading is +recomputed: smooth, hard across edges sharper than the angle. A filled hole has no place in the UV map: each new face takes one UV point from the old face beside it, so it shows -that texel's colour and adds no UV overlap (it counts in `uvZeroAreaTriangles`). Making normals consistent flips the -winding of shells that faced inward, which mirrors their UVs; `uvFlippedTriangles` can rise. +that texel's colour and adds no UV overlap (it counts in `uvZeroAreaTriangles`); it is shaded by its own direction, +not by its neighbours' custom normals. Welding does not join shells that merely touch or intersect. A mesh assembled from open, interpenetrating shells stays one: its open edges and non-manifold edges are reported, not repaired. Closing such a mesh means remeshing it @@ -87,9 +106,11 @@ and rebaking its texture, which this add-on does not do. ### orient -Turns every mesh in the scene, as one rigid body, onto its area-weighted principal axes: longest on Y, shortest on -Z, centred on the origin, the longest side scaled to `length` when given. The transform is baked into the mesh data -and the objects are left unparented at identity. Principal axes do not know bow from stern or up from down: +Turns `object_name` and everything parented under it (every object in the scene when absent), as one rigid body, +onto its area-weighted principal axes: longest on Y, shortest on Z, centred on the origin, the longest side scaled +to `length` when given. Objects outside that root are not touched. Rotation and scale are baked into the mesh data; +every object keeps its parent and its pivot point (a cut part's origin stays at the centre of its cut), and meshes +and empties end unrotated and unscaled. Principal axes do not know bow from stern or up from down: `flip_forward` and `roll_quarter_turns` choose, and `mirrorError` in the report (per axis, 0 is a perfect mirror) says which plane the body is symmetric across. `principal: false` keeps the current axes and applies only the turns, the centring and the scale. @@ -98,8 +119,9 @@ turns, the centring and the scale. Undoes lighting baked into the base colour texture, as far as the surface's own shape explains it. -For each texel the add-on knows the surface normal and the ambient occlusion there (cosine-weighted rays against -the mesh, per vertex). It fits log luminance as an intercept per hue cluster (`clusters`: how many distinct paints +For each texel the add-on knows the shading normal (the mesh's custom normals when it has them, so a shell wound +inside out is still read as it is drawn) and the ambient occlusion there (cosine-weighted rays against the mesh, +per vertex). It fits log luminance as an intercept per hue cluster (`clusters`: how many distinct paints the texture holds) plus a light term: the order-2 spherical harmonics of the normal and the log of occlusion. The fit follows the upper envelope of luminance (an expectile regression at 0.85), because within one hue the brightest paint at a given normal and occlusion shows how much light the bake put there, while darker paint in the @@ -115,7 +137,11 @@ is the share of texels that hit `max_gain`. What it cannot do. It removes smooth, shape-following light: sky-over-ground gradients and occlusion darkening. It does not remove cast shadows, specular highlights, or light the shape does not explain. It cannot tell dark -paint from shadow where a hue has no bright paint at all in some range of occlusion. Texels the generator filled +paint from shadow where a hue has no bright paint at all in some range of occlusion. It cannot tell paint from light +when the paint itself follows the shape: a smooth fade of one hue that runs with the normal (a hull painted lighter +above than below) is read as sky-over-ground light and flattened; in a probe such a fade kept 0.35 of its slope. +Paint in panels, bands or patches keeps its contrast (slope 1.00 in the same probe). On a mesh without custom +normals whose shells are wound inside out, the normals it reads are wrong; `audit` cannot see that case. Texels the generator filled with black stay black: there is no colour there to recover. It raises shaded paint by gain, so 8-bit noise and JPEG blocks in dark areas are raised with it. @@ -151,7 +177,8 @@ crease. `through` above 0 also seeds the far face of each part off the body, fou no longer than that share of the diagonal: a thin shell (a petal, a fin) is then held from both faces. The mesh is welded and triangulated first. Each part becomes an object `.`; both sides of every cut -are capped with faces of a dark `Polish Cap` material (pinned to one UV point each, as in `repair`); each part off +are capped with faces of a dark `Polish Cap` material (pinned to one UV point each, as in `repair`); no existing +face is turned and the custom shading normals are carried through, as in `repair`; each part off the body gets its origin at the centre of its cut and is parented to the body without moving; custom properties `polish_cut_normal` and `polish_cut_radius` record the cut's plane and mean radius. `joint_scale` above 0 adds a ball of that share of the cut radius at each root, parented to the body. The original object is removed. @@ -167,6 +194,9 @@ centre of the cut, not a designed hinge: it is a sensible pivot to start from. ## Tests - `tests/test_mesh_polish.py`: the arithmetic on hand-built meshes and textures, `brokkr_actions.json` against - Brokkr's own host-file checker, and the turntable recipe against the action table. No Blender; needs numpy. + Brokkr's own host-file checker, the private-directory guard, and the turntable recipe against the action table. + No Blender; needs numpy. - `tests/live/mesh_polish.py`: every action through `run_intent` in a background Blender against real bpy - (`mesh_polish.result.json` is the last run, Blender 5.3.0). + (`mesh_polish.result.json` is the last run, Blender 5.3.0). Its sphere is a generator's in miniature: torn at + every edge, half its faces wound inside out under outward custom normals. With `BROKKR_POLISH_HULLS` set to a + directory of generated `.glb` hulls it also repairs each and checks that no face was turned. From e141782a608f807fca5b2925d409adebda98476d Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 06:46:50 +0100 Subject: [PATCH 54/63] mesh polish: boundary_root, the cut-root formula cut_parts shared with the rig Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/brokkr_mesh_polish/__init__.py | 2 +- surfaces/blender/brokkr_mesh_polish/core.py | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/surfaces/blender/brokkr_mesh_polish/__init__.py b/surfaces/blender/brokkr_mesh_polish/__init__.py index 473550d..915ab5d 100644 --- a/surfaces/blender/brokkr_mesh_polish/__init__.py +++ b/surfaces/blender/brokkr_mesh_polish/__init__.py @@ -667,7 +667,7 @@ class BROKKR_MESH_POLISH_OT_cut_parts(PolishOperator): raise Refused(f"Part {name!r} came out empty: move its seed onto the surface.") lengths = np.array([e.calc_length() for e in cut]) mids = np.array([((e.verts[0].co + e.verts[1].co) / 2)[:] for e in cut]).reshape(-1, 3) - root_local = (mids * lengths[:, None]).sum(axis=0) / lengths.sum() if len(cut) else np.zeros(3) + root_local = core.boundary_root(mids, lengths) spread = mids - root_local normal_local = np.linalg.eigh((spread * lengths[:, None]).T @ spread)[1][:, 0] if len(cut) >= 3 else np.array([0.0, 0.0, 1.0]) mean_radius = float((np.linalg.norm(spread, axis=1) * lengths).sum() / lengths.sum()) if len(cut) else 0.0 diff --git a/surfaces/blender/brokkr_mesh_polish/core.py b/surfaces/blender/brokkr_mesh_polish/core.py index 9031425..179efb0 100644 --- a/surfaces/blender/brokkr_mesh_polish/core.py +++ b/surfaces/blender/brokkr_mesh_polish/core.py @@ -259,6 +259,12 @@ def grow_parts(count: int, pairs: np.ndarray, costs: np.ndarray, seeds: list[tup return np.asarray(part, dtype=np.int64), np.asarray(best) +def boundary_root(mids: np.ndarray, lengths: np.ndarray) -> np.ndarray: + """Where a part is rooted: the length-weighted mean of the midpoints of the edges along its cut (zeros when + it has no cut).""" + return (mids * lengths[:, None]).sum(axis=0) / lengths.sum() if len(lengths) else np.zeros(3) + + def parse_seeds(text: str) -> list[tuple[str, tuple[float, float, float]]]: """'hull=0,0,0; pod1=1,0,0.5; pod1=1.2,0,0.4' as [(name, (x, y, z))]; ValueError names the bad entry.""" seeds = [] From 62e7897f156132cd8114557886b84ddfe5e488db Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 06:49:57 +0100 Subject: [PATCH 55/63] brokkr_rig: body, tendrils and colliders host actions and the VRMC_springBone export hook Rigs a fused generated mesh for the spring-bone runtime: spine and seed-part bones with weights, tendril chains grown from shape diameter and geodesic bands, body colliders shrunk to clear every spring joint, and VRMC_springBone written by Blender's own glTF exporter through a user extension. Imports brokkr_mesh_polish instead of copying it; acceptance is Aetheria's SpringRigVerify.VerifyGlb. Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/brokkr_rig/__init__.py | 519 ++++++++++++++++++ .../blender/brokkr_rig/brokkr_actions.json | 207 +++++++ surfaces/blender/brokkr_rig/core.py | 349 ++++++++++++ surfaces/blender/docs/rig.md | 123 +++++ surfaces/blender/tests/live/rig.py | 272 +++++++++ surfaces/blender/tests/live/rig.result.json | 390 +++++++++++++ surfaces/blender/tests/test_rig.py | 266 +++++++++ 7 files changed, 2126 insertions(+) create mode 100644 surfaces/blender/brokkr_rig/__init__.py create mode 100644 surfaces/blender/brokkr_rig/brokkr_actions.json create mode 100644 surfaces/blender/brokkr_rig/core.py create mode 100644 surfaces/blender/docs/rig.md create mode 100644 surfaces/blender/tests/live/rig.py create mode 100644 surfaces/blender/tests/live/rig.result.json create mode 100644 surfaces/blender/tests/test_rig.py diff --git a/surfaces/blender/brokkr_rig/__init__.py b/surfaces/blender/brokkr_rig/__init__.py new file mode 100644 index 0000000..1302b3d --- /dev/null +++ b/surfaces/blender/brokkr_rig/__init__.py @@ -0,0 +1,519 @@ +"""Rig a fused generated mesh for the spring-bone runtime: body bones and weights, tendril chains grown from the +mesh's own thickness, body colliders, and VRMC_springBone written by Blender's own glTF exporter. + +A host add-on for Brokkr beside brokkr_mesh_polish (it imports that package's operator base and arithmetic, and +nothing from Brokkr): brokkr_actions.json beside this file lists the operators agents may run (docs/rig.md). +The arithmetic is core.py (numpy, tested without Blender); this file is the bpy around it. Every operator writes +a JSON report to WindowManager.brokkr_mesh_polish_result, as the polish operators do. + +The rig lives in the scene as bones, vertex groups and bone ID properties. glTF2ExportUserExtension below reads +those properties when anything exports (Brokkr's exportGltf or File > Export) and writes VRMC_springBone into +the GLB; whether the result is acceptable is the runtime's own parse (SpringRigData.FromGlbJson), which this +add-on does not copy. +""" +bl_info = {"name": "Brokkr Rig", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0), + "category": "Rigging", "description": "Rig generated creatures for spring-bone tendrils; agent-callable through Brokkr."} + +import json +from types import SimpleNamespace + +import bpy +import numpy as np +from mathutils import Matrix, Vector +from mathutils.bvhtree import BVHTree + +try: + from brokkr_mesh_polish import RESULT, PolishOperator, Refused, arrays, mesh_object + from brokkr_mesh_polish import core as polish + MISSING = None +except ImportError as error: # register() says so; the classes below only need something to subclass + RESULT, PolishOperator, Refused, polish, MISSING = "brokkr_mesh_polish_result", bpy.types.Operator, RuntimeError, None, error + +from . import core + +CHAIN, INDEX, STIFFNESS, DRAG, GRAVITY, HIT, COLLIDERS = ("rig_chain", "rig_index", "rig_stiffness", "rig_drag", "rig_gravity", + "rig_hit_radius", "rig_colliders") +GRAVITY_DOWN = (0.0, 0.0, -1.0) # Blender world; the exporter hook turns it into glTF world + + +# --- the scene around the arithmetic --------------------------------------------------------------------- + +def armature_of(obj, name: str): + if name: + arm = bpy.data.objects.get(name) + if arm is None or arm.type != "ARMATURE": + raise Refused(f"No armature object named {name!r}.") + return arm + for modifier in obj.modifiers: + if modifier.type == "ARMATURE" and modifier.object is not None: + return modifier.object + raise Refused(f"Object {obj.name!r} has no Armature modifier: run brokkr_rig.body first or give armature_name.") + + +def welded(obj) -> SimpleNamespace: + """The mesh as the rig sees it: world positions and triangles welded over UV seams (ids maps each mesh vertex to its + welded vertex), the welded edge graph and per-vertex normals.""" + data = arrays(obj) + V, T = data["V"], data["T"] + diagonal = float(np.linalg.norm(V.max(axis=0) - V.min(axis=0))) + ids, TW = polish.weld(V, T, diagonal * 1e-5) + count = int(ids.max()) + 1 + Vw, N = np.zeros((count, 3)), np.zeros((count, 3)) + Vw[ids] = V + np.add.at(N, ids, data["N"]) + N /= np.maximum(np.linalg.norm(N, axis=1, keepdims=True), 1e-30) + return SimpleNamespace(V=V, ids=ids, Vw=Vw, TW=TW, N=N, E=core.welded_edges(TW), count=count, + diagonal=diagonal, length=float((V.max(axis=0) - V.min(axis=0)).max())) + + +class edit_mode: + """Edit Mode on an armature object for the length of the block; yields its edit bones.""" + + def __init__(self, context, arm): + self.context, self.arm = context, arm + + def __enter__(self): + self.context.view_layer.objects.active = self.arm + bpy.ops.object.mode_set(mode="EDIT") + return self.arm.data.edit_bones + + def __exit__(self, *_): + bpy.ops.object.mode_set(mode="OBJECT") + + +def spine_of(arm) -> list: + """The spine of an armature as the runtime finds it: from the first root, the child with the most descendants at + each step. Bones that belong to tendril chains are not part of the body.""" + bones = [b for b in arm.data.bones if CHAIN not in b] + kids = {b.name: [c for c in b.children if CHAIN not in c] for b in bones} + weight = {} + + def count(bone): + weight[bone.name] = 1 + sum(count(c) for c in kids[bone.name]) + return weight[bone.name] + + roots = [b for b in bones if b.parent is None or CHAIN in b.parent] + if not roots: + raise Refused(f"Armature {arm.name!r} has no body bones.") + for root in roots: + count(root) + spine, bone = [], roots[0] + while bone is not None: + spine.append(bone) + bone = max(kids[bone.name], key=lambda c: weight[c.name], default=None) + return spine + + +def write_weights(obj, names: list, ids: np.ndarray, idx: np.ndarray, w: np.ndarray): + """Replace the mesh's vertex groups with one per bone name; idx indexes names, (idx, w) per welded vertex.""" + obj.vertex_groups.clear() + groups = [obj.vertex_groups.new(name=name) for name in names] + wi, ww = idx[ids].tolist(), w[ids].tolist() + for vertex in range(len(ids)): + for b, weight in zip(wi[vertex], ww[vertex]): + if weight > 0: + groups[b].add([vertex], weight, "REPLACE") + + +def read_weights(obj, names: list, ids: np.ndarray, count: int) -> np.ndarray: + """Dense weights (welded vertices, names) of the mesh's vertex groups called names.""" + column = {obj.vertex_groups[n].index: i for i, n in enumerate(names) if n in obj.vertex_groups} + out = np.zeros((len(obj.data.vertices), len(names))) + for vertex in obj.data.vertices: + for entry in vertex.groups: + if entry.group in column: + out[vertex.index, column[entry.group]] = entry.weight + dense = np.zeros((count, len(names))) + dense[ids] = out + return dense + + +def shape_diameter(w: SimpleNamespace) -> np.ndarray: + """Per welded vertex, the median of five rays going inward (one along the reversed normal, four jittered inside a + cone, fixed seed) to the far side of the surface; a vertex whose rays find no back face (an open sheet) reads 0.""" + live = (w.TW[:, 0] != w.TW[:, 1]) & (w.TW[:, 1] != w.TW[:, 2]) & (w.TW[:, 0] != w.TW[:, 2]) + tree = BVHTree.FromPolygons([tuple(p) for p in w.Vw], [tuple(int(i) for i in t) for t in w.TW[live]]) + jitter = np.random.default_rng(0).normal(0.0, 0.35, (w.count, 4, 3)) + reach, lift = 0.5 * w.length, 1e-5 * w.length + out = np.zeros(w.count) + for i in range(w.count): + inward = -w.N[i] + hits = [] + for k in range(5): + way = inward if k == 0 else inward + jitter[i, k - 1] + way = way / max(float(np.linalg.norm(way)), 1e-30) + if way @ inward < 0.5: + continue + hit = tree.ray_cast(Vector(w.Vw[i] + way * lift), Vector(way), reach) + if hit[0] is not None: + hits.append(hit[3]) + out[i] = np.median(hits) if hits else 0.0 + return out + + +def rounded(values) -> list: + return [round(float(x), 6) for x in values] + + +# --- operators ------------------------------------------------------------------------------------------- + +class BROKKR_RIG_OT_body(PolishOperator): + """Give a mesh its body skeleton and weights: a spine along the long axis (root at the head end) and a bone + for each named seed region, or the weights alone against an armature that is already authored""" + bl_idname = "brokkr_rig.body" + bl_label = "Rig Body" + object_name: bpy.props.StringProperty(name="Object") + armature_name: bpy.props.StringProperty(name="Armature", description="An authored armature to weight against; empty makes .rig") + spine_bones: bpy.props.IntProperty(name="Spine Bones", default=8, min=2, max=32, description="Bones along the long axis of a new armature") + head: bpy.props.EnumProperty(name="Head", items=[("+y", "+Y", "The head is at the +Y end"), ("-y", "-Y", "The head is at the -Y end")], + default="+y", description="Which end of the long axis is the head: the spine's root, where the swim wave starts") + seeds: bpy.props.StringProperty(name="Seeds", maxlen=4000, + description="name=x,y,z; name=x,y,z ... world-space surface points: each name is a part with its own bone (a jaw, a fin); the spine takes the rest") + crease_cost: bpy.props.FloatProperty(name="Crease Cost", default=40.0, min=0.0, max=1000.0, + description="How strongly parts stop at concave creases; 0 splits by distance alone") + smooth_rounds: bpy.props.IntProperty(name="Smooth Rounds", default=3, min=0, max=64, description="Laplacian rounds over the weights") + + def work(self, context): + obj = mesh_object(self.object_name) + try: + seeds = polish.parse_seeds(self.seeds) if self.seeds.strip() else [] + except ValueError as error: + raise Refused(str(error)) from None + w = welded(obj) + _, frame = polish.principal_frame(w.Vw, w.TW) + axis = frame[0] / np.linalg.norm(frame[0]) + existing = bpy.data.objects.get(self.armature_name) if self.armature_name else None + if self.armature_name and (existing is None or existing.type != "ARMATURE"): + raise Refused(f"No armature object named {self.armature_name!r}.") + if existing is None: + if bpy.data.objects.get(f"{obj.name}.rig") is not None: + raise Refused(f"{obj.name}.rig exists: give armature_name={obj.name}.rig to weight against it.") + if (axis[1] < 0) == (self.head == "+y"): + axis = -axis + joints, u, length = core.spine_points(w.Vw, axis, self.spine_bones) + names = [f"spine_{i:02d}" for i in range(self.spine_bones)] + spine = [(joints[i], joints[i + 1]) for i in range(self.spine_bones)] + knots = np.arange(self.spine_bones) * (length / self.spine_bones) + others = [] # (name, head, tail) of bones the armature does not have yet; filled from the regions + wanted = [name for name, _ in seeds] + else: + matrix = np.array(existing.matrix_world) + body = spine_of(existing) + names = [b.name for b in body] + spine = [(matrix[:3, :3] @ np.array(b.head_local) + matrix[:3, 3], matrix[:3, :3] @ np.array(b.tail_local) + matrix[:3, 3]) for b in body] + if len(names) < 2: + raise Refused(f"Armature {existing.name!r} has a spine of {len(names)} bone: a spine needs 2 or more.") + if spine[0][0] @ axis < spine[-1][0] @ axis: + axis = -axis + top = w.Vw @ axis + u = top.max() - top + knots = top.max() - np.array([head @ axis for head, _ in spine]) + if np.any(np.diff(knots) <= 0): + raise Refused("The spine's bones do not run from the head end to the tail end of the mesh's long axis.") + others = [b for b in existing.data.bones if b.name not in names and CHAIN not in b] + known = {b.name for b in others} + for name, _ in seeds: + if name not in known: + raise Refused(f"Seed {name!r} names no bone of {existing.name!r} outside its spine.") + wanted = [b.name for b in others] + tails = {b.name: matrix[:3, :3] @ np.array(b.tail_local) + matrix[:3, 3] for b in others} + seeds = seeds + [(name, tail) for name, tail in tails.items()] + parts = ["spine"] + [n for n in dict.fromkeys(wanted) if n != "spine"] + pairs = polish.face_adjacency(w.TW) + centroid = w.Vw[w.TW].mean(axis=1) + nearest = lambda point: int(np.argmin(((centroid - np.asarray(point)) ** 2).sum(axis=1))) # noqa: E731 + placed = [(nearest(point), 0) for point in ([a for a, _ in spine] + [spine[-1][1]])] + placed += [(nearest(point), parts.index(name) if name in parts else 0) for name, point in seeds] + part, _ = polish.grow_parts(len(w.TW), pairs, polish.crease_costs(w.Vw, w.TW, pairs, self.crease_cost), placed) + part[part < 0] = 0 + areas = polish.triangle_areas(w.Vw, w.TW) + pa, pb, mids, lengths = core.cut_edges(w.Vw, w.TW, part) + region = [] + for p in range(1, len(parts)): + mine = part == p + if not mine.any(): + raise Refused(f"Part {parts[p]!r} came out empty: move its seed onto the surface.") + tail = (centroid[mine] * areas[mine][:, None]).sum(axis=0) / max(float(areas[mine].sum()), 1e-30) + cut = (pa == p) | (pb == p) + region.append((parts[p], polish.boundary_root(mids[cut], lengths[cut]), tail)) + if existing is None: + for name, head, tail in region: + if np.linalg.norm(tail - head) < 1e-4 * w.diagonal: + raise Refused(f"Part {name!r} has no length from its root to its centre: move its seed.") + # weights: spine bones along the axis, a region 1 on its bone, then the rounds + bones = names + [n for n in parts[1:]] + W = np.zeros((w.count, len(bones))) + W[:, :len(names)] = core.axial_weights(u, knots) + for p in range(1, len(parts)): + verts = np.unique(w.TW[part == p]) + W[verts] = 0.0 + W[verts, len(names) + p - 1] = 1.0 + idx, weight = core.top4(core.smooth(W, w.E, self.smooth_rounds)) + # the scene: bake the object's transform, make or keep the armature, skin + mesh = obj.data + mesh.transform(obj.matrix_world) + obj.parent = None + obj.matrix_world = Matrix.Identity(4) + collection = obj.users_collection[0] if obj.users_collection else context.scene.collection + if existing is None: + arm = bpy.data.objects.new(f"{obj.name}.rig", bpy.data.armatures.new(f"{obj.name}.rig")) + collection.objects.link(arm) + with edit_mode(context, arm) as edits: + for i, (head, tail) in enumerate(spine): + bone = edits.new(names[i]) + bone.head, bone.tail = Vector(head), Vector(tail) + bone.parent = edits[names[i - 1]] if i else None + for name, head, tail in region: + bone = edits.new(name) + bone.head, bone.tail = Vector(head), Vector(tail) + bone.parent = edits[names[int(np.argmin([core.segment_distance(head[None], a, b)[0] for a, b in spine]))]] + else: + arm = existing + write_weights(obj, bones, w.ids, idx, weight) + for modifier in [m for m in obj.modifiers if m.type == "ARMATURE"]: + obj.modifiers.remove(modifier) + obj.modifiers.new("Armature", "ARMATURE").object = arm + obj.parent = arm + obj.matrix_parent_inverse = arm.matrix_world.inverted() + return {"object": obj.name, "armature": arm.name, "created": existing is None, "spine": names, + "parts": [{"name": n, "root": rounded(h), "tail": rounded(t), "triangles": int((part == i + 1).sum())} + for i, (n, h, t) in enumerate(region)], + "head": rounded(spine[0][0]), "tail": rounded(spine[-1][1]), "axis": rounded(axis), + "vertices": int(len(mesh.vertices)), "weldedVertices": w.count} + + +class BROKKR_RIG_OT_tendrils(PolishOperator): + """Grow spring chains from the mesh's thin parts: skin each tendril to a chain of bones hung from the body and + mark the chains' stiffness, drag, gravity and hit radii for the exporter""" + bl_idname = "brokkr_rig.tendrils" + bl_label = "Rig Tendrils" + object_name: bpy.props.StringProperty(name="Object") + armature_name: bpy.props.StringProperty(name="Armature", description="Empty: the object's Armature modifier") + tau: bpy.props.FloatProperty(name="Tau", default=0.04, min=0.0, max=0.5, description="Shape diameter below which the surface is thin, as a share of the longest side") + band: bpy.props.FloatProperty(name="Band", default=0.04, min=0.0, max=0.5, description="Distance from the body one joint ring spans, as a share of the longest side") + dilate: bpy.props.FloatProperty(name="Dilate", default=0.04, min=0.0, max=0.5, description="How far the thick body is grown over its roots, as a share of the longest side") + fold_bands: bpy.props.FloatProperty(name="Fold Bands", default=1.5, min=0.0, max=10.0, description="A chain whose every vertex lies within this many bands of the body is a vein and folds into it") + min_joints: bpy.props.IntProperty(name="Min Joints", default=2, min=1, max=64, description="A chain with fewer rings than this folds into the body") + blend: bpy.props.FloatProperty(name="Blend", default=0.5, min=0.0, max=4.0, description="Bands over which weights blend between neighbouring bones and into the body") + stiffness: bpy.props.FloatProperty(name="Stiffness", default=3.0, min=0.0, max=1000.0, description="Rate (1 per second) a joint closes on its rest pose, at the root") + stiffness_tip_ratio: bpy.props.FloatProperty(name="Tip Ratio", default=0.5, min=0.0, max=10.0, description="Stiffness at the tip as a multiple of the root's") + drag: bpy.props.FloatProperty(name="Drag", default=0.3, min=0.0, max=1.0, description="Share of velocity a joint loses per substep") + gravity_power: bpy.props.FloatProperty(name="Gravity", default=0.0, min=0.0, max=100.0, description="Displacement per second along the world's down, in scene units") + hit_scale: bpy.props.FloatProperty(name="Hit Scale", default=1.0, min=0.0, max=10.0, description="Joint hit radius as a multiple of half the ring's median shape diameter") + + def work(self, context): + obj = mesh_object(self.object_name) + arm = armature_of(obj, self.armature_name) + w = welded(obj) + body_bones = [b for b in arm.data.bones if CHAIN not in b] + if not body_bones: + raise Refused(f"Armature {arm.name!r} has no body bones.") + body_names = [b.name for b in body_bones] + Wb = read_weights(obj, body_names, w.ids, w.count) + known = Wb.sum(axis=1) > 0 # a vertex a past run skinned to a chain has none: it takes the nearest one's + if not known.any(): + raise Refused("No vertex has weight on a body bone: run brokkr_rig.body first.") + if not known.all(): + near = core.dijkstra(core.graph(w.Vw, w.E), np.flatnonzero(known))[2] + Wb = Wb[np.where(known, np.arange(w.count), np.where(near >= 0, near, 0))] + bidx, bw = core.top4(Wb) + scale, band = w.length, self.band * w.length + sd = shape_diameter(w) + try: + found = core.extract(w.Vw, w.E, sd, self.tau * scale, band, self.dilate * scale, self.fold_bands, self.min_joints) + except ValueError as error: + raise Refused(str(error)) from None + springs = core.plan(w.Vw, sd, found, band) + for spring in springs: + spring.bone = body_names[int(np.argmax(Wb[spring.anchor].sum(axis=0)))] + idx, weight, start = core.tendril_weights(w.Vw, w.E, found, springs, bidx, bw, len(body_names), band, self.blend) + names = list(body_names) + for c, spring in enumerate(springs): + spring.names = [f"tendril_{c:03d}_{k:02d}" for k in range(len(spring.pos))] + names += spring.names + matrix = np.array(arm.matrix_world) + inverse = np.linalg.inv(matrix) + to_arm = lambda p: inverse[:3, :3] @ np.asarray(p) + inverse[:3, 3] # noqa: E731 + with edit_mode(context, arm) as edits: + for old in [e for e in edits if CHAIN in e]: + edits.remove(old) + for spring in springs: + for k, name in enumerate(spring.names): + head = spring.pos[k] + tail = spring.pos[k + 1] if k + 1 < len(spring.pos) else head + (head - spring.pos[k - 1]) * 0.5 + bone = edits.new(name) + bone.head, bone.tail = Vector(to_arm(head)), Vector(to_arm(tail)) + bone.parent = edits[spring.names[k - 1]] if k else edits[spring.bone] + for c, spring in enumerate(springs): + last = len(spring.names) - 1 + for k, name in enumerate(spring.names): + bone = arm.data.bones[name] + bone[CHAIN], bone[INDEX] = f"tendril_{c:03d}", k + bone[STIFFNESS] = self.stiffness * (1.0 + (self.stiffness_tip_ratio - 1.0) * k / last) + bone[DRAG], bone[GRAVITY] = self.drag, self.gravity_power + bone[HIT] = float(0.5 * spring.sd[k] * self.hit_scale) + arm.data["rig_gravity_dir"] = list(GRAVITY_DOWN) + write_weights(obj, names, w.ids, idx, weight) + kept = [c for c in found.chains if not c.folded] + lost = ~found.body & ~np.isfinite(found.d) + shells = len(np.unique(polish.components(w.count, w.E[lost[w.E[:, 0]] & lost[w.E[:, 1]]])[lost])) if lost.any() else 0 + branches = int(sum(1 for r in range(len(found.parent)) if not found.on_main[r] and found.parent[r] >= 0 + and found.on_main[found.parent[r]] and found.tree[r] in {c.tree for c in kept})) + return {"object": obj.name, "armature": arm.name, "bodyVertices": int(found.body.sum()), "chains": len(springs), + "springBones": int(sum(len(s.pos) for s in springs)), "branchesRigid": branches, + "veinsFolded": len(found.chains) - len(kept), "shellsAttached": shells, + "unreachedVertices": int(lost.sum()), "rings": int(len(found.parent)), + "shapeDiameterMedian": float(np.median(sd)), "tau": self.tau * scale, "band": band} + + +class BROKKR_RIG_OT_colliders(PolishOperator): + """Size body colliders for the spring chains: a capsule on each spine bone, a sphere on each other body bone, + shrunk until every spring joint past the first stands outside its hit radius at rest""" + bl_idname = "brokkr_rig.colliders" + bl_label = "Rig Colliders" + object_name: bpy.props.StringProperty(name="Object") + armature_name: bpy.props.StringProperty(name="Armature", description="Empty: the object's Armature modifier") + scale: bpy.props.FloatProperty(name="Scale", default=0.8, min=0.0, max=2.0, description="Collider radius as a multiple of the median radius of the body around it") + + def work(self, context): + obj = mesh_object(self.object_name) + arm = armature_of(obj, self.armature_name) + w = welded(obj) + matrix = np.array(arm.matrix_world) + world = lambda p: matrix[:3, :3] @ np.array(p) + matrix[:3, 3] # noqa: E731 + body = [b for b in arm.data.bones if CHAIN not in b] + spine = {b.name for b in spine_of(arm)} + Wb = read_weights(obj, [b.name for b in body], w.ids, w.count) + solid = Wb.sum(axis=1) >= 0.5 + heaviest = Wb.argmax(axis=1) + chain = [b for b in arm.data.bones if CHAIN in b and b[INDEX] >= 1] + joints = np.array([world(b.head_local) for b in chain]).reshape(-1, 3) + hit = np.array([b[HIT] for b in chain]) + made = {"capsules": 0, "spheres": 0, "shrunk": 0, "dropped": 0, "skipped": 0} + for bone in body: + if COLLIDERS in bone: + del bone[COLLIDERS] + for column, bone in enumerate(body): + head, tail = world(bone.head_local), world(bone.tail_local) + if bone.name in spine: + radius = core.capsule_radius(w.Vw[solid], head, tail, self.scale) + shape, offset, end = "capsule", head, tail + else: + mine = solid & (heaviest == column) + if not mine.any(): + made["skipped"] += 1 + continue + offset, radius = core.sphere_fit(w.Vw[mine], self.scale) + shape, end = "sphere", offset + cleared = core.clear_radius(radius, joints, hit, offset, end) + if cleared < radius: + made["shrunk"] += 1 + if cleared <= 0: + made["dropped"] += 1 + continue + entry = {"shape": shape, "offset": rounded(offset), "radius": float(cleared)} + if shape == "capsule": + entry["tail"] = rounded(end) + bone[COLLIDERS] = [entry] + made["capsules" if shape == "capsule" else "spheres"] += 1 + made.update({"object": obj.name, "armature": arm.name, "springJoints": len(chain)}) + return made + + +# --- the export hook: VRMC_springBone ---------------------------------------------------------------------- + +def _node_matrix(node) -> np.ndarray: + if getattr(node, "matrix", None): + return np.array(node.matrix, dtype=np.float64).reshape(4, 4).T + x, y, z, s = node.rotation if getattr(node, "rotation", None) else (0.0, 0.0, 0.0, 1.0) + rotation = np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * s), 2 * (x * z + y * s)], + [2 * (x * y + z * s), 1 - 2 * (x * x + z * z), 2 * (y * z - x * s)], + [2 * (x * z - y * s), 2 * (y * z + x * s), 1 - 2 * (x * x + y * y)]]) + scale = np.array(node.scale) if getattr(node, "scale", None) else np.ones(3) + local = np.eye(4) + local[:3, :3] = rotation * scale + local[:3, 3] = node.translation if getattr(node, "translation", None) else (0.0, 0.0, 0.0) + return local + + +def _spring_bone(gltf, export_settings) -> dict | None: + """The VRMC_springBone object for the armatures this export carries (those with brokkr_rig chains whose bones all + became nodes), or None when there are none.""" + nodes = gltf.nodes or [] + node_of = {node.name: i for i, node in enumerate(nodes)} + parent = {} + for i, node in enumerate(nodes): + for child in node.children or []: + parent[child if isinstance(child, int) else next(j for j, n in enumerate(nodes) if n is child)] = i + world = {} + + def matrix_of(i): + if i not in world: + world[i] = (matrix_of(parent[i]) if i in parent else np.eye(4)) @ _node_matrix(nodes[i]) + return world[i] + + yup = bool(export_settings.get("gltf_yup", True)) + swing = np.array([[1.0, 0, 0], [0, 0, 1.0], [0, -1.0, 0]]) if yup else np.eye(3) + local = lambda i, p: (np.linalg.inv(matrix_of(i)) @ np.append(swing @ np.asarray(p, dtype=np.float64), 1.0))[:3].tolist() # noqa: E731 + springs, colliders = [], [] + for arm in sorted((o for o in bpy.data.objects if o.type == "ARMATURE"), key=lambda o: o.name): + by_chain = {} + for bone in arm.data.bones: + if CHAIN in bone: + by_chain.setdefault(bone[CHAIN], []).append(bone) + gravity = (swing @ np.asarray(list(arm.data.get("rig_gravity_dir", GRAVITY_DOWN)), dtype=np.float64)).tolist() + for name in sorted(by_chain): + chain = sorted(by_chain[name], key=lambda b: b[INDEX]) + if not all(b.name in node_of for b in chain): + continue + springs.append({"name": name, "colliderGroups": [0], "joints": [ + {"node": node_of[b.name], "hitRadius": float(b[HIT]), "stiffness": float(b[STIFFNESS]), "gravityPower": float(b[GRAVITY]), + "gravityDir": gravity, "dragForce": float(b[DRAG])} for b in chain]}) + for bone in arm.data.bones: + if COLLIDERS in bone and bone.name in node_of: + for entry in bone[COLLIDERS]: + entry = entry.to_dict() if hasattr(entry, "to_dict") else entry + at = node_of[bone.name] + shape = {"offset": local(at, entry["offset"]), "radius": float(entry["radius"])} + if entry["shape"] == "capsule": + shape["tail"] = local(at, entry["tail"]) + colliders.append({"node": at, "shape": {entry["shape"]: shape}}) + if not springs: + return None + if not colliders: + springs = [{k: v for k, v in s.items() if k != "colliderGroups"} for s in springs] + return {"specVersion": "1.0", "colliders": colliders, + "colliderGroups": [{"name": "body", "colliders": list(range(len(colliders)))}] if colliders else [], "springs": springs} + + +class glTF2ExportUserExtension: + """Blender's glTF exporter finds this class on every enabled add-on and calls its hook once the nodes are final.""" + + def __init__(self): + from io_scene_gltf2.io.com.gltf2_io_extensions import Extension + self.Extension = Extension + + def gather_gltf_extensions_hook(self, gltf, export_settings): + spring = _spring_bone(gltf, export_settings) + if spring is None: + return + gltf.extensions = gltf.extensions or {} + gltf.extensions["VRMC_springBone"] = self.Extension(name="VRMC_springBone", extension=spring, required=False) + gltf.extensions_used = gltf.extensions_used or [] + if "VRMC_springBone" not in gltf.extensions_used: + gltf.extensions_used.append("VRMC_springBone") + + +classes = (BROKKR_RIG_OT_body, BROKKR_RIG_OT_tendrils, BROKKR_RIG_OT_colliders) + + +def register(): + if MISSING is not None or not hasattr(bpy.types.WindowManager, RESULT): + raise RuntimeError(f"brokkr_rig needs brokkr_mesh_polish enabled first ({MISSING or 'its result property is not registered'}).") + for cls in classes: + bpy.utils.register_class(cls) + + +def unregister(): + for cls in reversed(classes): + bpy.utils.unregister_class(cls) diff --git a/surfaces/blender/brokkr_rig/brokkr_actions.json b/surfaces/blender/brokkr_rig/brokkr_actions.json new file mode 100644 index 0000000..d258802 --- /dev/null +++ b/surfaces/blender/brokkr_rig/brokkr_actions.json @@ -0,0 +1,207 @@ +{ + "schema": "brokkr.blender.host_actions.v0", + "actions": [ + { + "name": "brokkr_rig.body", + "doc": "Skin a mesh to its body: a new spine along the long axis (root at the head end) with a bone per seed part, or an authored armature, weighted. Bakes the object's transform.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63 + }, + { + "name": "armature_name", + "type": "string", + "maxLength": 63, + "doc": "an authored armature to weight against, kept as it is; empty makes .rig" + }, + { + "name": "spine_bones", + "type": "integer", + "minimum": 2, + "maximum": 32, + "default": 8, + "doc": "bones along the long axis of a new armature" + }, + { + "name": "head", + "type": "string", + "enum": [ + "+y", + "-y" + ], + "default": "+y", + "doc": "which end of the long axis is the head, the spine's root" + }, + { + "name": "seeds", + "type": "string", + "maxLength": 4000, + "doc": "name=x,y,z; name=x,y,z ... world-space surface points; each name is a part with its own bone, the spine takes the rest" + }, + { + "name": "crease_cost", + "type": "number", + "minimum": 0, + "maximum": 1000, + "default": 40, + "doc": "how strongly parts stop at concave creases" + }, + { + "name": "smooth_rounds", + "type": "integer", + "minimum": 0, + "maximum": 64, + "default": 3, + "doc": "Laplacian rounds over the weights" + } + ] + }, + { + "name": "brokkr_rig.tendrils", + "doc": "Grow spring chains from the thin parts of a skinned mesh: one bone chain per tendril hung from a body bone, weights, and spring parameters for the exporter.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63 + }, + { + "name": "armature_name", + "type": "string", + "maxLength": 63, + "doc": "an armature object; the object's Armature modifier when absent" + }, + { + "name": "tau", + "type": "number", + "minimum": 0.001, + "maximum": 0.5, + "default": 0.04, + "doc": "shape diameter below which the surface is thin, as a share of the longest side" + }, + { + "name": "band", + "type": "number", + "minimum": 0.002, + "maximum": 0.5, + "default": 0.04, + "doc": "distance from the body one joint ring spans, as a share of the longest side" + }, + { + "name": "dilate", + "type": "number", + "minimum": 0, + "maximum": 0.5, + "default": 0.04, + "doc": "how far the thick body is grown over its roots, as a share of the longest side" + }, + { + "name": "fold_bands", + "type": "number", + "minimum": 0, + "maximum": 10, + "default": 1.5, + "doc": "a chain whose every vertex lies within this many bands of the body is a vein and folds into it" + }, + { + "name": "min_joints", + "type": "integer", + "minimum": 1, + "maximum": 64, + "default": 2, + "doc": "a chain with fewer rings than this folds into the body" + }, + { + "name": "blend", + "type": "number", + "minimum": 0, + "maximum": 4, + "default": 0.5, + "doc": "bands over which weights blend between neighbouring bones and into the body" + }, + { + "name": "stiffness", + "type": "number", + "minimum": 0.01, + "maximum": 1000, + "default": 3, + "doc": "rate (1 per second) a joint closes on its rest pose, at the root" + }, + { + "name": "stiffness_tip_ratio", + "type": "number", + "minimum": 0.01, + "maximum": 10, + "default": 0.5, + "doc": "stiffness at the tip as a multiple of the root's" + }, + { + "name": "drag", + "type": "number", + "minimum": 0, + "maximum": 1, + "default": 0.3, + "doc": "share of velocity a joint loses per substep" + }, + { + "name": "gravity_power", + "type": "number", + "minimum": 0, + "maximum": 100, + "default": 0, + "doc": "displacement per second along the world's down, in scene units" + }, + { + "name": "hit_scale", + "type": "number", + "minimum": 0, + "maximum": 10, + "default": 1, + "doc": "joint hit radius as a multiple of half the ring's median shape diameter" + } + ] + }, + { + "name": "brokkr_rig.colliders", + "doc": "Size body colliders for the spring chains: a capsule per spine bone, a sphere per other body bone, shrunk to clear every spring joint past the first.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63 + }, + { + "name": "armature_name", + "type": "string", + "maxLength": 63, + "doc": "an armature object; the object's Armature modifier when absent" + }, + { + "name": "scale", + "type": "number", + "minimum": 0.05, + "maximum": 2, + "default": 0.8, + "doc": "collider radius as a multiple of the median radius of the body around it" + } + ] + } + ] +} \ No newline at end of file diff --git a/surfaces/blender/brokkr_rig/core.py b/surfaces/blender/brokkr_rig/core.py new file mode 100644 index 0000000..5dde1d9 --- /dev/null +++ b/surfaces/blender/brokkr_rig/core.py @@ -0,0 +1,349 @@ +"""The arithmetic of the rig builder: numpy only, no bpy, so every rule here is tested without Blender. + +A mesh is welded positions V (n,3) and unique edges E (k,2) of the welded graph (mesh polish's weld, so a vertex +split at a UV seam is one vertex here). Skin weights are (idx, w): four bone indices and four weights per vertex. + +Tendril extraction is a level-set walk from a thick body: every vertex gets a geodesic distance from the body, +the distance is cut into bands, each band into connected rings, and a ring is one joint at its centroid whose +parent is the ring one band nearer. Each tree's root-to-deepest-leaf path is one spring; the rest of the tree +rides the path rigidly. +""" +from __future__ import annotations + +import heapq +from types import SimpleNamespace + +import numpy as np +from brokkr_mesh_polish.core import components + + +# --- graph ----------------------------------------------------------------------------------------------- + +def welded_edges(TW: np.ndarray) -> np.ndarray: + """Unique edges (k,2), low id first, of the welded triangles; triangles that collapsed in the weld add none.""" + live = (TW[:, 0] != TW[:, 1]) & (TW[:, 1] != TW[:, 2]) & (TW[:, 0] != TW[:, 2]) + tw = TW[live] + return np.unique(np.sort(np.concatenate([tw[:, [0, 1]], tw[:, [1, 2]], tw[:, [2, 0]]]), axis=1), axis=0) + + +def graph(V: np.ndarray, E: np.ndarray) -> tuple[list, list, list]: + """Adjacency in compressed rows: (start, target, length); the neighbours of v are target[start[v]:start[v + 1]].""" + length = np.linalg.norm(V[E[:, 0]] - V[E[:, 1]], axis=1) + source = np.concatenate([E[:, 0], E[:, 1]]) + order = np.argsort(source, kind="stable") + return (np.searchsorted(source[order], np.arange(len(V) + 1)).tolist(), + np.concatenate([E[:, 1], E[:, 0]])[order].tolist(), np.concatenate([length, length])[order].tolist()) + + +def dijkstra(g: tuple, sources: np.ndarray, limit: float = float("inf")) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """(distance, predecessor, origin) over the edge graph from several sources; distance is inf, predecessor + and origin -1, where no source reaches within limit.""" + start, target, length = g + n = len(start) - 1 + best = [float("inf")] * n + pred = [-1] * n + origin = [-1] * n + heap = [] + for s in sources.tolist(): + best[s], origin[s] = 0.0, s + heap.append((0.0, s)) + heapq.heapify(heap) + while heap: + cost, u = heapq.heappop(heap) + if cost > best[u]: + continue + for k in range(start[u], start[u + 1]): + w, reach = target[k], cost + length[k] + if reach < best[w] and reach <= limit: + best[w], pred[w], origin[w] = reach, u, origin[u] + heapq.heappush(heap, (reach, w)) + return np.asarray(best), np.asarray(pred, dtype=np.int64), np.asarray(origin, dtype=np.int64) + + +# --- weights --------------------------------------------------------------------------------------------- + +def top4(W: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """(idx, w) of a dense weight matrix (n,bones): the four heaviest per vertex, normalised to sum 1.""" + keep = min(4, W.shape[1]) + idx = np.argsort(-W, axis=1, kind="stable")[:, :keep] + w = np.take_along_axis(W, idx, axis=1) + total = w.sum(axis=1, keepdims=True) + w = np.where(total > 0, w / np.maximum(total, 1e-30), 0.0) + if keep < 4: + idx, w = np.pad(idx, ((0, 0), (0, 4 - keep))), np.pad(w, ((0, 0), (0, 4 - keep))) + return idx, w + + +def axial_weights(u: np.ndarray, knots: np.ndarray) -> np.ndarray: + """(n, len(knots)): bone i weighs 1 at knot i and falls linearly to 0 at knot i + 1, where bone i + 1 takes over; + before the first knot and past the last, one bone. knots increase.""" + count = len(knots) + W = np.zeros((len(u), count)) + at = np.clip(np.searchsorted(knots, u, side="right") - 1, 0, count - 1) + nxt = np.minimum(at + 1, count - 1) + span = knots[nxt] - knots[at] + t = np.where(span > 0, np.clip((u - knots[at]) / np.where(span > 0, span, 1.0), 0.0, 1.0), 0.0) + rows = np.arange(len(u)) + W[rows, at] += 1.0 - t + W[rows, nxt] += t + return W + + +def smooth(W: np.ndarray, E: np.ndarray, rounds: int) -> np.ndarray: + """Laplacian rounds over the vertex graph: each vertex takes half its own weights and half its neighbours' mean.""" + degree = np.maximum(np.bincount(E.reshape(-1), minlength=len(W)), 1)[:, None] + for _ in range(rounds): + near = np.zeros_like(W) + np.add.at(near, E[:, 0], W[E[:, 1]]) + np.add.at(near, E[:, 1], W[E[:, 0]]) + W = 0.5 * W + 0.5 * near / degree + return W + + +def spine_points(V: np.ndarray, axis: np.ndarray, count: int) -> tuple[np.ndarray, np.ndarray, float]: + """(joints (count + 1,3), u, length): count equal bones from the head end (the far end along axis) to the tail + end, each joint centred on the median of the vertices around it; u is every vertex's distance from the head + end along axis, length the extent.""" + a = V @ axis + head, tail = float(a.max()), float(a.min()) + u = head - a + length = head - tail + step = length / count + side = V - np.outer(a, axis) + joints = np.empty((count + 1, 3)) + for i in range(count + 1): + near = np.abs(u - i * step) <= step + joints[i] = axis * (head - i * step) + (np.median(side[near], axis=0) if near.any() else 0.0) + return joints, u, length + + +def cut_edges(V: np.ndarray, TW: np.ndarray, part: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """The welded edges whose two triangles lie in different parts: (part a, part b, midpoint, length).""" + count = len(TW) + edges = np.sort(np.concatenate([TW[:, [0, 1]], TW[:, [1, 2]], TW[:, [2, 0]]]), axis=1) + face = np.tile(np.arange(count), 3) + order = np.lexsort((edges[:, 1], edges[:, 0])) + edges, face = edges[order], face[order] + same = (edges[1:] == edges[:-1]).all(axis=1) + i, j, e = face[:-1][same], face[1:][same], edges[:-1][same] + cut = part[i] != part[j] + e = e[cut] + return part[i][cut], part[j][cut], (V[e[:, 0]] + V[e[:, 1]]) / 2.0, np.linalg.norm(V[e[:, 0]] - V[e[:, 1]], axis=1) + + +# --- tendril extraction ---------------------------------------------------------------------------------- + +def body_region(g: tuple, E: np.ndarray, sd: np.ndarray, tau: float, dilate: float) -> np.ndarray: + """The body: the largest connected set of vertices whose shape diameter is at least tau (a vertex in an open + sheet reads 0 and is thin), grown geodesically by dilate.""" + n = len(sd) + thick = sd >= tau + if not thick.any(): + raise ValueError("no vertex is thicker than tau: lower tau") + label = components(n, E[thick[E[:, 0]] & thick[E[:, 1]]]) + body = thick & (label == np.bincount(label[thick], minlength=n).argmax()) + if dilate > 0: + body = np.isfinite(dijkstra(g, np.flatnonzero(body), dilate)[0]) + return body + + +def extract(V: np.ndarray, E: np.ndarray, sd: np.ndarray, tau: float, band: float, dilate: float, + fold_bands: float, min_joints: int) -> SimpleNamespace: + """Rings, the joint tree and the chains. tau, band and dilate are lengths. + + Returns: body, d (distance from the body), origin (nearest body vertex), ring (per vertex, -1 off the rings), + and per ring: parent (-1 touches the body), band, centroid, dist (mean distance), size, tree, on_main, fork + (the main-path ring a branch ring rides), index (position on its main path). chains is a list of + SimpleNamespace(tree, rings, folded): rings is the main path, root first; a tree whose farthest vertex is + within fold_bands bands of the body, or whose main path has fewer than min_joints rings, is folded + (a vein lying on the body).""" + n = len(V) + g = graph(V, E) + body = body_region(g, E, sd, tau, dilate) + d, pred, origin = dijkstra(g, np.flatnonzero(body)) + free = ~body & np.isfinite(d) + band_of = np.where(free, np.floor(d / band), -1).astype(np.int64) + same = free[E[:, 0]] & free[E[:, 1]] & (band_of[E[:, 0]] == band_of[E[:, 1]]) + label = components(n, E[same]) + ids = np.unique(label[free]) + ring = np.full(n, -1, dtype=np.int64) + ring[free] = np.searchsorted(ids, label[free]) + R = len(ids) + r = ring[free] + size = np.bincount(r, minlength=R) + centroid = np.stack([np.bincount(r, weights=V[free][:, k], minlength=R) for k in range(3)], axis=1) / np.maximum(size, 1)[:, None] + dist = np.bincount(r, weights=d[free], minlength=R) / np.maximum(size, 1) + ring_band = np.zeros(R, dtype=np.int64) + ring_band[r] = band_of[free] + far = np.zeros(R) + np.maximum.at(far, r, d[free]) + # a ring hangs from the ring its nearest vertex was reached through: one band nearer, or the body + near = np.flatnonzero(free) + near = near[np.lexsort((near, d[near], ring[near]))] + first = near[np.unique(ring[near], return_index=True)[1]] + up = pred[first] + parent = np.where(body[up], -1, ring[up]) + # the main path of each tree: at each ring the child with the tallest subtree (then the most vertices, then the lowest id) + order = np.argsort(-ring_band, kind="stable") + height = np.ones(R, dtype=np.int64) + main = np.full(R, -1, dtype=np.int64) + for c in order.tolist(): + if main[c] >= 0: + height[c] = 1 + height[main[c]] + p = parent[c] + if p >= 0 and (main[p] < 0 or (height[c], size[c], -c) > (height[main[p]], size[main[p]], -main[p])): + main[p] = c + tree = np.arange(R) + on_main = np.zeros(R, dtype=bool) + fork = np.arange(R) + index = np.zeros(R, dtype=np.int64) + for c in order[::-1].tolist(): + p = parent[c] + if p < 0: + on_main[c] = True + continue + tree[c] = tree[p] + on_main[c] = on_main[p] and main[p] == c + fork[c] = c if on_main[c] else fork[p] + index[c] = index[p] + 1 if on_main[c] else 0 + reach = np.zeros(R) + np.maximum.at(reach, tree, far) + chains = [] + for root in np.flatnonzero(parent < 0).tolist(): + path = [root] + while main[path[-1]] >= 0: + path.append(int(main[path[-1]])) + chains.append(SimpleNamespace(tree=root, rings=path, folded=bool(reach[root] <= fold_bands * band or len(path) < min_joints))) + return SimpleNamespace(body=body, d=d, pred=pred, origin=origin, ring=ring, parent=parent, band=ring_band, centroid=centroid, + dist=dist, size=size, tree=tree, on_main=on_main, fork=fork, index=index, chains=chains) + + +def plan(V: np.ndarray, sd: np.ndarray, found: SimpleNamespace, band: float) -> list[SimpleNamespace]: + """The springs: for each kept chain its joints (a ring's centroid each, then the tip at the leaf ring's + farthest vertex), the distance of each from the body, the median shape diameter of each ring, and the + vertex of the body the chain's first ring leaves from. The tip stands at least a quarter band from the last + ring's centroid.""" + out = [] + for chain in found.chains: + if chain.folded: + continue + rings = chain.rings + pos = [found.centroid[r] for r in rings] + dist = [float(found.dist[r]) for r in rings] + leaf = np.flatnonzero(found.ring == rings[-1]) + tip = leaf[np.argmax(found.d[leaf])] + tip_pos, tip_dist = V[tip].copy(), float(found.d[tip]) + gap = 0.25 * band + if np.linalg.norm(tip_pos - pos[-1]) < gap: + way = pos[-1] - (pos[-2] if len(pos) > 1 else V[found.origin[leaf[0]]]) + way = way / np.linalg.norm(way) if np.linalg.norm(way) > 0 else np.array([0.0, 0.0, 1.0]) + tip_pos, tip_dist = pos[-1] + way * gap, max(tip_dist, dist[-1] + gap) + hit = [float(np.median(sd[found.ring == r])) for r in rings] + [float(np.median(sd[leaf]))] + out.append(SimpleNamespace(tree=chain.tree, rings=rings, pos=np.array(pos + [tip_pos]), dist=np.array(dist + [tip_dist]), + sd=np.array(hit), anchor=np.unique(found.origin[found.ring == rings[0]]))) + return out + + +def tendril_weights(V: np.ndarray, E: np.ndarray, found: SimpleNamespace, springs: list, body_idx: np.ndarray, + body_w: np.ndarray, bodies: int, band: float, blend: float) -> tuple[np.ndarray, np.ndarray, list]: + """(idx, w, start): skin weights over bodies body bones then every spring's bones, spring c owning bones + start[c] .. start[c] + len(pos) - 1 (its rings, then the tip). + + A vertex on a spring's main path, at distance x from the body, takes bone k, the last joint at or before x, + blending linearly from bone k - 1 over blend bands from joint k (a joint's distance is its ring's mean); + a branch ring rides the main-path bone at its fork; a vertex within blend bands of the body takes the body + weights of its nearest body vertex in the complement; a folded vein takes those body weights; a vertex the + distance never reaches takes, per shell, the nearest spring bone.""" + n = len(V) + start, at = [], bodies + for s in springs: + start.append(at) + at += len(s.pos) + chain_of = {s.tree: c for c, s in enumerate(springs)} + ring_joint = {} # ring -> (spring, joint index) on the main path + for c, s in enumerate(springs): + for k, r in enumerate(s.rings): + ring_joint[r] = (c, k) + reach = blend * band + out = [None] * n + for v in range(n): + if found.body[v]: + out[v] = {int(b): float(w) for b, w in zip(body_idx[v], body_w[v]) if w > 0} + continue + r = found.ring[v] + if r < 0: + continue + near = int(found.origin[v]) + c = chain_of.get(int(found.tree[r])) + if c is None: + out[v] = {int(b): float(w) for b, w in zip(body_idx[near], body_w[near]) if w > 0} + continue + s = springs[c] + if found.on_main[r]: + k = int(np.searchsorted(s.dist, found.d[v], side="right")) - 1 + if k <= 0: + mix = {start[c]: 1.0} + else: + t = min((found.d[v] - s.dist[k]) / reach, 1.0) if reach > 0 else 1.0 + mix = {start[c] + k: t, **({start[c] + k - 1: 1.0 - t} if k > 0 and t < 1.0 else {})} + else: + mix = {start[c] + ring_joint[int(found.fork[r])][1]: 1.0} + share = min(found.d[v] / reach, 1.0) if reach > 0 else 1.0 + row = {b: w * share for b, w in mix.items()} + if share < 1.0: + for b, w in zip(body_idx[near], body_w[near]): + row[int(b)] = row.get(int(b), 0.0) + float(w) * (1.0 - share) + out[v] = row + lost = [v for v in range(n) if out[v] is None] + if lost: + lost = np.asarray(lost) + bone_pos = np.concatenate([s.pos for s in springs]) if springs else np.zeros((0, 3)) + bone_id = np.concatenate([start[c] + np.arange(len(s.pos)) for c, s in enumerate(springs)]) if springs else np.zeros(0, dtype=int) + pairs = E[np.isin(E[:, 0], lost) & np.isin(E[:, 1], lost)] + shell = components(n, pairs) + for label in np.unique(shell[lost]): + members = lost[shell[lost] == label] + if len(bone_pos): + bone = int(bone_id[np.argmin(np.linalg.norm(bone_pos - V[members].mean(axis=0), axis=1))]) + for v in members.tolist(): + out[v] = {bone: 1.0} + else: + for v in members.tolist(): + out[v] = {int(b): float(w) for b, w in zip(body_idx[v], body_w[v]) if w > 0} + idx, w = np.zeros((n, 4), dtype=np.int64), np.zeros((n, 4)) + for v, row in enumerate(out): + top = sorted(row.items(), key=lambda item: (-item[1], item[0]))[:4] + total = sum(x for _, x in top) + for slot, (b, x) in enumerate(top): + idx[v, slot], w[v, slot] = b, x / total + return idx, w, start + + +# --- colliders ------------------------------------------------------------------------------------------- + +def segment_distance(P: np.ndarray, a: np.ndarray, b: np.ndarray) -> np.ndarray: + """Distance from each point of P (k,3) to the segment a-b (a point when a == b).""" + ab = b - a + along = np.clip(((P - a) @ ab) / max(float(ab @ ab), 1e-30), 0.0, 1.0) + return np.linalg.norm(P - (a + along[:, None] * ab), axis=1) + + +def capsule_radius(V: np.ndarray, head: np.ndarray, tail: np.ndarray, scale: float) -> float: + """The median distance from the axis head-tail of the vertices that project onto it, times scale (0 if none).""" + ab = tail - head + t = ((V - head) @ ab) / max(float(ab @ ab), 1e-30) + on = (t >= 0.0) & (t <= 1.0) + return float(np.median(segment_distance(V[on], head, tail)) * scale) if on.any() else 0.0 + + +def sphere_fit(V: np.ndarray, scale: float) -> tuple[np.ndarray, float]: + """(centre, radius): the centroid of the vertices and the median distance from it, times scale.""" + centre = V.mean(axis=0) + return centre, float(np.median(np.linalg.norm(V - centre, axis=1)) * scale) + + +def clear_radius(radius: float, joints: np.ndarray, hit: np.ndarray, a: np.ndarray, b: np.ndarray) -> float: + """radius shrunk until every joint (k,3) stands at least its hit radius outside the capsule a-b (a sphere when a == b).""" + if not len(joints): + return radius + return min(radius, float((segment_distance(joints, a, b) - hit).min())) diff --git a/surfaces/blender/docs/rig.md b/surfaces/blender/docs/rig.md new file mode 100644 index 0000000..1b3a0b9 --- /dev/null +++ b/surfaces/blender/docs/rig.md @@ -0,0 +1,123 @@ +# Rigging generated creatures for spring-bone tendrils + +`surfaces/blender/brokkr_rig` is a Blender add-on that rigs a fused generated mesh (Tripo and its kin: one skin, +body and tendrils welded together) for a spring-bone runtime. 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, +`Refused`, `mesh_object`, `arrays` and arithmetic (weld, components, face adjacency, crease costs, seed growing, +`principal_frame`, `boundary_root`) instead of copying them, and nothing from `brokkr_bridge`. Enable +`brokkr_mesh_polish` first; `brokkr_rig` refuses to register without it. `brokkr_actions.json` beside its +`__init__.py` lists the three operators agents may run; the arithmetic is `core.py` (numpy only, tested without +Blender). Every action writes a JSON report to `brokkr_mesh_polish_result`, returned in the receipt's `hostResult`. + +## The contract it produces, and who owns it + +The GLB the exporter writes has one skin over every bone, every node with translation and rotation at unit scale +and no matrix, mesh primitives with exactly `POSITION`, `NORMAL`, `TEXCOORD_0`, `JOINTS_0`, `WEIGHTS_0` (at most 4 +influences, weights summing to 1), and `VRMC_springBone` 1.0: each spring a linear chain whose first joint hangs +from a body bone, colliders only on body bones in one group `body` named by every spring. Stiffness is a rate in +1 per second, not VRM's unit. + +Whether a GLB is acceptable is **Aetheria's** `SpringRigData.FromGlbJson`, not this add-on, which ships no copy of +its refusals. Run the owner's code on the output with `SpringRigVerify.VerifyGlb` (Aetheria, batch mode): + +```text +SPRINGRIG_GLB= Unity -batchmode -projectPath \ + -executeMethod Aetheria.EditorTools.SpringRigVerify.VerifyGlb -logFile +``` + +(no `-nographics`, no `-quit`; one Unity batch instance at a time). It logs the rig's bone, body, chain, joint and +collider counts and exits 0 on PASS. + +## Export + +There is no export action of its own: Brokkr's `exportGltf` (or File > Export > glTF) writes the GLB, and the +add-on's `glTF2ExportUserExtension` hook writes `VRMC_springBone` into it, mapping bone names to node indices from +the exporter's final node list. It acts only when an exported armature carries `brokkr_rig` chains, so any other +export is untouched. Collider offsets and capsule tails are stored in Blender world space on the body bones and +composed into each collider node's local glTF frame at export from the exported nodes' translation, rotation and +scale; the gravity direction goes into glTF world. Both follow `export_yup`. + +## Actions + +### body + +`brokkr_rig.body` (`object_name`, `armature_name`, `spine_bones` 2-32, `head` `+y`/`-y`, `seeds`, `crease_cost`, +`smooth_rounds`). Bakes the object's transform into its mesh and parents it to the armature at identity, so no +node carries a scale. + +With no `armature_name` it makes `.rig`: a spine of equal bones along the principal axis, the root at the +head end (`head` names which end of world Y; the swim wave runs head to tail), and one bone per seed name. `seeds` +reads as in `cut_parts` (`name=x,y,z; ...`, several points may name one part). The spine is an implicit part named +`spine` seeded at the surface nearest each spine joint; a seed named `spine` adds to it. Each named part is grown +from its seeds along concave creases (`grow_parts`); its bone runs from the root of the part's cut +(`boundary_root`) to its centroid and hangs from the nearest spine bone. + +With an existing `armature_name` the armature is kept as it is: its spine is the first root's heaviest-child chain +(as the runtime derives it), every other body bone is seeded at the surface nearest its tail (`seeds` may add +points for a bone by name). The spine's bones must run from the head end to the tail end along the long axis. + +Weights: spine bones by axial projection, linear between neighbouring joints; a part's region 1 on its bone; then +`smooth_rounds` Laplacian rounds over the welded vertex graph, the top 4 kept and normalised. + +### tendrils + +`brokkr_rig.tendrils` (`object_name`, `armature_name`, `tau`, `band`, `dilate` as shares of the longest side, +`fold_bands`, `min_joints`, `blend`, `stiffness`, `stiffness_tip_ratio`, `drag`, `gravity_power`, `hit_scale`). +Needs `body` first. The mesh is welded; each vertex gets a shape diameter (median of five inward rays, fixed +seed; an open sheet with no back face reads 0). The body is the largest component thicker than `tau`, dilated by +`dilate`. Edge distance from the body is cut into bands of `band`; each band splits into connected rings, one +joint per ring at its centroid, its parent the ring it touches one band nearer. + +- A tree (everything hanging from one root ring) whose farthest vertex lies within `fold_bands` bands of the body + is a surface vein and folds into the body; so does a tree whose main path has fewer than `min_joints` rings. +- Each remaining tree's root-to-deepest-leaf path is one spring, ending in a tip joint at the leaf ring's farthest + vertex (the runtime gives a chain's last joint its parent's aimed rotation). Side branches cannot be springs of + their own (a spring's first joint must hang from a body bone), so their vertices weight rigidly to the main-path + bone at their fork. +- Vertices the distance never reaches (detached shells) weight rigidly, per shell, to the nearest spring bone. +- Weights: a vertex between joints k and k+1 goes to bone k, blending linearly from bone k-1 over `blend` bands + from joint k, and with the body weights of its nearest body vertex within `blend` bands of the body. +- Bones `tendril__`; joint 0 hangs from the body bone with most weight at its ring's body boundary. Bone + ID properties: `rig_chain`, `rig_index`, `rig_stiffness` (tapered from the root to the tip by + `stiffness_tip_ratio`), `rig_drag`, `rig_gravity`, `rig_hit_radius` (half the ring's median shape diameter times + `hit_scale`). Running it again replaces every earlier chain. + +The report counts chains, spring bones, rigid branches, veins folded, shells attached and unreached vertices. + +### colliders + +`brokkr_rig.colliders` (`object_name`, `armature_name`, `scale`). A capsule per spine bone from head to tail, +radius the median radial distance of the body vertices projecting onto it times `scale`; a sphere per other body +bone at the centroid of its heaviest vertices, radius the median distance times `scale`. Each radius is then +shrunk until every spring joint past the first stands at least its hit radius outside it at rest (`shrunk` counts +them). Stored as the bone's `rig_colliders` property list. + +## What it cannot do + +It does not judge a rig: acceptance is the runtime's parse. It does not simulate the springs (the report's +chain, joint and collider counts are what was built, not how it moves). It reads thickness from rays against the +mesh, so a mesh whose windings face inward needs `repair` and `recalc_normals` first. A vein the dilation reaches +is absorbed before the fold rule sees it. Seeds on a smooth surface split by distance alone. + +## A recipe + +```json +{"requestedBy": "nibu/hands", "importDir": "work", "outputDir": "work", + "hostAddons": ["brokkr_mesh_polish", "brokkr_rig"], "saveBlend": "work/whale.blend", + "intents": [ + {"action": "importGltf", "filepath": "whale.glb"}, + {"action": "brokkr_mesh_polish.audit"}, + {"action": "brokkr_mesh_polish.repair", "object_name": "whale_mesh"}, + {"action": "brokkr_mesh_polish.orient", "object_name": "whale_root", "length": 1.0}, + {"action": "brokkr_rig.body", "object_name": "whale_mesh", "spine_bones": 8, "head": "+y", "seeds": "jaw=0.2,0.4,0"}, + {"action": "brokkr_rig.tendrils", "object_name": "whale_mesh", "tau": 0.04, "band": 0.04, "dilate": 0.04}, + {"action": "brokkr_rig.colliders", "object_name": "whale_mesh"}, + {"action": "exportGltf", "filepath": "whale_rigged.glb"}]} +``` + +Pick seed points from a flat turntable with `brokkr_mesh_polish.pick`, and pick `head` by eye from a render. Run +the recipe with `tools/run_intents.py` under private `BLENDER_USER_*` directories (`mesh-polish.md`), then +`VerifyGlb` on `whale_rigged.glb`. + +The live proof is `tests/live/rig.py` (a synthetic whale through the same intents; `rig.result.json` is its last +run). diff --git a/surfaces/blender/tests/live/rig.py b/surfaces/blender/tests/live/rig.py new file mode 100644 index 0000000..54bc1a4 --- /dev/null +++ b/surfaces/blender/tests/live/rig.py @@ -0,0 +1,272 @@ +"""Live proof, in a background Blender, that the brokkr_rig rows are admitted by Brokkr as host actions and that a +synthetic whale (a capsule body, six tendrils of which one forks and one is a vein lying on the body, a detached +bead and a jaw seed) goes through run_intent: repair, orient, body, tendrils, colliders, exportGltf, and comes out +as a GLB the exporter hook has given VRMC_springBone. Not part of the unittest run: it needs Blender. + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/rig.py -- + +Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses +without them). Writes .result.json and .glb (the synthetic whale's rig, for the runtime's own parse, +Aetheria SpringRigVerify.VerifyGlb) and exits 1 when a check failed. The acceptance is the runtime's parse, not +anything here: the structure checks below are what this builder promised, not the runtime's rules. +""" +import json +import math +import os +import struct +import sys +import tempfile +import time +import types +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] +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)) +T0 = time.time() +bpy.ops.wm.read_factory_settings(use_empty=True) +for module in ("brokkr_mesh_polish", "brokkr_rig"): + addon_utils.enable(module, default_set=True) +target = bt.BrokkrBlenderTarget(bpy) +WORK = Path(tempfile.mkdtemp(prefix="brokkr-rig-live-")) +target.configure_action_dirs("", str(WORK)) +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() + + +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 tube(start, end, radius=0.006, segments=6): + start, end = Vector(start), Vector(end) + along = end - start + matrix = Matrix.Translation((start + end) / 2) @ along.to_track_quat("Z", "Y").to_matrix().to_4x4() + return matrix, along.length, radius, segments + + +def make_whale(): + """Body: an ellipsoid 0.24 x 1.0 x 0.24. Tendrils are tubes whose first 0.03 lies inside the body, joined by an + exact union so the skin is fused as a generated mesh is; the bead is a separate shell.""" + body = bmesh.new() + bmesh.ops.create_uvsphere(body, u_segments=32, v_segments=24, radius=1.0, calc_uvs=True) + bmesh.ops.scale(body, vec=(0.12, 0.5, 0.12), verts=body.verts) + bm = bmesh.new() + inside = 0.03 + specs = [] + for y, tilt, length in ((-0.3, -0.4, 0.34), (-0.1, 0.4, 0.3), (0.1, -0.2, 0.36), (0.3, 0.3, 0.28)): + d = Vector((tilt, 0.0, -1.0)).normalized() + surface = Vector((0.0, y, -0.12 * math.sqrt(max(1.0 - (y / 0.5) ** 2, 0.0)))) + specs.append((surface - d * inside, surface + d * length)) + d = Vector((0.5, 0.2, -1.0)).normalized() # the forked one: a trunk with a side branch near its middle + surface = Vector((0.0, 0.0, -0.12)) + trunk = (surface - d * inside, surface + d * 0.4) + specs.append(trunk) + mid = surface + d * 0.2 + specs.append((mid - Vector((0.0, 0.01, 0.0)), mid + Vector((0.0, 0.18, -0.05)))) + specs.append((Vector((-0.02, -0.12, 0.125)), Vector((-0.02, 0.12, 0.125)))) # the vein lies along the top + for start, end in specs: + matrix, depth, radius, segments = tube(start, end, 0.015 if end.z > 0.1 else 0.006) + bmesh.ops.create_cone(bm, cap_ends=True, segments=segments, radius1=radius, radius2=radius, depth=depth, matrix=matrix) + bmesh.ops.subdivide_edges(bm, edges=[e for e in bm.edges if e.calc_length() > 0.05], cuts=15, use_grid_fill=True) + mesh = bpy.data.meshes.new("Whale") + body.to_mesh(mesh) + body.free() + mesh.uv_layers.new(name="UVMap") + tubes = bpy.data.meshes.new("WhaleTubes") + bm.to_mesh(tubes) + bm.free() + obj = bpy.data.objects.new("Whale", mesh) + other = bpy.data.objects.new("WhaleTubes", tubes) + for o in (obj, other): + bpy.context.scene.collection.objects.link(o) + mod = obj.modifiers.new("Union", "BOOLEAN") + mod.operation, mod.operand_type, mod.solver, mod.object, mod.use_self = "UNION", "OBJECT", "EXACT", other, True + bpy.context.view_layer.objects.active = obj + bpy.ops.object.modifier_apply(modifier="Union") + bpy.data.objects.remove(other) + bead = bmesh.new() + bmesh.ops.create_uvsphere(bead, u_segments=8, v_segments=6, radius=0.02, matrix=Matrix.Translation((0.3, 0.1, -0.3))) + mesh2 = bpy.data.meshes.new("Bead") + bead.to_mesh(mesh2) + bead.free() + both = bmesh.new() + both.from_mesh(obj.data) + both.from_mesh(mesh2) + both.to_mesh(obj.data) + both.free() + obj.data.uv_layers.new(name="UVMap") if not obj.data.uv_layers else None + bpy.data.meshes.remove(mesh2) + return obj + + +def glb_json(path): + blob = Path(path).read_bytes() + length = struct.unpack_from(" 0 + and arm.data.bones["jaw"].parent.name in body["spine"], body["parts"]) + head, tail = np.array(body["head"]), np.array(body["tail"]) + check("body: the root bone is at the +y end and the object's transform is baked", head[1] > tail[1] + and np.allclose(np.array(whale.matrix_world), np.eye(4), atol=1e-9) and arm.data.bones["spine_00"].parent is None, [head, tail]) +receipt, tendrils = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01) +check("tendrils accepted", receipt["status"] == "accepted", receipt["message"]) +R["tendrils"] = tendrils +if tendrils: + check("tendrils: five chains (the vein folded), the fork made one chain with a rigid branch, the bead attached", + tendrils["chains"] == 5 and tendrils["veinsFolded"] >= 1 and tendrils["branchesRigid"] >= 1 and tendrils["shellsAttached"] >= 1, tendrils) +receipt, colliders = send("brokkr_rig.colliders", object_name="Whale") +check("colliders accepted", receipt["status"] == "accepted", receipt["message"]) +R["colliders"] = colliders +receipt, again = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01) +check("tendrils run again on the same rig gives the same chains", again and tendrils and again["chains"] == tendrils["chains"] + and again["springBones"] == tendrils["springBones"], [again, tendrils]) +receipt, colliders = send("brokkr_rig.colliders", object_name="Whale") +R["colliders"] = colliders + +# --- export: the five attributes, weights, extension, structure ---------------------------------------------------- +receipt, _ = send("exportGltf", filepath="whale.glb", extras=False, yUp=True, applyModifiers=True) +check("exportGltf accepted", receipt["status"] == "accepted", receipt["message"]) +gltf, blob, bin_at = glb_json(WORK / "whale.glb") +ext = gltf.get("extensions", {}).get("VRMC_springBone") +check("VRMC_springBone is in extensions and extensionsUsed", ext is not None and "VRMC_springBone" in gltf.get("extensionsUsed", []), list(gltf.get("extensions", {}))) +if ext and tendrils and colliders: + check("the springs, joints and colliders are the built ones", len(ext["springs"]) == tendrils["chains"] + and sum(len(s["joints"]) for s in ext["springs"]) == tendrils["springBones"] + and len(ext["colliders"]) == colliders["capsules"] + colliders["spheres"] + and all(s["colliderGroups"] == [0] for s in ext["springs"]) and [g["name"] for g in ext["colliderGroups"]] == ["body"], + [len(ext["springs"]), len(ext["colliders"])]) +prims = [p for m in gltf["meshes"] for p in m["primitives"]] +check("mesh primitives carry exactly the five attributes", all(set(p["attributes"]) == {"POSITION", "NORMAL", "TEXCOORD_0", "JOINTS_0", "WEIGHTS_0"} for p in prims), + [sorted(p["attributes"]) for p in prims]) +worst_sum, worst_count = 0.0, 0 +for p in prims: + if "WEIGHTS_0" not in p["attributes"]: + check("every primitive is skinned", False, sorted(p["attributes"])) + continue + acc = gltf["accessors"][p["attributes"]["WEIGHTS_0"]] + view = gltf["bufferViews"][acc["bufferView"]] + W = np.frombuffer(blob, np.float32, acc["count"] * 4, bin_at + view.get("byteOffset", 0) + acc.get("byteOffset", 0)).reshape(-1, 4) + worst_sum = max(worst_sum, float(np.abs(W.sum(axis=1) - 1).max())) + worst_count = max(worst_count, int((W > 0).sum(axis=1).max())) +check("weights sum to 1 with at most four influences", worst_sum < 1e-5 and worst_count <= 4, [worst_sum, worst_count]) +nodes = gltf["nodes"] +parent = {c: i for i, n in enumerate(nodes) for c in n.get("children", [])} +check("no node carries a matrix and every scale is 1", all("matrix" not in n and all(abs(s - 1) < 1e-4 for s in n.get("scale", (1, 1, 1))) for n in nodes), None) +joints = gltf["skins"][0]["joints"] +check("one skin over every bone", len(gltf["skins"]) == 1 and len(joints) == len(arm.data.bones), [len(joints), len(arm.data.bones)]) +if ext: + in_spring = {j["node"] for s in ext["springs"] for j in s["joints"]} + linear = all(parent.get(s["joints"][0]["node"]) in set(joints) - in_spring and all(parent[s["joints"][k]["node"]] == s["joints"][k - 1]["node"] for k in range(1, len(s["joints"]))) + for s in ext["springs"]) + check("each spring is a linear chain, its first joint hung from a body bone, no bone in two springs", linear + and len(in_spring) == sum(len(s["joints"]) for s in ext["springs"]), None) + check("every segment has length", all(np.linalg.norm(nodes[j["node"]].get("translation", (0, 0, 0))) > 1e-6 for s in ext["springs"] for j in s["joints"][1:]), None) + check("colliders sit on body bones", all(c["node"] in set(joints) - in_spring for c in ext["colliders"]), None) + swing = np.array([[1.0, 0, 0], [0, 0, 1.0], [0, -1.0, 0]]) + where = [world_of(nodes, parent, j["node"])[:3, 3] for s in ext["springs"] for j in s["joints"]] + expect = [swing @ np.array(arm.matrix_world @ arm.data.bones[nodes[j["node"]]["name"]].head_local) for s in ext["springs"] for j in s["joints"]] + check("every joint's node stands where its bone's head is in the scene", np.allclose(where, expect, atol=1e-4), float(np.abs(np.array(where) - np.array(expect)).max())) +R["glb"] = {"nodes": len(nodes), "joints": len(joints), "springs": len(ext["springs"]) if ext else 0, "colliders": len(ext["colliders"]) if ext else 0} +Path(OUT + ".glb").write_bytes((WORK / "whale.glb").read_bytes()) + +# --- determinism, yUp, and a scene with no rig ------------------------------------------------------------------------ +send("exportGltf", filepath="again.glb", extras=False, yUp=True, applyModifiers=True) +a, b = glb_json(WORK / "whale.glb")[0], glb_json(WORK / "again.glb")[0] +check("two exports have identical JSON chunks", json.dumps(a, sort_keys=True) == json.dumps(b, sort_keys=True), None) +send("exportGltf", filepath="flat.glb", extras=False, yUp=False, applyModifiers=True) +flat, _, _ = glb_json(WORK / "flat.glb") +fext = flat.get("extensions", {}).get("VRMC_springBone") +if ext and fext: + nodes_f = flat["nodes"] + parent_f = {c: i for i, n in enumerate(nodes_f) for c in n.get("children", [])} + names = {n["name"]: i for i, n in enumerate(nodes)} + + def collider_world(gl, nd, par, c, key): + return (world_of(nd, par, c["node"]) @ np.append(c["shape"][list(c["shape"])[0]][key], 1.0))[:3] + + pairs = [(collider_world(gltf, nodes, parent, c, "offset"), collider_world(flat, nodes_f, parent_f, f, "offset")) + for c, f in zip(ext["colliders"], fext["colliders"])] + check("yUp false: a collider's node-local offset composes to the same scene point (up to the axis swing)", + bool(pairs) and all(np.allclose(up, swing @ flat_point, atol=1e-4) for up, flat_point in pairs), pairs[:1]) +bpy.ops.mesh.primitive_cube_add() +cube = bpy.context.active_object +cube.name = "Cube" +send("exportGltf", filepath="cube.glb", extras=False, yUp=True, applyModifiers=True, selection=["Cube"]) +cube_json, _, _ = glb_json(WORK / "cube.glb") +check("a scene with no rig springs exports no VRMC_springBone", "VRMC_springBone" not in cube_json.get("extensions", {}) + and "VRMC_springBone" not in cube_json.get("extensionsUsed", []), list(cube_json.get("extensions", {}))) + +R["ok"] = all(c["ok"] for c in R["checks"]) +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) +sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/rig.result.json b/surfaces/blender/tests/live/rig.result.json new file mode 100644 index 0000000..3cbaafd --- /dev/null +++ b/surfaces/blender/tests/live/rig.result.json @@ -0,0 +1,390 @@ +{ + "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_rig.body", + "brokkr_rig.tendrils", + "brokkr_rig.colliders" + ] + }, + { + "name": "fixture: one fused shell and a detached bead", + "ok": true, + "detail": { + "Whale": { + "triangles": 3094, + "vertices": 1551, + "weldedVertices": 1549, + "extent": [ + 1.0, + 0.451844, + 0.615025 + ], + "surfaceArea": 0.6858676781563833, + "degenerateTriangles": 0, + "edges": 4635, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "collapsedTriangles": 4, + "windingAgainstNormals": 1, + "shells": 2, + "shellTriangles": [ + 3014, + 80 + ], + "uvIslands": 721, + "uvMirroredTriangles": 1, + "uvZeroAreaTriangles": 1508, + "uvOutsideUnitTriangles": 0, + "uvCoverage": 1.0, + "uvOverlap": 1.0, + "baseColorImage": "", + "baseColorSize": [ + 0, + 0 + ], + "customNormals": false + } + } + }, + { + "name": "repair accepted", + "ok": true, + "detail": "Operator brokkr_mesh_polish.repair finished." + }, + { + "name": "orient accepted", + "ok": true, + "detail": "Operator brokkr_mesh_polish.orient finished." + }, + { + "name": "body accepted", + "ok": true, + "detail": "Operator brokkr_rig.body finished." + }, + { + "name": "body: a spine of six, a jaw bone parented to a spine bone", + "ok": true, + "detail": [ + { + "name": "jaw", + "root": [ + -0.157115, + 0.175099, + 0.032488 + ], + "tail": [ + -0.15589, + 0.217733, + 0.04605 + ], + "triangles": 91 + } + ] + }, + { + "name": "body: the root bone is at the +y end and the object's transform is baked", + "ok": true, + "detail": [ + "[-0.183123 0.5 -0.039007]", + "[-0.16983 -0.5 -0.027336]" + ] + }, + { + "name": "tendrils accepted", + "ok": true, + "detail": "Operator brokkr_rig.tendrils finished." + }, + { + "name": "tendrils: five chains (the vein folded), the fork made one chain with a rigid branch, the bead attached", + "ok": true, + "detail": { + "object": "Whale", + "armature": "Whale.rig", + "bodyVertices": 913, + "chains": 5, + "springBones": 50, + "branchesRigid": 1, + "veinsFolded": 10, + "shellsAttached": 1, + "unreachedVertices": 42, + "rings": 59, + "shapeDiameterMedian": 0.15453927963972092, + "tau": 0.05000000074505806, + "band": 0.03999999910593033 + } + }, + { + "name": "colliders accepted", + "ok": true, + "detail": "Operator brokkr_rig.colliders finished." + }, + { + "name": "tendrils run again on the same rig gives the same chains", + "ok": true, + "detail": [ + { + "object": "Whale", + "armature": "Whale.rig", + "bodyVertices": 913, + "chains": 5, + "springBones": 50, + "branchesRigid": 1, + "veinsFolded": 10, + "shellsAttached": 1, + "unreachedVertices": 42, + "rings": 59, + "shapeDiameterMedian": 0.15453927963972092, + "tau": 0.05000000074505806, + "band": 0.03999999910593033 + }, + { + "object": "Whale", + "armature": "Whale.rig", + "bodyVertices": 913, + "chains": 5, + "springBones": 50, + "branchesRigid": 1, + "veinsFolded": 10, + "shellsAttached": 1, + "unreachedVertices": 42, + "rings": 59, + "shapeDiameterMedian": 0.15453927963972092, + "tau": 0.05000000074505806, + "band": 0.03999999910593033 + } + ] + }, + { + "name": "exportGltf accepted", + "ok": true, + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-rig-live-hx2wf__p\\whale.glb (301168 bytes)." + }, + { + "name": "VRMC_springBone is in extensions and extensionsUsed", + "ok": true, + "detail": [ + "VRMC_springBone" + ] + }, + { + "name": "the springs, joints and colliders are the built ones", + "ok": true, + "detail": [ + 5, + 7 + ] + }, + { + "name": "mesh primitives carry exactly the five attributes", + "ok": true, + "detail": [ + [ + "JOINTS_0", + "NORMAL", + "POSITION", + "TEXCOORD_0", + "WEIGHTS_0" + ] + ] + }, + { + "name": "weights sum to 1 with at most four influences", + "ok": true, + "detail": [ + 1.1920928955078125e-07, + 4 + ] + }, + { + "name": "no node carries a matrix and every scale is 1", + "ok": true, + "detail": null + }, + { + "name": "one skin over every bone", + "ok": true, + "detail": [ + 57, + 57 + ] + }, + { + "name": "each spring is a linear chain, its first joint hung from a body bone, no bone in two springs", + "ok": true, + "detail": null + }, + { + "name": "every segment has length", + "ok": true, + "detail": null + }, + { + "name": "colliders sit on body bones", + "ok": true, + "detail": null + }, + { + "name": "every joint's node stands where its bone's head is in the scene", + "ok": true, + "detail": 7.357579227540434e-07 + }, + { + "name": "two exports have identical JSON chunks", + "ok": true, + "detail": null + }, + { + "name": "yUp false: a collider's node-local offset composes to the same scene point (up to the axis swing)", + "ok": true, + "detail": [ + [ + "[-0.183123 -0.039007 -0.5 ]", + "[-0.183123 0.5 -0.039007]" + ] + ] + }, + { + "name": "a scene with no rig springs exports no VRMC_springBone", + "ok": true, + "detail": [] + } + ], + "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_rig.body", + "brokkr_rig.tendrils", + "brokkr_rig.colliders" + ], + "audit": { + "Whale": { + "triangles": 3094, + "vertices": 1551, + "weldedVertices": 1549, + "extent": [ + 1.0, + 0.451844, + 0.615025 + ], + "surfaceArea": 0.6858676781563833, + "degenerateTriangles": 0, + "edges": 4635, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "collapsedTriangles": 4, + "windingAgainstNormals": 1, + "shells": 2, + "shellTriangles": [ + 3014, + 80 + ], + "uvIslands": 721, + "uvMirroredTriangles": 1, + "uvZeroAreaTriangles": 1508, + "uvOutsideUnitTriangles": 0, + "uvCoverage": 1.0, + "uvOverlap": 1.0, + "baseColorImage": "", + "baseColorSize": [ + 0, + 0 + ], + "customNormals": false + } + }, + "body": { + "object": "Whale", + "armature": "Whale.rig", + "created": true, + "spine": [ + "spine_00", + "spine_01", + "spine_02", + "spine_03", + "spine_04", + "spine_05" + ], + "parts": [ + { + "name": "jaw", + "root": [ + -0.157115, + 0.175099, + 0.032488 + ], + "tail": [ + -0.15589, + 0.217733, + 0.04605 + ], + "triangles": 91 + } + ], + "head": [ + -0.183123, + 0.5, + -0.039007 + ], + "tail": [ + -0.16983, + -0.5, + -0.027336 + ], + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "vertices": 1546, + "weldedVertices": 1546 + }, + "tendrils": { + "object": "Whale", + "armature": "Whale.rig", + "bodyVertices": 913, + "chains": 5, + "springBones": 50, + "branchesRigid": 1, + "veinsFolded": 10, + "shellsAttached": 1, + "unreachedVertices": 42, + "rings": 59, + "shapeDiameterMedian": 0.15453927963972092, + "tau": 0.05000000074505806, + "band": 0.03999999910593033 + }, + "colliders": { + "capsules": 6, + "spheres": 1, + "shrunk": 4, + "dropped": 0, + "skipped": 0, + "object": "Whale", + "armature": "Whale.rig", + "springJoints": 45 + }, + "glb": { + "nodes": 59, + "joints": 57, + "springs": 5, + "colliders": 7 + }, + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/test_rig.py b/surfaces/blender/tests/test_rig.py new file mode 100644 index 0000000..35bcf2b --- /dev/null +++ b/surfaces/blender/tests/test_rig.py @@ -0,0 +1,266 @@ +"""Rig builder tests. No Blender: the arithmetic in brokkr_rig/core.py on a hand-built tube graph with one fork, the +host action file against Brokkr's own checker, and the shared cut-root formula. + +Run: python3 -m unittest discover -s surfaces/blender/tests -v (needs numpy; skipped without it) +The operators and the exporter hook are exercised in a real Blender by tests/live/rig.py; the runtime's own parse +of the GLB is Aetheria's SpringRigVerify.VerifyGlb. + +Bounds follow lodur:ruling:deterministic-bound-margin: a deterministic reading is exact here, so each assertion is +the built value, and each names the mutant it kills. +""" +from __future__ import annotations + +import importlib +import importlib.util +import json +import re +import sys +import types +import unittest +from pathlib import Path + +SURFACE = Path(__file__).resolve().parents[1] +for name in ("brokkr_bridge", "brokkr_mesh_polish"): + package = types.ModuleType(name) + package.__path__ = [str(SURFACE / name)] + sys.modules.setdefault(name, package) +from brokkr_bridge import action_table as at # noqa: E402 + +try: + import numpy as np +except ImportError: # pragma: no cover + np = None + +if np is not None: + polish = importlib.import_module("brokkr_mesh_polish.core") + spec = importlib.util.spec_from_file_location("brokkr_rig_core", SURFACE / "brokkr_rig" / "core.py") + core = importlib.util.module_from_spec(spec) + spec.loader.exec_module(core) + +BAND, TAU = 0.25, 0.1 + + +def tube_graph(vein: bool = True): + """A body of three stations (thick), a trunk of nine stations along x that forks at station 5 into a branch of + three along y, and a short vein of two stations off the body. Every station is two vertices 0.01 apart, so a + ring is a handful of vertices. Distances from the body run .11 per trunk station: bands 0,0,1,1,2,2,3,3,3.""" + V, E, sd = [], [], [] + + def station(x, y, thick=False): + a = len(V) + V.extend([(x, y, 0.0), (x, y, 0.01)]) + sd.extend([1.0 if thick else 0.01] * 2) + E.append((a, a + 1)) + return a + + def join(a, b): + E.extend([(a, b), (a + 1, b + 1), (a, b + 1), (a + 1, b)]) + + body = [station(-0.2 + 0.1 * i, 0.0, True) for i in range(3)] + for a, b in zip(body, body[1:]): + join(a, b) + trunk, last = [], body[-1] + for k in range(1, 10): + trunk.append(station(0.11 * k, 0.0)) + join(last, trunk[-1]) + last = trunk[-1] + branch, last = [], trunk[4] + for k in range(1, 4): + branch.append(station(0.55, 0.11 * k)) + join(last, branch[-1]) + last = branch[-1] + veins, last = [], body[0] + for k in range(1, 3) if vein else (): + veins.append(station(-0.2, 0.11 * k)) + join(last, veins[-1]) + last = veins[-1] + return np.array(V), np.array(E), np.array(sd), {"body": body, "trunk": trunk, "branch": branch, "vein": veins} + + +def extract(fold_bands=1.5, min_joints=1, vein=True): + V, E, sd, at_ = tube_graph(vein) + return V, E, sd, at_, core.extract(V, E, sd, TAU, BAND, 0.0, fold_bands, min_joints) + + +class RingTests(unittest.TestCase): + @unittest.skipIf(np is None, "numpy") + def test_rings_make_the_tree(self): + """Dies if a ring's parent is taken from its own band.""" + V, E, sd, s, f = extract(vein=False) + self.assertEqual(int(f.body.sum()), 6) + trunk_rings = [int(f.ring[s["trunk"][i]]) for i in (0, 2, 4, 6)] + self.assertEqual([int(f.band[r]) for r in trunk_rings], [0, 1, 2, 3]) + self.assertEqual(len(f.parent), 5) + self.assertEqual([int(f.parent[r]) for r in trunk_rings], [-1, trunk_rings[0], trunk_rings[1], trunk_rings[2]]) + branch_ring = int(f.ring[s["branch"][2]]) + self.assertNotEqual(branch_ring, trunk_rings[3]) + self.assertEqual(int(f.parent[branch_ring]), trunk_rings[2]) + self.assertEqual(int(f.band[branch_ring]), 3) + self.assertEqual([int(r) for r in np.flatnonzero(f.parent < 0)], [trunk_rings[0]]) + for r in range(5): + self.assertNotEqual(int(f.band[f.parent[r]]) if f.parent[r] >= 0 else -1, int(f.band[r])) + + @unittest.skipIf(np is None, "numpy") + def test_main_path_and_tip(self): + """Dies without the tip or with the branch as a second spring.""" + V, E, sd, s, f = extract(vein=False) + self.assertEqual(len(f.chains), 1) + chain = f.chains[0] + trunk_rings = [int(f.ring[s["trunk"][i]]) for i in (0, 2, 4, 6)] + self.assertEqual(chain.rings, trunk_rings) + self.assertFalse(chain.folded) + branch_ring = int(f.ring[s["branch"][2]]) + self.assertFalse(bool(f.on_main[branch_ring])) + self.assertEqual(int(f.fork[branch_ring]), trunk_rings[2]) + springs = core.plan(V, sd, f, BAND) + self.assertEqual(len(springs), 1) + spring = springs[0] + self.assertEqual(len(spring.pos), 5) # four rings and the tip + tip = s["trunk"][8] + farthest = tip + int(np.argmax(f.d[[tip, tip + 1]])) + self.assertTrue(np.allclose(spring.pos[-1], V[farthest])) + self.assertGreater(float(np.linalg.norm(spring.pos[-1] - spring.pos[-2])), 0.0) + # the side branch's vertices weight 1 to the fork's bone + body_idx, body_w = np.zeros((len(V), 4), dtype=np.int64), np.zeros((len(V), 4)) + body_w[:, 0] = 1.0 + idx, w, start = core.tendril_weights(V, E, f, springs, body_idx, body_w, 1, BAND, 0.5) + for v in (s["branch"][1], s["branch"][2]): + self.assertEqual((int(idx[v, 0]), float(w[v, 0])), (start[0] + 2, 1.0)) + + @unittest.skipIf(np is None, "numpy") + def test_vein_folds(self): + """Dies with fold off or fold always on.""" + for bands, folded in ((0.0, [False, False]), (1.5, [True, False]), (4.0, [True, True])): + *_, f = extract(fold_bands=bands) + self.assertEqual(sorted(c.folded for c in f.chains), sorted(folded), bands) + *_, f = extract(min_joints=3) + self.assertEqual(sorted(c.folded for c in f.chains), [False, True]) # the vein has two rings + + +class WeightTests(unittest.TestCase): + @unittest.skipIf(np is None, "numpy") + def test_weights_partition(self): + """Dies if weights go to bone k + 1 (the joint the segment ends at).""" + V, E, sd, s, f = extract(vein=False) + springs = core.plan(V, sd, f, BAND) + body_idx, body_w = np.zeros((len(V), 4), dtype=np.int64), np.zeros((len(V), 4)) + body_w[:, 0] = 1.0 + idx, w, start = core.tendril_weights(V, E, f, springs, body_idx, body_w, 1, BAND, 0.5) + self.assertTrue(np.allclose(w.sum(axis=1), 1.0, atol=1e-6)) + self.assertLessEqual(int((w > 0).sum(axis=1).max()), 4) + self.assertTrue((idx[w > 0] < start[0] + len(springs[0].pos)).all()) + reach = 0.5 * BAND + D = springs[0].dist + for v in (s["trunk"][2], s["trunk"][3]): # outside the blend: bone k alone; inside: linear from bone k - 1 + d = f.d[v] + k = int(np.searchsorted(D, d, side="right")) - 1 + t = min((d - D[k]) / reach, 1.0) + got = {int(b): float(x) for b, x in zip(idx[v], w[v]) if x > 0} + if t >= 1.0: + self.assertEqual(got, {start[0] + k: 1.0}) + else: + self.assertAlmostEqual(got[start[0] + k], t, places=9) + self.assertAlmostEqual(got[start[0] + k - 1], 1.0 - t, places=9) + outside = [v for v in s["trunk"] if (lambda k: k >= 0 and (f.d[v] - D[k]) / reach >= 1.0)(int(np.searchsorted(D, f.d[v], side="right")) - 1)] + self.assertTrue(outside) + # a vertex at the body is the body's; one in the blend is part body + near = s["trunk"][0] + self.assertGreater(float(w[near][idx[near] == 0].sum()) if (idx[near] == 0).any() else 0.0, 0.0) + + @unittest.skipIf(np is None, "numpy") + def test_axial_weights_are_linear_between_knots_and_sum_to_one(self): + knots = np.array([0.0, 1.0, 3.0]) + W = core.axial_weights(np.array([-1.0, 0.0, 0.5, 1.0, 2.0, 3.0, 9.0]), knots) + self.assertTrue(np.allclose(W.sum(axis=1), 1.0)) + self.assertTrue(np.allclose(W[[0, 1, 3, 5, 6]], np.eye(3)[[0, 0, 1, 2, 2]])) + self.assertTrue(np.allclose(W[2], [0.5, 0.5, 0.0]) and np.allclose(W[4], [0.0, 0.5, 0.5])) + + @unittest.skipIf(np is None, "numpy") + def test_top4_keeps_the_heaviest_and_normalises(self): + idx, w = core.top4(np.array([[0.1, 0.5, 0.2, 0.15, 0.05]])) + self.assertEqual(sorted(idx[0].tolist()), [0, 1, 2, 3]) + self.assertAlmostEqual(float(w.sum()), 1.0, places=12) + self.assertAlmostEqual(float(w[0, 0]), 0.5 / 0.95, places=12) + + +class ColliderTests(unittest.TestCase): + @unittest.skipIf(np is None, "numpy") + def test_colliders_clear_rest(self): + """Dies without the shrink.""" + a, b = np.array([0.0, 0.0, 0.0]), np.array([1.0, 0.0, 0.0]) + joints = np.array([[0.5, 0.4, 0.0], [2.0, 0.0, 0.0]]) + hit = np.array([0.05, 0.05]) + radius = core.clear_radius(0.5, joints, hit, a, b) + self.assertAlmostEqual(radius, 0.35, places=12) + self.assertTrue((core.segment_distance(joints, a, b) - hit >= radius - 1e-12).all()) + self.assertFalse((core.segment_distance(joints, a, b) - hit >= 0.5).all()) + self.assertEqual(core.clear_radius(0.2, joints, hit, a, b), 0.2) # already clear: unchanged + self.assertAlmostEqual(core.clear_radius(1.0, joints[:1], hit[:1], a, a), float(np.linalg.norm([0.5, 0.4])) - 0.05, places=12) # a sphere + + @unittest.skipIf(np is None, "numpy") + def test_capsule_and_sphere_sizes(self): + ring = np.array([[np.cos(t), np.sin(t), z] for z in (0.2, 0.5, 0.8) for t in np.linspace(0, 6.2, 12)]) + self.assertAlmostEqual(core.capsule_radius(ring, np.array([0.0, 0.0, 0.0]), np.array([0.0, 0.0, 1.0]), 0.8), 0.8, places=9) + centre, radius = core.sphere_fit(ring[:12], 0.5) + self.assertTrue(np.allclose(centre[:2], ring[:12, :2].mean(axis=0))) + self.assertAlmostEqual(radius, 0.5 * float(np.median(np.linalg.norm(ring[:12] - centre, axis=1))), places=12) + + +class SharedRootTests(unittest.TestCase): + @unittest.skipIf(np is None, "numpy") + def test_boundary_root_equals_the_former_inline_formula(self): + mids = np.array([[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [2.0, 4.0, 0.0]]) + lengths = np.array([1.0, 1.0, 2.0]) + inline = (mids * lengths[:, None]).sum(axis=0) / lengths.sum() + self.assertTrue(np.array_equal(polish.boundary_root(mids, lengths), inline)) + self.assertTrue(np.array_equal(polish.boundary_root(np.zeros((0, 3)), np.zeros(0)), np.zeros(3))) + source = (SURFACE / "brokkr_mesh_polish" / "__init__.py").read_text(encoding="utf-8") + self.assertIn("core.boundary_root(mids, lengths)", source) + self.assertNotIn("(mids * lengths[:, None]).sum(axis=0) / lengths.sum() if len(cut)", source) + + +class HostFileTests(unittest.TestCase): + def setUp(self): + self.document = json.loads((SURFACE / "brokkr_rig" / "brokkr_actions.json").read_text(encoding="utf-8")) + + def test_brokkr_admits_the_file(self): + """rows-check: Brokkr's own host-file checker.""" + at.check_host(self.document, at.table()["charsets"]) + + def test_every_row_names_an_operator_and_property_the_add_on_defines(self): + source = (SURFACE / "brokkr_rig" / "__init__.py").read_text(encoding="utf-8") + 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, f"{row['name']}.{field['name']}") + + def test_a_valid_intent_is_admitted_and_a_bound_miss_is_refused(self): + host = [{**row, "host": "brokkr_rig"} for row in self.document["actions"]] + envelope = {"schema": "brokkr.blender.command_intent.v0", "commandId": "t-1", "requestedBy": "test/driver"} + admitted = at.validate({**envelope, "action": "brokkr_rig.tendrils", "object_name": "Hull"}, host) + self.assertEqual(admitted["tau"], 0.04) + with self.assertRaises(at.IntentInvalid): + at.validate({**envelope, "action": "brokkr_rig.tendrils", "object_name": "Hull", "tau": 0.9}, host) + + +class OwnershipTests(unittest.TestCase): + """The negative patterns of the cut: the contract's refusals, a second exporter and the bridge stay out of brokkr_rig.""" + PATTERNS = (r"non-unit scale|first joint|named twice|not a skin joint", r"brokkr_bridge", r"export_scene\.gltf|struct\.pack") + + def sources(self): + return {p.name: p.read_text(encoding="utf-8") for p in (SURFACE / "brokkr_rig").glob("*.py")} + + def test_no_pattern_matches_the_package(self): + for pattern in self.PATTERNS: + for name, text in self.sources().items(): + self.assertIsNone(re.search(pattern, text), f"{pattern} in {name}") + + def test_the_patterns_bite(self): + for pattern, planted in zip(self.PATTERNS, ("Node 3 has a non-unit scale", "from brokkr_bridge import x", "struct.pack(' Date: Tue, 1 Dec 2026 07:53:21 +0100 Subject: [PATCH 56/63] brokkr_rig: reruns depend only on their inputs; body clears chains it would orphan; reports and tests (Soul s1 fix batch) tendrils starts from the body weights kept on the mesh instead of the vertex groups a past run rewrote; body on an existing armature removes the chain bones; the spine seed stays off tendrils; tendrils reports the biggest chain's share, fused contacts and a warning; colliders report each shrink; mutants of stiffness taper, hit radius, shell bone, main path and fold rule are killed. Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/brokkr_rig/__init__.py | 88 +++++- surfaces/blender/brokkr_rig/core.py | 9 + surfaces/blender/docs/rig.md | 29 +- surfaces/blender/tests/live/rig.py | 45 ++- surfaces/blender/tests/live/rig.result.json | 291 +++++++++++++++++--- surfaces/blender/tests/test_rig.py | 69 ++++- 6 files changed, 468 insertions(+), 63 deletions(-) diff --git a/surfaces/blender/brokkr_rig/__init__.py b/surfaces/blender/brokkr_rig/__init__.py index 1302b3d..b153ccd 100644 --- a/surfaces/blender/brokkr_rig/__init__.py +++ b/surfaces/blender/brokkr_rig/__init__.py @@ -33,6 +33,8 @@ from . import core CHAIN, INDEX, STIFFNESS, DRAG, GRAVITY, HIT, COLLIDERS = ("rig_chain", "rig_index", "rig_stiffness", "rig_drag", "rig_gravity", "rig_hit_radius", "rig_colliders") +OPEN_SHEET_WARN = 0.042 # the share of the mesh one chain may hold before tendrils warns: the geometric mean of the lace leviathan (0.0227) and the skeletal hull (0.0774), docs/rig.md +SPINE_THICK = 0.04 # shape diameter, as a share of the longest side, a triangle needs to take a spine seed GRAVITY_DOWN = (0.0, 0.0, -1.0) # Blender world; the exporter hook turns it into glTF world @@ -115,6 +117,44 @@ def write_weights(obj, names: list, ids: np.ndarray, idx: np.ndarray, w: np.ndar groups[b].add([vertex], weight, "REPLACE") +SOURCE = ("rig_src_i0", "rig_src_i1", "rig_src_i2", "rig_src_i3", "rig_src_w0", "rig_src_w1", "rig_src_w2", "rig_src_w3") + + +def write_source(obj, names: list, ids: np.ndarray, idx: np.ndarray, w: np.ndarray): + """Keep the body's own weights on the mesh (eight point attributes and the bone names they index), so tendrils, + which rewrite the vertex groups, always start again from them: a rerun is a function of its inputs.""" + for name in SOURCE: + if name in obj.data.attributes: + obj.data.attributes.remove(obj.data.attributes[name]) + for slot in range(4): + for prefix, column in (("rig_src_i", idx[ids, slot]), ("rig_src_w", w[ids, slot])): + attribute = obj.data.attributes.new(f"{prefix}{slot}", "FLOAT", "POINT") + attribute.data.foreach_set("value", column.astype(np.float32)) + obj["rig_src_bones"] = json.dumps(names) + + +def read_source(obj, names: list, ids: np.ndarray, count: int) -> np.ndarray: + """Dense body weights (welded vertices, names) from write_source; Refused when body has not run or a bone it + named is gone.""" + if "rig_src_bones" not in obj or SOURCE[0] not in obj.data.attributes: + raise Refused(f"Object {obj.name!r} has no body weights: run brokkr_rig.body first.") + kept = json.loads(obj["rig_src_bones"]) + missing = [n for n in kept if n not in names] + if missing: + raise Refused(f"Body bone {missing[0]!r} is gone from the armature: run brokkr_rig.body again.") + column = [names.index(n) for n in kept] + n = len(obj.data.vertices) + own = np.zeros((n, len(names))) + for slot in range(4): + i, v = np.empty(n, dtype=np.float32), np.empty(n, dtype=np.float32) + obj.data.attributes[f"rig_src_i{slot}"].data.foreach_get("value", i) + obj.data.attributes[f"rig_src_w{slot}"].data.foreach_get("value", v) + np.add.at(own, (np.arange(n), np.array(column)[i.astype(np.int64)]), v.astype(np.float64)) + out = np.zeros((count, len(names))) + out[ids] = own + return out + + def read_weights(obj, names: list, ids: np.ndarray, count: int) -> np.ndarray: """Dense weights (welded vertices, names) of the mesh's vertex groups called names.""" column = {obj.vertex_groups[n].index: i for i, n in enumerate(names) if n in obj.vertex_groups} @@ -222,7 +262,11 @@ class BROKKR_RIG_OT_body(PolishOperator): pairs = polish.face_adjacency(w.TW) centroid = w.Vw[w.TW].mean(axis=1) nearest = lambda point: int(np.argmin(((centroid - np.asarray(point)) ** 2).sum(axis=1))) # noqa: E731 - placed = [(nearest(point), 0) for point in ([a for a, _ in spine] + [spine[-1][1]])] + sd = shape_diameter(w) # the spine's seeds take body surface: a triangle with a thin vertex is a tendril or a sheet + solid = (sd[w.TW] >= SPINE_THICK * w.length).all(axis=1) + pool = np.flatnonzero(solid) if solid.any() else np.arange(len(w.TW)) + nearest_solid = lambda point: int(pool[np.argmin(((centroid[pool] - np.asarray(point)) ** 2).sum(axis=1))]) # noqa: E731 + placed = [(nearest_solid(point), 0) for point in ([a for a, _ in spine] + [spine[-1][1]])] placed += [(nearest(point), parts.index(name) if name in parts else 0) for name, point in seeds] part, _ = polish.grow_parts(len(w.TW), pairs, polish.crease_costs(w.Vw, w.TW, pairs, self.crease_cost), placed) part[part < 0] = 0 @@ -269,13 +313,23 @@ class BROKKR_RIG_OT_body(PolishOperator): bone.parent = edits[names[int(np.argmin([core.segment_distance(head[None], a, b)[0] for a, b in spine]))]] else: arm = existing + cleared = 0 + if existing is not None: # chains hang on the old weights: they go, and tendrils runs again + with edit_mode(context, arm) as edits: + for old in [e for e in edits if CHAIN in e]: + edits.remove(old) + cleared += 1 + for bone in arm.data.bones: + if COLLIDERS in bone: + del bone[COLLIDERS] write_weights(obj, bones, w.ids, idx, weight) + write_source(obj, bones, w.ids, idx, weight) for modifier in [m for m in obj.modifiers if m.type == "ARMATURE"]: obj.modifiers.remove(modifier) obj.modifiers.new("Armature", "ARMATURE").object = arm obj.parent = arm obj.matrix_parent_inverse = arm.matrix_world.inverted() - return {"object": obj.name, "armature": arm.name, "created": existing is None, "spine": names, + return {"object": obj.name, "armature": arm.name, "created": existing is None, "chainBonesCleared": cleared, "spine": names, "parts": [{"name": n, "root": rounded(h), "tail": rounded(t), "triangles": int((part == i + 1).sum())} for i, (n, h, t) in enumerate(region)], "head": rounded(spine[0][0]), "tail": rounded(spine[-1][1]), "axis": rounded(axis), @@ -309,13 +363,7 @@ class BROKKR_RIG_OT_tendrils(PolishOperator): if not body_bones: raise Refused(f"Armature {arm.name!r} has no body bones.") body_names = [b.name for b in body_bones] - Wb = read_weights(obj, body_names, w.ids, w.count) - known = Wb.sum(axis=1) > 0 # a vertex a past run skinned to a chain has none: it takes the nearest one's - if not known.any(): - raise Refused("No vertex has weight on a body bone: run brokkr_rig.body first.") - if not known.all(): - near = core.dijkstra(core.graph(w.Vw, w.E), np.flatnonzero(known))[2] - Wb = Wb[np.where(known, np.arange(w.count), np.where(near >= 0, near, 0))] + Wb = read_source(obj, body_names, w.ids, w.count) bidx, bw = core.top4(Wb) scale, band = w.length, self.band * w.length sd = shape_diameter(w) @@ -345,13 +393,13 @@ class BROKKR_RIG_OT_tendrils(PolishOperator): bone.head, bone.tail = Vector(to_arm(head)), Vector(to_arm(tail)) bone.parent = edits[spring.names[k - 1]] if k else edits[spring.bone] for c, spring in enumerate(springs): - last = len(spring.names) - 1 + stiffness, hit = core.joint_params(spring.sd, self.stiffness, self.stiffness_tip_ratio, self.hit_scale) for k, name in enumerate(spring.names): bone = arm.data.bones[name] bone[CHAIN], bone[INDEX] = f"tendril_{c:03d}", k - bone[STIFFNESS] = self.stiffness * (1.0 + (self.stiffness_tip_ratio - 1.0) * k / last) + bone[STIFFNESS] = float(stiffness[k]) bone[DRAG], bone[GRAVITY] = self.drag, self.gravity_power - bone[HIT] = float(0.5 * spring.sd[k] * self.hit_scale) + bone[HIT] = float(hit[k]) arm.data["rig_gravity_dir"] = list(GRAVITY_DOWN) write_weights(obj, names, w.ids, idx, weight) kept = [c for c in found.chains if not c.folded] @@ -359,7 +407,19 @@ class BROKKR_RIG_OT_tendrils(PolishOperator): shells = len(np.unique(polish.components(w.count, w.E[lost[w.E[:, 0]] & lost[w.E[:, 1]]])[lost])) if lost.any() else 0 branches = int(sum(1 for r in range(len(found.parent)) if not found.on_main[r] and found.parent[r] >= 0 and found.on_main[found.parent[r]] and found.tree[r] in {c.tree for c in kept})) + on_chain = (found.ring >= 0) & np.isin(found.tree[np.maximum(found.ring, 0)], [c.tree for c in kept]) + kept_trees = [c.tree for c in kept] + trees = found.tree[found.ring[on_chain]] + open_share = float(np.bincount(trees).max() / w.count) if on_chain.any() else 0.0 # the biggest chain's share of the mesh + ring_of = np.where(found.ring >= 0, found.tree[np.maximum(found.ring, 0)], -1) + a, b = ring_of[w.E[:, 0]], ring_of[w.E[:, 1]] + fused = int(((a >= 0) & (b >= 0) & (a != b) & np.isin(a, [c.tree for c in kept]) & np.isin(b, [c.tree for c in kept])).sum()) + warnings = [] + if open_share >= OPEN_SHEET_WARN: + warnings.append(f"one chain holds {open_share:.0%} of the mesh: a plate of a hull may have become a chain; " + "raise tau or fold_bands, or rig a mesh whose tendrils are tubes") return {"object": obj.name, "armature": arm.name, "bodyVertices": int(found.body.sum()), "chains": len(springs), + "chainVertexShare": float(on_chain.mean()), "largestChainShare": open_share, "fusedContacts": fused, "warnings": warnings, "springBones": int(sum(len(s.pos) for s in springs)), "branchesRigid": branches, "veinsFolded": len(found.chains) - len(kept), "shellsAttached": shells, "unreachedVertices": int(lost.sum()), "rings": int(len(found.parent)), @@ -389,7 +449,7 @@ class BROKKR_RIG_OT_colliders(PolishOperator): chain = [b for b in arm.data.bones if CHAIN in b and b[INDEX] >= 1] joints = np.array([world(b.head_local) for b in chain]).reshape(-1, 3) hit = np.array([b[HIT] for b in chain]) - made = {"capsules": 0, "spheres": 0, "shrunk": 0, "dropped": 0, "skipped": 0} + made = {"capsules": 0, "spheres": 0, "shrunk": 0, "dropped": 0, "skipped": 0, "shrinks": [], "shrunkMax": 0.0} for bone in body: if COLLIDERS in bone: del bone[COLLIDERS] @@ -408,6 +468,8 @@ class BROKKR_RIG_OT_colliders(PolishOperator): cleared = core.clear_radius(radius, joints, hit, offset, end) if cleared < radius: made["shrunk"] += 1 + made["shrinks"].append({"bone": bone.name, "before": round(float(radius), 6), "after": round(float(max(cleared, 0.0)), 6)}) + made["shrunkMax"] = round(max(made["shrunkMax"], float(1.0 - max(cleared, 0.0) / radius)), 4) if cleared <= 0: made["dropped"] += 1 continue diff --git a/surfaces/blender/brokkr_rig/core.py b/surfaces/blender/brokkr_rig/core.py index 5dde1d9..35c8ba9 100644 --- a/surfaces/blender/brokkr_rig/core.py +++ b/surfaces/blender/brokkr_rig/core.py @@ -347,3 +347,12 @@ def clear_radius(radius: float, joints: np.ndarray, hit: np.ndarray, a: np.ndarr if not len(joints): return radius return min(radius, float((segment_distance(joints, a, b) - hit).min())) + + +# --- spring parameters ----------------------------------------------------------------------------------- + +def joint_params(sd: np.ndarray, stiffness: float, tip_ratio: float, hit_scale: float) -> tuple[np.ndarray, np.ndarray]: + """(stiffness, hit radius) per joint of a spring whose joints' median shape diameters are sd: stiffness tapers + linearly from the root's value to tip_ratio times it at the tip; the hit radius is half the diameter times hit_scale.""" + last = len(sd) - 1 + return stiffness * (1.0 + (tip_ratio - 1.0) * np.arange(last + 1) / last), 0.5 * np.asarray(sd) * hit_scale diff --git a/surfaces/blender/docs/rig.md b/surfaces/blender/docs/rig.md index 1b3a0b9..cf85323 100644 --- a/surfaces/blender/docs/rig.md +++ b/surfaces/blender/docs/rig.md @@ -48,22 +48,29 @@ node carries a scale. With no `armature_name` it makes `.rig`: a spine of equal bones along the principal axis, the root at the head end (`head` names which end of world Y; the swim wave runs head to tail), and one bone per seed name. `seeds` reads as in `cut_parts` (`name=x,y,z; ...`, several points may name one part). The spine is an implicit part named -`spine` seeded at the surface nearest each spine joint; a seed named `spine` adds to it. Each named part is grown +`spine` seeded at the surface nearest each spine joint and the tail point, among triangles whose three vertices have +a shape diameter of at least 0.04 of the longest side (a tendril or a sheet never takes a spine seed); a seed named +`spine` adds to it. Each named part is grown from its seeds along concave creases (`grow_parts`); its bone runs from the root of the part's cut (`boundary_root`) to its centroid and hangs from the nearest spine bone. With an existing `armature_name` the armature is kept as it is: its spine is the first root's heaviest-child chain (as the runtime derives it), every other body bone is seeded at the surface nearest its tail (`seeds` may add points for a bone by name). The spine's bones must run from the head end to the tail end along the long axis. +Chain bones an earlier `tendrils` left on that armature are removed (the report says how many: `chainBonesCleared`), +because they hang on the old weights; run `tendrils` again. Weights: spine bones by axial projection, linear between neighbouring joints; a part's region 1 on its bone; then -`smooth_rounds` Laplacian rounds over the welded vertex graph, the top 4 kept and normalised. +`smooth_rounds` Laplacian rounds over the welded vertex graph, the top 4 kept and normalised. They are also kept on +the mesh (point attributes `rig_src_*` and the object property `rig_src_bones`), because `tendrils` rewrites the +vertex groups. ### tendrils `brokkr_rig.tendrils` (`object_name`, `armature_name`, `tau`, `band`, `dilate` as shares of the longest side, `fold_bands`, `min_joints`, `blend`, `stiffness`, `stiffness_tip_ratio`, `drag`, `gravity_power`, `hit_scale`). -Needs `body` first. The mesh is welded; each vertex gets a shape diameter (median of five inward rays, fixed +Needs `body` first, and starts from the body's weights kept on the mesh, so a run depends only on the mesh and its +knobs, never on earlier runs. The mesh is welded; each vertex gets a shape diameter (median of five inward rays, fixed seed; an open sheet with no back face reads 0). The body is the largest component thicker than `tau`, dilated by `dilate`. Edge distance from the body is cut into bands of `band`; each band splits into connected rings, one joint per ring at its centroid, its parent the ring it touches one band nearer. @@ -82,22 +89,30 @@ joint per ring at its centroid, its parent the ring it touches one band nearer. `stiffness_tip_ratio`), `rig_drag`, `rig_gravity`, `rig_hit_radius` (half the ring's median shape diameter times `hit_scale`). Running it again replaces every earlier chain. -The report counts chains, spring bones, rigid branches, veins folded, shells attached and unreached vertices. +The report counts chains, spring bones, rigid branches, veins folded, shells attached and unreached vertices, and +gauges the rig: `chainVertexShare`, `largestChainShare` (the biggest chain's share of the mesh) and `fusedContacts` +(mesh edges joining two different chains). `warnings` says when one chain holds 4.2% of the mesh or more, which +is what a hull plate that became a chain looks like (the lace leviathan reads 2.3%, the skeletal and mantle hulls +7.7% and 11.2%; the bound is the geometric mean of the first two). An open sheet reads shape diameter 0, so on a +hull the builder succeeds; read the warning. ### colliders `brokkr_rig.colliders` (`object_name`, `armature_name`, `scale`). A capsule per spine bone from head to tail, radius the median radial distance of the body vertices projecting onto it times `scale`; a sphere per other body bone at the centroid of its heaviest vertices, radius the median distance times `scale`. Each radius is then -shrunk until every spring joint past the first stands at least its hit radius outside it at rest (`shrunk` counts -them). Stored as the bone's `rig_colliders` property list. +shrunk until every spring joint past the first stands at least its hit radius outside it at rest. The report lists +each shrink (`shrinks`: bone, before, after) and the largest fraction (`shrunkMax`): where tendrils lie on the +body at rest the rule fits colliders to the gaps between them (the leviathan's spine_07 shrinks by 91%). Stored as the bone's `rig_colliders` property list. ## What it cannot do It does not judge a rig: acceptance is the runtime's parse. It does not simulate the springs (the report's chain, joint and collider counts are what was built, not how it moves). It reads thickness from rays against the mesh, so a mesh whose windings face inward needs `repair` and `recalc_normals` first. A vein the dilation reaches -is absorbed before the fold rule sees it. Seeds on a smooth surface split by distance alone. +is absorbed before the fold rule sees it. Seeds on a smooth surface split by distance alone. A fused generated +mesh joins tendrils that touch: the edges between two chains stretch when the chains move apart (the leviathan has +132 such edges; `fusedContacts` counts them). ## A recipe diff --git a/surfaces/blender/tests/live/rig.py b/surfaces/blender/tests/live/rig.py index 54bc1a4..26de79f 100644 --- a/surfaces/blender/tests/live/rig.py +++ b/surfaces/blender/tests/live/rig.py @@ -186,10 +186,28 @@ if tendrils: receipt, colliders = send("brokkr_rig.colliders", object_name="Whale") check("colliders accepted", receipt["status"] == "accepted", receipt["message"]) R["colliders"] = colliders + + +def skin_state(): + """Every vertex's (group name, weight) pairs and every chain bone's properties, exactly as stored.""" + groups = [g.name for g in whale.vertex_groups] + weights = [sorted((groups[e.group], e.weight) for e in v.groups) for v in whale.data.vertices] + props = {b.name: [b[k] for k in ("rig_chain", "rig_index", "rig_stiffness", "rig_drag", "rig_gravity", "rig_hit_radius")] + for b in arm.data.bones if "rig_chain" in b} + return weights, props + + +first = skin_state() +send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.06, dilate=0.02) +other = skin_state() receipt, again = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01) -check("tendrils run again on the same rig gives the same chains", again and tendrils and again["chains"] == tendrils["chains"] - and again["springBones"] == tendrils["springBones"], [again, tendrils]) +check("tendrils with other knobs changes the skin", other != first, None) +check("tendrils, other knobs, then the first knobs again restores the weights and bone properties exactly", skin_state() == first, None) +check("the tendrils report says what it sees", tendrils and {"warnings", "largestChainShare", "chainVertexShare", "fusedContacts"} <= set(tendrils) + and len(tendrils["warnings"]) == 1 and "one chain holds" in tendrils["warnings"][0], tendrils) # five chains hold 13% each at most: hull-like by the gauge receipt, colliders = send("brokkr_rig.colliders", object_name="Whale") +check("the colliders report lists each shrink", colliders and len(colliders["shrinks"]) == colliders["shrunk"] + and all(x["after"] < x["before"] for x in colliders["shrinks"]), colliders) R["colliders"] = colliders # --- export: the five attributes, weights, extension, structure ---------------------------------------------------- @@ -204,6 +222,12 @@ if ext and tendrils and colliders: and len(ext["colliders"]) == colliders["capsules"] + colliders["spheres"] and all(s["colliderGroups"] == [0] for s in ext["springs"]) and [g["name"] for g in ext["colliderGroups"]] == ["body"], [len(ext["springs"]), len(ext["colliders"])]) +check("the extension is not required", "VRMC_springBone" not in gltf.get("extensionsRequired", []), gltf.get("extensionsRequired")) +if ext: + check("stiffness tapers from the root's 3 to the tip's 1.5 and hit radii are half a tube's diameter or less", + all(abs(s["joints"][0]["stiffness"] - 3.0) < 1e-6 and abs(s["joints"][-1]["stiffness"] - 1.5) < 1e-6 + and all(0 <= j["hitRadius"] <= 0.016 for j in s["joints"]) for s in ext["springs"]), + [[j["stiffness"] for j in ext["springs"][0]["joints"]], [j["hitRadius"] for j in ext["springs"][0]["joints"]]]) prims = [p for m in gltf["meshes"] for p in m["primitives"]] check("mesh primitives carry exactly the five attributes", all(set(p["attributes"]) == {"POSITION", "NORMAL", "TEXCOORD_0", "JOINTS_0", "WEIGHTS_0"} for p in prims), [sorted(p["attributes"]) for p in prims]) @@ -265,6 +289,23 @@ cube_json, _, _ = glb_json(WORK / "cube.glb") check("a scene with no rig springs exports no VRMC_springBone", "VRMC_springBone" not in cube_json.get("extensions", {}) and "VRMC_springBone" not in cube_json.get("extensionsUsed", []), list(cube_json.get("extensions", {}))) +# --- body again on its own armature: the chains go, nothing is left weighing nothing; colliders alone export no springs +chain_bones = sum(1 for b in arm.data.bones if "rig_chain" in b) +receipt, rebody = send("brokkr_rig.body", object_name="Whale", armature_name=arm.name, seeds="jaw=0,0.45,0.05") +check("body again clears the chain bones it would orphan", + rebody and rebody["chainBonesCleared"] == chain_bones > 0 and not any("rig_chain" in b for b in arm.data.bones), rebody) +send("exportGltf", filepath="cleared.glb", extras=False, yUp=True, applyModifiers=True) +cleared_json, _, _ = glb_json(WORK / "cleared.glb") +check("an armature with no chains exports no springs", "VRMC_springBone" not in cleared_json.get("extensions", {}), None) +receipt, lone = send("brokkr_rig.colliders", object_name="Whale") +send("exportGltf", filepath="colliders_only.glb", extras=False, yUp=True, applyModifiers=True) +only_json, _, _ = glb_json(WORK / "colliders_only.glb") +check("colliders without chains export no VRMC_springBone", lone and lone["capsules"] > 0 and "VRMC_springBone" not in only_json.get("extensions", {}) + and "VRMC_springBone" not in only_json.get("extensionsUsed", []), lone) +receipt, rerun = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01) +check("tendrils after the second body rebuilds the same chains", rerun and tendrils and rerun["chains"] == tendrils["chains"] + and rerun["springBones"] == tendrils["springBones"], [rerun, tendrils]) + R["ok"] = all(c["ok"] for c in R["checks"]) Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") for c in R["checks"]: diff --git a/surfaces/blender/tests/live/rig.result.json b/surfaces/blender/tests/live/rig.result.json index 3cbaafd..e00bb76 100644 --- a/surfaces/blender/tests/live/rig.result.json +++ b/surfaces/blender/tests/live/rig.result.json @@ -113,6 +113,12 @@ "armature": "Whale.rig", "bodyVertices": 913, "chains": 5, + "chainVertexShare": 0.36351875808538164, + "largestChainShare": 0.13389391979301424, + "fusedContacts": 0, + "warnings": [ + "one chain holds 13% of the mesh: a plate of a hull may have become a chain; raise tau or fold_bands, or rig a mesh whose tendrils are tubes" + ], "springBones": 50, "branchesRigid": 1, "veinsFolded": 10, @@ -130,45 +136,81 @@ "detail": "Operator brokkr_rig.colliders finished." }, { - "name": "tendrils run again on the same rig gives the same chains", + "name": "tendrils with other knobs changes the skin", "ok": true, - "detail": [ - { - "object": "Whale", - "armature": "Whale.rig", - "bodyVertices": 913, - "chains": 5, - "springBones": 50, - "branchesRigid": 1, - "veinsFolded": 10, - "shellsAttached": 1, - "unreachedVertices": 42, - "rings": 59, - "shapeDiameterMedian": 0.15453927963972092, - "tau": 0.05000000074505806, - "band": 0.03999999910593033 - }, - { - "object": "Whale", - "armature": "Whale.rig", - "bodyVertices": 913, - "chains": 5, - "springBones": 50, - "branchesRigid": 1, - "veinsFolded": 10, - "shellsAttached": 1, - "unreachedVertices": 42, - "rings": 59, - "shapeDiameterMedian": 0.15453927963972092, - "tau": 0.05000000074505806, - "band": 0.03999999910593033 - } - ] + "detail": null + }, + { + "name": "tendrils, other knobs, then the first knobs again restores the weights and bone properties exactly", + "ok": true, + "detail": null + }, + { + "name": "the tendrils report says what it sees", + "ok": true, + "detail": { + "object": "Whale", + "armature": "Whale.rig", + "bodyVertices": 913, + "chains": 5, + "chainVertexShare": 0.36351875808538164, + "largestChainShare": 0.13389391979301424, + "fusedContacts": 0, + "warnings": [ + "one chain holds 13% of the mesh: a plate of a hull may have become a chain; raise tau or fold_bands, or rig a mesh whose tendrils are tubes" + ], + "springBones": 50, + "branchesRigid": 1, + "veinsFolded": 10, + "shellsAttached": 1, + "unreachedVertices": 42, + "rings": 59, + "shapeDiameterMedian": 0.15453927963972092, + "tau": 0.05000000074505806, + "band": 0.03999999910593033 + } + }, + { + "name": "the colliders report lists each shrink", + "ok": true, + "detail": { + "capsules": 6, + "spheres": 1, + "shrunk": 4, + "dropped": 0, + "skipped": 0, + "shrinks": [ + { + "bone": "spine_01", + "before": 0.155853, + "after": 0.070036 + }, + { + "bone": "spine_02", + "before": 0.148599, + "after": 0.053107 + }, + { + "bone": "spine_03", + "before": 0.166193, + "after": 0.056984 + }, + { + "bone": "spine_04", + "before": 0.106817, + "after": 0.074496 + } + ], + "shrunkMax": 0.6571, + "object": "Whale", + "armature": "Whale.rig", + "springJoints": 45 + } }, { "name": "exportGltf accepted", "ok": true, - "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-rig-live-hx2wf__p\\whale.glb (301168 bytes)." + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-rig-live-237ky4n3\\whale.glb (301188 bytes)." }, { "name": "VRMC_springBone is in extensions and extensionsUsed", @@ -185,6 +227,37 @@ 7 ] }, + { + "name": "the extension is not required", + "ok": true, + "detail": null + }, + { + "name": "stiffness tapers from the root's 3 to the tip's 1.5 and hit radii are half a tube's diameter or less", + "ok": true, + "detail": [ + [ + 3, + 2.7857142857142856, + 2.5714285714285716, + 2.357142857142857, + 2.142857142857143, + 1.9285714285714284, + 1.7142857142857142, + 1.5 + ], + [ + 0.0059821512550115585, + 0.005849682260304689, + 0.005868155509233475, + 0.005716879619285464, + 0.00568680465221405, + 0.005836397642269731, + 0.005983717972412705, + 0.005983717972412705 + ] + ] + }, { "name": "mesh primitives carry exactly the five attributes", "ok": true, @@ -258,6 +331,126 @@ "name": "a scene with no rig springs exports no VRMC_springBone", "ok": true, "detail": [] + }, + { + "name": "body again clears the chain bones it would orphan", + "ok": true, + "detail": { + "object": "Whale", + "armature": "Whale.rig", + "created": false, + "chainBonesCleared": 50, + "spine": [ + "spine_00", + "spine_01", + "spine_02", + "spine_03", + "spine_04", + "spine_05" + ], + "parts": [ + { + "name": "jaw", + "root": [ + -0.160415, + 0.128395, + 0.030328 + ], + "tail": [ + -0.170113, + 0.140889, + 0.055153 + ], + "triangles": 140 + } + ], + "head": [ + -0.183123, + 0.5, + -0.039007 + ], + "tail": [ + -0.16983, + -0.5, + -0.027336 + ], + "axis": [ + 0.0, + 1.0, + -0.0 + ], + "vertices": 1546, + "weldedVertices": 1546 + } + }, + { + "name": "an armature with no chains exports no springs", + "ok": true, + "detail": null + }, + { + "name": "colliders without chains export no VRMC_springBone", + "ok": true, + "detail": { + "capsules": 6, + "spheres": 1, + "shrunk": 0, + "dropped": 0, + "skipped": 0, + "shrinks": [], + "shrunkMax": 0.0, + "object": "Whale", + "armature": "Whale.rig", + "springJoints": 0 + } + }, + { + "name": "tendrils after the second body rebuilds the same chains", + "ok": true, + "detail": [ + { + "object": "Whale", + "armature": "Whale.rig", + "bodyVertices": 913, + "chains": 5, + "chainVertexShare": 0.36351875808538164, + "largestChainShare": 0.13389391979301424, + "fusedContacts": 0, + "warnings": [ + "one chain holds 13% of the mesh: a plate of a hull may have become a chain; raise tau or fold_bands, or rig a mesh whose tendrils are tubes" + ], + "springBones": 50, + "branchesRigid": 1, + "veinsFolded": 10, + "shellsAttached": 1, + "unreachedVertices": 42, + "rings": 59, + "shapeDiameterMedian": 0.15453927963972092, + "tau": 0.05000000074505806, + "band": 0.03999999910593033 + }, + { + "object": "Whale", + "armature": "Whale.rig", + "bodyVertices": 913, + "chains": 5, + "chainVertexShare": 0.36351875808538164, + "largestChainShare": 0.13389391979301424, + "fusedContacts": 0, + "warnings": [ + "one chain holds 13% of the mesh: a plate of a hull may have become a chain; raise tau or fold_bands, or rig a mesh whose tendrils are tubes" + ], + "springBones": 50, + "branchesRigid": 1, + "veinsFolded": 10, + "shellsAttached": 1, + "unreachedVertices": 42, + "rings": 59, + "shapeDiameterMedian": 0.15453927963972092, + "tau": 0.05000000074505806, + "band": 0.03999999910593033 + } + ] } ], "hostErrors": [], @@ -313,6 +506,7 @@ "object": "Whale", "armature": "Whale.rig", "created": true, + "chainBonesCleared": 0, "spine": [ "spine_00", "spine_01", @@ -360,6 +554,12 @@ "armature": "Whale.rig", "bodyVertices": 913, "chains": 5, + "chainVertexShare": 0.36351875808538164, + "largestChainShare": 0.13389391979301424, + "fusedContacts": 0, + "warnings": [ + "one chain holds 13% of the mesh: a plate of a hull may have become a chain; raise tau or fold_bands, or rig a mesh whose tendrils are tubes" + ], "springBones": 50, "branchesRigid": 1, "veinsFolded": 10, @@ -376,6 +576,29 @@ "shrunk": 4, "dropped": 0, "skipped": 0, + "shrinks": [ + { + "bone": "spine_01", + "before": 0.155853, + "after": 0.070036 + }, + { + "bone": "spine_02", + "before": 0.148599, + "after": 0.053107 + }, + { + "bone": "spine_03", + "before": 0.166193, + "after": 0.056984 + }, + { + "bone": "spine_04", + "before": 0.106817, + "after": 0.074496 + } + ], + "shrunkMax": 0.6571, "object": "Whale", "armature": "Whale.rig", "springJoints": 45 diff --git a/surfaces/blender/tests/test_rig.py b/surfaces/blender/tests/test_rig.py index 35bcf2b..21755b0 100644 --- a/surfaces/blender/tests/test_rig.py +++ b/surfaces/blender/tests/test_rig.py @@ -40,9 +40,10 @@ if np is not None: BAND, TAU = 0.25, 0.1 -def tube_graph(vein: bool = True): +def tube_graph(vein: bool = True, perm=None): """A body of three stations (thick), a trunk of nine stations along x that forks at station 5 into a branch of - three along y, and a short vein of two stations off the body. Every station is two vertices 0.01 apart, so a + three along y, a short vein of two stations off the body (vein=True also adds a lone far + ring joined by one long edge and a detached shell). Every station is two vertices 0.01 apart, so a ring is a handful of vertices. Distances from the body run .11 per trunk station: bands 0,0,1,1,2,2,3,3,3.""" V, E, sd = [], [], [] @@ -74,11 +75,28 @@ def tube_graph(vein: bool = True): veins.append(station(-0.2, 0.11 * k)) join(last, veins[-1]) last = veins[-1] - return np.array(V), np.array(E), np.array(sd), {"body": body, "trunk": trunk, "branch": branch, "vein": veins} + lone, shell = [], [] + if vein: + a = len(V) + V.extend([(-0.1, 0.9, 0.0), (-0.1, 0.9, 0.01)]) + sd.extend([0.01, 0.01]) + E.extend([(a, a + 1), (body[1], a), (body[1] + 1, a + 1)]) + lone = [a] + b = len(V) + V.extend([(0.3, 0.0, 0.6), (0.3, 0.0, 0.61)]) + sd.extend([0.01, 0.01]) + E.append((b, b + 1)) + shell = [b] + V, E, sd = np.array(V), np.array(E), np.array(sd) + if perm is not None: # the same graph with its vertices numbered another way + V2, sd2 = np.empty_like(V), np.empty_like(sd) + V2[perm], sd2[perm] = V, sd + V, E, sd = V2, perm[E], sd2 + return V, E, sd, {"body": body, "trunk": trunk, "branch": branch, "vein": veins, "lone": lone, "shell": shell} -def extract(fold_bands=1.5, min_joints=1, vein=True): - V, E, sd, at_ = tube_graph(vein) +def extract(fold_bands=1.5, min_joints=1, vein=True, perm=None): + V, E, sd, at_ = tube_graph(vein, perm) return V, E, sd, at_, core.extract(V, E, sd, TAU, BAND, 0.0, fold_bands, min_joints) @@ -130,14 +148,51 @@ class RingTests(unittest.TestCase): @unittest.skipIf(np is None, "numpy") def test_vein_folds(self): """Dies with fold off or fold always on.""" - for bands, folded in ((0.0, [False, False]), (1.5, [True, False]), (4.0, [True, True])): + for bands, folded in ((0.0, [False] * 3), (1.5, [False, False, True]), (4.0, [True] * 3)): # trunk, a far lone ring, a vein *_, f = extract(fold_bands=bands) self.assertEqual(sorted(c.folded for c in f.chains), sorted(folded), bands) *_, f = extract(min_joints=3) - self.assertEqual(sorted(c.folded for c in f.chains), [False, True]) # the vein has two rings + self.assertEqual(sorted(c.folded for c in f.chains), [False, True, True]) # the vein has two rings, the lone ring one + + + @unittest.skipIf(np is None, "numpy") + def test_the_main_path_is_the_tallest_subtree_however_the_vertices_are_numbered(self): + """Dies if the main path is the shortest subtree, or the lowest ring id.""" + for seed in range(8): + perm = np.random.default_rng(seed).permutation(len(tube_graph(False)[0])) + V, E, sd, s, f = extract(vein=False, perm=perm) + leaf = f.chains[0].rings[-1] + self.assertIn(int(perm[s["trunk"][8]]), np.flatnonzero(f.ring == leaf).tolist(), seed) class WeightTests(unittest.TestCase): + @unittest.skipIf(np is None, "numpy") + def test_a_detached_shell_rides_the_nearest_spring_bone(self): + """Dies if the shell takes the farthest bone, or any other than the nearest.""" + V, E, sd, s, f = extract() + springs = core.plan(V, sd, f, BAND) + trunk = [sp for sp in springs if np.linalg.norm(sp.pos[0] - V[s["trunk"][0]]) < 0.2][0] + body_idx, body_w = np.zeros((len(V), 4), dtype=np.int64), np.zeros((len(V), 4)) + body_w[:, 0] = 1.0 + idx, w, start = core.tendril_weights(V, E, f, springs, body_idx, body_w, 1, BAND, 0.5) + every = np.concatenate([sp.pos for sp in springs]) + owner = np.concatenate([start[c] + np.arange(len(sp.pos)) for c, sp in enumerate(springs)]) + centre = V[s["shell"][0]:s["shell"][0] + 2].mean(axis=0) + near = int(owner[np.argmin(np.linalg.norm(every - centre, axis=1))]) + far = int(owner[np.argmax(np.linalg.norm(every - centre, axis=1))]) + self.assertNotEqual(near, far) + for v in (s["shell"][0], s["shell"][0] + 1): + self.assertEqual((int(idx[v, 0]), float(w[v, 0])), (near, 1.0)) + self.assertIn(near, range(start[springs.index(trunk)], start[springs.index(trunk)] + len(trunk.pos))) + + @unittest.skipIf(np is None, "numpy") + def test_stiffness_tapers_to_the_tip_ratio_and_the_hit_radius_is_half_the_diameter(self): + """Dies if the taper runs tip to root, or the hit radius is a diameter.""" + stiffness, hit = core.joint_params(np.array([0.02, 0.04, 0.06, 0.0]), 3.0, 0.5, 1.0) + self.assertTrue(np.allclose(stiffness, [3.0, 2.5, 2.0, 1.5])) + self.assertTrue(np.allclose(hit, [0.01, 0.02, 0.03, 0.0])) + self.assertTrue(np.allclose(core.joint_params(np.array([0.02, 0.04]), 3.0, 0.5, 2.0)[1], [0.02, 0.04])) + @unittest.skipIf(np is None, "numpy") def test_weights_partition(self): """Dies if weights go to bone k + 1 (the joint the segment ends at).""" From 804863ccc92518bb335d2d3a63352922bd918e0a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 08:38:05 +0100 Subject: [PATCH 57/63] brokkr_rig: no thin part is a reported outcome; shape rays reach the longest side; gauges, seeds and shrink pinned in core (Soul s2 fix batch) tendrils on a mesh with no rings reports zero chains instead of raising. The shape-diameter ray reach was half the longest side, so a body wider than that read thin; it is the longest side now. chain_gauges, seed_triangle and shrink_fraction move into core with tests; the live test pins stale colliders and the no-thin-part mesh. Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/brokkr_rig/__init__.py | 19 +++---- surfaces/blender/brokkr_rig/core.py | 25 +++++++++ surfaces/blender/docs/rig.md | 9 +++- surfaces/blender/tests/live/rig.py | 29 ++++++++++- surfaces/blender/tests/live/rig.result.json | 50 +++++++++++++++--- surfaces/blender/tests/test_rig.py | 56 ++++++++++++++++++--- 6 files changed, 157 insertions(+), 31 deletions(-) diff --git a/surfaces/blender/brokkr_rig/__init__.py b/surfaces/blender/brokkr_rig/__init__.py index b153ccd..39dbecb 100644 --- a/surfaces/blender/brokkr_rig/__init__.py +++ b/surfaces/blender/brokkr_rig/__init__.py @@ -174,7 +174,7 @@ def shape_diameter(w: SimpleNamespace) -> np.ndarray: live = (w.TW[:, 0] != w.TW[:, 1]) & (w.TW[:, 1] != w.TW[:, 2]) & (w.TW[:, 0] != w.TW[:, 2]) tree = BVHTree.FromPolygons([tuple(p) for p in w.Vw], [tuple(int(i) for i in t) for t in w.TW[live]]) jitter = np.random.default_rng(0).normal(0.0, 0.35, (w.count, 4, 3)) - reach, lift = 0.5 * w.length, 1e-5 * w.length + reach, lift = w.length, 1e-5 * w.length out = np.zeros(w.count) for i in range(w.count): inward = -w.N[i] @@ -264,9 +264,7 @@ class BROKKR_RIG_OT_body(PolishOperator): nearest = lambda point: int(np.argmin(((centroid - np.asarray(point)) ** 2).sum(axis=1))) # noqa: E731 sd = shape_diameter(w) # the spine's seeds take body surface: a triangle with a thin vertex is a tendril or a sheet solid = (sd[w.TW] >= SPINE_THICK * w.length).all(axis=1) - pool = np.flatnonzero(solid) if solid.any() else np.arange(len(w.TW)) - nearest_solid = lambda point: int(pool[np.argmin(((centroid[pool] - np.asarray(point)) ** 2).sum(axis=1))]) # noqa: E731 - placed = [(nearest_solid(point), 0) for point in ([a for a, _ in spine] + [spine[-1][1]])] + placed = [(core.seed_triangle(centroid, solid, point), 0) for point in ([a for a, _ in spine] + [spine[-1][1]])] placed += [(nearest(point), parts.index(name) if name in parts else 0) for name, point in seeds] part, _ = polish.grow_parts(len(w.TW), pairs, polish.crease_costs(w.Vw, w.TW, pairs, self.crease_cost), placed) part[part < 0] = 0 @@ -407,19 +405,14 @@ class BROKKR_RIG_OT_tendrils(PolishOperator): shells = len(np.unique(polish.components(w.count, w.E[lost[w.E[:, 0]] & lost[w.E[:, 1]]])[lost])) if lost.any() else 0 branches = int(sum(1 for r in range(len(found.parent)) if not found.on_main[r] and found.parent[r] >= 0 and found.on_main[found.parent[r]] and found.tree[r] in {c.tree for c in kept})) - on_chain = (found.ring >= 0) & np.isin(found.tree[np.maximum(found.ring, 0)], [c.tree for c in kept]) - kept_trees = [c.tree for c in kept] - trees = found.tree[found.ring[on_chain]] - open_share = float(np.bincount(trees).max() / w.count) if on_chain.any() else 0.0 # the biggest chain's share of the mesh - ring_of = np.where(found.ring >= 0, found.tree[np.maximum(found.ring, 0)], -1) - a, b = ring_of[w.E[:, 0]], ring_of[w.E[:, 1]] - fused = int(((a >= 0) & (b >= 0) & (a != b) & np.isin(a, [c.tree for c in kept]) & np.isin(b, [c.tree for c in kept])).sum()) + gauges = core.chain_gauges(found, w.E, [c.tree for c in kept], w.count) + open_share = gauges["largestChainShare"] warnings = [] if open_share >= OPEN_SHEET_WARN: warnings.append(f"one chain holds {open_share:.0%} of the mesh: a plate of a hull may have become a chain; " "raise tau or fold_bands, or rig a mesh whose tendrils are tubes") return {"object": obj.name, "armature": arm.name, "bodyVertices": int(found.body.sum()), "chains": len(springs), - "chainVertexShare": float(on_chain.mean()), "largestChainShare": open_share, "fusedContacts": fused, "warnings": warnings, + **gauges, "warnings": warnings, "springBones": int(sum(len(s.pos) for s in springs)), "branchesRigid": branches, "veinsFolded": len(found.chains) - len(kept), "shellsAttached": shells, "unreachedVertices": int(lost.sum()), "rings": int(len(found.parent)), @@ -469,7 +462,7 @@ class BROKKR_RIG_OT_colliders(PolishOperator): if cleared < radius: made["shrunk"] += 1 made["shrinks"].append({"bone": bone.name, "before": round(float(radius), 6), "after": round(float(max(cleared, 0.0)), 6)}) - made["shrunkMax"] = round(max(made["shrunkMax"], float(1.0 - max(cleared, 0.0) / radius)), 4) + made["shrunkMax"] = round(max(made["shrunkMax"], core.shrink_fraction(radius, cleared)), 4) if cleared <= 0: made["dropped"] += 1 continue diff --git a/surfaces/blender/brokkr_rig/core.py b/surfaces/blender/brokkr_rig/core.py index 35c8ba9..2638c2f 100644 --- a/surfaces/blender/brokkr_rig/core.py +++ b/surfaces/blender/brokkr_rig/core.py @@ -356,3 +356,28 @@ def joint_params(sd: np.ndarray, stiffness: float, tip_ratio: float, hit_scale: linearly from the root's value to tip_ratio times it at the tip; the hit radius is half the diameter times hit_scale.""" last = len(sd) - 1 return stiffness * (1.0 + (tip_ratio - 1.0) * np.arange(last + 1) / last), 0.5 * np.asarray(sd) * hit_scale + + +# --- seeds and gauges ------------------------------------------------------------------------------------ + +def seed_triangle(centroid: np.ndarray, solid: np.ndarray, point: np.ndarray) -> int: + """The triangle nearest point among the solid ones (all of them when none is solid).""" + pool = np.flatnonzero(solid) if solid.any() else np.arange(len(centroid)) + return int(pool[np.argmin(((centroid[pool] - np.asarray(point)) ** 2).sum(axis=1))]) + + +def chain_gauges(found: SimpleNamespace, E: np.ndarray, kept: list, count: int) -> dict: + """What a rig looks like from outside: the share of the mesh on kept chains, the biggest chain's share, and the + mesh edges joining two different kept chains. kept are the trees of the chains that are not folded.""" + ring = np.maximum(found.ring, 0) + tree = np.where(found.ring >= 0, found.tree[ring] if len(found.tree) else -1, -1) + mine = np.isin(tree, kept) & (found.ring >= 0) + a, b = tree[E[:, 0]], tree[E[:, 1]] + return {"chainVertexShare": float(mine.sum() / max(count, 1)), + "largestChainShare": float(np.bincount(tree[mine]).max() / max(count, 1)) if mine.any() else 0.0, + "fusedContacts": int((np.isin(a, kept) & np.isin(b, kept) & (a != b)).sum())} + + +def shrink_fraction(before: float, after: float) -> float: + """How much of a collider's radius a shrink took: 0 none, 1 all.""" + return 1.0 - max(after, 0.0) / before diff --git a/surfaces/blender/docs/rig.md b/surfaces/blender/docs/rig.md index cf85323..379dd96 100644 --- a/surfaces/blender/docs/rig.md +++ b/surfaces/blender/docs/rig.md @@ -94,7 +94,14 @@ gauges the rig: `chainVertexShare`, `largestChainShare` (the biggest chain's sha (mesh edges joining two different chains). `warnings` says when one chain holds 4.2% of the mesh or more, which is what a hull plate that became a chain looks like (the lace leviathan reads 2.3%, the skeletal and mantle hulls 7.7% and 11.2%; the bound is the geometric mean of the first two). An open sheet reads shape diameter 0, so on a -hull the builder succeeds; read the warning. +hull the builder succeeds; read the warning. The gauge is fitted to four meshes and catches a hull whose plates +merge into a few big chains. It does not catch one that fragments into many small plate chains: the submarine +reads 2.7% largest (9 chains, 11% of the mesh on chains) and gets no warning, and no second signal tried +(open-sheet share, ring width in shape diameters, share of the mesh on chains) separated it from the leviathan. +Look at the chains in a render before trusting a hull's rig. + +A mesh with no thin part (the crystal emblem) has no rings: `tendrils` is accepted, reports `chains` 0, removes +any chains from an earlier run, and leaves the skin as `body` made it. ### colliders diff --git a/surfaces/blender/tests/live/rig.py b/surfaces/blender/tests/live/rig.py index 26de79f..09c4396 100644 --- a/surfaces/blender/tests/live/rig.py +++ b/surfaces/blender/tests/live/rig.py @@ -206,8 +206,9 @@ check("tendrils, other knobs, then the first knobs again restores the weights an check("the tendrils report says what it sees", tendrils and {"warnings", "largestChainShare", "chainVertexShare", "fusedContacts"} <= set(tendrils) and len(tendrils["warnings"]) == 1 and "one chain holds" in tendrils["warnings"][0], tendrils) # five chains hold 13% each at most: hull-like by the gauge receipt, colliders = send("brokkr_rig.colliders", object_name="Whale") -check("the colliders report lists each shrink", colliders and len(colliders["shrinks"]) == colliders["shrunk"] - and all(x["after"] < x["before"] for x in colliders["shrinks"]), colliders) +check("the colliders report lists each shrink and the largest share taken", colliders and colliders["shrunk"] > 0 + and len(colliders["shrinks"]) == colliders["shrunk"] and all(x["after"] < x["before"] for x in colliders["shrinks"]) + and abs(colliders["shrunkMax"] - max(1 - x["after"] / x["before"] for x in colliders["shrinks"])) < 1e-3, colliders) R["colliders"] = colliders # --- export: the five attributes, weights, extension, structure ---------------------------------------------------- @@ -294,6 +295,7 @@ chain_bones = sum(1 for b in arm.data.bones if "rig_chain" in b) receipt, rebody = send("brokkr_rig.body", object_name="Whale", armature_name=arm.name, seeds="jaw=0,0.45,0.05") check("body again clears the chain bones it would orphan", rebody and rebody["chainBonesCleared"] == chain_bones > 0 and not any("rig_chain" in b for b in arm.data.bones), rebody) +check("body again leaves no collider from the old body", not any("rig_colliders" in b for b in arm.data.bones), None) send("exportGltf", filepath="cleared.glb", extras=False, yUp=True, applyModifiers=True) cleared_json, _, _ = glb_json(WORK / "cleared.glb") check("an armature with no chains exports no springs", "VRMC_springBone" not in cleared_json.get("extensions", {}), None) @@ -306,6 +308,29 @@ receipt, rerun = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band check("tendrils after the second body rebuilds the same chains", rerun and tendrils and rerun["chains"] == tendrils["chains"] and rerun["springBones"] == tendrils["springBones"], [rerun, tendrils]) +# --- a mesh with no thin part: no chains is an outcome, not a crash, and the skin stays the body's -------------------------- +ball = bmesh.new() +bmesh.ops.create_uvsphere(ball, u_segments=24, v_segments=12, radius=0.3, calc_uvs=True) +ball_mesh = bpy.data.meshes.new("Ball") +ball.to_mesh(ball_mesh) +ball.free() +ball_obj = bpy.data.objects.new("Ball", ball_mesh) +bpy.context.scene.collection.objects.link(ball_obj) +send("brokkr_rig.body", object_name="Ball", spine_bones=4) + + +def ball_weights(): + names = [g.name for g in ball_obj.vertex_groups] + return [sorted((names[e.group], e.weight) for e in v.groups) for v in ball_obj.data.vertices] + + +before = ball_weights() +receipt, bald = send("brokkr_rig.tendrils", object_name="Ball", tau=0.05, band=0.04, dilate=0.01) +check("tendrils on a mesh with no thin part is accepted and reports no chains", receipt["status"] == "accepted" and bald and bald["chains"] == 0 + and bald["springBones"] == 0 and bald["rings"] == 0 and bald["fusedContacts"] == 0, [receipt["message"], bald]) +check("and leaves the skin as body made it, with no chain bones", ball_weights() == before + and not any("rig_chain" in b for b in bpy.data.objects["Ball.rig"].data.bones), None) + R["ok"] = all(c["ok"] for c in R["checks"]) Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") for c in R["checks"]: diff --git a/surfaces/blender/tests/live/rig.result.json b/surfaces/blender/tests/live/rig.result.json index e00bb76..9cc1424 100644 --- a/surfaces/blender/tests/live/rig.result.json +++ b/surfaces/blender/tests/live/rig.result.json @@ -125,7 +125,7 @@ "shellsAttached": 1, "unreachedVertices": 42, "rings": 59, - "shapeDiameterMedian": 0.15453927963972092, + "shapeDiameterMedian": 0.15566504001617432, "tau": 0.05000000074505806, "band": 0.03999999910593033 } @@ -165,13 +165,13 @@ "shellsAttached": 1, "unreachedVertices": 42, "rings": 59, - "shapeDiameterMedian": 0.15453927963972092, + "shapeDiameterMedian": 0.15566504001617432, "tau": 0.05000000074505806, "band": 0.03999999910593033 } }, { - "name": "the colliders report lists each shrink", + "name": "the colliders report lists each shrink and the largest share taken", "ok": true, "detail": { "capsules": 6, @@ -210,7 +210,7 @@ { "name": "exportGltf accepted", "ok": true, - "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-rig-live-237ky4n3\\whale.glb (301188 bytes)." + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-rig-live-l9ustbpi\\whale.glb (301188 bytes)." }, { "name": "VRMC_springBone is in extensions and extensionsUsed", @@ -383,6 +383,11 @@ "weldedVertices": 1546 } }, + { + "name": "body again leaves no collider from the old body", + "ok": true, + "detail": null + }, { "name": "an armature with no chains exports no springs", "ok": true, @@ -425,7 +430,7 @@ "shellsAttached": 1, "unreachedVertices": 42, "rings": 59, - "shapeDiameterMedian": 0.15453927963972092, + "shapeDiameterMedian": 0.15566504001617432, "tau": 0.05000000074505806, "band": 0.03999999910593033 }, @@ -446,11 +451,42 @@ "shellsAttached": 1, "unreachedVertices": 42, "rings": 59, - "shapeDiameterMedian": 0.15453927963972092, + "shapeDiameterMedian": 0.15566504001617432, "tau": 0.05000000074505806, "band": 0.03999999910593033 } ] + }, + { + "name": "tendrils on a mesh with no thin part is accepted and reports no chains", + "ok": true, + "detail": [ + "Operator brokkr_rig.tendrils finished.", + { + "object": "Ball", + "armature": "Ball.rig", + "bodyVertices": 266, + "chains": 0, + "chainVertexShare": 0.0, + "largestChainShare": 0.0, + "fusedContacts": 0, + "warnings": [], + "springBones": 0, + "branchesRigid": 0, + "veinsFolded": 0, + "shellsAttached": 0, + "unreachedVertices": 0, + "rings": 0, + "shapeDiameterMedian": 0.5665553510189056, + "tau": 0.03000000163912775, + "band": 0.024000000417232492 + } + ] + }, + { + "name": "and leaves the skin as body made it, with no chain bones", + "ok": true, + "detail": null } ], "hostErrors": [], @@ -566,7 +602,7 @@ "shellsAttached": 1, "unreachedVertices": 42, "rings": 59, - "shapeDiameterMedian": 0.15453927963972092, + "shapeDiameterMedian": 0.15566504001617432, "tau": 0.05000000074505806, "band": 0.03999999910593033 }, diff --git a/surfaces/blender/tests/test_rig.py b/surfaces/blender/tests/test_rig.py index 21755b0..e25cae1 100644 --- a/surfaces/blender/tests/test_rig.py +++ b/surfaces/blender/tests/test_rig.py @@ -40,7 +40,7 @@ if np is not None: BAND, TAU = 0.25, 0.1 -def tube_graph(vein: bool = True, perm=None): +def tube_graph(vein: bool = True, perm=None, trunk_stations: int = 9): """A body of three stations (thick), a trunk of nine stations along x that forks at station 5 into a branch of three along y, a short vein of two stations off the body (vein=True also adds a lone far ring joined by one long edge and a detached shell). Every station is two vertices 0.01 apart, so a @@ -61,7 +61,7 @@ def tube_graph(vein: bool = True, perm=None): for a, b in zip(body, body[1:]): join(a, b) trunk, last = [], body[-1] - for k in range(1, 10): + for k in range(1, trunk_stations + 1): trunk.append(station(0.11 * k, 0.0)) join(last, trunk[-1]) last = trunk[-1] @@ -95,8 +95,8 @@ def tube_graph(vein: bool = True, perm=None): return V, E, sd, {"body": body, "trunk": trunk, "branch": branch, "vein": veins, "lone": lone, "shell": shell} -def extract(fold_bands=1.5, min_joints=1, vein=True, perm=None): - V, E, sd, at_ = tube_graph(vein, perm) +def extract(fold_bands=1.5, min_joints=1, vein=True, perm=None, trunk_stations=9): + V, E, sd, at_ = tube_graph(vein, perm, trunk_stations) return V, E, sd, at_, core.extract(V, E, sd, TAU, BAND, 0.0, fold_bands, min_joints) @@ -157,12 +157,52 @@ class RingTests(unittest.TestCase): @unittest.skipIf(np is None, "numpy") def test_the_main_path_is_the_tallest_subtree_however_the_vertices_are_numbered(self): - """Dies if the main path is the shortest subtree, or the lowest ring id.""" + """Dies if the main path is the shortest subtree, or the lowest ring id. The long trunk (12 stations, six rings + past the fork) is taller than the branch (one ring), so the height alone decides, never the size tie-break.""" for seed in range(8): - perm = np.random.default_rng(seed).permutation(len(tube_graph(False)[0])) - V, E, sd, s, f = extract(vein=False, perm=perm) + perm = np.random.default_rng(seed).permutation(len(tube_graph(False, trunk_stations=12)[0])) + V, E, sd, s, f = extract(vein=False, perm=perm, trunk_stations=12) leaf = f.chains[0].rings[-1] - self.assertIn(int(perm[s["trunk"][8]]), np.flatnonzero(f.ring == leaf).tolist(), seed) + self.assertIn(int(perm[s["trunk"][11]]), np.flatnonzero(f.ring == leaf).tolist(), seed) + self.assertEqual(len(f.chains[0].rings), 6) + + @unittest.skipIf(np is None, "numpy") + def test_a_mesh_with_no_thin_part_has_no_rings_and_no_chains(self): + V, E, sd, s = tube_graph(False) + f = core.extract(V, E, np.ones(len(V)), TAU, BAND, 0.0, 1.5, 1) + self.assertEqual((len(f.parent), f.chains, int(f.body.sum())), (0, [], len(V))) + self.assertEqual(core.plan(V, np.ones(len(V)), f, BAND), []) + self.assertEqual(core.chain_gauges(f, E, [], len(V)), {"chainVertexShare": 0.0, "largestChainShare": 0.0, "fusedContacts": 0}) + idx, w, start = core.tendril_weights(V, E, f, [], np.zeros((len(V), 4), dtype=np.int64), np.eye(4)[[0] * len(V)], 1, BAND, 0.5) + self.assertTrue((w[:, 0] == 1.0).all() and start == []) + + @unittest.skipIf(np is None, "numpy") + def test_gauges_count_the_biggest_chain_the_total_and_only_edges_between_chains(self): + """Dies if the largest share is the total, or fused contacts count edges inside one chain.""" + V, E, sd, s, f = extract() + kept = [c.tree for c in f.chains if not c.folded] + self.assertEqual(len(kept), 2) # the trunk and the lone ring + n = len(V) + own = core.chain_gauges(f, E, kept, n) + self.assertAlmostEqual(own["largestChainShare"], 24 / n) # the trunk's 9 stations and the branch's 3, two vertices each + self.assertAlmostEqual(own["chainVertexShare"], 26 / n) + self.assertEqual(own["fusedContacts"], 0) # trunk-branch edges are one chain + crossed = np.vstack([E, [s["trunk"][2], s["lone"][0]], [s["trunk"][3], s["lone"][0]]]) + self.assertEqual(core.chain_gauges(f, crossed, kept, n)["fusedContacts"], 2) + + @unittest.skipIf(np is None, "numpy") + def test_a_spine_seed_takes_the_nearest_solid_triangle_not_the_nearest_triangle(self): + """Dies if the seed is the nearest triangle whatever its thickness, or if no solid triangle leaves it nowhere.""" + centre = np.array([[0.0, 0, 0], [1.0, 0, 0], [3.0, 0, 0]]) + solid = np.array([False, True, True]) + self.assertEqual(core.seed_triangle(centre, solid, np.array([0.1, 0, 0])), 1) + self.assertEqual(core.seed_triangle(centre, np.array([False] * 3), np.array([0.1, 0, 0])), 0) # nothing solid: the nearest + + @unittest.skipIf(np is None, "numpy") + def test_shrink_fraction_is_the_share_of_the_radius_taken(self): + self.assertAlmostEqual(core.shrink_fraction(0.1, 0.0079), 0.921) + self.assertEqual(core.shrink_fraction(0.2, 0.2), 0.0) + self.assertEqual(core.shrink_fraction(0.2, -0.1), 1.0) class WeightTests(unittest.TestCase): From 9a8b72a2138fec4a7f6e733750fd7224f07563ed Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 14:48:03 +0100 Subject: [PATCH 58/63] brokkr_kitbash: a part kit as data, the mechanical kit, and four host actions core.py (numpy and stdlib, no bpy) owns brokkr.kit.v0: check_kit, load_kit by name only, resolve_params and parse_params, and build, which turns a part's tube, box and repeat shapes into closed outward-wound shells with socket frames. Expressions are parsed with ast and walked against a whitelist; nothing is run. kits/mechanical.v0.json holds nine parts. __init__.py is a host add-on beside brokkr_mesh_polish and brokkr_rig with place_part, set_params, describe and report. A placed part is its kit_kit, kit_part and kit_params ID properties; the mesh is derived from them and set_params rebuilds it in the same datablock, so transform, parent, modifiers and materials stay. Socket frames are derived at each report. test_kitbash.py runs without Blender; tests/live/kitbash.py proves the rows through run_intent in a background Blender 5.3, its result committed. Cut aetheria-release:cut_spec:cut-chassis-kit-format.r1. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 184 +++++++ .../brokkr_kitbash/brokkr_actions.json | 111 ++++ surfaces/blender/brokkr_kitbash/core.py | 478 ++++++++++++++++++ .../brokkr_kitbash/kits/mechanical.v0.json | 295 +++++++++++ surfaces/blender/tests/live/kitbash.py | 210 ++++++++ .../blender/tests/live/kitbash.result.json | 362 +++++++++++++ surfaces/blender/tests/test_kitbash.py | 413 +++++++++++++++ 7 files changed, 2053 insertions(+) create mode 100644 surfaces/blender/brokkr_kitbash/__init__.py create mode 100644 surfaces/blender/brokkr_kitbash/brokkr_actions.json create mode 100644 surfaces/blender/brokkr_kitbash/core.py create mode 100644 surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json create mode 100644 surfaces/blender/tests/live/kitbash.py create mode 100644 surfaces/blender/tests/live/kitbash.result.json create mode 100644 surfaces/blender/tests/test_kitbash.py diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py new file mode 100644 index 0000000..ea1c2fd --- /dev/null +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -0,0 +1,184 @@ +"""Kitbash parts: place a parametric machine part from a kit, re-parameterise it, and report where its sockets are. + +A host add-on for Brokkr beside brokkr_mesh_polish and brokkr_rig (it imports the polish package's operator base, +Refused and mesh_object, and nothing from Brokkr): brokkr_actions.json beside this file lists the operators agents +may run (docs/kitbash.md). The kit format, its checks and the geometry are core.py (numpy, tested without +Blender); this file is the bpy around it. Every operator writes a JSON report to +WindowManager.brokkr_mesh_polish_result, as the polish operators do. + +What a placed part is lives on its object as three ID properties: kit_kit, kit_part and kit_params. The mesh is +derived from them (set_params rebuilds it), and socket frames are derived again at every report: nothing else in +the scene stores them. Placement, materials and export are Brokkr's own rows (setObjectTransform, assignMaterial, +exportGltf). +""" +bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0), + "category": "Object", "description": "Parametric machine parts from kits, with socket frames; agent-callable through Brokkr."} + +import json +import math + +import bpy +import numpy as np + +try: + from brokkr_mesh_polish import RESULT, PolishOperator, Refused, mesh_object + MISSING = None +except ImportError as error: # register() says so; the classes below only need something to subclass + RESULT, PolishOperator, Refused, mesh_object, MISSING = "brokkr_mesh_polish_result", bpy.types.Operator, RuntimeError, None, error + +from . import core + +KIT, PART, PARAMS = "kit_kit", "kit_part", "kit_params" +BEVEL = "Kit Bevel" +BEVEL_SEGMENTS, BEVEL_ANGLE = 2, math.radians(30.0) +REPORT_LIMIT = 16000 # characters of a result Brokkr copies into a receipt before it truncates + + +def kit_work(work): + """A KitError from core is this request's refusal.""" + def wrapped(self, context): + try: + return work(self, context) + except core.KitError as error: + raise Refused(str(error)) from None + return wrapped + + +def write_mesh(mesh, built) -> None: + """The built part into an empty mesh datablock: vertices, n-gon faces, and flat shading on every face not marked smooth.""" + mesh.vertices.add(len(built.V)) + mesh.vertices.foreach_set("co", built.V.astype(np.float32).ravel()) + mesh.loops.add(len(built.faces)) + mesh.loops.foreach_set("vertex_index", built.faces) + mesh.polygons.add(len(built.counts)) + mesh.polygons.foreach_set("loop_start", (np.cumsum(built.counts) - built.counts).astype(np.int32)) + sharp = mesh.attributes.get("sharp_face") or mesh.attributes.new("sharp_face", "BOOLEAN", "FACE") + sharp.data.foreach_set("value", ~built.smooth) + mesh.update(calc_edges=True) + + +def sync_bevel(obj, width: float) -> None: + modifier = obj.modifiers.get(BEVEL) + if modifier is None and width > 0: + modifier = obj.modifiers.new(BEVEL, "BEVEL") + modifier.segments, modifier.limit_method, modifier.angle_limit = BEVEL_SEGMENTS, "ANGLE", BEVEL_ANGLE + if modifier is not None: + modifier.width = width + + +def kit_part_of(obj): + """(part, stored params) of a placed part, read from its ID properties.""" + if PART not in obj: + raise Refused(f"{obj.name!r} is not a kit part (it has no {PART} property); place_part makes one.") + try: + stored = json.loads(obj.get(PARAMS, "{}")) + except ValueError: + stored = None + if not isinstance(stored, dict): + raise Refused(f"{obj.name!r} has a {PARAMS} property that is not a JSON object.") + return core.part(core.load_kit(str(obj.get(KIT, ""))), str(obj[PART])), stored + + +def part_report(obj, part, built) -> dict: + return {"object": obj.name, "kit": part["kit"], "part": part["name"], "params": built.params, + "faces": len(obj.data.polygons), "shells": built.shell_count, "bevel": round(built.bevel, 6), + "sockets": core.socket_rows(built.sockets, np.array(obj.matrix_world))} + + +def bounded(report: dict, advice: str) -> dict: + size = len(json.dumps(report, separators=(",", ":"))) + if size > REPORT_LIMIT: + raise Refused(f"The report is {size} characters, over the {REPORT_LIMIT} a receipt carries: {advice}.") + return report + + +class BROKKR_KITBASH_OT_place_part(PolishOperator): + """Place a kit part at the origin as a new mesh object: its geometry from the kit and params, a Bevel modifier + when the part has a bevel, and the kit, part and params stored on the object""" + bl_idname = "brokkr_kitbash.place_part" + bl_label = "Place Kit Part" + kit: bpy.props.StringProperty(name="Kit", default="mechanical") + part: bpy.props.StringProperty(name="Part") + object_name: bpy.props.StringProperty(name="Object") + params: bpy.props.StringProperty(name="Params", description="name=value; name=value ... the rest take the part's defaults") + + @kit_work + def work(self, context): + part = core.part(core.load_kit(self.kit), self.part) + if self.object_name in bpy.data.objects: + raise Refused(f"An object named {self.object_name!r} exists; nothing changed.") + built = core.build(part, core.parse_params(self.params)) + mesh = bpy.data.meshes.new(self.object_name) + write_mesh(mesh, built) + obj = bpy.data.objects.new(self.object_name, mesh) + context.scene.collection.objects.link(obj) + sync_bevel(obj, built.bevel) + obj[KIT], obj[PART], obj[PARAMS] = part["kit"], part["name"], json.dumps(built.params) + return part_report(obj, part, built) + + +class BROKKR_KITBASH_OT_set_params(PolishOperator): + """Change params of a placed kit part and rebuild its mesh in place: its transform, parent, modifiers and + material slots stay, and the Bevel width follows""" + bl_idname = "brokkr_kitbash.set_params" + bl_label = "Set Kit Part Params" + object_name: bpy.props.StringProperty(name="Object") + params: bpy.props.StringProperty(name="Params", description="name=value; name=value ... the rest keep their stored values") + + @kit_work + def work(self, context): + obj = mesh_object(self.object_name) + part, stored = kit_part_of(obj) + built = core.build(part, core.resolve_params(part, core.parse_params(self.params), stored)) + obj.data.clear_geometry() + write_mesh(obj.data, built) + sync_bevel(obj, built.bevel) + obj[PARAMS] = json.dumps(built.params) + return part_report(obj, part, built) + + +class BROKKR_KITBASH_OT_describe(PolishOperator): + """List a kit's parts, or one part: params with type, bounds, default and doc, and sockets in the part's frame + at default params""" + bl_idname = "brokkr_kitbash.describe" + bl_label = "Describe Kit" + bl_options = {"REGISTER"} + kit: bpy.props.StringProperty(name="Kit", default="mechanical") + part: bpy.props.StringProperty(name="Part", description="Empty: every part of the kit") + + @kit_work + def work(self, context): + return bounded(core.describe(core.load_kit(self.kit), self.part), "name a part to describe it alone") + + +class BROKKR_KITBASH_OT_report(PolishOperator): + """Report placed kit parts as the scene has them: kit, part, params, faces, shells and each socket's world frame""" + bl_idname = "brokkr_kitbash.report" + bl_label = "Report Kit Parts" + bl_options = {"REGISTER"} + object_name: bpy.props.StringProperty(name="Object", description="Empty: every object that is a kit part") + + @kit_work + def work(self, context): + chosen = [mesh_object(self.object_name)] if self.object_name else sorted( + (o for o in context.scene.objects if o.type == "MESH" and PART in o), key=lambda o: o.name) + parts = [] + for obj in chosen: + part, stored = kit_part_of(obj) + parts.append(part_report(obj, part, core.build(part, stored))) + return bounded({"parts": parts}, "name an object to report it alone") + + +classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KITBASH_OT_describe, BROKKR_KITBASH_OT_report) + + +def register(): + if MISSING is not None or not hasattr(bpy.types.WindowManager, RESULT): + raise RuntimeError(f"brokkr_kitbash needs brokkr_mesh_polish enabled first ({MISSING or 'its result property is not registered'}).") + for cls in classes: + bpy.utils.register_class(cls) + + +def unregister(): + for cls in reversed(classes): + bpy.utils.unregister_class(cls) diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json new file mode 100644 index 0000000..41e010a --- /dev/null +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -0,0 +1,111 @@ +{ + "schema": "brokkr.blender.host_actions.v0", + "actions": [ + { + "name": "brokkr_kitbash.place_part", + "doc": "Place a kit part at the origin as a new mesh object (move it with setObjectTransform). Reports its params, faces, shells and each socket's world 4x4 (rows; column 2 is the outward normal, column 3 the origin).", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "kit", + "type": "string", + "chars": "id", + "minLength": 1, + "maxLength": 32, + "default": "mechanical", + "doc": "a kit shipped with the add-on (a-z, 0-9, _)" + }, + { + "name": "part", + "type": "string", + "required": true, + "chars": "id", + "minLength": 1, + "maxLength": 32, + "doc": "a part of the kit; brokkr_kitbash.describe lists them" + }, + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "the new object's name; refused when an object has it" + }, + { + "name": "params", + "type": "string", + "maxLength": 4000, + "default": "", + "doc": "name=value; name=value ... inside each param's bounds; the rest take the part's defaults" + } + ] + }, + { + "name": "brokkr_kitbash.set_params", + "doc": "Change params of a placed kit part and rebuild its mesh in place; transform, parent, modifiers and materials stay. Reports as place_part.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63 + }, + { + "name": "params", + "type": "string", + "required": true, + "maxLength": 4000, + "doc": "name=value; name=value ... the rest keep their stored values" + } + ] + }, + { + "name": "brokkr_kitbash.describe", + "doc": "A kit's parts, or one part: params (type, min, max, default, doc) and sockets in the part's frame at default params.", + "changesScene": false, + "editModeSafe": true, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "kit", + "type": "string", + "chars": "id", + "minLength": 1, + "maxLength": 32, + "default": "mechanical" + }, + { + "name": "part", + "type": "string", + "chars": "id", + "maxLength": 32, + "default": "", + "doc": "empty: every part of the kit" + } + ] + }, + { + "name": "brokkr_kitbash.report", + "doc": "Placed kit parts as the scene has them: kit, part, params, faces, shells and each socket's world 4x4.", + "changesScene": false, + "editModeSafe": true, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "maxLength": 63, + "default": "", + "doc": "empty: every object that is a kit part" + } + ] + } + ] +} diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py new file mode 100644 index 0000000..0d6b0c8 --- /dev/null +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -0,0 +1,478 @@ +"""The kit format: what a kit document may say, and the geometry and socket frames a part and its params produce. + +numpy and the standard library only, no Blender: tests/test_kitbash.py runs this file as it is. A kit is data +(kits/.v0.json beside this file). A part is a list of shapes (tube, box, repeat) whose numbers may be +expressions over the part's params, and a list of sockets, each a frame on one of the part's flat faces. An +expression is parsed with ast.parse and walked against a whitelist; nothing in a kit is ever run as Python. + + kit = load_kit("mechanical") + built = build(part(kit, "tank"), {"length": 1.2}) # Built: V, faces, counts, smooth, shell_count, sockets + +Every refusal is a KitError whose message names the kit, part and field. +""" +from __future__ import annotations + +import ast +import json +import math +import re +from pathlib import Path +from typing import Any, NamedTuple + +import numpy as np + +SCHEMA = "brokkr.kit.v0" +KITS = Path(__file__).with_name("kits") +KIT_NAME = r"[a-z0-9_]{1,32}" +NAME = r"[a-z][a-z0-9_]{0,31}" +CALLS = {"min": min, "max": max} +AXES = {"+x": (1.0, 0.0, 0.0), "-x": (-1.0, 0.0, 0.0), "+y": (0.0, 1.0, 0.0), "-y": (0.0, -1.0, 0.0), + "+z": (0.0, 0.0, 1.0), "-z": (0.0, 0.0, -1.0)} +PLACED = ("at", "rot") +SHAPES = {"tube": (("r0", "r1", "length", "segments"), ("inner0", "inner1", "smooth") + PLACED), + "box": (("size",), PLACED), + "repeat": (("count", "step", "of"), ())} +SEGMENTS = (3, 128) +COPIES = (1, 256) + + +class KitError(ValueError): + """The kit document, a param or a build breaks a rule of the format; the message names where.""" + + +# --- expressions --------------------------------------------------------------------------------------------- + +class Expr: + """A number, or an expression over a part's params that passed the whitelist. value(env) walks the tree.""" + __slots__ = ("source", "tree", "where") + + def __init__(self, source, tree, where): + self.source, self.tree, self.where = source, tree, where + + def value(self, env: dict[str, float]) -> float: + result = self.source if self.tree is None else _walk(self.tree, env, self) + if not math.isfinite(result): + raise KitError(f"{self.where}: {self.source!r} is not a finite number") + return float(result) + + +def parse(value: Any, names, where: str) -> Expr: + """The Expr for a numeric field: a finite number, or a string of + - * /, unary minus, parentheses, min(a,b), + max(a,b), numbers and the names given. Anything else is refused here, before any build.""" + if isinstance(value, (int, float)) and not isinstance(value, bool): + if not math.isfinite(value): + raise KitError(f"{where}: {value!r} is not a finite number") + return Expr(value, None, where) + if not isinstance(value, str): + raise KitError(f"{where} must be a number or an expression string, not {type(value).__name__}") + try: + tree = ast.parse(value, mode="eval").body + except (SyntaxError, ValueError, RecursionError, MemoryError): + raise KitError(f"{where}: {value!r} does not parse as an expression") from None + try: + _admit(tree, frozenset(names), where, value) + except RecursionError: + raise KitError(f"{where}: {value!r} nests too deeply") from None + return Expr(value, tree, where) + + +def _admit(node, names, where, source) -> None: + if isinstance(node, ast.BinOp) and isinstance(node.op, (ast.Add, ast.Sub, ast.Mult, ast.Div)): + _admit(node.left, names, where, source) + _admit(node.right, names, where, source) + elif isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.USub, ast.UAdd)): + _admit(node.operand, names, where, source) + elif isinstance(node, ast.Constant) and type(node.value) in (int, float): + pass + elif isinstance(node, ast.Name): + if node.id not in names: + raise KitError(f"{where}: {source!r} names {node.id!r}, which is not a param of this part ({', '.join(sorted(names)) or 'it has none'})") + elif isinstance(node, ast.Call): + if not isinstance(node.func, ast.Name) or node.func.id not in CALLS: + raise KitError(f"{where}: {source!r} calls something other than min or max") + if len(node.args) != 2 or node.keywords: + raise KitError(f"{where}: {source!r}: {node.func.id} takes exactly two positional arguments") + for argument in node.args: + _admit(argument, names, where, source) + else: + raise KitError(f"{where}: {source!r} uses {type(node).__name__}; an expression is + - * /, unary minus, " + "parentheses, min(a,b), max(a,b), numbers and param names") + + +def _walk(node, env, expr: Expr) -> float: + if isinstance(node, ast.Constant): + return node.value + if isinstance(node, ast.Name): + return env[node.id] + if isinstance(node, ast.UnaryOp): + operand = _walk(node.operand, env, expr) + return -operand if isinstance(node.op, ast.USub) else operand + if isinstance(node, ast.Call): + return CALLS[node.func.id](_walk(node.args[0], env, expr), _walk(node.args[1], env, expr)) + left, right = _walk(node.left, env, expr), _walk(node.right, env, expr) + if isinstance(node.op, ast.Add): + return left + right + if isinstance(node.op, ast.Sub): + return left - right + if isinstance(node.op, ast.Mult): + return left * right + if right == 0: + raise KitError(f"{expr.where}: division by zero in {expr.source!r}") + return left / right + + +# --- the kit document ---------------------------------------------------------------------------------------- + +def _keys(value: Any, where: str, required, optional=()) -> None: + if not isinstance(value, dict): + raise KitError(f"{where} must be an object") + for key in value: + if key not in required and key not in optional: + raise KitError(f"{where} has no key {key!r}; its keys: {', '.join((*required, *optional))}") + for key in required: + if key not in value: + raise KitError(f"{where} lacks {key!r}") + + +def _text(value: Any, where: str) -> str: + if not isinstance(value, str): + raise KitError(f"{where} must be a string") + return value + + +def _name(value: Any, where: str, seen: set) -> str: + if not isinstance(value, str) or not re.fullmatch(NAME, value) or value in CALLS: + raise KitError(f"{where}: {value!r} is not a name (a-z first, then a-z, 0-9 or _, at most 32, not min or max)") + if value in seen: + raise KitError(f"{where}: {value!r} is listed twice") + seen.add(value) + return value + + +def _number(value: Any, where: str) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + raise KitError(f"{where} must be a finite number") + return value + + +def _vector(value: Any, names, where: str) -> list[Expr]: + if not isinstance(value, list) or len(value) != 3: + raise KitError(f"{where} must be an array of three numbers or expressions") + return [parse(item, names, f"{where}[{i}]") for i, item in enumerate(value)] + + +ZERO = [Expr(0.0, None, "zero")] * 3 + + +def _shape(shape: Any, names, where: str, inside_repeat: bool = False) -> dict: + kind = shape.get("shape") if isinstance(shape, dict) else None + if kind not in SHAPES: + raise KitError(f"{where}: unknown shape {kind!r}; shapes are {', '.join(SHAPES)}") + where = f"{where} ({kind})" + required, optional = SHAPES[kind] + _keys(shape, where, ("shape", *required), optional) + if kind == "repeat": + if inside_repeat: + raise KitError(f"{where}: a repeat cannot hold a repeat") + return {"shape": kind, "count": parse(shape["count"], names, f"{where} count"), + "step": _vector(shape["step"], names, f"{where} step"), + "of": _shape(shape["of"], names, f"{where} of", inside_repeat=True)} + made = {"shape": kind, "where": where, + "at": _vector(shape["at"], names, f"{where} at") if "at" in shape else ZERO, + "rot": _vector(shape["rot"], names, f"{where} rot") if "rot" in shape else ZERO} + if kind == "box": + made["size"] = _vector(shape["size"], names, f"{where} size") + return made + for key in ("r0", "r1", "length", "segments"): + made[key] = parse(shape[key], names, f"{where} {key}") + for key in ("inner0", "inner1"): + made[key] = parse(shape.get(key, 0), names, f"{where} {key}") + if not isinstance(shape.get("smooth", False), bool): + raise KitError(f"{where} smooth must be true or false") + made["smooth"] = shape.get("smooth", False) + return made + + +def check_kit(document: Any) -> dict: + """The checked kit: {'kit', 'doc', 'socketTypes', 'parts': {name: part}} with every numeric field an Expr. + Refuses, naming kit, part and field, anything the format does not say (the module docstring and docs/kitbash.md).""" + if not isinstance(document, dict) or document.get("schema") != SCHEMA: + raise KitError(f"kit schema must be {SCHEMA}") + _keys(document, "kit", ("schema", "kit", "doc", "socketTypes", "parts")) + kit = document["kit"] + if not isinstance(kit, str) or not re.fullmatch(KIT_NAME, kit): + raise KitError(f"kit name {kit!r} must be 1 to 32 of a-z, 0-9 and _") + here = f"kit {kit!r}" + _text(document["doc"], f"{here} doc") + if not isinstance(document["socketTypes"], dict) or not isinstance(document["parts"], list): + raise KitError(f"{here}: socketTypes must be an object and parts an array") + types = {} + for name, entry in document["socketTypes"].items(): + where = f"{here} socket type {name!r}" + _name(name, where, set()) + _keys(entry, where, ("match", "doc")) + 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")} + 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) + where = f"{here} part {name!r}" + _keys(part, where, ("name", "doc", "params", "shapes", "sockets"), ("bevel",)) + if not all(isinstance(part[key], list) for key in ("params", "shapes", "sockets")): + raise KitError(f"{where}: params, shapes and sockets must be arrays") + params, names = [], set() + for p_index, param in enumerate(part["params"]): + p_name = _name(param.get("name") if isinstance(param, dict) else None, f"{where} param {p_index}", names) + p_where = f"{where} param {p_name!r}" + _keys(param, p_where, ("name", "type", "min", "max", "default", "doc")) + if param["type"] not in ("number", "integer"): + raise KitError(f"{p_where}: type must be 'number' or 'integer'") + low, high, default = (_number(param[key], f"{p_where} {key}") for key in ("min", "max", "default")) + if low > high: + raise KitError(f"{p_where}: min {low} is above max {high}") + if not low <= default <= high: + raise KitError(f"{p_where}: default {default} is outside [{low}, {high}]") + if param["type"] == "integer": + for key, value in (("min", low), ("max", high), ("default", default)): + if value != int(value): + raise KitError(f"{p_where}: an integer param's {key} must be whole, not {value}") + low, high, default = int(low), int(high), int(default) + params.append({"name": p_name, "type": param["type"], "min": low, "max": high, "default": default, + "doc": _text(param["doc"], f"{p_where} doc")}) + shapes = [_shape(shape, names, f"{where} shape {i}") for i, shape in enumerate(part["shapes"])] + if not shapes: + raise KitError(f"{where} has no shapes") + sockets, socket_names = [], set() + for s_index, socket in enumerate(part["sockets"]): + s_name = _name(socket.get("name") if isinstance(socket, dict) else None, f"{where} socket {s_index}", socket_names) + s_where = f"{where} socket {s_name!r}" + _keys(socket, s_where, ("name", "type", "size", "at", "z", "y")) + if socket["type"] not in types: + raise KitError(f"{s_where}: type {socket['type']!r} is not one of the kit's socketTypes ({', '.join(types) or 'none'})") + for key in ("z", "y"): + if socket[key] not in AXES: + raise KitError(f"{s_where}: {key} must be one of {', '.join(AXES)}") + if socket["z"][1] == socket["y"][1]: + raise KitError(f"{s_where}: z ({socket['z']}) and y ({socket['y']}) lie on the same axis") + sockets.append({"name": s_name, "type": socket["type"], "size": parse(socket["size"], names, f"{s_where} size"), + "at": _vector(socket["at"], names, f"{s_where} at"), "z": socket["z"], "y": socket["y"]}) + parts[name] = {"kit": kit, "name": name, "doc": _text(part["doc"], f"{where} doc"), "params": params, + "bevel": parse(part["bevel"], names, f"{where} bevel") if "bevel" in part else None, + "shapes": shapes, "sockets": sockets} + return {"kit": kit, "doc": document["doc"], "socketTypes": types, "parts": parts} + + +def load_kit(name: str) -> dict: + """The checked kit kits/.v0.json. The name is the only thing a caller chooses: it cannot spell a path.""" + if not isinstance(name, str) or not re.fullmatch(KIT_NAME, name): + raise KitError(f"kit name {name!r} must be 1 to 32 of a-z, 0-9 and _") + path = KITS / f"{name}.v0.json" + if not path.is_file(): + raise KitError(f"no kit named {name!r}; kits: {', '.join(kit_names()) or 'none'}") + try: + document = json.loads(path.read_text(encoding="utf-8")) + except ValueError as error: + raise KitError(f"kit {name!r} is not JSON: {error}") from None + kit = check_kit(document) + if kit["kit"] != name: + raise KitError(f"kit file {path.name} says it is kit {kit['kit']!r}") + return kit + + +def kit_names() -> list[str]: + return sorted(p.name[:-len(".v0.json")] for p in KITS.glob("*.v0.json")) + + +def part(kit: dict, name: str) -> dict: + found = kit["parts"].get(name) + if found is None: + raise KitError(f"kit {kit['kit']!r} has no part {name!r}; its parts: {', '.join(kit['parts'])}") + return found + + +# --- params -------------------------------------------------------------------------------------------------- + +def parse_params(text: str) -> dict[str, float]: + """'k=v; k=v' as a dict of numbers. Refuses a repeated key and a value that is not a finite number.""" + given: dict[str, float] = {} + for item in text.split(";"): + if not item.strip(): + continue + key, equals, value = item.partition("=") + key = key.strip() + if not equals or not key: + raise KitError(f"params: {item.strip()!r} is not name=value") + if key in given: + raise KitError(f"params: {key!r} is given twice") + try: + number = float(value) + except ValueError: + number = math.nan + if not math.isfinite(number): + raise KitError(f"params: {key} = {value.strip()!r} is not a number") + given[key] = number + return given + + +def resolve_params(part: dict, given: dict, base: dict | None = None) -> dict: + """Every param of the part, in the part's order: base overlaid by given, defaults for the rest. Refuses an + unknown param, a value outside the inclusive [min, max], and a fraction for an integer param.""" + merged = {**(base or {}), **given} + here = f"kit {part['kit']!r} part {part['name']!r}" + known = [p["name"] for p in part["params"]] + for key in merged: + if key not in known: + raise KitError(f"{here} has no param {key!r}; its params: {', '.join(known) or 'none'}") + resolved = {} + for param in part["params"]: + name = param["name"] + value = merged.get(name, param["default"]) + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + raise KitError(f"{here} param {name!r} must be a finite number") + if not param["min"] <= value <= param["max"]: + raise KitError(f"{here} param {name!r} = {value} is outside [{param['min']}, {param['max']}] (bounds included)") + if param["type"] == "integer": + if value != int(value): + raise KitError(f"{here} param {name!r} is an integer; {value} is not whole") + value = int(value) + resolved[name] = value if param["type"] == "integer" else float(value) + return resolved + + +# --- geometry ------------------------------------------------------------------------------------------------ + +class Built(NamedTuple): + """A part at given params, in the part's frame, metres. Face i has counts[i] corners, listed in order in + faces (quads and n-gon caps, wound outward); smooth[i] marks tube sides to shade smooth. Each socket is + {'name', 'type', 'size', 'matrix'} with matrix the 4x4 frame: column 2 the outward normal, column 1 up, + column 0 = y cross z, column 3 the origin.""" + V: np.ndarray + faces: np.ndarray + counts: np.ndarray + smooth: np.ndarray + shell_count: int + sockets: list + bevel: float + params: dict + + +def _whole(expr: Expr, env, bounds) -> int: + value = expr.value(env) + if abs(value - round(value)) > 1e-9 or not bounds[0] <= round(value) <= bounds[1]: + raise KitError(f"{expr.where} is {value}: it must be a whole number from {bounds[0]} to {bounds[1]}") + return int(round(value)) + + +def _rotation(degrees) -> np.ndarray: + """XYZ Euler: about x, then y, then z, each about the fixed axes of the shape's own origin.""" + (cx, sx), (cy, sy), (cz, sz) = ((math.cos(math.radians(a)), math.sin(math.radians(a))) for a in degrees) + rx = np.array([[1.0, 0.0, 0.0], [0.0, cx, -sx], [0.0, sx, cx]]) + ry = np.array([[cy, 0.0, sy], [0.0, 1.0, 0.0], [-sy, 0.0, cy]]) + rz = np.array([[cz, -sz, 0.0], [sz, cz, 0.0], [0.0, 0.0, 1.0]]) + return rz @ ry @ rx + + +def _tube(shape: dict, env): + r0, r1, length = (shape[key].value(env) for key in ("r0", "r1", "length")) + i0, i1 = shape["inner0"].value(env), shape["inner1"].value(env) + n = _whole(shape["segments"], env, SEGMENTS) + where = shape["where"] + if length <= 0: + raise KitError(f"{where}: length {length} must be above 0") + if not (0 <= i0 < r0 and 0 <= i1 < r1): + raise KitError(f"{where}: needs 0 <= inner < outer at both ends, got inner {i0}, {i1} and outer {r0}, {r1}") + if (i0 > 0) != (i1 > 0): + raise KitError(f"{where}: inner0 and inner1 must both be above 0 (hollow) or both be 0 (solid), got {i0}, {i1}") + angle = 2.0 * math.pi * np.arange(n) / n + cos, sin = np.cos(angle), np.sin(angle) + ring = lambda r, z: np.column_stack([r * cos, r * sin, np.full(n, z)]) # noqa: E731 + k = np.arange(n) + j = (k + 1) % n + side = np.column_stack([k, j, n + j, n + k]) + if i0 > 0: + V = np.vstack([ring(r0, 0.0), ring(r1, length), ring(i0, 0.0), ring(i1, length)]) + inner = np.column_stack([2 * n + j, 2 * n + k, 3 * n + k, 3 * n + j]) + bottom = np.column_stack([k, 2 * n + k, 2 * n + j, j]) + top = np.column_stack([n + k, n + j, 3 * n + j, 3 * n + k]) + faces = np.concatenate([side, inner, bottom, top]).ravel() + counts = np.full(4 * n, 4) + smooth = np.repeat([shape["smooth"], shape["smooth"], False, False], n) + else: + V = np.vstack([ring(r0, 0.0), ring(r1, length)]) + faces = np.concatenate([side.ravel(), k[::-1], n + k]) + counts = np.concatenate([np.full(n, 4), [n, n]]) + smooth = np.concatenate([np.full(n, shape["smooth"]), [False, False]]) + return V, faces, counts, smooth + + +BOX_FACES = np.array([[0, 3, 2, 1], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]]) +BOX_SIGNS = np.array([[-1, -1, -1], [1, -1, -1], [1, 1, -1], [-1, 1, -1], [-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1]]) * 0.5 + + +def _box(shape: dict, env): + size = np.array([e.value(env) for e in shape["size"]]) + if not (size > 0).all(): + raise KitError(f"{shape['where']}: every size must be above 0, got {size.tolist()}") + return BOX_SIGNS * size, BOX_FACES.ravel(), np.full(6, 4), np.zeros(6, dtype=bool) + + +def _placed(shape: dict, env): + V, faces, counts, smooth = (_tube if shape["shape"] == "tube" else _box)(shape, env) + rotation = _rotation([e.value(env) for e in shape["rot"]]) + return V @ rotation.T + np.array([e.value(env) for e in shape["at"]]), faces, counts, smooth + + +def build(part: dict, params: dict | None = None) -> Built: + """The part at these params (resolve_params fills and checks them). The same part and params give + byte-identical arrays.""" + env = resolve_params(part, params or {}) + shells = [] + for shape in part["shapes"]: + if shape["shape"] == "repeat": + count = _whole(shape["count"], env, COPIES) + step = np.array([e.value(env) for e in shape["step"]]) + V, faces, counts, smooth = _placed(shape["of"], env) + shells += [(V + k * step, faces, counts, smooth) for k in range(count)] + else: + shells.append(_placed(shape, env)) + offsets = np.cumsum([0] + [len(s[0]) for s in shells[:-1]]) + sockets = [] + for socket in part["sockets"]: + z, y = np.array(AXES[socket["z"]]), np.array(AXES[socket["y"]]) + matrix = np.eye(4) + matrix[:3, 0], matrix[:3, 1], matrix[:3, 2] = np.cross(y, z), y, z + matrix[:3, 3] = [e.value(env) for e in socket["at"]] + size = socket["size"].value(env) + if size <= 0: + raise KitError(f"{socket['size'].where} is {size}: a socket's size must be above 0") + sockets.append({"name": socket["name"], "type": socket["type"], "size": size, "matrix": matrix}) + bevel = part["bevel"].value(env) if part["bevel"] is not None else 0.0 + if bevel < 0: + raise KitError(f"{part['bevel'].where} is {bevel}: a bevel is 0 or more") + return Built(V=np.vstack([s[0] for s in shells]).astype(np.float64), + faces=np.concatenate([s[1] + o for s, o in zip(shells, offsets)]).astype(np.int32), + counts=np.concatenate([s[2] for s in shells]).astype(np.int32), + smooth=np.concatenate([s[3] for s in shells]).astype(bool), + shell_count=len(shells), sockets=sockets, bevel=bevel, params=env) + + +# --- reports ------------------------------------------------------------------------------------------------- + +def rows(matrix) -> list[list[float]]: + """A 4x4 as rows of 6 decimals, for a report.""" + return [[round(float(value), 6) + 0.0 for value in row] for row in np.asarray(matrix)] + + +def socket_rows(sockets: list, frame=None) -> list[dict]: + """Sockets for a report, their frames carried into `frame` (a 4x4; the part's own frame when None).""" + frame = np.eye(4) if frame is None else np.asarray(frame, dtype=np.float64) + return [{"name": s["name"], "type": s["type"], "size": round(s["size"], 6), "matrix": rows(frame @ s["matrix"])} for s in sockets] + + +def describe(kit: dict, name: str = "") -> dict: + """The kit's parts (or the one named): params with their bounds, and sockets in the part frame at default params.""" + chosen = [part(kit, name)] if name else list(kit["parts"].values()) + return {"kit": kit["kit"], "doc": kit["doc"], "socketTypes": kit["socketTypes"], + "parts": [{"name": p["name"], "doc": p["doc"], "params": p["params"], + "sockets": socket_rows(build(p).sockets)} for p in chosen]} diff --git a/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json b/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json new file mode 100644 index 0000000..41d2da7 --- /dev/null +++ b/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json @@ -0,0 +1,295 @@ +{ + "schema": "brokkr.kit.v0", + "kit": "mechanical", + "doc": "Ship machinery: engines, tanks, structure, plumbing and cooling. Parts run along +z; metres.", + "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"} + }, + "parts": [ + { + "name": "nozzle", + "doc": "Rocket engine: mount flange, chamber with gimbal lugs, throat collar and a hollow hooped bell opening along +z.", + "params": [ + {"name": "throat_r", "type": "number", "min": 0.04, "max": 0.12, "default": 0.07, "doc": "throat radius"}, + {"name": "exit_r", "type": "number", "min": 0.16, "max": 0.45, "default": 0.26, "doc": "bell exit radius"}, + {"name": "length", "type": "number", "min": 0.25, "max": 1.0, "default": 0.5, "doc": "bell length, throat to exit"}, + {"name": "wall", "type": "number", "min": 0.004, "max": 0.015, "default": 0.008, "doc": "bell wall thickness"}, + {"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of every round"} + ], + "bevel": "0.3*wall", + "shapes": [ + {"shape": "tube", "r0": "2.1*throat_r", "r1": "2.1*throat_r", "length": "0.3*throat_r", "segments": "segments", "smooth": true}, + {"shape": "repeat", "count": 2, "step": ["2.62*throat_r", 0, 0], "of": + {"shape": "tube", "r0": "0.14*throat_r", "r1": "0.14*throat_r", "length": "0.35*throat_r", "segments": 6, "at": ["-1.31*throat_r", "-1.31*throat_r", "0.1*throat_r"]}}, + {"shape": "repeat", "count": 2, "step": ["2.62*throat_r", 0, 0], "of": + {"shape": "tube", "r0": "0.14*throat_r", "r1": "0.14*throat_r", "length": "0.35*throat_r", "segments": 6, "at": ["-1.31*throat_r", "1.31*throat_r", "0.1*throat_r"]}}, + {"shape": "tube", "r0": "1.6*throat_r", "r1": "1.6*throat_r", "length": "1.75*throat_r", "segments": "segments", "smooth": true, "at": [0, 0, "0.15*throat_r"]}, + {"shape": "tube", "r0": "1.6*throat_r", "r1": "throat_r+wall", "length": "throat_r", "segments": "segments", "smooth": true, "at": [0, 0, "1.9*throat_r"]}, + {"shape": "tube", "r0": "1.78*throat_r", "r1": "1.78*throat_r", "length": "0.5*throat_r", "segments": "segments", "smooth": true, "at": [0, 0, "1.6*throat_r"]}, + {"shape": "tube", "r0": "throat_r+wall", "r1": "throat_r+wall+0.226*(exit_r-throat_r-wall)", "inner0": "throat_r", "inner1": "throat_r+0.226*(exit_r-throat_r-wall)", + "length": "0.12*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r"]}, + {"shape": "tube", "r0": "throat_r+wall+0.226*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.482*(exit_r-throat_r-wall)", "inner0": "throat_r+0.226*(exit_r-throat_r-wall)", "inner1": "throat_r+0.482*(exit_r-throat_r-wall)", + "length": "0.16*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.12*length"]}, + {"shape": "tube", "r0": "throat_r+wall+0.482*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.75*(exit_r-throat_r-wall)", "inner0": "throat_r+0.482*(exit_r-throat_r-wall)", "inner1": "throat_r+0.75*(exit_r-throat_r-wall)", + "length": "0.22*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.28*length"]}, + {"shape": "tube", "r0": "throat_r+wall+0.75*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.9375*(exit_r-throat_r-wall)", "inner0": "throat_r+0.75*(exit_r-throat_r-wall)", "inner1": "throat_r+0.9375*(exit_r-throat_r-wall)", + "length": "0.25*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.5*length"]}, + {"shape": "tube", "r0": "throat_r+wall+0.9375*(exit_r-throat_r-wall)", "r1": "exit_r", "inner0": "throat_r+0.9375*(exit_r-throat_r-wall)", "inner1": "exit_r-wall", + "length": "0.25*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.75*length"]}, + {"shape": "tube", "r0": "throat_r+2.4*wall+0.5795*(exit_r-throat_r-wall)", "r1": "throat_r+2.4*wall+0.616*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5*wall+0.5795*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5*wall+0.616*(exit_r-throat_r-wall)", + "length": "0.03*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.36*length"]}, + {"shape": "tube", "r0": "throat_r+2.4*wall+0.825*(exit_r-throat_r-wall)", "r1": "throat_r+2.4*wall+0.8475*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5*wall+0.825*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5*wall+0.8475*(exit_r-throat_r-wall)", + "length": "0.03*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.6*length"]}, + {"shape": "tube", "r0": "throat_r+2.4*wall+0.965*(exit_r-throat_r-wall)", "r1": "throat_r+2.4*wall+0.9725*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5*wall+0.965*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5*wall+0.9725*(exit_r-throat_r-wall)", + "length": "0.03*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.86*length"]}, + {"shape": "repeat", "count": 2, "step": ["3.4*throat_r", 0, 0], "of": + {"shape": "box", "size": ["0.5*throat_r", "0.35*throat_r", "0.6*throat_r"], "at": ["-1.7*throat_r", 0, "throat_r"]}}, + {"shape": "repeat", "count": 2, "step": [0, "3.4*throat_r", 0], "of": + {"shape": "box", "size": ["0.35*throat_r", "0.5*throat_r", "0.6*throat_r"], "at": [0, "-1.7*throat_r", "throat_r"]}}, + {"shape": "tube", "r0": "exit_r+1.6*wall", "r1": "exit_r+1.6*wall", "inner0": "exit_r-0.5*wall", "inner1": "exit_r-0.5*wall", + "length": "3*wall", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+length-2.5*wall"]} + ], + "sockets": [ + {"name": "mount", "type": "flange", "size": "2*throat_r", "at": [0, 0, 0], "z": "-z", "y": "+y"} + ] + }, + { + "name": "tank", + "doc": "Pressure tank: domed ends with flanged ports, weld bands, two straps on saddle cradles and a mounting pad.", + "params": [ + {"name": "radius", "type": "number", "min": 0.12, "max": 0.35, "default": 0.22, "doc": "shell radius"}, + {"name": "length", "type": "number", "min": 0.6, "max": 2.0, "default": 0.9, "doc": "port face to port face"}, + {"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of every round"} + ], + "bevel": "0.008*radius", + "shapes": [ + {"shape": "tube", "r0": "0.3*radius", "r1": "0.3*radius", "length": "0.05*radius", "segments": "segments", "smooth": true}, + {"shape": "tube", "r0": "0.2*radius", "r1": "0.2*radius", "length": "0.18*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.02*radius"]}, + {"shape": "tube", "r0": "0.47*radius", "r1": "0.85*radius", "length": "0.15*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.12*radius"]}, + {"shape": "tube", "r0": "0.85*radius", "r1": "radius", "length": "0.22*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.27*radius"]}, + {"shape": "tube", "r0": "radius", "r1": "radius", "length": "length-0.98*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.49*radius"]}, + {"shape": "tube", "r0": "radius", "r1": "0.85*radius", "length": "0.22*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.49*radius"]}, + {"shape": "tube", "r0": "0.85*radius", "r1": "0.47*radius", "length": "0.15*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.27*radius"]}, + {"shape": "tube", "r0": "0.2*radius", "r1": "0.2*radius", "length": "0.18*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.2*radius"]}, + {"shape": "tube", "r0": "0.3*radius", "r1": "0.3*radius", "length": "0.05*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.05*radius"]}, + {"shape": "repeat", "count": 2, "step": [0, 0, "length-0.98*radius"], "of": + {"shape": "tube", "r0": "1.012*radius", "r1": "1.012*radius", "inner0": "0.97*radius", "inner1": "0.97*radius", "length": "0.04*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.47*radius"]}}, + {"shape": "repeat", "count": 2, "step": [0, 0, "0.56*(length-0.98*radius)"], "of": + {"shape": "tube", "r0": "1.035*radius", "r1": "1.035*radius", "inner0": "0.97*radius", "inner1": "0.97*radius", "length": "0.1*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.44*radius+0.22*(length-0.98*radius)"]}}, + {"shape": "repeat", "count": 2, "step": [0, 0, "0.56*(length-0.98*radius)"], "of": + {"shape": "box", "size": ["1.3*radius", "0.55*radius", "0.1*radius"], "at": [0, "-0.85*radius", "0.49*radius+0.22*(length-0.98*radius)"]}}, + {"shape": "box", "size": ["1.5*radius", "0.08*radius", "0.56*(length-0.98*radius)+0.3*radius"], "at": [0, "-1.14*radius", "length/2"]} + ], + "sockets": [ + {"name": "port_a", "type": "flange", "size": "0.4*radius", "at": [0, 0, 0], "z": "-z", "y": "+y"}, + {"name": "port_b", "type": "flange", "size": "0.4*radius", "at": [0, 0, "length"], "z": "+z", "y": "+y"}, + {"name": "saddle", "type": "mount", "size": "1.5*radius", "at": [0, "-1.18*radius", "length/2"], "z": "-y", "y": "+z"} + ] + }, + { + "name": "ribbed_cylinder", + "doc": "Finned housing (motor, exchanger, capacitor): a drum with cooling ribs, end flanges, four tie bolts and a cable raceway.", + "params": [ + {"name": "radius", "type": "number", "min": 0.08, "max": 0.3, "default": 0.15, "doc": "drum radius"}, + {"name": "length", "type": "number", "min": 0.3, "max": 1.5, "default": 0.6, "doc": "end face to end face"}, + {"name": "ribs", "type": "integer", "min": 2, "max": 24, "default": 10, "doc": "rib rings"}, + {"name": "rib_depth", "type": "number", "min": 0.01, "max": 0.05, "default": 0.03, "doc": "how far ribs stand off the drum"}, + {"name": "rib_width", "type": "number", "min": 0.008, "max": 0.03, "default": 0.015, "doc": "rib thickness along the axis (narrowed when ribs crowd)"}, + {"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of every round"} + ], + "bevel": "0.15*min(min(rib_width,rib_depth),0.6*(length-3*rib_width)/ribs)", + "shapes": [ + {"shape": "tube", "r0": "radius+1.6*rib_depth", "r1": "radius+1.6*rib_depth", "length": "1.5*rib_width", "segments": "segments", "smooth": true}, + {"shape": "tube", "r0": "radius", "r1": "radius", "length": "length-1.5*rib_width", "segments": "segments", "smooth": true, "at": [0, 0, "0.75*rib_width"]}, + {"shape": "tube", "r0": "radius+1.6*rib_depth", "r1": "radius+1.6*rib_depth", "length": "1.5*rib_width", "segments": "segments", "smooth": true, "at": [0, 0, "length-1.5*rib_width"]}, + {"shape": "repeat", "count": "ribs", "step": [0, 0, "(length-3*rib_width)/ribs"], "of": + {"shape": "tube", "r0": "radius+rib_depth", "r1": "radius+rib_depth", "length": "min(rib_width,0.6*(length-3*rib_width)/ribs)", "segments": "segments", "smooth": true, + "at": [0, 0, "1.5*rib_width+0.5*(length-3*rib_width)/ribs-0.5*min(rib_width,0.6*(length-3*rib_width)/ribs)"]}}, + {"shape": "repeat", "count": 2, "step": ["1.4142*(radius+0.5*rib_depth)", 0, 0], "of": + {"shape": "tube", "r0": "0.28*rib_depth", "r1": "0.28*rib_depth", "length": "length-1.5*rib_width", "segments": 6, "at": ["-0.7071*(radius+0.5*rib_depth)", "-0.7071*(radius+0.5*rib_depth)", "0.75*rib_width"]}}, + {"shape": "repeat", "count": 2, "step": ["1.4142*(radius+0.5*rib_depth)", 0, 0], "of": + {"shape": "tube", "r0": "0.28*rib_depth", "r1": "0.28*rib_depth", "length": "length-1.5*rib_width", "segments": 6, "at": ["-0.7071*(radius+0.5*rib_depth)", "0.7071*(radius+0.5*rib_depth)", "0.75*rib_width"]}}, + {"shape": "box", "size": ["0.45*radius", "0.15*radius+1.3*rib_depth", "length-3*rib_width"], "at": [0, "0.925*radius+0.65*rib_depth", "length/2"]} + ], + "sockets": [ + {"name": "end_a", "type": "flange", "size": "2*radius", "at": [0, 0, 0], "z": "-z", "y": "+y"}, + {"name": "end_b", "type": "flange", "size": "2*radius", "at": [0, 0, "length"], "z": "+z", "y": "+y"} + ] + }, + { + "name": "strut", + "doc": "Structural strut: an I-beam with web stiffeners between two pinned end blocks.", + "params": [ + {"name": "length", "type": "number", "min": 0.3, "max": 2.0, "default": 0.8, "doc": "end face to end face"}, + {"name": "width", "type": "number", "min": 0.04, "max": 0.12, "default": 0.08, "doc": "flange width (x)"}, + {"name": "thickness", "type": "number", "min": 0.02, "max": 0.08, "default": 0.05, "doc": "beam depth (y)"}, + {"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of the pins"} + ], + "bevel": "0.03*min(width,thickness)", + "shapes": [ + {"shape": "box", "size": ["1.3*width", "1.3*thickness", "0.9*width"], "at": [0, 0, "0.45*width"]}, + {"shape": "box", "size": ["1.3*width", "1.3*thickness", "0.9*width"], "at": [0, 0, "length-0.45*width"]}, + {"shape": "repeat", "count": 2, "step": [0, 0, "length-0.9*width"], "of": + {"shape": "tube", "r0": "0.3*width", "r1": "0.3*width", "length": "1.7*thickness", "segments": "segments", "smooth": true, "rot": [-90, 0, 0], "at": [0, "-0.85*thickness", "0.45*width"]}}, + {"shape": "repeat", "count": 2, "step": [0, "0.78*thickness", 0], "of": + {"shape": "box", "size": ["width", "0.22*thickness", "length-0.9*width"], "at": [0, "-0.39*thickness", "length/2"]}}, + {"shape": "box", "size": ["0.18*width", "0.6*thickness", "length-0.9*width"], "at": [0, 0, "length/2"]}, + {"shape": "repeat", "count": 3, "step": [0, 0, "(length-1.8*width)/4"], "of": + {"shape": "box", "size": ["0.9*width", "0.7*thickness", "0.08*width"], "at": [0, 0, "0.9*width+(length-1.8*width)/4"]}} + ], + "sockets": [ + {"name": "end_a", "type": "pivot", "size": "0.6*width", "at": [0, 0, 0], "z": "-z", "y": "+y"}, + {"name": "end_b", "type": "pivot", "size": "0.6*width", "at": [0, 0, "length"], "z": "+z", "y": "+y"} + ] + }, + { + "name": "actuator", + "doc": "Tie-rod hydraulic cylinder: pinned base eye, square caps, barrel, ports, and a rod with its eye; extension moves rod_end.", + "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": "rod radius"}, + {"name": "extension", "type": "number", "min": 0.0, "max": 0.8, "default": 0.15, "doc": "rod travel out of the gland"}, + {"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"]}, + {"shape": "tube", "r0": "rod_r", "r1": "rod_r", "length": "extension+0.9*body_r", "segments": "segments", "smooth": true, "at": [0, 0, "2.4*body_r+body_len"]}, + {"shape": "box", "size": ["1.2*body_r", "0.9*body_r", "1.4*body_r"], "at": [0, 0, "3.8*body_r+body_len+extension"]}, + {"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", "3.8*body_r+body_len+extension"]} + ], + "sockets": [ + {"name": "base", "type": "pivot", "size": "0.9*body_r", "at": [0, 0, 0], "z": "-z", "y": "+y"}, + {"name": "rod_end", "type": "pivot", "size": "0.9*body_r", "at": [0, 0, "4.5*body_r+body_len+extension"], "z": "+z", "y": "+y"} + ] + }, + { + "name": "pipe_fitting", + "doc": "Flanged tee: a run along +z with a branch along +x at its middle, a reinforced hub and bolted flanges.", + "params": [ + {"name": "pipe_r", "type": "number", "min": 0.03, "max": 0.07, "default": 0.05, "doc": "pipe radius"}, + {"name": "run", "type": "number", "min": 0.4, "max": 1.0, "default": 0.5, "doc": "run length, face a to face b"}, + {"name": "branch", "type": "number", "min": 0.15, "max": 0.5, "default": 0.25, "doc": "branch length, run axis to face c"}, + {"name": "flange_r", "type": "number", "min": 0.09, "max": 0.14, "default": 0.095, "doc": "flange radius"}, + {"name": "flange_t", "type": "number", "min": 0.012, "max": 0.04, "default": 0.02, "doc": "flange thickness"}, + {"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of every round"} + ], + "bevel": "min(0.15*flange_t,0.06*(flange_r-pipe_r))", + "shapes": [ + {"shape": "tube", "r0": "pipe_r", "r1": "pipe_r", "length": "run-flange_t", "segments": "segments", "smooth": true, "at": [0, 0, "0.5*flange_t"]}, + {"shape": "tube", "r0": "flange_r", "r1": "flange_r", "length": "flange_t", "segments": "segments", "smooth": true}, + {"shape": "tube", "r0": "flange_r", "r1": "flange_r", "length": "flange_t", "segments": "segments", "smooth": true, "at": [0, 0, "run-flange_t"]}, + {"shape": "tube", "r0": "1.3*pipe_r", "r1": "1.3*pipe_r", "length": "min(3*pipe_r,run-4*flange_t)", "segments": "segments", "smooth": true, "at": [0, 0, "run/2-min(3*pipe_r,run-4*flange_t)/2"]}, + {"shape": "tube", "r0": "pipe_r", "r1": "pipe_r", "length": "branch-0.5*flange_t", "segments": "segments", "smooth": true, "rot": [0, 90, 0], "at": [0, 0, "run/2"]}, + {"shape": "tube", "r0": "1.3*pipe_r", "r1": "1.3*pipe_r", "length": "min(2.2*pipe_r,branch-2*flange_t)", "segments": "segments", "smooth": true, "rot": [0, 90, 0], "at": [0, 0, "run/2"]}, + {"shape": "tube", "r0": "flange_r", "r1": "flange_r", "length": "flange_t", "segments": "segments", "smooth": true, "rot": [0, 90, 0], "at": ["branch-flange_t", 0, "run/2"]}, + {"shape": "repeat", "count": 2, "step": ["0.7072*(flange_r+pipe_r)", 0, 0], "of": + {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "at": ["-0.3536*(flange_r+pipe_r)", "-0.3536*(flange_r+pipe_r)", "0.15*flange_t"]}}, + {"shape": "repeat", "count": 2, "step": ["0.7072*(flange_r+pipe_r)", 0, 0], "of": + {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "at": ["-0.3536*(flange_r+pipe_r)", "0.3536*(flange_r+pipe_r)", "0.15*flange_t"]}}, + {"shape": "repeat", "count": 2, "step": ["0.7072*(flange_r+pipe_r)", 0, 0], "of": + {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "at": ["-0.3536*(flange_r+pipe_r)", "-0.3536*(flange_r+pipe_r)", "run-1.5*flange_t"]}}, + {"shape": "repeat", "count": 2, "step": ["0.7072*(flange_r+pipe_r)", 0, 0], "of": + {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "at": ["-0.3536*(flange_r+pipe_r)", "0.3536*(flange_r+pipe_r)", "run-1.5*flange_t"]}}, + {"shape": "repeat", "count": 2, "step": [0, 0, "0.7072*(flange_r+pipe_r)"], "of": + {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "rot": [0, 90, 0], "at": ["branch-1.5*flange_t", "-0.3536*(flange_r+pipe_r)", "run/2-0.3536*(flange_r+pipe_r)"]}}, + {"shape": "repeat", "count": 2, "step": [0, 0, "0.7072*(flange_r+pipe_r)"], "of": + {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "rot": [0, 90, 0], "at": ["branch-1.5*flange_t", "0.3536*(flange_r+pipe_r)", "run/2-0.3536*(flange_r+pipe_r)"]}} + ], + "sockets": [ + {"name": "a", "type": "flange", "size": "2*pipe_r", "at": [0, 0, 0], "z": "-z", "y": "+y"}, + {"name": "b", "type": "flange", "size": "2*pipe_r", "at": [0, 0, "run"], "z": "+z", "y": "+y"}, + {"name": "c", "type": "flange", "size": "2*pipe_r", "at": ["branch", 0, "run/2"], "z": "+x", "y": "+z"} + ] + }, + { + "name": "radiator_stack", + "doc": "Fin stack: plate fins on a spine and two heat pipes, between a base block and a header.", + "params": [ + {"name": "fins", "type": "integer", "min": 3, "max": 40, "default": 12, "doc": "fin plates"}, + {"name": "fin_w", "type": "number", "min": 0.15, "max": 0.6, "default": 0.3, "doc": "fin width (x)"}, + {"name": "fin_h", "type": "number", "min": 0.08, "max": 0.4, "default": 0.18, "doc": "fin height (y)"}, + {"name": "fin_t", "type": "number", "min": 0.003, "max": 0.012, "default": 0.005, "doc": "fin thickness"}, + {"name": "pitch", "type": "number", "min": 0.015, "max": 0.05, "default": 0.025, "doc": "fin spacing along +z"}, + {"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of the heat pipes"} + ], + "bevel": "0.2*fin_t", + "shapes": [ + {"shape": "box", "size": ["0.5*fin_w", "0.85*fin_h", "0.12*fin_h"], "at": [0, 0, "0.06*fin_h"]}, + {"shape": "box", "size": ["0.1*fin_w", "0.55*fin_h", "fins*pitch+0.06*fin_h"], "at": [0, 0, "0.09*fin_h+0.5*fins*pitch"]}, + {"shape": "repeat", "count": "fins", "step": [0, 0, "pitch"], "of": + {"shape": "box", "size": ["fin_w", "fin_h", "fin_t"], "at": [0, 0, "0.12*fin_h+0.5*pitch"]}}, + {"shape": "repeat", "count": 2, "step": ["0.64*fin_w", 0, 0], "of": + {"shape": "tube", "r0": "0.07*fin_h", "r1": "0.07*fin_h", "length": "fins*pitch+0.1*fin_h", "segments": "segments", "smooth": true, "at": ["-0.32*fin_w", 0, "0.06*fin_h"]}}, + {"shape": "box", "size": ["0.8*fin_w", "0.3*fin_h", "0.1*fin_h"], "at": [0, 0, "0.17*fin_h+fins*pitch"]} + ], + "sockets": [ + {"name": "base", "type": "mount", "size": "min(0.5*fin_w,0.85*fin_h)", "at": [0, 0, 0], "z": "-z", "y": "+y"} + ] + }, + { + "name": "vent", + "doc": "Louvred vent: a framed box on a back plate with tilted slats; it breathes along +z.", + "params": [ + {"name": "width", "type": "number", "min": 0.2, "max": 0.8, "default": 0.4, "doc": "frame width (x)"}, + {"name": "height", "type": "number", "min": 0.15, "max": 0.6, "default": 0.3, "doc": "frame height (y)"}, + {"name": "depth", "type": "number", "min": 0.04, "max": 0.15, "default": 0.08, "doc": "frame depth (z)"}, + {"name": "slats", "type": "integer", "min": 2, "max": 16, "default": 6, "doc": "louvre slats"}, + {"name": "slat_t", "type": "number", "min": 0.003, "max": 0.01, "default": 0.005, "doc": "slat thickness"}, + {"name": "tilt", "type": "number", "min": 0.0, "max": 60.0, "default": 35.0, "doc": "slat tilt in degrees; 0 is edge-on, fully open"} + ], + "bevel": "0.25*slat_t", + "shapes": [ + {"shape": "box", "size": ["width-0.048*min(width,height)", "height-0.048*min(width,height)", "0.12*depth"], "at": [0, 0, "0.06*depth"]}, + {"shape": "repeat", "count": 2, "step": ["width-0.08*min(width,height)", 0, 0], "of": + {"shape": "box", "size": ["0.08*min(width,height)", "height", "0.95*depth"], "at": ["-(width-0.08*min(width,height))/2", 0, "0.525*depth"]}}, + {"shape": "repeat", "count": 2, "step": [0, "height-0.08*min(width,height)", 0], "of": + {"shape": "box", "size": ["width-0.16*min(width,height)", "0.08*min(width,height)", "0.95*depth"], "at": [0, "-(height-0.08*min(width,height))/2", "0.525*depth"]}}, + {"shape": "repeat", "count": "slats", "step": [0, "(height-0.16*min(width,height))/slats", 0], "of": + {"shape": "box", "size": ["width-0.12*min(width,height)", "slat_t", "min(0.62*depth,1.1*(height-0.16*min(width,height))/slats)"], "rot": ["tilt", 0, 0], + "at": [0, "-(height-0.16*min(width,height))/2+0.5*(height-0.16*min(width,height))/slats", "0.56*depth"]}} + ], + "sockets": [ + {"name": "back", "type": "mount", "size": "0.9*min(width,height)", "at": [0, 0, 0], "z": "-z", "y": "+y"} + ] + }, + { + "name": "plate", + "doc": "Cover plate: a bolted rim around a raised panel; mounts on its back and carries a part on its front.", + "params": [ + {"name": "width", "type": "number", "min": 0.1, "max": 1.0, "default": 0.4, "doc": "x size"}, + {"name": "height", "type": "number", "min": 0.1, "max": 1.0, "default": 0.3, "doc": "y size"}, + {"name": "thickness", "type": "number", "min": 0.005, "max": 0.05, "default": 0.015, "doc": "back face to panel face (z)"} + ], + "bevel": "0.1*thickness", + "shapes": [ + {"shape": "box", "size": ["width", "height", "0.7*thickness"], "at": [0, 0, "0.35*thickness"]}, + {"shape": "box", "size": ["width-0.24*min(width,height)", "height-0.24*min(width,height)", "0.7*thickness"], "at": [0, 0, "0.65*thickness"]}, + {"shape": "repeat", "count": 2, "step": ["width-0.12*min(width,height)", 0, 0], "of": + {"shape": "tube", "r0": "0.036*min(width,height)", "r1": "0.036*min(width,height)", "length": "0.6*thickness", "segments": 6, + "at": ["-(width-0.12*min(width,height))/2", "-(height-0.12*min(width,height))/2", "0.35*thickness"]}}, + {"shape": "repeat", "count": 2, "step": ["width-0.12*min(width,height)", 0, 0], "of": + {"shape": "tube", "r0": "0.036*min(width,height)", "r1": "0.036*min(width,height)", "length": "0.6*thickness", "segments": 6, + "at": ["-(width-0.12*min(width,height))/2", "(height-0.12*min(width,height))/2", "0.35*thickness"]}} + ], + "sockets": [ + {"name": "back", "type": "mount", "size": "min(width,height)", "at": [0, 0, 0], "z": "-z", "y": "+y"}, + {"name": "front", "type": "mount", "size": "0.76*min(width,height)", "at": [0, 0, "thickness"], "z": "+z", "y": "+y"} + ] + } + ] +} diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py new file mode 100644 index 0000000..7ab51e5 --- /dev/null +++ b/surfaces/blender/tests/live/kitbash.py @@ -0,0 +1,210 @@ +"""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 nine parts, setObjectTransform, +assignMaterial, set_params, report, the refusals, and exportGltf. Not part of the unittest run: it needs Blender. + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash.py -- + +Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses +without them). Writes .result.json and exits 1 when a check failed. +""" +import importlib.util +import json +import math +import os +import sys +import tempfile +import types +from pathlib import Path + +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] +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 tests load it: what each placed mesh is compared against +spec.loader.exec_module(core) + +sys.path.append(str(SURFACE)) +bpy.ops.wm.read_factory_settings(use_empty=True) +for module in ("brokkr_mesh_polish", "brokkr_kitbash"): + addon_utils.enable(module, default_set=True) +target = bt.BrokkrBlenderTarget(bpy) +WORK = Path(tempfile.mkdtemp(prefix="brokkr-kitbash-live-")) +target.configure_action_dirs("", str(WORK)) +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] + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail}) # what was seen, when it was not what was promised + + +def 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"])[:300], flush=True) + return receipt, result + + +def extent(obj, axis=2): + co = np.array([v.co[:] for v in obj.data.vertices]) + return float(co[:, axis].max() - co[:, axis].min()) + + +check("the four kitbash rows load as host actions with no errors", not R["hostErrors"] + and [r for r in R["hostRows"] if r.startswith("brokkr_kitbash.")] == ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", + "brokkr_kitbash.describe", "brokkr_kitbash.report"], [R["hostErrors"], R["hostRows"]]) + +# --- describe --------------------------------------------------------------------------------------------------------- +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 nine parts, whole, inside a receipt", receipt["status"] == "accepted" and names == list(kit["parts"]) and len(names) == 9 + 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"] + and [p["name"] for p in one["parts"][0]["params"]] == ["body_r", "body_len", "rod_r", "extension", "segments"] + and one["parts"][0]["sockets"] == core.socket_rows(core.build(kit["parts"]["actuator"]).sockets), one) +check("describe changes nothing", len(bpy.data.objects) == 0 and len(bpy.data.meshes) == 0, [len(bpy.data.objects), len(bpy.data.meshes)]) + +# --- place every part at default ----------------------------------------------------------------------------------------- +placed = {} +for index, name in enumerate(names): + receipt, report = send("brokkr_kitbash.place_part", part=name, object_name=f"P_{name}") + obj = bpy.data.objects.get(f"P_{name}") + reference = core.build(kit["parts"][name]) + faces = len(obj.data.polygons) if obj else -1 + clean = obj is not None and not obj.data.validate(verbose=False) + flat = np.zeros(max(faces, 0), dtype=bool) + if obj: + obj.data.attributes["sharp_face"].data.foreach_get("value", flat) + bevel = obj.modifiers.get("Kit Bevel") if obj else None + evaluated = len(obj.evaluated_get(bpy.context.evaluated_depsgraph_get()).data.polygons) if obj else -1 + placed[name] = report + check(f"place_part {name}: core's faces, a valid mesh, core's flat faces, at the origin", receipt["status"] == "accepted" and report + and faces == len(reference.counts) == report["faces"] and clean and report["shells"] == reference.shell_count + and flat.tolist() == (~reference.smooth).tolist() and list(obj.location) == [0.0, 0.0, 0.0] + and np.allclose(np.array([v.co[:] for v in obj.data.vertices]), reference.V, atol=1e-6), + [receipt["message"], faces, len(reference.counts), clean]) + check(f"place_part {name}: a Bevel of the part's width, 2 segments, angle 30, that evaluates", bevel is not None + and abs(bevel.width - reference.bevel) < 1e-7 and bevel.segments == 2 and bevel.limit_method == "ANGLE" + and abs(bevel.angle_limit - math.radians(30)) < 1e-6 and evaluated > faces, [bevel and bevel.width, reference.bevel, evaluated, faces]) + 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("nine parts are nine mesh objects", len(bpy.data.objects) == 9 and all(o.type == "MESH" for o in bpy.data.objects), len(bpy.data.objects)) + +# --- set_params keeps what is not derived -------------------------------------------------------------------------------- +tank = bpy.data.objects["P_tank"] +send("setObjectTransform", targetObjectName="P_tank", location=[1.0, 2.0, 3.0], rotationEuler=[0.3, -0.2, 0.5], scale=[1.0, 1.0, 1.0]) +send("assignMaterial", targetObjectName="P_tank", materialName="Tank Paint", color=[0.35, 0.35, 0.35]) +send("setObjectParent", targetObjectName="P_tank", parentObjectName="P_plate") +before = {"z": extent(tank), "mesh": tank.data.name, "basis": [list(r) for r in tank.matrix_basis], "parent": tank.parent and tank.parent.name, + "materials": [s.material and s.material.name for s in tank.material_slots], "modifiers": [m.name for m in tank.modifiers], + "faces": len(tank.data.polygons)} +receipt, grown = send("brokkr_kitbash.set_params", object_name="P_tank", params="length=1.8") +after = {"z": extent(tank), "mesh": tank.data.name, "basis": [list(r) for r in tank.matrix_basis], "parent": tank.parent and tank.parent.name, + "materials": [s.material and s.material.name for s in tank.material_slots], "modifiers": [m.name for m in tank.modifiers], + "faces": len(tank.data.polygons)} +check("set_params doubling the tank's length doubles its z extent", receipt["status"] == "accepted" and abs(before["z"] - 0.9) < 1e-6 + and abs(after["z"] - 1.8) < 1e-6, [before["z"], after["z"]]) +check("set_params keeps the mesh datablock, transform, parent, Bevel and the assigned material", before["parent"] == "P_plate" + and before["materials"] == ["Tank Paint"] and before["modifiers"] == ["Kit Bevel"] + and {k: v for k, v in after.items() if k != "z"} == {k: v for k, v in before.items() if k != "z"} and not tank.data.validate(verbose=False), [before, after]) +check("set_params stores the merged params and reports them", grown and json.loads(tank["kit_params"]) == grown["params"] + == {"radius": 0.22, "length": 1.8, "segments": 24}, grown) +receipt, wide = send("brokkr_kitbash.set_params", object_name="P_tank", params="radius=0.3; segments=12") +check("set_params overlays the stored params, and the Bevel width follows the part's bevel", wide and wide["params"] == {"radius": 0.3, "length": 1.8, "segments": 12} + and abs(tank.modifiers["Kit Bevel"].width - 0.008 * 0.3) < 1e-7 and len(tank.data.polygons) == len(core.build(kit["parts"]["tank"], wide["params"]).counts), + [wide and wide["params"], tank.modifiers["Kit Bevel"].width]) + +# --- report: sockets in the world ------------------------------------------------------------------------------------------- +send("setObjectTransform", targetObjectName="P_pipe_fitting", location=[-2.0, 0.5, 1.0], rotationEuler=[1.1, 0.4, -0.7]) +bpy.context.view_layer.update() +receipt, reported = send("brokkr_kitbash.report") +worst, listed = 0.0, [] +for entry in (reported or {}).get("parts", []): + obj = bpy.data.objects[entry["object"]] + listed.append(entry["object"]) + local = core.build(core.part(kit, entry["part"]), entry["params"]).sockets + world = np.array(obj.matrix_world) + for socket, mine in zip(entry["sockets"], local): + worst = max(worst, float(np.abs(np.array(socket["matrix"]) - world @ mine["matrix"]).max())) +check("report lists every kit part with socket frames equal to matrix_world times the local frame", receipt["status"] == "accepted" + and listed == sorted(f"P_{n}" for n in names) and worst < 1e-6, [listed, worst]) +receipt, single = send("brokkr_kitbash.report", object_name="P_tank") +tank_world = np.array(tank.matrix_world) +check("report of the parented, rotated tank carries its parent's and its own transform", single and len(single["parts"]) == 1 + and single["parts"][0]["params"] == wide["params"] and single["parts"][0]["faces"] == len(tank.data.polygons) + and np.abs(np.array(single["parts"][0]["sockets"][2]["matrix"]) - tank_world @ core.build(kit["parts"]["tank"], wide["params"]).sockets[2]["matrix"]).max() < 1e-6 + and np.abs(tank_world[:3, 3] - [1.0, 2.0, 3.0]).max() < 1e-6, single) + +# --- refusals leave the scene as it was -------------------------------------------------------------------------------------- +bpy.ops.mesh.primitive_cube_add() +bpy.context.active_object.name = "Plain" + + +def scene_state(): + return (sorted(o.name for o in bpy.data.objects), sorted(m.name for m in bpy.data.meshes), + {o.name: (len(o.data.polygons), o.get("kit_params")) for o in bpy.data.objects}) + + +state = scene_state() +refusals = [ + ("an unknown kit", "brokkr_kitbash.place_part", {"kit": "hydraulic", "part": "tank", "object_name": "X"}, "no kit named 'hydraulic'"), + ("a kit name that spells a path", "brokkr_kitbash.place_part", {"kit": "../x", "part": "tank", "object_name": "X"}, "kit"), + ("a kit name with a dot", "brokkr_kitbash.place_part", {"kit": "mechanical.v0", "part": "tank", "object_name": "X"}, "must be 1 to 32 of"), + ("an unknown part", "brokkr_kitbash.place_part", {"part": "wing", "object_name": "X"}, "has no part 'wing'"), + ("an out-of-range param", "brokkr_kitbash.place_part", {"part": "tank", "object_name": "X", "params": "radius=5"}, "param 'radius' = 5.0 is outside [0.12, 0.35]"), + ("a fraction for an integer param", "brokkr_kitbash.place_part", {"part": "tank", "object_name": "X", "params": "segments=12.5"}, "is an integer"), + ("an existing name", "brokkr_kitbash.place_part", {"part": "tank", "object_name": "P_plate"}, "An object named 'P_plate' exists"), + ("set_params on a plain mesh", "brokkr_kitbash.set_params", {"object_name": "Plain", "params": "length=1"}, "is not a kit part"), + ("set_params with an unknown param", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "girth=1"}, "has no param 'girth'"), + ("set_params out of range", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "length=0.1"}, "is outside [0.6, 2.0]"), + ("set_params with a repeated key", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "length=1; length=1.2"}, "'length' is given twice"), + ("report of a plain mesh", "brokkr_kitbash.report", {"object_name": "Plain"}, "is not a kit part"), + ("describe of an unknown part", "brokkr_kitbash.describe", {"part": "wing"}, "has no part 'wing'"), +] +for label, action, fields, expected in refusals: + receipt, _ = send(action, **fields) + check(f"refused, scene unchanged: {label}", receipt["status"] != "accepted" and expected in str(receipt["message"]) and scene_state() == state, + [receipt["status"], receipt["message"]]) + +# --- export --------------------------------------------------------------------------------------------------------------- +receipt, _ = send("exportGltf", filepath="kit.glb", extras=False, yUp=True, applyModifiers=True, selection=[f"P_{n}" for n in names]) +glb = WORK / "kit.glb" +meshes = -1 +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 nine parts succeeds", receipt["status"] == "accepted" and meshes == 9, [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} +R["ok"] = all(c["ok"] for c in R["checks"]) +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) +sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/kitbash.result.json b/surfaces/blender/tests/live/kitbash.result.json new file mode 100644 index 0000000..2097f87 --- /dev/null +++ b/surfaces/blender/tests/live/kitbash.result.json @@ -0,0 +1,362 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "the four kitbash rows load as host actions with no errors", + "ok": true, + "detail": null + }, + { + "name": "describe lists nine parts, whole, inside a receipt", + "ok": true, + "detail": null + }, + { + "name": "describe of one part gives its params and its sockets at default params", + "ok": true, + "detail": null + }, + { + "name": "describe changes nothing", + "ok": true, + "detail": null + }, + { + "name": "place_part nozzle: core's faces, a valid mesh, core's flat faces, at the origin", + "ok": true, + "detail": null + }, + { + "name": "place_part nozzle: a Bevel of the part's width, 2 segments, angle 30, that evaluates", + "ok": true, + "detail": null + }, + { + "name": "place_part nozzle: kit, part and every resolved param stored on the object, sockets reported in the part frame", + "ok": true, + "detail": null + }, + { + "name": "place_part tank: core's faces, a valid mesh, core's flat faces, at the origin", + "ok": true, + "detail": null + }, + { + "name": "place_part tank: a Bevel of the part's width, 2 segments, angle 30, that evaluates", + "ok": true, + "detail": null + }, + { + "name": "place_part tank: kit, part and every resolved param stored on the object, sockets reported in the part frame", + "ok": true, + "detail": null + }, + { + "name": "place_part ribbed_cylinder: core's faces, a valid mesh, core's flat faces, at the origin", + "ok": true, + "detail": null + }, + { + "name": "place_part ribbed_cylinder: a Bevel of the part's width, 2 segments, angle 30, that evaluates", + "ok": true, + "detail": null + }, + { + "name": "place_part ribbed_cylinder: kit, part and every resolved param stored on the object, sockets reported in the part frame", + "ok": true, + "detail": null + }, + { + "name": "place_part strut: core's faces, a valid mesh, core's flat faces, at the origin", + "ok": true, + "detail": null + }, + { + "name": "place_part strut: a Bevel of the part's width, 2 segments, angle 30, that evaluates", + "ok": true, + "detail": null + }, + { + "name": "place_part strut: kit, part and every resolved param stored on the object, sockets reported in the part frame", + "ok": true, + "detail": null + }, + { + "name": "place_part actuator: core's faces, a valid mesh, core's flat faces, at the origin", + "ok": true, + "detail": null + }, + { + "name": "place_part actuator: a Bevel of the part's width, 2 segments, angle 30, that evaluates", + "ok": true, + "detail": null + }, + { + "name": "place_part actuator: 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: core's faces, a valid mesh, core's flat faces, at the origin", + "ok": true, + "detail": null + }, + { + "name": "place_part pipe_fitting: a Bevel of the part's width, 2 segments, angle 30, that evaluates", + "ok": true, + "detail": null + }, + { + "name": "place_part pipe_fitting: kit, part and every resolved param stored on the object, sockets reported in the part frame", + "ok": true, + "detail": null + }, + { + "name": "place_part radiator_stack: core's faces, a valid mesh, core's flat faces, at the origin", + "ok": true, + "detail": null + }, + { + "name": "place_part radiator_stack: a Bevel of the part's width, 2 segments, angle 30, that evaluates", + "ok": true, + "detail": null + }, + { + "name": "place_part radiator_stack: kit, part and every resolved param stored on the object, sockets reported in the part frame", + "ok": true, + "detail": null + }, + { + "name": "place_part vent: core's faces, a valid mesh, core's flat faces, at the origin", + "ok": true, + "detail": null + }, + { + "name": "place_part vent: a Bevel of the part's width, 2 segments, angle 30, that evaluates", + "ok": true, + "detail": null + }, + { + "name": "place_part vent: kit, part and every resolved param stored on the object, sockets reported in the part frame", + "ok": true, + "detail": null + }, + { + "name": "place_part plate: core's faces, a valid mesh, core's flat faces, at the origin", + "ok": true, + "detail": null + }, + { + "name": "place_part plate: a Bevel of the part's width, 2 segments, angle 30, that evaluates", + "ok": true, + "detail": null + }, + { + "name": "place_part plate: kit, part and every resolved param stored on the object, sockets reported in the part frame", + "ok": true, + "detail": null + }, + { + "name": "nine parts are nine mesh objects", + "ok": true, + "detail": null + }, + { + "name": "set_params doubling the tank's length doubles its z extent", + "ok": true, + "detail": null + }, + { + "name": "set_params keeps the mesh datablock, transform, parent, Bevel and the assigned material", + "ok": true, + "detail": null + }, + { + "name": "set_params stores the merged params and reports them", + "ok": true, + "detail": null + }, + { + "name": "set_params overlays the stored params, and the Bevel width follows the part's bevel", + "ok": true, + "detail": null + }, + { + "name": "report lists every kit part with socket frames equal to matrix_world times the local frame", + "ok": true, + "detail": null + }, + { + "name": "report of the parented, rotated tank carries its parent's and its own transform", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: an unknown kit", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a kit name that spells a path", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a kit name with a dot", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: an unknown part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: an out-of-range param", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a fraction for an integer param", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: an existing name", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on a plain mesh", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params with an unknown param", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params out of range", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params with a repeated key", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: report of a plain mesh", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: describe of an unknown part", + "ok": true, + "detail": null + }, + { + "name": "exportGltf of all nine parts succeeds", + "ok": true, + "detail": null + } + ], + "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_kitbash.place_part", + "brokkr_kitbash.set_params", + "brokkr_kitbash.describe", + "brokkr_kitbash.report" + ], + "placed": { + "nozzle": { + "faces": 1024, + "shells": 21, + "bevel": 0.0024, + "sockets": [ + "mount" + ] + }, + "tank": { + "faces": 636, + "shells": 16, + "bevel": 0.00176, + "sockets": [ + "port_a", + "port_b", + "saddle" + ] + }, + "ribbed_cylinder": { + "faces": 376, + "shells": 18, + "bevel": 0.00225, + "sockets": [ + "end_a", + "end_b" + ] + }, + "strut": { + "faces": 100, + "shells": 10, + "bevel": 0.0015, + "sockets": [ + "end_a", + "end_b" + ] + }, + "actuator": { + "faces": 238, + "shells": 15, + "bevel": 0.0024, + "sockets": [ + "base", + "rod_end" + ] + }, + "pipe_fitting": { + "faces": 278, + "shells": 19, + "bevel": 0.0027, + "sockets": [ + "a", + "b", + "c" + ] + }, + "radiator_stack": { + "faces": 142, + "shells": 17, + "bevel": 0.001, + "sockets": [ + "base" + ] + }, + "vent": { + "faces": 66, + "shells": 11, + "bevel": 0.00125, + "sockets": [ + "back" + ] + }, + "plate": { + "faces": 44, + "shells": 6, + "bevel": 0.0015, + "sockets": [ + "back", + "front" + ] + } + }, + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py new file mode 100644 index 0000000..c0b0bcd --- /dev/null +++ b/surfaces/blender/tests/test_kitbash.py @@ -0,0 +1,413 @@ +"""Kitbash tests. No Blender: the kit format and geometry in brokkr_kitbash/core.py, the mechanical kit at every +corner of its params, and the host action file against Brokkr's own checker. + +Run: python3 -m unittest discover -s surfaces/blender/tests -v (needs numpy; skipped without it) +The operators are exercised in a real Blender by tests/live/kitbash.py. + +Bounds follow lodur:ruling:deterministic-bound-margin: a deterministic reading is exact here, so each assertion is +the built value, and each names the mutant it kills. +""" +from __future__ import annotations + +import copy +import importlib.util +import json +import math +import random +import re +import sys +import types +import unittest +from collections import Counter +from pathlib import Path + +SURFACE = Path(__file__).resolve().parents[1] +package = types.ModuleType("brokkr_bridge") +package.__path__ = [str(SURFACE / "brokkr_bridge")] +sys.modules.setdefault("brokkr_bridge", package) +from brokkr_bridge import action_table as at # noqa: E402 + +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_core", SURFACE / "brokkr_kitbash" / "core.py") + core = importlib.util.module_from_spec(spec) + spec.loader.exec_module(core) + + +def param(name, low=0.0, high=10.0, default=1.0, kind="number"): + return {"name": name, "type": kind, "min": low, "max": high, "default": default, "doc": ""} + + +def document(shapes=None, params=(), sockets=(), **extra): + """A kit of one part 'p'.""" + part = {"name": "p", "doc": "", "params": list(params), "shapes": shapes or [{"shape": "box", "size": [1, 1, 1]}], + "sockets": list(sockets), **extra} + return {"schema": "brokkr.kit.v0", "kit": "t", "doc": "", "socketTypes": {"mount": {"match": "fits", "doc": ""}}, "parts": [part]} + + +def built(shapes, params=(), given=None): + return core.build(core.part(core.check_kit(document(shapes, params)), "p"), given or {}) + + +def faces_of(b): + start = 0 + for count in b.counts: + yield b.faces[start:start + count] + start += count + + +def closed_and_oriented(b) -> bool: + """Every directed edge exactly once, with its reverse exactly once.""" + edges = Counter() + for face in faces_of(b): + for i in range(len(face)): + edges[(int(face[i]), int(face[(i + 1) % len(face)]))] += 1 + return all(n == 1 and edges.get((v, u)) == 1 for (u, v), n in edges.items()) + + +def signed_volume(b) -> float: + total = 0.0 + for face in faces_of(b): + p = b.V[face] + for i in range(1, len(face) - 1): + total += float(np.dot(p[0], np.cross(p[i], p[i + 1]))) / 6.0 + return total + + +def frustum(r0, r1, h, n) -> float: + a0, a1 = (0.5 * n * r * r * math.sin(2 * math.pi / n) for r in (r0, r1)) + return h / 3.0 * (a0 + a1 + math.sqrt(a0 * a1)) + + +def point_triangle(p, a, b, c) -> float: + """Distance from p to triangle abc (Ericson, Real-Time Collision Detection 5.1.5).""" + ab, ac, ap = b - a, c - a, p - a + d1, d2 = ab @ ap, ac @ ap + if d1 <= 0 and d2 <= 0: + return float(np.linalg.norm(ap)) + bp = p - b + d3, d4 = ab @ bp, ac @ bp + if d3 >= 0 and d4 <= d3: + return float(np.linalg.norm(bp)) + vc = d1 * d4 - d3 * d2 + if vc <= 0 and d1 >= 0 and d3 <= 0: + return float(np.linalg.norm(ap - ab * (d1 / (d1 - d3)))) + cp = p - c + d5, d6 = ab @ cp, ac @ cp + if d6 >= 0 and d5 <= d6: + return float(np.linalg.norm(cp)) + vb = d5 * d2 - d1 * d6 + if vb <= 0 and d2 >= 0 and d6 <= 0: + return float(np.linalg.norm(ap - ac * (d2 / (d2 - d6)))) + va = d3 * d6 - d5 * d4 + if va <= 0 and d4 - d3 >= 0 and d5 - d6 >= 0: + return float(np.linalg.norm(bp - (c - b) * ((d4 - d3) / ((d4 - d3) + (d5 - d6))))) + normal = np.cross(ab, ac) + return float(abs(ap @ normal) / np.linalg.norm(normal)) + + +def socket_seat(b, socket) -> float: + """Distance from the socket's origin to the nearest face whose normal is the socket's z (inf when none faces it).""" + origin, z = socket["matrix"][:3, 3], socket["matrix"][:3, 2] + best = math.inf + for face in faces_of(b): + p = b.V[face] + normal = np.cross(p[1] - p[0], p[2] - p[0]) + normal /= np.linalg.norm(normal) + if np.abs(normal - z).max() > 1e-6: + continue + best = min([best] + [point_triangle(origin, p[0], p[i], p[i + 1]) for i in range(1, len(face) - 1)]) + return best + + +@unittest.skipIf(np is None, "numpy is not installed") +class ExpressionTests(unittest.TestCase): + def test_the_whitelist_evaluates_exactly_and_refuses_the_rest(self): + """expr-whitelist. Mutant M1 (drop the call-name check): pow(a,b) is admitted (abs(a) still dies on its one + argument, so the two-argument call is the witness).""" + env = {"a": 1.5, "b": 0.25} + self.assertEqual(core.parse("2*(a+b)-min(a,3)/4", env, "t").value(env), 2 * (1.5 + 0.25) - 1.5 / 4) + self.assertEqual(core.parse("-a+max(b,-2)", env, "t").value(env), -1.25) + self.assertEqual(core.parse("+a", env, "t").value(env), 1.5) + self.assertEqual(core.parse(3, env, "t").value(env), 3.0) + for text in ("a.real", "a[0]", "a**2", "a Date: Tue, 1 Dec 2026 14:48:03 +0100 Subject: [PATCH 59/63] docs: kitbash.md, the kit format by example, the four actions and a recipe Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 167 +++++++++++++++++++++++++++++++ 1 file changed, 167 insertions(+) create mode 100644 surfaces/blender/docs/kitbash.md diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md new file mode 100644 index 0000000..a893abf --- /dev/null +++ b/surfaces/blender/docs/kitbash.md @@ -0,0 +1,167 @@ +# Kitbash parts: machinery from kits + +`surfaces/blender/brokkr_kitbash` is a Blender add-on that places parametric machine parts from a **kit** and +reports where their **sockets** are. 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`. +Enable `brokkr_mesh_polish` first; `brokkr_kitbash` refuses to register without it. `brokkr_actions.json` beside +its `__init__.py` lists the four operators agents may run. Every action writes a JSON report to +`brokkr_mesh_polish_result`, returned in the receipt's `hostResult`. + +Who owns what: + +- `brokkr_kitbash/core.py` (numpy and the standard library, no Blender) owns the kit format: what a kit document + may say (`check_kit`), what a part's params may be (`resolve_params`), and the geometry and socket frames a part + and its params produce (`build`). There is no other validator of the format. +- `brokkr_kitbash/kits/.v0.json` own kit content. A kit is chosen by name (`a-z`, `0-9`, `_`, at most 32); + the name is the only thing an intent contributes to the path. +- In the scene, an object's `kit_kit`, `kit_part` and `kit_params` ID properties own what that part is. Its mesh is + derived from them: `set_params` rebuilds it, and an edit made to the mesh by hand is lost at the next + `set_params`. Socket frames are derived at every report and stored nowhere. + +This add-on places and re-parameterises parts. Mating sockets, booleans and baking are not here. + +## A part, end to end + +A kit document is `{schema: "brokkr.kit.v0", kit, doc, socketTypes, parts}`. One part of a kit, whole: + +```json +{ + "name": "standoff", + "doc": "A post on a square foot.", + "params": [ + {"name": "height", "type": "number", "min": 0.05, "max": 0.5, "default": 0.2, "doc": "foot face to top face"}, + {"name": "radius", "type": "number", "min": 0.01, "max": 0.05, "default": 0.02, "doc": "post radius"}, + {"name": "bolts", "type": "integer", "min": 1, "max": 4, "default": 2, "doc": "bolts along x"} + ], + "bevel": "0.1*radius", + "shapes": [ + {"shape": "box", "size": ["6*radius", "3*radius", "radius"], "at": [0, 0, "0.5*radius"]}, + {"shape": "tube", "r0": "radius", "r1": "0.8*radius", "length": "height-0.5*radius", "segments": 24, "smooth": true, + "at": [0, 0, "0.5*radius"]}, + {"shape": "repeat", "count": "bolts", "step": ["4*radius/max(bolts-1,1)", 0, 0], "of": + {"shape": "tube", "r0": "0.3*radius", "r1": "0.3*radius", "length": "0.4*radius", "segments": 6, + "at": ["-2*radius", 0, "0.9*radius"]}} + ], + "sockets": [ + {"name": "foot", "type": "mount", "size": "3*radius", "at": [0, 0, 0], "z": "-z", "y": "+y"}, + {"name": "top", "type": "mount", "size": "1.6*radius", "at": [0, 0, "height"], "z": "+z", "y": "+y"} + ] +} +``` + +Lengths are metres in the part's own frame. Unknown keys are refused at every level, and so is a repeated part, +param or socket name, a default outside `[min, max]`, and an integer param with a fractional bound or default. + +**Params** are `number` or `integer` with inclusive bounds. A param name is lower case (`a-z`, then `a-z`, `0-9`, +`_`) and is not `min` or `max`. + +**Shapes.** Each is one or more closed shells wound outward. `at` (metres) and `rot` (XYZ Euler degrees: about x, +then y, then z, about the shape's own origin) place it, rotation first; both default to zero. + +| shape | fields | what it is | +| --- | --- | --- | +| `tube` | `r0`, `r1`, `length`, `segments`, `inner0`?, `inner1`?, `smooth`? | A frustum on +z from radius `r0` at z=0 to `r1` at z=`length`, with n-gon caps. Inner radii above 0 make it hollow (an inner wall and two flat end rings); they are both above 0 or both 0, and below the outer radius. `segments` is 3 to 128. `smooth` shades the walls smooth; caps stay flat. | +| `box` | `size` | A box centred on its origin; every size above 0. | +| `repeat` | `count`, `step`, `of` | `count` copies (1 to 256) of one tube or box at `k * step`, k from 0. A repeat cannot hold a repeat. | + +Shells may overlap (a pad that runs into a tank), and a part is then not one solid: reports give the shell count. + +**`bevel`** is the width of a Bevel modifier `place_part` adds (2 segments, edges sharper than 30 degrees). Keep it +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 +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. + +## Expressions + +Every numeric field of a shape or socket, and `bevel`, is a number or a string over the part's params: + +```text ++ - * / unary minus ( ) min(a, b) max(a, b) numbers param names +``` + +An expression is parsed once and walked against that list when the kit is checked; an attribute, subscript, +power, comparison, any other call, a keyword argument, a lambda or a string is refused there, naming the part and +field. Nothing in a kit is run as Python. Division by zero and a `count` or `segments` that is not whole are +refused when the part is built, naming the expression. + +## 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: transform, parent, modifiers and material slots stay, and the Bevel width follows. | +| `brokkr_kitbash.report` | `object_name` (default: every kit part) | Each part as the scene has it: kit, part, params, faces, shells, and each socket's world frame. Changes nothing. | + +`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. + +A socket in a report is `{name, type, size, matrix}`: `matrix` is the 4x4 as four rows of 6 decimals, in world +space for `place_part`, `set_params` and `report`. Column 2 is the outward normal, column 1 up, column 3 the +origin. A report over 16000 characters (what a receipt carries) is refused with advice to name one part or +object. + +Placement, look and export are Brokkr's own rows: `setObjectTransform`, `assignMaterial`, `exportGltf`. +`place_part` has no location or colour fields. + +## A recipe + +`tools/run_intents.py` runs this in a background Blender (`install.md`, private user directories required): + +```json +{"requestedBy": "nibu/hands", "outputDir": "/work/out", "hostAddons": ["brokkr_mesh_polish", "brokkr_kitbash"], + "saveBlend": "/work/out/engine.blend", + "intents": [ + {"action": "brokkr_kitbash.describe", "part": "tank"}, + {"action": "brokkr_kitbash.place_part", "part": "tank", "object_name": "Tank", "params": "radius=0.3; length=1.4"}, + {"action": "setObjectTransform", "targetObjectName": "Tank", "location": [0, 0.6, 0], "rotationEuler": [1.5708, 0, 0]}, + {"action": "assignMaterial", "targetObjectName": "Tank", "materialName": "Machinery", "color": [0.35, 0.35, 0.35]}, + {"action": "brokkr_kitbash.place_part", "part": "nozzle", "object_name": "Nozzle"}, + {"action": "brokkr_kitbash.set_params", "object_name": "Nozzle", "params": "exit_r=0.32"}, + {"action": "brokkr_kitbash.report"}, + {"action": "exportGltf", "filepath": "engine.glb", "selection": ["Tank", "Nozzle"]} + ]} +``` + +The receipts file holds each report in `hostResult`. `tools/turntable_recipe.py` renders the saved `.blend`. + +## The mechanical kit + +`kits/mechanical.v0.json`: nine parts, each along +z, with socket types `flange` (equal), `mount` (fits) and +`pivot` (equal). + +| part | params | sockets | +| --- | --- | --- | +| `nozzle` | `throat_r`, `exit_r`, `length`, `wall`, `segments` | `mount` (flange) | +| `tank` | `radius`, `length`, `segments` | `port_a`, `port_b` (flange), `saddle` (mount) | +| `ribbed_cylinder` | `radius`, `length`, `ribs`, `rib_depth`, `rib_width`, `segments` | `end_a`, `end_b` (flange) | +| `strut` | `length`, `width`, `thickness`, `segments` | `end_a`, `end_b` (pivot) | +| `actuator` | `body_r`, `body_len`, `rod_r`, `extension`, `segments` | `base`, `rod_end` (pivot); `rod_end` moves with `extension` | +| `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) | +| `plate` | `width`, `height`, `thickness` | `back`, `front` (mount) | + +`describe` gives the bounds and docs. + +## Adding a part or a kit + +Edit the kit's JSON (or add `kits/.v0.json`, whose `kit` field is ``), then run the tests: + +```text +python -m unittest discover -s surfaces/blender/tests -p "test_kitbash.py" -v +``` + +`MechanicalKitTests` builds every part of `mechanical` at its default, all-minimum and all-maximum params and at +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_nine_parts_and_three_socket_types`. +The operators are exercised in a real Blender by `tests/live/kitbash.py`. From d952fb55e97ba3bd03b21f83e549aa35abfd039a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 15:21:36 +0100 Subject: [PATCH 60/63] brokkr_kitbash: one owner per part (shared mesh, scale), named refusals, materials by shape Fixes from verdict aetheria-release:verdict:cut-chassis-kit-format.s1. set_params refuses a mesh datablock another object uses: rebuilding it changed the linked duplicate while its kit_params stayed. set_params and report refuse a part whose world transform scales, mirrors or shears: a part's size is its params and a socket frame is a rotation and an origin. set_params carries per-face material_index by shape (Built.shape names each face's shape), so an assignment survives a change of segments or counts. Kit-side mistakes are KitErrors: an unhashable value where a name belongs, an integer no float holds, and vertices that overflow are refused by name. Tests pin the finite check, socket size, bevel sign and the hollow tube's inner radii (Soul's N4, N8, N9, N10). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 44 ++++++++++++- .../brokkr_kitbash/brokkr_actions.json | 4 +- surfaces/blender/brokkr_kitbash/core.py | 61 +++++++++++++------ surfaces/blender/docs/kitbash.md | 12 +++- surfaces/blender/tests/live/kitbash.py | 37 ++++++++++- .../blender/tests/live/kitbash.result.json | 53 ++++++++++++++-- surfaces/blender/tests/test_kitbash.py | 46 +++++++++++++- 7 files changed, 224 insertions(+), 33 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index ea1c2fd..eb004e0 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -8,7 +8,9 @@ WindowManager.brokkr_mesh_polish_result, as the polish operators do. What a placed part is lives on its object as three ID properties: kit_kit, kit_part and kit_params. The mesh is derived from them (set_params rebuilds it), and socket frames are derived again at every report: nothing else in -the scene stores them. Placement, materials and export are Brokkr's own rows (setObjectTransform, assignMaterial, +the scene stores them. Two things would give a part a second owner and are refused: a mesh datablock shared with +another object (set_params), and a world transform that scales, mirrors or shears (set_params and report: a +part's size is its params). Placement, materials and export are Brokkr's own rows (setObjectTransform, assignMaterial, exportGltf). """ bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0), @@ -66,10 +68,19 @@ def sync_bevel(obj, width: float) -> None: modifier.width = width +RIGID = 1e-5 # how far a world matrix's 3x3 may stand from a rotation + + def kit_part_of(obj): - """(part, stored params) of a placed part, read from its ID properties.""" + """(part, stored params) of a placed part, read from its ID properties. Refuses a part whose world transform is + not rigid: its socket frames would not be frames, and its size would have a second owner.""" if PART not in obj: raise Refused(f"{obj.name!r} is not a kit part (it has no {PART} property); place_part makes one.") + turn = np.array(obj.matrix_world)[:3, :3] + if np.abs(turn.T @ turn - np.eye(3)).max() > RIGID or np.linalg.det(turn) < 0: + scale = ", ".join(f"{s:.4g}" for s in obj.matrix_world.to_scale()) + raise Refused(f"{obj.name!r} is scaled, mirrored or sheared in the world (scale {scale}): a kit part's size is its params. " + "Set its scale, and its parents', to 1 (setObjectTransform) and resize it with set_params.") try: stored = json.loads(obj.get(PARAMS, "{}")) except ValueError: @@ -85,6 +96,22 @@ def part_report(obj, part, built) -> dict: "sockets": core.socket_rows(built.sockets, np.array(obj.matrix_world))} +def carried_materials(mesh, old, new): + """Per-face material indices for a rebuilt mesh, or None when there is nothing to carry: each shape of the part + keeps the index most of its faces had (the lowest on a tie), since faces do not survive a change of segments + or counts but shapes do. A mesh that is no longer the old build (edited by hand) carries nothing.""" + if old is None or len(mesh.polygons) != len(old.counts): + return None + index = np.zeros(len(old.counts), dtype=np.int32) + mesh.polygons.foreach_get("material_index", index) + if not index.any(): + return None + carried = np.zeros(len(new.counts), dtype=np.int32) + for shape in np.unique(old.shape): + carried[new.shape == shape] = np.bincount(index[old.shape == shape]).argmax() + return carried + + def bounded(report: dict, advice: str) -> dict: size = len(json.dumps(report, separators=(",", ":"))) if size > REPORT_LIMIT: @@ -119,7 +146,7 @@ class BROKKR_KITBASH_OT_place_part(PolishOperator): class BROKKR_KITBASH_OT_set_params(PolishOperator): """Change params of a placed kit part and rebuild its mesh in place: its transform, parent, modifiers and - material slots stay, and the Bevel width follows""" + material slots stay, each shape keeps its faces' material, and the Bevel width follows""" bl_idname = "brokkr_kitbash.set_params" bl_label = "Set Kit Part Params" object_name: bpy.props.StringProperty(name="Object") @@ -129,9 +156,20 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator): def work(self, context): obj = mesh_object(self.object_name) part, stored = kit_part_of(obj) + if obj.data.users > 1: + raise Refused(f"{obj.name!r} shares its mesh {obj.data.name!r} with {obj.data.users - 1} other user(s): rebuilding it would change " + "them while their params stay. Give it its own mesh (place_part a new part) and set that; nothing changed.") built = core.build(part, core.resolve_params(part, core.parse_params(self.params), stored)) + try: + old = core.build(part, stored) + except core.KitError: # stored params an edited kit no longer admits: nothing to map faces by + old = None + materials = carried_materials(obj.data, old, built) obj.data.clear_geometry() write_mesh(obj.data, built) + if materials is not None: + obj.data.polygons.foreach_set("material_index", materials) + obj.data.update() sync_bevel(obj, built.bevel) obj[PARAMS] = json.dumps(built.params) return part_report(obj, part, built) diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 41e010a..b570c13 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -45,7 +45,7 @@ }, { "name": "brokkr_kitbash.set_params", - "doc": "Change params of a placed kit part and rebuild its mesh in place; transform, parent, modifiers and materials stay. Reports as place_part.", + "doc": "Change params of a placed kit part and rebuild its mesh in place; transform, parent, modifiers and materials stay. Refuses 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 and each socket's world 4x4.", + "doc": "Placed kit parts as the scene has them: kit, part, params, faces, shells and each socket's world 4x4. Refuses a part scaled in the world: resize with set_params.", "changesScene": false, "editModeSafe": true, "result": "brokkr_mesh_polish_result", diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index 0d6b0c8..a9b0c6b 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -40,6 +40,16 @@ class KitError(ValueError): """The kit document, a param or a build breaks a rule of the format; the message names where.""" +def finite(value: Any) -> bool: + """A number (not a bool) a float can hold: an integer too large for one is not finite.""" + if isinstance(value, bool) or not isinstance(value, (int, float)): + return False + try: + return math.isfinite(float(value)) + except OverflowError: + return False + + # --- expressions --------------------------------------------------------------------------------------------- class Expr: @@ -50,8 +60,11 @@ class Expr: self.source, self.tree, self.where = source, tree, where def value(self, env: dict[str, float]) -> float: - result = self.source if self.tree is None else _walk(self.tree, env, self) - if not math.isfinite(result): + try: + result = self.source if self.tree is None else _walk(self.tree, env, self) + except OverflowError: # an integer literal no float holds + result = math.inf + if not finite(result): raise KitError(f"{self.where}: {self.source!r} is not a finite number") return float(result) @@ -60,8 +73,8 @@ def parse(value: Any, names, where: str) -> Expr: """The Expr for a numeric field: a finite number, or a string of + - * /, unary minus, parentheses, min(a,b), max(a,b), numbers and the names given. Anything else is refused here, before any build.""" if isinstance(value, (int, float)) and not isinstance(value, bool): - if not math.isfinite(value): - raise KitError(f"{where}: {value!r} is not a finite number") + if not finite(value): + raise KitError(f"{where}: {str(value)[:40]} is not a finite number") return Expr(value, None, where) if not isinstance(value, str): raise KitError(f"{where} must be a number or an expression string, not {type(value).__name__}") @@ -150,7 +163,7 @@ def _name(value: Any, where: str, seen: set) -> str: def _number(value: Any, where: str) -> float: - if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + if not finite(value): raise KitError(f"{where} must be a finite number") return value @@ -166,7 +179,7 @@ ZERO = [Expr(0.0, None, "zero")] * 3 def _shape(shape: Any, names, where: str, inside_repeat: bool = False) -> dict: kind = shape.get("shape") if isinstance(shape, dict) else None - if kind not in SHAPES: + if not isinstance(kind, str) or kind not in SHAPES: raise KitError(f"{where}: unknown shape {kind!r}; shapes are {', '.join(SHAPES)}") where = f"{where} ({kind})" required, optional = SHAPES[kind] @@ -248,10 +261,10 @@ def check_kit(document: Any) -> dict: s_name = _name(socket.get("name") if isinstance(socket, dict) else None, f"{where} socket {s_index}", socket_names) s_where = f"{where} socket {s_name!r}" _keys(socket, s_where, ("name", "type", "size", "at", "z", "y")) - if socket["type"] not in types: + if not isinstance(socket["type"], str) or socket["type"] not in types: raise KitError(f"{s_where}: type {socket['type']!r} is not one of the kit's socketTypes ({', '.join(types) or 'none'})") for key in ("z", "y"): - if socket[key] not in AXES: + if not isinstance(socket[key], str) or socket[key] not in AXES: raise KitError(f"{s_where}: {key} must be one of {', '.join(AXES)}") if socket["z"][1] == socket["y"][1]: raise KitError(f"{s_where}: z ({socket['z']}) and y ({socket['y']}) lie on the same axis") @@ -328,7 +341,7 @@ def resolve_params(part: dict, given: dict, base: dict | None = None) -> dict: for param in part["params"]: name = param["name"] value = merged.get(name, param["default"]) - if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + if not finite(value): raise KitError(f"{here} param {name!r} must be a finite number") if not param["min"] <= value <= param["max"]: raise KitError(f"{here} param {name!r} = {value} is outside [{param['min']}, {param['max']}] (bounds included)") @@ -344,13 +357,15 @@ def resolve_params(part: dict, given: dict, base: dict | None = None) -> dict: class Built(NamedTuple): """A part at given params, in the part's frame, metres. Face i has counts[i] corners, listed in order in - faces (quads and n-gon caps, wound outward); smooth[i] marks tube sides to shade smooth. Each socket is + faces (quads and n-gon caps, wound outward); smooth[i] marks tube sides to shade smooth; shape[i] is the index, + in the part's shapes list, of the shape the face belongs to (every copy of a repeat shares one). Each socket is {'name', 'type', 'size', 'matrix'} with matrix the 4x4 frame: column 2 the outward normal, column 1 up, column 0 = y cross z, column 3 the origin.""" V: np.ndarray faces: np.ndarray counts: np.ndarray smooth: np.ndarray + shape: np.ndarray shell_count: int sockets: list bevel: float @@ -427,15 +442,22 @@ def build(part: dict, params: dict | None = None) -> Built: """The part at these params (resolve_params fills and checks them). The same part and params give byte-identical arrays.""" env = resolve_params(part, params or {}) - shells = [] - for shape in part["shapes"]: - if shape["shape"] == "repeat": - count = _whole(shape["count"], env, COPIES) - step = np.array([e.value(env) for e in shape["step"]]) - V, faces, counts, smooth = _placed(shape["of"], env) - shells += [(V + k * step, faces, counts, smooth) for k in range(count)] - else: - shells.append(_placed(shape, env)) + here = f"kit {part['kit']!r} part {part['name']!r}" + shells, owner = [], [] + with np.errstate(over="ignore", invalid="ignore"): # a huge value is refused below, not warned about + for index, shape in enumerate(part["shapes"]): + if shape["shape"] == "repeat": + count = _whole(shape["count"], env, COPIES) + step = np.array([e.value(env) for e in shape["step"]]) + V, faces, counts, smooth = _placed(shape["of"], env) + made = [(V + k * step, faces, counts, smooth) for k in range(count)] + else: + made = [_placed(shape, env)] + for shell in made: + if not np.isfinite(shell[0]).all(): + raise KitError(f"{here} shape {index} ({shape['shape']}): its vertices are not finite at these params") + shells += made + owner += [index] * len(made) offsets = np.cumsum([0] + [len(s[0]) for s in shells[:-1]]) sockets = [] for socket in part["sockets"]: @@ -454,6 +476,7 @@ def build(part: dict, params: dict | None = None) -> Built: faces=np.concatenate([s[1] + o for s, o in zip(shells, offsets)]).astype(np.int32), counts=np.concatenate([s[2] for s in shells]).astype(np.int32), smooth=np.concatenate([s[3] for s in shells]).astype(bool), + shape=np.concatenate([np.full(len(s[2]), o) for s, o in zip(shells, owner)]).astype(np.int32), shell_count=len(shells), sockets=sockets, bevel=bevel, params=env) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index a893abf..8ce9c2c 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -19,6 +19,11 @@ Who owns what: - In the scene, an object's `kit_kit`, `kit_part` and `kit_params` ID properties own what that part is. Its mesh is derived from them: `set_params` rebuilds it, and an edit made to the mesh by hand is lost at the next `set_params`. Socket frames are derived at every report and stored nowhere. +- Two things would give a part a second owner, and are refused. `set_params` refuses an object whose mesh + datablock another object uses (a linked duplicate): rebuilding it would change the other while its params stay. + `set_params` and `report` refuse a part whose world transform scales, mirrors or shears, its parents' + 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`. This add-on places and re-parameterises parts. Mating sockets, booleans and baking are not here. @@ -88,8 +93,9 @@ Every numeric field of a shape or socket, and `bevel`, is a number or a string o An expression is parsed once and walked against that list when the kit is checked; an attribute, subscript, power, comparison, any other call, a keyword argument, a lambda or a string is refused there, naming the part and -field. Nothing in a kit is run as Python. Division by zero and a `count` or `segments` that is not whole are -refused when the part is built, naming the expression. +field. Nothing in a kit is run as Python. Division by zero, a result that is not a finite number, and a `count` +or `segments` that is not whole are refused when the part is built, naming the expression; so is a shape whose +vertices overflow. ## The actions @@ -97,7 +103,7 @@ refused when the part is built, naming the expression. | --- | --- | --- | | `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: transform, parent, modifiers and material slots stay, and the Bevel width follows. | +| `brokkr_kitbash.set_params` | `object_name`, `params` | Overlays `params` on the stored ones and rebuilds the mesh in the same datablock: transform, parent, 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. | | `brokkr_kitbash.report` | `object_name` (default: every kit part) | Each part as the scene has it: kit, part, params, faces, shells, and each socket's world frame. Changes nothing. | `params` is `name=value; name=value`; a param left out takes the part's default (`place_part`) or keeps its stored diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py index 7ab51e5..410cab3 100644 --- a/surfaces/blender/tests/live/kitbash.py +++ b/surfaces/blender/tests/live/kitbash.py @@ -142,8 +142,8 @@ check("set_params overlays the stored params, and the Bevel width follows the pa # --- report: sockets in the world ------------------------------------------------------------------------------------------- send("setObjectTransform", targetObjectName="P_pipe_fitting", location=[-2.0, 0.5, 1.0], rotationEuler=[1.1, 0.4, -0.7]) +receipt, reported = send("brokkr_kitbash.report") # straight after the move, before anything here updates the view layer: the frames are already the moved ones bpy.context.view_layer.update() -receipt, reported = send("brokkr_kitbash.report") worst, listed = 0.0, [] for entry in (reported or {}).get("parts", []): obj = bpy.data.objects[entry["object"]] @@ -161,9 +161,29 @@ check("report of the parented, rotated tank carries its parent's and its own tra and np.abs(np.array(single["parts"][0]["sockets"][2]["matrix"]) - tank_world @ core.build(kit["parts"]["tank"], wide["params"]).sockets[2]["matrix"]).max() < 1e-6 and np.abs(tank_world[:3, 3] - [1.0, 2.0, 3.0]).max() < 1e-6, single) +# --- per-face materials ride on the part's shapes ---------------------------------------------------------------------------- +strut = bpy.data.objects["P_strut"] +send("assignMaterial", targetObjectName="P_strut", materialName="Strut Paint", color=[0.35, 0.35, 0.35]) +strut.data.materials.append(bpy.data.materials.new("Pin Steel")) +PINS = 2 # the strut's third shape: the repeat of two pins +was = core.build(kit["parts"]["strut"]) +strut.data.polygons.foreach_set("material_index", np.where(was.shape == PINS, 1, 0).astype(np.int32)) +receipt, _ = send("brokkr_kitbash.set_params", object_name="P_strut", params="segments=12; length=1.2") +now = core.build(kit["parts"]["strut"], {"segments": 12, "length": 1.2}) +index = np.zeros(len(strut.data.polygons), dtype=np.int32) +strut.data.polygons.foreach_get("material_index", index) +check("set_params with other segments keeps each shape's material: the pins stay Pin Steel, the rest Strut Paint", receipt["status"] == "accepted" + and len(now.counts) != len(was.counts) and index.tolist() == np.where(now.shape == PINS, 1, 0).tolist() and int(index.sum()) == 2 * (12 + 2) + and [s.material.name for s in strut.material_slots] == ["Strut Paint", "Pin Steel"], [receipt["message"], int(index.sum()), len(index)]) + # --- refusals leave the scene as it was -------------------------------------------------------------------------------------- bpy.ops.mesh.primitive_cube_add() bpy.context.active_object.name = "Plain" +twin = bpy.data.objects["P_vent"].copy() # a linked duplicate: one mesh, two objects, each with its own kit_params +twin.name = "P_vent_twin" +bpy.context.scene.collection.objects.link(twin) +send("setObjectTransform", targetObjectName="P_radiator_stack", scale=[2.0, 2.0, 2.0]) +send("setObjectTransform", targetObjectName="P_actuator", scale=[-1.0, 1.0, 1.0]) def scene_state(): @@ -185,6 +205,12 @@ refusals = [ ("set_params out of range", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "length=0.1"}, "is outside [0.6, 2.0]"), ("set_params with a repeated key", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "length=1; length=1.2"}, "'length' is given twice"), ("report of a plain mesh", "brokkr_kitbash.report", {"object_name": "Plain"}, "is not a kit part"), + ("set_params on a mesh a linked duplicate shares", "brokkr_kitbash.set_params", {"object_name": "P_vent", "params": "slats=9"}, "shares its mesh 'P_vent' with 1 other user"), + ("set_params on the linked duplicate", "brokkr_kitbash.set_params", {"object_name": "P_vent_twin", "params": "slats=9"}, "shares its mesh 'P_vent' with 1 other user"), + ("report of a scaled part", "brokkr_kitbash.report", {"object_name": "P_radiator_stack"}, "'P_radiator_stack' is scaled, mirrored or sheared in the world (scale 2, 2, 2)"), + ("set_params on a scaled part", "brokkr_kitbash.set_params", {"object_name": "P_radiator_stack", "params": "fins=5"}, "is scaled, mirrored or sheared"), + ("report of a mirrored part", "brokkr_kitbash.report", {"object_name": "P_actuator"}, "'P_actuator' is scaled, mirrored or sheared"), + ("report of every part while one is scaled", "brokkr_kitbash.report", {}, "is scaled, mirrored or sheared"), ("describe of an unknown part", "brokkr_kitbash.describe", {"part": "wing"}, "has no part 'wing'"), ] for label, action, fields, expected in refusals: @@ -192,6 +218,15 @@ for label, action, fields, expected in refusals: check(f"refused, scene unchanged: {label}", receipt["status"] != "accepted" and expected in str(receipt["message"]) and scene_state() == state, [receipt["status"], receipt["message"]]) +bpy.data.objects.remove(twin) +send("setObjectTransform", targetObjectName="P_radiator_stack", scale=[1.0, 1.0, 1.0]) +send("setObjectTransform", targetObjectName="P_actuator", scale=[1.0, 1.0, 1.0]) +receipt, alone = send("brokkr_kitbash.set_params", object_name="P_vent", params="slats=9") +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"]) == 9, receipt["message"]) + # --- export --------------------------------------------------------------------------------------------------------------- receipt, _ = send("exportGltf", filepath="kit.glb", extras=False, yUp=True, applyModifiers=True, selection=[f"P_{n}" for n in names]) glb = WORK / "kit.glb" diff --git a/surfaces/blender/tests/live/kitbash.result.json b/surfaces/blender/tests/live/kitbash.result.json index 2097f87..ab893bc 100644 --- a/surfaces/blender/tests/live/kitbash.result.json +++ b/surfaces/blender/tests/live/kitbash.result.json @@ -191,6 +191,11 @@ "ok": true, "detail": null }, + { + "name": "set_params with other segments keeps each shape's material: the pins stay Pin Steel, the rest Strut Paint", + "ok": true, + "detail": null + }, { "name": "refused, scene unchanged: an unknown kit", "ok": true, @@ -251,11 +256,51 @@ "ok": true, "detail": null }, + { + "name": "refused, scene unchanged: set_params on a mesh a linked duplicate shares", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on the linked duplicate", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: report of a scaled part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on a scaled part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: report of a mirrored part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: report of every part while one is scaled", + "ok": true, + "detail": null + }, { "name": "refused, scene unchanged: describe of an unknown part", "ok": true, "detail": null }, + { + "name": "with the duplicate gone the vent's mesh is its own again and set_params rebuilds it", + "ok": true, + "detail": null + }, + { + "name": "with scale back at 1 every part reports again", + "ok": true, + "detail": null + }, { "name": "exportGltf of all nine parts succeeds", "ok": true, @@ -278,16 +323,16 @@ ], "placed": { "nozzle": { - "faces": 1024, - "shells": 21, + "faces": 1312, + "shells": 24, "bevel": 0.0024, "sockets": [ "mount" ] }, "tank": { - "faces": 636, - "shells": 16, + "faces": 740, + "shells": 20, "bevel": 0.00176, "sockets": [ "port_a", diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index c0b0bcd..5481efd 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -150,6 +150,34 @@ class ExpressionTests(unittest.TestCase): core.build(core.part(kit, "p")) self.assertEqual(float(np.ptp(core.build(core.part(kit, "p"), {"a": 3}).V[:, 0])), 0.5) + def test_a_value_no_float_holds_is_refused_by_name(self): + """Mutant N4 (finite check dropped in Expr.value): 1e308*a at a=10 is inf and is no longer refused there.""" + part = core.part(core.check_kit(document([{"shape": "box", "size": ["1e308*a", 1, "a*" + "9" * 400]}], [param("a", 0, 10, 0)])), "p") + with self.assertRaisesRegex(core.KitError, r"part 'p' shape 0 \(box\) size\[0\]: '1e308\*a' is not a finite number"): + core.build(part, {"a": 10}) + with self.assertRaisesRegex(core.KitError, r"size\[2\]: 'a\*9+' is not a finite number"): # an integer literal no float holds + core.build(part, {"a": 1e-300}) + for doc, message in ((document([{"shape": "box", "size": [10 ** 400, 1, 1]}]), r"size\[0\]: 1000\d+ is not a finite number"), + (document(params=[param("a", 0, 10 ** 400, 1)]), r"param 'a' max must be a finite number")): + with self.assertRaisesRegex(core.KitError, message): + core.check_kit(doc) + with self.assertRaisesRegex(core.KitError, r"param 'a' must be a finite number"): + core.resolve_params(part, {"a": 10 ** 400}) + far = core.part(core.check_kit(document([{"shape": "box", "size": [1, 1, 1]}, {"shape": "box", "size": [1e308, 1, 1], "at": [1.5e308, 0, 0]}])), "p") + with self.assertRaisesRegex(core.KitError, r"part 'p' shape 1 \(box\): its vertices are not finite"): # each number finite, their sum not + core.build(far) + + def test_a_socket_size_is_above_zero_and_a_bevel_is_not_negative(self): + """Mutants N8 (socket size <= 0 allowed) and N9 (negative bevel allowed).""" + socket = {"name": "s", "type": "mount", "size": "a-1", "at": [0, 0, 0], "z": "+z", "y": "+y"} + part = core.part(core.check_kit(document(params=[param("a")], sockets=[socket], bevel="2-a")), "p") + self.assertEqual((core.build(part, {"a": 2}).sockets[0]["size"], core.build(part, {"a": 2}).bevel), (1.0, 0.0)) + for a in (1.0, 0.5): + with self.assertRaisesRegex(core.KitError, r"part 'p' socket 's' size is -?0\.\d: a socket's size must be above 0"): + core.build(part, {"a": a}) + with self.assertRaisesRegex(core.KitError, r"part 'p' bevel is -1\.0: a bevel is 0 or more"): + core.build(part, {"a": 3}) + @unittest.skipIf(np is None, "numpy is not installed") class CheckKitTests(unittest.TestCase): @@ -175,6 +203,10 @@ class CheckKitTests(unittest.TestCase): (document([{**box, "size": ["width", 1, 1]}], [param("a")]), r"part 'p' shape 0 \(box\) size\[0\]: 'width' names 'width'"), (document(params=[param("min")]), r"part 'p' param 0: 'min' is not a name"), (document(bevel="a.b"), r"part 'p' bevel: 'a\.b' uses Attribute"), + (document(sockets=[{**socket, "type": ["mount"]}]), r"part 'p' socket 's': type \['mount'\] is not one of"), # unhashable where a name belongs + (document(sockets=[{**socket, "z": {}}]), r"part 'p' socket 's': z must be one of"), + (document([{"shape": ["box"], "size": [1, 1, 1]}]), r"part 'p' shape 0: unknown shape \['box'\]"), + (document(sockets=[{**socket, "at": [0, 0, 10 ** 400]}]), r"part 'p' socket 's' at\[2\]: 1000\d+ is not a finite number"), ] for doc, message in cases: with self.assertRaisesRegex(core.KitError, message): @@ -199,7 +231,8 @@ class CheckKitTests(unittest.TestCase): class ShapeTests(unittest.TestCase): def test_tubes_are_closed_oriented_and_hold_their_volume(self): """tube-closed-oriented. Mutants M3 (inner wall not reversed) and M4 (solid tube without its top cap) break - the edge census; M5 (r0 and r1 swapped) puts the z=0 ring at r1.""" + the edge census; M5 (r0 and r1 swapped) puts the z=0 ring at r1; N10 (inner0 and inner1 swapped) puts the + z=0 inner ring at inner1, which volume and the census cannot see.""" for n in (3, 32): solid = built([{"shape": "tube", "r0": 0.5, "r1": 0.3, "length": 2.0, "segments": n}]) hollow = built([{"shape": "tube", "r0": 0.5, "r1": 0.3, "inner0": 0.2, "inner1": 0.1, "length": 2.0, "segments": n, "smooth": True}]) @@ -211,6 +244,9 @@ class ShapeTests(unittest.TestCase): low = b.V[np.abs(b.V[:, 2]) < 1e-12] self.assertTrue(np.allclose(np.linalg.norm(low[:n, :2], axis=1), 0.5, atol=1e-12)) self.assertEqual(float(b.V[:, 2].max()), 2.0) + for rows_, radius, z in ((slice(2 * n, 3 * n), 0.2, 0.0), (slice(3 * n, 4 * n), 0.1, 2.0)): + self.assertTrue(np.allclose(np.linalg.norm(hollow.V[rows_, :2], axis=1), radius, atol=1e-12)) + self.assertTrue((hollow.V[rows_, 2] == z).all()) self.assertEqual(solid.smooth.tolist(), [False] * (n + 2)) self.assertEqual(hollow.smooth.tolist(), [True] * (2 * n) + [False] * (2 * n)) # both walls smooth, both end rings flat tube = {"shape": "tube", "r0": 1, "r1": 1, "length": 1, "segments": 8} @@ -246,6 +282,14 @@ class ShapeTests(unittest.TestCase): with self.assertRaisesRegex(core.KitError, "count is .*whole number from 1 to 256"): built([shape], [param("n", 0, 300, 4), param("a")], {"n": count}) + def test_every_face_names_its_shape(self): + """What set_params carries per-face materials by: a repeat's copies share their shape's index.""" + b = built([{"shape": "box", "size": [1, 1, 1]}, + {"shape": "repeat", "count": 3, "step": [2, 0, 0], "of": {"shape": "box", "size": [1, 1, 1]}}, + {"shape": "tube", "r0": 1, "r1": 1, "length": 1, "segments": 8}]) + self.assertEqual(b.shape.tolist(), [0] * 6 + [1] * 18 + [2] * 10) + self.assertEqual((b.shape.dtype, b.shell_count), (np.int32, 5)) + def test_sockets_are_right_handed_frames(self): socket = {"name": "s", "type": "mount", "size": "2*a", "at": ["a", 2, 3], "z": "+x", "y": "+z"} kit = core.check_kit(document(params=[param("a")], sockets=[socket])) From ee2f6af9e4b8b6dc602ed92017ffa0a8aa6f160c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 15:21:36 +0100 Subject: [PATCH 61/63] mechanical kit: an eight-frustum bell and four-frustum elliptical tank domes Softens the cone banding on the nozzle and the two-cone tank ends. Params and sockets are unchanged. Co-Authored-By: Claude Fable 5.2 --- .../brokkr_kitbash/kits/mechanical.v0.json | 48 +++++++++++-------- 1 file changed, 29 insertions(+), 19 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json b/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json index 41d2da7..a47db06 100644 --- a/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json +++ b/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json @@ -28,21 +28,27 @@ {"shape": "tube", "r0": "1.6*throat_r", "r1": "1.6*throat_r", "length": "1.75*throat_r", "segments": "segments", "smooth": true, "at": [0, 0, "0.15*throat_r"]}, {"shape": "tube", "r0": "1.6*throat_r", "r1": "throat_r+wall", "length": "throat_r", "segments": "segments", "smooth": true, "at": [0, 0, "1.9*throat_r"]}, {"shape": "tube", "r0": "1.78*throat_r", "r1": "1.78*throat_r", "length": "0.5*throat_r", "segments": "segments", "smooth": true, "at": [0, 0, "1.6*throat_r"]}, - {"shape": "tube", "r0": "throat_r+wall", "r1": "throat_r+wall+0.226*(exit_r-throat_r-wall)", "inner0": "throat_r", "inner1": "throat_r+0.226*(exit_r-throat_r-wall)", - "length": "0.12*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r"]}, - {"shape": "tube", "r0": "throat_r+wall+0.226*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.482*(exit_r-throat_r-wall)", "inner0": "throat_r+0.226*(exit_r-throat_r-wall)", "inner1": "throat_r+0.482*(exit_r-throat_r-wall)", - "length": "0.16*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.12*length"]}, - {"shape": "tube", "r0": "throat_r+wall+0.482*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.75*(exit_r-throat_r-wall)", "inner0": "throat_r+0.482*(exit_r-throat_r-wall)", "inner1": "throat_r+0.75*(exit_r-throat_r-wall)", - "length": "0.22*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.28*length"]}, - {"shape": "tube", "r0": "throat_r+wall+0.75*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.9375*(exit_r-throat_r-wall)", "inner0": "throat_r+0.75*(exit_r-throat_r-wall)", "inner1": "throat_r+0.9375*(exit_r-throat_r-wall)", - "length": "0.25*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.5*length"]}, - {"shape": "tube", "r0": "throat_r+wall+0.9375*(exit_r-throat_r-wall)", "r1": "exit_r", "inner0": "throat_r+0.9375*(exit_r-throat_r-wall)", "inner1": "exit_r-wall", - "length": "0.25*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.75*length"]}, - {"shape": "tube", "r0": "throat_r+2.4*wall+0.5795*(exit_r-throat_r-wall)", "r1": "throat_r+2.4*wall+0.616*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5*wall+0.5795*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5*wall+0.616*(exit_r-throat_r-wall)", - "length": "0.03*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.36*length"]}, - {"shape": "tube", "r0": "throat_r+2.4*wall+0.825*(exit_r-throat_r-wall)", "r1": "throat_r+2.4*wall+0.8475*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5*wall+0.825*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5*wall+0.8475*(exit_r-throat_r-wall)", + {"shape": "tube", "r0": "throat_r+wall", "r1": "throat_r+wall+0.1164*(exit_r-throat_r-wall)", "inner0": "throat_r", "inner1": "throat_r+0.1164*(exit_r-throat_r-wall)", + "length": "0.06*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r"]}, + {"shape": "tube", "r0": "throat_r+wall+0.1164*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.2604*(exit_r-throat_r-wall)", "inner0": "throat_r+0.1164*(exit_r-throat_r-wall)", "inner1": "throat_r+0.2604*(exit_r-throat_r-wall)", + "length": "0.08*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.06*length"]}, + {"shape": "tube", "r0": "throat_r+wall+0.2604*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.4224*(exit_r-throat_r-wall)", "inner0": "throat_r+0.2604*(exit_r-throat_r-wall)", "inner1": "throat_r+0.4224*(exit_r-throat_r-wall)", + "length": "0.1*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.14*length"]}, + {"shape": "tube", "r0": "throat_r+wall+0.4224*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.5904*(exit_r-throat_r-wall)", "inner0": "throat_r+0.4224*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5904*(exit_r-throat_r-wall)", + "length": "0.12*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.24*length"]}, + {"shape": "tube", "r0": "throat_r+wall+0.5904*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.75*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5904*(exit_r-throat_r-wall)", "inner1": "throat_r+0.75*(exit_r-throat_r-wall)", + "length": "0.14*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.36*length"]}, + {"shape": "tube", "r0": "throat_r+wall+0.75*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.8844*(exit_r-throat_r-wall)", "inner0": "throat_r+0.75*(exit_r-throat_r-wall)", "inner1": "throat_r+0.8844*(exit_r-throat_r-wall)", + "length": "0.16*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.5*length"]}, + {"shape": "tube", "r0": "throat_r+wall+0.8844*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.9676*(exit_r-throat_r-wall)", "inner0": "throat_r+0.8844*(exit_r-throat_r-wall)", "inner1": "throat_r+0.9676*(exit_r-throat_r-wall)", + "length": "0.16*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.66*length"]}, + {"shape": "tube", "r0": "throat_r+wall+0.9676*(exit_r-throat_r-wall)", "r1": "exit_r", "inner0": "throat_r+0.9676*(exit_r-throat_r-wall)", "inner1": "exit_r-wall", + "length": "0.18*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.82*length"]}, + {"shape": "tube", "r0": "throat_r+2.4*wall+0.6132*(exit_r-throat_r-wall)", "r1": "throat_r+2.4*wall+0.6474*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5*wall+0.6132*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5*wall+0.6474*(exit_r-throat_r-wall)", + "length": "0.03*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.38*length"]}, + {"shape": "tube", "r0": "throat_r+2.4*wall+0.834*(exit_r-throat_r-wall)", "r1": "throat_r+2.4*wall+0.8592*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5*wall+0.834*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5*wall+0.8592*(exit_r-throat_r-wall)", "length": "0.03*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.6*length"]}, - {"shape": "tube", "r0": "throat_r+2.4*wall+0.965*(exit_r-throat_r-wall)", "r1": "throat_r+2.4*wall+0.9725*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5*wall+0.965*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5*wall+0.9725*(exit_r-throat_r-wall)", + {"shape": "tube", "r0": "throat_r+2.4*wall+0.9748*(exit_r-throat_r-wall)", "r1": "throat_r+2.4*wall+0.9802*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5*wall+0.9748*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5*wall+0.9802*(exit_r-throat_r-wall)", "length": "0.03*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.86*length"]}, {"shape": "repeat", "count": 2, "step": ["3.4*throat_r", 0, 0], "of": {"shape": "box", "size": ["0.5*throat_r", "0.35*throat_r", "0.6*throat_r"], "at": ["-1.7*throat_r", 0, "throat_r"]}}, @@ -57,7 +63,7 @@ }, { "name": "tank", - "doc": "Pressure tank: domed ends with flanged ports, weld bands, two straps on saddle cradles and a mounting pad.", + "doc": "Pressure tank: elliptical domed ends with flanged ports, weld bands, two straps on saddle cradles and a mounting pad.", "params": [ {"name": "radius", "type": "number", "min": 0.12, "max": 0.35, "default": 0.22, "doc": "shell radius"}, {"name": "length", "type": "number", "min": 0.6, "max": 2.0, "default": 0.9, "doc": "port face to port face"}, @@ -67,11 +73,15 @@ "shapes": [ {"shape": "tube", "r0": "0.3*radius", "r1": "0.3*radius", "length": "0.05*radius", "segments": "segments", "smooth": true}, {"shape": "tube", "r0": "0.2*radius", "r1": "0.2*radius", "length": "0.18*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.02*radius"]}, - {"shape": "tube", "r0": "0.47*radius", "r1": "0.85*radius", "length": "0.15*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.12*radius"]}, - {"shape": "tube", "r0": "0.85*radius", "r1": "radius", "length": "0.22*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.27*radius"]}, + {"shape": "tube", "r0": "0.47*radius", "r1": "0.6984*radius", "length": "0.07*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.12*radius"]}, + {"shape": "tube", "r0": "0.6984*radius", "r1": "0.8512*radius", "length": "0.08*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.19*radius"]}, + {"shape": "tube", "r0": "0.8512*radius", "r1": "0.9581*radius", "length": "0.1*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.27*radius"]}, + {"shape": "tube", "r0": "0.9581*radius", "r1": "radius", "length": "0.12*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.37*radius"]}, {"shape": "tube", "r0": "radius", "r1": "radius", "length": "length-0.98*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.49*radius"]}, - {"shape": "tube", "r0": "radius", "r1": "0.85*radius", "length": "0.22*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.49*radius"]}, - {"shape": "tube", "r0": "0.85*radius", "r1": "0.47*radius", "length": "0.15*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.27*radius"]}, + {"shape": "tube", "r0": "radius", "r1": "0.9581*radius", "length": "0.12*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.49*radius"]}, + {"shape": "tube", "r0": "0.9581*radius", "r1": "0.8512*radius", "length": "0.1*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.37*radius"]}, + {"shape": "tube", "r0": "0.8512*radius", "r1": "0.6984*radius", "length": "0.08*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.27*radius"]}, + {"shape": "tube", "r0": "0.6984*radius", "r1": "0.47*radius", "length": "0.07*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.19*radius"]}, {"shape": "tube", "r0": "0.2*radius", "r1": "0.2*radius", "length": "0.18*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.2*radius"]}, {"shape": "tube", "r0": "0.3*radius", "r1": "0.3*radius", "length": "0.05*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.05*radius"]}, {"shape": "repeat", "count": 2, "step": [0, 0, "length-0.98*radius"], "of": From bd61f1cf1efb5fcf310bcc588821b59cfdea28b3 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 16:18:38 +0100 Subject: [PATCH 62/63] brokkr_kitbash: attach, detach, boolean and apply; set_params keeps an assembly seated A connection belongs to the child: its parent pointer under an identity parent inverse and kit_socket, kit_parent_socket and kit_roll. core.mate derives its matrix_basis, core.mate_refusal says what may mate, and reports give the residual and whether it holds. set_params checks every connection the part is an end of before it writes, then seats the part and the parts attached to it. boolean adds an Exact, self-intersecting Boolean above the Bevel; apply bakes the evaluated mesh and marks the part baked. Cut aetheria-release:cut_spec:cut-chassis-kit-assembly.r1. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 279 ++++++++++- .../brokkr_kitbash/brokkr_actions.json | 122 ++++- surfaces/blender/brokkr_kitbash/core.py | 61 +++ surfaces/blender/tests/live/kitbash.py | 6 +- .../blender/tests/live/kitbash.result.json | 8 +- .../blender/tests/live/kitbash_assembly.py | 446 ++++++++++++++++++ .../tests/live/kitbash_assembly.result.json | 372 +++++++++++++++ surfaces/blender/tests/test_kitbash.py | 150 +++++- 8 files changed, 1414 insertions(+), 30 deletions(-) create mode 100644 surfaces/blender/tests/live/kitbash_assembly.py create mode 100644 surfaces/blender/tests/live/kitbash_assembly.result.json diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index eb004e0..5d8da04 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -1,4 +1,4 @@ -"""Kitbash parts: place a parametric machine part from a kit, re-parameterise it, and report where its sockets are. +"""Kitbash parts: place parametric machine parts from a kit, mate them socket to socket, cut them, and bake them. A host add-on for Brokkr beside brokkr_mesh_polish and brokkr_rig (it imports the polish package's operator base, Refused and mesh_object, and nothing from Brokkr): brokkr_actions.json beside this file lists the operators agents @@ -9,9 +9,16 @@ WindowManager.brokkr_mesh_polish_result, as the polish operators do. What a placed part is lives on its object as three ID properties: kit_kit, kit_part and kit_params. The mesh is derived from them (set_params rebuilds it), and socket frames are derived again at every report: nothing else in the scene stores them. Two things would give a part a second owner and are refused: a mesh datablock shared with -another object (set_params), and a world transform that scales, mirrors or shears (set_params and report: a -part's size is its params). Placement, materials and export are Brokkr's own rows (setObjectTransform, assignMaterial, -exportGltf). +another object (set_params, apply), and a world transform that scales, mirrors or shears (a part's size is its +params). + +A connection belongs to the child: its parent pointer (under an identity parent inverse) and three more ID +properties, kit_socket, kit_parent_socket and kit_roll. Its matrix_basis is derived from them and both parts' +params by core.mate; attach and set_params write it, and a report says how far the child stands from it. A boolean +belongs to its Boolean modifier on the target (the modifier's object is the cutter; its name is a label). kit_baked +says apply replaced the mesh with the evaluated one: the params then only place the part's sockets. Placing a +loose part, hiding a cutter, materials and export are Brokkr's own rows (setObjectTransform, setObjectVisibility, +assignMaterial, exportGltf). """ bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0), "category": "Object", "description": "Parametric machine parts from kits, with socket frames; agent-callable through Brokkr."} @@ -19,8 +26,10 @@ bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0), import json import math +import bmesh import bpy import numpy as np +from mathutils import Matrix try: from brokkr_mesh_polish import RESULT, PolishOperator, Refused, mesh_object @@ -31,7 +40,10 @@ except ImportError as error: # register() says so; the classes below only need from . import core KIT, PART, PARAMS = "kit_kit", "kit_part", "kit_params" +SOCKET, PARENT_SOCKET, ROLL, BAKED = "kit_socket", "kit_parent_socket", "kit_roll", "kit_baked" +HELD = 1e-5 # a connection holds when its residual is at most this (as RIGID) BEVEL = "Kit Bevel" +BOOLEAN = "Kit Boolean " # a Boolean modifier's name is this and its cutter's name: a label, the cutter is modifier.object BEVEL_SEGMENTS, BEVEL_ANGLE = 2, math.radians(30.0) REPORT_LIMIT = 16000 # characters of a result Brokkr copies into a receipt before it truncates @@ -90,10 +102,98 @@ def kit_part_of(obj): return core.part(core.load_kit(str(obj.get(KIT, ""))), str(obj[PART])), stored +def built_part(obj): + """(part, the part built at the object's stored params): where its sockets are, baked or not.""" + part, stored = kit_part_of(obj) + return part, core.build(part, stored) + + +def link(obj): + """The connection a child states, (its socket, the parent's socket, roll in degrees), or None. The parent is + obj.parent and is stored nowhere else. attach, set_params, detach and every report read it here.""" + if SOCKET not in obj: + return None + roll = obj.get(ROLL, 0.0) + return str(obj[SOCKET]), str(obj.get(PARENT_SOCKET, "")), float(roll) if core.finite(roll) else 0.0 + + +def attached(obj) -> list: + """The children that state a connection to obj.""" + return [child for child in obj.children if SOCKET in child] + + +def mated(parent, parent_part, parent_built, child, child_part, child_built, stated): + """(parent socket, child socket) of the connection `stated` between two built parts, or a refusal that names + it: parts of two kits, a socket name a part does not have, or sockets core.mate_refusal will not mate.""" + try: + sockets = core.joint(parent_part, parent_built, stated[1], child_part, child_built, stated[0]) + refusal = core.mate_refusal(core.load_kit(parent_part["kit"])["socketTypes"], *sockets) + except core.KitError as error: + refusal = str(error) + if refusal: + raise Refused(f"{child.name!r} on {parent.name!r}: {refusal}; nothing changed.") + return sockets + + +def seat(child, basis) -> None: + """Write an attached child's derived matrix_basis, under an identity parent inverse.""" + child.matrix_parent_inverse = Matrix.Identity(4) + child.matrix_basis = Matrix(np.asarray(basis).tolist()) + + +def connection_report(obj, part, built): + """None for a part that states no connection, else what it states and whether it holds: the parent is a part + of the same kit, both sockets exist, the parent inverse is the identity and the child stands within HELD of + core.mate. A child moved or re-parented by another action reads holds false until set_params seats it again.""" + stated = link(obj) + if stated is None: + return None + row = {"parent": obj.parent.name if obj.parent else None, "socket": stated[0], "parentSocket": stated[1], + "roll": round(stated[2], 6), "residual": None, "holds": False} + try: + if obj.parent is None: + return row + parent_part, parent_built = built_part(obj.parent) + parent_socket, socket = core.joint(parent_part, parent_built, stated[1], part, built, stated[0]) + except (Refused, core.KitError): + return row + row["residual"] = round(core.residual(obj.parent.matrix_world, parent_socket, obj.matrix_world, socket, stated[2]), 9) + row["holds"] = bool(np.abs(np.array(obj.matrix_parent_inverse) - np.eye(4)).max() <= HELD and row["residual"] <= HELD) + return row + + def part_report(obj, part, built) -> dict: + """A part as the scene has it. Reads stored properties and matrices only: no modifier is evaluated.""" return {"object": obj.name, "kit": part["kit"], "part": part["name"], "params": built.params, "faces": len(obj.data.polygons), "shells": built.shell_count, "bevel": round(built.bevel, 6), - "sockets": core.socket_rows(built.sockets, np.array(obj.matrix_world))} + "sockets": core.socket_rows(built.sockets, np.array(obj.matrix_world)), + "connection": connection_report(obj, part, built), "baked": bool(obj.get(BAKED, False))} + + +def own_mesh(obj, doing: str) -> None: + if obj.data.users > 1: + raise Refused(f"{obj.name!r} shares its mesh {obj.data.name!r} with {obj.data.users - 1} other user(s): {doing} it would change " + "them while their params stay. Give it its own mesh (place_part a new part) and set that; nothing changed.") + + +def booleans(obj) -> list: + return [{"cutter": m.object.name if m.object else None, "operation": m.operation} for m in obj.modifiers if m.type == "BOOLEAN"] + + +def evaluated_of(context, obj): + """(depsgraph, obj with its modifier stack evaluated). An Exact Boolean costs about a second a part, so only + boolean and apply call this; no report does.""" + depsgraph = context.evaluated_depsgraph_get() + return depsgraph, obj.evaluated_get(depsgraph) + + +def measured(mesh) -> dict: + """Faces, signed volume (overlapping shells count twice) and edges that do not join exactly two faces.""" + bm = bmesh.new() + bm.from_mesh(mesh) + row = {"faces": len(bm.faces), "volume": round(bm.calc_volume(signed=True), 9), "nonManifoldEdges": sum(1 for e in bm.edges if not e.is_manifold)} + bm.free() + return row def carried_materials(mesh, old, new): @@ -145,8 +245,9 @@ class BROKKR_KITBASH_OT_place_part(PolishOperator): class BROKKR_KITBASH_OT_set_params(PolishOperator): - """Change params of a placed kit part and rebuild its mesh in place: its transform, parent, modifiers and - material slots stay, each shape keeps its faces' material, and the Bevel width follows""" + """Change params of a placed kit part and rebuild its mesh in place: its modifiers and material slots stay, + each shape keeps its faces' material, the Bevel width follows, and its connection and those of the parts + attached to it are seated again on the moved sockets""" bl_idname = "brokkr_kitbash.set_params" bl_label = "Set Kit Part Params" object_name: bpy.props.StringProperty(name="Object") @@ -156,10 +257,20 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator): def work(self, context): obj = mesh_object(self.object_name) part, stored = kit_part_of(obj) - if obj.data.users > 1: - raise Refused(f"{obj.name!r} shares its mesh {obj.data.name!r} with {obj.data.users - 1} other user(s): rebuilding it would change " - "them while their params stay. Give it its own mesh (place_part a new part) and set that; nothing changed.") + if obj.get(BAKED): + raise Refused(f"{obj.name!r} is baked: apply replaced its mesh, and its params now only place its sockets. " + "place_part a new part to change them; nothing changed.") + own_mesh(obj, "rebuilding") built = core.build(part, core.resolve_params(part, core.parse_params(self.params), stored)) + seats, stated = [], link(obj) # every connection this part is an end of, checked against its new sockets before anything is written + if stated is not None: + if obj.parent is None: + raise Refused(f"{obj.name!r} states a connection and has no parent: detach it to clear the connection; nothing changed.") + parent_part, parent_built = built_part(obj.parent) + seats.append((obj, core.mate(*mated(obj.parent, parent_part, parent_built, obj, part, built, stated), stated[2]))) + for child in attached(obj): + child_part, child_built = built_part(child) + seats.append((child, core.mate(*mated(obj, part, built, child, child_part, child_built, link(child)), link(child)[2]))) try: old = core.build(part, stored) except core.KitError: # stored params an edited kit no longer admits: nothing to map faces by @@ -172,9 +283,145 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator): obj.data.update() sync_bevel(obj, built.bevel) obj[PARAMS] = json.dumps(built.params) + for seated, basis in seats: # deeper descendants follow through parenting: their sockets did not move + seat(seated, basis) + if seats: + context.view_layer.update() return part_report(obj, part, built) +class BROKKR_KITBASH_OT_attach(PolishOperator): + """Seat a socket of a kit part on a socket of another part of its kit and parent it there: origins together, + normals opposed, turned by roll about the parent socket's normal""" + bl_idname = "brokkr_kitbash.attach" + bl_label = "Attach Kit Part" + object_name: bpy.props.StringProperty(name="Object", description="The child: the part that moves") + socket: bpy.props.StringProperty(name="Socket", description="The child's socket") + parent_name: bpy.props.StringProperty(name="Parent") + parent_socket: bpy.props.StringProperty(name="Parent Socket") + roll: bpy.props.FloatProperty(name="Roll", default=0.0, min=-360.0, max=360.0, + description="Degrees about the parent socket's normal, right-handed; at 0 the two sockets' ys line up") + + @kit_work + def work(self, context): + child, parent = mesh_object(self.object_name), mesh_object(self.parent_name) + part, built = built_part(child) + parent_part, parent_built = built_part(parent) + if child == parent: + raise Refused(f"{child.name!r} cannot be attached to itself; nothing changed.") + if child.parent is not None: + raise Refused(f"{child.name!r} has a parent, {child.parent.name!r}: detach it first (setObjectParent with an empty parent " + "for a parent it was not attached to); nothing changed.") + ancestor = parent.parent + while ancestor is not None: + if ancestor == child: + raise Refused(f"{parent.name!r} is below {child.name!r}: attaching {child.name!r} to it would close a loop; nothing changed.") + ancestor = ancestor.parent + stated = (self.socket, self.parent_socket, float(self.roll)) + sockets = mated(parent, parent_part, parent_built, child, part, built, stated) + users = [c.name for c in attached(parent) if c.get(PARENT_SOCKET) == self.parent_socket] + if parent.get(SOCKET) == self.parent_socket: + users.append(parent.parent.name if parent.parent else parent.name) + if users: + raise Refused(f"Socket {self.parent_socket!r} of {parent.name!r} is occupied (by {users[0]!r}); nothing changed.") + users = [c.name for c in attached(child) if c.get(PARENT_SOCKET) == self.socket] + if users: + raise Refused(f"Socket {self.socket!r} of {child.name!r} is occupied (by {users[0]!r}); nothing changed.") + child.parent = parent + seat(child, core.mate(*sockets, stated[2])) + child[SOCKET], child[PARENT_SOCKET], child[ROLL] = stated + context.view_layer.update() + return part_report(child, part, built) + + +class BROKKR_KITBASH_OT_detach(PolishOperator): + """Clear a kit part's connection: it stays where it stands in the world, loses its parent, and the parts + attached to it stay attached to it""" + bl_idname = "brokkr_kitbash.detach" + bl_label = "Detach Kit Part" + object_name: bpy.props.StringProperty(name="Object") + + @kit_work + def work(self, context): + obj = mesh_object(self.object_name) + if SOCKET not in obj: + raise Refused(f"{obj.name!r} is not attached (it has no {SOCKET} property); nothing changed.") + part, built = built_part(obj) + world = obj.matrix_world.copy() + obj.parent = None + obj.matrix_world = world + for key in (SOCKET, PARENT_SOCKET, ROLL): + if key in obj: + del obj[key] + return part_report(obj, part, built) + + +class BROKKR_KITBASH_OT_boolean(PolishOperator): + """Cut a kit part with another mesh object through a live Boolean modifier (Exact, with self-intersection: kit + parts are overlapping shells) placed above the Bevel; evaluates the part once and reports the result""" + bl_idname = "brokkr_kitbash.boolean" + bl_label = "Boolean Kit Part" + object_name: bpy.props.StringProperty(name="Object", description="The kit part that is cut") + cutter: bpy.props.StringProperty(name="Cutter", description="Any other mesh object; it is not changed") + operation: bpy.props.EnumProperty(name="Operation", default="DIFFERENCE", items=[ + ("DIFFERENCE", "Difference", ""), ("UNION", "Union", ""), ("INTERSECT", "Intersect", "")]) + + @kit_work + def work(self, context): + obj = mesh_object(self.object_name) + part, built = built_part(obj) + cutter = bpy.data.objects.get(self.cutter) + if cutter is None or cutter.type != "MESH": + raise Refused(f"No mesh object named {self.cutter!r} to cut with; nothing changed.") + if cutter == obj: + raise Refused(f"{obj.name!r} cannot cut itself; nothing changed.") + if any(m.type == "BOOLEAN" and m.object == cutter for m in obj.modifiers): + raise Refused(f"{cutter.name!r} is already the object of a Boolean on {obj.name!r}; nothing changed.") + modifier = obj.modifiers.new(BOOLEAN + cutter.name, "BOOLEAN") + modifier.operation, modifier.object = self.operation, cutter + # TRANSFER: with the default (INDEX) the result gains an empty material slot for a cutter that has no materials + modifier.solver = "EXACT" + modifier.use_self = True + modifier.material_mode = "TRANSFER" + names = [m.name for m in obj.modifiers] + if BEVEL in names: # cut first, then bevel the cut's edges with the rest + obj.modifiers.move(len(names) - 1, names.index(BEVEL)) + report = part_report(obj, part, built) + _, evaluated = evaluated_of(context, obj) + report["booleans"], report["evaluated"] = booleans(obj), measured(evaluated.to_mesh()) + evaluated.to_mesh_clear() + return report + + +class BROKKR_KITBASH_OT_apply(PolishOperator): + """Bake a kit part: its mesh becomes its evaluated mesh (Booleans and Bevel applied), every modifier goes, its + material slots stay, and it is marked baked; its sockets and connections stay as they are""" + bl_idname = "brokkr_kitbash.apply" + bl_label = "Apply Kit Part" + object_name: bpy.props.StringProperty(name="Object") + + @kit_work + def work(self, context): + obj = mesh_object(self.object_name) + part, built = built_part(obj) + own_mesh(obj, "baking") + if not obj.modifiers: + raise Refused(f"{obj.name!r} has no modifiers to apply; nothing changed.") + cutters, slots = [row["cutter"] for row in booleans(obj)], len(obj.data.materials) + depsgraph, evaluated = evaluated_of(context, obj) + baked = bpy.data.meshes.new_from_object(evaluated, preserve_all_data_layers=True, depsgraph=depsgraph) + while len(baked.materials) > slots and baked.materials[len(baked.materials) - 1] is None: + baked.materials.pop() # a Boolean gives a part that had no material slot one empty slot + old, name = obj.data, obj.data.name + obj.data = baked + obj.modifiers.clear() + if old.users == 0: + bpy.data.meshes.remove(old) + baked.name = name + obj[BAKED] = True + return {**part_report(obj, part, built), **measured(baked), "cutters": cutters} + + class BROKKR_KITBASH_OT_describe(PolishOperator): """List a kit's parts, or one part: params with type, bounds, default and doc, and sockets in the part's frame at default params""" @@ -190,7 +437,8 @@ class BROKKR_KITBASH_OT_describe(PolishOperator): class BROKKR_KITBASH_OT_report(PolishOperator): - """Report placed kit parts as the scene has them: kit, part, params, faces, shells and each socket's world frame""" + """Report placed kit parts as the scene has them: kit, part, params, faces, shells, each socket's world frame, + the connection and whether it holds, and whether the part is baked""" bl_idname = "brokkr_kitbash.report" bl_label = "Report Kit Parts" bl_options = {"REGISTER"} @@ -200,14 +448,11 @@ class BROKKR_KITBASH_OT_report(PolishOperator): def work(self, context): chosen = [mesh_object(self.object_name)] if self.object_name else sorted( (o for o in context.scene.objects if o.type == "MESH" and PART in o), key=lambda o: o.name) - parts = [] - for obj in chosen: - part, stored = kit_part_of(obj) - parts.append(part_report(obj, part, core.build(part, stored))) - return bounded({"parts": parts}, "name an object to report it alone") + return bounded({"parts": [part_report(obj, *built_part(obj)) for obj in chosen]}, "name an object to report it alone") -classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KITBASH_OT_describe, BROKKR_KITBASH_OT_report) +classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KITBASH_OT_describe, BROKKR_KITBASH_OT_report, + BROKKR_KITBASH_OT_attach, BROKKR_KITBASH_OT_detach, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_apply) def register(): diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index b570c13..e75ec1b 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -45,7 +45,7 @@ }, { "name": "brokkr_kitbash.set_params", - "doc": "Change params of a placed kit part and rebuild its mesh in place; transform, parent, modifiers and materials stay. Refuses 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 baked 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 and each socket's world 4x4. 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 baked. Evaluates no modifier. Refuses a part scaled in the world: resize with set_params.", "changesScene": false, "editModeSafe": true, "result": "brokkr_mesh_polish_result", @@ -106,6 +106,124 @@ "doc": "empty: every object that is a kit part" } ] + }, + { + "name": "brokkr_kitbash.attach", + "doc": "Seat a socket of a kit part on a socket of another part of its kit 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.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "the child: the part that moves" + }, + { + "name": "socket", + "type": "string", + "required": true, + "chars": "id", + "minLength": 1, + "maxLength": 32, + "doc": "the child's socket; brokkr_kitbash.report lists a part's sockets" + }, + { + "name": "parent_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "the part it is attached to" + }, + { + "name": "parent_socket", + "type": "string", + "required": true, + "chars": "id", + "minLength": 1, + "maxLength": 32, + "doc": "the parent's socket" + }, + { + "name": "roll", + "type": "number", + "minimum": -360, + "maximum": 360, + "default": 0, + "doc": "degrees about the parent socket's normal, right-handed; at 0 the two sockets' up axes line up" + } + ] + }, + { + "name": "brokkr_kitbash.detach", + "doc": "Clear a kit part's connection: it keeps its place in the world and loses its parent; parts attached to it stay attached to it.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63 + } + ] + }, + { + "name": "brokkr_kitbash.boolean", + "doc": "Cut a kit part with another mesh object through a live Boolean modifier (Exact, self-intersection on) above its Bevel. Evaluates the part once, about a second: reports the result's faces, volume and non-manifold edges. The cutter is not changed; hide it with setObjectVisibility.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "the kit part that is cut" + }, + { + "name": "cutter", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "any other mesh object" + }, + { + "name": "operation", + "type": "string", + "enum": [ + "DIFFERENCE", + "UNION", + "INTERSECT" + ], + "default": "DIFFERENCE" + } + ] + }, + { + "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 and a mesh another object shares.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63 + } + ] } ] } diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index a9b0c6b..49b3c36 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -8,6 +8,9 @@ expression is parsed with ast.parse and walked against a whitelist; nothing in a kit = load_kit("mechanical") built = build(part(kit, "tank"), {"length": 1.2}) # Built: V, faces, counts, smooth, shell_count, sockets +Two sockets mate through mate (the child's matrix under its parent), mate_refusal (what may mate) and residual +(how far a placed child stands from its mate). + Every refusal is a KitError whose message names the kit, part and field. """ from __future__ import annotations @@ -493,6 +496,64 @@ def socket_rows(sockets: list, frame=None) -> list[dict]: return [{"name": s["name"], "type": s["type"], "size": round(s["size"], 6), "matrix": rows(frame @ s["matrix"])} for s in sockets] +# --- mating -------------------------------------------------------------------------------------------------- + +FLIP = np.diag([-1.0, 1.0, -1.0, 1.0]) # half a turn about y: a mating socket's z faces the other's, y stays up + + +def _roll(degrees: float) -> np.ndarray: + turn = np.eye(4) + turn[:3, :3] = _rotation((0.0, 0.0, degrees)) + return turn + + +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 residual(parent_world, parent_socket: dict, child_world, child_socket: dict, roll_degrees: float) -> 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 + return float(np.abs(wanted - np.asarray(child_world, dtype=np.float64) @ child_socket["matrix"]).max()) + + +EQUAL, SLACK = 0.01, 1e-9 # 'equal' sizes may differ by 1 percent of the larger; SLACK keeps a size at the limit inside it + + +def mate_refusal(kit_types: dict, parent_socket: dict, child_socket: dict) -> str | None: + """None when the two sockets may mate, else a sentence naming both: they are of one type, and their sizes + agree as that type's match says ('equal': within 1 percent of the larger; 'fits': the child at most the parent).""" + 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"]: + return f"{both} are of different types" + 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)" + elif c["size"] > p["size"] * (1 + SLACK): + return f"{both} are {p['type']} sockets, where the child fits the parent: it is larger" + return None + + +def joint(parent_part: dict, parent_built: Built, parent_socket: str, child_part: dict, child_built: Built, child_socket: str): + """(parent socket, child socket) of a connection between two built parts, by socket name. Refuses parts of + different kits (socket types belong to a kit) and a name the part has no socket for.""" + if parent_part["kit"] != child_part["kit"]: + raise KitError(f"part {child_part['name']!r} is of kit {child_part['kit']!r} and part {parent_part['name']!r} of kit " + f"{parent_part['kit']!r}: socket types belong to a kit, so parts of different kits do not mate") + found = [] + for part, built, name in ((parent_part, parent_built, parent_socket), (child_part, child_built, child_socket)): + match = [s for s in built.sockets if s["name"] == name] + if not match: + raise KitError(f"kit {part['kit']!r} part {part['name']!r} has no socket {name!r}; its sockets: " + f"{', '.join(s['name'] for s in built.sockets) or 'none'}") + found.append(match[0]) + return found[0], found[1] + + def describe(kit: dict, name: str = "") -> dict: """The kit's parts (or the one named): params with their bounds, and sockets in the part frame at default params.""" chosen = [part(kit, name)] if name else list(kit["parts"].values()) diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py index 410cab3..a05ee4e 100644 --- a/surfaces/blender/tests/live/kitbash.py +++ b/surfaces/blender/tests/live/kitbash.py @@ -73,9 +73,9 @@ def extent(obj, axis=2): return float(co[:, axis].max() - co[:, axis].min()) -check("the four kitbash rows load as host actions with no errors", not R["hostErrors"] - and [r for r in R["hostRows"] if r.startswith("brokkr_kitbash.")] == ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", - "brokkr_kitbash.describe", "brokkr_kitbash.report"], [R["hostErrors"], R["hostRows"]]) +check("the eight kitbash rows load as host actions with no errors", not R["hostErrors"] + and [r for r in R["hostRows"] if r.startswith("brokkr_kitbash.")] == [f"brokkr_kitbash.{name}" for name in ( + "place_part", "set_params", "describe", "report", "attach", "detach", "boolean", "apply")], [R["hostErrors"], R["hostRows"]]) # --- describe --------------------------------------------------------------------------------------------------------- kit = core.load_kit("mechanical") diff --git a/surfaces/blender/tests/live/kitbash.result.json b/surfaces/blender/tests/live/kitbash.result.json index ab893bc..14da142 100644 --- a/surfaces/blender/tests/live/kitbash.result.json +++ b/surfaces/blender/tests/live/kitbash.result.json @@ -2,7 +2,7 @@ "blender": "5.3.0", "checks": [ { - "name": "the four kitbash rows load as host actions with no errors", + "name": "the eight kitbash rows load as host actions with no errors", "ok": true, "detail": null }, @@ -319,7 +319,11 @@ "brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", - "brokkr_kitbash.report" + "brokkr_kitbash.report", + "brokkr_kitbash.attach", + "brokkr_kitbash.detach", + "brokkr_kitbash.boolean", + "brokkr_kitbash.apply" ], "placed": { "nozzle": { diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py new file mode 100644 index 0000000..2bb8481 --- /dev/null +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -0,0 +1,446 @@ +"""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, drift and how it is cleared, detach, boolean (Exact, +self-intersection on, above the Bevel) on two targets, and apply. 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 -- + +Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses +without them). is an absolute path; writes .result.json and exits 1 when a check failed. + +An Exact Boolean costs about a second a part and evaluation, so only two parts are ever cut here (the tank and +one plate). Bounds follow lodur:ruling:deterministic-bound-margin: each sits at the geometric mean of the shipped +worst reading and the least claimed mutant's, both written beside it; the result file carries the readings. +""" +import importlib.util +import json +import math +import os +import sys +import tempfile +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 + +spec = importlib.util.spec_from_file_location("brokkr_kitbash_core_reference", SURFACE / "brokkr_kitbash" / "core.py") +core = importlib.util.module_from_spec(spec) # core as the unit tests load it: the frames every reading here is taken against +spec.loader.exec_module(core) + +sys.path.append(str(SURFACE)) +bpy.ops.wm.read_factory_settings(use_empty=True) +for module in ("brokkr_mesh_polish", "brokkr_kitbash"): + addon_utils.enable(module, default_set=True) +target = bt.BrokkrBlenderTarget(bpy) +WORK = Path(tempfile.mkdtemp(prefix="brokkr-kitbash-assembly-")) +target.configure_action_dirs("", str(WORK)) +target.reload_host_actions() +R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], "readings": {}} +COUNT = [0] +kit = core.load_kit("mechanical") +# Metres (or a difference of unit vectors) between where a seated socket is and where its mate puts it, read from +# the two world matrices. Shipped worst 1.5e-07 (float32 matrices, parts a few metres from the origin); least +# claimed mutant 0.22 (A8, a part not seated again after its own extension changed); separation 1.5e6. +SEATED = 1.8e-4 +# Metres between how far a part moved and how far the socket that carries it moved. Shipped worst 2.7e-07; least +# claimed mutant 0.84 (A7, attached children not seated again); separation 3.1e6. +CARRIED = 4.8e-4 +# Degrees between the roll read from the two world frames and the roll asked for. Shipped worst 6.3e-06; least +# claimed mutant 74 (A2, roll sign reversed, at roll 37); separation 1.2e7. +ROLL = 2.2e-2 +# Largest entry of matrix_world after detach minus before. Shipped worst 1.5e-08; least claimed mutant 2.9 +# (A10, detach drops the world matrix); separation 1.9e8. +KEPT = 2.1e-4 +# Cubic metres left of the 1.8 m tank (its 20 shells as one solid) with a 0.3 m box cut from its wall. Shipped +# 0.2539; least claimed mutant 0.0079 (A11, self-intersection off: overlapping shells cancel); separation 32. +CUT = 0.045 + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail}) # what was seen, when it was not what was promised + + +def reading(name, value): + R["readings"][name] = max(R["readings"].get(name, 0.0), float(value)) + return float(value) + + +def 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"])[:300], flush=True) + return receipt, result + + +def place(name, part, params="", location=None, rotation=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]) + return bpy.data.objects[name] + + +def frame(obj, socket): + """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["matrix"] for s in built.sockets if s["name"] == socket) + + +def seated(child, socket, parent, parent_socket, roll=None): + """How far a child's socket is from seated on its parent's: origins apart, or normals not opposed. With a roll, + also records the degrees between it and the roll read from the two frames.""" + a, b = frame(parent, parent_socket), frame(child, socket) + if roll is not None: + read = math.degrees(math.atan2(np.cross(a[:3, 1], b[:3, 1]) @ a[:3, 2], a[:3, 1] @ b[:3, 1])) + reading("roll", abs((read - roll + 180.0) % 360.0 - 180.0)) + return max(float(np.abs(a[:3, 3] - b[:3, 3]).max()), float(np.abs(a[:3, 2] + b[:3, 2]).max())) + + +def connection(name): + receipt, report = send("brokkr_kitbash.report", object_name=name) + return report["parts"][0]["connection"] if report else {"error": receipt["message"]} + + +def holds(name, parent, socket, parent_socket, roll=0.0): + found = connection(name) or {} + return found == {**found, "parent": parent, "socket": socket, "parentSocket": parent_socket, "roll": roll, "holds": True} \ + and found.get("residual", 1.0) <= 1e-5, found + + +def held(report): + """An attach or set_params report whose connection holds.""" + return bool(report and report.get("connection") and report["connection"]["holds"] and report["connection"]["residual"] <= 1e-5) + + +def scene_state(): + return {o.name: (o.parent and o.parent.name, np.round(np.array(o.matrix_basis), 6).tolist(), np.round(np.array(o.matrix_parent_inverse), 6).tolist(), + {k: o[k] for k in sorted(o.keys()) if k.startswith("kit_")}, [(m.name, m.type) for m in o.modifiers], + o.data.name if o.type == "MESH" else None, len(o.data.polygons) if o.type == "MESH" else None, + [s.material and s.material.name for s in o.material_slots], o.hide_render) + for o in bpy.data.objects}, sorted(m.name for m in bpy.data.meshes) + + +def refused(label, action, fields, expected): + state = scene_state() + receipt, _ = send(action, **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 measure(mesh): + bm = bmesh.new() + bm.from_mesh(mesh) + row = {"faces": len(bm.faces), "volume": round(bm.calc_volume(signed=True), 9), "nonManifoldEdges": sum(1 for e in bm.edges if not e.is_manifold)} + bm.free() + return row + + +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()) + row = measure(shown.to_mesh()) + shown.to_mesh_clear() + return row, [m.name if m else None for m in shown.data.materials] + + +rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")] +check("the eight kitbash rows load as host actions with no errors", not R["hostErrors"] and rows == [f"brokkr_kitbash.{n}" for n in ( + "place_part", "set_params", "describe", "report", "attach", "detach", "boolean", "apply")], [R["hostErrors"], rows]) + +# --- attach ------------------------------------------------------------------------------------------------------------- +tank = place("Tank", "tank", location=[1.0, 2.0, 3.0], rotation=[0.3, -0.2, 0.5]) # port size 0.088 +tee = place("Tee", "pipe_fitting", "pipe_r=0.044", location=[-2.0, 0.5, 1.0], rotation=[1.1, 0.4, -0.7]) +nozzle = place("Nozzle", "nozzle", "throat_r=0.044", location=[0.0, 4.0, 0.0]) +spare = place("Spare", "nozzle", "throat_r=0.044", location=[0.0, 6.0, 0.0]) +wide = place("Wide", "nozzle", location=[0.0, 8.0, 0.0]) # throat 0.07: flange size 0.14 +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) + +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" + and nozzle.parent == tee and np.array_equal(np.array(nozzle.matrix_parent_inverse), np.eye(4)) + and (nozzle["kit_socket"], nozzle["kit_parent_socket"], nozzle["kit_roll"]) == ("mount", "c", 37.0) + and sorted(k for k in nozzle.keys() if k.startswith("kit_")) == ["kit_kit", "kit_params", "kit_parent_socket", "kit_part", "kit_roll", "kit_socket"], + [receipt["message"], dict(nozzle.items())]) +gap = reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) +check("attach seats the nozzle's mount on the tee's c: origins together, normals opposed, rolled 37 degrees", gap < SEATED and R["readings"]["roll"] < ROLL, dict(R["readings"])) +check("attach reports the child: its connection holds, and its sockets are the seated world frames", report + and report["connection"] == {**report["connection"], "parent": "Tee", "socket": "mount", "parentSocket": "c", "roll": 37.0, "holds": True} + and report["connection"]["residual"] <= 1e-5 and report["object"] == "Nozzle" + and np.abs(np.array(report["sockets"][0]["matrix"]) - frame(nozzle, "mount")).max() < 2e-6, report) +check("report shows the same connection", holds("Nozzle", "Tee", "mount", "c", 37.0)[0], connection("Nozzle")) +receipt, report = send("brokkr_kitbash.attach", object_name="Tee", socket="a", parent_name="Tank", parent_socket="port_b") +check("attach of the tee to the tank's port carries the nozzle with it", receipt["status"] == "accepted" and held(report) and report["connection"]["roll"] == 0.0 and reading("seated", seated(tee, "a", tank, "port_b", 0.0)) < SEATED + and reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) < SEATED and R["readings"]["roll"] < ROLL + and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], [receipt["message"], R["readings"]]) + +refused("sockets of different types", "brokkr_kitbash.attach", {"object_name": "Radiator", "socket": "base", "parent_name": "Tee", "parent_socket": "b"}, + "'Radiator' on 'Tee': socket 'base' (mount, size 0.15) and parent socket 'b' (flange, size 0.088) are of different types") +refused("flanges of different sizes", "brokkr_kitbash.attach", {"object_name": "Wide", "socket": "mount", "parent_name": "Tee", "parent_socket": "b"}, + "mate at equal sizes") +refused("a parent socket a child is on", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Tee", "parent_socket": "c"}, + "Socket 'c' of 'Tee' is occupied (by 'Nozzle')") +refused("a parent socket the parent is attached by", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Tee", "parent_socket": "a"}, + "Socket 'a' of 'Tee' is occupied (by 'Tank')") +refused("a loop through a grandchild", "brokkr_kitbash.attach", {"object_name": "Tank", "socket": "port_a", "parent_name": "Nozzle", "parent_socket": "mount"}, + "'Nozzle' is below 'Tank'") +refused("a child that has a parent", "brokkr_kitbash.attach", {"object_name": "Nozzle", "socket": "mount", "parent_name": "Tee", "parent_socket": "b"}, + "'Nozzle' has a parent, 'Tee'") +refused("a part to itself", "brokkr_kitbash.attach", {"object_name": "Tank", "socket": "port_a", "parent_name": "Tank", "parent_socket": "port_b"}, + "cannot be attached to itself") +refused("a socket the parent does not have", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Tee", "parent_socket": "d"}, + "'Spare' on 'Tee': kit 'mechanical' part 'pipe_fitting' has no socket 'd'; its sockets: a, b, c") +refused("a socket the child does not have", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "throat", "parent_name": "Tee", "parent_socket": "b"}, + "part 'nozzle' has no socket 'throat'") +refused("a child that is not a kit part", "brokkr_kitbash.attach", {"object_name": "Plain", "socket": "a", "parent_name": "Tee", "parent_socket": "b"}, + "'Plain' is not a kit part") +refused("a parent that is not a kit part", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Plain", "parent_socket": "b"}, + "'Plain' is not a kit part") +refused("detach of a part that is not attached", "brokkr_kitbash.detach", {"object_name": "Spare"}, "'Spare' is not attached") +send("brokkr_kitbash.detach", object_name="Tee") +send("setObjectTransform", targetObjectName="Tee", location=[-2.0, 0.5, 1.0], rotationEuler=[1.1, 0.4, -0.7]) +refused("a child socket one of its own children is on", "brokkr_kitbash.attach", {"object_name": "Tee", "socket": "c", "parent_name": "Tank", "parent_socket": "port_b"}, + "Socket 'c' of 'Tee' is occupied (by 'Nozzle')") +send("brokkr_kitbash.attach", object_name="Tee", socket="a", parent_name="Tank", parent_socket="port_b") +receipt, report = send("brokkr_kitbash.attach", object_name="Spare", socket="mount", parent_name="Tee", parent_socket="b", roll=-90.0) +check("a second nozzle attaches to the tee's free socket, rolled -90", receipt["status"] == "accepted" and held(report) + and reading("seated", seated(spare, "mount", tee, "b", -90.0)) < SEATED and R["readings"]["roll"] < ROLL, [receipt["message"], R["readings"]]) + +# --- set_params seats what is attached again ---------------------------------------------------------------------------------- +was = {name: np.array(bpy.data.objects[name].matrix_world) for name in ("Tank", "Tee", "Nozzle", "Spare")} +receipt, report = send("brokkr_kitbash.set_params", object_name="Tank", params="length=1.8") +moved = {name: np.array(bpy.data.objects[name].matrix_world) - was[name] for name in was} +port = np.array(tank.matrix_world)[:3, :3] @ [0.0, 0.0, 0.9] # where port_b went: 0.9 along the tank's own z +check("set_params doubling the tank's length moves the tee and both nozzles by the port's displacement, and nothing turns", + receipt["status"] == "accepted" and np.abs(moved["Tank"]).max() == 0.0 + and all(reading("carried", np.abs(moved[n][:3, 3] - port).max()) < CARRIED and np.abs(moved[n][:3, :3]).max() < 1e-6 for n in ("Tee", "Nozzle", "Spare")), + [receipt["message"], {n: m[:3, 3].tolist() for n, m in moved.items()}, port.tolist()]) +check("after it every connection holds", holds("Tee", "Tank", "a", "port_b")[0] and holds("Nozzle", "Tee", "mount", "c", 37.0)[0] + and holds("Spare", "Tee", "mount", "b", -90.0)[0] and reading("seated", seated(tee, "a", tank, "port_b")) < SEATED + and reading("seated", seated(nozzle, "mount", tee, "c")) < SEATED, [connection("Tee"), connection("Nozzle"), connection("Spare")]) +refused("set_params that breaks the part's own connection", "brokkr_kitbash.set_params", {"object_name": "Tee", "params": "pipe_r=0.06"}, + "'Tee' on 'Tank': socket 'a' (flange, size 0.12) and parent socket 'port_b' (flange, size 0.088)") +refused("set_params that breaks a child's connection", "brokkr_kitbash.set_params", {"object_name": "Tank", "params": "radius=0.3"}, + "'Tee' on 'Tank': socket 'a' (flange, size 0.088) and parent socket 'port_b' (flange, size 0.12)") +receipt, report = send("brokkr_kitbash.set_params", object_name="Tee", params="branch=0.4; run=0.6") +check("set_params on the tee keeps its own seat and moves each nozzle with its socket", receipt["status"] == "accepted" and held(report) + and reading("seated", seated(tee, "a", tank, "port_b")) < SEATED and reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) < SEATED + and reading("seated", seated(spare, "mount", tee, "b", -90.0)) < SEATED and holds("Nozzle", "Tee", "mount", "c", 37.0)[0] + and holds("Spare", "Tee", "mount", "b", -90.0)[0] and R["readings"]["roll"] < ROLL, [receipt["message"], R["readings"]]) + +# a strut hangs from one actuator's rod, and a second actuator hangs from the strut by its own rod +lift = place("Lift", "actuator", location=[4.0, 0.0, 0.0], rotation=[0.2, 0.9, -0.4]) # pivot size 0.054 +strut = place("Strut", "strut", "width=0.09") +ram = place("Ram", "actuator") +send("brokkr_kitbash.attach", object_name="Strut", socket="end_a", parent_name="Lift", parent_socket="rod_end", roll=90.0) +send("brokkr_kitbash.attach", object_name="Ram", socket="rod_end", parent_name="Strut", parent_socket="end_b") +base = frame(ram, "base") +receipt, report = send("brokkr_kitbash.set_params", object_name="Ram", params="extension=0.5") +back = frame(ram, "base")[:3, 3] - base[:3, 3] +check("extending an actuator that hangs by its rod seats it again: the rod end stays, the body backs off by the travel", + reading("seated", seated(ram, "rod_end", strut, "end_b", 0.0)) < SEATED and receipt["status"] == "accepted" and held(report) + and reading("carried", np.abs(back - base[:3, 2] * 0.35).max()) < CARRIED, [receipt["message"], connection("Ram"), back.tolist()]) +tip = frame(strut, "end_b") +receipt, report = send("brokkr_kitbash.set_params", object_name="Lift", params="extension=0.6") +check("extending the actuator above moves the strut on its rod and the ram below with it", receipt["status"] == "accepted" + and holds("Strut", "Lift", "end_a", "rod_end", 90.0)[0] and holds("Ram", "Strut", "rod_end", "end_b")[0] + and reading("seated", seated(strut, "end_a", lift, "rod_end", 90.0)) < SEATED + and reading("carried", np.abs(frame(strut, "end_b")[:3, 3] - tip[:3, 3] - np.array(lift.matrix_world)[:3, 2] * 0.45).max()) < CARRIED, + [receipt["message"], connection("Strut"), connection("Ram")]) + +# --- drift and detach --------------------------------------------------------------------------------------------------------- +send("setObjectTransform", targetObjectName="Nozzle", location=[0.25, 0.0, 0.0]) +found = connection("Nozzle") or {} +check("setObjectTransform on an attached child shows in its report: holds false, with the residual", found.get("holds") is False and found["parent"] == "Tee" + and found["residual"] > 0.1, found) +refused("attach of a drifted child, which still has its parent", "brokkr_kitbash.attach", + {"object_name": "Nozzle", "socket": "mount", "parent_name": "Tee", "parent_socket": "c"}, "'Nozzle' has a parent, 'Tee'") +send("brokkr_kitbash.set_params", object_name="Tee", params="run=0.6") +check("set_params on its parent seats it again", holds("Nozzle", "Tee", "mount", "c", 37.0)[0] and reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) < SEATED, + connection("Nozzle")) +send("setObjectTransform", targetObjectName="Nozzle", rotationEuler=[0.0, 0.5, 0.0]) +drifted = connection("Nozzle") or {} +send("brokkr_kitbash.set_params", object_name="Nozzle", params="exit_r=0.3") +check("set_params on the drifted child itself seats it again", drifted.get("holds") is False and holds("Nozzle", "Tee", "mount", "c", 37.0)[0] + and reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) < SEATED, [drifted, connection("Nozzle")]) +nozzle.matrix_parent_inverse = nozzle.matrix_basis.inverted() # as parenting by hand in the viewport leaves it; the basis below keeps the nozzle where it is +nozzle.matrix_basis = nozzle.matrix_basis @ nozzle.matrix_basis +bpy.context.view_layer.update() +found = connection("Nozzle") or {} +check("a parent inverse that is not the identity does not hold, wherever the child stands", found.get("holds") is False and found["residual"] <= 1e-5 + and seated(nozzle, "mount", tee, "c") < SEATED, found) +send("brokkr_kitbash.set_params", object_name="Tee", params="run=0.6") +check("and set_params on the parent writes the identity back", holds("Nozzle", "Tee", "mount", "c", 37.0)[0] + and np.array_equal(np.array(nozzle.matrix_parent_inverse), np.eye(4)), connection("Nozzle")) +send("setObjectParent", targetObjectName="Spare", parentObjectName="") +found = connection("Spare") +check("setObjectParent clearing an attached child's parent shows as a connection with no parent", found and found == {**found, "parent": None, "holds": False, "residual": None}, found) +refused("set_params on a part whose connection has no parent", "brokkr_kitbash.set_params", {"object_name": "Spare", "params": "exit_r=0.3"}, + "'Spare' states a connection and has no parent") +send("setObjectParent", targetObjectName="Spare", parentObjectName="Plain") +found = connection("Spare") or {} +refused("set_params on a part parented to something that is not a kit part", "brokkr_kitbash.set_params", {"object_name": "Spare", "params": "exit_r=0.3"}, + "'Plain' is not a kit part") +receipt, report = send("brokkr_kitbash.detach", object_name="Spare") +check("detach clears what is left of it", found.get("holds") is False and found.get("parent") == "Plain" and receipt["status"] == "accepted" and spare.parent is None + and report and report["connection"] is None and not [k for k in spare.keys() if k in ("kit_socket", "kit_parent_socket", "kit_roll")], [found, report]) + +before = {name: np.array(bpy.data.objects[name].matrix_world) for name in ("Tee", "Nozzle")} +receipt, report = send("brokkr_kitbash.detach", object_name="Tee") +check("detach leaves the tee where it stood, with no parent and no connection", receipt["status"] == "accepted" and tee.parent is None + and report and report["connection"] is None and sorted(k for k in tee.keys() if k.startswith("kit_")) == ["kit_kit", "kit_params", "kit_part"] + and reading("kept", max(np.abs(np.array(bpy.data.objects[n].matrix_world) - before[n]).max() for n in before)) < KEPT, [receipt["message"], R["readings"]]) +check("and the nozzle stays attached to the tee", nozzle.parent == tee and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], connection("Nozzle")) +send("brokkr_kitbash.attach", object_name="Tee", socket="b", parent_name="Tank", parent_socket="port_a", roll=180.0) +check("the freed tee attaches by another socket to the tank's other port", holds("Tee", "Tank", "b", "port_a", 180.0)[0] + and reading("seated", seated(tee, "b", tank, "port_a", 180.0)) < SEATED and R["readings"]["roll"] < ROLL, connection("Tee")) + +# --- boolean: the tank, with two material slots ----------------------------------------------------------------------------------- +send("assignMaterial", targetObjectName="Tank", materialName="Tank Paint", color=[0.35, 0.35, 0.35]) +send("assignMaterial", targetObjectName="Tank", materialName="Strap Steel", color=[0.2, 0.2, 0.2]) +tank_built = core.build(kit["parts"]["tank"], json.loads(tank["kit_params"])) +STRAPS = sorted(set(tank_built.shape.tolist()))[-1] +tank.data.polygons.foreach_set("material_index", np.where(tank_built.shape == STRAPS, 1, 0).astype(np.int32)) +side = np.array(tank.matrix_world) @ [0.24, 0.0, 0.9, 1.0] # on the barrel's wall, halfway along +send("createObject", objectType="MESH", name="Box", location=side[:3].tolist(), size=0.3) +box = bpy.data.objects["Box"] +box_was = (box.hide_render, box.hide_viewport, len(box.data.polygons), [m.name for m in box.modifiers], box.parent) +raw = measure(tank.data) +receipt, cut = send("brokkr_kitbash.boolean", object_name="Tank", cutter="Box") +modifier = tank.modifiers.get("Kit Boolean Box") +check("boolean adds a Boolean modifier above the Bevel: Exact, self-intersection on, difference, the cutter its object", + receipt["status"] == "accepted" and [m.name for m in tank.modifiers] == ["Kit Boolean Box", "Kit Bevel"] and modifier is not None and modifier.type == "BOOLEAN" + and (modifier.solver, modifier.use_self, modifier.operation, modifier.operand_type, modifier.object) == ("EXACT", True, "DIFFERENCE", "OBJECT", box), + [receipt["message"], [m.name for m in tank.modifiers]]) +shown, shown_slots = evaluated(tank) +check("boolean reports the evaluated mesh, with less volume than the uncut tank and no non-manifold edge", cut and cut["evaluated"] == shown + and CUT < cut["evaluated"]["volume"] < raw["volume"] - 0.005 and cut["evaluated"]["nonManifoldEdges"] == 0 + and cut["booleans"] == [{"cutter": "Box", "operation": "DIFFERENCE"}] and cut["faces"] == len(tank.data.polygons) == raw["faces"], + [cut and cut["evaluated"], shown, raw]) +R["tank"] = {"raw": raw, "cut": cut and cut["evaluated"]} +check("the cut tank shows the tank's two material slots and no other", shown_slots == ["Tank Paint", "Strap Steel"] and modifier is not None and modifier.material_mode == "TRANSFER", shown_slots) +check("boolean leaves the cutter as it was", (box.hide_render, box.hide_viewport, len(box.data.polygons), [m.name for m in box.modifiers], box.parent) == box_was + and "kit_part" not in box, box_was) +refused("a cutter that already cuts the part", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Box", "operation": "UNION"}, + "'Box' is already the object of a Boolean on 'Tank'") +refused("the part as its own cutter", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Tank"}, "cannot cut itself") +refused("a cutter that does not exist", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Nothing"}, "No mesh object named 'Nothing'") +send("createObject", objectType="EMPTY", name="Marker") +refused("a cutter that is not a mesh", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Marker"}, "No mesh object named 'Marker'") +refused("boolean on a mesh that is not a kit part", "brokkr_kitbash.boolean", {"object_name": "Plain", "cutter": "Box"}, "'Plain' is not a kit part") +receipt, report = send("brokkr_kitbash.set_params", object_name="Tank", params="segments=16") +resized, _ = evaluated(tank) +check("set_params on the cut tank rebuilds it under the live Boolean, and the tee stays on its port", receipt["status"] == "accepted" + and [m.name for m in tank.modifiers] == ["Kit Boolean Box", "Kit Bevel"] and tank.modifiers["Kit Boolean Box"].object == box + 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") +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 = tank.data.name, len(bpy.data.meshes) +sockets_before = send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0]["sockets"] +receipt, baked = send("brokkr_kitbash.apply", 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"], [receipt["message"], baked, shown]) +check("apply 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") +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] + 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) + and reading("seated", seated(radiator, "base", tank, "saddle", 0.0)) < SEATED, receipt["message"]) + +# --- the second target: a plate with no material slot, cut twice ---------------------------------------------------------------------- +plate = place("Plate", "plate", location=[0.0, -3.0, 0.0]) +send("createObject", objectType="MESH", name="Slot", location=[0.1, -3.0, 0.0], size=0.1) +send("createObject", objectType="MESH", name="Hole", location=[-0.1, -3.0, 0.0], size=0.05) +receipt, first = send("brokkr_kitbash.boolean", object_name="Plate", cutter="Slot") +receipt, second = send("brokkr_kitbash.boolean", object_name="Plate", cutter="Hole") +check("two cutters stack in the order they came, both above the Bevel", receipt["status"] == "accepted" + and [m.name for m in plate.modifiers] == ["Kit Boolean Slot", "Kit Boolean Hole", "Kit Bevel"] + and second["booleans"] == [{"cutter": "Slot", "operation": "DIFFERENCE"}, {"cutter": "Hole", "operation": "DIFFERENCE"}] + and second["evaluated"]["volume"] < first["evaluated"]["volume"] and first["evaluated"]["nonManifoldEdges"] == second["evaluated"]["nonManifoldEdges"] == 0 + 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.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]) +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") +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 + 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()))]) +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) + 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'") +big = place("Big", "vent", "width=0.8; height=0.6") +refused("a part larger than the seat", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Plate", "parent_socket": "back"}, + "are mount sockets, where the child fits the parent: it is larger") + +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) diff --git a/surfaces/blender/tests/live/kitbash_assembly.result.json b/surfaces/blender/tests/live/kitbash_assembly.result.json new file mode 100644 index 0000000..3be8cda --- /dev/null +++ b/surfaces/blender/tests/live/kitbash_assembly.result.json @@ -0,0 +1,372 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "the eight kitbash rows load as host actions with no errors", + "ok": true, + "detail": null + }, + { + "name": "a part nobody attached reports connection null and baked false", + "ok": true, + "detail": null + }, + { + "name": "attach parents the nozzle to the tee under an identity parent inverse and stores the three properties", + "ok": true, + "detail": null + }, + { + "name": "attach seats the nozzle's mount on the tee's c: origins together, normals opposed, rolled 37 degrees", + "ok": true, + "detail": null + }, + { + "name": "attach reports the child: its connection holds, and its sockets are the seated world frames", + "ok": true, + "detail": null + }, + { + "name": "report shows the same connection", + "ok": true, + "detail": null + }, + { + "name": "attach of the tee to the tank's port carries the nozzle with it", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: sockets of different types", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: flanges of different sizes", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a parent socket a child is on", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a parent socket the parent is attached by", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a loop through a grandchild", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a child that has a parent", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a part to itself", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a socket the parent does not have", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a socket the child does not have", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a child that is not a kit part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a parent that is not a kit part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: detach of a part that is not attached", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a child socket one of its own children is on", + "ok": true, + "detail": null + }, + { + "name": "a second nozzle attaches to the tee's free socket, rolled -90", + "ok": true, + "detail": null + }, + { + "name": "set_params doubling the tank's length moves the tee and both nozzles by the port's displacement, and nothing turns", + "ok": true, + "detail": null + }, + { + "name": "after it every connection holds", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params that breaks the part's own connection", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params that breaks a child's connection", + "ok": true, + "detail": null + }, + { + "name": "set_params on the tee keeps its own seat and moves each nozzle with its socket", + "ok": true, + "detail": null + }, + { + "name": "extending an actuator that hangs by its rod seats it again: the rod end stays, the body backs off by the travel", + "ok": true, + "detail": null + }, + { + "name": "extending the actuator above moves the strut on its rod and the ram below with it", + "ok": true, + "detail": null + }, + { + "name": "setObjectTransform on an attached child shows in its report: holds false, with the residual", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: attach of a drifted child, which still has its parent", + "ok": true, + "detail": null + }, + { + "name": "set_params on its parent seats it again", + "ok": true, + "detail": null + }, + { + "name": "set_params on the drifted child itself seats it again", + "ok": true, + "detail": null + }, + { + "name": "a parent inverse that is not the identity does not hold, wherever the child stands", + "ok": true, + "detail": null + }, + { + "name": "and set_params on the parent writes the identity back", + "ok": true, + "detail": null + }, + { + "name": "setObjectParent clearing an attached child's parent shows as a connection with no parent", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on a part whose connection has no parent", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on a part parented to something that is not a kit part", + "ok": true, + "detail": null + }, + { + "name": "detach clears what is left of it", + "ok": true, + "detail": null + }, + { + "name": "detach leaves the tee where it stood, with no parent and no connection", + "ok": true, + "detail": null + }, + { + "name": "and the nozzle stays attached to the tee", + "ok": true, + "detail": null + }, + { + "name": "the freed tee attaches by another socket to the tank's other port", + "ok": true, + "detail": null + }, + { + "name": "boolean adds a Boolean modifier above the Bevel: Exact, self-intersection on, difference, the cutter its object", + "ok": true, + "detail": null + }, + { + "name": "boolean reports the evaluated mesh, with less volume than the uncut tank and no non-manifold edge", + "ok": true, + "detail": null + }, + { + "name": "the cut tank shows the tank's two material slots and no other", + "ok": true, + "detail": null + }, + { + "name": "boolean leaves the cutter as it was", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a cutter that already cuts the part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: the part as its own cutter", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a cutter that does not exist", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a cutter that is not a mesh", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: boolean on a mesh that is not a kit part", + "ok": true, + "detail": null + }, + { + "name": "set_params on the cut tank rebuilds it under the live Boolean, and the tee stays on its port", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: apply on a mesh that is not a kit part", + "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", + "ok": true, + "detail": null + }, + { + "name": "apply keeps the material slots exactly, and faces of both materials", + "ok": true, + "detail": null + }, + { + "name": "apply marks the part baked and keeps what it is", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on a baked part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: apply on a baked part with no modifiers left", + "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", + "ok": true, + "detail": null + }, + { + "name": "a new part attaches to a baked one", + "ok": true, + "detail": null + }, + { + "name": "two cutters stack in the order they came, both above the Bevel", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: apply on a mesh a linked duplicate shares", + "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)", + "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", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a loop of two", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a part larger than the seat", + "ok": true, + "detail": null + } + ], + "hostErrors": [], + "readings": { + "carried": 2.7e-07, + "kept": 1.5e-08, + "roll": 6.3e-06, + "seated": 1.5e-07 + }, + "tank": { + "raw": { + "faces": 740, + "volume": 0.264901065, + "nonManifoldEdges": 0 + }, + "cut": { + "faces": 2337, + "volume": 0.25387923, + "nonManifoldEdges": 0 + } + }, + "plate": { + "raw": { + "faces": 44, + "volume": 0.002056141, + "nonManifoldEdges": 0 + }, + "slot": { + "faces": 504, + "volume": 0.001448832, + "nonManifoldEdges": 0 + }, + "slotAndHole": { + "faces": 558, + "volume": 0.001411154, + "nonManifoldEdges": 0 + } + }, + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 5481efd..fe6aa5f 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -2,7 +2,7 @@ corner of its params, and the host action file against Brokkr's own checker. Run: python3 -m unittest discover -s surfaces/blender/tests -v (needs numpy; skipped without it) -The operators are exercised in a real Blender by tests/live/kitbash.py. +The operators are exercised in a real Blender by tests/live/kitbash.py and tests/live/kitbash_assembly.py. Bounds follow lodur:ruling:deterministic-bound-margin: a deterministic reading is exact here, so each assertion is the built value, and each names the mutant it kills. @@ -389,6 +389,111 @@ class MechanicalKitTests(unittest.TestCase): self.assertEqual(described["parts"][0]["params"][0], {"name": "radius", "type": "number", "min": 0.12, "max": 0.35, "default": 0.22, "doc": "shell radius"}) +@unittest.skipIf(np is None, "numpy is not installed") +class MateTests(unittest.TestCase): + """core.mate, residual, mate_refusal and joint. The four bounds sit at the geometric mean of the shipped worst + reading and the least claimed mutant's (lodur:ruling:deterministic-bound-margin); a shipped reading of exactly + 0 is taken as one float step (2.2e-16; 2.8e-14 degrees for the roll, which is read through a sum with 180).""" + PAIRS = [("pipe_fitting", {}, "c", "nozzle", {"throat_r": 0.05}, "mount"), ("pipe_fitting", {}, "b", "tank", {"radius": 0.25}, "port_b"), + ("strut", {"width": 0.09}, "end_b", "actuator", {"body_r": 0.06}, "rod_end"), ("tank", {}, "saddle", "radiator_stack", {}, "base"), + ("plate", {}, "front", "vent", {"width": 0.2, "height": 0.15}, "back")] + ORIGIN = 6.2e-8 # shipped 8.9e-16; least mutant 4.36 (the child socket's inverse replaced by its transpose); separation 4.9e15 + NORMAL = 2.1e-8 # shipped 0; least mutant 1.974 (A1, FLIP dropped); separation above 8e15 + ROLL = 2.2e-6 # degrees. shipped 0; least mutant 180 (A2, roll sign reversed, at roll -90); separation above 6e15 + RESIDUAL = 4.2e-8 # shipped 8.9e-16; least mutant 1.999 (A1 and A2 both); separation 2.2e15 + + @classmethod + def setUpClass(cls): + cls.kit = core.load_kit("mechanical") + + def sockets(self, parent, parent_params, parent_socket, child, child_params, child_socket): + parts = self.kit["parts"] + return core.joint(parts[parent], core.build(parts[parent], parent_params), parent_socket, + parts[child], core.build(parts[child], child_params), child_socket) + + def test_a_mated_child_sits_on_the_parent_socket_at_its_roll(self): + """mate-math, read from the two world frames and not through core.residual. Mutants A1 (FLIP dropped: the + normals agree instead of opposing) and A2 (roll sign reversed).""" + rng = random.Random("mate") + worst = {"origin": 0.0, "normal": 0.0, "roll": 0.0, "residual": 0.0} + for pair in self.PAIRS: + sp, sc = self.sockets(*pair) + self.assertIsNone(core.mate_refusal(self.kit["socketTypes"], sp, sc), pair) + for _ in range(4): + 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, 37.0, -90.0, 180.0): + child = world @ core.mate(sp, sc, roll) + a, b = world @ sp["matrix"], child @ sc["matrix"] + read = math.degrees(math.atan2(np.cross(a[:3, 1], b[:3, 1]) @ a[:3, 2], a[:3, 1] @ b[:3, 1])) # the child's y from the parent's, about the parent's z + worst["origin"] = max(worst["origin"], float(np.abs(a[:3, 3] - b[:3, 3]).max())) + worst["normal"] = max(worst["normal"], float(np.abs(a[:3, 2] + b[:3, 2]).max())) + worst["roll"] = max(worst["roll"], abs((read - roll + 180.0) % 360.0 - 180.0)) + worst["residual"] = max(worst["residual"], core.residual(world, sp, child, sc, roll)) + self.assertLess(np.abs(child[:3, :3].T @ child[:3, :3] - np.eye(3)).max(), 1e-12) + if roll == 0.0: + self.assertLess(np.abs(a[:3, 1] - b[:3, 1]).max(), self.NORMAL, "roll 0 lines the two ys up") + self.assertLess(worst["origin"], self.ORIGIN) + self.assertLess(worst["normal"], self.NORMAL) + self.assertLess(worst["roll"], self.ROLL) + self.assertLess(worst["residual"], self.RESIDUAL) + + def test_residual_is_how_far_the_child_stands_from_its_mate(self): + sp, sc = self.sockets(*self.PAIRS[0]) + world = np.eye(4) + world[:3, 3] = [1.0, 2.0, 3.0] + child = world @ core.mate(sp, sc, 37.0) + moved = child.copy() + moved[0, 3] += 0.25 + self.assertAlmostEqual(core.residual(world, sp, moved, sc, 37.0), 0.25, places=12) + self.assertGreater(core.residual(world, sp, child, sc, 38.0), 0.01) # the stated roll is part of the mate + self.assertEqual(core.FLIP.tolist(), [[-1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, -1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]) + + def test_what_may_mate(self): + """mate-refusal. Mutants A3 (fits reversed) and A4 (equal at 10 percent).""" + types = self.kit["socketTypes"] + socket = lambda name, kind, size: {"name": name, "type": kind, "size": size, "matrix": np.eye(4)} # noqa: E731 + self.assertRegex(core.mate_refusal(types, socket("p", "flange", 0.1), socket("c", "mount", 0.1)), + r"socket 'c' \(mount, size 0\.1\) and parent socket 'p' \(flange, size 0\.1\) are of different types") + for kind in ("flange", "pivot"): # equal: within 1 percent of the larger, the limit included + self.assertIsNone(core.mate_refusal(types, socket("p", kind, 100.0), socket("c", kind, 99.0))) + self.assertIsNone(core.mate_refusal(types, socket("p", kind, 99.0), socket("c", kind, 100.0))) + self.assertIsNone(core.mate_refusal(types, socket("p", kind, 0.2), socket("c", kind, 0.198))) + self.assertIn("mate at equal sizes", core.mate_refusal(types, socket("p", kind, 100.0), socket("c", kind, 98.99))) + self.assertIn("mate at equal sizes", core.mate_refusal(types, socket("p", kind, 98.99), socket("c", kind, 100.0))) + self.assertIsNone(core.mate_refusal(types, socket("p", "mount", 0.3), socket("c", "mount", 0.3))) # fits: the child at most the parent + self.assertIsNone(core.mate_refusal(types, socket("p", "mount", 0.3), socket("c", "mount", 0.1))) + self.assertIn("it is larger", core.mate_refusal(types, socket("p", "mount", 0.3), socket("c", "mount", 0.3 + 1e-6))) + self.assertIn("it is larger", core.mate_refusal(types, socket("p", "mount", 0.1), socket("c", "mount", 0.3))) + + def test_the_kit_s_own_flanges_do_not_meet_everywhere(self): + """A chamber flange (ribbed_cylinder, 0.16 and up) and the plumbing (pipe_fitting, 0.14 and down) never mate.""" + parts = self.kit["parts"] + drum = core.build(parts["ribbed_cylinder"], {"radius": 0.08}).sockets[1] + pipe = core.build(parts["pipe_fitting"], {"pipe_r": 0.07}).sockets[0] + self.assertEqual((drum["size"], pipe["size"]), (0.16, 0.14)) + self.assertIn("mate at equal sizes", core.mate_refusal(self.kit["socketTypes"], drum, pipe)) + + def test_a_joint_is_two_named_sockets_of_one_kit(self): + """The cross-kit refusal (one kit ships, so no scene can show it) and the unknown-socket refusals.""" + parts = self.kit["parts"] + tank, fitting = core.build(parts["tank"]), core.build(parts["pipe_fitting"]) + sp, sc = core.joint(parts["tank"], tank, "port_b", parts["pipe_fitting"], fitting, "a") + self.assertEqual((sp["name"], sc["name"]), ("port_b", "a")) + other = {**parts["pipe_fitting"], "kit": "hydraulic"} + with self.assertRaisesRegex(core.KitError, "part 'pipe_fitting' is of kit 'hydraulic' and part 'tank' of kit 'mechanical'.*do not mate"): + core.joint(parts["tank"], tank, "port_b", other, fitting, "a") + with self.assertRaisesRegex(core.KitError, "part 'tank' has no socket 'port_c'; its sockets: port_a, port_b, saddle"): + core.joint(parts["tank"], tank, "port_c", parts["pipe_fitting"], fitting, "a") + with self.assertRaisesRegex(core.KitError, "part 'pipe_fitting' has no socket 'd'; its sockets: a, b, c"): + core.joint(parts["tank"], tank, "port_b", parts["pipe_fitting"], fitting, "d") + + +ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report", + "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.boolean", "brokkr_kitbash.apply"] + + class HostFileTests(unittest.TestCase): def setUp(self): self.document = json.loads((SURFACE / "brokkr_kitbash" / "brokkr_actions.json").read_text(encoding="utf-8")) @@ -396,8 +501,7 @@ class HostFileTests(unittest.TestCase): def test_brokkr_admits_the_file(self): """rows-check: Brokkr's own host-file checker.""" at.check_host(self.document, at.table()["charsets"]) - self.assertEqual([row["name"] for row in self.document["actions"]], - ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report"]) + self.assertEqual([row["name"] for row in self.document["actions"]], ROWS) def test_every_row_names_an_operator_and_property_the_add_on_defines(self): source = (SURFACE / "brokkr_kitbash" / "__init__.py").read_text(encoding="utf-8") @@ -421,11 +525,30 @@ class HostFileTests(unittest.TestCase): with self.assertRaises(at.IntentInvalid): at.validate({**envelope, "action": "brokkr_kitbash.place_part", "part": "tank", "object_name": "Tank", "location": "0,0,0"}, host) + def test_the_assembly_rows_take_scalars_inside_their_bounds(self): + host = [{**row, "host": "brokkr_kitbash"} for row in self.document["actions"]] + envelope = {"schema": "brokkr.blender.command_intent.v0", "commandId": "t-1", "requestedBy": "test/driver"} + attach = {**envelope, "action": "brokkr_kitbash.attach", "object_name": "Nozzle", "socket": "mount", "parent_name": "Tee", "parent_socket": "c"} + self.assertEqual(at.validate(attach, host)["roll"], 0) + self.assertEqual(at.validate({**attach, "roll": -360}, host)["roll"], -360) + boolean = {**envelope, "action": "brokkr_kitbash.boolean", "object_name": "Tank", "cutter": "Box"} + 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}): + with self.assertRaises(at.IntentInvalid, msg=str(bad)): + at.validate(bad, host) + for row in self.document["actions"][4:]: + self.assertTrue(all(field["type"] in ("string", "number") for field in row["fields"]), row["name"]) + class OwnershipTests(unittest.TestCase): """The negative patterns of the cut: expressions are walked and never run, the bridge stays out, core needs no Blender, and schemas/ holds no second statement of the kit format.""" - PACKAGE = (r"\beval\(|\bexec\(|\bcompile\(", r"brokkr_bridge") + PACKAGE = (r"\beval\(|\bexec\(|\bcompile\(", r"brokkr_bridge", + r"\bsolver\s*=\s*[\"']MANIFOLD|\buse_self\s*=\s*False", # a boolean is Exact with self-intersection, nothing else + 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 CORE = r"^import bpy|^from bpy|^import bmesh" SCHEMAS = r"brokkr\.kit\.v0" @@ -443,9 +566,24 @@ 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_boolean_and_apply_evaluate_a_modifier_stack(self): + """An Exact Boolean costs about a second a part: report, attach, detach and set_params read stored state only.""" + 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]) + callers = [body.split("(")[0] for body in source.split("class BROKKR_KITBASH_OT_")[1:] if "evaluated_of(" in body] + self.assertEqual(callers, ["boolean", "apply"]) + self.assertEqual(source.count("evaluated_of("), 3) + self.assertEqual(source.count("to_mesh("), 1) + def test_the_patterns_bite(self): - for pattern, planted in zip(self.PACKAGE, ("value = eval(text)", "from brokkr_bridge import x")): - self.assertIsNotNone(re.search(pattern, planted)) + planted = ("value = eval(text)", "from brokkr_bridge import x", 'modifier.solver = "MANIFOLD"', "cutter.hide_render = True", 'obj["kit_parent"] = parent.name') + self.assertEqual(len(planted), len(self.PACKAGE)) + for pattern, text in zip(self.PACKAGE, planted): + self.assertIsNotNone(re.search(pattern, text)) + for text in ("modifier.use_self = False", "cutter.display_type = 'WIRE'", "obj.hide_viewport = True", 'KEY = "kit_parent_name"'): + self.assertTrue(any(re.search(pattern, text) for pattern in self.PACKAGE[2:]), text) + self.assertIsNone(re.search(self.PACKAGE[4], 'PARENT_SOCKET = "kit_parent_socket"')) for planted in ("exec(text)", "code = compile(text, 'kit', 'eval')", "KIT = re.compile('x')"): self.assertIsNotNone(re.search(self.PACKAGE[0], planted)) for planted in ("import bpy", "x = 1\nfrom bpy import props", "import bmesh"): From 03f182fa06932216289612f296ae787ed4ae40f5 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 16:18:39 +0100 Subject: [PATCH 63/63] docs: kitbash.md, assembling parts: connections, drift, boolean and apply Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 125 +++++++++++++++++++++++++++---- 1 file changed, 109 insertions(+), 16 deletions(-) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 8ce9c2c..d5c5d00 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -1,12 +1,12 @@ # Kitbash parts: machinery from kits -`surfaces/blender/brokkr_kitbash` is a Blender add-on that places parametric machine parts from a **kit** and -reports where their **sockets** are. It is the machinery vocabulary of a ship's fixed chassis: the frame, tanks, +`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. 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`. Enable `brokkr_mesh_polish` first; `brokkr_kitbash` refuses to register without it. `brokkr_actions.json` beside -its `__init__.py` lists the four operators agents may run. Every action writes a JSON report to +its `__init__.py` lists the eight operators agents may run. Every action writes a JSON report to `brokkr_mesh_polish_result`, returned in the receipt's `hostResult`. Who owns what: @@ -24,8 +24,11 @@ Who owns what: `set_params` and `report` refuse a part whose world transform scales, mirrors or shears, its parents' 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`. - -This add-on places and re-parameterises parts. Mating sockets, booleans and baking are not here. +- 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"). +- 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 part, end to end @@ -83,6 +86,73 @@ be compared when sockets are mated: `equal` (within 1 percent) or `fits` (the ch 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. +## Assembling parts + +**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, + +```text +matrix_basis = S_parent @ 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` and `set_params` +write it; nothing else should. + +**What may mate** (`core.mate_refusal`): two sockets of one kit and 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. `attach` also +refuses, changing nothing: + +- a child that has a parent (`detach` it; `setObjectParent` with an empty parent clears a parent it was not + attached to); +- a parent that is the child, or is below it (a loop); +- an occupied socket: one a child is already attached to, or the one the part itself is attached by; +- a part that is not a kit part, or is scaled in the world. + +A part may carry a child on every socket but the one it hangs by, so assemblies are trees: tank, then a tee on +its port, then a nozzle on each free flange of the tee. + +**`set_params` keeps an assembly together.** Sockets move with params (an actuator's `rod_end` with `extension`, a +tank's `port_b` with `length`). After the rebuild `set_params` writes the derived `matrix_basis` of the part +itself, if it is attached, and of each part attached to it; what hangs further down follows through parenting. +Before it writes anything it checks every one of those connections against the part's new sockets, and a change +that breaks one (a `pipe_r` that no longer matches the flange it is bolted to) is refused, naming the +connection. + +**Drift.** `setObjectTransform` and `setObjectParent` are Brokkr's own rows and can move or re-parent an attached +child. Reports show it: a part's `connection` is `null`, or + +```json +{"parent": "Tee", "socket": "mount", "parentSocket": "c", "roll": 37.0, "residual": 2.1e-07, "holds": true} +``` + +`residual` is the largest entry of the difference between the socket's world frame and the frame its mate asks +for; `holds` is true when the parent is a kit part of the same kit, both sockets exist, the parent inverse is the +identity and the residual is at most 1e-5. The next `set_params` on the child or on its parent (with any param, +even at its current value) seats it again. A child whose parent was cleared or replaced by something that is not +a kit part reads `holds` false with a `null` residual, and `set_params` refuses it: `detach` clears what is left. +`detach` keeps the part where it stands in the world and leaves the parts attached to it attached. + +**`boolean`** adds a Boolean modifier named `Kit Boolean ` to a kit part, above its `Kit Bevel`, so the +cut's edges are bevelled with the rest. The modifier's object is the cutter; the name is a label. The solver is +always Exact with self-intersection on: a kit part is many overlapping closed shells, and the faster solvers +give wrong solids for those (the 1.8 m tank minus a box keeps 0.254 m3 with self-intersection and 0.008 m3 +without). That costs about a second per part each time the part is evaluated (0.3 s for a pipe fitting, 1.5 s +for a tank, on Blender 5.3), so keep live booleans few and `apply` them when the shape is settled. `boolean` +evaluates the part 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 part's material slots as they are; a cutter that has materials brings them, after +the part's own, on the faces it makes. + +**`apply`** bakes a part: its mesh becomes the evaluated mesh (booleans and bevel applied), every modifier goes, +and `kit_baked` is set. The material slots are the part's own, followed by any a cutter brought. 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`. + ## Expressions Every numeric field of a shape or socket, and `bevel`, is a number or a string over the part's params: @@ -103,19 +173,24 @@ vertices overflow. | --- | --- | --- | | `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: transform, parent, 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. | -| `brokkr_kitbash.report` | `object_name` (default: every kit part) | Each part as the scene has it: kit, part, params, faces, shells, and each socket's world frame. Changes nothing. | +| `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, and a baked part. | +| `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` and `baked`. 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. Reports the child. | +| `brokkr_kitbash.detach` | `object_name` | Clears the part's connection; it stays where it stands. Refuses a part that is not attached. | +| `brokkr_kitbash.boolean` | `object_name`, `cutter`, `operation` (`DIFFERENCE`, `UNION` or `INTERSECT`; default `DIFFERENCE`) | Adds a live Exact Boolean above the Bevel. Refuses a cutter that is the part, is not a mesh, or already cuts it. Reports the part, `booleans: [{cutter, operation}]` and `evaluated`. | +| `brokkr_kitbash.apply` | `object_name` | Bakes the evaluated mesh into the part and clears its modifiers. Refuses a part with no modifiers and a mesh another object shares. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. | `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. A socket in a report is `{name, type, size, matrix}`: `matrix` is the 4x4 as four rows of 6 decimals, in world -space for `place_part`, `set_params` and `report`. Column 2 is the outward normal, column 1 up, column 3 the +space for every action that reports a placed part. Column 2 is the outward normal, column 1 up, column 3 the origin. A report over 16000 characters (what a receipt carries) is refused with advice to name one part or object. -Placement, look and export are Brokkr's own rows: `setObjectTransform`, `assignMaterial`, `exportGltf`. -`place_part` has no location or colour fields. +Placing a loose part, look, hiding a cutter and export are Brokkr's own rows: `setObjectTransform`, +`assignMaterial`, `setObjectVisibility`, `exportGltf`. `place_part` has no location or colour fields. Move an +assembly by its root: an attached part is placed by its connection. ## A recipe @@ -129,14 +204,23 @@ Placement, look and export are Brokkr's own rows: `setObjectTransform`, `assignM {"action": "brokkr_kitbash.place_part", "part": "tank", "object_name": "Tank", "params": "radius=0.3; length=1.4"}, {"action": "setObjectTransform", "targetObjectName": "Tank", "location": [0, 0.6, 0], "rotationEuler": [1.5708, 0, 0]}, {"action": "assignMaterial", "targetObjectName": "Tank", "materialName": "Machinery", "color": [0.35, 0.35, 0.35]}, - {"action": "brokkr_kitbash.place_part", "part": "nozzle", "object_name": "Nozzle"}, - {"action": "brokkr_kitbash.set_params", "object_name": "Nozzle", "params": "exit_r=0.32"}, - {"action": "brokkr_kitbash.report"}, - {"action": "exportGltf", "filepath": "engine.glb", "selection": ["Tank", "Nozzle"]} + {"action": "brokkr_kitbash.place_part", "part": "pipe_fitting", "object_name": "Tee", "params": "pipe_r=0.06"}, + {"action": "brokkr_kitbash.attach", "object_name": "Tee", "socket": "a", "parent_name": "Tank", "parent_socket": "port_b"}, + {"action": "brokkr_kitbash.place_part", "part": "nozzle", "object_name": "Nozzle", "params": "throat_r=0.06"}, + {"action": "brokkr_kitbash.attach", "object_name": "Nozzle", "socket": "mount", "parent_name": "Tee", "parent_socket": "c", "roll": 90}, + {"action": "brokkr_kitbash.set_params", "object_name": "Tank", "params": "length=1.8"}, + {"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.report", "object_name": "Nozzle"}, + {"action": "exportGltf", "filepath": "engine.glb", "selection": ["Tank", "Tee", "Nozzle"]} ]} ``` -The receipts file holds each report in `hostResult`. `tools/turntable_recipe.py` renders the saved `.blend`. +The tank's port is 0.4 of its radius across (0.12 m here), so the tee and the nozzle are given the matching +`pipe_r` and `throat_r`. `set_params` on the tank carries the tee and the nozzle out with its port. The receipts +file holds each report in `hostResult`. `tools/turntable_recipe.py` renders the saved `.blend`. ## The mechanical kit @@ -157,6 +241,13 @@ The receipts file holds each report in `hostResult`. `tools/turntable_recipe.py` `describe` gives the bounds and docs. +Which flanges can meet follows from the sizes: a tank port is `0.4*radius` (0.048 to 0.14), a pipe fitting's +three faces `2*pipe_r` (0.06 to 0.14), a nozzle's mount `2*throat_r` (0.08 to 0.24), and a ribbed cylinder's ends +`2*radius` (0.16 to 0.6). So tanks, fittings and nozzles plumb together, and a ribbed cylinder takes only a +nozzle (throat 0.08 and up) or another ribbed cylinder: its smallest flange is larger than the largest pipe. +Struts and actuators pin together when `0.6*width` equals `0.9*body_r`. Mounts (`fits`) take any part whose +seat is no larger than theirs. + ## Adding a part or a kit Edit the kit's JSON (or add `kits/.v0.json`, whose `kit` field is ``), then run the tests: @@ -170,4 +261,6 @@ python -m unittest discover -s surfaces/blender/tests -p "test_kitbash.py" -v 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_nine_parts_and_three_socket_types`. -The operators are exercised in a real Blender by `tests/live/kitbash.py`. +`MateTests` covers the mate arithmetic and what may mate. The operators are exercised in a real Blender by +`tests/live/kitbash.py` (placing and re-parameterising) and `tests/live/kitbash_assembly.py` (attach, detach, +`set_params` on assemblies, boolean and apply).