We're now starting to open pandoras box of textures! As multiple textures mean you can combine textures - both loaded ones and generated ones - you can also mix transforms so the different textures are manimpulated in different ways.
These textures are eventually combined to create an infinite number of possibilities. For example, loading in a brick surface and mixing in dirt and scratches on top.
Simple multitexturing example - combining two textures together to create a new result.
The simple fragment shader below has two textures (myTexture0 and myTexture1). We use the first texture as the main color and the second texture contains some scratches and noise that we want to overlay.
We scale and clamp the noise texture and use only one of the components - the texture is black and white (so we only need the red component);
@group(0) @binding(1) var mySampler: sampler; @group(0) @binding(2) var myTexture0: texture_2d<f32>; @group(0) @binding(3) var<uniform> myTimer : f32; @group(0) @binding(4) var myTexture1: texture_2d<f32>;
var texCol0 = textureSample(myTexture0, mySampler, uv ).xyz;
var texCol1 = textureSample(myTexture1, mySampler, uv ).xyz;
var col = texCol0 * clamp(texCol1.r*1.5, 0.0, 1.0);
return vec4<f32>( col, 1.0 ); // set alpha to 1.0 so there isn't any transparncy
}
Example shows the original texture and a scratch texture which are combined to produce a scratched old texture.
Textures can come in many formats - for 32bit rgba and single 8bit gray scale - this can be accomodated for in the file and the shader so your loading and rendering is more efficient (just default to 32bit so it's easier for the examples).
The full code for the example is given below.
// Load matrix library on dynamically (on-the-fly) let matprom = await fetch( 'https://cdnjs.cloudflare.com/ajax/libs/gl-matrix/2.6.0/gl-matrix-min.js' ); let mattex = await matprom.text(); var script = document.createElement('script'); script.type = 'text/javascript'; script.innerHTML = mattex; document.head.appendChild(script);
// ------------- let canvas = document.createElement('canvas'); document.body.appendChild( canvas ); canvas.height=canvas.width=512;
The example just combines two textures in the simplest way - as discussed in previous tutorials - textures can be manipulated in many different ways (texture transforms) so the combined result can be very unique.
Things to Try
• Adding a 3rd texture
• Use transforms to manipulate the uv coordinates for one of the textures (rotated and stretched)
• Modify the texture `sampler` so it supports texture repeating and mirroring (so combined textures can be tiled instead of just clamping to the last pixel)