投影矩阵实现 [英] Projection matrix implementation
问题描述
我试图从头开始构建自己的Rasteriser / Graphics管线(模仿OpenGL),我在实现工作透视投影矩阵时遇到问题。这是我目前的尝试:
I'm trying to build my own Rasteriser/Graphics pipeline (mimicking OpenGL) from scratch and I'm having problems with implementing a working perspective projection matrix. This is my current attempt:
template<typename T>
Matrix<T,4,4> Perspective(T fov,T aspect, T near, T far)
{
T mat00 = 1 / (aspect*tan(0.5f*fov));
T mat11 = 1 / tan(0.5f*fov);
T mat22 = (-near-far)/(near-far);
T mat32 = (2*near*far)/(near-far);
T data[] =
{
mat00, 0, 0, 0,
0 , mat11, 0, 0,
0 , 0, mat22,mat32,
0 , 0, 1, 0
};
return Matrix<T,4,4>(data);
}
然后将其传递给执行以下操作的顶点处理:
This is then passed to the vertex processing which performs the following:
printf("Vertex inital:");vert.Print();
vert = vert* m_ModelMatrix;
printf("Vertex model:");vert.Print();
vert = vert* m_ProjectionMatrix;
printf("Vertex projection:");vert.Print();
其输出是(对于随机选择的顶点):
The output of which is (for a randomly selected vertex):
Vertex inital:(1.000000,0.000000,-1.000000,1.000000)
Vertex model:(-1.900000,-2.300000,2.599999,1.000000)
Vertex projection:(-3.669604,-5.552692,2.405004,2.599999)
的顶点:$ b $ b
The above vertex corresponds to one of the vertices in this triangle:
我的问题是投影矩阵看起来是完全错误的。当我增加Z平移时,三角形朝向右上角对角线移动,同时看起来较小,当我减小 Z值时,三角形移动对角线朝向左下角,同时显示为较大。有没有人遇到这个问题?
My problem is the projection matrix appears to be completely wrong. When I increase the Z translation the triangle moves diagonally towards the top-right corner while appearing smaller, when I decrease the Z value the triangle moves diagonally towards the bottom-left corner while appearing larger. Has anyone else encountered this issue?
作为参考,我的矢量*矩阵操作的实现:
For reference, my implementation of the vector*matrix operation:
template<typename T,unsigned int length>
Vector<T,length> Vector<T,length>::operator* (const Matrix<T,length,length> & matrix) const
{
T temp[length];
memset(temp,0,length*sizeof(T));
const T * matrixData = matrix.GetData();
//For each row in the matrix & in the returned vector...
for(unsigned int iRow = 0; iRow < length; ++iRow)
{
//For each column in this vector & matrix...
for(unsigned int iColumn = 0; iColumn < length; ++iColumn)
{
temp[iRow] += m_Data[iColumn]*matrixData[iRow*length + iColumn];
}
}
return Vector<T,length>(temp);
}
推荐答案
项目后相当一些休息,我意识到,我的投影鸿沟(aka / w)只是划分xyz坐标。因此,当我应用屏幕空间矩阵时,translate列被乘以大于一个W值,导致三角形随着Z减小而移动到右上角。
So I came back to this project after quite some break and I realised that my projection divide (aka /w) was only dividing the xyz coords. So when I applied the screenspace matrix the translate column was being multiplied by the 'greater than one' W value causing the triangle to move to the upper right as Z decreases.
这篇关于投影矩阵实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!