You can wrap any image or texture on the surface using the mesh.addTexCoord( texPoint )
function. Here texPoint
is of the ofPoint
type. It is a 2D point that should lie in range [0, w] × [0, h], where w × h is the size of the image that you want to use as a texture. Remember that you should call this function as many times as you call the mesh.addVertex()
function so that all the vertices will have texture coordinates.
During rendering each primitive of the mesh (whether triangle, line, or point depends on the mesh's mode), the texture coordinates of each rendered pixel will be calculated by OpenGL as interpolation of texture coordinates of the primitive's vertices. Resulting texture coordinates for the pixel are used for the pixel's color computing. In other words, the final pixel color is computed using three values: the color given by the texture, the color of the last ofSetColor()
calling, and the shading information obtained from the light and normals data. To change the algorithm of computing pixel color and the use of fragment shaders, see Chapter 8, Using Shaders.
For example, let's wrap the sunflower.png
image onto the pyramid.
Copy the image into the bin/data
folder of the project, and declare the ofImage
image in the testApp
class declaration. Then add the following lines in testApp::setup()
:
//Set up a texture coordinates for all the vertices mesh.addTexCoord( ofPoint( 100, 100 ) ); //v3 mesh.addTexCoord( ofPoint( 10, 300 ) ); //v2 mesh.addTexCoord( ofPoint( 10, 10 ) ); //v0 mesh.addTexCoord( ofPoint( 100, 100 ) ); //v3 mesh.addTexCoord( ofPoint( 300, 10 ) ); //v1 mesh.addTexCoord( ofPoint( 10, 300 ) ); //v2 mesh.addTexCoord( ofPoint( 100, 100 ) ); //v3 mesh.addTexCoord( ofPoint( 10, 10 ) ); //v0 mesh.addTexCoord( ofPoint( 300, 10 ) ); //v1 //Load an image image.loadImage( "sunflower.png" );
Finally, in testApp::draw()
, find the following lines:
ofSetColor( 0, 128, 0 ); //Set a dark green color mesh.draw();
Replace the preceding lines with the following:
ofSetColor( 255, 255, 255 ); //Set white color image.bind(); //Use image's texture for drawing mesh.draw(); //Draw mesh image.unbind(); //End using image's texture
After running the preceding code, you will see the pyramid with a wrapped texture as shown in the following screenshot: