Nehe OpenGL Tutorial Lesson Sixth: texture mapping

Source: Internet
Author: User
Tags clear screen

Go from "translation" Nehe OpenGL tutorial

Objective

Statement, this Nehe OpenGL tutorial series of articles by 51 blog yarin Translation (2010-08-19), this blog for reprint and a little collation and modification. Thank you for compiling Nehe's OpenGL pipeline tutorial, as well as yarn translation finishing.

Nehe OpenGL Lesson Sixth: texture mapping

Texture mapping:

In this lesson, I'll teach you how to map textures to six facets of a cube.

learning texture map texture mapping (map) has many benefits. Let's say you want a missile to fly over the screen. Based on the knowledge of the previous lessons, our most feasible approach may be to build a missile's contours and add interesting colors with a lot of polygons. With texture mapping, you can use a real missile image and let it fly over the screen. Which do you think looks better? A picture of a whole bunch of triangles and quads? The benefits of using texture mapping are more than just a good look, and your program will run faster. The missile map may be just a quadrilateral that flies over a window. A polygon-built missile is likely to include hundreds or thousands of polygons. Obviously, the mapping greatly saves CPU time.
Now we add five lines of code at the beginning of the first lesson's code. The first line added is #include <stdio.h>. It allows us to manipulate the file, and we added this line in order to use fopen () in the later code. Then we added three new floating-point variables ... xrot, Yrot and Zrot. These variables are used to rotate the cube around the X, Y, and Z axes. The last line Gluint Texture[1] allocates storage space for a texture. If you need more than one texture, you should change the parameter 1 to the parameter you want.  
  
#include  <stdio.h>       //standard input/ header file for Output Library
#include header file for  <glaux.h>       //Glaux library

Glfloat Xrot; X Rotational Volume
Glfloat Yrot; Y Rotation Amount
Glfloat Zrot; Z Rotation Amount

Gluint Texture[1]; Store a texture

Immediately following the code above in Resizeglscene (), we added this section of code. This code is used to load the bitmap file. If the file does not exist, returns NULL informing the program that the bitmap could not be loaded. Before I start explaining this code, I think there are a few things that are important to use as textures, and you have to understand. The width and height of this image must be 2 of the n-th square, and the widths and heights must be at least 64 pixels, and for compatibility reasons, the width and height of the image should not exceed 256 pixels. If the width and height of your original footage are not 64,128,256 pixels, use the image processing software to re-change the size of the image. There are certain ways to get around these limits, but now we just need to use the standard texture size.
First, we create a file handle. A handle is a numeric value that is used to identify a resource, which enables the program to access the resource. Let's start by setting the handle to NULL first.

Aux_rgbimagerec *loadbmp (char *filename)//loading bitmap images
{
FILE *file=null; File handle

Next, check to see if the file name is provided. Because Loadbmp () can be called without arguments, we have to check it. You don't want to load anything ...:)

if (! FileName)//Ensure that the file name is provided
{
return NULL; If not provided, returns NULL
}

Then check to see if the file exists. The following line attempts to open the file.

File=fopen (Filename, "R"); Try to open a file

If we can open the file, it's clear that the file exists. Use fclose (file) to close the file. Auxdibimageload (Filename) reads the image data and returns it.

Does the if (file)//files exist?
{
Fclose (File); Close handle
Return Auxdibimageload (Filename); Load a bitmap and return a pointer
}

If we cannot open the file, we will return NULL. This means that the file cannot be loaded. The program later checks to see if the file is loaded. If not, we will exit the program and pop up the error message.

return NULL; If loading fails, returns NULL
}

The next section of code loads the bitmap (calling the code above) and transforms it into a texture.

