# reshape function for correct proportion between window and viewport

If I want to keep the proportion of object while reshaping I can only manage to do that in the following way:

void Reshape(GLsizei nWidth, GLsizei nHeight)
{
int windowWidth = glutGet(GLUT_WINDOW_WIDTH);
int windowHeight = glutGet(GLUT_WINDOW_HEIGHT);

GLfloat new_aspect = (float)nWidth / float(nHeight);

if (aspect < new_aspect) {
glViewport(0, 0, nHeight*aspect, nHeight);
}
else if (aspect > new_aspect){
glViewport(0, 0, nWidth, nWidth / aspect);
}
else {
glViewport(0, 0, nWidth, nHeight);
}

}

This gives some part of window unused by viewport as shown in picture,[ATTACH=CONFIG]1296[/ATTACH]

But is there any strategy on keeping proportions automatically between window and viewport? It would be very kind of you to let me know that.

You have two choices, in theory:

1. Use your windowing tools to prevent the window from being resized. Your code looks like FreeGLUT, which doesn’t offer you the ability to fix the size of a window.

2. Apply the aspect ratio to your projection matrix, not your viewport. That will allow you to render into the entire window but without distortions.

Thanks Alfonso for the reply. But I’m still a bit confused:

1)That means, using freeglut, I can’t resize windows. Can I do it using glfw?
2)You wrote about applying aspect ratio, then what about orthographic projection, how to prevent distortion using orthographic projection?

Thank you.

You wrote about applying aspect ratio, then what about orthographic projection, how to prevent distortion using orthographic projection?

The math is the same for either matrix. The aspect ratio is used as a scale factor for the X or Y dimension of the projection matrix.

I used the following for orthographic projection, but it didn’t work. What’s wrong?

glm::mat4 projection_matrix;

if (aspect >= 1.0)
projection_matrix = glm::ortho(-2.0faspect, 2.0faspect, -2.0f, 2.0f, 1.0f, 10.0f);
else
projection_matrix = glm::ortho(-2.0f, 2.0f, -2.0f/aspect, 2.0f/aspect, 1.0f, 10.0f);

my reshape function is as follows:

void Reshape(int width, int height)
{
glViewport(0, 0, width, height);

aspect = float(height) / float(width);
}

It works Alfonso, my code was wrong, aspect should be Width/ Height.
Thank you!