最近希望用 Blender 生成 Instance 的能力,將生成的導入遊戲引擎中來渲染。Instance Rendering 是個好東西,特別是針對大場景,渲染成批的基本相同的物體的時候非常有用。
希望能用 Blender 做一些模板出來,通過改變輸入的參數,來得到 Blender 給我們計算出來的結果。
這裏我拿 Geometry nodes 來做實驗,我新建了一個 Geometry Graph 如下圖所示:
很簡單的功能,就是在 Curve 上採樣一些點,來生成幾何體,這些幾何體都是相同的 Mesh,所以用 Instance 生成最好不過了。目前的數據還比較簡單,我們想要的其實就是這些幾何體的位置。我們可以寫如下腳本來控制參數(採樣數量 count)以及輸出 Instance 的 Transform Matrix 。
有幾個 Tips
- 如果是在 Blender 的 GUI 內部運行 Python 腳本,那麼在腳本中 print 的信息是沒法在 Blender 的 GUI 上輸出的。一個比較簡單的方法是,從命令行運行 Blender,這樣print的信息就會輸出在這個控制檯上,比如 Mac:
./Applications/Blender.app/Contents/MacOS/Blender
- 如果需要寫 Blender 腳本,強烈建議打開
PythonTooltips
,(Edit->Preference->Interface->PythonTooltips) 這個功能可以在 Blender 的 GUI 界面上顯示某個屬性對應的 Python 接口,非常方便,只需要將光標懸停在上面即可,如下圖所示:
下面是腳本部分,主要做了兩件事情:
- 從控制檯獲取參數,修改 Geometry Nodes 裏 node 的參數
- 獲取生成的 Instance 的 Transform Matrix
這有一個坑,就是在設置完 node 的參數後,需要調用一下bpy.context.view_layer.update
,不然在後面獲取 Instance Data 的時候沒辦法獲取最新的值。
import sys
import bpy
# get args from console
count = int(sys.argv[-1])
C = bpy.context
depsgraph = C.evaluated_depsgraph_get()
# set geometry node parameter
bpy.data.node_groups["test"].nodes['Resample Curve'].inputs[2].default_value = count
# make sure call this method to update data!!
bpy.context.view_layer.update()
data = []
# if the object is instance, we can record its value of transform matrix
for object_instance in depsgraph.object_instances:
obj = object_instance.object
if object_instance.is_instance:
print(object_instance.matrix_world)
data.append(object_instance.matrix_world)
print("count: ", len(data))
我們嘗試運行一下:
export PATH=$PATH:/Applications/Blender.app/Contents/MacOS
Blender instanceData.blend --background --python script.py -- 3
控制檯輸出爲:
<Matrix 4x4 (1.0000, 0.0000, 0.0000, 0.0000)
(0.0000, 1.0000, 0.0000, 0.0000)
(0.0000, 0.0000, 1.0000, 0.0000)
(0.0000, 0.0000, 0.0000, 1.0000)>
<Matrix 4x4 (1.0000, 0.0000, 0.0000, 0.0000)
(0.0000, 1.0000, 0.0000, 0.0000)
(0.0000, 0.0000, 1.0000, 1.7000)
(0.0000, 0.0000, 0.0000, 1.0000)>
<Matrix 4x4 (1.0000, 0.0000, 0.0000, 0.0000)
(0.0000, 1.0000, 0.0000, 0.0000)
(0.0000, 0.0000, 1.0000, 3.4000)
(0.0000, 0.0000, 0.0000, 1.0000)>
count: 3
Blender quit
完整的 project https://github.com/MangoWAY/BlenderDemo