【发布时间】:2015-09-09 20:04:36
【问题描述】:
我使用 OpenGL 创建了一个简单的 2D 区域,由图块组成。默认情况下,这些图块已相对于屏幕的纵横比进行了拉伸。为了解决这个问题,我尝试使用正交投影矩阵。这是我创建它的方法:
public void createProjectionMatrix() {
float left = 0;
float right = DisplayManager.getScreenWidth();
float top = 0;
float bottom = DisplayManager.getScreenHeight();
float near = 1;
float far = -1;
projectionMatrix.m00 = 2 / (r - l);
projectionMatrix.m11 = 2 / (t - b);
projectionMatrix.m22 = -2 / (f - n);
projectionMatrix.m30 = - (r + l) / (r - l);
projectionMatrix.m31 = - (t + b) / (t - b);
projectionMatrix.m32 = - (f + n) / (f - n);
projectionMatrix.m33 = 1;
}
问题可能就在这里,但我就是找不到。然后我在创建渲染器时调用此方法,将其存储在统一变量中并在顶点着色器中使用,如下所示:
vec4 worldPosition = transformationMatrix * vec4(position, 0, 1);
gl_Position = projectionMatrix * viewMatrix * worldPosition;
其中 projectionMatrix 是一个 mat4,对应于之前创建的正交投影矩阵。
现在除了清晰的颜色渲染之外什么都没有。
编辑:
在渲染器创建后和着色器创建后立即创建正交投影矩阵并将其加载到着色器中。
public Renderer() {
createOrthoMatrix();
terrainShader.start();
terrainShader.loadProjectionMatrix(projectionMatrix);
terrainShader.stop();
GL11.glEnable(GL13.GL_MULTISAMPLE);
GL11.glClearColor(0, 0, 0.5f, 1);
}
其余的矩阵在每次渲染时通过 loadUniforms() 方法传入。
for(Terrain t : batch) {
loadUniforms(t, terrainManager, camera, lights);
GL11.glDrawElements(GL11.GL_TRIANGLES, model.getModel().getVertexCount(), GL11.GL_UNSIGNED_INT, 0);
}
private void loadUniforms(Terrain t, TerrainManager tm, Camera camera, List<Light> lights) {
Matrix4f matrix = Maths.createTransformationMatrix(t.getPosition(), 0, 0, 0, 1);
terrainShader.loadTransformationMatrix(matrix);
terrainShader.loadViewMatrix(camera);
terrainShader.loadNumberOfRows(tm.getNumberOfRows());
terrainShader.loadOffset(t.getOffset());
terrainShader.loadLights(lights);
}
最后这就是顶点着色器的样子:
#version 400 core
in vec2 position;
uniform mat4 transformationMatrix;
uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;
void main(void) {
vec4 worldPosition = transformationMatrix * vec4(position, 0, 1);
gl_Position = projectionMatrix * viewMatrix * worldPosition;
}
【问题讨论】:
-
@genpfault 感谢您指出这一点!但问题依然存在
-
到时候MCVE。
-
矩阵结构/类中元素的顺序是什么?
-
如果它之前渲染得很好,那么你现在应该有一个小于一个像素的渲染大小。尝试在矩阵中包含一个比例因子(将
m00和m11乘以某个大值(例如100),看看是否是这种情况)。而且您可能需要转置矩阵(交换列和行)。这就是@RetoKoradi 想要查看矩阵声明的原因。
标签: opengl matrix 2d glsl orthographic