Luren Wang
Luren Wang

Reputation: 55

Wrong display when using glutReshapeFunc to change window size

I have know that glutReshapeFunc can be used to react to window resize, so I used it to reset projection matrix and render shape to match the window. The code is as the following:

#include <GLUT/glut.h>

GLsizei wndWidth = 400;
GLsizei wndHeight = 300;

void init() {
    glClearColor(1.0, 1.0, 1.0, 0.0);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0, 400, 0, 300);
}

void drawSegment() {
    glClear(GL_COLOR_BUFFER_BIT);

    glColor3f(0, 0, 1.0);

    glBegin(GL_LINE_LOOP);
    glVertex2i(10, 10);
    glVertex2i(wndWidth-10, wndHeight-10);
    glVertex2i(wndWidth-10, 10);
    glEnd();

    glFlush();
}

void reshapeFunc(int width, int height) {


    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0, GLdouble(width), 0, GLdouble(height));

    glClear(GL_COLOR_BUFFER_BIT);

    wndWidth = width;
    wndHeight = height;
}

int main(int argc, char **argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);

    glutInitWindowSize(400, 300);
    glutInitWindowPosition(0, 0);
    glutCreateWindow("Draw Window");

    init();
    glutDisplayFunc(drawSegment);
    glutReshapeFunc(reshapeFunc);

    glutMainLoop();
}

In my opinion, After window resize, the triangle should always take up half of the window. But in fact, the triangle remains its size after window resize, as if wndWidth and wndHeight does not change in drawSegment. So why i get the wrong result and how can i fix it?

Upvotes: 1

Views: 52

Answers (1)

Rabbid76
Rabbid76

Reputation: 211219

The projection matrix transforms the view coordinates to clip coordinates and clip coordinates are transformed to normalized device coordinates (at orthographic projection clip coordinates and normalized device coordinates are equal).
How the normalized device coordinates are mapped to window coordinates is specified by glViewport.
After the size of the window has changed you have to respecify the mapping:

void reshapeFunc(int width, int height) {

    glViewport(0, 0, width, height);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0, GLdouble(width), 0, GLdouble(height));

    wndWidth = width;
    wndHeight = height;
}

Upvotes: 1

Related Questions