Mipmap Blits

Generating Mipmaps with a Render-Pipeline Blit

The portable method draws each level from the one above it. A render pass targets a view of level n (one level, one layer), a bind group samples a view of level n - 1, and a full-screen triangle with a linear sampler averages each 2 x 2 block of texels. Reading one level of a texture while writing another in the same pass is legal, because WebGPU tracks usage per subresource. This file, loaded with a classic <script> tag, is the chapter's generator:

demos/ch04/mipmaps.js: a render-pass mipmap generator for 2D and 2D-array texturesJavaScript
// mipmaps.js: generateMipmaps(device, texture) fills mip levels 1..n-1 of a 2D or 2D-array
// texture, drawing each level from the one above it through a linear filter (Section 4.13.2).
// The texture needs TEXTURE_BINDING and RENDER_ATTACHMENT usage and a filterable format.
const mipPipelines = new Map();                        // one pipeline per texture format
function generateMipmaps(device, texture) {
  let pipeline = mipPipelines.get(texture.format);
  if (!pipeline) {
    const module = device.createShaderModule({ code: /* wgsl */ `
      struct Out { @builtin(position) pos: vec4f, @location(0) uv: vec2f }
      @vertex fn vs(@builtin(vertex_index) v: u32) -> Out {
        let p = array(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3))[v];   // covers the target
        return Out(vec4f(p, 0, 1), vec2f(p.x + 1, 1 - p.y) / 2);
      }
      @group(0) @binding(0) var above: texture_2d<f32>;
      @group(0) @binding(1) var smp: sampler;
      @fragment fn fs(in: Out) -> @location(0) vec4f {
        return textureSample(above, smp, in.uv);         // a 2 x 2 average at even sizes
      }` });
    pipeline = device.createRenderPipeline({ layout: 'auto', vertex: { module },
      fragment: { module, targets: [{ format: texture.format }] } });
    mipPipelines.set(texture.format, pipeline);
  }
  const sampler = device.createSampler({ minFilter: 'linear', magFilter: 'linear' });
  const view = (level, layer) => texture.createView({ dimension: '2d',
    baseMipLevel: level, mipLevelCount: 1, baseArrayLayer: layer, arrayLayerCount: 1 });
  const encoder = device.createCommandEncoder();
  for (let layer = 0; layer < texture.depthOrArrayLayers; layer++) {
    for (let level = 1; level < texture.mipLevelCount; level++) {
      const pass = encoder.beginRenderPass({ colorAttachments: [{ view: view(level, layer),
        loadOp: 'clear', storeOp: 'store' }] });
      pass.setPipeline(pipeline);
      pass.setBindGroup(0, device.createBindGroup({ layout: pipeline.getBindGroupLayout(0),
        entries: [{ binding: 0, resource: view(level - 1, layer) },   // read the level above
                  { binding: 1, resource: sampler }] }));
      pass.draw(3);                                    // one oversized triangle
      pass.end();
    }
  }
  device.queue.submit([encoder.finish()]);
}

The texture needs RENDER_ATTACHMENT and a filterable, renderable format (rgba8unorm, rgba8unorm-srgb, rgba16float and friends; an -srgb format averages in linear light, which is the correct way). For odd sizes the 2 x 2 average skips texels: the 1 x 1 level of Gardens in Glass came out (40, 128, 119), against a true mean of (53, 129, 121), because the last step samples the middle of three texels. A compute version writes each level through a storage texture and can reduce odd sizes exactly, or build several levels per dispatch with workgroup memory; it needs a storage-capable format, so rgba8unorm-srgb must go through a render pass.

