Search code examples
c++openglresizerenderscale

How do you adjust an opengl viewport size without scaling its contents


When my window is resized, i don't want the contents to scale but just to increase the view port size. I found this while searching on stackoverflow (http://stackoverflow.com/questions/5894866/resize-viewport-crop-scene) which is pretty much the same as my problem. However I'm confused as to what to set the Zoom to and where, i tried it with 1.0f but then nothing was shown at all :s

This is resize function code at the moment which does scaling:

void GLRenderer::resize() {
    RECT rect;
    int width, height;
    GLfloat aspect;

    GetClientRect(hWnd, &rect);
    width = rect.right;
    height = rect.bottom;

    if (height == 0) {
        height = 1;
    }

    aspect = (GLfloat) width / height;

    glViewport(0, 0, width, height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45.0, aspect, 0.1, 100.0);
    glMatrixMode(GL_MODELVIEW);
}

And my function to render a simple triangle:

void GLRenderer::render() {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glLoadIdentity();
    glTranslated(0, 0, -20);

    glBegin(GL_TRIANGLES);
        glColor3d(1, 0, 0);
        glVertex3d(0, 1, 0);
        glVertex3d(1, -1, 0);
        glVertex3d(-1, -1, 0);
    glEnd();

    SwapBuffers(hDC);
}

Solution

  • You can change the zoom in y (height) with the "field of view" parameter to gluPerspective. The one that is 45 degrees in your code. As it is currently always 45 degrees, you will always get the same view angle (in y). How to change this value as a function of the height of the window is not obvious. A linear relation would fail for big values (180 degrees and up). I would try to use arctan(height/k), where 'k' is something like 500.

    Notice also that when you extend the window in x, you will already get what you want (the way your source code currently is). That is, you get a wider field of view. That is because you change the aspect (second argument) to a value depending on the ratio between x and y.

    Height and Width is measured in pixels, so a value of 1 is not good.

    Notice that you are using deprecated legacy OpenGL. See Legacy OpenGL for more information.