From 0 to glTF with WebGPU: Basic Materials and Textures

https://www.willusher.io/graphics/2024/04/28/0-to-gltf-basic-materials
Figure 1: The happy duck we’ll be able to render at the end of this post

Now that we can load up complex scene hierarchies from glTF files and render them correctly, let’s start getting some more interesting colors on screen! glTF defines a physically based BRDF, with support for metallic and roughness properties, along with normal, emission and occlusion texture maps. There are a number of extensions on top of this basic material model (the KHR_materials_* extensions) that add even more advanced material definitions.

We’ll keep it simple to start. Today we’re going to take the first step of loading the base glTF material parameters and textures from the glB file and passing them to our shader. In the shader we’ll color the object by its base color properties, without applying any lighting or material model yet.

Code Changes from the Previous Post

If you’re following along from the previous lesson’s code, I’ve made a few cleanups while writing this lesson to make it easier to keep growing the lesson’s codebase:

  • Split up the different GLTF* classes into separate files instead of having it all in import_glb.ts
  • Split up the JSON importing work in uploadGLB to a few separate functions that load each individual part: loadBufferViews, loadAccessors, loadMeshes

I’ve also stopped writing the JavaScript versions of these posts, the rest of the series will be in TypeScript only. The full code for this post can be found on Github.

Loading glTF Images, Samplers and Textures

Each texture in the glTF file references an image and, optionally, a sampler. The image defines the data for the texture, while the sampler defines the way that texture coordinates should be looked up within the image and how texels should be interpolated. The texture references the image and sampler by their index in the corresponding image and sampler array, similar to how accessors reference buffer views.

The texture array from Duck.glb is shown below. We have a single texture, which uses sampler 0 and image (source) 0:

"textures": [
  {
    "sampler": 0,
    "source": 0
  }
]

The glTF images elements can either reference a file by URI, or a buffer view that contains the texture data. Since we’re only loading glB files in this series, we would expect to always have the texture data embedded in the file and will assume we always have a buffer view like below. The image specifies the buffer view containing its data, and the type of data within that buffer view. In this case, it’s a PNG.

"images": [
  {
    "bufferView": 3,
    "mimeType": "image/png"
  }
]

Note that it’s not required that all images in a glB file use buffer views for their data, for example I could have a glB file with lower resolution textures that can be downloaded quickly, that references higher resolution textures by URL that I can fetch asynchronously. We won’t be dealing with these kinds of files in this series though.

Finally, the glTF samplers specify how we should lookup and interpolate texels in the image when rendering. These parameters map directly to the WebGL/OpenGL glTexParameter parameter values. The mag/min filter parameters define the texture filtering under magnification and minification, respectively, by directly specifying the OpenGL enum parameter value. Similarly, wrapS and wrapT specify the texture wrapping mode to be used for samples out of the texture bounds.

"samplers": [
  {
    "magFilter": 9729,
    "minFilter": 9986,
    "wrapS": 10497,
    "wrapT": 10497
  }
]

We’ll load the data “bottom-up” by first loading the image and sampler data, then loading the texture data. That way we have objects representing the images and samplers that the textures can share.

Parsing Samplers into GLTFSamplers

The samplers are simple enough to load, we’ll start by defining some enums that store the glTF sampler parameter values so we don’t need to just remember some magic numbers.

export enum GLTFTextureFilter {
  NEAREST = 9728,
  LINEAR = 9729,
  NEAREST_MIPMAP_NEAREST = 9984,
  LINEAR_MIPMAP_NEAREST = 9985,
  NEAREST_MIPMAP_LINEAR = 9986,
  LINEAR_MIPMAP_LINEAR = 9987,
}

export enum GLTFTextureWrap {
  REPEAT = 10497,
  CLAMP_TO_EDGE = 33071,
  MIRRORED_REPEAT = 33648,
}

Along with some utility functions to get the corresponding WebGPU GPUFilterMode, GPUMipMapFilterMode, and GPUAddressMode from the GLTF enums:

export function gltfTextureFilterMode(filter: GLTFTextureFilter) {
  switch (filter) {
    case GLTFTextureFilter.NEAREST_MIPMAP_NEAREST:
    case GLTFTextureFilter.NEAREST_MIPMAP_LINEAR:
    case GLTFTextureFilter.NEAREST:
      return "nearest" as GPUFilterMode;
    case GLTFTextureFilter.LINEAR_MIPMAP_NEAREST:
    case GLTFTextureFilter.LINEAR_MIPMAP_LINEAR:
    case GLTFTextureFilter.LINEAR:
      return "linear" as GPUFilterMode;
  }
}

export function gltfTextureMipMapMode(filter: GLTFTextureFilter) {
  switch (filter) {
    case GLTFTextureFilter.NEAREST_MIPMAP_NEAREST:
    case GLTFTextureFilter.LINEAR_MIPMAP_NEAREST:
    case GLTFTextureFilter.NEAREST:
      return "nearest" as GPUMipmapFilterMode;
    case GLTFTextureFilter.LINEAR_MIPMAP_LINEAR:
    case GLTFTextureFilter.NEAREST_MIPMAP_LINEAR:
    case GLTFTextureFilter.LINEAR:
      return "linear" as GPUMipmapFilterMode;
  }
}

export function gltfAddressMode(mode: GLTFTextureWrap) {
  switch (mode) {
    case GLTFTextureWrap.REPEAT:
      return "repeat" as GPUAddressMode;
    case GLTFTextureWrap.CLAMP_TO_EDGE:
      return "clamp-to-edge" as GPUAddressMode;
    case GLTFTextureWrap.MIRRORED_REPEAT:
      return "mirror-repeat" as GPUAddressMode;
  }
}

We can now define a GLTFSampler class which will take these GLTF sampler parameters and convert them to their WebGPU equivalents, although for now we’re ignoring mip maps. The class also provides a create method that will create the actual GPUSampler object with the specified sampler parameters. The GPUSampler is what we will pass to our shaders later on to use when sampling the texture.

export class GLTFSampler {
  magFilter: GPUFilterMode = "linear";
  minFilter: GPUFilterMode = "linear";

  wrapU: GPUAddressMode = "repeat";
  wrapV: GPUAddressMode = "repeat";

  sampler: GPUSampler = null;

  constructor(
    magFilter: GLTFTextureFilter,
    minFilter: GLTFTextureFilter,
    wrapU: GLTFTextureWrap,
    wrapV: GLTFTextureWrap
  ) {
    this.magFilter = gltfTextureFilterMode(magFilter);
    this.minFilter = gltfTextureFilterMode(minFilter);

    this.wrapU = gltfAddressMode(wrapU);
    this.wrapV = gltfAddressMode(wrapV);
  }

  // Create the GPU sampler
  create(device: GPUDevice) {
    this.sampler = device.createSampler({
      magFilter: this.magFilter,
      minFilter: this.minFilter,
      addressModeU: this.wrapU,
      addressModeV: this.wrapV,
      mipmapFilter: "nearest",
    });
  }
}

All that’s left to do is add a function in import_glb.ts that takes the JSON chunk and loads up any samplers within it and returns them. We have to handle the case that there are no samplers in the file, the file can omit samplers even if it has textures.

function loadSamplers(jsonChunk: any) {
  let samplers = [];
  if (!jsonChunk.samplers) {
    return [];
  }

  for (let s of jsonChunk.samplers) {
    samplers.push(
      new GLTFSampler(
        s["magFilter"] as GLTFTextureFilter,
        s["minFilter"] as GLTFTextureFilter,
        s["wrapS"] as GLTFTextureWrap,
        s["wrapT"] as GLTFTextureWrap
      )
    );
  }
  return samplers;
}

Loading Images into GLTFImages

Next, we need to load the image data out of the glB file by going through the images in the file, getting the data each of their buffer view’s references and turning it into an ImageBitmap that we can upload to the GPU.

We’ll actually start by defining an enum that we’ll need later, ImageUsage, which records how an image is being used by materials in the scene. Images in a glTF file can be used in a number of material inputs:

  • Base Color: the texture contains sRGB color data
  • Metallic + Roughness: the blue channel stores the metalness values, the green channel stores roughness. Texture values are in linear space
  • Normal: the texture stores tangent-space normal, with RGB = XYZ. Texture values are in linear space
  • Occlusion: the R channel of the texture stores occlusion values. Texture values are in linear space
  • Emission: the texture contains sRGB emission values

In order to pick the right texture format, rgba8unorm-srgb or rgba8unorm, we need to know how a texture is used in the materials referencing it.

export enum ImageUsage {
  BASE_COLOR,
  METALLIC_ROUGHNESS,
  NORMAL,
  OCCLUSION,
  EMISSION,
}

Now let’s define our GLTFImage class. It will take an ImageBitmap, track its usage, and let us upload it to the GPU to produce a GPUTexture and GPUTextureView that we can pass to our shaders. Most of the work happens in GPUTexture::upload. Here we actually upload the ImageBitmap to a texture on the GPU using copyExternalImageToTexture . It’s worth noting that this code assumes each image will only have one usage, i.e., that an image used as a base color texture won’t also be used as a normal texture. This is likely a safe assumption, but if this is not the case in some interesting files, we could support creating an sRGB and non-sRGB texture view and the material can get the appropriate view for its usage.

// Stores the image data texture for an image in the file
export class GLTFImage {
  bitmap: ImageBitmap;

  // How the texture is used in the materials
  // referencing it
  usage: ImageUsage = ImageUsage.BASE_COLOR;

  image: GPUTexture = null;
  view: GPUTextureView = null;

  constructor(bitmap: ImageBitmap) {
    this.bitmap = bitmap;
  }

  // Set the usage mode for the image
  setUsage(usage: ImageUsage) {
    this.usage = usage;
  }

