Swizzling

Vector Swizzling and Component-Wise Operations

Swizzling reads components by xyzw or rgba names in any order (c.bgr, v.xxy). Arithmetic is component-wise, scalars apply to every component, and comparisons return vec<bool> for any(), all() and select():

Swizzles, swizzle assignment and component-wise math on BookNest blueJavaScript
// out: 8 x f32
@group(0) @binding(0) var<storage, read_write> out: array<f32>;
@compute @workgroup_size(1) fn main() {
  var c = vec4f(0.08, 0.40, 0.75, 1.0);          // BookNest blue
  let bgr = c.bgr;                                 // reordered copy
  let grey = dot(c.rgb, vec3f(0.299, 0.587, 0.114));
  c.rb = c.br;                                     // swizzle assignment swaps red and blue
  let lit = c.rgb * 1.5 + 0.1;                     // scalar applied to each component
  let bright = lit > vec3f(0.5);                   // vec3<bool>
  out[0] = bgr.x; out[1] = grey; out[2] = c.r; out[3] = c.b;
  out[4] = lit.x; out[5] = lit.z;
  out[6] = f32(any(bright)); out[7] = f32(all(bright));
}
Output
out: 0.75, 0.34422001242637634, 0.75, 0.07999999821186066, 1.225000023841858,
  0.2199999988079071, 1, 0

c.rb = c.br needs the swizzle_assignment extension (Chrome 154 1 has it); otherwise write c = c.bgra;. The name sets cannot mix: c.xg failed with "invalid mixing of vector swizzle characters rgba with xyzw". Nothing clamps lit.x (1.225) until an 8-bit render target stores it.

Swizzles and component-wise math on BookNest blue, as colour swatches painted by a fragment shaderHTMLLive
<!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="320"></canvas>
  <canvas id="labels" width="600" height="320"></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);
}
function label(text, x, y, size = 12, color = '#2b2b2b', font = 'system-ui, sans-serif') {
  ink.font = `${size}px ${font}`; ink.fillStyle = color; ink.textAlign = 'center'; ink.fillText(text, x, y);
}

// Six swatches, each a different swizzle or component-wise expression of one colour.
const code = /* wgsl */ `
@vertex fn vs(@builtin(vertex_index) v: u32) -> @builtin(position) vec4f {
  let p = array(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3))[v];
  return vec4f(p, 0, 1);
}
@fragment fn fs(@builtin(position) pos: vec4f) -> @location(0) vec4f {
  var c = vec4f(0.08, 0.40, 0.75, 1.0);            // BookNest blue
  let column = u32(pos.x / 100);
  let inside = pos.y > 40 && pos.y < 190 && fract(pos.x / 100) > 0.08 && fract(pos.x / 100) < 0.92;
  if (!inside) { return vec4f(0.97, 0.96, 0.93, 1); }
  let grey = dot(c.rgb, vec3f(0.299, 0.587, 0.114));
  let lit = c.rgb * 1.5 + 0.1;                     // scalar applied to each component
  switch column {
    case 0u: { return c; }
    case 1u: { return vec4f(c.bgr, 1); }            // reordered copy
    case 2u: { return vec4f(vec3f(grey), 1); }      // a scalar splatted to all three
    case 3u: { c = c.bgra; return c; }              // red and blue swapped (c.rb = c.br)
    case 4u: { return vec4f(lit, 1); }              // 1.225 is clamped only when stored
    default: { return vec4f(c.rrb * vec3f(1, 1, 0.6) + c.xxx, 1); }   // names repeat freely
  }
}`;

const lab = /* wgsl */ `
@group(0) @binding(0) var<storage, read_write> out: array<f32>;
@compute @workgroup_size(1) fn main() {
  var c = vec4f(0.08, 0.40, 0.75, 1.0);
  let bgr = c.bgr;
  let grey = dot(c.rgb, vec3f(0.299, 0.587, 0.114));
  c = c.bgra;                                      // or c.rb = c.br with swizzle_assignment
  let lit = c.rgb * 1.5 + 0.1;
  let bright = lit > vec3f(0.5);                   // vec3<bool>
  out[0] = bgr.x; out[1] = grey; out[2] = c.r; out[3] = c.b;
  out[4] = lit.x; out[5] = lit.z;       // lit.x = 1.225: nothing clamps it here
  out[6] = f32(any(bright)); out[7] = f32(all(bright));
}`;

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

  const module = device.createShaderModule({ code });
  const render = device.createRenderPipeline({ layout: 'auto', vertex: { module }, fragment: { module, targets: [{ format }] } });
  const B = GPUBufferUsage;
  const out = device.createBuffer({ size: 32, usage: B.STORAGE | B.COPY_SRC });
  const read = device.createBuffer({ size: 32, usage: B.COPY_DST | B.MAP_READ });
  const compute = device.createComputePipeline({ layout: 'auto', compute: { module: device.createShaderModule({ code: lab }) } });

  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(render);
  pass.draw(3);
  pass.end();
  const cp = encoder.beginComputePass();
  cp.setPipeline(compute);
  cp.setBindGroup(0, device.createBindGroup({ layout: compute.getBindGroupLayout(0), entries: [{ binding: 0, resource: { buffer: out } }] }));
  cp.dispatchWorkgroups(1);
  cp.end();
  encoder.copyBufferToBuffer(out, 0, read, 0, 32);
  device.queue.submit([encoder.finish()]);
  await read.mapAsync(GPUMapMode.READ);
  const v = [...new Float32Array(read.getMappedRange())].map((x) => +x.toFixed(4));
  read.unmap();

  ['c', 'c.bgr', 'vec3f(grey)', 'c.bgra', 'c.rgb*1.5+0.1', 'c.rrb, c.xxx'].forEach((t, i) =>
    label(t, 50 + i * 100, 210, 11.5, '#222', 'ui-monospace, monospace'));
  label('Compute lab, same expressions:', 300, 248, 12.5, '#444');
  label(`bgr.x = ${v[0]}   grey = ${v[1]}   swapped c.r = ${v[2]}, c.b = ${v[3]}`, 300, 270, 12, '#1f4f8a', 'ui-monospace, monospace');
  label(`after the swap: lit.x = ${v[4]} (not clamped), lit.z = ${v[5]}, any = ${v[6]}, all = ${v[7]}`, 300, 290, 12, '#1f4f8a', 'ui-monospace, monospace');
  label('Mixing name sets (c.xg) is a compile error: rgba and xyzw cannot share one swizzle.', 300, 312, 11.5, '#8a2b2b');
}
main();
</script>