· 6 years ago · Mar 28, 2020, 09:48 PM
1#define _CRT_SECURE_NO_WARNINGS 1
2#define _ENGINE_VERSION "0.0.03c";
3
4/* GAME ENGINE WRITTEN WITH THE DIRECTX11 API BY THOMAS WOODMAN
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========================================
453/23/2020 (My 31st Birthday) Upgrading to 0.0.03b
46========================================
47-Massive amount of work/experimentation has been taken all month long; Fell back to Legacy, went back to standard up-to-date SDK, *a lot* of learning/trial and error
48-Binary is now 64-bit; This is due to ASSIMP's lib is only x64, no point in compiling 32-bit binaries anymore anyways, especially for a game engine
49-Implemented Skybox(Upgraded it to DXTK/d3d11 standards)
50-Implemented ASSIMP Mesh Loader, loads basic meshes with embedded diffuse textures
51-Removed old deprecated OBJ Loader
52-BSP Map Now Draws within a standard for-loop pursuant to number of faces, PVS_Render() wouldn't draw properly, random shadows and random tri's appearing/disappearing
53========================================
543/26/2020(6:06AM) Upgrading to 0.0.03c
55========================================
56-SpriteBatch/SpriteFont now work perfectly. Understanding that DX11 is a state-machine is very important; Can now make use of DXTK tools without destroying the scene.
57-DXTK's Model drawing now works without a hitch. Now this engine has two separate ways of drawing meshes, we shall see which one is perferred(obj/fbx/3ds's converted to .CUO/SDKMESH, or my ASSIMP modelloader?)
58-OBJ meshes that the player holds/uses no longer clips into the walls of other objects, i.e. the BSP map (WARNING: DISABLING Z-BUFFER WHILE DRAWING MESHES CAUSES THEM TO LOSE *THEIR* SENSE OF DEPTH AS WELL) this problem must be solved later
59-Remember: DXTK draws need ALL states proprerly set: The IA(Input Assembler) Layout, the Topology(in most cases TRIANGLELIST), shaders, OutputMerger(OM) Render Targets, and Z-Buffer MUST be enabled.
60-XMVECTOR's for First Person Camera have been converted to DirectX's namespace and using SimpleMath Library(DirectX::SimpleMath::Vector3 rather than XMVECTOR, should help with collison detection in the future)
61-Collision Detection System now using DirectX::SimpleMath::Vector3 because D3DXVECTOR3 no longer exists in the Windows SDK (In 2005 I was competing with SEGA in terms of game development; I wasted my 20's to drugs and now I have a decade of catch-up...fucking oxy/heroin)
62-Z-Buffer Problem stated just a few lines earlier regarding mesh losing depth has been fixed by clearing the depth state prior to its draw (Thank you Jesse Natalie from Microsoft for the advice!)
63/*-----------------------------------------------CHANGELOG--------------------------------------------------------------*/
64//Include and link appropriate libraries and headers//
65#pragma comment(lib, "d3d11.lib")
66//#pragma comment(lib, "d3dx11.lib")
67//#pragma comment(lib, "d3dx10.lib")
68#pragma comment (lib, "D3D10_1.lib")
69#pragma comment (lib, "DXGI.lib")
70#pragma comment (lib, "D2D1.lib")
71#pragma comment (lib, "dwrite.lib")
72#pragma comment (lib, "dinput8.lib")
73#pragma comment (lib, "dxguid.lib")
74#pragma comment (lib, "C:\\DirectXTK\\Bin\\Desktop_2017_Win10\\x64\\Release\\DirectXTK.lib")
75#pragma comment (lib, "D3DCompiler.lib")
76#pragma comment (lib, "C:\\DX11Engine\\DX11Engine\\lib\\x64\\assimp-vc140-mt.lib")
77#pragma warning( disable : 4005)
78
79/***************************************/
80//DEBUG #DEFINES TO SWTICH BETWEEN WEAPONS
81/***************************************/
82#define __PPSH //PPSH41 Submachine Gun
83//#define __PISTOL //Colt .45 ACP Pistol
84#include <windows.h>
85#include <d3d11.h>
86//#include <d3dx11.h>
87//#include <d3dx10.h>
88//#include <xnamath.h>
89#include <SpriteFont.h>
90#include <SpriteBatch.h>
91#include <DirectXMath.h>
92#include <SimpleMath.h>
93#include <DirectXPackedVector.h>
94#include <DirectXCollision.h>
95#include <DirectXColors.h>
96#include <WICTextureLoader.h>
97#include <Effects.h>
98#include <Model.h>
99#include <CommonStates.h>
100#include <DDSTextureLoader.h>
101#include <GeometricPrimitive.h>
102#include <PrimitiveBatch.h>
103
104#include <wrl/client.h>
105#include <d3dcompiler.h>
106#include <D3D10_1.h>
107#include <DXGI.h>
108#include <D2D1.h>
109#include <sstream>
110#include <dwrite.h>
111#include <dinput.h>
112#include <vector> //For OBJ Mesh
113#include <fstream> //For OBJ Mesh
114#include <istream> //For OBJ Mesh
115
116#include "assimp/Importer.hpp"
117#include "assimp/postprocess.h"
118#include "assimp/scene.h"
119
120using namespace DirectX;
121using namespace Microsoft::WRL;
122using namespace DirectX::PackedVector;
123using namespace DirectX::SimpleMath;
124#include "Structs.h"
125#include "bsp.h"
126#include "ModelLoader.h"
127//Global Declarations - Interfaces//
128IDXGISwapChain* SwapChain;
129ID3D11Device* d3d11Device;
130ID3D11DeviceContext* d3d11DevCon;
131ID3D11RenderTargetView* renderTargetView;
132ID3D11Buffer* groundIndexBuffer;
133ID3D11DepthStencilView* depthStencilView;
134ID3D11Texture2D* depthStencilBuffer;
135ID3D11Buffer* groundVertexBuffer;
136ID3D11VertexShader* VS;
137ID3D11PixelShader* PS;
138ID3D11PixelShader* D2D_PS;
139ID3DBlob* D2D_PS_Buffer;
140ID3DBlob* VS_Buffer;
141ID3DBlob* PS_Buffer;
142ID3D11InputLayout* vertLayout;
143ID3D11Buffer* cbPerObjectBuffer;
144ID3D11BlendState* Transparency;
145ID3D11RasterizerState* CCWcullMode;
146ID3D11RasterizerState* CWcullMode;
147ID3D11RasterizerState* RSCullNone;
148ID3D11ShaderResourceView* CubesTexture;
149ID3D11ShaderResourceView* SkyMapTexture;
150ID3D11SamplerState* CubesTexSamplerState;
151ID3D11Buffer* cbPerFrameBuffer;
152ID3D11BlendState* d2dTransparency;
153ID3D10Device1 *d3d101Device;
154IDXGIKeyedMutex *keyedMutex11;
155IDXGIKeyedMutex *keyedMutex10;
156ID2D1RenderTarget *D2DRenderTarget;
157ID2D1SolidColorBrush *Brush;
158Microsoft::WRL::ComPtr<ID3D11Texture2D> backBuffer;
159//Microsoft::WRL::ComPtr<ID3D11Device> device;
160ID3D11Texture2D *BackBuffer11;
161ID3D11Texture2D *sharedTex11;
162ID3D11Buffer *d2dVertBuffer;
163ID3D11Buffer *d2dIndexBuffer;
164ID3D11Buffer *d2dVertBuffer2;
165ID3D11Buffer *d2dIndexBuffer2;
166ID3D11ShaderResourceView *d2dTexture;
167IDWriteFactory *DWriteFactory;
168IDWriteTextFormat *TextFormat;
169ID3D11DepthStencilState* DSLessEqual;
170ID3D11Buffer* OBJVertexBuffer;
171ID3D11Buffer* OBJIndexBuffer;
172IEffect *Effect;
173//ID3D11RasterizerState* RSCullNone; //OBJ MESH VAR(initally)
174
175std::unique_ptr<DirectX::SpriteBatch> spriteBatch;
176std::unique_ptr<DirectX::SpriteFont> spriteFont;
177ModelLoader ModelOne;
178IDirectInputDevice8* DIKeyboard;
179IDirectInputDevice8* DIMouse;
180
181bool g_bShowConsole = true;
182bool g_bCollision = false;
183float distance = 0.0f;
184int test = 0;
185
186void DetectCollison(void);
187
188std::wstring printText;
189std::wstring Unicode(const std::string s)
190{
191 std::wstring wsTmp(s.begin(), s.end());
192 return wsTmp;
193}
194
195//Global Declarations - Others//
196LPCTSTR WndClassName = "firstwindow";
197HWND hwnd = NULL;
198HRESULT hr;
199
200int Width = 1920;
201int Height = 1200;
202
203DIMOUSESTATE mouseLastState;
204LPDIRECTINPUT8 DirectInput;
205
206float rotx = 0;
207float rotz = 0;
208float scaleX = 1.0f;
209float scaleY = 1.0f;
210
211#ifdef __PISTOL
212float objRotX = -0.42f; //FOR M1911 PISTOL MESH
213float objRotY = 0.39f;
214float objRotZ = 0.11f;
215float objTransX = -2.24f;
216float objTransY = -15.4103f;
217float objTransZ = -2.3f;
218#endif
219#ifdef __PPSH
220float objRotX = 0.26f; //FOR PPSH41 SUBMACHINEGUN MESH
221float objRotY = 2.09f;
222float objRotZ = 0.33f;
223float objTransX = -46.74f;
224float objTransY = -23.4103f;
225float objTransZ = 15.7f;
226#endif
227XMMATRIX Rotationx;
228XMMATRIX Rotationz;
229
230XMMATRIX WVP;
231XMMATRIX cube1World;
232XMMATRIX cube2World;
233XMMATRIX camView;
234XMMATRIX camProjection;
235
236XMMATRIX meshView;
237XMMATRIX meshProjection;
238
239XMMATRIX d2dWorld;
240DirectX::SimpleMath::Vector3 g_vCamPosition;
241DirectX::SimpleMath::Vector3 camPosition;
242DirectX::SimpleMath::Vector3 newCamPosition;
243DirectX::SimpleMath::Vector3 oldCamPosition;
244DirectX::SimpleMath::Vector3 camTarget;
245XMVECTOR camUp;
246XMVECTOR camDir;
247XMVECTOR DefaultForward = XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);
248XMVECTOR DefaultRight = XMVectorSet(1.0f, 0.0f, 0.0f, 0.0f);
249XMVECTOR camForward = XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);
250XMVECTOR camRight = XMVectorSet(1.0f, 0.0f, 0.0f, 0.0f);
251XMVECTOR vLen = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
252XMVECTOR g_vMeshPosition = XMVectorSet(10.0f, 1.0f, 10.0f, 0.0f);
253XMVECTOR g_vMeshAt = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
254XMVECTOR g_vMeshUp = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
255
256XMMATRIX camRotationMatrix;
257XMMATRIX groundWorld;
258XMMATRIX meshWorld;
259XMMATRIX mapWorld;
260///////////////**************new(OBJ MESH)**************////////////////////
261XMMATRIX cupWorld;
262
263///////////////**************new(OBJ MESH)**************////////////////////
264///////////////**************new(SKYBOX)**************////////////////////
265ID3D11Buffer* sphereIndexBuffer;
266ID3D11Buffer* sphereVertBuffer;
267
268ID3D11VertexShader* SKYMAP_VS;
269ID3D11PixelShader* SKYMAP_PS;
270ID3D10Blob* SKYMAP_VS_Buffer;
271ID3D10Blob* SKYMAP_PS_Buffer;
272
273ID3D11ShaderResourceView* smrv;
274
275
276
277
278XMMATRIX Rotationy;
279
280
281
282
283
284
285
286//////////////////////////////////////////////////////////////////
287/*//////////////////////////DIRECTXTK MESH TEST/////////////////*/
288DirectX::SimpleMath::Matrix m_world;
289DirectX::SimpleMath::Matrix m_view;
290DirectX::SimpleMath::Matrix m_proj;
291
292std::unique_ptr<DirectX::CommonStates> m_states;
293std::unique_ptr<DirectX::IEffectFactory> m_fxFactory;
294std::unique_ptr<DirectX::Model> m_model;
295///////////////**************new**************////////////////////
296int NumSphereVertices;
297int NumSphereFaces;
298
299XMMATRIX sphereWorld;
300///////////////**************new**************////////////////////
301///////////////**************new**************////////////////////
302void CreateSphere(int LatLines, int LongLines);
303///////////////**************new**************////////////////////
304///////////////**************new(SKYBOX)**************////////////////////
305float moveLeftRight = 0.0f;
306float moveBackForward = 0.0f;
307
308float camYaw = 0.0f;
309float camPitch = 0.0f;
310
311XMMATRIX Rotation;
312XMMATRIX Scale;
313XMMATRIX Translation;
314float rot = 0.01f;
315
316double countsPerSecond = 0.0;
317__int64 CounterStart = 0;
318
319int frameCount = 0;
320int fps = 0;
321
322__int64 frameTimeOld = 0;
323double frameTime;
324
325//Function Prototypes//
326bool InitializeDirect3d11App(HINSTANCE hInstance);
327void CleanUp();
328bool InitScene();
329void DrawScene();
330bool InitD2D_D3D101_DWrite(IDXGIAdapter1 *Adapter);
331void InitD2DScreenTexture();
332void UpdateScene(double time);
333
334void UpdateCamera();
335
336void RenderText(std::wstring text, int inInt);
337
338void StartTimer();
339double GetTime();
340double GetFrameTime();
341
342bool InitializeWindow(HINSTANCE hInstance,
343 int ShowWnd,
344 int width, int height,
345 bool windowed);
346WPARAM messageloop();
347
348bool InitDirectInput(HINSTANCE hInstance);
349void DetectInput(double time);
350
351void DrawConsole(void);
352
353LRESULT CALLBACK WndProc(HWND hWnd,
354 UINT msg,
355 WPARAM wParam,
356 LPARAM lParam);
357
358//Create effects constant buffer's structure//
359//Create effects constant buffer's structure//
360
361
362cbPerObject cbPerObj;
363
364///////////////**************FOR BSP HEADER**************///////////
365/* BSP TEXTURE CODE FOR DIRECTXTK
366std::string texfilename = str;
367std::wstring wfilename(texfilename.begin(), texfilename.end());
368hr = CreateWICTextureFromFile(d3d11Device, d3d11DevCon,
369wfilename.c_str(), nullptr, &pTexture);
370//////////////////////////////////////////////////////////////////*/
371///////////////**************new**************////////////////////
372///////////////**************new (OBJ MESH)**************////////////////////
373
374
375std::vector<SurfaceMaterial> material;
376
377
378Light light[2];
379
380
381CBSP bsp;
382
383
384cbPerFrame constbuffPerFrame;
385
386
387
388/*******************/
389//ASSIMP MESH LOADER
390////////////////////////////////////////////////////////////////
391ModelLoader::ModelLoader() :
392 dev(nullptr),
393 devcon(nullptr),
394 meshes(),
395 directory(),
396 textures_loaded(),
397 hwnd(nullptr) {
398 // empty
399}
400
401
402ModelLoader::~ModelLoader() {
403 // empty
404}
405
406bool ModelLoader::Load(HWND hwnd, ID3D11Device * dev, ID3D11DeviceContext * devcon, std::string filename) {
407 Assimp::Importer importer;
408
409 const aiScene* pScene = importer.ReadFile(filename,
410 aiProcess_Triangulate |
411 aiProcess_ConvertToLeftHanded);
412
413 if (pScene == NULL)
414 return false;
415
416 this->directory = filename.substr(0, filename.find_last_of("/\\"));
417
418 this->dev = dev;
419 this->devcon = devcon;
420 this->hwnd = hwnd;
421
422 processNode(pScene->mRootNode, pScene);
423
424 return true;
425}
426
427void ModelLoader::Draw(ID3D11DeviceContext* devcon) {
428 for (int i = 0; i < meshes.size(); ++i) {
429
430 //Set the WVP matrix and send it to the constant buffer in effect file
431 WVP = meshWorld * meshView * meshProjection;
432 cbPerObj.WVP = XMMatrixTranspose(WVP);
433 cbPerObj.World = XMMatrixTranspose(meshWorld);
434 d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
435 meshes[i].Draw(devcon);
436 d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
437 }
438}
439
440std::string textype;
441
442Mesh ModelLoader::processMesh(aiMesh * mesh, const aiScene * scene) {
443 // Data to fill
444 std::vector<VERTEX> vertices;
445 std::vector<UINT> indices;
446 std::vector<Texture> textures;
447
448 if (mesh->mMaterialIndex >= 0) {
449 aiMaterial* mat = scene->mMaterials[mesh->mMaterialIndex];
450
451 if (textype.empty()) {
452 textype = determineTextureType(scene, mat);
453 }
454 }
455
456 // Walk through each of the mesh's vertices
457 for (UINT i = 0; i < mesh->mNumVertices; i++) {
458 VERTEX vertex;
459
460 vertex.X = mesh->mVertices[i].x;
461 vertex.Y = mesh->mVertices[i].y;
462 vertex.Z = mesh->mVertices[i].z;
463
464 if (mesh->mTextureCoords[0]) {
465 vertex.texcoord.x = (float)mesh->mTextureCoords[0][i].x;
466 vertex.texcoord.y = (float)mesh->mTextureCoords[0][i].y;
467 }
468
469 vertices.push_back(vertex);
470 }
471
472 for (UINT i = 0; i < mesh->mNumFaces; i++) {
473 aiFace face = mesh->mFaces[i];
474
475 for (UINT j = 0; j < face.mNumIndices; j++)
476 indices.push_back(face.mIndices[j]);
477 }
478
479 if (mesh->mMaterialIndex >= 0) {
480 aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];
481
482 std::vector<Texture> diffuseMaps = this->loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse", scene);
483 textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
484 }
485
486 return Mesh(dev, vertices, indices, textures);
487}
488
489std::vector<Texture> ModelLoader::loadMaterialTextures(aiMaterial * mat, aiTextureType type, std::string typeName, const aiScene * scene) {
490 std::vector<Texture> textures;
491 for (UINT i = 0; i < mat->GetTextureCount(type); i++) {
492 aiString str;
493 mat->GetTexture(type, i, &str);
494 // Check if texture was loaded before and if so, continue to next iteration: skip loading a new texture
495 bool skip = false;
496 for (UINT j = 0; j < textures_loaded.size(); j++) {
497 if (std::strcmp(textures_loaded[j].path.c_str(), str.C_Str()) == 0) {
498 textures.push_back(textures_loaded[j]);
499 skip = true; // A texture with the same filepath has already been loaded, continue to next one. (optimization)
500 break;
501 }
502 }
503 if (!skip) { // If texture hasn't been loaded already, load it
504 HRESULT hr;
505 Texture texture;
506 if (textype == "embedded compressed texture") {
507 int textureindex = getTextureIndex(&str);
508 texture.texture = getTextureFromModel(scene, textureindex);
509 }
510 else {
511 std::string filename = std::string(str.C_Str());
512 filename = directory + '/' + filename;
513 std::wstring filenamews = std::wstring(filename.begin(), filename.end());
514 hr = CreateWICTextureFromFile(dev, devcon, filenamews.c_str(), nullptr, &texture.texture);
515 if (FAILED(hr))
516 MessageBox(hwnd, filename.c_str(), filename.c_str(), MB_ICONERROR | MB_OK);
517 }
518 texture.type = typeName;
519 texture.path = str.C_Str();
520 textures.push_back(texture);
521 this->textures_loaded.push_back(texture); // Store it as texture loaded for entire model, to ensure we won't unnecesery load duplicate textures.
522 }
523 }
524 return textures;
525}
526
527void ModelLoader::Close() {
528 for (auto& t : textures_loaded)
529 t.Release();
530
531 for (int i = 0; i < meshes.size(); i++) {
532 meshes[i].Close();
533 }
534}
535
536void ModelLoader::processNode(aiNode * node, const aiScene * scene) {
537 for (UINT i = 0; i < node->mNumMeshes; i++) {
538 aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
539 meshes.push_back(this->processMesh(mesh, scene));
540 }
541
542 for (UINT i = 0; i < node->mNumChildren; i++) {
543 this->processNode(node->mChildren[i], scene);
544 }
545}
546
547std::string ModelLoader::determineTextureType(const aiScene * scene, aiMaterial * mat) {
548 aiString textypeStr;
549 mat->GetTexture(aiTextureType_DIFFUSE, 0, &textypeStr);
550 std::string textypeteststr = textypeStr.C_Str();
551 if (textypeteststr == "*0" || textypeteststr == "*1" || textypeteststr == "*2" || textypeteststr == "*3" || textypeteststr == "*4" || textypeteststr == "*5") {
552 if (scene->mTextures[0]->mHeight == 0) {
553 return "embedded compressed texture";
554 }
555 else {
556 return "embedded non-compressed texture";
557 }
558 }
559 if (textypeteststr.find('.') != std::string::npos) {
560 return "textures are on disk";
561 }
562
563 return ".";
564}
565
566int ModelLoader::getTextureIndex(aiString * str) {
567 std::string tistr;
568 tistr = str->C_Str();
569 tistr = tistr.substr(1);
570 return stoi(tistr);
571}
572
573ID3D11ShaderResourceView * ModelLoader::getTextureFromModel(const aiScene * scene, int textureindex) {
574 HRESULT hr;
575 ID3D11ShaderResourceView *texture;
576
577 int* size = reinterpret_cast<int*>(&scene->mTextures[textureindex]->mWidth);
578
579 hr = CreateWICTextureFromMemory(dev, devcon, reinterpret_cast<unsigned char*>(scene->mTextures[textureindex]->pcData), *size, nullptr, &texture);
580 if (FAILED(hr))
581 MessageBox(hwnd, "Texture couldn't be created from memory!", "Error!", MB_ICONERROR | MB_OK);
582
583 return texture;
584}
585
586/////////////////////////////////////////////////
587//END ASSIMP MESH LOADER
588/////////////////////////////////////////////////
589
590std::vector<std::string> DebugConsole;
591void Console(std::string str)
592{
593 str.append("\r\n");
594 DebugConsole.push_back(str);
595}
596
597
598D3D11_INPUT_ELEMENT_DESC layout[] =
599{
600 { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
601 { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
602 { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 20, D3D11_INPUT_PER_VERTEX_DATA, 0 }
603};
604UINT numElements = ARRAYSIZE(layout);
605int nNumIndices = 0;
606int nNumVertex = 0;
607//ModelObject Model1;
608
609///////////////**************new(OBJ MESH)**************////////////////////
610void FlatSquare(
611 float left,
612 float right,
613 float top,
614 float bottom,
615 D2D1::ColorF color)
616{
617
618 ID2D1SolidColorBrush *Brush2;
619 D2DRenderTarget->CreateSolidColorBrush(color, &Brush2);
620 D2D1_COLOR_F Color = D2D1::ColorF(1.0f, 0.0f, 0.0f, 1.0f);
621 Brush2->SetColor(color);
622 D2D1_SIZE_F rtSize = D2DRenderTarget->GetSize();
623 D2D1_RECT_F rectangle2 = D2D1::RectF(
624 left,
625 top,
626 right,
627 bottom
628 );
629 D2DRenderTarget->FillRectangle(&rectangle2, Brush2);
630 D2DRenderTarget->DrawRectangle(&rectangle2, Brush2);
631
632}
633
634/*float DotProduct(const D3DXVECTOR3 & v1, const D3DXVECTOR3 & v2)
635{
636return (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z);
637}*/
638float DotProduct(const DirectX::SimpleMath::Vector3 & v1, const DirectX::SimpleMath::Vector3 & v2)
639{
640 return (XMVectorGetX(v1)*XMVectorGetX(v2) + XMVectorGetY(v2)*XMVectorGetY(v2) + XMVectorGetZ(v1)*XMVectorGetZ(v2));
641}
642void DetectCollison()
643{
644 DirectX::SimpleMath::Vector3 vectorSub = camTarget - camPosition;
645 DirectX::SimpleMath::Vector3 length = XMVector3Length(vectorSub);
646
647
648 XMStoreFloat(&distance, length);
649 vLen = camTarget - camPosition;
650
651 DirectX::SimpleMath::Vector3 vStart = { XMVectorGetX(camPosition), XMVectorGetZ(camPosition), XMVectorGetY(camPosition) };
652 //XMVectorGet
653 DirectX::SimpleMath::Vector3 vEnd = { XMVectorGetX(newCamPosition), XMVectorGetZ(newCamPosition), XMVectorGetY(newCamPosition) };
654 DirectX::SimpleMath::Vector3 vHit;
655 DirectX::SimpleMath::Vector3 vHitWallNormal;
656 std::ostringstream printstring;
657 bool bHitWall = (bsp.TraceSphere(vStart, vEnd, 90.0f, &vHit, &vHitWallNormal));//if TRUE then collision has been detected
658 if (bHitWall)
659 {
660 g_bCollision = true;
661 /*DirectX::SimpleMath::Vector3 vDir = (vEnd - vStart);
662
663 DirectX::SimpleMath::Vector3 vHitDir;
664 // Increase or wall normal slightly so our final result which slides
665 // along the wall isn't on the wall but a slight nudge away from it.
666 vHitWallNormal *= 1.5f;
667
668 vHitDir = vDir - (vHitWallNormal * DotProduct(vHitWallNormal, vDir));
669 //D3DXVec3Normalize(&vHitDir, &vHitDir);
670
671 vHitDir = vHitDir.Normalize;
672 DirectX::SimpleMath::Vector3 temp = vEnd - vHit;
673 //XMVECTOR vLength =
674 // XMVector3Length(temp);
675 //float fLen = D3DXVec3Length(&(vEnd - vHit));
676 float fLen = temp.Distance;
677 DirectX::SimpleMath::Vector3 vNewPos = vHit + vHitDir * fLen;
678
679 // If our new position which slides along the wall has a collision, then
680 // we'll just use the original wall position
681 DirectX::SimpleMath::Vector3 a, b; // Not used
682 if (bsp.TraceSphere(
683 vStart,
684 vNewPos,
685 90.0f,
686 &a, &b))
687 {
688 vNewPos = vHit;
689 newCamPosition = XMVectorSet(vHit.x, vHit.z, vHit.y, 0.0f); //Z and Y are inverted
690 Console("TRIED TO SLIDE!!!!!!");
691 return;
692 }*/
693 newCamPosition = XMVectorSet(vHit.x, vHit.z, vHit.y, 0.0f); //Z and Y are inverted
694 printstring << "Collision at : " << vHit.x << "," << vHit.y << "," << vHit.z;
695 //g_bCollision = true; //Let's not constrict the player for now
696 std::string coll = printstring.str();
697 Console(coll);
698 return;
699 }
700 else
701 {
702 g_bCollision = false;
703 newCamPosition = XMVectorSet(vEnd.x, vEnd.z, vHit.y, 0.0f); //Z and Y are inverted
704 }
705
706}
707int WINAPI WinMain(HINSTANCE hInstance, //Main windows function
708 HINSTANCE hPrevInstance,
709 LPSTR lpCmdLine,
710 int nShowCmd)
711{
712 Console("Initializing Win32 Window...");
713 if (!InitializeWindow(hInstance, nShowCmd, Width, Height, true))
714 {
715 MessageBox(0, "Window Initialization - Failed",
716 "Error", MB_OK);
717 return 0;
718 }
719 Console("Window Initialized.");
720 if (!InitializeDirect3d11App(hInstance)) //Initialize Direct3D
721 {
722 MessageBox(0, "Direct3D Initialization - Failed",
723 "Error", MB_OK);
724 return 0;
725 }
726 Console("Direct3D11 Initialized Successfully.");
727 if (!InitScene()) //Initialize our scene
728 {
729 MessageBox(0, "Scene Initialization - Failed",
730 "Error", MB_OK);
731 return 0;
732 }
733
734 if (!InitDirectInput(hInstance))
735 {
736 MessageBox(0, "Direct Input Initialization - Failed",
737 "Error", MB_OK);
738 return 0;
739 }
740 Console("DirectInput Initialized.");
741 Console("Entering MessageLoop..");
742 messageloop();
743
744 CleanUp();
745
746 return 0;
747}
748
749bool InitializeWindow(HINSTANCE hInstance,
750 int ShowWnd,
751 int width, int height,
752 bool windowed)
753{
754 typedef struct _WNDCLASS {
755 UINT cbSize;
756 UINT style;
757 WNDPROC lpfnWndProc;
758 int cbClsExtra;
759 int cbWndExtra;
760 HANDLE hInstance;
761 HICON hIcon;
762 HCURSOR hCursor;
763 HBRUSH hbrBackground;
764 LPCTSTR lpszMenuName;
765 LPCTSTR lpszClassName;
766 } WNDCLASS;
767
768 WNDCLASSEX wc;
769
770 wc.cbSize = sizeof(WNDCLASSEX);
771 wc.style = CS_HREDRAW | CS_VREDRAW;
772 wc.lpfnWndProc = WndProc;
773 wc.cbClsExtra = NULL;
774 wc.cbWndExtra = NULL;
775 wc.hInstance = hInstance;
776 wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
777 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
778 wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
779 wc.lpszMenuName = NULL;
780 wc.lpszClassName = WndClassName;
781 wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
782
783 if (!RegisterClassEx(&wc))
784 {
785 MessageBox(NULL, "Error registering class",
786 "Error", MB_OK | MB_ICONERROR);
787 return 1;
788 }
789
790 hwnd = CreateWindowEx(
791 NULL,
792 WndClassName,
793 "DEVELOPERS",
794 WS_OVERLAPPEDWINDOW,
795 CW_USEDEFAULT, CW_USEDEFAULT,
796 width, height,
797 NULL,
798 NULL,
799 hInstance,
800 NULL
801 );
802
803 if (!hwnd)
804 {
805 MessageBox(NULL, "Error creating window",
806 "Error", MB_OK | MB_ICONERROR);
807 return 1;
808 }
809
810 ShowWindow(hwnd, ShowWnd);
811 UpdateWindow(hwnd);
812
813 return true;
814}
815
816bool InitializeDirect3d11App(HINSTANCE hInstance)
817{
818 //Describe our SwapChain Buffer
819 DXGI_MODE_DESC bufferDesc;
820
821 ZeroMemory(&bufferDesc, sizeof(DXGI_MODE_DESC));
822
823 bufferDesc.Width = Width;
824 bufferDesc.Height = Height;
825 bufferDesc.RefreshRate.Numerator = 60;
826 bufferDesc.RefreshRate.Denominator = 1;
827 bufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
828 bufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
829 bufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
830
831 //Describe our SwapChain
832 DXGI_SWAP_CHAIN_DESC swapChainDesc;
833
834 ZeroMemory(&swapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC));
835
836 swapChainDesc.BufferDesc = bufferDesc;
837 swapChainDesc.SampleDesc.Count = 1;
838 swapChainDesc.SampleDesc.Quality = 0;
839 swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
840 swapChainDesc.BufferCount = 1;
841 swapChainDesc.OutputWindow = hwnd;
842 ///////////////**************new**************////////////////////
843 swapChainDesc.Windowed = true;
844 ///////////////**************new**************////////////////////
845 swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
846
847 // Create DXGI factory to enumerate adapters///////////////////////////////////////////////////////////////////////////
848 IDXGIFactory1 *DXGIFactory;
849
850 HRESULT hr = CreateDXGIFactory1(__uuidof(IDXGIFactory1), (void**)&DXGIFactory);
851
852 // Use the first adapter
853 IDXGIAdapter1 *Adapter;
854
855 hr = DXGIFactory->EnumAdapters1(0, &Adapter);
856
857 DXGIFactory->Release();
858
859 //Create our Direct3D 11 Device and SwapChain//////////////////////////////////////////////////////////////////////////
860 hr = D3D11CreateDeviceAndSwapChain(Adapter, D3D_DRIVER_TYPE_UNKNOWN, NULL, D3D11_CREATE_DEVICE_BGRA_SUPPORT,// | D3D11_CREATE_DEVICE_DEBUG,
861 NULL, NULL, D3D11_SDK_VERSION, &swapChainDesc, &SwapChain, &d3d11Device, NULL, &d3d11DevCon);
862
863 //Initialize Direct2D, Direct3D 10.1, DirectWrite
864 InitD2D_D3D101_DWrite(Adapter);
865
866 //Release the Adapter interface
867 Adapter->Release();
868
869 //Create our BackBuffer and Render Target
870 hr = SwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&BackBuffer11);
871 hr = d3d11Device->CreateRenderTargetView(BackBuffer11, NULL, &renderTargetView);
872 //Describe our Depth/Stencil Buffer
873 D3D11_TEXTURE2D_DESC depthStencilDesc;
874
875 depthStencilDesc.Width = Width;
876 depthStencilDesc.Height = Height;
877 depthStencilDesc.MipLevels = 1;
878 depthStencilDesc.ArraySize = 1;
879 depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
880 depthStencilDesc.SampleDesc.Count = 1;
881 depthStencilDesc.SampleDesc.Quality = 0;
882 depthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
883 depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
884 depthStencilDesc.CPUAccessFlags = 0;
885 depthStencilDesc.MiscFlags = 0;
886 SwapChain->SetFullscreenState(false, 0);
887 //Create the Depth/Stencil View
888 d3d11Device->CreateTexture2D(&depthStencilDesc, NULL, &depthStencilBuffer);
889 d3d11Device->CreateDepthStencilView(depthStencilBuffer, NULL, &depthStencilView);
890 spriteBatch = std::make_unique<DirectX::SpriteBatch>(d3d11DevCon);
891 spriteFont = std::make_unique<DirectX::SpriteFont>(d3d11Device, L"myfile.spritefont");
892
893 return true;
894}
895
896bool InitD2D_D3D101_DWrite(IDXGIAdapter1 *Adapter)
897{
898 //Create our Direc3D 10.1 Device///////////////////////////////////////////////////////////////////////////////////////
899 hr = D3D10CreateDevice1(Adapter, D3D10_DRIVER_TYPE_HARDWARE, NULL, D3D10_CREATE_DEVICE_BGRA_SUPPORT,
900 D3D10_FEATURE_LEVEL_9_3, D3D10_1_SDK_VERSION, &d3d101Device);
901
902 //Create Shared Texture that Direct3D 10.1 will render on//////////////////////////////////////////////////////////////
903 D3D11_TEXTURE2D_DESC sharedTexDesc;
904
905 ZeroMemory(&sharedTexDesc, sizeof(sharedTexDesc));
906
907 sharedTexDesc.Width = Width;
908 sharedTexDesc.Height = Height;
909 sharedTexDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
910 sharedTexDesc.MipLevels = 1;
911 sharedTexDesc.ArraySize = 1;
912 sharedTexDesc.SampleDesc.Count = 1;
913 sharedTexDesc.Usage = D3D11_USAGE_DEFAULT;
914 sharedTexDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
915 sharedTexDesc.MiscFlags = D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX;
916
917 hr = d3d11Device->CreateTexture2D(&sharedTexDesc, NULL, &sharedTex11);
918
919 // Get the keyed mutex for the shared texture (for D3D11)///////////////////////////////////////////////////////////////
920 hr = sharedTex11->QueryInterface(__uuidof(IDXGIKeyedMutex), (void**)&keyedMutex11);
921
922 // Get the shared handle needed to open the shared texture in D3D10.1///////////////////////////////////////////////////
923 IDXGIResource *sharedResource10;
924 HANDLE sharedHandle10;
925
926 hr = sharedTex11->QueryInterface(__uuidof(IDXGIResource), (void**)&sharedResource10);
927
928 hr = sharedResource10->GetSharedHandle(&sharedHandle10);
929
930 sharedResource10->Release();
931
932 // Open the surface for the shared texture in D3D10.1///////////////////////////////////////////////////////////////////
933 IDXGISurface1 *sharedSurface10;
934
935 hr = d3d101Device->OpenSharedResource(sharedHandle10, __uuidof(IDXGISurface1), (void**)(&sharedSurface10));
936
937 hr = sharedSurface10->QueryInterface(__uuidof(IDXGIKeyedMutex), (void**)&keyedMutex10);
938
939 // Create D2D factory///////////////////////////////////////////////////////////////////////////////////////////////////
940 ID2D1Factory *D2DFactory;
941 hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, __uuidof(ID2D1Factory), (void**)&D2DFactory);
942
943 D2D1_RENDER_TARGET_PROPERTIES renderTargetProperties;
944
945 ZeroMemory(&renderTargetProperties, sizeof(renderTargetProperties));
946
947 renderTargetProperties.type = D2D1_RENDER_TARGET_TYPE_HARDWARE;
948 renderTargetProperties.pixelFormat = D2D1::PixelFormat(DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED);
949
950 hr = D2DFactory->CreateDxgiSurfaceRenderTarget(sharedSurface10, &renderTargetProperties, &D2DRenderTarget);
951
952 sharedSurface10->Release();
953 D2DFactory->Release();
954
955 // Create a solid color brush to draw something with
956 hr = D2DRenderTarget->CreateSolidColorBrush(D2D1::ColorF(1.0f, 1.0f, 1.0f, 1.0f), &Brush);
957
958 //DirectWrite///////////////////////////////////////////////////////////////////////////////////////////////////////////
959 hr = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory),
960 reinterpret_cast<IUnknown**>(&DWriteFactory));
961
962 hr = DWriteFactory->CreateTextFormat(
963 Unicode("Lucida Console").c_str(),
964 NULL,
965 DWRITE_FONT_WEIGHT_REGULAR,
966 DWRITE_FONT_STYLE_NORMAL,
967 DWRITE_FONT_STRETCH_NORMAL,
968 12.0f,
969 Unicode("en-us").c_str(),
970 &TextFormat
971 );
972
973 hr = TextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
974 hr = TextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
975
976 d3d101Device->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_POINTLIST);
977 return true;
978}
979
980bool InitDirectInput(HINSTANCE hInstance)
981{
982 hr = DirectInput8Create(hInstance,
983 DIRECTINPUT_VERSION,
984 IID_IDirectInput8,
985 (void**)&DirectInput,
986 NULL);
987
988 hr = DirectInput->CreateDevice(GUID_SysKeyboard,
989 &DIKeyboard,
990 NULL);
991
992 hr = DirectInput->CreateDevice(GUID_SysMouse,
993 &DIMouse,
994 NULL);
995
996 hr = DIKeyboard->SetDataFormat(&c_dfDIKeyboard);
997 hr = DIKeyboard->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
998
999 hr = DIMouse->SetDataFormat(&c_dfDIMouse);
1000 hr = DIMouse->SetCooperativeLevel(hwnd, DISCL_EXCLUSIVE | DISCL_NOWINKEY | DISCL_FOREGROUND);
1001
1002 return true;
1003}
1004
1005void UpdateCamera()
1006{
1007 camRotationMatrix = XMMatrixRotationRollPitchYaw(camPitch, camYaw, 0);
1008 camTarget = XMVector3TransformCoord(DefaultForward, camRotationMatrix);
1009 camTarget = XMVector3Normalize(camTarget);
1010
1011 XMMATRIX RotateYTempMatrix;
1012 RotateYTempMatrix = XMMatrixRotationY(camYaw);
1013
1014 camRight = XMVector3TransformCoord(DefaultRight, RotateYTempMatrix);
1015 camUp = XMVector3TransformCoord(camUp, RotateYTempMatrix);
1016 camForward = XMVector3TransformCoord(DefaultForward, RotateYTempMatrix);
1017 oldCamPosition = camPosition;
1018 newCamPosition += moveLeftRight*camRight;
1019 newCamPosition += moveBackForward*camForward;
1020 DetectCollison();
1021 if (!g_bCollision)
1022 {
1023 camPosition = newCamPosition;
1024 }
1025 else
1026 camPosition = oldCamPosition;
1027
1028 camDir = camPosition - camTarget;
1029 // camDir = XMVector3Length(camDir, )
1030
1031 moveLeftRight = 0.0f;
1032 moveBackForward = 0.0f;
1033
1034 camTarget = camPosition + camTarget;
1035 meshView = XMMatrixLookAtLH(g_vMeshAt, g_vMeshPosition, g_vMeshUp);
1036 camView = XMMatrixLookAtLH(camPosition, camTarget, camUp);
1037}
1038
1039void DetectInput(double time)
1040{
1041 DIMOUSESTATE mouseCurrState;
1042
1043 BYTE keyboardState[256];
1044
1045 DIKeyboard->Acquire();
1046 DIMouse->Acquire();
1047
1048 DIMouse->GetDeviceState(sizeof(DIMOUSESTATE), &mouseCurrState);
1049
1050 DIKeyboard->GetDeviceState(sizeof(keyboardState), (LPVOID)&keyboardState);
1051
1052 if (keyboardState[DIK_ESCAPE] & 0x80)
1053 PostMessage(hwnd, WM_DESTROY, 0, 0);
1054
1055 float speed = 150.0f * (float)time;
1056
1057 if (keyboardState[DIK_A] & 0x80)
1058 {
1059 //if (!g_bCollision)
1060 moveLeftRight -= speed;
1061 }
1062 if (keyboardState[DIK_D] & 0x80)
1063 {
1064 //if (!g_bCollision)
1065 moveLeftRight += speed;
1066 }
1067 if (keyboardState[DIK_W] & 0x80)
1068 {
1069 //if (!g_bCollision)
1070 moveBackForward += speed;
1071 //else
1072 // moveBackForward -= speed;
1073 }
1074 if (keyboardState[DIK_S] & 0x80)
1075 {
1076 //if (!g_bCollision)
1077 moveBackForward -= speed;
1078 //else
1079 // moveBackForward += speed;
1080
1081 }
1082 if (keyboardState[DIK_DOWN] & 0x80)
1083 {
1084 objRotY -= 0.01f;
1085 }
1086 if (keyboardState[DIK_UP] & 0x80)
1087 {
1088 objRotY += 0.01f;
1089 }
1090 if (keyboardState[DIK_RIGHT] & 0x80)
1091 {
1092 objRotZ += 0.01f;
1093 }
1094 if (keyboardState[DIK_LEFT] & 0x80)
1095 {
1096 objRotZ -= 0.01f;
1097 }
1098 if (keyboardState[DIK_INSERT] & 0x80)
1099 {
1100 objRotX += 0.01f;
1101 }
1102 if (keyboardState[DIK_DELETE] & 0x80)
1103 {
1104 objRotX -= 0.01f;
1105 }
1106 if (keyboardState[DIK_NUMPAD8] & 0x80)
1107 objTransX += 1.00f;
1108 if (keyboardState[DIK_NUMPAD2] & 0x80)
1109 objTransX -= 1.00f;
1110 if (keyboardState[DIK_NUMPAD6] & 0x80)
1111 objTransY += 1.00f;
1112 if (keyboardState[DIK_NUMPAD4] & 0x80)
1113 objTransY -= 1.00f;
1114 if (keyboardState[DIK_NUMPAD3] & 0x80)
1115 objTransZ += 1.00f;
1116 if (keyboardState[DIK_NUMPAD1] & 0x80)
1117 objTransZ -= 1.00f;
1118 if (keyboardState[DIK_GRAVE] & 0x80)
1119 {
1120 g_bShowConsole = !g_bShowConsole;
1121 Sleep(100);
1122 }
1123
1124 if ((mouseCurrState.lX != mouseLastState.lX) || (mouseCurrState.lY != mouseLastState.lY))
1125 {
1126 camYaw += mouseLastState.lX * 0.0025f;
1127
1128 camPitch += mouseCurrState.lY * 0.0025f;
1129
1130 mouseLastState = mouseCurrState;
1131 }
1132
1133 UpdateCamera();
1134
1135 return;
1136}
1137
1138
1139void CleanUp()
1140{
1141 SwapChain->SetFullscreenState(false, NULL);
1142 PostMessage(hwnd, WM_DESTROY, 0, 0);
1143
1144 //Release the COM Objects we created
1145 SwapChain->Release();
1146 d3d11Device->Release();
1147 d3d11DevCon->Release();
1148 renderTargetView->Release();
1149 groundVertexBuffer->Release();
1150 groundIndexBuffer->Release();
1151 VS->Release();
1152 PS->Release();
1153 VS_Buffer->Release();
1154 PS_Buffer->Release();
1155 vertLayout->Release();
1156 depthStencilView->Release();
1157 depthStencilBuffer->Release();
1158 cbPerObjectBuffer->Release();
1159 Transparency->Release();
1160 CCWcullMode->Release();
1161 CWcullMode->Release();
1162
1163 d3d101Device->Release();
1164 keyedMutex11->Release();
1165 keyedMutex10->Release();
1166 D2DRenderTarget->Release();
1167 Brush->Release();
1168 BackBuffer11->Release();
1169 sharedTex11->Release();
1170 DWriteFactory->Release();
1171 TextFormat->Release();
1172 d2dTexture->Release();
1173
1174 ///////////////**************new(SKYBOX)**************////////////////////
1175 // sphereIndexBuffer->Release();
1176 // sphereVertBuffer->Release();
1177
1178 SKYMAP_VS->Release();
1179 SKYMAP_PS->Release();
1180 SKYMAP_VS_Buffer->Release();
1181 SKYMAP_PS_Buffer->Release();
1182
1183 // smrv->Release();
1184
1185 DSLessEqual->Release();
1186 //RSCullNone->Release();
1187 ///////////////**************new(SKYBOX)**************////////////////////
1188 cbPerFrameBuffer->Release();
1189
1190 DIKeyboard->Unacquire();
1191 DIMouse->Unacquire();
1192 DirectInput->Release();
1193}
1194
1195void InitD2DScreenTexture()
1196{
1197 //Create the vertex buffer
1198 Vertex v[] =
1199 {
1200 // Front Face
1201 Vertex(-1.0f, -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, -1.0f, -1.0f),
1202 Vertex(-1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, -1.0f),
1203 Vertex(1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f),
1204 Vertex(1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f),
1205 };
1206
1207 DWORD indices[] = {
1208 // Front Face
1209 0, 1, 2,
1210 0, 2, 3,
1211 };
1212
1213 D3D11_BUFFER_DESC indexBufferDesc;
1214 ZeroMemory(&indexBufferDesc, sizeof(indexBufferDesc));
1215
1216 indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
1217 indexBufferDesc.ByteWidth = sizeof(DWORD)* ARRAYSIZE(indices);
1218 indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
1219 indexBufferDesc.CPUAccessFlags = 0;
1220 indexBufferDesc.MiscFlags = 0;
1221
1222 D3D11_SUBRESOURCE_DATA iinitData;
1223
1224 iinitData.pSysMem = indices;
1225 d3d11Device->CreateBuffer(&indexBufferDesc, &iinitData, &d2dIndexBuffer);
1226
1227
1228 D3D11_BUFFER_DESC vertexBufferDesc;
1229 ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc));
1230
1231 vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
1232 vertexBufferDesc.ByteWidth = sizeof(Vertex)* ARRAYSIZE(v);
1233 vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
1234 vertexBufferDesc.CPUAccessFlags = 0;
1235 vertexBufferDesc.MiscFlags = 0;
1236
1237 D3D11_SUBRESOURCE_DATA vertexBufferData;
1238
1239 ZeroMemory(&vertexBufferData, sizeof(vertexBufferData));
1240 vertexBufferData.pSysMem = v;
1241 hr = d3d11Device->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &d2dVertBuffer);
1242
1243 //Create A shader resource view from the texture D2D will render to,
1244 //So we can use it to texture a square which overlays our scene
1245 d3d11Device->CreateShaderResourceView(sharedTex11, NULL, &d2dTexture);
1246}
1247bool InitScene()
1248{
1249#ifdef __PPSH
1250 ModelOne.Load(NULL, d3d11Device, d3d11DevCon, "meshes\\ppsh41.obj");
1251#endif
1252#ifdef __PISTOL
1253 ModelOne.Load(NULL, d3d11Device, d3d11DevCon, "meshes\\M1911.obj");
1254#endif
1255// Model1.LoadModel("C:\\DX11Engine\\DX11Engine\\ppsh41.obj");
1256 Console("Generating BSP map...");
1257 bsp.Create(d3d11Device, d3d11DevCon, "dxtest.bsp");
1258 InitD2DScreenTexture();
1259 Console("Creating Sky Sphere...");
1260 CreateSphere(10, 10);
1261 Console("Loading OBJ Meshes...");
1262
1263 // std::shared_ptr<IEffect> effect;
1264 // effect = Apply(d3d11DevCon);
1265 //m_world = Matrix::Identity;
1266 //m_view = Matrix::CreateLookAt(Vector3(2.f, 2.f, 2.f),
1267 // Vector3::Zero, Vector3::UnitY);
1268 // m_proj = Matrix::CreatePerspectiveFieldOfView(XM_PI / 4.f,
1269 //float(Width) / float(Height), 0.1f, 10000.f);
1270 ///////////////**************new**************//////////////////// //OLD OBJ LOADER (DEPRECATED)
1271 //if (!LoadObjModel(d3d11Device, d3d11DevCon, SwapChain, Unicode("M1911.obj").c_str(), &meshVertBuff, &meshIndexBuff, meshSubsetIndexStart, meshSubsetTexture, material, meshSubsets, true, false))
1272 // return false;
1273 ///////////////**************new**************////////////////////
1274 Console("Compiling HLSL Shaders...");
1275 //Compile Shaders from shader file
1276
1277 //hr = D3DCompileFromFile("Effects.fx", 0, 0, "VS", "vs_4_0", 0, 0, 0, &VS_Buffer, 0, 0);
1278
1279 hr = D3DCompileFromFile(L"Effects.fx", NULL, NULL, "VS", "vs_4_0", NULL, 0, &VS_Buffer, NULL);
1280 if (hr != S_OK)
1281 MessageBoxA(NULL, "Error Compiling Shader", "Error", MB_OK);
1282 hr = D3DCompileFromFile(L"Effects.fx", NULL, NULL, "PS", "ps_4_0", NULL, 0, &PS_Buffer, NULL);
1283 hr = D3DCompileFromFile(L"Effects.fx", NULL, NULL, "D2D_PS", "ps_4_0", NULL, 0, &D2D_PS_Buffer, NULL);
1284 hr = D3DCompileFromFile(L"Effects.fx", NULL, NULL, "SKYMAP_VS", "vs_4_0", NULL, 0, &SKYMAP_VS_Buffer, NULL);
1285 hr = D3DCompileFromFile(L"Effects.fx", NULL, NULL, "SKYMAP_PS", "ps_4_0", NULL, 0, &SKYMAP_PS_Buffer, NULL);
1286 // hr = D3DX11CompileFromFile("Effects.fx", 0, 0, "PS", "ps_4_0", 0, 0, 0, &PS_Buffer, 0, 0);
1287 //hr = D3DX11CompileFromFile("Effects.fx", 0, 0, "D2D_PS", "ps_4_0", 0, 0, 0, &D2D_PS_Buffer, 0, 0);
1288 ///////////////**************new**************////////////////////
1289 //hr = D3DX11CompileFromFile("Effects.fx", 0, 0, "SKYMAP_VS", "vs_4_0", 0, 0, 0, &SKYMAP_VS_Buffer, 0, 0);
1290 //hr = D3DX11CompileFromFile("Effects.fx", 0, 0, "SKYMAP_PS", "ps_4_0", 0, 0, 0, &SKYMAP_PS_Buffer, 0, 0);
1291 ///////////////**************new**************////////////////////
1292
1293 //Create the Shader Objects
1294 hr = d3d11Device->CreateVertexShader(VS_Buffer->GetBufferPointer(), VS_Buffer->GetBufferSize(), NULL, &VS);
1295 hr = d3d11Device->CreatePixelShader(PS_Buffer->GetBufferPointer(), PS_Buffer->GetBufferSize(), NULL, &PS);
1296 hr = d3d11Device->CreatePixelShader(D2D_PS_Buffer->GetBufferPointer(), D2D_PS_Buffer->GetBufferSize(), NULL, &D2D_PS);
1297 hr = d3d11Device->CreateVertexShader(SKYMAP_VS_Buffer->GetBufferPointer(), SKYMAP_VS_Buffer->GetBufferSize(), NULL, &SKYMAP_VS);
1298 hr = d3d11Device->CreatePixelShader(SKYMAP_PS_Buffer->GetBufferPointer(), SKYMAP_PS_Buffer->GetBufferSize(), NULL, &SKYMAP_PS);
1299
1300 //Set Vertex and Pixel Shaders
1301 d3d11DevCon->VSSetShader(VS, 0, 0);
1302 d3d11DevCon->PSSetShader(PS, 0, 0);
1303
1304 light[0].pos = XMFLOAT3(0.0f, 1.0f, 0.0f);
1305 light[0].dir = XMFLOAT3(0.0f, 0.0f, 1.0f);
1306 light[0].range = 100.0f;
1307 light[0].cone = 20.0f;
1308 light[0].att = XMFLOAT3(0.4f, 0.002f, 0.000f);
1309 light[0].ambient = XMFLOAT4(0.2f, 0.2f, 0.2f, 1.0f);
1310 light[0].diffuse = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
1311
1312 light[1].pos = XMFLOAT3(0.0f, 1.0f, 0.0f);
1313 light[1].dir = XMFLOAT3(1.0f, 0.0f, 0.0f);
1314 light[1].range = 0.0f;
1315 light[1].cone = 20.0f;
1316 light[1].att = XMFLOAT3(0.4f, 0.002f, 0.000f);
1317 light[1].ambient = XMFLOAT4(0.2f, 0.2f, 0.2f, 1.0f);
1318 light[1].diffuse = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f);
1319
1320
1321 //Create the vertex buffer
1322 Vertex v[] =
1323 {
1324 // Bottom Face
1325 Vertex(-1.0f, -1.0f, -1.0f, 100.0f, 100.0f, 0.0f, 1.0f, 0.0f),
1326 Vertex(1.0f, -1.0f, -1.0f, 0.0f, 100.0f, 0.0f, 1.0f, 0.0f),
1327 Vertex(1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f),
1328 Vertex(-1.0f, -1.0f, 1.0f, 100.0f, 0.0f, 0.0f, 1.0f, 0.0f),
1329 };
1330
1331 DWORD indices[] = {
1332 0, 1, 2,
1333 0, 2, 3,
1334 };
1335
1336 D3D11_BUFFER_DESC indexBufferDesc;
1337 ZeroMemory(&indexBufferDesc, sizeof(indexBufferDesc));
1338
1339 indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
1340 indexBufferDesc.ByteWidth = sizeof(DWORD)* ARRAYSIZE(indices);
1341 indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
1342 indexBufferDesc.CPUAccessFlags = 0;
1343 indexBufferDesc.MiscFlags = 0;
1344
1345 D3D11_SUBRESOURCE_DATA iinitData;
1346
1347 iinitData.pSysMem = indices;
1348 d3d11Device->CreateBuffer(&indexBufferDesc, &iinitData, &groundIndexBuffer);
1349
1350 D3D11_BUFFER_DESC vertexBufferDesc;
1351 ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc));
1352
1353 vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
1354 vertexBufferDesc.ByteWidth = sizeof(Vertex)* ARRAYSIZE(v);
1355 vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
1356 vertexBufferDesc.CPUAccessFlags = 0;
1357 vertexBufferDesc.MiscFlags = 0;
1358
1359 D3D11_SUBRESOURCE_DATA vertexBufferData;
1360
1361 ZeroMemory(&vertexBufferData, sizeof(vertexBufferData));
1362 vertexBufferData.pSysMem = v;
1363 hr = d3d11Device->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &groundVertexBuffer);
1364
1365 //Create the Input Layout
1366 hr = d3d11Device->CreateInputLayout(layout, numElements, VS_Buffer->GetBufferPointer(),
1367 VS_Buffer->GetBufferSize(), &vertLayout);
1368
1369 //Set the Input Layout
1370 d3d11DevCon->IASetInputLayout(vertLayout);
1371
1372 //Set Primitive Topology
1373 d3d11DevCon->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
1374
1375 //Create the Viewport
1376 D3D11_VIEWPORT viewport;
1377 ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));
1378
1379 viewport.TopLeftX = 0;
1380 viewport.TopLeftY = 0;
1381 viewport.Width = (float)Width;
1382 viewport.Height = (float)Height;
1383 viewport.MinDepth = 0.0f;
1384 viewport.MaxDepth = 1.0f;
1385
1386 //Set the Viewport
1387 d3d11DevCon->RSSetViewports(1, &viewport);
1388
1389 //Create the buffer to send to the cbuffer in effect file
1390 D3D11_BUFFER_DESC cbbd;
1391 ZeroMemory(&cbbd, sizeof(D3D11_BUFFER_DESC));
1392
1393 cbbd.Usage = D3D11_USAGE_DEFAULT;
1394 cbbd.ByteWidth = sizeof(cbPerObject);
1395 cbbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
1396 cbbd.CPUAccessFlags = 0;
1397 cbbd.MiscFlags = 0;
1398
1399 hr = d3d11Device->CreateBuffer(&cbbd, NULL, &cbPerObjectBuffer);
1400
1401 //Create the buffer to send to the cbuffer per frame in effect file
1402 ZeroMemory(&cbbd, sizeof(D3D11_BUFFER_DESC));
1403
1404 cbbd.Usage = D3D11_USAGE_DEFAULT;
1405 cbbd.ByteWidth = sizeof(cbPerFrame);
1406 cbbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
1407 cbbd.CPUAccessFlags = 0;
1408 cbbd.MiscFlags = 0;
1409
1410 hr = d3d11Device->CreateBuffer(&cbbd, NULL, &cbPerFrameBuffer);
1411
1412 //Camera information
1413 camPosition = XMVectorSet(0.0f, 15.0f, -8.0f, 0.0f);
1414 camTarget = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
1415 camUp = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
1416
1417 //Set the View matrix
1418 camView = XMMatrixLookAtLH(camPosition, camTarget, camUp);
1419 //camView = Matrix::CreateLookAt(camPosition, camTarget, camUp);
1420 //Set the Projection matrix
1421 //camProjection = Matrix::CreatePerspectiveFieldOfView(0.4*XM_PI, (float)(Width / Height), 1.0f, 3000.0f);
1422 camProjection = XMMatrixPerspectiveFovLH(0.4f*XM_PI, (float)(Width / Height), 1.0f, 10000.0f);
1423 meshProjection = XMMatrixPerspectiveFovLH(0.4f*XM_PI, (float)(Width / Height), 2.0f, 1000.0f);
1424 D3D11_BLEND_DESC blendDesc;
1425 ZeroMemory(&blendDesc, sizeof(blendDesc));
1426
1427 D3D11_RENDER_TARGET_BLEND_DESC rtbd;
1428 ZeroMemory(&rtbd, sizeof(rtbd));
1429
1430 rtbd.BlendEnable = true;
1431 rtbd.SrcBlend = D3D11_BLEND_SRC_COLOR;
1432 rtbd.DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
1433 rtbd.BlendOp = D3D11_BLEND_OP_ADD;
1434 rtbd.SrcBlendAlpha = D3D11_BLEND_ONE;
1435 rtbd.DestBlendAlpha = D3D11_BLEND_ZERO;
1436 rtbd.BlendOpAlpha = D3D11_BLEND_OP_ADD;
1437 rtbd.RenderTargetWriteMask = D3D10_COLOR_WRITE_ENABLE_ALL;
1438
1439 blendDesc.AlphaToCoverageEnable = false;
1440 blendDesc.RenderTarget[0] = rtbd;
1441
1442 d3d11Device->CreateBlendState(&blendDesc, &d2dTransparency);
1443
1444 ///////////////**************new**************////////////////////
1445 ZeroMemory(&rtbd, sizeof(rtbd));
1446
1447 rtbd.BlendEnable = true;
1448 rtbd.SrcBlend = D3D11_BLEND_INV_SRC_ALPHA;
1449 rtbd.DestBlend = D3D11_BLEND_SRC_ALPHA;
1450 rtbd.BlendOp = D3D11_BLEND_OP_ADD;
1451 rtbd.SrcBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
1452 rtbd.DestBlendAlpha = D3D11_BLEND_SRC_ALPHA;
1453 rtbd.BlendOpAlpha = D3D11_BLEND_OP_ADD;
1454 rtbd.RenderTargetWriteMask = D3D10_COLOR_WRITE_ENABLE_ALL;
1455
1456 blendDesc.AlphaToCoverageEnable = false;
1457 blendDesc.RenderTarget[0] = rtbd;
1458
1459 d3d11Device->CreateBlendState(&blendDesc, &Transparency);
1460 ///////////////**************new**************////////////////////
1461
1462 HRESULT hr = CreateWICTextureFromFile(d3d11Device, d3d11DevCon,
1463 L"grass.jpg", nullptr, &CubesTexture);
1464 //DX::ThrowIfFailed(hr);
1465 //hr = D3DX11CreateShaderResourceViewFromFile(d3d11Device, "grass.jpg",
1466 // NULL, NULL, &CubesTexture, NULL);
1467
1468 ///////////////**************new(SKYBOX)**************////////////////////
1469 //Tell D3D we will be loading a cube texture
1470 //D3DX11_IMAGE_LOAD_INFO loadSMInfo;
1471 //loadSMInfo.MiscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE;
1472
1473 //Load the texture
1474 ID3D11Texture2D* SMTexture = 0;
1475 // hr = D3DX11CreateTextureFromFile(d3d11Device, "skymap.dds",
1476 // &loadSMInfo, 0, (ID3D11Resource**)&SMTexture, 0);
1477
1478
1479
1480// hr = CreateDDSTextureFromFile(d3d11Device, L"skymap.dds", 0,
1481// nullptr, (ID3D11Resource**)&SMTexture);
1482 //CreateDDSTextureFromFile(d3d11Device, L"skymap.dds", (ID3D11Resource**)SkyMapTexture, 0);
1483
1484
1485
1486
1487
1488
1489
1490 //Tell D3D We have a cube texture, which is an array of 2D textures
1491 D3D11_SHADER_RESOURCE_VIEW_DESC SMViewDesc;
1492 //.SMViewDesc.Format = SMTextureDesc.Format;
1493 SMViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
1494 SMViewDesc.TextureCube.MipLevels = 1;
1495 SMViewDesc.TextureCube.MostDetailedMip = 0;
1496
1497 ID3D11Texture2D* texture = nullptr;
1498
1499 //hr = d3d11Device->CreateTexture2D(&SMTextureDesc, NULL, &SMTexture);
1500 //CreateDDSTextureFromFileEx(d3d11Device, L"skymap.dds", 10000, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, D3D11_RESOURCE_MISC_TEXTURECUBE, false, &SMTexture, &SkyMapTexture);
1501 CreateDDSTextureFromFileEx(d3d11Device, L"skymap.dds", 0, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE,
1502 0, D3D11_RESOURCE_MISC_TEXTURECUBE, false,(ID3D11Resource**)&texture,(ID3D11ShaderResourceView**)&SkyMapTexture);
1503 //Create the Resource view
1504 D3D11_TEXTURE2D_DESC texDesc;
1505 texture->GetDesc(&texDesc);
1506
1507 D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
1508
1509 srvDesc.TextureCube.MipLevels = texDesc.MipLevels;
1510 srvDesc.TextureCube.MostDetailedMip = 0;
1511 srvDesc.Format = texDesc.Format;
1512 srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
1513
1514 hr = d3d11Device->CreateShaderResourceView(texture, &srvDesc, &SkyMapTexture);
1515 ///////////////**************new(SKYBOX)**************////////////////////
1516// D3D11_TEXTURE2D_DESC texDesc;
1517// texture->GetDesc(&texDesc);
1518
1519 // Describe the Sample State
1520 D3D11_SAMPLER_DESC sampDesc;
1521 ZeroMemory(&sampDesc, sizeof(sampDesc));
1522 sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
1523 sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
1524 sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
1525 sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
1526 sampDesc.ComparisonFunc = D3D11_COMPARISON_EQUAL;
1527 sampDesc.MinLOD = 0;
1528 sampDesc.MaxLOD = D3D11_FLOAT32_MAX;
1529
1530 //Create the Sample State
1531 hr = d3d11Device->CreateSamplerState(&sampDesc, &CubesTexSamplerState);
1532
1533 D3D11_RASTERIZER_DESC cmdesc;
1534
1535 ZeroMemory(&cmdesc, sizeof(D3D11_RASTERIZER_DESC));
1536 cmdesc.FillMode = D3D11_FILL_SOLID;
1537 cmdesc.CullMode = D3D11_CULL_BACK;
1538 cmdesc.DepthBias = 0;
1539 cmdesc.DepthBiasClamp = true;
1540 cmdesc.FrontCounterClockwise = true;
1541
1542
1543 hr = d3d11Device->CreateRasterizerState(&cmdesc, &CCWcullMode);
1544
1545 cmdesc.FrontCounterClockwise = false;
1546
1547 hr = d3d11Device->CreateRasterizerState(&cmdesc, &CWcullMode);
1548
1549 cmdesc.CullMode = D3D11_CULL_NONE;
1550 //cmdesc.FillMode = D3D11_FILL_WIREFRAME;
1551 hr = d3d11Device->CreateRasterizerState(&cmdesc, &RSCullNone);
1552
1553 D3D11_DEPTH_STENCIL_DESC dssDesc;
1554 ZeroMemory(&dssDesc, sizeof(D3D11_DEPTH_STENCIL_DESC));
1555 dssDesc.DepthEnable = false;
1556 dssDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
1557 dssDesc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL;
1558 // Depth test parameters
1559 dssDesc.DepthEnable = false;
1560 dssDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
1561 dssDesc.DepthFunc = D3D11_COMPARISON_LESS;
1562
1563 // Stencil test parameters
1564 dssDesc.StencilEnable = true;
1565 dssDesc.StencilReadMask = 0xFF;
1566 dssDesc.StencilWriteMask = 0xFF;
1567
1568 // Stencil operations if pixel is front-facing
1569 dssDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
1570 dssDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
1571 dssDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
1572 dssDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
1573
1574 // Stencil operations if pixel is back-facing
1575 dssDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
1576 dssDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
1577 dssDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
1578 dssDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
1579 d3d11Device->CreateDepthStencilState(&dssDesc, &DSLessEqual);
1580 //m_states = std::make_unique<CommonStates>(d3d11Device);
1581
1582 //m_fxFactory = std::make_unique<EffectFactory>(d3d11Device);
1583
1584 //m_model = Model::CreateFromCMO(d3d11Device, L"cup.cmo", *m_fxFactory);
1585 return true;
1586}
1587
1588
1589void StartTimer()
1590{
1591 LARGE_INTEGER frequencyCount;
1592 QueryPerformanceFrequency(&frequencyCount);
1593
1594 countsPerSecond = double(frequencyCount.QuadPart);
1595
1596 QueryPerformanceCounter(&frequencyCount);
1597 CounterStart = frequencyCount.QuadPart;
1598}
1599
1600double GetTime()
1601{
1602 LARGE_INTEGER currentTime;
1603 QueryPerformanceCounter(¤tTime);
1604 return double(currentTime.QuadPart - CounterStart) / countsPerSecond;
1605}
1606
1607double GetFrameTime()
1608{
1609 LARGE_INTEGER currentTime;
1610 __int64 tickCount;
1611 QueryPerformanceCounter(¤tTime);
1612
1613 tickCount = currentTime.QuadPart - frameTimeOld;
1614 frameTimeOld = currentTime.QuadPart;
1615
1616 if (tickCount < 0.0f)
1617 tickCount = (__int64)0.0f;
1618
1619 return float(tickCount) / countsPerSecond;
1620}
1621
1622void UpdateScene(double time)
1623{
1624 cupWorld = XMMatrixIdentity();
1625 Translation = XMMatrixTranslation(0.0f, 0.0f, 0.0f);
1626 Scale = XMMatrixScaling(10.0f, 10.0f, 10.0f);
1627 cupWorld = Translation * Scale;
1628 //////////////////////////////////////////
1629 //Reset cube1World
1630 groundWorld = XMMatrixIdentity();
1631
1632 //Define cube1's world space matrix
1633 Scale = XMMatrixScaling(5000.0f, 10.0f, 5000.0f);
1634 Translation = XMMatrixTranslation(0.0f, -80.0f, 0.0f);
1635
1636 //Set cube1's world space using the transformations
1637 groundWorld = Scale * Translation;
1638
1639 mapWorld = XMMatrixIdentity();
1640 Scale = XMMatrixScaling(1.0f, 1.0f, 1.0f);
1641 Translation = XMMatrixTranslation(0.0f, 25.0f, 0.0f);
1642 mapWorld = Scale * Translation;
1643
1644 ///////////////**************new(OBJ MESH)**************////////////////////
1645 meshWorld = XMMatrixIdentity();
1646
1647 //Define cube1's world space matrix
1648 Rotation = XMMatrixRotationX(objRotX) * XMMatrixRotationY(objRotY) * XMMatrixRotationZ(objRotZ);
1649 Scale = XMMatrixScaling(1.0f, 1.0f, 1.0f);
1650 camDir = camTarget - camPosition;
1651 Translation = XMMatrixTranslation(XMVectorGetX(g_vMeshPosition) + objTransX, XMVectorGetY(g_vMeshPosition) + objTransY, XMVectorGetZ(g_vMeshPosition) + objTransZ);
1652 //Translation = XMMatrixTranslation(XMVectorGetX(camPosition) + mapx, XMVectorGetY(camPosition) -9, XMVectorGetZ(camPosition) + mapz);
1653 meshWorld = Scale * Translation * Rotation;
1654 ///////////////**************new(OBJ MESH)**************////////////////////
1655 ///////////////**************new(SKYBOX)**************////////////////////
1656 //Reset sphereWorld
1657 sphereWorld = XMMatrixIdentity();
1658
1659 //Define sphereWorld's world space matrix
1660 Scale = XMMatrixScaling(5000.0f, 5000.0f, 5000.0f);
1661 //Make sure the sphere is always centered around camera
1662 //Translation = XMMatrixTranslation(XMVectorGetX(camPosition), XMVectorGetY(camPosition), XMVectorGetZ(camPosition));
1663 Translation = XMMatrixTranslation(0.0f, 0.0f, 0.0f);
1664 //Set sphereWorld's world space using the transformations
1665 sphereWorld = Scale * Translation;
1666 ///////////////**************new(SKYBOX)**************////////////////////
1667 ///////////////**************new(SPOTLIGHT)**************////////////////////
1668 light[0].pos.x = XMVectorGetX(camPosition);
1669 light[0].pos.y = XMVectorGetY(camPosition);
1670 light[0].pos.z = XMVectorGetZ(camPosition);
1671
1672 light[0].dir.x = XMVectorGetX(camTarget) - light[0].pos.x;
1673 light[0].dir.y = XMVectorGetY(camTarget) - light[0].pos.y;
1674 light[0].dir.z = XMVectorGetZ(camTarget) - light[0].pos.z;
1675 ///////////////**************new(SPOTLIGHT)**************////////////////////
1676 /*lightmesh.pos.x = (100.0f);
1677 lightmesh.pos.y = (5.0f);
1678 lightmesh.pos.z = (0.0f);
1679 lightmesh.dir.x = XMVectorGetX(camTarget) + light.pos.x;
1680 lightmesh.dir.y = XMVectorGetY(camTarget) + light.pos.y;
1681 lightmesh.dir.z = XMVectorGetZ(camTarget) + light.pos.z;*/
1682}
1683//FlatSquare(0, Width, 0, Height / 4, (D2D1::ColorF(1.0f, 1.0f, 1.0f, 0.4f))); //Draw the debug console's transparent rec
1684void RenderText(std::wstring text, int inInt)
1685{
1686
1687 d3d11DevCon->PSSetShader(D2D_PS, 0, 0);
1688
1689 //Release the D3D 11 Device
1690 keyedMutex11->ReleaseSync(0);
1691
1692 //Use D3D10.1 device
1693 keyedMutex10->AcquireSync(0, 5);
1694
1695 //Draw D2D content
1696 D2DRenderTarget->BeginDraw();
1697
1698 //Clear D2D Background
1699 D2DRenderTarget->Clear(D2D1::ColorF(0.0f, 0.0f, 0.0f, 0.0f));
1700
1701 //Create our string
1702 std::wostringstream printString;
1703 printString << text << inInt;
1704 printText = printString.str();
1705
1706 //Set the Font Color
1707 D2D1_COLOR_F FontColor = D2D1::ColorF(1.0f, 1.0f, 1.0f, 1.0f);
1708
1709 //Set the brush color D2D will use to draw with
1710 Brush->SetColor(FontColor);
1711
1712 //Create the D2D Render Area
1713 D2D1_RECT_F layoutRect = D2D1::RectF(0.0f, 0.0f, (float)Width, (float)Height);
1714
1715 //Draw the Text
1716 D2DRenderTarget->DrawText(
1717 printText.c_str(),
1718 wcslen(printText.c_str()),
1719 TextFormat,
1720 layoutRect,
1721 Brush
1722 );
1723
1724 D2DRenderTarget->EndDraw();
1725
1726 //Release the D3D10.1 Device
1727 keyedMutex10->ReleaseSync((UINT64)1);
1728
1729 //Use the D3D11 Device
1730 keyedMutex11->AcquireSync(1, 5);
1731
1732 //Use the shader resource representing the direct2d render target
1733 //to texture a square which is rendered in screen space so it
1734 //overlays on top of our entire scene. We use alpha blending so
1735 //that the entire background of the D2D render target is "invisible",
1736 //And only the stuff we draw with D2D will be visible (the text)
1737
1738 //Set the blend state for D2D render target texture objects
1739 d3d11DevCon->OMSetBlendState(d2dTransparency, NULL, 0xffffffff);
1740
1741 //Set the d2d Index buffer
1742 d3d11DevCon->IASetIndexBuffer(d2dIndexBuffer, DXGI_FORMAT_R32_UINT, 0);
1743 //Set the d2d vertex buffer
1744 UINT stride = sizeof(Vertex);
1745 UINT offset = 0;
1746 d3d11DevCon->IASetVertexBuffers(0, 1, &d2dVertBuffer, &stride, &offset);
1747
1748 WVP = XMMatrixIdentity();
1749 cbPerObj.WVP = XMMatrixTranspose(WVP);
1750 d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
1751 d3d11DevCon->VSSetConstantBuffers(0, 1, &cbPerObjectBuffer);
1752 d3d11DevCon->PSSetShaderResources(0, 1, &d2dTexture);
1753 d3d11DevCon->PSSetSamplers(0, 1, &CubesTexSamplerState);
1754
1755 d3d11DevCon->RSSetState(CWcullMode);
1756 d3d11DevCon->DrawIndexed(6, 0, 0);
1757}
1758void DrawConsole(int fps)
1759{
1760 //Draw D2D content
1761 D2DRenderTarget->BeginDraw();
1762
1763 //Clear D2D Background
1764 D2DRenderTarget->Clear(D2D1::ColorF(0.0f, 0.0f, 0.0f, 0.0f));
1765
1766 //Create our string
1767 std::wostringstream printString;
1768 std::ostringstream PrintString;
1769 printString << "Engine Version: " _ENGINE_VERSION;
1770 printString << "\r\n";
1771
1772 printString << "FPS: " << fps << "\r\n" << "CamPosition: (" << XMVectorGetX(camPosition) << "," << XMVectorGetY(camPosition) << "," << XMVectorGetZ(camPosition) << ")";
1773 printString << " camTarget: (" << XMVectorGetX(camTarget) << "," << XMVectorGetY(camTarget) << "," << XMVectorGetZ(camTarget) << ")";
1774 printString << " camDir: (" << XMVectorGetX(camDir) << "," << XMVectorGetY(camDir) << "," << XMVectorGetZ(camDir) << ")";
1775 printString << " Distance: " << distance << " objRotX: " << objRotX << " objRotY:" << objRotY << " objRotZ: " << objRotZ << " objTransX: " << objTransX << " objTransY:" << objTransY << " objTransZ: " << objTransZ << "\r\n"; "\r\n";
1776 std::string s;
1777
1778 //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
1779 for (int x = 22; x > 0; --x)
1780 {
1781 if (x <= DebugConsole.size() - 1)
1782 s += DebugConsole[DebugConsole.size() - x];
1783 }
1784
1785
1786
1787 printString << Unicode(s);
1788 printText = printString.str();
1789
1790 //Set the Font Color
1791 D2D1_COLOR_F FontColor = D2D1::ColorF(1.0f, 1.0f, 1.0f, 1.0f);
1792
1793 //Set the brush color D2D will use to draw with
1794 Brush->SetColor(FontColor);
1795
1796 //Create the D2D Render Area
1797 D2D1_RECT_F layoutRect = D2D1::RectF(0.0f, 0.0f, (float)Width, (float)Height);
1798
1799 //Draw the Text
1800 D2DRenderTarget->DrawText(
1801 printText.c_str(),
1802 wcslen(printText.c_str()),
1803 TextFormat,
1804 layoutRect,
1805 Brush
1806 );
1807 //FlatSquare(400, 500, 400, 500, (D2D1::ColorF(1.0f, 0.0f, 0.0f, 1.0f))); //Draw the debug console's transparent rec
1808 //FlatSquare(0, 0, 0, 0, 0, 0);
1809 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
1810 D2DRenderTarget->EndDraw();
1811}
1812void DrawD2D(int inInt)
1813{
1814
1815 d3d11DevCon->PSSetShader(D2D_PS, 0, 0);
1816
1817 //Release the D3D 11 Device
1818 keyedMutex11->ReleaseSync(0);
1819
1820 //Use D3D10.1 device
1821 keyedMutex10->AcquireSync(0, 5);
1822 const wchar_t* output = L"Hello World";
1823 //spriteBatch->Begin();
1824 // 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));
1825 //spriteBatch->End();
1826 DrawConsole(inInt);
1827 //Release the D3D10.1 Device
1828 keyedMutex10->ReleaseSync(1);
1829
1830 //Use the D3D11 Device
1831 keyedMutex11->AcquireSync(1, 5);
1832
1833 //Use the shader resource representing the direct2d render target
1834 //to texture a square which is rendered in screen space so it
1835 //overlays on top of our entire scene. We use alpha blending so
1836 //that the entire background of the D2D render target is "invisible",
1837 //And only the stuff we draw with D2D will be visible (the text)
1838
1839 //Set the blend state for D2D render target texture objects
1840 d3d11DevCon->OMSetBlendState(d2dTransparency, NULL, 0xffffffff);
1841
1842 //Set the d2d Index buffer
1843 d3d11DevCon->IASetIndexBuffer(d2dIndexBuffer, DXGI_FORMAT_R32_UINT, 0);
1844 //Set the d2d vertex buffer
1845 UINT stride = sizeof(Vertex);
1846 UINT offset = 0;
1847 d3d11DevCon->IASetVertexBuffers(0, 1, &d2dVertBuffer, &stride, &offset);
1848
1849 WVP = XMMatrixIdentity();
1850 cbPerObj.WVP = XMMatrixTranspose(WVP);
1851 d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
1852 d3d11DevCon->VSSetConstantBuffers(0, 1, &cbPerObjectBuffer);
1853 d3d11DevCon->PSSetShaderResources(0, 1, &d2dTexture);
1854 d3d11DevCon->PSSetSamplers(0, 1, &CubesTexSamplerState);
1855
1856 d3d11DevCon->RSSetState(CWcullMode);
1857 //Draw the second cube
1858 d3d11DevCon->DrawIndexed(6, 0, 0);
1859
1860}
1861
1862
1863void DrawScene()
1864{
1865
1866 //Clear our render target and depth/stencil view
1867 float bgColor[4] = { 0.1f, 0.1f, 0.1f, 1.0f };
1868 d3d11DevCon->ClearRenderTargetView(renderTargetView, bgColor);
1869 d3d11DevCon->ClearDepthStencilView(depthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
1870
1871 constbuffPerFrame.light[0] = light[0];
1872 constbuffPerFrame.light[1] = light[1];
1873 d3d11DevCon->UpdateSubresource(cbPerFrameBuffer, 0, NULL, &constbuffPerFrame, 0, 0);
1874 d3d11DevCon->PSSetConstantBuffers(0, 1, &cbPerFrameBuffer);
1875
1876 //Set our Render Target
1877 d3d11DevCon->OMSetRenderTargets(1, &renderTargetView, depthStencilView);
1878
1879 //Set the default blend state (no blending) for opaque objects
1880 d3d11DevCon->OMSetBlendState(0, 0, 0xffffffff);
1881
1882 //Set Vertex and Pixel Shaders
1883 d3d11DevCon->VSSetShader(VS, 0, 0);
1884 d3d11DevCon->PSSetShader(PS, 0, 0);
1885 //Set the Input Layout
1886 d3d11DevCon->IASetInputLayout(vertLayout);
1887 D3D11_DEPTH_STENCIL_DESC dssDesc;
1888 ZeroMemory(&dssDesc, sizeof(D3D11_DEPTH_STENCIL_DESC));
1889 dssDesc.DepthEnable = true;
1890 dssDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
1891 dssDesc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL;
1892 d3d11Device->CreateDepthStencilState(&dssDesc, &DSLessEqual);
1893 d3d11Device->CreateDepthStencilView(depthStencilBuffer, NULL, &depthStencilView);
1894 ZeroMemory(&dssDesc, sizeof(D3D11_DEPTH_STENCIL_DESC));
1895 dssDesc.DepthEnable = true;
1896 dssDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
1897 dssDesc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL;
1898 d3d11Device->CreateDepthStencilState(&dssDesc, &DSLessEqual);
1899 d3d11Device->CreateDepthStencilView(depthStencilBuffer, NULL, &depthStencilView);
1900 d3d11DevCon->VSSetShader(VS, 0, 0);
1901 d3d11DevCon->PSSetShader(PS, 0, 0);
1902 d3d11DevCon->OMSetRenderTargets(1, &renderTargetView, depthStencilView);
1903 d3d11DevCon->OMSetDepthStencilState(DSLessEqual, 0);
1904 //////////////////////GRASS GROUND//////////////////////////////////////////
1905 //Set the cubes index buffer
1906 d3d11DevCon->IASetIndexBuffer(groundIndexBuffer, DXGI_FORMAT_R32_UINT, 0);
1907 //Set the cubes vertex buffer
1908 UINT stride = sizeof(Vertex);
1909 UINT offset = 0;
1910 d3d11DevCon->IASetVertexBuffers(0, 1, &groundVertexBuffer, &stride, &offset);
1911
1912 //Set the WVP matrix and send it to the constant buffer in effect file
1913 WVP = groundWorld * camView * camProjection;
1914 cbPerObj.WVP = XMMatrixTranspose(WVP);
1915 cbPerObj.World = XMMatrixTranspose(groundWorld);
1916 d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
1917 d3d11DevCon->VSSetConstantBuffers(0, 1, &cbPerObjectBuffer);
1918 d3d11DevCon->PSSetShaderResources(0, 1, &CubesTexture);
1919 d3d11DevCon->PSSetSamplers(0, 1, &CubesTexSamplerState);
1920 d3d11DevCon->RSSetState(CCWcullMode);
1921 d3d11DevCon->DrawIndexed(6, 0, 0);
1922 //////////////////////END GRASS GROUND//////////////////////////////////////
1923
1924
1925 //////////////////////END OBJ MODEL///////////////////////////////////////////////
1926 //////////////////////BSP MAP///////////////////////////////////////////////
1927 //Set the BSP vertex/index buffer
1928
1929 ID3D11Buffer* bspvertexbuffer = bsp.GetVertexBuffer();
1930 d3d11DevCon->IASetVertexBuffers(0, 1, &bspvertexbuffer, &stride, &offset);
1931 d3d11DevCon->RSSetState(RSCullNone);
1932
1933
1934 d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
1935 WVP = mapWorld * camView * camProjection;
1936 cbPerObj.WVP = XMMatrixTranspose(WVP);
1937 cbPerObj.World = XMMatrixTranspose(mapWorld);
1938
1939 d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
1940 //d3d11DevCon->Draw(bsp.m_nNumVerts, 0);
1941 for (int x = 0; x < bsp.m_nNumFaces; x++)
1942 bsp.DrawFace(d3d11Device, d3d11DevCon, x);
1943 //bsp.PVS_Render(d3d11Device, d3d11DevCon, DirectX::SimpleMath::Vector3((XMVectorGetX(camPosition), XMVectorGetY(camPosition), XMVectorGetZ(camPosition))));
1944 d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
1945 //////////////////////END BSP MAP/////////////////////////////////////////////
1946 WVP = cupWorld * camView * camProjection;
1947 cbPerObj.WVP = XMMatrixTranspose(WVP);
1948 cbPerObj.World = XMMatrixTranspose(cupWorld);
1949
1950 //d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
1951 //auto mesh = m_model.get();
1952 //mesh->Draw(d3d11DevCon, (DirectX::CommonStates)cupWorld, camView, camProjection, false);
1953 /*for (auto it = m_model->meshes.cbegin(); it != m_model->meshes.cend(); ++it)
1954 {
1955 auto mesh = it->get();
1956 assert(mesh != 0);
1957
1958 //mesh->PrepareForRendering(deviceContext, states, true);
1959
1960 // Do model-level setCustomState work here
1961 d3d11DevCon->OMSetBlendState(Transparency, NULL, 0xffffffff);
1962 mesh->Draw(d3d11DevCon, cupWorld, camView, camProjection, false);
1963 mesh->Draw(d3d11DevCon,
1964 }
1965 d3d11DevCon->OMSetBlendState(Transparency, NULL, 0xffffffff);*/
1966 //m_states = std::make_unique<CommonStates>(d3d11Device);
1967 //Model model;
1968 //model.CreateFromCMO(d3d11Device, L"cup.cmo", *m_fxFactory);
1969 //model.Draw(d3d11DevCon, *m_states, meshWorld, meshView, meshProjection);
1970 //m_fxFactory = std::make_unique<EffectFactory>(d3d11Device);
1971 //Set our Render Target
1972 d3d11DevCon->OMSetRenderTargets(1, &renderTargetView, depthStencilView);
1973
1974 //Set the default blend state (no blending) for opaque objects
1975 d3d11DevCon->OMSetBlendState(0, 0, 0xffffffff);
1976
1977 //cup->Draw(d3d11DevCon, *m_states, meshWorld, meshView, meshProjection);
1978 //m_model->Draw(d3d11DevCon, *m_states, meshWorld, meshView, meshProjection); //draw is right here
1979 d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
1980
1981 //////////////////////SKYSPHERE///////////////////////////////////////////////////
1982 /////Draw the Sky's Sphere//////
1983 //Set the spheres index buffer
1984 d3d11DevCon->IASetIndexBuffer(sphereIndexBuffer, DXGI_FORMAT_R32_UINT, 0);
1985 //Set the spheres vertex buffer
1986 d3d11DevCon->IASetVertexBuffers(0, 1, &sphereVertBuffer, &stride, &offset);
1987
1988 //Set the WVP matrix and send it to the constant buffer in effect file
1989 WVP = sphereWorld * camView * camProjection;
1990 cbPerObj.WVP = XMMatrixTranspose(WVP);
1991 cbPerObj.World = XMMatrixTranspose(sphereWorld);
1992 d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
1993 d3d11DevCon->VSSetConstantBuffers(0, 1, &cbPerObjectBuffer);
1994 //Send our skymap resource view to pixel shader
1995 d3d11DevCon->PSSetShaderResources(0, 1, &SkyMapTexture);
1996 d3d11DevCon->PSSetSamplers(0, 1, &CubesTexSamplerState);
1997
1998 //Set the new VS and PS shaders
1999 d3d11DevCon->VSSetShader(SKYMAP_VS, 0, 0);
2000 d3d11DevCon->PSSetShader(SKYMAP_PS, 0, 0);
2001 //Set the new depth/stencil and RS states
2002 d3d11DevCon->OMSetDepthStencilState(DSLessEqual, 0);
2003 d3d11DevCon->RSSetState(RSCullNone);
2004 d3d11DevCon->DrawIndexed(NumSphereFaces * 3, 0, 0);
2005
2006 //Set the default VS, PS shaders and depth/stencil state
2007 d3d11DevCon->VSSetShader(VS, 0, 0);
2008 d3d11DevCon->PSSetShader(PS, 0, 0);
2009 d3d11DevCon->OMSetDepthStencilState(NULL, 0);
2010 //////////////////////END SKYSPHERE///////////////////////////////////////////////////
2011 //D3D11_DEPTH_STENCIL_DESC dssDesc;
2012 ZeroMemory(&dssDesc, sizeof(D3D11_DEPTH_STENCIL_DESC));
2013 dssDesc.DepthEnable = true;
2014 dssDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
2015 dssDesc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL;
2016 d3d11Device->CreateDepthStencilState(&dssDesc, &DSLessEqual);
2017 d3d11Device->CreateDepthStencilView(depthStencilBuffer, NULL, &depthStencilView);
2018 d3d11DevCon->VSSetShader(VS, 0, 0);
2019 d3d11DevCon->PSSetShader(PS, 0, 0);
2020 d3d11DevCon->OMSetRenderTargets(1, &renderTargetView, depthStencilView);
2021 d3d11DevCon->OMSetDepthStencilState(DSLessEqual, 0);
2022
2023/* ZeroMemory(&dssDesc, sizeof(D3D11_DEPTH_STENCIL_DESC));
2024 dssDesc.DepthEnable = true;
2025 dssDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
2026 dssDesc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL;
2027 d3d11Device->CreateDepthStencilState(&dssDesc, &DSLessEqual);
2028 d3d11Device->CreateDepthStencilView(depthStencilBuffer, NULL, &depthStencilView);*/
2029 //Set Vertex and Pixel Shaders
2030 d3d11DevCon->VSSetShader(VS, 0, 0);
2031 d3d11DevCon->PSSetShader(PS, 0, 0);
2032 d3d11DevCon->OMSetRenderTargets(1, &renderTargetView, depthStencilView);
2033
2034 //Set the default blend state (no blending) for opaque objects
2035 d3d11DevCon->OMSetBlendState(0, 0, 0xffffffff);
2036
2037 //cup->Draw(d3d11DevCon, *m_states, meshWorld, meshView, meshProjection);
2038 //m_model->Draw(d3d11DevCon, *m_states, meshWorld, meshView, meshProjection); //draw is right here
2039 d3d11DevCon->VSSetConstantBuffers(0, 1, &cbPerObjectBuffer);
2040 d3d11DevCon->PSSetConstantBuffers(1, 1, &cbPerObjectBuffer);
2041 d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
2042 //////////////////////OBJ MODEL///////////////////////////////////////////////
2043
2044 d3d11DevCon->RSSetState(CWcullMode);
2045 //Set the WVP matrix and send it to the constant buffer in effect file
2046 WVP = meshWorld * meshView * meshProjection;
2047 cbPerObj.WVP = XMMatrixTranspose(WVP);
2048 cbPerObj.World = XMMatrixTranspose(meshWorld);
2049 //ModelOne.meshes[0].Draw(d3d11DevCon);
2050 //d3d11DevCon->RSSetState(RSCullNone);
2051 d3d11DevCon->ClearDepthStencilView(depthStencilView, D3D11_CLEAR_DEPTH, 1.0, NULL);
2052 ModelOne.Draw(d3d11DevCon);
2053 d3d11DevCon->VSSetConstantBuffers(0, 1, &cbPerObjectBuffer);
2054 //////////////////////CUP/////////////////////////////////////////////////////////
2055 d3d11DevCon->RSSetState(CWcullMode);
2056 /*m_states = std::make_unique<CommonStates>(d3d11Device);
2057
2058 m_fxFactory = std::make_unique<EffectFactory>(d3d11Device);
2059
2060 //std::unique_ptr<CommonStates> states(new CommonStates(d3d11Device));
2061 //DGSLEffectFactory fx(d3d11Device);
2062 d3d11DevCon->OMSetDepthStencilState(m_states->DepthNone(), 0);
2063 auto samplerState = m_states->LinearWrap();
2064 d3d11DevCon->PSSetSamplers(0, 1, &samplerState);
2065 auto cup = Model::CreateFromCMO(d3d11Device, L"pistol.cmo", *m_fxFactory);*/
2066 //auto pistol = Model::CreateFromSDKMESH(d3d11Device, L"pistol.SDKMESH", *m_fxFactory);
2067
2068
2069 d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0);
2070 //cup->Draw(d3d11DevCon, *m_states, meshWorld, meshView, meshProjection, false);
2071 //////////////////////END STUPID CUP/////////////////////////////////////////////////////////
2072
2073 //Model1.Render(meshWorld);
2074 d3d11DevCon->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); //Just to reset state
2075 if (g_bShowConsole) {
2076 DrawD2D(fps);
2077 }
2078;
2079
2080 /*ZeroMemory(&dssDesc, sizeof(D3D11_DEPTH_STENCIL_DESC));
2081 dssDesc.DepthEnable = true;
2082 dssDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
2083 dssDesc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL;
2084 d3d11Device->CreateDepthStencilState(&dssDesc, &DSLessEqual);
2085 d3d11Device->CreateDepthStencilView(depthStencilBuffer, NULL, &depthStencilView);
2086 d3d11DevCon->VSSetShader(VS, 0, 0);
2087 d3d11DevCon->PSSetShader(PS, 0, 0);
2088 d3d11DevCon->OMSetRenderTargets(1, &renderTargetView, depthStencilView);
2089 d3d11DevCon->OMSetDepthStencilState(DSLessEqual, 0);*/
2090 std::wstring helloworld = L"DIRECTX11 APPLICATION TEST";
2091 //wchar_t *helloworld;
2092 //swprintf(helloworld, "Hello World");
2093
2094/* spriteBatch->Begin();
2095 spriteFont->DrawString(spriteBatch.get(), helloworld.c_str(), DirectX::XMFLOAT2(0, 350), DirectX::Colors::White, 0.0f, DirectX::XMFLOAT2(0.0f,0.0f), DirectX::XMFLOAT2(1.0f, 1.0f));
2096 spriteBatch->End();
2097 //************************************************************************* RESETTING STATES DUE TO SPRITEBATCH
2098 d3d11DevCon->IASetInputLayout(vertLayout);
2099 d3d11DevCon->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
2100 d3d11DevCon->VSSetShader(VS, 0, 0);
2101 d3d11DevCon->PSSetShader(PS, 0, 0);
2102 //TurnOffAlphaBlending(m_pImmediateContext);
2103 d3d11DevCon->OMSetRenderTargets(1, &renderTargetView, depthStencilView);
2104
2105 //Set the default blend state (no blending) for opaque objects
2106 d3d11DevCon->OMSetBlendState(0, 0, 0xffffffff);
2107 // Set the depth stencil state.
2108 ZeroMemory(&dssDesc, sizeof(D3D11_DEPTH_STENCIL_DESC));
2109 dssDesc.DepthEnable = false;
2110 dssDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
2111 dssDesc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL;
2112 d3d11Device->CreateDepthStencilState(&dssDesc, &DSLessEqual);
2113 d3d11Device->CreateDepthStencilView(depthStencilBuffer, NULL, &depthStencilView);
2114 d3d11DevCon->VSSetShader(VS, 0, 0);
2115 d3d11DevCon->PSSetShader(PS, 0, 0);
2116 d3d11DevCon->OMSetRenderTargets(1, &renderTargetView, depthStencilView);
2117 d3d11DevCon->OMSetDepthStencilState(DSLessEqual, 0);
2118 d3d11DevCon->OMSetDepthStencilState(DSLessEqual, 0);
2119 d3d11DevCon->RSSetState(RSCullNone);
2120
2121 //*************************************************************************/
2122
2123 //Present the backbuffer to the screen
2124 SwapChain->Present(0, 0);
2125}
2126///////////////**************new**************////////////////////
2127void CreateSphere(int LatLines, int LongLines)
2128{
2129 NumSphereVertices = ((LatLines - 2) * LongLines) + 2;
2130 NumSphereFaces = ((LatLines - 3)*(LongLines) * 2) + (LongLines * 2);
2131
2132 float sphereYaw = 0.0f;
2133 float spherePitch = 0.0f;
2134
2135 std::vector<Vertex> vertices(NumSphereVertices);
2136
2137 XMVECTOR currVertPos = XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);
2138
2139 vertices[0].pos.x = 0.0f;
2140 vertices[0].pos.y = 0.0f;
2141 vertices[0].pos.z = 1.0f;
2142
2143 for (DWORD i = 0; i < (unsigned int)LatLines - 2; ++i)
2144 {
2145 spherePitch = float((i + 1) * (3.14 / (LatLines - 1)));
2146 Rotationx = XMMatrixRotationX(spherePitch);
2147 for (DWORD j = 0; j < (unsigned int)LongLines; ++j)
2148 {
2149 sphereYaw = (float)(j * (6.28 / (unsigned int)(LongLines)));
2150 Rotationy = XMMatrixRotationZ(sphereYaw);
2151 currVertPos = XMVector3TransformNormal(XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f), (Rotationx * Rotationy));
2152 currVertPos = XMVector3Normalize(currVertPos);
2153 vertices[i*LongLines + j + 1].pos.x = XMVectorGetX(currVertPos);
2154 vertices[i*LongLines + j + 1].pos.y = XMVectorGetY(currVertPos);
2155 vertices[i*LongLines + j + 1].pos.z = XMVectorGetZ(currVertPos);
2156 }
2157 }
2158
2159 vertices[NumSphereVertices - 1].pos.x = 0.0f;
2160 vertices[NumSphereVertices - 1].pos.y = 0.0f;
2161 vertices[NumSphereVertices - 1].pos.z = -1.0f;
2162
2163
2164 D3D11_BUFFER_DESC vertexBufferDesc;
2165 ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc));
2166
2167 vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
2168 vertexBufferDesc.ByteWidth = sizeof(Vertex)* NumSphereVertices;
2169 vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
2170 vertexBufferDesc.CPUAccessFlags = 0;
2171 vertexBufferDesc.MiscFlags = 0;
2172
2173 D3D11_SUBRESOURCE_DATA vertexBufferData;
2174
2175 ZeroMemory(&vertexBufferData, sizeof(vertexBufferData));
2176 vertexBufferData.pSysMem = &vertices[0];
2177 hr = d3d11Device->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &sphereVertBuffer);
2178
2179
2180 std::vector<DWORD> indices(NumSphereFaces * 3);
2181
2182 int k = 0;
2183 for (DWORD l = 0; l < (unsigned int)LongLines - 1; ++l)
2184 {
2185 indices[k] = 0;
2186 indices[k + 1] = l + 1;
2187 indices[k + 2] = l + 2;
2188 k += 3;
2189 }
2190
2191 indices[k] = 0;
2192 indices[k + 1] = LongLines;
2193 indices[k + 2] = 1;
2194 k += 3;
2195
2196 for (DWORD i = 0; i < (unsigned int)LatLines - 3; ++i)
2197 {
2198 for (DWORD j = 0; j < (unsigned int)LongLines - 1; ++j)
2199 {
2200 indices[k] = i*LongLines + j + 1;
2201 indices[k + 1] = i*LongLines + j + 2;
2202 indices[k + 2] = (i + 1)*LongLines + j + 1;
2203
2204 indices[k + 3] = (i + 1)*LongLines + j + 1;
2205 indices[k + 4] = i*LongLines + j + 2;
2206 indices[k + 5] = (i + 1)*LongLines + j + 2;
2207
2208 k += 6; // next quad
2209 }
2210
2211 indices[k] = (i*LongLines) + LongLines;
2212 indices[k + 1] = (i*LongLines) + 1;
2213 indices[k + 2] = ((i + 1)*LongLines) + LongLines;
2214
2215 indices[k + 3] = ((i + 1)*LongLines) + LongLines;
2216 indices[k + 4] = (i*LongLines) + 1;
2217 indices[k + 5] = ((i + 1)*LongLines) + 1;
2218
2219 k += 6;
2220 }
2221
2222 for (DWORD l = 0; l < (unsigned int)LongLines - 1; ++l)
2223 {
2224 indices[k] = NumSphereVertices - 1;
2225 indices[k + 1] = (NumSphereVertices - 1) - (l + 1);
2226 indices[k + 2] = (NumSphereVertices - 1) - (l + 2);
2227 k += 3;
2228 }
2229
2230 indices[k] = NumSphereVertices - 1;
2231 indices[k + 1] = (NumSphereVertices - 1) - LongLines;
2232 indices[k + 2] = NumSphereVertices - 2;
2233
2234 D3D11_BUFFER_DESC indexBufferDesc;
2235 ZeroMemory(&indexBufferDesc, sizeof(indexBufferDesc));
2236
2237 indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
2238 indexBufferDesc.ByteWidth = sizeof(DWORD)* NumSphereFaces * 3;
2239 indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
2240 indexBufferDesc.CPUAccessFlags = 0;
2241 indexBufferDesc.MiscFlags = 0;
2242
2243 D3D11_SUBRESOURCE_DATA iinitData;
2244
2245 iinitData.pSysMem = &indices[0];
2246 d3d11Device->CreateBuffer(&indexBufferDesc, &iinitData, &sphereIndexBuffer);
2247
2248}
2249///////////////**************new**************////////////////////
2250
2251
2252
2253
2254WPARAM messageloop() {
2255 MSG msg;
2256 ZeroMemory(&msg, sizeof(MSG));
2257 while (true)
2258 {
2259 BOOL PeekMessageL(
2260 LPMSG lpMsg,
2261 HWND hWnd,
2262 UINT wMsgFilterMin,
2263 UINT wMsgFilterMax,
2264 UINT wRemoveMsg
2265 );
2266
2267 if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
2268 {
2269 if (msg.message == WM_QUIT)
2270 break;
2271 TranslateMessage(&msg);
2272 DispatchMessage(&msg);
2273 }
2274 else {
2275 // run game code
2276 frameCount++;
2277 if (GetTime() > 1.0f)
2278 {
2279 fps = frameCount;
2280 frameCount = 0;
2281 StartTimer();
2282 }
2283
2284 frameTime = GetFrameTime();
2285
2286 DetectInput(frameTime);
2287 UpdateScene(frameTime);
2288 DrawScene();
2289 }
2290 }
2291 return msg.wParam;
2292}
2293
2294LRESULT CALLBACK WndProc(HWND hwnd,
2295 UINT msg,
2296 WPARAM wParam,
2297 LPARAM lParam)
2298{
2299 switch (msg)
2300 {
2301 case WM_KEYDOWN:
2302 if (wParam == VK_ESCAPE) {
2303 DestroyWindow(hwnd);
2304 }
2305 return 0;
2306
2307 case WM_DESTROY:
2308 PostQuitMessage(0);
2309 return 0;
2310 }
2311 return DefWindowProc(hwnd,
2312 msg,
2313 wParam,
2314 lParam);
2315}