Sign in to follow this  

DX10 Skybox problem

This topic is 2062 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi guys,
This code is sampled from iedoc's tutorials.Im having problems loading my skybox.
The scene (a terrain with spheres) loads fine. The spheres can be picked, upon picking the last sphere
the skybox appears as a terrain above my own terrain. It appears to be loading the skybox as
a model I have tried everyway i know how but cannot seem to get this to work.
Suggestions much appreciated.
The problem seems where to place this bit here

[CODE]
//draw skymap based off loaded mesh sphere
fxSkyMapVar->SetResource(smrv);
for( UINT p = 0; p < skymaptechDesc.Passes; ++p )
{
SkyMapTechnique->GetPassByIndex( p )->Apply( 0 );
d3dDevice->DrawIndexed(NumFaces * 3, 0, 0);
}
[/CODE]

The full source code

[CODE]
#include <Windows.h>
#include <D3D10_1.h>
#include <d3d10.h>
#include <d3dx10.h>
#include <string>
#include <vector>
#include <dinput.h>
#include <fstream>
#include <istream>
#include <xnamath.h>
#include <DXGI.h>
#include <D2D1.h>
#include <sstream>
#include <dwrite.h>
#include <dinput.h>
#include <mmsystem.h>
#include <cstdlib>
#include <ctime>
#pragma comment (lib, "dinput8.lib")
#pragma comment (lib, "dxguid.lib")
#pragma comment(lib, "D3D10.lib")
#pragma comment(lib, "d3dx10d.lib")
#pragma comment (lib, "DXGI.lib")
#pragma comment (lib, "D2D1.lib")
#pragma comment (lib, "dwrite.lib")
#pragma comment (lib, "winmm.lib")
using namespace std;
LPCTSTR WndClassName = L"firstwindow";
HWND hwnd = NULL;
const int Width = 800;
const int Height = 600;
bool InitializeWindow(HINSTANCE hInstance,
int ShowWnd,
int width, int height,
bool windowed);
HRESULT hr;
ID3D10Device* d3dDevice;
IDXGISwapChain* SwapChain;
ID3D10RenderTargetView* RenderTargetView;
ID3D10Effect* FX;
ID3D10InputLayout* VertexLayout;
ID3D10InputLayout* pVertexLayout;
ID3D10EffectVariable* fxLightVar;
D3DXMATRIX Rotation;
float rot = 0.01f;
/********************************************************************************************/
ID3D10InputLayout* mVertexLayout;
/********************************************************************************************/
ID3D10Buffer* VertexBuffer;
ID3D10Buffer* IndexBuffer;
ID3D10EffectTechnique* Technique;
ID3D10DepthStencilView* DepthStencilView;
ID3D10Texture2D* DepthStencilBuffer;
D3DXMATRIX WVP;
ID3D10EffectMatrixVariable* fxWVPVar;
D3DXMATRIX World;
D3DXMATRIX View;
D3DXMATRIX Projection;
IDirectInputDevice8* DIKeyboard;
IDirectInputDevice8* DIMouse;
DIMOUSESTATE mouseLastState;
LPDIRECTINPUT8 DirectInput;
///////////////////textures/////////////////////////////////////////////////////////////////////
ID3D10ShaderResourceView* DiffuseMapResourceView;
ID3D10EffectShaderResourceVariable* fxDiffuseMapVar;
ID3D10Buffer* cbPerObjectBuffer;
std::vector<ID3D10ShaderResourceView*> meshSRV;
std::vector<std::wstring> textureNameArray;
/********************************************************************************************/
D3DXMATRIX camView;
D3DXMATRIX camProjection;
/********************************************************************************************/
ID3D10VertexShader* VS;
ID3D10PixelShader* PS;
ID3D10VertexShader* SKYMAP_VS;
ID3D10PixelShader* SKYMAP_PS;
ID3D10Blob* SKYMAP_VS_Buffer;
ID3D10Blob* SKYMAP_PS_Buffer;
ID3D10Blob* D2D_PS_Buffer;
ID3D10Blob* VS_Buffer;
ID3D10Blob* PS_Buffer;
ID3D10PixelShader* D2D_PS;
ID3D10SamplerState* CubesTexSamplerState;
ID3D10RasterizerState* RSCullNone;
////////////////////textures/////////////////////////////////////////////////////////////////
/////////////////////////skybox/////////////////////////////////////////////////
ID3D10EffectShaderResourceVariable* fxSkyMapVar;
ID3D10ShaderResourceView* smrv = 0;
ID3D10EffectTechnique* SkyMapTechnique;
void CreateSphere(int LatLines, int LongLines);
/////////////////////////skybox////////////////////////////////////////////////
//////////////////////load model///////////////////////////////////////////////
vector<ID3DX10Mesh*> meshes;
int meshCount;
bool LoadMesh(wstring filename);
vector<UINT> meshSubsets;
int meshTextures = 0;
vector<ID3D10ShaderResourceView*> TextureResourceViews;
D3DXMATRIX Scale;
D3DXMATRIX Translation;
D3DXMATRIX Transformations;
//////////picker
bool isShoot = false;
void pick(float mouseX, float mouseY);
int numSpheres = 10;
int spheres[10];
D3DXMATRIX SphereLocalSpace[100];
int ClientWidth = 0;
int ClientHeight = 0;
void CreateSphere(int LatLines, int LongLines);
////////picker
///////////////timer scores////////////////////////////////////////////////
ID3DX10Font* Font;
wstring printScoreFPS = L"";
int totalScore = 0;

__int64 frameTimeOld = 0;
double gameTime;
//gametime
// Some global variables used to measure the time
void InitGameTime();
float GetGameTime();
int TimeLeft = 100;
int constTimeLeft = 100; // This will be used to subtract GetGameTime() from, and store it into TimeLeft
float timeAtGameStart = 0;
float oldTime = 0;
UINT64 ticksPerSecond;
// Global variables for measuring fps
float lastUpdate = 0;
float fpsUpdateInterval = 2.5f;
int numFrames = 0;
float fps = 0;
/////////////////////////timer scores//////////////////////////////////
//////////////////////load model ///////////////////////////////////////////////
ID3DX10Mesh* sphereBoundingBox;
ID3D10ShaderResourceView* BoundingBoxTexture;
bool showBoundingVolumes = true;
bool spacePress = false;
int bbShots;

