OpenGL basic knowledge

xiaoxiao2021-03-05  36

Environment: VC6

Well, here is good news for all game lovers and beginning game programmers. This article will show you how to create a simple Balloon Show game using OpenGL libraries. The OpenGL libraries can be used with other language platforms, but it is best to use them With the Visual C Environment Because Most of The Game Program Use VC To make their games. This Article Shows The step by step handling from the beginning.

The first thing you will have to do is build a project in Visual C . After you have created a new Win32 Application (not a console application) in Visual C , you will need to link the OpenGL libraries. In Visual C , go to Project , Settings, and then click on the link tab. Under "Object / library modules" at the beginning of the line (before kernel32.lib), add opengl32.lib glu32.lib and glaux.lib. Once you've done this, Click Ok. You're Now Ready to Write An OpenGL Windows Program. Your Program Should Include All these Header Files:

#include "windows.h" //Header File for Windows

#include "gl / gl.h" // Header File for the OpenGL32 LIBRARY

#include "gl / glu.h" //Header File for the glu32 library

#include "GL / GLAUX.H" // HEADER File for the Glaux Library

THE FEW VARIABLES THAT WE Do SET UP ARE VERY IMPORTANT, AND WILL BE USED IN JUST ABOUT EVERY OpenGL Program Write Using this Code. The Data Types for OpenGL Are Also Defined. For Example:

Glvoid

Gluint

GLFLOAT

The first line sets up a Rendering Context. Every OpenGL program is linked to a Rendering Context. A Rendering Context is what links OpenGL calls to the Device Context. The OpenGL Rendering Context is defined as hRC. In order for your program to draw to a Window, you need to create a Device Context; this is done in the second line The Windows Device Context is defined as hDC The DC connects the Window to the GDI (Graphics Device Interface) The RC connects OpenGL to the DC.HDC... HDC = NULL; // Private GDI Device Context

Hglrc hrc = null; // permanent rendering context

HWND HWND = NULL; // Holds Our Window Handle

Hinstance Hinstance; // Holds The Instance of the Application

The first line below sets up an array, keys [256], that we will use to monitor key presses on the keyboard. There are many ways to watch for key presses on the keyboard, but this is the way I do it. It's reliable And IT CAN Handle More Than One Key Being Pressed At A Time.

The active variable will be used to tell our program whether or not our Window has been minimized to the taskbar The variable fullscreen is fairly obvious If our program is running in fullscreen mode, fullscreen will be TRUE;.. If our program is running in Windowed Mode, Fullscreen Will Be false.

Bool Keys [256]; // array buy for the keyboard routine

Bool Active = true; // window activ flag set to true by default /

Bool Fullscreen = true; // Fullscreen Flag Set to Fullscreen Mode

// by Default

In The Following Line, We define WndProc () SO That CreateGLWindow () CAN make reference to wndproc ().

Lresult Callback WndProc (HWND, UINT, WPARAM, LPARAM);

The OpenGL Scene Will Be Resized Based ON The Width and Height of The Window It's Being Displayed In.glvoid ResizeGlscene (Glsizei Width, Glsizei Height)

// resize and initialize the gl window

{

IF (height == 0) // prevent a divide by zero by

{// MAKING Height Equal ONE

HEIGHT = 1;

}

GLVIEWPORT (0, 0, Width, Height); // Reset The Current ViewPort

The following lines set the screen up for a perspective view. This means that things in the distance get smaller. This creates a realistic looking scene. The perspective is calculated with a 45 degree viewing angle based on the window's width and height. The 0.1f 100.0f area the starting point and ending point for how deep we can draw into the screen.

Glmatrixmode (GL_Projection); // Select the Projection Matrix

GLLoadIdentity (); // reset the Projection Matrix

// Calculate the aspect ratio of the window

Gluperspective (45.0F, (GLFLOAT) Width / (GLFLOAT) Height, 0.1F, 100.0F);

GLmatrixmode (GL_ModelView); // Select The ModelView Matrix

GLLoadIdentity (); // reset the modelview matrix

}

In the next section of code, we do all of the setup for OpenGL. We set what color to clear the screen to, and we turn on the depth buffer, enable smooth shading, and so forth. This routine will not be called until the OpenGL Window Has Been Created.

INT INITGL (GLVOID) // All setup for OpenGL

// Goes here

