Sei sulla pagina 1di 78

DIRECTX LAB RECORD

By

K.SARAVANAN

UGPGMD06111

Record submitted to

IMAGE COLLEGE OF ARTS, ANIMATION & TECHNOLOGY

In partial fulfillment of the requirement


For the award of the degree of

B.A. (Hons.) Digital Media


in

UG GAME DEVELOPMENT

IMAGE COLLEGE OF ARTS, ANIMATION & TECHNOLOGY


Affiliated to UNIVERSITY OF WALES (UK)
CHENNAI – 600 004
INDEX
1. Program a small database for storing and retrieving game details using
STL Classes

2. Program a Window with necessary menu operations and messages

3. Initialize a D3D window and draw a triangle in it

4. Construct cube with vertex and index buffers. Apply color on its faces and
lit the faces.

5 Draw a 3D cross with texturing and necessary Lighting.


6. Create your dream house with vertices & indices without transform, use
flexible camera.

7. Create 2D Level Design, with your 2D characters, BG & props.

8. Create a window, place your 2D character, and assign the controls to


handle the character. (controls like up, left, jump, top & bottom)

9. Create a program to handle your character’s movement with proper


collision detection. You can allow your character within the limits of
window’s boundary.

10. Combine the concepts of the above and make a proper game (single
level).

1. Aim: Program a Window with necessary menu operations and messages


Step1: Include header files and library files
Step2: Include resource header files
Step3: Include resource script(menu, icons)
Step4: Register window class
Step5: Show window
Step6: update window
Step7: Initialize D3D
Step8: Release all the devices and objects

#include <windows.h>
#include <d3d9.h>
#include <d3dx9.h>
#include "resource.h"
HWND g_hWnd = NULL;
LPDIRECT3D9 g_pD3D = NULL;
LPDIRECT3DDEVICE9 g_pd3dDevice = NULL;
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow);
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam,
LPARAM lParam);
void init(void);
void shutDown(void);
void render(void);

int WINAPI WinMain( HINSTANCE hInstance,


HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow )
{
WNDCLASSEX winClass;
MSG uMsg;

memset(&uMsg,0,sizeof(uMsg));

winClass.lpszClassName = "MY_WINDOWS_CLASS";
winClass.cbSize = sizeof(WNDCLASSEX);
winClass.style = CS_HREDRAW | CS_VREDRAW;
winClass.lpfnWndProc = WindowProc;
winClass.hInstance = hInstance;
winClass.hIcon = LoadIcon(hInstance,
(LPCTSTR)IDI_DIRECTX_ICON);
winClass.hIconSm = LoadIcon(hInstance, (LPCTSTR)IDI_DIRECTX_ICON);
winClass.hCursor = LoadCursor(NULL, IDC_ARROW);
winClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
winClass.lpszMenuName = NULL;
winClass.cbClsExtra = 0;
winClass.cbWndExtra = 0;

if( !RegisterClassEx(&winClass) )
return E_FAIL;

g_hWnd = CreateWindowEx( NULL, "MY_WINDOWS_CLASS",


"Direct3D (DX9) - Initialization",
WS_OVERLAPPEDWINDOW |
WS_VISIBLE,
0, 0, 640, 480, NULL, NULL, hInstance,
NULL );

if( g_hWnd == NULL )


return E_FAIL;

ShowWindow( g_hWnd, nCmdShow );


UpdateWindow( g_hWnd );

init();

while( uMsg.message != WM_QUIT )


{
if( PeekMessage( &uMsg, NULL, 0, 0, PM_REMOVE ) )
{
TranslateMessage( &uMsg );
DispatchMessage( &uMsg );
}
else
render();
}

shutDown();

UnregisterClass( "MY_WINDOWS_CLASS", winClass.hInstance );

return uMsg.wParam;
}

LRESULT CALLBACK WindowProc( HWND hWnd,


UINT msg,
WPARAM wParam,
LPARAM lParam )
{
switch( msg )
{
case WM_KEYDOWN:
{
switch( wParam )
{
case VK_ESCAPE:
PostQuitMessage(0);
break;
}
}
break;

case WM_CLOSE:
{
PostQuitMessage(0);
}
case WM_DESTROY:
{
PostQuitMessage(0);
}
break;

default:
{
return DefWindowProc( hWnd, msg, wParam, lParam );
}
break;
}

return 0;
}

void init( void )


{
g_pD3D = Direct3DCreate9( D3D_SDK_VERSION );

if( g_pD3D == NULL )


{
// TO DO: Respond to failure of Direct3DCreate8
return;
}

D3DDISPLAYMODE d3ddm;

if( FAILED( g_pD3D->GetAdapterDisplayMode( D3DADAPTER_DEFAULT,


&d3ddm ) ) )
{
// TO DO: Respond to failure of GetAdapterDisplayMode
return;
}
HRESULT hr;

if( FAILED( hr = g_pD3D->CheckDeviceFormat( D3DADAPTER_DEFAULT,


D3DDEVTYPE_HAL,

d3ddm.Format, D3DUSAGE_DEPTHSTENCIL,

D3DRTYPE_SURFACE, D3DFMT_D16 ) ) )
{
if( hr == D3DERR_NOTAVAILABLE )
// POTENTIAL PROBLEM: We need at least a 16-bit z-buffer!
return;
}

D3DCAPS9 d3dCaps;

if( FAILED( g_pD3D->GetDeviceCaps( D3DADAPTER_DEFAULT,


D3DDEVTYPE_HAL, &d3dCaps ) ) )
{
// TO DO: Respond to failure of GetDeviceCaps
return;
}

DWORD dwBehaviorFlags = 0;

if( d3dCaps.VertexProcessingCaps != 0 )
dwBehaviorFlags |=
D3DCREATE_HARDWARE_VERTEXPROCESSING;
else
dwBehaviorFlags |=
D3DCREATE_SOFTWARE_VERTEXPROCESSING;

//
// Everything checks out - create a simple, windowed device.
//
D3DPRESENT_PARAMETERS d3dpp;
memset(&d3dpp, 0, sizeof(d3dpp));

d3dpp.BackBufferFormat = d3ddm.Format;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.Windowed = TRUE;
d3dpp.EnableAutoDepthStencil = TRUE;
d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;

if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT,


D3DDEVTYPE_HAL, g_hWnd,
dwBehaviorFlags, &d3dpp, &g_pd3dDevice ) ) )
{
// TO DO: Respond to failure of CreateDevice
return;
}
}

void shutDown( void )


{
if( g_pd3dDevice != NULL )
g_pd3dDevice->Release();

if( g_pD3D != NULL )


g_pD3D->Release();
}

void render( void )


{
g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,
D3DCOLOR_COLORVALUE(0.0f,1.0f,0.0f,1.0f), 1.0f, 0 );

g_pd3dDevice->BeginScene();
// Render geometry here...

g_pd3dDevice->EndScene();

g_pd3dDevice->Present( NULL, NULL, NULL, NULL );


}

Resource.h

#define IDC_MYICON 2
#define IDD_DIRECTX_DIALOG 102
#define IDD_ABOUTBOX 103
#define IDS_APP_TITLE 103
#define IDM_ABOUT 104
#define IDM_EXIT 105
#define IDS_HELLO 106
#define IDI_DIRECTX_ICON 107
#define IDC_DIRECTX_MENU 108
#define IDC_DIRECTX_ACCELERATOR 109
#define IDC_DIRECTX 110
#define IDR_MAINFRAME 128
#define IDC_STATIC -1
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 129
#define _APS_NEXT_COMMAND_VALUE 32771
#define _APS_NEXT_CONTROL_VALUE 1000
#define _APS_NEXT_SYMED_VALUE 110
#endif
#endif

2.Aim:Initialize a D3D window and draw a triangle in it


Step1: Include header files and library files
Step2: Register window class
Step3: Show window
Step4: update window
Step5: Initialize D3D
Step6: Draw triangle in it
Step7: If the escape key has been pressed then the shut down function will
work.
Step8: Release D3D Object and D3D device
#include<windows.h>
#include<d3dx9.h>
#define D3DFVF_D3DVertex (D3DFVF_XYZ | D3DFVF_DIFFUSE)
// Function Prototypes...
bool InitializeDirect3D(HWND hwnd);
void RenderScene();
void ShutdownDirect3D();
LPDIRECT3D9 Direct3D_Object = NULL;
LPDIRECT3DDEVICE9 D3D_Device = NULL;
struct Vertex
{
FLOAT x, y, z; // x, y, and z coordinates.
DWORD color; // Color of this vertex.
};
Vertex Triangle_Data[3] = {
{-0.5f, -0.5f, 0.0f, D3DCOLOR_XRGB(255,255,0)},
{0.5f, -0.5f, 0.0f, D3DCOLOR_XRGB(255,255,0)},
{0.0f, 0.3f, 0.0f, D3DCOLOR_XRGB(0,0,255)}
};
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam,
LPARAM lParam)
{
switch(message)
{
case WM_KEYUP:
// If the user presses the escape key then exit the application.
if(wParam == VK_ESCAPE)
PostQuitMessage(0);
break;
case WM_DESTROY:
case WM_CLOSE:
PostQuitMessage(0);
break;
default:
break;
}
return DefWindowProc( hwnd, message, wParam, lParam );
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR
lpCmdLine, int nShowCmd)
{
MSG msg; // Message object.
HWND hwnd; // Handle to the window.
WNDCLASSEX windowClass; // Window class object.
bool done = false;
// This is the Window class.
windowClass.cbSize = sizeof(WNDCLASSEX); // size of the
WNDCLASSEX structure.
windowClass.style = CS_HREDRAW | CS_VREDRAW; // style of the window.
windowClass.lpfnWndProc = WndProc; // Address to the windows
procedure.
windowClass.cbClsExtra = 0; // Extra class information.
windowClass.cbWndExtra = 0; // Extra window information.
windowClass.hInstance = hInstance; // Handle of application
Instance.
windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);// Window Icon.
windowClass.hCursor = LoadCursor(NULL, IDC_ARROW); // Load mouse cursor.
windowClass.hbrBackground = NULL; // Background color.
windowClass.lpszMenuName = NULL; // Menu.
windowClass.lpszClassName = "UGPClass"; // Name of the window
class.
windowClass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);// Minimized
window icon.
if(!RegisterClassEx(&windowClass)) return 0;

