Renderer.cpp 28 KB

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