Nehe OpenGL Tutorial Lesson 38th: Resource Files

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 38th: Resource Files

To load an image from a resource file:

How to save the image data to the *.exe program, use Windows resource file, it is simple and practical.

Welcome to the 38th lesson of the Nehe tutorial. It's been a while since the writing of the last class, and by writing the code for the whole day, maybe the pen has rusted:)
Now that you've learned how to do grid mapping, how to read into bitmap and various raster images ... So how do you do triangle maps and how do you show your textures in. exe files?

I am often asked these two questions, but once you see how simple they are, you will scold yourself unexpectedly:)

I will not explain every detail in everything, just give you some pictures, you can understand. I will be based on the latest code, please download it under the homepage "Nehegl I Basecode" or at the bottom of this page.

First, we load the image into the resource file. I have already known how to do it, but, you neglect a few steps, so worth some useless resource files. There are bitmap files in it, but they can't be used.

You remember that, don't you? We did it using Visual C + + 6.0. If you use other tools, this page is completely inapplicable to the resources section (especially those graphs).

* Temporarily you can only use 24bit BMP images. If read 8bit bmp file to write a lot of extra code. I would love to hear from you who have smaller/better loader. I read in 8bit and 24bit BMP code is really bloated. You can do it with loadimage.


Open the file, click on the "Insert" menu, select "Resources"


Then select the resource type bitmap file you want to insert, click Insert

Then the file window, go to the Data directory, select three graphics files (with ctrl) and click "Read in". Note The file type is correct.


It will pop up three warnings (one file at a time) and say it is read correctly, but the file cannot be browsed or edited because it has more than 256 colors. It's nothing!

Once all the graphics are in, a list will appear. Each graph is assigned an ID, each with a idb_bitmap, and then the number 1-3. If you're too lazy to change it, you don't have to worry about it. But we are still more diligent!


Right-click each ID, select Properties, and then rename to match the file name. Just like I did in the picture.


Next, select "File--〉 all save". You have just created a new resource file, so Windows will ask you what name to take. You can also call "Lesson38.rc", then save.
So far, you've got a resource file that's full of bitmap graphics files saved on your hard drive, and you need to complete a series of steps to use these files.


The next step is to add the resource files to your own project. Select "Project--〉 add to project--〉 file"


Select Resorce.h file and resource file lesson38.rc (with ctrl)


Finally confirm that the resource file lesson38.rc into the Resource Files folder. Just like in the picture above, click and drag into the Resource Files folder.
After the move, select "File--〉 all save" and then the file section will be fine. A lot of pictures:)

Then we start the Code section. The most important line of the following is the # include "resource.h". Without this line, there will be countless undefined variable errors when compiling. The Resource.h file defines the object in the resource file. So to read from the idb_butterfly1 inside the data, it is best to include this header file!

#include <windows.h>
#include <gl\gl.h>
#include <gl\glu.h>
#include <gl\glaux.h>
#include "NeHeGL.h"
#include header file for "resource.h"//Resource files

#pragma comment (lib, "Opengl32.lib")
#pragma comment (lib, "Glu32.lib")
#pragma comment (lib, "Glaux.lib")

gl_window* G_window;
Keys* G_keys;

The first line below allocates the space required for three textures, and the following structure is used to hold information about about 50 objects moving on the screen.
Tex will track the textures used for each object, x is the X coordinate of the object, y is the y coordinate, z,z coordinates, Yi is a random number to control the object falling speed,
Spinz is used to control the rotation along the z axis, Spinzi is another random tree, recording the rotational speed. The flap is used to control the wings of an object (one will explain this) and the random number fi controls the speed of the flapping of the wings.
 
//define the ID of three saved texture variables
Gluint texture[3];            //save three textures

struct object            //defines an object
{
 int   tex;           //Texture value
 float x;           //location
  float y;          
 float z;           
 float yi;            //Speed
 float spinz;          //the angle and speed of rotation along the z axis
 float spinzi;          
 float flap;           //whether to flip the triangle
 float fi;           
};

Object OBJ[50]; Creation of 50 objects

The following code is the initialization of object Obj[loop], with loops from 0 to 49 (representing one of 50 objects). First, the random textures are represented from 0 to 2.
A random coloring of butterflies. The x-coordinate randomly takes the value between -17.0f and +17.0f, and Y takes 18.0f, which is a little bit from the top of the screen,
The object is not visible at the beginning. Z is also a random number between -10.0f and -40.F, Spinzi takes -1.0f to 1.0f. Flap Wing Center
Position, for 0.0f. The last beat speed fi and the drop speed Yi are also random.

