问题
I'm still a beginner in OpenGL. I'm trying to draw a perfect square on the screen size 1280 by 720 using shaders.
I'm using OpenGL core profile, version 3.3. I was stuck with this when I tried to draw a square in 1280 by 720
After some time of searching, I realized that the size is distort by the viewport size, after changing the viewport size to 720 by 720, I got this.
In the legacy OpenGL, they have a solution to fix this, but now it's deprecated in the Core profile.
Issue: How can I draw a perfect square in 1280 x 720 screensize, using only core profile, OpenGL 3.3?
回答1:
Applying a projection transformation is the most standard way of solving this. You can find details on how to do that in almost any tutorial that shows how to use OpenGL with shaders. In summary, you typically have a projection matrix as a uniform variable in your vertex shader, and apply it to the input positions:
uniform mat4 ProjMat;
in vec4 InPosition;
...
gl_Position = ProjMat * InPosition;
In your C++ code, you calculate the matrix to apply the necessary scaling, and set it using glUniformMatrix4fv()
.
Another option is that you keep the viewport square. While the viewport is often set to match the size of the window, this does not have to be the case. For example, the viewport can extend beyond the size of the window.
To use this approach, you would have something like this in the code where you set the viewport in response to window (re-)size events. With w
and h
the width and height of the window:
if (w > h) {
glViewport(0, (h - w) / 2, w, w);
} else {
glViewport((w - h) / 2, 0, h, h);
}
This takes the larger of the two window dimensions as the viewport size, and extends the viewport beyond the window in the other dimension to produce a square viewport.
回答2:
Scale everything by (2.0/width, 2.0/height)
. If you have a camera matrix, just multiply it with this scaling.
Using that transform, you can input positions as pixels with the origin at the middle of the screen.
来源:https://stackoverflow.com/questions/32421262/opengl-viewport-distortion