Vous êtes sur la page 1sur 44

Loading And Moving Through A 3D World

Acknowledgement
The satisfaction and happiness that accompanies the successful completion of any task would be incomplete without the mention of the people who made it possible. Many are responsible for the knowledge and experience I have gained during my project. I consider it my privilege to express my gratitude and respect to all those who guided, inspired and helped me in the completion of this project. I owe a debt of gratitude to all of them who were so generous with their time and expertise. I wish also to thank them for their warm hospitality. We have been strongly supported by our lectures and guides,Mr.NAGESH BABU,Mrs.ANURADHA S.G AND Ms.SWATHI .We are thankful for their valuable guidance & suggestions provided, without which successful completion of completion of our project wouldnt have been possible I would like to express my gratitude and thanks to my Principal Prof. L. Sharana Prabhu, and Dr. K. Karibasappa, Prof. & Head of Department, Department of Computer Science, Rao Bahadur Y. Mahabaleshwarappa Engineering College, Cantonment, Bellary, for their support through out the Project. We are grateful to our institution R.Y.M.E.C, Bellary with its very high Ideals & Inspirations for providing us the opportunity & infrastructure to carry out the project successfully. I also extend my sincere thanks and gratitude to my parents and friends for the enthusiasm they infused into me during my work and helping me in completing this project. I offer my regards and blessings to all of those who supported me in any respect during the completion of the project.

Project Associates

CHAITRA.R.G B.V.SWETHA
Deparment of Computer Science And Engineering 1

Loading And Moving Through A 3D World

SYNOPSIS
Title: Loading and Moving Through A 3D World. Aim: To load a 3D world from a data file, and move through the 3D world.This demo moves
us through a small room of rendered walls. Uses the arrow keys to move around. 3D world is basically a collection of sectors. A sector holds a series of polygons. A sector can be a room, a cube, or any enclosed volume. So a 3D world consists of sectors and sectors is consists of triangles and triangles is consists of vertex. The triangle is basically a polygon made up of vertices. We define each point on the triangle with its position in 3D space(x,y,z) as well as its texture co-ordinates(u,v). The world is loaded from disk which is more flexible. The type of data file to be used is text i.e, it loads the world by reading triangle coordinates from a text file. To get data from the file, first we create a new function called setupworld( ).We define the file as filein and open it for read only access. Readstr( ) function will read one meaning line of text into an initialized string. The sector data must be read. The rest of the world loading process will use the same process. We initialize the sector and read some data into it. Displaying worlds: Now we can load the sector into memory and display onto the screen. The user must be able to walk around and explore the world. Camera rotations and translations are made based on user keyboard input. to do this 1) Rotate and translate the camera positions according to user commands. 2) Rotate the world around the origin in the opposite direction of the camera rotation. 3) Translate the world in the opposite manner that the camera has been translated. Deparment of Computer Science And Engineering 2

Loading And Moving Through A 3D World Thus when either the left or right cursor key is pressed the rotation variables is incremented or decremented appropriately. When the forward or backward cursor key is pressed a new location for the camera is calculated. While running the program, buttons F, B, PgUp and PgDown can be pressed to see added effects. PgUp/Down simply tilts the camera up and down. The texture included is simply a mud texture.

Requirements:
OpenGL version 1.5 or higher

System Requirements:
WindowsXP Windows 2000 Microsoft Visual Studio 6.0

Deparment of Computer Science And Engineering

Loading And Moving Through A 3D World

TABLE OF CONTENTS

Page No Acknowledgements Synopsis 1. Preamble 1.1 Objective Of Study 1.2 Introduction 2. Analysis 2.1 Software Requirement Specification 2.2 Functional Requirements 2.3 External Interface Requirements 2.3.1 User Interface 2.4 Design Constraints 2.4.1 Software Constraints 2.4.2 Hardware Constraints 3. Design 3.1 Data Design 3.1.1 Data Definitions 3.2 Architectural Design 3.3 Procedural Design 3.4 Data Flow diagrams 4. Pseudo Code 5. Testing 5.1 System Testing 5.2 Unit Testing 5.3 Integrating Testing 6. Sample Outputs 7. Conclusion & Future Work 8. References 19 25 26 39 39 40 41 42 43 44 1 2 5 5 5 8 8 9 15 16 16 16 16 17 17 17 18

Deparment of Computer Science And Engineering

Loading And Moving Through A 3D World

1 Preamble
1.1 objective of study
To load a 3D world from a data file, and move through the 3D world. This demo moves us through a small room of rendered walls. Uses the arrow keys to move around.

1.2 Introduction
To load a 3D world from a data file, and move through the 3D world. 3D computer graphics are graphics that use a three-dimensional representation of geometric data that is stored in the computer for the purposes of performing calculations and rendering 2D images. Such images may be viewing for later play or for real-time. A 3D model is the mathematical representation of any three-dimensional object (either inanimate or living). A model is not technically a graphic until it is visually displayed. Due to 3D printing, 3D models are not confined to virtual space. A model can be displayed visually as a two-dimensional image through a process called 3D rendering, or used in non-graphical computer stimulations and calculations. This program is basically 3D world which is a collection of sectors. A sector holds a series of polygons. A sector can be a room, a cube, or any enclosed volume. So a 3D world consists of sectors and sectors is consists of triangles and triangles is consists of vertex. The triangle is basically a polygon made up of vertices. We define each point on the triangle with its position in 3D space(x,y,z) as well as its texture co-ordinates(u,v). The world is loaded from disk which is more flexible. The type of data file to be used is text i.e, it loads the world by reading triangle coordinates from a text file. To get data from the file, first we create a new function called setupworld( ).We define the file as filein and open it for read only access. Readstr( ) function will read one meaning line of text into an initialized string. The sector data must be read. The rest of the world loading process will use the same process. We initialize the sector and read some data into it.

