WebGPU 高亮效果:描边与选中态实现

原作者: webgpufundamentals Contributors


这是“制作 3D 编辑器”系列的第一篇。每篇都接着上一篇往下讲,所以按顺序看会顺一些。这篇假设你已经看过场景图(Scene Graphs)和后处理(Post Processing)这两篇。

系列目录:

  1. 高亮(Highlighting) ⬅ 你在这里
  2. 相机控制(Camera Controls)
  3. 拾取(Picking)

假设我们要做个简单的 3D 编辑器,灵感来自 Blender、Maya、Unity 或 Unreal,能选中并操作 3D 对象。场景图那篇里已经有节点了,可以用 UI 按钮选中某个节点,改它的平移、旋转、缩放。要是能一眼看出选中的是哪个节点就更好了,这篇就来补上。

从第一次加上节点选择的那个示例出发,场景长这样:

想高亮选中的对象,可以把它单独画到一张纹理上。

这张纹理的 alpha 值就勾出了选中对象的剪影。

然后把这个 alpha 遮罩喂给后处理阶段:遮罩 alpha 是 0、但旁边有非零值的地方,就涂上高亮色,轮廓就出来了。

下面这个着色器跟后处理那套差不多,按 alpha 遮罩画轮廓:

struct VSOutput {
  @builtin(position) position: vec4f,
  @location(0) texcoord: vec2f,
};

@vertex fn vs(
  @builtin(vertex_index) vertexIndex : u32,
) -> VSOutput {
  var pos = array(
    vec2f(-1.0, -1.0),
    vec2f(-1.0,  3.0),
    vec2f( 3.0, -1.0),
  );

  var vsOutput: VSOutput;
  let xy = pos[vertexIndex];
  vsOutput.position = vec4f(xy, 0.0, 1.0);
  vsOutput.texcoord = xy * vec2f(0.5, -0.5) + vec2f(0.5);
  return vsOutput;
}

@group(0) @binding(0) var mask: `texture_2d<f32>`;

fn isOnEdge(pos: vec2i) -> bool {
  // 注意:我们需要确保不会使用超出边界的
  // 纹理坐标调用 textureLoad,因为那样
  // 不同 GPU 上会返回不同的结果
  let size = vec2i(textureDimensions(mask, 0));
  let start = max(pos - 2, vec2i(0));
  let end = min(pos + 2, size);

  for (var y = start.y; y <= end.y; y++) {
    for (var x = start.x; x <= end.x; x++) {
      let s = textureLoad(mask, vec2i(x, y), 0).a;
      if (s > 0) {
        return true;
      }
    }
  }
  return false;
};

@fragment fn fs2d(fsInput: VSOutput) -> @location(0) vec4f {
  let pos = vec2i(fsInput.position.xy);

  // 获取当前纹素。
  // 如果不为 0,则位于被选中对象内部
  let s = textureLoad(mask, pos, 0).a;
  if (s > 0) {
    discard;
  }

  let hit = isOnEdge(pos);
  if (!hit) {
    discard;
  }
  return vec4f(1, 0.5, 0, 1); // 橙色
}

着色器先看遮罩里当前像素是不是大于 0。大于 0 就说明它在遮罩内部(也就是选中对象的区域),这时候什么都不该画,直接 discard 把片段丢掉。

不然就调 isOnEdge 去看邻居。附近一个大于 0 的像素都没有,说明不在边上,同样 discard。

剩下的情况就是在边缘上,涂橙色。

