PDA

View Full Version : Draw a polygon when mouse is clicked, issue



ramy1989
04-09-2012, 07:09 PM
The goal is: I have a window initialized with GLUT (600x600), it's all white, I have to listen the mouse, and paint it red when the mouse is clicked.
So whenever the mouse is clicked, it must become red.
I have written this code:



#include <stdlib.h>
#include <stdarg.h>
#include <GLUT/GLUT.h>
#include <OpenGL/OpenGL.h>

double width=600;
double height=600;

void processMouse(int button, int state, int x, int y)
{
if(state==GLUT_DOWN)
{
glColor4f(1.0,0.0,0.0,0.0);
glBegin(GL_POLYGON);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(1.0, 0.0, 0.0);
glVertex3f(1.0, 1.0, 0.0);
glVertex3f(0.0, 1.0, 0.0);
glEnd();
glFlush();
}
}

static void render()
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
glutMouseFunc(processMouse);

}

int main(int argc, char **argv)
{
glutInit(&amp;argc,argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(width, height);
glutCreateWindow("Board");
glutDisplayFunc(render);
glutMainLoop();
}


But the problem is that when I run the program, if I click somewhere on the window with the mouse, only a part of the window becomes red (the part on bottom right).If I open a whatever graphical application (like google chrome for example) after having clicked the mouse, it turns red.
But I don't get why it doesn't turn red before, from when I draw the polygon in processMouse function.It's like ignoring the commands.

carsten neumann
04-10-2012, 04:39 AM
You should not issue drawing commands from the mouse callback, their effect is lost the next time your display callback runs - all rendering should happen in your display callback, the other callbacks can modify your programs state (e.g. a variable) to indicate what needs to be drawn.
You should also not register the mouse callback from your display callback, but instead do it as part of program initialization.
Since you are using double buffering, your display callback should end with a call to glutSwapBuffers() so that what you've just drawn to the back buffer becomes visible.