Calling glLoadIdentity shows awkward behaviour - opengl

I have written this piece of code in c to draw a planet system with a sun and a planet
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0,0.0,0.0);
glMatrixMode(GL_MODELVIEW_MATRIX);
glPushMatrix();
glutWireSphere(1.0, 20, 16);
glLoadIdentity();
glRotatef((GLfloat) year ,0.0,1.0,0.0);
glTranslatef(2.0, 0.0, 0.0);
glRotatef((GLfloat) day, 0.0, 1.0, 0.0);
glutWireSphere(0.2, 10, 8);
glPopMatrix();
glutSwapBuffers();
But when I compile and run the code, second sphere is not in the view. After I increase the value of y, it appears for half of the rotation when it is behind the centre sphere and then goes out of View again, also the size of the sphere is larger than expected. if I comment out the call to glLoadIdentity(), everything works fine. As much as I know, glLoadIdentity() loads the current Matrix(ModelView_Matrix) with an identity matrix so that the effect of all the translations and rotations is reversed but why in this case the objects drawn when its called are in different manner when no rotations or transformations are being performed before its call?

I suspect that you do have other transformations in the ModelView matrix. If it was already set to the identity, then loading identity would not change the behaviour.
The code you have provided only sets up a local model transform. There are no projection or view transformations being applied, so these must be done elsewhere. Perhaps at initialisation.
Without a prior view transformation, the first sphere would be drawn at the same position as the view - in other words, the camera would be inside the sphere.

I suspect your problem is related to the way you make use of glPushMatrix and glPopMatrix in conjunction with glLoadIdentity:
Suppose you have some matrix A on your modelview stack. Now you use glPushMatrix, essentially saving A to restore it later. Inside the push-pop block, you tell GLUT to draw a sphere, which it dutyfully does, using the previously mentioned modelview matrix A.
If you now call glLoadIdentity, anything that A was before, is gone until you call glPopMatrix, which restores the previous state of A.
So in short, transformation calls after glLoadIdentity are based on the identity matrix rather than the matrix state previous to glPushMatrix.
Seeing that what you want to do is drawing a solar system. It'd probably be best to do something like:
glPushMatrix();
/* Transformations positioning the sun */
/* Draw the sun */
glPushMatrix();
/* Transformations for getting from the sun to the planet */
/* Draw the planet */
glPopMatrix();
glPopMatrix();
As an aside, the fixed-function pipeline (glTranslate, glRotate, glPushMatrix, ...) has been deprecated for quite a while now (about 10 years?), so I'd suggest picking up OpenGL using a more modern approach.
Edit:
While re-reading the question, another thing struck my attention:
Assuming year is designating where the planet is in its revolution around the sun and day specifies how much the plant is rotated around its own polar axis, the correct order of transformations would be:
Rotate by day around the y-axis
Translate
Rotate by year around the y-axis
(Right now, you're doing it the opposite way, which could explain the strange behaviour you're experiencing. See also here.)
According to the comment by JasonD, your transformation order was right in the first place, but still it won't hurt to know about the background. ;)

Related

Rotating 'camera' in OpenGL around object not object around camera