void setobject (int loop)//loop set of 50 objects
{
Obj[loop].tex=rand ()%3; Texture
Obj[loop].x=rand ()%34-17.0f; Position
obj[loop].y=18.0f;
obj[loop].z=-(rand ()%30000/1000.0f) +10.0f);
Obj[loop].spinzi= (rand ()%10000)/5000.0f-1.0f; Rotating
obj[loop].flap=0.0f;
obj[loop].fi=0.05f+ (rand ()%100)/1000.0f;
obj[loop].yi=0.001f+ (rand ()%1000)/10000.0f;
}

It's time to go to the most interesting places. Reads the bitmap from the resource file into the texture. Hbmp is a pointer to this bitmap file,
It will tell our program where to read the data. BMP is a bitmap structure, we keep the data read from the resource file inside.
The third line is to tell our program which id:idb_butterfly1,idb_butterfly2,idb_butterfly3 we will use. To use more
Image, simply increase the image in the resource file and add the new ID in texture[].

void Loadgltextures ()//resource file read in bitmap, to texture
{
Hbitmap hbmp; Bitmap handle
BITMAP BMP; Bitmap structure

Texture handle
Byte texture[]={idb_butterfly1, Idb_butterfly2, idb_butterfly3};

The following line uses sizeof (Texture) to calculate how many textures to create. We have 3 IDs, which is 3 textures.

Glgentextures (sizeof (Texture), &texture[0]); Create a three texture
for (int loop=0; loop<sizeof (Texture); loop++)//cyclic loading of all bitmaps
{

LoadImage requires the following parameters: GetModuleHandle (NULL)-point to instance handle, Makeintresource (Texture[loop])-convert texture[loop] from integral to one
The source value, which is the graphic file to read. Image_bitmap-told us to read a BITMAP file.
The next two parameters (0,0) are the height and width pixels of the read-in image, which is set to 0 using the default size.
The last parameter (lr_createdibsection) returns the DIB section bitmap?? This is a bitmap with no color information saved. And that's what we need.
Hbmp points to bitmap data read from LoadImage ().

hbmp= (HBITMAP) LoadImage (GetModuleHandle (NULL), Makeintresource (Texture[loop]), Image_bitmap, 0, 0, LR_ CreateDIBSection);

Check if the pointer hbmp is valid, which points to useful data. If you do not point to any data, you can also eject the error message.
If the data exists, use GetObject () to obtain data (sizeof (BMP)) from hbmp and store it in BMP.
Glpixelstorei tells OpenGL that the data is stored in Word alignments, which is 4 bytes per pixel. The
binds the texture, sets the filter to Gl_linear_mipmap_linear (nice and smooth), and then generates the texture.
Notice that we use bmp.bmwidth and bmp.bmheight to get the height and width of the image. Using Gl_bgr_ext to swap red and blue, the actual resource data used is the
obtained from the bmp.bmbits. The
finally deletes the bitmap object, releasing any system resource space associated with it.

  if (hbmp)           //Bitmap exists
  {         //exists
    getobject (Hbmp,sizeof (BMP), &bmp);      //get bitmap
    Glpixelstorei (gl_unpack_alignment,4);     //four bytes to its memory
   glbindtexture ( gl_texture_2d, Texture[loop]);     //binding Location Map
   gltexparameteri (GL_TEXTURE_2D , gl_texture_mag_filter,gl_linear);   //set the texture filter
   gltexparameteri (GL_TEXTURE_2D,GL_ Texture_min_filter,gl_linear_mipmap_linear);
  //Creating Textures
   glubuild2dmipmaps (gl_texture_2d, 3, Bmp.bmwidth, Bmp.bmheight, GL_BGR_ EXT, Gl_unsigned_byte, bmp.bmbits);
   deleteobject (hbmp);       //Delete Bitmap object
  }
 }
}

Init code is nothing new, just adds the Loadgltextures () call above the code. Clear screen color is black, do not carry out depth detection, so faster. Enable Texture mapping
and process color effects.

BOOL Initialize (gl_window* Window, keys* Keys)//initialization
{
G_window = window;
G_keys = keys;

Loadgltextures (); Loading textures

 glclearcolor (0.0f, 0.0f, 0.0f, 0.5f);        //Setting the background
 glcleardepth (1.0f);         
 gldepthfunc (gl_lequal);         
 gldisable (GL_DEPTH_ test);          //enable depth Test
 glshademodel (gl_smooth);         
 glhint (Gl_perspective_correction_hint, GL_NICEST);     
 glenable (gl_texture_2d);          // Enable 2D texture
 glblendfunc (gl_one,gl_src_alpha);         //use blending
 glenable (gl_blend);          
  
Initialize all objects  

for (int loop=0; loop<50; loop++)
{
SetObject (loop);
}

return TRUE; Successful return
}

void Deinitialize (void)
{
}

