gpt4 book ai didi

c++ - 在opengl中创建一个分形树

转载 作者:太空宇宙 更新时间:2023-11-04 12:03:26 25 4
gpt4 key购买 nike

在 opengl 中创建分形时遇到一点问题。这是我当前的代码

void generateTree(){
Point3f startPoint({0.0f,0.0f,0.0f});
Point3f endPoint({1.0f,0.0f,0.0f});
float rotation = 90.0f;
glutWireSphere(0.05, 4, 4);
_generateTreeBranches(startPoint,1.0f,rotation,0);
}

void _generateTreeBranches(const Point3f& newPosition,
float length,
float rotation,
const int depth)
{
if(depth > MAX_DEPTH) return;
cout << "at depth = " << depth << endl;


if(depth == 0){
glColor3f(1.0f,1.0f,1.0f);
}else if(depth == 1){
glColor3f(1.0f,0.0f,0.0f);
}else{
glColor3f(0.0f,1.0f,0.0f);
}

glTranslatef(newPosition.x,newPosition.y,newPosition.z);
glRotatef(rotation, 0.0f, 0.0f, 1.0f);
drawLine(length);
glRotatef(-rotation, 0.0f, 0.0f, 1.0f);
glTranslatef(-newPosition.x,-newPosition.y,-newPosition.z);



const float newLength = length * BRANCH_LENGTH_DECREASE_FACTOR;
int nextDepth = depth + 1;
Point3f nextPosition = {newPosition.x+length, newPosition.y, newPosition.z};

float leftRotation = rotation + CHILD_BRANCH_ANGLE * nextDepth;
_generateTreeBranches(nextPosition,newLength,leftRotation,nextDepth);

float rightRotation = rotation - CHILD_BRANCH_ANGLE * nextDepth;
_generateTreeBranches(nextPosition,newLength,rightRotation,nextDepth);

}

虽然旋转似乎是正确的,但定位不正确。新分支不是从父分支的终点开始绘制的。有人可以帮我解决这个问题。查看完整代码 here

最佳答案

nextPosition 的公式不正确,因为它没有考虑当前分支所面对的方向

 Point3f nextPosition = {newPosition.x+length, newPosition.y, newPosition.z};

应该是这样的(请仔细检查):

Point3f nextPosition = {newPosition.x+length*cos(rotation), newPosition.y+length*sin(rotation), newPosition.z};

另外,请像这样立即使用 glLoadIdentity() 重置矩阵:

glTranslatef(newPosition.x,newPosition.y,newPosition.z);
glRotatef(rotation, 0.0f, 0.0f, 1.0f);
drawLine(length);
glLoadIdentity();

它会比你试图做的更清楚。

关于c++ - 在opengl中创建一个分形树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13133574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com