我目前遇到来自移动(类太阳)光源的定向光影贴图的问题。
当我最初实现时,光投影矩阵被计算为 3D,阴影贴图看起来很漂亮。然后我了解到,对于我正在尝试做的事情,正交投影会更好,但我很难替换正确的投影矩阵。
正如人们所期望的那样,每个滴答声,太阳都会沿着一个圆圈移动一定的量。我使用本土的“lookAt”方法来确定正确的查看矩阵。因此,例如,白天从早上 6 点到下午 6 点出现。当太阳位于上午 9 点的位置(45 度)时,它应该查看原点并将阴影贴图渲染到帧缓冲区。正交投影似乎发生的事情是它不会“向下倾斜”到原点。它只是继续直视 Z 轴。早上 6 点和下午 6 点看起来一切正常,但例如中午 12 点,就什么也没有了。
这是我设置的方式:
原始 3D 投影矩阵:
Matrix4f projectionMatrix = new Matrix4f();
float aspectRatio = (float) width / (float) height;
float y_scale = (float) (1 / cos(toRadians(fov / 2f)));
float x_scale = y_scale / aspectRatio;
float frustum_length = far_z - near_z;
projectionMatrix.m00 = x_scale;
projectionMatrix.m11 = y_scale;
projectionMatrix.m22 = (far_z + near_z) / (near_z - far_z);
projectionMatrix.m23 = -1;
projectionMatrix.m32 = -((2 * near_z * far_z) / frustum_length);
观察方法:
public Matrix4f lookAt( float x, float y, float z,
float center_x, float center_y, float center_z ) {
Vector3f forward = new Vector3f( center_x - x, center_y - y, center_z - z );
Vector3f up = new Vector3f( 0, 1, 0 );
if ( center_x == x && center_z == z && center_y != y ) {
up.y = 0;
up.z = 1;
}
Vector3f side = new Vector3f();
forward.normalise();
Vector3f.cross(forward, up, side );
side.normalise();
Vector3f.cross(side, forward, up);
up.normalise();
Matrix4f multMatrix = new Matrix4f();
multMatrix.m00 = side.x;
multMatrix.m10 = side.y;
multMatrix.m20 = side.z;
multMatrix.m01 = up.x;
multMatrix.m11 = up.y;
multMatrix.m21 = up.z;
multMatrix.m02 = -forward.x;
multMatrix.m12 = -forward.y;
multMatrix.m22 = -forward.z;
Matrix4f translation = new Matrix4f();
translation.m30 = -x;
translation.m31 = -y;
translation.m32 = -z;
Matrix4f result = new Matrix4f();
Matrix4f.mul( multMatrix, translation, result );
return result;
}
正交投影(使用宽度 100,高度 75,近 1.0,远 100)我已经尝试了许多不同的值:
Matrix4f projectionMatrix = new Matrix4f();
float r = width * 1.0f;
float l = -width;
float t = height * 1.0f;
float b = -height;
projectionMatrix.m00 = 2.0f / ( r - l );
projectionMatrix.m11 = 2.0f / ( t - b );
projectionMatrix.m22 = 2.0f / (far_z - near_z);
projectionMatrix.m30 = - ( r + l ) / ( r - l );
projectionMatrix.m31 = - ( t + b ) / ( t - b );
projectionMatrix.m32 = -(far_z + near_z) / (far_z - near_z);
projectionMatrix.m33 = 1;
阴影贴图顶点着色器:
#version 150 core
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform mat4 modelMatrix;
in vec4 in_Position;
out float pass_Position;
void main(void) {
gl_Position = projectionMatrix * viewMatrix * modelMatrix * in_Position;
pass_Position = gl_Position.z;
}
阴影贴图片段着色器:
#version 150 core
in vec4 pass_Color;
in float pass_Position;
layout(location=0) out float fragmentdepth;
out vec4 out_Color;
void main(void) {
fragmentdepth = gl_FragCoord.z;
}
我觉得我在这里遗漏了一些非常简单的东西。正如我所说,这适用于 3D 投影矩阵,但我希望阴影在用户环游世界时保持不变,这对于定向照明和正交投影是有意义的。