Renderer.h 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Image/Surface.h>
  5. #include <Renderer/Frustum.h>
  6. #include <Renderer/ConstantBuffer.h>
  7. #include <Renderer/PipelineState.h>
  8. #include <Renderer/CommandQueue.h>
  9. #include <Renderer/DescriptorHeap.h>
  10. // Forward declares
  11. class Texture;
  12. /// Camera setup
  13. struct CameraState
  14. {
  15. CameraState() : mPos(Vec3::sZero()), mForward(0, 0, -1), mUp(0, 1, 0), mFOVY(DegreesToRadians(70.0f)), mFarPlane(100.0f) { }
  16. Vec3 mPos; ///< Camera position
  17. Vec3 mForward; ///< Camera forward vector
  18. Vec3 mUp; ///< Camera up vector
  19. float mFOVY; ///< Field of view in radians in up direction
  20. float mFarPlane; ///< Distance of far plane
  21. };
  22. /// Responsible for rendering primitives to the screen
  23. class Renderer
  24. {
  25. public:
  26. /// Destructor
  27. ~Renderer();
  28. /// Initialize DirectX
  29. void Initialize();
  30. /// Callback when the window resizes and the back buffer needs to be adjusted
  31. void OnWindowResize();
  32. /// Get window size
  33. int GetWindowWidth() { return mWindowWidth; }
  34. int GetWindowHeight() { return mWindowHeight; }
  35. /// Access to the window handle
  36. HWND GetWindowHandle() const { return mhWnd; }
  37. /// Access to the most important DirectX structures
  38. ID3D12Device * GetDevice() { return mDevice.Get(); }
  39. ID3D12RootSignature * GetRootSignature() { return mRootSignature.Get(); }
  40. ID3D12GraphicsCommandList * GetCommandList() { return mCommandList.Get(); }
  41. CommandQueue & GetUploadQueue() { return mUploadQueue; }
  42. DescriptorHeap & GetDSVHeap() { return mDSVHeap; }
  43. DescriptorHeap & GetSRVHeap() { return mSRVHeap; }
  44. /// Start / end drawing a frame
  45. void BeginFrame(const CameraState &inCamera, float inWorldScale);
  46. void EndFrame();
  47. /// Switch between orthographic and 3D projection mode
  48. void SetProjectionMode();
  49. void SetOrthoMode();
  50. /// Create texture from an image surface
  51. Ref<Texture> CreateTexture(const Surface *inSurface);
  52. /// Create a texture to render to (currently depth buffer only)
  53. Ref<Texture> CreateRenderTarget(int inWidth, int inHeight);
  54. /// Change the render target to a texture. Use nullptr to set back to the main render target.
  55. void SetRenderTarget(Texture *inRenderTarget);
  56. /// Compile a vertex shader
  57. ComPtr<ID3DBlob> CreateVertexShader(const char *inFileName);
  58. /// Compile a pixel shader
  59. ComPtr<ID3DBlob> CreatePixelShader(const char *inFileName);
  60. /// Create a constant buffer for the shader
  61. unique_ptr<ConstantBuffer> CreateConstantBuffer(uint inBufferSize);
  62. /// Create pipeline state object that defines the complete state of how primitives should be rendered
  63. unique_ptr<PipelineState> 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);
  64. /// Get the camera state / frustum (only valid between BeginFrame() / EndFrame())
  65. const CameraState & GetCameraState() const { return mCameraState; }
  66. const Frustum & GetCameraFrustum() const { return mCameraFrustum; }
  67. /// Get the light frustum (only valid between BeginFrame() / EndFrame())
  68. const Frustum & GetLightFrustum() const { return mLightFrustum; }
  69. /// How many frames our pipeline is
  70. static const uint cFrameCount = 2;
  71. /// Which frame is currently rendering (to keep track of which buffers are free to overwrite)
  72. uint GetCurrentFrameIndex() const { return mFrameIndex; }
  73. /// Create a buffer on the default heap (usable for permanent buffers)
  74. ComPtr<ID3D12Resource> CreateD3DResourceOnDefaultHeap(const void *inData, uint64 inSize);
  75. /// Create buffer on the upload heap (usable for temporary buffers).
  76. ComPtr<ID3D12Resource> CreateD3DResourceOnUploadHeap(uint64 inSize);
  77. /// Recycle a buffer on the upload heap. This puts it back in a cache and will reuse it when it is certain the GPU is no longer referencing it.
  78. void RecycleD3DResourceOnUploadHeap(ID3D12Resource *inResource, uint64 inSize);
  79. /// Keeps a reference to the resource until the current frame has finished
  80. void RecycleD3DObject(ID3D12Object *inResource);
  81. private:
  82. // Wait for pending GPU work to complete
  83. void WaitForGpu();
  84. // Create render targets and their views
  85. void CreateRenterTargets();
  86. // Create a depth buffer for the back buffer
  87. void CreateDepthBuffer();
  88. // Function to create a ID3D12Resource on specified heap with specified state
  89. ComPtr<ID3D12Resource> CreateD3DResource(D3D12_HEAP_TYPE inHeapType, D3D12_RESOURCE_STATES inResourceState, uint64 inSize);
  90. // Copy CPU memory into a ID3D12Resource
  91. void CopyD3DResource(ID3D12Resource *inDest, const void *inSrc, uint64 inSize);
  92. // Copy a CPU resource to a GPU resource
  93. void CopyD3DResource(ID3D12Resource *inDest, ID3D12Resource *inSrc, uint64 inSize);
  94. HWND mhWnd;
  95. int mWindowWidth = 1920;
  96. int mWindowHeight = 1080;
  97. unique_ptr<ConstantBuffer> mVertexShaderConstantBufferProjection[cFrameCount];
  98. unique_ptr<ConstantBuffer> mVertexShaderConstantBufferOrtho[cFrameCount];
  99. unique_ptr<ConstantBuffer> mPixelShaderConstantBuffer[cFrameCount];
  100. CameraState mCameraState;
  101. Frustum mCameraFrustum;
  102. Frustum mLightFrustum;
  103. // DirectX interfaces
  104. ComPtr<IDXGIFactory4> mDXGIFactory;
  105. ComPtr<ID3D12Device> mDevice;
  106. DescriptorHeap mRTVHeap; ///< Render target view heap
  107. DescriptorHeap mDSVHeap; ///< Depth stencil view heap
  108. DescriptorHeap mSRVHeap; ///< Shader resource view heap
  109. ComPtr<IDXGISwapChain3> mSwapChain;
  110. ComPtr<ID3D12Resource> mRenderTargets[cFrameCount]; ///< Two render targets (we're double buffering in order for the CPU to continue while the GPU is rendering)
  111. D3D12_CPU_DESCRIPTOR_HANDLE mRenderTargetViews[cFrameCount]; ///< The two render views corresponding to the render targets
  112. ComPtr<ID3D12Resource> mDepthStencilBuffer; ///< The main depth buffer
  113. D3D12_CPU_DESCRIPTOR_HANDLE mDepthStencilView { 0 }; ///< A view for binding the depth buffer
  114. ComPtr<ID3D12CommandAllocator> mCommandAllocators[cFrameCount]; ///< Two command allocator lists (one per frame)
  115. ComPtr<ID3D12CommandQueue> mCommandQueue; ///< The command queue that will execute commands (there's only 1 since we want to finish rendering 1 frame before moving onto the next)
  116. ComPtr<ID3D12GraphicsCommandList> mCommandList; ///< The command list
  117. ComPtr<ID3D12RootSignature> mRootSignature; ///< The root signature, we have a simple application so we only need 1, which is suitable for all our shaders
  118. Ref<Texture> mRenderTargetTexture; ///< When rendering to a texture, this is the active texture
  119. CommandQueue mUploadQueue; ///< Queue used to upload resources to GPU memory
  120. // Synchronization objects used to finish rendering and swapping before reusing a command queue
  121. uint mFrameIndex; ///< Current frame index (0 or 1)
  122. HANDLE mFenceEvent; ///< Fence event to wait for the previous frame rendering to complete (in order to free 1 of the buffers)
  123. ComPtr<ID3D12Fence> mFence; ///< Fence object, used to signal the end of a frame
  124. UINT64 mFenceValues[cFrameCount] = {}; ///< Values that were used to signal completion of one of the two frames
  125. using ResourceCache = unordered_map<uint64, vector<ComPtr<ID3D12Resource>>>;
  126. ResourceCache mResourceCache; ///< Cache items ready to be reused
  127. ResourceCache mDelayCached[cFrameCount]; ///< List of reusable ID3D12Resources that are potentially referenced by the GPU so can be used only when the GPU finishes
  128. vector<ComPtr<ID3D12Object>> mDelayReleased[cFrameCount]; ///< Objects that are potentially referenced by the GPU so can only be freed when the GPU finishes
  129. bool mIsExiting = false; ///< When exiting we don't want to add references too buffers
  130. };