Skip to content

【Blender导出模型AO图】

AO 全称为 Ambient Occlusion 表示模型在环境光的受光概率遮罩。

越不容易被光照到的地方就越黑。

通常可以使用AO图增加模型光影细节。

Blender 通过使用脚本,快速导出模型的AO图。

测试使用的是Blender4.2版本。

Markdown 图片

Markdown 图片

脚本

python
import bpy

def bake_ao_texture(output_path, image_name="AO_Texture", resolution=1024):
    # Ensure we are in object mode
    if bpy.context.active_object.mode != 'OBJECT':
        bpy.ops.object.mode_set(mode='OBJECT')
    
    # Get the active object
    obj = bpy.context.active_object
    
    # Create a new image for baking
    image = bpy.data.images.new(name=image_name, width=resolution, height=resolution)
    
    # Create a new material if the object doesn't have one
    if not obj.data.materials:
        mat = bpy.data.materials.new(name="AO_Material")
        obj.data.materials.append(mat)
    else:
        mat = obj.data.materials[0]
    
    # Use nodes
    mat.use_nodes = True
    nodes = mat.node_tree.nodes
    links = mat.node_tree.links
    
    # Clear existing nodes
    for node in nodes:l
        nodes.remove(node)
    
    # Add necessary nodes
    ao_node = nodes.new(type='ShaderNodeAmbientOcclusion')
    bsdf_node = nodes.new(type='ShaderNodeBsdfPrincipled')
    output_node = nodes.new(type='ShaderNodeOutputMaterial')
    texture_node = nodes.new(type='ShaderNodeTexImage')
    
    # Set the image to the texture node
    texture_node.image = image
    
    # Connect nodes
    links.new(ao_node.outputs['Color'], bsdf_node.inputs['Base Color'])
    links.new(bsdf_node.outputs['BSDF'], output_node.inputs['Surface'])
    
    # Select the texture node for baking
    nodes.active = texture_node
    
    # Set bake type to Ambient Occlusion
    bpy.context.scene.cycles.bake_type = 'AO'
    
    # Bake the AO texture
    bpy.ops.object.bake(type='AO')
    
    # Save the image
    image.filepath_raw = output_path
    image.file_format = 'PNG'
    image.save()


# Example usage
bake_ao_texture(output_path="E:/test/AO_Texture.png", resolution=2048)

使用方式

需要先设置渲染模式为“Cycles”。

Markdown 图片

1.准备已经展好UV的模型(测试可以使用猴头)。

2.场景中选中目标模型。

3.切换到脚本模式。

4.粘贴入本文的脚本。

5.根据需要修改output_path。

6.点击运行脚本。

我使用该脚本生成的AO图:

Markdown 图片

MIT Licensed