// Create the window.


hwnd = CreateWindowEx(NULL,
// The extended style.
"UGPClass",
"Direct3D Demo by wunderkindse",
WS_OVERLAPPEDWINDOW | WS_VISIBLE |
WS_SYSMENU |WS_CLIPCHILDREN |
WS_CLIPSIBLINGS,
100, 100,
640, 480,
NULL,
NULL,
hInstance,
NULL);

if(!hwnd) return 0;
ShowWindow(hwnd, SW_SHOW);
UpdateWindow(hwnd);
done = false; // false = run program, true means stop.
// Initialize Direct3D. If all went well then continue.
if(!InitializeDirect3D(hwnd)) done = true;
// Application loop.
while(!done)
{
if(PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE))
{
// If a quit message is received then stop rendering and quit the app.
if(msg.message == WM_QUIT)
{
done = true;
}
TranslateMessage(&msg); // Translate any messages.
DispatchMessage(&msg); // Dispatch any messages.
}
else
{
RenderScene(); // Render a frame.
}
}
ShutdownDirect3D();

UnregisterClass("UGPClass", windowClass.hInstance);

return (int)msg.wParam;
}
bool InitializeDirect3D(HWND hwnd)
{
D3DDISPLAYMODE DisplayMode;
D3DPRESENT_PARAMETERS Present_Parameters;
D3DCAPS9 D3DCaps;
ZeroMemory(&Present_Parameters, sizeof(Present_Parameters));
Direct3D_Object = Direct3DCreate9(D3D_SDK_VERSION);
if(Direct3D_Object == NULL)
{
MessageBox(NULL, "Error, couldn't initialize DirectX!?!",
"Error!", MB_OK);
return false;
}

if(FAILED(Direct3D_Object->GetAdapterDisplayMode(D3DADAPTER_DEFAULT,
&DisplayMode)))
{
MessageBox(NULL, "Error setting the display mode.", "Error!", MB_OK);
return false;
}
if(FAILED(Direct3D_Object->GetDeviceCaps(D3DADAPTER_DEFAULT,
D3DDEVTYPE_HAL, &D3DCaps)))
{
return false;
}

processing.
DWORD VertexProcessing = 0;

if(D3DCaps.VertexProcessingCaps != 0)
VertexProcessing |= D3DCREATE_HARDWARE_VERTEXPROCESSING;
else
VertexProcessing |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;

Present_Parameters.Windowed = TRUE; // Window mode (not


fullscreen).
Present_Parameters.SwapEffect = D3DSWAPEFFECT_DISCARD;
Present_Parameters.BackBufferFormat = DisplayMode.Format;// Render to the
area of the screen.
Present_Parameters.BackBufferCount = 1;
Present_Parameters.EnableAutoDepthStencil = TRUE;
Present_Parameters.AutoDepthStencilFormat = D3DFMT_D16;

if(FAILED(Direct3D_Object->CreateDevice(D3DADAPTER_DEFAULT,
D3DDEVTYPE_HAL, hwnd,
VertexProcessing,
&Present_Parameters, &D3D_Device)))
{
MessageBox(NULL, "CreateDevice() failed! Make sure you have DirectX
9.",
"Error!", MB_OK);
return false;
}

if(D3D_Device == NULL)
{
MessageBox(NULL, "D3D_Device is equal to NULL!?!", "Error!", MB_OK);
return false;
}
D3D_Device->SetRenderState(D3DRS_LIGHTING, FALSE);
D3D_Device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
return true;
}
void RenderScene()
{
D3D_Device->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,
D3DCOLOR_XRGB(0,0,0), 1.0f, 0);
D3D_Device->BeginScene();
LPDIRECT3DVERTEXBUFFER9 Vertex_Buffer;

if(FAILED(D3D_Device->CreateVertexBuffer(3 * sizeof(Vertex),
0, D3DFVF_D3DVertex,
D3DPOOL_DEFAULT, &Vertex_Buffer, NULL)))
{
return; // Exit this function if there is some kind of problem.
}
Vertex* Vertices;
if(FAILED(Vertex_Buffer->Lock(0, sizeof(Triangle_Data), (void**)&Vertices,
0)))
return;
memcpy(Vertices, Triangle_Data, sizeof(Triangle_Data));

Vertex_Buffer->Unlock();

D3D_Device->SetStreamSource(0, Vertex_Buffer, 0, sizeof(Vertex));


D3D_Device->SetFVF(D3DFVF_D3DVertex);
D3D_Device->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);
Vertex_Buffer->Release();

D3D_Device->EndScene();

D3D_Device->Present(NULL, NULL, NULL, NULL);


}
void ShutdownDirect3D()
{

if(D3D_Device != NULL)
{
D3D_Device->Release();
D3D_Device = NULL;
}

if(Direct3D_Object != NULL)
{
Direct3D_Object->Release();
Direct3D_Object = NULL;
}
}

3.Aim:Construct cube index buffers. Apply color on its faces and lit the faces.

Step1: Include header files and library files


Step2: Register window class
Step3: Show window
Step4: update window
Step5: Initialize D3D
Step 6: Create vertex and index buffers.
Step 7: Fill the buffers with the cube data.
Step 8: Define unique vertices
Step 9: define the triangles of the cube
Step 10: Draw the cube on the screen
Step 11: Releasing all the objects and devices

#include <windows.h>
#include<d3dx9.h>
IDirect3DDevice9* Device = 0;
const int Width = 640;
const int Height = 480;

IDirect3DVertexBuffer9* VB = 0;
IDirect3DIndexBuffer9* IB = 0;

struct Vertex
{
Vertex(){}
Vertex(float x, float y, float z)
{
_x = x; _y = y; _z = z;
}
float _x, _y, _z;
static const DWORD FVF;
};
const DWORD Vertex::FVF = D3DFVF_XYZ;

bool Setup()
{
//
// Create vertex and index buffers.
//

Device->CreateVertexBuffer(
8 * sizeof(Vertex),
D3DUSAGE_WRITEONLY,
Vertex::FVF,
D3DPOOL_MANAGED,
&VB,
0);

Device->CreateIndexBuffer(
36 * sizeof(WORD),
D3DUSAGE_WRITEONLY,
D3DFMT_INDEX16,
D3DPOOL_MANAGED,
&IB,
0);

// define unique vertices:


Vertex* vertices;
VB->Lock(0, 0, (void**)&vertices, 0);

// vertices of a unit cube


vertices[0] = Vertex(-1.0f, -1.0f, -1.0f);
vertices[1] = Vertex(-1.0f, 1.0f, -1.0f);
vertices[2] = Vertex( 1.0f, 1.0f, -1.0f);
vertices[3] = Vertex( 1.0f, -1.0f, -1.0f);
vertices[4] = Vertex(-1.0f, -1.0f, 1.0f);
vertices[5] = Vertex(-1.0f, 1.0f, 1.0f);
vertices[6] = Vertex( 1.0f, 1.0f, 1.0f);
vertices[7] = Vertex( 1.0f, -1.0f, 1.0f);

VB->Unlock();
// define the triangles of the cube:
WORD* indices = 0;
IB->Lock(0, 0, (void**)&indices, 0);

// front side
indices[0] = 0; indices[1] = 1; indices[2] = 2;
indices[3] = 0; indices[4] = 2; indices[5] = 3;

// back side
indices[6] = 4; indices[7] = 6; indices[8] = 5;
indices[9] = 4; indices[10] = 7; indices[11] = 6;

// left side
indices[12] = 4; indices[13] = 5; indices[14] = 1;
indices[15] = 4; indices[16] = 1; indices[17] = 0;

// right side
indices[18] = 3; indices[19] = 2; indices[20] = 6;
indices[21] = 3; indices[22] = 6; indices[23] = 7;

// top
indices[24] = 1; indices[25] = 5; indices[26] = 6;
indices[27] = 1; indices[28] = 6; indices[29] = 2;

// bottom
indices[30] = 4; indices[31] = 0; indices[32] = 3;
indices[33] = 4; indices[34] = 3; indices[35] = 7;

IB->Unlock();

//
// Position and aim the camera.
//
D3DXVECTOR3 position(0.0f, 0.0f, -5.0f);
D3DXVECTOR3 target(0.0f, 0.0f, 0.0f);
D3DXVECTOR3 up(0.0f, 1.0f, 0.0f);
D3DXMATRIX V;
D3DXMatrixLookAtLH(&V, &position, &target, &up);

Device->SetTransform(D3DTS_VIEW, &V);

//
// Set the projection matrix.
//

D3DXMATRIX proj;
D3DXMatrixPerspectiveFovLH(
&proj,
D3DX_PI * 0.5f, // 90 - degree
(float)Width / (float)Height,
1.0f,
1000.0f);
Device->SetTransform(D3DTS_PROJECTION, &proj);

//
// Switch to wireframe mode.
//

Device->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME);

return true;
}

void Cleanup()
{
d3d::Release<IDirect3DVertexBuffer9*>(VB);
d3d::Release<IDirect3DIndexBuffer9*>(IB);
}
bool Display(float timeDelta)
{
if( Device )
{
//
// spin the cube:
//
D3DXMATRIX Rx, Ry;

// rotate 45 degrees on x-axis


D3DXMatrixRotationX(&Rx, 3.14f / 4.0f);

// incremement y-rotation angle each frame


static float y = 0.0f;
D3DXMatrixRotationY(&Ry, y);
y += timeDelta;

// reset angle to zero when angle reaches 2*PI


if( y >= 6.28f )
y = 0.0f;

// combine x- and y-axis rotation transformations.


D3DXMATRIX p = Rx * Ry;

Device->SetTransform(D3DTS_WORLD, &p);

//
// draw the scene:
//
Device->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xffffffff,
1.0f, 0);
Device->BeginScene();

Device->SetStreamSource(0, VB, 0, sizeof(Vertex));


Device->SetIndices(IB);
Device->SetFVF(Vertex::FVF);

// Draw cube.
Device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 8, 0, 12);

Device->EndScene();
Device->Present(0, 0, 0, 0);
}
return true;
}

//
// WndProc
//
LRESULT CALLBACK d3d::WndProc(HWND hwnd, UINT msg, WPARAM wParam,
LPARAM lParam)
{
switch( msg )
{
case WM_DESTROY:
::PostQuitMessage(0);
break;

case WM_KEYDOWN:
if( wParam == VK_ESCAPE )
::DestroyWindow(hwnd);
break;
}
return ::DefWindowProc(hwnd, msg, wParam, lParam);
}

//
// WinMain
//
int WINAPI WinMain(HINSTANCE hinstance,
HINSTANCE prevInstance,
PSTR cmdLine,
int showCmd)
{
if(!d3d::InitD3D(hinstance,
Width, Height, true, D3DDEVTYPE_HAL, &Device))
{
::MessageBox(0, "InitD3D() - FAILED", 0, 0);
return 0;
}

if(!Setup())
{
::MessageBox(0, "Setup() - FAILED", 0, 0);
return 0;
}

d3d::EnterMsgLoop( Display );

Cleanup();

Device->Release();

return 0;
}

AIM:Create your dream house with vertices & indices , use flexible camera

Step1: Include header files and library files


Step2: Register window class
Step3: Show window
Step4: update window
Step5: Initialize D3D
Step 6: Create vertex and index buffers.
Step 7: Fill the buffers with the cube data.
Step 8: Define unique vertices
Step 9: define the triangles of the cube
Step 10: Set the ambient color for the material
Step 11: Create the cubes
Step 12: Set the virtual keys
Step 13: Draw the house on the screen
Step 14: Releasing all the object and the devices

#include <windows.h>
#include <mmsystem.h>
#include <d3d9.h>
#include <d3dx9.h>
#include "resource.h"
HWND g_hWnd = NULL;
LPDIRECT3D9 g_pD3D = NULL;
LPDIRECT3DDEVICE9 g_pd3dDevice = NULL;
LPDIRECT3DVERTEXBUFFER9 g_pVertexBuffer = NULL;

unsigned long g_dwNumMaterials = 0L;

IDirect3DVertexBuffer9* VB = 0;
IDirect3DIndexBuffer9* IB = 0;
D3DXMATRIX translationMatrix;
D3DXMATRIX scalingMatrix;
D3DXMATRIX worldmatrix;
D3DXMATRIX rotationMatrix;
D3DXMATRIX rotationMatrix1;
const int Width = 640;
const int Height = 480;

D3DMATERIAL9 Mtrls[4];

Mtrls[0] = d3d::RED_MTRL;
Mtrls[1] = d3d::BLUE_MTRL;
Mtrls[2] = d3d::GREEN_MTRL;
Mtrls[3] = d3d::YELLOW_MTRL;

D3DXVECTOR3 dir(1.0f, -0.0f, 0.25f);


D3DXCOLOR c = d3d::WHITE;
D3DLIGHT9 dirLight = d3d::InitDirectionalLight(&dir, &c);

g_pd3dDevice->SetLight(0, &dirLight);
g_pd3dDevice->LightEnable(0, true);

struct Vertex1
{
Vertex1(){}
Vertex1(float x1, float y1, float z1,D3DCOLOR C1)
{
_x = x1; _y = y1; _z = z1; C=C1;
}
float _x, _y, _z;
D3DCOLOR C;

static const DWORD FVF;


};
const DWORD Vertex1::FVF = D3DFVF_XYZ| D3DFVF_DIFFUSE;

bool Setup()
{
//
// Create vertex and index buffers.
//

g_pd3dDevice ->CreateVertexBuffer(
8 * sizeof(Vertex1),
D3DUSAGE_WRITEONLY,
Vertex1::FVF,
D3DPOOL_MANAGED,
&VB,
0);

g_pd3dDevice ->CreateIndexBuffer(
36 * sizeof(WORD),
D3DUSAGE_WRITEONLY,
D3DFMT_INDEX16,
D3DPOOL_MANAGED,
&IB,
0);

//
// Fill the buffers with the cube data.
//

// define unique vertices:


Vertex1* vertices;
VB->Lock(0, 0, (void**)&vertices, 0);

// vertices of a unit cube


vertices[0] = Vertex1(-0.03f, -1.0f, -1.0f,D3DCOLOR_ARGB(50, 100,
100,100));
vertices[1] = Vertex1(-0.03f, 1.0f, -1.0f,D3DCOLOR_ARGB(200,155, 100,
100));
vertices[2] = Vertex1( 0.03f, 1.0f, -1.0f,D3DCOLOR_ARGB(150,155, 100,
155));
vertices[3] = Vertex1( 0.03f, -1.0f, -1.0f,D3DCOLOR_ARGB(200,200, 100,
255));
vertices[4] = Vertex1(-0.03f, -1.0f, 0.25f,D3DCOLOR_ARGB(150,55, 100,
255));
vertices[5] = Vertex1(-0.03f, 1.0f, 0.25f,D3DCOLOR_ARGB(100,155,
100, 100));
vertices[6] = Vertex1( 0.03f, 1.0f, 0.25f,D3DCOLOR_ARGB(150,55, 100,
160));
vertices[7] = Vertex1( 0.03f, -1.0f, 0.25f,D3DCOLOR_ARGB(200,55, 100,
155));

VB->Unlock();

// define the triangles of the cube:


WORD* indices = 0;
IB->Lock(0, 0, (void**)&indices, 0);

//front side
indices[4]=2;indices[5]=3;indices[3]=0;
indices[2]=2;indices[0]=0;indices[1]=1;

//right side
indices[6]=6;indices[7]=7;indices[8]=3;
indices[11]=6;indices[9]=3;indices[10]=2;

//left side
indices[18]=1;indices[19]=0;indices[20]=4;
indices[23]=1;indices[21]=4;indices[22]=5;

//back side
indices[12]=5;indices[13]=4;indices[14]=7;
indices[17]=5;indices[15]=7;indices[16]=6;
//top side
indices[24]=6;indices[25]=2;indices[26]=1;
indices[29]=6;indices[27]=1;indices[28]=5;

//bottom side
indices[30]=3;indices[31]=7;indices[32]=4;
indices[35]=3;indices[33]=4;indices[34]=0;

IB->Unlock();

//
// Position and aim the camera.
//

D3DXVECTOR3 position(0.0f, 0.0f, -5.0f);


D3DXVECTOR3 target(0.0f, 0.0f, 0.0f);
D3DXVECTOR3 up(0.0f, 1.0f, 0.0f);
D3DXMATRIX V;
D3DXMatrixLookAtLH(&V, &position, &target, &up);

g_pd3dDevice->SetTransform(D3DTS_VIEW, &V);

//
// Set the projection matrix.
//

D3DXMATRIX proj;
D3DXMatrixPerspectiveFovLH(
&proj,
D3DX_PI * 0.5f, // 90 - degree
(float)Width / (float)Height,
1.0f,
1000.0f);
g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &proj);

//
// Switch to wireframe mode.
//

g_pd3dDevice->SetRenderState(D3DRS_FILLMODE, NULL);

return true;
}
void Cleanup()
{
//g_pd3dDevice->Release<IDirect3DVertexBuffer9*>(VB);
//g_pd3dDevice->Release<IDirect3DIndexBuffer9*>(IB);

VB->Release();
IB-> Release();
}

POINT g_ptLastMousePosit;
POINT g_ptCurrentMousePosit;
bool g_bMousing = false;
float g_fMoveSpeed = 25.0f;
float g_fElpasedTime;
double g_dCurTime;
double g_dLastTime;

D3DXVECTOR3 g_vEye(5.0f, 5.0f, -5.0f); // Eye Position


D3DXVECTOR3 g_vLook(-0.5f, -0.5f, 0.5f); // Look Vector
D3DXVECTOR3 g_vUp(0.0f, 1.0f, 0.0f); // Up Vector
D3DXVECTOR3 g_vRight(1.0f, 0.0f, 0.0f); // Right Vector
struct Vertex
{
float x, y, z;
DWORD color;

enum FVF
{
FVF_Flags = D3DFVF_XYZ | D3DFVF_DIFFUSE
};
};

Vertex g_lineVertices[] =
{
{ 0.0f, 0.0f, 0.0f, 0xffff0000 }, // red = +x Axis
{ 5.0f, 0.0f, 0.0f, 0xffff0000 },
{ 0.0f, 0.0f, 0.0f, 0xff00ff00 }, // green = +y Axis
{ 0.0f, 5.0f, 0.0f, 0xff00ff00 },
{ 0.0f, 0.0f, 5.0f, 0xff0000ff }, // blue = +z Axis
{ 0.0f, 0.0f, 0.0f, 0xff0000ff }
};

//------------------------------------------------------------------------------
// PROTOTYPES
//------------------------------------------------------------------------------
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow);
LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam,
LPARAM lParam);
void init(void);
void shutDown(void);
void render(void);
void getRealTimeUserInput(void);
//void updateViewMatrix(void);

//------------------------------------------------------------------------------
// Name: WinMain()
// Desc: The application's entry point
//------------------------------------------------------------------------------
int WINAPI WinMain( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow )
{
WNDCLASSEX winClass;
MSG uMsg;

memset(&uMsg,0,sizeof(uMsg));

winClass.lpszClassName = "MY_WINDOWS_CLASS";
winClass.cbSize = sizeof(WNDCLASSEX);
winClass.style = CS_HREDRAW | CS_VREDRAW;
winClass.lpfnWndProc = WindowProc;
winClass.hInstance = hInstance;
winClass.hIcon = LoadIcon(hInstance,
(LPCTSTR)IDI_DIRECTX_ICON);
winClass.hIconSm = LoadIcon(hInstance, (LPCTSTR)IDI_DIRECTX_ICON);
winClass.hCursor = LoadCursor(NULL, IDC_ARROW);
winClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
winClass.lpszMenuName = NULL;
winClass.cbClsExtra = 0;
winClass.cbWndExtra = 0;

if( !RegisterClassEx(&winClass) )
return E_FAIL;

g_hWnd = CreateWindowEx( NULL, "MY_WINDOWS_CLASS",


"Direct3D (DX9) - First Person Shooter style controls",
WS_OVERLAPPEDWINDOW |
WS_VISIBLE,
0, 0, 640, 480, NULL, NULL, hInstance,
NULL );

if( g_hWnd == NULL )


return E_FAIL;

ShowWindow( g_hWnd, nCmdShow );


UpdateWindow( g_hWnd );

init();

if(!Setup())
{
::MessageBox(0, "Setup() - FAILED", 0, 0);
return 0;
}

while( uMsg.message != WM_QUIT )


{
if( PeekMessage( &uMsg, NULL, 0, 0, PM_REMOVE ) )
{
TranslateMessage( &uMsg );
DispatchMessage( &uMsg );
}
else
{
g_dCurTime = timeGetTime();
g_fElpasedTime = (float)((g_dCurTime - g_dLastTime) *
0.001);
g_dLastTime = g_dCurTime;

render();
}
}
shutDown();

UnregisterClass( "MY_WINDOWS_CLASS", winClass.hInstance );

return uMsg.wParam;
}

