WebGPU 矩阵栈(Matrix Stacks)

正文
这篇是 3D 数学系列的第 8 篇。每一篇都搭在上一篇上面,所以按顺序读会顺一点。
矩阵栈(matrix stack)顾名思义,就是由矩阵组成的栈。想把物体互相之间摆好位置、调好朝向,它特别顺手。为了演示,我们来做一组文件柜,有矩阵栈这事会轻松很多。
为了简单起见,我们从上一篇文章的最后一个示例出发,把原来的字母“F”换成单位立方体。
-function createFVertices() {
+function createCubeVertices() {
* // left
* 0, 0, 0,
* 0, 0, -1,
* 0, 1, 0,
* 0, 1, -1,
*
* // right
* 1, 0, 0,
* 1, 0, -1,
* 1, 1, 0,
* 1, 1, -1,
* ];
*
* const indices = [
* 0, 2, 1, 2, 3, 1, // left
* 4, 5, 6, 6, 5, 7, // right
* 0, 4, 2, 2, 4, 6, // front
* 1, 3, 5, 5, 3, 7, // back
* 0, 1, 4, 4, 1, 5, // bottom
* 2, 6, 3, 3, 6, 7, // top
* ];
*
* const quadColors = [
* 200, 70, 120, // left column front
* 80, 70, 200, // left column back
* 70, 200, 210, // top
* 160, 160, 220, // top rung right
* 90, 130, 110, // top rung bottom
* 200, 200, 70, // between top and middle rung
* ];
...
上面的数据会生成这样一个立方体。

旧代码一上来就把 26 个“objectInfos”建好了,每个“objectInfo”带一组 uniform buffer 和 bindGroup,对应一个要画的物体。现在改成按需创建,想画多少个就画多少个。
- const numFs = 5 * 5 + 1;
const objectInfos = [];
- for (let i = 0; i < numFs; ++i) {
function createObjectInfo() {
// matrix
const uniformBufferSize = (16) * 4;
const uniformBuffer = device.createBuffer({
...
- objectInfos.push({
+ return {
uniformBuffer,
uniformValues,
matrixValue,
bindGroup,
- });
+ };
}
每个立方体得能区分开,所以需要一点改颜色的手段。我们改片元着色器,让它从 uniform buffer 里拿一个颜色,再乘上顶点颜色。这样每个立方体的顶点颜色都能微调一下。
struct Uniforms {
matrix: mat4x4f,
+ color: vec4f,
};
struct Vertex {
@location(0) position: vec4f,
@location(1) color: vec4f,
};
struct VSOutput {
@builtin(position) position: vec4f,
@location(0) color: vec4f,
};
@group(0) @binding(0) `var<uniform>` uni: Uniforms;
@vertex fn vs(vert: Vertex) -> VSOutput {
var vsOut: VSOutput;
vsOut.position = uni.matrix * vert.position;
vsOut.color = vert.color;
return vsOut;
}
@fragment fn fs(vsOut: VSOutput) -> @location(0) vec4f {
- return vsOut.color;
+ return vsOut.color * uni.color;
}
uniform buffer 的创建逻辑也得跟着改,给新颜色留位置。
function createObjectInfo() {
- // matrix
- const uniformBufferSize = (16) * 4;
+ // matrix and color
+ const uniformBufferSize = (16 + 4) * 4;
const uniformBuffer = device.createBuffer({
label: 'uniforms',
size: uniformBufferSize,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
});
const uniformValues = new Float32Array(uniformBufferSize / 4);
// offsets to the various uniform values in float32 indices
const kMatrixOffset = 0;
+ const kColorOffset = 16;
const matrixValue = uniformValues.subarray(kMatrixOffset, kMatrixOffset + 16);
+ const colorValue = uniformValues.subarray(kColorOffset, kColorOffset + 4);
const bindGroup = device.createBindGroup({
label: 'bind group for object',
layout: pipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: uniformBuffer },
],
});
return {
uniformBuffer,
uniformValues,
+ colorValue,
matrixValue,
bindGroup,
};
}
接下来,把“绘制物体”那段代码抽成一个函数。
let depthTexture;
+ let objectNdx = 0;
+ function drawObject(ctx, matrix, color) {
+ const { pass, viewProjectionMatrix } = ctx;
+ if (objectNdx === objectInfos.length) {
+ objectInfos.push(createObjectInfo());
+ }
+ const {
+ matrixValue,
+ colorValue,
+ uniformBuffer,
+ uniformValues,
+ bindGroup,
+ } = objectInfos[objectNdx++];
+
+ mat4.multiply(viewProjectionMatrix, matrix, matrixValue);
+ colorValue.set(color);
+
+ // upload the uniform values to the uniform buffer
+ device.queue.writeBuffer(uniformBuffer, 0, uniformValues);
+
+ pass.setBindGroup(0, bindGroup);
+ pass.draw(numVertices);
+ }
function render() {
+ objectNdx = 0;
...
const encoder = device.createCommandEncoder();
const pass = encoder.beginRenderPass(renderPassDescriptor);
pass.setPipeline(pipeline);
pass.setVertexBuffer(0, vertexBuffer);
- // update target X,Z based on angle
- settings.target[0] = Math.cos(settings.targetAngle) * radius;
- settings.target[2] = Math.sin(settings.targetAngle) * radius;
...
+ objectNdx = 0;
- objectInfos.forEach(({
- matrixValue,
- uniformBuffer,
- uniformValues,
- bindGroup,
- }, i) => {
- const deep = 5;
- const across = 5;
- if (i < 25) {
- // compute grid positions
- const gridX = i % across;
- const gridZ = i / across | 0;
-
- // compute 0 to 1 positions
- const u = gridX / (across - 1);
- const v = gridZ / (deep - 1);
-
- // center and spread out
- const x = (u - 0.5) * across * 150;
- const z = (v - 0.5) * deep * 150;
-
- // aim this F from it's position toward the target F
- const aimMatrix = mat4.aim([x, 0, z], settings.target, up);
- mat4.multiply(viewProjectionMatrix, aimMatrix, matrixValue);
- } else {
- mat4.translate(viewProjectionMatrix, settings.target, matrixValue);
- }
-
- // upload the uniform values to the uniform buffer
- device.queue.writeBuffer(uniformBuffer, 0, uniformValues);
-
- pass.setBindGroup(0, bindGroup);
- pass.draw(numVertices);
- });
pass.end();
const commandBuffer = encoder.finish();
device.queue.submit([commandBuffer]);
}
加的这个 drawObject 会在需要时新建一个“objectInfo”(里面有 uniform buffer 和类型化数组视图)。它收一个叫 ctx 的上下文,里面装着 pass encoder 和当前的 viewProjectionMatrix,再收一个矩阵和一个颜色。函数把传进来的矩阵跟 viewProjectionMatrix 相乘,填好这个对象的 uniform buffer,然后设 bind group、调 draw。
现在加点代码,用它画立方体。
function render() {
...
const encoder = device.createCommandEncoder();
const pass = encoder.beginRenderPass(renderPassDescriptor);
pass.setPipeline(pipeline);
pass.setVertexBuffer(0, vertexBuffer);
...
objectNdx = 0;
+ const ctx = { pass, viewProjectionMatrix };
+ drawObject(ctx, mat4.rotationY(settings.baseRotation), [1, 1, 1, 1]);
pass.end();
const commandBuffer = encoder.finish();
device.queue.submit([commandBuffer]);
}
上面传的是绕 Y 轴旋转的矩阵加白色。意思是立方体按原来的顶点颜色画。
GUI 和相机也得调一下。
- const radius = 200;
const settings = {
- target: [0, 200, 300],
- targetAngle: 0,
+ baseRotation: 0,
};
const radToDegOptions = { min: -360, max: 360, step: 1, converters: GUI.converters.radToDeg };
const gui = new GUI();
gui.onChange(render);
- gui.add(settings.target, '1', -100, 300).name('target height');
- gui.add(settings, 'targetAngle', radToDegOptions).name('target angle');
+ gui.add(settings, 'baseRotation', radToDegOptions);
...
function render() {
...
- const eye = [-500, 300, -500];
- const target = [0, -100, 0];
+ const eye = [0, 2, 3];
+ const target = [0, 1, 0];
const up = [0, 1, 0];
// Compute a view matrix
const viewMatrix = mat4.lookAt(eye, target, up);
现在有个立方体了。
立方体能画了,那就上矩阵栈,做一组文件柜。
先写一个矩阵栈类。
class MatrixStack {
#matrix;
#stack;
constructor() {
this.reset();
}
reset() {
this.#matrix = mat4.identity();
this.#stack = [];
return this;
}
save() {
this.#stack.push(this.#matrix);
this.#matrix = mat4.copy(this.#matrix);
return this;
}
restore() {
this.#matrix = this.#stack.pop();
return this;
}
get() {
return this.#matrix;
}
set(matrix) {
return this.#matrix.set(matrix);
}
translate(translation) {
mat4.translate(this.#matrix, translation, this.#matrix);
return this;
}
rotateX(angle) {
mat4.rotateX(this.#matrix, angle, this.#matrix);
return this;
}
rotateY(angle) {
mat4.rotateY(this.#matrix, angle, this.#matrix);
return this;
}
rotateZ(angle) {
mat4.rotateZ(this.#matrix, angle, this.#matrix);
return this;
}
scale(scale) {
mat4.scale(this.#matrix, scale, this.#matrix);
return this;
}
}
这个类很简单。它维护一个 #stack(矩阵数组)和一个 #matrix,后者其实就是栈顶那个矩阵。另外加了些方法,用之前写的 mat4 函数来操作栈顶。
注意:它虽然是个栈,但我特意把方法名写成 save 和 restore,没用更传统的 push 和 pop。因为 save 和 restore 跟 Canvas 2D API 里的 save 和 restore 对得上,那两个也是拿来操作自己的矩阵栈的。
上面代码引了个还不存在的 mat4.copy,补上。
const mat4 = {
+ copy(src, dst) {
+ dst = dst || new Float32Array(16);
+ dst.set(src);
+ return dst;
+ },
...
有了这个,就能画一个带把手的文件柜抽屉了。抽屉是个大立方体,把手是个小立方体。
+ const kHandleColor = [0.5, 0.5, 0.5, 1];
+ const kDrawerColor = [1, 1, 1, 1];
+
+ const kDrawerSize = [40, 30, 50];
+ const kHandleSize = [10, 2, 2];
+
+ const [kWidth, kHeight, kDepth] = [0, 1, 2];
+
+ const kHandlePosition = [
+ (kDrawerSize[kWidth] - kHandleSize[kWidth]) / 2,
+ kDrawerSize[kHeight] * 2 / 3,
+ kHandleSize[kDepth],
+ ];
+
+ function drawDrawer(ctx) {
+ const { stack } = ctx;
+ stack.save();
+ stack.scale(kDrawerSize);
+ drawObject(ctx, stack.get(), kDrawerColor);
+ stack.restore();
+
+ stack.save();
+ stack.translate(kHandlePosition);
+ stack.scale(kHandleSize);
+ drawObject(ctx, stack.get(), kHandleColor);
+ stack.restore();
+ }
+
+ const stack = new MatrixStack();
...
function render() {
...
// combine the view and projection matrixes
const viewProjectionMatrix = mat4.multiply(projection, viewMatrix);
+ stack.save();
+ stack.rotateY(settings.baseRotation);
+ stack.translate([(kDrawerSize[kWidth] * -0.5), 0, 0]);
+ objectNdx = 0;
- const ctx = { pass, stack, viewProjectionMatrix };
- drawObject(ctx, mat4.rotationY(settings.baseRotation), [1, 1, 1, 1]);
+ const ctx = { stack, viewProjectionMatrix };
+ drawDrawer(ctx);
+ stack.restore();
pass.end();
const commandBuffer = encoder.finish();
device.queue.submit([commandBuffer]);
}
上面这段建了个 MatrixStack,塞进传给 drawDrawer 的 ctx 里,靠它算矩阵。我们没直接造旋转矩阵,而是在栈上做旋转,再平移抽屉一半宽度,把它摆正。栈传进 drawDrawer,它画两个立方体:一个缩放到 kDrawerSize,另一个挪到 kHandlePosition、缩放到 kHandleSize。因为走了矩阵栈,两个都会带上栈里已有的旋转和平移。
抽屉立方体用 kDrawerColor(白色)画,所以顶点颜色不变。把手用 kHandleColor(50% 灰)画,立方体就暗一点。
相机位置也微调一下:
- const eye = [0, 2, 3];
- const target = [0, 1, 0];
+ const eye = [0, 20, 100];
+ const target = [0, 20, 0];
const up = [0, 1, 0];
// Compute a view matrix
const viewMatrix = mat4.lookAt(eye, target, up);
这样文件柜抽屉就出来了。
你可能会问,折腾矩阵栈图什么?我们画一个 4 抽屉的文件柜,看看原因。
const kHandleColor = [0.5, 0.5, 0.5, 1];
const kDrawerColor = [1, 1, 1, 1];
+ const kCabinetColor = [0.75, 0.75, 0.75, 0.75];
+ const kNumDrawersPerCabinet = 4;
const kDrawerSize = [40, 30, 50];
const kHandleSize = [10, 2, 2];
const [kWidth, kHeight, kDepth] = [0, 1, 2];
const kHandlePosition = [
(kDrawerSize[kWidth] - kHandleSize[kWidth]) / 2,
kDrawerSize[kHeight] * 2 / 3,
kHandleSize[kDepth],
];
+ const kDrawerSpacing = kDrawerSize[kHeight] + 3;
function drawDrawer(ctx) {
const { stack } = ctx;
stack.save();
stack.scale(kDrawerSize);
drawObject(ctx, stack.get(), kDrawerColor);
stack.restore();
stack.save();
stack.translate(kHandlePosition);
stack.scale(kHandleSize);
drawObject(ctx, stack.get(), kHandleColor);
stack.restore();
}
+ function drawCabinet(ctx, numDrawersPerCabinet) {
+ const { stack } = ctx;
+
+ const kCabinetSize = [
+ kDrawerSize[kWidth] + 6,
+ kDrawerSpacing * numDrawersPerCabinet + 6,
+ kDrawerSize[kDepth] + 4,
+ ];
+
+ stack.save();
+ stack.scale(kCabinetSize);
+ drawObject(ctx, stack.get(), kCabinetColor);
+ stack.restore();
+
+ for (let i = 0; i < numDrawersPerCabinet; ++i) {
+ stack.save();
+ stack.translate([3, i * kDrawerSpacing + 5, 1]);
+ drawDrawer(ctx);
+ stack.restore();
+ }
+ }
function render() {
...
- const eye = [0, 20, 100];
- const target = [0, 20, 0];
+ const eye = [0, 80, 200];
+ const target = [0, 80, 0];
const up = [0, 1, 0];
// Compute a view matrix
const viewMatrix = mat4.lookAt(eye, target, up);
// combine the view and projection matrixes
const viewProjectionMatrix = mat4.multiply(projection, viewMatrix);
// combine the view and projection matrixes
const viewProjectionMatrix = mat4.multiply(projection, viewMatrix);
stack.save();
stack.rotateY(settings.baseRotation);
stack.translate([(kDrawerSize[kWidth] * -0.5), 0, 0]);
objectNdx = 0;
const ctx = { pass, stack, viewProjectionMatrix };
- drawDrawer(ctx);
+ drawCabinet(ctx, kNumDrawersPerCabinet);
stack.restore();
pass.end();
const commandBuffer = encoder.finish();
device.queue.submit([commandBuffer]);
}
这段里,drawCabinet 画一个跟 kCabinetSize 一样大的立方体,比我们要的抽屉数量略高一点。然后纯靠矩阵栈把每个抽屉挪到该在的位置,还稍微往柜体前面探一点。
drawDrawer 一个字都没改。有矩阵栈在,原样拿来用就行。
继续,画多个文件柜。
const kHandleColor = [0.5, 0.5, 0.5, 1];
const kDrawerColor = [1, 1, 1, 1];
const kCabinetColor = [0.75, 0.75, 0.75, 0.75];
const kNumDrawersPerCabinet = 4;
+ const kNumCabinets = 5;
const kDrawerSize = [40, 30, 50];
const kHandleSize = [10, 2, 2];
const [kWidth, kHeight, kDepth] = [0, 1, 2];
const kHandlePosition = [
(kDrawerSize[kWidth] - kHandleSize[kWidth]) / 2,
kDrawerSize[kHeight] * 2 / 3,
kHandleSize[kDepth],
];
const kDrawerSpacing = kDrawerSize[kHeight] + 3;
+ const kCabinetSpacing = kDrawerSize[kWidth] + 10;
...
function drawCabinet(ctx, numDrawersPerCabinet) {
const { stack } = ctx;
const kCabinetSize = [
kDrawerSize[kWidth] + 6,
kDrawerSpacing * numDrawersPerCabinet + 6,
kDrawerSize[kDepth] + 4,
];
stack.save();
stack.scale(kCabinetSize);
drawObject(ctx, stack.get(), kCabinetColor);
stack.restore();
for (let i = 0; i < numDrawersPerCabinet; ++i) {
stack.save();
stack.translate([3, i * kDrawerSpacing + 5, 1]);
drawDrawer(ctx);
stack.restore();
}
}
+ function drawCabinets(ctx, numCabinets) {
+ const { stack } = ctx;
+ for (let i = 0; i < numCabinets; ++i) {
+ stack.save();
+ stack.translate([i * kCabinetSpacing, 0, 0]);
+ drawCabinet(ctx, kNumDrawersPerCabinet);
+ stack.restore();
+ }
+ }
function render() {
...
// combine the view and projection matrixes
const viewProjectionMatrix = mat4.multiply(projection, viewMatrix);
stack.save();
stack.rotateY(settings.baseRotation);
- stack.translate([(kDrawerSize[kWidth] * -0.5), 0, 0]);
+ stack.translate([(kNumCabinets - 0.5) * kCabinetSpacing * -0.5, 0, 0]);
objectNdx = 0;
const ctx = { pass, stack, viewProjectionMatrix };
- drawCabinet(ctx, kNumDrawersPerCabinet);
+ drawCabinets(ctx, kNumCabinets);
stack.restore();
pass.end();
const commandBuffer = encoder.finish();
device.queue.submit([commandBuffer]);
}
现在有 drawCabinets 了,它只是拿 drawCabinet 画我们指定数量的柜子。render 里把柜子总宽度的一半平移过去,就居中了。
希望这能让你感觉到矩阵栈的好处。复用物体、摆位置、调朝向、改缩放,都变得很轻松。
递归树
再做一个例子。用立方体造一棵递归树。这需要一个函数来加树的“树枝”,写成递归的,传 treeDepth 进去。深度大于 0 就递归加两个更小的分支,深度减一级。
const degToRad = d => d * Math.PI / 180;
const settings = {
baseRotation: 0,
+ scale: 0.9,
+ rotationX: degToRad(20),
+ rotationY: degToRad(10),
};
const radToDegOptions = { min: -180, max: 180, step: 1, converters: GUI.converters.radToDeg };
+ const treeRadToDegOptions = { min: 0, max: 90, step: 1, converters: GUI.converters.radToDeg };
const gui = new GUI();
gui.onChange(render);
+ gui.add(settings, 'scale', 0.1, 1.2);
+ gui.add(settings, 'rotationX', treeRadToDegOptions);
+ gui.add(settings, 'rotationY', treeRadToDegOptions);
gui.add(settings, 'baseRotation', radToDegOptions);
+ const kTreeDepth = 6;
+ const [/*kWidth*/, kHeight, /*kDepth*/] = [0, 1, 2];
+ // Moves the 1 unit cube so it's center above the origin so that when it scales
+ // it scales out in x and z and up (y) from the origin
+ const kBranchPosition = [-0.5, 0, 0.5];
+ const kBranchSize = [20, 150, 20];
+
+ const kWhite = [1, 1, 1, 1];
+
+ function drawBranch(ctx) {
+ const { stack } = ctx;
+ stack
+ .save()
+ .scale(kBranchSize)
+ .translate(kBranchPosition);
+ drawObject(ctx, stack.get(), kWhite);
+ stack.restore();
+ }
+
+ function drawTreeLevel(ctx, offset, treeDepth) {
+ const { stack } = ctx;
+ const s = offset ? settings.scale : 1;
+ const y = offset ? kBranchSize[kHeight] : 0;
+ stack
+ .save()
+ .translate([0, y, 0])
+ .rotateZ(offset * settings.rotationX)
+ .rotateY(Math.abs(offset) * settings.rotationY)
+ .scale([s, s, s]);
+
+ drawBranch(ctx);
+
+ if (treeDepth > 0) {
+ drawTreeLevel(ctx, -1, treeDepth - 1);
+ drawTreeLevel(ctx, +1, treeDepth - 1);
+ }
+
+ stack.restore();
+ }
function render() {
...
- const eye = [0, 80, 200];
- const target = [0, 80, 0];
+ const eye = [0, 450, 1000];
+ const target = [0, 450, 0];
const up = [0, 1, 0];
// Compute a view matrix
const viewMatrix = mat4.lookAt(eye, target, up);
// combine the view and projection matrixes
const viewProjectionMatrix = mat4.multiply(projection, viewMatrix);
stack.save();
stack.rotateY(settings.baseRotation);
- stack.translate([(kNumCabinets - 0.5) * kCabinetSpacing * -0.5, 0, 0]);
objectNdx = 0;
const ctx = { pass, stack, viewProjectionMatrix };
- drawCabinets(ctx, kNumCabinets);
+ drawTreeLevel(ctx, 0, kTreeDepth);
stack.restore();
pass.end();
const commandBuffer = encoder.finish();
device.queue.submit([commandBuffer]);
}
drawTreeLevel 用的是我们的矩阵栈。它先 save 存下当前矩阵,然后 translate 把树枝挪到当前树枝的末端。offset 为 0 是根节点,不用平移。
offset 接着喂给 rotateZ,让当前树枝顺时针或逆时针转。有矩阵栈,它会相对父树枝转。
offset 再喂给 rotateY,这次取 offset 的绝对值。你可以把 Math.abs 去掉,看看差别。
最后 scale 一下,让每个树枝比父树枝小(或大),根节点(offset 为 0)除外。
然后调 drawBranch。它画一个 kBranchSize 大小的立方体,还会平移原始单位立方体,让立方体中心落在原点上方,这样缩放时它会沿 +Y 轴往上长。
接着,深度大于 0 就递归调 drawTreeLevel 加两个分支,一个偏移 -1,一个偏移 +1。每个分支都从栈上的矩阵起步,所以会相对父分支摆位置、调朝向。
最后 restore 栈。
调 “rotationX”,树枝会散开或聚拢。调 “rotationY”,树枝会从 x 平面散开。可能还得调 “baseRotation” 才看得出效果。调 “scale”,每个树枝相对父分支变小或变大。
说不定能给你点灵感,去做个算法树生成器[1]。
再给每个分支挂个装饰物。不用立方体,用圆锥体当装饰物。生成圆锥顶点的代码在下面。
// tip is at origin, base is below
function createConeVertices({ radius = 1, height = 1, subdivisions = 6 } = {}) {
const positions = [];
const colors = [];
function addVertex(angle, radius, height, color) {
const c = Math.cos(angle);
const s = Math.sin(angle);
positions.push(c * radius, height, s * radius);
colors.push(...color);
}
for (let i = 0; i < subdivisions; ++i) {
const angle0 = ((i + 0) / subdivisions) * Math.PI * 2;
const angle1 = ((i + 1) / subdivisions) * Math.PI * 2;
const u = (i + 1) / subdivisions;
const color = [u * 128 + 127, 0, 0];
// add side
addVertex(angle0, 0, 0, color);
addVertex(angle1, radius, -height, color);
addVertex(angle0, radius, -height, color);
// add top
addVertex(angle0, radius, -height, color);
addVertex(angle1, radius, -height, color);
addVertex(angle0, 0, -height, color);
}
const numVertices = positions.length / 3;
const vertexData = new Float32Array(numVertices * 4); // xyz + color
const colorData = new Uint8Array(vertexData.buffer);
for (let i = 0; i < numVertices; ++i) {
const position = positions.slice(i * 3, i * 3 + 3);
vertexData.set(position, i * 4);
const color = colors.slice(i * 3, i * 3 + 3);
colorData.set(color, i * 16 + 12);
colorData[i * 16 + 15] = 255;
}
return {
vertexData,
numVertices,
};
}
这段代码绕圆走一圈,每一边加一个三角形,顶上再加对应的三角形,每个面给个红色调。跟立方体那个函数一样,返回 vertexData 和 numVertices。各种几何图元怎么造,这里先不展开。
把建顶点缓冲区的代码包成函数,这样能调两次:一次给立方体,一次给圆锥体。
- const { vertexData, numVertices } = createCubeVertices();
+ function createVertices({vertexData, numVertices}, name) {
* const vertexBuffer = device.createBuffer({
- label: `vertex buffer vertices`,
+ label: `${name}: vertex buffer vertices`,
size: vertexData.byteLength,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(vertexBuffer, 0, vertexData);
+ return {
+ vertexBuffer,
+ numVertices,
+ };
* }
+ const cubeVertices = createVertices(createCubeVertices(), 'cube');
+ const ornamentVertices = createVertices(createConeVertices({
+ radius: 20,
+ height: 60,
+ }), 'ornament');
然后改 drawObject,让它收一个顶点参数。
- function drawObject(ctx, matrix, color) {
+ function drawObject(ctx, vertices, matrix, color) {
const { pass, viewProjectionMatrix } = ctx;
+ const { vertexBuffer, numVertices } = vertices;
if (objectNdx === objectInfos.length) {
objectInfos.push(createObjectInfo());
}
const {
matrixValue,
colorValue,
uniformBuffer,
uniformValues,
bindGroup,
} = objectInfos[objectNdx++];
mat4.multiply(viewProjectionMatrix, matrix, matrixValue);
colorValue.set(color);
// upload the uniform values to the uniform buffer
device.queue.writeBuffer(uniformBuffer, 0, uniformValues);
+ pass.setVertexBuffer(0, vertexBuffer);
pass.setBindGroup(0, bindGroup);
pass.draw(numVertices);
}
画树枝的代码也改,把立方体顶点传进去。
function drawBranch(ctx) {
const { stack } = ctx;
stack.save().scale(kBranchSize).translate(kBranchPosition);
-drawObject(ctx, stack.get(), kWhite);
+drawObject(ctx, cubeVertices, stack.get(), kWhite);
stack.restore();
}
同时,顶点缓冲区不用提前设了。
function render() {
...
const encoder = device.createCommandEncoder();
const pass = encoder.beginRenderPass(renderPassDescriptor);
pass.setPipeline(pipeline);
- pass.setVertexBuffer(0, vertexBuffer);
...
接着在 drawTreeLevel 里加代码,深度为零时画装饰物。
function drawTreeLevel(ctx, offset, treeDepth) {
const { stack } = ctx;
const s = offset ? settings.scale : 1;
const y = offset ? kBranchSize[kHeight] : 0;
stack
.save()
.translate([0, y, 0])
.rotateZ(offset * settings.rotationX)
.rotateY(Math.abs(offset) * settings.rotationY)
.scale([s, s, s]);
drawBranch(ctx);
if (treeDepth > 0) {
drawTreeLevel(ctx, -1, treeDepth - 1);
drawTreeLevel(ctx, +1, treeDepth - 1);
}
+ if (treeDepth === 0 && offset > 0) {
+ const position = vec3.getTranslation(stack.get());
+ drawObject(ctx, ornamentVertices, mat4.translation(position), kWhite);
+ }
stack.restore();
}
这里用到一个 vec3.getTranslation,得补上。
const vec3 = {
...
getTranslation(m, dst) {
dst = dst || new Float32Array(3);
dst[0] = m[12];
dst[1] = m[13];
dst[2] = m[14];
return dst;
},
};
getTranslation 从矩阵里取当前的平移分量,跟我们在关于 3D 数学的文章里说的一样。
上面这段调 getTranslation 拿矩阵栈当前的平移量,也就是最后一个树枝的底部位置。装饰物不能直接用矩阵栈画,因为它会跟着树枝一起定向、缩放,而我们要装饰物自然下垂。所以从栈里取出平移量,传一个只带这个平移的矩阵进去。平移量在树枝底部,画一个就够,这就是为什么只在 offset > 0 时画,不然同一个位置会画两个装饰物。
下一篇:场景图。
关键的三点
按需创建 uniform buffer 和 bind group(资源惰性分配)。原代码预先建好固定数量的 objectInfos(每个物体一组 uniform buffer 和 bind group),新代码改成在 drawObject 里,等真要画更多对象时才动态建。没用到的对象就不会占着 GPU 内存,资源利用率上去了。
靠矩阵栈复用层级变换(少算很多,也少管状态)。用 MatrixStack 的 save/restore 维护父子对象间的相对变换。文件柜的柜体、抽屉、把手,还有递归树的分支,都只要在父变换上追加局部变换,不用手算绝对矩阵,重复计算和嵌套变换的复杂度都降下来了。
用 uniform 颜色调制顶点颜色,几何数据就能复用。所有对象(抽屉、把手、柜体、树枝等)都共用同一份单位立方体/圆锥体顶点数据,只是通过 uniform buffer 传不同颜色,再乘上顶点颜色来区分外观。这样不用给每个对象复制一份不同颜色的顶点缓冲区,显存带宽和存储都省了。
术语对照
本文代码按 WebGPU 和 WGSL(WebGPU Shading Language)写,不是 GLSL/OpenGL/WebGL。翻译时注意了这些术语:
- uniform buffer → 统一缓冲区
- bind group → 绑定组
- render pass encoder → 渲染通道编码器
- vertex buffer → 顶点缓冲区
- vertex shader / fragment shader → 顶点着色器 / 片元着色器
- mat4x4f / vec4f → WGSL 中的 4×4 浮点矩阵 / 4 分量浮点向量
- @group / @binding → WGSL 的资源绑定注解,对应 WebGPU 的 bind group 与 binding 编号
- @location → 顶点属性位置注解
- @builtin(position) → 内建输出位置(相当于 GLSL 中
gl_Position,但属于 WGSL 内置变量) - GPUBufferUsage.UNIFORM / COPY_DST / VERTEX → WebGPU API 中缓冲区用途标志
- writeBuffer / setBindGroup / setVertexBuffer / draw → WebGPU 命令编码器方法
全文没用 GLSL 里常见的 attribute、varying、gl_Position 这类术语,跟 WebGPU/WGSL 规范是对齐的。
脚注:
[1] 通常不会通过逐个绘制立方体或圆柱体来生成树,但递归和矩阵栈的技术会被使用——只是不再绘制单个立方体,而是使用这些矩阵来帮助生成顶点,并为整棵树构建一个单一的网格。 返回