  // Upload the image to the GPU and create the view
  upload(device: GPUDevice) {
    // Pick the right texture format to use based on the
    // image's usage
    let format: GPUTextureFormat = "rgba8unorm-srgb";
    switch (this.usage) {
      case ImageUsage.BASE_COLOR:
        format = "rgba8unorm-srgb";
        break;
      case ImageUsage.METALLIC_ROUGHNESS:
        format = "rgba8unorm";
        break;
      case ImageUsage.NORMAL:
      case ImageUsage.OCCLUSION:
      case ImageUsage.EMISSION:
        throw new Error("Unhandled image format for now, TODO!");
    }

    const imgSize = [this.bitmap.width, this.bitmap.height, 1];
    this.image = device.createTexture({
      size: imgSize,
      format: format,
      // Note: the render attachment usage is required for
      // copyExternalImageToTexture we aren't going to actually
      // render to these images ourselves
      usage:
        GPUTextureUsage.TEXTURE_BINDING |
        GPUTextureUsage.COPY_DST |
        GPUTextureUsage.RENDER_ATTACHMENT,
    });

    device.queue.copyExternalImageToTexture(
      { source: this.bitmap },
      { texture: this.image },
      imgSize
    );

    this.view = this.image.createView();
  }
}

With the GLTFImage implemented, we can now write a function to load all the images in the glTF file into GLTFImages for use later on. To create an image bitmap from the binary data referenced by the GLTFBufferView we first create a Blob from the view and specify the mimeType. We can then pass the Blob to createImageBitmap to create an ImageBitmap that we can pass to copyExternalImageToTexture.

async function loadImages(jsonChunk: any, bufferViews: GLTFBufferView[]) {
  let images: GLTFImage[] = [];
  if (!jsonChunk.images) {
    return images;
  }
  for (let img of jsonChunk.images) {
    const bv = bufferViews[img["bufferView"]];
    const blob = new Blob([bv.view], { type: img["mimeType"] });
    const bitmap = await createImageBitmap(blob);
    images.push(new GLTFImage(bitmap));
  }
  return images;
}

Loading the GLTFTextures

All the hard work is done by the GLTFSampler and GLTFImage, the GLTFTexture just references a sampler and image source to combine them. Since the GLTFTexture is what’s going to be stored by the material, it’s convenient to implement setUsage on it as well to simply pass the usage flag through to the referenced image.

export class GLTFTexture {
  sampler: GLTFSampler;
  image: GLTFImage;

  constructor(sampler: GLTFSampler, image: GLTFImage) {
    this.sampler = sampler;
    this.image = image;
  }

  // Set the texture's image usage flag
  setUsage(usage: ImageUsage) {
    this.image.setUsage(usage);
  }
}

Loading the textures from the glTF file is similarly simple, with one caveat. It’s valid to not specify a sampler at all! In this case, the importer is expected to use an appropriate default filtering mode and repeat addressing. We handle this by creating a default sampler to use if no sampler was referenced and adding it to the samplers list if it was used so that we can create it on the device later on.

function loadTextures(
  jsonChunk: any,
  images: GLTFImage[],
  samplers: GLTFSampler[]
) {
  let textures: GLTFTexture[] = [];
  if (!jsonChunk.textures) {
    return textures;
  }
  const defaultSampler = new GLTFSampler(
    GLTFTextureFilter.LINEAR,
    GLTFTextureFilter.LINEAR,
    GLTFTextureWrap.REPEAT,
    GLTFTextureWrap.REPEAT
  );
  let usedDefaultSampler = false;

  for (let t of jsonChunk.textures) {
    let sampler = null;
    if ("sampler" in t) {
      sampler = samplers[t["sampler"]];
    } else {
      // If no sampler was specified, use the default
      sampler = defaultSampler;
      usedDefaultSampler = true;
    }
    textures.push(new GLTFTexture(sampler, images[t["source"]]));
  }
  // If we used the default sampler add it to the samplers list so its
  // GPU resources will be created
  if (usedDefaultSampler) {
    samplers.push(defaultSampler);
  }
  return textures;
}

Loading GLTFMaterials

Materials in glTF specify the PBR model parameters and textures, as shown below for the Duck. Here we have a base color texture reference, along with metallic and emissive factors.

"materials": [
  {
    "pbrMetallicRoughness":
    {
      "baseColorTexture": {"index": 0},
      "metallicFactor": 0.0
    },
    "emissiveFactor": [0.0, 0.0, 0.0]
  }
]

We’ll represent these with the GLTFMaterial class, shown below. When provided textures, the material class will mark them with their corresponding usage in the material. The GLTFMaterial::upload method will upload the baseColorFactor, metallicFactor and roughnessFactor parameters to a uniform buffer and create a bind group referencing the material parameters (uniform buffer and any relevant textures). This is omitted for brevity, but can be found on Github.

export class GLTFMaterial {
  baseColorFactor: vec4 = [1, 1, 1, 1];
  baseColorTexture: GLTFTexture | null = null;

  metallicFactor: number = 1;
  roughnessFactor: number = 1;
  metallicRoughnessTexture: GLTFTexture | null = null;

  // Uniform buffer holding the material factor params
  paramBuffer: GPUBuffer = null;

  // Bind group layout and bind groups for the material parameters
  bindGroupLayout: GPUBindGroupLayout = null;
  bindGroup: GPUBindGroup = null;

  constructor(
    baseColorFactor: vec4,
    baseColorTexture: GLTFTexture | null,
    metallicFactor: number,
    roughnessFactor: number,
    metallicRoughnessTexture: GLTFTexture | null
  ) {
    this.baseColorFactor = baseColorFactor;
    this.baseColorTexture = baseColorTexture;
    if (this.baseColorTexture) {
      this.baseColorTexture.setUsage(ImageUsage.BASE_COLOR);
    }

    this.metallicFactor = metallicFactor;
    this.roughnessFactor = roughnessFactor;
    this.metallicRoughnessTexture = metallicRoughnessTexture;
    if (this.metallicRoughnessTexture) {
      this.metallicRoughnessTexture.setUsage(ImageUsage.METALLIC_ROUGHNESS);
    }
  }

  // Upload params buffer and create the bind group and bind group layout
  // for the material params
  upload(device: GPUDevice) {
    // See github...
  }
}

We’ll load the materials from the file by adding a new loadMaterials function, that goes through any materials in the file and constructs the corresponding GLTFMaterial. If any values are missing from the material we apply the default value from the spec.

function loadMaterials(jsonChunk: any, textures: GLTFTexture[]) {
  let materials = [];
  for (let m of jsonChunk.materials) {
    const pbrMR = m["pbrMetallicRoughness"];
    // Default base color factor of 1, 1, 1
    const baseColorFactor = pbrMR["baseColorFactor"] ?? [1, 1, 1, 1];
    const metallicFactor = pbrMR["metallicFactor"] ?? 1;
    const roughnessFactor = pbrMR["roughnessFactor"] ?? 1;

    let baseColorTexture: GLTFTexture | null = null;
    if ("baseColorTexture" in pbrMR) {
      baseColorTexture = textures[pbrMR["baseColorTexture"]["index"]];
    }
    let metallicRoughnessTexture: GLTFTexture | null = null;
    if ("metallicRoughnessTexture" in pbrMR) {
      metallicRoughnessTexture =
        textures[pbrMR["metallicRoughnessTexture"]["index"]];
    }
    materials.push(
      new GLTFMaterial(
        baseColorFactor,
        baseColorTexture,
        metallicFactor,
        roughnessFactor,
        metallicRoughnessTexture
      )
    );
  }
  return materials;
}

Loading and Using Materials for Primitives

When we were loading primitives before, we skipped the “material” field that each primitive has. Now it’s time to come back and load it. Since we’re applying textures, we also will start loading the TEXCOORDS_0 attribute that can also be specified on a primitive. The mesh loading code has been split out to loadMeshes as part of the code organization cleanup from the previous step. This function will now also take the GLTFMaterial[] array so that we can pass the corresponding material to each primitive when it’s created. We’ll also modify the GLTFPrimitive constructor to take a GLTFMaterial as a parameter and store it as a member variable.

function loadMeshes(
  jsonChunk: any,
  accessors: GLTFAccessor[],
  materials: GLTFMaterial[]
) {
  let meshes = [];
  for (let mesh of jsonChunk.meshes) {
    let meshPrimitives = [];
    for (let prim of mesh.primitives) {
      // Get topology and indices as before...

      // Get the positions and the texture coordinates
      let positions = null;
      let texcoords = null;
      for (let attr in prim["attributes"]) {
        let accessor = accessors[prim["attributes"][attr]];
        if (attr === "POSITION") {
          positions = accessor;
        } else if (attr === "TEXCOORD_0") {
          texcoords = accessor;
        }
      }

      // Lookup the material for the primitive
      let mat = materials[prim["material"]];

      // Add the primitive to the mesh's list of primitives
      meshPrimitives.push(
        new GLTFPrimitive(mat, positions, indices, texcoords, topology)
      );
    }
    meshes.push(new GLTFMesh(mesh["name"], meshPrimitives));
  }
  return meshes;
}

Updating GLTFPrimitive buildRenderPipeline

Our GLTFPrimitive gets two additions in buildRenderPipeline :

  • Adding the texture coordinates attribute, if it has texture coordinates
  • Adding the material bind group layout to its render pipeline’s bind group layouts

Our vertexState will now be built as shown below. We add the position attribute buffer as before, and now, if we have texture coordinates, we add the texture coordinates vertex buffer as well.

let vertexBuffers: GPUVertexBufferLayout[] = [
  {
    arrayStride: this.positions.byteStride,
    attributes: [
      {
        format: this.positions.elementType as GPUVertexFormat,
        offset: 0,
        shaderLocation: 0,
      },
    ],
  },
];
if (this.texcoords) {
  vertexBuffers.push({
    arrayStride: this.texcoords.byteStride,
    attributes: [
      {
        format: this.texcoords.elementType as GPUVertexFormat,
        offset: 0,
        shaderLocation: 1,
      },
    ],
  });
}

// Vertex attribute state and shader stage
let vertexState = {
  // Shader stage info
  module: shaderModule,
  entryPoint: "vertex_main",
  // Vertex buffer info
  buffers: vertexBuffers,
};

We’ll also now add the primitive’s material bind group layout to its pipeline:

// Add the material bind group layout
bindGroupLayouts.push(this.material.bindGroupLayout);

let layout = device.createPipelineLayout({
  bindGroupLayouts: bindGroupLayouts,
});

Updating uploadGLB

We can now add calls to our loader functions in uploadGLB . We start by loading all the buffer views, and accessors, after which we get the images, samplers, textures and materials. Finally we can load the meshes. Once all the data has been loaded from the file we know what usage our GPU objects have and can upload them.

