OpenGL glRotatef() Transformation doesn't "stick"

This topic is 2682 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Hi all,

I am trying to implement user input to navigate around a generated terrain. I am using SDL to create the window, and manage keystroke events. All of the drawing, rendering etc. is in OpenGL. My problem is this:
Instead of using gluLookAt(), I have written custom routines as indicated in the "red book" (Chapter 3 - Viewing Advanced try this section in 'Viewing Transformations' section of that chapter.) My glTranslatef() functions move the POV based on user input, BUT when you 'pivot' you point of view (Rotate about the y-axis) The view rotates around the POV. But - as soon as the keyup event occurs, the viewpoint "Snaps" back to wherever it was before the last tranformation occurred. So basically, it's like walking around, but whenever you spin, you are immediately forced back into the heading you had before you attempted to spin.
I am somewhat new to OpenGL but feel fairly comfortable with most of the concepts. I have attempted a wide variety of fixes to troubleshoot this to no avail. The following is my code, commented to try to illustrate what I'm trying to do. This code is merely proto-type for learning purposes and won't resemble anything I would do in production so any comments concerning optimization, design suggestions are certainly welcome, but I would really appreciate some help concerning this.

//following values are incremented / decremented per event keystrokefloat Ang = 0.0;float x_pos = 0.0;float y_pos = 0.0;float z_pos = 0.0;bool x_rot = false;bool y_rot = false;float x_input = 0.0;float y_input = 4.85;float z_input = 0.0; // This function actually builds the terrainvoid buildTerrain(){ // Here, an 80X80 array is generated with height values to use as vertices for my GL_QUADS    //implementing glList since these values are static.    glNewList(1, GL_COMPILE);    // Terrain rendering routine goes here       glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);    glBindTexture(GL_TEXTURE_2D, myTexture);//texture mapping for terrain    glBegin(GL_QUADS);//draws the polygons based the values obtained by the array generated above (or described rather.)        for(int x = 0; x<tWidth-1; x++){        for(int y = 0; y<tHeight-1; y++){            glTexCoord2f(0.0f, 0.0f);            glVertex3f(x+0, terrain[x+0][y+1], y+1);            glTexCoord2f(1.0f, 0.0f);            glVertex3f(x+1, terrain[x+1][y+1], y+1);            glTexCoord2f(1.0f, 1.0f);            glVertex3f(x+1, terrain[x+1][y+0], y+0);            glTexCoord2f(0.0f, 1.0f);            glVertex3f(x+0, terrain[x+0][y+0], y+0);                    }    }     glEnd();    glEndList();    }//Here is where I attempt to perform all of my transformations:void mainLoop() {    while(true) {        processEvents();//y,x,z *_input are incremented based on keypresses (the events are mapped in code below.)        y_input += y_pos;        x_input += x_pos;        z_input += z_pos;                // Graphical commands...//We are in the GL_MODELVIEW matrix mode here. This was the last matrix mode set in the function: setupOpenGL(). //I didn't provide that code since I'm fairly certain it's not relavant. It sets the perspective, lighting, loads textures, and fog.        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);        glLoadIdentity();//x_rot set to "true" if the right arrow key is depressed, when true,the polygons above rotate counter clockwise.              if (x_rot) {            Ang += .5;           glRotatef(Ang, 0.0, 1.0, 0.0);                } // if x_rot is false, no rotation occurs but the viewing plans "snaps //back to the world coordinates it had before the rotate call (but after the translate calls.) //y_rot set to "true" if the left arrow key is depressed, when true,the polygons above rotate clockwise.          if (y_rot) {           Ang += .5;           glRotatef(Ang, 0.0, -1.0, 0.0);            }//This translate function sets the user at eye level with the rendered terrain. removing this does not affect the rotation bevavior        glTranslatef(-tWidth/2, -12, -tHeight/2);//This translation works as intended        glTranslatef(x_input, y_input, z_input);        glCallList(1); // <--(Render terrain from list)        SDL_GL_SwapBuffers();            }}// Handle SDL keypressesvoid handleKeys(SDL_keysym* keysym, bool state) {//the state variable is true if a key is pressed down, false when the key is released.    if (state) {       switch(keysym->sym) {         case SDLK_ESCAPE:                 endProgram(0);              break;         case SDLK_UP:             y_pos -= .10;             break;         case SDLK_DOWN:             y_pos += .10;             break;//x and z transformations are set similarly.//tell main() that a rotation is occuring.          case SDLK_RIGHT:             x_rot = true;             break;         case SDLK_LEFT:             y_rot = true;             break;       }    } else {         switch(keysym->sym) {            case SDLK_ESCAPE:                    endProgram(0);                 break;            case SDLK_UP:                y_pos = 0.0;                break;            case SDLK_DOWN :                y_pos = 0.0;                break;  //tell main() to stop rotating. Reset the Angle about which to rotate to zero.            case SDLK_RIGHT:                 Ang = 0;                 x_rot = false;                 break;            case SDLK_LEFT:                 Ang = 0;                 y_rot = false;                 break;            }     }          } // Process SDL eventsvoid processEvents() {    SDL_Event event;    while(SDL_PollEvent(&event)) {        switch(event.type) {            case SDL_KEYDOWN:                   handleKeys(&event.key.keysym, true );                break;            case SDL_KEYUP:                handleKeys(&event.key.keysym, false);                   break;            case SDL_QUIT   : endProgram(0); break;        }            }    }