In my app I have a set of object lying around the scene. They are all grouped inside box. When user zoom out to see whole box and starts rotate it then the pivot point is in the middle of box,. When you zoom in to see specific object inside then rotating camera so that the object that you are looking at (or space in front of you) then they are still rotating around this previous pivot point.
What I would like to achieve is to have pivot point always in front of camera. In other words, when you zoom out and see box it rotates as it is doing now. When you zoom in to specific object/space then camera rotate around it.
I've created simple images to show what I mean - triangle is camera, red box is some object/space and orange circle is a path on which element is going on while rotating. The first one is what I have now, the second what I'd like to have.
I know that in OpenGL there isn't something like camera, so in fact it is whole world moving and not one point. So far I've created something like that:
glPushMatrix();
glTranslatef(translate[0], translate[1], translate[2]);
glRotatef(rot, 0.0, 1.0, 0.0);
DrawObject();
glPopMatrix();
translate is an array of values simulating camera movement.
EDIT:
After Ike answer I modified a little my code so now it looks like this:
glPushMatrix();
glTranslatef(pivot[0], pivot[1], pivot[2]);
glRotatef(rot, 0.0, 1.0, 0.0);
glTranslatef(translate[0], translate[1], translate[2]);
glPopMatrix();
So if I'm getting Iko's solution correctly now my biggest concern is calculating correctly pivot point according to place that I'm looking at. Is it correct thinking?
One way to get this kind of representation is to kind of translate the pivot to the origin, then rotate, and then step backwards, away from the pivot.
Effectively you translate in the opposite direction of the pivot (negative pivot, effectively moving it to the origin). Then rotate to the desired viewing angle. And then "step back" (translate along -Z in a right-handed coordinate system).
Something like this:
mat4 modelview_matrix(float distance, const vec3& pivot, const vec3& rotation_xyz)
{
mat4 distance_mat = tmat(0.0, 0.0, -distance);
mat4 rot_mat = rmat(rotation_xyz[0], rotation_xyz[1], rotation_xyz[2]);
mat4 pivot_mat = tmat(-pivot[0], -pivot[1], -pivot[2]);
return distance_mat * rot_mat * pivot_mat;
}
tmat and rmat above are basically just constructing translation and rotation matrices.
That allows you to orbit the camera around a pivot of your choice. Panning can be achieved by actually moving the pivot around, giving you those CAD-style viewport navigation controls.
So if I'm getting Iko's solution correctly now my biggest concern is
calculating correctly pivot point according to place that I'm looking
at. Is it correct thinking?
Pretty much -- maybe with a slight tweak. That pivot point will always be what you look at -- it's going to be your center of interest. You can, for example, put it at the center of the bounding box of your scene, e.g. (some 3D software does this to fit/frame the view around the scene). After that, it's up to you to place the pivot point where you like based on the kind of software design you're after. The camera will always be looking at it.
Edit
glPushMatrix();
glTranslatef(pivot[0], pivot[1], pivot[2]);
glRotatef(rot, 0.0, 1.0, 0.0);
glTranslatef(translate[0], translate[1], translate[2]);
glPopMatrix();
For this kind of thing, you probably want something more like this:
glTranslatef(-pivot[0], -pivot[1], -pivot[2]);
glRotatef(rot, 0.0, 1.0, 0.0);
glTranslatef(0, 0, -distance);
... and outside of pushing to the transformation stack and rendering individual objects (do this at the top of the call stack). That's what gives you something akin to "camera control".
Then when you render each object, push the current transformation and do the necessary local transformations for each object and child. That gives you something akin to objects moving around and being oriented in the world independently of the camera, and a motion hierarchy with parent-child relationships.

OpenGL, model matrix as no rotation/translation/scale

