So I'm trying to draw a zigzag line inside the window, which gets its x and y coordinates from the mouse clicks. So after every click on the window, the last two vertices will be connected together and so on.
#include <iostream>
#include <GL/glut.h>
void init(){
glClearColor(1.0, 1.0, 1.0, 1.0);
glViewport(0, 0, 800, 400);
gluOrtho2D(0.0, 800.0, 0.0, 400.0);
}
int x1, y1, x2, y2, count = -1;
void mouse(int key, int state, int x, int y){
if(key == GLUT_LEFT_BUTTON){
if(state == GLUT_DOWN){
count++;
if(count%2 == 0){
x1 = x;
y1 = 400.0-y;
}
else{
x2 = x;
y2 = 400.0-y;
glutPostRedisplay();
}
}
}
}
void Display(){
glClear(GL_COLOR_BUFFER_BIT);
glColor3i(1, 1, 1);
if(count != 0){
glBegin(GL_LINE_STRIP);
glVertex2i(x1, y1);
glVertex2i(x2, y2);
glEnd();
}
glFlush();
}
int main(int argc, char* argv[]) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
glutInitWindowSize(800, 400);
glutCreateWindow("Vije e thyer");
init();
glutMouseFunc(mouse);
glutDisplayFunc(Display);
glutMainLoop();
return 0;
}
I expect it to show every line drawn on the window, but the last line disappears as soon as a new one is created. I think that's a problem with glutPostRedisplay.
All your old lines disappear because you call glClear
, which clears your screen. Calling glClear every frame is a good idea, but now after calling glClear, you only draw a single line segment between the last two points you clicked on.
What you could do to make it work is just skip the call to glClear
, but that's really not the way OpenGL is intended to be used, and it's not flexible at all (what if you want to make the lines wiggle a bit, or change color?). Additionally it is error-prone, especially with double-buffering. Suppose you click twice on consecutive frames. One of your line segments only ever gets drawn in one frame, so it is only ever drawn to one of the two buffers. This will make your segment appear to flicker on your screen. Or if you change your window size, you'll definitely lose some of the information in your screen buffers (if not the entire buffer contents).
What you need to do is keep track of all the points you want to draw, in a list or something, then redraw the entire zig-zag line each frame.