dchhetri
dchhetri

Reputation: 7136

Any advice on how to rotate/translate object properly in opengl, trying to achieve the following effect

Trying to generate a recursive tree made of lines. My current draw function isn't working like planned. Before I show the problem here is the draw code :

void _generateTreeBranches(const Point3f& startPoint,
                       const Point3f& endPoint,
                       float rotation,
                       const int depth)
{

 if(depth > MAX_DEPTH) return;
cout << "at depth = " << depth << endl;

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

float distanceOfPoint = pointDistance(startPoint, endPoint);


glRotatef(rotation, 0.0f, 0.0f, 1.0f);
glTranslatef(-startPoint.x, 0.0f, 0.0f);
    drawLine(startPoint, endPoint);
glTranslatef(startPoint.x, 0.0f, 0.0f);
glRotatef(-rotation, 0.0f, 0.0f, 1.0f);

const float nextLength = distanceOfPoint;
Point3f nextBranchStart = endPoint;
Point3f nextBranchEnd = {endPoint.x + nextLength,endPoint.y,endPoint.z};
_generateTreeBranches(nextBranchStart, nextBranchEnd,45.0f,depth+1);

That draws something like this

 /__

whereas I am trying to get it to draw something like so

__/

Any help on achieving the above?

Upvotes: 1

Views: 310

Answers (1)

Sebastian Cabot
Sebastian Cabot

Reputation: 1822

We don't know the state of the modelview matrix at the calling point so let's call it MV

First call (Order of matrix operations)

T = Translate by -x
R = Rotate by r
TRANSFORMATION = MV(R(T(v)))
DRAW

Second call (Order of matrix operations)

T = Translate by -x2
R = Rotate by r2

START FROM FIRST CALL
Rm1 = Rotate by -r
Tm1 = Translate by x
Tm2 = Translate by -x
Rm2 = Rotate by r
END FROM FIRST CALL

TRANSFORMATION = MV(Rm2(Tm2(Tm1(Rm1(R(T(v)))))))
DRAW

As you can see you are rotating translated and rotated values. afterwards you are trying to undo something that can no longer be undone.

So depending on the value of MV and r all kind of things might happen.

If you want to undo the matrix operations use glPush/PopMatrix not the reverse of the operation that will just produce floating point errors in the best case and what you see in the recursive case.

For what you are trying to do the first rotation should be 0 and you have to make sure the the modelview matrix is Identity, and use glPush/PopMatrix

Also - unless your real code actually needs recursion use loops.

Upvotes: 1

Related Questions