// Load the buffer views
const bufferViews = loadBufferViews(jsonChunk, binaryChunk);
// Load the GLTF accessors
const accessors = loadAccessors(jsonChunk, bufferViews);
// Load and decode all the images in the file
const images = await loadImages(jsonChunk, bufferViews);
// Load all the samplers in the file
const samplers = loadSamplers(jsonChunk);
// Load all the textures, which just combine a sampler + image
const textures = loadTextures(jsonChunk, images, samplers);
// Load all the materials
const materials = loadMaterials(jsonChunk, textures);
// Load all meshes
const meshes = loadMeshes(jsonChunk, accessors, materials);

// Upload data to the GPU

// Upload the buffer views used by mesh
bufferViews.forEach((bv: GLTFBufferView) => {
  if (bv.needsUpload) {
    bv.upload(device);
  }
});
// Upload all images, now that we know their usage and can
// pick the right GPU texture format
images.forEach((img: GLTFImage) => {
  img.upload(device);
});
// Create all samplers
samplers.forEach((s: GLTFSampler) => {
  s.create(device);
});
// Create bind groups and UBOs for materials
materials.forEach((mat: GLTFMaterial) => {
  mat.upload(device);
});

Updating the Shader to use the Material

Since we’re not using a fancy material or lighting model yet to implement the GLTFMaterial, our changes to the shader code are pretty simple. First, we’ll add new vertex inputs and outputs to pass the texture coordinates through from the vertex shader to the fragment shader, along with a new float2 alias.

alias float2 = vec2<f32>;

struct VertexInput {
    @location(0) position: float3,
    @location(1) texcoords: float2,
};

struct VertexOutput {
    @builtin(position) position: float4,
    @location(0) world_pos: float3,
    @location(1) texcoords: float2,
};

Our material parameters will be passed as uniforms, samplers, and textures in the material bind group. Let’s add these definitions to our shader:

struct MaterialParams {
    base_color_factor: float4,
    metallic_factor: f32,
    roughness_factor: f32,
};

@group(2) @binding(0)
var<uniform> material_params: MaterialParams;

@group(2) @binding(1)
var base_color_sampler: sampler;

@group(2) @binding(2)
var base_color_texture: texture_2d<f32>;

Finally, in the fragment shader we can use the material parameters to color the fragment. Since we’re now dealing with sRGB textures and want our rendering to be gamma correct, I’ve also added a linear_to_srgb utility function in the shader to convert our linear color values back to sRGB for display.

@fragment
fn fragment_main(in: VertexOutput) -> @location(0) float4 {
    let base_color = textureSample(base_color_texture, base_color_sampler, in.texcoords);
    var color = material_params.base_color_factor * base_color;

    color.x = linear_to_srgb(color.x);
    color.y = linear_to_srgb(color.y);
    color.z = linear_to_srgb(color.z);
    color.w = 1.0;
    return color;
}

Results

That’s it! With everything in, you should see a nicely rendered Duck like shown below. The full code, and the Duck model (from the glTF sample models repo) can be found on Github. You can run the demo embedded below, or directly here. If you try out a few models you might find the code crashes or doesn’t render materials correctly in some cases. This is because we have some built in assumptions in the code now, that all primitives will have materials, textures are always using texcoord 0, etc. We’ll come back to this later when we look at dynamically creating shaders specific to each primitive configuration.

If you have questions or want to discuss this post, you can use the Github discussion forum.

