当前位置:   article > 正文

Blender程序化设置材质【Python】_blender scripts shader

blender scripts shader

本文介绍如何使用 Python 创建新材质、添加着色器、创建新对象并将材质分配给 Blender 中的对象。

在这里插入图片描述

首先,创建一种新材质。该函数将字符串作为新材质的名称:

import bpy

def newMaterial(id):

    mat = bpy.data.materials.get(id)

    if mat is None:
        mat = bpy.data.materials.new(name=id)

    mat.use_nodes = True

    if mat.node_tree:
        mat.node_tree.links.clear()
        mat.node_tree.nodes.clear()

    return mat
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

然后为材质添加着色器。输入着色器的类型(即漫反射、发射、光泽)和 rgb 颜色:

def newShader(id, type, r, g, b):

    mat = newMaterial(id)

    nodes = mat.node_tree.nodes
    links = mat.node_tree.links
    output = nodes.new(type='ShaderNodeOutputMaterial')

    if type == "diffuse":
        shader = nodes.new(type='ShaderNodeBsdfDiffuse')
        nodes["Diffuse BSDF"].inputs[0].default_value = (r, g, b, 1)

    elif type == "emission":
        shader = nodes.new(type='ShaderNodeEmission')
        nodes["Emission"].inputs[0].default_value = (r, g, b, 1)
        nodes["Emission"].inputs[1].default_value = 1

    elif type == "glossy":
        shader = nodes.new(type='ShaderNodeBsdfGlossy')
        nodes["Glossy BSDF"].inputs[0].default_value = (r, g, b, 1)
        nodes["Glossy BSDF"].inputs[1].default_value = 0

    links.new(shader.outputs[0], output.inputs[0])

    return mat
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

然后创建对象,分配材质并调用函数:

def drawObject():

    mat = newShader("Shader1", "diffuse", 1, 1, 1)
    bpy.ops.mesh.primitive_cube_add(size=2, align='WORLD', location=(0, 0, 0))
    bpy.context.active_object.data.materials.append(mat)

drawObject()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

原文链接:Blender程序化分配材质 — BimAnt

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/332522
推荐阅读
相关标签
  

闽ICP备14008679号