how to rotate this openGl code - opengl

in this code i'm try to draw simple olympic ring and rotate it... the below work fine but i can't rotate the rings.. help me to solve this problme...
void myReshape (int width, int height)
{
glViewport (0, 0, width, height);
glMatrixMode (GL_PROJECTION);
glLoadIdentity();
gluOrtho2D (-5, 105, -5, 105);
glMatrixMode (GL_MODELVIEW);
glLoadIdentity ();
glTranslatef (0.375, 0.375, 0.0);
}
int main (int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition(100,100);
glutInitWindowSize(110*PIXEL_SIZE, 110*PIXEL_SIZE);
glutCreateWindow ("Olymipc Rings || rotation ");
glClearColor(1.0, 1.0, 1.0, 0.0);
glPointSize(PIXEL_SIZE);
glShadeModel (GL_FLAT);
glutDisplayFunc(display);
glutReshapeFunc(myReshape);
glutMainLoop();
return 0;
}

Use glRotatef(axis_x,axis_y,axis,z, angle) function before you draw the rings .
If you want to keep rotating the ring always use glutIdle(myidle) in your main() function and increment the value of angle there and also use glutPostRedisplay().
Use glPushMatrix() before and glPopMatrix() and after your ring drawings if you do not want the rotation to effect other drawings.
for example if you want to rotate your rings about x axis your code will look like
float angle=0;
void display (void) {
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_LINE_LOOP);
glVertex2i(-1,-1);
glVertex2i(100,-1);
glVertex2i(100,100);
glVertex2i(-1,100);
glEnd();
glPushMatrix(); //enters temporarily in a stack
for(int i = 0 ; i <5; i++)
{
glRotatef(1,0,0, angle)
glColor3f(color[i][0],color[i][1],color[i][2]);
draw_circle(center[i][0],center[i][1],ring_radius);
}
glPopMatrix(); // comes out of the stack
glScalef(0.001, 0.001, 0.001);
drawText(MESSAGE);
glFlush();
}
void myidle()
{
angle++; //angle value keeps on increasing
glutPostRedisplay(); // draws your drawing with updated value of angle to the screen
}
int main (int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition(100,100);
glutInitWindowSize(110*PIXEL_SIZE, 110*PIXEL_SIZE);
glutCreateWindow ("Olymipc Rings || rotation ");
glClearColor(1.0, 1.0, 1.0, 0.0);
glPointSize(PIXEL_SIZE);
glShadeModel (GL_FLAT);
glutDisplayFunc(display);
glutIdleFunc(myidle); //just like DisplayFunc keeps on getting calls
glutReshapeFunc(myReshape);
glutMainLoop();
return 0;
Read about glPopMatrix(), glPushMatrix() and call back functions like glutIdleFunc().
I hope this will help!!

Try this:
#include <stdlib.h>
#include <stdio.h>
#include <GL/glut.h>
#include <GL/gl.h>
#include <math.h>
#define PIXEL_SIZE 3
#define MESSAGE "hello world !"
void draw_circle(int x, int y, int r);
int ring_radius = 19;
int color[5][3]={{0,0,1}, {0,0,0},{1,0,0}, {1,1,0},{0,1,0}};
int center[5][2]={{15,60},{50,60},{85,60},{33,45},{68,45}};
//=========================================================
void drawText(const char * message)
{
glRasterPos2f((GLfloat)0, (GLfloat)-400);
while (*message)
{
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_12, *message);
glutStrokeCharacter(GLUT_STROKE_ROMAN,*message++);
}
}
void display (void)
{
int ms = glutGet(GLUT_ELAPSED_TIME);
glMatrixMode (GL_PROJECTION);
glLoadIdentity();
gluOrtho2D (-5, 105, -5, 105);
glMatrixMode (GL_MODELVIEW);
glLoadIdentity ();
glTranslatef (0.375, 0.375, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_LINE_LOOP);
glVertex2i(-1,-1);
glVertex2i(100,-1);
glVertex2i(100,100);
glVertex2i(-1,100);
glEnd();
const float deg_per_sec = 60.0f;
float angle = deg_per_sec * ( (float)ms / 1000.0f );
for(int i = 0 ; i <5; i++)
{
glColor3f(color[i][0],color[i][1],color[i][2]);
glPushMatrix();
glTranslatef( center[i][0], center[i][1], 0 );
glRotatef(angle, 0, 0, 1);
glTranslatef( -center[i][0], -center[i][1], 0 );
draw_circle(center[i][0],center[i][1],ring_radius);
glPopMatrix();
}
glScalef(0.001, 0.001, 0.001);
drawText(MESSAGE);
glFlush();
glutSwapBuffers();
}
void draw_circle(int center_x, int center_y , int radius)
{
int r = radius;
int h = 1 - r ; /*initialization */
int x = 0;
int y = r;
int dU=3;
int dD = 5 - 2*r;
int i = center_x;
int j = center_y;
glPointSize(6);
glBegin(GL_POINTS);
while( y > x )
{
if (h<0)
{
dU= dU + 2;
h = h + dU;
x = x + 1;
dD = dD + 2;
}
else
{
dD = 2*(x-y) + 5;
h = h + dD;
x = x + 1;
y = y - 1;
dU = dU + 2;
dD = dD + 4;
}
glVertex2i(x+i, y+j);
glVertex2i(-x+i, y+j);
glVertex2i(x+i, -y+j);
glVertex2i(-x+i,-y+j);
glVertex2i(y+i, x+j);
glVertex2i(y+i, -x+j);
glVertex2i(-y+i, x+j);
glVertex2i(-y+i, -x+j);
}
glEnd();
}
void myReshape (int width, int height)
{
glViewport (0, 0, width, height);
}
void idle()
{
glutPostRedisplay();
}
int main (int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB);
glutInitWindowPosition(100,100);
glutInitWindowSize(110*PIXEL_SIZE, 110*PIXEL_SIZE);
glutCreateWindow ("Olymipc Rings || rotation ");
glClearColor(1.0, 1.0, 1.0, 0.0);
glPointSize(PIXEL_SIZE);
glShadeModel (GL_FLAT);
glutDisplayFunc(display);
glutReshapeFunc(myReshape);
glutIdleFunc(idle);
glutMainLoop();
return 0;
}

