OpenGL ES (10): 答疑解惑 -- 投影视图矩阵和相机视图变换矩阵

1.介绍


之前的代码如下:


private final float[] mMVPMatrix = new float[16];
private final float[] mProjectionMatrix = new float[16];
private final float[] mViewMatrix = new float[16];
 
@Override
public void onSurfaceChanged(GL10 unused, int width, int height) {
    GLES20.glViewport(0, 0, width, height);
    float ratio = (float) width / height;
//得到投影矩阵
    Matrix.frustumM(mProjectionMatrix, 0, -ratio, ratio, -1, 1, 3, 7);
}

@Override
public void onDrawFrame(GL10 unused) {
//得到相机视图变换矩阵
    Matrix.setLookAtM(mViewMatrix, 0, 0, 0, 5, 0f, 0f, 0f, 0f, 1.0f, 0.0f);

//结合
    Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mViewMatrix, 0);
    //新的矩阵mMVPMatrix传入,绘制图形
    mTriangle.draw(mMVPMatrix);
}

可以看到我们分别是用两个方法得到投影矩阵和相机视图变换矩阵

  • Matrix.setLookAtM(mViewMatrix, 0, cx, cy, cz, tx, ty, tz, upx, upy, upz)
  • Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far)

下面详细解释这两个方法。

2. 相机视图变换矩阵 Matrix.setLookAtM(mViewMatrix, 0, cx, cy, cz, tx, ty, tz, upx, upy, upz)


Matrix.setLookAtM 
需要填充的参数 
float cx, //摄像机位置x 
float cy, //摄像机位置y 
float cz, //摄像机位置z 
float tx, //摄像机目标点x 
float ty, //摄像机目标点y 
float tz, //摄像机目标点z 
float upx, //摄像机UP向量X分量 
float upy, //摄像机UP向量Y分量 
float upz //摄像机UP向量Z分量 

  • tx,ty, tz,为图像的中心位置设置到原点即 tx = 0,ty = 0, tz = 0;
  • 摄像机的位置,即观察者眼睛的位置 我们设置在目标点的正前方(位置z轴正方向),cx = 0, cy = 0, cz = 5;
  • 接着是摄像机顶部的方向了,很显然相机旋转,up的方向就会改变,这样就会会影响到绘制图像的角度。

例如设置up方向为y轴正方向,upx = 0,upy = 1,upz = 0。这是相机正对着目标图像,则绘制出来的效果如下图所示 

如果设置up方向为x轴正方向,upx = 1,upy = 0,upz = 0,绘制的图像就会如下图所示

显然如果设置在z轴方向,图像就会看不见。

3.投影矩阵 Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far)


Matrix.frustumM 
需要填充的参数有 
float left, //near面的left 
float right, //near面的right 
float bottom, //near面的bottom 
float top, //near面的top 
float near, //near面距离 
float far //far面距离 

  • 先是left,right和bottom,top,这4个参数会影响图像左右和上下缩放比,所以往往会设置的值分别-(float) width / height和(float) width / height,top和bottom和top会影响上下缩放比,如果left和right已经设置好缩放,则bottom只需要设置为-1,top设置为1,这样就能保持图像不变形。( 也可以将left,right 与bottom,top交换比例,即bottom和top设置为 -height/width 和 height/width, left和right设置为-1和1。 )
  • near和far参数稍抽象一点,就是一个立方体的前面和后面,near和far需要结合拍摄相机即观察者眼睛的位置来设置,例如setLookAtM中设置cx = 0, cy = 0, cz = 5,near设置的范围需要是小于5才可以看得到绘制的图像,如果大于5,图像就会处于眼睛的后面,这样绘制的图像就会消失在镜头前,far参数影响的是立体图形的背面,far一定比near大,一般会设置得比较大,如果设置的比较小,一旦3D图形尺寸很大,这时候由于far太小,这个投影矩阵没法容纳图形全部的背面,这样3D图形的背面会有部分隐藏掉的。

猜你喜欢

转载自blog.csdn.net/qq_38261174/article/details/83050348
今日推荐