v146 · Web APIs · WGSL Syntax

WGSL Syntax

Before and after WGSL patterns for textures and samplers — the restricted module-scope-only approach vs the new let variable and function-parameter patterns in Chrome 146.

basic sampling

Before Chrome 146

@group(0) @binding(0)
var myTex: texture_2d<f32>;
@group(0) @binding(1)
var mySampler: sampler;

@fragment fn fs(
  @location(0) uv: vec2f
) -> @location(0) vec4f {
  // Must reference module-level
  // names directly in every call
  return textureSample(
    myTex, mySampler, uv
  );
}

Chrome 146+

@group(0) @binding(0)
var myTex: texture_2d<f32>;
@group(0) @binding(1)
var mySampler: sampler;

@fragment fn fs(
  @location(0) uv: vec2f
) -> @location(0) vec4f {
  // Local let aliases
  let t = myTex;
  let s = mySampler;
  return textureSample(t, s, uv);
}

reusable helper function

// Chrome 146+: pass texture/sampler as function parameters
@group(0) @binding(0) var albedoTex: texture_2d<f32>;
@group(0) @binding(1) var normalTex: texture_2d<f32>;
@group(0) @binding(2) var linearSampler: sampler;

// Helper that works with any texture
fn sampleLinear(
  tex: texture_2d<f32>,
  smp: sampler,
  uv: vec2f,
  mip: f32
) -> vec4f {
  return textureSampleLevel(tex, smp, uv, mip);
}

@fragment fn fs(@location(0) uv: vec2f) -> @location(0) vec4f {
  let albedo = sampleLinear(albedoTex, linearSampler, uv, 0.0);
  let normal = sampleLinear(normalTex, linearSampler, uv, 0.0);
  return albedo * dot(normal.xyz, vec3f(0, 0, 1));
}

limitations

// Texture lets can alias, but cannot be reassigned
let t = myTex;
// t = otherTex;  // ✗ error — let is immutable

// Texture lets can be passed by value to functions
// (textures are handles, not copied data — always fine)
let s = mySampler;
let colour = helper(t, s, uv);

// Cannot store in arrays or structs (spec restriction)
// var textures = array<texture_2d<f32>, 2>(myTex, myTex2);
// ✗ Not allowed

see also

scenario focus

Select a scenario to focus its rendered example and summary.