Deparment of Computer Science And Engineering

Loading And Moving Through A 3D World The process of creating 3D computer graphics can be sequentially divided into three basic phases: 1. 3D modeling which describes the process of forming the shape of an object 2. Layout and Animation which describes the motion and placement of objects within a scene, and 3. 3D rendering which produces an image of an object.

Modeling

A 3D rendering with ray tracing and ambient occlusion using Blender and Yarfray The model describes the process of forming the shape of an object. The two most common sources of 3Dmodels are those originated on the computer by an artist or engineer using some kind of 3D modeling tool, and those scanned into a computer from real-world objects. Models can also be produced procedurally or via physical stimulation.

Layout and animation


Before objects are rendered, they must be placed (laid out) within a scene. This is what defines the spatial relationships between objects in a scene including location and size. Animation refers to the temporal description of an object, i.e., how it moves and deforms over time. Popular methods include keyframing, inverse kinematics, and motion capture, though many of these techniques are used in conjunction with each other. As with modeling, physical stimulation is another way.

Deparment of Computer Science And Engineering

Loading And Moving Through A 3D World

Rendering

During the 3D rendering step, the number of reflections light rays can take, as well as various other attributes, can be tailored to achieve a desired visual effect. Rendering converts a model into an image either by simulating light transport to get photorealistic images, or by applying some kind of style as in non-photorealistic rendering. The two basic operations in realistic rendering are transport (how much light gets from one place to another) and scattering (how surfaces interact with light). This step is usually performed using 3D computer graphics software or a 3D graphics API. The process of altering the scene into a suitable form for rendering also involves 3D projection image to be viewed in two dimensions which allows a three-dimensional

Deparment of Computer Science And Engineering

Loading And Moving Through A 3D World

2 Analysis
2.1 Software Requirements Specification Document Purpose
This SRS document is intended to provide a full listing of the product requirements for a fully operable 3D map editing program. This document will explicitly describe each function of the system, and it will identify any constraints, assumptions, or dependencies of the system. The primary target audience of this document is the developers of the system, Team Ratatosk. Others who may read this document include game developers using our system or anyone considering using our system.

Scope
The application under development is called Genesis. The name comes directly from its purpose which is to provide the user with a simple and intuitive way to build 3D virtual environments. Our product will provide basic viewing functionality but is not intended to be used as a 3D rendering application or game engine. Ideally the final product will have a rich file format that may be utilized in many different games and genres. The main benefit to using our application is that most (if not all) map editors on the market are highly specialized for a given game and are fairly complex to use. This means that a lot of time will be required to learn the editor as well as writing an importer for what is (often) a poorly documented file format. Our product will produce a content rich file format that is well documented making it applicable for many different genres. It will be easy to write code to support our application's file format. The ideal customer is one who has access to a game engine but does not want to spend the effort required to build a level editor. Our customer will benefit from using this tool over designing their own because of the time required to fully design, implement, and test an application of this type will be able to be spent creating content for their application. Further, we will provide a well thought out and documented file format that will allow those who wish to use this application for level design to select almost any game engine and will make the process of writing an environment importer for said engine fairly simple. Deparment of Computer Science And Engineering 8

Loading And Moving Through A 3D World

2.2 Functional Requirements

Create a new 3D world

The user needs to be able to create a new map that he may then begin editing. Without this, there would be nothing to edit. Inputs A size (in tiles) given by the user A default tile Outputs A new map of a chosen size. The size will be measured by the number of tiles in the width and length. All tiles will be standard size.

Save a created world


The user needs to be able to save any maps he has created. This includes saving all changes in elevation and textures, as well as any 3D objects that were placed. Inputs A created world including any 3D objects that were placed Outputs A map file defined by the genesis file format (.GFF)

Load a saved world

Deparment of Computer Science And Engineering

Loading And Moving Through A 3D World The user needs to be able to load any created world into the program. Inputs A map file saved to disk in the genesis file format. Outputs The world in a 3D view ready for editing and/or viewing. This will be useful to the users as it will allow them to use

Import 3D models into libraries.

Imported 3D models that can later be added to the world. Without these 3D models, the world would be simple, dull terrain. Since our application only supports terrain editing within the program, we must allow the user to import models created in other programs so that they may be seamlessly added to the world.

Inputs Th e i n p u t s w i l l b e t h e 3 D m o d e l s t h a t a r e b e i n g i m p o r t e d . Th e s e 3 D m o d e l s w i l l b e i n t h e 3 D S f i l e f o r m a t . Outputs Th e o u t p u t w i l l b e t h e m o d e l b e i n g a d d e d i n t o a l i s t ( a library). This library can be saved to disk and will that were added to it upon being opened.

