Advertisement

Perspective Matrix

Started by March 13, 2022 12:02 PM
2 comments, last by dpadam450 2 years, 8 months ago

Hi, recently I'm trying to make a perspective projection matrix for OpenGL. I've been successful so far, the perspectivity itself is working. My problem is with the aspect ratio: when I render a cube, it is stretched when the aspect ratio isn't 1. I've found a similar question in the forum that was marked as solved but that didn't help me. The aspect ratio is correct, it's printed out when resized.

One weird behaviour I encountered is that when the aspect ratio is between 2 and 3, the projection works as expected, so when I toggle between 1.9 and 2 the cube on the screen scales immediately in one direction.

Here is my matrix (I know that it's row major):

float b,t,l,r,n,f,an;
n = 0.1;
f = 100;
an = 3.14/2;
	
t = tan(an/2) * n;
b = -t;
r = t*ar;
l = -r;
float p[] = {
	2*n/(r-l),	0,			(r+l)/(r-l),	0,
	0,			2*n/(t-b),	(t+b)/(t-b),	0,
	0,			0,			-(f+n)/(f-n),	-2*f*n/(f-n),
	0,			0,				-1,				0
};

In my own projects, I use this one (column-major):

  • a is the aspect ratio.
  • angle is the field of view
getPerspectiveProjection(angle, a, zMin, zMax) {
        var ang = Math.tan(angle * Math.PI / 360);
        return [
            0.5 / ang, 0, 0, 0,
            0, 0.5 * a / ang, 0, 0,
            0, 0, -(zMax + zMin) / (zMax - zMin), -1,
            0, 0, (-2 * zMax * zMin) / (zMax - zMin), 0
        ];
    }

If you copy & pasted your code, please tell me what ar is, and if right is just negative left then two of the terms in your matrix are equal to zero. (I wager that the perspective projection matrix you googled is flat-out wrong!)

Advertisement

My problem is with the aspect ratio: when I render a cube, it is stretched when the aspect ratio isn't 1

Post a screenshot with the snipping tool. You can't just change the aspect ratio of a projection matrix. A projection matrix itself defines your view into the world. If you are changing numbers, you are changing your field of view of your camera in the horizontal or vertical directions.

If your program is a square window, your aspect ratio is 1. If you keep it a square window and your aspect ratio is 2. Then you are taking 2x as wide a field of view (a 2x bigger image essentially) and crunching it down by ½ so that it fits your square. Which is why your square is getting wider stretched, or crunched smaller. Your aspect must match your viewport/programs window size.

NBA2K, Madden, Maneater, Killing Floor, Sims

This topic is closed to new replies.

Advertisement