Agentic Blender (bpy + bmesh) visual feedback loop workflow & prompt (HADLEY ST-01) A developer published a Blender Visual Feedback Loop (VFL) script that captures a deterministic six-view contact sheet and close-up renders of a 3D asset using only Blender's bundled bpy, mathutils, and numpy modules. The tool, designed to run inside Blender MCP via execute_blender_code, supports Blender 3.6 through 5.x and offers clay-render modes with configurable dark, mid, and light backgrounds plus a built-in 5x7 bitmap font for view labels. It is intended to give agentic modeling workflows a repeatable visual inspection grid. | | """ | | | 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, | | | |