| name | script-blender-automation |
| description | Write Blender Python scripts for procedural modeling, animation, batch operations, and add-on development using advanced bpy API patterns. Use when automating repetitive modeling or animation tasks, generating procedural geometry from algorithms or data, creating batch rendering pipelines with parameter variations, building custom operators or add-ons, or integrating Blender with external data pipelines and APIs.
|
| license | MIT |
| allowed-tools | Read Write Edit Bash Grep Glob |
| metadata | {"author":"Philipp Thoss","version":"1.1","domain":"blender","complexity":"advanced","language":"Python","tags":"blender, bpy, automation, procedural, animation, batch-processing, add-on"} |
Script Blender Automation
Advanced Blender Python scripting for procedural modeling, keyframe animation, batch operations, operator registration, and add-on development. Covers complex geometry generation, automated workflows, and integration with external data sources.
When to Use
- Automating repetitive modeling or animation tasks
- Generating procedural geometry from algorithms or data
- Creating batch rendering pipelines with parameter variations
- Building custom operators or add-ons for workflow enhancement
- Integrating Blender with external data pipelines or APIs
- Scripting complex animations with mathematical precision
- Developing reusable tools for team workflows
Inputs
| Input | Type | Description | Example |
|---|
| Automation requirements | Specification | Task description, parameters, constraints | Render 100 variations, animate path from data |
| Data sources | Files/APIs | External data for procedural generation | CSV coordinates, JSON parameters, API responses |
| Algorithm definitions | Code/Math | Procedural generation logic | Fractal patterns, parametric curves, L-systems |
| Operator specifications | Requirements | Custom tool behavior and UI | Tool name, properties, modal interaction |
| Animation parameters | Keyframes/Data | Timing, easing, constraints | Frame ranges, interpolation curves |
Procedure
1. Procedural Geometry Generation
Create mesh geometry programmatically using BMesh:
import bpy
import bmesh
import math
def create_parametric_surface(name, u_res=32, v_res=32):
"""Generate parametric surface using mathematical function."""
mesh = bpy.data.meshes.new(name)
obj = bpy.data.objects.new(name, mesh)
bpy.context.collection.objects.link(obj)
bm = bmesh.new()
verts = []
for i in range(u_res):
for j in range(v_res):
u = (i / (u_res - 1)) * 2 * math.pi
v = (j / (v_res - 1)) * math.pi
x = math.sin(v) * math.cos(u)
y = math.sin(v) * math.sin(u)
z = math.cos(v)
vert = bm.verts.new((x, y, z))
verts.append(vert)
bm.verts.ensure_lookup_table()
for i in range(u_res - 1):
for j in range(v_res - 1):
v1 = verts[i * v_res + j]
v2 = verts[(i + 1) * v_res + j]
v3 = verts[(i + 1) * v_res + (j + 1)]
v4 = verts[i * v_res + (j + 1)]
bm.faces.new([v1, v2, v3, v4])
bm.to_mesh(mesh)
bm.free()
return obj
Expected: Complex geometry generated from mathematical functions
On failure: Check BMesh API calls, verify vertex indexing, ensure faces are manifold
2. Keyframe Animation Automation
Script animation keyframes and drivers:
def animate_rotation(obj, start_frame=1, end_frame=250, axis='Z', rotations=2):
"""Animate object rotation over time."""
obj.rotation_euler[2] = 0
obj.keyframe_insert(data_path="rotation_euler", index=2, frame=start_frame)
obj.rotation_euler[2] = rotations * 2 * math.pi
obj.keyframe_insert(data_path="rotation_euler", index=2, frame=end_frame)
if obj.animation_data and obj.animation_data.action:
for fcurve in obj.animation_data.action.fcurves:
if 'rotation_euler' in fcurve.data_path:
for keyframe in fcurve.keyframe_points:
keyframe.interpolation = 'LINEAR'
def animate_material_property(mat, property_path, values, frames):
"""Animate material node values."""
if not mat.node_tree:
return
nodes = mat.node_tree.nodes
emission = nodes.get('Emission')
if emission:
for frame, value in zip(frames, values):
emission.inputs['Strength'].default_value = value
emission.inputs[].keyframe_insert(
data_path=,
frame=frame
)
():
driver = obj.driver_add(property_path)
driver.driver. =
driver.driver.expression = expression
Expected: Keyframes inserted, animation plays back correctly
On failure: Check property paths, verify data_path syntax, ensure objects are keyable
3. Batch Processing Operations
Process multiple objects or files in batch:
import os
from pathlib import Path
def batch_import_and_render(input_dir, output_dir, file_pattern="*.obj"):
"""Import multiple files and render each."""
input_path = Path(input_dir)
output_path = Path(output_dir)
output_path.mkdir(exist_ok=True)
scene = bpy.context.scene
for obj_file in input_path.glob(file_pattern):
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete()
bpy.ops.import_scene.obj(filepath=str(obj_file))
setup_camera()
setup_lighting()
output_file = output_path / f"{obj_file.stem}.png"
scene.render.filepath = str(output_file)
bpy.ops.render.render(write_still=True)
print(f"Rendered: {output_file}")
def batch_material_variation(base_object, colors, output_prefix):
"""Render object with multiple material colors."""
mat = base_object.data.materials[0]
bsdf = mat.node_tree.nodes.get('Principled BSDF')
if not bsdf:
return
for i, color in enumerate(colors):
bsdf.inputs['Base Color'].default_value = color + (,)
bpy.context.scene.render.filepath =
bpy.ops.render.render(write_still=)
Expected: Multiple files processed, renders generated for each variant
On failure: Check file paths exist, verify import operators, handle missing materials
4. Custom Operator Development
Create custom operators for reusable tools:
import bpy
from bpy.props import FloatProperty, IntProperty
class OBJECT_OT_generate_spiral(bpy.types.Operator):
"""Generate a spiral curve"""
bl_idname = "object.generate_spiral"
bl_label = "Generate Spiral"
bl_options = {'REGISTER', 'UNDO'}
radius: FloatProperty(
name="Radius",
description="Spiral radius",
default=2.0,
min=0.1,
max=10.0
)
turns: IntProperty(
name="Turns",
description="Number of spiral turns",
default=5,
min=1,
max=20
)
resolution: IntProperty(
name="Resolution",
description="Points per turn",
default=32,
min=8,
max=128
)
def execute(self, context):
curve = bpy.data.curves.new('Spiral', 'CURVE')
curve.dimensions = '3D'
spline = curve.splines.new('NURBS')
num_points = self.turns * self.resolution
spline.points.add(num_points - 1)
i (num_points):
t = i / .resolution
angle = t * * math.pi
x = .radius * math.cos(angle)
y = .radius * math.sin(angle)
z = t *
spline.points[i].co = (x, y, z, )
obj = bpy.data.objects.new(, curve)
context.collection.objects.link(obj)
obj.select_set()
context.view_layer.objects.active = obj
.report({}, )
{}
():
bpy.utils.register_class(OBJECT_OT_generate_spiral)
():
bpy.utils.unregister_class(OBJECT_OT_generate_spiral)
__name__ == :
register()
Expected: Operator appears in search, executes with proper undo support
On failure: Check bl_idname format (lowercase category.name — a dotted category prefix is required, underscores between words), verify property types
5. Modal Operator for Interactive Tools
Create interactive modal operators:
class OBJECT_OT_modal_scale(bpy.types.Operator):
"""Interactive scaling with mouse"""
bl_idname = "object.modal_scale"
bl_label = "Modal Scale"
bl_options = {'REGISTER', 'UNDO'}
def __init__(self):
self.initial_mouse_x = 0
self.initial_scale = 1.0
def modal(self, context, event):
if event.type == 'MOUSEMOVE':
delta = event.mouse_x - self.initial_mouse_x
scale = self.initial_scale + (delta / 100.0)
scale = max(0.1, scale)
context.active_object.scale = (scale, scale, scale)
elif event.type == 'LEFTMOUSE':
return {'FINISHED'}
elif event.type in {'RIGHTMOUSE', 'ESC'}:
context.active_object.scale = (
self.initial_scale,
self.initial_scale,
self.initial_scale
)
return {}
{}
():
context.active_object:
.initial_mouse_x = event.mouse_x
.initial_scale = context.active_object.scale[]
context.window_manager.modal_handler_add()
{}
:
.report({}, )
{}
Expected: Interactive operator responds to mouse, left-click confirms, ESC cancels
On failure: Check event types, ensure modal handler is added, handle no active object
6. Add-on Packaging
Structure code as installable add-on:
bl_info = {
"name": "Custom Tools",
"author": "Your Name",
"version": (1, 0, 0),
"blender": (3, 0, 0),
"location": "View3D > Add > Mesh",
"description": "Collection of custom modeling tools",
"category": "Add Mesh",
}
import bpy
from .operators import OBJECT_OT_generate_spiral
classes = (
OBJECT_OT_generate_spiral,
)
def menu_func(self, context):
"""Add to menu."""
self.layout.operator(OBJECT_OT_generate_spiral.bl_idname)
def register():
for cls in classes:
bpy.utils.register_class(cls)
bpy.types.VIEW3D_MT_mesh_add.append(menu_func)
def unregister():
bpy.types.VIEW3D_MT_mesh_add.remove(menu_func)
for cls in reversed(classes):
bpy.utils.unregister_class(cls)
if __name__ == "__main__":
register()
Expected: Add-on installs via Preferences, which copies it into Blender's scripts/addons directory — a script left anywhere else is not an installed add-on; operators appear in menus
On failure: Check bl_info format, verify Blender version requirement, ensure all classes listed, import add-on submodules relatively (from .operators import ...) so they resolve against the add-on package rather than a same-named top-level module, and keep the dependency direction one-way (__init__ imports operators, never the reverse) to avoid circular imports
7. Data-Driven Procedural Generation
Generate geometry from external data:
import csv
import json
def create_from_csv(filepath):
"""Generate objects from CSV data."""
with open(filepath, 'r') as f:
reader = csv.DictReader(f)
for row in reader:
name = row['name']
x, y, z = float(row['x']), float(row['y']), float(row['z'])
scale = float(row.get('scale', 1.0))
bpy.ops.mesh.primitive_uv_sphere_add(location=(x, y, z))
obj = bpy.context.active_object
obj.name = name
obj.scale = (scale, scale, scale)
def create_from_json(filepath):
"""Generate scene from JSON configuration."""
with open(filepath, 'r') as f:
config = json.load(f)
for obj_config in config.get('objects', []):
obj_type = obj_config['type']
location = obj_config['location']
if obj_type == 'cube':
bpy.ops.mesh.primitive_cube_add(location=location)
elif obj_type == 'sphere':
bpy.ops.mesh.primitive_uv_sphere_add(location=location)
obj = bpy.context.active_object
obj.name = obj_config.get(, )
obj_config:
mat_name = obj_config[]
mat = bpy.data.materials.get(mat_name)
mat:
obj.data.materials.append(mat)
Expected: Objects created based on external data files
On failure: Validate file format, handle missing fields, provide default values
Validation Checklist
Common Pitfalls
- Context access: Not all operators work in all contexts (viewport vs render)
- BMesh cleanup: Always call
bm.free() after bm.to_mesh() to prevent memory leaks
- Animation keyframe timing: Frame numbers start at 1, not 0
- Driver expression errors: Validate expressions, use safe namespace
- Modal operator blocking: Don't block in modal(), use non-blocking operations
- Version compatibility: API changes between Blender versions, document requirements
Related Skills