From cf627e950bd4e3976cfebb288cf409d96e1af1f6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 01:58:11 +0100 Subject: [PATCH] Blender add-on: exportGltf stages and never overwrites, render GL refusal probes a real render, meshType refused off MESH exportGltf writes into a staging folder and moves files into place, refusing any taken name (textures included); a failed export leaves nothing and the name is retryable. The headless GL refusal renders one pixel in a child Blender instead of loading libEGL. meshType on a non-MESH objectType is refused. Live scripts for both run on Blender 5.3.0; docs and the preference text now name exportGltf. The symlink test skips when the OS denies symlinks. Co-Authored-By: Claude Sonnet 5.5 --- docs/provider-contract.md | 1 + surfaces/blender/brokkr_bridge/__init__.py | 2 +- .../blender/brokkr_bridge/blender_target.py | 126 ++++++++++----- 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 | 144 ++++++++++++++---- 10 files changed, 581 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/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..f71fd3b 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -6,8 +6,11 @@ import json import math import os import re +import shutil import struct +import subprocess import sys +import tempfile import uuid import zlib from array import array @@ -42,10 +45,11 @@ 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 # Actions that only read the scene and so push no undo step. READ_ACTIONS = ("look",) @@ -732,8 +736,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)) @@ -892,30 +897,57 @@ 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 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 = Path(tempfile.mkdtemp(prefix=".brokkr-export-", dir=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()) + 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: + (path.parent / relative).parent.mkdir(parents=True, exist_ok=True) + os.rename(stage / relative, path.parent / relative) + except BaseException: + if stage is not None: + shutil.rmtree(stage, ignore_errors=True) + for folder in made: # deepest first: only the folders this call made, only if still empty + try: + folder.rmdir() + except OSError: + pass + raise + 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 +1056,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 +1547,29 @@ def _load_cultmesh(cultlib_py_src: str) -> tuple[Any, Any]: return cultmesh_py, cultcache_py +GL_PROBE_SCRIPT = Path(__file__).with_name("gl_probe.py") # runs inside the child Blender + + @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 +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. Probed once per binary and engine and cached for the + life of the process; an exit with no completion marker, a signal, or a hang is the failure.""" + if not binary or not os.path.isfile(binary): + return "the Blender binary is unknown, so rendering could not be probed" + command = [binary, "--background", "--factory-startup", "--python-exit-code", "1", + "--python", str(GL_PROBE_SCRIPT), "--", engine] try: - ctypes.CDLL(GL_RUNTIME_LIBRARY) - except OSError: - return GL_RUNTIME_LIBRARY - return None + done = subprocess.run(command, capture_output=True, text=True, timeout=GL_PROBE_TIMEOUT_SECONDS, check=False) + except subprocess.TimeoutExpired: + return f"a one-pixel test render did not finish in {GL_PROBE_TIMEOUT_SECONDS} s" + except OSError as exc: + return f"the one-pixel test render could not start: {exc}" + if done.returncode == 0 and "BROKKR_GL_PROBE_OK" in done.stdout: + return None + return f"a one-pixel test render exited with status {done.returncode}" 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..48314fc 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. 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..1429394 --- /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-mp8mip04\\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-mp8mip04\\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-mp8mip04\\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-mp8mip04\\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-mp8mip04\\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..030a3f6 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,45 @@ 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_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 +471,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 +511,55 @@ 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 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, "run", wraps=bt.subprocess.run) 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):