· 6 years ago · Mar 14, 2020, 03:18 AM
1#define _CRT_SECURE_NO_WARNINGS 1
2#define _ENGINE_VERSION "0.0.03b";
3
4/* GAME ENGINE WRITTEN WITH THE DIRECTX11 API BY THOMAS WOODMAN WITH IEDOC'S TUTORIAL CODE
5/*-----------------------------------------------CHANGELOG--------------------------------------------------------------/
63/4/2020(9:53PM) Upgrading to 0.0.01c
7========================================
8-BSP Header file has been upgraded from DirectX9/D3D9 to DirectX11/D3DX11 (There are however issues with collision detection, implementation is *very* redumentary)
9-Created Debug Console that can be toggled with the tidle(~) key (win32 API's Sleep() Function was needed to stop the extremely fast toggling)
10-Implemented Console() function, which stores all logs in a std::string vector, rather than a linked list as in the last project
11-Console provides real-time feedback of camera position, camera target, camera direction, distance, and FPS to the user
12-OBJ Loader function has its own header file, for now just to clear code on the main CPP so it is less crowded, still very hard-coded
13-Implented FlatSquare() function, which allows for D2D Drawing of rects with color and alpha values(Used in the Debug Console)
14-Implemented SKYBOX for sky, there seems to be a problem culling/stencil/depth issues as certain parts of BSP maps disappear at a certain distance
15-Eliminated 100% of compiler warnings
16========================================
173/6/2020(6:06AM) Upgrading to 0.0.02a
18========================================
19-Created new XMVECTOR's oldCamPosition/newCamPosition, elementary collision detection is now in-tact (Y and Z axis are inverted with BSP maps)
20-Reset Ground Matrix's translation and mapWorld Matrix translation to align with the camera and ground
21========================================
223/6/2020(6:06AM) Upgrading to 0.0.02b
23========================================
24-Eliminated clipping of objects at a certain distance (camProjection Matrix's FOV was set only to 1000, duh!)
25-Ground, BSP map, and meshes are all rendered even with console enabled(the order in which you draw things is very tricky in DX11..I anticipate more problems like these)
26========================================
273/6/2020(6:06AM) Upgrading to 0.0.02c
28========================================
29-Adjusted the output of the debug console std::string vector to the 23 last elements of the vector to fit the debug console's transparant box so informaton doesn't trail off screen
30-Made minor adjustments to collision detection, still unable to slide against walls of BSP maps while in motion
31========================================
323/6/2020(6:06AM) Upgrading to 0.0.03a
33========================================
34-Implemented pistol OBJ Mesh
35-OBJ Mesh has its own Scale Matrix, Translation Matrix, Rotation Matrix, World and View Matrix, shares Projection Matrix with FPS Camera
36-Implemented Translation and Rotation variables that can be changed (i.e. AK-47 would point farther away and rotate less, flashlight would be closer and rotate with player)
37========================================
383/6/2020(6:06AM) Upgrading to 0.0.03a
39========================================
40-DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS!!
41-Entire Engine has been UPGRADED to make use of the static DirectXTK lib, and has done away with *ALL* deprecated DX9/10/11 CODE, this engine now solely relies on d3d11.lib and the DirectXTK
42-This is an extreme upgrade done in two days, no more old deprecated DX code, and can now make use of the *ENTIRE* tool kit, for sprites, meshes, etc!
43-All DirectX functions are included in the standard Windows SDK now. Now there's no need for making use of *any* directX headers, except for toolkits.
44/*-----------------------------------------------CHANGELOG--------------------------------------------------------------*/
45//Include and link appropriate libraries and headers//
46#pragma comment(lib, "d3d11.lib")
47//#pragma comment(lib, "d3dx11.lib")
48//#pragma comment(lib, "d3dx10.lib")
49#pragma comment (lib, "D3D10_1.lib")
50#pragma comment (lib, "DXGI.lib")
51#pragma comment (lib, "D2D1.lib")
52#pragma comment (lib, "dwrite.lib")
53#pragma comment (lib, "dinput8.lib")
54#pragma comment (lib, "dxguid.lib")
55#pragma comment (lib, "DirectXTK.lib")
56#pragma comment (lib, "D3DCompiler.lib")
57#pragma warning( disable : 4005)
58#include <windows.h>
59#include <d3d11.h>
60//#include <d3dx11.h>
61//#include <d3dx10.h>
62//#include <xnamath.h>
63#include <SpriteFont.h>
64#include <SpriteBatch.h>
65#include <DirectXMath.h>
66#include <SimpleMath.h>
67#include <DirectXPackedVector.h>
68#include <DirectXCollision.h>
69#include <DirectXColors.h>
70#include <WICTextureLoader.h>
71#include <Effects.h>
72#include <Model.h>
73#include <CommonStates.h>
74#include <DDSTextureLoader.h>
75#include <GeometricPrimitive.h>
76#include <PrimitiveBatch.h>
77#include <wrl/client.h>
78#include <d3dcompiler.h>
79#include <D3D10_1.h>
80#include <DXGI.h>
81#include <D2D1.h>
82#include <sstream>
83#include <dwrite.h>
84#include <dinput.h>
85#include <vector> //For OBJ Mesh
86#include <fstream> //For OBJ Mesh
87#include <istream> //For OBJ Mesh
88using namespace DirectX;
89using namespace Microsoft::WRL;
90using namespace DirectX::PackedVector;
91using namespace DirectX::SimpleMath;
92#include "Structs.h"
93#include "bsp.h"
94#include "OBJLoader.h"
95//Global Declarations - Interfaces//
96IDXGISwapChain* SwapChain;
97ID3D11Device* d3d11Device;
98ID3D11DeviceContext* d3d11DevCon;
99ID3D11RenderTargetView* renderTargetView;
100ID3D11Buffer* groundIndexBuffer;
101ID3D11DepthStencilView* depthStencilView;
102ID3D11Texture2D* depthStencilBuffer;
103ID3D11Buffer* groundVertexBuffer;
104ID3D11VertexShader* VS;
105ID3D11PixelShader* PS;
106ID3D11PixelShader* D2D_PS;
107ID3DBlob* D2D_PS_Buffer;
108ID3DBlob* VS_Buffer;
109ID3DBlob* PS_Buffer;
110ID3D11InputLayout* vertLayout;
111ID3D11Buffer* cbPerObjectBuffer;
112ID3D11BlendState* Transparency;
113ID3D11RasterizerState* CCWcullMode;
114ID3D11RasterizerState* CWcullMode;
115ID3D11ShaderResourceView* CubesTexture;
116ID3D11ShaderResourceView* SkyMapTexture;
117ID3D11SamplerState* CubesTexSamplerState;
118ID3D11Buffer* cbPerFrameBuffer;
119ID3D11BlendState* d2dTransparency;
120ID3D10Device1 *d3d101Device;
121IDXGIKeyedMutex *keyedMutex11;
122IDXGIKeyedMutex *keyedMutex10;
123ID2D1RenderTarget *D2DRenderTarget;
124ID2D1SolidColorBrush *Brush;
125Microsoft::WRL::ComPtr<ID3D11Texture2D> backBuffer;
126//Microsoft::WRL::ComPtr<ID3D11Device> device;
127ID3D11Texture2D *BackBuffer11;
128ID3D11Texture2D *sharedTex11;
129ID3D11Buffer *d2dVertBuffer;
130ID3D11Buffer *d2dIndexBuffer;
131ID3D11Buffer *d2dVertBuffer2;
132ID3D11Buffer *d2dIndexBuffer2;
133ID3D11ShaderResourceView *d2dTexture;
134IDWriteFactory *DWriteFactory;
135IDWriteTextFormat *TextFormat;
136ID3D11DepthStencilState* DSLessEqual;
137ID3D11Buffer* OBJVertexBuffer;
138ID3D11Buffer* OBJIndexBuffer;
139IEffect *Effect;
140ID3D11RasterizerState* RSCullNone; //OBJ MESH VAR(initally)
141
142std::unique_ptr<DirectX::SpriteBatch> spriteBatch;
143std::unique_ptr<DirectX::SpriteFont> spriteFont;
144
145IDirectInputDevice8* DIKeyboard;
146IDirectInputDevice8* DIMouse;
147
148bool g_bShowConsole = true;
149bool g_bCollision = false;
150float distance = 0.0f;
151int test = 0;
152
153void DetectCollison(void);
154
155std::wstring printText;
156std::wstring Unicode(const std::string s)
157{
158 std::wstring wsTmp(s.begin(), s.end());
159 return wsTmp;
160}
161
162//Global Declarations - Others//
163LPCTSTR WndClassName = "firstwindow";
164HWND hwnd = NULL;
165HRESULT hr;
166
167int Width = 1920;
168int Height = 1200;
169
170DIMOUSESTATE mouseLastState;
171LPDIRECTINPUT8 DirectInput;
172
173float rotx = 0;
174float rotz = 0;
175float scaleX = 1.0f;
176float scaleY = 1.0f;
177
178
179float objRotX = -0.42f;
180float objRotY = 0.39f;
181float objRotZ = 0.11f;
182float objTransX = -2.24f;
183float objTransY = -15.4103f;
184float objTransZ = -2.3f;
185XMMATRIX Rotationx;
186XMMATRIX Rotationz;
187
188XMMATRIX WVP;
189XMMATRIX cube1World;
190XMMATRIX cube2World;
191XMMATRIX camView;
192XMMATRIX camProjection;
193
194XMMATRIX meshView;
195XMMATRIX meshProjection;
196
197XMMATRIX d2dWorld;
198XMVECTOR g_vCamPosition;
199XMVECTOR camPosition;
200XMVECTOR newCamPosition;
201XMVECTOR oldCamPosition;
202XMVECTOR camTarget;
203XMVECTOR camUp;
204XMVECTOR camDir;
205XMVECTOR DefaultForward = XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);
206XMVECTOR DefaultRight = XMVectorSet(1.0f, 0.0f, 0.0f, 0.0f);
207XMVECTOR camForward = XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);
208XMVECTOR camRight = XMVectorSet(1.0f, 0.0f, 0.0f, 0.0f);
209XMVECTOR vLen = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
210XMVECTOR g_vMeshPosition = XMVectorSet(10.0f, 1.0f, 10.0f, 0.0f);
211XMVECTOR g_vMeshAt = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
212XMVECTOR g_vMeshUp = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
213
214XMMATRIX camRotationMatrix;
215XMMATRIX groundWorld;
216
217XMMATRIX mapWorld;
218///////////////**************new(OBJ MESH)**************////////////////////
219XMMATRIX cupWorld;
220
221///////////////**************new(OBJ MESH)**************////////////////////
222///////////////**************new(SKYBOX)**************////////////////////
223ID3D11Buffer* sphereIndexBuffer;
224ID3D11Buffer* sphereVertBuffer;
225
226ID3D11VertexShader* SKYMAP_VS;
227ID3D11PixelShader* SKYMAP_PS;
228ID3D10Blob* SKYMAP_VS_Buffer;
229ID3D10Blob* SKYMAP_PS_Buffer;
230
231ID3D11ShaderResourceView* smrv;
232
233
234
235
236XMMATRIX Rotationy;
237
238//////////////////////////////////////////////////////////////////
239/*//////////////////////////DIRECTXTK MESH TEST/////////////////*/
240DirectX::SimpleMath::Matrix m_world;
241DirectX::SimpleMath::Matrix m_view;
242DirectX::SimpleMath::Matrix m_proj;
243
244std::unique_ptr<DirectX::CommonStates> m_states;
245std::unique_ptr<DirectX::IEffectFactory> m_fxFactory;
246std::unique_ptr<DirectX::Model> m_model;
247///////////////**************new**************////////////////////
248int NumSphereVertices;
249int NumSphereFaces;
250
251XMMATRIX sphereWorld;
252///////////////**************new**************////////////////////
253///////////////**************new**************////////////////////
254void CreateSphere(int LatLines, int LongLines);
255///////////////**************new**************////////////////////
256///////////////**************new(SKYBOX)**************////////////////////
257float moveLeftRight = 0.0f;
258float moveBackForward = 0.0f;
259
260float camYaw = 0.0f;
261float camPitch = 0.0f;
262
263XMMATRIX Rotation;
264XMMATRIX Scale;
265XMMATRIX Translation;
266float rot = 0.01f;
267
268double countsPerSecond = 0.0;
269__int64 CounterStart = 0;
270
271int frameCount = 0;
272int fps = 0;
273
274__int64 frameTimeOld = 0;
275double frameTime;
276
277//Function Prototypes//
278bool InitializeDirect3d11App(HINSTANCE hInstance);
279void CleanUp();
280bool InitScene();
281void DrawScene();
282bool InitD2D_D3D101_DWrite(IDXGIAdapter1 *Adapter);
283void InitD2DScreenTexture();
284void UpdateScene(double time);
285
286void UpdateCamera();
287
288void RenderText(std::wstring text, int inInt);
289
290void StartTimer();
291double GetTime();
292double GetFrameTime();
293
294bool InitializeWindow(HINSTANCE hInstance,
295 int ShowWnd,
296 int width, int height,
297 bool windowed);
298int messageloop();
299
300bool InitDirectInput(HINSTANCE hInstance);
301void DetectInput(double time);
302
303void DrawConsole(void);
304
305LRESULT CALLBACK WndProc(HWND hWnd,
306 UINT msg,
307 WPARAM wParam,
308 LPARAM lParam);
309
310//Create effects constant buffer's structure//
311//Create effects constant buffer's structure//
312
313
314cbPerObject cbPerObj;
315
316///////////////**************FOR BSP HEADER**************///////////
317/* BSP TEXTURE CODE FOR DIRECTXTK
318std::string texfilename = str;
319std::wstring wfilename(texfilename.begin(), texfilename.end());
320hr = CreateWICTextureFromFile(d3d11Device, d3d11DevCon,
321wfilename.c_str(), nullptr, &pTexture);
322//////////////////////////////////////////////////////////////////*/
323///////////////**************new**************////////////////////
324///////////////**************new (OBJ MESH)**************////////////////////
325
326
327std::vector<SurfaceMaterial> material;
328
329//Define LoadObjModel function after we create surfaceMaterial structure
330bool LoadObjModel(ID3D11Device* d3d11Device, ID3D11DeviceContext* d3d11DevCon, ID3D11Device*, IDXGISwapChain* SwapChain, std::wstring filename, //.obj filename
331 ID3D11Buffer** vertBuff, //mesh vertex buffer
332 ID3D11Buffer** indexBuff, //mesh index buffer
333 std::vector<int>& subsetIndexStart, //start index of each subset
334 std::vector<int>& subsetMaterialArray, //index value of material for each subset
335 std::vector<SurfaceMaterial>& material, //vector of material structures
336 int& subsetCount, //Number of subsets in mesh
337 bool isRHCoordSys, //true if model was created in right hand coord system
338 bool computeNormals); //true to compute the normals, false to use the files normals
339///////////////**************new(OBJ MESH)**************////////////////////
340Light light;
341
342
343CBSP bsp;
344
345
346cbPerFrame constbuffPerFrame;
347
348
349std::vector<std::string> DebugConsole;
350void Console(std::string str)
351{
352 str.append("\r\n");
353 DebugConsole.push_back(str);
354}
355
356
357D3D11_INPUT_ELEMENT_DESC layout[] =
358{
359 { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
360 { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
361 { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 20, D3D11_INPUT_PER_VERTEX_DATA, 0 }
362};
363UINT numElements = ARRAYSIZE(layout);
364int nNumIndices = 0;
365int nNumVertex = 0;
366
367
368///////////////**************new(OBJ MESH)**************////////////////////
369void FlatSquare(
370 float left,
371 float right,
372 float top,
373 float bottom,
374 D2D1::ColorF color)
375{
376
377 ID2D1SolidColorBrush *Brush2;
378 D2DRenderTarget->CreateSolidColorBrush(color, &Brush2);
379 D2D1_COLOR_F Color = D2D1::ColorF(1.0f, 0.0f, 0.0f, 1.0f);
380 Brush2->SetColor(color);
381 D2D1_SIZE_F rtSize = D2DRenderTarget->GetSize();
382 D2D1_RECT_F rectangle2 = D2D1::RectF(
383 left,
384 top,
385 right,
386 bottom
387 );
388 D2DRenderTarget->FillRectangle(&rectangle2, Brush2);
389 D2DRenderTarget->DrawRectangle(&rectangle2, Brush2);
390
391}
392
393/*float DotProduct(const D3DXVECTOR3 & v1, const D3DXVECTOR3 & v2)
394{
395 return (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z);
396}*/
397void DetectCollison()
398{
399 /*XMVECTOR vectorSub = XMVectorSubtract(camTarget, camPosition);
400 XMVECTOR length = XMVector3Length(vectorSub);
401
402
403 XMStoreFloat(&distance, length);
404 vLen = camTarget - camPosition;
405
406 D3DXVECTOR3 vStart = { XMVectorGetX(camPosition), XMVectorGetZ(camPosition), XMVectorGetY(camPosition) };
407 XMVector3Length(vLen);
408 //XMVectorGet
409 D3DXVECTOR3 vEnd = { XMVectorGetX(newCamPosition), XMVectorGetZ(newCamPosition), XMVectorGetY(newCamPosition) };
410 D3DXVECTOR3 vHit;
411 D3DXVECTOR3 vHitWallNormal;
412 std::ostringstream printstring;
413 bool bHitWall = (bsp.TraceSphere(vStart, vEnd, 90.0f, &vHit, &vHitWallNormal));//if TRUE then collision has been detected
414 if (bHitWall)
415 {
416 g_bCollision = true;
417 D3DXVECTOR3 vDir = (vEnd - vStart);
418
419 D3DXVECTOR3 vHitDir;
420 // Increase or wall normal slightly so our final result which slides
421 // along the wall isn't on the wall but a slight nudge away from it.
422 vHitWallNormal *= 1.5f;
423
424 vHitDir = vDir - (vHitWallNormal * DotProduct(vHitWallNormal, vDir));
425 D3DXVec3Normalize(&vHitDir, &vHitDir);
426
427 float fLen = D3DXVec3Length(&(vEnd - vHit));
428
429 D3DXVECTOR3 vNewPos = vHit + vHitDir * fLen;
430
431 // If our new position which slides along the wall has a collision, then
432 // we'll just use the original wall position
433 D3DXVECTOR3 a, b; // Not used
434 if (bsp.TraceSphere(
435 vStart,
436 vNewPos,
437 90.0f,
438 &a, &b))
439 {
440 vNewPos = vHit;
441 newCamPosition = XMVectorSet(vHit.x, vHit.z, vHit.y, 0.0f); //Z and Y are inverted
442 Console("TRIED TO SLIDE!!!!!!");
443 return;
444 }
445 newCamPosition = XMVectorSet(vHit.x, vHit.z, vHit.y, 0.0f); //Z and Y are inverted
446 printstring << "Collision at : " << vHit.x << "," << vHit.y << "," << vHit.z;
447 //g_bCollision = true; //Let's not constrict the player for now
448 std::string coll = printstring.str();
449 Console(coll);
450 return;
451 }
452 else
453 {
454 g_bCollision = false;
455 newCamPosition = XMVectorSet(vEnd.x, vEnd.z, vHit.y, 0.0f); //Z and Y are inverted
456 }*/
457
458}
459int WINAPI WinMain(HINSTANCE hInstance, //Main windows function
460 HINSTANCE hPrevInstance,
461 LPSTR lpCmdLine,
462 int nShowCmd)
463{
464 Console("Initalizing Win32 Window...");
465 if (!InitializeWindow(hInstance, nShowCmd, Width, Height, true))
466 {
467 MessageBox(0, "Window Initialization - Failed",
468 "Error", MB_OK);
469 return 0;
470 }
471 Console("Window Initalized.");
472 if (!InitializeDirect3d11App(hInstance)) //Initialize Direct3D
473 {
474 MessageBox(0, "Direct3D Initialization - Failed",
475 "Error", MB_OK);
476 return 0;
477 }
478 Console("Direct3D11 Initalized Successfully.");
479 if (!InitScene()) //Initialize our scene
480 {
481 MessageBox(0, "Scene Initialization - Failed",
482 "Error", MB_OK);
483 return 0;
484 }
485
486 if (!InitDirectInput(hInstance))
487 {
488 MessageBox(0, "Direct Input Initialization - Failed",
489 "Error", MB_OK);
490 return 0;
491 }
492 Console("DirectInput Initalized.");
493 Console("Entering MessageLoop..");
494 messageloop();
495
496 CleanUp();
497
498 return 0;
499}
500
501bool InitializeWindow(HINSTANCE hInstance,
502 int ShowWnd,
503 int width, int height,
504 bool windowed)
505{
506 typedef struct _WNDCLASS {
507 UINT cbSize;
508 UINT style;
509 WNDPROC lpfnWndProc;
510 int cbClsExtra;
511 int cbWndExtra;
512 HANDLE hInstance;
513 HICON hIcon;
514 HCURSOR hCursor;
515 HBRUSH hbrBackground;
516 LPCTSTR lpszMenuName;
517 LPCTSTR lpszClassName;
518 } WNDCLASS;
519
520 WNDCLASSEX wc;
521
522 wc.cbSize = sizeof(WNDCLASSEX);
523 wc.style = CS_HREDRAW | CS_VREDRAW;
524 wc.lpfnWndProc = WndProc;
525 wc.cbClsExtra = NULL;
526 wc.cbWndExtra = NULL;
527 wc.hInstance = hInstance;
528 wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
529 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
530 wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
531 wc.lpszMenuName = NULL;
532 wc.lpszClassName = WndClassName;
533 wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
534
535 if (!RegisterClassEx(&wc))
536 {
537 MessageBox(NULL, "Error registering class",
538 "Error", MB_OK | MB_ICONERROR);
539 return 1;
540 }
541
542 hwnd = CreateWindowEx(
543 NULL,
544 WndClassName,
545 "DEVELOPERS",
546 WS_OVERLAPPEDWINDOW,
547 CW_USEDEFAULT, CW_USEDEFAULT,
548 width, height,
549 NULL,
550 NULL,
551 hInstance,
552 NULL
553 );
554
555 if (!hwnd)
556 {
557 MessageBox(NULL, "Error creating window",
558 "Error", MB_OK | MB_ICONERROR);
559 return 1;
560 }
561
562 ShowWindow(hwnd, ShowWnd);
563 UpdateWindow(hwnd);
564
565 return true;
566}
567
568bool InitializeDirect3d11App(HINSTANCE hInstance)
569{
570 //Describe our SwapChain Buffer
571 DXGI_MODE_DESC bufferDesc;
572
573 ZeroMemory(&bufferDesc, sizeof(DXGI_MODE_DESC));
574
575 bufferDesc.Width = Width;
576 bufferDesc.Height = Height;
577 bufferDesc.RefreshRate.Numerator = 60;
578 bufferDesc.RefreshRate.Denominator = 1;
579 bufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
580 bufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
581 bufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
582
583 //Describe our SwapChain
584 DXGI_SWAP_CHAIN_DESC swapChainDesc;
585
586 ZeroMemory(&swapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC));
587
588 swapChainDesc.BufferDesc = bufferDesc;
589 swapChainDesc.SampleDesc.Count = 1;
590 swapChainDesc.SampleDesc.Quality = 0;
591 swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
592 swapChainDesc.BufferCount = 1;
593 swapChainDesc.OutputWindow = hwnd;
594 ///////////////**************new**************////////////////////
595 swapChainDesc.Windowed = true;
596 ///////////////**************new**************////////////////////
597 swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
598
599 // Create DXGI factory to enumerate adapters///////////////////////////////////////////////////////////////////////////
600 IDXGIFactory1 *DXGIFactory;
601
602 HRESULT hr = CreateDXGIFactory1(__uuidof(IDXGIFactory1), (void**)&DXGIFactory);
603
604 // Use the first adapter
605 IDXGIAdapter1 *Adapter;
606
607 hr = DXGIFactory->EnumAdapters1(0, &Adapter);
608
609 DXGIFactory->Release();
610
611 //Create our Direct3D 11 Device and SwapChain//////////////////////////////////////////////////////////////////////////
612 hr = D3D11CreateDeviceAndSwapChain(Adapter, D3D_DRIVER_TYPE_UNKNOWN, NULL, D3D11_CREATE_DEVICE_BGRA_SUPPORT | D3D11_CREATE_DEVICE_DEBUG,
613 NULL, NULL, D3D11_SDK_VERSION, &swapChainDesc, &SwapChain, &d3d11Device, NULL, &d3d11DevCon);
614
615 //Initialize Direct2D, Direct3D 10.1, DirectWrite
616 //InitD2D_D3D101_DWrite(Adapter);
617
618 //Release the Adapter interface
619 Adapter->Release();
620
621 //Create our BackBuffer and Render Target
622 hr = SwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&BackBuffer11);
623 hr = d3d11Device->CreateRenderTargetView(BackBuffer11, NULL, &renderTargetView);
624 //Describe our Depth/Stencil Buffer
625 D3D11_TEXTURE2D_DESC depthStencilDesc;
626
627 depthStencilDesc.Width = Width;
628 depthStencilDesc.Height = Height;
629 depthStencilDesc.MipLevels = 1;
630 depthStencilDesc.ArraySize = 1;
631 depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
632 depthStencilDesc.SampleDesc.Count = 1;
633 depthStencilDesc.SampleDesc.Quality = 0;
634 depthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
635 depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
636 depthStencilDesc.CPUAccessFlags = 0;
637 depthStencilDesc.MiscFlags = 0;
638 SwapChain->SetFullscreenState(false, 0);
639 //Create the Depth/Stencil View
640 d3d11Device->CreateTexture2D(&depthStencilDesc, NULL, &depthStencilBuffer);
641 d3d11Device->CreateDepthStencilView(depthStencilBuffer, NULL, &depthStencilView);
642 spriteBatch = std::make_unique<DirectX::SpriteBatch>(d3d11DevCon);
643 spriteFont = std::make_unique<DirectX::SpriteFont>(d3d11Device, L"myfile.spritefont");
644
645 return true;
646}
647
648bool InitD2D_D3D101_DWrite(IDXGIAdapter1 *Adapter)
649{
650 //Create our Direc3D 10.1 Device///////////////////////////////////////////////////////////////////////////////////////
651 hr = D3D10CreateDevice1(Adapter, D3D10_DRIVER_TYPE_HARDWARE, NULL, D3D10_CREATE_DEVICE_BGRA_SUPPORT,
652 D3D10_FEATURE_LEVEL_9_3, D3D10_1_SDK_VERSION, &d3d101Device);
653
654 //Create Shared Texture that Direct3D 10.1 will render on//////////////////////////////////////////////////////////////
655 D3D11_TEXTURE2D_DESC sharedTexDesc;
656
657 ZeroMemory(&sharedTexDesc, sizeof(sharedTexDesc));
658
659 sharedTexDesc.Width = Width;
660 sharedTexDesc.Height = Height;
661 sharedTexDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
662 sharedTexDesc.MipLevels = 1;
663 sharedTexDesc.ArraySize = 1;
664 sharedTexDesc.SampleDesc.Count = 1;
665 sharedTexDesc.Usage = D3D11_USAGE_DEFAULT;
666 sharedTexDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
667 sharedTexDesc.MiscFlags = D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX;
668
669 hr = d3d11Device->CreateTexture2D(&sharedTexDesc, NULL, &sharedTex11);
670
671 // Get the keyed mutex for the shared texture (for D3D11)///////////////////////////////////////////////////////////////
672 hr = sharedTex11->QueryInterface(__uuidof(IDXGIKeyedMutex), (void**)&keyedMutex11);
673
674 // Get the shared handle needed to open the shared texture in D3D10.1///////////////////////////////////////////////////
675 IDXGIResource *sharedResource10;
676 HANDLE sharedHandle10;
677
678 hr = sharedTex11->QueryInterface(__uuidof(IDXGIResource), (void**)&sharedResource10);
679
680 hr = sharedResource10->GetSharedHandle(&sharedHandle10);
681
682 sharedResource10->Release();
683
684 // Open the surface for the shared texture in D3D10.1///////////////////////////////////////////////////////////////////
685 IDXGISurface1 *sharedSurface10;
686
687 hr = d3d101Device->OpenSharedResource(sharedHandle10, __uuidof(IDXGISurface1), (void**)(&sharedSurface10));
688
689 hr = sharedSurface10->QueryInterface(__uuidof(IDXGIKeyedMutex), (void**)&keyedMutex10);
690
691 // Create D2D factory///////////////////////////////////////////////////////////////////////////////////////////////////
692 ID2D1Factory *D2DFactory;
693 hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, __uuidof(ID2D1Factory), (void**)&D2DFactory);
694
695 D2D1_RENDER_TARGET_PROPERTIES renderTargetProperties;
696
697 ZeroMemory(&renderTargetProperties, sizeof(renderTargetProperties));
698
699 renderTargetProperties.type = D2D1_RENDER_TARGET_TYPE_HARDWARE;
700 renderTargetProperties.pixelFormat = D2D1::PixelFormat(DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED);
701
702 hr = D2DFactory->CreateDxgiSurfaceRenderTarget(sharedSurface10, &renderTargetProperties, &D2DRenderTarget);
703
704 sharedSurface10->Release();
705 D2DFactory->Release();
706
707 // Create a solid color brush to draw something with
708 hr = D2DRenderTarget->CreateSolidColorBrush(D2D1::ColorF(1.0f, 1.0f, 1.0f, 1.0f), &Brush);
709
710 //DirectWrite///////////////////////////////////////////////////////////////////////////////////////////////////////////
711 hr = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory),
712 reinterpret_cast<IUnknown**>(&DWriteFactory));
713
714 hr = DWriteFactory->CreateTextFormat(
715 Unicode("Lucida Console").c_str(),
716 NULL,
717 DWRITE_FONT_WEIGHT_REGULAR,
718 DWRITE_FONT_STYLE_NORMAL,
719 DWRITE_FONT_STRETCH_NORMAL,
720 12.0f,
721 Unicode("en-us").c_str(),
722 &TextFormat
723 );
724
725 hr = TextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
726 hr = TextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
727
728 d3d101Device->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_POINTLIST);
729 return true;
730}
731
732bool InitDirectInput(HINSTANCE hInstance)
733{
734 hr = DirectInput8Create(hInstance,
735 DIRECTINPUT_VERSION,
736 IID_IDirectInput8,
737 (void**)&DirectInput,
738 NULL);
739
740 hr = DirectInput->CreateDevice(GUID_SysKeyboard,
741 &DIKeyboard,
742 NULL);
743
744 hr = DirectInput->CreateDevice(GUID_SysMouse,
745 &DIMouse,
746 NULL);
747
748 hr = DIKeyboard->SetDataFormat(&c_dfDIKeyboard);
749 hr = DIKeyboard->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
750
751 hr = DIMouse->SetDataFormat(&c_dfDIMouse);
752 hr = DIMouse->SetCooperativeLevel(hwnd, DISCL_EXCLUSIVE | DISCL_NOWINKEY | DISCL_FOREGROUND);
753
754 return true;
755}
756
757void UpdateCamera()
758{
759 camRotationMatrix = XMMatrixRotationRollPitchYaw(camPitch, camYaw, 0);
760 camTarget = XMVector3TransformCoord(DefaultForward, camRotationMatrix);
761 camTarget = XMVector3Normalize(camTarget);
762
763 XMMATRIX RotateYTempMatrix;
764 RotateYTempMatrix = XMMatrixRotationY(camYaw);
765
766 camRight = XMVector3TransformCoord(DefaultRight, RotateYTempMatrix);
767 camUp = XMVector3TransformCoord(camUp, RotateYTempMatrix);
768 camForward = XMVector3TransformCoord(DefaultForward, RotateYTempMatrix);
769 oldCamPosition = camPosition;
770 newCamPosition += moveLeftRight*camRight;
771 newCamPosition += moveBackForward*camForward;
772 DetectCollison();
773 if (!g_bCollision)
774 {
775 camPosition = newCamPosition;
776 }
777 else
778 camPosition = oldCamPosition;
779
780 camDir = camPosition - camTarget;
781// camDir = XMVector3Length(camDir, )
782
783 moveLeftRight = 0.0f;
784 moveBackForward = 0.0f;
785
786 camTarget = camPosition + camTarget;
787 meshView = XMMatrixLookAtLH(g_vMeshAt, g_vMeshPosition, g_vMeshUp);
788 camView = XMMatrixLookAtLH(camPosition, camTarget, camUp);
789}
790
791void DetectInput(double time)
792{
793 DIMOUSESTATE mouseCurrState;
794
795 BYTE keyboardState[256];
796
797 DIKeyboard->Acquire();
798 DIMouse->Acquire();
799
800 DIMouse->GetDeviceState(sizeof(DIMOUSESTATE), &mouseCurrState);
801
802 DIKeyboard->GetDeviceState(sizeof(keyboardState), (LPVOID)&keyboardState);
803
804 if (keyboardState[DIK_ESCAPE] & 0x80)
805 PostMessage(hwnd, WM_DESTROY, 0, 0);
806
807 float speed = 150.0f * (float)time;
808
809 if (keyboardState[DIK_A] & 0x80)
810 {
811 //if (!g_bCollision)
812 moveLeftRight -= speed;
813 }
814 if (keyboardState[DIK_D] & 0x80)
815 {
816 //if (!g_bCollision)
817 moveLeftRight += speed;
818 }
819 if (keyboardState[DIK_W] & 0x80)
820 {
821 //if (!g_bCollision)
822 moveBackForward += speed;
823 //else
824 // moveBackForward -= speed;
825 }
826 if (keyboardState[DIK_S] & 0x80)
827 {
828 //if (!g_bCollision)
829 moveBackForward -= speed;
830 //else
831 // moveBackForward += speed;
832
833 }
834 if (keyboardState[DIK_DOWN] & 0x80)
835 {
836 objRotY -= 0.01f;
837 }
838 if (keyboardState[DIK_UP] & 0x80)
839 {
840 objRotY += 0.01f;
841 }
842 if (keyboardState[DIK_RIGHT] & 0x80)
843 {
844 objRotZ += 0.01f;
845 }
846 if (keyboardState[DIK_LEFT] & 0x80)
847 {
848 objRotZ -= 0.01f;
849 }
850 if (keyboardState[DIK_INSERT] & 0x80)
851 {
852 objRotX += 0.01f;
853 }
854 if (keyboardState[DIK_DELETE] & 0x80)
855 {
856 objRotX -= 0.01f;
857 }
858 if (keyboardState[DIK_NUMPAD8] & 0x80)
859 objTransX += 0.01f;
860 if (keyboardState[DIK_NUMPAD2] & 0x80)
861 objTransX -= 0.01f;
862 if (keyboardState[DIK_NUMPAD6] & 0x80)
863 objTransY += 0.01f;
864 if (keyboardState[DIK_NUMPAD4] & 0x80)
865 objTransY -= 0.01f;
866 if (keyboardState[DIK_NUMPAD3] & 0x80)
867 objTransZ += 0.01f;
868 if (keyboardState[DIK_NUMPAD1] & 0x80)
869 objTransZ -= 0.01f;
870 if (keyboardState[DIK_GRAVE] & 0x80)
871 {
872 g_bShowConsole = !g_bShowConsole;
873 Sleep(100);
874 }
875
876 if ((mouseCurrState.lX != mouseLastState.lX) || (mouseCurrState.lY != mouseLastState.lY))
877 {
878 camYaw += mouseLastState.lX * 0.0025f;
879
880 camPitch += mouseCurrState.lY * 0.0025f;
881
882 mouseLastState = mouseCurrState;
883 }
884
885 UpdateCamera();
886
887 return;
888}
889
890
891void CleanUp()
892{
893 SwapChain->SetFullscreenState(false, NULL);
894 PostMessage(hwnd, WM_DESTROY, 0, 0);
895
896 //Release the COM Objects we created
897 SwapChain->Release();
898 d3d11Device->Release();
899 d3d11DevCon->Release();
900 renderTargetView->Release();
901 groundVertexBuffer->Release();
902 groundIndexBuffer->Release();
903 VS->Release();
904 PS->Release();
905 VS_Buffer->Release();
906 PS_Buffer->Release();
907 vertLayout->Release();
908 depthStencilView->Release();
909 depthStencilBuffer->Release();
910 cbPerObjectBuffer->Release();
911 Transparency->Release();
912 CCWcullMode->Release();
913 CWcullMode->Release();
914
915 d3d101Device->Release();
916 keyedMutex11->Release();
917 keyedMutex10->Release();
918 D2DRenderTarget->Release();
919 Brush->Release();
920 BackBuffer11->Release();
921 sharedTex11->Release();
922 DWriteFactory->Release();
923 TextFormat->Release();
924 d2dTexture->Release();
925 ///////////////**************new(OBJ MESH)**************////////////////////
926 meshVertBuff->Release();
927 meshIndexBuff->Release();
928 ///////////////**************new(OBJ MESH)**************////////////////////
929 ///////////////**************new(SKYBOX)**************////////////////////
930// sphereIndexBuffer->Release();
931// sphereVertBuffer->Release();
932
933 SKYMAP_VS->Release();
934 SKYMAP_PS->Release();
935 SKYMAP_VS_Buffer->Release();
936 SKYMAP_PS_Buffer->Release();
937
938// smrv->Release();
939
940 DSLessEqual->Release();
941 //RSCullNone->Release();
942 ///////////////**************new(SKYBOX)**************////////////////////
943 cbPerFrameBuffer->Release();
944
945 DIKeyboard->Unacquire();
946 DIMouse->Unacquire();
947 DirectInput->Release();
948}
949
950void InitD2DScreenTexture()
951{
952 //Create the vertex buffer
953 Vertex v[] =
954 {
955 // Front Face
956 Vertex(-1.0f, -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, -1.0f, -1.0f),
957 Vertex(-1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, -1.0f),
958 Vertex(1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f),
959 Vertex(1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f),
960 };
961
962 DWORD indices[] = {
963 // Front Face
964 0, 1, 2,
965 0, 2, 3,
966 };
967
968 D3D11_BUFFER_DESC indexBufferDesc;
969 ZeroMemory(&indexBufferDesc, sizeof(indexBufferDesc));
970
971 indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
972 indexBufferDesc.ByteWidth = sizeof(DWORD)* ARRAYSIZE(indices);
973 indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
974 indexBufferDesc.CPUAccessFlags = 0;
975 indexBufferDesc.MiscFlags = 0;
976
977 D3D11_SUBRESOURCE_DATA iinitData;
978
979 iinitData.pSysMem = indices;
980 d3d11Device->CreateBuffer(&indexBufferDesc, &iinitData, &d2dIndexBuffer);
981
982
983 D3D11_BUFFER_DESC vertexBufferDesc;
984 ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc));
985
986 vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
987 vertexBufferDesc.ByteWidth = sizeof(Vertex)* ARRAYSIZE(v);
988 vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
989 vertexBufferDesc.CPUAccessFlags = 0;
990 vertexBufferDesc.MiscFlags = 0;
991
992 D3D11_SUBRESOURCE_DATA vertexBufferData;
993
994 ZeroMemory(&vertexBufferData, sizeof(vertexBufferData));
995 vertexBufferData.pSysMem = v;
996 hr = d3d11Device->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &d2dVertBuffer);
997
998 //Create A shader resource view from the texture D2D will render to,
999 //So we can use it to texture a square which overlays our scene
1000 d3d11Device->CreateShaderResourceView(sharedTex11, NULL, &d2dTexture);
1001}
1002bool InitScene()
1003{
1004
1005 Console("Generating BSP map...");
1006 bsp.Create(d3d11Device, d3d11DevCon, "dxtest.bsp");
1007 InitD2DScreenTexture();
1008 Console("Creating Sky Sphere...");
1009 //CreateSphere(10, 10);
1010 Console("Loading OBJ Meshes...");
1011
1012// std::shared_ptr<IEffect> effect;
1013// effect = Apply(d3d11DevCon);
1014 //m_world = Matrix::Identity;
1015 //m_view = Matrix::CreateLookAt(Vector3(2.f, 2.f, 2.f),
1016 // Vector3::Zero, Vector3::UnitY);
1017// m_proj = Matrix::CreatePerspectiveFieldOfView(XM_PI / 4.f,
1018 //float(Width) / float(Height), 0.1f, 10000.f);
1019 ///////////////**************new**************////////////////////
1020 if (!LoadObjModel(d3d11Device, d3d11DevCon, SwapChain, Unicode("M1911.obj").c_str(), &meshVertBuff, &meshIndexBuff, meshSubsetIndexStart, meshSubsetTexture, material, meshSubsets, true, false))
1021 return false;
1022 ///////////////**************new**************////////////////////
1023 Console("Compiling HLSL Shaders...");
1024 //Compile Shaders from shader file
1025
1026 //hr = D3DCompileFromFile("Effects.fx", 0, 0, "VS", "vs_4_0", 0, 0, 0, &VS_Buffer, 0, 0);
1027
1028 hr = D3DCompileFromFile(L"Effects.fx", NULL, NULL, "VS", "vs_4_0", NULL, 0, &VS_Buffer, NULL);
1029 if (hr != S_OK)
1030 MessageBoxA(NULL, "Error Compiling Shader", "Error", MB_OK);
1031 hr = D3DCompileFromFile(L"Effects.fx", NULL, NULL, "PS", "ps_4_0", NULL, 0, &PS_Buffer, NULL);
1032 hr = D3DCompileFromFile(L"Effects.fx", NULL, NULL, "D2D_PS", "ps_4_0", NULL, 0, &D2D_PS_Buffer, NULL);
1033 hr = D3DCompileFromFile(L"Effects.fx", NULL, NULL, "SKYMAP_VS", "vs_4_0", NULL, 0, &SKYMAP_VS_Buffer, NULL);
1034 hr = D3DCompileFromFile(L"Effects.fx", NULL, NULL, "SKYMAP_PS", "ps_4_0", NULL, 0, &SKYMAP_PS_Buffer, NULL);
1035// hr = D3DX11CompileFromFile("Effects.fx", 0, 0, "PS", "ps_4_0", 0, 0, 0, &PS_Buffer, 0, 0);
1036 //hr = D3DX11CompileFromFile("Effects.fx", 0, 0, "D2D_PS", "ps_4_0", 0, 0, 0, &D2D_PS_Buffer, 0, 0);
1037 ///////////////**************new**************////////////////////
1038 //hr = D3DX11CompileFromFile("Effects.fx", 0, 0, "SKYMAP_VS", "vs_4_0", 0, 0, 0, &SKYMAP_VS_Buffer, 0, 0);
1039 //hr = D3DX11CompileFromFile("Effects.fx", 0, 0, "SKYMAP_PS", "ps_4_0", 0, 0, 0, &SKYMAP_PS_Buffer, 0, 0);
1040 ///////////////**************new**************////////////////////
1041
1042 //Create the Shader Objects
1043 hr = d3d11Device->CreateVertexShader(VS_Buffer->GetBufferPointer(), VS_Buffer->GetBufferSize(), NULL, &VS);
1044 hr = d3d11Device->CreatePixelShader(PS_Buffer->GetBufferPointer(), PS_Buffer->GetBufferSize(), NULL, &PS);
1045 hr = d3d11Device->CreatePixelShader(D2D_PS_Buffer->GetBufferPointer(), D2D_PS_Buffer->GetBufferSize(), NULL, &D2D_PS);
1046 hr = d3d11Device->CreateVertexShader(SKYMAP_VS_Buffer->GetBufferPointer(), SKYMAP_VS_Buffer->GetBufferSize(), NULL, &SKYMAP_VS);
1047 hr = d3d11Device->CreatePixelShader(SKYMAP_PS_Buffer->GetBufferPointer(), SKYMAP_PS_Buffer->GetBufferSize(), NULL, &SKYMAP_PS);
1048
1049 //Set Vertex and Pixel Shaders
1050 d3d11DevCon->VSSetShader(VS, 0, 0);
1051 d3d11DevCon->PSSetShader(PS, 0, 0);
1052
1053 light.pos = XMFLOAT3(0.0f, 1.0f, 0.0f);
1054 light.dir = XMFLOAT3(0.0f, 0.0f, 1.0f);
1055 light.range = 10000.0f;
1056 light.cone = 20.0f;
1057 light.att = XMFLOAT3(0.4f, 0.002f, 0.000f);
1058 light.ambient = XMFLOAT4(0.2f, 0.2f, 0.2f, 1.0f);
1059 light.diffuse = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
1060
1061
1062 //Create the vertex buffer
1063 Vertex v[] =
1064 {
1065 // Bottom Face
1066 Vertex(-1.0f, -1.0f, -1.0f, 100.0f, 100.0f, 0.0f, 1.0f, 0.0f),
1067 Vertex(1.0f, -1.0f, -1.0f, 0.0f, 100.0f, 0.0f, 1.0f, 0.0f),
1068 Vertex(1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f),
1069 Vertex(-1.0f, -1.0f, 1.0f, 100.0f, 0.0f, 0.0f, 1.0f, 0.0f),
1070 };
1071
1072 DWORD indices[] = {
1073 0, 1, 2,
1074 0, 2, 3,
1075 };
1076
1077 D3D11_BUFFER_DESC indexBufferDesc;
1078 ZeroMemory(&indexBufferDesc, sizeof(indexBufferDesc));
1079
1080 indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
1081 indexBufferDesc.ByteWidth = sizeof(DWORD)* ARRAYSIZE(indices);
1082 indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
1083 indexBufferDesc.CPUAccessFlags = 0;
1084 indexBufferDesc.MiscFlags = 0;
1085
1086 D3D11_SUBRESOURCE_DATA iinitData;
1087
1088 iinitData.pSysMem = indices;
1089 d3d11Device->CreateBuffer(&indexBufferDesc, &iinitData, &groundIndexBuffer);
1090
1091 D3D11_BUFFER_DESC vertexBufferDesc;
1092 ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc));
1093
1094 vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
1095 vertexBufferDesc.ByteWidth = sizeof(Vertex)* ARRAYSIZE(v);
1096 vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
1097 vertexBufferDesc.CPUAccessFlags = 0;
1098 vertexBufferDesc.MiscFlags = 0;
1099
1100 D3D11_SUBRESOURCE_DATA vertexBufferData;
1101
1102 ZeroMemory(&vertexBufferData, sizeof(vertexBufferData));
1103 vertexBufferData.pSysMem = v;
1104 hr = d3d11Device->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &groundVertexBuffer);
1105
1106 //Create the Input Layout
1107 hr = d3d11Device->CreateInputLayout(layout, numElements, VS_Buffer->GetBufferPointer(),
1108 VS_Buffer->GetBufferSize(), &vertLayout);
1109
1110 //Set the Input Layout
1111 d3d11DevCon->IASetInputLayout(vertLayout);
1112
1113 //Set Primitive Topology
1114 d3d11DevCon->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
1115
1116 //Create the Viewport
1117 D3D11_VIEWPORT viewport;
1118 ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));
1119
1120 viewport.TopLeftX = 0;
1121 viewport.TopLeftY = 0;
1122 viewport.Width = (float)Width;
1123 viewport.Height = (float)Height;
1124 viewport.MinDepth = 0.0f;
1125 viewport.MaxDepth = 1.0f;
1126
1127 //Set the Viewport
1128 d3d11DevCon->RSSetViewports(1, &viewport);
1129
1130 //Create the buffer to send to the cbuffer in effect file
1131 D3D11_BUFFER_DESC cbbd;
1132 ZeroMemory(&cbbd, sizeof(D3D11_BUFFER_DESC));
1133
1134 cbbd.Usage = D3D11_USAGE_DEFAULT;
1135 cbbd.ByteWidth = sizeof(cbPerObject);
1136 cbbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
1137 cbbd.CPUAccessFlags = 0;
1138 cbbd.MiscFlags = 0;
1139
1140 hr = d3d11Device->CreateBuffer(&cbbd, NULL, &cbPerObjectBuffer);
1141
1142 //Create the buffer to send to the cbuffer per frame in effect file
1143 ZeroMemory(&cbbd, sizeof(D3D11_BUFFER_DESC));
1144
1145 cbbd.Usage = D3D11_USAGE_DEFAULT;
1146 cbbd.ByteWidth = sizeof(cbPerFrame);
1147 cbbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
1148 cbbd.CPUAccessFlags = 0;
1149 cbbd.MiscFlags = 0;
1150
1151 hr = d3d11Device->CreateBuffer(&cbbd, NULL, &cbPerFrameBuffer);
1152
1153 //Camera information
1154 camPosition = XMVectorSet(0.0f, 15.0f, -8.0f, 0.0f);
1155 camTarget = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
1156 camUp = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
1157
1158 //Set the View matrix
1159 camView = XMMatrixLookAtLH(camPosition, camTarget, camUp);
1160
1161 //Set the Projection matrix
1162 camProjection = XMMatrixPerspectiveFovLH(0.4f*XM_PI, (float)(Width / Height), 1.0f, 100000.0f);
1163 meshProjection = XMMatrixPerspectiveFovLH(0.4f*XM_PI, (float)(Width / Height), 1.0f, 200000.0f);
1164 D3D11_BLEND_DESC blendDesc;
1165 ZeroMemory(&blendDesc, sizeof(blendDesc));
1166
1167 D3D11_RENDER_TARGET_BLEND_DESC rtbd;
1168 ZeroMemory(&rtbd, sizeof(rtbd));
1169
1170 rtbd.BlendEnable = true;
1171 rtbd.SrcBlend = D3D11_BLEND_SRC_COLOR;
1172 rtbd.DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
1173 rtbd.BlendOp = D3D11_BLEND_OP_ADD;
1174 rtbd.SrcBlendAlpha = D3D11_BLEND_ONE;
1175 rtbd.DestBlendAlpha = D3D11_BLEND_ZERO;
1176 rtbd.BlendOpAlpha = D3D11_BLEND_OP_ADD;
1177 rtbd.RenderTargetWriteMask = D3D10_COLOR_WRITE_ENABLE_ALL;
1178
1179 blendDesc.AlphaToCoverageEnable = false;
1180 blendDesc.RenderTarget[0] = rtbd;
1181
1182 d3d11Device->CreateBlendState(&blendDesc, &d2dTransparency);
1183
1184 ///////////////**************new**************////////////////////
1185 ZeroMemory(&rtbd, sizeof(rtbd));
1186
1187 rtbd.BlendEnable = true;
1188 rtbd.SrcBlend = D3D11_BLEND_INV_SRC_ALPHA;
1189 rtbd.DestBlend = D3D11_BLEND_SRC_ALPHA;
1190 rtbd.BlendOp = D3D11_BLEND_OP_ADD;
1191 rtbd.SrcBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
1192 rtbd.DestBlendAlpha = D3D11_BLEND_SRC_ALPHA;
1193 rtbd.BlendOpAlpha = D3D11_BLEND_OP_ADD;
1194 rtbd.RenderTargetWriteMask = D3D10_COLOR_WRITE_ENABLE_ALL;
1195
1196 blendDesc.AlphaToCoverageEnable = false;
1197 blendDesc.RenderTarget[0] = rtbd;
1198
1199 d3d11Device->CreateBlendState(&blendDesc, &Transparency);
1200 ///////////////**************new**************////////////////////
1201
1202 HRESULT hr = CreateWICTextureFromFile(d3d11Device, d3d11DevCon,
1203 L"grass.jpg", nullptr, &CubesTexture);
1204 //DX::ThrowIfFailed(hr);
1205 //hr = D3DX11CreateShaderResourceViewFromFile(d3d11Device, "grass.jpg",
1206 // NULL, NULL, &CubesTexture, NULL);
1207
1208 ///////////////**************new(SKYBOX)**************////////////////////
1209 //Tell D3D we will be loading a cube texture
1210 //D3DX11_IMAGE_LOAD_INFO loadSMInfo;
1211 //loadSMInfo.MiscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE;
1212
1213 //Load the texture
1214 ID3D11Texture2D* SMTexture = 0;
1215// hr = D3DX11CreateTextureFromFile(d3d11Device, "skymap.dds",
1216// &loadSMInfo, 0, (ID3D11Resource**)&SMTexture, 0);
1217
1218
1219
1220 hr = CreateDDSTextureFromFile(d3d11Device, L"skymap.dds",
1221 nullptr, &SkyMapTexture);
1222
1223
1224 //Create the textures description
1225 /*D3D11_TEXTURE2D_DESC SMTextureDesc;
1226 SMTexture->GetDesc(&SMTextureDesc);
1227
1228 //Tell D3D We have a cube texture, which is an array of 2D textures
1229 D3D11_SHADER_RESOURCE_VIEW_DESC SMViewDesc;
1230 SMViewDesc.Format = SMTextureDesc.Format;
1231 SMViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
1232 SMViewDesc.TextureCube.MipLevels = SMTextureDesc.MipLevels;
1233 SMViewDesc.TextureCube.MostDetailedMip = 0;*/
1234
1235 //Create the Resource view
1236 //hr = d3d11Device->CreateShaderResourceView(SkyMapTexture, &SMViewDesc, &smrv);
1237 ///////////////**************new(SKYBOX)**************////////////////////
1238
1239
1240 // Describe the Sample State
1241 D3D11_SAMPLER_DESC sampDesc;
1242 ZeroMemory(&sampDesc, sizeof(sampDesc));
1243 sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
1244 sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
1245 sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
1246 sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
1247 sampDesc.ComparisonFunc = D3D11_COMPARISON_EQUAL;
1248 sampDesc.MinLOD = 0;
1249 sampDesc.MaxLOD = D3D11_FLOAT32_MAX;
1250
1251 //Create the Sample State
1252 hr = d3d11Device->CreateSamplerState(&sampDesc, &CubesTexSamplerState);
1253
1254 D3D11_RASTERIZER_DESC cmdesc;
1255
1256 ZeroMemory(&cmdesc, sizeof(D3D11_RASTERIZER_DESC));
1257 cmdesc.FillMode = D3D11_FILL_SOLID;
1258 cmdesc.CullMode = D3D11_CULL_BACK;
1259 cmdesc.FrontCounterClockwise = true;
1260 hr = d3d11Device->CreateRasterizerState(&cmdesc, &CCWcullMode);
1261
1262 cmdesc.FrontCounterClockwise = false;
1263
1264 hr = d3d11Device->CreateRasterizerState(&cmdesc, &CWcullMode);
1265
1266 cmdesc.CullMode = D3D11_CULL_NONE;
1267 //cmdesc.FillMode = D3D11_FILL_WIREFRAME;
1268 hr = d3d11Device->CreateRasterizerState(&cmdesc, &RSCullNone);
1269
1270 D3D11_DEPTH_STENCIL_DESC dssDesc;
1271 ZeroMemory(&dssDesc, sizeof(D3D11_DEPTH_STENCIL_DESC));
1272 dssDesc.DepthEnable = true;
1273 dssDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
1274 dssDesc.DepthFunc = D3D11_COMPARISON_EQUAL;
1275
1276 d3d11Device->CreateDepthStencilState(&dssDesc, &DSLessEqual);
1277 m_states = std::make_unique<CommonStates>(d3d11Device);
1278
1279 m_fxFactory = std::make_unique<EffectFactory>(d3d11Device);
1280
1281 m_model = Model::CreateFromCMO(d3d11Device, L"cup.cmo", *m_fxFactory);
1282 return true;
1283}
1284
1285
1286void StartTimer()
1287{
1288 LARGE_INTEGER frequencyCount;
1289 QueryPerformanceFrequency(&frequencyCount);
1290
1291 countsPerSecond = double(frequencyCount.QuadPart);
1292
1293 QueryPerformanceCounter(&frequencyCount);
1294 CounterStart = frequencyCount.QuadPart;
1295}
1296
1297double GetTime()
1298{
1299 LARGE_INTEGER currentTime;
1300 QueryPerformanceCounter(¤tTime);
1301 return double(currentTime.QuadPart - CounterStart) / countsPerSecond;
1302}
1303
1304double GetFrameTime()
1305{
1306 LARGE_INTEGER currentTime;
1307 __int64 tickCount;
1308 QueryPerformanceCounter(¤tTime);
1309
1310 tickCount = currentTime.QuadPart - frameTimeOld;
1311 frameTimeOld = currentTime.QuadPart;
1312
1313 if (tickCount < 0.0f)
1314 tickCount = (__int64)0.0f;
1315
1316 return float(tickCount) / countsPerSecond;
1317}
1318
1319void UpdateScene(double time)
1320{
1321 cupWorld = XMMatrixIdentity();
1322 Translation = XMMatrixTranslation(0.0f, 0.0f, 0.0f);
1323 Scale = XMMatrixScaling(10.0f, 10.0f, 10.0f);
1324 cupWorld = Translation * Scale;
1325 //////////////////////////////////////////
1326 //Reset cube1World
1327 groundWorld = XMMatrixIdentity();
1328
1329 //Define cube1's world space matrix
1330 Scale = XMMatrixScaling(5000.0f, 10.0f, 5000.0f);
1331 Translation = XMMatrixTranslation(0.0f, -80.0f, 0.0f);
1332
1333 //Set cube1's world space using the transformations
1334 groundWorld = Scale * Translation;
1335
1336 mapWorld = XMMatrixIdentity();
1337 Scale = XMMatrixScaling(1.0f, 1.0f, 1.0f);
1338 Translation = XMMatrixTranslation(0.0f, 25.0f, 0.0f);
1339 mapWorld = Scale * Translation;
1340
1341 ///////////////**************new(OBJ MESH)**************////////////////////
1342 meshWorld = XMMatrixIdentity();
1343
1344 //Define cube1's world space matrix
1345 Rotation = XMMatrixRotationX(objRotX) * XMMatrixRotationY(objRotY) * XMMatrixRotationZ(objRotZ);
1346 Scale = XMMatrixScaling(1.0f, 1.0f, 1.0f);
1347 camDir = camTarget - camPosition;
1348 Translation = XMMatrixTranslation(XMVectorGetX(g_vMeshPosition) + objTransX, XMVectorGetY(g_vMeshPosition) + objTransY, XMVectorGetZ(g_vMeshPosition) + objTransZ);
1349 //Translation = XMMatrixTranslation(XMVectorGetX(camPosition) + mapx, XMVectorGetY(camPosition) -9, XMVectorGetZ(camPosition) + mapz);
1350 meshWorld = Scale * Translation * Rotation;
1351 ///////////////**************new(OBJ MESH)**************////////////////////
1352 ///////////////**************new(SKYBOX)**************////////////////////
1353 //Reset sphereWorld
1354 sphereWorld = XMMatrixIdentity();
1355
1356 //Define sphereWorld's world space matrix
1357 Scale = XMMatrixScaling(5000.0f, 5000.0f, 5000.0f);
1358 //Make sure the sphere is always centered around camera
1359 //Translation = XMMatrixTranslation(XMVectorGetX(camPosition), XMVectorGetY(camPosition), XMVectorGetZ(camPosition));
1360 Translation = XMMatrixTranslation(0.0f, 0.0f, 0.0f);
1361 //Set sphereWorld's world space using the transformations
1362 sphereWorld = Scale * Translation;
1363 ///////////////**************new(SKYBOX)**************////////////////////
1364 ///////////////**************new(SPOTLIGHT)**************////////////////////
1365 light.pos.x = XMVectorGetX(camPosition);
1366 light.pos.y = XMVectorGetY(camPosition);
1367 light.pos.z = XMVectorGetZ(camPosition);
1368
1369 light.dir.x = XMVectorGetX(camTarget) - light.pos.x;
1370 light.dir.y = XMVectorGetY(camTarget) - light.pos.y;
1371 light.dir.z = XMVectorGetZ(camTarget) - light.pos.z;
1372 ///////////////**************new(SPOTLIGHT)**************////////////////////
1373 /*lightmesh.pos.x = (100.0f);
1374 lightmesh.pos.y = (5.0f);
1375 lightmesh.pos.z = (0.0f);
1376 lightmesh.dir.x = XMVectorGetX(camTarget) + light.pos.x;
1377 lightmesh.dir.y = XMVectorGetY(camTarget) + light.pos.y;
1378 lightmesh.dir.z = XMVectorGetZ(camTarget) + light.pos.z;*/
1379}
1380//FlatSquare(0, Width, 0, Height / 4, (D2D1::ColorF(1.0f, 1.0f, 1.0f, 0.4f))); //Draw the debug console's transparent rec
1381void RenderText(std::wstring text, int inInt)
1382{
1383
1384 d3d11DevCon->PSSetShader(D2D_PS, 0, 0);
1385
1386 //Release the D3D 11 Device
1387 keyedMutex11->ReleaseSync(0);
1388
1389 //Use D3D10.1 device
1390 keyedMutex10->AcquireSync(0, 5);
1391
1392 //Draw D2D content
1393 D2DRenderTarget->BeginDraw();
1394
1395 //Clear D2D Background
1396 D2DRenderTarget->Clear(D2D1::ColorF(0.0f, 0.0f, 0.0f, 0.0f));
1397
1398 //Create our string
1399 std::wostringstream printString;
1400 printString << text << inInt;
1401 printText = printString.str();
1402
1403 //Set the Font Color
1404 D2D1_COLOR_F FontColor = D2D1::ColorF(1.0f, 1.0f, 1.0f, 1.0f);
1405
1406 //Set the brush color D2D will use to draw with
1407 Brush->SetColor(FontColor);
1408
1409 //Create the D2D Render Area
1410 D2D1_RECT_F layoutRect = D2D1::RectF(0, 0, Width, Height);
1411
1412 //Draw the Text
1413 D2DRenderTarget->DrawText(
1414 printText.c_str(),
1415 wcslen(printText.c_str()),
1416 TextFormat,
1417 layoutRect,
1418 Brush
1419 );
1420
1421 D2DRenderTarget->EndDraw();
1422
1423 //Release the D3D10.1 Device
1424 keyedMutex10->ReleaseSync(1);
1425
1426 //Use the D3D11 Device
1427 keyedMutex11->AcquireSync(1, 5);
1428
1429 //Use the shader resource representing the direct2d render target
1430 //to texture a square which is rendered in screen space so it
1431 //overlays on top of our entire scene. We use alpha blending so
1432 //that the entire background of the D2D render target is "invisible",
1433 //And only the stuff we draw with D2D will be visible (the text)
1434
1435 //Set the blend state for D2D render target texture objects
1436 d3d11DevCon->OMSetBlendState(d2dTransparency, NULL, 0xffffffff);
1437
1438 //Set the d2d Index buffer
1439 d3d11DevCon->IASetIndexBuffer(d2dIndexBuffer, DXGI_FORMAT_R32_UINT, 0);
1440 //Set the d2d vertex buffer
1441 UINT stride = sizeof(Vertex);
1442 UINT offset = 0;
1443 d3d11DevCon->IASetVertexBuffers(0, 1, &d2dVertBuffer, &stride, &offset);
1444
1445 WVP = XMMatrixIdentity();
1446 cbPerObj.WVP = XMMatrixTranspose(WVP);
1447 d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
1448 d3d11DevCon->VSSetConstantBuffers(0, 1, &cbPerObjectBuffer);
1449 d3d11DevCon->PSSetShaderResources(0, 1, &d2dTexture);
1450 d3d11DevCon->PSSetSamplers(0, 1, &CubesTexSamplerState);
1451
1452 d3d11DevCon->RSSetState(CWcullMode);
1453 d3d11DevCon->DrawIndexed(6, 0, 0);
1454}
1455void DrawConsole(int fps)
1456{
1457 //Draw D2D content
1458 D2DRenderTarget->BeginDraw();
1459
1460 //Clear D2D Background
1461 D2DRenderTarget->Clear(D2D1::ColorF(0.0f, 0.0f, 0.0f, 0.0f));
1462
1463 //Create our string
1464 std::wostringstream printString;
1465 std::ostringstream PrintString;
1466 printString << "Engine Version: " _ENGINE_VERSION;
1467 printString << "\r\n";
1468
1469 printString << "FPS: " << fps << "\r\n" << "CamPosition: (" << XMVectorGetX(camPosition) << "," << XMVectorGetY(camPosition) << "," << XMVectorGetZ(camPosition) << ")";
1470 printString << " camTarget: (" << XMVectorGetX(camTarget) << "," << XMVectorGetY(camTarget) << "," << XMVectorGetZ(camTarget) << ")";
1471 printString << " camDir: (" << XMVectorGetX(camDir) << "," << XMVectorGetY(camDir) << "," << XMVectorGetZ(camDir) << ")";
1472 printString << " Distance: " << distance << " objRotX: " << objRotX << " objRotY:" << objRotY << " objRotZ: " << objRotZ << " objTransX: " << objTransX << " objTransY:" << objTransY << " objTransZ: " << objTransZ << "\r\n"; "\r\n";
1473 std::string s;
1474
1475 //Print out only the last 23 elements of the debug vector so it stays within the debug console's box and doesn't trail off screen
1476 for (int x = 22; x > 0; --x)
1477 {
1478 if (x <= DebugConsole.size() - 1)
1479 s += DebugConsole[DebugConsole.size() - x];
1480 }
1481
1482
1483
1484 printString << Unicode(s);
1485 printText = printString.str();
1486
1487 //Set the Font Color
1488 D2D1_COLOR_F FontColor = D2D1::ColorF(1.0f, 1.0f, 1.0f, 1.0f);
1489
1490 //Set the brush color D2D will use to draw with
1491 Brush->SetColor(FontColor);
1492
1493 //Create the D2D Render Area
1494 D2D1_RECT_F layoutRect = D2D1::RectF(0.0f, 0.0f, (float)Width, (float)Height);
1495
1496 //Draw the Text
1497 D2DRenderTarget->DrawText(
1498 printText.c_str(),
1499 wcslen(printText.c_str()),
1500 TextFormat,
1501 layoutRect,
1502 Brush
1503 );
1504
1505 //FlatSquare(0, 0, 0, 0, 0, 0);
1506 FlatSquare(0, (float)Width, 0, (float)(Height / 4.0f), (D2D1::ColorF(1.0f, 1.0f, 1.0f, 0.4f))); //Draw the debug console's transparent rec
1507 D2DRenderTarget->EndDraw();
1508}
1509void DrawD2D( int inInt)
1510{
1511
1512 d3d11DevCon->PSSetShader(D2D_PS, 0, 0);
1513
1514 //Release the D3D 11 Device
1515 keyedMutex11->ReleaseSync(0);
1516
1517 //Use D3D10.1 device
1518 keyedMutex10->AcquireSync(0, 5);
1519 const wchar_t* output = L"Hello World";
1520 //spriteBatch->Begin();
1521 // spriteFont->DrawString(spriteBatch.get(), output, DirectX::XMFLOAT2(0, 0), DirectX::Colors::White, 0.0f, DirectX::XMFLOAT2(0.0f,0.0f), DirectX::XMFLOAT2(1.0f, 1.0f));
1522 //spriteBatch->End();
1523 DrawConsole(inInt);
1524 //Release the D3D10.1 Device
1525 keyedMutex10->ReleaseSync(1);
1526
1527 //Use the D3D11 Device
1528 keyedMutex11->AcquireSync(1, 5);
1529
1530 //Use the shader resource representing the direct2d render target
1531 //to texture a square which is rendered in screen space so it
1532 //overlays on top of our entire scene. We use alpha blending so
1533 //that the entire background of the D2D render target is "invisible",
1534 //And only the stuff we draw with D2D will be visible (the text)
1535
1536 //Set the blend state for D2D render target texture objects
1537 d3d11DevCon->OMSetBlendState(d2dTransparency, NULL, 0xffffffff);
1538
1539 //Set the d2d Index buffer
1540 d3d11DevCon->IASetIndexBuffer(d2dIndexBuffer, DXGI_FORMAT_R32_UINT, 0);
1541 //Set the d2d vertex buffer
1542 UINT stride = sizeof(Vertex);
1543 UINT offset = 0;
1544 d3d11DevCon->IASetVertexBuffers(0, 1, &d2dVertBuffer, &stride, &offset);
1545
1546 WVP = XMMatrixIdentity();
1547 cbPerObj.WVP = XMMatrixTranspose(WVP);
1548 d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
1549 d3d11DevCon->VSSetConstantBuffers(0, 1, &cbPerObjectBuffer);
1550 d3d11DevCon->PSSetShaderResources(0, 1, &d2dTexture);
1551 d3d11DevCon->PSSetSamplers(0, 1, &CubesTexSamplerState);
1552
1553 d3d11DevCon->RSSetState(CWcullMode);
1554 //Draw the second cube
1555 d3d11DevCon->DrawIndexed(6, 0, 0);
1556}
1557
1558
1559void DrawScene()
1560{
1561 //Clear our render target and depth/stencil view
1562 float bgColor[4] = { 0.1f, 0.1f, 0.1f, 1.0f };
1563 d3d11DevCon->ClearRenderTargetView(renderTargetView, bgColor);
1564 d3d11DevCon->ClearDepthStencilView(depthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
1565
1566 constbuffPerFrame.light = light;
1567 d3d11DevCon->UpdateSubresource(cbPerFrameBuffer, 0, NULL, &constbuffPerFrame, 0, 0);
1568 d3d11DevCon->PSSetConstantBuffers(0, 1, &cbPerFrameBuffer);
1569
1570 //Set our Render Target
1571 d3d11DevCon->OMSetRenderTargets(1, &renderTargetView, depthStencilView);
1572
1573 //Set the default blend state (no blending) for opaque objects
1574 d3d11DevCon->OMSetBlendState(0, 0, 0xffffffff);
1575
1576 //Set Vertex and Pixel Shaders
1577 d3d11DevCon->VSSetShader(VS, 0, 0);
1578 d3d11DevCon->PSSetShader(PS, 0, 0);
1579
1580
1581 //////////////////////GRASS GROUND//////////////////////////////////////////
1582 //Set the cubes index buffer
1583 d3d11DevCon->IASetIndexBuffer(groundIndexBuffer, DXGI_FORMAT_R32_UINT, 0);
1584 //Set the cubes vertex buffer
1585 UINT stride = sizeof(Vertex);
1586 UINT offset = 0;
1587 d3d11DevCon->IASetVertexBuffers(0, 1, &groundVertexBuffer, &stride, &offset);
1588
1589 //Set the WVP matrix and send it to the constant buffer in effect file
1590 WVP = groundWorld * camView * camProjection;
1591 cbPerObj.WVP = XMMatrixTranspose(WVP);
1592 cbPerObj.World = XMMatrixTranspose(groundWorld);
1593 d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
1594 d3d11DevCon->VSSetConstantBuffers(0, 1, &cbPerObjectBuffer);
1595 d3d11DevCon->PSSetShaderResources(0, 1, &CubesTexture);
1596 d3d11DevCon->PSSetSamplers(0, 1, &CubesTexSamplerState);
1597 d3d11DevCon->RSSetState(CCWcullMode);
1598 d3d11DevCon->DrawIndexed(6, 0, 0);
1599 //////////////////////END GRASS GROUND//////////////////////////////////////
1600
1601
1602 //////////////////////BSP MAP///////////////////////////////////////////////
1603 //Set the BSP vertex/index buffer
1604 ID3D11Buffer* bspvertexbuffer = bsp.GetVertexBuffer();
1605 d3d11DevCon->IASetVertexBuffers(0, 1, &bspvertexbuffer, &stride, &offset);
1606 d3d11DevCon->RSSetState(CWcullMode);
1607
1608
1609 d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
1610 WVP = mapWorld * camView * camProjection;
1611 cbPerObj.WVP = XMMatrixTranspose(WVP);
1612 cbPerObj.World = XMMatrixTranspose(mapWorld);
1613
1614 d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
1615 bsp.PVS_Render(d3d11Device, d3d11DevCon, DirectX::SimpleMath::Vector3((XMVectorGetX(camPosition), XMVectorGetY(camPosition), XMVectorGetZ(camPosition))));
1616 d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
1617 //////////////////////END BSP MAP/////////////////////////////////////////////
1618 WVP = cupWorld * camView * camProjection;
1619 cbPerObj.WVP = XMMatrixTranspose(WVP);
1620 cbPerObj.World = XMMatrixTranspose(cupWorld);
1621
1622 //d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
1623 //auto mesh = m_model.get();
1624 //mesh->Draw(d3d11DevCon, (DirectX::CommonStates)cupWorld, camView, camProjection, false);
1625 /*for (auto it = m_model->meshes.cbegin(); it != m_model->meshes.cend(); ++it)
1626 {
1627 auto mesh = it->get();
1628 assert(mesh != 0);
1629
1630 //mesh->PrepareForRendering(deviceContext, states, true);
1631
1632 // Do model-level setCustomState work here
1633 d3d11DevCon->OMSetBlendState(Transparency, NULL, 0xffffffff);
1634 mesh->Draw(d3d11DevCon, cupWorld, camView, camProjection, false);
1635 mesh->Draw(d3d11DevCon,
1636 }
1637 d3d11DevCon->OMSetBlendState(Transparency, NULL, 0xffffffff);*/
1638 //m_states = std::make_unique<CommonStates>(d3d11Device);
1639 //Model model;
1640 //model.CreateFromCMO(d3d11Device, L"cup.cmo", *m_fxFactory);
1641 //model.Draw(d3d11DevCon, *m_states, meshWorld, meshView, meshProjection);
1642 //m_fxFactory = std::make_unique<EffectFactory>(d3d11Device);
1643 //Set our Render Target
1644 d3d11DevCon->OMSetRenderTargets(1, &renderTargetView, depthStencilView);
1645
1646 //Set the default blend state (no blending) for opaque objects
1647 d3d11DevCon->OMSetBlendState(0, 0, 0xffffffff);
1648 //Set Vertex and Pixel Shaders
1649 d3d11DevCon->VSSetShader(VS, 0, 0);
1650 d3d11DevCon->PSSetShader(PS, 0, 0);
1651 //m_model->Draw(d3d11DevCon, *m_states, meshWorld, meshView, meshProjection); //draw is right here
1652 d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
1653
1654 //////////////////////SKYSPHERE///////////////////////////////////////////////////
1655 /////Draw the Sky's Sphere//////
1656 //Set the spheres index buffer
1657 /*d3d11DevCon->IASetIndexBuffer(sphereIndexBuffer, DXGI_FORMAT_R32_UINT, 0);
1658 //Set the spheres vertex buffer
1659 d3d11DevCon->IASetVertexBuffers(0, 1, &sphereVertBuffer, &stride, &offset);
1660
1661 //Set the WVP matrix and send it to the constant buffer in effect file
1662 WVP = sphereWorld * camView * camProjection;
1663 cbPerObj.WVP = XMMatrixTranspose(WVP);
1664 cbPerObj.World = XMMatrixTranspose(sphereWorld);
1665 d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
1666 d3d11DevCon->VSSetConstantBuffers(0, 1, &cbPerObjectBuffer);
1667 //Send our skymap resource view to pixel shader
1668 d3d11DevCon->PSSetShaderResources(0, 1, &smrv);
1669 d3d11DevCon->PSSetSamplers(0, 1, &CubesTexSamplerState);
1670
1671 //Set the new VS and PS shaders
1672 d3d11DevCon->VSSetShader(SKYMAP_VS, 0, 0);
1673 d3d11DevCon->PSSetShader(SKYMAP_PS, 0, 0);
1674 //Set the new depth/stencil and RS states
1675 d3d11DevCon->OMSetDepthStencilState(DSLessEqual, 0);
1676 d3d11DevCon->RSSetState(RSCullNone);
1677 d3d11DevCon->DrawIndexed(NumSphereFaces * 3, 0, 0);
1678 */
1679 //Set the default VS, PS shaders and depth/stencil state
1680 d3d11DevCon->VSSetShader(VS, 0, 0);
1681 d3d11DevCon->PSSetShader(PS, 0, 0);
1682 d3d11DevCon->OMSetDepthStencilState(NULL, 0);
1683 //////////////////////END SKYSPHERE///////////////////////////////////////////////////
1684
1685 //////////////////////OBJ MODEL///////////////////////////////////////////////
1686
1687 //Draw our model's NON-transparent subsets
1688 for (int i = 0; i < meshSubsets; ++i)
1689 {
1690 //Set the grounds index buffer
1691 d3d11DevCon->IASetIndexBuffer(meshIndexBuff, DXGI_FORMAT_R32_UINT, 0);
1692 //Set the grounds vertex buffer
1693 d3d11DevCon->IASetVertexBuffers(0, 1, &meshVertBuff, &stride, &offset);
1694
1695 //Set the WVP matrix and send it to the constant buffer in effect file
1696 WVP = meshWorld * meshView * meshProjection;
1697 cbPerObj.WVP = XMMatrixTranspose(WVP);
1698 cbPerObj.World = XMMatrixTranspose(meshWorld);
1699 cbPerObj.difColor = material[meshSubsetTexture[i]].difColor;
1700 cbPerObj.hasTexture = material[meshSubsetTexture[i]].hasTexture;
1701 d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
1702 d3d11DevCon->VSSetConstantBuffers(0, 1, &cbPerObjectBuffer);
1703 d3d11DevCon->PSSetConstantBuffers(1, 1, &cbPerObjectBuffer);
1704 if (material[meshSubsetTexture[i]].hasTexture)
1705 d3d11DevCon->PSSetShaderResources(0, 1, &meshSRV[material[meshSubsetTexture[i]].texArrayIndex]);
1706 d3d11DevCon->PSSetSamplers(0, 1, &CubesTexSamplerState);
1707
1708 d3d11DevCon->RSSetState(RSCullNone);
1709 int indexStart = meshSubsetIndexStart[i];
1710 int indexDrawAmount = meshSubsetIndexStart[i + 1] - meshSubsetIndexStart[i];
1711 if (!material[meshSubsetTexture[i]].transparent)
1712 d3d11DevCon->DrawIndexed(indexDrawAmount, indexStart, 0);
1713 }
1714
1715 ///////////////**************new**************////////////////////
1716 //Draw our model's TRANSPARENT subsets now
1717
1718 //Set our blend state
1719 d3d11DevCon->OMSetBlendState(Transparency, NULL, 0xffffffff);
1720
1721 for (int i = 0; i < meshSubsets; ++i)
1722 {
1723 //Set the grounds index buffer
1724 d3d11DevCon->IASetIndexBuffer(meshIndexBuff, DXGI_FORMAT_R32_UINT, 0);
1725 //Set the grounds vertex buffer
1726 d3d11DevCon->IASetVertexBuffers(0, 1, &meshVertBuff, &stride, &offset);
1727
1728 //Set the WVP matrix and send it to the constant buffer in effect file
1729 WVP = meshWorld * meshView * meshProjection;
1730 cbPerObj.WVP = XMMatrixTranspose(WVP);
1731 cbPerObj.World = XMMatrixTranspose(meshWorld);
1732 cbPerObj.difColor = material[meshSubsetTexture[i]].difColor;
1733 cbPerObj.hasTexture = material[meshSubsetTexture[i]].hasTexture;
1734 d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
1735 d3d11DevCon->VSSetConstantBuffers(0, 1, &cbPerObjectBuffer);
1736 d3d11DevCon->PSSetConstantBuffers(1, 1, &cbPerObjectBuffer);
1737 if (material[meshSubsetTexture[i]].hasTexture)
1738 d3d11DevCon->PSSetShaderResources(0, 1, &meshSRV[material[meshSubsetTexture[i]].texArrayIndex]);
1739 d3d11DevCon->PSSetSamplers(0, 1, &CubesTexSamplerState);
1740
1741 d3d11DevCon->RSSetState(RSCullNone);
1742 int indexStart = meshSubsetIndexStart[i];
1743 int indexDrawAmount = meshSubsetIndexStart[i + 1] - meshSubsetIndexStart[i];
1744 if (material[meshSubsetTexture[i]].transparent)
1745 d3d11DevCon->DrawIndexed(indexDrawAmount, indexStart, 0);
1746 }
1747
1748 //////////////////////END OBJ MODEL///////////////////////////////////////////////
1749
1750
1751
1752// if (g_bShowConsole)
1753// DrawD2D(fps);
1754 //std::wstring helloworld = L"Hello World";
1755 //wchar_t *helloworld;
1756 //swprintf(helloworld, "Hello World");
1757
1758 //Present the backbuffer to the screen
1759 SwapChain->Present(0, 0);
1760}
1761///////////////**************new**************////////////////////
1762void CreateSphere(int LatLines, int LongLines)
1763{
1764 NumSphereVertices = ((LatLines - 2) * LongLines) + 2;
1765 NumSphereFaces = ((LatLines - 3)*(LongLines)* 2) + (LongLines * 2);
1766
1767 float sphereYaw = 0.0f;
1768 float spherePitch = 0.0f;
1769
1770 std::vector<Vertex> vertices(NumSphereVertices);
1771
1772 XMVECTOR currVertPos = XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);
1773
1774 vertices[0].pos.x = 0.0f;
1775 vertices[0].pos.y = 0.0f;
1776 vertices[0].pos.z = 1.0f;
1777
1778 for (DWORD i = 0; i < (unsigned int)LatLines - 2; ++i)
1779 {
1780 spherePitch = float((i + 1) * (3.14 / (LatLines - 1)));
1781 Rotationx = XMMatrixRotationX(spherePitch);
1782 for (DWORD j = 0; j < (unsigned int)LongLines; ++j)
1783 {
1784 sphereYaw = (float)(j * (6.28 / (unsigned int)(LongLines)));
1785 Rotationy = XMMatrixRotationZ(sphereYaw);
1786 currVertPos = XMVector3TransformNormal(XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f), (Rotationx * Rotationy));
1787 currVertPos = XMVector3Normalize(currVertPos);
1788 vertices[i*LongLines + j + 1].pos.x = XMVectorGetX(currVertPos);
1789 vertices[i*LongLines + j + 1].pos.y = XMVectorGetY(currVertPos);
1790 vertices[i*LongLines + j + 1].pos.z = XMVectorGetZ(currVertPos);
1791 }
1792 }
1793
1794 vertices[NumSphereVertices - 1].pos.x = 0.0f;
1795 vertices[NumSphereVertices - 1].pos.y = 0.0f;
1796 vertices[NumSphereVertices - 1].pos.z = -1.0f;
1797
1798
1799 D3D11_BUFFER_DESC vertexBufferDesc;
1800 ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc));
1801
1802 vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
1803 vertexBufferDesc.ByteWidth = sizeof(Vertex)* NumSphereVertices;
1804 vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
1805 vertexBufferDesc.CPUAccessFlags = 0;
1806 vertexBufferDesc.MiscFlags = 0;
1807
1808 D3D11_SUBRESOURCE_DATA vertexBufferData;
1809
1810 ZeroMemory(&vertexBufferData, sizeof(vertexBufferData));
1811 vertexBufferData.pSysMem = &vertices[0];
1812 hr = d3d11Device->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &sphereVertBuffer);
1813
1814
1815 std::vector<DWORD> indices(NumSphereFaces * 3);
1816
1817 int k = 0;
1818 for (DWORD l = 0; l < (unsigned int)LongLines - 1; ++l)
1819 {
1820 indices[k] = 0;
1821 indices[k + 1] = l + 1;
1822 indices[k + 2] = l + 2;
1823 k += 3;
1824 }
1825
1826 indices[k] = 0;
1827 indices[k + 1] = LongLines;
1828 indices[k + 2] = 1;
1829 k += 3;
1830
1831 for (DWORD i = 0; i < (unsigned int)LatLines - 3; ++i)
1832 {
1833 for (DWORD j = 0; j < (unsigned int)LongLines - 1; ++j)
1834 {
1835 indices[k] = i*LongLines + j + 1;
1836 indices[k + 1] = i*LongLines + j + 2;
1837 indices[k + 2] = (i + 1)*LongLines + j + 1;
1838
1839 indices[k + 3] = (i + 1)*LongLines + j + 1;
1840 indices[k + 4] = i*LongLines + j + 2;
1841 indices[k + 5] = (i + 1)*LongLines + j + 2;
1842
1843 k += 6; // next quad
1844 }
1845
1846 indices[k] = (i*LongLines) + LongLines;
1847 indices[k + 1] = (i*LongLines) + 1;
1848 indices[k + 2] = ((i + 1)*LongLines) + LongLines;
1849
1850 indices[k + 3] = ((i + 1)*LongLines) + LongLines;
1851 indices[k + 4] = (i*LongLines) + 1;
1852 indices[k + 5] = ((i + 1)*LongLines) + 1;
1853
1854 k += 6;
1855 }
1856
1857 for (DWORD l = 0; l < (unsigned int)LongLines - 1; ++l)
1858 {
1859 indices[k] = NumSphereVertices - 1;
1860 indices[k + 1] = (NumSphereVertices - 1) - (l + 1);
1861 indices[k + 2] = (NumSphereVertices - 1) - (l + 2);
1862 k += 3;
1863 }
1864
1865 indices[k] = NumSphereVertices - 1;
1866 indices[k + 1] = (NumSphereVertices - 1) - LongLines;
1867 indices[k + 2] = NumSphereVertices - 2;
1868
1869 D3D11_BUFFER_DESC indexBufferDesc;
1870 ZeroMemory(&indexBufferDesc, sizeof(indexBufferDesc));
1871
1872 indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
1873 indexBufferDesc.ByteWidth = sizeof(DWORD)* NumSphereFaces * 3;
1874 indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
1875 indexBufferDesc.CPUAccessFlags = 0;
1876 indexBufferDesc.MiscFlags = 0;
1877
1878 D3D11_SUBRESOURCE_DATA iinitData;
1879
1880 iinitData.pSysMem = &indices[0];
1881 d3d11Device->CreateBuffer(&indexBufferDesc, &iinitData, &sphereIndexBuffer);
1882
1883}
1884///////////////**************new**************////////////////////
1885
1886
1887
1888
1889int messageloop(){
1890 MSG msg;
1891 ZeroMemory(&msg, sizeof(MSG));
1892 while (true)
1893 {
1894 BOOL PeekMessageL(
1895 LPMSG lpMsg,
1896 HWND hWnd,
1897 UINT wMsgFilterMin,
1898 UINT wMsgFilterMax,
1899 UINT wRemoveMsg
1900 );
1901
1902 if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
1903 {
1904 if (msg.message == WM_QUIT)
1905 break;
1906 TranslateMessage(&msg);
1907 DispatchMessage(&msg);
1908 }
1909 else{
1910 // run game code
1911 frameCount++;
1912 if (GetTime() > 1.0f)
1913 {
1914 fps = frameCount;
1915 frameCount = 0;
1916 StartTimer();
1917 }
1918
1919 frameTime = GetFrameTime();
1920
1921 DetectInput(frameTime);
1922 UpdateScene(frameTime);
1923 DrawScene();
1924 }
1925 }
1926 return msg.wParam;
1927}
1928
1929LRESULT CALLBACK WndProc(HWND hwnd,
1930 UINT msg,
1931 WPARAM wParam,
1932 LPARAM lParam)
1933{
1934 switch (msg)
1935 {
1936 case WM_KEYDOWN:
1937 if (wParam == VK_ESCAPE){
1938 DestroyWindow(hwnd);
1939 }
1940 return 0;
1941
1942 case WM_DESTROY:
1943 PostQuitMessage(0);
1944 return 0;
1945 }
1946 return DefWindowProc(hwnd,
1947 msg,
1948 wParam,
1949 lParam);
1950}