0

我想生成一个投影矩阵,它将从任意相机渲染一个对象。我已经设法设置了一个 viewMatrix,它将从任意眼睛位置查看对象,但我在设置投影矩阵时遇到了困难。

假设一个以 (x,y,z) 为中心且距离中心最远的点为 r 的对象对于任何任意方向都可以完全封闭在一个半径为 r 且原点为 (x,y,z) 的球体中,我计算了我的视角矩阵如下:

float dist2Object = (float) Math.sqrt(vec.lengthSquared());

float objectRadius = (float) Math.sqrt(3 * Math.pow(0.5, 2));
float far = dist2Object + objectRadius;
float near = dist2Object - objectRadius;

// fov_2 = FOV / 2
float fov_2 = (float) (Math.asin(objectRadius / dist2Object));

float r = (float) (Math.tan(fov_2));
float frustum_length = far - near;

depthProjectionMatrix.m00 = 1 / r;
depthProjectionMatrix.m11 = depthProjectionMatrix.m00;
depthProjectionMatrix.m22 = -((far + near) / frustum_length);
depthProjectionMatrix.m23 = -1;
depthProjectionMatrix.m32 = -((2 * near * far) / frustum_length);
depthProjectionMatrix.m33 = 0;

在我的例子中:

  • vec 是从相机到物体的向量
  • 该对象是一个立方体,其最远顶点为 (0.5, 0.5, 0.5),给出 sqrt(0.75) 的 ar

据我所知,几何和三角应该是正确的,但是使用以下片段着色器渲染坐标:

#version 150 core

in vec3 pCoord;

out vec4 out_Color;

void main(void) {
    out_Color = vec4(0,1,0,1);
    if(pCoord.x <= -1){
        out_Color = vec4(1,0,0,1);
    }
    if(pCoord.x >= 1){
        out_Color = vec4(0,0,1,1);
    }
    if(pCoord.z <= -1){
        out_Color = vec4(1,0,1,1);
    }
    if(pCoord.z >= 1){
        out_Color = vec4(1,0,1,1);
    }
}

如图所示, FOV太窄,近平面和远平面也太窄。

我怎样才能解决这个问题?

4

1 回答 1

0

有一段时间没有这样做了,但您似乎在计算中缺少视口大小。这是我用于项目的内容。请注意,此处的矩阵以 _11 开头,您使用 m00:

double aspectRatio = (double)this.viewPort.Width /(double)this.viewPort.Height;
double fov = Math.toRadians(fieldOfView/2.0);
double size = nearClip * Math.tan(fov);

double left = -size* aspectRatio, right = size* aspectRatio, bottom = -size , top = size ;

projectionMatrix.resetToZero();

// the values in comments are for non symetrical frustrum 

// First Column
projectionMatrix._11 = (float) (nearClip/right);//(float) ((2 * nearClip )/ (double)(right - left));

// Second Column
projectionMatrix._22 = (float)(nearClip/top);//(float) (2 * nearClip / (double)(top - bottom));

// Third Column
projectionMatrix._31 = 0;//(float) ((right + left) / (right - left));
projectionMatrix._32 = 0;//(float) ((top + bottom) / (top - bottom));
projectionMatrix._33 = -1*(farClip + nearClip) / (float)(farClip - nearClip);
projectionMatrix._34 = -1;

// Fourth Column
projectionMatrix._43 = -(2 * farClip * nearClip) / (float)(farClip - nearClip);
于 2014-07-04T11:55:52.180 回答