WebGL簡易教程(六):第一個三維示例(使用模型視圖投影變換)


1. 概述

在上一篇教程《WebGL簡易教程(五):圖形變換(模型、視圖、投影變換)》中,詳細講解了OpenGL\WebGL關於繪制場景的模型變換、視圖變換以及投影變換的過程。不過那篇教程是純理論知識,這里就具體結合一個實際的例子,進一步理解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點改進:

  1. 數據加入Z值;
  2. 加入了深度測試;
  3. 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)的功能,啟用該功能就會檢測物體(實際是每個像素)的深度,來決定是否繪制。其啟用函數為:
2
除此之外,還應該注意在繪制每一幀之前都應該清除深度緩沖區(depth buffer)。WebGL有多種緩沖區。我們之前用到的與頂點着色器交互的緩沖區對象就是頂點緩沖區,每次重新繪制刷新的就是顏色緩沖區。深度緩沖區記錄的就是每個幾何圖形的深度信息,每繪制一幀,都應清除深度緩沖區:
3
在本例中的相關代碼為:

  // ...

  // 開啟深度測試
  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,就會發現瀏覽器頁面顯示了一個由遠及近,近大遠小的三個三角形。如圖所示:
1

4. 參考

本來部分代碼和插圖來自《WebGL編程指南》。

代碼和數據地址

上一篇
目錄
下一篇


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM