Renderer.h 8.1 KB

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