WebGPU 加载图像到纹理

原文标题:WebGPU Loading Images into Textures


这篇讲怎么把图像加载进纹理,还有在 GPU 上生成 mipmap。

WebGPU Loading Images into Textures

使用 copyExternalImageToTexture 加载图像

上一篇里,我们用 device.createTexture 建纹理,再用 device.queue.writeTexture 写数据。其实 device.queue 上还有个函数 device.queue.copyExternalImageToTexture,能把图像直接复制进纹理。它收一个 ImageBitmap 当源,所以我们可以从上一篇文章的 magFilter 示例下手,改成加载几张图片。

先写一段从图片 URL 拿 ImageBitmap 的代码:

async function loadImageBitmap(url) {
  const res = await fetch(url);
  const blob = await res.blob();
  return await createImageBitmap(blob, { colorSpaceConversion: "none" });
}

这段先 fetch 拿到图片响应,取出 Blob(图片文件的原始数据),再调浏览器标准 API createImageBitmap 生成 ImageBitmap。传 { colorSpaceConversion: 'none' } 是告诉浏览器别做任何色彩空间转换。要不要让浏览器转,看你的需求——WebGPU 里我们经常加载法线贴图、高度图这类非颜色数据,这时候绝对不想浏览器动图像数据。

拿到 ImageBitmap 之后,加载一张图片,建一张同样尺寸的纹理。这里用下面这张 F 纹理(带个 F 好观察方向):

-  const texture = device.createTexture({
-    label: 'yellow F on red',
-    size: [kTextureWidth, kTextureHeight],
-    format: 'rgba8unorm',
-    usage:
-      GPUTextureUsage.TEXTURE_BINDING |
-      GPUTextureUsage.COPY_DST,
-  });
+  const url = 'resources/images/f-texture.png';
+  const source = await loadImageBitmap(url);
+  const texture = device.createTexture({
+    label: url,
+    format: 'rgba8unorm',
+    size: [source.width, source.height],
+    usage: GPUTextureUsage.TEXTURE_BINDING |
+           GPUTextureUsage.COPY_DST |
+           GPUTextureUsage.RENDER_ATTACHMENT,
+  });

得注意,copyExternalImageToTexture 要求纹理的 usage 里带上 GPUTextureUsage.COPY_DST 和 GPUTextureUsage.RENDER_ATTACHMENT 这两个标志。

接着把 ImageBitmap 复制进纹理:

-  device.queue.writeTexture(
-      { texture },
-      textureData,
-      { bytesPerRow: kTextureWidth * 4 },
-      { width: kTextureWidth, height: kTextureHeight },
-  );
+  device.queue.copyExternalImageToTexture(
+    { source, flipY: true },
+    { texture },
+    { width: source.width, height: source.height },
+  );

copyExternalImageToTexture 的参数顺序是源、目标、尺寸。源对象里能设 flipY: true,加载时把 Y 轴翻过来。

这样就能跑了。

Simple Image Loading Functions

在 GPU 上生成 mipmap

在上一篇文章里我们生成过 mipmap,但那是直接改图像数据。加载图片的时候,你也可以先画到 2D canvas,再调 getImageData 取像素,然后生成 mip 上传。但这路子很慢,而且 canvas 2D 渲染本身有损(跟实现相关)。

之前生成 mip 用的是双线性插值,GPU 在 minFilter: linear 下干的就是这件事。所以这个特性可以拿来在 GPU 上生成 mip。

先算需要几层 mip:

const numMipLevels = (...sizes) => {
  const maxSize = Math.max(...sizes);
  return (1 + Math.log2(maxSize)) | 0;
};

Math.log2 算的是把一个数除以 2 多少次能到 1。比如 numMipLevels(123, 456) 返回 9,因为要 9 层(0 到 8)。

建纹理时把 mip 层数写对:

