WebGL簡易教程(六):第一個三維示例(使用模型視圖投影變換)
- 2019 年 10 月 5 日
- 筆記
目錄
1. 概述
在上一篇教程《WebGL簡易教程(五):圖形變換(模型、視圖、投影變換)》中,詳細講解了OpenGLWebGL關於繪製場景的模型變換、視圖變換以及投影變換的過程。不過那篇教程是純理論知識,這裡就具體結合一個實際的例子,進一步理解WebGL中是如何通過圖形變換讓一個真正的三維場景顯示出來。
2. 示例:繪製多個三角形
繼續改進之前的程式碼,這次就更進一步,在一個場景中繪製了三個三角形。
2.1. Triangle_MVPMatrix.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Hello Triangle</title> </head> <body onload="main()"> <canvas id="webgl" width="400" height="400"> Please use a browser that supports "canvas" </canvas> <script src="../lib/webgl-utils.js"></script> <script src="../lib/webgl-debug.js"></script> <script src="../lib/cuon-utils.js"></script> <script src="../lib/cuon-matrix.js"></script> <script src="Triangle_MVPMatrix.js"></script> </body> </html>
與之間的程式碼相比,這段程式碼主要是引入了一個cuon-matrix.js,這個是一個圖形矩陣的處理庫,能夠方便與GLSL進行交互。
2.2. Triangle_MVPMatrix.js
// 頂點著色器程式 var VSHADER_SOURCE = 'attribute vec4 a_Position;n' + // attribute variable 'attribute vec4 a_Color;n' + 'uniform mat4 u_MvpMatrix;n' + 'varying vec4 v_Color;n' + 'void main() {n' + ' gl_Position = u_MvpMatrix * a_Position;n' + // Set the vertex coordinates of the point ' v_Color = a_Color;n' + '}n'; // 片元著色器程式 var FSHADER_SOURCE = 'precision mediump float;n' + 'varying vec4 v_Color;n' + 'void main() {n' + ' gl_FragColor = v_Color;n' + '}n'; function main() { // 獲取 <canvas> 元素 var canvas = document.getElementById('webgl'); // 獲取WebGL渲染上下文 var gl = getWebGLContext(canvas); if (!gl) { console.log('Failed to get the rendering context for WebGL'); return; } // 初始化著色器 if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) { console.log('Failed to intialize shaders.'); return; } // 設置頂點位置 var n = initVertexBuffers(gl); if (n < 0) { console.log('Failed to set the positions of the vertices'); return; } //設置MVP矩陣 setMVPMatrix(gl,canvas); // 指定清空<canvas>的顏色 gl.clearColor(0.0, 0.0, 0.0, 1.0); // 開啟深度測試 gl.enable(gl.DEPTH_TEST); // 清空顏色和深度緩衝區 gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); // 繪製三角形 gl.drawArrays(gl.TRIANGLES, 0, n); } //設置MVP矩陣 function setMVPMatrix(gl,canvas) { // Get the storage location of u_MvpMatrix var u_MvpMatrix = gl.getUniformLocation(gl.program, 'u_MvpMatrix'); if (!u_MvpMatrix) { console.log('Failed to get the storage location of u_MvpMatrix'); return; } //模型矩陣 var modelMatrix = new Matrix4(); modelMatrix.setTranslate(0.75, 0, 0); //視圖矩陣 var viewMatrix = new Matrix4(); // View matrix viewMatrix.setLookAt(0, 0, 5, 0, 0, -100, 0, 1, 0); //投影矩陣 var projMatrix = new Matrix4(); // Projection matrix projMatrix.setPerspective(30, canvas.width / canvas.height, 1, 100); //MVP矩陣 var mvpMatrix = new Matrix4(); mvpMatrix.set(projMatrix).multiply(viewMatrix).multiply(modelMatrix); //將MVP矩陣傳輸到著色器的uniform變數u_MvpMatrix gl.uniformMatrix4fv(u_MvpMatrix, false, mvpMatrix.elements); } // function initVertexBuffers(gl) { // 頂點坐標和顏色 var verticesColors = new Float32Array([ 0.0, 1.0, -4.0, 0.4, 1.0, 0.4, //綠色在後 -0.5, -1.0, -4.0, 0.4, 1.0, 0.4, 0.5, -1.0, -4.0, 1.0, 0.4, 0.4, 0.0, 1.0, -2.0, 1.0, 1.0, 0.4, //黃色在中 -0.5, -1.0, -2.0, 1.0, 1.0, 0.4, 0.5, -1.0, -2.0, 1.0, 0.4, 0.4, 0.0, 1.0, 0.0, 0.4, 0.4, 1.0, //藍色在前 -0.5, -1.0, 0.0, 0.4, 0.4, 1.0, 0.5, -1.0, 0.0, 1.0, 0.4, 0.4, ]); // var n = 9; // 點的個數 var FSIZE = verticesColors.BYTES_PER_ELEMENT; //數組中每個元素的位元組數 // 創建緩衝區對象 var vertexBuffer = gl.createBuffer(); if (!vertexBuffer) { console.log('Failed to create the buffer object'); return -1; } // 將緩衝區對象綁定到目標 gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); // 向緩衝區對象寫入數據 gl.bufferData(gl.ARRAY_BUFFER, verticesColors, gl.STATIC_DRAW); //獲取著色器中attribute變數a_Position的地址 var a_Position = gl.getAttribLocation(gl.program, 'a_Position'); if (a_Position < 0) { console.log('Failed to get the storage location of a_Position'); return -1; } // 將緩衝區對象分配給a_Position變數 gl.vertexAttribPointer(a_Position, 3, gl.FLOAT, false, FSIZE * 6, 0); // 連接a_Position變數與分配給它的緩衝區對象 gl.enableVertexAttribArray(a_Position); //獲取著色器中attribute變數a_Color的地址 var a_Color = gl.getAttribLocation(gl.program, 'a_Color'); if (a_Color < 0) { console.log('Failed to get the storage location of a_Color'); return -1; } // 將緩衝區對象分配給a_Color變數 gl.vertexAttribPointer(a_Color, 3, gl.FLOAT, false, FSIZE * 6, FSIZE * 3); // 連接a_Color變數與分配給它的緩衝區對象 gl.enableVertexAttribArray(a_Color); // 解除綁定 gl.bindBuffer(gl.ARRAY_BUFFER, null); return n; }
相比之前的程式碼,主要做了3點改進:
- 數據加入Z值;
- 加入了深度測試;
- MVP矩陣設置;
2.2.1. 數據加入Z值
之前繪製的三角形,只有X坐標和Y坐標,Z值坐標自動補足為默認為0的。在這裡會繪製了3個三角形,每個三角形的深度不同。如下程式碼所示,定義了3個三角形9個點,每個點包含xyz資訊和rgb資訊:
// 頂點坐標和顏色 var verticesColors = new Float32Array([ 0.0, 1.0, -4.0, 0.4, 1.0, 0.4, //綠色在後 -0.5, -1.0, -4.0, 0.4, 1.0, 0.4, 0.5, -1.0, -4.0, 1.0, 0.4, 0.4, 0.0, 1.0, -2.0, 1.0, 1.0, 0.4, //黃色在中 -0.5, -1.0, -2.0, 1.0, 1.0, 0.4, 0.5, -1.0, -2.0, 1.0, 0.4, 0.4, 0.0, 1.0, 0.0, 0.4, 0.4, 1.0, //藍色在前 -0.5, -1.0, 0.0, 0.4, 0.4, 1.0, 0.5, -1.0, 0.0, 1.0, 0.4, 0.4, ]);
這意味著與著色器傳輸變數的函數gl.vertexAttribPointer()的參數也得相應的變化。注意要深入理解這個函數每個參數代表的含義:
// ... // 將緩衝區對象分配給a_Position變數 gl.vertexAttribPointer(a_Position, 3, gl.FLOAT, false, FSIZE * 6, 0); // ... // 將緩衝區對象分配給a_Color變數 gl.vertexAttribPointer(a_Color, 3, gl.FLOAT, false, FSIZE * 6, FSIZE * 3);
2.2.2. 加入深度測試
在默認情況下,WebGL是根據頂點在緩衝區的順序來進行繪製的,後繪製的圖形會覆蓋已經繪製好的圖形。但是這樣往往與實際物體遮擋情況不同,造成一些很怪異的現象,比如遠的物體反而遮擋了近的物體。所以WebGL提供了一種深度檢測(DEPTH_TEST)的功能,啟用該功能就會檢測物體(實際是每個像素)的深度,來決定是否繪製。其啟用函數為:
除此之外,還應該注意在繪製每一幀之前都應該清除深度緩衝區(depth buffer)。WebGL有多種緩衝區。我們之前用到的與頂點著色器交互的緩衝區對象就是頂點緩衝區,每次重新繪製刷新的就是顏色緩衝區。深度緩衝區記錄的就是每個幾何圖形的深度資訊,每繪製一幀,都應清除深度緩衝區:
在本例中的相關程式碼為:
// ... // 開啟深度測試 gl.enable(gl.DEPTH_TEST); // 清空顏色和深度緩衝區 gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); // ...
2.2.3. MVP矩陣設置
在上一篇教程中提到過,WebGL的任何圖形變換過程影響的都是物體的頂點,模型變換、視圖變換、投影變換都是在頂點著色器中實現的。由於每個頂點都是要進行模型視圖投影變換的,所以可以合併成一個MVP矩陣,將其傳入到頂點著色器中的:
//... 'uniform mat4 u_MvpMatrix;n' + 'void main() {n' + ' gl_Position = u_MvpMatrix * a_Position;n' + // Set the vertex coordinates of the point //... '}n';
在函數setMVPMatrix()中,創建了MVP矩陣,並將其傳入到著色器:
//設置MVP矩陣 function setMVPMatrix(gl,canvas) { // Get the storage location of u_MvpMatrix var u_MvpMatrix = gl.getUniformLocation(gl.program, 'u_MvpMatrix'); if (!u_MvpMatrix) { console.log('Failed to get the storage location of u_MvpMatrix'); return; } //模型矩陣 var modelMatrix = new Matrix4(); modelMatrix.setTranslate(0.75, 0, 0); //視圖矩陣 var viewMatrix = new Matrix4(); // View matrix viewMatrix.setLookAt(0, 0, 5, 0, 0, -100, 0, 1, 0); //投影矩陣 var projMatrix = new Matrix4(); // Projection matrix projMatrix.setPerspective(30, canvas.width / canvas.height, 1, 100); //MVP矩陣 var mvpMatrix = new Matrix4(); mvpMatrix.set(projMatrix).multiply(viewMatrix).multiply(modelMatrix); //將MVP矩陣傳輸到著色器的uniform變數u_MvpMatrix gl.uniformMatrix4fv(u_MvpMatrix, false, mvpMatrix.elements); }
在上述程式碼中,依次分別設置了:
- 模型矩陣:X方向上平移了0.75個單位。
- 視圖矩陣:視點為(0,0,5),觀察點為(0,0,-100),上方向為(0,1,0)的觀察視角。
- 投影矩陣:垂直張角為30,畫圖視圖的寬高比,近截面距離為1,遠截面為100的視錐體。
三者級聯,得到MVP矩陣,將其傳入到頂點著色器中。
3. 結果
用瀏覽器打開Triangle_MVPMatrix.html,就會發現瀏覽器頁面顯示了一個由遠及近,近大遠小的三個三角形。如圖所示:
4. 參考
本來部分程式碼和插圖來自《WebGL編程指南》,源程式碼鏈接:https://share.weiyun.com/5VjlUKo ,密碼:sw0x2x。會在此共享目錄中持續更新後續的內容。