Renderer.h 8.1 KB

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