Save library
The user should be able to save lists (libraries) of objects that he h a s i m p o r t e d f o r u s e i n h i s w o r l d . Th e s e l i b r a r i e s w i l l b e s a v e d a s Deparment of Computer Science And Engineering 10

Loading And Moving Through A 3D World simple lists of paths that point to the various objects in the file system. Inputs A user created library of 3D models or Textures Outputs A file that contains the list of these objects

Load library
The user should be able to load the libraries created in and saved in library of this document. Inputs The library file to load Outputs The application will load all models or textures associated with a given library.

Create resource archive


This will result in a file containing all resources used in a given world. Included will be the terrain, environment textures 3D models Inputs The textures associated with the map The trigger data The 3D models loaded on the map Outputs .gar file which contains all resources.

Deparment of Computer Science And Engineering

11

Loading And Moving Through A 3D World

Place 3D models in world


The user should be able to place 3D models that have been imported into their map. Inputs A 3D model from a model library. Outputs An instance of the 3D model placed into the map.

Filter Onscreen Objects


The user should be able to view certain subsets of all of the items that can be displayed on a map. These items include textures and 3D models. Inputs A boolean to specify if the user wishes to view 3D models. A boolean to specify if the user wishes to view textures Outputs. The 3D view without the items that the user has specified to filter.

Changing the view perspective The user should be able to move the camera's current position to view different portions of the world. This include both moving around the world and zooming in and out of the world. This will allow the world to be viewed as close as necessary to get the details of the world exactly how they want. The user will not be able to scroll completely off the world. Inputs User input on where to move or zoom. 12

Deparment of Computer Science And Engineering

Loading And Moving Through A 3D World Outputs The movement and zoom of the world.

Apply texture to tile(s) The user should be able to select the texture of each tile to allow greater customization. Inputs A texture to be applied. A tile to apply the texture to. Outputs The tile with the given texture applied.

Create a Project The user will want to be able to save collections of maps,3D model libraries, and texture libraries that are related to each other. This can be used to create a project for a game or to create a collection of levels with similar tilesets and 3D models. Inputs An initial map or new map. The name of the project. A project file location. Outputs The 3D view of the initial map with the ability to view all of the information in the project.

Save a Project

Deparment of Computer Science And Engineering

13

Loading And Moving Through A 3D World The user will wish to be able to save a project so that he can load it again the next time he runs the application. Inputs The project name. The maps in the project. The libraries in the project Outputs A project file containing the list of maps and the information for the libraries.

Load a Project
The user will wish to be able to load a project that he has previously saved. Inputs A project file. Outputs A 3D view of the first map in the project and all of the information and libraries are loaded.

Moving 3D Models
The user will wish to be able to move a 3D model on the x,y and z a x e s s o t h a t h e c a n p r e c i s e l y p l a c e t h e o b j e c t . Th e m o d e l c a n b e moved anywhere the user wishes. Inputs A 3D model. An amount to move the model. The axes to move the model on. Outputs 14

Deparment of Computer Science And Engineering

Loading And Moving Through A 3D World The 3D model moved in the direction(s) the user has selected.

S c a l i n g 3 D M od e l s The user will wish to be able to scale the size of the models. This allows for a map to have differently sized trees or buildings. The model can be scaled to any size the user wishes. Inputs A 3D model. Amount to scale the 3D model by. Outputs The 3D model resized by the amount specified by the user.

Rotating 3D Models
The user will wish to be able to rotate the models in the 3D world. Inputs A 3D model. Amount to rotate the 3D model by. Outputs The 3D model rotated by the amount specified by the user.

2.3 External Interface Requirements Deparment of Computer Science And Engineering 15

Loading And Moving Through A 3D World

The system will interface with the user through a GUI. The user will be able perform all the functions of the system by interacting with a visual r e p r e s e n t a t i o n o f a 3 D m a p . Th e y w i l l i n d i c a t e w h a t a c t i o n t h e y w a n t t o t a k e w h i l e u s i n g t h e a p p l i c a t i o n t h r o u gh k e y s t r o k e s . T h i s i n t e r f a c e w i l l be optimized by keeping the interface uncluttered and easy to understand. 2.3.1 User Interface Users of the World Wide Web typically access documents comprised of t e x t a n d i m a g e s , w i t h a c c e s s t o a u d i o a n d v i d e o . T h e 3 D e n v i r o n m en t s are equally viable and compelling "documents" of interest on the web, with applicability to architecture, education, engineering, advertising, entertainment, and more. Many computer users move through 3D worlds on a daily basis and have attained a certain savvy for navigating with s i m p l e k e y p a d c o m m a n d s a n d m o u s e g e s t u r e s . Th e u s e r w i l l u s e t h e mouse and keyboard to interface with the program. Viewing and interacting with 3D data can be significantly more complicated than viewing 2D text and graphics. Users need to examine 3D objects from different viewpoints and navigate through scenes to gain a better understanding of the data. An interface for the exploration of 3D data must provide adequate controls for the user to inspect objects and scenes. For this purpose the user interface has been developed.

2.4 Design Constraints 2.4.1 Software constraints


The project runs on visual basic c++ with opengl software.

2.4.2 Hardware constraints


The hardware requirements are very minimal

Deparment of Computer Science And Engineering

16

Loading And Moving Through A 3D World

