WebGPU 正交投影
说明:本文为技术深度解读,非逐字全盘翻译。代码保留原文英文形式,叙述性内容编译为中文。
这是 WebGPU 3D 数学系列的第 5 篇。前四篇是平移、旋转、缩放、矩阵数学。再往后是透视投影、相机、矩阵栈、场景图这些。
关键的三点
- 打开深度纹理,配上深度比较测试。用
depthStencil状态让 GPU 自己管遮挡,不用手动给三角形排序,过度绘制(overdraw)也少了。 - 把顶点属性合到一个交错缓冲区里。位置和颜色塞进同一个
GPUBuffer,一次setVertexBuffer绑完,状态切换少了,缓存局部性也上去了。 - 背面剔除、顶点颜色属性、复用矩阵数组,三样一起上。
cullMode把背向三角形剔掉,光栅化和片元着色器的压力都轻;顶点颜色用unorm8x4替掉 uniform 颜色,省得每帧更新动态 uniform;矩阵运算复用dst数组,少分配。
从 2D 到 3D 的矩阵扩展
前面的 2D 示例用 3×3 矩阵处理 (x, y) 点。进 3D 就得换成 (x, y, z) 点和 4×4 矩阵。顶点着色器的位置从 vec2f 变 vec4f,矩阵从 mat3x3f 变 mat4x4f:
struct Uniforms {
color: vec4f,
- matrix: mat3x3f,
+ matrix: mat4x4f,
};
struct Vertex {
- @location(0) position: vec2f,
+ @location(0) position: vec4f,
};
struct VSOutput {
@builtin(position) position: vec4f,
};
@group(0) @binding(0) `var<uniform>` uni: Uniforms;
@vertex fn vs(vert: Vertex) -> VSOutput {
var vsOut: VSOutput;
-
- let clipSpace = (uni.matrix * vec3f(vert.position, 1)).xy;
- vsOut.position = vec4f(clipSpace, 0.0, 1.0);
vsOut.position = uni.matrix * vert.position;
return vsOut;
}
@fragment fn fs(vsOut: VSOutput) -> @location(0) vec4f {
return uni.color;
}
3D 里 w 分量默认就是 1,所以 vec4f 位置可以直接跟 4×4 矩阵相乘,着色器代码反而更短了。
构建 3D “F” 几何体
要做出立体的样子,前、后、左、右、顶、底这些面都得有三角形。直观点的做法:把前面的顶点复制一份,z 坐标改成 30,再加索引把前后两个面连起来:
const positions = [
// 前面
0, 0, 0, 30, 0, 0, 0, 150, 0, 30, 150, 0,
// ... 其余顶点
// 后面
0, 0, 30, 30, 0, 30, 0, 150, 30, 30, 150, 30,
// ...
];
const indices = [
// 前面
0, 1, 2, 2, 1, 3,
// ...
// 后面
12, 13, 14, 14, 13, 15,
// ...
];
接着不走索引,给每个面刷上不同颜色,渲染出来一眼就能看清 3D 结构:
const quadColors = [
200,
70,
120, // left column front
200,
70,
120, // top rung front
// ...
];
const numVertices = indices.length;
const vertexData = new Float32Array(numVertices * 4); // xyz + color
const colorData = new Uint8Array(vertexData.buffer);
for (let i = 0; i < indices.length; ++i) {
const positionNdx = indices[i] * 3;
const position = positions.slice(positionNdx, positionNdx + 3);
vertexData.set(position, i * 4);
const quadNdx = ((i / 6) | 0) * 3;
const color = quadColors.slice(quadNdx, quadNdx + 3);
colorData.set(color, i * 16 + 12); // set RGB
colorData[i * 16 + 15] = 255; // set A
}
这里把顶点数据当成 Float32Array,同时开一个 Uint8Array 视图往里写 RGBA 颜色字节。GPU 端靠 unorm8x4 格式自动归一化到 0~1,不用自己除 255。