LRESULT CALLBACK WindowProc( HWND hWnd,


UINT msg,
WPARAM wParam,
LPARAM lParam )
{
switch( msg )
{
case WM_KEYDOWN:
{
switch( wParam )
{
case VK_ESCAPE:
PostQuitMessage(0);
break;
}
}
break;

case WM_LBUTTONDOWN:
{
g_bMousing = true;
}
break;

case WM_LBUTTONUP:
{
g_bMousing = false;
}
break;

case WM_CLOSE:
{
PostQuitMessage(0);
}

case WM_DESTROY:
{
PostQuitMessage(0);
}
break;

default:
{
return DefWindowProc( hWnd, msg, wParam, lParam );
}
break;
}

return 0;
}

void getRealTimeUserInput( void )


{
//
// Get mouse input...
//

POINT mousePosit;
GetCursorPos( &mousePosit );
ScreenToClient( g_hWnd, &mousePosit );

g_ptCurrentMousePosit.x = mousePosit.x;
g_ptCurrentMousePosit.y = mousePosit.y;
D3DXMATRIX matRotation;

if( g_bMousing )
{
int nXDiff = (g_ptCurrentMousePosit.x - g_ptLastMousePosit.x);
int nYDiff = (g_ptCurrentMousePosit.y - g_ptLastMousePosit.y);

if( nYDiff != 0 )
{
D3DXMatrixRotationAxis( &matRotation, &g_vRight,
D3DXToRadian((float)nYDiff / 3.0f));
// D3DXVec3TransformCoord( &g_vLook, &g_vLook, &matRotation
);
// D3DXVec3TransformCoord( &g_vUp, &g_vUp, &matRotation );
}

if( nXDiff != 0 )
{
D3DXMatrixRotationAxis( &matRotation,
&D3DXVECTOR3(0,1,0), D3DXToRadian((float)nXDiff / 3.0f) );
D3DXVec3TransformCoord( &g_vLook, &g_vLook, &matRotation
);
// D3DXVec3TransformCoord( &g_vUp, &g_vUp, &matRotation );
}
}

g_ptLastMousePosit.x = g_ptCurrentMousePosit.x;
g_ptLastMousePosit.y = g_ptCurrentMousePosit.y;

//
// Get keyboard input...
//

unsigned char keys[256];


GetKeyboardState( keys );

D3DXVECTOR3 tmpLook = g_vLook;


D3DXVECTOR3 tmpRight = g_vRight;

// Up Arrow Key - View moves forward


if( keys[VK_UP] & 0x80 )
g_vEye -= tmpLook*-g_fMoveSpeed*g_fElpasedTime;

// Down Arrow Key - View moves backward


if( keys[VK_DOWN] & 0x80 )
g_vEye += (tmpLook*-g_fMoveSpeed)*g_fElpasedTime;

// Left Arrow Key - View side-steps or strafes to the left


if( keys[VK_LEFT] & 0x80 )
g_vEye -= (tmpRight*g_fMoveSpeed)*g_fElpasedTime;

// Right Arrow Key - View side-steps or strafes to the right


if( keys[VK_RIGHT] & 0x80 )
g_vEye += (tmpRight*g_fMoveSpeed)*g_fElpasedTime;

// Home Key - View elevates up


if( keys[VK_HOME] & 0x80 )
g_vEye.y += g_fMoveSpeed*g_fElpasedTime;

// End Key - View elevates down


if( keys[VK_END] & 0x80 )
g_vEye.y -= g_fMoveSpeed*g_fElpasedTime;
}

//------------------------------------------------------------------------------
// Name: init()
// Desc:
//------------------------------------------------------------------------------
void init( void )
{
g_pD3D = Direct3DCreate9( D3D_SDK_VERSION );

D3DDISPLAYMODE d3ddm;
g_pD3D->GetAdapterDisplayMode( D3DADAPTER_DEFAULT, &d3ddm );

D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory( &d3dpp, sizeof(d3dpp) );

d3dpp.Windowed = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.BackBufferFormat = d3ddm.Format;
d3dpp.EnableAutoDepthStencil = TRUE;
d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;

g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, g_hWnd,


D3DCREATE_SOFTWARE_VERTEXPROCESSING,
&d3dpp, &g_pd3dDevice );

g_pd3dDevice->CreateVertexBuffer( 6*sizeof(Vertex),
D3DUSAGE_WRITEONLY,
Vertex::FVF_Flags, D3DPOOL_DEFAULT,
&g_pVertexBuffer, NULL );
void *pVertices = NULL;

g_pVertexBuffer->Lock( 0, sizeof(g_lineVertices), (void**)&pVertices, 0 );


memcpy( pVertices, g_lineVertices, sizeof(g_lineVertices) );
g_pVertexBuffer->Unlock();

g_pd3dDevice->SetRenderState( D3DRS_LIGHTING, FALSE );


g_pd3dDevice->SetRenderState( D3DRS_FILLMODE,
D3DFILL_WIREFRAME );
g_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );
D3DXMATRIX matProj;
D3DXMatrixPerspectiveFovLH( &matProj, D3DXToRadian( 45.0f ),
640.0f / 480.0f, 0.1f, 500.0f );
g_pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj );

//--------------------------------------------------------------------------

// LPD3DXBUFFER pD3DXMtrlBuffer;

/* D3DXLoadMeshFromX( "teapot.x", D3DXMESH_SYSTEMMEM,


g_pd3dDevice, NULL,
&pD3DXMtrlBuffer, NULL, &g_dwNumMaterials,
&g_pMesh );

// We need to extract the material properties and texture names


// from the pD3DXMtrlBuffer
D3DXMATERIAL *d3dxMaterials = (D3DXMATERIAL*)pD3DXMtrlBuffer-
>GetBufferPointer();
g_pMeshMaterials = new D3DMATERIAL9[g_dwNumMaterials];
g_pMeshTextures = new LPDIRECT3DTEXTURE9[g_dwNumMaterials];

for( unsigned long i = 0; i < g_dwNumMaterials; ++i )


{
// Copy the material over...
g_pMeshMaterials[i] = d3dxMaterials[i].MatD3D;

// Set the ambient color for the material (D3DX does not do this)
g_pMeshMaterials[i].Ambient = g_pMeshMaterials[i].Diffuse;

// Create the texture...


g_pMeshTextures[i] = NULL;
D3DXCreateTextureFromFile( g_pd3dDevice,
d3dxMaterials[i].pTextureFilename,
&g_pMeshTextures[i] );
}
pD3DXMtrlBuffer->Release(); */
}

void updateViewMatrix( void )


{
D3DXMATRIX view;
D3DXMatrixIdentity( &view );

D3DXVec3Normalize( &g_vLook, &g_vLook );


D3DXVec3Cross( &g_vRight, &g_vUp, &g_vLook );
D3DXVec3Normalize( &g_vRight, &g_vRight );
D3DXVec3Cross( &g_vUp, &g_vLook, &g_vRight );
D3DXVec3Normalize( &g_vUp, &g_vUp );

view._11 = g_vRight.x;
view._12 = g_vUp.x;
view._13 = g_vLook.x;
view._14 = 0.0f;

view._21 = g_vRight.y;
view._22 = g_vUp.y;
view._23 = g_vLook.y;
view._24 = 0.0f;

view._31 = g_vRight.z;
view._32 = g_vUp.z;
view._33 = g_vLook.z;
view._34 = 0.0f;

view._41 = -D3DXVec3Dot( &g_vEye, &g_vRight );


view._42 = -D3DXVec3Dot( &g_vEye, &g_vUp );
view._43 = -D3DXVec3Dot( &g_vEye, &g_vLook );
view._44 = 1.0f;
g_pd3dDevice->SetTransform( D3DTS_VIEW, &view );
}

void shutDown( void )


{
if( g_pMeshMaterials != NULL )
delete[] g_pMeshMaterials;

if( g_pMeshTextures != NULL )


{
for( unsigned long i = 0; i < g_dwNumMaterials; ++i )
{
if( g_pMeshTextures[i] != NULL )
g_pMeshTextures[i]->Release();
}

delete[] g_pMeshTextures;
}

if( g_pMesh != NULL )


g_pMesh->Release();

if( g_pVertexBuffer != NULL )


g_pVertexBuffer->Release();

if( g_pd3dDevice != NULL )


g_pd3dDevice->Release();

if( g_pD3D != NULL )


g_pD3D->Release();
}

void render( void )


{
g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,
D3DCOLOR_COLORVALUE(0.2f, 0.0f, 0.30, 0.9f), 1.0f, 0 );

getRealTimeUserInput();
updateViewMatrix();

D3DXMATRIX matWorld;
D3DXMatrixScaling( &matWorld, 2.0f, 2.0f, 2.0f );
g_pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld );

g_pd3dDevice->BeginScene();

/* for( unsigned long i = 0; i < g_dwNumMaterials; ++i )


{
g_pd3dDevice->SetMaterial( &g_pMeshMaterials[i] );
g_pd3dDevice->SetTexture( 0, g_pMeshTextures[i] );
g_pMesh->DrawSubset( i );
} */

// Draw cube.

g_pd3dDevice->SetStreamSource(0, VB, 0, sizeof(Vertex1));


