Page 8: Using Textures

CS559 Spring 2021 Sample Solution - Workbook 11

Written by CS559 course staff

You can try out the example solutions here. The interesting code is on page 6, page 7 and page 9.

Image-Based Textures and Shaders

Shaders can look up values (usually colors) in images. This is how we implement traditional texture mapping.

First, we need to put the image file into a uniform variable. More specifically, we don’t only need an image, but also all the machinery that can read values from it. For example, we might use a mip-map. The GLSL data type is called a sampler2D.

Setting up a sampler2D from the host side is complicated. Fortunately, THREE does it for us. All we need to do is create a Texture and assign it to a uniform variable.

Then, in our shader program we refer to this sampler2D uniform using the texture2D function, which looks up a position in the texture.

Here’s a simple example (image © UW-Madison):

You can look at 11-08-01.js (11-08-01.html) and the shaders shaders/11-08-01.vs and shaders/11-08-01.fs to see how it works. Notice how the uniform is set up in the JS file, and then accessed in the fragment shader.

A More Complex Example

In this example, we’ll make a planet. We’ll have a texture with blue (ocean) and green (land) and we’ll put it on a sphere.

Then, we’ll add mountains - we’ll use the green brightness as a height, and use that to displace the vertices of the sphere. We’ll have to do this in the vertex shader.

The interesting part of this is the vertex shader shaders/11-08-02.vs. Note how I look up values in the texture, and use the amount of green to move the vertices in the normal direction.

This is the opposite of a normal map (which we will discuss in class next week, so don’t worry if you aren’t familiar with them yet): there is no lighting, but we are really moving the geometry. It is a displacement map.

You can also look at 11-08-02.js (11-08-02.html) and shaders/11-08-02.fs - but these are pretty much the same as prior examples.

Summary: Textures in Shaders

Now that we’ve seen how to use textures in shaders, we have all the main pieces. Now it’s time to make some shaders on Next: All Together .

There are no points associated with this page.