矩阵函数与正交投影
3D 的平移、旋转、缩放矩阵都存在 Float32Array(16) 里,按列主序排。核心函数长这样:
const mat4 = {
translation([tx, ty, tz], dst) {
dst = dst || new Float32Array(16);
dst[0] = 1;
dst[1] = 0;
dst[2] = 0;
dst[3] = 0;
dst[4] = 0;
dst[5] = 1;
dst[6] = 0;
dst[7] = 0;
dst[8] = 0;
dst[9] = 0;
dst[10] = 1;
dst[11] = 0;
dst[12] = tx;
dst[13] = ty;
dst[14] = tz;
dst[15] = 1;
return dst;
},
rotationX(angleInRadians, dst) {
const c = Math.cos(angleInRadians);
const s = Math.sin(angleInRadians);
dst = dst || new Float32Array(16);
dst[0] = 1;
dst[1] = 0;
dst[2] = 0;
dst[3] = 0;
dst[4] = 0;
dst[5] = c;
dst[6] = s;
dst[7] = 0;
dst[8] = 0;
dst[9] = -s;
dst[10] = c;
dst[11] = 0;
dst[12] = 0;
dst[13] = 0;
dst[14] = 0;
dst[15] = 1;
return dst;
},
// rotationY, rotationZ, scaling ...
};
正交投影函数参数更通用,左、右、下、上、近、远六个裁剪面都能显式指定:
ortho(left, right, bottom, top, near, far, dst) {
dst = dst || new Float32Array(16);
dst[0] = 2 / (right - left);
dst[1] = 0;
dst[2] = 0;
dst[3] = 0;
dst[4] = 0;
dst[5] = 2 / (top - bottom);
dst[6] = 0;
dst[7] = 0;
dst[8] = 0;
dst[9] = 0;
dst[10] = 1 / (near - far);
dst[11] = 0;
dst[12] = (right + left) / (left - right);
dst[13] = (top + bottom) / (bottom - top);
dst[14] = near / (near - far);
dst[15] = 1;
return dst;
}
调用示例:
mat4.ortho(
0, // left
canvas.clientWidth, // right
canvas.clientHeight, // bottom
0, // top
200, // near
-200, // far
matrixValue, // dst
);
背面剔除与深度纹理
三角形全画出来,后面的可能盖住前面的,画面就乱了。WebGPU 给了 cullMode,可以按朝向剔三角形:
primitive: {
cullMode: 'front', // 或 'back'
},
像素空间里 Y 轴朝下,矩阵会把所有三角形垂直翻一遍,所以这里用 cullMode: 'front',同时保证所有三角形的顶点绕向一致。
光靠剔除还是解决不了谁挡谁的顺序问题。办法是上深度纹理(深度缓冲 / Z-Buffer):建好深度纹理,在渲染管线里配上深度测试:
depthStencil: {
depthWriteEnabled: true,
depthCompare: 'less',
format: 'depth24plus',
},
depthCompare: 'less' 的意思是,新片元的深度值比深度缓冲里已有的值小时,才画这个片元、才更新深度缓冲。这样远处的像素盖不住近处的。
渲染通道描述符里得加上深度附件:
const renderPassDescriptor = {
colorAttachments: [
{
loadOp: "clear",
storeOp: "store",
},
],
depthStencilAttachment: {
depthClearValue: 1.0,
depthLoadOp: "clear",
depthStoreOp: "store",
},
};
每帧渲染时,画布尺寸一变,就得建一张同尺寸的深度纹理,或者重建一张:
let depthTexture;
function render() {
const canvasTexture = context.getCurrentTexture();
renderPassDescriptor.colorAttachments[0].view = canvasTexture.createView();
if (
!depthTexture ||
depthTexture.width !== canvasTexture.width ||
depthTexture.height !== canvasTexture.height
) {
if (depthTexture) {
depthTexture.destroy();
}
depthTexture = device.createTexture({
size: [canvasTexture.width, canvasTexture.height],
format: "depth24plus",
usage: GPUTextureUsage.RENDER_ATTACHMENT,
});
}
renderPassDescriptor.depthStencilAttachment.view = depthTexture.createView();
// ...
}
这样遮挡就对了。
术语对照
| 原文术语 | 推荐中文译名 | 备注 |
|---|---|---|
| clip space | 裁剪空间 | 顶点着色器输出坐标所在空间,X/Y/Z 范围为 -1 |
| vertex shader | 顶点着色器 | 处理每个顶点的着色器 |
| fragment shader | 片元着色器 | 处理每个像素的着色器 |
| uniform | 统一变量 | 一组常量数据,通过绑定组传递 |
| inter-stage variable | 阶段间变量 | 从顶点着色器传递到片元着色器的变量 |
| cull mode | 剔除模式 | 'back' / 'front' / 'none' |
| depth texture / depth buffer / Z-buffer | 深度纹理 / 深度缓冲 / Z 缓冲 | 存储每个像素深度值的纹理 |
depth24plus | 深度格式 depth24plus | 24 位深度 + 可能带模板位 |
unorm8x4 | 无符号归一化 8 位 4 分量 | 自动将 0 |
@builtin(position) | 内置位置输出 | 顶点着色器必须输出的裁剪空间位置 |
@location | 属性位置 | 指定着色器输入/输出位置 |
@group / @binding | 绑定组 / 绑定编号 | 资源绑定模型 |
GPUBufferUsage | GPU 缓冲区用途 | 如 VERTEX、INDEX、UNIFORM、COPY_DST 等 |
GPUTextureUsage.RENDER_ATTACHMENT | 纹理渲染附件用途 | 纹理可作为渲染通道的附件 |
orthographic | 正交 | 源自 orthogonal(直角) |
下一篇讲怎么给场景加上透视投影,让远处的物体小一点、近处的大一点。