g_pd3dDevice->SetIndices(IB);
D3DXMatrixTranslation(&translationMatrix,3.0f,1.0f,0.0f);
D3DXMatrixScaling(&scalingMatrix,1.0f,2.0f,5.0f);
worldmatrix=translationMatrix *scalingMatrix;
g_pd3dDevice->SetTransform( D3DTS_WORLD, &worldmatrix );
g_pd3dDevice->SetFVF(Vertex1::FVF);
g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 8,
0, 12);

g_pd3dDevice->SetStreamSource(0, VB, 0, sizeof(Vertex1));


g_pd3dDevice->SetIndices(IB);

// Draw cube.
D3DXMatrixTranslation(&translationMatrix,3.0f,1.0f,2.0f);
D3DXMatrixScaling(&scalingMatrix,1.0f,2.0f,5.0f);
worldmatrix=translationMatrix *scalingMatrix;

g_pd3dDevice->SetTransform( D3DTS_WORLD, &worldmatrix );


g_pd3dDevice->SetFVF(Vertex1::FVF);
g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 8,
0, 12);
g_pd3dDevice->SetStreamSource(0, VB, 0, sizeof(Vertex1));
g_pd3dDevice->SetIndices(IB);

// Draw cube.
D3DXMatrixTranslation(&translationMatrix,-3.0f,1.0f,0.0f);
D3DXMatrixScaling(&scalingMatrix,1.0f,2.0f,5.0f);
worldmatrix=translationMatrix *scalingMatrix;

g_pd3dDevice->SetTransform( D3DTS_WORLD, &worldmatrix );


g_pd3dDevice->SetFVF(Vertex1::FVF);
g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 8,
0, 12);
// Draw cube.
D3DXMatrixTranslation(&translationMatrix,-3.0f,1.0f,2.0f);
D3DXMatrixScaling(&scalingMatrix,1.0f,2.0f,5.0f);
worldmatrix=translationMatrix *scalingMatrix;

g_pd3dDevice->SetTransform( D3DTS_WORLD, &worldmatrix );


g_pd3dDevice->SetFVF(Vertex1::FVF);
g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 8,
0, 12);

g_pd3dDevice->SetStreamSource(0, VB, 0, sizeof(Vertex1));


g_pd3dDevice->SetIndices(IB);

// Draw cube.
D3DXMatrixTranslation(&translationMatrix,5.0f,1.0f,0.73f);
D3DXMatrixScaling(&scalingMatrix,1.0f,2.0f,3.0f);
D3DXMatrixRotationY(&rotationMatrix,D3DX_PI/2);
worldmatrix=translationMatrix *scalingMatrix*rotationMatrix;

g_pd3dDevice->SetTransform( D3DTS_WORLD, &worldmatrix );


g_pd3dDevice->SetFVF(Vertex1::FVF);
g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 8,
0, 12);

D3DXMatrixTranslation(&translationMatrix,0.50f,1.0f,0.05f);
D3DXMatrixScaling(&scalingMatrix,1.0f,2.0f,3.0f);
D3DXMatrixRotationY(&rotationMatrix,D3DX_PI/2);
worldmatrix=translationMatrix *scalingMatrix*rotationMatrix;

g_pd3dDevice->SetTransform( D3DTS_WORLD, &worldmatrix );


g_pd3dDevice->SetFVF(Vertex1::FVF);
g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 8,
0, 12);

D3DXMatrixTranslation(&translationMatrix,-1.0f,1.0f,2.05f);
D3DXMatrixScaling(&scalingMatrix,1.0f,2.0f,3.0f);
D3DXMatrixRotationY(&rotationMatrix,D3DX_PI/2);
worldmatrix=translationMatrix *scalingMatrix*rotationMatrix;

g_pd3dDevice->SetTransform( D3DTS_WORLD, &worldmatrix );


g_pd3dDevice->SetFVF(Vertex1::FVF);
g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 8,
0, 12);

D3DXMatrixTranslation(&translationMatrix,-5.0f,1.0f,2.05f);
D3DXMatrixScaling(&scalingMatrix,1.0f,2.0f,3.0f);
D3DXMatrixRotationY(&rotationMatrix,D3DX_PI/2);
worldmatrix=translationMatrix *scalingMatrix*rotationMatrix;
g_pd3dDevice->SetTransform( D3DTS_WORLD, &worldmatrix );
g_pd3dDevice->SetFVF(Vertex1::FVF);
g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 8,
0, 12);
// Draw cube.
D3DXMatrixTranslation(&translationMatrix,-11.0f,1.0f,0.73f);
D3DXMatrixScaling(&scalingMatrix,1.0f,2.0f,3.0f);
D3DXMatrixRotationY(&rotationMatrix,D3DX_PI/2);
worldmatrix=translationMatrix *scalingMatrix*rotationMatrix;

g_pd3dDevice->SetTransform( D3DTS_WORLD, &worldmatrix );


g_pd3dDevice->SetFVF(Vertex1::FVF);
g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 8,
0, 12);

// Draw cube.
D3DXMatrixTranslation(&translationMatrix,0.0f,0.10f,0.60f);
D3DXMatrixScaling(&scalingMatrix,2.0f,4.0f,15.0f);
D3DXMatrixRotationZ(&rotationMatrix,D3DX_PI/2);
worldmatrix=translationMatrix *scalingMatrix*rotationMatrix;

g_pd3dDevice->SetTransform( D3DTS_WORLD, &worldmatrix );


g_pd3dDevice->SetFVF(Vertex1::FVF);
g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 8,
0, 12);
// Draw cube
D3DXMatrixTranslation(&translationMatrix,2.50f,0.10f,0.60f);
D3DXMatrixScaling(&scalingMatrix,1.0f,4.0f,15.0f);
D3DXMatrixRotationZ(&rotationMatrix,D3DX_PI/2);
worldmatrix=translationMatrix *scalingMatrix*rotationMatrix;

g_pd3dDevice->SetTransform( D3DTS_WORLD, &worldmatrix );


g_pd3dDevice->SetFVF(Vertex1::FVF);
g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 8,
0, 12);
// Draw cube
D3DXMatrixTranslation(&translationMatrix,27.50f,0.10f,0.60f);
D3DXMatrixScaling(&scalingMatrix,0.20f,2.0f,15.0f);
D3DXMatrixRotationZ(&rotationMatrix,D3DX_PI/3);
worldmatrix=translationMatrix *scalingMatrix*rotationMatrix;

g_pd3dDevice->SetTransform( D3DTS_WORLD, &worldmatrix );


g_pd3dDevice->SetFVF(Vertex1::FVF);
g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 8,
0, 12);

D3DXMatrixTranslation(&translationMatrix,29.50f,0.50f,0.60f);
D3DXMatrixScaling(&scalingMatrix,0.20f,2.0f,15.0f);
D3DXMatrixRotationZ(&rotationMatrix,D3DX_PI/2);
worldmatrix=translationMatrix *scalingMatrix*rotationMatrix;

g_pd3dDevice->SetTransform( D3DTS_WORLD, &worldmatrix );


g_pd3dDevice->SetFVF(Vertex1::FVF);
g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 8,
0, 12);

// Draw cube.
D3DXMatrixTranslation(&translationMatrix,1.3f,-2.3f,0.4f);
D3DXMatrixScaling(&scalingMatrix,5.0f,2.0f,3.0f);
D3DXMatrixRotationZ(&rotationMatrix,D3DX_PI/2);
D3DXMatrixRotationX(&rotationMatrix1,D3DX_PI/4);
worldmatrix=translationMatrix
*scalingMatrix*rotationMatrix*rotationMatrix1;

g_pd3dDevice->SetTransform( D3DTS_WORLD, &worldmatrix );


g_pd3dDevice->SetFVF(Vertex1::FVF);
g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 8,
0, 12);
// Draw cube.
D3DXMatrixTranslation(&translationMatrix,-.4f,-2.3f,-1.10f);
D3DXMatrixScaling(&scalingMatrix,5.0f,2.0f,3.0f);
D3DXMatrixRotationZ(&rotationMatrix,D3DX_PI/2);
D3DXMatrixRotationX(&rotationMatrix1,3*D3DX_PI/4);
worldmatrix=translationMatrix
*scalingMatrix*rotationMatrix*rotationMatrix1;

g_pd3dDevice->SetTransform( D3DTS_WORLD, &worldmatrix );


g_pd3dDevice->SetFVF(Vertex1::FVF);
g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 8,
0, 12);

D3DXMatrixScaling( &matWorld, 1.0f, 1.0f, 1.0f );


g_pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld );

g_pd3dDevice->SetStreamSource( 0, g_pVertexBuffer, 0, sizeof(Vertex) );


g_pd3dDevice->SetFVF( Vertex::FVF_Flags );
g_pd3dDevice->DrawPrimitive( D3DPT_LINELIST, 0, 3 );

g_pd3dDevice->EndScene();
g_pd3dDevice->Present( NULL, NULL, NULL, NULL );
}

5.Aim:Create a window, place your 2D character, and assign the controls to


handle the character. (controls like up, left, jump, top & bottom)
Step1: Include header files and library files
Step2: Register window class
Step3: Show window
Step4: update window
Step5: Initialize D3D
Step6: Create a rectangle using triangle strip
Step 7: Applied texture on it
Step 8: Create another rectangle , applied texture of the hero and blended that to
the background
Step 9: create a movement function ie adding some constant to the vertices
Step 10 : calling movement function while pressing the virtual keys
Step 11 : release all the objects and devices

#define WIN32_LEAN_AND_MEAN
#define VC_LEANMEAN

#include<d3dx9.h>

#define D3DFVF_D3DVertex (D3DFVF_XYZ | D3DFVF_TEX1 )

bool InitializeDirect3D(HWND hwnd, bool fullscreen);


bool InitializeObject1();
bool InitializeObject2();
void RenderScene();
void ShutdownDirect3D();
void drawPolygon1();
void drawPolygon2();
void drawPolygon3();
bool updating();
bool updating2();
bool InitializeObject3();

LPDIRECT3D9 Direct3D_Object = NULL;