glRotatef

Related

Moving a Sphere Around a Ellipse

I am trying to write a simple program that moves a Sphere around a Ellipse in OpenGL. I thought that if I set translate coordinates to the same as the Ellipse coordinates it would simulate motion.
This is the code I already have:
#include "stdafx.h"
#include <windows.h>
#include <GL/Gl.h>
#include <GL/GLU.h>
#include <GL/glut.h>
#include <math.h>
const float eRad = 6.5;
void drawSphere(void)
{
float x = 0.5;
float y = 0.4;
float z = 0.0;
glMatrixMode(GL_PROJECTION | GL_MODELVIEW);
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT);
// Draw the Ellipse
glColor3d(1.0, 0.0, 1.0);
glBegin(GL_LINE_STRIP);
for (float i = 0; i <= eRad; i += 0.1)
{
glVertex2f(x*cos(i), y*sin(i));
}
glEnd();
//Draw the Sphere
glColor3d(1.0, 1.0, 0.0);
glPushMatrix();
glTranslatef(0.5, 0, 0);
glutWireSphere(0.15, 30, 30);
glPopMatrix();
glFlush();
}
void animation(void)
{
float x = 0.2;
float y = 0.1;
float z = 0.0;
for (float i = 0; i <= eRad; i += 0.1)
{
glTranslated(x*cos(i), y*sin(i), z);
}
drawSphere();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(600, 600);
glutInitWindowPosition(0, 0);
glutCreateWindow("Moving Sphere Test");
glutDisplayFunc(drawSphere);
glutIdleFunc(animation);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glViewport(0, 0, 600, 600);
glutMainLoop();
}
The issue I am having is that the Ellipse is drawn in and so is the sphere, but its just staying at one point on the ellipse. So what am I doing wrong?
Yes, you need to use the functions correctly. The animation happens in glutDisplayFunc, the state setting can happen in glutIdleFunc(It does not have to). The gultTimerFunc() callback is what you want to be called every frame. I made a few modifications to your code. But you might want to use the GLUT correctly.
const float eRad = 6.5;
static float iter = 0.0;
void drawSphere(void)
{
float x = 0.5;
float y = 0.4;
float z = 0.0;
glMatrixMode(GL_PROJECTION | GL_MODELVIEW);
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT);
// Draw the Ellipse
glColor3d(1.0, 0.0, 1.0);
glBegin(GL_LINE_STRIP);
for (float i = 0; i <= eRad; i += 0.1)
{
glVertex2f(x*cos(i), y*sin(i));
}
glEnd();
//Draw the Sphere
glColor3d(1.0, 1.0, 0.0);
glPushMatrix();
glTranslatef(x*cos(iter), y*sin(iter), 0);
glutWireSphere(0.15, 30, 30);
glPopMatrix();
glFlush();
}
void animation(void)
{
iter = (iter < 6.5) ? iter+0.0001 : 0.0;
}
void Timer(int value) {
glutTimerFunc(33, Timer, 0);
glutPostRedisplay();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(600, 600);
glutInitWindowPosition(0, 0);
glutCreateWindow("Moving Sphere Test");
glutDisplayFunc(drawSphere);
glutIdleFunc(animation);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glViewport(0, 0, 600, 600);
Timer(0);
glutMainLoop();
}

