在二叉樹分形基礎上,引入樹幹與樹枝差異化參數,並增加二級分支,構建更逼真的自然樹木分形。每次迭代從線段末端生成:1 條樹幹延伸 + 2 條一級分支 + 2 條二級分支(中點發出),共 5 條新線段。
trunk_angle:樹幹偏離父線段角度;branch_angle:一級分支偏離角度;trunk_c:樹幹長度縮放係數;branch_c:一級分支長度縮放係數;branch2 = branch * 1.25:二級分支較長(模擬側枝較粗)。static void FractalTree(const Vector3& vStart, const Vector3& vEnd,
Yreal trunk_angle, Yreal branch_angle,
Yreal trunk_c, Yreal branch_c,
Vector3* pVertices) {
Vector3 vSub = vEnd - vStart;
Yreal len = D3DXVec3Length(&vSub);
Yreal alfa = atan2f(vSub.y, vSub.x);
Yreal trunk = len * trunk_c;
Yreal branch = len * branch_c;
Yreal branch2 = branch * 1.25f;
// 1. 樹幹延伸
pVertices[0] = vEnd;
pVertices[1].x = pVertices[0].x + trunk * cosf(alfa + trunk_angle);
pVertices[1].y = pVertices[0].y + trunk * sinf(alfa + trunk_angle);
pVertices[1].z = 0.0f;
// 2. 一級分支(左右對稱)
pVertices[2] = vEnd;
pVertices[3].x = pVertices[2].x + branch * cosf(alfa + branch_angle);
pVertices[3].y = pVertices[2].y + branch * sinf(alfa + branch_angle);
pVertices[3].z = 0.0f;
pVertices[4] = vEnd;
pVertices[5].x = pVertices[4].x + branch * cosf(alfa - branch_angle);
pVertices[5].y = pVertices[4].y + branch * sinf(alfa - branch_angle);
pVertices[5].z = 0.0f;
// 3. 二級分支(從 55% 處發出,更長)
pVertices[6] = vStart + vSub * 0.55f;
pVertices[7].x = pVertices[6].x + branch2 * cosf(alfa + branch_angle);
pVertices[7].y = pVertices[6].y + branch2 * sinf(alfa + branch_angle);
pVertices[7].z = 0.0f;
pVertices[8] = pVertices[6];
pVertices[9].x = pVertices[8].x + branch2 * cosf(alfa - branch_angle);
pVertices[9].y = pVertices[8].y + branch2 * sinf(alfa - branch_angle);
pVertices[9].z = 0.0f;
}
void BuildTree(Vector3 start, Vector3 end, int depth, int maxDepth,
Yreal trunk_ang, Yreal branch_ang, Yreal trunk_c, Yreal branch_c,
vector>& segments) {
if (depth > maxDepth) return;
segments.push_back({start, end});
Vector3 verts[10];
FractalTree(start, end, trunk_ang, branch_ang, trunk_c, branch_c, verts);
// 5 條新線段遞歸
BuildTree(verts[0], verts[1], depth+1, maxDepth, trunk_ang, branch_ang, trunk_c, branch_c, segments); // 樹幹
BuildTree(verts[2], verts[3], depth+1, maxDepth, trunk_ang, branch_ang, trunk_c, branch_c, segments); // 右一級
BuildTree(verts[4], verts[5], depth+1, maxDepth, trunk_ang, branch_ang, trunk_c, branch_c, segments); // 左一級
BuildTree(verts[6], verts[7], depth+1, maxDepth, trunk_ang, branch_ang, trunk_c, branch_c, segments); // 右二級
BuildTree(verts[8], verts[9], depth+1, maxDepth, trunk_ang, branch_ang, trunk_c, branch_c, segments); // 左二級
}
| 參數組合 | 視覺效果 |
|---|---|
trunk_angle=0, branch_angle=30° | 直立主幹,對稱側枝 → 松樹/杉樹 |
trunk_angle=15°, branch_angle=45° | 主幹傾斜,大角度分叉 → 橡樹/闊葉樹 |
trunk_c=0.8, branch_c=0.6 | 主幹較長,側枝快速遞減 → 喬木 |
trunk_c=0.6, branch_c=0.7 | 側枝相對較長 → 灌木叢 |
增加 maxDepth | 分支層次更豐富,細節更細膩 |
此模型是程序化植被生成的進階基石,通過調整 6 個核心參數即可覆蓋從針葉林到熱帶雨林的多樣樹形,廣泛用於遊戲地形、電影特效與虛擬現實場景構建。