Sub topic 15
Building the setup with Python
This chapter turns the lighting setup from earlier chapters into a script. The result is one file that builds the lamps, the aim constraints, the HDRI World and the render settings. You can run it again on any scene and get the same lighting.
I assume you know the earlier chapters' vocabulary (power, size, key/fill/rim, Environment Texture and Background nodes). I also assume you can run a script from Blender's Scripting workspace.
Why script lighting
A scripted rig has three advantages over one built by hand:
- Repeatability. You can apply the same rig to many scenes or many shots.
- Parameters in one place. Power, size and HDRI rotation become variables, so a lighting sweep is a loop.
- Headless rendering. A script can run without the interface, for example on a render machine.
The script runs against Blender's data API, bpy.data. The model has two layers, and mixing them up is the most common source of errors:
- A data block holds the properties. A light data block (
bpy.data.lights) has energy, color and size. - An object (
bpy.data.objects) holds the location, rotation and constraints, and points at the data block.
Creating a light therefore takes two steps: create the data, then create an object that uses it and link the object into a collection.
Lamps: one helper, three lights
A single helper keeps the three-point rig short. It reuses existing data blocks by name. Without that check, each run would add Key.001, Key.002 and so on.
import math
import bpy
scene = bpy.context.scene
def get_or_create_light(name, kind):
"""Return an object named `name` whose light data has type `kind`."""
data = bpy.data.lights.get(name) or bpy.data.lights.new(name=name, type=kind)
data.type = kind
obj = bpy.data.objects.get(name) or bpy.data.objects.new(name, data)
obj.data = data
if not obj.users_collection:
scene.collection.objects.link(obj)
return obj
def aim_at(obj, target):
"""Point the light's local -Z axis at `target` with a Track To constraint."""
con = obj.constraints.get("Aim") or obj.constraints.new(type='TRACK_TO')
con.name = "Aim"
con.target = target
con.track_axis = 'TRACK_NEGATIVE_Z'
con.up_axis = 'UP_Y'
subject = bpy.data.objects.get("Subject")
if subject is None:
subject = bpy.data.objects.new("Subject", None) # an Empty at the origin
scene.collection.objects.link(subject)
RIG = [
# name, energy W, size m, color, location
("Key", 1000.0, 2.0, (1.0, 0.95, 0.9), (4.0, -4.0, 5.0)),
("Fill", 300.0, 4.0, (0.85, 0.9, 1.0), (-5.0, -3.0, 2.0)),
("Rim", 600.0, 1.0, (1.0, 1.0, 1.0), (-2.0, 5.0, 4.0)),
]
for name, energy, size, color, loc in RIG:
obj = get_or_create_light(name, 'AREA')
obj.data.energy = energy
obj.data.size = size
obj.data.color = color
obj.location = loc
aim_at(obj, subject)Properties that differ by lamp type
The property names depend on the light type, and an assignment to a property the type lacks raises AttributeError.
| Light type | Power property | Size property |
|---|---|---|
| `POINT` | `energy` (watts) | `shadow_soft_size` (radius) |
| `SPOT` | `energy` (watts) | `shadow_soft_size`, plus `spot_size` (cone angle in radians) and `spot_blend` |
| `SUN` | `energy` (strength in W/m², typically 1 to 10) | `angle` (radians) |
| `AREA` | `energy` (watts) | `size`, and `shape` (`'SQUARE'`, `'RECTANGLE'`, `'DISK'`, `'ELLIPSE'`) |
Sun lights are the usual trap. A value like 1000 that suits an area light will blow out a Sun completely. For a rectangular area light, set data.shape = 'RECTANGLE' first, then size and size_y.
Aiming without a constraint
A constraint keeps the aim live: if you move the subject, the light follows. If you want a fixed rotation baked into the object, compute it instead:
from mathutils import Vector
def aim_fixed(obj, target_location):
direction = Vector(target_location) - obj.location
obj.rotation_euler = direction.to_track_quat('-Z', 'Y').to_euler()This sets the rotation once. The light will not follow later changes, but there is no constraint to evaluate or accidentally delete.
The World and the HDRI
The World shader is a node tree on the world data block. The script below clears the tree and rebuilds it, so reruns are safe. It also guards against a missing image file, which would otherwise stop the script with a RuntimeError partway through the setup.
import math
import bpy
scene = bpy.context.scene
world = scene.world or bpy.data.worlds.new("World")
scene.world = world
world.use_nodes = True # needed before Blender 5.0; deprecated in later versions
nodes = world.node_tree.nodes
links = world.node_tree.links
nodes.clear()
out = nodes.new('ShaderNodeOutputWorld')
bg = nodes.new('ShaderNodeBackground')
bg.inputs['Strength'].default_value = 1.0
coord = nodes.new('ShaderNodeTexCoord')
mapping = nodes.new('ShaderNodeMapping')
mapping.inputs['Rotation'].default_value[2] = math.radians(90.0) # spin around Z
env = nodes.new('ShaderNodeTexEnvironment')
try:
env.image = bpy.data.images.load("//hdri/studio.exr", check_existing=True)
except RuntimeError:
print("HDRI not found; using a flat gray World instead")
env.image = None
bg.inputs['Color'].default_value = (0.05, 0.05, 0.05, 1.0)
links.new(coord.outputs['Generated'], mapping.inputs['Vector'])
links.new(mapping.outputs['Vector'], env.inputs['Vector'])
if env.image:
links.new(env.outputs['Color'], bg.inputs['Color'])
links.new(bg.outputs['Background'], out.inputs['Surface'])Points to check in this script:
nodes.clear()removes everything, including the default Background and World Output nodes. That is why both are created again. Without it, each run would stack another node set.- Rotation is stored in radians, as a vector indexed 0, 1, 2 for X, Y, Z. Index 2 rotates the HDRI around the vertical axis, which moves the sun in the image relative to your key light.
- Strength on the Background node scales the whole HDRI. Change it there, not in the image.
//paths are relative to the saved .blend file. In an unsaved file//resolves against the current working directory, so save first or use an absolute path.check_existing=Truereuses an image already loaded under the same path, so reruns do not addstudio.exr.001.
Render settings and running the script
Put the options that affect how the lighting looks in the same file:
import bpy
scene = bpy.context.scene
scene.render.engine = 'CYCLES'
scene.cycles.samples = 128
scene.cycles.use_denoising = True
scene.view_settings.exposure = 0.0
scene.render.film_transparent = True # hide the HDRI, keep its lightfilm_transparent removes the HDRI from the visible background but not from the lighting, so reflections and shadows still use it.
Engine identifiers for EEVEE changed between releases ('BLENDER_EEVEE', then 'BLENDER_EEVEE_NEXT' in 4.2, and back to 'BLENDER_EEVEE' in 5.0). If you target EEVEE, read the valid values from your build with scene.render.bl_rna.properties['engine'].enum_items.keys(). Do not hard-code one.
To run the whole script without opening the interface:
blender --background scene.blend --python lighting.py --render-frame 1Blender runs the Python file first, then renders frame 1. Python arguments such as --python must come before --render-frame, because the command line is processed in order. If you want to keep the result, add bpy.ops.wm.save_mainfile() to the end of the script.
Common failures
| Symptom | Likely cause |
|---|---|
| Duplicate lights (`Key.001`) after rerunning | The script calls `lights.new` without looking up the existing name |
| Light exists in the data but is not in the scene | The object was never linked to a collection |
| Black render | Light faces away (`TRACK_Z` instead of `TRACK_NEGATIVE_Z`), or HDRI strength is 0 |
| `AttributeError: ... has no attribute 'size'` | `size` assigned to a Point or Sun light |
| `RuntimeError` from `images.load` | Wrong or unsaved-relative HDRI path |
| HDRI sun does not match key light | Mapping Z rotation not matched to the key light direction |
Exercise
Extend the script so it also creates a Sun light named "Sun" aimed at the subject, with strength 3 and a soft-shadow angle of 2 degrees. Which two property names do you set, and what units does each use?
Show answer
Use obj = get_or_create_light("Sun", 'SUN'), then obj.data.energy = 3.0 and obj.data.angle = math.radians(2.0), and call aim_at(obj, subject). For a Sun light, energy is strength in W/m², and angle is stored in radians, which is why math.radians converts the 2 degrees. Setting size would fail, because Sun lights have no size property.
Exercise
You run the World script twice and then open the Shader Editor. Why does the node tree contain only one set of nodes, and what would you see if you removed the nodes.clear() line?
Show answer
nodes.clear() deletes every node at the start of each run, and the script then creates a fresh set, so the tree always holds exactly one set. Without that line, each run would add another Texture Coordinate, Mapping and Environment Texture node. The new Background and World Output nodes would be added next to the old ones, so the tree would contain duplicates of every node.