Attempt at Box Translation Results in Hung Output?

I have been trying to animate a simple box that moves from left to right in the viewport while changing its color at random. It is meant to restart animating on a left mouse click, and close on a right mouse click. I have been debugging my code below, and though I think my methodology is reasonable, whenever I run the code, color change does not happen, and the animation hangs immediately. Principally I am wondering if this has to do with my use of Sleep() (which documentation leads me to believe should accept milliseconds as arguments), or if my loop structure in general is the problem. When I debug, though, it seems to exit the loop without throwing an exception.
Code below - any help in resolving the hanging issue?
#define GLUT_DISABLE_ATEXIT_HACK
#include <GL/glut.h>
#include <GL/gl.h>
#include <unistd.h>
//#include <assert.h>
float boxX = 0;
float boxY = 100;
float boxWidth = 75;
float boxHeight = 75;
void display(void)
{
int const windowWidth = glutGet(GLUT_WINDOW_WIDTH);
int const windowHeight = glutGet(GLUT_WINDOW_HEIGHT);
float const aspectRatio = (float)windowWidth / (float)windowHeight;
glClearColor (0.0, 0.0, 0.0, 0.0); /* Set background to black */
glClear (GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(aspectRatio, aspectRatio, aspectRatio, aspectRatio, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
while (boxX != windowWidth)
{
glClear (GL_COLOR_BUFFER_BIT);
float leftCorner = (float)boxX / windowWidth;
float rightCorner = leftCorner + (float)boxWidth / windowWidth;
float bottomCorner = (float)boxY / windowHeight;
float topCorner = bottomCorner + (float)boxY / windowHeight;
glBegin(GL_POLYGON);
glColor3f (rand(), rand(), rand()); //Randomize the box's colour as it moves
glVertex2d(leftCorner, topCorner);
glVertex2d(rightCorner, topCorner);
glVertex2d(rightCorner, bottomCorner);
glVertex2d(leftCorner, bottomCorner);
glEnd();
boxX += 0.1; //Move the box
glutSwapBuffers();
Sleep(200000);
glutPostRedisplay();
}
}
void mouseBehav( int button, int state, int x, int y )
{
if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN)
{
int windowID = glutCreateWindow ("Rainbow Box Animation");
glutDestroyWindow (windowID);
exit (0);
glutPostRedisplay();
}
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
boxX = 0;
glutPostRedisplay();
}
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize (500, 500);
glutInitWindowPosition ((glutGet(GLUT_SCREEN_WIDTH)-250)/2, (glutGet(GLUT_SCREEN_HEIGHT)-250)/2);
glutCreateWindow ("Rainbow Box Animation");
glutMouseFunc(mouseBehav);
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
using sleep() in a glutDisplayFunc() callback
No. Just...no.
Set up a timer callback for ~16-33ms and update boxX in that:
#include <GL/glut.h>
float boxX = 0;
float boxY = 0;
float boxWidth = 75;
float boxHeight = 75;
bool animate = false;
void timer( int value )
{
const int w = glutGet(GLUT_WINDOW_WIDTH);
if( boxX + boxWidth >= w / 2 )
{
animate = false;
}
if( animate )
{
boxX += 1; //Move the box
}
glutTimerFunc( 16, timer, 0 );
glutPostRedisplay();
}
void display()
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
const int w = glutGet(GLUT_WINDOW_WIDTH);
const int h = glutGet(GLUT_WINDOW_HEIGHT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho( -w/2, w/2, -h/2, h/2, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
const float leftCorner = boxX;
const float rightCorner = leftCorner + boxWidth;
const float bottomCorner = boxY;
const float topCorner = bottomCorner + boxHeight;
glBegin(GL_POLYGON);
glColor3ub(rand()%255, rand()%255, rand()%255); //Randomize the box's colour as it moves
glVertex2d(leftCorner, topCorner);
glVertex2d(rightCorner, topCorner);
glVertex2d(rightCorner, bottomCorner);
glVertex2d(leftCorner, bottomCorner);
glEnd();
glutSwapBuffers();
}
void mouse( int button, int state, int x, int y )
{
if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN)
{
exit(0);
}
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
boxX = 0;
animate = true;
}
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition( (glutGet(GLUT_SCREEN_WIDTH)-250)/2, (glutGet(GLUT_SCREEN_HEIGHT)-250)/ 2);
glutCreateWindow ("Rainbow Box Animation");
glutMouseFunc(mouse);
glutDisplayFunc(display);
glutTimerFunc( 0, timer, 0 );
glutMainLoop();
return 0;
}