3 Design
3.1 Data Design 3.1.1 Data Defination This program is basically 3D world which is a collection of sectors. A sector holds a series of polygons. A sector can be a room, a cube, or any enclosed volume. So a 3D world consists of sectors and sectors is consists of triangles and triangles is consists of vertex. The triangle is basically a polygon made up of vertices. We define each point on the triangle with its position in 3D space(x,y,z) as well as its texture co-ordinates(u,v). AUX_RGBImageRec *LoadBMP( ):This function is used to load the image from a file. File was must exist. We load the bit map and return a pointer. int LoadGLTextures():This function loads the bitmap and covert to textures. Status variable is used to indicate the status and initially this status is set to false. We use AUX_RGBImageRec *LoadBMP( ) to create a storage space for the texture. GLvoid ReSizeGLScene( ):It is used to resize and initialize the GL window . int InitGL( ):It is used for setting up the opengl. int DrawGLScene( ):This function is used for drawing. Readstr( ):Function will read one meaning line of text into an initialized string. Deparment of Computer Science And Engineering 17

Loading And Moving Through A 3D World setupworld( ):This function is used to get data from the file, we define the file as filein and open it for read only access.

3.2 Architecture Design

Right handed co-ordinate system

Camera system axis

Deparment of Computer Science And Engineering

18

Loading And Moving Through A 3D World

position

orientation

3.3 Procedural design


Moving in a 3D world Camera
The project is based on how to move in a 3D environment. The control movement is by using keyboard and mouse. It uses matrices transformations. The camera implemented here is semi-advanced one, it support all of this features : - forward, backward, upward, downward, left and right displacement - x (look up/down) and y(head rotation) rotation - Time based movement - 3rd Person camera - Actions : Walk, Run, Duck, Free fall/Jump (with gravity). Deparment of Computer Science And Engineering 19

Loading And Moving Through A 3D World

Mechanical Basis
Mechanical is based on 1. Co-ordinate system and 2. Rotations. It will be usefull for the position and the orientation of the camera (i.e the viewer) in relation to a fixed coordinate system.

Coordinate system

A coordinate system is composed of 3 vectors X, Y and Z:

