在LWJGL 3中渲染透视投影矩阵

时间:2016-05-03 04:42:34

标签: java opengl lwjgl

在我的顶点着色器中添加透视投影矩阵时,纹理四边形不可见。

shader.vert

#version 400

in vec3 position;
in vec2 textureCoordinate;

out vec3 colour;
out vec2 passTextureCoordinate;

uniform mat4 transformationMatrix;
uniform mat4 projectionMatrix;

void main() {
  gl_Position = projectionMatrix * transformationMatrix * vec4(position, 1.0);
  passTextureCoordinate = textureCoordinate;
  colour = vec3(position.x+.5f, 0.0, position.y+.5f);
}

当我设置 projectionMatrix 以确认其渲染正常时。此外,当我将其设置为正交投影时,它也会渲染。

创建透视投影矩阵:

private static final float FOV = 70f;
private static final float NEAR_PLANE = 1.0f;
private static final float FAR_PLANE = 1000.0f;

    private void createProjectionMatrix(){
      IntBuffer w = BufferUtils.createIntBuffer(4);
      IntBuffer h = BufferUtils.createIntBuffer(4);
      GLFW.glfwGetWindowSize(WindowManager.getWindow(), w, h);
      float width = w.get(0);
      float height = h.get(0);
      float aspectRatio = width / height;
      float yScale = (float) ((1f / Math.tan(Math.toRadians(FOV / 2f))) * aspectRatio);
      float xScale = y_scale / aspectRatio;
      float frustumLength = FAR_PLANE - NEAR_PLANE;

      projectionMatrix = new Matrix4f();
      projectionMatrix.m00 = xScale;
      projectionMatrix.m11 = yScale;
      projectionMatrix.m22 = -((FAR_PLANE + NEAR_PLANE) / frustumLength);
      projectionMatrix.m23 = -1;
      projectionMatrix.m32 = -((2 * NEAR_PLANE * FAR_PLANE) / frustumLength);
      projectionMatrix.m33 = 0;
}

结果矩阵:

0.8925925 0.0       0.0       0.0
0.0       1.428148  0.0       0.0
0.0       0.0      -1.002002 -2.002002
0.0       0.0      -1.0       0.0

这是正交投影矩阵的代码。

正交投影矩阵:

private void createOrthographicMatrix() {
    projectionMatrix = Matrix4f.orthographic(-10f, 10f, -10f * 9f / 16f, 10f * 9f / 16f, -1f, 1f);
}

结果矩阵:

0.1  0.0      0.0  0.0
0.0  0.177778 0.0  0.0
0.0  0.0     -1.0  0.0
0.0  0.0      0.0  1.0

我怀疑我在设置中遗漏了一些东西。但是还没弄明白。

2 个答案:

答案 0 :(得分:2)

您尚未指定您尝试绘制的三角形的确切位置。但是,如果三角形与您正在使用的邻域矩阵一起显示,则三角形很可能不会与您的透视矩阵一起出现。

在正交情况下,您将近平面设置为z_eye=1,远平面设置为z_eye=-1,因此z_eye范围[-1,1]之外的所有内容都将永远不会出现可见。在透视设置中,您将近平面设置为z_eye=-1,将远平面设置为z_eye=-1000。 (请注意,眼睛空间中的查看方向为-z,您为近平面和远平面指定的值是到该查看方向的距离,因此实际的z值被否定。这也意味着在正交情况下,您实际上将近平面设置在“相机”后面。 这意味着只有当基元落入[-1000,-1]中的z范围时才能看到基元。

因此只有两个矩阵才能看到一个原始的,如果它只放在摄像机前面的一个单位(z_eye=-1),并且只有没有任何数值不稳定。

答案 1 :(得分:0)

所以,我的问题不是在投影矩阵中,而是在生成变换矩阵的方法中。我意外地将Z坐到了Y.因为我的Y值总是0所以是Z值。结果,对象始终在截头锥体之外。

public static Matrix4f createTransformationMatrix(Vector3f translation, float rx, float ry, float rz, float scale) {
    Matrix4f translations = new Matrix4f();
    translations.setIdentity();

    translations = Matrix4f.translate(translation.x, translation.y, translation.y); // Bug
    ...
}

我希望解决方案会更有趣。