Sub topic 17
Automating the Bake with Python
This chapter assumes you can prepare high- and low-poly meshes, create UVs, and edit materials in Blender. The script below automates the repeatable parts of a Cycles bake: choosing the objects, creating target images, selecting the active image node, baking, and saving the results.
The bake sequence
A scripted Selected to Active bake follows this order:
The high-poly object is selected first, and the low-poly object is selected last and made active. Blender projects rays from the active low-poly surface toward the selected high-poly surface.
A repeatable Python bake
The helper function creates a Non-Color image, adds an Image Texture node, and makes that node the bake target. It then selects the two objects and saves the baked image.
import bpy
HIGH_NAME = "Asset_high"
LOW_NAME = "Asset_low"
SIZE = 2048
high = bpy.data.objects[HIGH_NAME]
low = bpy.data.objects[LOW_NAME]
scene = bpy.context.scene
scene.render.engine = "CYCLES"
scene.cycles.samples = 64
bake = scene.render.bake
bake.use_selected_to_active = True
bake.use_cage = False
bake.cage_extrusion = 0.02
bake.max_ray_distance = 0.0
bake.margin = 16
bake.normal_space = "TANGENT"
material = low.active_material
if material is None:
raise RuntimeError("The low-poly object needs an active material.")
material.use_nodes = True
nodes = material.node_tree.nodes
def bake_map(name, bake_type, filename):
image = bpy.data.images.get(name)
if image is None:
image = bpy.data.images.new(name, width=SIZE, height=SIZE)
image.colorspace_settings.name = "Non-Color"
target = nodes.new("ShaderNodeTexImage")
target.name = name + "_BakeTarget"
target.image = image
nodes.active = target
bpy.ops.object.select_all(action="DESELECT")
high.select_set(True)
low.select_set(True)
bpy.context.view_layer.objects.active = low
bpy.ops.object.bake(type=bake_type, use_clear=True)
image.filepath_raw = "//" + filename
image.file_format = "PNG"
image.save()
bake_map("Asset_normal", "NORMAL", "Asset_normal.png")
bake_map("Asset_ao", "AO", "Asset_ao.png")The active Image Texture node matters. Blender writes the bake into the image connected to that node, even if other image nodes exist in the material.
Common scripting mistakes
- The low-poly object is selected but is not active.
- The target image uses sRGB instead of
Non-Color. - The low-poly object has no UV map.
- The image node is created but not assigned as the active node.
- The source and target names do not match the scene.
- The script saves a relative path somewhere different from the blend file.
Exercise
Exercise
Which object must be active when using Selected to Active, and why?
Show answer
The low-poly object must be active because Blender uses its UV layout as the destination for the projected bake.