Issue displaying OpenGL terrain mesh in C - c

I am having issues making my openGL terrain display in the window. I just get a see-through window, and I'm not sure what I'm missing.
Here is my code:
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include <stdlib.h>
#define MAP_SCALE 20.0f
#define MAP_X 5
#define MAP_Z 5
int height[5][5] ={
{ 0, 0, 1, 1, 2 },
{ 0, 1, 2, 2, 3 },
{ 0, 1, 3, 2, 3 },
{ 0, 1, 2, 1, 2 },
{ 0, 0, 1, 1, 1 } };
float terrain[5][5][3];
int x, z;
float aspect = 1.0f;
void initializeTerrain()
{
for (z = 0; z < MAP_Z; z++)
{
for (x = 0; x < MAP_X; x++)
{
terrain[x][z][0] = (float)(x);
terrain[x][z][1] = (float)height[x][z];
terrain[x][z][2] = -(float)(z);
}
}
}
void display(void){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glColor3f(1.0, 0.0, 0.0);
for (z = 0; z < MAP_Z-1; z++)
{
glBegin(GL_TRIANGLE_STRIP);
for (x = 0; x < MAP_X-1; x++)
{
glVertex3f(terrain[x][z][0], terrain[x][z][1], terrain[x][z][2]);
glVertex3f(terrain[x+1][z][0], terrain[x+1][z][1], terrain[x+1][z][2]);
glVertex3f(terrain[x][z+1][0], terrain[x][z+1][1], terrain[x][z+1][2]);
glVertex3f(terrain[x+1][z+1][0], terrain[x+1][z+1][1], terrain[x+1][z+1][2]);
}
glEnd();
}
glFlush();
}
void myInit(){
initializeTerrain();
glMatrixMode(GL_PROJECTION);
glViewport(0, 0, 500, 500);
gluLookAt(1,1,0, 0,0,0, 0.0, 1.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glClearColor(0.0, 0.0, 1.0, 1.0);
}
void reshape(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (w <= h)
glOrtho(-10.0, 10.0, -5.0 * (GLfloat) h / (GLfloat) w,
15.0 * (GLfloat) h / (GLfloat) w, -10.0, 10.0);
else
glOrtho(-10.0 * (GLfloat) w / (GLfloat) h,
10.0 * (GLfloat) w / (GLfloat) h, -5.0, 15.0, -10.0, 10.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void main(int argc, char** argv){
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutCreateWindow("A3");
myInit();
glutReshapeFunc(reshape);
glutDisplayFunc(display);
glutMainLoop();
}
When I resize, it fills with white, but I don't get the mesh. Can anyone help?
Thanks!

You requested a double buffered window, so you have to do a doublebuffer swap when you're done drawing. Replace that glFinish() in your display function with glutSwapBuffers().

Related

Draw cubes with random colors using OpenGL

I want every cube to have a random color but with this code the colors keep changing all the time
int espacioX = -500;
int espacioY = -500;
for(int i=1; i<=100; i++){
for(int j=1; j<=100; j++){
randomR = (double)rand() / (RAND_MAX);
randomG = (double)rand() / (RAND_MAX);
randomB = (double)rand() / (RAND_MAX);
glColor3f(randomR,randomG,randomB);
glTranslatef(espacioX,espacioY,0);
glutSolidCube(9);
glTranslatef(-espacioX,-espacioY,0);
espacioX+=10;
}
glTranslatef(-1000,0,0);
espacioY+=10;
}
How do I make them stay in the same color while the program is running?
Edit:
This is the comple code:
#include <windows.h>
/***** OpenGL library imports. *****/
#include<gl\glut.h> //basic header file for OpenGL
//#include <gl\glaux.h> // Header File For The Glaux Library
/***** C library imports. *****/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int ScreenWidth = 0;
int ScreenHeight = 0;
int last_x = 0, last_y = 0,left = 1,middle = 0,right = 0;
int zoom_y = 0;
int anglex=0, angley=0, anglez=0;
int lookfrom=450;
int ang=0;
void myGlutKeyboard(unsigned char Key, int x, int y)
{
printf("%5d\n",Key);
glutPostRedisplay();
}
void init_GL_params()
{
static GLfloat light_ambient[] = { .250, .250, .250, .250 };
static GLfloat light_diffuse[] = { .250, .250, .25, .250 };
static GLfloat light_specular[] = { .250, .250, .250, .250 };
static GLfloat light1_diffuse[] = { .250, .250, .250, .0 };
static GLfloat light1_specular[] = { .250, .250, .250, .0 };
glEnable (GL_LIGHTING);
glEnable (GL_LIGHT0);
glEnable (GL_LIGHT1);
glDisable (GL_TEXTURE_2D);
glDisable (GL_TEXTURE_GEN_S);
glDisable (GL_TEXTURE_GEN_T);
glShadeModel (GL_FLAT);
glEnable (GL_DEPTH_TEST);
glDepthFunc (GL_LESS);
glEnable (GL_CULL_FACE);
glCullFace (GL_BACK);
glFrontFace (GL_CCW);
glMatrixMode (GL_PROJECTION);
glLoadIdentity();
glLightfv (GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv (GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv (GL_LIGHT0, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT1, GL_DIFFUSE, light1_diffuse);
glLightfv(GL_LIGHT1, GL_SPECULAR, light1_specular);
glLightfv (GL_LIGHT1, GL_AMBIENT, light_ambient);
glColor3f (1.0, 1.0, 1.0);
}
void setLightPosition()
{
static GLfloat light_position[] = { 100, 200.0, 10, 1.0 };
static GLfloat light1_position[] = { -0.0, 300.0, 0.0, 1.0 };
// set the light position (for some reason we have to do this in model view.
glLightfv (GL_LIGHT0, GL_POSITION, light_position);
glLightfv(GL_LIGHT1, GL_POSITION, light1_position);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glEnable(GL_COLOR_MATERIAL);
}
void myGlutDisplay(void)
{
init_GL_params();
// clear the window
glClearColor (0,0,0,0); //Color de fondo R G B
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode (GL_MODELVIEW);
glLoadIdentity();
setLightPosition(); //Posici{on de la fuente de luz
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluPerspective(60.0f, 1.0, 1.0f, 10000.0f);
gluLookAt( //punto de vista
0 ,100 ,lookfrom , // desde donde veo xyz
0, 0, 0, // hacia donde veo xyz
0,1,0 );
glRotatef(anglex, 1.0, 0.0, 0.0);
glRotatef(angley, 0.0, 1.0, 0.0);
glRotatef(anglez, 0.0, 0.0, 1.0);
//Empieza a dibujar
int espacioX = 500;
int espacioY = 500;
double randomR, randomG, randomB;
for(int i=1; i<=100; i++){
for(int j=1; j<=100; j++){
randomR = (double)rand() / (RAND_MAX);
randomG = (double)rand() / (RAND_MAX);
randomB = (double)rand() / (RAND_MAX);
glColor3f(randomR,randomG,randomB);
glTranslatef(espacioX,espacioY,0);
glutSolidCube(9);
glTranslatef(-espacioX,-espacioY,0);
espacioX-=10;
}
glTranslatef(1000,0,0);
espacioY-=10;
}
glFlush(); // Flush The GL Pipeline
glutSwapBuffers();
}
void myGlutReshape2(int mWidth, int mHeight)
{
ScreenWidth = mWidth;
ScreenHeight = mHeight;
glViewport(0, 0, (GLsizei) ScreenWidth, (GLsizei) ScreenHeight);
glutPostRedisplay();
}
/****************************************************************/
void myGlutIdle(void)
{
glutPostRedisplay();
}
/***************************************************************/
void myGlutMouse(int button, int button_state, int x, int y){
if ( (button == GLUT_LEFT_BUTTON) && (button_state == GLUT_DOWN) )
{
last_x = x;
last_y = y;
left = 1;
middle = 0;
right = 0;
}
else if ((button == GLUT_RIGHT_BUTTON) && (button_state == GLUT_DOWN) )
{
zoom_y = y;
right = 1;
left = 0;
middle = 0;
}
}
void myGlutMotion(int x, int y){
if (left){
anglex+= (float) (y - last_y);
angley+= (float) (x - last_x);
last_x = x;
last_y = y;
}
if (right)
{
lookfrom += (y - zoom_y);
zoom_y = y;
}
}
void GlutInit(int argc, char** argv)
{
ScreenWidth = 700;
ScreenHeight = 700;
/****************************************/
/* Initialize GLUT and create window */
/****************************************/
glutInit(&argc, argv);
glutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE | GLUT_STENCIL ); //set up the display as a double buffer using RGB values
glutInitWindowPosition(90, 50); //set the position of where you want the window to open
glutInitWindowSize(ScreenWidth, ScreenHeight); //set how big you want the initial window to be
glutCreateWindow("Testing Virtual Environment" ); //what do you want the window to be called (titlebar text)
//register callbacks
glutDisplayFunc(myGlutDisplay); //Register the display callback
glutReshapeFunc(myGlutReshape2); // -- Resize handler
glutKeyboardFunc(myGlutKeyboard); // -- Keyboard handler
glutMouseFunc(myGlutMouse); // -- Mouse Click handler
glutMotionFunc(myGlutMotion); // -- Mous motion handler
glutIdleFunc(myGlutIdle); // -- Idle handler
glFlush();
}
int main( int argc, char **argv )
{
GlutInit(argc, argv);
glutMainLoop();
return 0;
}
It was a sample code so I just posted the part that I edited, sorry. When I did a cube or a sphere with an specific color it always stayed the same so i didn't realiza that this refresh the image all the time. I don't really understand the whole thing so I don't know where it's refreshing the image.
Why not set SEED to some constant value at start of myGlutDisplay(void). That will give you the same random values each frame without any big change in your code for example like this:
void myGlutDisplay(void)
{
init_GL_params();
// clear the window
glClearColor (0,0,0,0); //Color de fondo R G B
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode (GL_MODELVIEW);
glLoadIdentity();
setLightPosition(); //Posici{on de la fuente de luz
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluPerspective(60.0f, 1.0, 1.0f, 10000.0f);
gluLookAt( //punto de vista
0 ,100 ,lookfrom , // desde donde veo xyz
0, 0, 0, // hacia donde veo xyz
0,1,0 );
glRotatef(anglex, 1.0, 0.0, 0.0);
glRotatef(angley, 0.0, 1.0, 0.0);
glRotatef(anglez, 0.0, 0.0, 1.0);
//Empieza a dibujar
int espacioX = 500;
int espacioY = 500;
double randomR, randomG, randomB;
srand(0x98765432); // this is the SEED
for(int i=1; i<=100; i++){
for(int j=1; j<=100; j++){
randomR = (double)rand() / (RAND_MAX);
randomG = (double)rand() / (RAND_MAX);
randomB = (double)rand() / (RAND_MAX);
glColor3f(randomR,randomG,randomB);
glTranslatef(espacioX,espacioY,0);
glutSolidCube(9);
glTranslatef(-espacioX,-espacioY,0);
espacioX-=10;
}
glTranslatef(1000,0,0);
espacioY-=10;
}
glFlush(); // Flush The GL Pipeline
glutSwapBuffers();
}
The value of the SEED will give you the pattern. So changing the constant will change the colors. Beware wrong constant (like 0) can corrupt the randomness of the rand() function.
It seems like you are running this code inside another loop which means you are calculating your random variables every time the scene is redrawn, this would cause the colors to change and the obvious solution would be to poulate your list of cubes once and then iterate through the list drawing the cubes on each scene refresh.
However, without seeing the rest of your code it is unclear. Please include more information so we can give you a better answer.

OpenGL not displaying anything when gluLookAt called

I am working on a practice OpenGL program. I am basically trying to display a pyramid. I pasted the code I have so far bellow. The issue I am having is that when I call gluLookAt my screen becomes completely black. This does not make sense to me. My pyramid has triangles with dimensions bounded within a box of size (1, 1, 1) and it is at the origin. So therefore if I position the eye at something far away if (10, 10, 10) and look at (0, 0, 0) why do I not see the pyramid. When I comment out gluLookAt I can see it clearly.
#include <GL/glut.h>
#include <stdlib.h>
#include <stdio.h>
struct
{
GLuint trifan;
GLuint tribase;
GLuint colors;
} b;
void display();
void init_buffer();
void check_errors();
void reshape(int w, int h);
void keyboard(unsigned char k, int x, int y);
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitWindowSize(500, 500);
glutCreateWindow("Pyramid");
init_buffer();
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
glutMainLoop();
}
void init_buffer()
{
glGenBuffers(1, &(b.trifan));
glBindBuffer(GL_ARRAY_BUFFER, b.trifan);
GLfloat trifan[6][3] =
{
{0.0, 1.0, 0.0},
{1.0, 0.0, 1.0},
{-1.0, 0.0, 1.0},
{-1.0, 0.0, -1.0},
{1.0, 0.0, -1.0},
{1.0, 0.0, 1.0}
};
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 3 * 6, trifan, GL_STATIC_COPY);
glGenBuffers(1, &b.colors);
glBindBuffer(GL_ARRAY_BUFFER, b.colors);
GLfloat colors[6][3] =
{
{1.0, 0.0, 0.0},
{1.0, 0.0, 0.0},
{1.0, 0.0, 0.0},
{1.0, 0.0, 1.0},
{0.5, 0.0, 1.0},
{1.0, 0.0, 0.5},
};
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 3 * 6, colors, GL_STATIC_COPY);
check_errors();
}
void reshape(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60, (float)w / (float)h, 1.0, 100.0);
}
float angle = 0.0;
float zoom = 1.0;
void keyboard(unsigned char k, int x, int y)
{
if(k == 'x')
{
angle += 10;
}
else if(k == 'y')
{
angle -= 10;
}
else if(k == 'w')
{
zoom += 0.1;
}
else if(k == 's')
{
zoom -= 0.1;
}
glutPostRedisplay();
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotated(angle, 1.0, 0.0, 0.0);
gluLookAt(10.0, 10.0, 10.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
{
glBindBuffer(GL_ARRAY_BUFFER, b.trifan);
glVertexPointer(3, GL_FLOAT, 0, 0);
glBindBuffer(GL_ARRAY_BUFFER, b.colors);
glColorPointer(3, GL_FLOAT, 0, 0);
glDrawArrays(GL_TRIANGLE_FAN, 0, 6);
}
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
check_errors();
glFlush();
}
void check_errors()
{
GLint err = glGetError();
if(err != GL_NO_ERROR)
{
fputs((char*)gluErrorString(err), stderr);
exit(1);
}
}

strange output: Opengl

I have to create a room using openGL and glut. From what I see in the output it looks like the left wall gets drawn but I can't see the front wall at all. I only have to draw 2 walls and have the camera pointing towards the corner where the 2 walls meet. Any idea what I'm doing wrong?
My code:
#include <gl/gl.h>
#include <gl/glut.h>
/*defining colors used in the room*/
GLfloat black[] = {0.0, 0.0, 0.0, 1.0};
GLfloat white[] = {1.0, 1.0, 1.0, 1.0};
GLfloat brown[] = {165.0/255.0, 42.0/255.0, 42.0/255.0, 1.0};
void drawFloor()
{
glBegin(GL_POLYGON);
glColor4fv(black);
glVertex3f(0.0, 0.0, -3.0);
glVertex3f(1.0, 0.0, -3.0);
glVertex3f(2.0, 0.0, -3.0);
glEnd();
}
void drawWalls()
{
glBegin(GL_QUAD_STRIP);
glColor4fv(white);
glPolygonMode(GL_FRONT, GL_FILL);
int i;
//draw left wall
for (i = 0; i <= 5; i++)
{
glVertex3f(0.0, 0.0, i);
glVertex3f(0.0, 1.0, i);
}
//draw front wall
for(i = 1; i <= 5; i++)
{
glVertex3f(i, 0, 5);
}
glEnd();
}
void display()
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0.0, 0.0, -1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0);
drawFloor();
drawWalls();
glFlush();
}
void reshape(int w, int h)
{
glViewport(0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60, (GLfloat) w / (GLfloat) h, 1, 500);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void idleFunc()
{
glutPostRedisplay();
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(500, 500);
glutInitWindowPosition(0, 0);
glutCreateWindow("My room");
glEnable(GL_DEPTH_TEST);
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutIdleFunc(idleFunc);
glutMainLoop();
}

new to OpenGL: glutMouseFunc

I'm trying to change the sphere position after a mouse click but it doesnt work when using the x and y from glutMouseFunc ,, here is the code :
//
#include "stdafx.h"
#include <stdlib.h>
#include <GL/glut.h>
bool Cone=false , ConeSelected=false,
Cube=false, CubeSelected=false,
Sphere=false, SphereSelected=false,
Teapot=false, TeapotSelected =false,
Torus=false, TorusSelected=false;
static float XSphere=0, YSphere=-1.5 ,ZSphere=0;
void init(void)
{
GLfloat blankMaterial[] = {1.0, 0.0, 0.0};
GLfloat whiteDiffuseLight[] = {30};
glClearColor (0.0, 0.1, 0.2, 0.0);
glClearDepth(1.0);
glShadeModel (GL_FLAT);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_DEPTH_TEST);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, blankMaterial);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, blankMaterial);
glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, whiteDiffuseLight);
}
void display(void)
{
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
//Drawing Cube
if(Cube)
{
glPushMatrix();
glColor3f(0, 1, 0);
glTranslatef(-3,0,-3);
glRotatef(20, 1,0,0);
glutSolidCube(2);
glPopMatrix() ;
}
//drawing cone
if(Cone)
{
glPushMatrix();
glColor3f (1.0, 0.0, 1.0);
glTranslatef(0,2,0);
glRotatef(50, 1,0,0);
glutSolidCone(.5,1,10,10);
glPopMatrix() ;
}
//Drawing Solid Sphere
if(Sphere)
{
glPushMatrix();
glTranslatef(XSphere,YSphere,ZSphere);
glutSolidSphere(.5, 20, 20);
glPopMatrix();
glDisable(GL_DEPTH_TEST);
}
glColor3f (1.0f, 1.0f, 1.0f);
//drawing Torus
if(Torus)
{
glPushMatrix();
glColor3f (1.0, 1.0, 1.0);
glTranslatef(2,2,0);
glRotatef(60, 1,0,0);
glutSolidTorus(.2,.5,40,30);
glPopMatrix() ;
}
//Drawing teapot
if(Teapot)
{
glPushMatrix ();
glTranslatef (2.0, 0.0, 0.0);
glutSolidTeapot(.5);
glPopMatrix ();
}
glFlush();
glutSwapBuffers();
}
void reshape (int w, int h)
{
glViewport (0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluPerspective(60.0, (GLfloat) w/(GLfloat) h, 1.0, 20.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
}
void keyboard (unsigned char key, int x, int y)
{int modifiers = glutGetModifiers();
switch (key) {
case 'A':
Teapot=Cone=Sphere=Cube=Torus=true;
glutPostRedisplay();
break;
case 'D':
Teapot=Cone=Sphere=Cube=Torus=false;
glutPostRedisplay();
break;
case 'S':
Teapot=Cone=Cube=Torus=false;
Sphere=true;
TeapotSelected=ConeSelected=CubeSelected=TorusSelected=false;
SphereSelected=true;
break;
case 27:
exit(0);
break;
default:
break;
}
}
Here in the mouse section I tried to set the gltranslation in the above drawing sphere but when I checked the results for x and y they were large and that's why I couldnt see the sphere after clicking the mouse , how can i fix this ??
void MyMouse(int button, int state, int x, int y)
{
switch (button)
{
case GLUT_LEFT_BUTTON:
if(state == GLUT_UP)
{
if (SphereSelected)
{
Cone=Cube=Torus=Teapot=false;
Sphere=true;
XSphere=x;
YSphere=y;
ZSphere=1;
glutPostRedisplay();
}
}
break;
}
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB|GLUT_DEPTH);
glutInitWindowSize (900, 900);
glutInitWindowPosition (0, 100);
glutCreateWindow ("Scene Modeling and Interaction");
init ();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutMouseFunc(MyMouse);
glutMainLoop();
return 0;
}
The x and y that the mouse function gives you are in screen pixel coordinates, not in the coordinates that your scene uses. In order to do this, you have to center your coordinates (by subtracting by half your screen size) and scaling them to about your screen size (by dividing them by something on the order of your screen size).
Thus, you probably want to do something like
XSphere = (x - 450) * 3.0 / 900;
YSphere = (450 - y) * 3.0 / 900;
and play around with the 3.0 until it gives you something reasonable.

OpenGL moving objects from corner

I have an openGL program thats using GLUT and I'm stuck with moving it from the top left corner to bottom right when i resize the window. I'm trying to get a ratio down and i cant figure it out.
#include <stdio.h>
#include <stdlib.h>
#include <GLUT/glut.h>
//global variables
GLsizei wh = 500, ww = 500;
double height;
double width;
double top = 500;
double bottom = 450;
int right = 50;
int left = 0;
double ratiowidth = 500/500;
double ratioheight = 500/500;
void myinit(){
glClearColor (0.0, 0.0, 0.0, 0.0);
}
void reshape(int w, int h){
if(h == 0){
h = 1;
}
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, (GLsizei) w, 0, (GLsizei)h);
glViewport(0,0,w,h);
glMatrixMode(GL_MODELVIEW);
int difference = h - wh;
int difference2 = w - ww;
left = left + difference2;
right = right + difference2;
wh = (GLsizei)h;
ww = (GLsizei)w;
height = h;
width = w;
}
void mouse(int button, int state, int x, int y){
if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN){
top = height;
bottom = height - 50;
right = 50;
left = 0;
ratiowidth = width/height;
ratioheight = height/width;
}
if(button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN){
exit(0);
}
}
void display(){
glClear (GL_COLOR_BUFFER_BIT);
glColor3i (rand(), rand(), rand());
glBegin(GL_POLYGON);
glVertex3f (left,top,0.0);
glVertex3f (right, top, 0.0);
glVertex3f (right, bottom, 0.0);
glVertex3f (left, bottom, 0.0);
glEnd();
if(bottom == 0 || bottom < 0)
bottom = 0;
else{
left = left + ratiowidth;
right = right + ratiowidth;
top = top - ratioheight;
bottom = bottom - ratioheight;
}
glutSwapBuffers();
usleep(10000);
glutPostRedisplay();
}
int main(int argc, char** argv) {
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(ww, wh);
glutInitWindowPosition(100,100);
glutCreateWindow("moving Square");
myinit();
glutReshapeFunc(reshape);
glutDisplayFunc(display);
glutMouseFunc(mouse);
glutMainLoop();
return 0;
}
glBegin(GL_POLYGON);
glVertex3f (left,top,0.0);
glVertex3f (right, top, 0.0);
glVertex3f (right, bottom, 0.0);
glVertex3f (left, bottom, 0.0);
glEnd();
Careful with your winding order. glFrontFace() defaults to GL_CCW. Perhaps you meant this:
glBegin(GL_POLYGON);
glVertex3f (left, bottom, 0.0);
glVertex3f (right, bottom, 0.0);
glVertex3f (right, top, 0.0);
glVertex3f (left,top,0.0);
glEnd();
EDIT: This is what I think you were trying to do:
#include <GL/glut.h>
struct State
{
double x; // in units
double y;
double xvel; // in units per second
double yvel;
};
State curState = { 0 };
void myinit()
{
curState.xvel = 100;
curState.yvel = 100;
}
void Integrate( State* state, double dt )
{
state->x += state->xvel * dt;
state->y += state->yvel * dt;
}
double GetSeconds()
{
return glutGet(GLUT_ELAPSED_TIME) / 1000.0f;
}
void reshape(int w, int h)
{
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, (GLsizei)w, 0, (GLsizei)h);
}
void mouse(int button, int state, int x, int y)
{
if(button == GLUT_LEFT_BUTTON && state == GLUT_UP)
{
curState.x = 0;
curState.y = 0;
}
if(button == GLUT_RIGHT_BUTTON && state == GLUT_UP)
{
exit(0);
}
}
void display()
{
glClearColor (0.0, 0.0, 0.0, 0.0);
glClear (GL_COLOR_BUFFER_BIT);
float w = 20;
float h = 20;
float x = curState.x;
float y = curState.y;
glColor3ub(rand()%255, rand()%255, rand()%255);
glBegin(GL_QUADS);
glVertex2f( x - w/2, y - h/2 );
glVertex2f( x + w/2, y - h/2 );
glVertex2f( x + w/2, y + h/2 );
glVertex2f( x - w/2, y + h/2 );
glEnd();
static double lastTime = GetSeconds();
double curTime = GetSeconds();
Integrate( &curState, curTime - lastTime );
lastTime = curTime;
glutSwapBuffers();
}
void timer(int extra)
{
glutPostRedisplay();
glutTimerFunc(16, timer, 0);
}
int main(int argc, char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition(100,100);
glutCreateWindow("moving Square");
myinit();
glutReshapeFunc(reshape);
glutTimerFunc(0, timer, 0);
glutDisplayFunc(display);
glutMouseFunc(mouse);
glutMainLoop();
return 0;
}
Be aware that there are probably some C++-isms in there :)

Resources