Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

製作樹

這是一個關於如何從頭開始製作樹和其他型別植被的小教學.

The aim is to not focus on the modeling techniques (there are plenty of tutorials about that), but how to make them look good in Godot.

../../_images/tree_sway.gif

從一棵樹開始

我從 SketchFab 上獲取了這棵樹:

../../_images/tree_base.png

https://sketchfab.com/models/ea5e6ed7f9d6445ba69589d503e8cebf

然後用 Blender 打開。

用頂點顏色繪製

The first thing you may want to do is to use the vertex colors to paint how much the tree will sway when there is wind. Just use the vertex color painting tool of your favorite 3D modeling program and paint something like this:

../../_images/tree_vertex_paint.png

這有點誇張, 但這個想法是, 顏色表明了多少搖擺影響樹的每個部分. 這個比例尺更能說明問題:

../../_images/tree_gradient.png

為葉子編寫自訂著色器

這是一個簡單的樹葉著色器的範例:

shader_type spatial;
render_mode depth_prepass_alpha, cull_disabled, world_vertex_coords;

這是一個空間著色器. 沒有前/後剔除(所以可以從兩邊看到葉子), 並且使用了alpha預通道, 所以使用透明度(和葉子投射陰影)導致的深度偽影比較少. 最後, 對於搖擺的效果, 推薦使用世界座標, 以使樹可以被複製, 移動等, 並且仍然可以和其他樹一起使用.

uniform sampler2D texture_albedo : source_color;
uniform vec4 transmission : source_color;

在這裡, 紋理和透射顏色被讀取, 透射顏色被用來給葉子新增一些背光, 模擬地下散射.

uniform float sway_speed = 1.0;
uniform float sway_strength = 0.05;
uniform float sway_phase_len = 8.0;

void vertex() {
    float strength = COLOR.r * sway_strength;
    VERTEX.x += sin(VERTEX.x * sway_phase_len * 1.123 + TIME * sway_speed) * strength;
    VERTEX.y += sin(VERTEX.y * sway_phase_len + TIME * sway_speed * 1.12412) * strength;
    VERTEX.z += sin(VERTEX.z * sway_phase_len * 0.9123 + TIME * sway_speed * 1.3123) * strength;
}

這是建立葉子擺動的程式碼. 它是基本的(只是使用正弦波乘以時間和軸的位置, 但工作得很好). 注意, 強度乘以顏色. 每個軸使用不同的小的接近1.0的乘法係數, 所以軸不同步出現.

最後, 剩下的就是片段著色器了:

void fragment() {
    vec4 albedo_tex = texture(texture_albedo, UV);
    ALBEDO = albedo_tex.rgb;
    ALPHA = albedo_tex.a;
    METALLIC = 0.0;
    ROUGHNESS = 1.0;
    TRANSMISSION = transmission.rgb;
}

差不多就是這樣.

主幹著色器是類似的, 除了它不寫到alpha通道(因此不需要alpha前置)和不需要傳輸工作. 這兩個著色器都可以通過新增法線對應, AO和其他對應來改進.

改進著色器

還有更多的資源可以做到這一點, 您可以閱讀. 現在您已經瞭解了基礎知識, 建議閱讀GPU Gems3中關於Crysis如何做到這一點的章節(主要關注搖擺程式碼, 因為許多其他技術都已經過時了):

https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch16.html