I am playing with opnegl (the old one, sorry for the modern opengl guys), and I'm trying to understand the matrixes and replace glRotatef, glTranslatef etc with glLoadMatrixf.
I don't understand how to set a matrix with no rotation, no translation, no scale. I thought I could use an identity matrix but it doesn't work.
I'd like to have a matrix such that writing:
glPushMatrix();
{
drawMyCube();
}
glPopMatrix();
is the equivalent to writing:
glPushMatrix();
{
glLoadMatrixf( myCubeTransform.getTranspose() );
drawMyCube();
}
glPopMatrix();
If I have something like:
/* 1: */ // glLoadMatrixf( myCubeTransform.getTranspose() );
/* 2: */ // glLoadIdentity();
In the first place I thought to use myCubeTranform Matrix4 class (and I'm using a row-major order matrix class so I have to getTranspose() to match opengl column-major order) but it doesn't work, so I used glLoadIdentity to be sure to does not make mess with my Matrix4 class (some bug in matrix code?) and.. it doesn't work either.
So my question: how to set a transform matrix with no translation, no rotation, no scale?
With "does not work" I mean that my cube is not in the origin (where I want it to be). Actually, I don't see it at all (prob. it is drawn outside the view frustum?)
glLoadMatrix will replace what's on top of the matrix stack. Which means, that it will nil your view setup, that you probably did before. You have to choices: Either implement the view part yourself as well and pre-multiply that on the model transformation. Or (for learning purposes) use glMultMatrix instead of where you have glLoadMatrix right now.

GL_MODELVIEW and GL_PROJECTION

My code Currently looks like this :
glViewport (0, 0, this->w(), this->h());
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-1.0, 1.0, -1.0, 1.0, 1.5, 20.0);
//glTranslated (m_fXmovement, 0.0, m_fZmovement - 5);
//glRotated (m_fYangleView, 1.0, 0.0, 0.0);
//glRotated (m_fXangleView, 0.0, 1.0, 0.0);
///// Model View \\\\\
glMatrixMode(GL_MODELVIEW);
glTranslated (m_fXmovement, 0.0, m_fZmovement - 5 );
glRotated (m_fYangleView, 1.0, 0.0, 0.0);
glRotated (m_fXangleView, 0.0, 1.0, 0.0);
DrawWaveFrontObject (m_pDataObjectMedia);
glPushMatrix();
glTranslated (0.0, -3.0, 0.0);
DrawArea();
glPopMatrix();
DrawClickAnimation();
glLoadIdentity();
First I had the movement part in GL_PROJECTION and all was running fine until I was working with fog.... It felt like the Camera isn't moving, it felt more like an additional camera pointing to that camera....
Then I accidentally copied the movement parts to the GL_MODELVIEW and the fog was acting as I wanted it to act..... all was fine accepting the click animation wasn't in relation to the area anymore, now the animation moved with my ego perspective.... and I don't really get it what kind of drawing I have to put in which of these two VIEW's. Could anyone give me examples or explanations according to my code or a hint what I could improve in my styl?
Quote from opengl.org forum:
The projection matrix is used to create your viewing volume. Imagine a
scene in the real world. You don't really see everything around you,
only what your eyes allow you to see. If you're a fish for example you
see things a bit broader. So when we say that we set up the projection
matrix we mean that we set up what we want to see from the scene that
we create. I mean you can draw objects anywhere in your world. If they
are not inside the view volume you won't see anything. When you create
the view volume imagine that you create 6 clipping planes that define
your field of view.
As for the modelview matrix, it is used to make various
transformations to the models (objects) in your world. Like this you
only have to define your object once and then translate it or rotate
it or scale it.
You would use the projection matrix before drawing the objects in your
scene to set the view volume. Then you draw your object and change the
modelview matrix accordingly. Of course you can change your matrix
midway of drawing your models if for example you want to draw a scene
and then draw some text (which with some methods you can work easier
in orthographic projection) then change back to modelview matrix.
As for the name modelview it has to do with the duality of modeling
and viewing transformations. If you draw the camera 5 units back, or
move the object 5 units forwards it is essentially the same.
First of all, I suggest that you try to abandon the fixed-function pipeline (glTranslate etc) since it's been deprecated for like 10 years now. Look here for a more modern tutorial if you're interested.
As for your problem, you can imagine the meaning of the two matrices like this: The projection matrix essentially captures properties intrinsic to the camera itself, like how its field of view is shaped.
On the other hand, the modelview matrix is composed of two parts, the model matrix and the view matrix. The model part is for transforming from object space (relative to an object itself) to world space. Then, the view part translates from there to the eye space, in which the camera sits at the origin and points down the (negative?) z axis. Together, the modelview matrix essentially states how objects are to be positioned relative to the camera.
For further information, this resource gives a detailed description of graphics transformations in the context of OpenGL.
[Jan, 2017] Edit: Pages from the first link seem to be unable to access these days, so there is another link to the same content from their archive.

How to use gluPerspective only once?

glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
//set viewpoint
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(VIEW_ANGLE,Screen_Ratio,NEAR_CLIP,FAR_CLIP);
gluLookAt(0,5,5, 0,0,0, 0,1,0);
//transform model 1
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef(Theta, 0,1,0);
//draw model 1
glBegin(GL_QUADS);
...
glEnd();
The code above works fine, but is there any way to remove the call to gluPerspective?
What I mean is, I would like to call it only once in initialization, instead of repeatedly during each rendering.
You call gluPerspective there, because it belongs there. OpenGL is not a scene graph where you initialize things. It's a state driven drawing API. The projection matrix is a state and every serious graphics application changes this state multiple times throughout a single frame rendering.
OpenGL does not know geometrical objects, positions and cameras. It just pushes points, lines and triangles through a processing pipeline, and draws the result to the screen. After something has been drawn, OpenGL has no recollection of it, whatsoever.
I mean calling it only once in initialization.
OpenGL is not initialized (except creation of the rendering context, but actually this is part of the operating system's graphics stack, not OpenGL). Sure, you upload textures and buffer object data to it, but that can happen anytime.
Do not use gluLookAt on the projection matrix, as it defines the camera/view and therefore belongs to the modelview matrix, usually as the left-most transformation (the first after glLoadIdentity), where it makes up the view part of the word modelview. Although it also works your way, it's conceptually wrong. This would also solve your issue, as then you just don't have to touch the projection matrix every frame.
But actually datenwolf's approach is more conceptually clean regarding OpenGL's state machine architecture.
If you don't call glLoadIdentity() (which resets the current matrix to be the identity matrix, i.e. undoes what gluPerspective() has done) every frame and instead carefully push/pop the transform matrices you can get away with calling it only in initialization quite happily. Usually it's far easier just to call load identity each time your start drawing and then reset it. e.g.:
// Initalisation
glLoadIdentity();
gluPerspective(...);
Then later on:
// Drawing each frame
glClear(...);
glPushMatrix();
gluLookAt(...);
//draw stuff
glPopMatrix();

OpenGL Rotation

I'm trying to do a simple rotation in OpenGL but must be missing the point.
I'm not looking for a specific fix so much as a quick explanation or link that explains OpenGL rotation more generally.
At the moment I have code like this:
glPushMatrix();
glRotatef(90.0, 0.0, 1.0, 0.0);
glBegin(GL_TRIANGLES);
glVertex3f( 1.0, 1.0, 0.0 );
glVertex3f( 3.0, 2.0, 0.0 );
glVertex3f( 3.0, 1.0, 0.0 );
glEnd();
glPopMatrix();
But the result is not a triangle rotated 90 degrees.
Edit
Hmm thanks to Mike Haboustak - it appeared my code was calling a SetCamera function that use glOrtho. I'm too new to OpenGL to have any idea of what this meant but disabling this and rotating in the Z-axis produced the desired result.
Ensure that you're modifying the modelview matrix by putting the following before the glRotatef call:
glMatrixMode(GL_MODELVIEW);
Otherwise, you may be modifying either the projection or a texture matrix instead.
Do you get a 1 unit straight line? It seems that 90deg rot. around Y is going to have you looking at the side of a triangle with no depth.
You should try rotating around the Z axis instead and see if you get something that makes more sense.
OpenGL has two matrices related to the display of geometry, the ModelView and the Projection. Both are applied to coordinates before the data becomes visible on the screen. First the ModelView matrix is applied, transforming the data from model space into view space. Then the Projection matrix is applied with transforms the data from view space for "projection" on your 2D monitor.
ModelView is used to position multiple objects to their locations in the "world", Projection is used to position the objects onto the screen.
Your code seems fine, so I assume from reading the documentation you know what the nature of functions like glPushMatrix() is. If rotating around Z still doesn't make sense, verify that you're editing the ModelView matrix by calling glMatrixMode.
The "accepted answer" is not fully correct - rotating around the Z will not help you see this triangle unless you've done some strange things prior to this code. Removing a glOrtho(...) call might have corrected the problem in this case, but you still have a couple of other issues.
Two major problems with the code as written:
Have you positioned the camera previously? In OpenGL, the camera is located at the origin, looking down the Z axis, with positive Y as up. In this case, the triangle is being drawn in the same plane as your eye, but up and to the right. Unless you have a very strange projection matrix, you won't see it. gluLookat() is the easiest command to do this, but any command that moves the current matrix (which should be MODELVIEW) can be made to work.
You are drawing the triangle in a left handed, or clockwise method, whereas the default for OpenGL is a right handed, or counterclockwise coordinate system. This means that, if you are culling backfaces (which you are probably not, but will likely move onto as you get more advanced), you would not see the triangle as expected. To see the problem, put your right hand in front of your face and, imagining it is in the X-Y plane, move your fingers in the order you draw the vertices (1,1) to (3,2) to (3,1). When you do this, your thumb is facing away from your face, meaning you are looking at the back side of the triangle. You need to get into the habit of drawing faces in a right handed method, since that is the common way it is done in OpenGL.
The best thing I can recommend is to use the NeHe tutorials - http://nehe.gamedev.net/. They begin by showing you how to set up OpenGL in several systems, move onto drawing triangles, and continue slowly and surely to more advanced topics. They are very easy to follow.
Regarding Projection matrix, you can find a good source to start with here:
http://msdn.microsoft.com/en-us/library/bb147302(VS.85).aspx
It explains a bit about how to construct one type of projection matrix. Orthographic projection is the very basic/primitive form of such a matrix and basically what is does is taking 2 of the 3 axes coordinates and project them to the screen (you can still flip axes and scale them but there is no warp or perspective effect).
transformation of matrices is most likely one of the most important things when rendering in 3D and basically involves 3 matrix stages:
Transform1 = Object coordinates system to World (for example - object rotation and scale)
Transform2 = World coordinates system to Camera (placing the object in the right place)
Transform3 = Camera coordinates system to Screen space (projecting to screen)
Usually the 3 matrix multiplication result is referred to as the WorldViewProjection matrix (if you ever bump into this term), since it transforms the coordinates from Model space through World, then to Camera and finally to the screen representation.
Have fun