const texture = device.createTexture({
  label: url,
  format: "rgba8unorm",
  mipLevelCount: numMipLevels(source.width, source.height),
  size: [source.width, source.height],
  usage:
    GPUTextureUsage.TEXTURE_BINDING |
    GPUTextureUsage.COPY_DST |
    GPUTextureUsage.RENDER_ATTACHMENT,
});
device.queue.copyExternalImageToTexture(
  { source, flipY: true },
  { texture },
  { width: source.width, height: source.height },
);

生成 mip 的完整函数在下面(有点长,但跟之前的纹理示例几乎一样):

const generateMips = (() => {
  let sampler;
  let module;
  const pipelineByFormat = {};

  return function generateMips(device, texture) {
    if (!module) {
      module = device.createShaderModule({
        label: 'textured quad shaders for mip level generation',
        code: /* wgsl */ `
          struct VSOutput {
            @builtin(position) position: vec4f,
            @location(0) texcoord: vec2f,
          };

          @vertex fn vs(
            @builtin(vertex_index) vertexIndex : u32
          ) -> VSOutput {
            let pos = array(
              // 1st triangle
              vec2f( 0.0,  0.0),  // center
              vec2f( 1.0,  0.0),  // right, center
              vec2f( 0.0,  1.0),  // center, top

              // 2nd triangle
              vec2f( 0.0,  1.0),  // center, top
              vec2f( 1.0,  0.0),  // right, center
              vec2f( 1.0,  1.0),  // right, top
            );

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

          @group(0) @binding(0) var ourSampler: sampler;
          @group(0) @binding(1) var ourTexture: `texture_2d<f32>`;

          @fragment fn fs(fsInput: VSOutput) -> @location(0) vec4f {
            return textureSample(ourTexture, ourSampler, fsInput.texcoord);
          }
        `,
      });

      sampler = device.createSampler({
        minFilter: 'linear',
      });
    }

    if (!pipelineByFormat[texture.format]) {
      pipelineByFormat[texture.format] = device.createRenderPipeline({
        label: 'mip level generator pipeline',
        layout: 'auto',
        vertex: {
          module,
        },
        fragment: {
          module,
          targets: [{ format: texture.format }],
        },
      });
    }
    const pipeline = pipelineByFormat[texture.format];

    const encoder = device.createCommandEncoder({
      label: 'mip gen encoder',
    });

    for (let baseMipLevel = 1; baseMipLevel < texture.mipLevelCount; ++baseMipLevel) {
      const bindGroup = device.createBindGroup({
        layout: pipeline.getBindGroupLayout(0),
        entries: [
          { binding: 0, resource: sampler },
          {
            binding: 1,
            resource: texture.createView({
              baseMipLevel: baseMipLevel - 1,
              mipLevelCount: 1,
            }),
          },
        ],
      });

      const renderPassDescriptor = {
        label: 'our basic canvas renderPass',
        colorAttachments: [
          {
            view: texture.createView({
              baseMipLevel,
              mipLevelCount: 1,
            }),
            loadOp: 'clear',
            storeOp: 'store',
          },
        ],
      };

      const pass = encoder.beginRenderPass(renderPassDescriptor);
      pass.setPipeline(pipeline);
      pass.setBindGroup(0, bindGroup);
      pass.draw(6);  // call our vertex shader 6 times
      pass.end();
    }
    const commandBuffer = encoder.finish();
    device.queue.submit([commandBuffer]);
  };
})();

几个要点:

  • 用闭包把 module、sampler、pipelineByFormat 存起来复用。
  • 着色器跟前面几乎一样,只是顶点位置不再走 uni.matrix,改成直接映射到裁剪空间,纹理坐标的 Y 也翻一下,保证画满整个目标 mip 层。
  • pipelineByFormat 按纹理格式缓存渲染管线,因为管线得知道目标格式。
  • 靠 texture.createView 挑具体的 mip 层:绑定组里读上一级 mip,渲染目标设成当前 mip。
  • 一层层遍历,逐级生成。

注意:这个函数只管 2D 纹理。立方体贴图文章会把它扩展到 2D 数组纹理和立方体贴图。

Simple Image Loading Functions