OpenGL with two loops, one loop is not working

My OpenGL program is not working properly. Inside the drawScene() function I created two loops. One loop for GL_LINES another loop for GL_POINTS. The GL_LINES loop works fine but GL_POINTS loop doesn't work. Any help appreciated.
#include <iostream>
#include <stdlib.h>
#include <GL/glut.h>
#include <math.h>
#define PI 3.14159265
using namespace std;
//Called when a key is pressed
void handleKeypress(unsigned char key, int x, int y) {
switch (key) {
case 27: //Escape key
exit(0);
}
}
//Initializes 3D rendering
void initRendering() {
glEnable(GL_DEPTH_TEST);
glEnable(GL_COLOR_MATERIAL); //Enable color
glClearColor(0.7f, 0.9f, 1.0f, 1.0f); //Change the background to sky blue
}
//Called when the window is resized
void handleResize(int w, int h) {
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0, (double)w / (double)h, 1.0, 200.0);
}
float _angle = 0.0f;
float _cameraAngle = 0.0f;
float x = -1.5;
float y = -0.5;
//Draws the 3D scene
void drawScene() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glLineWidth (9.0f);
glBegin(GL_LINES);
glColor3f(1.0f, 0.0f, 0.0f);
double r = 0.5;
for(int c = 0;c<=360;c++){
double y = r*cos (c*PI/180);
double x = r*sin (c*PI/180);
glVertex3d(x,y,-5.0);
glVertex3d(0.0,0.0,-5.0);
}
glEnd();
glPointSize (7.0f);
glBegin(GL_POINTS);
glColor3f(0.0f, 1.0f, 0.0f);
double r = 1.0;
for(int c = 0;c<=360;c++){
double y = r*cos (c*PI/180);
double x = r*sin (c*PI/180);
glVertex3d(x,y,-5.0);
//glVertex3d(0.0,0.0,-5.0);
}
glEnd();
glutSwapBuffers();
//glutPostRedisplay();
}
void update(int value) {
_angle += 2.0f;
if (_angle > 360) {
_angle -= 360;
}
glutPostRedisplay();
glutTimerFunc(60, update, 0);
}
int main(int argc, char** argv) {
//Initialize GLUT
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(400, 400);
//Create the window
glutCreateWindow("two circle");
initRendering();
//Set handler functions
glutDisplayFunc(drawScene);
glutKeyboardFunc(handleKeypress);
glutReshapeFunc(handleResize);
glutTimerFunc(25, update, 0); //Add a timer
glutMainLoop();
return 0;
}
Right now, you're declaring the variable r in two places: where you set double r = 0.5; and at double r = 1.0;
Try changing it to:
double r = 0.5;
//First loop
r = 1.0;
//Second loop

randoming translation in GLUT turns bad

this is my cube. Once created, it has a random x position on either -2, -1, 0, 1, or 2.
void cube(void)
{
srand (time(0));
int cube_posX;
int lowv = -2;
int highv = 2;
cube_posX = rand() % (highv - lowv + 1) + lowv;
glTranslatef(cube_posX, 0.0, cube_angle);
glRotatef(cube_angle, 90.0, 0.0, 1.0);
glutSolidCube(0.25);
}
and this is how I move the cube slowly forward
void MOVE_CUBE(int value)
{
cube_posZ = cube_posZ - 0.01;
glutPostRedisplay();
glutTimerFunc(25, MOVE_CUBE, 0);
}
and finally putting them in display:
void init(void)
{
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
}
float cam_eyeX = 0.0, cam_eyeY = 1.5, cam_eyeZ = 5.0;
float cam_centerX = 0.0, cam_centerY = 0.0, cam_centerZ = 0.0;
void display(void)
{
glClearColor(1.0,1.0,1.0,1.0); //to add background color (white)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
gluLookAt(cam_eyeX, cam_eyeY, cam_eyeZ, cam_centerX, cam_centerY, cam_centerZ, 0.0, 1.0, 0.0); //camera! (cam position X, cam position Y, cam position Z, cam target X, cam target Y, cam target Z, up position X, up position Y, up position Z)
cube();
glutSwapBuffers();
angle += 0.05; //to affect the glRotate function
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.0, 100.0);
glMatrixMode (GL_MODELVIEW);
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH); // Set up display buffer
glutInitWindowSize(750, 500); //window's size
glutInitWindowPosition(100, 100); //window's position
glutCreateWindow("Hendra Ganteng!"); //window's title
init();
glutDisplayFunc(display);
glutIdleFunc (display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard_Handler);
MOVE_CUBE(0);
glutMainLoop();
return 0;
}
But when I see it in action, the cube moves forward flawlessly, but keeps changing x position onto those 5 possibilities (-2,-1,0,1,2) every 0.5 to 1 second. If I disable the srand(time(0)), the cube changes its x position rapidly. I just want to make it stay in 1 x position so then I can call more cubes in different x position. Could someone please kindly what's wrong in my code?
How is that behaviour not expected? You are generating a random X position every time you display your cube. If you re-seed the random number generator using the time, then it will be start a different sequence whenever the time changes (once per second).
Instead, you should pre-generate your cube(s). How about this:
// Global cube data
struct Cube {
int x;
double angle;
};
vector<Cube> cubes;
const int num_cubes = 1;
// Example initialisation...
void InitCubes()
{
cubes.reserve(num_cubes);
for( int i = 0; i < num_cubes; i++ )
{
Cube cube;
cube.x = rand() % (highv - lowv + 1) + lowv;
cube.angle = 0.0;
cubes.push_back(cube);
}
}
Now the update/display cycles simply need to modify the angle, but not the x-position.
void UpdateCube( Cube & cube )
{
cube.angle += 0.05;
}
void DisplayCube( Cube & cube )
{
glTranslatef((double)cube.x, 0.0, cube.angle);
glRotatef(cube.angle, 90.0, 0.0, 1.0);
glutSolidCube(0.25);
}
In your main function, call InitCubes() during startup.
In your display function, do this:
void display(void)
{
glClearColor(1.0,1.0,1.0,1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
gluLookAt(cam_eyeX, cam_eyeY, cam_eyeZ, cam_centerX, cam_centerY, cam_centerZ, 0.0, 1.0, 0.0);
// Display cubes
for( int i = 0; i < cubes.size(); i++ ) DisplayCube( cubes[i] );
glutSwapBuffers();
glFlush();
// Update cubes for next render cycle.
for( int i = 0; i < cubes.size(); i++ ) UpdateCube( cubes[i] );
}

Delta zeta not applied by gltranslatef

The program should simulate a planet rotating around another planet.
I use gltranslatef to let the planet move around the bigger planet, but the problem is that the planet should hide when is over the bigger planet, because dz is -0.5.
But if I test the program I always see the red planet over the blue one.
Another problem I have: the planet rotates too fast, how do I slow it?
#include <OpenGL/OpenGL.h>
#include <GLUT/GLUT.h>
#include "utility.h"
GLfloat dx=0.0;
GLfloat dz=-0.5;
bool plus=true;
void init()
{
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glLoadIdentity();
glOrtho(-1, 1, -1, 1, -1, 1);
glEnable(GLUT_DEPTH);
}
void render()
{
glClearColor(BLACK);
glClear(GL_COLOR_BUFFER_BIT);
glColor4f(BLUE);
glutWireSphere(0.25, 100, 100);
glPushMatrix();
glLoadIdentity();
glTranslatef(-0.5+dx, 0.0, -dz);
glColor4f(RED);
glutWireSphere(0.05, 100, 100);
glPopMatrix();
glFlush();
}
void idle()
{
if(plus)
{
dx+=0.05;
}
else
{
dx-=0.05;
}
if(dx>=1.0)
{
dx=0.5;
plus=false;
}
else if(dx<=-0.0)
{
dx=0.0;
plus=true;
}
glutPostRedisplay();
}
int main(int argc, const char * argv[])
{
glutInit(&argc, (char**)argv);
glutInitWindowSize(500, 500);
glutInitWindowPosition(150, 150);
glutInitWindowPosition(0, 0);
glutCreateWindow("Simple");
glutIdleFunc(idle);
init();
glutDisplayFunc(render);
glutMainLoop();
return 0;
}
I haven't understood well how does the idle function work, why it gets called so many times? Can't I choose a time interval with which the idle function gets called?
More info: RED and BLUE are RGB floats, defined in the utility.h header file.
plus is a bool that is used to know if I have to decrease or increase dx.
Give this a shot:
#include <GL/glut.h>
double GetSeconds()
{
return glutGet(GLUT_ELAPSED_TIME) / 1000.0f;
}
void render()
{
glClearColor(0,0,0,0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glColor3ub(0,0,255);
glutWireSphere(0.25, 100, 100);
glPushMatrix();
glLoadIdentity();
static double prv = GetSeconds();
double cur = GetSeconds();
double delta = cur - prv;
prv = cur;
const float DEG_PER_SEC = 60.0f;
static float angle = 0.0f;
angle += DEG_PER_SEC * delta;
while( angle > 360 ) angle -= 360;
glPushMatrix();
glRotatef( angle, 0, 1, 0 );
glTranslatef( 0.5, 0, 0);
glColor3ub(255,0,0);
glutWireSphere(0.05, 100, 100);
glPopMatrix();
glutSwapBuffers();
}
void reshape(int w, int h)
{
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-1, 1, -1, 1, -1, 1);
}
void timer(int extra)
{
glutPostRedisplay();
glutTimerFunc(16, timer, 0);
}
int main(int argc, const char * argv[])
{
glutInit(&argc, (char**)argv);
glutInitWindowSize(500, 500);
glutInitWindowPosition(150, 150);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("Simple");
glutReshapeFunc(reshape);
glutTimerFunc(0, timer, 0);
glutDisplayFunc(render);
glEnable( GL_DEPTH_TEST );
glutMainLoop();
return 0;
}
Important parts:
Explicit glMatrixMode() calls
Calling glutInitDisplayMode() before glutCreateWindow()
Double-buffering requires glutSwapBuffers()
Clearing the depth buffer via GL_DEPTH_BUFFER_BIT
glEnable( GL_DEPTH_TEST )
glRotatef() for planet rotation
Timer-based animation