WebGPU Scene Graphs(场景图)
导言
这是 3D 数学系列的第 9 篇,前面依次讲过平移、旋转、缩放、矩阵数学、正交投影、透视投影、相机和矩阵栈。上一篇用矩阵栈(Matrix Stack)在代码里拼变换,好让物体相对别的物体定位、定向、缩放。场景图(Scene Graph)思路差不多,区别在于它不靠代码,靠数据搭父子节点树,每个子节点拿父节点的矩阵算出自己的世界矩阵。
比如文件柜场景,场景图大概长这样:
root
+-cabinet0
| +-cabinet0-mesh
| +-drawer0
| | +-drawer0-drawer-mesh
| | +-drawer0-handle-mesh
| +-drawer1
| | +-drawer1-drawer-mesh
| | +-drawer1-handle-mesh
...
+-cabinet1
| ...
场景图的好处是把所有变换关系都存进节点里,想动哪一块直接动,不用在代码里递归处理。
核心实现:SceneGraphNode 类
先要一个表示场景图节点的类:
class SceneGraphNode {
constructor(name, source) {
this.name = name;
this.children = [];
this.localMatrix = mat4.identity();
this.worldMatrix = mat4.identity();
this.source = source;
}
addChild(child) {
child.setParent(this);
}
removeChild(child) {
child.setParent(null);
}
setParent(parent) {
// 从原父节点移除
if (this.parent) {
const ndx = this.parent.children.indexOf(this);
if (ndx >= 0) {
this.parent.children.splice(ndx, 1);
}
}
// 添加到新父节点
if (parent) {
parent.children.push(this);
}
this.parent = parent;
}
updateWorldMatrix() {
// 如果有 source,先更新局部矩阵
this.source?.getMatrix(this.localMatrix);
if (this.parent) {
// 有父节点:世界矩阵 = 父世界矩阵 * 局部矩阵
mat4.multiply(
this.parent.worldMatrix,
this.localMatrix,
this.worldMatrix,
);
} else {
// 根节点:直接复制局部矩阵为世界矩阵
mat4.copy(this.localMatrix, this.worldMatrix);
}
// 递归更新所有子节点
this.children.forEach(function (child) {
child.updateWorldMatrix();
});
}
}
每个节点里有:
localMatrix:相对父节点的位置、旋转和缩放。worldMatrix:相对场景图外部的世界坐标变换。source:可选对象,带getMatrix方法,用来按自定义方式算局部矩阵。updateWorldMatrix:更新自己和所有子节点的世界矩阵。
TRS 源(Translation, Rotation, Scale)
TRS 是平移(Translation)、旋转(Rotation)、缩放(Scale)的缩写,也是场景图里算局部矩阵最常用的方式。这里用 Float32Array 存数据,方便拿 set 方法动态改。
class TRS {
constructor({
translation = [0, 0, 0],
rotation = [0, 0, 0],
scale = [1, 1, 1],
} = {}) {
this.translation = new Float32Array(translation);
this.rotation = new Float32Array(rotation);
this.scale = new Float32Array(scale);
}
getMatrix(dst) {
mat4.translation(this.translation, dst);
mat4.rotateX(dst, this.rotation[0], dst);
mat4.rotateY(dst, this.rotation[1], dst);
mat4.rotateZ(dst, this.rotation[2], dst);
mat4.scale(dst, this.scale, dst);
return dst;
}
}
getMatrix 的算法顺序是 translation × rotationX × rotationY × rotationZ × scale。实际项目里常会让人调旋转顺序(ZYX、YZX 之类),也可能上四元数或几何代数。
构建场景图
写个辅助函数,把 SceneGraphNode 和 TRS 源拼一起:
function addTRSSceneGraphNode(name, parent, trs) {
const node = new SceneGraphNode(name, new TRS(trs));
if (parent) {
node.setParent(parent);
}
return node;
}
再加个加网格(mesh)的辅助函数:
const meshes = [];
function addMesh(node, vertices, color) {
const mesh = { node, vertices, color };
meshes.push(mesh);
return mesh;
}
加立方体节点:
function addCubeNode(name, parent, trs, color) {
const node = addTRSSceneGraphNode(name, parent, trs);
return addMesh(node, cubeVertices, color);
}
文件柜场景图
建根节点,循环往里塞文件柜:
const root = new SceneGraphNode("root");
for (let cabinetNdx = 0; cabinetNdx < kNumCabinets; ++cabinetNdx) {
addCabinet(root, cabinetNdx);
}
addCabinet 和 addDrawer 长这样:
function addCabinet(parent, cabinetNdx) {
const cabinetName = `cabinet${cabinetNdx}`;
const cabinet = addTRSSceneGraphNode(cabinetName, parent, {
translation: [cabinetNdx * kCabinetSpacing, 0, 0],
});
const kCabinetSize = [
kDrawerSize[kWidth] + 6,
kDrawerSpacing * kNumDrawersPerCabinet + 6,
kDrawerSize[kDepth] + 4,
];
addCubeNode(
`${cabinetName}-mesh`,
cabinet,
{ scale: kCabinetSize },
kCabinetColor,
);
for (let drawerNdx = 0; drawerNdx < kNumDrawersPerCabinet; ++drawerNdx) {
addDrawer(cabinet, drawerNdx);
}
}
function addDrawer(parent, drawerNdx) {
const drawerName = `drawer${drawerNdx}`;
const drawer = addTRSSceneGraphNode(drawerName, parent, {
translation: [3, drawerNdx * kDrawerSpacing + 5, 1],
});
addCubeNode(
`${drawerName}-drawer-mesh`,
drawer,
{ scale: kDrawerSize },
kDrawerColor,
);
addCubeNode(
`${drawerName}-handle-mesh`,
drawer,
{
translation: kHandlePosition,
scale: kHandleSize,
},
kHandleColor,
);
}
渲染循环调整
用场景图替掉原来的矩阵栈调用:
// 旧代码(矩阵栈)
// stack.save();
// stack.rotateY(settings.baseRotation);
// stack.translate([(kNumCabinets - 0.5) * kCabinetSpacing * -0.5, 0, 0]);
// const ctx = { pass, stack, viewProjectionMatrix };
// drawCabinets(ctx, kNumCabinets);
// stack.restore();
// 新代码(场景图)
const ctx = { pass, viewProjectionMatrix };
root.updateWorldMatrix();
for (const mesh of meshes) {
drawMesh(ctx, mesh);
}
相机代码也改成靠矩阵求逆:
const cameraMatrix = mat4.identity();
mat4.translate(cameraMatrix, [120, 100, 0], cameraMatrix);
mat4.rotateY(cameraMatrix, settings.cameraRotation, cameraMatrix);
mat4.translate(cameraMatrix, [60, 0, 300], cameraMatrix);
const viewMatrix = mat4.inverse(cameraMatrix);
const viewProjectionMatrix = mat4.multiply(projection, viewMatrix);
添加 GUI 控制
场景图的一个核心价值:它是数据,所以挂到 UI 上很方便。我们加了个 TRSUIHelper 类,把任意 TRS 暴露给 GUI 编辑。
class TRSUIHelper {
#trs = new TRS();
setTRS(trs) {
this.#trs = trs;
}
get translationX() {
return this.#trs.translation[0];
}
set translationX(x) {
this.#trs.translation[0] = x;
}
// ... 其余 translation/rotation/scale 的 getter/setter
}
顺便遍历场景图生成节点选择按钮:
function setCurrentSceneGraphNode(node) {
trsUIHelper.setTRS(node.source);
trsFolder.name(`orientation: ${node.name}`);
trsFolder.updateDisplay();
// 标记选中的节点按钮
for (const b of nodeButtons) {
const name = b.button.getName().replace(prefixRE, "");
b.button.name(`${b.node === node ? kSelected : kUnelected}${name}`);
}
}
默认只显示一部分 TRS 控件(文件柜主要关心 translation z)。
动画
场景图另一个好处是给节点加动画很容易。把抽屉节点塞进 animNodes 数组,按时间改 translation z:
const animNodes = [];
function addDrawer(parent, drawerNdx) {
// ... 创建节点后
animNodes.push(drawer);
}
function animate(time) {
animNodes.forEach((node, i) => {
const source = node.source;
const t = time + i * 1;
const l = Math.sin(t) * 0.5 + 0.5;
source.translation[2] = lerp(1, kDrawerSize[2] * 0.8, l);
});
}
为了撑住动画循环,我们写了 requestRender 和 wasRunning 做时间步管理,暂停期间不会出现时间跳变。
制作手部场景图
我们还用立方体拼了个简单的手,场景图结构是这样:
root
+-wrist
+-palm
| +-thumb
| | +-thumb-mesh
| | +-thumb-1
| | +-thumb-1-mesh
| +-index finger
| | +-index finger-mesh
| | +-index finger-1
| | +-index finger-1-mesh
| | +-index finger-2
| | +-index finger-2-mesh
...
+-palm-mesh
addFinger 建手指的多个关节:
function addFinger(name, parent, segments, segmentHeight, trs) {
const nodes = [];
const baseName = name;
for (let i = 0; i < segments; ++i) {
const node = addTRSSceneGraphNode(name, parent, trs);
nodes.push(node);
const meshNode = addTRSSceneGraphNode(`${name}-mesh`, node, {
scale: [10, segmentHeight, 10],
});
addMesh(meshNode, cubeVertices, kWhite);
parent = node;
name = `${baseName}-${i + 1}`;
trs = {
translation: [0, segmentHeight, 0],
rotation: [degToRad(15), 0, 0],
};
}
return nodes;
}
发射投射物
场景图还能随手拿到任意节点的位置和朝向。比如从食指末端打投射物。先在 SceneGraphNode 里加个 find 方法:
find(name) {
if (this.name === name) {
return this;
}
for (const child of this.children) {
const found = child.find(name);
if (found) {
return found;
}
}
return undefined;
}
然后找到食指最后一个关节,挂一个代表指尖的子节点:
const fingerTip = addTRSSceneGraphNode(
"finger-tip",
root.find("index finger-2"),
{ translation: [0, 30, 0] },
);
发射逻辑:
const kShotVelocity = 100; // 单位/秒
const shots = [];
let shotId = 0;
function fireShot() {
const node = new SceneGraphNode(`shot-${shotId++}`);
node.setParent(root);
mat4.translate(fingerTip.worldMatrix, [0, 20, 0], node.localMatrix);
const mesh = addMesh(node, shotVertices, kWhite);
const velocity = vec3.mulScalar(
vec3.normalize(vec3.getAxis(fingerTip.worldMatrix, 1)),
kShotVelocity,
);
shots.push({
node,
mesh,
velocity,
endTime: performance.now() * 0.001 + 5,
});
requestRender();
}
投射物更新和清理:
function processShots(now, deltaTime) {
if (shots.length > 0) {
requestRender();
while (shots.length && shots[0].endTime <= now) {
const shot = shots.shift();
shot.node.setParent(null);
removeMesh(shot.mesh);
}
for (const shot of shots) {
const v = vec3.mulScalar(shot.velocity, deltaTime);
mat4.multiply(
mat4.translation(v),
shot.node.localMatrix,
shot.node.localMatrix,
);
}
}
}
总结
这篇讲了场景图的概念和实现。场景图是大多数 3D 引擎(Unity、Unreal、Blender、Three.js 等)的地基,它把变换关系组织成节点树,操作、动画、查询变换都方便。相机一般也挂在场景图里,这样能被父节点带着走(车载相机、旋转监控相机都是这路子)。做 3D 编辑器里的操纵器(平移/旋转/缩放控件)也离不开它,这部分或许后面再讲。
关键的三点
数据驱动的层次结构,替掉代码矩阵栈。场景图把变换关系存成节点树,子节点的世界矩阵 = 父节点世界矩阵 × 自己的局部矩阵。这样不用在代码里手动维护矩阵栈,任意子节点的位置、旋转、缩放都能单独调,渲染逻辑一行不用动。
TRS 源抽象,矩阵按需算。局部矩阵的计算封进 TRS 源对象,UI 和动画直接改 translation、rotation、scale 数组,每帧更新世界矩阵时再靠 getMatrix 现算。设计清晰,也不用频繁造临时矩阵对象,换别的变换来源(四元数、几何代数)也好扩展。
按需渲染循环 + 时间步管理。用 requestRender 管渲染请求,只有 GUI 变了、动画在跑、或者还有活跃投射物时才请求下一帧。wasRunning 标志处理动画时钟,暂停期间不会时间跳变,动画连续性有了,多余渲染也省了。
术语对照
这篇讲的是 WebGPU,着色器语言是 WGSL(WebGPU Shading Language),不是 GLSL。但术语上 WebGPU 和 WebGL 有很多对应或相似的地方,关键术语列在下面,方便对照:
| 英文术语 | 中文翻译 | 备注 / WebGL 对应 |
|---|---|---|
| Scene Graph | 场景图 | 与 WebGL 中概念相同 |
| Node | 节点 | 场景图的基本单元 |
| Local Matrix / World Matrix | 局部矩阵 / 世界矩阵 | 与 WebGL 中的模型矩阵概念一致 |
| Translation / Rotation / Scale | 平移 / 旋转 / 缩放 | 3D 变换基础 |
| TRS | 平移旋转缩放(变换) | 常见变换组合 |
| Matrix Stack | 矩阵栈 | WebGL 旧版固定管线中常见(如 glPushMatrix/glPopMatrix),现代 WebGL 需自行实现 |
| View Matrix / Projection Matrix | 视图矩阵 / 投影矩阵 | 与 WebGL 中一致 |
| Vertex Buffer | 顶点缓冲区 | WebGPU 用 GPUBuffer,WebGL 用 WebGLBuffer |
| Uniform Buffer / Uniforms | 统一变量缓冲区 / 统一变量 | WebGPU 里靠 Bind Group 给,WebGL 用 uniform 变量 |
| Bind Group | 绑定组 | WebGPU 特有概念,类似 WebGL 中的 uniform 块绑定 |
| WGSL | WGSL(WebGPU 着色语言) | WebGPU 着色语言,取代 GLSL |
| GLSL | OpenGL 着色语言 | 给 WebGL 和 OpenGL 用,WebGPU 不再用 |
| Pass / Render Pass | 渲染通道 | WebGPU 概念,对应 WebGL 的绘制循环 |
| Compute Shader | 计算着色器 | 两边都支持,但编程语言不同 |
补充一句:这篇代码里的矩阵运算函数(mat4.multiply、mat4.rotateY 等)来自自定义的 mat4 数学库,不是 WebGPU 或 GLSL 内建的。WebGPU 里实际的顶点变换一般写在 WGSL 着色器内(用 mat4x4<f32> 这类类型),而不是在 JavaScript 里算。这篇为了教学,把矩阵运算放在 CPU 端做,方便看清场景图的数据怎么流动。
这篇就是对 WebGPU Scene Graphs 的解读。全文在忠实原意的前提下做了精简和整合,核心代码和实现逻辑都留着,关键术语也顺手核对了一遍。
