Blender のノードを Python から操作する
カテゴリ:blender
まずはマテリアルノードから説明する。コンポジターノードでも基本は同じだ。
ノードツリー
ノードツリーはノードとノード間の接続情報であるリンクとに分かれて格納されている。それらを取得するには、まずマテリアルからノードツリーを取得する必要がある。
node_tree = bpy.data.materials['Material'].node_tree
オブジェクトからマテリアルを取得するならマテリアルスロットを指定する。
node_tree = bpy.context.active_object.material_slots[0].material.node_tree
ノード
ノードのリストはノードツリーの nodes から取得できる。ノードはノードの位置やラベル、デフォルト値などを設定できる。入力は上から順に inputs[0], inputs[1], ... でアクセスでき、出力も上から順に outputs[0], ... でアクセスできる。入力や出力はリンクを張るときに指定する。ノード名は ShaderNode(NodeInternal) を参照。
nodes = node_tree.nodes
for n in nodes:
print(n.label)
# ノードの全削除
for n in nodes:
nodes.remove(n)
# 出力ノードの作成
output = nodes.new(type='ShaderNodeOutputMaterial')
output.label = 'Material Output'
output.location = (300, 0)
# 放射ノードの作成
emission = nodes.new(type='ShaderNodeEmission')
emission.label = 'My Emission'
emission.location = (0, 0)
emission.inputs[0].default_value = (0, 0, 0, 1)
プリンシプル BSDF のようにソケット入力のないパラメーターはプロパティから直接設定できる。
p_bsdf = nodes[1] # Principled BSDF とする p_bsdf.distribution = 'GGX'
フレーム
parent を設定すればフレームの中にノードを入れられる。
frame = nodes.new(type='NodeFrame') p_bsdf.parent = frame
ノードグループ
ノードグループの作成は How to handle creating a node group in a script? を参照。
リンク
リンクのリストはノードツリーの links から取得できる。リンクの作成には new を使い、削除には remove を使う。
links = node_tree.links
# リンクの全削除
for l in links:
links.remove(l)
# 放射ノードの「放射(outputs[0])」を Material Output の「サーフェス(inputs[0])」につなぐ
links.new(emission.outputs[0], output.inputs[0])
コンポジット
まずコンポジターノードを有効にする。
bpy.context.scene.use_nodes = True
シーンから node_tree を取得すれば、マテリアルノードと同様に扱える。コンポジターノードはCompositorNode(NodeInternal) を参照。
node_tree = bpy.context.scene.node_tree