Three.js 是偉大的開源 WebGL 函式庫,讓 JavaScript 能操作 GPU,在瀏覽器端實現真正的 3D。由於技術仍在發展,資料匱乏,學習多半得靠範例與原始碼摸索。
這是 WebGL 著色器教學的後半段。上一篇結束時,我們在螢幕中央畫了一顆粉紅球體;本篇會加入動畫迴圈、attribute 與 uniform 變數,並用 varying 變數讓頂點著色器能把資訊傳給片段著色器。最終效果是粉紅球體從頂部向兩側「點燃」並規律跳動——視覺上有點迷幻,卻能幫助你理解三種變數如何互相串接。
先讓球體不要看起來那麼扁平。Three.js 內建的光照著色器遠比我們需要的複雜,因此這裡先手動模擬。作法是透過 varying 變數把頂點法向量傳到片段著色器:
// 頂點著色器與片段著色器都宣告這個 varying 變數
varying vec3 vNormal;
void main() {
// normal 是 Three.js 建立並傳入的 attribute
vNormal = normal;
gl_Position = projectionMatrix *
modelViewMatrix *
vec4(position, 1.0);
}
片段著色器中宣告同名變數,把法線與一個代表右上方光線的向量做點積,再把結果套到顏色上:
varying vec3 vNormal;
void main() {
// 光線向量
vec3 light = vec3(0.5, 0.2, 1.0);
light = normalize(light); // 歸一化
// 光線與法線的點積,若為負則取 0
float dProd = max(0.0, dot(vNormal, light));
gl_FragColor = vec4(dProd, // R
dProd, // G
dProd, // B
1.0); // A
}
用點積的原因是:它代表兩向量的「相似度」。兩個歸一化向量方向相同時點積為 1,方向相反時為 -1。把這個值套到亮度上,球體右上方會被完全照亮,另一側則趨近 0 甚至負值——我們把負值歸零,最基礎的光照就出現了。
接著為每個頂點傳入一個隨機數,用來把頂點沿法線方向推開一段距離,讓球體變成每次重新整理都不同的不規則形狀。
attribute float displacement;
varying vec3 vNormal;
void main() {
vNormal = normal;
// 把隨機數轉為三維向量,才能與法線相乘
vec3 newPosition = position + normal * vec3(displacement);
gl_Position = projectionMatrix *
modelViewMatrix *
vec4(newPosition, 1.0);
}
此時畫面不會有任何變化,因為 displacement 尚未被設定,著色器會使用 0 作為預設值。另外注意:position 和所有 attribute 變數一樣都是唯讀的,所以必須把新座標指派給另一個向量。
attribute 物件與頂點一一對應,因此球體的每個頂點都有一個值:
var attributes = {
displacement: {
type: 'f', // 浮點數
value: [] // 空陣列
}
};
var vShader = $('#vertexshader');
var fShader = $('#fragmentshader');
// 建立含 attribute 的著色器材質
var shaderMaterial = new THREE.MeshShaderMaterial({
attributes: attributes,
vertexShader: vShader.text(),
fragmentShader: fShader.text()
});
// 填入隨機數
var verts = sphere.geometry.vertices;
var values = attributes.displacement.value;
for (var v = 0; v < verts.length; v++) {
values.push(Math.random() * 30);
}
這下就能看到變形的球體了。最酷的是:所有變形都發生在 GPU 上。
需要兩件事:一個 uniform 變數 amplitude,用來在每一帧控制位移幅度(可用正弦或餘弦產生,因為其值域剛好是 -1 到 1);以及一個 frame loop。
// 頂點著色器
uniform float amplitude;
attribute float displacement;
varying vec3 vNormal;
void main() {
vNormal = normal;
// amplitude 每帧平滑變化,畫面就動起來了
vec3 newPosition = position +
normal *
vec3(displacement * amplitude);
gl_Position = projectionMatrix *
modelViewMatrix *
vec4(newPosition, 1.0);
}
// 著色器材質
var uniforms = {
amplitude: {
type: 'f',
value: 0
}
};
var shaderMaterial = new THREE.MeshShaderMaterial({
uniforms: uniforms,
attributes: attributes,
vertexShader: vShader.text(),
fragmentShader: fShader.text()
});
畫面看起來像是退回了光滑球體,這是因為 amplitude 仍是 0,乘上 displacement 後自然毫無變化。只要把渲染包成函式交給 requestAnimationFrame 調用,在其中更新 amplitude 即可:
var frame = 0;
function update() {
// amplitude 取自 frame 的正弦值
uniforms.amplitude.value = Math.sin(frame);
frame += 0.1;
renderer.render(scene, camera);
requestAnimFrame(update);
}
requestAnimFrame(update);
你現在會看到球體正怪異地脈動。著色器還有太多內容沒講完,但希望這篇能帶你跨過門檻——之後看到別人的著色器時,你應該讀得懂,也有信心動手寫自己的版本。作者同樣打包了本課原始碼。