ID3D10RasterizerState* WireFrame;
DWORD NumVertices;
DWORD NumFaces;
DWORD rows = 100;
DWORD cols = 100;
float moveLeftRight = 0.0f;
float moveBackForward = 0.0f;
//camera start position
D3DXVECTOR3 Position = D3DXVECTOR3( 50.0f, 15.0f, 10.0f );
D3DXVECTOR3 Target = D3DXVECTOR3( 0.0f, 0.0f, 1.0f);
D3DXVECTOR3 Up = D3DXVECTOR3( 0.0f, 1.0f, 0.0f );
D3DXVECTOR3 DefaultForward = D3DXVECTOR3(0.0f,0.0f,1.0f);
D3DXVECTOR3 DefaultRight = D3DXVECTOR3(1.0f,0.0f,0.0f);
D3DXVECTOR3 Forward = D3DXVECTOR3(0.0f,0.0f,1.0f);
D3DXVECTOR3 Right = D3DXVECTOR3(1.0f,0.0f,0.0f);
D3DXMATRIX rotationMatrix;
float yaw = 0.0f;
float pitch = 0.0f;
void UpdateCamera();
bool InitializeDirect3dApp(HINSTANCE hInstance);
bool InitDirectInput(HINSTANCE hInstance);
void DetectInput();
bool InitScene();
void DrawScene();
bool ReleaseObjects();
int messageloop();
LRESULT CALLBACK WndProc(HWND hWnd,
UINT msg,
WPARAM wParam,
LPARAM lParam);
struct Vertex
{
Vertex(){}
Vertex(float x, float y, float z, float u, float v,
float fr, float fg, float fb, float fa)
: pos(x,y,z), texCoord(u, v), color(fr, fg, fb, fa) {}
D3DXVECTOR3 pos;

D3DXVECTOR2 texCoord;
D3DXCOLOR color;

};
///////////////////////////vertex struct for sphere model
struct pVertex
{
pVertex(){}
pVertex(float x, float y, float z,
float u, float v, float nx, float ny, float nz)
: ppos(x,y,z), ptexCoord(u,v), pnormal(nx,ny,nz){}
D3DXVECTOR3 ppos;
D3DXVECTOR2 ptexCoord;
D3DXVECTOR3 pnormal;
};
//Create effects constant buffer's structure//
struct cbPerObject
{
XMMATRIX WVP;
XMMATRIX World;
//These will be used for the pixel shader
XMFLOAT4 difColor;
BOOL hasTexture;
//Because of HLSL structure packing, we will use windows BOOL
//instead of bool because HLSL packs things into 4 bytes, and
//bool is only one byte, where BOOL is 4 bytes
BOOL hasNormMap;
};

