5.8 - Example 4: Textures¶
This example will hopefully help you get excited about the possibilities of shader programs. We won’t talk through the steps in detail, but the code is shown in the demo below.
Fragment shaders assign colors to pixels. They can be as simple as the examples in the previous demos, or they can be incredibly complex. Only your imagination limits you!
This example does the following:
- The model defined in
simple_model_04.js
is enhanced to store “texture coordinates” with each vertex. In this example, “texture coordinates” are 2 numbers that will be used by a procedural texture map, which is implemented in the fragment shader. - Three buffer objects are built: one for the vertex locations, (x,y,z), one for the vertex color values, RGB, and one for the texture coordinates, which we will refer to as (s,t).
- At render time, each attribute variable in the vertex shader is linked to the buffer object that contains its data.
- The entire model is rendered with a single call to
gl.drawArrays()
. - The fragment shader uses the texture coordinates to modify the color of each fragment. Note that the texture coordinates and the vertex colors are “varying” their values between the values that were set for the vertices.
A Texture Map Example¶
Show:
Code
Canvas
Run Info
A simple, 3D model where pixel colors are calculated using a procedural texture map.
Animate
Shader errors,
Shader warnings,
Javascript info
Summary¶
Let’s summarize the big picture once more before leaving this topic:
- A vertex shader program retrieves vertex and other associated data from buffer objects. All buffer objects are 1-dimensional arrays. The data in the buffer objects are organized by vertex. The vertex shader calculates the position a vertex in the scene and prepares any data needed by the fragment shader for calculating colors.
- A fragment shader program receives data from the vertex shader for each vertex and then interpolates the values over the fragments of the primitive (either a point, line or triangle).
- A pre-processing step must create appropriate buffer objects and copy the model data to the GPU’s buffer objects.
- Each time a model is rendered, a shader’s variables must be linked to their
appropriate buffer objects and then
gl.drawArrays()
initiates the rendering process.