着色器有了,还得把后处理那篇的设置代码搬过来:

  const postProcessModule = device.createShaderModule({
    code: /* wgsl */ `
      struct VSOutput {
        @builtin(position) position: vec4f,
        @location(0) texcoord: vec2f,
      };

      @vertex fn vs(
        @builtin(vertex_index) vertexIndex : u32,
      ) -> VSOutput {
        var pos = array(
          vec2f(-1.0, -1.0),
          vec2f(-1.0,  3.0),
          vec2f( 3.0, -1.0),
        );

        var vsOutput: VSOutput;
        let xy = pos[vertexIndex];
        vsOutput.position = vec4f(xy, 0.0, 1.0);
        vsOutput.texcoord = xy * vec2f(0.5, -0.5) + vec2f(0.5);
        return vsOutput;
      }

      @group(0) @binding(0) var mask: `texture_2d<f32>`;

      fn isOnEdge(pos: vec2i) -> bool {
        // 注意:我们需要确保不会使用超出边界的
        // 纹理坐标调用 textureLoad,因为那样
        // 不同 GPU 上会返回不同的结果
        let size = vec2i(textureDimensions(mask, 0));
        let start = max(pos - 2, vec2i(0));
        let end = min(pos + 2, size);

        for (var y = start.y; y <= end.y; y++) {
          for (var x = start.x; x <= end.x; x++) {
            let s = textureLoad(mask, vec2i(x, y), 0).a;
            if (s > 0) {
              return true;
            }
          }
        }
        return false;
      };

      @fragment fn fs2d(fsInput: VSOutput) -> @location(0) vec4f {
        let pos = vec2i(fsInput.position.xy);

        // 获取当前纹素。如果不为 0,则位于被选中对象内部
        let s = textureLoad(mask, pos, 0).a;
        if (s > 0) {
          discard;
        }

        let hit = isOnEdge(pos);
        if (!hit) {
          discard;
        }
        return vec4f(1, 0.5, 0, 1);
      }
    `,
  });

  const postProcessPipeline = device.createRenderPipeline({
    layout: 'auto',
    vertex: { module: postProcessModule },
    fragment: {
      module: postProcessModule,
      targets: [ { format: presentationFormat }],
    },
  });

-  const postProcessSampler = device.createSampler({
-    minFilter: 'linear',
-    magFilter: 'linear',
-  });

  const postProcessRenderPassDescriptor = {
    label: 'post process render pass',
    colorAttachments: [
-      { loadOp: 'clear', storeOp: 'store' },
+      { loadOp: 'load', storeOp: 'store' },
    ],
  };

-  let renderTarget;
  let postProcessBindGroup;
+  let lastPostProcessTexture;

  function setupPostProcess(texture) {
-    if (renderTarget?.width === canvasTexture.width &&
-        renderTarget?.height === canvasTexture.height) {
-      return;
-    }
-
-    renderTarget?.destroy();
-    renderTarget = device.createTexture({
-      size: canvasTexture,
-      format: 'rgba8unorm',
-      usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
-    });
-    const renderTargetView = renderTarget.createView();
-    renderPassDescriptor.colorAttachments[0].view = renderTargetView;

+    if (!postProcessBindGroup || texture !== lastPostProcessTexture) {
+      lastPostProcessTexture = texture;
*      postProcessBindGroup = device.createBindGroup({
*        layout: postProcessPipeline.getBindGroupLayout(0),
*        entries: [
-          { binding: 0, resource: renderTargetView },
-          { binding: 1, resource: postProcessSampler },
-          { binding: 2, resource: postProcessUniformBuffer },
+          { binding: 0, resource: texture },
*        ],
*      });
+    }
  }

  function postProcess(encoder, srcTexture, dstTexture) {
-    device.queue.writeBuffer(
-      postProcessUniformBuffer,
-      0,
-      new Float32Array([
-        settings.affectAmount,
-        settings.bandMult,
-        settings.cellMult,
-        settings.cellBright,
-      ]),
-    );

    postProcessRenderPassDescriptor.colorAttachments[0].view = dstTexture.createView();
    const pass = encoder.beginRenderPass(postProcessRenderPassDescriptor);
    pass.setPipeline(postProcessPipeline);
    pass.setBindGroup(0, postProcessBindGroup);
    pass.draw(3);
    pass.end();
  }

渲染的时候还要用上这些后处理对象:

+  let selectedMeshes = [];

  function render() {

    ...

-    const encoder = device.createCommandEncoder();
-    const pass = encoder.beginRenderPass(renderPassDescriptor);
-    pass.setPipeline(pipeline);

    const aspect = canvas.clientWidth / canvas.clientHeight;
    const projection = mat4.perspective(
        degToRad(60), // fieldOfView,
        aspect,
        1,      // zNear
        2000,   // zFar
    );

    // 从计算出的矩阵获取相机位置
    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);

+    const encoder = device.createCommandEncoder();
+    {
+      const pass = encoder.beginRenderPass(renderPassDescriptor);
+      pass.setPipeline(pipeline);

*      const ctx = { pass, viewProjectionMatrix };
*      root.updateWorldMatrix();
*      for (const mesh of meshes) {
*        drawMesh(ctx, mesh);
*      }
*
*      pass.end();
+    }

+    // 将选中对象绘制到 postTexture
+    {
+       if (!postTexture ||
+            postTexture.width !== canvasTexture.width)
+            postTexture.height !== canvasTexture.height) {
+         postTexture?.destroy();
+         postTexture = device.createTexture({
+          format: canvasTexture.format,
+          canvasTexture, // 用于尺寸
+          usage: GPUTextureUsage.RENDER_ATTACHMENT |
+                 GPUTextureUsage.TEXTURE_BINDING,
+         });
+       }
+      setupPostProcess(postTexture);
+
+      renderPassDescriptor.colorAttachments[0].view = postTexture.createView();
+      const pass = encoder.beginRenderPass(renderPassDescriptor);
+      pass.setPipeline(pipeline);
+
+      const ctx = { pass, viewProjectionMatrix };
+      for (const mesh of selectedMeshes) {
+        drawMesh(ctx, mesh);
+      }
+
+      pass.end();
+
+      // 基于 postTexture 的 alpha 在 canvasTexture 上绘制轮廓
+      postProcess(encoder, undefined, canvasTexture);
+    }

    const commandBuffer = encoder.finish();
    device.queue.submit([commandBuffer]);
  }

这段代码先画原始场景,再把 selectedMeshes 画进 postTexture。接着把 postTexture 交给后处理,最后把轮廓画到 canvasTexture 上。

有两处代码都在纹理尺寸一变就重建纹理,可以抽个辅助函数简化一下:

+  function makeNewTextureIfSizeDifferent(texture, size, format, usage) {
+    if (!texture ||
+        texture.width !== size.width ||
+        texture.height !== size.height) {
+      texture?.destroy();
+      texture = device.createTexture({
+        format,
+        size,
+        usage,
+      });
+    }
+    return texture;
+  }

...

  function render() {
    ...

    // 如果没有深度纹理或者尺寸与 canvasTexture 不同,则创建新的深度纹理
-    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,
-      });
-    }
+    depthTexture = makeNewTextureIfSizeDifferent(
+      depthTexture,
+      canvasTexture, // 用于尺寸
+      'depth24plus',
+      GPUTextureUsage.RENDER_ATTACHMENT,
+    );

...

    // 将选中对象绘制到 postTexture
    {
-      if (!postTexture ||
-           postTexture.width !== canvasTexture.width)
-           postTexture.height !== canvasTexture.height) {
-        postTexture?.destroy();
-        postTexture = device.createTexture({
-         format: canvasTexture.format,
-         canvasTexture, // 用于尺寸
-         usage: GPUTextureUsage.RENDER_ATTACHMENT |
-                GPUTextureUsage.TEXTURE_BINDING,
-        });
-      }
+      postTexture = makeNewTextureIfSizeDifferent(
+        postTexture,
+        canvasTexture, // 用于尺寸
+        canvasTexture.format,
+        GPUTextureUsage.RENDER_ATTACHMENT |
+        GPUTextureUsage.TEXTURE_BINDING,
+      );
      setupPostProcess(postTexture);

剩下的就是 selectedMeshes 怎么填。场景全是立方体,而且有些节点默认是隐藏的,填的时候得把子节点也算进去,看看所有子节点里有没有用到某个网格:

+  function meshUsesNode(mesh, node) {
+    if (!node) {
+      return false;
+    }
+    if (mesh.node === node) {
+      return true;
+    }
+    for (const child of node.children) {
+      if (meshUsesNode(mesh, child)) {
+        return true;
+      }
+    }
+    return false;
+  }

  const kUnelected = '\u3000'; // 全角空格
  const kSelected = '➡️';
  const prefixRE = new RegExp(`^(?:${kUnelected}|${kSelected})`);

  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}`);
    }

+    selectedMeshes = meshes.filter(mesh => meshUsesNode(mesh, node));

+    render();
  }

这样选中的对象就高亮出来了。

到这儿高亮已经有了,接下来就能做拖拽移动相机,不用再靠 UI 按钮。


关键的三点

离屏渲染选中对象生成 alpha 遮罩。只把选中的网格画到一张独立纹理(postTexture),而不是对整场景做全屏后处理、也不是把所有对象重画一遍。第二遍渲染的开销一下就小了,因为参与绘制的就那几个选中对象;顺手生成的 alpha 遮罩还能直接拿去查轮廓。

边缘检测中的边界安全处理。isOnEdge 里用 max(pos - 2, vec2i(0)) 和 min(pos + 2, size) 把采样范围卡在纹理有效区域里。textureLoad 碰到越界纹素,不同 GPU 可能给出不同结果,显式卡一下才能跨平台一致。

纹理复用与按需重建。靠 makeNewTextureIfSizeDifferent 先看尺寸变没变,只有对不上才销毁重建。这样就不会每帧都建/销纹理,省下显存分配和 GC 的压力。另外后处理通道用的是 loadOp: 'load' 而不是 clear,画布上已经画好的场景留着,不做多余的清除。


术语对照

这篇涉及的核心 API 和着色器语言是 WebGPU 和 WGSL,不是 GLSL/WebGL,不过有些概念能对上。下面列出关键术语和建议译法:

英文术语中文翻译说明
texture_2d<f32>二维浮点纹理WGSL 里的纹理类型,跟 GLSL 的 sampler2D 有点像但更显式
textureLoad纹理加载WGSL 内置函数,直接读指定纹素,不做过滤
textureDimensions纹理尺寸返回纹理的宽度和高度
discard丢弃片段跟 GLSL 的 discard 一样,终止当前片段
@builtin(position)内建变量(位置)对应 GLSL 的 gl_Position
@location(0)位置索引 0对应 GLSL 的 layout(location=0)
@group(0) @binding(0)绑定组 0,绑定点 0WebGPU 的资源绑定模型,类似 WebGL 的 uniform/texture unit 但更统一
bind group绑定组一组绑定的资源集合,对应 WebGL 里多个 uniform/texture 的组合
render pass渲染通道WebGPU 的渲染流程单元,类似 WebGL 的一次 draw call 集合
render pipeline渲染管线装着着色器、混合状态、深度模板等完整配置
GPUTextureUsage.RENDER_ATTACHMENTGPU 纹理用途:渲染附件表示纹理能当渲染目标
GPUTextureUsage.TEXTURE_BINDINGGPU 纹理用途:纹理绑定表示纹理能当着色器资源绑定
loadOp: 'load'加载操作:加载渲染通道开始时保留附件已有内容,对应 WebGL 里不清画布
storeOp: 'store'存储操作:存储渲染通道结束后把结果写回纹理
vec2i / vec4f二维整数向量 / 四维浮点向量WGSL 类型,对应 GLSL 的 ivec2 / vec4
u32 / f3232 位无符号整数 / 32 位浮点数WGSL 标量类型

这些术语在编译时都保留了英文原名,或者用了行业通用的中文译法,技术上应该没问题。想深究的话,可以对着 WebGPU 规范再查一遍。