LPDIRECT3DDEVICE9 D3D_Device = NULL;
LPDIRECT3DVERTEXBUFFER9 Vertex_Buffer1 = NULL;
LPDIRECT3DVERTEXBUFFER9 Vertex_Buffer2 = NULL;
LPDIRECT3DVERTEXBUFFER9 Vertex_Buffer3 = NULL;
LPDIRECT3DTEXTURE9 Texture1 = NULL;
LPDIRECT3DTEXTURE9 Texture2 = NULL;
LPDIRECT3DTEXTURE9 Texture3 = NULL;
D3DXMATRIX WorldMatrix;
FLOAT X=-0.07f,Y=0.07f;
FLOAT M=0.07f,N=0.07f;
FLOAT O=-0.07f,P=-0.07f;
FLOAT Q=0.07f,R=-0.07f;

// Vertex stucture.
struct Vertex
{
FLOAT x, y, z; // x, y, and z coordinates.
FLOAT tu, tv; // Texture coordinates.
};

LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam,


LPARAM lParam)
{

switch(message)
{
case WM_KEYDOWN:

switch(wParam)
{
case VK_ESCAPE:
PostQuitMessage(0);
break;

case VK_RIGHT:

if(X<0.4)

X=X+0.01f;
M=M+0.01f;
O=O+0.01f;
Q=Q+0.01f;

updating();
RenderScene();
}
break;

case VK_LEFT:

if(X>(-0.4)||(Y>(0.5)))
{

X=X-0.01f;
M=M-0.01f;
O=O-0.01f;
Q=Q-0.01f;

updating();
RenderScene();
}
break;

case VK_UP:

Y=Y+0.01f;
N=N+0.01f;
P=P+0.01f;
R=R+0.01f;

updating();
RenderScene();
break;

case VK_DOWN:

Y=Y-0.01f;
N=N-0.01f;
P=P-0.01f;
R=R-0.01f;

updating();
RenderScene();
break;

break;

case WM_DESTROY:

case WM_CLOSE:
PostQuitMessage(0);
break;

default:
break;
}

return DefWindowProc( hwnd, message, wParam, lParam );


}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR


lpCmdLine, int nShowCmd)
{

MSG msg;
HWND hwnd;
WNDCLASSEX windowClass;
bool done = false;

// This is the Window class.


windowClass.cbSize = sizeof(WNDCLASSEX);
windowClass.style = CS_HREDRAW | CS_VREDRAW;
windowClass.lpfnWndProc = WndProc;
windowClass.cbClsExtra = 0;
windowClass.cbWndExtra = 0;
windowClass.hInstance = hInstance;
windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);
windowClass.hbrBackground = NULL;
windowClass.lpszMenuName = NULL;
windowClass.lpszClassName = "UGPClass";
windowClass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);

if(!RegisterClassEx(&windowClass)) return 0;

hwnd = CreateWindowEx(NULL,
"UGPClass",
"Dream Simulator",// Window name.
WS_OVERLAPPEDWINDOW | WS_VISIBLE |
WS_SYSMENU |WS_CLIPCHILDREN |
WS_CLIPSIBLINGS,
100, 100,
640, 480,
NULL,
NULL,
hInstance,
NULL);

if(!hwnd) return 0;

ShowWindow(hwnd, SW_SHOW); // Show the window.


UpdateWindow(hwnd); // Update its display.

done = false; // false = run program, true means stop.


if(!InitializeDirect3D(hwnd, true)) done = true;

// Application loop.
while(!done)
{
if(PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE))
{
// If a quit message is received then stop rendering and quit the app.
if(msg.message == WM_QUIT)
{
done = true;
}

TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
RenderScene();
}
}

ShutdownDirect3D();

UnregisterClass("UGPClass", windowClass.hInstance);

return (int)msg.wParam;
}

bool InitializeDirect3D(HWND hwnd, bool fullscreen)


{

D3DDISPLAYMODE DisplayMode;

D3DPRESENT_PARAMETERS Present_Parameters;

D3DCAPS9 D3DCaps;

ZeroMemory(&Present_Parameters, sizeof(Present_Parameters));

Direct3D_Object = Direct3DCreate9(D3D_SDK_VERSION);

if(Direct3D_Object == NULL)
{
MessageBox(NULL, "Error, couldn't initialize DirectX!?!",
"Error!", MB_OK);
return false;
}

if(FAILED(Direct3D_Object->GetAdapterDisplayMode(D3DADAPTER_DEFAULT,
&DisplayMode)))
{
MessageBox(NULL, "Error setting the display mode.", "Error!", MB_OK);
return false;
}

if(FAILED(Direct3D_Object->GetDeviceCaps(D3DADAPTER_DEFAULT,
D3DDEVTYPE_HAL, &D3DCaps)))
return false;

DWORD VertexProcessing = 0;

if(D3DCaps.VertexProcessingCaps != 0)
VertexProcessing |= D3DCREATE_HARDWARE_VERTEXPROCESSING;
else
VertexProcessing |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;

if(fullscreen)
{
Present_Parameters.Windowed = FALSE; // Window mode
(fullscreen).
Present_Parameters.BackBufferWidth = 640;
Present_Parameters.BackBufferHeight = 480;
}
else
Present_Parameters.Windowed = TRUE; // Window mode (not
fullscreen).
Present_Parameters.SwapEffect = D3DSWAPEFFECT_DISCARD; // Dealing with
animation (see doc).
Present_Parameters.BackBufferFormat = DisplayMode.Format;// Render to the
area of the screen.
Present_Parameters.BackBufferCount = 1; // Number of back buffers.
Present_Parameters.EnableAutoDepthStencil = TRUE; // Check
documentation.
Present_Parameters.AutoDepthStencilFormat = D3DFMT_D16; // Check
documentation.

// Now we must create the rendering device.


if(FAILED(Direct3D_Object->CreateDevice(D3DADAPTER_DEFAULT,
D3DDEVTYPE_HAL, hwnd,
VertexProcessing,
&Present_Parameters, &D3D_Device)))
{
MessageBox(NULL, "CreateDevice() failed! Make sure you have DirectX 9.",
"Error!", MB_OK);
return false;
}

// One last check to be sure.


if(D3D_Device == NULL)
{
MessageBox(NULL, "D3D_Device is equal to NULL!?!", "Error!", MB_OK);
return false;
}

D3D_Device->SetRenderState(D3DRS_LIGHTING, FALSE); // Lighting off.


D3D_Device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);// Culling off.
D3D_Device->SetRenderState(D3DRS_ZENABLE, TRUE); // Enable depth
testing.

if(!InitializeObject1()) return false;


if(!InitializeObject2()) return false;
if(!InitializeObject3()) return false;

D3D_Device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);


D3D_Device->SetSamplerState(0, D3DSAMP_MAGFILTER,
D3DTEXF_LINEAR);
D3D_Device->SetSamplerState(0, D3DSAMP_ADDRESSU,
D3DTADDRESS_WRAP);
D3D_Device->SetSamplerState(0, D3DSAMP_ADDRESSV,
D3DTADDRESS_WRAP);

//blending..
D3D_Device->SetRenderState(D3DRS_SRCBLEND,D3DBLEND_SRCALPHA);
D3D_Device-
>SetRenderState(D3DRS_DESTBLEND,D3DBLEND_INVSRCALPHA);
D3D_Device-
>SetTextureStageState(0,D3DTSS_ALPHAARG1,D3DTA_TEXTURE);
D3D_Device-
>SetTextureStageState(0,D3DTSS_ALPHAOP,D3DTOP_SELECTARG1);

return true;
}

Vertex* Vertices2;

bool InitializeObject1()
{

Vertex Polygon_Data1[4] =
{
{-1.0f, 1.0f, 1.0f, 0.0, 0.0},
{1.0f, 1.0f, 1.0f, 1.0, 0.0},
{-1.0f, -1.0f, 1.0f, 0.0, 1.0},
{1.0f, -1.0f, 1.0f, 1.0, 1.0}
};

if(FAILED(D3D_Device->CreateVertexBuffer(sizeof(Polygon_Data1),
0, D3DFVF_D3DVertex,
D3DPOOL_DEFAULT, &Vertex_Buffer1, NULL)))
{
return false;
}

Vertex* Vertices1;

if(FAILED(Vertex_Buffer1->Lock(0, sizeof(Polygon_Data1), (void**)&Vertices1,


0)))
return false;

memcpy(Vertices1, Polygon_Data1, sizeof(Polygon_Data1));

Vertex_Buffer1->Unlock();

if(D3DXCreateTextureFromFile(D3D_Device, "i LIKE2.jpg", &Texture1) != D3D_OK)


return false;

return true;
}

bool InitializeObject2()
{

Vertex Polygon_Data2[4] =
{
{X, Y, 0.0f, 0.0, 0.0},
{M, N, 0.0f, 1.0, 0.0},
{O, P, 0.0f, 0.0, 1.0},
{Q, R, 0.0f, 1.0, 1.0}
};
if(FAILED(D3D_Device->CreateVertexBuffer(sizeof(Polygon_Data2),
0, D3DFVF_D3DVertex,
D3DPOOL_DEFAULT, &Vertex_Buffer2, NULL)))
{
return false;
}

Vertex* Vertices2;

if(FAILED(Vertex_Buffer2->Lock(0, sizeof(Polygon_Data2),(void**)&Vertices2, 0)))


return false;

memcpy(Vertices2, Polygon_Data2, sizeof(Polygon_Data2));

Vertex_Buffer2->Unlock();

if(D3DXCreateTextureFromFile(D3D_Device, "heroGametest.bmp", &Texture2) !=


D3D_OK)
return false;

return true;
}

Vertex* Vertices3;

bool InitializeObject3()
{

Vertex Polygon_Data3[4] =
{

{-1.0f, 1.0f, 0.0f, 0.0, 0.0},


{1.0f, 1.0f, 0.0f, 1.0, 0.0},
{-1.0f, -1.0f, 0.0f, 0.0, 1.0},
{1.0f, -1.0f, 0.0f, 1.0, 1.0}
};

if(FAILED(D3D_Device->CreateVertexBuffer(sizeof(Polygon_Data3),
0, D3DFVF_D3DVertex,
D3DPOOL_DEFAULT, &Vertex_Buffer3, NULL)))
{
return false;
}

//Vertex* Vertices3;

if(FAILED(Vertex_Buffer3->Lock(0, sizeof(Polygon_Data3),(void**)&Vertices3, 0)))


return false;

memcpy(Vertices3, Polygon_Data3, sizeof(Polygon_Data3));

Vertex_Buffer3->Unlock();

if(D3DXCreateTextureFromFile(D3D_Device, "stars4.bmp", &Texture3) != D3D_OK)


return false;

return true;
}

