本文譯自:http://developer.android.com/guide/topics/graphics/opengl.html
在OpenGL ES 2.0中的投影和照相視圖
在ES 2.0的API中,首先要通過把一個矩陣成員添加給繪圖物件頂部的著色器(Vertex Shaders)來使用投影和照相視圖。然後,這個被添加的矩陣成員能夠產生並把投影和照相視圖應用給繪圖物件。
1. 給頂層著色器(Vertex Shaders)添加矩陣---給視圖投影矩陣建立一個有效,並且要把它作為著色位置的倍增器。在下面的代碼中,包含的uMVPMatrix成員允許把投影和照相視圖的矩陣應用到使用該著色器的繪圖物件的座標上:
privatefinalString vertexShaderCode =
// This matrix member variable provides a hook to manipulate
// the coordinates of objects that use this vertex shader
"uniform mat4 uMVPMatrix; \n"+
"attribute vec4 vPosition; \n"+
"void main(){ \n"+
// the matrix must be included as part of gl_Position
" gl_Position = uMVPMatrix * vPosition; \n"+
"} \n";
注意:在上例的頂層著色器(Vertex Shader)中定義了一個單一變換矩陣,你可以把投影矩陣和照相視圖矩陣一起組合到這個變換矩陣中。根據應用程式的需要,也可以在頂層著色器(Vertex
Shader)中分別定義投影矩陣和照相視圖矩陣,這樣就可以分別對它們進行改變。
2. 訪問著色器矩陣---在頂層著色器(Veterx Shader)中建立了一個應用於投影和照相視圖的回調之後,就能夠訪問這個應用於投影矩陣和照相視圖矩陣的變數。下面的代碼顯示了如何編輯GLSurfaceView.Renderer類onSurfaceCreated()方法,來實現對定義在Vertex Shader中的矩陣變數的訪問。
publicvoid onSurfaceCreated(GL10 unused,EGLConfig config){
...
muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram,"uMVPMatrix");
...
}
3. 建立投影和照相視圖矩陣---產生應用與繪圖物件的投影和視圖矩陣。下列代碼顯示了如何編輯GLSurfaceView.Renderer類的onSurfaceCreated()和onSurfaceChanged()方法,來實現基於裝置的螢幕外觀比率的照相視圖矩陣和投影矩陣的建立:
publicvoid onSurfaceCreated(GL10 unused,EGLConfig config){
...
// Create a camera view matrix
Matrix.setLookAtM(mVMatrix,0,0,0,-3,0f,0f,0f,0f,1.0f,0.0f);
}
publicvoid onSurfaceChanged(GL10 unused,int width,int height){
GLES20.glViewport(0,0, width, height);
float ratio =(float) width / height;
// create a projection matrix from device screen geometry
Matrix.frustumM(mProjMatrix,0,-ratio, ratio,-1,1,3,7);
}
4. 應用投影和照相視圖矩陣---要適用投影和照相視圖的變換,就要把它們一起設定給Verter Shader。下面的代碼顯示了如果編輯GLSurfaceView.Render類的onDrawFrame()方法,來實現上面代碼中建立的投影矩陣和照相視圖的合成,然後,把它應用到由OpenGL來呈現的繪圖物件上。
publicvoid onDrawFrame(GL10 unused){
...
// Combine the projection and camera view matrices
Matrix.multiplyMM(mMVPMatrix,0, mProjMatrix,0, mVMatrix,0);
// Apply the combined projection and camera view transformations
GLES20.glUniformMatrix4fv(muMVPMatrixHandle,1,false, mMVPMatrix,0);
// Draw objects
...
}
關於如何使用OpenGL ES 2.0的完整的樣本,請看OpenGL ES 2.0指南(http://developer.android.com/training/graphics/opengl/index.html)