Right-handed Coordinate system Suppose that we have a fixed coordinate system. To position an object in this coordinate system, we have to know the position and the orientation of this object in the fixed system. This defines a second coordinate system relative associated to this object with X', Y' and Z' vectors. The object considered is fix in this axis system. In the following, the object considered is a camera. So, the camera's position defines the eye position. The orientation of the camera defines the view direction (Z' vector). X', Y' and Z' vectors are the camera coordinate system.

Deparment of Computer Science And Engineering

20

Loading And Moving Through A 3D World Here is represented the fix axis system (X,Y,Z) and the (moving) axis system associated with the camera (X',Y',Z') :

Camera system axis

The camera coordinate system is obtained by translating the fixed axis system (position of the camera). We have a temporary coordinate system (X1, Y1, Z1):

Position

Then, with a rotated of this temporary axis system, camera and we have the camera co-ordinate system:

Deparment of Computer Science And Engineering

21

Loading And Moving Through A 3D World

Orientation

We use Z' vector for the view direction (forward). The Y' vector for the upward vector and X' for the side vector (left because right-handed coordinate system).

Coordinate system properties


The coordinate system has two properties 1. 2. 1. Vectors X=Y^Z Y=Z^X Z=X^Y ^ represent the cross product (vectorial product). orthogonal orthonormal orthogonal are orthogonal (perpendicular) when following egalities are true:

2. orthonormal
The norm (magnitude) of the 3 vectors that define a coordinate system is always 1. ||X|| = ||Y|| = ||Z|| = 1. From above properties we can note that, if we know two vectors of magnitude 1 and if the vectors are orthogonal, we can calculate the third vector to form an (orthogonal) coordinate system.

Deparment of Computer Science And Engineering

22

Loading And Moving Through A 3D World

Coordinate system representation


There are two ways to work with coordinate system for the storage of his position/orientation. We need to store the camera position (ie the center of the coordinate system) in a vector (camX, camY, camZ). For the orientation : - either store rotation angles.

- or store X', Y' and Z' vectors represented above (or just two due to the orthogonal property,
see above).

Basic function of a camera


The basic functions of a camera are: 1. 2. 3. Move forward / backward. Move on its sides (ie Strafe). Turn around up vector.

For a better camera, we will also add these features: 1. Move upward / downward. 2. Turn around side vector (look at the ground/sky). 3. Time based movement (Advanced part). 4. Action like walking, running, jumping. (Advanced part)

Basic function needed by all camera: 1. 2. translation and rotation

Notations Notations used are: Fixed coordinate system (X, Y, Z) Camera coordinate system (X', Y', Z') New camera coordinate system (X'', Y'', Z'') obtain after a transformation. A vector V=(v1, v2, v3) expressed in the fixed coordinate system (X, Y, Z) can be written like this : Deparment of Computer Science And Engineering 23

Loading And Moving Through A 3D World V = v1.X + v2.Y + v3.Z = |v1| |v2| |v3| v1, v2 and v3 are scalars (number) -> Lower case X, Y, Z are vectors -> Upper case

Rotation transformation
Suppose this rotation around x vector:

X Rotation There is an easy way to represent this rotation: using matrices. Effectively, there are predefined matrices to represent a rotation on an axis. For example, the rotation around the x axis is represented by Rx (matrix representing the transformation from original state (X,Y,Z) to final state (X',Y',Z')) : [Rx] = | 1 0 0 | is the rotation angle | 0 cos sin | | 0 -sin cos | Applying this transformation give these formulas: (X',Y',Z') = [Rx] * (X,Y,Z) ie X' = 1.X + 0.Y + 0.Z = X ( and X = X' Y = cos.Y'-sin.Z' 24 Y' = 0.X + cos.Y + sin.Z = cos.Y+sin.Z Deparment of Computer Science And Engineering

Loading And Moving Through A 3D World Z' = 0.X - sin.Y + cos.Z = -sin.Y+cos.Z Z = sin.Y'+cos.Z' )

There are similar matrices for y and z rotation : [Ry] = | cos 0 -sin | | 0 1 0 | | sin 0 cos | [Rz] = | cos sin 0 | | -sin cos 0 | | 0 0 1|

Translation transformation
To translate the camera from a displacement experimented in the fixed coordinate system, we simply add the current position and the displacement. Because, the position of the camera is expressed in the fixed coordinate system If the displacement is expressed in the camera coordinate system (example, move forward). We first have to express the displacement in the fixed coordinate system. We can move in a camera using arrow keys.

3.4 Data Flow Diagrams

Deparment of Computer Science And Engineering

25

Loading And Moving Through A 3D World

4 Pseudocode
#include <windows.h> #include <math.h> #include <stdio.h> #include <gl\gl.h> #include <gl\glu.h> #include <gl\glaux.h> // Header File For Windows // Math Library Header File // Header File For Standard Input/Output // Header File For The OpenGL32 Library // Header File For The GLu32 Library // Header File For The Glaux Library

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 bool bool bool bool bool bool keys[256]; active=TRUE; fullscreen=TRUE; blend; bp; fp; // Array Used For The Keyboard Routine // Window Active Flag Set To TRUE By Default // Fullscreen Flag Set To Fullscreen Mode By Default // Blending ON/OFF // B Pressed? // F Pressed?

const float piover180 = 0.0174532925f; float heading; float xpos; float zpos; GLfloat yrot; GLfloat walkbias = 0; GLfloat walkbiasangle = 0; GLfloat lookupdown = 0.0f; GLfloat z=0.0f; GLuint filter; GLuint texture[3]; typedef struct tagVERTEX { float x, y, z; float u, v; } VERTEX; typedef struct tagTRIANGLE { VERTEX vertex[3]; } TRIANGLE; typedef struct tagSECTOR { int numtriangles; TRIANGLE* triangle; Deparment of Computer Science And Engineering 26 // Y Rotation

// Depth Into The Screen // Which Filter To Use // Storage For 3 Textures

Loading And Moving Through A 3D World } SECTOR; SECTOR sector1; LRESULT // Our Model Goes Here:

CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

void readstr(FILE *f,char *string) { do { fgets(string, 255, f); } while ((string[0] == '/') || (string[0] == '\n')); return; } void SetupWorld() { float x, y, z, u, v; int numtriangles; FILE *filein; char oneline[255]; filein = fopen("data/world.txt", "rt"); readstr(filein,oneline); sscanf(oneline, "NUMPOLLIES %d\n", &numtriangles); sector1.triangle = new TRIANGLE[numtriangles]; sector1.numtriangles = numtriangles; for (int loop = 0; loop < numtriangles; loop++) { for (int vert = 0; vert < 3; vert++) { readstr(filein,oneline); sscanf(oneline, "%f %f %f %f %f", &x, &y, &z, &u, &v); sector1.triangle[loop].vertex[vert].x = x; sector1.triangle[loop].vertex[vert].y = y; sector1.triangle[loop].vertex[vert].z = z; sector1.triangle[loop].vertex[vert].u = u; sector1.triangle[loop].vertex[vert].v = v; } } fclose(filein); return; } AUX_RGBImageRec *LoadBMP(char *Filename) { FILE *File=NULL; if (!Filename) { Deparment of Computer Science And Engineering 27 // Loads A Bitmap Image // File Handle

return NULL; } File=fopen(Filename,"r");

Loading And Moving Through A 3D World // If Not Return NULL // Check To See If The File Exists // Does The File Exist? // Close The Handle / / If Load Failed Return NULL

if (File) { fclose(File); return auxDIBImageLoad(Filename); } return NULL; } int LoadGLTextures() { int Status=FALSE; AUX_RGBImageRec *TextureImage[1]; Texture memset(TextureImage,0,sizeof(void *)*1);

// Status Indicator // Create Storage Space For The // Set The Pointer To NULL

if (TextureImage[0]=LoadBMP("Data/Mud.bmp")) { Status=TRUE; // Set The Status To TRUE glGenTextures(3, &texture[0]); glBindTexture(GL_TEXTURE_2D, texture[0]); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, 3, TextureImage[0]->sizeX, TextureImage[0]->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[0]->data); 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); glBindTexture(GL_TEXTURE_2D, texture[2]); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMA P_NEAREST); Deparment of Computer Science And Engineering 28

Loading And Moving Through A 3D World gluBuild2DMipmaps(GL_TEXTURE_2D, 3, TextureImage[0]->sizeX, TextureImage[0]>sizeY, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[0]->data); } if (TextureImage[0]) // If Texture Exists { if (TextureImage[0]->data) // If Texture Image Exists { free(TextureImage[0]->data); } free(TextureImage[0]); } return Status; } GLvoid ReSizeGLScene(GLsizei width, GLsizei height) // Resize And Initialize The GL Window { if (height==0) { height=1; } glViewport(0,0,width,height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } int InitGL(GLvoid) { if (!LoadGLTextures()) { return FALSE; } glEnable(GL_TEXTURE_2D); glBlendFunc(GL_SRC_ALPHA,GL_ONE); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClearDepth(1.0); glDepthFunc(GL_LESS); glEnable(GL_DEPTH_TEST); glShadeModel(GL_SMOOTH); glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST); SetupWorld(); return TRUE; } Deparment of Computer Science And Engineering 29 // Return The Status // Free The Image Structure

Loading And Moving Through A 3D World int DrawGLScene(GLvoid) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); GLfloat x_m, y_m, z_m, u_m, v_m; GLfloat xtrans = -xpos; GLfloat ztrans = -zpos; GLfloat ytrans = -walkbias-0.25f; GLfloat sceneroty = 360.0f - yrot; int numtriangles; glRotatef(lookupdown,1.0f,0,0); glRotatef(sceneroty,0,1.0f,0); glTranslatef(xtrans, ytrans, ztrans); glBindTexture(GL_TEXTURE_2D, texture[filter]); numtriangles = sector1.numtriangles; for (int loop_m = 0; loop_m < numtriangles; loop_m++) { glBegin(GL_TRIANGLES); glNormal3f( 0.0f, 0.0f, 1.0f); x_m = sector1.triangle[loop_m].vertex[0].x; y_m = sector1.triangle[loop_m].vertex[0].y; z_m = sector1.triangle[loop_m].vertex[0].z; u_m = sector1.triangle[loop_m].vertex[0].u; v_m = sector1.triangle[loop_m].vertex[0].v; glTexCoord2f(u_m,v_m); glVertex3f(x_m,y_m,z_m); x_m = sector1.triangle[loop_m].vertex[1].x; y_m = sector1.triangle[loop_m].vertex[1].y; z_m = sector1.triangle[loop_m].vertex[1].z; u_m = sector1.triangle[loop_m].vertex[1].u; v_m = sector1.triangle[loop_m].vertex[1].v; glTexCoord2f(u_m,v_m); glVertex3f(x_m,y_m,z_m); x_m = sector1.triangle[loop_m].vertex[2].x; y_m = sector1.triangle[loop_m].vertex[2].y; z_m = sector1.triangle[loop_m].vertex[2].z; u_m = sector1.triangle[loop_m].vertex[2].u; v_m = sector1.triangle[loop_m].vertex[2].v; glTexCoord2f(u_m,v_m); glVertex3f(x_m,y_m,z_m); glEnd(); } return TRUE; } GLvoid KillGLWindow(GLvoid) { if (fullscreen) { Deparment of Computer Science And Engineering 30

Loading And Moving Through A 3D World ChangeDisplaySettings(NULL,0); ShowCursor(TRUE); } if (hRC) { if (!wglMakeCurrent(NULL,NULL)) { MessageBox(NULL,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION); } if (!wglDeleteContext(hRC)) MessageBox(NULL,"ReleaseRenderingContextFailed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION); } hRC=NULL; } if (hDC && !ReleaseDC(hWnd,hDC)) { MessageBox(NULL,"ReleaseDeviceContextFailed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION); hDC=NULL; } if (hWnd && !DestroyWindow(hWnd)) { MessageBox(NULL,"CouldNotReleasehWnd.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION); hWnd=NULL; } if (!UnregisterClass("OpenGL",hInstance)) { MessageBox(NULL,"CouldNotUnregisterClass.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION); hInstance=NULL; } } BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag) { GLuint PixelFormat; WNDCLASS wc; DWORD dwExStyle; DWORD dwStyle; WindowRect; WindowRect.left=(long)0; // Set Left Value To 0 WindowRect.right=(long)width; Deparment of Computer Science And Engineering 31

WindowRect.top=(long)0; WindowRect.bottom=(long)height; fullscreen=fullscreenflag;

Loading And Moving Through A 3D World // Set Top Value To 0 // Set The Global Fullscreen Flag

hInstance= GetModuleHandle(NULL); wc.style= CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc= (WNDPROC) WndProc; wc.cbClsExtra = 0; wc.cbWndExtra= 0; wc.hInstance = hInstance; wc.hIco= LoadIcon(NULL, IDI_WINLOGO); wc.hCursor= LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = NULL; wc.lpszMenuName = NULL; wc.lpszClassName = "OpenGL"; if (!RegisterClass(&wc)) { MessageBox(NULL,"FailedToRegisterTheWindowClass.","ERROR",MB_OK| MB_ICONEXCLAMATION); return FALSE; } if (fullscreen) { DEVMODE dmScreenSettings; memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); dmScreenSettings.dmSize=sizeof(dmScreenSettings); dmScreenSettings.dmPelsWidth = width; dmScreenSettings.dmPelsHeight = height; dmScreenSettings.dmBitsPerPel = bits; dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH| DM_PELSHEIGHT; if(ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)! =DISP_CHANGE_SUCCESSFUL) { if (MessageBox(NULL,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card.UseWindowedModeInstead?","NeHeGL",MB_YESNO| MB_ICONEXCLAMATION)==IDYES) { fullscreen=FALSE; Fullscreen = FALSE } else { MessageBox(NULL,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP); return FALSE; } } } Deparment of Computer Science And Engineering 32

Loading And Moving Through A 3D World if (fullscreen) { dwExStyle=WS_EX_APPWINDOW; dwStyle=WS_POPUP; ShowCursor(FALSE); } else { dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; dwStyle=WS_OVERLAPPEDWINDOW; } AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle); if (!(hWnd=CreateWindowEx(dwExStyle,WindowRect.right-WindowRect.left, WindowRect.bottom-WindowRect.top,hInstance,NULL))) { KillGLWindow(); MessageBox(NULL,"WindowCreationError.","ERROR",MB_OK| MB_ICONEXCLAMATION); return FALSE; } static PIXELFORMATDESCRIPTOR pfd= { sizeof(PIXELFORMATDESCRIPTOR),1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL|PFD_DOUBLEBUFFER,PFD_TYPE_RGBA, 0, 0, 0, 0, 0, 0, 0,0,0,0, 0, 0, 0,16,0,0,PFD_MAIN_PLANE, 0,0, 0, 0 }; if (!(hDC=GetDC(hWnd))) { KillGLWindow(); MessageBox(NULL,"Can'tCreateAGLDeviceContext.","ERROR",MB_OK| MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd))) { KillGLWindow(); MessageBox(NULL,"Can'tFindASuitablePixelFormat.","ERROR",MB_OK| MB_ICONEXCLAMATION); return FALSE; } if(!SetPixelFormat(hDC,PixelFormat,&pfd)) { KillGLWindow(); MessageBox(NULL,"Can'tSetThePixelFormat.","ERROR",MB_OK| MB_ICONEXCLAMATION); return FALSE; // Return FALSE } Deparment of Computer Science And Engineering 33

Loading And Moving Through A 3D World if (!(hRC=wglCreateContext(hDC))) { KillGLWindow(); MessageBox(NULL,"Can'tCreateAGLRenderingContext.","ERROR",MB_OK| MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if(!wglMakeCurrent(hDC,hRC)) { KillGLWindow(); MessageBox(NULL,"Can'tActivateTheGLRenderingContext.","ERROR",MB_OK| MB_ICONEXCLAMATION); return FALSE; // Return FALSE } ShowWindow(hWnd,SW_SHOW); SetForegroundWindow(hWnd); SetFocus(hWnd); ReSizeGLScene(width, height); if (!InitGL()) { KillGLWindow(); MessageBox(NULL,"InitializationFailed.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } return TRUE; } LRESULT CALLBACK WndProc( HWND wParam,LPARAM lParam) { switch (uMsg) { case WM_ACTIVATE: { if (!HIWORD(wParam)) { active=TRUE; } else { active=FALSE; } return 0; } case WM_SYSCOMMAND: { switch (wParam) { case SC_SCREENSAVE: Deparment of Computer Science And Engineering hWnd, UINT uMsg, WPARAM

// Check Minimization State // Program Is Active

34

Loading And Moving Through A 3D World case SC_MONITORPOWER: return 0; } break; // Exit } case WM_CLOSE: { PostQuitMessage(0); // Send A Quit Message return 0; // Jump Back } case WM_KEYDOWN: { keys[wParam] = TRUE; // If So, Mark It As TRUE return 0; // Jump Back } case WM_KEYUP: { keys[wParam] = FALSE; // If So, Mark It As FALSE return 0; // Jump Back } case WM_SIZE: { ReSizeGLScene(LOWORD(lParam),HIWORD(lParam)); return 0; // Jump Back } } return DefWindowProc(hWnd,uMsg,wParam,lParam); } int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow) { MSG msg; BOOL done=FALSE; if(MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?","Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO) { fullscreen=FALSE; } if (!CreateGLWindow("Lionel Brits & NeHe's 3D World Tutorial",640,480,16,fullscreen)) { return 0; } while(!done) // Loop That Runs While done=FALSE { if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) { if (msg.message==WM_QUIT) { Deparment of Computer Science And Engineering 35

Loading And Moving Through A 3D World done=TRUE; } else { TranslateMessage(&msg); // Translate The Message DispatchMessage(&msg); // Dispatch The Message } } else { DrawGLScene(); if ((active && !DrawGLScene()) || keys[VK_ESCAPE]) { done=TRUE; } else { SwapBuffers(hDC); if (keys['B'] && !bp) { bp=TRUE; blend=!blend; if (!blend) { glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST); } else { glEnable(GL_BLEND); glDisable(GL_DEPTH_TEST); } } if (!keys['B']) { bp=FALSE; } if (keys['F'] && !fp) { fp=TRUE; filter+=1; if (filter>2) { filter=0; } } if (!keys['F']) { fp=FALSE; Deparment of Computer Science And Engineering 36

Loading And Moving Through A 3D World } if (keys[VK_PRIOR]) { z-=0.02f; } if (keys[VK_NEXT]) { z+=0.02f; } if (keys[VK_UP]) { xpos -= (float)sin(heading*piover180) * 0.05f; zpos -= (float)cos(heading*piover180) * 0.05f; if (walkbiasangle >= 359.0f) { walkbiasangle = 0.0f; } else { walkbiasangle+= 10; } walkbias = (float)sin(walkbiasangle * piover180)/20.0f; } if (keys[VK_DOWN]) { xpos += (float)sin(heading*piover180) * 0.05f; zpos += (float)cos(heading*piover180) * 0.05f; if (walkbiasangle <= 1.0f) { walkbiasangle = 359.0f; } else { walkbiasangle-= 10; } walkbias = (float)sin(walkbiasangle * piover180)/20.0f; } if (keys[VK_RIGHT]) { heading -= 1.0f; yrot = heading; } if (keys[VK_LEFT]) { heading += 1.0f; yrot = heading; } if (keys[VK_PRIOR]) { Deparment of Computer Science And Engineering 37

Loading And Moving Through A 3D World lookupdown-= 1.0f; } if (keys[VK_NEXT]) { lookupdown+= 1.0f; } if (keys[VK_F1]) // Is F1 Being Pressed? { keys[VK_F1]=FALSE; // If So Make Key FALSE KillGLWindow(); // Kill Our Current Window fullscreen=!fullscreen; if (!CreateGLWindow("Lionel Brits & NeHe's 3D World Tutorial",640,480,16,fullscreen)) { return 0; // Quit If Window Was Not Created } } } } } KillGLWindow(); return (msg.wParam); }

5 Testing
5.1 SYSTEM TESTING

Deparment of Computer Science And Engineering

38

Loading And Moving Through A 3D World System testing is a collection of tests designed to verify that a program or system of programs is ready for production. As a rule, system testing t a k e s , a s i t s i n p u t , a l l o f t h e " i n t e g r a t e d " s o f t w a r e c o m p o n en t s t h a t h a v e successfully passed and also the software system itself integrated with any applicable hardware system(s). The purpose of integration testing is to detect any inconsistencies between integrated together (called the software units that are or between any of the assemblages)

assemblages and the hardware. System testing is a more limiting type of testing; it seeks to detect defects both within the "inter-assemblages" and also within the system as a whole. SYSTEM TESTING

UNIT Testing

INTEGRATION Testing

During testing, tried to make sure that the product does exactly what is supposed to do. Testing is the final verification and validation activity within the organization itself. In the testing stage, try to achieve the following goals. Affirm the quality of the product, to find and eliminate any residual errors from previous stages. Validate the software as a solution to the original problem, to demonstrate the presence of all specified functionality in the product, to estimate the operational reliability of the system. The different stages of Testing:: Unit testing Integration testing

5.2 UNIT TESTING


Deparment of Computer Science And Engineering 39

Loading And Moving Through A 3D World Unit testing is a procedure used to validate that individual unit of is working properly. A unit is the smallest testable part of an application. In a unit may be an individual program, function, procedure etc, while the smallest unit is always a Class; which may be a base/super class, abstract class or derived/child class. Units are distinguished from in that modules are typically made up of units.

This program has been tested and found to be working correctly.

5.3 INTEGRATING TESTING


Integration testing is the phase of in which individual software modules are combined and tested as a group. It follows and proceeds. Integration Deparment of Computer Science And Engineering 40

testing

takes

as

its

input

Loading And Moving Through A 3D World that has been, groups them in larger

aggregates, applies tests defined in integration to those aggregates, and delivers as its output the integrated system ready for.

Deparment of Computer Science And Engineering

41

Loading And Moving Through A 3D World

6 Sample outputs

7 Conclusion and future work

Deparment of Computer Science And Engineering

42

Loading And Moving Through A 3D World T h i s p r o j e c t i s i m p l e m e n t e d u s i n g C a n d C + + l a n g u a g e . Th e p r o j e c t helps us to analyze how we can use the different standard functions for creating the animated world and can be used for making a gaming package. Creating a 3D world with geometric models or multiple images are common techniques in practices today. Adding 3D Objects to the game is a fairly simple process once comfortable working in the 3D coordinate system. It dumps the texture coordinates and position of vertices into the structure and then simply renders them. The project is to design and develop a 3D world using OpenGL the p r o j e c t d e a l s w i t h l o a d i n g t h e 3 D w o r l d a n d m o v i n g t h r o u gh i t . O u r p r o j e c t c a n s i m u l a t e v i e w i n g a n d w a l k i n g i n 3 D e n v i r o n m en t u s i n g arrow keys. We can even include some added effects to work. It need to be interactive, three-dimensional, have some sort of c h a l l e n g i n g g o a l s , a n d b e f u n t o u s e . Th e g o a l o f t h i s p r o j e c t i s t o g i v e a practical experience to ground the understanding of computer graphics. By the end of the project we should be able to confidently create 3D user interfaces to many different computer applications and be able to integrate 3D interaction into those interfaces.

8 References
www.google.com 1. Moving in A 3D world- camera. 43

Deparment of Computer Science And Engineering

2. 3. 1. 1. 2. 3.

Loading And Moving Through A 3D World External interface requirements. Testing. Introduction. Pseudocode. Synopsis. Data Definitions.

Wikipedia www.nehe.gamedev.net

Deparment of Computer Science And Engineering

44

Vous aimerez peut-être aussi