简单图像加载辅助函数

为了加载图像、生成 mip 省事,封装两个函数:

function copySourceToTexture(device, texture, source, { flipY } = {}) {
  device.queue.copyExternalImageToTexture(
    { source, flipY },
    { texture },
    { width: source.width, height: source.height },
  );

  if (texture.mipLevelCount > 1) {
    generateMips(device, texture);
  }
}
function createTextureFromSource(device, source, options = {}) {
  const texture = device.createTexture({
    format: "rgba8unorm",
    mipLevelCount: options.mips ? numMipLevels(source.width, source.height) : 1,
    size: [source.width, source.height],
    usage:
      GPUTextureUsage.TEXTURE_BINDING |
      GPUTextureUsage.COPY_DST |
      GPUTextureUsage.RENDER_ATTACHMENT,
  });
  copySourceToTexture(device, texture, source, options);
  return texture;
}
async function createTextureFromImage(device, url, options) {
  const imgBitmap = await loadImageBitmap(url);
  return createTextureFromSource(device, imgBitmap, options);
}

把原来的 createTextureWithMips 调用换掉:

-  const textures = [
-    createTextureWithMips(createBlendedMipmap(), 'blended'),
-    createTextureWithMips(createCheckedMipmap(), 'checker'),
-  ];
+  const textures = await Promise.all([
+    await createTextureFromImage(device,
+        'resources/images/f-texture.png', {mips: true, flipY: false}),
+    await createTextureFromImage(device,
+        'resources/images/coins.jpg', {mips: true}),
+    await createTextureFromImage(device,
+        'resources/images/Granite_paving_tileable_512x512.jpeg', {mips: true}),
+  ]);

加载 Canvas

copyExternalImageToTexture 也收 HTMLCanvasElement 当源。可以先在 2D canvas 上画,再把结果加载到 WebGPU 纹理。

先做个 canvas 动画:

const size = 256;
const half = size / 2;

const ctx = document.createElement("canvas").getContext("2d");
ctx.canvas.width = size;
ctx.canvas.height = size;

const hsl = (h, s, l) =>
  `hsl(${(h * 360) | 0}, ${s * 100}%, ${(l * 100) | 0}%)`;

function update2DCanvas(time) {
  time *= 0.0001;
  ctx.clearRect(0, 0, size, size);
  ctx.save();
  ctx.translate(half, half);
  const num = 20;
  for (let i = 0; i < num; ++i) {
    ctx.fillStyle = hsl((i / num) * 0.2 + time * 0.1, 1, (i % 2) * 0.5);
    ctx.fillRect(-half, -half, size, size);
    ctx.rotate(time * 0.5);
    ctx.scale(0.85, 0.85);
    ctx.translate(size / 16, 0);
  }
  ctx.restore();
}

function render(time) {
  update2DCanvas(time);
  requestAnimationFrame(render);
}
requestAnimationFrame(render);

把 canvas 塞进 WebGPU,改动很少:

+  const texture = createTextureFromSource(device, ctx.canvas, {mips: true});

  const textures = await Promise.all([
-    await createTextureFromImage(device,
-        'resources/images/f-texture.png', {mips: true, flipY: false}),
-    await createTextureFromImage(device,
-        'resources/images/coins.jpg', {mips: true}),
-    await createTextureFromImage(device,
-        'resources/images/Granite_paving_tileable_512x512.jpeg', {mips: true}),
+    texture,
  ]);

然后换成 requestAnimationFrame 循环,每帧更新 2D canvas 再上传:

-  function render() {
+  function render(time) {
+    update2DCanvas(time);
+    copySourceToTexture(device, texture, ctx.canvas);

     ...

    requestAnimationFrame(render);
  }
  requestAnimationFrame(render);

加载 Video

视频也差不多。ImageBitmap 和 HTMLCanvasElement 的尺寸属性是 width / height,HTMLVideoElement 却是 videoWidth / videoHeight。辅助函数得改一下才兼容:

+  function getSourceSize(source) {
+    return [
+      source.videoWidth || source.width,
+      source.videoHeight || source.height,
+    ];
+  }

  function copySourceToTexture(device, texture, source, {flipY} = {}) {
    device.queue.copyExternalImageToTexture(
      { source, flipY, },
      { texture },
-      { width: source.width, height: source.height },
+      getSourceSize(source),
    );

    if (texture.mipLevelCount > 1) {
      generateMips(device, texture);
    }
  }

  function createTextureFromSource(device, source, options = {}) {
+    const size = getSourceSize(source);
    const texture = device.createTexture({
      format: 'rgba8unorm',
-      mipLevelCount: options.mips ? numMipLevels(source.width, source.height) : 1,
-      size: [source.width, source.height],
+      mipLevelCount: options.mips ? numMipLevels(...size) : 1,
+      size,
      usage: GPUTextureUsage.TEXTURE_BINDING |
             GPUTextureUsage.COPY_DST |
             GPUTextureUsage.RENDER_ATTACHMENT,
    });
    copySourceToTexture(device, texture, source, options);
    return texture;
  }

视频元素得等播放开始才能用。可以用 video.requestVideoFrameCallback 拿新帧回调,不支持就退回去轮询 currentTime:

+  function startPlayingAndWaitForVideo(video) {
+    return new Promise((resolve, reject) => {
+      video.addEventListener('error', reject);
+      if ('requestVideoFrameCallback' in video) {
+        video.requestVideoFrameCallback(resolve);
+      } else {
+        const timeWatcher = () => {
+          if (video.currentTime > 0) {
+            resolve();
+          } else {
+            requestAnimationFrame(timeWatcher);
+          }
+        };
+        timeWatcher();
+      }
+      video.play().catch(reject);
+    });
+  }

另外,浏览器一般要求用户先交互才让播视频,所以得加个点击播放的按钮:

<body>
  <canvas></canvas>
  +
  <div id="start">
    +
    <div>▶️</div>
    +
  </div>
</body>
#start {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
#start > div {
  font-size: 200px;
  cursor: pointer;
}
+  function waitForClick() {
+    return new Promise(resolve => {
+      window.addEventListener(
+        'click',
+        () => {
+          document.querySelector('#start').style.display = 'none';
+          resolve();
+        },
+        { once: true });
+    });
+  }

再优化一下:只在视频有新帧时才更新纹理,别每个渲染帧都复制一遍视频数据:

  const video = document.createElement('video');
  video.muted = true;
  video.loop = true;
  video.preload = 'auto';
  video.src = 'resources/videos/Golden_retriever_swimming_the_doggy_paddle-360-no-audio.webm';
  await waitForClick();
  await startPlayingAndWaitForVideo(video);