int loadgltextures ()//load bitmap (call above code) and convert to texture
{

Then set a variable called Status. We use it to track whether we can load bitmaps and whether we can create textures. The Status default is set to FALSE (indicating that nothing is loaded or created).

int status=false; Status indicator

Now we create an image record that stores the bitmap. The secondary record contains the width, height, and data of the bitmap.

Aux_rgbimagerec *textureimage[1]; Create a texture's storage space

Clear the image record to make sure its contents are empty

memset (textureimage,0,sizeof (void *)); Set the pointer to NULL

now loads the bitmap and transforms it into a texture. Textureimage[0]=loadbmp ("Data/nehe.bmp") calls the code for Loadbmp (). Load the nehe.bmp bitmap file in the Data directory. If everything works, the image data will be stored in textureimage[0], the Status is set to TRUE, and then we start creating textures.  
  
 //loads the bitmap, checks for errors, and exits
 if (textureimage[0]=loadbmp ("data/nehe.bmp") if the bitmap is not found
 {
  status=true;       //set Status to TRUE

Now use the data in textureimage[0] to create the texture. The first line glgentextures (1, &texture[0]) tells OpenGL that we want to generate a texture name (if you want to load multiple textures, increase the number). It's worth noting that we started using Gluint texture[1] to create a texture storage space, and you might think that the first texture was stored in &texture[1], but that's wrong. The correct address should be &texture[0]. Similarly, if you use Gluint texture[2], the second texture is stored in texture[1]. "Translator Note: Learn C, there should be no obstacles here, the array is zero-based." 』
The second line, Glbindtexture (gl_texture_2d, texture[0]), tells OpenGL to bind the texture name texture[0] to the texture target. The texture is only height (on the Y-axis) and width (on the X-axis). The main function assigns the texture name to the texture data. In this example we tell OpenGL that the memory at &texture[0] is already available. The textures we create will be stored in the point-of-memory area of &texture[0].

Glgentextures (1, &texture[0]); Creating textures

Using a typical texture generated from bitmap data
Glbindtexture (gl_texture_2d, texture[0]);

down we create a real texture. The following line tells OpenGL that this texture is a 2D texture (gl_texture_2d). The parameter "0" represents the level of detail of the image, which is usually zero. Parameter three is the component number of the data. Because the image is composed of three components of red data, green data, blue data. Textureimage[0]->sizex is the width of the texture. If you know the width, you can fill it in here, but the computer can easily indicate this value for you. Textureimage[0]->sizey is the height of the texture. Parameter 0 is the value of the border, which is generally "0". Gl_rgb tells OpenGL that the image data is composed of red, green, and blue tri-color data.
Gl_unsigned_byte means that the data that makes up the image is of the unsigned byte type. At last... Textureimage[0]->data tells the source of the OpenGL texture data. In this example, point to the data stored in the textureimage[0] record.  
  
  //generate Textures
  glteximage2d (gl_texture_2d, 0, 3, textureimage[0]- >sizex, Textureimage[0]->sizey, 0, Gl_rgb, Gl_unsigned_byte, textureimage[0]->data);

The following two lines tell OpenGL when the image is displayed, when it is larger than the original texture (gl_texture_mag_filter) or smaller than the original texture (gl_texture_min_filter), OpenGL uses the filtering method. Usually I use gl_linear in both cases. This makes the texture appear smooth from very far away to the screen very close. Using gl_linear requires more computing from the CPU and graphics. If your machine is slow, you should probably use Gl_nearest. The texture of the filter is enlarged, it looks mottled "translator note: Mosaic." You can also combine these two filtering methods. Use Gl_linear near, gl_nearest at a distance.

Gltexparameteri (gl_texture_2d,gl_texture_min_filter,gl_linear); Linear filtering
Gltexparameteri (gl_texture_2d,gl_texture_mag_filter,gl_linear); Linear filtering
}

Now let's release the memory previously used to store the bitmap data. Let's first see if the bitmap data is stored. If so, then check to see if the data is already stored. If it is already stored, delete it. Then release the textureimage[0] image structure to ensure that all memory can be released.

if (textureimage[0])//texture exists
{
if (textureimage[0]->data)//texture image exists
{
Free (textureimage[0]->data); Releasing the memory occupied by the texture image
}

Free (textureimage[0]); Releasing the image structure
}

Finally, the status variable is returned. If everything is OK, the value of the variable Status is TRUE. Otherwise, FALSE.

return Status; Return to Status
}

I only add a few lines of code to INITGL. But in order to make it easier for you to see which lines have been added, I've pasted this code all over again. if (! Loadgltextures ()) This line of code calls the subroutine above to load the bitmap and generate the texture. If the Loadgltextures () call fails for any reason, the next line returns false. If everything is OK and the texture is created, we enable 2D texture mapping. If you forget to enable it, your object will always look pure white, which is certainly not a good thing.  
  
int initgl (glvoid)         //here to start all settings for OpenGL
{
 if (! Loadgltextures ())        //call texture Load subroutine
 {
  return FALSE;        //if failed to load, returns false
 }

 glenable (gl_texture_2d);       Enable texture mapping
 glshademodel (Gl_smooth);       //enable Shadow smoothing
 glclearcolor ( 0.0f, 0.0f, 0.0f, 0.5f);      //black background
 glcleardepth (1.0f);        //setting the depth cache
 glenable (gl_depth_test);       //Enable depth testing
 gldepthfunc (gl_lequal);        //the type of depth test performed
 glhint (GL_ Perspective_correction_hint, gl_nicest);    //true fine perspective correction
 return true;         //Initialize OK
}

Now we're mapping "translator Note: Actually the map is a texture map. It's not good to change the terminology, I'd like to cut two words less. ^_^ "over the cube. This piece of code is a crazy comment, it should be very understood. Starting two lines of code glclear () and glloadidentity () is the code in the first lesson. Glclear (Gl_color_buffer_bit | Gl_depth_buffer_bit) Clear the screen and set it to the color we selected in INITGL (), in this case, black. The depth cache is also cleared. The model observation matrix is also reset using Glloadidentity ().  
  
int drawglscene (glvoid)         //start with all the drawing from here
{
 glclear (gl_color_buffer_bit | Gl_depth_buffer_bit)    //clear screen and depth cache
 glloadidentity ();        //resets the current model observation matrix
 gltranslatef (0.0f,0.0f,-5.0f);       //move into Screen 5 Units

The following three exercise cubes rotate around the x, Y, and Z axes. The number of rotations depends on the value of the variable Xrot, Yrot, and Zrot.

Glrotatef (xrot,1.0f,0.0f,0.0f); Rotate around X axis
Glrotatef (yrot,0.0f,1.0f,0.0f); Rotate around the y-axis
Glrotatef (zrot,0.0f,0.0f,1.0f); Rotate around the z axis

The next line of code selects the textures we use. If you use more than one texture in your scene, you should select the texture you want to bind using to Glbindtexture (gl_texture_2d, the number that corresponds to the texture used by texture[). When you want to change the texture, you should bind the new texture. It is worth noting that you cannot bind textures between glbegin () and Glend () and must be bound before glbegin () or after Glend (). Notice how we use Glbindtexture to specify and bind textures later.

Glbindtexture (gl_texture_2d, texture[0]); Select Textures

In order to map the texture correctly to the quadrilateral, you must map the upper-right corner of the texture to the upper-right corner of the quad, the upper-left corner of the texture mapped to the upper-left corner of the quad, the lower-right corner of the texture mapped to the lower-right corner of the quad, and the lower-left corner of the texture mapped If the mapping is wrong, the image may appear upside-down, sideways, or nothing.
The first parameter of the GLTEXCOORD2F is the x-coordinate. 0.0F is the left side of the texture. 0.5f is the midpoint of the texture and 1.0f is the right side of the texture. The second parameter of the gltexcoord2f is the y-coordinate. 0.0F is the bottom of the texture. The 0.5f is the midpoint of the texture and 1.0f is the top of the texture.

So the top left coordinate of the texture is x:0.0f,y:1.0f, and the top left vertex of the quad is X: -1.0f,y:1.0f. The remaining three points and so on.

Try playing gltexcoord2f x, y coordinate parameters. Changing the 1.0f to 0.5f will only show the left half of the texture, and changing 0.0f to 0.5f will show only the right half of the texture.

Glbegin (gl_quads);
Front
GLTEXCOORD2F (0.0f, 0.0f); glvertex3f ( -1.0f, -1.0f, 1.0f); Bottom left of texture and quadrilateral
GLTEXCOORD2F (1.0f, 0.0f); glvertex3f (1.0f, -1.0f, 1.0f); Bottom right of texture and quadrilateral
GLTEXCOORD2F (1.0f, 1.0f); glvertex3f (1.0f, 1.0f, 1.0f); Textures and quads on top right
GLTEXCOORD2F (0.0f, 1.0f); glvertex3f ( -1.0f, 1.0f, 1.0f); Texture and quads on top left
Behind
GLTEXCOORD2F (1.0f, 0.0f); glvertex3f ( -1.0f, -1.0f, -1.0f); Bottom right of texture and quadrilateral
GLTEXCOORD2F (1.0f, 1.0f); glvertex3f ( -1.0f, 1.0f, -1.0f); Textures and quads on top right
GLTEXCOORD2F (0.0f, 1.0f); glvertex3f (1.0f, 1.0f, -1.0f); Texture and quads on top left
GLTEXCOORD2F (0.0f, 0.0f); glvertex3f (1.0f, -1.0f, -1.0f); Bottom left of texture and quadrilateral
Top Face
GLTEXCOORD2F (0.0f, 1.0f); glvertex3f ( -1.0f, 1.0f, -1.0f); Texture and quads on top left
GLTEXCOORD2F (0.0f, 0.0f); glvertex3f ( -1.0f, 1.0f, 1.0f); Bottom left of texture and quadrilateral
GLTEXCOORD2F (1.0f, 0.0f); glvertex3f (1.0f, 1.0f, 1.0f); Bottom right of texture and quadrilateral
GLTEXCOORD2F (1.0f, 1.0f); glvertex3f (1.0f, 1.0f, -1.0f); Textures and quads on top right
Bottom surface
GLTEXCOORD2F (1.0f, 1.0f); glvertex3f ( -1.0f, -1.0f, -1.0f); Textures and quads on top right
GLTEXCOORD2F (0.0f, 1.0f); glvertex3f (1.0f, -1.0f, -1.0f); Texture and quads on top left
GLTEXCOORD2F (0.0f, 0.0f); glvertex3f (1.0f, -1.0f, 1.0f); Bottom left of texture and quadrilateral
GLTEXCOORD2F (1.0f, 0.0f); glvertex3f ( -1.0f, -1.0f, 1.0f); Bottom right of texture and quadrilateral
Right
GLTEXCOORD2F (1.0f, 0.0f); glvertex3f (1.0f, -1.0f, -1.0f); Bottom right of texture and quadrilateral
GLTEXCOORD2F (1.0f, 1.0f); glvertex3f (1.0f, 1.0f, -1.0f); Textures and quads on top right
GLTEXCOORD2F (0.0f, 1.0f); glvertex3f (1.0f, 1.0f, 1.0f); Texture and quads on top left
GLTEXCOORD2F (0.0f, 0.0f); glvertex3f (1.0f, -1.0f, 1.0f); Bottom left of texture and quadrilateral
Left
GLTEXCOORD2F (0.0f, 0.0f); glvertex3f ( -1.0f, -1.0f, -1.0f); Bottom left of texture and quadrilateral
GLTEXCOORD2F (1.0f, 0.0f); glvertex3f ( -1.0f, -1.0f, 1.0f); Bottom right of texture and quadrilateral
GLTEXCOORD2F (1.0f, 1.0f); glvertex3f ( -1.0f, 1.0f, 1.0f); Textures and quads on top right
GLTEXCOORD2F (0.0f, 1.0f); glvertex3f ( -1.0f, 1.0f, -1.0f); Texture and quads on top left
Glend ();

Now increase the value of Xrot, Yrot and Zrot. Try changing the value of each variable each time to adjust the rotation speed of the cube, or change the +/-number to adjust the direction of rotation of the cube.

xrot+=0.3f; X-axis Rotation
yrot+=0.2f; Y-axis Rotation
zrot+=0.4f; Z-axis Rotation
return true; Continue running
}

Original source code and version of the download:

http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=06

Nehe OpenGL Tutorial Lesson Sixth: texture mapping

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.