main.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. // ---------------------------------------------------------------------------
  2. // Simple Assimp Directx11 Sample
  3. // This is a very basic sample and only reads diffuse texture
  4. // but this can load both embedded textures in fbx and non-embedded textures
  5. //
  6. //
  7. // Replace ourModel->Load(hwnd, dev, devcon, "Models/myModel.fbx") this with your
  8. // model name (line 480)
  9. // If your model isn't a fbx with embedded textures make sure your model's
  10. // textures are in same directory as your model
  11. //
  12. //
  13. // Written by IAS. :)
  14. // ---------------------------------------------------------------------------
  15. #include <Windows.h>
  16. #include <shellapi.h>
  17. #include <stdexcept>
  18. #include <windowsx.h>
  19. #include <d3d11_1.h>
  20. #include <dxgi1_2.h>
  21. #include <DirectXMath.h>
  22. #include <d3dcompiler.h>
  23. #include "ModelLoader.h"
  24. #include "UTFConverter.h"
  25. #include "SafeRelease.hpp"
  26. #ifdef _MSC_VER
  27. #pragma comment (lib, "d3d11.lib")
  28. #pragma comment (lib, "Dxgi.lib")
  29. #pragma comment(lib,"d3dcompiler.lib")
  30. #pragma comment (lib, "dxguid.lib")
  31. #endif // _MSC_VER
  32. using namespace DirectX;
  33. using namespace AssimpSamples::SharedCode;
  34. #define VERTEX_SHADER_FILE L"VertexShader.hlsl"
  35. #define PIXEL_SHADER_FILE L"PixelShader.hlsl"
  36. // ------------------------------------------------------------
  37. // Structs
  38. // ------------------------------------------------------------
  39. struct ConstantBuffer {
  40. XMMATRIX mWorld;
  41. XMMATRIX mView;
  42. XMMATRIX mProjection;
  43. };
  44. // ------------------------------------------------------------
  45. // Window Variables
  46. // ------------------------------------------------------------
  47. #define SCREEN_WIDTH 800
  48. #define SCREEN_HEIGHT 600
  49. const char g_szClassName[] = "directxWindowClass";
  50. static std::string g_ModelPath;
  51. UINT width, height;
  52. HWND g_hwnd = nullptr;
  53. // ------------------------------------------------------------
  54. // DirectX Variables
  55. // ------------------------------------------------------------
  56. D3D_DRIVER_TYPE g_driverType = D3D_DRIVER_TYPE_NULL;
  57. D3D_FEATURE_LEVEL g_featureLevel = D3D_FEATURE_LEVEL_11_0;
  58. ID3D11Device *dev = nullptr;
  59. ID3D11Device1 *dev1 = nullptr;
  60. ID3D11DeviceContext *devcon = nullptr;
  61. ID3D11DeviceContext1 *devcon1 = nullptr;
  62. IDXGISwapChain *swapchain = nullptr;
  63. IDXGISwapChain1 *swapchain1 = nullptr;
  64. ID3D11RenderTargetView *backbuffer = nullptr;
  65. ID3D11VertexShader *pVS = nullptr;
  66. ID3D11PixelShader *pPS = nullptr;
  67. ID3D11InputLayout *pLayout = nullptr;
  68. ID3D11Buffer *pConstantBuffer = nullptr;
  69. ID3D11Texture2D *g_pDepthStencil = nullptr;
  70. ID3D11DepthStencilView *g_pDepthStencilView = nullptr;
  71. ID3D11SamplerState *TexSamplerState = nullptr;
  72. ID3D11RasterizerState *rasterstate = nullptr;
  73. ID3D11Debug* d3d11debug = nullptr;
  74. XMMATRIX m_World;
  75. XMMATRIX m_View;
  76. XMMATRIX m_Projection;
  77. // ------------------------------------------------------------
  78. // Function identifiers
  79. // ------------------------------------------------------------
  80. void InitD3D(HINSTANCE hinstance, HWND hWnd);
  81. void CleanD3D(void);
  82. void RenderFrame(void);
  83. void InitPipeline();
  84. void InitGraphics();
  85. HRESULT CompileShaderFromFile(LPCWSTR pFileName, const D3D_SHADER_MACRO* pDefines, LPCSTR pEntryPoint, LPCSTR pShaderModel, ID3DBlob** ppBytecodeBlob);
  86. void Throwanerror(LPCSTR errormessage);
  87. // ------------------------------------------------------------
  88. // Our Model
  89. // ------------------------------------------------------------
  90. ModelLoader *ourModel = nullptr;
  91. LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  92. {
  93. switch (msg)
  94. {
  95. case WM_CLOSE:
  96. DestroyWindow(hwnd);
  97. break;
  98. case WM_DESTROY:
  99. PostQuitMessage(0);
  100. break;
  101. default:
  102. return DefWindowProc(hwnd, msg, wParam, lParam);
  103. }
  104. return 0;
  105. }
  106. int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/,
  107. LPWSTR /*lpCmdLine*/, int nCmdShow)
  108. {
  109. int argc;
  110. LPWSTR* argv = CommandLineToArgvW(GetCommandLineW(), &argc);
  111. if (!argv) {
  112. MessageBox(nullptr,
  113. TEXT("An error occurred while reading command line arguments."),
  114. TEXT("Error!"),
  115. MB_ICONERROR | MB_OK);
  116. return EXIT_FAILURE;
  117. }
  118. // Free memory allocated from CommandLineToArgvW.
  119. auto free_command_line_allocated_memory = [&argv]() {
  120. if (argv) {
  121. LocalFree(argv);
  122. argv = nullptr;
  123. }
  124. };
  125. // Ensure that a model file has been specified.
  126. if (argc < 2) {
  127. MessageBox(nullptr,
  128. TEXT("No model file specified. The program will now close."),
  129. TEXT("Error!"),
  130. MB_ICONERROR | MB_OK);
  131. free_command_line_allocated_memory();
  132. return EXIT_FAILURE;
  133. }
  134. // Retrieve the model file path.
  135. g_ModelPath = UTFConverter(argv[1]).str();
  136. free_command_line_allocated_memory();
  137. WNDCLASSEX wc;
  138. MSG msg;
  139. wc.cbSize = sizeof(WNDCLASSEX);
  140. wc.style = 0;
  141. wc.lpfnWndProc = WndProc;
  142. wc.cbClsExtra = 0;
  143. wc.cbWndExtra = 0;
  144. wc.hInstance = hInstance;
  145. wc.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
  146. wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
  147. wc.hbrBackground = nullptr;
  148. wc.lpszMenuName = nullptr;
  149. wc.lpszClassName = g_szClassName;
  150. wc.hIconSm = LoadIcon(nullptr, IDI_APPLICATION);
  151. if (!RegisterClassEx(&wc))
  152. {
  153. MessageBox(nullptr, "Window Registration Failed!", "Error!",
  154. MB_ICONEXCLAMATION | MB_OK);
  155. return 0;
  156. }
  157. RECT wr = { 0,0, SCREEN_WIDTH, SCREEN_HEIGHT };
  158. AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
  159. g_hwnd = CreateWindowEx(
  160. WS_EX_CLIENTEDGE,
  161. g_szClassName,
  162. " Simple Textured Directx11 Sample ",
  163. WS_OVERLAPPEDWINDOW,
  164. CW_USEDEFAULT, CW_USEDEFAULT, wr.right - wr.left, wr.bottom - wr.top,
  165. nullptr, nullptr, hInstance, nullptr
  166. );
  167. if (g_hwnd == nullptr)
  168. {
  169. MessageBox(nullptr, "Window Creation Failed!", "Error!",
  170. MB_ICONEXCLAMATION | MB_OK);
  171. return 0;
  172. }
  173. ShowWindow(g_hwnd, nCmdShow);
  174. UpdateWindow(g_hwnd);
  175. width = wr.right - wr.left;
  176. height = wr.bottom - wr.top;
  177. try {
  178. InitD3D(hInstance, g_hwnd);
  179. while (true)
  180. {
  181. if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
  182. {
  183. TranslateMessage(&msg);
  184. DispatchMessage(&msg);
  185. if (msg.message == WM_QUIT)
  186. break;
  187. }
  188. RenderFrame();
  189. }
  190. CleanD3D();
  191. return static_cast<int>(msg.wParam);
  192. } catch (const std::exception& e) {
  193. MessageBox(g_hwnd, e.what(), TEXT("Error!"), MB_ICONERROR | MB_OK);
  194. CleanD3D();
  195. return EXIT_FAILURE;
  196. } catch (...) {
  197. MessageBox(g_hwnd, TEXT("Caught an unknown exception."), TEXT("Error!"), MB_ICONERROR | MB_OK);
  198. CleanD3D();
  199. return EXIT_FAILURE;
  200. }
  201. }
  202. void InitD3D(HINSTANCE /*hinstance*/, HWND hWnd)
  203. {
  204. HRESULT hr;
  205. UINT createDeviceFlags = 0;
  206. #ifdef _DEBUG
  207. createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
  208. #endif
  209. D3D_DRIVER_TYPE driverTypes[] =
  210. {
  211. D3D_DRIVER_TYPE_HARDWARE,
  212. D3D_DRIVER_TYPE_WARP,
  213. D3D_DRIVER_TYPE_REFERENCE,
  214. };
  215. UINT numDriverTypes = ARRAYSIZE(driverTypes);
  216. D3D_FEATURE_LEVEL featureLevels[] =
  217. {
  218. D3D_FEATURE_LEVEL_11_1,
  219. D3D_FEATURE_LEVEL_11_0,
  220. D3D_FEATURE_LEVEL_10_1,
  221. D3D_FEATURE_LEVEL_10_0,
  222. };
  223. UINT numFeatureLevels = ARRAYSIZE(featureLevels);
  224. for (UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++)
  225. {
  226. g_driverType = driverTypes[driverTypeIndex];
  227. hr = D3D11CreateDevice(nullptr, g_driverType, nullptr, createDeviceFlags, featureLevels, numFeatureLevels,
  228. D3D11_SDK_VERSION, &dev, &g_featureLevel, &devcon);
  229. if (hr == E_INVALIDARG)
  230. {
  231. // DirectX 11.0 platforms will not recognize D3D_FEATURE_LEVEL_11_1 so we need to retry without it
  232. hr = D3D11CreateDevice(nullptr, g_driverType, nullptr, createDeviceFlags, &featureLevels[1], numFeatureLevels - 1,
  233. D3D11_SDK_VERSION, &dev, &g_featureLevel, &devcon);
  234. }
  235. if (SUCCEEDED(hr))
  236. break;
  237. }
  238. if (FAILED(hr))
  239. Throwanerror("Directx Device Creation Failed!");
  240. #if _DEBUG
  241. hr = dev->QueryInterface(IID_PPV_ARGS(&d3d11debug));
  242. if (FAILED(hr))
  243. OutputDebugString(TEXT("Failed to retrieve DirectX 11 debug interface.\n"));
  244. #endif
  245. UINT m4xMsaaQuality;
  246. dev->CheckMultisampleQualityLevels(
  247. DXGI_FORMAT_R8G8B8A8_UNORM, 4, &m4xMsaaQuality);
  248. // Obtain DXGI factory from device (since we used nullptr for pAdapter above)
  249. IDXGIFactory1* dxgiFactory = nullptr;
  250. {
  251. IDXGIDevice* dxgiDevice = nullptr;
  252. hr = dev->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<void**>(&dxgiDevice));
  253. if (SUCCEEDED(hr))
  254. {
  255. IDXGIAdapter* adapter = nullptr;
  256. hr = dxgiDevice->GetAdapter(&adapter);
  257. if (SUCCEEDED(hr))
  258. {
  259. hr = adapter->GetParent(__uuidof(IDXGIFactory1), reinterpret_cast<void**>(&dxgiFactory));
  260. adapter->Release();
  261. }
  262. dxgiDevice->Release();
  263. }
  264. }
  265. if (FAILED(hr))
  266. Throwanerror("DXGI Factory couldn't be obtained!");
  267. // Create swap chain
  268. IDXGIFactory2* dxgiFactory2 = nullptr;
  269. hr = dxgiFactory->QueryInterface(__uuidof(IDXGIFactory2), reinterpret_cast<void**>(&dxgiFactory2));
  270. if (dxgiFactory2)
  271. {
  272. // DirectX 11.1 or later
  273. hr = dev->QueryInterface(__uuidof(ID3D11Device1), reinterpret_cast<void**>(&dev1));
  274. if (SUCCEEDED(hr))
  275. {
  276. (void)devcon->QueryInterface(__uuidof(ID3D11DeviceContext1), reinterpret_cast<void**>(&devcon1));
  277. }
  278. DXGI_SWAP_CHAIN_DESC1 sd;
  279. ZeroMemory(&sd, sizeof(sd));
  280. sd.Width = SCREEN_WIDTH;
  281. sd.Height = SCREEN_HEIGHT;
  282. sd.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  283. sd.SampleDesc.Count = 4;
  284. sd.SampleDesc.Quality = m4xMsaaQuality - 1;
  285. sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  286. sd.BufferCount = 1;
  287. hr = dxgiFactory2->CreateSwapChainForHwnd(dev, hWnd, &sd, nullptr, nullptr, &swapchain1);
  288. if (SUCCEEDED(hr))
  289. {
  290. hr = swapchain1->QueryInterface(__uuidof(IDXGISwapChain), reinterpret_cast<void**>(&swapchain));
  291. }
  292. dxgiFactory2->Release();
  293. }
  294. else
  295. {
  296. // DirectX 11.0 systems
  297. DXGI_SWAP_CHAIN_DESC sd;
  298. ZeroMemory(&sd, sizeof(sd));
  299. sd.BufferCount = 1;
  300. sd.BufferDesc.Width = SCREEN_WIDTH;
  301. sd.BufferDesc.Height = SCREEN_HEIGHT;
  302. sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  303. sd.BufferDesc.RefreshRate.Numerator = 60;
  304. sd.BufferDesc.RefreshRate.Denominator = 1;
  305. sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  306. sd.OutputWindow = hWnd;
  307. sd.SampleDesc.Count = 1;
  308. sd.SampleDesc.Quality = m4xMsaaQuality - 1;
  309. sd.Windowed = TRUE;
  310. hr = dxgiFactory->CreateSwapChain(dev, &sd, &swapchain);
  311. }
  312. // Note this tutorial doesn't handle full-screen swapchains so we block the ALT+ENTER shortcut
  313. dxgiFactory->MakeWindowAssociation(g_hwnd, DXGI_MWA_NO_ALT_ENTER);
  314. dxgiFactory->Release();
  315. if (FAILED(hr))
  316. Throwanerror("Swapchain Creation Failed!");
  317. ID3D11Texture2D *pBackBuffer;
  318. swapchain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);
  319. dev->CreateRenderTargetView(pBackBuffer, nullptr, &backbuffer);
  320. pBackBuffer->Release();
  321. D3D11_TEXTURE2D_DESC descDepth;
  322. ZeroMemory(&descDepth, sizeof(descDepth));
  323. descDepth.Width = SCREEN_WIDTH;
  324. descDepth.Height = SCREEN_HEIGHT;
  325. descDepth.MipLevels = 1;
  326. descDepth.ArraySize = 1;
  327. descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
  328. descDepth.SampleDesc.Count = 4;
  329. descDepth.SampleDesc.Quality = m4xMsaaQuality - 1;
  330. descDepth.Usage = D3D11_USAGE_DEFAULT;
  331. descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL;
  332. descDepth.CPUAccessFlags = 0;
  333. descDepth.MiscFlags = 0;
  334. hr = dev->CreateTexture2D(&descDepth, nullptr, &g_pDepthStencil);
  335. if (FAILED(hr))
  336. Throwanerror("Depth Stencil Texture couldn't be created!");
  337. // Create the depth stencil view
  338. D3D11_DEPTH_STENCIL_VIEW_DESC descDSV;
  339. ZeroMemory(&descDSV, sizeof(descDSV));
  340. descDSV.Format = descDepth.Format;
  341. descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
  342. descDSV.Texture2D.MipSlice = 0;
  343. hr = dev->CreateDepthStencilView(g_pDepthStencil, 0, &g_pDepthStencilView);
  344. if (FAILED(hr))
  345. {
  346. Throwanerror("Depth Stencil View couldn't be created!");
  347. }
  348. devcon->OMSetRenderTargets(1, &backbuffer, g_pDepthStencilView);
  349. D3D11_RASTERIZER_DESC rasterDesc;
  350. rasterDesc.AntialiasedLineEnable = false;
  351. rasterDesc.CullMode = D3D11_CULL_BACK;
  352. rasterDesc.DepthBias = 0;
  353. rasterDesc.DepthBiasClamp = 0.0f;
  354. rasterDesc.DepthClipEnable = true;
  355. rasterDesc.FillMode = D3D11_FILL_SOLID;
  356. rasterDesc.FrontCounterClockwise = false;
  357. rasterDesc.MultisampleEnable = false;
  358. rasterDesc.ScissorEnable = false;
  359. rasterDesc.SlopeScaledDepthBias = 0.0f;
  360. dev->CreateRasterizerState(&rasterDesc, &rasterstate);
  361. devcon->RSSetState(rasterstate);
  362. D3D11_VIEWPORT viewport;
  363. ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));
  364. viewport.TopLeftX = 0;
  365. viewport.TopLeftY = 0;
  366. viewport.MinDepth = 0.0f;
  367. viewport.MaxDepth = 1.0f;
  368. viewport.Width = SCREEN_WIDTH;
  369. viewport.Height = SCREEN_HEIGHT;
  370. devcon->RSSetViewports(1, &viewport);
  371. InitPipeline();
  372. InitGraphics();
  373. }
  374. void CleanD3D(void)
  375. {
  376. if (swapchain)
  377. swapchain->SetFullscreenState(FALSE, nullptr);
  378. if (ourModel) {
  379. ourModel->Close();
  380. delete ourModel;
  381. ourModel = nullptr;
  382. }
  383. SafeRelease(TexSamplerState);
  384. SafeRelease(pConstantBuffer);
  385. SafeRelease(pLayout);
  386. SafeRelease(pVS);
  387. SafeRelease(pPS);
  388. SafeRelease(rasterstate);
  389. SafeRelease(g_pDepthStencilView);
  390. SafeRelease(g_pDepthStencil);
  391. SafeRelease(backbuffer);
  392. SafeRelease(swapchain);
  393. SafeRelease(swapchain1);
  394. SafeRelease(devcon1);
  395. SafeRelease(dev1);
  396. SafeRelease(devcon);
  397. #if _DEBUG
  398. if (d3d11debug) {
  399. OutputDebugString(TEXT("Dumping DirectX 11 live objects.\n"));
  400. d3d11debug->ReportLiveDeviceObjects(D3D11_RLDO_DETAIL);
  401. SafeRelease(d3d11debug);
  402. } else {
  403. OutputDebugString(TEXT("Unable to dump live objects: no DirectX 11 debug interface available.\n"));
  404. }
  405. #endif
  406. SafeRelease(dev);
  407. }
  408. void RenderFrame(void)
  409. {
  410. static float t = 0.0f;
  411. static ULONGLONG timeStart = 0;
  412. ULONGLONG timeCur = GetTickCount64();
  413. if (timeStart == 0)
  414. timeStart = timeCur;
  415. t = (timeCur - timeStart) / 1000.0f;
  416. float clearColor[4] = { 0.0f, 0.2f, 0.4f, 1.0f };
  417. devcon->ClearRenderTargetView(backbuffer, clearColor);
  418. devcon->ClearDepthStencilView(g_pDepthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
  419. devcon->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  420. m_World = XMMatrixRotationY(-t);
  421. ConstantBuffer cb;
  422. cb.mWorld = XMMatrixTranspose(m_World);
  423. cb.mView = XMMatrixTranspose(m_View);
  424. cb.mProjection = XMMatrixTranspose(m_Projection);
  425. devcon->UpdateSubresource(pConstantBuffer, 0, nullptr, &cb, 0, 0);
  426. devcon->VSSetShader(pVS, 0, 0);
  427. devcon->VSSetConstantBuffers(0, 1, &pConstantBuffer);
  428. devcon->PSSetShader(pPS, 0, 0);
  429. devcon->PSSetSamplers(0, 1, &TexSamplerState);
  430. ourModel->Draw(devcon);
  431. swapchain->Present(0, 0);
  432. }
  433. void InitPipeline()
  434. {
  435. ID3DBlob *VS, *PS;
  436. if(FAILED(CompileShaderFromFile(SHADER_PATH VERTEX_SHADER_FILE, 0, "main", "vs_4_0", &VS)))
  437. Throwanerror(UTFConverter(L"Failed to compile shader from file " VERTEX_SHADER_FILE).c_str());
  438. if(FAILED(CompileShaderFromFile(SHADER_PATH PIXEL_SHADER_FILE, 0, "main", "ps_4_0", &PS)))
  439. Throwanerror(UTFConverter(L"Failed to compile shader from file " PIXEL_SHADER_FILE).c_str());
  440. dev->CreateVertexShader(VS->GetBufferPointer(), VS->GetBufferSize(), nullptr, &pVS);
  441. dev->CreatePixelShader(PS->GetBufferPointer(), PS->GetBufferSize(), nullptr, &pPS);
  442. D3D11_INPUT_ELEMENT_DESC ied[] =
  443. {
  444. { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
  445. { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }
  446. };
  447. dev->CreateInputLayout(ied, 2, VS->GetBufferPointer(), VS->GetBufferSize(), &pLayout);
  448. devcon->IASetInputLayout(pLayout);
  449. }
  450. void InitGraphics()
  451. {
  452. HRESULT hr;
  453. m_Projection = XMMatrixPerspectiveFovLH(XM_PIDIV4, SCREEN_WIDTH / (float)SCREEN_HEIGHT, 0.01f, 1000.0f);
  454. D3D11_BUFFER_DESC bd;
  455. ZeroMemory(&bd, sizeof(bd));
  456. bd.Usage = D3D11_USAGE_DEFAULT;
  457. bd.ByteWidth = sizeof(ConstantBuffer);
  458. bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
  459. bd.CPUAccessFlags = 0;
  460. hr = dev->CreateBuffer(&bd, nullptr, &pConstantBuffer);
  461. if (FAILED(hr))
  462. Throwanerror("Constant buffer couldn't be created");
  463. D3D11_SAMPLER_DESC sampDesc;
  464. ZeroMemory(&sampDesc, sizeof(sampDesc));
  465. sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
  466. sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
  467. sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
  468. sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
  469. sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
  470. sampDesc.MinLOD = 0;
  471. sampDesc.MaxLOD = D3D11_FLOAT32_MAX;
  472. hr = dev->CreateSamplerState(&sampDesc, &TexSamplerState);
  473. if (FAILED(hr))
  474. Throwanerror("Texture sampler state couldn't be created");
  475. XMVECTOR Eye = XMVectorSet(0.0f, 5.0f, -300.0f, 0.0f);
  476. XMVECTOR At = XMVectorSet(0.0f, 100.0f, 0.0f, 0.0f);
  477. XMVECTOR Up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
  478. m_View = XMMatrixLookAtLH(Eye, At, Up);
  479. ourModel = new ModelLoader;
  480. if (!ourModel->Load(g_hwnd, dev, devcon, g_ModelPath))
  481. Throwanerror("Model couldn't be loaded");
  482. }
  483. HRESULT CompileShaderFromFile(LPCWSTR pFileName, const D3D_SHADER_MACRO* pDefines, LPCSTR pEntryPoint, LPCSTR pShaderModel, ID3DBlob** ppBytecodeBlob)
  484. {
  485. UINT compileFlags = D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR;
  486. #ifdef _DEBUG
  487. compileFlags |= D3DCOMPILE_DEBUG;
  488. #endif
  489. ID3DBlob* pErrorBlob = nullptr;
  490. HRESULT result = D3DCompileFromFile(pFileName, pDefines, D3D_COMPILE_STANDARD_FILE_INCLUDE, pEntryPoint, pShaderModel, compileFlags, 0, ppBytecodeBlob, &pErrorBlob);
  491. if (FAILED(result))
  492. {
  493. if (pErrorBlob != nullptr)
  494. OutputDebugStringA((LPCSTR)pErrorBlob->GetBufferPointer());
  495. }
  496. if (pErrorBlob != nullptr)
  497. pErrorBlob->Release();
  498. return result;
  499. }
  500. void Throwanerror(LPCSTR errormessage)
  501. {
  502. throw std::runtime_error(errormessage);
  503. }