blender插件开发的基本流程是这样的,想做一个功能首先先学会怎么操作,再复制信息窗口上的代码,最后在blender里测试一下,基本完成,当信息窗口里没有操作的代码时,就去翻PythonAPI。
围绕物体旋转的相机把前面几篇的东西都用上了,我这篇文章算Blender插件开发的一个总结,以后没遇到特别功能基本不跟新了
贴代码
def execute(self, context):
parent_object = bpy.data.objects["酒瓶"]
#先获得模型大尺寸
object_size = get_object_size(parent_object)
#删除已有相机
for obj in bpy.data.objects:
if obj.type == "CAMERA":
bpy.data.cameras.remove(obj.data)
# 创建相机,z轴比物体高2,斜着的俯视角
bpy.ops.object.camera_add(enter_editmode=False, align='VIEW', location=(0, -10, object_size[2] + 2),
rotation=(0, 0, 0), scale=(1, 1, 1))
camera = bpy.context.object
# 创建一个空物体,位置在物体的中心点
parent_location = (0, 0, object_size[2] / 2)
bpy.ops.object.empty_add(type='PLAIN_AXES', align='WORLD', location=parent_location, scale=(1.0, 1.0, 1.0))
empty_object = bpy.context.object
# 将相机移到空物体的子级
bpy.ops.object.select_all(action='DESELECT')
bpy.context.view_layer.objects.active = empty_object
camera.select_set(True)
bpy.ops.object.parent_set(type='OBJECT')
# 给相机添加一个约束,使相机镜头始终对准空物体
constraint = camera.constraints.new('DAMPED_TRACK')
constraint.target = empty_object
constraint.track_axis = 'TRACK_NEGATIVE_Z'
bpy.ops.object.select_all(action='DESELECT')
# 给空物体的位置添加3个驱动器,使空物体始终在物体的中心点
location_names = ('location_x', 'location_y', 'location_z')
transform_types = ('LOC_X', 'LOC_Y', 'LOC_Z')
for i in range(3):
d = empty_object.driver_add('location', i).driver
v = d.variables.new()
v.type = 'TRANSFORMS'
v.name = location_names[i]
v.targets[0].id = parent_object
v.targets[0].transform_type = transform_types[i]
v.targets[0].transform_space = 'WORLD_SPACE'
d.expression = v.name + "+" + str(parent_location[i])
# 给空物体添加一个旋转驱动器,使空物体随着帧号进行旋转
od = empty_object.driver_add('rotation_euler', 2).driver
od.type = 'SCRIPTED'
od.use_self = True
od.expression = "(frame-1)/12"
# 给场景添加一个HDR
world = context.scene.world
node_tree = world.node_tree
world.use_nodes = True
nodes = node_tree.nodes
links = node_tree.links
nodes.clear()
links.clear()
tex_environment_node = nodes.new("ShaderNodeTexEnvironment")
tex_environment_node.location = (-300, 0)
tex_environment_node.select = False
background_node = nodes.new("ShaderNodeBackground")
background_node.location = (0, 0)
background_node.select = False
output_world_node = nodes.new("ShaderNodeOutputWorld")
output_world_node.location = (200, 0)
output_world_node.select = False
links.new(tex_environment_node.outputs[0], background_node.inputs[0])
links.new(background_node.outputs[0], output_world_node.inputs[0])
image = None
# 获取系统自带的HDR
if 'city.exr' in bpy.data.images:
image = bpy.data.images['city.exr']
else:
for sl in bpy.context.preferences.studio_lights:
if sl.type == 'WORLD' and sl.name == 'city.exr':
image = bpy.data.images.load(sl.path)
break
if image is None:
print("找不到系统HDR,请手动设置HDR")
else:
tex_environment_node.image = image
return {'FINISHED'}
?
|