bool updating()
{
Vertex Polygon_Data2[4] =
{
{X, Y, 0.0f, 0.0, 0.0},
{M, N, 0.0f, 1.0, 0.0},
{O, P, 0.0f, 0.0, 1.0},
{Q, R, 0.0f, 1.0, 1.0}
};

if(FAILED(Vertex_Buffer2->Lock(0, sizeof(Polygon_Data2),(void**)&Vertices2, 0)))


return false;

memcpy(Vertices2, Polygon_Data2, sizeof(Polygon_Data2));

Vertex_Buffer2->Unlock();

//if(D3DXCreateTextureFromFile(D3D_Device, "heroGame.bmp", &Texture2) !=


D3D_OK)
// return false;
return true;
}

bool updating2()
{
Vertex Polygon_Data3[4] =
{
{X, Y, 0.0f, 0.0, 0.0},
{M, N, 0.0f, 1.0, 0.0},
{O, P, 0.0f, 0.0, 1.0},
{Q, R, 0.0f, 1.0, 1.0}
};

if(FAILED(Vertex_Buffer3->Lock(0, sizeof(Polygon_Data3),(void**)&Vertices2, 0)))


return false;

memcpy(Vertices3, Polygon_Data3, sizeof(Polygon_Data3));

Vertex_Buffer3->Unlock();

//if(D3DXCreateTextureFromFile(D3D_Device, "heroGame.bmp", &Texture2) !=


D3D_OK)
// return false;

return true;
}

void RenderScene()
{

D3D_Device->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,


D3DCOLOR_XRGB(0,0,0), 1.0f, 0);

D3D_Device->BeginScene();

drawPolygon1();
drawPolygon2();
drawPolygon3();

D3D_Device->EndScene();
D3D_Device->Present(NULL, NULL, NULL, NULL);
}

void drawPolygon1()
{

D3D_Device->SetTexture(0, Texture1);

D3D_Device->SetStreamSource(0, Vertex_Buffer1, 0, sizeof(Vertex));

D3D_Device->SetFVF(D3DFVF_D3DVertex);

D3D_Device->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);

void drawPolygon3()
{

D3D_Device->SetTexture(0,Texture3);
D3D_Device->SetStreamSource(0, Vertex_Buffer3, 0, sizeof(Vertex));
D3D_Device->SetFVF(D3DFVF_D3DVertex);

D3D_Device->SetRenderState(D3DRS_ALPHABLENDENABLE,true);
D3D_Device->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
D3D_Device->SetRenderState(D3DRS_ALPHABLENDENABLE,false);

void drawPolygon2()
{

D3D_Device->SetTexture(0, Texture2);

D3D_Device->SetStreamSource(0, Vertex_Buffer2, 0, sizeof(Vertex));

D3D_Device->SetFVF(D3DFVF_D3DVertex);

D3D_Device->SetRenderState(D3DRS_ALPHABLENDENABLE,true);
D3D_Device->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
D3D_Device->SetRenderState(D3DRS_ALPHABLENDENABLE,false);
}

void ShutdownDirect3D()
{
// Here we release the Direct3D objects.
if(Texture1 != NULL)
{
Texture1->Release();
Texture1 = NULL;
}

if(Texture2 != NULL)
{
Texture2->Release();
Texture2 = NULL;
}

if(D3D_Device != NULL)
{
D3D_Device->Release();
D3D_Device = NULL;
}

if(Direct3D_Object != NULL)
{
Direct3D_Object->Release();
Direct3D_Object = NULL;
}

if(Vertex_Buffer1 != NULL)
{
// Release the buffer.
Vertex_Buffer1->Release();
Vertex_Buffer1 = NULL;
}

if(Vertex_Buffer2 != NULL)
{
// Release the buffer.
Vertex_Buffer2->Release();
Vertex_Buffer2 = NULL;
}
if(Vertex_Buffer3!=NULL)
{
//releasiing the buffer

Vertex_Buffer3->Release();
Vertex_Buffer3=NULL;
}
}

6.Create a program to handle your character’s movement with proper collision


detection. You can allow your character within the limits of window’s boundary.

Step1: Include header files and library files


Step2: Register window class
Step3: Show window
Step4: update window
Step5: Initialize D3D
Step6: Create a rectangle using triangle strip
Step 7: Applied texture on it
Step 8: Create another rectangle , applied texture of the hero and blended that to
the background
Step 9: create a movement function ie adding some constant to the vertices
Step 10 : calling movement function while pressing the virtual keys
Step 11: limiting the movement function to x and y direction simulates collision
detection.
Step 12 : release all the objects and devices

#define WIN32_LEAN_AND_MEAN
#define VC_LEANMEAN
#include<d3dx9.h>
#define D3DFVF_D3DVertex (D3DFVF_XYZ | D3DFVF_TEX1 )
bool InitializeDirect3D(HWND hwnd, bool fullscreen);
bool InitializeObject1();
bool InitializeObject2();
void RenderScene();
void ShutdownDirect3D();
void drawPolygon1();
void drawPolygon2();
void drawPolygon3();
bool updating();
bool updating2();
bool InitializeObject3();
LPDIRECT3D9 Direct3D_Object = NULL;
LPDIRECT3DDEVICE9 D3D_Device = NULL;
LPDIRECT3DVERTEXBUFFER9 Vertex_Buffer1 = NULL;
LPDIRECT3DVERTEXBUFFER9 Vertex_Buffer2 = NULL;
LPDIRECT3DVERTEXBUFFER9 Vertex_Buffer3 = NULL;
LPDIRECT3DTEXTURE9 Texture1 = NULL;
LPDIRECT3DTEXTURE9 Texture2 = NULL;
LPDIRECT3DTEXTURE9 Texture3 = NULL;
D3DXMATRIX WorldMatrix;
FLOAT X=-0.07f,Y=0.07f;
FLOAT M=0.07f,N=0.07f;
FLOAT O=-0.07f,P=-0.07f;
FLOAT Q=0.07f,R=-0.07f;
// Vertex stucture.
struct Vertex
{
FLOAT x, y, z; // x, y, and z coordinates.
FLOAT tu, tv; // Texture coordinates.
};
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam,
LPARAM lParam)
{

switch(message)
{
case WM_KEYDOWN:

switch(wParam)
{
case VK_ESCAPE:
PostQuitMessage(0);
break;

case VK_RIGHT:

if(X<0.4)

X=X+0.01f;
M=M+0.01f;
O=O+0.01f;
Q=Q+0.01f;
updating();
RenderScene();
}
break;

case VK_LEFT:

if(X>(-0.4)||(Y>(0.5)))
{

X=X-0.01f;
M=M-0.01f;
O=O-0.01f;
Q=Q-0.01f;

updating();
RenderScene();
}
break;

case VK_UP:

Y=Y+0.01f;
N=N+0.01f;
P=P+0.01f;
R=R+0.01f;

updating();
RenderScene();
break;

case VK_DOWN:
Y=Y-0.01f;
N=N-0.01f;
P=P-0.01f;
R=R-0.01f;

updating();
RenderScene();
break;

break;
case WM_DESTROY:
case WM_CLOSE:
PostQuitMessage(0);
break;

default:
break;
}
return DefWindowProc( hwnd, message, wParam, lParam );
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR
lpCmdLine, int nShowCmd)
{
MSG msg;
HWND hwnd;
WNDCLASSEX windowClass;
bool done = false;
// This is the Window class.
windowClass.cbSize = sizeof(WNDCLASSEX);
windowClass.style = CS_HREDRAW | CS_VREDRAW;
windowClass.lpfnWndProc = WndProc;
windowClass.cbClsExtra = 0;
windowClass.cbWndExtra = 0;
windowClass.hInstance = hInstance;
windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);
windowClass.hbrBackground = NULL;
windowClass.lpszMenuName = NULL;
windowClass.lpszClassName = "UGPClass";
windowClass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if(!RegisterClassEx(&windowClass)) return 0;

hwnd = CreateWindowEx(NULL,
"UGPClass",
"Dream Simulator",// Window name.
WS_OVERLAPPEDWINDOW | WS_VISIBLE |
WS_SYSMENU |WS_CLIPCHILDREN |
WS_CLIPSIBLINGS,
100, 100,
640, 480,
NULL,
NULL,
hInstance,
NULL);

if(!hwnd) return 0;

ShowWindow(hwnd, SW_SHOW); // Show the window.


UpdateWindow(hwnd); // Update its display.

done = false; // false = run program, true means stop.


if(!InitializeDirect3D(hwnd, true)) done = true;

// Application loop.
while(!done)
{
if(PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE))
{
// If a quit message is received then stop rendering and quit the app.
if(msg.message == WM_QUIT)
{
done = true;
}

TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
RenderScene();
}
}
ShutdownDirect3D();
UnregisterClass("UGPClass", windowClass.hInstance);
return (int)msg.wParam;
}
bool InitializeDirect3D(HWND hwnd, bool fullscreen)
{
D3DDISPLAYMODE DisplayMode;
D3DPRESENT_PARAMETERS Present_Parameters;
D3DCAPS9 D3DCaps;
ZeroMemory(&Present_Parameters, sizeof(Present_Parameters));
Direct3D_Object = Direct3DCreate9(D3D_SDK_VERSION);
if(Direct3D_Object == NULL)
{
MessageBox(NULL, "Error, couldn't initialize DirectX!?!",
"Error!", MB_OK);
return false;
}
if(FAILED(Direct3D_Object->GetAdapterDisplayMode(D3DADAPTER_DEFAULT,
&DisplayMode)))
{
MessageBox(NULL, "Error setting the display mode.", "Error!", MB_OK);
return false;
}

if(FAILED(Direct3D_Object->GetDeviceCaps(D3DADAPTER_DEFAULT,
D3DDEVTYPE_HAL, &D3DCaps)))
return false;

DWORD VertexProcessing = 0;

if(D3DCaps.VertexProcessingCaps != 0)
VertexProcessing |=
D3DCREATE_HARDWARE_VERTEXPROCESSING;
else
VertexProcessing |=
D3DCREATE_SOFTWARE_VERTEXPROCESSING;

if(fullscreen)
{
Present_Parameters.Windowed = FALSE; // Window mode
(fullscreen).
Present_Parameters.BackBufferWidth = 640;
Present_Parameters.BackBufferHeight = 480;
}
else
Present_Parameters.Windowed = TRUE; // Window mode (not
fullscreen).
Present_Parameters.SwapEffect = D3DSWAPEFFECT_DISCARD; // Dealing
with animation (see doc).
Present_Parameters.BackBufferFormat = DisplayMode.Format;// Render to the
area of the screen.
Present_Parameters.BackBufferCount = 1; // Number of back
buffers.
Present_Parameters.EnableAutoDepthStencil = TRUE; // Check
documentation.
Present_Parameters.AutoDepthStencilFormat = D3DFMT_D16; // Check
documentation.