struct Light
{
Light()
{
ZeroMemory(this, sizeof(Light));
}
D3DXVECTOR3 dir;
float pad;
D3DXCOLOR ambient;
D3DXCOLOR diffuse;
};
Light light;
cbPerObject cbPerObj;
D3D10_INPUT_ELEMENT_DESC layout[] =
{
{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
////////////////////new//////////////////////////////////////////////////////////////////////
{"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0},
////////////////////new//////////////////////////////////////////////////////////////////////
{"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 20, D3D10_INPUT_PER_VERTEX_DATA, 0},
// For the vertex shader to work correctly, you must make sure that the vertex shader does not
// take more input than the input layout provides. For example, you can have a vertex shader
// that takes position and color only, and an input layout that provides position, color, and tex coords,
// but you cannot have a vertex shader that takes in position, color, and tex coords if the input layout
// only provides position and color. The vertex shader (VS) in the vertex.fx file takes in position, tex coords,
// color, normals, and tangents, so we need to make sure our input layout also provides AT LEAST that many elements,
// even if we are not using all of them
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 36, D3D10_INPUT_PER_VERTEX_DATA, 0},
{ "TANGENT", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 48, D3D10_INPUT_PER_VERTEX_DATA, 0}
};
/********************************************************************************************/
D3D10_INPUT_ELEMENT_DESC pLayout[] =
{
{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
////////////////////new//////////////////////////////////////////////////////////////////////
{"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0},
////////////////////new//////////////////////////////////////////////////////////////////////
{"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 20, D3D10_INPUT_PER_VERTEX_DATA, 0},
};
/********************************************************************************************/
int WINAPI WinMain(HINSTANCE hInstance, //Main windows function
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nShowCmd)
{
if(!InitializeWindow(hInstance, nShowCmd, Width, Height, false))
{
MessageBox(0, L"Window Initialization - Failed",
L"Error", MB_OK);
return 0;
}
if(!InitializeDirect3dApp(hInstance))
{
MessageBox(0, L"Direct3D Initialization - Failed",
L"Error", MB_OK);
return 0;
}
if(!InitDirectInput(hInstance))
{
MessageBox(0, L"Direct Input Initialization - Failed",
L"Error", MB_OK);
return 0;
}
if(!InitScene())
{
MessageBox(0, L"Scene Initialization - Failed",
L"Error", MB_OK);
return 0;
}
messageloop();
if(!ReleaseObjects())
{
MessageBox(0, L"Object Releasing - Failed",
L"Error", MB_OK);
return 0;
}
return 0;
}


/////////////////////picker///////////////////////////////////////////////
void pick(float mouseX, float mouseY)
{
//Transform 2D pick position on screen space to 3D ray in View space
D3DXVECTOR3 pickRayViewSpace;
pickRayViewSpace.x = ((( 2.0f * mouseX) / ClientWidth ) - 1 ) / Projection(0,0);
pickRayViewSpace.y = -((( 2.0f * mouseY) / ClientHeight) - 1 ) / Projection(1,1);
pickRayViewSpace.z = 1.0f;
D3DXVECTOR3 pickRayViewSpacePos(0.0f, 0.0f, 0.0f);
D3DXVECTOR3 pickRayViewSpaceDir(pickRayViewSpace.x, pickRayViewSpace.y, pickRayViewSpace.z);
// Transform 3D Ray from View space to 3D ray in World space
D3DXMATRIX pickRayWorldSpace;
D3DXMatrixInverse(&pickRayWorldSpace, 0, &View);
D3DXVec3TransformCoord(&pickRayViewSpacePos, &pickRayViewSpacePos, &pickRayWorldSpace);
D3DXVec3TransformNormal(&pickRayViewSpaceDir, &pickRayViewSpaceDir, &pickRayWorldSpace);
// Transform 3D Ray from World space to each objects/models own local space
int closestObject = -1;
float closestObjectDist = FLT_MAX;
for(int i = 0; i < numSpheres; i++)
{
if(spheres[i] == 1)
{
D3DXMATRIX pickRayLocalSpace;
D3DXMatrixInverse(&pickRayLocalSpace,NULL,&SphereLocalSpace[i]);
D3DXVECTOR3 pickRayLocalSpacePos,pickRayLocalSpaceDir;
D3DXVec3TransformCoord(&pickRayLocalSpacePos,&pickRayViewSpacePos,&pickRayLocalSpace);
D3DXVec3TransformNormal(&pickRayLocalSpaceDir,&pickRayViewSpaceDir,&pickRayLocalSpace);
D3DXVec3Normalize(&pickRayLocalSpaceDir,&pickRayLocalSpaceDir);
UINT numHits = 0;
float hitDistance;
meshes[0]->Intersect(&pickRayLocalSpacePos, &pickRayLocalSpaceDir, &numHits,
0, 0, 0, &hitDistance, 0);
//Find nearest object hit, if any
if(numHits > 0)
{
if(hitDistance < closestObjectDist)
{
closestObject = i;
closestObjectDist = hitDistance;
}
}
}
}
if(closestObject >= 0)
{
spheres[closestObject] = 0;
totalScore++;

}
}
////////////////////picker/////////////////////////////////////////////////

/************************************Heightmap Stuff****************************************************/
struct HeightMapInfo{
int terrainWidth;
int terrainHeight;
D3DXVECTOR3 *heightMap;
};
bool HeightMapLoad(char* filename, HeightMapInfo &hminfo)
{
FILE *filePtr;
BITMAPFILEHEADER bitmapFileHeader;
BITMAPINFOHEADER bitmapInfoHeader;
int imageSize, index;
unsigned char height;
// Open the file
filePtr = fopen(filename,"rb");
if (filePtr == NULL)
return 0;
// Read bitmaps header
fread(&bitmapFileHeader, sizeof(BITMAPFILEHEADER), 1,filePtr);

// Read the info header
fread(&bitmapInfoHeader, sizeof(BITMAPINFOHEADER), 1, filePtr);
// Get the width and height (width and length) of the image
hminfo.terrainWidth = bitmapInfoHeader.biWidth;
hminfo.terrainHeight = bitmapInfoHeader.biHeight;
// Size of the image in bytes. the 3 represents RBG for each pixel
imageSize = hminfo.terrainWidth * hminfo.terrainHeight * 3;
// Initialize the array which stores the image data
unsigned char* bitmapImage = new unsigned char[imageSize];
// Go to the beginning of the image data
fseek(filePtr, bitmapFileHeader.bfOffBits, SEEK_SET);
// Store image data in bitmapImage
fread(bitmapImage, 1, imageSize, filePtr);
// Close file
fclose(filePtr);
// Initialize the heightMap array (stores the vertices of our terrain)
hminfo.heightMap = new D3DXVECTOR3[hminfo.terrainWidth * hminfo.terrainHeight];
// We use a greyscale image, so all 3 rgb values are the same, but we only need one for the height
// So we use this counter to skip 3 values in the image data
int k=0;
int Ter;

srand(time(0));
for (int x=0; x<5; x++)
{
Ter = rand()%10;
}
// Read the image data into our heightMap array
for(int j=0; j< hminfo.terrainHeight; j++)
{
for(int i=0; i< hminfo.terrainWidth; i++)
{
height = bitmapImage[k];

index = ( hminfo.terrainHeight * j) + i;
hminfo.heightMap[index].x = (float)i;
//control height of vertices
hminfo.heightMap[index].y = (float)height / 6;
hminfo.heightMap[index].z = (float)j;
k+=3;
}
}
delete [] bitmapImage;
bitmapImage = 0;
return true;
}
/************************************Heightmap Stuff****************************************************/
bool InitializeWindow(HINSTANCE hInstance,
int ShowWnd,
int width, int height,
bool windowed)
{
typedef struct _WNDCLASS {
UINT cbSize;
UINT style;
WNDPROC lpfnWndProc;
int cbClsExtra;
int cbWndExtra;
HANDLE hInstance;
HICON hIcon;
HCURSOR hCursor;
HBRUSH hbrBackground;
LPCTSTR lpszMenuName;
LPCTSTR lpszClassName;
} WNDCLASS;
WNDCLASSEX wc;
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = NULL;
wc.cbWndExtra = NULL;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 2);
wc.lpszMenuName = NULL;
wc.lpszClassName = WndClassName;
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if (!RegisterClassEx(&wc))
{
MessageBox(NULL, L"Error registering class",
L"Error", MB_OK | MB_ICONERROR);
return 1;
}
hwnd = CreateWindowEx(
NULL,
WndClassName,
L"Window Title",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
width, height,
NULL,
NULL,
hInstance,
NULL
);
if (!hwnd)
{
MessageBox(NULL, L"Error creating window",
L"Error", MB_OK | MB_ICONERROR);
return 1;
}
ShowWindow(hwnd, ShowWnd);
UpdateWindow(hwnd);

return true;
}
bool InitializeDirect3dApp(HINSTANCE hInstance)
{
UINT createDeviceFlags = 0;
D3D10_DRIVER_TYPE driverTypes[] =
{
D3D10_DRIVER_TYPE_HARDWARE,
D3D10_DRIVER_TYPE_REFERENCE,
};
UINT numDriverTypes = sizeof( driverTypes ) / sizeof( driverTypes[0] );
DXGI_SWAP_CHAIN_DESC scd;
scd.BufferDesc.Width = Width;
scd.BufferDesc.Height = Height;
scd.BufferDesc.RefreshRate.Numerator = 60;
scd.BufferDesc.RefreshRate.Denominator = 1;
scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
scd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
scd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
//no multisampling
scd.SampleDesc.Count = 1;
scd.SampleDesc.Quality = 0;
scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
scd.BufferCount = 1;
scd.OutputWindow = hwnd;
scd.Windowed = true;
scd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
scd.Flags = 0;
D3D10CreateDeviceAndSwapChain(0, D3D10_DRIVER_TYPE_HARDWARE, 0, 0, D3D10_SDK_VERSION, &scd, &SwapChain, &d3dDevice);
ID3D10Texture2D* backBuffer;
SwapChain->GetBuffer(0, _uuidof(ID3D10Texture2D), reinterpret_cast<void**>(&backBuffer));
d3dDevice->CreateRenderTargetView(backBuffer, 0, &RenderTargetView);
backBuffer->Release();
D3D10_TEXTURE2D_DESC depthStencilDesc;
depthStencilDesc.Width = Width;
depthStencilDesc.Height = Height;
depthStencilDesc.MipLevels = 1;
depthStencilDesc.ArraySize = 1;
depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthStencilDesc.SampleDesc.Count = 1;
depthStencilDesc.SampleDesc.Quality = 0;
depthStencilDesc.Usage = D3D10_USAGE_DEFAULT;
depthStencilDesc.BindFlags = D3D10_BIND_DEPTH_STENCIL;
depthStencilDesc.CPUAccessFlags = 0;
depthStencilDesc.MiscFlags = 0;
d3dDevice->CreateTexture2D(&depthStencilDesc, NULL, &DepthStencilBuffer);
d3dDevice->CreateDepthStencilView(DepthStencilBuffer, NULL, &DepthStencilView);
d3dDevice->OMSetRenderTargets(1, &RenderTargetView, DepthStencilView);
// Setup the viewport
D3D10_VIEWPORT vp;
vp.Width = Width;
vp.Height = Height;
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
vp.TopLeftX = 0;
vp.TopLeftY = 0;
d3dDevice->RSSetViewports( 1, &vp );
D3DXMatrixIdentity( &World );

Position = D3DXVECTOR3( 10.0f, 30.0f, 10.0f );
Target = D3DXVECTOR3( 0.0f, 0.0f, 0.0f );
Up = D3DXVECTOR3( 0.0f, 1.0f, 0.0f );
D3DXMatrixLookAtLH( &View, &Position, &Target, &Up );
return true;
}
bool InitDirectInput(HINSTANCE hInstance)
{
DirectInput8Create(hInstance,
DIRECTINPUT_VERSION,
IID_IDirectInput8,
(void**)&DirectInput,
NULL);
DirectInput->CreateDevice(GUID_SysKeyboard,
&DIKeyboard,
NULL);
DirectInput->CreateDevice(GUID_SysMouse,
&DIMouse,
NULL);
DIKeyboard->SetDataFormat(&c_dfDIKeyboard);
DIKeyboard->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
DIMouse->SetDataFormat(&c_dfDIMouse);
DIMouse->SetCooperativeLevel(hwnd, DISCL_NONEXCLUSIVE | DISCL_NOWINKEY | DISCL_FOREGROUND);
return true;
}
void UpdateCamera()
{
D3DXMatrixRotationYawPitchRoll( &rotationMatrix, yaw, pitch, 0 );
D3DXVec3TransformCoord( &Target, &DefaultForward, &rotationMatrix );
D3DXVec3Normalize( &Target, &Target );
//D3DXMATRIX RotateYTempMatrix;
//D3DXMatrixRotationY(&RotateYTempMatrix, yaw);


/************************************Heightmap Stuff****************************************************/
// Just changed the camera from first person to free look
D3DXVec3TransformNormal(&Right, &DefaultRight, &rotationMatrix);
D3DXVec3TransformNormal(&Forward, &DefaultForward, &rotationMatrix);
D3DXVec3Cross(&Up, &Forward, &Right);
/************************************Heightmap Stuff****************************************************/

Position += moveLeftRight*Right;
Position += moveBackForward*Forward;
moveLeftRight = 0.0f;
moveBackForward = 0.0f;
Target = Position + Target;
D3DXMatrixLookAtLH( &View, &Position, &Target, &Up );
}
void DetectInput()
{
float speed = 0.2f;
//float speed = 10.0f * numFrames;

DIMOUSESTATE mouseCurrState;
BYTE keyboardState[256];
DIKeyboard->Acquire();
DIMouse->Acquire();
DIMouse->GetDeviceState(sizeof(DIMOUSESTATE), &mouseCurrState);
DIKeyboard->GetDeviceState(sizeof(keyboardState),(LPVOID)&keyboardState);
/////////////////////////new/////////////////////////////////////////////////
if(keyboardState[DIK_ESCAPE] & 0x80)
{
SwapChain->SetFullscreenState(false, NULL);
PostMessage(hwnd, WM_DESTROY, 0, 0);
}
/////////////////////////new/////////////////////////////////////////////////
if(keyboardState[DIK_A] & 0x80)
{
moveLeftRight -= speed;
}
if(keyboardState[DIK_D] & 0x80)
{
moveLeftRight += speed;
}
if(keyboardState[DIK_W] & 0x80)
{
moveBackForward += speed;
}
if(keyboardState[DIK_S] & 0x80)
{
moveBackForward -= speed;
}

if((mouseCurrState.lX != mouseLastState.lX) || (mouseCurrState.lY != mouseLastState.lY))
{
yaw += mouseLastState.lX * 0.01f;
pitch += mouseCurrState.lY * 0.001f;
mouseLastState = mouseCurrState;
}
/////////////////////////new/////////////////////////////////////////////////
if(mouseCurrState.rgbButtons[0])
{
if(isShoot == false)
{
POINT mousePos;
GetCursorPos(&mousePos);
ScreenToClient(hwnd, &mousePos);
int mousex = mousePos.x;
int mousey = mousePos.y;
pick(mousex, mousey);
isShoot = true;
}
}
if(!mouseCurrState.rgbButtons[0])
{
isShoot = false;
}
/////////////////////////new/////////////////////////////////////////////////
UpdateCamera();
return;
}

//my countdown timer********************************
// Called once at the start of the game
void InitGameTime()
{
// We need to know how often the clock is updated
if( !QueryPerformanceFrequency((LARGE_INTEGER *)&ticksPerSecond) )
ticksPerSecond = 1000;
// If timeAtGameStart is 0 then we get the time since
// the start of the computer when we call GetGameTime()
timeAtGameStart = 0;
timeAtGameStart = GetGameTime();
}
///fps Called once for every frame
// You don't even need this function
int UpdateFPS()
{
numFrames++;
float currentUpdate = GetGameTime();
if( currentUpdate - lastUpdate > fpsUpdateInterval )
{
fps = numFrames / (currentUpdate - lastUpdate);
lastUpdate = currentUpdate;
numFrames = 0;
}
return fps;
}
// Called every time you need the current game time
/*************** To make this clear, this function returns the time IN SECONDS since the start of the game */
float GetGameTime()
{
UINT64 ticks;
float time;
// This is the number of clock ticks since start
if( !QueryPerformanceCounter((LARGE_INTEGER *)&ticks) )
ticks = (UINT64)timeGetTime();
// Divide by frequency to get the time in seconds
time = (float)(__int64)ticks/(float)(__int64)ticksPerSecond;
// Subtract the time at game start to get
// the time since the game started
time -= timeAtGameStart;
//added this
/* if(TimeLeft>0)
{
/***********************This is called once per frame. It has nothing to do with the time.
TimeLeft will decrease one every frame, even if the frames per second is 500 or 1. On faster computers
where the fps is 500, then in one second, TimeLeft will subtract 500. but on slower computers, where the fps
is 3, then TimeLeft will subtract only 3 in one second.*/
/*TimeLeft -= 1.0f/UpdateFPS();

}*/
//exit condition
if (TimeLeft==0)
{
MessageBox(NULL, L"GAME OVER: EXIT GAME",
L"GAME OVER", MB_YESNO | MB_ICONQUESTION == IDYES);
DestroyWindow(hwnd);

}
return time;
}

//*********countdown timer ********************************
/////////////////////////new/////////////////////////////////////////////////
//////////////////////load model////////////////////////////////////////////
bool LoadMesh(wstring filename)
{
HRESULT hr = 0;
ID3DX10Mesh* tempMesh;
wifstream fileIn (filename.c_str());
wstring skipString;
UINT meshVertices = 0;
UINT meshTriangles = 0;
UINT tempMeshSubsets = 0;
if (fileIn)
{
fileIn >> skipString; // #Subsets
fileIn >> tempMeshSubsets;
fileIn >> skipString; // #Vertices
fileIn >> meshVertices;
fileIn >> skipString; // #Faces (Triangles)
fileIn >> meshTriangles;

meshSubsets.push_back(tempMeshSubsets);
hr = D3DX10CreateMesh(d3dDevice,
/********************************************************************************************/
pLayout,
/********************************************************************************************/
3,
layout[0].SemanticName,
meshVertices,
meshTriangles,
D3DX10_MESH_32_BIT,
&tempMesh);
if(FAILED(hr))
{
MessageBox(0, L"Mesh Creation - Failed",
L"Error", MB_OK);
return false;
}
fileIn >> skipString; //#Subset_info
for(UINT i = 0; i < tempMeshSubsets; ++i)
{
std::wstring diffuseMapFilename;
fileIn >> diffuseMapFilename;
ID3D10ShaderResourceView* DiffuseMapResourceView;
D3DX10CreateShaderResourceViewFromFile(d3dDevice,
diffuseMapFilename.c_str(), 0, 0, &DiffuseMapResourceView, 0 );
TextureResourceViews.push_back(DiffuseMapResourceView);
meshTextures++;
}
pVertex* verts = new pVertex[meshVertices];
fileIn >> skipString; //#Vertex_info
for(UINT i = 0; i < meshVertices; ++i)
{
fileIn >> skipString; //Vertex Position
fileIn >> verts[i].ppos.x;
fileIn >> verts[i].ppos.y;
fileIn >> verts[i].ppos.z;
fileIn >> skipString; //Vertex Normal
fileIn >> verts[i].pnormal.x;
fileIn >> verts[i].pnormal.y;
fileIn >> verts[i].pnormal.z;
fileIn >> skipString; //Vertex Texture Coordinates
fileIn >> verts[i].ptexCoord.x;
fileIn >> verts[i].ptexCoord.y;
}
tempMesh->SetVertexData(0, verts);
delete[] verts;
DWORD* indices = new DWORD[meshTriangles*3];
UINT* attributeIndex = new UINT[meshTriangles];
fileIn >> skipString; //#Face_Index
for(UINT i = 0; i < meshTriangles; ++i)
{
fileIn >> indices[i*3+0];
fileIn >> indices[i*3+1];
fileIn >> indices[i*3+2];
fileIn >> attributeIndex[i]; //Current Subset
}
tempMesh->SetIndexData(indices, meshTriangles*3);
tempMesh->SetAttributeData(attributeIndex);
delete[] indices;
delete[] attributeIndex;
tempMesh->GenerateAdjacencyAndPointReps(0.001f);
tempMesh->Optimize(D3DX10_MESHOPT_ATTR_SORT|D3DX10_MESHOPT_VERTEX_CACHE,0,0);
tempMesh->CommitToDevice();
meshCount++;
meshes.push_back(tempMesh);
}
else
{
MessageBox(0, L"Load Mesh File - Failed",
L"Error", MB_OK);
return false;
}

return true;
}
/////////////
void CreateSphere(int LatLines, int LongLines)
{
NumVertices = LatLines * LongLines;
NumFaces = (LatLines-1)*(LongLines-1)*2;
float sphereYaw = 0.0f;
float spherePitch = 0.0f;
std::vector<Vertex> vertices(NumVertices);
D3DXVECTOR3 currVertPos = D3DXVECTOR3(0.0f, 1.0f, 0.0f);
for(DWORD i = 0; i < LatLines; ++i)
{
sphereYaw = i * (3.14/LatLines);
for(DWORD j = 0; j < LongLines; ++j)
{
spherePitch = j * (3.14/LongLines);
D3DXMatrixRotationYawPitchRoll( &rotationMatrix, sphereYaw, spherePitch, 0 );
D3DXVec3TransformCoord( &currVertPos, &DefaultForward, &rotationMatrix );
D3DXVec3Normalize( &currVertPos, &currVertPos );
vertices[i*LongLines+j].pos = currVertPos;
}
}
D3D10_BUFFER_DESC bd;
bd.Usage = D3D10_USAGE_IMMUTABLE;
bd.ByteWidth = sizeof( Vertex ) * NumVertices;
bd.BindFlags = D3D10_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = 0;
bd.MiscFlags = 0;
D3D10_SUBRESOURCE_DATA InitData;
InitData.pSysMem = &vertices[0];
d3dDevice->CreateBuffer( &bd, &InitData, &VertexBuffer );
std::vector<DWORD> indices(NumFaces * 3);
int k = 0;
for(DWORD i = 0; i < LatLines-1; ++i)
{
for(DWORD j = 0; j < LongLines-1; ++j)
{
indices[k] = i*LongLines+j;
indices[k+1] = i*LongLines+j+1;
indices[k+2] = (i+1)*LongLines+j;
indices[k+3] = (i+1)*LongLines+j;
indices[k+4] = i*LongLines+j+1;
indices[k+5] = (i+1)*LongLines+j+1;
k += 6;
}
}
D3D10_BUFFER_DESC ibd;
ibd.Usage = D3D10_USAGE_IMMUTABLE;
ibd.ByteWidth = sizeof(DWORD) * NumFaces * 3;
ibd.BindFlags = D3D10_BIND_INDEX_BUFFER;
ibd.CPUAccessFlags = 0;
ibd.MiscFlags = 0;
D3D10_SUBRESOURCE_DATA iinitData;
iinitData.pSysMem = &indices[0];
d3dDevice->CreateBuffer(&ibd, &iinitData, &IndexBuffer);
UINT stride = sizeof( Vertex );
UINT offset = 0;
d3dDevice->IASetVertexBuffers( 0, 1, &VertexBuffer, &stride, &offset );
d3dDevice->IASetIndexBuffer(IndexBuffer, DXGI_FORMAT_R32_UINT, 0);
}

///////////////////////load model////////////////////////////////////////////
bool InitScene()
{
InitGameTime();
ID3D10Blob* compilationErrors = 0;
HRESULT hr = 0;

/////////////////////////new/////////////////////////////////////////////////
D3DX10_FONT_DESC fd;
fd.Height = 25;
fd.Width = 0;
fd.Weight = 0;
fd.MipLevels = 1;
fd.Italic = false;
fd.CharSet = OUT_DEFAULT_PRECIS;
fd.Quality = DEFAULT_QUALITY;
fd.PitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
wcscpy_s(fd.FaceName, L"Arial");
D3DX10CreateFontIndirect(d3dDevice, &fd, &Font);
/////////////////////////new/////////////////////////////////////////////////
LoadMesh(L"sphere.dat"); //meshes[0]
for(int i = 0; i < 3; i++)
{
spheres[i] = 1;
}
CreateSphere(10, 10);
/************************************Heightmap Stuff****************************************************/
HeightMapInfo hmInfo;
HeightMapLoad("heightmap.bmp", hmInfo);
cols = hmInfo.terrainWidth;
rows = hmInfo.terrainHeight;
NumVertices = rows * cols;
NumFaces = (rows-1)*(cols-1)*3;
std::vector<Vertex> vertices(NumVertices);
for(DWORD i = 0; i < rows; ++i)
{
for(DWORD j = 0; j < cols; ++j)
{
float x = ((cols - 1) * 0.5f) - j;
vertices[i*cols+j].pos = hmInfo.heightMap[i*cols+j];
vertices[i*cols+j].color = D3DXCOLOR(0.0f, 1.0f, 1.0f, 1.0f);
}
}
/************************************Heightmap Stuff****************************************************/
std::vector<DWORD> indices(NumFaces * 3);
int k = 0;
float texUIndex = 0;
float texVIndex = 0;
for(DWORD i = 0; i < rows-1; i++)
{
for(DWORD j = 0; j < cols-1; j++)
{
indices[k] = i*cols+j;
vertices[i*cols+j].texCoord = D3DXVECTOR2(texUIndex + 0.0f, texVIndex + 1.0f); // Bottom left of quad
indices[k+1] = i*cols+j+1;
vertices[i*cols+j+1].texCoord = D3DXVECTOR2(texUIndex + 1.0f, texVIndex + 1.0f); // Bottom right of quad
indices[k+2] = (i+1)*cols+j;
vertices[(i+1)*cols+j].texCoord = D3DXVECTOR2(texUIndex + 0.0f, texVIndex + 0.0f); // Top left of quad

indices[k+3] = (i+1)*cols+j;
vertices[(i+1)*cols+j].texCoord = D3DXVECTOR2(texUIndex + 0.0f, texVIndex + 0.0f); // Top left of quad
indices[k+4] = i*cols+j+1;
vertices[i*cols+j+1].texCoord = D3DXVECTOR2(texUIndex + 1.0f, texVIndex + 1.0f); // Bottom right of quad
indices[k+5] = (i+1)*cols+j+1;
vertices[(i+1)*cols+j+1].texCoord = D3DXVECTOR2(texUIndex + 1.0f, texVIndex + 0.0f); // Top right of quad
k += 6; // next quad
texUIndex++;
}
texUIndex = 0;
texVIndex++;
}
D3D10_BUFFER_DESC bd;
bd.Usage = D3D10_USAGE_IMMUTABLE;
bd.ByteWidth = sizeof( Vertex ) * NumVertices;
bd.BindFlags = D3D10_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = 0;
bd.MiscFlags = 0;
D3D10_SUBRESOURCE_DATA InitData;
InitData.pSysMem = &vertices[0];
d3dDevice->CreateBuffer( &bd, &InitData, &VertexBuffer );
D3D10_BUFFER_DESC ibd;
ibd.Usage = D3D10_USAGE_IMMUTABLE;
ibd.ByteWidth = sizeof(DWORD) * NumFaces * 3;
ibd.BindFlags = D3D10_BIND_INDEX_BUFFER;
ibd.CPUAccessFlags = 0;
ibd.MiscFlags = 0;
D3D10_SUBRESOURCE_DATA iinitData;
iinitData.pSysMem = &indices[0];
d3dDevice->CreateBuffer(&ibd, &iinitData, &IndexBuffer);
UINT stride = sizeof( Vertex );
UINT offset = 0;
d3dDevice->IASetVertexBuffers( 0, 1, &VertexBuffer, &stride, &offset );
d3dDevice->IASetIndexBuffer(IndexBuffer, DXGI_FORMAT_R32_UINT, 0);

///
////////////////////////////skymap/////////////////////////////
D3DX10_IMAGE_LOAD_INFO loadSMInfo;
loadSMInfo.MiscFlags = D3D10_RESOURCE_MISC_TEXTURECUBE;
ID3D10Texture2D* SMTexture = 0;
hr = D3DX10CreateTextureFromFile(d3dDevice, L"skymap.dds",
&loadSMInfo, 0, (ID3D10Resource**)&SMTexture, 0);
if(FAILED(hr))
{
MessageBox(0, L"Load cube texture - Failed",
L"Error", MB_OK);
return false;
}
D3D10_TEXTURE2D_DESC SMTextureDesc;
SMTexture->GetDesc(&SMTextureDesc);
D3D10_SHADER_RESOURCE_VIEW_DESC SMViewDesc;
SMViewDesc.Format = SMTextureDesc.Format;
SMViewDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURECUBE;
SMViewDesc.TextureCube.MipLevels = SMTextureDesc.MipLevels;
SMViewDesc.TextureCube.MostDetailedMip = 0;
hr = d3dDevice->CreateShaderResourceView(SMTexture, &SMViewDesc, &smrv);
if(FAILED(hr))
{
MessageBox(0, L"Create Cube Texture RV - Failed",
L"Error", MB_OK);
return false;
}
SMTexture->Release();
/////////////////////////skymap/////////////////////////////////////////////////
///lights
light.dir = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
light.ambient = D3DXCOLOR(0.0f, 0.0f, 0.2f, 0.0f);
light.diffuse = D3DXCOLOR(0.0f, 0.0f, 0.0f, 0.0f);


hr = D3DX10CreateEffectFromFile( L"vertex.fx", NULL, NULL, "fx_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0,
d3dDevice, NULL, NULL, &FX, &compilationErrors, NULL );
if(FAILED(hr))
{
MessageBoxA(0, (char*)compilationErrors->GetBufferPointer(), 0, 0);
compilationErrors->Release();
return false;
}
D3DX10CreateShaderResourceViewFromFile(d3dDevice, L"Terrain.jpg", 0, 0, &DiffuseMapResourceView, 0 );
Technique = FX->GetTechniqueByName( "Tech" );
/////////////////////////new/////////////////////////////////////////////////
SkyMapTechnique = FX->GetTechniqueByName("SkyMapTech");
/////////////////////////new/////////////////////////////////////////////////
fxWVPVar = FX->GetVariableByName("WVP")->AsMatrix();
fxDiffuseMapVar = FX->GetVariableByName("DiffuseMap")->AsShaderResource();
fxLightVar = FX->GetVariableByName("light");
fxSkyMapVar = FX->GetVariableByName("SkyMap")->AsShaderResource();
D3D10_PASS_DESC PassDesc;
Technique->GetPassByIndex( 0 )->GetDesc( &PassDesc );

d3dDevice->CreateInputLayout( pLayout, 3, PassDesc.pIAInputSignature,
PassDesc.IAInputSignatureSize, &pVertexLayout );

d3dDevice->CreateInputLayout( layout, 5, PassDesc.pIAInputSignature,
PassDesc.IAInputSignatureSize, &VertexLayout );
d3dDevice->IASetInputLayout( VertexLayout );
d3dDevice->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST );

D3D10_RASTERIZER_DESC wfdesc;
ZeroMemory(&wfdesc, sizeof(D3D10_RASTERIZER_DESC));
wfdesc.FillMode = D3D10_FILL_SOLID;
wfdesc.CullMode = D3D10_CULL_NONE;
wfdesc.FrontCounterClockwise = true;
hr = d3dDevice->CreateRasterizerState(&wfdesc, &WireFrame);
if(FAILED(hr))
{
MessageBox(0, L"RS STATE Creation - Failed",
L"Error", MB_OK);
return false;
}


// you need to create the constant buffer
D3D10_BUFFER_DESC cbbd;
ZeroMemory(&cbbd, sizeof(D3D10_BUFFER_DESC));
cbbd.Usage = D3D10_USAGE_DEFAULT;
cbbd.ByteWidth = sizeof(cbPerObject);
cbbd.BindFlags = D3D10_BIND_CONSTANT_BUFFER;
cbbd.CPUAccessFlags = 0;
cbbd.MiscFlags = 0;
hr = d3dDevice->CreateBuffer(&cbbd, NULL, &cbPerObjectBuffer);
/********************************************************************************************/
/////////////////////////new/////////////////////////////////////////////////
for( int i = 0; i < numSpheres; i++)
{
spheres[i] = 1;
}
/////////////////////////new/////////////////////////////////////////////////
//StartTimer();
InitGameTime();
return true;
}
bool ReleaseObjects()
{
if( d3dDevice ) d3dDevice->ClearState();
if( VertexBuffer ) VertexBuffer->Release();
if( IndexBuffer ) IndexBuffer->Release();
if( VertexLayout ) VertexLayout->Release();
if( FX ) FX->Release();
if( RenderTargetView ) RenderTargetView->Release();
if( SwapChain ) SwapChain->Release();
if( d3dDevice ) d3dDevice->Release();
if( DiffuseMapResourceView ) DiffuseMapResourceView->Release();
DIKeyboard->Unacquire();
DIMouse->Unacquire();
DirectInput->Release();
/////////////////////////new/////////////////////////////////////////////////
for(int i = 0; i < meshCount; i++)
if( meshes[i] ) meshes[i]->Release();
/////////////////////////new/////////////////////////////////////////////////
Font->Release();
return true;
}
void DrawScene()
{
//Draw Scene Here
D3DXCOLOR bgColor( 0.5f, 0.5f, 0.5f, 1.0f);
d3dDevice->ClearRenderTargetView( RenderTargetView, bgColor );
d3dDevice->ClearDepthStencilView(DepthStencilView, D3D10_CLEAR_DEPTH|D3D10_CLEAR_STENCIL, 1.0f, 0);
D3DXMatrixPerspectiveFovLH(&Projection, 0.4f*3.14f, (float)Width/Height, 1.0f, 1000.0f);

fxLightVar->SetRawValue(&light, 0, sizeof(Light));
/////////////////////////new/////////////////////////////////////////////////
D3D10_TECHNIQUE_DESC skymaptechDesc;
SkyMapTechnique->GetDesc( &skymaptechDesc );
/////////////////////////new/////////////////////////////////////////////////
/////////////////////////new/////////////////////////////////////////////////
d3dDevice->OMSetDepthStencilState(0, 0);
d3dDevice->IASetInputLayout( VertexLayout );
d3dDevice->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
/////////////////////////new////////////////////////////////////////////////*/
D3D10_TECHNIQUE_DESC techDesc;
Technique->GetDesc( &techDesc );
d3dDevice->RSSetState(NULL);
//Draw stuff without wireframe
d3dDevice->RSSetState(WireFrame);
WVP = World * View * Projection;
fxWVPVar->SetMatrix((float*)&WVP);

////////////////////new//////////////////////////////////////////////////////////////////////
fxDiffuseMapVar->SetResource(DiffuseMapResourceView);
////////////////////new//////////////////////////////////////////////////////////////////////
UINT stride = sizeof( Vertex );
UINT offset = 0;
d3dDevice->IASetVertexBuffers( 0, 1, &VertexBuffer, &stride, &offset );
d3dDevice->IASetIndexBuffer(IndexBuffer, DXGI_FORMAT_R32_UINT, 0);

d3dDevice->IASetInputLayout( VertexLayout );
//draw wireframe plane
for( UINT p = 0; p < techDesc.Passes; ++p )
{
Technique->GetPassByIndex( p )->Apply( 0 );
d3dDevice->DrawIndexed(NumFaces*3, 0, 0);
}


/////////////////////////spheres and their positioning/////////////////////////////////////////////////
float sphereXPos = 30.0f;
float sphereZPos = 120.0f;
float sxadd = 0.0f;
float szadd = 0.0f;
for(int i = 0; i < numSpheres; i++)
{
sxadd++;
if(sxadd == 8)
{
szadd -= 1.0f;
sxadd = 0;
}

D3DXVECTOR3 rotaxis(0.0f, 1.0f, 0.0f);
D3DXMatrixRotationAxis(&Rotation, &rotaxis, rot);
rot += .0005f;
D3DXMatrixScaling( &Scale, 2.0f, 2.0f, 2.0f );
D3DXMatrixTranslation( &Translation, sphereXPos + sxadd*20.0f, 20.0f, sphereZPos + szadd*5.0f );
D3DXMatrixRotationAxis(&Rotation, &rotaxis, -rot);
SphereLocalSpace[i] = Rotation * Scale * Translation;

WVP = SphereLocalSpace[i] * View * Projection;
fxWVPVar->SetMatrix((float*)&WVP);
//draw sphere
if(spheres[i] == 1)
{
for( UINT p = 0; p < techDesc.Passes; ++p )
{
for(UINT subsetID = 0; subsetID < meshSubsets[0]; ++subsetID)
{
fxDiffuseMapVar->SetResource(TextureResourceViews[subsetID /*+ meshSubsets[0]*/]); // There is no mesh before mesh[0], so you don't have to add the
// previous meshes subset count to this, since there isn't one
Technique->GetPassByIndex( p )->Apply( 0 );
meshes[0]->DrawSubset(subsetID);
}
}
}
}
/////////////////////////new/////////////////////////////////////////////////

//draw skymap based off loaded mesh sphere
fxSkyMapVar->SetResource(smrv);
for( UINT p = 0; p < skymaptechDesc.Passes; ++p )
{
SkyMapTechnique->GetPassByIndex( p )->Apply( 0 );
d3dDevice->DrawIndexed(NumFaces * 3, 0, 0);
}


/////////////////////////new/////////////////////////////////////////////////
wostringstream printString;
printString << L"Score: " << totalScore << L"\n"
<< L"Time Left: " << TimeLeft << L"\n"
<< L"FPS: " << fps << L"\n"
<< L"Game Time: " << GetGameTime();
printScoreFPS = printString.str();
D3DXCOLOR FontColor(1.0f, 1.0f, 1.0f, 1.0f);
RECT R = {10, 10, 0, 0};
Font->DrawText(0, printScoreFPS.c_str(), -1, &R, DT_NOCLIP, FontColor);
/////////////////////////new/////////////////////////////////////////////////

SwapChain->Present( 0, 0 );
}
int messageloop(){
MSG msg;
ZeroMemory(&msg, sizeof(MSG));
while(true)
{
BOOL PeekMessageL(
LPMSG lpMsg,
HWND hWnd,
UINT wMsgFilterMin,
UINT wMsgFilterMax,
UINT wRemoveMsg
);
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if (msg.message == WM_QUIT)
break;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else{
// run game code
/////////////////////////new/////////////////////////////////////////////////
numFrames++;
// Your problem is that this if statement is called every frame because GetGameTime returns the time in seconds
// since the start of the game, so it will ALWAYS be over 1 (after the initial first second anyway)
// What you need to do is get the time, store it into a variable called oldTime, then subtract it from GetGameTime()
// and if it's over 1, then we know one second has passed
if(GetGameTime() - oldTime > 1.0f)
{
fps = numFrames;
numFrames = 0;
//InitGameTime();
// reset oldTime
oldTime = GetGameTime();
/***************** because GetGameTime() returns the time IN SECONDS since the start of the game, you can
subtract whatever this returns from TimeLeft ever second (assuming TimeLeft is in seconds)*/
TimeLeft = constTimeLeft - GetGameTime();
}
//numFrames = GetGameTime(); // Why did you set numFrames to the game time?
gameTime = GetGameTime();
/////////////////////////new/////////////////////////////////////////////////
/////run game code
//GetGameTime();
DetectInput();
DrawScene();
}
}
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd,
UINT msg,
WPARAM wParam,
LPARAM lParam)
{
switch( msg )
{
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_SIZE:
ClientWidth = LOWORD(lParam);
ClientHeight = HIWORD(lParam);
return 0;

}
return DefWindowProc(hwnd,
msg,
wParam,
lParam);
}
[/CODE]

Share this post


Link to post
Share on other sites

This topic is 2062 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this