OpenGL – ortho Projection matrix, glViewport

2dopenglprojection-matrixviewport

I'm having trouble wrapping my head around how these work. First, in a 2d game the projection matrix should be set up as ortho with left, right, top, bottom matching the window, right? But when the window resizes, should I just change glViewport, not the projection matrix? And how do I keep the aspect ratio?

Could someone explain the purposes of these two things, in 2d orthographical game, so that I can understand it better?

It feels like OpenGL is doing a lot of useless stuff in a 2d setup. Rasterizing and calculating fragments when the images are already there, converting vertex coordinates to NDC only to be converted back to what they already where by glViewport.

Also, how come in legacy free OpenGL we have to make our own matrices, but not our own calculations that glViewport does?

Thanks.

Best Answer

Don't confuse what you input to GL and what it outputs to.

the parameters you use to compute the Ortho matrix are the ones that correlate to your input. The output of a projection matrix is always the [-1:1]x[-1:1]x[-1:1] cube.

the viewport translates that cube to your render target coordinates. So that's typically what you want to change to match your new window size (well, that and the framebuffer itself).

Yes, GL does a lot of useless stuff for a 2D rendering path. It's a 3D API after all...

I'll finish by saying that you don't have to build matrices to do 2D transforms, so long as your vertex shader outputs in the cube I mentioned earlier. If you want to write the upper right corner of the viewport, you can always pass your vertices directly as (0,0) (0,1) (1,0) (1,1) and simply output that.

Related Topic