Title: Advanced Game Technology CMPCD3026 CMPSEM044
1Advanced Game TechnologyCMPCD3026-CMPSEM044
Abdennour El Rhalibi Room 723 a.elrhalibi_at_livjm.ac
.uk
2Course Details (Attempt)
- 3D Game Engines Components
- DirectX D3D, 3D Modelling and Rendering
- Recap
- Meshes, Level Loading and Editing
- Terrain Rendering and LOD
- Camera Setting and Animation
- Spatial Data structure BSP and PVS
- NPC Behaviour and 3D PathFinding A, Flocking,
Scripting - 3D Collision Detection and Response
- Shading languages
- Game networking Issues Architecture, Protocol,
Event Synchronisation - Introduction to Console Programming
3Recap. to DirectX
- Resources, Initializing the Render State,
- and Rendering
4Program Flow
- This is not just applicable to DirectX.
main()
begin
resources
Models, textures, sounds, etc.
acquire
setup state
Camera, Alpha, Lighting, etc.
update
Apply changes to your world.
render
render
Project your world onto the screen.
release
resources
Free resources previously acquired.
fin
return 0
5Program Flow
begin
Main loop Loops once per frame
resources
acquire
setup state
update
Resources Infrequent loop when important changes
(popup, change resolution, monitor, etc)
render
render
release
resources
fin
6DXUT
- Framework that allows you to program in DirectX
without all the Win32 stuff. - Win32 HWND
- DirectX Device Enumeration
- Compatibility checks
- Found in DirectX SDK Sample Browser.
- http//msdn.microsoft.com/library/default.asp?url
/archive/en-us/directx9_c_Aug_2005/directx/graphic
s/Reference/DXUTReference/DXUTReference.asp
7In DXUT
WinMain() // done for you
begin
resources
acquire
OnResetDevice()
setup state
update
OnFrameMove()
render
render
OnFrameRender()
release
resources
OnLostDevice()
fin
return 0 // done for you
8Polygons
- A polygon is a closed 3-D figure defined by at
least 3 vertices. - A polygon can have any number of vertices, but
the most useful to us is the triangle. - The three vertices that make up a triangle are
guaranteed to be coplanar which makes rendering
MUCH more efficient. - You can compose any mesh from a set of triangles,
even smooth objects. - Triangles are the (current) standard way of
rendering objects, for the most part. - Each vertex stores several pieces of information.
Among the most important are - Position in our 3-dimensional world.
- Normal
- Color
- Texture Coordinates
9Meshes
- What is a mesh?
- Collection of vertices that define
- Positions
- Normals
- Other
- What is a mesh to a DirectX programmer?
- Store above data in special memory given to you
by DirectX. - Special suited for graphics card use.
10Meshes in DirectX
- What it looks like.
- ID3DXMesh g_pMesh //declare our type
- Where do meshes come from?
- D3DXCreateBox( pd3dDevice, width, length, height,
g_pMesh) - Device given to you by DXUT
- Width x length x height
- g_pMesh pass a pointer to the pointer to your
mesh. - How do I get rid of it?
- g_pMesh-gtRelease()
11Matrices!
- Three types of matrices
- WORLD transformation matrix
- Translation
- Rotation
- Scale
- VIEW
- Describes what you are looking at.
- PROJECTION
- How things are transformed onto the 2D screen.
12Render State
- The Device is the object in DirectX that holds
all of the render state information. - The render states are set and will stay until
something happens (or you change it). - Hundreds of render states but we are going to
focus on the most important.
13Setting Up The Camera
- Need to set up VIEW and PROJECTION matrices.
- Get DirectX to make them for you based on minimal
input parameters. - // define our view and projection matrices
- D3DXMATRIX view
- D3DXVECTOR3 eye(0,0,-5)
- D3DXVECTOR3 at(0,0,0)
- D3DXVECTOR3 up(0,1,0)
- D3DXMatrixLookAtLH(view, eye, at, up)
- //Need to specify
- // - the field of view (how much of the scene we
can see) - // - view aspect ratio (image width height ratio)
- // - distance to front clipping plane
- // - distance to back clipping plane
- D3DXMATRIX proj
- D3DXMatrixPerspectiveFovLH(proj, D3DX_PI / 4.0f,
4.0f/3 , 1.0f, 100.0f) - // actually set the matrices to the device
- pd3dDevice-gtSetTransform(D3DTS_VIEW, view)
14In DXUT
WinMain() // done for you
begin
resources
acquire
OnResetDevice()
setup state
update
OnFrameMove()
render
render
OnFrameRender()
release
resources
OnLostDevice()
fin
return 0 // done for you
15Loading Meshes From a File
- DirectX uses a standard .X file format for
loading in mesh data. This is not the only way,
just the easiest. - D3DXLoadMeshFromX( boxmesh.x, D3DX_SYSTEMMEM,
pd3dDevice, NULL, NULL, NULL, NULL, g_pMesh ) - Once we have our mesh loaded we can use it the
same as before.
16Meshes Summary
- What was a mesh?
- Collection of vertices.
- Vertices store information such as position,
normal, and texture coordinates. - Stores other properties such as materials.
- What it looked like in code
- ID3DXMesh g_pMesh //declare our type... in
device_reset() - D3DXCreateBox( pd3dDevice, width, length, height,
g_pMesh, NULL) - g_pMesh-gtDrawSubset(0) //in render()
- g_pMesh-gtRelease() // in device_lost()
17Rendering
- Take something and throw it at the screen
- How do we throw our mesh at the screen??
- g_pMesh-gtDrawSubset(0)
18Where do we go from here?
- Transformations / Movement
- Lighting
- Texturing
- Animation
- Input
- Shaders
- And everything else in the game
19Matrix Transformations
- Transformations are used to convert geometry from
one coordinate space to another. A coordinate
space basically defines what our origin and three
axes are. - You can transform any vector (x, y, z) into
another vector (x', y', z') using a 4 by 4
matrix. - These can be multiplied together in sequence to
convert the vector through several coordinate
spaces. - This is one of the most powerful things in
computer graphics, as everything is based off
these principles.
20World Transformation
- The positions and normals that are stored inside
of a mesh are considered to be in model space
where each vertex is defined relative to the
models local origin. - A world transformation converts coordinates from
model space to world space, where vertices are
defined relative to an origin common to all the
objects in a scene. - So basically a world transformation puts a model
into the world. - The world transformation can include any
combination of translations, rotations, and
scalings. - You can combine the matrices that produce these
effects into a single matrix to calculate several
transformations all at once. - Since the order of multiplication matters,
generally you will do - world scale rotation translation
21World Transformations
- Translation
- D3DXMatrixTranslation(D3DXMATRIX matrix, float
x, float y, float z) - Scaling
- D3DXMatrixScaling(D3DXMATRIX matrix, float sx,
float sy, float sz) - Rotation
- D3DXMatrixRotationX(D3DXMATRIX matrix, float
angle) - D3DXMatrixRotationY(D3DXMATRIX matrix, float
angle) - D3DXMatrixRotationZ(D3DXMATRIX matrix, float
angle) - D3DXMatrixRotationAxis(D3DXMATRIX matrix,
D3DXVECTOR3 vector, float angle) - An Example
- //rotate everything we render around the X axis
by Pi/2 - D3DXMATRIX rot
22Lighting
- Lighting is used to illuminate objects in a
scene. - When lighting is enabled in DirectX, the color of
each vertex is calculated for you based on a
combination of - The diffuse and specular colors at the vertex.
- The current material color and the texture, if
one is set. - The light sources color and intensity and the
scene's ambient light level. - Materials
- How the light reflects off a surface.
- Direct light and ambient light levels define the
light that is reflected. - Required if lighting is enabled.
23Turning on Lighting in DirectX
//Define our light and enable it D3DLIGHT9
d3dLight // Initialize the structure. ZeroMemory
(d3dLight, sizeof(d3dLight)) // Set up a white
point light. d3dLight.Type D3DLIGHT_POINT d3dLi
ght.Diffuse.r 1.0f d3dLight.Diffuse.g
1.0f d3dLight.Diffuse.b 1.0f //Position the
Light d3dLight.Position.x 0.0f d3dLight.Positio
n.y 100.0f d3dLight.Position.z -100.0f //
Don't attenuate. d3dLight.Attenuation0 1.0f
d3dLight.Range 150.0f // Set the
property information for the first
light. pd3dDevice-gtSetLight(0, d3dLight) //actu
ally enable the light now pd3dDevice-gtLightEnable(
0, true)
This is just for diffuse light but would be
similar for ambient and specular.
- //Define our material
- D3DMATERIAL9 mat
- // Set diffuse to a light blue
- mat.Diffuse.r 0.0f
- mat.Diffuse.g 0.5f
- mat.Diffuse.b 1.0f
- mat.Diffuse.a 1.0f
- //set ambient and specular
- //
- //set the material to the device
- //(stays until changed)
- pd3dDevice-gtSetMaterial(mat)
24Lighting Some More
- There are also different types of lights
- Point (the one we used)
- Spot
- Directional
- This is a very simple lighting model, but it will
suffice for now. - Eventually you will want a better way to
illuminate our scenes
25Texturing
- Objects in a scene will look very bland just
colored and lit. - Texturing can add a lot of detail to a scene.
- One step closer to being somewhat realistic.
- What we are trying to achieve is to apply a
texture onto some surface (or model).
26Polygons and Vertices
- Talked briefly about polygons and vertices
before. - Lets look at the problem at a per-polygon level.
- If we can get one polygon textured, then it will
be easy to get all of them textured in the same
way. - We need some new information at each vertex.
- Appropriately called texture coordinates.
- Textures can be thought of as wallpaper that is
shrink-wrapped onto a surface.
27Texture Coordinates
- Texture coordinates are two-dimensional
coordinate in texture space in the range 0.0
1.0. (0.0, 0.0) represents the top-left side of
the texture and (1.0, 1.0) represents the
lower-right side of the texture. - Using these texture coordinates we can figure out
which area in the texture belongs over the
polygon.
28How it works for a whole model
- Unwrapping process of generating texture
coordinates so that we can apply a texture to a
model. - Usually dont need to know how to do this just
that your model already has texture coordinates.
29Syntax
- Declare our data type
- IDirect3DTexture9 g_pTex
- Load in our texture can load most standard
formats. - D3DXCreateTextureFromFile(pd3dDevice,
texture.bmp,g_pTex) - Set our texture before rendering
- pd3dDevice-gtSetTexture(0, g_pTex)
30Other Applications of Textures
- Multi-texturing
- Normal Maps
- Specular Maps
- Detail Textures
- Store Data
31 32Acquire Get Resources
- //Declare our global variables at the top
- ID3DXMesh g_pMesh
- IDirect3DTexture9 g_pTexture
- // Called when our device is created or reset
- HRESULT CALLBACK OnResetDevice( IDirect3DDevice9
pd3dDevice, - const D3DSURFACE_DESC
pBackBufferSurfaceDesc, void pUserContext ) -
- // load a mesh with normals
- D3DXLoadMeshFromX( boxmesh.x, D3DX_SYSTEMMEM,
pd3dDevice, NULL, - NULL, NULL, NULL, g_pMesh )
- // load our texture
- D3DXCreateTextureFromFile( pd3dDevice,
"texture.bmp", g_pTexture )
33Acquire Setup State
- HRESULT CALLBACK OnResetDevice( IDirect3DDevice9
pd3dDevice, - const D3DSURFACE_DESC
pBackBufferSurfaceDesc, void pUserContext ) -
- // get resources
- // define our view matrix
- D3DXMATRIX view
- D3DXVECTOR3 eye(0,0,-5)
- D3DXVECTOR3 at(0,0,0)
- D3DXVECTOR3 up(0,1,0)
- D3DXMatrixLookAtLH(view, eye, at, up)
- // define our projection matrix
- D3DXMATRIX proj
- D3DXMatrixPerspectiveFovLH(proj, D3DX_PI /
4.0f, 4.0f/ 3, 1.0f, 100.0f) - // set these matrices to the device
- pd3dDevice-gtSetTransform(D3DTS_VIEW, view)
- pd3dDevice-gtSetTransform(D3DTS_PROJECTION,
proj)
34setup_lighting()
- void setup_lighting()
-
- // Set the RGBA for diffuse reflection.
- D3DMATERIAL9 mat
- mat.Diffuse.r 0.0f
- mat.Diffuse.g 0.5f
- mat.Diffuse.b 1.0f
- mat.Diffuse.a 1.0f
- pd3dDevice-gtSetMaterial(mat)
- // Initialize the light.
- D3DLIGHT9 d3dLight
- ZeroMemory(d3dLight, sizeof(d3dLight))
- // Set up a white point light.
- d3dLight.Type D3DLIGHT_POINT
- d3dLight.Diffuse.r 1.0f
- d3dLight.Diffuse.g 1.0f
- d3dLight.Diffuse.b 1.0f
//Position the Light d3dLight.Position.x
0.0f d3dLight.Position.y 100.0f
d3dLight.Position.z -100.0f // Don't
attenuate. d3dLight.Attenuation0 1.0f
d3dLight.Range 150.0f // Set the
property information for the first light.
pd3dDevice-gtSetLight(0, d3dLight)
//actually enable the light now
pd3dDevice-gtLightEnable(0, true)
35Render
- void CALLBACK OnFrameRender( IDirect3DDevice9
pd3dDevice, double fTime, float fElapsedTime,
void pUserContext ) -
- HRESULT hr
- // Clear the render target and the zbuffer
- pd3dDevice-gtClear(0, NULL, D3DCLEAR_TARGET
D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 45, 50, 170),
1.0f, 0) - // Render the scene
- if( SUCCEEDED( pd3dDevice-gtBeginScene() ) )
-
- // set our texture
- pd3dDevice-gtSetTexture(0, g_pTexture)
- // update angle
- static float angle 0.0f
- angle fElapsedTime
- if(angle gt 2.0f D3DX_PI)
- angle 0.0f
36Release
- // Release all of our resources created in
OnResetDevice() - void CALLBACK OnLostDevice( void pUserContext )
-
- if( g_pTexture )
- g_pTexture-gtRelease()
- if( g_pMesh )
- g_pMesh-gtRelease()
37Meshes, Level Loading and Editing Lecture 3
38Overview
- 3D Primitives
- Meshes
- D3D Data Structures
- Vertex Buffers (VB)
- Flexible Vertex Format (FVF)
- Loading and Editing
- Meshes
- Setting World and View
- Transforming
39Meshes
- A scene is a collection of objects or models. An
object is represented as a triangle mesh
approximation. - The triangles of the mesh are the building blocks
of the object that we are modeling. - We use the terms all interchangeably to refer to
the triangles of a mesh polygons, primitives and
mesh geometry. - Triangles are primitives, but Direct3D also
supports line and point primitives.
40Meshes
- Meshes are data structures that hold several
primitives to create complex shapes - You can associate vertices, faces, materials,
textures, and more to a mesh - Meshes can be created with a modeling software
(like 3D Studio) and then exported to X file
format and loaded
41Types of Primitives
42Vertex Buffers
- Vertex buffers, represented by the
IDirect3DVertexBuffer9 interface, are memory
buffers that contain vertex data - Vertex buffers can contain any vertex type -
transformed or untransformed, lit or unlit - The flexibility of vertex buffers make them ideal
staging points for reusing transformed geometry - Ex Rendering models that use multiple textures
the geometry is transformed only once, and then
portions of it can be rendered as needed,
interleaved with the required texture changes - Vertex buffer is described in terms of its
capabilities if it can exist only in system
memory, if it is only used for write operations,
and the type and number of vertices it can
contain traits described by D3DVERTEXBUFFER_DESC
43Flexible Vertex Formats
- A flexible vertex format
- (FVF) code describes
- the contents of vertices
- stored interleaved in a
- single data stream
- struct BLENDVERTEX
-
- D3DXVECTOR3 v // Referenced as v0 in the vertex
shader - FLOAT blend1 // Referenced as v1.x in the vertex
shader - FLOAT blend2 // Referenced as v1.y in the vertex
shader - FLOAT blend3 // Referenced as v1.z in the vertex
shader - // v1.w 1.0 - (v1.x v1.y v1.z)
- D3DXVECTOR3 n // Referenced as v3 in the vertex
shader - FLOAT tu, tv // Referenced as v7 in the vertex
shader -
- define D3DFVF_BLENDVERTEX (D3DFVF_XYZB3D3DFVF_NO
RMALD3DFVF_TEX1)
443DStep1 Example
- The following slides introduce 3D programming
with reference to a minimal example program
called 3dstep1 - which - loads a 3D object from disk
- displays the lit object on screen
- allows the user to rotate the object around the y
axis - Allows the user to extend the transform to rotate
the object around the x an z axis and to
translate in all the plans
45Modelling and Loading
46Rendering modes
- Can be set to solid, wire-frame or point
47Initialise 3D world
- Any 3D world must have . . .
- Some sort of camera and viewing system
- Lighting and rendering settings
- Objects and ways of transforming them
48Initialise 3D world
- To initialise the 3D world in D3D we have to
specify three matrices
49The matrices
- The world transformation matrix defines how to
translate, scale, and rotate the geometry in the
3-D model space. - The view transformation matrix defines the
position and rotation of the view. The view
matrix is the camera for the scene. - The projection transformation matrix defines how
geometry is transformed from 3-D view space to
2-D viewport space.
50Initialise 3D world
- A D3D 3D world must have . . .
- A camera - set in D3D by setting a camera matrix
and a perspective projection matrix - Lighting - in D3D could be directional, point,
spot, or ambient lighting - Device rendering settings - fill and backface
culling modes, depth (z) buffering - Objects - 3D objects, created on the fly, or
loaded from disk in the D3D .x file format (which
you may have modelled in 3DStudio MAX)
51D3D Z buffering
- D3D uses z (depth) buffering in order to work out
which polygons to display on screen - Considering what colour a particular pixel will
be a ray is cast into the scene - any number of polygons may be intersected by the
ray - the z buffer is used to determine which is
nearest and therefore visible
52So to Initialise the 3D world . . .
- Need to
- Turn on depth buffering
- Set rendering (fill) and backface culling modes
- create a camera matrix and set its parameters
- set the camera matrix to be the device camera
matrix - set the perspective projection matrix
- set the projection matrix to be the device
projection matrix
53Turn on depth buffering
- Two lines of code are needed to turn z buffering
on using the DXU library
54Back face culling
- Back face culling is used to remove surfaces that
should be facing away from the camera - Can be set to none, clockwise, or anticlockwise
- The orientation is calculated from the surface
normal vector - Whether the inside or outside surface is shown
depends on whether the polygon vertices are
specifies clockwise or anticlockwise
55Back face culling
- None
- Clockwise
- Anticlockwise
56Set Rendering (fill) and cull modes
- One function call each . . .
57Setting up the camera matrix
- To set up camera matrix we specify
- the cameras position in space
- where the camera is looking
- and which way is up
58Setting up the projection matrix
- Need to specify
- the field of view (how much of the scene we can
see) - view aspect ratio (image width height ratio)
- distance to front clipping plane
- distance to back clipping plane
59Effect of changing field of view
60The world matrix
- Transformations of the world matrix will
transform all items in the world - Set to identity matrix - no transformation
61Putting it all together - Initialise3DWorld
62Camera aspect ratio
- Aspect ratio is device width/device height
- Screen is usually 640 by 480 1.333
- Wrong aspect ratio leads to image distortion
- eg rotate car with screen 400x400 and a. ratio
1.33
63Lights
- There are three main types of lights
- Point lights - a point in space emitting light
- Spot lights, like real spot lights
- directional lights, light that comes from a
certain direction and exists everywhere in the
world - doesnt occur in real life but probably
the most useful type to use - Also ambient light - exists everywhere in scene -
by itself its like cartoon rendering - solid
colour with no shading
64Ambient light
- Background light, is modelled as a constant
- With ambient light alone, all surfaces have equal
brightness
65Putting it together - the InitialiseLights
function
66Dealing with 3D objects
- In D3D objects are stored in .x files
- To load an object into your program you need to
define a data structure to store it - The DXUMESH struct does this for you
- You can draw the mesh with the DXUDrawMesh()
function - When you are finished with the mesh you should
dispose of it with the DXUReleaseMesh() function
67Dealing with 3D objects - code
68Transforming an object
- We can transform an object by transforming the
WORLD matrix - This is easiest way to transform
- BUT it actually applies the transformation to the
whole world - Which is OK if we only have one object, but is
NOT OK if we need to transform objects
independently
69D3DXMatrixRotationY() function
- To set up a matrix for rotation we can use
D3DXMatrixRotationY() which we pass a pointer to
a matrix and an angle in radians - Then if we set the device World matrix to be a
matrix with rotation then the world will be
rotated - (in the following code the DegToRad() macro
converts from degrees to radians)
70Putting it together - the UpdateWorld () function
713DStep1 - functions
- Discussion so far has described in detail three
functions in the program - Initialise3DWorld()
- InitialiseLights()
- UpdateWorld()
- We just need a main loop and a functions to load
the world, render it, and release it - to
complete the program
723DStep1- LoadWorld()
- This loads the car mesh, a font for writing, and
initialises the 3D world and lighting
733DStep1- RenderWorld()
- Draws the mesh and string
743DStep1- Release World
753DStep1- WinMain()
- The Winmain() function does the D3D, windows, and
input initialisation we have already seen and
discussed - It calls LoadWorld() to initialise the world
- Game loop calls updateWorld and renderWorld
- Cleans up on exit()
76(No Transcript)
77Summary
- You should be able to take 3Dstep1 and do various
things like - load up a different object
- load up two objects
- play around with the lighting parameters
- create another light
- transform the object around the other axes
- Etc