void update (DWORD milliseconds)//update, performing animations
{
if (G_keys->keydown [vk_escape] = = TRUE)//press ESC to exit
{
Terminateapplication (G_window);
}

if (G_keys->keydown [vk_f1] = = TRUE)//press F1 to toggle display mode
{
Togglefullscreen (G_window);
}
}

Next look at the drawing code. In this section I will explain how to map an image to two triangles in as simple a way as possible. Some people think there's reason to believe that an image to a triangle
It is not possible to have a single mapping on the
In fact, you can easily map images into any shape area. Make the image match the boundary or not consider the form at all. It doesn't matter at all. (Translator: I think the author's intention
Thought is that the analytic innuendo from the rectangle to the triangle does not exist, but without considering so much, continuous innuendo between arbitrary shapes can always exist. He said to match the texture to the boundary.
, presumably referring to a parameterized method, which simply makes the distortion minimal. )
First clear the screen, the cycle of polishing 50 butterfly objects.

void Draw (void)//Draw Scene
{
Glclear (Gl_color_buffer_bit | Gl_depth_buffer_bit);

for (int loop=0; loop<50; loop++)
{

Call Glloadidentify () to reset the projection matrix, and then select the object's texture. Position the butterfly with Gltranslatef () and rotate it 45 degrees along the x-axis. Make it slightly inclined to the audience, which
The sample is more stereoscopic. Finally, it rotates along the z axis and the butterfly falls.

Glloadidentity (); Reset Matrix
Glbindtexture (gl_texture_2d, Texture[obj[loop].tex]); Binding Textures
Gltranslatef (OBJ[LOOP].X,OBJ[LOOP].Y,OBJ[LOOP].Z); Drawing objects
Glrotatef (45.0f,1.0f,0.0f,0.0f);
Glrotatef ((Obj[loop].spinz), 0.0f,0.0f,1.0f);

In fact, there is no big difference between the map on the triangle and the square. Only you have three fixed points, be careful.
In the code below, we will value the first triangle. Start at the upper-right corner of an imagined square, to the upper-left corner, and then to the lower-left corner. The polishing result looks like this:


Notice that half a butterfly appears. The other half appears in a second triangle. Similarly, the three texture coordinates do not correspond to the vertex coordinates, which gives sufficient information to define a map on a triangle.
Glbegin (Gl_triangles);

GLTEXCOORD2F (1.0f,1.0f); glvertex3f (1.0f, 1.0f, 0.0f);
GLTEXCOORD2F (0.0f,1.0f); glvertex3f ( -1.0f, 1.0f, Obj[loop].flap);
GLTEXCOORD2F (0.0f,0.0f); glvertex3f ( -1.0f,-1.0f, 0.0f);

The following code touches the other half. Ditto, but our triangle has changed from top right to lower left, then to bottom right.


The 3rd of the 2nd and second triangles of the first triangle (that is, the tip of the wings) reciprocating in the z direction (i.e. between z=-1.0f and 1.0f), two triangles along the body of a butterfly
The body folds up, produces the beating effect, is simple and feasible.

GLTEXCOORD2F (1.0f,1.0f); glvertex3f (1.0f, 1.0f, 0.0f);
GLTEXCOORD2F (0.0f,0.0f); glvertex3f ( -1.0f,-1.0f, 0.0f);
GLTEXCOORD2F (1.0f,0.0f); glvertex3f (1.0f,-1.0f, Obj[loop].flap);

Glend ();

The following paragraph moves the butterfly from top to bottom by decreasing obj[loop].yi from the obj[loop].y. Spinz value Increment Spinzi (can be positive) flap increment fi.fi positive or negative depending on wing to
Up or down movement.

Move, select an image
Obj[loop].y-=obj[loop].yi;
Obj[loop].spinz+=obj[loop].spinzi;
obj[loop].flap+=obj[loop].fi;

When the butterfly is running down, it needs to check if the screen is out, and if so, call SetObject (loop) to give the butterfly a new texture, a new drop speed, etc.

if (obj[loop].y<-18.0f)//Determine if the screen is exceeded, if it is reset
{
SetObject (loop);
}

When flapping the wings, also check whether the flap is less than -1.0f or greater than 1.0f, if so, make fi=-fi to change the direction of movement. Sleep (15) is used to slow down the operating speed, 15 mm per frame
Seconds. On my friend's machine, this makes the butterflies fly wildly. But I am too lazy to change:)

if ((obj[loop].flap>1.0f) | | | (obj[loop].flap<-1.0f))
{
obj[loop].fi=-obj[loop].fi;
}
}

Sleep (15);

Glflush ();
}
Original source code and version of the download:

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

Nehe OpenGL Tutorial Lesson 38th: Resource Files

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.