{

Glshademodel (GL_SMOOTH); // enables smooth shading

GlclearColor (0.0F, 0.0F, 0.0F, 0.0F); // Black Background

Glcleardepth (1.0F); // Depth Buffer Setup

Glenable (GL_DEPTH_TEST); // Enables Depth Testing

GLDEPTHFUNC (GL_LEQUAL); // The Type of Depth Test // TO DO

GLHINT (GL_PERSPECTIVE_CORRECTION_HINT, // Really Nice Perspective

GL_NICEST); // Calculations

Return True; // Initialization Went OK

}

Anything You Plan to Display On The Screen Will Go in This Section Of Code.

INT Drawglscene (Glvoid) // Here's Where We do all the drawing

{

GLCLEAR (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Clear the screen and the defth buffer

The next three lines of code position and rotate the texture mapped cube. GlTranslatef (0.0f, 0.0f, z) moves the cube to the value of z on the z plane (away from and towards the viewer). GlRotatef (xrot, 1.0 F, 0.0F, 0.0F) Uses The variable xrot to rotate the cube on the x axis. Glrotatef (YROT, 1.0F, 0.0F, 0.0F) Uses the variable yrot to rotate the cube on the y axis. these Things Will Be Covered in detail later.

GltranslateF (0.0F, 0.0F, Z); // translate INTO / OUT OF THE

// Screen by Z

Glrotatef (xROT, 1.0F, 0.0F, 0.0F); // rotate on the x Axis by xROT

GLROTATEF (YROT, 0.0F, 1.0F, 0.0F); // rotate on the y axis by yrot

.................

GlbindTexture (GL_Texture_2D, Texture [Filter]);

// Select a Texture Based on Filter

.

Q = glunewquadric (); // Create a new quadratic

Gluquadricnormals (Q, GL_SMOOTH); // Generate Smooth Normals

// for the quad

GluquadricTexture (Q, GL_TRUE); // Enable Texture Coords

// for the quad

GLTEXGENI (GL_S, GL_TEXTURE_GEN_MODE, / / ​​SET UP sphere mappinggl_sphere_map);

GLTEXGENI (GL_T, GL_TEXTURE_GEN_MODE, / / ​​SET UP sphere mapping

GL_Sphere_map);

The following code is to make a cube with given bitmap textures on all sides of the cube-front, back, top, bottom, right, and left. The code for the front side is shown here and the rest is in the source code provided WITH THIS.

Glbegin (GL_QUADS); // Front Face

Glnormal3f (0.0F, 0.0F, 1.0F); // Normal Pointing Towards

// viewer

GLTEXCOORD2F (0.0F, 0.0F); // Point 1 (Front)

GlvertEX3F (-1.0F, -1.0F, 1.0F);

GLTEXCOORD2F (1.0F, 0.0F); // Point 2 (FRONT)

Glvertex3f (1.0F, -1.0F, 1.0F);

GLTEXCOORD2F (1.0F, 1.0F); // Point 3 (FRONT)

Glvertex3f (1.0F, 1.0F, 1.0F);

GLTEXCOORD2F (0.0F, 1.0F);

GlvertEX3F (-1.0F, 1.0F, 1.0F); // Point 4 (Front)

glend;

GLLoadIdentity (); // Reset the Current ModelView Matrix

Return true; // everything went OK

}

The Following Function Code Destroys The OpenGL WINDOW. The First Thing We do in killglwindow () IS Check to See WHETHER WE Are, We'll Switch Back to the Desktop.

GLVOID KILLGLWINDOW (GLVOID)

The Following Function Creates a OpenGL Window and Here You Can Set The size, Style, And Other Attributes of The Window.

Bool CreateglWindow (Char * Title, Int Width, Int Height,

INT BITS, BOOL FULLSCREENFLAG)

Texture binding

Gluint Texture [3] Creates Storage Space for the Three Different Textures. The Textures Will Be Stored At Texture [0], Texture [1], And Texture [2].

Gluint Texture [3]; // Storage for 3 Textures

AUX_RGBIMAGEREC * LOADBMP (Char * filename)

Now we load in a bitmap. The above function codes the loading, and building texture maps from bitmap images. The section of code that loads the bitmap (calling the code above) and converts it into three textures. A variable Status is used to keep TRACK OF WHETHER OR NOT The Texture Was Loaded and created. The variable for storing the image is aux_rgbimagerec. this is created in the function (). Creating motion Effects

Now We're Going To Set Up Up The Angle on The x Axis (xROT), The speted the crate is spinning at the x axis (xspeed), and the Speed ​​The Crate (YSPEED). We'll Also Create A Variable Called Z That Will Control How Deep In THE SCREEN (on the z axis) The balloon is or its zoom IS.

GLFLOAT XROT; // x rotation

GLFLOAT YROT; // Y Rotation

GLFLOAT XSPEED; // x rotation speed

GLFLOAT YSPEED; // Y Rotation Speed

GLFLOAT Z = -5.0F; // Depth (zoom) INTO THE SCREEN

GLFLOAT HEIGHT = 2.0F; // Height of Balloon from Floor

Creating Lighting Effects

.

BOOL Light; // Lighting ON / OFF

The first type of light is called ambient light. Ambient light is light that does not come from any particular direction. All the objects in your scene will be lit up by the ambient light. The second type of light is called diffuse light. Diffuse light is created by your light source and is reflected off the surface of an object in your scene. Any surface of an object that the light hits directly will be very bright, and areas the light barely gets to will be darker. This creates a nice SHADING Effect On The Sides of Our Crate and The Balloon.glflofloat Lightambient [] = {0.5F, 0.5F, 0.5F, 1.0F};

// Ambient Light Values ​​(NEW)

GLFLOAT LIGHTDIFFUSE [] = {1.0F, 1.0F, 1.0F, 1.0F};

/ DIFFUSE LIGHT VALUES (New) /

THIS TELLS OpenGL The Designated Coordinates Are The Position of The Light Source.

GLFLOAT LIGHTPSITION [] = {0.0F, 0.0F, // Light Position (New)

2.0F, 1.0F};

The Variables LP and fp is used to store WHETHER or NOT the 'L' or 'F' Key Has Been Pressed.

BOOL LP; // L PRESSED?

BOOL fp; // f Pressed?

CREANG FILTER Effects

Gluint Filter; // Which Filter To Use

The filter variable above keeps track of which texture to display. The first texture (texture 0) is made using gl_nearest (no smoothing). The second texture (texture 1) uses gl_linear filtering, which smooths the image out quite a bit. The third texture (texture 2) uses mipmapped textures, creating a very nice looking texture. The variable filter will equal 0, 1, or 2, depending on the texture we want to use. We start off with the first texture.

You'll notice we're Using GL_Nearest for Both the min and mag. You can Mix GL_NEAREST with GL_LINEAR, AND THE TEXTURE WILL LOOK A bit better, but're interested in schegether, so we'll Use low quality for Both. The MIN_FILTER is the filter used when an image is drawn smaller than the original texture size. The MAG_FILTER is used when the image is bigger than the original texture size.// Create Nearest Filtered Texture

Glbindtexture (GL_Texture_2D, Texture [0]);

GLTEXPARETERI (GL_Texture_2D, GL_TEXTURE_MAG_FILTER, / / ​​(NEW)

GL_NEAREST);

Gltexparameteri (GL_Texture_2D, GL_TEXTURE_MIN_FILTER, / / ​​(NEW)

GL_NEAREST);

Glteximage2D (GL_Texture_2D, 0, 3, TextureImage [0] -> SIZEX,

TextureImage [0] -> Sizey, 0, GL_RGB, GL_UNSIGNED_BYTE,

TextureImage [0] -> DATA);

In using linear filtered texture maps, they require a hefty amount of processing power, but they look really nice. The first type of texture we're going to create in this tutorial uses GL_NEAREST. Basically, this type of texture has no filtering at all IT Takes Very Little Processing Power, And It's Look All Blocky, It's Probably..

// Create Linear Filtered Texture

GlbindTexture (GL_Texture_2d, Texture [1]);

Gltexparameteri (GL_Texture_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

GLTEXPARAMETERI (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

Glteximage2D (GL_Texture_2D, 0, 3, TextureImage [0] -> SIZEX,

TextureImage [0] -> Sizey, 0, GL_RGB, GL_UNSIGNED_BYTE,

TextureImage [0] -> DATA);

When you tell OpenGL to build a mipmapped texture, OpenGL tries to build different-sized, high quality textures. When you draw a mipmapped texture to the screen, OpenGL will select the BEST looking texture from the ones it built (texture with the most detail ) and draw it to the screen instead of resizing the Original Image (Which Causes Detail Loss) .// CREATE MIPMAPPED Texture

GlbindTexture (GL_Texture_2d, Texture [2]);

Gltexparameteri (GL_Texture_2D, GL_TEXTURE_MAG_FILTER,

GL_LINEAR);

Gltexparameteri (GL_Texture_2D, GL_TEXTURE_MIN_FILTER, / / ​​(NEW)

GL_LINEAR_MIPMAP_NEAREST

. The following line builds the mipmapped texture We're creating a 2D texture using three colors (red, maroon, amd blue) TextureImage [0] -.> SizeX is the bitmap's width, TextureImage [0] -> sizeY is the bitmap's height ., GL_RGB means we're using Red, Maroon, amd Blue colors in that order GL_UNSIGNED_BYTE means the data that makes the texture is made up of bytes, and TextureImage [0] -> data points to the bitmap data that we're building The Texture from.

Glubuild2DMIPMAPS (GL_Texture_2d, 3, // (NEW)

TextureImage [0] -> SIZEX,

TextureImage [0] -> Sizey, GL_RGB,

GL_unsigned_byte, TextureImage [0] -> DATA);

}

Creating Fogging Effects

We'll start by setting up all our variables needed to hold the information for fog The variable fogMode will be used to hold three types of fog:... GL_EXP, GL_EXP2, and GL_LINEAR I will explain the differences among these three later on The variables will start at the beginning of the code, after the line GLuint texture [3]. The variable fogfilter will be used to keep track of which fog type we will be using. The variable fogColor will hold the color we want the fog to be . (New)

Gluint fogmode [] = {gl_exp, gl_exp2,

GL_LINEAR}; // Storage for Three Types

// of fog

Gluint Fogfilter = 0; // Which fog to us

GLFLOAT FOGCOLOR [4] = {0.5F, 0.5F, // Fog Color

0.5F, 1.0F};

The drawglscene () Function Has The Following Code To Enable Fog Effects:

GlclearColor (0.5F, 0.5F, 0.5F, 1.0F); // We'll Clear to the THE

// color of the fog

// (MODIFIED)

GLFOGI (GL_FOG_MODE, FOGMODE [FOGFILTER]); // Fog Mode

GLFOGFV (GL_FOG_COLOR, FOGCOLOR); // SET FOG Color

GLFOGF (GL_FOG_DENSITY, 0.35F); // How Dense Will THE

// fog be

GLHINT (GL_FOG_HINT, GL_DONT_CARE); // Fog Hint Value

GLFOGF (GL_FOG_START, 1.0F); // Fog Start Depth

GLFOGF (GL_FOG_END, 5.0F); // Fog End Depth

Glenable (GL_FOG); // Enables GL_FOG

The above line, glEnable (GL_FOG) ;, is pretty much self explanatory It basically initializes the fog The line glFogi (GL_FOG_MODE, fogMode [fogfilter]);.... Establishes the fog filter mode Now, earlier we declared the array fogMode It .. held GL_EXP, GL_EXP2, and GL_LINEAR Here is when these variables come into play Let me explain each one: GL_EXP:. Basic rendered fog that fogs out all of the screen It does not give much of a fog effect, but gets the . job done on older PCs GL_EXP2: Is the next step up from GL_EXP This will fog out all of the screen; however, it will give more depth to the scene GL_LINEAR:. This is the best fog rendering mode Objects fade in and.. out of the fog much better glFogfv (GL_FOG_COLOR, fogcolor):... Sets the color of the fog The line glFogf (GL_FOG_DENSITY, 0.35f); establishes how dense the fog will be Increase the number and the fog becomes more dense; decrease IT and it becomes less dense. glhint (gl_fog_hint, gl_dont_care): Establishes the hint. I buy gl_dont_c Are, Because I Didn't Care About The Hint Value. Hint Value Can Be One of the Following Types:

GL_DONT_CARE: Lets OpenGL Choose The Kind of Fog (Per Vertex of Per Pixel) and an unknown formula. GL_NICEST: MAKES The Fog Per Pixel (Looks Good) GLFASTEST: MAKES The Fog Per Vertex (Faster, But Not AS Nice)

About the Author

Fatima Ahmed is in BS (Computer Science) Karachi University, a well-known university in Pakistan. Her interests are in writing technical articles for magazines and e-zines, surfing the net, making projects, and doing programming in different languages. Her articles CAN Be Found On this and other web sites. You can contact Her at: fatima_saffano2001@yahoo.com or fatima_bsku@yahoo.com.

References

Nehe's Game Programming Tutorials.Downloads

Download Source - 87 KB

转载请注明原文地址:https://www.9cbs.com/read-31922.html

New Post(0)