glutIdleFunc() uses up 100% of the CPU on a single core and 50% on a dual core.
How can I get around this high CPU usage without using shrieks Win32 “Sleep()” function?
I could use a glutTimerFunc() to glutPostRedisplay() every so often but I’m wondering if there is a cleaner way to do it?
#include <GL/freeglut.h>
#include <GL/glu.h>
using namespace std;
class box
{
public:
int Width;
int Height;
float X;
float Y;
float R;
float G;
float B;
void draw()
{
glBegin(GL_POLYGON);
glColor3f(R, G, B);
glVertex2i(X, Y);
glVertex2i(X + Width, Y);
glVertex2i(X + Width, Y + Height);
glVertex2i(X, Y + Height);
glEnd();
}
};
class player : public box
{
public:
bool Jumped;
};
box Terrain;
box Sky;
box Grass;
box Sun;
player Player;
box Platform;
unsigned char keys[256];
void load()
{
Terrain.X = 0;
Terrain.Y = 300;
Terrain.Height = 200;
Terrain.Width = 500;
Terrain.R = (float) 66 / 255;
Terrain.G = (float) 48 / 255;
Terrain.B = (float) 8 / 255;
Grass.X = 0;
Grass.Y = 298;
Grass.Height = 4;
Grass.Width = 500;
Grass.R = (float) 0 / 255;
Grass.G = (float) 255 / 255;
Grass.B = (float) 0 / 255;
Sky.X = 0;
Sky.Y = 0;
Sky.Height = 300;
Sky.Width = 500;
Sky.R = (float) 184 / 255;
Sky.G = (float) 254 / 255;
Sky.B = (float) 254 / 255;
Sun.X = 20;
Sun.Y = 20;
Sun.Width = 50;
Sun.Height = 50;
Sun.R = (float) 237 / 255;
Sun.G = (float) 182 / 255;
Sun.B = (float) 65 / 255;
Player.X = 248;
Player.Y = 290;
Player.Width = 4;
Player.Height = 8;
Player.R = 0.0f;
Player.G = 0.0f;
Player.B = 0.0f;
Player.Jumped = false;
Platform.X = 0;
Platform.Y = 280;
Platform.Height = 3;
Platform.Width = 100;
Platform.R = 1.0f;
Platform.G = 0.0f;
Platform.B = 0.0f;
}
void keydown(unsigned char key, int x, int y)
{
keys[key] = true;
}
void keyup(unsigned char key, int x, int y)
{
keys[key] = false;
}
void process()
{
if (keys['a'])
{
Player.X -= 0.04f;
}
if (keys['d'])
{
Player.X += 0.04f;
}
if (keys['w'])
{
if (Player.Jumped == false)
{
Player.Jumped = true;
Player.Y -= 25.0f;
}
}
if (keys['q'])
{
glutLeaveMainLoop();
}
if (Player.Jumped == true)
{
if((Player.Y > Platform.Y - Player.Height) & (Player.X > Platform.X && Player.X < Platform.X + Platform.Width))
{
}
else
{
Player.Y += 0.025f;
}
if (Player.Y > 290.0f)
{
Player.Jumped = false;
}
}
glutPostRedisplay();
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
Terrain.draw();
Sky.draw();
Sun.draw();
Grass.draw();
Player.draw();
Platform.draw();
glutSwapBuffers();
}
int main(int argc, char **argv)
{
load();
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutInitWindowPosition(0, 0);
glutInitWindowSize(500, 500);
glutCreateWindow("Rendering Test");
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
gluOrtho2D(0, 500, 500, 0);
glutDisplayFunc(display);
glutKeyboardFunc(keydown);
glutKeyboardUpFunc(keyup);
glutIdleFunc(process);
glutMainLoop();
return 0;
}