{
"by": "Twinklebear",
"descendants": 12,
"id": 40231988,
"kids": [
40234751,
40234712
],
"score": 52,
"time": 1714615411,
"title": "From 0 to glTF with WebGPU: Basic Materials and Textures",
"type": "story",
"url": "https://www.willusher.io/graphics/2024/04/28/0-to-gltf-basic-materials"
}
{
"author": null,
"date": "2024-04-28T12:00:00.000Z",
"description": null,
"image": "https://willusherio.b-cdn.net/webgpu-0-to-gltf/basic-material-textures-ts-duck.png",
"logo": "https://logo.clearbit.com/willusher.io",
"publisher": "Will Usher",
"title": "Will Usher",
"url": "https://www.willusher.io/graphics/2024/04/28/0-to-gltf-basic-materials/"
}
{
"url": "https://www.willusher.io/graphics/2024/04/28/0-to-gltf-basic-materials",
"title": "Will Usher",
"description": "Figure 1: The happy duck we’ll be able to render at the end of this postNow that we can load up complex scene hierarchies from glTF files and render them correctly, let’s start getting some more interesting...",
"links": [
"https://www.willusher.io/graphics/2024/04/28/0-to-gltf-basic-materials/",
"https://www.willusher.io/graphics/2024/04/28/0-to-gltf-basic-materials"
],
"image": "",
"content": "<div><article><div><figure><img src=\"https://willusherio.b-cdn.net/webgpu-0-to-gltf/basic-material-textures-ts-duck.png\" /><figcaption><i><b>Figure 1:</b>\nThe happy duck we’ll be able to render at the end of this post</i></figcaption></figure></div><p>Now that we can load up complex scene hierarchies from glTF files and render them correctly, let’s start getting some more interesting colors on screen! glTF defines a <a target=\"_blank\" href=\"https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#appendix-b-brdf-implementation\">physically based BRDF</a>, with support for metallic and roughness properties, along with normal, emission and occlusion texture maps. There are a number of <a target=\"_blank\" href=\"https://github.com/KhronosGroup/glTF/blob/main/extensions/README.md\">extensions</a> on top of this basic material model (the <code>KHR_materials_*</code> extensions) that add even more advanced material definitions.</p><p>We’ll keep it simple to start. Today we’re going to take the first step of loading the base glTF material parameters and textures from the glB file and passing them to our shader. In the shader we’ll color the object by its base color properties, without applying any lighting or material model yet.</p><h2 id=\"code-changes-from-the-previous-post\">Code Changes from the Previous Post</h2><p>If you’re following along from the <a target=\"_blank\" href=\"https://github.com/Twinklebear/webgpu-0-to-gltf/tree/main/4-full-scene-ts\">previous lesson’s code</a>, I’ve made a few cleanups while writing this lesson to make it easier to keep growing the lesson’s codebase:</p><ul><li>Split up the different <code>GLTF*</code> classes into separate files instead of having it all in <code>import_glb.ts</code></li><li>Split up the JSON importing work in <code>uploadGLB</code> to a few separate functions that load each individual part: <code>loadBufferViews</code>, <code>loadAccessors</code>, <code>loadMeshes</code></li></ul><p>I’ve also stopped writing the JavaScript versions of these posts, the rest of the series will be in TypeScript only. The full code for this post can be found on <a target=\"_blank\" href=\"https://github.com/Twinklebear/webgpu-0-to-gltf/tree/main/5-textures-ts\">Github</a>.</p><h2 id=\"loading-gltf-images-samplers-and-textures\">Loading glTF Images, Samplers and Textures</h2><p>Each texture in the glTF file references an image and, optionally, a sampler. The image defines the data for the texture, while the sampler defines the way that texture coordinates should be looked up within the image and how texels should be interpolated. The texture references the image and sampler by their index in the corresponding image and sampler array, similar to how accessors reference buffer views.</p><p>The texture array from Duck.glb is shown below. We have a single texture, which uses sampler 0 and image (source) 0:</p><div><pre><code><span><span><span>\"textures\"</span><span>:</span> [\n</span></span><span><span> {\n</span></span><span><span> <span>\"sampler\"</span>: <span>0</span>,\n</span></span><span><span> <span>\"source\"</span>: <span>0</span>\n</span></span><span><span> }\n</span></span><span><span>]\n</span></span></code></pre></div><p>The glTF images elements can either reference a file by URI, or a buffer view that contains the texture data. Since we’re only loading glB files in this series, we would expect to always have the texture data embedded in the file and will assume we always have a buffer view like below. The image specifies the buffer view containing its data, and the type of data within that buffer view. In this case, it’s a PNG.</p><div><pre><code><span><span><span>\"images\"</span><span>:</span> [\n</span></span><span><span> {\n</span></span><span><span> <span>\"bufferView\"</span>: <span>3</span>,\n</span></span><span><span> <span>\"mimeType\"</span>: <span>\"image/png\"</span>\n</span></span><span><span> }\n</span></span><span><span>]\n</span></span></code></pre></div><p>Note that it’s not required that all images in a glB file use buffer views for their data, for example I could have a glB file with lower resolution textures that can be downloaded quickly, that references higher resolution textures by URL that I can fetch asynchronously. We won’t be dealing with these kinds of files in this series though.</p><p>Finally, the glTF samplers specify how we should lookup and interpolate texels in the image when rendering. These parameters map directly to the WebGL/OpenGL <code>glTexParameter</code> parameter values. The mag/min filter parameters define the texture filtering under magnification and minification, respectively, by directly specifying the OpenGL enum parameter value. Similarly, wrapS and wrapT specify the texture wrapping mode to be used for samples out of the texture bounds.</p><div><pre><code><span><span><span>\"samplers\"</span><span>:</span> [\n</span></span><span><span> {\n</span></span><span><span> <span>\"magFilter\"</span>: <span>9729</span>,\n</span></span><span><span> <span>\"minFilter\"</span>: <span>9986</span>,\n</span></span><span><span> <span>\"wrapS\"</span>: <span>10497</span>,\n</span></span><span><span> <span>\"wrapT\"</span>: <span>10497</span>\n</span></span><span><span> }\n</span></span><span><span>]\n</span></span></code></pre></div><p>We’ll load the data “bottom-up” by first loading the image and sampler data, then loading the texture data. That way we have objects representing the images and samplers that the textures can share.</p><h2 id=\"parsing-samplers-into-gltfsamplers\">Parsing Samplers into GLTFSamplers</h2><p>The samplers are simple enough to load, we’ll start by defining some enums that store the glTF sampler parameter values so we don’t need to just remember some magic numbers.</p><div><pre><code><span><span><span>export</span> <span>enum</span> <span>GLTFTextureFilter</span> {\n</span></span><span><span> <span>NEAREST</span> <span>=</span> <span>9728</span>,\n</span></span><span><span> <span>LINEAR</span> <span>=</span> <span>9729</span>,\n</span></span><span><span> <span>NEAREST_MIPMAP_NEAREST</span> <span>=</span> <span>9984</span>,\n</span></span><span><span> <span>LINEAR_MIPMAP_NEAREST</span> <span>=</span> <span>9985</span>,\n</span></span><span><span> <span>NEAREST_MIPMAP_LINEAR</span> <span>=</span> <span>9986</span>,\n</span></span><span><span> <span>LINEAR_MIPMAP_LINEAR</span> <span>=</span> <span>9987</span>,\n</span></span><span><span>}\n</span></span><span><span>\n</span></span><span><span><span>export</span> <span>enum</span> <span>GLTFTextureWrap</span> {\n</span></span><span><span> <span>REPEAT</span> <span>=</span> <span>10497</span>,\n</span></span><span><span> <span>CLAMP_TO_EDGE</span> <span>=</span> <span>33071</span>,\n</span></span><span><span> <span>MIRRORED_REPEAT</span> <span>=</span> <span>33648</span>,\n</span></span><span><span>}\n</span></span></code></pre></div><p>Along with some utility functions to get the corresponding WebGPU <code>GPUFilterMode</code>, <code>GPUMipMapFilterMode</code>, and <code>GPUAddressMode</code> from the GLTF enums:</p><div><pre><code><span><span><span>export</span> <span>function</span> <span>gltfTextureFilterMode</span>(<span>filter</span>: <span>GLTFTextureFilter</span>) {\n</span></span><span><span> <span>switch</span> (<span>filter</span>) {\n</span></span><span><span> <span>case</span> <span>GLTFTextureFilter.NEAREST_MIPMAP_NEAREST</span>:\n</span></span><span><span> <span>case</span> <span>GLTFTextureFilter.NEAREST_MIPMAP_LINEAR</span>:\n</span></span><span><span> <span>case</span> <span>GLTFTextureFilter.NEAREST</span>:\n</span></span><span><span> <span>return</span> <span>\"nearest\"</span> <span>as</span> <span>GPUFilterMode</span>;\n</span></span><span><span> <span>case</span> <span>GLTFTextureFilter.LINEAR_MIPMAP_NEAREST</span>:\n</span></span><span><span> <span>case</span> <span>GLTFTextureFilter.LINEAR_MIPMAP_LINEAR</span>:\n</span></span><span><span> <span>case</span> <span>GLTFTextureFilter.LINEAR</span>:\n</span></span><span><span> <span>return</span> <span>\"linear\"</span> <span>as</span> <span>GPUFilterMode</span>;\n</span></span><span><span> }\n</span></span><span><span>}\n</span></span><span><span>\n</span></span><span><span><span>export</span> <span>function</span> <span>gltfTextureMipMapMode</span>(<span>filter</span>: <span>GLTFTextureFilter</span>) {\n</span></span><span><span> <span>switch</span> (<span>filter</span>) {\n</span></span><span><span> <span>case</span> <span>GLTFTextureFilter.NEAREST_MIPMAP_NEAREST</span>:\n</span></span><span><span> <span>case</span> <span>GLTFTextureFilter.LINEAR_MIPMAP_NEAREST</span>:\n</span></span><span><span> <span>case</span> <span>GLTFTextureFilter.NEAREST</span>:\n</span></span><span><span> <span>return</span> <span>\"nearest\"</span> <span>as</span> <span>GPUMipmapFilterMode</span>;\n</span></span><span><span> <span>case</span> <span>GLTFTextureFilter.LINEAR_MIPMAP_LINEAR</span>:\n</span></span><span><span> <span>case</span> <span>GLTFTextureFilter.NEAREST_MIPMAP_LINEAR</span>:\n</span></span><span><span> <span>case</span> <span>GLTFTextureFilter.LINEAR</span>:\n</span></span><span><span> <span>return</span> <span>\"linear\"</span> <span>as</span> <span>GPUMipmapFilterMode</span>;\n</span></span><span><span> }\n</span></span><span><span>}\n</span></span><span><span>\n</span></span><span><span><span>export</span> <span>function</span> <span>gltfAddressMode</span>(<span>mode</span>: <span>GLTFTextureWrap</span>) {\n</span></span><span><span> <span>switch</span> (<span>mode</span>) {\n</span></span><span><span> <span>case</span> <span>GLTFTextureWrap.REPEAT</span>:\n</span></span><span><span> <span>return</span> <span>\"repeat\"</span> <span>as</span> <span>GPUAddressMode</span>;\n</span></span><span><span> <span>case</span> <span>GLTFTextureWrap.CLAMP_TO_EDGE</span>:\n</span></span><span><span> <span>return</span> <span>\"clamp-to-edge\"</span> <span>as</span> <span>GPUAddressMode</span>;\n</span></span><span><span> <span>case</span> <span>GLTFTextureWrap.MIRRORED_REPEAT</span>:\n</span></span><span><span> <span>return</span> <span>\"mirror-repeat\"</span> <span>as</span> <span>GPUAddressMode</span>;\n</span></span><span><span> }\n</span></span><span><span>}\n</span></span></code></pre></div><p>We can now define a <code>GLTFSampler</code> class which will take these GLTF sampler parameters and convert them to their WebGPU equivalents, although for now we’re ignoring mip maps. The class also provides a <code>create</code> method that will create the actual <code>GPUSampler</code> object with the specified sampler parameters. The <code>GPUSampler</code> is what we will pass to our shaders later on to use when sampling the texture.</p><div><pre><code><span><span><span>export</span> <span>class</span> <span>GLTFSampler</span> {\n</span></span><span><span> <span>magFilter</span>: <span>GPUFilterMode</span> <span>=</span> <span>\"linear\"</span>;\n</span></span><span><span> <span>minFilter</span>: <span>GPUFilterMode</span> <span>=</span> <span>\"linear\"</span>;\n</span></span><span><span>\n</span></span><span><span> <span>wrapU</span>: <span>GPUAddressMode</span> <span>=</span> <span>\"repeat\"</span>;\n</span></span><span><span> <span>wrapV</span>: <span>GPUAddressMode</span> <span>=</span> <span>\"repeat\"</span>;\n</span></span><span><span>\n</span></span><span><span> <span>sampler</span>: <span>GPUSampler</span> <span>=</span> <span>null</span>;\n</span></span><span><span>\n</span></span><span><span> <span>constructor</span>(\n</span></span><span><span> <span>magFilter</span>: <span>GLTFTextureFilter</span>,\n</span></span><span><span> <span>minFilter</span>: <span>GLTFTextureFilter</span>,\n</span></span><span><span> <span>wrapU</span>: <span>GLTFTextureWrap</span>,\n</span></span><span><span> <span>wrapV</span>: <span>GLTFTextureWrap</span>\n</span></span><span><span> ) {\n</span></span><span><span> <span>this</span>.<span>magFilter</span> <span>=</span> <span>gltfTextureFilterMode</span>(<span>magFilter</span>);\n</span></span><span><span> <span>this</span>.<span>minFilter</span> <span>=</span> <span>gltfTextureFilterMode</span>(<span>minFilter</span>);\n</span></span><span><span>\n</span></span><span><span> <span>this</span>.<span>wrapU</span> <span>=</span> <span>gltfAddressMode</span>(<span>wrapU</span>);\n</span></span><span><span> <span>this</span>.<span>wrapV</span> <span>=</span> <span>gltfAddressMode</span>(<span>wrapV</span>);\n</span></span><span><span> }\n</span></span><span><span>\n</span></span><span><span> <span>// Create the GPU sampler\n</span></span></span><span><span><span></span> <span>create</span>(<span>device</span>: <span>GPUDevice</span>) {\n</span></span><span><span> <span>this</span>.<span>sampler</span> <span>=</span> <span>device</span>.<span>createSampler</span>({\n</span></span><span><span> <span>magFilter</span>: <span>this.magFilter</span>,\n</span></span><span><span> <span>minFilter</span>: <span>this.minFilter</span>,\n</span></span><span><span> <span>addressModeU</span>: <span>this.wrapU</span>,\n</span></span><span><span> <span>addressModeV</span>: <span>this.wrapV</span>,\n</span></span><span><span> <span>mipmapFilter</span><span>:</span> <span>\"nearest\"</span>,\n</span></span><span><span> });\n</span></span><span><span> }\n</span></span><span><span>}\n</span></span></code></pre></div><p>All that’s left to do is add a function in <code>import_glb.ts</code> that takes the JSON chunk and loads up any samplers within it and returns them. We have to handle the case that there are no samplers in the file, the file can omit samplers even if it has textures.</p><div><pre><code><span><span><span>function</span> <span>loadSamplers</span>(<span>jsonChunk</span>: <span>any</span>) {\n</span></span><span><span> <span>let</span> <span>samplers</span> <span>=</span> [];\n</span></span><span><span> <span>if</span> (<span>!</span><span>jsonChunk</span>.<span>samplers</span>) {\n</span></span><span><span> <span>return</span> [];\n</span></span><span><span> }\n</span></span><span><span>\n</span></span><span><span> <span>for</span> (<span>let</span> <span>s</span> <span>of</span> <span>jsonChunk</span>.<span>samplers</span>) {\n</span></span><span><span> <span>samplers</span>.<span>push</span>(\n</span></span><span><span> <span>new</span> <span>GLTFSampler</span>(\n</span></span><span><span> <span>s</span>[<span>\"magFilter\"</span>] <span>as</span> <span>GLTFTextureFilter</span>,\n</span></span><span><span> <span>s</span>[<span>\"minFilter\"</span>] <span>as</span> <span>GLTFTextureFilter</span>,\n</span></span><span><span> <span>s</span>[<span>\"wrapS\"</span>] <span>as</span> <span>GLTFTextureWrap</span>,\n</span></span><span><span> <span>s</span>[<span>\"wrapT\"</span>] <span>as</span> <span>GLTFTextureWrap</span>\n</span></span><span><span> )\n</span></span><span><span> );\n</span></span><span><span> }\n</span></span><span><span> <span>return</span> <span>samplers</span>;\n</span></span><span><span>}\n</span></span></code></pre></div><h2 id=\"loading-images-into-gltfimages\">Loading Images into GLTFImages</h2><p>Next, we need to load the image data out of the glB file by going through the images in the file, getting the data each of their buffer view’s references and turning it into an <code>ImageBitmap</code> that we can upload to the GPU.</p><p>We’ll actually start by defining an enum that we’ll need later, <code>ImageUsage</code>, which records how an image is being used by materials in the scene. Images in a glTF file can be used in a number of material inputs:</p><ul><li><a target=\"_blank\" href=\"https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#_material_pbrmetallicroughness_basecolortexture\">Base Color</a>: the texture contains sRGB color data</li><li><a target=\"_blank\" href=\"https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#_material_pbrmetallicroughness_metallicroughnesstexture\">Metallic + Roughness</a>: the blue channel stores the metalness values, the green channel stores roughness. Texture values are in linear space</li><li><a target=\"_blank\" href=\"https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#_material_normaltexture\">Normal</a>: the texture stores tangent-space normal, with RGB = XYZ. Texture values are in linear space</li><li><a target=\"_blank\" href=\"https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#_material_occlusiontexture\">Occlusion</a>: the R channel of the texture stores occlusion values. Texture values are in linear space</li><li><a target=\"_blank\" href=\"https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#_material_emissivetexture\">Emission</a>: the texture contains sRGB emission values</li></ul><p>In order to pick the right texture format, <code>rgba8unorm-srgb</code> or <code>rgba8unorm</code>, we need to know how a texture is used in the materials referencing it.</p><div><pre><code><span><span><span>export</span> <span>enum</span> <span>ImageUsage</span> {\n</span></span><span><span> <span>BASE_COLOR</span>,\n</span></span><span><span> <span>METALLIC_ROUGHNESS</span>,\n</span></span><span><span> <span>NORMAL</span>,\n</span></span><span><span> <span>OCCLUSION</span>,\n</span></span><span><span> <span>EMISSION</span>,\n</span></span><span><span>}\n</span></span></code></pre></div><p>Now let’s define our <code>GLTFImage</code> class. It will take an <code>ImageBitmap</code>, track its usage, and let us upload it to the GPU to produce a <code>GPUTexture</code> and <code>GPUTextureView</code> that we can pass to our shaders. Most of the work happens in <code>GPUTexture::upload</code>. Here we actually upload the <code>ImageBitmap</code> to a texture on the GPU using <a target=\"_blank\" href=\"https://gpuweb.github.io/gpuweb/#dom-gpuqueue-copyexternalimagetotexture\">copyExternalImageToTexture</a> . It’s worth noting that this code assumes each image will only have one usage, i.e., that an image used as a base color texture won’t also be used as a normal texture. This is likely a safe assumption, but if this is not the case in some interesting files, we could support creating an sRGB and non-sRGB texture view and the material can get the appropriate view for its usage.</p><div><pre><code><span><span><span>// Stores the image data texture for an image in the file\n</span></span></span><span><span><span></span><span>export</span> <span>class</span> <span>GLTFImage</span> {\n</span></span><span><span> <span>bitmap</span>: <span>ImageBitmap</span>;\n</span></span><span><span>\n</span></span><span><span> <span>// How the texture is used in the materials\n</span></span></span><span><span><span></span> <span>// referencing it\n</span></span></span><span><span><span></span> <span>usage</span>: <span>ImageUsage</span> <span>=</span> <span>ImageUsage</span>.<span>BASE_COLOR</span>;\n</span></span><span><span>\n</span></span><span><span> <span>image</span>: <span>GPUTexture</span> <span>=</span> <span>null</span>;\n</span></span><span><span> <span>view</span>: <span>GPUTextureView</span> <span>=</span> <span>null</span>;\n</span></span><span><span>\n</span></span><span><span> <span>constructor</span>(<span>bitmap</span>: <span>ImageBitmap</span>) {\n</span></span><span><span> <span>this</span>.<span>bitmap</span> <span>=</span> <span>bitmap</span>;\n</span></span><span><span> }\n</span></span><span><span>\n</span></span><span><span> <span>// Set the usage mode for the image\n</span></span></span><span><span><span></span> <span>setUsage</span>(<span>usage</span>: <span>ImageUsage</span>) {\n</span></span><span><span> <span>this</span>.<span>usage</span> <span>=</span> <span>usage</span>;\n</span></span><span><span> }\n</span></span><span><span>\n</span></span><span><span> <span>// Upload the image to the GPU and create the view\n</span></span></span><span><span><span></span> <span>upload</span>(<span>device</span>: <span>GPUDevice</span>) {\n</span></span><span><span> <span>// Pick the right texture format to use based on the\n</span></span></span><span><span><span></span> <span>// image's usage\n</span></span></span><span><span><span></span> <span>let</span> <span>format</span>: <span>GPUTextureFormat</span> <span>=</span> <span>\"rgba8unorm-srgb\"</span>;\n</span></span><span><span> <span>switch</span> (<span>this</span>.<span>usage</span>) {\n</span></span><span><span> <span>case</span> <span>ImageUsage.BASE_COLOR</span>:\n</span></span><span><span> <span>format</span> <span>=</span> <span>\"rgba8unorm-srgb\"</span>;\n</span></span><span><span> <span>break</span>;\n</span></span><span><span> <span>case</span> <span>ImageUsage.METALLIC_ROUGHNESS</span>:\n</span></span><span><span> <span>format</span> <span>=</span> <span>\"rgba8unorm\"</span>;\n</span></span><span><span> <span>break</span>;\n</span></span><span><span> <span>case</span> <span>ImageUsage.NORMAL</span>:\n</span></span><span><span> <span>case</span> <span>ImageUsage.OCCLUSION</span>:\n</span></span><span><span> <span>case</span> <span>ImageUsage.EMISSION</span>:\n</span></span><span><span> <span>throw</span> <span>new</span> Error(<span>\"Unhandled image format for now, TODO!\"</span>);\n</span></span><span><span> }\n</span></span><span><span>\n</span></span><span><span> <span>const</span> <span>imgSize</span> <span>=</span> [<span>this</span>.<span>bitmap</span>.<span>width</span>, <span>this</span>.<span>bitmap</span>.<span>height</span>, <span>1</span>];\n</span></span><span><span> <span>this</span>.<span>image</span> <span>=</span> <span>device</span>.<span>createTexture</span>({\n</span></span><span><span> <span>size</span>: <span>imgSize</span>,\n</span></span><span><span> <span>format</span>: <span>format</span>,\n</span></span><span><span> <span>// Note: the render attachment usage is required for\n</span></span></span><span><span><span></span> <span>// copyExternalImageToTexture we aren't going to actually\n</span></span></span><span><span><span></span> <span>// render to these images ourselves\n</span></span></span><span><span><span></span> <span>usage</span>:\n</span></span><span><span> <span>GPUTextureUsage.TEXTURE_BINDING</span> <span>|</span>\n</span></span><span><span> <span>GPUTextureUsage</span>.<span>COPY_DST</span> <span>|</span>\n</span></span><span><span> <span>GPUTextureUsage</span>.<span>RENDER_ATTACHMENT</span>,\n</span></span><span><span> });\n</span></span><span><span>\n</span></span><span><span> <span>device</span>.<span>queue</span>.<span>copyExternalImageToTexture</span>(\n</span></span><span><span> { <span>source</span>: <span>this.bitmap</span> },\n</span></span><span><span> { <span>texture</span>: <span>this.image</span> },\n</span></span><span><span> <span>imgSize</span>\n</span></span><span><span> );\n</span></span><span><span>\n</span></span><span><span> <span>this</span>.<span>view</span> <span>=</span> <span>this</span>.<span>image</span>.<span>createView</span>();\n</span></span><span><span> }\n</span></span><span><span>}\n</span></span></code></pre></div><p>With the <code>GLTFImage</code> implemented, we can now write a function to load all the images in the glTF file into <code>GLTFImages</code> for use later on. To create an image bitmap from the binary data referenced by the <code>GLTFBufferView</code> we first create a <a target=\"_blank\" href=\"https://developer.mozilla.org/en-US/docs/Web/API/Blob\">Blob</a> from the view and specify the mimeType. We can then pass the <code>Blob</code> to <a target=\"_blank\" href=\"https://developer.mozilla.org/en-US/docs/Web/API/createImageBitmap\">createImageBitmap</a> to create an <code>ImageBitmap</code> that we can pass to <code>copyExternalImageToTexture</code>.</p><div><pre><code><span><span><span>async</span> <span>function</span> <span>loadImages</span>(<span>jsonChunk</span>: <span>any</span>, <span>bufferViews</span>: <span>GLTFBufferView</span>[]) {\n</span></span><span><span> <span>let</span> <span>images</span>: <span>GLTFImage</span>[] <span>=</span> [];\n</span></span><span><span> <span>if</span> (<span>!</span><span>jsonChunk</span>.<span>images</span>) {\n</span></span><span><span> <span>return</span> <span>images</span>;\n</span></span><span><span> }\n</span></span><span><span> <span>for</span> (<span>let</span> <span>img</span> <span>of</span> <span>jsonChunk</span>.<span>images</span>) {\n</span></span><span><span> <span>const</span> <span>bv</span> <span>=</span> <span>bufferViews</span>[<span>img</span>[<span>\"bufferView\"</span>]];\n</span></span><span><span> <span>const</span> <span>blob</span> <span>=</span> <span>new</span> <span>Blob</span>([<span>bv</span>.<span>view</span>], { <span>type</span><span>:</span> <span>img</span>[<span>\"mimeType\"</span>] });\n</span></span><span><span> <span>const</span> <span>bitmap</span> <span>=</span> <span>await</span> <span>createImageBitmap</span>(<span>blob</span>);\n</span></span><span><span> <span>images</span>.<span>push</span>(<span>new</span> <span>GLTFImage</span>(<span>bitmap</span>));\n</span></span><span><span> }\n</span></span><span><span> <span>return</span> <span>images</span>;\n</span></span><span><span>}\n</span></span></code></pre></div><h2 id=\"loading-the-gltftextures\">Loading the GLTFTextures</h2><p>All the hard work is done by the <code>GLTFSampler</code> and <code>GLTFImage</code>, the <code>GLTFTexture</code> just references a sampler and image source to combine them. Since the <code>GLTFTexture</code> is what’s going to be stored by the material, it’s convenient to implement <code>setUsage</code> on it as well to simply pass the usage flag through to the referenced image.</p><div><pre><code><span><span><span>export</span> <span>class</span> <span>GLTFTexture</span> {\n</span></span><span><span> <span>sampler</span>: <span>GLTFSampler</span>;\n</span></span><span><span> <span>image</span>: <span>GLTFImage</span>;\n</span></span><span><span>\n</span></span><span><span> <span>constructor</span>(<span>sampler</span>: <span>GLTFSampler</span>, <span>image</span>: <span>GLTFImage</span>) {\n</span></span><span><span> <span>this</span>.<span>sampler</span> <span>=</span> <span>sampler</span>;\n</span></span><span><span> <span>this</span>.<span>image</span> <span>=</span> <span>image</span>;\n</span></span><span><span> }\n</span></span><span><span>\n</span></span><span><span> <span>// Set the texture's image usage flag\n</span></span></span><span><span><span></span> <span>setUsage</span>(<span>usage</span>: <span>ImageUsage</span>) {\n</span></span><span><span> <span>this</span>.<span>image</span>.<span>setUsage</span>(<span>usage</span>);\n</span></span><span><span> }\n</span></span><span><span>}\n</span></span></code></pre></div><p>Loading the textures from the glTF file is similarly simple, with one caveat. It’s valid to not specify a sampler at all! In this case, the <a target=\"_blank\" href=\"https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#_texture_sampler\">importer is expected to use an appropriate default filtering mode and repeat addressing</a>. We handle this by creating a default sampler to use if no sampler was referenced and adding it to the samplers list if it was used so that we can create it on the device later on.</p><div><pre><code><span><span><span>function</span> <span>loadTextures</span>(\n</span></span><span><span> <span>jsonChunk</span>: <span>any</span>,\n</span></span><span><span> <span>images</span>: <span>GLTFImage</span>[],\n</span></span><span><span> <span>samplers</span>: <span>GLTFSampler</span>[]\n</span></span><span><span>) {\n</span></span><span><span> <span>let</span> <span>textures</span>: <span>GLTFTexture</span>[] <span>=</span> [];\n</span></span><span><span> <span>if</span> (<span>!</span><span>jsonChunk</span>.<span>textures</span>) {\n</span></span><span><span> <span>return</span> <span>textures</span>;\n</span></span><span><span> }\n</span></span><span><span> <span>const</span> <span>defaultSampler</span> <span>=</span> <span>new</span> <span>GLTFSampler</span>(\n</span></span><span><span> <span>GLTFTextureFilter</span>.<span>LINEAR</span>,\n</span></span><span><span> <span>GLTFTextureFilter</span>.<span>LINEAR</span>,\n</span></span><span><span> <span>GLTFTextureWrap</span>.<span>REPEAT</span>,\n</span></span><span><span> <span>GLTFTextureWrap</span>.<span>REPEAT</span>\n</span></span><span><span> );\n</span></span><span><span> <span>let</span> <span>usedDefaultSampler</span> <span>=</span> <span>false</span>;\n</span></span><span><span>\n</span></span><span><span> <span>for</span> (<span>let</span> <span>t</span> <span>of</span> <span>jsonChunk</span>.<span>textures</span>) {\n</span></span><span><span> <span>let</span> <span>sampler</span> <span>=</span> <span>null</span>;\n</span></span><span><span> <span>if</span> (<span>\"sampler\"</span> <span>in</span> <span>t</span>) {\n</span></span><span><span> <span>sampler</span> <span>=</span> <span>samplers</span>[<span>t</span>[<span>\"sampler\"</span>]];\n</span></span><span><span> } <span>else</span> {\n</span></span><span><span> <span>// If no sampler was specified, use the default\n</span></span></span><span><span><span></span> <span>sampler</span> <span>=</span> <span>defaultSampler</span>;\n</span></span><span><span> <span>usedDefaultSampler</span> <span>=</span> <span>true</span>;\n</span></span><span><span> }\n</span></span><span><span> <span>textures</span>.<span>push</span>(<span>new</span> <span>GLTFTexture</span>(<span>sampler</span>, <span>images</span>[<span>t</span>[<span>\"source\"</span>]]));\n</span></span><span><span> }\n</span></span><span><span> <span>// If we used the default sampler add it to the samplers list so its\n</span></span></span><span><span><span></span> <span>// GPU resources will be created\n</span></span></span><span><span><span></span> <span>if</span> (<span>usedDefaultSampler</span>) {\n</span></span><span><span> <span>samplers</span>.<span>push</span>(<span>defaultSampler</span>);\n</span></span><span><span> }\n</span></span><span><span> <span>return</span> <span>textures</span>;\n</span></span><span><span>}\n</span></span></code></pre></div><h2 id=\"loading-gltfmaterials\">Loading GLTFMaterials</h2><p><a target=\"_blank\" href=\"https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#reference-material\">Materials in glTF</a> specify the PBR model parameters and textures, as shown below for the Duck. Here we have a base color texture reference, along with metallic and emissive factors.</p><div><pre><code><span><span><span>\"materials\"</span><span>:</span> [\n</span></span><span><span> {\n</span></span><span><span> <span>\"pbrMetallicRoughness\"</span>:\n</span></span><span><span> {\n</span></span><span><span> <span>\"baseColorTexture\"</span>: {<span>\"index\"</span>: <span>0</span>},\n</span></span><span><span> <span>\"metallicFactor\"</span>: <span>0.0</span>\n</span></span><span><span> },\n</span></span><span><span> <span>\"emissiveFactor\"</span>: [<span>0.0</span>, <span>0.0</span>, <span>0.0</span>]\n</span></span><span><span> }\n</span></span><span><span>]\n</span></span></code></pre></div><p>We’ll represent these with the <code>GLTFMaterial</code> class, shown below. When provided textures, the material class will mark them with their corresponding usage in the material. The <code>GLTFMaterial::upload</code> method will upload the <code>baseColorFactor</code>, <code>metallicFactor</code> and <code>roughnessFactor</code> parameters to a uniform buffer and create a bind group referencing the material parameters (uniform buffer and any relevant textures). This is omitted for brevity, but can be found on <a target=\"_blank\" href=\"https://github.com/Twinklebear/webgpu-0-to-gltf/blob/main/5-textures-ts/src/gltf_material.ts\">Github</a>.</p><div><pre><code><span><span><span>export</span> <span>class</span> <span>GLTFMaterial</span> {\n</span></span><span><span> <span>baseColorFactor</span>: <span>vec4</span> <span>=</span> [<span>1</span>, <span>1</span>, <span>1</span>, <span>1</span>];\n</span></span><span><span> <span>baseColorTexture</span>: <span>GLTFTexture</span> <span>|</span> <span>null</span> <span>=</span> <span>null</span>;\n</span></span><span><span>\n</span></span><span><span> <span>metallicFactor</span>: <span>number</span> <span>=</span> <span>1</span>;\n</span></span><span><span> <span>roughnessFactor</span>: <span>number</span> <span>=</span> <span>1</span>;\n</span></span><span><span> <span>metallicRoughnessTexture</span>: <span>GLTFTexture</span> <span>|</span> <span>null</span> <span>=</span> <span>null</span>;\n</span></span><span><span>\n</span></span><span><span> <span>// Uniform buffer holding the material factor params\n</span></span></span><span><span><span></span> <span>paramBuffer</span>: <span>GPUBuffer</span> <span>=</span> <span>null</span>;\n</span></span><span><span>\n</span></span><span><span> <span>// Bind group layout and bind groups for the material parameters\n</span></span></span><span><span><span></span> <span>bindGroupLayout</span>: <span>GPUBindGroupLayout</span> <span>=</span> <span>null</span>;\n</span></span><span><span> <span>bindGroup</span>: <span>GPUBindGroup</span> <span>=</span> <span>null</span>;\n</span></span><span><span>\n</span></span><span><span> <span>constructor</span>(\n</span></span><span><span> <span>baseColorFactor</span>: <span>vec4</span>,\n</span></span><span><span> <span>baseColorTexture</span>: <span>GLTFTexture</span> <span>|</span> <span>null</span>,\n</span></span><span><span> <span>metallicFactor</span>: <span>number</span>,\n</span></span><span><span> <span>roughnessFactor</span>: <span>number</span>,\n</span></span><span><span> <span>metallicRoughnessTexture</span>: <span>GLTFTexture</span> <span>|</span> <span>null</span>\n</span></span><span><span> ) {\n</span></span><span><span> <span>this</span>.<span>baseColorFactor</span> <span>=</span> <span>baseColorFactor</span>;\n</span></span><span><span> <span>this</span>.<span>baseColorTexture</span> <span>=</span> <span>baseColorTexture</span>;\n</span></span><span><span> <span>if</span> (<span>this</span>.<span>baseColorTexture</span>) {\n</span></span><span><span> <span>this</span>.<span>baseColorTexture</span>.<span>setUsage</span>(<span>ImageUsage</span>.<span>BASE_COLOR</span>);\n</span></span><span><span> }\n</span></span><span><span>\n</span></span><span><span> <span>this</span>.<span>metallicFactor</span> <span>=</span> <span>metallicFactor</span>;\n</span></span><span><span> <span>this</span>.<span>roughnessFactor</span> <span>=</span> <span>roughnessFactor</span>;\n</span></span><span><span> <span>this</span>.<span>metallicRoughnessTexture</span> <span>=</span> <span>metallicRoughnessTexture</span>;\n</span></span><span><span> <span>if</span> (<span>this</span>.<span>metallicRoughnessTexture</span>) {\n</span></span><span><span> <span>this</span>.<span>metallicRoughnessTexture</span>.<span>setUsage</span>(<span>ImageUsage</span>.<span>METALLIC_ROUGHNESS</span>);\n</span></span><span><span> }\n</span></span><span><span> }\n</span></span><span><span>\n</span></span><span><span> <span>// Upload params buffer and create the bind group and bind group layout\n</span></span></span><span><span><span></span> <span>// for the material params\n</span></span></span><span><span><span></span> <span>upload</span>(<span>device</span>: <span>GPUDevice</span>) {\n</span></span><span><span> <span>// See github...\n</span></span></span><span><span><span></span> }\n</span></span><span><span>}\n</span></span></code></pre></div><p>We’ll load the materials from the file by adding a new <code>loadMaterials</code> function, that goes through any materials in the file and constructs the corresponding <code>GLTFMaterial</code>. If any values are missing from the material we apply the default value from the spec.</p><div><pre><code><span><span><span>function</span> <span>loadMaterials</span>(<span>jsonChunk</span>: <span>any</span>, <span>textures</span>: <span>GLTFTexture</span>[]) {\n</span></span><span><span> <span>let</span> <span>materials</span> <span>=</span> [];\n</span></span><span><span> <span>for</span> (<span>let</span> <span>m</span> <span>of</span> <span>jsonChunk</span>.<span>materials</span>) {\n</span></span><span><span> <span>const</span> <span>pbrMR</span> <span>=</span> <span>m</span>[<span>\"pbrMetallicRoughness\"</span>];\n</span></span><span><span> <span>// Default base color factor of 1, 1, 1\n</span></span></span><span><span><span></span> <span>const</span> <span>baseColorFactor</span> <span>=</span> <span>pbrMR</span>[<span>\"baseColorFactor\"</span>] <span>??</span> [<span>1</span>, <span>1</span>, <span>1</span>, <span>1</span>];\n</span></span><span><span> <span>const</span> <span>metallicFactor</span> <span>=</span> <span>pbrMR</span>[<span>\"metallicFactor\"</span>] <span>??</span> <span>1</span>;\n</span></span><span><span> <span>const</span> <span>roughnessFactor</span> <span>=</span> <span>pbrMR</span>[<span>\"roughnessFactor\"</span>] <span>??</span> <span>1</span>;\n</span></span><span><span>\n</span></span><span><span> <span>let</span> <span>baseColorTexture</span>: <span>GLTFTexture</span> <span>|</span> <span>null</span> <span>=</span> <span>null</span>;\n</span></span><span><span> <span>if</span> (<span>\"baseColorTexture\"</span> <span>in</span> <span>pbrMR</span>) {\n</span></span><span><span> <span>baseColorTexture</span> <span>=</span> <span>textures</span>[<span>pbrMR</span>[<span>\"baseColorTexture\"</span>][<span>\"index\"</span>]];\n</span></span><span><span> }\n</span></span><span><span> <span>let</span> <span>metallicRoughnessTexture</span>: <span>GLTFTexture</span> <span>|</span> <span>null</span> <span>=</span> <span>null</span>;\n</span></span><span><span> <span>if</span> (<span>\"metallicRoughnessTexture\"</span> <span>in</span> <span>pbrMR</span>) {\n</span></span><span><span> <span>metallicRoughnessTexture</span> <span>=</span>\n</span></span><span><span> <span>textures</span>[<span>pbrMR</span>[<span>\"metallicRoughnessTexture\"</span>][<span>\"index\"</span>]];\n</span></span><span><span> }\n</span></span><span><span> <span>materials</span>.<span>push</span>(\n</span></span><span><span> <span>new</span> <span>GLTFMaterial</span>(\n</span></span><span><span> <span>baseColorFactor</span>,\n</span></span><span><span> <span>baseColorTexture</span>,\n</span></span><span><span> <span>metallicFactor</span>,\n</span></span><span><span> <span>roughnessFactor</span>,\n</span></span><span><span> <span>metallicRoughnessTexture</span>\n</span></span><span><span> )\n</span></span><span><span> );\n</span></span><span><span> }\n</span></span><span><span> <span>return</span> <span>materials</span>;\n</span></span><span><span>}\n</span></span></code></pre></div><h2 id=\"loading-and-using-materials-for-primitives\">Loading and Using Materials for Primitives</h2><p>When we were loading primitives before, we skipped the “material” field that each primitive has. Now it’s time to come back and load it. Since we’re applying textures, we also will start loading the <code>TEXCOORDS_0</code> attribute that can also be specified on a primitive. The mesh loading code has been split out to <a target=\"_blank\" href=\"https://github.com/Twinklebear/webgpu-0-to-gltf/blob/main/5-textures-ts/src/import_glb.ts#L238-L289\">loadMeshes</a> as part of the code organization cleanup from the previous step. This function will now also take the <code>GLTFMaterial[]</code> array so that we can pass the corresponding material to each primitive when it’s created. We’ll also modify the <code>GLTFPrimitive</code> constructor to take a <code>GLTFMaterial</code> as a parameter and store it as a member variable.</p><div><pre><code><span><span><span>function</span> <span>loadMeshes</span>(\n</span></span><span><span> <span>jsonChunk</span>: <span>any</span>,\n</span></span><span><span> <span>accessors</span>: <span>GLTFAccessor</span>[],\n</span></span><span><span> <span>materials</span>: <span>GLTFMaterial</span>[]\n</span></span><span><span>) {\n</span></span><span><span> <span>let</span> <span>meshes</span> <span>=</span> [];\n</span></span><span><span> <span>for</span> (<span>let</span> <span>mesh</span> <span>of</span> <span>jsonChunk</span>.<span>meshes</span>) {\n</span></span><span><span> <span>let</span> <span>meshPrimitives</span> <span>=</span> [];\n</span></span><span><span> <span>for</span> (<span>let</span> <span>prim</span> <span>of</span> <span>mesh</span>.<span>primitives</span>) {\n</span></span><span><span> <span>// Get topology and indices as before...\n</span></span></span><span><span><span></span>\n</span></span><span><span> <span>// Get the positions and the texture coordinates\n</span></span></span><span><span><span></span> <span>let</span> <span>positions</span> <span>=</span> <span>null</span>;\n</span></span><span><span> <span>let</span> <span>texcoords</span> <span>=</span> <span>null</span>;\n</span></span><span><span> <span>for</span> (<span>let</span> <span>attr</span> <span>in</span> <span>prim</span>[<span>\"attributes\"</span>]) {\n</span></span><span><span> <span>let</span> <span>accessor</span> <span>=</span> <span>accessors</span>[<span>prim</span>[<span>\"attributes\"</span>][<span>attr</span>]];\n</span></span><span><span> <span>if</span> (<span>attr</span> <span>===</span> <span>\"POSITION\"</span>) {\n</span></span><span><span> <span>positions</span> <span>=</span> <span>accessor</span>;\n</span></span><span><span> } <span>else</span> <span>if</span> (<span>attr</span> <span>===</span> <span>\"TEXCOORD_0\"</span>) {\n</span></span><span><span> <span>texcoords</span> <span>=</span> <span>accessor</span>;\n</span></span><span><span> }\n</span></span><span><span> }\n</span></span><span><span>\n</span></span><span><span> <span>// Lookup the material for the primitive\n</span></span></span><span><span><span></span> <span>let</span> <span>mat</span> <span>=</span> <span>materials</span>[<span>prim</span>[<span>\"material\"</span>]];\n</span></span><span><span>\n</span></span><span><span> <span>// Add the primitive to the mesh's list of primitives\n</span></span></span><span><span><span></span> <span>meshPrimitives</span>.<span>push</span>(\n</span></span><span><span> <span>new</span> <span>GLTFPrimitive</span>(<span>mat</span>, <span>positions</span>, <span>indices</span>, <span>texcoords</span>, <span>topology</span>)\n</span></span><span><span> );\n</span></span><span><span> }\n</span></span><span><span> <span>meshes</span>.<span>push</span>(<span>new</span> <span>GLTFMesh</span>(<span>mesh</span>[<span>\"name\"</span>], <span>meshPrimitives</span>));\n</span></span><span><span> }\n</span></span><span><span> <span>return</span> <span>meshes</span>;\n</span></span><span><span>}\n</span></span></code></pre></div><h2 id=\"updating-gltfprimitive-buildrenderpipeline\">Updating GLTFPrimitive buildRenderPipeline</h2><p>Our <a target=\"_blank\" href=\"https://github.com/Twinklebear/webgpu-0-to-gltf/blob/main/5-textures-ts/src/gltf_primitive.ts\">GLTFPrimitive</a> gets two additions in <code>buildRenderPipeline</code> :</p><ul><li>Adding the texture coordinates attribute, if it has texture coordinates</li><li>Adding the material bind group layout to its render pipeline’s bind group layouts</li></ul><p>Our <code>vertexState</code> will now be built as shown below. We add the position attribute buffer as before, and now, if we have texture coordinates, we add the texture coordinates vertex buffer as well.</p><div><pre><code><span><span><span>let</span> <span>vertexBuffers</span>: <span>GPUVertexBufferLayout</span>[] <span>=</span> [\n</span></span><span><span> {\n</span></span><span><span> <span>arrayStride</span>: <span>this.positions.byteStride</span>,\n</span></span><span><span> <span>attributes</span><span>:</span> [\n</span></span><span><span> {\n</span></span><span><span> <span>format</span>: <span>this.positions.elementType</span> <span>as</span> <span>GPUVertexFormat</span>,\n</span></span><span><span> <span>offset</span>: <span>0</span>,\n</span></span><span><span> <span>shaderLocation</span>: <span>0</span>,\n</span></span><span><span> },\n</span></span><span><span> ],\n</span></span><span><span> },\n</span></span><span><span>];\n</span></span><span><span><span>if</span> (<span>this</span>.<span>texcoords</span>) {\n</span></span><span><span> <span>vertexBuffers</span>.<span>push</span>({\n</span></span><span><span> <span>arrayStride</span>: <span>this.texcoords.byteStride</span>,\n</span></span><span><span> <span>attributes</span><span>:</span> [\n</span></span><span><span> {\n</span></span><span><span> <span>format</span>: <span>this.texcoords.elementType</span> <span>as</span> <span>GPUVertexFormat</span>,\n</span></span><span><span> <span>offset</span>: <span>0</span>,\n</span></span><span><span> <span>shaderLocation</span>: <span>1</span>,\n</span></span><span><span> },\n</span></span><span><span> ],\n</span></span><span><span> });\n</span></span><span><span>}\n</span></span><span><span>\n</span></span><span><span><span>// Vertex attribute state and shader stage\n</span></span></span><span><span><span></span><span>let</span> <span>vertexState</span> <span>=</span> {\n</span></span><span><span> <span>// Shader stage info\n</span></span></span><span><span><span></span> <span>module</span>: <span>shaderModule</span>,\n</span></span><span><span> <span>entryPoint</span><span>:</span> <span>\"vertex_main\"</span>,\n</span></span><span><span> <span>// Vertex buffer info\n</span></span></span><span><span><span></span> <span>buffers</span>: <span>vertexBuffers</span>,\n</span></span><span><span>};\n</span></span></code></pre></div><p>We’ll also now add the primitive’s material bind group layout to its pipeline:</p><div><pre><code><span><span><span>// Add the material bind group layout\n</span></span></span><span><span><span></span><span>bindGroupLayouts</span>.<span>push</span>(<span>this</span>.<span>material</span>.<span>bindGroupLayout</span>);\n</span></span><span><span>\n</span></span><span><span><span>let</span> <span>layout</span> <span>=</span> <span>device</span>.<span>createPipelineLayout</span>({\n</span></span><span><span> <span>bindGroupLayouts</span>: <span>bindGroupLayouts</span>,\n</span></span><span><span>});\n</span></span></code></pre></div><h2 id=\"updating-uploadglb\">Updating uploadGLB</h2><p>We can now add calls to our loader functions in <code>uploadGLB</code> . We start by loading all the buffer views, and accessors, after which we get the images, samplers, textures and materials. Finally we can load the meshes. Once all the data has been loaded from the file we know what usage our GPU objects have and can upload them.</p><div><pre><code><span><span><span>// Load the buffer views\n</span></span></span><span><span><span></span><span>const</span> <span>bufferViews</span> <span>=</span> <span>loadBufferViews</span>(<span>jsonChunk</span>, <span>binaryChunk</span>);\n</span></span><span><span><span>// Load the GLTF accessors\n</span></span></span><span><span><span></span><span>const</span> <span>accessors</span> <span>=</span> <span>loadAccessors</span>(<span>jsonChunk</span>, <span>bufferViews</span>);\n</span></span><span><span><span>// Load and decode all the images in the file\n</span></span></span><span><span><span></span><span>const</span> <span>images</span> <span>=</span> <span>await</span> <span>loadImages</span>(<span>jsonChunk</span>, <span>bufferViews</span>);\n</span></span><span><span><span>// Load all the samplers in the file\n</span></span></span><span><span><span></span><span>const</span> <span>samplers</span> <span>=</span> <span>loadSamplers</span>(<span>jsonChunk</span>);\n</span></span><span><span><span>// Load all the textures, which just combine a sampler + image\n</span></span></span><span><span><span></span><span>const</span> <span>textures</span> <span>=</span> <span>loadTextures</span>(<span>jsonChunk</span>, <span>images</span>, <span>samplers</span>);\n</span></span><span><span><span>// Load all the materials\n</span></span></span><span><span><span></span><span>const</span> <span>materials</span> <span>=</span> <span>loadMaterials</span>(<span>jsonChunk</span>, <span>textures</span>);\n</span></span><span><span><span>// Load all meshes\n</span></span></span><span><span><span></span><span>const</span> <span>meshes</span> <span>=</span> <span>loadMeshes</span>(<span>jsonChunk</span>, <span>accessors</span>, <span>materials</span>);\n</span></span><span><span>\n</span></span><span><span><span>// Upload data to the GPU\n</span></span></span><span><span><span></span>\n</span></span><span><span><span>// Upload the buffer views used by mesh\n</span></span></span><span><span><span></span><span>bufferViews</span>.<span>forEach</span>((<span>bv</span>: <span>GLTFBufferView</span>) <span>=&gt;</span> {\n</span></span><span><span> <span>if</span> (<span>bv</span>.<span>needsUpload</span>) {\n</span></span><span><span> <span>bv</span>.<span>upload</span>(<span>device</span>);\n</span></span><span><span> }\n</span></span><span><span>});\n</span></span><span><span><span>// Upload all images, now that we know their usage and can\n</span></span></span><span><span><span>// pick the right GPU texture format\n</span></span></span><span><span><span></span><span>images</span>.<span>forEach</span>((<span>img</span>: <span>GLTFImage</span>) <span>=&gt;</span> {\n</span></span><span><span> <span>img</span>.<span>upload</span>(<span>device</span>);\n</span></span><span><span>});\n</span></span><span><span><span>// Create all samplers\n</span></span></span><span><span><span></span><span>samplers</span>.<span>forEach</span>((<span>s</span>: <span>GLTFSampler</span>) <span>=&gt;</span> {\n</span></span><span><span> <span>s</span>.<span>create</span>(<span>device</span>);\n</span></span><span><span>});\n</span></span><span><span><span>// Create bind groups and UBOs for materials\n</span></span></span><span><span><span></span><span>materials</span>.<span>forEach</span>((<span>mat</span>: <span>GLTFMaterial</span>) <span>=&gt;</span> {\n</span></span><span><span> <span>mat</span>.<span>upload</span>(<span>device</span>);\n</span></span><span><span>});\n</span></span></code></pre></div><h2 id=\"updating-the-shader-to-use-the-material\">Updating the Shader to use the Material</h2><p>Since we’re not using a fancy material or lighting model yet to implement the GLTFMaterial, our changes to the <a target=\"_blank\" href=\"https://github.com/Twinklebear/webgpu-0-to-gltf/blob/main/5-textures-ts/src/gltf_prim.wgsl\">shader code</a> are pretty simple. First, we’ll add new vertex inputs and outputs to pass the texture coordinates through from the vertex shader to the fragment shader, along with a new <code>float2</code> alias.</p><div><pre><code><span><span>alias float2 <span>=</span> <span>vec2</span><span>&lt;</span>f32<span>&gt;</span>;\n</span></span><span><span>\n</span></span><span><span><span>struct</span> VertexInput {\n</span></span><span><span> <span>@</span>location(<span>0</span>) position<span>:</span> float3,\n</span></span><span><span> <span>@</span>location(<span>1</span>) texcoords<span>:</span> float2,\n</span></span><span><span>};\n</span></span><span><span>\n</span></span><span><span><span>struct</span> VertexOutput {\n</span></span><span><span> <span>@</span>builtin(position) position<span>:</span> float4,\n</span></span><span><span> <span>@</span>location(<span>0</span>) world_pos<span>:</span> float3,\n</span></span><span><span> <span>@</span>location(<span>1</span>) texcoords<span>:</span> float2,\n</span></span><span><span>};\n</span></span></code></pre></div><p>Our material parameters will be passed as uniforms, samplers, and textures in the material bind group. Let’s add these definitions to our shader:</p><div><pre><code><span><span><span>struct</span> MaterialParams {\n</span></span><span><span> base_color_factor<span>:</span> float4,\n</span></span><span><span> metallic_factor<span>:</span> f32,\n</span></span><span><span> roughness_factor<span>:</span> f32,\n</span></span><span><span>};\n</span></span><span><span>\n</span></span><span><span><span>@</span>group(<span>2</span>) <span>@</span>binding(<span>0</span>)\n</span></span><span><span>var<span>&lt;</span><span>uniform</span><span>&gt;</span> material_params<span>:</span> MaterialParams;\n</span></span><span><span>\n</span></span><span><span><span>@</span>group(<span>2</span>) <span>@</span>binding(<span>1</span>)\n</span></span><span><span>var base_color_sampler<span>:</span> sampler;\n</span></span><span><span>\n</span></span><span><span><span>@</span>group(<span>2</span>) <span>@</span>binding(<span>2</span>)\n</span></span><span><span>var base_color_texture<span>:</span> texture_2d<span>&lt;</span>f32<span>&gt;</span>;\n</span></span></code></pre></div><p>Finally, in the fragment shader we can use the material parameters to color the fragment. Since we’re now dealing with sRGB textures and want our rendering to be gamma correct, I’ve also added a <a target=\"_blank\" href=\"https://github.com/Twinklebear/webgpu-0-to-gltf/blob/main/5-textures-ts/src/gltf_prim.wgsl#L45-L50\">linear_to_srgb</a> utility function in the shader to convert our linear color values back to sRGB for display.</p><div><pre><code><span><span><span>@</span>fragment\n</span></span><span><span>fn fragment_main(<span>in</span><span>:</span> VertexOutput) <span>-&gt;</span> <span>@</span>location(<span>0</span>) float4 {\n</span></span><span><span> let base_color <span>=</span> textureSample(base_color_texture, base_color_sampler, <span>in</span>.texcoords);\n</span></span><span><span> var color <span>=</span> material_params.base_color_factor <span>*</span> base_color;\n</span></span><span><span>\n</span></span><span><span> color.x <span>=</span> linear_to_srgb(color.x);\n</span></span><span><span> color.y <span>=</span> linear_to_srgb(color.y);\n</span></span><span><span> color.z <span>=</span> linear_to_srgb(color.z);\n</span></span><span><span> color.w <span>=</span> <span>1.0</span>;\n</span></span><span><span> <span>return</span> color;\n</span></span><span><span>}\n</span></span></code></pre></div><h2 id=\"results\">Results</h2><p>That’s it! With everything in, you should see a nicely rendered Duck like shown below. The full code, and the Duck model (from the glTF sample models repo) can be found on <a target=\"_blank\" href=\"https://github.com/Twinklebear/webgpu-0-to-gltf/tree/main/5-textures-ts\">Github</a>. You can run the demo embedded below, or directly <a target=\"_blank\" href=\"https://www.willusher.io/webgpu-0-to-gltf/5-textures-ts\">here</a>. If you try out a few models you might find the code crashes or doesn’t render materials correctly in some cases. This is because we have some built in assumptions in the code now, that all primitives will have materials, textures are always using texcoord 0, etc. We’ll come back to this later when we look at dynamically creating shaders specific to each primitive configuration.</p><p>If you have questions or want to discuss this post, you can use the <a target=\"_blank\" href=\"https://github.com/Twinklebear/webgpu-0-to-gltf/discussions/5\">Github discussion forum</a>.</p></article></div>",
"author": "",
"favicon": "https://www.willusher.io/favicon.ico",
"source": "willusher.io",
"published": "",
"ttr": 639,
"type": ""
}