gpt4 book ai didi

math - 如何建立透视投影矩阵(无API)

转载 作者:行者123 更新时间:2023-12-03 12:39:12 26 4
gpt4 key购买 nike

我开发了一个简单的3D引擎(不使用任何API),成功地将场景转换为世界和 View 空间,但是使用透视投影矩阵(OpenGL样式)来投影场景(从 View 空间)时遇到了麻烦。我不确定fov,near和far值以及我得到的场景是否失真。
我希望有人能指导我如何正确构建和使用带有示例代码的透视投影矩阵。在此先感谢您的帮助。

矩阵构建:

double f = 1 / Math.Tan(fovy / 2);
return new double[,] {

{ f / Aspect, 0, 0, 0 },
{ 0, f, 0, 0 },
{ 0, 0, (Far + Near) / (Near - Far), (2 * Far * Near) / (Near - Far) },
{ 0, 0, -1, 0 }
};

矩阵用途:
foreach (Point P in T.Points)
{
.
. // Transforming the point to homogen point matrix, to world space, and to view space (works fine)
.

// projecting the point with getProjectionMatrix() specified in the previous code :

double[,] matrix = MatrixMultiply( GetProjectionMatrix(Fovy, Width/Height, Near, Far) , viewSpacePointMatrix );

// translating to Cartesian coordinates (from homogen):

matrix [0, 0] /= matrix [3, 0];
matrix [1, 0] /= matrix [3, 0];
matrix [2, 0] /= matrix [3, 0];
matrix [3, 0] = 1;
P = MatrixToPoint(matrix);

// adjusting to the screen Y axis:

P.y = this.Height - P.y;

// Printing...
}

最佳答案

以下是透视投影矩阵的典型实现。
这是一个很好的链接,可以解释OpenGL Projection Matrix的所有内容

void ComputeFOVProjection( Matrix& result, float fov, float aspect, float nearDist, float farDist, bool leftHanded /* = true */ )
{
//
// General form of the Projection Matrix
//
// uh = Cot( fov/2 ) == 1/Tan(fov/2)
// uw / uh = 1/aspect
//
// uw 0 0 0
// 0 uh 0 0
// 0 0 f/(f-n) 1
// 0 0 -fn/(f-n) 0
//
// Make result to be identity first

// check for bad parameters to avoid divide by zero:
// if found, assert and return an identity matrix.
if ( fov <= 0 || aspect == 0 )
{
Assert( fov > 0 && aspect != 0 );
return;
}

float frustumDepth = farDist - nearDist;
float oneOverDepth = 1 / frustumDepth;

result[1][1] = 1 / tan(0.5f * fov);
result[0][0] = (leftHanded ? 1 : -1 ) * result[1][1] / aspect;
result[2][2] = farDist * oneOverDepth;
result[3][2] = (-farDist * nearDist) * oneOverDepth;
result[2][3] = 1;
result[3][3] = 0;
}

关于math - 如何建立透视投影矩阵(无API),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18404890/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com