// Now we must create the rendering device.


if(FAILED(Direct3D_Object->CreateDevice(D3DADAPTER_DEFAULT,
D3DDEVTYPE_HAL, hwnd,
VertexProcessing,
&Present_Parameters, &D3D_Device)))
{
MessageBox(NULL, "CreateDevice() failed! Make sure you have DirectX
9.",
"Error!", MB_OK);
return false;
}

// One last check to be sure.


if(D3D_Device == NULL)
{
MessageBox(NULL, "D3D_Device is equal to NULL!?!", "Error!", MB_OK);
return false;
}

D3D_Device->SetRenderState(D3DRS_LIGHTING, FALSE); // Lighting off.


D3D_Device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);// Culling
off.
D3D_Device->SetRenderState(D3DRS_ZENABLE, TRUE); // Enable depth
testing.
if(!InitializeObject1()) return false;
if(!InitializeObject2()) return false;
if(!InitializeObject3()) return false;

D3D_Device->SetSamplerState(0, D3DSAMP_MINFILTER,
D3DTEXF_LINEAR);
D3D_Device->SetSamplerState(0, D3DSAMP_MAGFILTER,
D3DTEXF_LINEAR);
D3D_Device->SetSamplerState(0, D3DSAMP_ADDRESSU,
D3DTADDRESS_WRAP);
D3D_Device->SetSamplerState(0, D3DSAMP_ADDRESSV,
D3DTADDRESS_WRAP);

//blending..
D3D_Device-
>SetRenderState(D3DRS_SRCBLEND,D3DBLEND_SRCALPHA);
D3D_Device-
>SetRenderState(D3DRS_DESTBLEND,D3DBLEND_INVSRCALPHA);
D3D_Device-
>SetTextureStageState(0,D3DTSS_ALPHAARG1,D3DTA_TEXTURE);
D3D_Device-
>SetTextureStageState(0,D3DTSS_ALPHAOP,D3DTOP_SELECTARG1);
return true;
}
Vertex* Vertices2;
bool InitializeObject1()
{
Vertex Polygon_Data1[4] =
{
{-1.0f, 1.0f, 1.0f, 0.0, 0.0},
{1.0f, 1.0f, 1.0f, 1.0, 0.0},
{-1.0f, -1.0f, 1.0f, 0.0, 1.0},
{1.0f, -1.0f, 1.0f, 1.0, 1.0}
};
if(FAILED(D3D_Device->CreateVertexBuffer(sizeof(Polygon_Data1),
0, D3DFVF_D3DVertex,
D3DPOOL_DEFAULT, &Vertex_Buffer1, NULL)))
{
return false;
}
Vertex* Vertices1;
if(FAILED(Vertex_Buffer1->Lock(0, sizeof(Polygon_Data1), (void**)&Vertices1,
0)))
return false;
memcpy(Vertices1, Polygon_Data1, sizeof(Polygon_Data1));
Vertex_Buffer1->Unlock();
if(D3DXCreateTextureFromFile(D3D_Device, "i LIKE2.jpg", &Texture1) !=
D3D_OK)
return false;

return true;
}
bool InitializeObject2()
{
Vertex Polygon_Data2[4] =
{
{X, Y, 0.0f, 0.0, 0.0},
{M, N, 0.0f, 1.0, 0.0},
{O, P, 0.0f, 0.0, 1.0},
{Q, R, 0.0f, 1.0, 1.0}
};
if(FAILED(D3D_Device->CreateVertexBuffer(sizeof(Polygon_Data2),
0, D3DFVF_D3DVertex,
D3DPOOL_DEFAULT, &Vertex_Buffer2, NULL)))
{
return false;
}
Vertex* Vertices2;
if(FAILED(Vertex_Buffer2->Lock(0, sizeof(Polygon_Data2),(void**)&Vertices2,
0)))
return false;
memcpy(Vertices2, Polygon_Data2, sizeof(Polygon_Data2));
Vertex_Buffer2->Unlock();
if(D3DXCreateTextureFromFile(D3D_Device, "heroGametest.bmp", &Texture2) !
= D3D_OK)
return false;
return true;
}
Vertex* Vertices3;
bool InitializeObject3()
{
Vertex Polygon_Data3[4] =
{
{-1.0f, 1.0f, 0.0f, 0.0, 0.0},
{1.0f, 1.0f, 0.0f, 1.0, 0.0},
{-1.0f, -1.0f, 0.0f, 0.0, 1.0},
{1.0f, -1.0f, 0.0f, 1.0, 1.0}
};

if(FAILED(D3D_Device->CreateVertexBuffer(sizeof(Polygon_Data3),
0, D3DFVF_D3DVertex,
D3DPOOL_DEFAULT, &Vertex_Buffer3, NULL)))
{
return false;
}

//Vertex* Vertices3;
if(FAILED(Vertex_Buffer3->Lock(0, sizeof(Polygon_Data3),(void**)&Vertices3,
0)))
return false;
memcpy(Vertices3, Polygon_Data3, sizeof(Polygon_Data3));
Vertex_Buffer3->Unlock();
if(D3DXCreateTextureFromFile(D3D_Device, "stars4.bmp", &Texture3) !=
D3D_OK)
return false;

return true;
}
bool updating()
{
Vertex Polygon_Data2[4] =
{
{X, Y, 0.0f, 0.0, 0.0},
{M, N, 0.0f, 1.0, 0.0},
{O, P, 0.0f, 0.0, 1.0},
{Q, R, 0.0f, 1.0, 1.0}
};
if(FAILED(Vertex_Buffer2->Lock(0, sizeof(Polygon_Data2),(void**)&Vertices2,
0)))
return false;
memcpy(Vertices2, Polygon_Data2, sizeof(Polygon_Data2));

Vertex_Buffer2->Unlock();
//if(D3DXCreateTextureFromFile(D3D_Device, "heroGame.bmp", &Texture2) !=
D3D_OK)
// return false;

return true;
}

bool updating2()
{
Vertex Polygon_Data3[4] =
{
{X, Y, 0.0f, 0.0, 0.0},
{M, N, 0.0f, 1.0, 0.0},
{O, P, 0.0f, 0.0, 1.0},
{Q, R, 0.0f, 1.0, 1.0}
};
if(FAILED(Vertex_Buffer3->Lock(0, sizeof(Polygon_Data3),(void**)&Vertices2,
0)))
return false;
memcpy(Vertices3, Polygon_Data3, sizeof(Polygon_Data3));
Vertex_Buffer3->Unlock();
//if(D3DXCreateTextureFromFile(D3D_Device, "heroGame.bmp", &Texture2) !=
D3D_OK)
// return false;

return true;
}

void RenderScene()
{

D3D_Device->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,


D3DCOLOR_XRGB(0,0,0), 1.0f, 0);

D3D_Device->BeginScene();
drawPolygon1();
drawPolygon2();
drawPolygon3();
D3D_Device->EndScene();
D3D_Device->Present(NULL, NULL, NULL, NULL);
}
void drawPolygon1()
{
D3D_Device->SetTexture(0, Texture1);
D3D_Device->SetStreamSource(0, Vertex_Buffer1, 0, sizeof(Vertex));
D3D_Device->SetFVF(D3DFVF_D3DVertex);
D3D_Device->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);

}
void drawPolygon3()
{

D3D_Device->SetTexture(0,Texture3);
D3D_Device->SetStreamSource(0, Vertex_Buffer3, 0, sizeof(Vertex));
D3D_Device->SetFVF(D3DFVF_D3DVertex);

D3D_Device->SetRenderState(D3DRS_ALPHABLENDENABLE,true);
D3D_Device->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
D3D_Device->SetRenderState(D3DRS_ALPHABLENDENABLE,false);

}
void drawPolygon2()
{
D3D_Device->SetTexture(0, Texture2);

D3D_Device->SetStreamSource(0, Vertex_Buffer2, 0, sizeof(Vertex));

D3D_Device->SetFVF(D3DFVF_D3DVertex);

D3D_Device->SetRenderState(D3DRS_ALPHABLENDENABLE,true);
D3D_Device->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
D3D_Device->SetRenderState(D3DRS_ALPHABLENDENABLE,false);

void ShutdownDirect3D()
{
// Here we release the Direct3D objects.
if(Texture1 != NULL)
{
Texture1->Release();
Texture1 = NULL;
}

if(Texture2 != NULL)
{
Texture2->Release();
Texture2 = NULL;
}

if(D3D_Device != NULL)
{
D3D_Device->Release();
D3D_Device = NULL;
}

if(Direct3D_Object != NULL)
{
Direct3D_Object->Release();
Direct3D_Object = NULL;
}

if(Vertex_Buffer1 != NULL)
{
// Release the buffer.
Vertex_Buffer1->Release();
Vertex_Buffer1 = NULL;
}

if(Vertex_Buffer2 != NULL)
{
// Release the buffer.
Vertex_Buffer2->Release();
Vertex_Buffer2 = NULL;
}
if(Vertex_Buffer3!=NULL)
{
//releasiing the buffer
Vertex_Buffer3->Release();
Vertex_Buffer3=NULL;
}
}

Potrebbero piacerti anche