+  let alwaysUpdateVideo = !('requestVideoFrameCallback' in video);
+  let haveNewVideoFrame = false;
+  if (!alwaysUpdateVideo) {
+    function recordHaveNewFrame() {
+      haveNewVideoFrame = true;
+      video.requestVideoFrameCallback(recordHaveNewFrame);
+    }
+    video.requestVideoFrameCallback(recordHaveNewFrame);
+  }

  ...

  function render() {
+    if (alwaysUpdateVideo || haveNewVideoFrame) {
+      haveNewVideoFrame = false;
      copySourceToTexture(device, texture, video);
    }

    ...

但这里得提一句:WebGPU 对视频有专门的高效支持。这篇用 copyExternalImageToTexture,其实多了一次拷贝。比如 4K 视频 3840×2160,rgba8unorm 下每帧要复制约 31MB。下一篇讲外部纹理,能直接拿视频数据用(零拷贝),只是方法和限制都不一样。

纹理图集(Texture Atlases)

同一个物体要好几张纹理的时候(比如椅子腿是木头、坐垫是布料),可以每个部分单独画,但 Draw Call 就多了。更常见的做法是上纹理图集:把多张图并到一张大纹理里,再用纹理坐标挑不同区域。

比如把 6 张图并成一张 4×2 的图集:

然后给立方体每个面设上对应图集区域的纹理坐标。顶点数据在下面(位置加纹理坐标):

function createCubeVertices() {
  const vertexData = new Float32Array([
    //  position   |  texture coordinate
    //-------------+----------------------
    // front face     select the top left image
    -1, 1, 1, 0, 0, -1, -1, 1, 0, 0.5, 1, 1, 1, 0.25, 0, 1, -1, 1, 0.25, 0.5,
    // right face     select the top middle image
    1, 1, -1, 0.25, 0, 1, 1, 1, 0.5, 0, 1, -1, -1, 0.25, 0.5, 1, -1, 1, 0.5,
    0.5,
    // back face      select to top right image
    1, 1, -1, 0.5, 0, 1, -1, -1, 0.5, 0.5, -1, 1, -1, 0.75, 0, -1, -1, -1, 0.75,
    0.5,
    // left face       select the bottom left image
    -1, 1, 1, 0, 0.5, -1, 1, -1, 0.25, 0.5, -1, -1, 1, 0, 1, -1, -1, -1, 0.25,
    1,
    // bottom face     select the bottom middle image
    1, -1, 1, 0.25, 0.5, -1, -1, 1, 0.5, 0.5, 1, -1, -1, 0.25, 1, -1, -1, -1,
    0.5, 1,
    // top face        select the bottom right image
    -1, 1, 1, 0.5, 0.5, 1, 1, 1, 0.75, 0.5, -1, 1, -1, 0.5, 1, 1, 1, -1, 0.75,
    1,
  ]);

  const indexData = new Uint16Array([
    0,
    1,
    2,
    2,
    1,
    3, // front
    4,
    5,
    6,
    6,
    5,
    7, // right
    8,
    9,
    10,
    10,
    9,
    11, // back
    12,
    13,
    14,
    14,
    13,
    15, // left
    16,
    17,
    18,
    18,
    17,
    19, // bottom
    20,
    21,
    22,
    22,
    21,
    23, // top
  ]);

  return {
    vertexData,
    indexData,
    numVertices: indexData.length,
  };
}

着色器跟之前的纹理示例几乎一样,只是把颜色属性换成纹理坐标:

struct Uniforms {
  matrix: mat4x4f,
};

struct Vertex {
  @location(0) position: vec4f,
-  @location(1) color: vec4f,
+  @location(1) texcoord: vec2f,
};

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

@group(0) @binding(0) `var<uniform>` uni: Uniforms;
+@group(0) @binding(1) var ourSampler: sampler;
+@group(0) @binding(2) var ourTexture: `texture_2d<f32>`;

@vertex fn vs(vert: Vertex) -> VSOutput {
  var vsOut: VSOutput;
  vsOut.position = uni.matrix * vert.position;
-  vsOut.color = vert.color;
+  vsOut.texcoord = vert.texcoord;
  return vsOut;
}

@fragment fn fs(vsOut: VSOutput) -> @location(0) vec4f {
-  return vsOut.color;
+  return textureSample(ourTexture, ourSampler, vsOut.texcoord);
}

管线配置里改顶点布局:

  const pipeline = device.createRenderPipeline({
    label: '2 attributes',
    layout: 'auto',
    vertex: {
      module,
      buffers: [
        {
-          arrayStride: (4) * 4, // (3) floats 4 bytes each + one 4 byte color
+          arrayStride: (3 + 2) * 4, // (3+2) floats 4 bytes each
          attributes: [
            {shaderLocation: 0, offset: 0, format: 'float32x3'},  // position
-            {shaderLocation: 1, offset: 12, format: 'unorm8x4'},  // color
+            {shaderLocation: 1, offset: 12, format: 'float32x2'},  // texcoord
          ],
        },
      ],
    },
    fragment: {
      module,
      targets: [{ format: presentationFormat }],
    },
    primitive: {
      cullMode: 'back',
    },
    depthStencil: {
      depthWriteEnabled: true,
      depthCompare: 'less',
      format: 'depth24plus',
    },
  });

建索引缓冲区,加载纹理图集:

-  const { vertexData, numVertices } = createFVertices();
+  const { vertexData, indexData, numVertices } = createCubeVertices();
  const vertexBuffer = device.createBuffer({
    label: 'vertex buffer vertices',
    size: vertexData.byteLength,
    usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
  });
  device.queue.writeBuffer(vertexBuffer, 0, vertexData);

+  const indexBuffer = device.createBuffer({
+    label: 'index buffer',
+    size: indexData.byteLength,
+    usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST,
+  });
+  device.queue.writeBuffer(indexBuffer, 0, indexData);

加载纹理,建采样器:

+  const texture = await createTextureFromImage(device,
+      'resources/images/noodles.jpg', {mips: true, flipY: false});
+
+  const sampler = device.createSampler({
+    magFilter: 'linear',
+    minFilter: 'linear',
+    mipmapFilter: 'linear',
+  });

  const bindGroup = device.createBindGroup({
    label: 'bind group for object',
    layout: pipeline.getBindGroupLayout(0),
    entries: [
      { binding: 0, resource: uniformBuffer },
+      { binding: 1, resource: sampler },
+      { binding: 2, resource: texture },
    ],
  });

渲染改成索引绘制:

    const encoder = device.createCommandEncoder();
    const pass = encoder.beginRenderPass(renderPassDescriptor);
    pass.setPipeline(pipeline);
    pass.setVertexBuffer(0, vertexBuffer);
+    pass.setIndexBuffer(indexBuffer, 'uint16');

    ...

    pass.setBindGroup(0, bindGroup);
-    pass.draw(numVertices);
+    pass.drawIndexed(numVertices);

    pass.end();

这样立方体每个面显示图集里不同的图,只用一张纹理、一次绘制。

好处很直白:只加载一张纹理,着色器也简单(只引用一张),整个形状一次 Draw Call 画完,不用一张纹理来一次。


关键的三点

在 GPU 上生成 mipmap。靠 GPU 的双线性插值(minFilter: linear)逐级生成 mip,不用绕去 canvas 2D getImageData 在 CPU 端做。这样又快,也躲开了 canvas 2D 渲染的精度损失和多余的内存拷贝。

用纹理图集减少 Draw Call 和纹理切换。把多张纹理并进一张图集(Texture Atlas),用纹理坐标选区域。这样几种材质能共用一次绘制,CPU 提交开销和纹理绑定的切换成本都明显降下来,材质多的模型(比如椅子、汽车)尤其划算。

视频纹理按帧驱动更新(顺带推荐外部纹理)。靠 requestVideoFrameCallback,只在视频有新帧时调 copyExternalImageToTexture,别每个渲染帧都把整段视频数据复制一遍。更好的方案是 WebGPU 的外部纹理(importExternalTexture),直接引用视频帧,零拷贝,4K 这种高分辨率视频很适合。


术语对照

这篇讲的是 WebGPU / WGSL,不是 GLSL / WebGL。术语这么处理(附中英对照):

  • mipmap / mip level:mipmap / mip 层级,保留英文常见用法。
  • sampler:采样器。
  • texture:纹理。
  • texture_2d:2D 纹理(WGSL 类型)。
  • bind group:绑定组。
  • render pass:渲染通道。
  • texture atlas:纹理图集。
  • copyExternalImageToTexture:WebGPU API 方法,保留原文。
  • GPUTextureUsage.COPY_DST / RENDER_ATTACHMENT:WebGPU 纹理用途标志,保留原文。
  • ImageBitmap / HTMLCanvasElement / HTMLVideoElement:浏览器 API,保留原文。

文中的 WGSL 着色器代码都是 WebGPU 标准写法,@builtin(position)、@location、textureSample 这类关键词没翻译,为的是技术准确。有 GLSL 背景的读者得注意,WGSL 语法跟它不一样,但概念(mipmap、采样器、纹理坐标)是通的。