Sorry for the amount of code I posted. This issue is really nagging me and I have tried the following means to correct it:
use push/pop matrix to retain the rotated view. As anticipated, this achieved the opposite effect.
Change the Matrix mode to GL_PROJECTION for the rotation transformations only. This worked but the x y and z coords for my translation (even though I switched back to GL_MODELVIEW and called glLoadIdentity(). I was skeptical of this however since the red book and all other sources I've read concerning viewing transformations make absolutely no mention of changing the matrix mode when using rotate as a viewing transformation.

Whew. Sorry for the diatribe but any ideas would help. Thanks!

Share on other sites
At the beginning of mainLoop, you call glLoadIdentity. This loads the identity matrix on the current stack, wiping any previous values on the stack. You then only apply a rotation if x_rot or y_rot are true. So once you let go of the key and cause those variables to be false, the rotation is not applied any longer.

To fix this, you should be accumulating the rotation amounts into variables like you do with the x/y/z position and applying them via glRotatef always.

In other words, change x_rot and y_rot to floats that represent rotation about those axes. In the key down handling, add some value to x_rot or y_rot, depending. In mainloop, call glRotatef(x_rot, 1,0,0) and glRotate(y_rot,0,1,0) without guarding them with if statements.

Share on other sites
Thanks,

That makes sense. I had attempted to do something like that, but still had the if statements surrounding the rotation blocks, I believe. And it works. Thank you. Now this begs another question:
Now, my forward / backward translation occurs along the "world" z axis. I will research this but, without using gluLookAt(), what is the best recommended method for "re-aligning" the Z-axis to now be the POV once a rotation is complete? Should I alter the GL_PERSPECTIVE matrix? This makes sense, but is it costly or not the correct way to achieve this?

Share on other sites
I'll take a wild stab at the new problem,
Could you just convert your view rotation (y axis?) to radians, use it to come up with a vector along x/z that becomes "forwards/backwards"?

Share on other sites
to onfu: That's what I was thinking of doing. Just create a callable routine that will do just that. Another option would be changing the viewport to orient towards that new vector, although the vector computation would still be required. It would probably be easiest to keep it in the MODELVIEW matrix. This seems like a pretty straightforward transformation. What is industry standard for this sort of thing? The "red book" uses a flight simulator as an example but it doesn't mention anything about re-orienting your axes for rotational changes - kind of implying that openGL does that for you.

Share on other sites
Quote:
 Original post by eggmattersto onfu: That's what I was thinking of doing. Just create a callable routine that will do just that. Another option would be changing the viewport to orient towards that new vector, although the vector computation would still be required. It would probably be easiest to keep it in the MODELVIEW matrix. This seems like a pretty straightforward transformation. What is industry standard for this sort of thing? The "red book" uses a flight simulator as an example but it doesn't mention anything about re-orienting your axes for rotational changes - kind of implying that openGL does that for you.
You don't need to modify any matrices or transforms (particularly not the viewport or projection transforms) in order to move your object in the direction it's facing.

Typically, when using the fixed-function pipeline you would specify the position of your object using glTranslate*(). The position itself you can store and update in any way you see fit. It's common to update a position as follows (e.g.):
position += forward_direction * speed * time_delta;
So all you need is a forward direction vector.

Depending on your needs, you can easily construct the forward direction vector using trig as suggested previously. For other cases, you may want to build a transform representing the object's orientation and extract the direction vectors (side, up, and forward) from that transform.

Share on other sites
Sounds good. I'll update the forward direction vector (go forward using keypress) to be the vector the POV is facing after a rotation translation by taking onfu's advice.

Share on other sites
Almost there. Trying to update the translate vectors to be the components of the rotated angle. My trig, albeit rusty, is pretty good. I'm not afraid of the math and all. But, can some kind soul point me in the direction of a good 3D tutorial in OpenGL, or Game programming in general? Would much appreciate. Thanks!

Share on other sites
rough pseudo code should be something like:

//(move forwards)
glTranslatef(moveVectorX,0,moveVectorZ);

//(move backwards)
glTranslatef(-moveVectorX,0,-moveVectorZ);

-------------

probably some proper tweaking needed since I'm going off memory more to do with how I move game objects around in my 2D engine.

Share on other sites
Quote:
This is unlikely to work the way you expect it to. What you would typically do here would be to store the position of the camera, update that position using the 'moveVector' variables calculated above, and then submit the position as the argument to glTranslate*().

Share on other sites
the X and Z might not be correctly laid out either in what I wrote...I just figured it'd be enough to get it on the right track.

Of course since its returning to identity each frame you need to do a lot more than I posted there.

Share on other sites
Awesome thanks! That definitely has me on the right track. I'll let you know what I finally come up with.

• 10
• 11
• 11
• 10
• 12
• Similar Content

• Good Evening,
I want to make a 2D game which involves displaying some debug information. Especially for collision, enemy sights and so on ...
First of I was thinking about all those shapes which I need will need for debugging purposes: circles, rectangles, lines, polygons.
I am really stucked right now because of the fundamental question:
Where do I store my vertices positions for each line (object)? Currently I am not using a model matrix because I am using orthographic projection and set the final position within the VBO. That means that if I add a new line I would have to expand the "points" array and re-upload (recall glBufferData) it every time. The other method would be to use a model matrix and a fixed vbo for a line but it would be also messy to exactly create a line from (0,0) to (100,20) calculating the rotation and scale to make it fit.
If I proceed with option 1 "updating the array each frame" I was thinking of having 4 draw calls every frame for the lines vao, polygons vao and so on.
In addition to that I am planning to use some sort of ECS based architecture. So the other question would be:
Should I treat those debug objects as entities/components?
For me it would make sense to treat them as entities but that's creates a new issue with the previous array approach because it would have for example a transform and render component. A special render component for debug objects (no texture etc) ... For me the transform component is also just a matrix but how would I then define a line?
Treating them as components would'nt be a good idea in my eyes because then I would always need an entity. Well entity is just an id !? So maybe its a component?
Regards,
LifeArtist
• By QQemka
Hello. I am coding a small thingy in my spare time. All i want to achieve is to load a heightmap (as the lowest possible walking terrain), some static meshes (elements of the environment) and a dynamic character (meaning i can move, collide with heightmap/static meshes and hold a varying item in a hand ). Got a bunch of questions, or rather problems i can't find solution to myself. Nearly all are deal with graphics/gpu, not the coding part. My c++ is on high enough level.
Let's go:
Heightmap - i obviously want it to be textured, size is hardcoded to 256x256 squares. I can't have one huge texture stretched over entire terrain cause every pixel would be enormous. Thats why i decided to use 2 specified textures. First will be a tileset consisting of 16 square tiles (u v range from 0 to 0.25 for first tile and so on) and second a 256x256 buffer with 0-15 value representing index of the tile from tileset for every heigtmap square. Problem is, how do i blend the edges nicely and make some computationally cheap changes so its not obvious there are only 16 tiles? Is it possible to generate such terrain with some existing program?
Collisions - i want to use bounding sphere and aabb. But should i store them for a model or entity instance? Meaning i have 20 same trees spawned using the same tree model, but every entity got its own transformation (position, scale etc). Storing collision component per instance grats faster access + is precalculated and transformed (takes additional memory, but who cares?), so i stick with this, right? What should i do if object is dynamically rotated? The aabb is no longer aligned and calculating per vertex min/max everytime object rotates/scales is pretty expensive, right?
Drawing aabb - problem similar to above (storing aabb data per instance or model). This time in my opinion per model is enough since every instance also does not have own vertex buffer but uses the shared one (so 20 trees share reference to one tree model). So rendering aabb is about taking the model's aabb, transforming with instance matrix and voila. What about aabb vertex buffer (this is more of a cosmetic question, just curious, bumped onto it in time of writing this). Is it better to make it as 8 points and index buffer (12 lines), or only 2 vertices with min/max x/y/z and having the shaders dynamically generate 6 other vertices and draw the box? Or maybe there should be just ONE 1x1x1 cube box template moved/scaled per entity?
What if one model got a diffuse texture and a normal map, and other has only diffuse? Should i pass some bool flag to shader with that info, or just assume that my game supports only diffuse maps without fancy stuff?
There were several more but i forgot/solved them at time of writing
• By RenanRR
Hi All,
I'm reading the tutorials from learnOpengl site (nice site) and I'm having a question on the camera (https://learnopengl.com/Getting-started/Camera).
I always saw the camera being manipulated with the lookat, but in tutorial I saw the camera being changed through the MVP arrays, which do not seem to be camera, but rather the scene that changes:
#version 330 core layout (location = 0) in vec3 aPos; layout (location = 1) in vec2 aTexCoord; out vec2 TexCoord; uniform mat4 model; uniform mat4 view; uniform mat4 projection; void main() { gl_Position = projection * view * model * vec4(aPos, 1.0f); TexCoord = vec2(aTexCoord.x, aTexCoord.y); } then, the matrix manipulated:
..... glm::mat4 projection = glm::perspective(glm::radians(fov), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); ourShader.setMat4("projection", projection); .... glm::mat4 view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp); ourShader.setMat4("view", view); .... model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); ourShader.setMat4("model", model);
So, some doubts:
- Why use it like that?
- Is it okay to manipulate the camera that way?
-in this way, are not the vertex's positions that changes instead of the camera?
- I need to pass MVP to all shaders of object in my scenes ?

What it seems, is that the camera stands still and the scenery that changes...
it's right?

Thank you

• Sampling a floating point texture where the alpha channel holds 4-bytes of packed data into the float. I don't know how to cast the raw memory to treat it as an integer so I can perform bit-shifting operations.

int rgbValue = int(textureSample.w);//4 bytes of data packed as color
// algorithm might not be correct and endianness might need switching.
vec3 extractedData = vec3(  rgbValue & 0xFF000000,  (rgbValue << 8) & 0xFF000000, (rgbValue << 16) & 0xFF000000);
extractedData /= 255.0f;

• While writing a simple renderer using OpenGL, I faced an issue with the glGetUniformLocation function. For some reason, the location is coming to be -1.
Anyone has any idea .. what should I do?