"""Official CLEVR Blender 2.79/Cycles release renderer. The release renderer reconstructs a normalized CLEVR world with the official ``base_scene.blend``, shape meshes, material library, and ``utils.py`` loader. The same Cycles invocation emits both the RGB observation and the Object Index pass used as the semantic node map. The lightweight Pillow renderer remains a unit-test helper; it is not an allowed production release backend. """ from __future__ import annotations import io import os import struct import subprocess import tempfile from dataclasses import dataclass from pathlib import Path from typing import Any from ..hashing import canonical_json, canonical_json_hash, sha256_bytes from ..sources.base import World from ..sources.world_ops import hidden_nodes, world_sha256 from .base import ( RenderedAssets, RenderError, _encode_uint32_png, validate_rendered_assets, ) class ClevrBlenderVisibilityError(RenderError): """A structurally valid CLEVR world is not fully observable in the render.""" _BLENDER_TIMEOUT_RETRIES = 2 @dataclass(frozen=True) class ClevrBlenderConfig: blender_executable: Path dataset_gen_root: Path dataset_gen_revision: str | None = None runtime_library_dir: Path | None = None bridge_script: Path | None = None samples: int = 32 timeout_seconds: int = 300 @property def image_generation_dir(self) -> Path: return self.dataset_gen_root / "image_generation" @property def base_scene_blendfile(self) -> Path: return self.image_generation_dir / "data" / "base_scene.blend" @property def shape_dir(self) -> Path: return self.image_generation_dir / "data" / "shapes" @property def material_dir(self) -> Path: return self.image_generation_dir / "data" / "materials" def resolved_bridge_script(self) -> Path: if self.bridge_script is not None: return self.bridge_script return Path(__file__).resolve().parents[3] / "scripts" / "render_clevr_scene_blender.py" @dataclass(frozen=True) class ClevrBlenderResult: rgba_png: bytes node_map_png: bytes node_table: tuple[str, ...] node_pixel_counts: dict[str, int] renderer_spec: dict[str, Any] invocation_sha256: str @property def rgba_sha256(self) -> str: return sha256_bytes(self.rgba_png) @property def node_map_sha256(self) -> str: return sha256_bytes(self.node_map_png) def blender_renderer_spec(config: ClevrBlenderConfig) -> dict[str, Any]: """Return the pinned-input contract recorded alongside a Blender render.""" return { "renderer_name": "clevr_official_blender_bridge", "renderer_version": "2", "backend": "blender_2_79", "observation_output": "rgba_png", "node_map_authority": "cycles_object_index_pass", "blender_release": "2.79b-linux-glibc219-x86_64", "dataset_gen_repository": "facebookresearch/clevr-dataset-gen", "dataset_gen_revision": config.dataset_gen_revision, "base_scene_blendfile": "image_generation/data/base_scene.blend", "shape_dir": "image_generation/data/shapes", "material_dir": "image_generation/data/materials", "bridge_script": "scripts/render_clevr_scene_blender.py", "samples": config.samples, } def _blender_seed(seed: int) -> int: """Map stable unsigned item seeds into Blender 2.79's signed IntProperty.""" return seed & 0x7FFFFFFF def render_clevr_blender_rgba( world: World, *, config: ClevrBlenderConfig, seed: int, width: int = 480, height: int = 320, ) -> ClevrBlenderResult: """Render observation and semantic ownership through official CLEVR assets.""" if world.get("world_schema") != "clevr_world_v1": raise RenderError("Blender bridge requires clevr_world_v1") _validate_config(config) backend_seed = _blender_seed(seed) invocation = { "world_sha256": canonical_json_hash(world), "seed": seed, "backend_seed": backend_seed, "width": width, "height": height, "renderer_spec": blender_renderer_spec(config), } with tempfile.TemporaryDirectory(prefix="explicit-clevr-blender-") as temp: temp_dir = Path(temp) world_path = temp_dir / "world.json" output_path = temp_dir / "rgba.png" node_map_raw_path = temp_dir / "node-map.uint32.raw" world_path.write_text(canonical_json(world), encoding="utf-8") command = [ str(config.blender_executable), "--background", "--python", str(config.resolved_bridge_script()), "--", "--world-json", str(world_path), "--output", str(output_path), "--node-map-raw", str(node_map_raw_path), "--image-generation-dir", str(config.image_generation_dir), "--base-scene", str(config.base_scene_blendfile), "--shape-dir", str(config.shape_dir), "--material-dir", str(config.material_dir), "--seed", str(backend_seed), "--width", str(width), "--height", str(height), "--samples", str(config.samples), ] env = dict(os.environ) if config.runtime_library_dir is not None: existing = env.get("LD_LIBRARY_PATH") env["LD_LIBRARY_PATH"] = ( f"{config.runtime_library_dir}{os.pathsep}{existing}" if existing else str(config.runtime_library_dir) ) completed = _run_blender_command( command, env=env, timeout_seconds=config.timeout_seconds, ) if completed.returncode != 0: stderr = completed.stderr.decode("utf-8", errors="replace")[-4000:] raise RenderError(f"CLEVR Blender bridge exited {completed.returncode}: {stderr}") if not output_path.is_file(): logs = ( completed.stdout.decode("utf-8", errors="replace") + completed.stderr.decode("utf-8", errors="replace") )[-4000:] raise RenderError(f"CLEVR Blender bridge produced no rgba.png: {logs}") rgba_png = output_path.read_bytes() if not rgba_png.startswith(b"\x89PNG\r\n\x1a\n"): raise RenderError("CLEVR Blender bridge output is not a PNG") rgba_png = _canonical_rgba_png(rgba_png, width=width, height=height) node_map_png, node_table, node_pixel_counts = _load_node_map( node_map_raw_path, world=world, width=width, height=height, ) return ClevrBlenderResult( rgba_png=rgba_png, node_map_png=node_map_png, node_table=node_table, node_pixel_counts=node_pixel_counts, renderer_spec=blender_renderer_spec(config), invocation_sha256=canonical_json_hash(invocation), ) def _run_blender_command( command: list[str], *, env: dict[str, str], timeout_seconds: int, ) -> subprocess.CompletedProcess[bytes]: """Retry legacy Blender futex timeouts without changing the render input. Blender 2.79 occasionally remains asleep in a futex wait after many successful background invocations. ``subprocess.run`` kills and reaps the timed-out process, so retrying the exact command in a fresh process preserves the deterministic candidate and renderer inputs. Other launch failures remain immediate hard failures, and persistent timeouts still fail the release instead of silently changing the selected dataset. """ timeout: subprocess.TimeoutExpired | None = None for _attempt in range(_BLENDER_TIMEOUT_RETRIES + 1): try: return subprocess.run( command, env=env, check=False, capture_output=True, timeout=timeout_seconds, ) except subprocess.TimeoutExpired as exc: timeout = exc except OSError as exc: raise RenderError(f"CLEVR Blender bridge failed to start: {exc}") from exc assert timeout is not None raise RenderError( f"CLEVR Blender bridge timed out after {_BLENDER_TIMEOUT_RETRIES + 1} attempts: {timeout}" ) from timeout def _canonical_rgba_png(payload: bytes, *, width: int, height: int) -> bytes: """Strip Blender metadata and encode only the observed RGBA pixels.""" from PIL import Image try: with Image.open(io.BytesIO(payload)) as image: rgba = image.convert("RGBA") rgba.load() except (OSError, ValueError) as exc: raise RenderError(f"CLEVR Blender observation cannot be decoded: {exc}") from exc if rgba.size != (width, height): raise RenderError( f"CLEVR Blender observation dimensions differ: {rgba.size} != {(width, height)}" ) output = io.BytesIO() rgba.save( output, format="PNG", optimize=False, compress_level=9, ) return output.getvalue() def render_clevr_blender_assets( world: World, *, config: ClevrBlenderConfig, renderer_id: str, seed: int, width: int = 480, height: int = 320, ) -> RenderedAssets: """Return the repository's standard asset contract from one Blender render.""" result = render_clevr_blender_rgba( world, config=config, seed=seed, width=width, height=height, ) visible = list(result.node_table[1:]) hidden = sorted(hidden_nodes(world)) spec = result.renderer_spec manifest = { "renderer_id": renderer_id, "renderer_name": str(spec["renderer_name"]), "renderer_version": str(spec["renderer_version"]), "backend": str(spec["backend"]), "backend_version": "2.79b", "font_name": None, "font_sha256": None, "locale": "C", "seed": seed, "backend_seed": _blender_seed(seed), "width": width, "height": height, "world_sha256": world_sha256(world), "rgba_sha256": result.rgba_sha256, "node_map_sha256": result.node_map_sha256, "node_table": list(result.node_table), "visible_node_ids": visible, "hidden_node_ids": hidden, "node_map_coverage": {node_id: result.node_pixel_counts[node_id] for node_id in visible}, "text_glyph_count": 0, "official_clevr_assets": { "base_scene": str(spec["base_scene_blendfile"]), "shape_dir": str(spec["shape_dir"]), "material_dir": str(spec["material_dir"]), "samples": int(spec["samples"]), "node_map_pass": str(spec["node_map_authority"]), }, "invocation_sha256": result.invocation_sha256, } assets = RenderedAssets( rgba_png=result.rgba_png, node_map_png=result.node_map_png, render_manifest=manifest, text_manifest={"world_sha256": world_sha256(world), "glyphs": []}, ) validate_rendered_assets(assets) return assets def _load_node_map( path: Path, *, world: World, width: int, height: int, ) -> tuple[bytes, tuple[str, ...], dict[str, int]]: import numpy as np try: payload = path.read_bytes() except OSError as exc: raise RenderError(f"CLEVR Blender node-map pass is missing: {exc}") from exc if len(payload) < 8: raise RenderError("CLEVR Blender node-map pass is truncated") raw_width, raw_height = struct.unpack("