Renderer.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <TestFramework.h>
  4. #include <Renderer/Renderer.h>
  5. #include <Renderer/Texture.h>
  6. #include <Renderer/FatalErrorIfFailed.h>
  7. #include <Core/Profiler.h>
  8. #include <Utils/ReadData.h>
  9. #include <Utils/Log.h>
  10. #pragma warning (push, 0)
  11. #pragma warning (disable : 4668) // DirectXMath.h(22): warning C4668: '_MANAGED' is not defined as a preprocessor macro, replacing with '0' for '#if/#elif'
  12. #include <d3dcompiler.h>
  13. #include <ShellScalingApi.h>
  14. #include <DirectXMath.h>
  15. #pragma warning (pop)
  16. #pragma comment(lib, "dxgi.lib")
  17. #pragma comment(lib, "d3d12.lib")
  18. #pragma comment(lib, "d3dcompiler.lib")
  19. static Renderer *sRenderer = nullptr;
  20. struct VertexShaderConstantBuffer
  21. {
  22. DirectX::XMFLOAT4X4 mView;
  23. DirectX::XMFLOAT4X4 mProjection;
  24. DirectX::XMFLOAT4X4 mLightView;
  25. DirectX::XMFLOAT4X4 mLightProjection;
  26. };
  27. struct PixelShaderConstantBuffer
  28. {
  29. DirectX::XMFLOAT4 mCameraPos;
  30. DirectX::XMFLOAT4 mLightPos;
  31. };
  32. //--------------------------------------------------------------------------------------
  33. // Called every time the application receives a message
  34. //--------------------------------------------------------------------------------------
  35. static LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
  36. {
  37. PAINTSTRUCT ps;
  38. HDC hdc;
  39. switch (message)
  40. {
  41. case WM_PAINT:
  42. hdc = BeginPaint(hWnd, &ps);
  43. EndPaint(hWnd, &ps);
  44. break;
  45. case WM_SIZE:
  46. if (sRenderer != nullptr)
  47. sRenderer->OnWindowResize();
  48. break;
  49. case WM_DESTROY:
  50. PostQuitMessage(0);
  51. break;
  52. default:
  53. return DefWindowProc(hWnd, message, wParam, lParam);
  54. }
  55. return 0;
  56. }
  57. Renderer::~Renderer()
  58. {
  59. // Ensure that the GPU is no longer referencing resources that are about to be cleaned up by the destructor.
  60. WaitForGpu();
  61. // Don't add more stuff to the delay reference list
  62. mIsExiting = true;
  63. CloseHandle(mFenceEvent);
  64. }
  65. void Renderer::WaitForGpu()
  66. {
  67. // Schedule a Signal command in the queue
  68. UINT64 current_fence_value = mFenceValues[mFrameIndex];
  69. FatalErrorIfFailed(mCommandQueue->Signal(mFence.Get(), current_fence_value));
  70. // Wait until the fence has been processed
  71. FatalErrorIfFailed(mFence->SetEventOnCompletion(current_fence_value, mFenceEvent));
  72. WaitForSingleObjectEx(mFenceEvent, INFINITE, FALSE);
  73. // Increment the fence value for all frames
  74. for (uint n = 0; n < cFrameCount; ++n)
  75. mFenceValues[n] = current_fence_value + 1;
  76. // Release all used resources
  77. for (vector<ComPtr<ID3D12Object>> &list : mDelayReleased)
  78. list.clear();
  79. // Anything that's not used yet can be removed, delayed objects are now available
  80. mResourceCache.clear();
  81. mDelayCached[mFrameIndex].swap(mResourceCache);
  82. }
  83. void Renderer::CreateRenterTargets()
  84. {
  85. // Create render targets and views
  86. for (uint n = 0; n < cFrameCount; ++n)
  87. {
  88. mRenderTargetViews[n] = mRTVHeap.Allocate();
  89. FatalErrorIfFailed(mSwapChain->GetBuffer(n, IID_PPV_ARGS(&mRenderTargets[n])));
  90. mDevice->CreateRenderTargetView(mRenderTargets[n].Get(), nullptr, mRenderTargetViews[n]);
  91. }
  92. }
  93. void Renderer::CreateDepthBuffer()
  94. {
  95. // Free any previous depth stencil view
  96. if (mDepthStencilView.ptr != 0)
  97. mDSVHeap.Free(mDepthStencilView);
  98. // Free any previous depth stencil buffer
  99. mDepthStencilBuffer.Reset();
  100. // Allocate depth stencil buffer
  101. D3D12_CLEAR_VALUE clear_value = {};
  102. clear_value.Format = DXGI_FORMAT_D32_FLOAT;
  103. clear_value.DepthStencil.Depth = 1.0f;
  104. clear_value.DepthStencil.Stencil = 0;
  105. D3D12_HEAP_PROPERTIES heap_properties = {};
  106. heap_properties.Type = D3D12_HEAP_TYPE_DEFAULT;
  107. heap_properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  108. heap_properties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  109. heap_properties.CreationNodeMask = 1;
  110. heap_properties.VisibleNodeMask = 1;
  111. D3D12_RESOURCE_DESC depth_stencil_desc = {};
  112. depth_stencil_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
  113. depth_stencil_desc.Alignment = 0;
  114. depth_stencil_desc.Width = mWindowWidth;
  115. depth_stencil_desc.Height = mWindowHeight;
  116. depth_stencil_desc.DepthOrArraySize = 1;
  117. depth_stencil_desc.MipLevels = 1;
  118. depth_stencil_desc.Format = DXGI_FORMAT_D32_FLOAT;
  119. depth_stencil_desc.SampleDesc.Count = 1;
  120. depth_stencil_desc.SampleDesc.Quality = 0;
  121. depth_stencil_desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
  122. depth_stencil_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
  123. FatalErrorIfFailed(mDevice->CreateCommittedResource(&heap_properties, D3D12_HEAP_FLAG_NONE, &depth_stencil_desc, D3D12_RESOURCE_STATE_DEPTH_WRITE, &clear_value, IID_PPV_ARGS(&mDepthStencilBuffer)));
  124. // Allocate depth stencil view
  125. D3D12_DEPTH_STENCIL_VIEW_DESC depth_stencil_view_desc = {};
  126. depth_stencil_view_desc.Format = DXGI_FORMAT_D32_FLOAT;
  127. depth_stencil_view_desc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
  128. depth_stencil_view_desc.Flags = D3D12_DSV_FLAG_NONE;
  129. mDepthStencilView = mDSVHeap.Allocate();
  130. mDevice->CreateDepthStencilView(mDepthStencilBuffer.Get(), &depth_stencil_view_desc, mDepthStencilView);
  131. }
  132. void Renderer::Initialize()
  133. {
  134. // Prevent this window from auto scaling
  135. SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE);
  136. // Register class
  137. WNDCLASSEX wcex;
  138. wcex.cbSize = sizeof(WNDCLASSEX);
  139. wcex.style = CS_HREDRAW | CS_VREDRAW;
  140. wcex.lpfnWndProc = WndProc;
  141. wcex.cbClsExtra = 0;
  142. wcex.cbWndExtra = 0;
  143. wcex.hInstance = GetModuleHandle(nullptr);
  144. wcex.hIcon = nullptr;
  145. wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
  146. wcex.hbrBackground = nullptr;
  147. wcex.lpszMenuName = nullptr;
  148. wcex.lpszClassName = L"TestFrameworkClass";
  149. wcex.hIconSm = nullptr;
  150. if (!RegisterClassEx(&wcex))
  151. FatalError("Failed to register window class");
  152. // Create window
  153. RECT rc = { 0, 0, mWindowWidth, mWindowHeight };
  154. AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE);
  155. mhWnd = CreateWindow(L"TestFrameworkClass", L"TestFramework", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
  156. rc.right - rc.left, rc.bottom - rc.top, nullptr, nullptr, wcex.hInstance, nullptr);
  157. if (!mhWnd)
  158. FatalError("Failed to create window");
  159. // Show window
  160. ShowWindow(mhWnd, SW_SHOW);
  161. #if defined(_DEBUG)
  162. // Enable the D3D12 debug layer
  163. ComPtr<ID3D12Debug> debug_controller;
  164. if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debug_controller))))
  165. debug_controller->EnableDebugLayer();
  166. #endif
  167. // Create DXGI factory
  168. FatalErrorIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&mDXGIFactory)));
  169. // Find adapter
  170. ComPtr<IDXGIAdapter1> adapter;
  171. // First check if we have the Windows 1803 IDXGIFactory6 interface
  172. ComPtr<IDXGIFactory6> factory6;
  173. if (SUCCEEDED(mDXGIFactory->QueryInterface(IID_PPV_ARGS(&factory6))))
  174. {
  175. for (UINT index = 0; DXGI_ERROR_NOT_FOUND != factory6->EnumAdapterByGpuPreference(index, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&adapter)); ++index)
  176. {
  177. DXGI_ADAPTER_DESC1 desc;
  178. adapter->GetDesc1(&desc);
  179. // We don't want software renderers
  180. if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)
  181. continue;
  182. // Check to see whether the adapter supports Direct3D 12
  183. if (SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&mDevice))))
  184. break;
  185. }
  186. }
  187. else
  188. {
  189. // Fall back to the older method that may not get the fastest GPU
  190. for (UINT index = 0; DXGI_ERROR_NOT_FOUND != mDXGIFactory->EnumAdapters1(index, &adapter); ++index)
  191. {
  192. DXGI_ADAPTER_DESC1 desc;
  193. adapter->GetDesc1(&desc);
  194. // We don't want software renderers
  195. if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)
  196. continue;
  197. // Check to see whether the adapter supports Direct3D 12
  198. if (SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&mDevice))))
  199. break;
  200. }
  201. }
  202. #ifdef _DEBUG
  203. // Enable breaking on errors
  204. ComPtr<ID3D12InfoQueue> pInfoQueue;
  205. if (SUCCEEDED(mDevice.As(&pInfoQueue)))
  206. {
  207. pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_CORRUPTION, TRUE);
  208. pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, TRUE);
  209. pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_WARNING, TRUE);
  210. }
  211. #endif // _DEBUG
  212. // Disable full screen transitions
  213. FatalErrorIfFailed(mDXGIFactory->MakeWindowAssociation(mhWnd, DXGI_MWA_NO_ALT_ENTER));
  214. // Create heaps
  215. mRTVHeap.Init(mDevice.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_RTV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 2);
  216. mDSVHeap.Init(mDevice.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_DSV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 4);
  217. mSRVHeap.Init(mDevice.Get(), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 128);
  218. // Create a command queue
  219. D3D12_COMMAND_QUEUE_DESC queue_desc = {};
  220. queue_desc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
  221. queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
  222. FatalErrorIfFailed(mDevice->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&mCommandQueue)));
  223. // Create a command allocator for each frame
  224. for (uint n = 0; n < cFrameCount; n++)
  225. FatalErrorIfFailed(mDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&mCommandAllocators[n])));
  226. // Describe and create the swap chain
  227. DXGI_SWAP_CHAIN_DESC swap_chain_desc = {};
  228. swap_chain_desc.BufferCount = cFrameCount;
  229. swap_chain_desc.BufferDesc.Width = mWindowWidth;
  230. swap_chain_desc.BufferDesc.Height = mWindowHeight;
  231. swap_chain_desc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  232. swap_chain_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  233. swap_chain_desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
  234. swap_chain_desc.OutputWindow = mhWnd;
  235. swap_chain_desc.SampleDesc.Count = 1;
  236. swap_chain_desc.Windowed = TRUE;
  237. ComPtr<IDXGISwapChain> swap_chain;
  238. FatalErrorIfFailed(mDXGIFactory->CreateSwapChain(mCommandQueue.Get(), &swap_chain_desc, &swap_chain));
  239. FatalErrorIfFailed(swap_chain.As(&mSwapChain));
  240. mFrameIndex = mSwapChain->GetCurrentBackBufferIndex();
  241. CreateRenterTargets();
  242. CreateDepthBuffer();
  243. // Create a root signature suitable for all our shaders
  244. D3D12_ROOT_PARAMETER params[3] = {};
  245. // Mapping a constant buffer to slot 0 for the vertex shader
  246. params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
  247. params[0].Descriptor.ShaderRegister = 0;
  248. params[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
  249. // Mapping a constant buffer to slot 1 in the pixel shader
  250. params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
  251. params[1].Descriptor.ShaderRegister = 1;
  252. params[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  253. // Mapping a texture to slot 2 in the pixel shader
  254. D3D12_DESCRIPTOR_RANGE range = {};
  255. range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
  256. range.BaseShaderRegister = 2;
  257. range.NumDescriptors = 1;
  258. params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
  259. params[2].DescriptorTable.NumDescriptorRanges = 1;
  260. params[2].DescriptorTable.pDescriptorRanges = &range;
  261. params[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  262. D3D12_STATIC_SAMPLER_DESC samplers[3] = {};
  263. // Sampler 0: Non-wrapping linear filtering
  264. samplers[0].Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
  265. samplers[0].AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
  266. samplers[0].AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
  267. samplers[0].AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
  268. samplers[0].MipLODBias = 0.0f;
  269. samplers[0].MaxAnisotropy = 1;
  270. samplers[0].ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS;
  271. samplers[0].BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK;
  272. samplers[0].MinLOD = 0.0f;
  273. samplers[0].MaxLOD = D3D12_FLOAT32_MAX;
  274. samplers[0].ShaderRegister = 0;
  275. samplers[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
  276. // Sampler 1: Wrapping and linear filtering
  277. samplers[1] = samplers[0];
  278. samplers[1].AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
  279. samplers[1].AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
  280. samplers[1].AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
  281. samplers[1].ShaderRegister = 1;
  282. // Sampler 2: Point filtering, using SampleCmp mode to compare if sampled value <= reference value (for shadows)
  283. samplers[2] = samplers[0];
  284. samplers[2].Filter = D3D12_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT;
  285. samplers[2].ComparisonFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL;
  286. samplers[2].ShaderRegister = 2;
  287. D3D12_ROOT_SIGNATURE_DESC root_signature_desc = {};
  288. root_signature_desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
  289. root_signature_desc.NumParameters = ARRAYSIZE(params);
  290. root_signature_desc.pParameters = params;
  291. root_signature_desc.NumStaticSamplers = ARRAYSIZE(samplers);
  292. root_signature_desc.pStaticSamplers = samplers;
  293. ComPtr<ID3DBlob> signature;
  294. ComPtr<ID3DBlob> error;
  295. FatalErrorIfFailed(D3D12SerializeRootSignature(&root_signature_desc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error));
  296. FatalErrorIfFailed(mDevice->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&mRootSignature)));
  297. // Create the command list
  298. FatalErrorIfFailed(mDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, mCommandAllocators[mFrameIndex].Get(), nullptr, IID_PPV_ARGS(&mCommandList)));
  299. // Command lists are created in the recording state, but there is nothing to record yet. The main loop expects it to be closed, so close it now
  300. FatalErrorIfFailed(mCommandList->Close());
  301. // Create synchronization object
  302. FatalErrorIfFailed(mDevice->CreateFence(mFenceValues[mFrameIndex], D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&mFence)));
  303. // Increment fence value so we don't skip waiting the first time a command list is executed
  304. mFenceValues[mFrameIndex]++;
  305. // Create an event handle to use for frame synchronization
  306. mFenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
  307. if (mFenceEvent == nullptr)
  308. FatalErrorIfFailed(HRESULT_FROM_WIN32(GetLastError()));
  309. // Initialize the queue used to upload resources to the GPU
  310. mUploadQueue.Initialize(mDevice.Get());
  311. // Create constant buffer. One per frame to avoid overwriting the constant buffer while the GPU is still using it.
  312. for (uint n = 0; n < cFrameCount; ++n)
  313. {
  314. mVertexShaderConstantBufferProjection[n] = CreateConstantBuffer(sizeof(VertexShaderConstantBuffer));
  315. mVertexShaderConstantBufferOrtho[n] = CreateConstantBuffer(sizeof(VertexShaderConstantBuffer));
  316. mPixelShaderConstantBuffer[n] = CreateConstantBuffer(sizeof(PixelShaderConstantBuffer));
  317. }
  318. // Store global renderer now that we're done initializing
  319. sRenderer = this;
  320. }
  321. void Renderer::OnWindowResize()
  322. {
  323. // Wait for the previous frame to be rendered
  324. WaitForGpu();
  325. // Get new window size
  326. RECT rc;
  327. GetClientRect(mhWnd, &rc);
  328. mWindowWidth = max<LONG>(rc.right - rc.left, 8);
  329. mWindowHeight = max<LONG>(rc.bottom - rc.top, 8);
  330. // Free the render targets and views to allow resizing the swap chain
  331. for (uint n = 0; n < cFrameCount; ++n)
  332. {
  333. mRTVHeap.Free(mRenderTargetViews[n]);
  334. mRenderTargets[n].Reset();
  335. }
  336. // Resize the swap chain buffers
  337. FatalErrorIfFailed(mSwapChain->ResizeBuffers(cFrameCount, mWindowWidth, mWindowHeight, DXGI_FORMAT_R8G8B8A8_UNORM, 0));
  338. // Back buffer index may have changed after the resize (it always seems to go to 0 again)
  339. mFrameIndex = mSwapChain->GetCurrentBackBufferIndex();
  340. // Since we may have switched frame index and we know everything is done, we need to update the fence value for our other frame as completed
  341. for (uint n = 0; n < cFrameCount; ++n)
  342. if (mFrameIndex != n)
  343. mFenceValues[n] = mFence->GetCompletedValue();
  344. // Recreate render targets
  345. CreateRenterTargets();
  346. // Recreate depth buffer
  347. CreateDepthBuffer();
  348. }
  349. void Renderer::BeginFrame(const CameraState &inCamera, float inWorldScale)
  350. {
  351. JPH_PROFILE_FUNCTION();
  352. // Store state
  353. mCameraState = inCamera;
  354. // Reset command allocator
  355. FatalErrorIfFailed(mCommandAllocators[mFrameIndex]->Reset());
  356. // Reset command list
  357. FatalErrorIfFailed(mCommandList->Reset(mCommandAllocators[mFrameIndex].Get(), nullptr));
  358. // Set root signature
  359. mCommandList->SetGraphicsRootSignature(mRootSignature.Get());
  360. // Set SRV heap
  361. ID3D12DescriptorHeap *heaps[] = { mSRVHeap.Get() };
  362. mCommandList->SetDescriptorHeaps(_countof(heaps), heaps);
  363. // Indicate that the back buffer will be used as a render target.
  364. D3D12_RESOURCE_BARRIER barrier;
  365. barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  366. barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
  367. barrier.Transition.pResource = mRenderTargets[mFrameIndex].Get();
  368. barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT;
  369. barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET;
  370. barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
  371. mCommandList->ResourceBarrier(1, &barrier);
  372. // Set the main back buffer as render target
  373. SetRenderTarget(nullptr);
  374. // Clear the back buffer.
  375. const float blue[] = { 0.098f, 0.098f, 0.439f, 1.000f };
  376. mCommandList->ClearRenderTargetView(mRenderTargetViews[mFrameIndex], blue, 0, nullptr);
  377. mCommandList->ClearDepthStencilView(mDepthStencilView, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr);
  378. // Light properties
  379. Vec3 light_pos = inWorldScale * Vec3(250, 250, 250);
  380. Vec3 light_tgt = Vec3::sZero();
  381. Vec3 light_up = Vec3(0, 1, 0);
  382. Vec3 light_fwd = (light_tgt - light_pos).Normalized();
  383. float light_fov = DegreesToRadians(20.0f);
  384. float light_near = 1.0f;
  385. float light_far = 1000.0f;
  386. // Camera properties
  387. float camera_fovy = inCamera.mFOVY;
  388. float camera_aspect = static_cast<float>(GetWindowWidth()) / GetWindowHeight();
  389. float camera_fovx = 2.0f * atan(camera_aspect * tan(0.5f * camera_fovy));
  390. float camera_near = 0.01f * inWorldScale;
  391. float camera_far = inCamera.mFarPlane * inWorldScale;
  392. // Set constants for vertex shader in projection mode
  393. VertexShaderConstantBuffer *vs = mVertexShaderConstantBufferProjection[mFrameIndex]->Map<VertexShaderConstantBuffer>();
  394. // Camera projection and view
  395. DirectX::XMStoreFloat4x4(
  396. &vs->mProjection,
  397. DirectX::XMMatrixPerspectiveFovRH(
  398. camera_fovy,
  399. camera_aspect,
  400. camera_near,
  401. camera_far));
  402. Vec3 tgt = inCamera.mPos + inCamera.mForward;
  403. DirectX::XMStoreFloat4x4(
  404. &vs->mView,
  405. DirectX::XMMatrixLookAtRH(reinterpret_cast<const DirectX::XMVECTOR &>(inCamera.mPos), reinterpret_cast<const DirectX::XMVECTOR &>(tgt), reinterpret_cast<const DirectX::XMVECTOR &>(inCamera.mUp)));
  406. // Light projection and view
  407. DirectX::XMStoreFloat4x4(
  408. &vs->mLightProjection,
  409. DirectX::XMMatrixPerspectiveFovRH(
  410. light_fov,
  411. 1.0f,
  412. light_near,
  413. light_far));
  414. DirectX::XMStoreFloat4x4(
  415. &vs->mLightView,
  416. DirectX::XMMatrixLookAtRH(reinterpret_cast<const DirectX::XMVECTOR &>(light_pos), reinterpret_cast<const DirectX::XMVECTOR &>(light_tgt), reinterpret_cast<const DirectX::XMVECTOR &>(light_up)));
  417. mVertexShaderConstantBufferProjection[mFrameIndex]->Unmap();
  418. // Set constants for vertex shader in ortho mode
  419. vs = mVertexShaderConstantBufferOrtho[mFrameIndex]->Map<VertexShaderConstantBuffer>();
  420. // Camera projection and view
  421. DirectX::XMStoreFloat4x4(
  422. &vs->mProjection,
  423. DirectX::XMMatrixOrthographicOffCenterRH(
  424. 0.0f,
  425. float(mWindowWidth),
  426. float(mWindowHeight),
  427. 0.0f,
  428. 0.0f,
  429. 1.0f));
  430. DirectX::XMStoreFloat4x4(
  431. &vs->mView,
  432. DirectX::XMMatrixIdentity());
  433. // Light projection and view are unused in ortho mode
  434. DirectX::XMStoreFloat4x4(
  435. &vs->mLightView,
  436. DirectX::XMMatrixIdentity());
  437. DirectX::XMStoreFloat4x4(
  438. &vs->mLightProjection,
  439. DirectX::XMMatrixIdentity());
  440. mVertexShaderConstantBufferOrtho[mFrameIndex]->Unmap();
  441. // Switch to 3d projection mode
  442. SetProjectionMode();
  443. // Set constants for pixel shader
  444. PixelShaderConstantBuffer *ps = mPixelShaderConstantBuffer[mFrameIndex]->Map<PixelShaderConstantBuffer>();
  445. ps->mCameraPos = DirectX::XMFLOAT4(inCamera.mPos.GetX(), inCamera.mPos.GetY(), inCamera.mPos.GetZ(), 0);
  446. ps->mLightPos = DirectX::XMFLOAT4(light_pos.GetX(), light_pos.GetY(), light_pos.GetZ(), 0);
  447. mPixelShaderConstantBuffer[mFrameIndex]->Unmap();
  448. // Set the pixel shader constant buffer data.
  449. mPixelShaderConstantBuffer[mFrameIndex]->Bind(1);
  450. // Calculate camera frustum
  451. mCameraFrustum = Frustum(inCamera.mPos, inCamera.mForward, inCamera.mUp, camera_fovx, camera_fovy, camera_near, camera_far);
  452. // Calculate light frustum
  453. mLightFrustum = Frustum(light_pos, light_fwd, light_up, light_fov, light_fov, light_near, light_far);
  454. }
  455. void Renderer::EndFrame()
  456. {
  457. JPH_PROFILE_FUNCTION();
  458. // Indicate that the back buffer will now be used to present.
  459. D3D12_RESOURCE_BARRIER barrier;
  460. barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  461. barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
  462. barrier.Transition.pResource = mRenderTargets[mFrameIndex].Get();
  463. barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
  464. barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT;
  465. barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
  466. mCommandList->ResourceBarrier(1, &barrier);
  467. // Close the command list
  468. FatalErrorIfFailed(mCommandList->Close());
  469. // Execute the command list
  470. ID3D12CommandList* command_lists[] = { mCommandList.Get() };
  471. mCommandQueue->ExecuteCommandLists(_countof(command_lists), command_lists);
  472. // Present the frame
  473. FatalErrorIfFailed(mSwapChain->Present(1, 0));
  474. // Schedule a Signal command in the queue
  475. UINT64 current_fence_value = mFenceValues[mFrameIndex];
  476. FatalErrorIfFailed(mCommandQueue->Signal(mFence.Get(), current_fence_value));
  477. // Update the frame index
  478. mFrameIndex = mSwapChain->GetCurrentBackBufferIndex();
  479. // If the next frame is not ready to be rendered yet, wait until it is ready
  480. UINT64 completed_value = mFence->GetCompletedValue();
  481. if (completed_value < mFenceValues[mFrameIndex])
  482. {
  483. FatalErrorIfFailed(mFence->SetEventOnCompletion(mFenceValues[mFrameIndex], mFenceEvent));
  484. WaitForSingleObjectEx(mFenceEvent, INFINITE, FALSE);
  485. }
  486. // Release all used resources
  487. mDelayReleased[mFrameIndex].clear();
  488. // Anything that's not used yet can be removed, delayed objects are now available
  489. mResourceCache.clear();
  490. mDelayCached[mFrameIndex].swap(mResourceCache);
  491. // Set the fence value for the next frame.
  492. mFenceValues[mFrameIndex] = current_fence_value + 1;
  493. }
  494. void Renderer::SetProjectionMode()
  495. {
  496. mVertexShaderConstantBufferProjection[mFrameIndex]->Bind(0);
  497. }
  498. void Renderer::SetOrthoMode()
  499. {
  500. mVertexShaderConstantBufferOrtho[mFrameIndex]->Bind(0);
  501. }
  502. Ref<Texture> Renderer::CreateTexture(const Surface *inSurface)
  503. {
  504. return new Texture(this, inSurface);
  505. }
  506. Ref<Texture> Renderer::CreateRenderTarget(int inWidth, int inHeight)
  507. {
  508. return new Texture(this, inWidth, inHeight);
  509. }
  510. void Renderer::SetRenderTarget(Texture *inRenderTarget)
  511. {
  512. // Unset the previous render target
  513. if (mRenderTargetTexture != nullptr)
  514. mRenderTargetTexture->SetAsRenderTarget(false);
  515. mRenderTargetTexture = nullptr;
  516. if (inRenderTarget == nullptr)
  517. {
  518. // Set the main back buffer as render target
  519. mCommandList->OMSetRenderTargets(1, &mRenderTargetViews[mFrameIndex], FALSE, &mDepthStencilView);
  520. // Set viewport
  521. D3D12_VIEWPORT viewport = { 0.0f, 0.0f, static_cast<float>(mWindowWidth), static_cast<float>(mWindowHeight), 0.0f, 1.0f };
  522. mCommandList->RSSetViewports(1, &viewport);
  523. // Set scissor rect
  524. D3D12_RECT scissor_rect = { 0, 0, static_cast<LONG>(mWindowWidth), static_cast<LONG>(mWindowHeight) };
  525. mCommandList->RSSetScissorRects(1, &scissor_rect);
  526. }
  527. else
  528. {
  529. // Use the texture as render target
  530. inRenderTarget->SetAsRenderTarget(true);
  531. mRenderTargetTexture = inRenderTarget;
  532. }
  533. }
  534. ComPtr<ID3DBlob> Renderer::CreateVertexShader(const char *inFileName)
  535. {
  536. UINT flags = D3DCOMPILE_ENABLE_STRICTNESS;
  537. #ifdef _DEBUG
  538. flags |= D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION;
  539. #endif
  540. const D3D_SHADER_MACRO defines[] =
  541. {
  542. { nullptr, nullptr }
  543. };
  544. // Read shader source file
  545. vector<uint8> data = ReadData(inFileName);
  546. // Compile source
  547. ComPtr<ID3DBlob> shader_blob, error_blob;
  548. HRESULT hr = D3DCompile(&data[0],
  549. (uint)data.size(),
  550. inFileName,
  551. defines,
  552. D3D_COMPILE_STANDARD_FILE_INCLUDE,
  553. "main",
  554. "vs_5_0",
  555. flags,
  556. 0,
  557. shader_blob.GetAddressOf(),
  558. error_blob.GetAddressOf());
  559. if (FAILED(hr))
  560. {
  561. // Throw error if compilation failed
  562. if (error_blob)
  563. OutputDebugStringA((const char *)error_blob->GetBufferPointer());
  564. FatalError("Failed to compile vertex shader");
  565. }
  566. return shader_blob;
  567. }
  568. ComPtr<ID3DBlob> Renderer::CreatePixelShader(const char *inFileName)
  569. {
  570. UINT flags = D3DCOMPILE_ENABLE_STRICTNESS;
  571. #ifdef _DEBUG
  572. flags |= D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION;
  573. #endif
  574. const D3D_SHADER_MACRO defines[] =
  575. {
  576. { nullptr, nullptr }
  577. };
  578. // Read shader source file
  579. vector<uint8> data = ReadData(inFileName);
  580. // Compile source
  581. ComPtr<ID3DBlob> shader_blob, error_blob;
  582. HRESULT hr = D3DCompile(&data[0],
  583. (uint)data.size(),
  584. inFileName,
  585. defines,
  586. D3D_COMPILE_STANDARD_FILE_INCLUDE,
  587. "main",
  588. "ps_5_0",
  589. flags,
  590. 0,
  591. shader_blob.GetAddressOf(),
  592. error_blob.GetAddressOf());
  593. if (FAILED(hr))
  594. {
  595. // Throw error if compilation failed
  596. if (error_blob)
  597. OutputDebugStringA((const char *)error_blob->GetBufferPointer());
  598. FatalError("Failed to compile pixel shader");
  599. }
  600. return shader_blob;
  601. }
  602. unique_ptr<ConstantBuffer> Renderer::CreateConstantBuffer(uint inBufferSize)
  603. {
  604. return make_unique<ConstantBuffer>(this, inBufferSize);
  605. }
  606. unique_ptr<PipelineState> Renderer::CreatePipelineState(ID3DBlob *inVertexShader, const D3D12_INPUT_ELEMENT_DESC *inInputDescription, uint inInputDescriptionCount, ID3DBlob *inPixelShader, D3D12_FILL_MODE inFillMode, D3D12_PRIMITIVE_TOPOLOGY_TYPE inTopology, PipelineState::EDepthTest inDepthTest, PipelineState::EBlendMode inBlendMode, PipelineState::ECullMode inCullMode)
  607. {
  608. return make_unique<PipelineState>(this, inVertexShader, inInputDescription, inInputDescriptionCount, inPixelShader, inFillMode, inTopology, inDepthTest, inBlendMode, inCullMode);
  609. }
  610. ComPtr<ID3D12Resource> Renderer::CreateD3DResource(D3D12_HEAP_TYPE inHeapType, D3D12_RESOURCE_STATES inResourceState, uint64 inSize)
  611. {
  612. // Create a new resource
  613. D3D12_RESOURCE_DESC desc;
  614. desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  615. desc.Alignment = 0;
  616. desc.Width = inSize;
  617. desc.Height = 1;
  618. desc.DepthOrArraySize = 1;
  619. desc.MipLevels = 1;
  620. desc.Format = DXGI_FORMAT_UNKNOWN;
  621. desc.SampleDesc.Count = 1;
  622. desc.SampleDesc.Quality = 0;
  623. desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  624. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  625. D3D12_HEAP_PROPERTIES heap_properties = {};
  626. heap_properties.Type = inHeapType;
  627. heap_properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
  628. heap_properties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
  629. heap_properties.CreationNodeMask = 1;
  630. heap_properties.VisibleNodeMask = 1;
  631. ComPtr<ID3D12Resource> resource;
  632. FatalErrorIfFailed(mDevice->CreateCommittedResource(&heap_properties, D3D12_HEAP_FLAG_NONE, &desc, inResourceState, nullptr, IID_PPV_ARGS(&resource)));
  633. return resource;
  634. }
  635. void Renderer::CopyD3DResource(ID3D12Resource *inDest, const void *inSrc, uint64 inSize)
  636. {
  637. // Copy data to destination buffer
  638. void *data;
  639. D3D12_RANGE range = { 0, 0 }; // We're not going to read
  640. FatalErrorIfFailed(inDest->Map(0, &range, &data));
  641. memcpy(data, inSrc, inSize);
  642. inDest->Unmap(0, nullptr);
  643. }
  644. void Renderer::CopyD3DResource(ID3D12Resource *inDest, ID3D12Resource *inSrc, uint64 inSize)
  645. {
  646. // Start a commandlist for the upload
  647. ID3D12GraphicsCommandList *list = mUploadQueue.Start();
  648. // Copy the data to the GPU
  649. list->CopyBufferRegion(inDest, 0, inSrc, 0, inSize);
  650. // Change the state of the resource to generic read
  651. D3D12_RESOURCE_BARRIER barrier;
  652. barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
  653. barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
  654. barrier.Transition.pResource = inDest;
  655. barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST;
  656. barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_GENERIC_READ;
  657. barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
  658. list->ResourceBarrier(1, &barrier);
  659. // Wait for copying to finish
  660. mUploadQueue.ExecuteAndWait();
  661. }
  662. ComPtr<ID3D12Resource> Renderer::CreateD3DResourceOnDefaultHeap(const void *inData, uint64 inSize)
  663. {
  664. ComPtr<ID3D12Resource> upload = CreateD3DResourceOnUploadHeap(inSize);
  665. ComPtr<ID3D12Resource> resource = CreateD3DResource(D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST, inSize);
  666. CopyD3DResource(upload.Get(), inData, inSize);
  667. CopyD3DResource(resource.Get(), upload.Get(), inSize);
  668. RecycleD3DResourceOnUploadHeap(upload.Get(), inSize);
  669. return resource;
  670. }
  671. ComPtr<ID3D12Resource> Renderer::CreateD3DResourceOnUploadHeap(uint64 inSize)
  672. {
  673. // Try cache first
  674. ResourceCache::iterator i = mResourceCache.find(inSize);
  675. if (i != mResourceCache.end() && !i->second.empty())
  676. {
  677. ComPtr<ID3D12Resource> resource = i->second.back();
  678. i->second.pop_back();
  679. return resource;
  680. }
  681. return CreateD3DResource(D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, inSize);
  682. }
  683. void Renderer::RecycleD3DResourceOnUploadHeap(ID3D12Resource *inResource, uint64 inSize)
  684. {
  685. if (!mIsExiting)
  686. mDelayCached[mFrameIndex][inSize].push_back(inResource);
  687. }
  688. void Renderer::RecycleD3DObject(ID3D12Object *inResource)
  689. {
  690. if (!mIsExiting)
  691. mDelayReleased[mFrameIndex].push_back(inResource);
  692. }