简体   繁体   English

在OpenGL中创建分形树

[英]Creating a fractal tree in opengl

Having a little trouble creating a fractal in opengl. 在opengl中创建分形有些麻烦。 Here is my current code 这是我当前的代码

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);

}

The positioning isn't correct, although the rotation seems to be right. 定位不正确,尽管旋转似乎正确。 The new branches arent' being draw starting at the end point of the parent's branch. 从父级分支的端点开始绘制新的分支。 Can someone help me on fixing this problem. 有人可以帮我解决这个问题。 Check out the full code here 在此处查看完整代码

The formula for nextPosition is incorrect as it didn't factor in the direction which the current branch is facing nextPosition的公式不正确,因为它没有考虑当前分支所面向的方向

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

It should be something like this (please check exactly): 应该是这样的(请仔细检查):

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

Also, please use glLoadIdentity() to reset the matrix immediately like this: 另外,请使用glLoadIdentity()立即重置矩阵,如下所示:

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

It will be much clearer than what you are trying to do. 这将比您要尝试的要清楚得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM