Miscellaneous Shader Input(杂项着色器输入)


关于编译

这篇是 WebGPU Fundamentals 系列里「向着色器传数据」的一篇。前面几篇依次讲过:

阶段间变量(Inter-stage Variables)→ Uniforms → Storage Buffers → Vertex Buffers → Textures → Loading Images → Using Video → Cube Maps → Storage Textures → Multisampling / MSAA → Immediates → Constants,本篇是最后一篇:Miscellaneous Shader Input。

这里只讲一种不太常见、但很好用的输入方式:firstInstance。


正文解读:用 firstInstance 给着色器传递数据

调 draw 或者 drawIndexed 的时候,可以塞一个 firstInstance 进去:

pass.draw(
  numVertices,
  (numInstances = 1),
  (firstVertex = 0),
  (firstInstance = 0),
); // <== 这里

pass.drawIndexed(
  indexCount,
  (instanceCount = 1),
  (firstIndex = 0),
  (baseVertex = 0),
  (firstInstance = 0),
); // <== 这里

这个值在着色器里对应 @builtin(instance_index)。也就是说,哪怕不做真正的实例化渲染,也能拿它传一个索引,用这个索引去选不同的数据。拿“第一篇文章”里那个简单三角形举例,可以这么改。

示例 1:用 instanceIndex 选择偏移量

+struct VertexOut {
+  @builtin(position) pos: vec4f,
+  @location(0) @interpolate(flat, either) colorNdx: u32,
+};

@vertex fn vs(
*  @builtin(vertex_index) vertexIndex : u32,
+  @builtin(instance_index) instanceIndex: u32,
) -> VertexOut {
  let pos = array(
    vec2f( 0.0,  0.5),  // top center
    vec2f(-0.5, -0.5),  // bottom left
    vec2f( 0.5, -0.5)   // bottom right
  );
+  let offsets = array(
+    vec2f( 0.0,  0.5),  // top middle
+    vec2f(-0.5, -0.5),  // left bottom
+    vec2f( 0.5, -0.5),  // right bottom
+  );

-  return vec4f(pos[vertexIndex], 0.0, 1.0);
+  return VertexOut(
+    vec4f(pos[vertexIndex] + offsets[instanceIndex], 0.0, 1.0),
+    instanceIndex,
+  );
}

-@fragment fn fs() -> @location(0) vec4f {
-  return vec4f(1, 0, 0, 1);
-}
+@fragment fn fs(in: VertexOut) -> @location(0) vec4f {
+  let colors = array(
+    vec4f(1, 1, 0, 1),  // yellow
+    vec4f(0, 1, 1, 1),  // cyan
+    vec4f(1, 0, 1, 1),  // magenta
+  );
+  return colors[in.colorNdx];
+}

这段代码用 instanceIndex 选偏移量,再通过一个带 @interpolate(flat, either) 的阶段间变量,把实例索引送到片元着色器。
flat 就是“别插值”;either 表示从三角形的第一个或最后一个顶点取值。反正所有顶点传的值都一样,取头取尾没区别。不过 either 在兼容模式(compatibility mode)下也能用,所以更推荐。

最后把 draw 多调两次,画出 3 个三角形:

function render() {
  // 获取 canvas 当前纹理并设为渲染目标
  renderPassDescriptor.colorAttachments[0].view = context
    .getCurrentTexture()
    .createView();

  const encoder = device.createCommandEncoder({ label: "our encoder" });
  const pass = encoder.beginRenderPass(renderPassDescriptor);
  pass.setPipeline(pipeline);
  pass.draw(3); // 调用顶点着色器 3 次
  +pass.draw(3, 1, 0, 1); // 为 instance_index 传递 1
  +pass.draw(3, 1, 0, 2); // 为 instance_index 传递 2
  pass.end();

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

渲出来就是三个不同颜色的三角形(在线示例看原文链接)。


示例 2:结合 Storage Buffer 数组

也不一定非得在着色器里写死数组,可以用 instance_index 从 Storage Buffer 的数组里取数据:

struct VertexOut {
  @builtin(position) pos: vec4f,
  @location(0) @interpolate(flat, either) instanceIndex: u32,
};

struct PerInstanceInfo {
  matrix: mat4x4f,
  color: vec4f,
};

@group(0) @binding(0) `var<storage, read>` perInst: `array<PerInstanceInfo>`;

@vertex fn vs(
  @location(0) position: vec4f,
  @builtin(instance_index) instanceIndex: u32,
) -> VertexOut {
  let info = perInst[instanceIndex];

  return VertexOut(
    info.matrix * position,
    instanceIndex,
  );
}

@fragment fn fs(in: VertexOut) -> @location(0) vec4f {
  let info = perInst[in.instanceIndex];
  return info.color;
}

何时使用该方法

用不用这招,你自己定。draw 之间的小幅变化,用 immediates 也行。

firstInstance 的好处是:

  1. WebGPU API 调用次数少;
  2. 不用为了传一个数字专门建个 ArrayBufferView。

这个系列在生成 mipmap、还要让它兼容 compatibility mode 的时候也用到了这招。有了它,选 2D 数组纹理或立方体贴图的某一层很省事,不用另外建 uniform buffer。

顺带说一句:vertex_index 也能通过 draw 的参数控制,但平时它要用来选顶点,所以很少拿它传自定义数据。


关键的三点

  1. 用 firstInstance 传轻量整数索引,省掉额外的 Uniform Buffer / ArrayBufferView
    只是单个数字或者变化很少的时候,直接塞进 draw/drawIndexed 的 firstInstance,着色器里用 @builtin(instance_index) 读。这样 WebGPU 调用少,也不用为了一个小值去建 JS 类型数组视图或者绑 uniform 资源。

  2. 配 Storage Buffer 数组,用 instanceIndex 直接索引 per-instance 数据
    把多个实例的矩阵、颜色一次性放进 var<storage, read> array<PerInstanceInfo>,着色器里用 instanceIndex 取。这样就不用每个实例单独设 uniform,也不用反复 draw。批量传参,绑定和调用都简单。

  3. 用 @interpolate(flat, either) 传常量阶段间变量,兼容性更好也不吃插值开销
    从顶点着色器往片元着色器传不该插值的值(比如实例索引)时,用 flat 关掉插值;选 either 在 compatibility mode 下也能正常工作。比默认插值更省、也更可移植。


术语对照

查下来,这篇用的基本都是 WebGPU / WGSL 术语,不是 GLSL/WebGL 代码。核心术语和 GLSL/WebGL 的对应关系如下:

WebGPU/WGSL 术语说明GLSL/WebGL 类似术语或概念
@builtin(instance_index)当前实例索引gl_InstanceID / gl_InstanceID(WebGL2)
@builtin(vertex_index)当前顶点索引gl_VertexID / gl_VertexIndex
@builtin(position)顶点输出裁剪坐标gl_Position
@interpolate(flat, either)阶段间变量插值修饰符GLSL flat 插值限定符
Storage Buffer可读可写的缓冲区Shader Storage Buffer Object(SSBO)
Uniform Buffer只读统一缓冲区Uniform Buffer Object(UBO)
Vertex Buffer顶点数据缓冲区Vertex Buffer Object(VBO)
Inter-stage Variables顶点到片元之间的传递变量varying / in / out
firstInstancedraw 系列调用参数,指定实例索引起始值baseInstance(部分 GLES/GL 版本)
compatibility modeWebGPU 兼容模式WebGL 模式相关,非 GLSL 原生术语
no interpolation禁用插值flat

结论:这篇没有混用 GLSL/WebGL 术语,用法符合 WebGPU/WGSL 规范。either 是 WGSL 特有的插值采样选项,GLSL 里没有直接对应的东西。