Game Development Reference
In-Depth Information
Samplers do not have a value. They cannot be set by expressions in a shader. They
can only be passed to a function as an in parameter. Putting it together, a sampler
value can be set in the shader code.
The sampler can only be used as a parameter in one of the GLSL standard library's
texture lookup functions. These functions access the texture referred to by the
sampler. They take a texture coordinate as parameters.
We will cover only two functions for now, texture and textureOffset . The texture
function is declared as follows:
vec texture(sampler sampler, vec texCoord);
The process of fetching data from a texture, at a particular location, is called
sampling. This function returns the samples of the texture associated with the
sampler, at the location texCoord . The size of the vec type of texCoord depends
on the dimensionality of the sampler. A 1D sampler takes a float size whereas
a 2D sampler takes a vec2 size.
vec textureOffset(sampler sampler, vec texCoord, vec offset);
We can add a texel offset to the texture coordinates, sampled with texture functions.
This is useful for sampling from a collection of images, all on a single texture.
Applying a texture to the square
In our code example, we will simply add a texture to the square we rendered in
Chapter 1 , Getting Started with WebGL Game Development . We will now just summarize
the changed code snippets that we added to render the square with a texture instead
of a predefined color. Open the 04-SquareWithTexture.html file in your favorite
text editor and review the following changes:
1.
We added the texture map array to the initBuffers function.
2.
We created a buffer, made the buffer the active buffer using bindBuffer ,
and allocated memory for the buffer. Note that the texture coordinates are
defined for each vertex, as shown in the following code snippet:
function initBuffers() {
...
verticesTextureBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, verticesTextureBuffer);
 
Search WWH ::




Custom Search