Blender スクリプト例

関連する外部ページ

サイト内の関連情報

前準備

Blenderは,3次元コンピュータグラフィックス・アニメーションソフトウェアである.3次元モデルの編集,レンダリング,光源やカメラ等の設定による3次元コンピュータグラフィックス・アニメーション作成機能がある.

メニューの日本語化を行っておくと使いやすい.「編集(Edit)→プリファレンス(Preferences)→インターフェイス(Interface)→翻訳(Translation)」で設定できる.

スクリプトの実行方法

Blenderは,Pythonスクリプトによる操作ができる.スクリプトは bpy モジュールを用いて記述する.

  1. Pythonスクリプトを指定してBlenderを起動する.blender コマンドが使えない場合は,Blender実行ファイルへのフルパスを使う.実行結果(print の出力)は,Blenderを起動したコマンドプロンプトまたはターミナルに表示される.

    blender --python hoge.py
    

    必要なモジュールが別ディレクトリにあるときは,スクリプト内でPythonの検索パスに追加する.

    import sys
    sys.path.append('/path/to/dir')
    
  2. バックグラウンド(batch)モードでの実行.画面を表示せずにスクリプトを実行する.

    blender -b --python hoge.py
    
  3. 対話(interactive)モードでの実行.Pythonコンソールが起動する.

    blender --python-console
    
  4. Blenderの画面内で実行する場合は,ワークスペースを「Scripting」に変更し,テキストエディタにスクリプトを記述して実行する.

スクリプト例

次のプログラムは,初期シーン(Cubeがある状態)で実行する.すべてのメッシュオブジェクトにSolidifyモディファイア(面に厚みを付けるモディファイア)を追加し,設定した厚みを表示する.

import bpy
import random

for obj in bpy.data.objects:
    if obj.type == 'MESH':
        modifier = obj.modifiers.new(name=obj.name + '_solidify', type='SOLIDIFY')
        modifier.thickness = random.random() * 0.2
        print(obj.name, modifier.thickness)

実行後,メッシュオブジェクトのモディファイア一覧にSolidifyモディファイアが追加され,オブジェクト名と厚みが表示される.

次のプログラムは,オブジェクトを1つ選択した状態で実行する.選択されているオブジェクトの名前を表示する.

import bpy

obj = bpy.context.selected_objects[0]
print('Selected object:', obj.name)

次のプログラムは,選択されているオブジェクトと,アクティブなオブジェクトを表示する.

import bpy

print(bpy.context.selected_objects)
print(bpy.context.active_object)

次のプログラムは,ファイル内のすべてのオブジェクトを表示する.

import bpy

for obj in bpy.data.objects:
    print(obj)

次のプログラムは,初期シーンの Cube メッシュを対象にして実行する.頂点の座標を表示する.

import bpy

mesh = bpy.data.meshes['Cube']
print(mesh.vertices[0].co)
print(mesh.vertices[0].co.y)

次のプログラムは,初期シーンの Cube を選択し,面を三角形に変換して,各面の頂点座標を表示する.オブジェクトモードで実行する.

import bpy

obj = bpy.data.objects['Cube']
bpy.ops.object.select_all(action='DESELECT')
obj.select_set(True)
bpy.context.view_layer.objects.active = obj

bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='SELECT')
print(bpy.ops.mesh.quads_convert_to_tris())
bpy.ops.object.mode_set(mode='OBJECT')

mesh = obj.data
for polygon in mesh.polygons:
    for vertex_index in polygon.vertices:
        print(mesh.vertices[vertex_index].co)

次のプログラムは,現在のシーン内の MESH オブジェクトと,ファイル内のオブジェクト,メッシュ,マテリアルのデータを表示する.

import bpy

for obj in bpy.context.scene.objects:
    if obj.type == 'MESH':
        print(obj)
for obj in bpy.data.objects:
    if obj.type == 'MESH':
        print(obj)
for mesh in bpy.data.meshes:
    print(mesh)
for material in bpy.data.materials:
    print(material)

Bash からスクリプトを作成して実行する

Bashが使える環境では,次のようにPythonスクリプトを作成し,Blenderのバックグラウンドモードで実行できる.次の例では,bpy モジュールの属性の一覧を表示する.

#!/bin/bash
cat > /tmp/hoge.py <<-BPY
import bpy

print(dir(bpy))
BPY
blender -b --python /tmp/hoge.py

上のスクリプトの BPY で囲まれた部分を,前節のプログラム例に置き換えることで,他のスクリプトも同じ手順で実行できる.