因此,我目前正在为Android进行2D游戏项目,并且正在使用Opengl ES 2.0。我的深度缓冲区默认范围是0.0到1.0,但我想将其扩展到0.0-100.0。我尝试使用GLES20.glDepthRangef,但它似乎对我不起作用。Z值超出范围的图像:0.0-1.0不会显示在屏幕上。我想念什么吗?我将不胜感激!
private final float[] mtrxProjection = new float[16];
private final float[] mtrxView = new float[16];
private final float[] mtrxProjectionAndView = new float[16];
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
//current width and height.
swp = width;
shp = height;
// Redo the Viewport, making it fullscreen.
GLES20.glViewport(0, 0, (int)swp, (int)shp);
// Clear our matrices
for(int i=0;i<16;i++)
{
mtrxProjection[i] = 0.0f;
mtrxView[i] = 0.0f;
mtrxProjectionAndView[i] = 0.0f;
}
// Setup our screen width and height for normal sprite translation.
Matrix.orthoM(mtrxProjection, 0, 0f, swp, 0.0f, shp, 0, 100);
// Depth testing
GLES20.glEnable( GLES20.GL_DEPTH_TEST );
GLES20.glDepthFunc( GLES20.GL_LEQUAL );
GLES20.glDepthMask( true );
GLES20.glDepthRangef(0, 100);
// Set the camera position (View matrix)
Matrix.setLookAtM(mtrxView, 0, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
// Calculate the projection and view transformation
Matrix.multiplyMM(mtrxProjectionAndView, 0, mtrxProjection, 0, mtrxView, 0);
}
这是我的顶点着色器:
public static final String vs_Image =
"uniform mat4 u_MVPMatrix;" + // u_MVPMatrix is the mtrxProjectionAndView calculated above
"attribute vec4 a_position;" +
"attribute vec2 a_texCoord;" +
"varying vec2 v_texCoord;" +
"void main() {" +
" gl_Position = u_MVPMatrix * a_position;" +
" v_texCoord = a_texCoord;" +
"}";
参数glDepthRange()
必须在0.0到1.0的范围内。它的工作方式是0.0到1.0代表深度缓冲区的整个可用范围。glDepthRange()
可用于将深度值映射到整个可用范围的子范围,但不能扩展可用范围。
控制映射到深度缓冲区范围的坐标范围的方法是使用顶点着色器中应用的变换。生成的顶点着色器的输出坐标gl_Position
位于剪辑坐标中,通过将位置的x,y和z除以w坐标可将其转换为归一化设备坐标(NDC),通常将其称为透视划分。NDC中然后映射到深度缓冲区范围的z值范围是[-1.0,1.0]。
在特定的顶点着色器中,可以gl_Position
通过将输入位置乘以来获得u_MVPMatrix
。要解决您的问题,您需要确保正确设置此矩阵。使用glDepthRange()
不是您要找的解决方案。
使用投影矩阵,您已经在z方向上设置了100个单位的范围,这看起来与您的目标一致:
Matrix.orthoM(mtrxProjection, 0, 0f, swp, 0.0f, shp, 0, 100);
问题似乎出在您的视图矩阵上:
Matrix.setLookAtM(mtrxView, 0, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
第3至第5个自变量是视点,在您的调用中为(0.0,0.0,1.0)。第6至第8个自变量是您要查看的点,在您的调用中为(0.0,0.0,0.0)。因此,您正在从z轴上的一个点看,从原点到原点的距离为一个单位。由于投影矩阵给出的总z范围为100个单位,因此视图体积中z值的范围为[-99.0,1.0]。
如果要将可见z范围改为[0.0,100.0],则需要将视图矩阵中的视点调整为距原点100个单位。调用将如下所示:
Matrix.setLookAtM(mtrxView, 0, 0f, 0f, 100f, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
现在,您从点(0.0,0.0,100.0)朝原点看,投影矩阵给出了100个单位的范围。这为z坐标提供了[0.0,100.0]可见范围。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句