我正在制作软件渲染器。
有时,变换后的顶点的 w 坐标为 0。
因此,如果我将其他坐标除以 w,则会发生错误。
如果相机位置的z坐标与顶点位置的z坐标相等,则变换后的顶点的w坐标为0。
我的代码有问题吗?
下面的代码是我的转换代码。
void Camera::ComputeWorldToCameraMat()
{
Vector3 zaxis;
zaxis.Set( _dir.x - _pos.x, _dir.y - _pos.y, _dir.z - _pos.z );
zaxis.Normalize();
// xaxis = zaxis X up
Vector3 xaxis;
xaxis = cross(zaxis, _up);
xaxis.Normalize();
Vector3 yaxis;
yaxis = cross(zaxis, xaxis);
_worldToCamera.Identity();
_worldToCamera.a11 = xaxis.x;
_worldToCamera.a12 = yaxis.x;
_worldToCamera.a13 = zaxis.x;
_worldToCamera.a14 = 0;
_worldToCamera.a21 = xaxis.y;
_worldToCamera.a22 = yaxis.y;
_worldToCamera.a23 = zaxis.y;
_worldToCamera.a24 = 0;
_worldToCamera.a31 = xaxis.z;
_worldToCamera.a32 = yaxis.z;
_worldToCamera.a33 = zaxis.z;
_worldToCamera.a34 = 0;
_worldToCamera.a41 = -dot(xaxis, _pos);
_worldToCamera.a42 = -dot(yaxis, _pos);
_worldToCamera.a43 = -dot(zaxis, _pos);
_worldToCamera.a44 = 1;
}
void Camera::ComputeProjectionMat( Viewport* viewport)
{
int width = viewport->_width;
int height = viewport->_height;
//float tanfov = (float)tan(_fov * 0.5f);
float cot = 1.0f / tan( _fov * 0.5f );
float aspect = (float)(width / height);
_projection.Identity();
_projection.a11 = cot / aspect;
_projection.a12 = 0;
_projection.a13 = 0;
_projection.a14 = 0;
_projection.a21 = 0;
_projection.a22 = cot;
_projection.a23 = 0;
_projection.a24 = 0;
_projection.a31 = 0;
_projection.a32 = 0;
_projection.a33 = -1 * (_farZ + _nearZ) / ( _farZ - _nearZ );
_projection.a34 = 2 * ( _nearZ * _farZ ) / ( _farZ - _nearZ );
_projection.a41 = 0;
_projection.a42 = 0;
_projection.a43 = 1;
_projection.a44 = 0;
}