generateMipmaps() fills every level of a cover texture by drawing each from the one above, shown level by levelHTMLLive
<!doctype html>
<style>
  body { margin: 0; background: #f7f4ee; font: 14px system-ui, sans-serif; }
  .stage { position: relative; width: 100%; max-width: 600px; }
  .stage canvas { display: block; width: 100%; }
  .stage canvas + canvas { position: absolute; inset: 0; pointer-events: none; }
</style>
<div class="stage">
  <canvas id="view" width="600" height="330"></canvas>
  <canvas id="labels" width="600" height="330"></canvas>
</div>
<script>
const canvas = document.getElementById('view');
const ink = document.getElementById('labels').getContext('2d');

function showMessage(text) {                     // 2D fallback when WebGPU is missing
  const ctx = canvas.getContext('2d');
  ctx.fillStyle = '#fbeaea'; ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = '#8a2b2b'; ctx.font = '18px system-ui, sans-serif'; ctx.textAlign = 'center';
  ctx.fillText(text, canvas.width / 2, canvas.height / 2);
}

// generateMipmaps(device, texture) fills mip levels 1..n-1 of a 2D or 2D-array texture,
// drawing each level from the one above it through a linear filter.
const mipPipelines = new Map();                        // one pipeline per texture format
function generateMipmaps(device, texture) {
  let pipeline = mipPipelines.get(texture.format);
  if (!pipeline) {
    const module = device.createShaderModule({ code: /* wgsl */ `
      struct Out { @builtin(position) pos: vec4f, @location(0) uv: vec2f }
      @vertex fn vs(@builtin(vertex_index) v: u32) -> Out {
        let p = array(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3))[v];   // covers the target
        return Out(vec4f(p, 0, 1), vec2f(p.x + 1, 1 - p.y) / 2);
      }
      @group(0) @binding(0) var above: texture_2d<f32>;
      @group(0) @binding(1) var smp: sampler;
      @fragment fn fs(in: Out) -> @location(0) vec4f {
        return textureSample(above, smp, in.uv);         // a 2 x 2 average at even sizes
      }` });
    pipeline = device.createRenderPipeline({ layout: 'auto', vertex: { module },
      fragment: { module, targets: [{ format: texture.format }] } });
    mipPipelines.set(texture.format, pipeline);
  }
  const sampler = device.createSampler({ minFilter: 'linear', magFilter: 'linear' });
  const view = (level, layer) => texture.createView({ dimension: '2d',
    baseMipLevel: level, mipLevelCount: 1, baseArrayLayer: layer, arrayLayerCount: 1 });
  const encoder = device.createCommandEncoder();
  for (let layer = 0; layer < texture.depthOrArrayLayers; layer++) {
    for (let level = 1; level < texture.mipLevelCount; level++) {
      const pass = encoder.beginRenderPass({ colorAttachments: [{ view: view(level, layer),
        loadOp: 'clear', storeOp: 'store' }] });
      pass.setPipeline(pipeline);
      pass.setBindGroup(0, device.createBindGroup({ layout: pipeline.getBindGroupLayout(0),
        entries: [{ binding: 0, resource: view(level - 1, layer) },   // read the level above
                  { binding: 1, resource: sampler }] }));
      pass.draw(3);                                    // one oversized triangle
      pass.end();
    }
  }
  device.queue.submit([encoder.finish()]);
}

// Shows one mip level of the cover at its real size, texel for texel.
const show = /* wgsl */ `
@group(0) @binding(0) var level: texture_2d<f32>;
@group(0) @binding(1) var smp: sampler;
struct Out { @builtin(position) pos: vec4f, @location(0) uv: vec2f }
@vertex fn vs(@builtin(vertex_index) v: u32) -> Out {
  let q = vec2f(f32(v & 1), f32(v >> 1));
  return Out(vec4f(q * 2 - 1, 0, 1), vec2f(q.x, 1 - q.y));
}
@fragment fn fs(in: Out) -> @location(0) vec4f { return textureSample(level, smp, in.uv); }`;

async function main() {
  const adapter = await navigator.gpu?.requestAdapter();
  if (!adapter) return showMessage('WebGPU is not available in this browser');
  const device = await adapter.requestDevice();
  const context = canvas.getContext('webgpu');
  const format = navigator.gpu.getPreferredCanvasFormat();
  context.configure({ device, format });

  // A 256 x 384 cover painted with the 2D API: floor(log2(384)) + 1 = 9 levels.
  const art = new OffscreenCanvas(256, 384), g = art.getContext('2d');
  g.fillStyle = '#1f5f8b'; g.fillRect(0, 0, 256, 384);
  g.fillStyle = '#f5ecd7'; g.fillRect(0, 120, 256, 110);
  g.fillStyle = '#16384f'; g.font = 'bold 34px Georgia, serif'; g.textAlign = 'center';
  g.fillText('The Quiet', 128, 168); g.fillText('Harbor', 128, 208);
  g.fillStyle = '#f5ecd7'; g.font = '22px Georgia, serif'; g.fillText('A. Marlowe', 128, 330);
  for (let k = 0; k < 6; k++) { g.fillStyle = 'rgba(255,255,255,0.25)'; g.fillRect(20 + k * 38, 40, 18, 50); }
  const texture = device.createTexture({ size: [256, 384], mipLevelCount: 9, format: 'rgba8unorm',
    usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT });
  device.queue.copyExternalImageToTexture({ source: art }, { texture }, [256, 384]);
  generateMipmaps(device, texture);

  const module = device.createShaderModule({ code: show });
  const pipeline = device.createRenderPipeline({ layout: 'auto', primitive: { topology: 'triangle-strip' },
    vertex: { module }, fragment: { module, targets: [{ format }] } });
  const nearest = device.createSampler();
  const encoder = device.createCommandEncoder();
  const pass = encoder.beginRenderPass({ colorAttachments: [{ view: context.getCurrentTexture().createView(),
    clearValue: [0.97, 0.96, 0.93, 1], loadOp: 'clear', storeOp: 'store' }] });
  pass.setPipeline(pipeline);
  let x = 10;
  ink.font = '10.5px system-ui, sans-serif'; ink.fillStyle = '#333';
  for (let level = 0; level < 9; level++) {
    const w = Math.max(256 >> level, 1), h = Math.max(384 >> level, 1);
    const scale = level === 0 ? 0.6 : 1;              // level 0 shrunk to fit the row
    pass.setViewport(x, 40, w * scale, h * scale, 0, 1);
    pass.setBindGroup(0, device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [
      { binding: 0, resource: texture.createView({ baseMipLevel: level, mipLevelCount: 1 }) }, { binding: 1, resource: nearest }] }));
    pass.draw(4);
    ink.fillText(`L${level}`, x, 34);
    if (level > 1 && level < 6) ink.fillText(`${w}x${h}`, x, 40 + h + 14);
    x += w * scale + 10;
  }
  pass.end();
  device.queue.submit([encoder.finish()]);

  ink.fillStyle = '#222'; ink.font = '12px system-ui, sans-serif';
  ink.fillText('Level 0 (256 x 384) shown at 60%; levels 1 to 8 at their real size.', 10, 16);
  ink.fillText('8 render passes: each targets one level view and samples the level above with a linear filter.', 10, 318);
}
main();
</script>