# Agentic Blender (bpy + bmesh) visual feedback loop workflow & prompt (HADLEY ST-01)

> Source: <https://gist.github.com/Esdeaz/4813b877dff22dda12b812409efaa446>
> Published: 2026-12-03 16:49:02+00:00

**Key takeaway:** The VFL script renders a fixed six-view contact sheet (3/4 front and rear perspective plus top, front, right, and back orthographic) from a named collection, giving agents a deterministic multi-angle image set to inspect instead of ad-hoc screenshots.

|  | """ | 
|  | Blender Visual Feedback Loop (VFL) — Deterministic Multi-Angle Contact Sheet & Close-Up Capture. | 
|  |  | 
|  | Zero external dependencies beyond Blender's bundled bpy, mathutils, and numpy. | 
|  | Compatible with Blender 3.6, 4.x, and 5.x. | 
|  |  | 
|  | Usage inside Blender MCP (execute_blender_code): | 
|  | import sys, importlib | 
|  | sys.path.insert(0, r"/path/to/vfl/scripts") | 
|  | import vfl_capture; importlib.reload(vfl_capture) | 
|  | out = vfl_capture.capture_contact_sheet( | 
|  | output_path=r"/tmp/vfl_stage1.png", | 
|  | target_collection="Asset_MyModel", | 
|  | mode="clay", | 
|  | ) | 
|  | """ | 
|  |  | 
|  | import math | 
|  | import os | 
|  | import shutil | 
|  | import tempfile | 
|  | import bpy | 
|  | import numpy as np | 
|  | from mathutils import Matrix, Vector | 
|  |  | 
|  | STUDIO_COL_NAME = "_VFL_Studio" | 
|  | _TEMP_PREFIX = "_VFL_TMP_" | 
|  |  | 
|  | # Canonical 6-view inspection grid (3 columns x 2 rows) | 
|  | # Azimuth convention (Blender front = -Y, right = +X, up = +Z): | 
|  | #   0 deg = Front (-Y), +90 deg = Right (+X), 180 deg = Back (+Y), -90 deg = Left (-X) | 
|  | DEFAULT_VIEWS = [ | 
|  | {"label": "3/4 FRONT", "type": "PERSP", "az": 35.0, "el": 22.0, "lens": 50.0}, | 
|  | {"label": "3/4 REAR",  "type": "PERSP", "az": -145.0, "el": 22.0, "lens": 50.0}, | 
|  | {"label": "TOP (+Z)",  "type": "ORTHO", "az": 0.0, "el": 90.0, "up": (0.0, 1.0, 0.0)}, | 
|  | {"label": "FRONT (-Y)", "type": "ORTHO", "az": 0.0, "el": 0.0}, | 
|  | {"label": "RIGHT (+X)", "type": "ORTHO", "az": 90.0, "el": 0.0}, | 
|  | {"label": "BACK (+Y)",  "type": "ORTHO", "az": 180.0, "el": 0.0}, | 
|  | ] | 
|  |  | 
|  | _BG_PRESETS = { | 
|  | "dark":  {"world": (0.045, 0.050, 0.060, 1.0), "world_str": 0.60, "floor": (0.075, 0.080, 0.090, 1.0)}, | 
|  | "mid":   {"world": (0.170, 0.190, 0.220, 1.0), "world_str": 0.85, "floor": (0.130, 0.145, 0.165, 1.0)}, | 
|  | "light": {"world": (0.460, 0.485, 0.520, 1.0), "world_str": 1.00, "floor": (0.360, 0.380, 0.405, 1.0)}, | 
|  | } | 
|  |  | 
|  | # Minimal 5x7 uppercase bitmap font (each int is a 5-bit row, MSB on left) | 
|  | _FONT_5X7 = { | 
|  | "A": (0x0E, 0x11, 0x11, 0x1F, 0x11, 0x11, 0x11), | 
|  | "B": (0x1E, 0x11, 0x11, 0x1E, 0x11, 0x11, 0x1E), | 
|  | "C": (0x0E, 0x11, 0x10, 0x10, 0x10, 0x11, 0x0E), | 
|  | "D": (0x1C, 0x12, 0x11, 0x11, 0x11, 0x12, 0x1C), | 
|  | "E": (0x1F, 0x10, 0x10, 0x1E, 0x10, 0x10, 0x1F), | 
|  | "F": (0x1F, 0x10, 0x10, 0x1E, 0x10, 0x10, 0x10), | 
|  | "G": (0x0E, 0x11, 0x10, 0x17, 0x11, 0x11, 0x0F), | 
|  | "H": (0x11, 0x11, 0x11, 0x1F, 0x11, 0x11, 0x11), | 
|  | "I": (0x0E, 0x04, 0x04, 0x04, 0x04, 0x04, 0x0E), | 
|  | "J": (0x07, 0x02, 0x02, 0x02, 0x12, 0x12, 0x0C), | 
|  | "K": (0x11, 0x12, 0x14, 0x18, 0x14, 0x12, 0x11), | 
|  | "L": (0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x1F), | 
|  | "M": (0x11, 0x1B, 0x15, 0x15, 0x11, 0x11, 0x11), | 
|  | "N": (0x11, 0x19, 0x15, 0x13, 0x11, 0x11, 0x11), | 
|  | "O": (0x0E, 0x11, 0x11, 0x11, 0x11, 0x11, 0x0E), | 
|  | "P": (0x1E, 0x11, 0x11, 0x1E, 0x10, 0x10, 0x10), | 
|  | "Q": (0x0E, 0x11, 0x11, 0x11, 0x15, 0x12, 0x0D), | 
|  | "R": (0x1E, 0x11, 0x11, 0x1E, 0x14, 0x12, 0x11), | 
|  | "S": (0x0F, 0x10, 0x10, 0x0E, 0x01, 0x01, 0x1E), | 
|  | "T": (0x1F, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04), | 
|  | "U": (0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x0E), | 
|  | "V": (0x11, 0x11, 0x11, 0x11, 0x11, 0x0A, 0x04), | 
|  | "W": (0x11, 0x11, 0x11, 0x15, 0x15, 0x1B, 0x11), | 
|  | "X": (0x11, 0x11, 0x0A, 0x04, 0x0A, 0x11, 0x11), | 
|  | "Y": (0x11, 0x11, 0x0A, 0x04, 0x04, 0x04, 0x04), | 
|  | "Z": (0x1F, 0x01, 0x02, 0x04, 0x08, 0x10, 0x1F), | 
|  | "0": (0x0E, 0x11, 0x13, 0x15, 0x19, 0x11, 0x0E), | 
|  | "1": (0x04, 0x0C, 0x04, 0x04, 0x04, 0x04, 0x0E), | 
|  | "2": (0x0E, 0x11, 0x01, 0x06, 0x08, 0x10, 0x1F), | 
|  | "3": (0x1E, 0x01, 0x01, 0x0E, 0x01, 0x01, 0x1E), | 
|  | "4": (0x02, 0x06, 0x0A, 0x12, 0x1F, 0x02, 0x02), | 
|  | "5": (0x1F, 0x10, 0x1E, 0x01, 0x01, 0x11, 0x0E), | 
|  | "6": (0x06, 0x08, 0x10, 0x1E, 0x11, 0x11, 0x0E), | 
|  | "7": (0x1F, 0x01, 0x02, 0x04, 0x08, 0x08, 0x08), | 
|  | "8": (0x0E, 0x11, 0x11, 0x0E, 0x11, 0x11, 0x0E), | 
|  | "9": (0x0E, 0x11, 0x11, 0x0F, 0x01, 0x02, 0x0C), | 
|  | " ": (0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00), | 
|  | "/": (0x01, 0x02, 0x02, 0x04, 0x08, 0x08, 0x10), | 
|  | "-": (0x00, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x00), | 
|  | "+": (0x00, 0x04, 0x04, 0x1F, 0x04, 0x04, 0x00), | 
|  | "(": (0x02, 0x04, 0x08, 0x08, 0x08, 0x04, 0x02), | 
|  | ")": (0x08, 0x04, 0x02, 0x02, 0x02, 0x04, 0x08), | 
|  | "[": (0x0E, 0x08, 0x08, 0x08, 0x08, 0x08, 0x0E), | 
|  | "]": (0x0E, 0x02, 0x02, 0x02, 0x02, 0x02, 0x0E), | 
|  | ":": (0x00, 0x04, 0x04, 0x00, 0x04, 0x04, 0x00), | 
|  | ".": (0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04), | 
|  | ",": (0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x08), | 
|  | "_": (0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F), | 
|  | } | 
|  |  | 
|  |  | 
|  | def _pick_eevee_engine(): | 
|  | """Return the valid EEVEE engine identifier across Blender 3.6, 4.x, and 5.x.""" | 
|  | prop = bpy.types.RenderSettings.bl_rna.properties["engine"] | 
|  | valid = {item.identifier for item in prop.enum_items} | 
|  | for candidate in ("BLENDER_EEVEE_NEXT", "BLENDER_EEVEE", "CYCLES", "BLENDER_WORKBENCH"): | 
|  | if candidate in valid: | 
|  | return candidate | 
|  | return next(iter(valid)) | 
|  |  | 
|  |  | 
|  | def _set_input(node, names, value): | 
|  | for name in names: | 
|  | sock = node.inputs.get(name) | 
|  | if sock is not None: | 
|  | sock.default_value = value | 
|  | return sock | 
|  | return None | 
|  |  | 
|  |  | 
|  | def _ensure_node_tree(datablock): | 
|  | if hasattr(datablock, "use_nodes") and not datablock.use_nodes: | 
|  | datablock.use_nodes = True | 
|  | return datablock.node_tree | 
|  |  | 
|  |  | 
|  | def _collect_collection_meshes(col): | 
|  | meshes = [] | 
|  | for obj in col.objects: | 
|  | if obj.type == "MESH" and not obj.hide_viewport and not obj.hide_render: | 
|  | meshes.append(obj) | 
|  | for child in col.children: | 
|  | if child.name != STUDIO_COL_NAME: | 
|  | meshes.extend(_collect_collection_meshes(child)) | 
|  | return meshes | 
|  |  | 
|  |  | 
|  | def _resolve_target_meshes(target_collection=None, target_objects=None): | 
|  | if target_objects is not None: | 
|  | resolved = [] | 
|  | for item in target_objects: | 
|  | obj = bpy.data.objects.get(item) if isinstance(item, str) else item | 
|  | if obj is not None and obj.type == "MESH": | 
|  | resolved.append(obj) | 
|  | if not resolved: | 
|  | raise ValueError(f"No valid MESH objects found in target_objects={target_objects!r}") | 
|  | return resolved | 
|  |  | 
|  | if target_collection is not None: | 
|  | col = bpy.data.collections.get(target_collection) if isinstance(target_collection, str) else target_collection | 
|  | if col is None: | 
|  | raise ValueError(f"Collection not found: {target_collection!r}") | 
|  | meshes = _collect_collection_meshes(col) | 
|  | if not meshes: | 
|  | raise ValueError(f"No visible MESH objects in collection {col.name!r}") | 
|  | return meshes | 
|  |  | 
|  | studio_col = bpy.data.collections.get(STUDIO_COL_NAME) | 
|  | studio_objs = set(studio_col.all_objects) if studio_col else set() | 
|  | meshes = [ | 
|  | obj for obj in bpy.context.scene.objects | 
|  | if obj.type == "MESH" | 
|  | and obj not in studio_objs | 
|  | and not obj.hide_viewport | 
|  | and not obj.hide_render | 
|  | ] | 
|  | if not meshes: | 
|  | raise ValueError("No visible MESH objects found in the current scene.") | 
|  | return meshes | 
|  |  | 
|  |  | 
|  | def _compute_world_bounds(mesh_objects): | 
|  | """Compute evaluated world-space AABB (respecting modifiers) for mesh_objects.""" | 
|  | depsgraph = bpy.context.evaluated_depsgraph_get() | 
|  | xs, ys, zs = [], [], [] | 
|  |  | 
|  | for obj in mesh_objects: | 
|  | eval_obj = obj.evaluated_get(depsgraph) | 
|  | if eval_obj.data is None or len(eval_obj.data.vertices) == 0: | 
|  | continue | 
|  | mw = eval_obj.matrix_world | 
|  | for corner in eval_obj.bound_box: | 
|  | wc = mw @ Vector(corner) | 
|  | xs.append(wc.x) | 
|  | ys.append(wc.y) | 
|  | zs.append(wc.z) | 
|  |  | 
|  | if not xs: | 
|  | raise ValueError("Target mesh objects have zero vertices.") | 
|  |  | 
|  | bmin = Vector((min(xs), min(ys), min(zs))) | 
|  | bmax = Vector((max(xs), max(ys), max(zs))) | 
|  | center = (bmin + bmax) * 0.5 | 
|  | size = bmax - bmin | 
|  | radius = max(size.length * 0.5, 0.05) | 
|  | corners = [ | 
|  | Vector((x, y, z)) | 
|  | for x in (bmin.x, bmax.x) | 
|  | for y in (bmin.y, bmax.y) | 
|  | for z in (bmin.z, bmax.z) | 
|  | ] | 
|  | return bmin, bmax, center, size, radius, corners | 
|  |  | 
|  |  | 
|  | def _dir_from_az_el(az_deg, el_deg): | 
|  | """Unit vector from target center to camera (az=0 -> -Y front, +90 -> +X right).""" | 
|  | az = math.radians(az_deg) | 
|  | el = math.radians(el_deg) | 
|  | ce = math.cos(el) | 
|  | return Vector((math.sin(az) * ce, -math.cos(az) * ce, math.sin(el))).normalized() | 
|  |  | 
|  |  | 
|  | def _camera_basis(forward, up_hint=None): | 
|  | """Return right-handed orthonormal (right, up, -forward) and 3x3 rotation matrix.""" | 
|  | fwd = forward.normalized() | 
|  | if up_hint is not None: | 
|  | up_ref = Vector(up_hint).normalized() | 
|  | elif abs(fwd.z) > 0.995: | 
|  | up_ref = Vector((0.0, 1.0, 0.0)) | 
|  | else: | 
|  | up_ref = Vector((0.0, 0.0, 1.0)) | 
|  |  | 
|  | right = fwd.cross(up_ref) | 
|  | if right.length < 1e-6: | 
|  | right = fwd.cross(Vector((1.0, 0.0, 0.0))) | 
|  | right.normalize() | 
|  | up = right.cross(fwd).normalized() | 
|  | rot = Matrix((right, up, -fwd)).transposed() | 
|  | return right, up, rot | 
|  |  | 
|  |  | 
|  | def _position_camera(cam_obj, center, corners, radius, view_cfg, aspect, padding=1.22, clip_radius=None): | 
|  | cam_dir = _dir_from_az_el(view_cfg["az"], view_cfg["el"]) | 
|  | forward = -cam_dir | 
|  | right, up, rot = _camera_basis(forward, view_cfg.get("up")) | 
|  |  | 
|  | cam_data = cam_obj.data | 
|  | cam_data.sensor_fit = "HORIZONTAL" | 
|  | cam_data.sensor_width = 36.0 | 
|  | far_ref = max(radius, float(clip_radius or radius)) | 
|  | cam_data.clip_start = max(0.005, radius * 0.005) | 
|  | cam_data.clip_end = max(100.0, far_ref * 60.0) | 
|  |  | 
|  | if view_cfg["type"] == "ORTHO": | 
|  | cam_data.type = "ORTHO" | 
|  | xs = [(c - center).dot(right) for c in corners] | 
|  | ys = [(c - center).dot(up) for c in corners] | 
|  | span_x = max(xs) - min(xs) | 
|  | span_y = max(ys) - min(ys) | 
|  | cam_data.ortho_scale = max(span_x, span_y * aspect, 0.1) * padding | 
|  | dist = radius * 4.0 + 1.0 | 
|  | else: | 
|  | cam_data.type = "PERSP" | 
|  | lens = float(view_cfg.get("lens", 50.0)) | 
|  | cam_data.lens = lens | 
|  | half_tan_x = (cam_data.sensor_width * 0.5) / lens | 
|  | half_tan_y = half_tan_x / aspect | 
|  | dist = radius * 2.5 | 
|  | req = [] | 
|  | for c in corners: | 
|  | v = c - center | 
|  | px = abs(v.dot(right)) | 
|  | py = abs(v.dot(up)) | 
|  | # v.dot(forward) is negative for corners closer to the camera | 
|  | pz = v.dot(forward) | 
|  | d_need = -pz + max(px / half_tan_x, py / half_tan_y) * padding | 
|  | req.append(d_need) | 
|  | dist = max(max(req), radius * 1.1) | 
|  |  | 
|  | loc = center + cam_dir * dist | 
|  | mat = rot.to_4x4() | 
|  | mat.translation = loc | 
|  | cam_obj.matrix_world = mat | 
|  |  | 
|  |  | 
|  | def _build_diagnostic_material(mode, radius): | 
|  | mat = bpy.data.materials.new(name=f"{_TEMP_PREFIX}Mat_{mode}") | 
|  | nt = _ensure_node_tree(mat) | 
|  | nt.nodes.clear() | 
|  |  | 
|  | out = nt.nodes.new("ShaderNodeOutputMaterial") | 
|  |  | 
|  | if mode == "clay": | 
|  | bsdf = nt.nodes.new("ShaderNodeBsdfPrincipled") | 
|  | _set_input(bsdf, ("Roughness",), 0.58) | 
|  | _set_input(bsdf, ("Specular IOR Level", "Specular"), 0.35) | 
|  | _set_input(bsdf, ("Metallic",), 0.0) | 
|  |  | 
|  | ao = nt.nodes.new("ShaderNodeAmbientOcclusion") | 
|  | ao.samples = 8 | 
|  | ao.inputs["Distance"].default_value = max(0.05, radius * 0.28) | 
|  |  | 
|  | mr = nt.nodes.new("ShaderNodeMapRange") | 
|  | mr.inputs["From Min"].default_value = 0.0 | 
|  | mr.inputs["From Max"].default_value = 1.0 | 
|  | mr.inputs["To Min"].default_value = 0.38 | 
|  | mr.inputs["To Max"].default_value = 1.0 | 
|  |  | 
|  | vm = nt.nodes.new("ShaderNodeVectorMath") | 
|  | vm.operation = "SCALE" | 
|  | vm.inputs[0].default_value = (0.58, 0.56, 0.53) | 
|  |  | 
|  | nt.links.new(ao.outputs["AO"], mr.inputs["Value"]) | 
|  | nt.links.new(mr.outputs["Result"], vm.inputs["Scale"]) | 
|  | nt.links.new(vm.outputs["Vector"], bsdf.inputs["Base Color"]) | 
|  | nt.links.new(bsdf.outputs["BSDF"], out.inputs["Surface"]) | 
|  |  | 
|  | elif mode == "wireframe": | 
|  | bsdf = nt.nodes.new("ShaderNodeBsdfPrincipled") | 
|  | _set_input(bsdf, ("Base Color",), (0.68, 0.69, 0.71, 1.0)) | 
|  | _set_input(bsdf, ("Roughness",), 0.65) | 
|  | _set_input(bsdf, ("Specular IOR Level", "Specular"), 0.25) | 
|  |  | 
|  | wire = nt.nodes.new("ShaderNodeWireframe") | 
|  | wire.use_pixel_size = True | 
|  | wire.inputs["Size"].default_value = 1.25 | 
|  |  | 
|  | em = nt.nodes.new("ShaderNodeEmission") | 
|  | em.inputs["Color"].default_value = (0.03, 0.04, 0.06, 1.0) | 
|  | em.inputs["Strength"].default_value = 1.0 | 
|  |  | 
|  | mix = nt.nodes.new("ShaderNodeMixShader") | 
|  | nt.links.new(wire.outputs["Fac"], mix.inputs["Fac"]) | 
|  | nt.links.new(bsdf.outputs["BSDF"], mix.inputs[1]) | 
|  | nt.links.new(em.outputs["Emission"], mix.inputs[2]) | 
|  | nt.links.new(mix.outputs["Shader"], out.inputs["Surface"]) | 
|  |  | 
|  | elif mode == "normals": | 
|  | geom = nt.nodes.new("ShaderNodeNewGeometry") | 
|  |  | 
|  | front_bsdf = nt.nodes.new("ShaderNodeBsdfPrincipled") | 
|  | _set_input(front_bsdf, ("Base Color",), (0.14, 0.44, 0.88, 1.0)) | 
|  | _set_input(front_bsdf, ("Roughness",), 0.55) | 
|  |  | 
|  | back_em = nt.nodes.new("ShaderNodeEmission") | 
|  | back_em.inputs["Color"].default_value = (1.0, 0.04, 0.04, 1.0) | 
|  | back_em.inputs["Strength"].default_value = 1.8 | 
|  |  | 
|  | mix = nt.nodes.new("ShaderNodeMixShader") | 
|  | nt.links.new(geom.outputs["Backfacing"], mix.inputs["Fac"]) | 
|  | nt.links.new(front_bsdf.outputs["BSDF"], mix.inputs[1]) | 
|  | nt.links.new(back_em.outputs["Emission"], mix.inputs[2]) | 
|  | nt.links.new(mix.outputs["Shader"], out.inputs["Surface"]) | 
|  |  | 
|  | return mat | 
|  |  | 
|  |  | 
|  | def _build_studio_world(bg_tone): | 
|  | preset = _BG_PRESETS.get(bg_tone, _BG_PRESETS["mid"]) | 
|  | world = bpy.data.worlds.new(name=f"{_TEMP_PREFIX}World") | 
|  | nt = _ensure_node_tree(world) | 
|  | nt.nodes.clear() | 
|  | bg = nt.nodes.new("ShaderNodeBackground") | 
|  | bg.inputs["Color"].default_value = preset["world"] | 
|  | bg.inputs["Strength"].default_value = preset["world_str"] | 
|  | out = nt.nodes.new("ShaderNodeOutputWorld") | 
|  | nt.links.new(bg.outputs["Background"], out.inputs["Surface"]) | 
|  | return world | 
|  |  | 
|  |  | 
|  | def _create_area_light(col, name, center, radius, az_deg, el_deg, dist_mult, size_mult, energy_mult, color): | 
|  | ldata = bpy.data.lights.new(name=name, type="AREA") | 
|  | ldata.shape = "RECTANGLE" | 
|  | ldata.size = max(0.3, radius * size_mult) | 
|  | ldata.size_y = max(0.3, radius * size_mult * 0.75) | 
|  | ldata.energy = max(5.0, energy_mult * (radius ** 2)) | 
|  | ldata.color = color | 
|  |  | 
|  | lobj = bpy.data.objects.new(name=name, object_data=ldata) | 
|  | col.objects.link(lobj) | 
|  |  | 
|  | direction = _dir_from_az_el(az_deg, el_deg) | 
|  | loc = center + direction * (radius * dist_mult) | 
|  | _, _, rot = _camera_basis(-direction) | 
|  | mat = rot.to_4x4() | 
|  | mat.translation = loc | 
|  | lobj.matrix_world = mat | 
|  | return lobj | 
|  |  | 
|  |  | 
|  | def _create_ground_plane(col, center, radius, ground_z, bg_tone): | 
|  | preset = _BG_PRESETS.get(bg_tone, _BG_PRESETS["mid"]) | 
|  | half = max(radius * 5.0, 2.5) | 
|  | mesh = bpy.data.meshes.new(name=f"{_TEMP_PREFIX}GroundMesh") | 
|  | verts = [(-half, -half, 0.0), (half, -half, 0.0), (half, half, 0.0), (-half, half, 0.0)] | 
|  | mesh.from_pydata(verts, [], [(0, 1, 2, 3)]) | 
|  | mesh.update() | 
|  |  | 
|  | mat = bpy.data.materials.new(name=f"{_TEMP_PREFIX}GroundMat") | 
|  | nt = _ensure_node_tree(mat) | 
|  | nt.nodes.clear() | 
|  | bsdf = nt.nodes.new("ShaderNodeBsdfPrincipled") | 
|  | _set_input(bsdf, ("Base Color",), preset["floor"]) | 
|  | _set_input(bsdf, ("Roughness",), 0.88) | 
|  | _set_input(bsdf, ("Specular IOR Level", "Specular"), 0.15) | 
|  | out = nt.nodes.new("ShaderNodeOutputMaterial") | 
|  | nt.links.new(bsdf.outputs["BSDF"], out.inputs["Surface"]) | 
|  | mesh.materials.append(mat) | 
|  |  | 
|  | obj = bpy.data.objects.new(name=f"{_TEMP_PREFIX}Ground", object_data=mesh) | 
|  | obj.location = (center.x, center.y, ground_z) | 
|  | col.objects.link(obj) | 
|  | return obj, mat | 
|  |  | 
|  |  | 
|  | def cleanup_studio(): | 
|  | """Remove any leftover _VFL_Studio collection and temporary VFL datablocks.""" | 
|  | col = bpy.data.collections.get(STUDIO_COL_NAME) | 
|  | if col is not None: | 
|  | for obj in list(col.objects): | 
|  | bpy.data.objects.remove(obj, do_unlink=True) | 
|  | bpy.data.collections.remove(col) | 
|  |  | 
|  | for container in ( | 
|  | bpy.data.objects, | 
|  | bpy.data.cameras, | 
|  | bpy.data.lights, | 
|  | bpy.data.meshes, | 
|  | bpy.data.materials, | 
|  | bpy.data.worlds, | 
|  | bpy.data.images, | 
|  | ): | 
|  | for item in list(container): | 
|  | if item.name.startswith(_TEMP_PREFIX): | 
|  | container.remove(item) | 
|  |  | 
|  |  | 
|  | def _set_raw_colorspace(img): | 
|  | for cs in ("Non-Color", "Raw"): | 
|  | try: | 
|  | img.colorspace_settings.name = cs | 
|  | return | 
|  | except Exception: | 
|  | continue | 
|  |  | 
|  |  | 
|  | def _load_tile_array(filepath): | 
|  | img = bpy.data.images.load(filepath, check_existing=False) | 
|  | try: | 
|  | _set_raw_colorspace(img) | 
|  | w, h = int(img.size[0]), int(img.size[1]) | 
|  | buf = np.empty(w * h * 4, dtype=np.float32) | 
|  | img.pixels.foreach_get(buf) | 
|  | return buf.reshape((h, w, 4)) | 
|  | finally: | 
|  | bpy.data.images.remove(img) | 
|  |  | 
|  |  | 
|  | def _draw_label(arr, text, x0, y_top, scale=2): | 
|  | """Draw a high-contrast bitmap label in bottom-up RGBA float array arr (H, W, 4).""" | 
|  | text = text.upper() | 
|  | h, w, _ = arr.shape | 
|  | char_w = 6 * scale | 
|  | char_h = 7 * scale | 
|  | pad_x = 6 | 
|  | pad_y = 5 | 
|  | box_w = len(text) * char_w - scale + pad_x * 2 | 
|  | box_h = char_h + pad_y * 2 | 
|  |  | 
|  | bx0 = max(0, x0) | 
|  | bx1 = min(w, x0 + box_w) | 
|  | by1 = min(h, y_top + 1) | 
|  | by0 = max(0, by1 - box_h) | 
|  |  | 
|  | if bx1 > bx0 and by1 > by0: | 
|  | arr[by0:by1, bx0:bx1, :3] = arr[by0:by1, bx0:bx1, :3] * 0.22 + 0.04 | 
|  | arr[by0:by1, bx0:bx1, 3] = 1.0 | 
|  |  | 
|  | cursor_x = x0 + pad_x | 
|  | text_top = by1 - 1 - pad_y | 
|  | for ch in text: | 
|  | glyph = _FONT_5X7.get(ch, _FONT_5X7[" "]) | 
|  | for gy, row_bits in enumerate(glyph): | 
|  | for gx in range(5): | 
|  | if row_bits & (1 << (4 - gx)): | 
|  | px0 = cursor_x + gx * scale | 
|  | px1 = min(w, px0 + scale) | 
|  | py_hi = text_top - gy * scale + 1 | 
|  | py_lo = max(0, py_hi - scale) | 
|  | if 0 <= px0 < w and py_hi > py_lo: | 
|  | arr[py_lo:py_hi, px0:px1, :3] = (0.96, 0.97, 0.99) | 
|  | arr[py_lo:py_hi, px0:px1, 3] = 1.0 | 
|  | cursor_x += char_w | 
|  |  | 
|  |  | 
|  | def _save_rgba_array(arr, output_path): | 
|  | h, w, _ = arr.shape | 
|  | out_dir = os.path.dirname(os.path.abspath(output_path)) | 
|  | if out_dir: | 
|  | os.makedirs(out_dir, exist_ok=True) | 
|  | img = bpy.data.images.new(name=f"{_TEMP_PREFIX}Sheet", width=w, height=h, alpha=True) | 
|  | try: | 
|  | _set_raw_colorspace(img) | 
|  | img.pixels.foreach_set(np.ascontiguousarray(arr, dtype=np.float32).ravel()) | 
|  | img.filepath_raw = output_path | 
|  | img.file_format = "PNG" | 
|  | img.save() | 
|  | finally: | 
|  | bpy.data.images.remove(img) | 
|  |  | 
|  |  | 
|  | def _swap_materials(mesh_objects, override_mat): | 
|  | """Temporarily replace materials on mesh_objects (safe for shared/instanced meshes).""" | 
|  | # Pass 1: read-only snapshot before any mutation | 
|  | orig_mesh_mats = {} | 
|  | orig_obj_slots = [] | 
|  | for obj in mesh_objects: | 
|  | mesh = obj.data | 
|  | if mesh not in orig_mesh_mats: | 
|  | orig_mesh_mats[mesh] = list(mesh.materials) | 
|  | orig_obj_slots.append((obj, [(s.link, s.material) for s in obj.material_slots])) | 
|  |  | 
|  | # Pass 2: apply override | 
|  | for mesh in orig_mesh_mats: | 
|  | if len(mesh.materials) == 0: | 
|  | mesh.materials.append(override_mat) | 
|  | else: | 
|  | for i in range(len(mesh.materials)): | 
|  | mesh.materials[i] = override_mat | 
|  | for obj, _ in orig_obj_slots: | 
|  | for slot in obj.material_slots: | 
|  | if slot.link == "OBJECT": | 
|  | slot.material = override_mat | 
|  |  | 
|  | return orig_mesh_mats, orig_obj_slots | 
|  |  | 
|  |  | 
|  | def _restore_materials(saved): | 
|  | orig_mesh_mats, orig_obj_slots = saved | 
|  | for mesh, mats in orig_mesh_mats.items(): | 
|  | mesh.materials.clear() | 
|  | for m in mats: | 
|  | mesh.materials.append(m) | 
|  | for obj, slots in orig_obj_slots: | 
|  | for idx, (link, mat) in enumerate(slots): | 
|  | if idx < len(obj.material_slots): | 
|  | obj.material_slots[idx].link = link | 
|  | if link == "OBJECT": | 
|  | obj.material_slots[idx].material = mat | 
|  |  | 
|  |  | 
|  | def _capture_views( | 
|  | output_path, | 
|  | mesh_objects, | 
|  | center, | 
|  | corners, | 
|  | radius, | 
|  | views, | 
|  | mode="clay", | 
|  | tile_size=(640, 480), | 
|  | grid_cols=3, | 
|  | padding=1.22, | 
|  | bg_tone="mid", | 
|  | samples=16, | 
|  | ground_plane=True, | 
|  | ground_z=0.0, | 
|  | use_scene_lights=False, | 
|  | draw_labels=True, | 
|  | studio_center=None, | 
|  | studio_radius=None, | 
|  | ): | 
|  | scene = bpy.context.scene | 
|  | render = scene.render | 
|  | cleanup_studio() | 
|  |  | 
|  | light_center = studio_center if studio_center is not None else center | 
|  | light_radius = max(float(studio_radius), radius) if studio_radius is not None else radius | 
|  |  | 
|  | # Snapshot mutable scene state | 
|  | orig = { | 
|  | "engine": render.engine, | 
|  | "res_x": render.resolution_x, | 
|  | "res_y": render.resolution_y, | 
|  | "res_pct": render.resolution_percentage, | 
|  | "pix_x": render.pixel_aspect_x, | 
|  | "pix_y": render.pixel_aspect_y, | 
|  | "border": render.use_border, | 
|  | "crop": render.use_crop_to_border, | 
|  | "filepath": render.filepath, | 
|  | "file_format": render.image_settings.file_format, | 
|  | "color_mode": render.image_settings.color_mode, | 
|  | "color_depth": render.image_settings.color_depth, | 
|  | "film_transparent": render.film_transparent, | 
|  | "camera": scene.camera, | 
|  | "world": scene.world, | 
|  | "exposure": scene.view_settings.exposure, | 
|  | "gamma": scene.view_settings.gamma, | 
|  | "eevee_samples": getattr(scene.eevee, "taa_render_samples", None), | 
|  | "cycles_samples": getattr(scene.cycles, "samples", None), | 
|  | } | 
|  |  | 
|  | hidden_lights = [] | 
|  | saved_materials = [] | 
|  | tmp_dir = tempfile.mkdtemp(prefix="vfl_cap_") | 
|  |  | 
|  | try: | 
|  | studio_col = bpy.data.collections.new(STUDIO_COL_NAME) | 
|  | scene.collection.children.link(studio_col) | 
|  |  | 
|  | # Configure render settings | 
|  | render.engine = _pick_eevee_engine() | 
|  | render.resolution_x = int(tile_size[0]) | 
|  | render.resolution_y = int(tile_size[1]) | 
|  | render.resolution_percentage = 100 | 
|  | render.pixel_aspect_x = 1.0 | 
|  | render.pixel_aspect_y = 1.0 | 
|  | render.use_border = False | 
|  | render.use_crop_to_border = False | 
|  | render.film_transparent = False | 
|  | render.image_settings.file_format = "PNG" | 
|  | render.image_settings.color_mode = "RGBA" | 
|  | render.image_settings.color_depth = "8" | 
|  | scene.view_settings.exposure = 0.0 | 
|  | scene.view_settings.gamma = 1.0 | 
|  |  | 
|  | if hasattr(scene.eevee, "taa_render_samples"): | 
|  | scene.eevee.taa_render_samples = int(samples) | 
|  | if hasattr(scene.cycles, "samples"): | 
|  | scene.cycles.samples = int(samples) | 
|  |  | 
|  | # Studio world & 3-point lighting (unless shaded + use_scene_lights=True) | 
|  | if not (mode == "shaded" and use_scene_lights): | 
|  | for obj in scene.objects: | 
|  | if obj.type == "LIGHT" and not obj.hide_render: | 
|  | obj.hide_render = True | 
|  | hidden_lights.append(obj) | 
|  | scene.world = _build_studio_world(bg_tone) | 
|  | _create_area_light(studio_col, f"{_TEMP_PREFIX}Key",  light_center, light_radius,   42.0, 40.0, 2.6, 1.4, 42.0, (1.00, 0.97, 0.92)) | 
|  | _create_area_light(studio_col, f"{_TEMP_PREFIX}Fill", light_center, light_radius,  -55.0, 22.0, 2.8, 2.2, 18.0, (0.86, 0.92, 1.00)) | 
|  | _create_area_light(studio_col, f"{_TEMP_PREFIX}Rim",  light_center, light_radius,  155.0, 38.0, 2.6, 1.6, 28.0, (0.98, 0.99, 1.00)) | 
|  |  | 
|  | # Ground plane at ground_z (exposes floating or sunk geometry immediately) | 
|  | if ground_plane: | 
|  | _create_ground_plane(studio_col, light_center, light_radius, ground_z, bg_tone) | 
|  |  | 
|  | # Diagnostic material override (skip for shaded) | 
|  | if mode in ("clay", "wireframe", "normals"): | 
|  | diag_mat = _build_diagnostic_material(mode, light_radius) | 
|  | saved_materials = _swap_materials(mesh_objects, diag_mat) | 
|  |  | 
|  | # Studio camera | 
|  | cam_data = bpy.data.cameras.new(name=f"{_TEMP_PREFIX}Cam") | 
|  | cam_obj = bpy.data.objects.new(name=f"{_TEMP_PREFIX}Cam", object_data=cam_data) | 
|  | studio_col.objects.link(cam_obj) | 
|  | scene.camera = cam_obj | 
|  |  | 
|  | aspect = float(tile_size[0]) / float(tile_size[1]) | 
|  | rendered_tiles = [] | 
|  |  | 
|  | for idx, vcfg in enumerate(views): | 
|  | _position_camera(cam_obj, center, corners, radius, vcfg, aspect, padding=padding, clip_radius=light_radius) | 
|  | tile_path = os.path.join(tmp_dir, f"tile_{idx:02d}.png") | 
|  | render.filepath = tile_path | 
|  | bpy.ops.render.render(write_still=True) | 
|  | rendered_tiles.append((vcfg.get("label", f"VIEW {idx+1}"), _load_tile_array(tile_path))) | 
|  |  | 
|  | # Stitch tiles into contact sheet (or single frame) | 
|  | if len(rendered_tiles) == 1: | 
|  | label, arr = rendered_tiles[0] | 
|  | if draw_labels and label: | 
|  | _draw_label(arr, f"{label} [{mode}]", 10, arr.shape[0] - 11, scale=2) | 
|  | _save_rgba_array(arr, output_path) | 
|  | else: | 
|  | th, tw, _ = rendered_tiles[0][1].shape | 
|  | cols = min(int(grid_cols), len(rendered_tiles)) | 
|  | rows = math.ceil(len(rendered_tiles) / cols) | 
|  | gap = 4 | 
|  | out_w = cols * tw + (cols + 1) * gap | 
|  | out_h = rows * th + (rows + 1) * gap | 
|  |  | 
|  | canvas = np.zeros((out_h, out_w, 4), dtype=np.float32) | 
|  | canvas[:, :, :3] = (0.08, 0.09, 0.11) | 
|  | canvas[:, :, 3] = 1.0 | 
|  |  | 
|  | for idx, (label, tile_arr) in enumerate(rendered_tiles): | 
|  | r = idx // cols | 
|  | c = idx % cols | 
|  | # Bottom-up row placement: row 0 is at the top of the image | 
|  | x0 = gap + c * (tw + gap) | 
|  | y0 = gap + (rows - 1 - r) * (th + gap) | 
|  | canvas[y0:y0 + th, x0:x0 + tw, :] = tile_arr | 
|  | if draw_labels and label: | 
|  | badge = f"{label} [{mode}]" if idx == 0 else label | 
|  | _draw_label(canvas, badge, x0 + 8, y0 + th - 9, scale=2) | 
|  |  | 
|  | _save_rgba_array(canvas, output_path) | 
|  |  | 
|  | return os.path.abspath(output_path) | 
|  |  | 
|  | finally: | 
|  | if saved_materials: | 
|  | _restore_materials(saved_materials) | 
|  | for lobj in hidden_lights: | 
|  | lobj.hide_render = False | 
|  |  | 
|  | render.engine = orig["engine"] | 
|  | render.resolution_x = orig["res_x"] | 
|  | render.resolution_y = orig["res_y"] | 
|  | render.resolution_percentage = orig["res_pct"] | 
|  | render.pixel_aspect_x = orig["pix_x"] | 
|  | render.pixel_aspect_y = orig["pix_y"] | 
|  | render.use_border = orig["border"] | 
|  | render.use_crop_to_border = orig["crop"] | 
|  | render.filepath = orig["filepath"] | 
|  | render.image_settings.file_format = orig["file_format"] | 
|  | render.image_settings.color_mode = orig["color_mode"] | 
|  | render.image_settings.color_depth = orig["color_depth"] | 
|  | render.film_transparent = orig["film_transparent"] | 
|  | scene.camera = orig["camera"] | 
|  | scene.world = orig["world"] | 
|  | scene.view_settings.exposure = orig["exposure"] | 
|  | scene.view_settings.gamma = orig["gamma"] | 
|  | if orig["eevee_samples"] is not None and hasattr(scene.eevee, "taa_render_samples"): | 
|  | scene.eevee.taa_render_samples = orig["eevee_samples"] | 
|  | if orig["cycles_samples"] is not None and hasattr(scene.cycles, "samples"): | 
|  | scene.cycles.samples = orig["cycles_samples"] | 
|  |  | 
|  | cleanup_studio() | 
|  | shutil.rmtree(tmp_dir, ignore_errors=True) | 
|  |  | 
|  |  | 
|  | def capture_contact_sheet( | 
|  | output_path, | 
|  | target_collection=None, | 
|  | target_objects=None, | 
|  | mode="clay", | 
|  | tile_size=(640, 480), | 
|  | grid_cols=3, | 
|  | padding=1.22, | 
|  | bg_tone="mid", | 
|  | samples=16, | 
|  | ground_plane=True, | 
|  | ground_z=0.0, | 
|  | use_scene_lights=False, | 
|  | views=None, | 
|  | ): | 
|  | """Render a labeled 6-view inspection contact sheet and return its absolute path.""" | 
|  | if mode not in ("clay", "shaded", "wireframe", "normals"): | 
|  | raise ValueError(f"Unsupported mode {mode!r}; use 'clay', 'shaded', 'wireframe', or 'normals'.") | 
|  | mesh_objects = _resolve_target_meshes(target_collection=target_collection, target_objects=target_objects) | 
|  | _, _, center, _, radius, corners = _compute_world_bounds(mesh_objects) | 
|  | return _capture_views( | 
|  | output_path=output_path, | 
|  | mesh_objects=mesh_objects, | 
|  | center=center, | 
|  | corners=corners, | 
|  | radius=radius, | 
|  | views=views or DEFAULT_VIEWS, | 
|  | mode=mode, | 
|  | tile_size=tile_size, | 
|  | grid_cols=grid_cols, | 
|  | padding=padding, | 
|  | bg_tone=bg_tone, | 
|  | samples=samples, | 
|  | ground_plane=ground_plane, | 
|  | ground_z=ground_z, | 
|  | use_scene_lights=use_scene_lights, | 
|  | ) | 
|  |  | 
|  |  | 
|  | def capture_closeup( | 
|  | output_path, | 
|  | target, | 
|  | target_collection=None, | 
|  | mode="shaded", | 
|  | azimuth_deg=35.0, | 
|  | elevation_deg=18.0, | 
|  | lens=65.0, | 
|  | size=(1024, 768), | 
|  | padding=1.25, | 
|  | bg_tone="mid", | 
|  | samples=24, | 
|  | ground_plane=True, | 
|  | ground_z=0.0, | 
|  | use_scene_lights=False, | 
|  | label=None, | 
|  | ): | 
|  | """ | 
|  | Render a high-res close-up framed on: | 
|  | - target = object name (str), | 
|  | - target = list of object names / bpy.types.Object, or | 
|  | - target = ((x, y, z), radius) world coordinate tuple. | 
|  | """ | 
|  | if mode not in ("clay", "shaded", "wireframe", "normals"): | 
|  | raise ValueError(f"Unsupported mode {mode!r}; use 'clay', 'shaded', 'wireframe', or 'normals'.") | 
|  | all_meshes = _resolve_target_meshes(target_collection=target_collection) | 
|  | _, _, studio_center, _, studio_radius, _ = _compute_world_bounds(all_meshes) | 
|  | if isinstance(target, tuple) and len(target) == 2 and isinstance(target[0], (tuple, list, Vector)): | 
|  | center = Vector(target[0]) | 
|  | radius = max(float(target[1]), 0.03) | 
|  | corners = [ | 
|  | center + Vector((dx, dy, dz)) | 
|  | for dx in (-radius, radius) | 
|  | for dy in (-radius, radius) | 
|  | for dz in (-radius, radius) | 
|  | ] | 
|  | view_label = label or "CLOSEUP" | 
|  | else: | 
|  | focus_list = [target] if isinstance(target, (str, bpy.types.Object)) else list(target) | 
|  | focus_meshes = _resolve_target_meshes(target_objects=focus_list) | 
|  | _, _, center, _, radius, corners = _compute_world_bounds(focus_meshes) | 
|  | view_label = label or (focus_meshes[0].name if len(focus_meshes) == 1 else "CLOSEUP") | 
|  |  | 
|  | view = {"label": view_label, "type": "PERSP", "az": float(azimuth_deg), "el": float(elevation_deg), "lens": float(lens)} | 
|  | return _capture_views( | 
|  | output_path=output_path, | 
|  | mesh_objects=all_meshes, | 
|  | center=center, | 
|  | corners=corners, | 
|  | radius=radius, | 
|  | views=[view], | 
|  | mode=mode, | 
|  | tile_size=size, | 
|  | grid_cols=1, | 
|  | padding=padding, | 
|  | bg_tone=bg_tone, | 
|  | samples=samples, | 
|  | ground_plane=ground_plane, | 
|  | ground_z=ground_z, | 
|  | use_scene_lights=use_scene_lights, | 
|  | studio_center=studio_center, | 
|  | studio_radius=studio_radius, | 
|  | ) |
