'glViewport issue - getting stretched camera views

Hello I've tried to split a window in four viewports where I want to render a scene in each viewport. For simplicity I have simplified the code to only contain a single camera view. The code look roughly as follows:

void setup_trf(const PolarCoords& pc, double aspect)
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(60, aspect, 0.01, 1000);
    //glFrustum(-1.0, 1.0, -1.0, 1.0, 1.5, 20.0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    double eye_x, eye_y, eye_z;
    pc.to_cartesian(eye_x, eye_y, eye_z);

    double look_x = 0;
    double look_y = 0;
    double look_z = 0;

    double up_x = 0;
    double up_y = 0;
    double up_z = 1;
    gluLookAt(
        eye_x, eye_y, eye_z,
        look_x, look_y, look_z,
        up_x, up_y, up_z);
}

void draw_scene(int w, int h) {
    glClearColor(0.0f, 0.75f, 1.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    double aspect = w / double(h);

    glViewport(0, h / 2, w / 2, h);
    setup_trf(app_state.m_polar, aspect);
    draw_sphere();

    glViewport(w / 2, h / 2, w, h);
    setup_trf(app_state.m_polar, aspect*0.5);
    draw_sphere();

    glViewport(0, 0, w / 2, h/2);
    setup_trf(app_state.m_polar, aspect);
    draw_sphere();

    glViewport(w / 2, 0, w, h / 2);
    setup_trf(app_state.m_polar, aspect);
    draw_sphere();
}

And the result is the following: view of the sphere

Anyone knows why the image gets stretched in the different viewports?



Solution 1:[1]

The 1st and 2nd parameter of glViewport are the bottom left coordinate (origin) of the viewport rectangle. But the 3rd and 4th parameter are the width and height of the viewport rectangle rather than the top right coordinate.

This means the 3rd and 4th parameter have to be the half of the window size (w/2, h/2) in each case:

glViewport(0, h/2, w/2, h/2);
setup_trf(app_state.m_polar, aspect);
draw_sphere();

glViewport(w/2, h/2, w/2, h/2);
setup_trf(app_state.m_polar, aspect);
draw_sphere();

glViewport(0, 0, w/2, h/2);
setup_trf(app_state.m_polar, aspect);
draw_sphere();

glViewport(w/2, 0, w/2, h/2);
setup_trf(app_state.m_polar, aspect);
draw_sphere();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rabbid76