編輯:關於 Android 程式設計
在 OpenGL ES 的學習路徑上,畫出一個三角形大約相當於其他語言裡的「Hello World」——它足夠簡單,卻又涵蓋了整条渲染管線必備的環節。把這一步走通,後續無論是貼圖、光照還是自定義效果,都只是在同一套骨架上繼續加肉。以下整理一份完整的實作流程,也方便日後沉澱成自己可重複使用的工具類。
若要使用 OpenGL ES 2.0 的 API,必須先在清單檔中明確宣告需求,這樣系統才會在安裝與執行時做過濾與檢查:
<uses-feature android:glesVersion="0x00020000" android:required="true" />
GLSurfaceView 可以理解成一塊專用的畫布,所有 GL 指令的繪製結果都呈現在它上面。實作時我們通常會繼承它,封裝成自己的檢視類別:
public class MyGLSurfaceView extends GLSurfaceView {
private Context mContext;
public MyGLSurfaceView(Context context) {
super(context);
}
public MyGLSurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
}
}
Renderer 是 GLSurfaceView.Renderer 的實作類,它決定了這塊畫布上究竟要畫什麼。需要實作三個回呼:
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
}
@Override
public void onDrawFrame(GL10 gl) {
}
三者職責分明:onSurfaceCreated() 在 surface 建立時觸發,適合放初始化工作;onSurfaceChanged() 在尺寸或方向改變時觸發,用來重設視埠與投影;onDrawFrame() 則是每一幀都會被呼叫的繪製入口。
在把資料交給 shader 之前,必須先說清楚「怎麼讀」:
// 傳參數給 shader 時反覆用到的步長與偏移
private final int mStrideBytes = 7 * 4; // 3 個座標 + 4 個顏色 = 7 個 float,每個 float 4 位元組
private final int mPositionOffset = 0; // 頂點座標的偏移量
private final int mPositionDataSize = 3; // 每 3 個數據組成一個頂點座標
private final int mColorOffset = 3; // 顏色資料從第 3 個位置開始
private final int mColorDataSize = 4; // 4 個數據描述一個顏色
mStrideBytes 告訴 OpenGL「每次跳過多少位元組去取下一組資料」。以 7 個 float 為一組、每個 float 4 位元組而言,一次跨距就是 7 × 4 = 28 位元組。資料本身的樣子如下:
-0.5f, -0.25f, 0.0f, // point
1.0f, 0.0f, 0.0f, 1.0f, // color
三個數字描述一點的位置,四個數字描述該點的顏色(A、R、G、B),因此讀顏色時偏移量為 3,讀座標時偏移量為 0。
// 交給 OpenGL 的頂點資料
private final float vertexData[] = {
// X, Y, Z, R, G, B, A
-0.5f, -0.25f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, // 左下:紅
0.5f, -0.25f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, // 右下:藍
0.0f, 0.559f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f // 頂端:綠
};
每組七個數字,前三個是位置,後四個是顏色,正好對應上一小節的參數設定。這就是應用程式送進 OpenGL 管線的原始素材。
private FloatBuffer mShaderDateBuffer;
private FloatBuffer getVertexBuffer(float[] data) {
// 先配置一塊直接記憶體
ByteBuffer vbb = ByteBuffer.allocateDirect(data.length * 4); // 每個 float 佔 4 個位元組
// 使用與本地硬體一致的字節順序,通常能讓 buffer 讀寫更有效率
vbb.order(ByteOrder.nativeOrder());
FloatBuffer vertexBuffer = vbb.asFloatBuffer();
vertexBuffer.put(data);
vertexBuffer.position(0);
return vertexBuffer;
}
這段程式碼幾乎是固定寫法,記住即可,不理解也不影響後續使用。
OpenGL 裡有三個關鍵矩陣:
* Model Matrix(模型矩陣)
* View Matrix(視圖矩陣)
* Projection Matrix(投影矩陣)
所謂座標變換,就是把同一個座標,從一個座標系表達到另一個座標系裡。下圖是世界座標系下的相機:
而在 OpenGL 中,資料從使用者建立的局部座標系出發,經過一連串處理,最後被渲染到螢幕上:
OpenGL 本身只規範了裁剪座標系、標準化裝置座標系與螢幕座標系;局部座標系、世界座標系與相機座標系則是為方便開發者而存在的概念:
換成座標的語言,整個過程可以這樣看:
茶壺在 Model Matrix 中的定義,以及它在世界座標系中的位置:
從世界座標系進入相機座標系:
之所以要把世界座標系轉換到相機座標系,是因為我們最終看到的畫面,是相機「拍到」的內容,而不是俯視一切的上帝視角。從相機座標系再到裁剪座標系,靠的是投影變換,而投影又分為正交投影與透視投影兩種。
那麼這些概念和三個矩陣如何對應?簡單說:Model Matrix 負責把模型座標系轉到世界座標系,View Matrix 負責把世界座標系轉到相機座標系,Projection Matrix 則負責轉到裁剪座標系。
模型矩陣,這裡順便示範了 rotateM 的用法:
private float[] mModelMatrix = new float[16];
private void initModelMatrix() {
// 每 10 秒旋轉一圈
long time = SystemClock.uptimeMillis() % 10000L;
float angleInDegrees = (360.0f / 10000.0f) * ((int) time);
// 先設為單位矩陣
Matrix.setIdentityM(mModelMatrix, 0);
// 以 Z 軸為旋轉軸,旋轉 angleInDegrees 度
Matrix.rotateM(mModelMatrix, 0, angleInDegrees, 0.0f, 0.0f, 1.0f);
}
視圖矩陣需要三個要素:相機位置、觀察方向、以及向上的向量:
private float[] mViewMatrix = new float[16];
private void initViewMatrix() {
// 眼睛(相機)的位置
final float eyeX = 0.0f;
final float eyeY = 0.0f;
final float eyeZ = 1.5f;
// 觀察方向,look 也稱作 center;center 指向 eye 的向量即視線方向,與實際看過去的方向相反
final float lookX = 0.0f;
final float lookY = 0.0f;
final float lookZ = -5.0f;
// up 向量:eye 只是一個點,必須搭配 look 與 up 並依右手定則,才能唯一確定一個座標系
final float upX = 0.0f;
final float upY = 1.0f;
final float upZ = 0.0f;
Matrix.setLookAtM(mViewMatrix, 0,
eyeX, eyeY, eyeZ,
lookX, lookY, lookZ,
upX, upY, upZ);
}
投影矩陣則用來描述視埠大小、遠近裁剪面與透視關係:
private float[] mProjectionMatrix = new float[16];
private void initProjectionMatrix(int width, int height) {
// 讓 OpenGL 的視埠與 surface 尺寸一致
GLES20.glViewport(0, 0, width, height);
// 高度固定,寬度依螢幕比例變化
final float ratio = (float) width / height;
final float left = -ratio;
final float right = ratio;
final float bottom = -1.0f;
final float top = 1.0f;
final float near = 1.0f;
final float far = 10.0f;
Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
}
編譯 shader 的流程可以抽成工具方法:
public static int compileShader(final int shaderType, final String shaderSource) {
// 建立 shader 句柄
int shaderHandle = GLES20.glCreateShader(shaderType);
if (shaderHandle != 0) {
// 把原始碼綁定到 shader 物件上
GLES20.glShaderSource(shaderHandle, shaderSource);
// 編譯
GLES20.glCompileShader(shaderHandle);
// 取得編譯狀態
final int[] compileStatus = new int[1];
GLES20.glGetShaderiv(shaderHandle, GLES20.GL_COMPILE_STATUS, compileStatus, 0);
// 編譯失敗則回收句柄
if (compileStatus[0] == 0) {
Log.e(TAG, "Error compiling shader: " + GLES20.glGetShaderInfoLog(shaderHandle));
GLES20.glDeleteShader(shaderHandle);
shaderHandle = 0;
}
}
if (shaderHandle == 0) {
throw new RuntimeException("Error creating shader.");
}
return shaderHandle;
}
shaderType 只有兩種:GLES20.GL_VERTEX_SHADER 與 GLES20.GL_FRAGMENT_SHADER。回傳的句柄後續會用來傳入參數與進行計算。
頂點著色器:
uniform mat4 u_MVPMatrix; // 應用程式傳入的變換矩陣,MVP 即 model-view-projection
attribute vec4 a_Position; // 頂點座標
attribute vec4 a_Color; // 頂點顏色
varying vec4 v_Color; // 傳給片段著色器處理
void main() {
v_Color = a_Color;
gl_Position = u_MVPMatrix * a_Position;
}
片段著色器:
precision mediump float;
varying vec4 v_Color; // 名稱必須與頂點著色器中的宣告一致
void main() {
gl_FragColor = v_Color;
}
這些變數名稱與 C 語言中的宣告一致,應用程式就是透過名稱取得位置索引,再傳入資料:
private String[] mAttributes = { "u_MVPMatrix", "a_Position", "a_Color" };
接著把兩支 shader 附加到同一個 program 並完成鏈接:
public static int createAndLinkProgram(final int vertexShaderHandle,
final int fragmentShaderHandle,
final String[] attributes) {
int programHandle = GLES20.glCreateProgram();
if (programHandle != 0) {
GLES20.glAttachShader(programHandle, vertexShaderHandle);
GLES20.glAttachShader(programHandle, fragmentShaderHandle);
// 主動綁定 attribute 的順序索引
if (attributes != null) {
final int size = attributes.length;
for (int i = 0; i < size; i++) {
GLES20.glBindAttribLocation(programHandle, i, attributes[i]);
}
}
GLES20.glLinkProgram(programHandle);
final int[] linkStatus = new int[1];
GLES20.glGetProgramiv(programHandle, GLES20.GL_LINK_STATUS, linkStatus, 0);
if (linkStatus[0] == 0) {
Log.e(TAG, "Error compiling program: " + GLES20.glGetProgramInfoLog(programHandle));
GLES20.glDeleteProgram(programHandle);
programHandle = 0;
}
}
if (programHandle == 0) {
throw new RuntimeException("Error creating program.");
}
return programHandle;
}
初始化都在 onSurfaceCreated() 中完成:
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
// 清屏
GLES20.glClearColor(0f, 0f, 0f, 0f);
initViewMatrix();
initShader();
}
private void initShader() {
int vertexShaderHandle = ShaderHelper.compileShader(GLES20.GL_VERTEX_SHADER,
TextResourceReader.readTextFileFromResource(mContext, R.raw.vertex_shader));
int fragmentShaderHandle = ShaderHelper.compileShader(GLES20.GL_FRAGMENT_SHADER,
TextResourceReader.readTextFileFromResource(mContext, R.raw.fragment_shader));
int programHandle = ShaderHelper.createAndLinkProgram(
vertexShaderHandle, fragmentShaderHandle, mAttributes);
// 鏈接完成後,把 GLSL 中宣告的三個變數取出來,方便後續賦值
mMVPMatrixHandle = GLES20.glGetUniformLocation(programHandle, "u_MVPMatrix");
mPositionHandle = GLES20.glGetAttribLocation(programHandle, "a_Position");
mColorHandle = GLES20.glGetAttribLocation(programHandle, "a_Color");
GLES20.glUseProgram(programHandle);
}
尺寸變化時只需要重算投影矩陣:
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
initProjectionMatrix(width, height);
}
真正的繪製發生在 onDrawFrame():
@Override
public void onDrawFrame(GL10 gl) {
GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);
initModelMatrix();
drawFrame(mShaderDateBuffer);
}
private void drawFrame(final FloatBuffer frameBuffer) {
// 定位到座標資料的起點
frameBuffer.position(mPositionOffset);
// 為頂點著色器的位置屬性賦值:
// 1. mPositionHandle:GLSL 中 a_Position 的位置索引
// 2. mPositionDataSize:每個頂點由幾個值組成,只能是 1、2、3 或 4
// 3. GL_FLOAT:資料型別
// 4. false:不做標準化
// 5. mStrideBytes:每組資料的跨度
// 6. frameBuffer:資料來源
GLES20.glVertexAttribPointer(mPositionHandle, mPositionDataSize,
GLES20.GL_FLOAT, false, mStrideBytes, frameBuffer);
GLES20.glEnableVertexAttribArray(mPositionHandle);
// 定位到顏色資料的起點
frameBuffer.position(mColorOffset);
GLES20.glVertexAttribPointer(mColorHandle, mColorDataSize,
GLES20.GL_FLOAT, false, mStrideBytes, frameBuffer);
GLES20.glEnableVertexAttribArray(mColorHandle);
// 計算 MVP = Projection * View * Model
Matrix.multiplyMM(mMVPMatrix, 0, mViewMatrix, 0, mModelMatrix, 0);
Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mMVPMatrix, 0);
GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mMVPMatrix, 0);
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 3);
}
OpenGL 中所有圖形最終都要拆成三角形來繪製,而繪製動作由 glDrawArrays 完成:
glDrawArrays(int mode, int first, int count)
* 參數一 mode,有三種常見取值:
1. GL_TRIANGLES:每三個頂點獨立構成一個三角形,彼此不連接。
2. GL_TRIANGLE_FAN:以 V0V1V2、V0V2V3、V0V3V4…… 的扇形方式串接。
3. GL_TRIANGLE_STRIP:以 V0V1V2、V1V2V3、V2V3V4…… 的帶狀方式串接,並能保證所有三角形朝向一致。
* 參數二 first:從緩衝區的哪個位置開始取資料,一般為 0。
* 參數三 count:要繪製的頂點數量。
最后在 Activity 中把版本檢查與生命週期處理補上:
private MyGLSurfaceView mGLSurfaceView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initGL();
final ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
final boolean supportsEs2 = configurationInfo.reqGlEsVersion >= 0x20000;
if (supportsEs2) {
// 要求一個 OpenGL ES 2.0 的 context
mGLSurfaceView.setEGLContextClientVersion(2);
mGLSurfaceView.setRenderer(new MyRender(this));
} else {
// 若還想支援 ES 1.x,可在此建立對應的 renderer
return;
}
setContentView(mGLSurfaceView);
}
private void initGL() {
mGLSurfaceView = new MyGLSurfaceView(this);
}
// Activity 暫停與恢復時,必須把事件轉交給 GLSurfaceView
@Override
protected void onPause() {
super.onPause();
mGLSurfaceView.onPause();
}
@Override
protected void onResume() {
super.onResume();
mGLSurfaceView.onResume();
}
把整個流程攤開來看,畫一個三角形的難度和寫一個 Hello World 差不多:宣告需求、準備畫布、實作渲染器、準備頂點資料、配置矩陣、編譯鏈接 shader,最後在每一幀裡把資料餵進管線。真正需要花時間理解的,反而是座標系與矩陣那一段。
Activity 啟動模式之 singleTask:跨應用場景下的棧行為
先看 singleTask 的官方定義: 只有一個實例。在同一個應用中啟動它時,若不存在該實例,則在當前任務棧頂創建;若已存在,則銷毀其之上的所有 Activity 實例
Android UI 系列:Dialog 對話框完整圖解
在介面上彈出一個對話框,是 Android 開發中再日常不過的操作。本篇系統性地梳理 Dialog 的概念,並逐一實作五種常見的 AlertDialog 變體。 一、D
用 Wireshark 抓包定位 Android 網路請求的耗時瓶頸
Wireshark 是相當可靠的 TCP 抓包工具,光是四十多 MB 的安裝檔就能想像它的分量。搭配它的表達式篩選器,能在海量封包裡迅速鎖定目標。近期我就靠它推斷出一個網
Android 資料儲存實戰:用 SQLiteDatabase 打造一個學生管理系統
這篇文章是上一篇《Android 資料儲存:如何搞定 SQLite Database》的配套實作練習。之所以把它單獨拎出來寫,是因為除了資料庫本身,還牽涉到不少其他知識