SleakEngine 0.1.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
DirectX12Renderer.hpp
Go to the documentation of this file.
1#include <Core/OSDef.hpp>
2
3#ifdef PLATFORM_WIN
4
5#ifndef _DIRECTX12RENDERER_H
6#define _DIRECTX12RENDERER_H
7
8#include <backends/imgui_impl_dx12.h>
9#include <d3d12.h>
10#include <d3dcompiler.h>
11#include <dxgi1_4.h>
12#include <imgui.h>
13#include <wrl/client.h>
14
15#include <Core/Window.hpp>
16#include <cstdint>
17#include <utility>
18#include <vector>
19
28
29namespace Sleak {
30namespace RenderEngine {
31
32/// D3D12 backend: explicit command lists, per-frame allocators, and a shared SRV descriptor heap.
33class ENGINE_API DirectX12Renderer : public Renderer, public RenderContext {
34public:
35 DirectX12Renderer(Window* window);
36 virtual ~DirectX12Renderer();
37
38 bool Initialize() override;
39 void BeginRender() override;
40 void EndRender() override;
41 void Cleanup() override;
42 void WaitIdle() override { WaitForGPU(); }
43#ifdef SLEAK_HOT_RELOAD
44 /// Rebuilds the PSOs of live shaders and fixed passes using the stems.
45 bool ReloadShaders(const std::vector<std::string>& stems) override;
46#endif
47
48 virtual void Resize(uint32_t width, uint32_t height) override;
49
50 /// True if the current adapter/driver supports D3D12 feature level 11_0.
51 static bool IsSupport();
52
53 virtual bool CreateImGUI() override;
54
55 virtual RenderContext* GetContext() override { return this; }
56
57 // Feature capability mask
58 virtual uint32_t GetFeatureCaps() const override { return CapShadows; }
59
60 // RenderContext interface
61 virtual void Draw(uint32_t vertexCount) override;
62 virtual void Draw(uint32_t vertexCount, uint32_t firstVertex) override;
63 virtual void DrawIndexed(uint32_t indexCount) override;
64 virtual void DrawIndexed(uint32_t indexCount, uint32_t firstIndex,
65 int32_t baseVertex) override;
66 virtual void DrawInstance(uint32_t instanceCount,
67 uint32_t vertexPerInstance) override;
68 virtual void DrawIndexedInstance(uint32_t instanceCount,
69 uint32_t indexPerInstance) override;
70 virtual void DrawIndexedInstance(uint32_t instanceCount,
71 uint32_t indexPerInstance,
72 uint32_t firstIndex,
73 int32_t baseVertex) override;
74
75 virtual void SetRenderFace(RenderFace face) override;
76 virtual void SetRenderMode(RenderMode mode) override;
77 virtual void SetViewport(float x, float y, float width, float height,
78 float minDepth = 0.0f,
79 float maxDepth = 1.0f) override;
80 virtual void ClearRenderTarget(float r, float g, float b,
81 float a) override;
82 virtual void ClearDepthStencil(bool clearDepth, bool clearStencil,
83 float depth, uint8_t stencil) override;
84
85 virtual void BindVertexBuffer(RefPtr<BufferBase> buffer,
86 uint32_t slot = 0) override;
87 virtual void BindIndexBuffer(RefPtr<BufferBase> buffer,
88 uint32_t slot = 0) override;
89 virtual void BindConstantBuffer(RefPtr<BufferBase> buffer,
90 uint32_t slot = 0) override;
91
92 virtual BufferBase* CreateBuffer(BufferType Type, uint32_t size,
93 void* data) override;
94 virtual Shader* CreateShader(const std::string& shaderSource) override;
95 virtual Texture* CreateTexture(const std::string& TexturePath) override;
96 virtual Texture* CreateTextureFromData(uint32_t width, uint32_t height,
97 void* data) override;
98
99 /// Loads a cubemap from six face image paths.
100 Texture* CreateCubemapTexture(const std::array<std::string, 6>& facePaths);
101 /// Loads a cubemap by converting a single equirectangular panorama.
102 Texture* CreateCubemapTextureFromPanorama(const std::string& panoramaPath);
103
104 // Lighting/fog UBO (matches ShadowLightUBO from Vulkan path)
105 void UpdateShadowLightUBO(const void* data, uint32_t size) override;
106
107 // Skybox state management
108 virtual void BindTexture(RefPtr<Sleak::Texture> texture, uint32_t slot = 0) override;
109 virtual void BindTextureRaw(Sleak::Texture* texture, uint32_t slot = 0) override;
110 virtual void BeginSkyboxPass() override;
111 virtual void EndSkyboxPass() override;
112 virtual void BeginDebugLinePass() override;
113 virtual void EndDebugLinePass() override;
114
115 /// Sets a shader's PSO unless a skybox or debug line pass owns it.
116 void BindShaderPipeline(ID3D12PipelineState* pso);
117
118 private:
119 /// Fixed-function state that, with the shader bytecode, identifies a PSO.
120 struct PipelineKey {
121 uint64_t vsHash = 0;
122 uint64_t psHash = 0;
123 uint32_t vertexFormat = 0;
124 D3D12_CULL_MODE cullMode = D3D12_CULL_MODE_FRONT;
125 BOOL depthClip = TRUE;
126 INT depthBias = 0;
127 float depthBiasClamp = 0.0f;
128 float slopeScaledDepthBias = 0.0f;
129 D3D12_DEPTH_WRITE_MASK depthWrite = D3D12_DEPTH_WRITE_MASK_ALL;
130 D3D12_COMPARISON_FUNC depthFunc = D3D12_COMPARISON_FUNC_LESS;
131 BOOL blendEnable = FALSE;
132 D3D12_PRIMITIVE_TOPOLOGY_TYPE topology =
133 D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
134 DXGI_FORMAT rtvFormat = DXGI_FORMAT_R8G8B8A8_UNORM;
135 DXGI_FORMAT dsvFormat = DXGI_FORMAT_D32_FLOAT;
136
137 bool operator==(const PipelineKey&) const = default;
138 };
139
140 /// Returns the cached PSO for the key, building it on a miss.
141 ID3D12PipelineState* GetPipeline(const PipelineKey& key, ID3DBlob* vs,
142 ID3DBlob* ps);
143 /// Returns the default-state PSO for a vertex/pixel shader pair.
144 ID3D12PipelineState* GetShaderPipeline(ID3DBlob* vs, ID3DBlob* ps);
145#ifdef SLEAK_HOT_RELOAD
146 /// Recompiles live shaders using the stems, collecting their old PSOs.
147 void ReloadLiveShaders(const std::vector<std::string>& stems,
148 std::vector<ID3D12PipelineState*>& replaced);
149 /// Rebuilds a fixed pass PSO, keeping the old one on failure.
150 void ReloadPassPipeline(ID3D12PipelineState*& pso, bool& failed,
151 bool (DirectX12Renderer::*create)(),
152 const char* stem,
153 std::vector<ID3D12PipelineState*>& replaced);
154 /// Recompiles the shadow vertex shader and rebuilds the shadow PSO.
155 void ReloadShadowPassPSO(std::vector<ID3D12PipelineState*>& replaced);
156 /// Drops cached PSOs that were replaced and that nothing binds anymore.
157 void PruneReplacedPipelines(
158 const std::vector<ID3D12PipelineState*>& replaced);
159#endif
160 /// Reapplies the last shader PSO after a pass override ends.
161 void RestoreShaderPipeline();
162 /// Copies the light/fog constants into the ring and binds them at b2.
163 void BindLightConstants();
164
165 /// Creates the DXGI factory, enumerates adapters, and creates the D3D12 device.
166 bool CreateDevice();
167 bool CreateCommandQueue();
168 /// Creates the swapchain and its per-frame buffers.
169 bool CreateSwapChain();
170 /// Creates per-frame command allocators and the shared graphics command list.
171 bool CreateCommandAllocatorAndList();
172 /// Creates the RTV heap and a render target view for each swapchain buffer.
173 bool CreateRenderTargetViews();
174 bool CreateDepthStencilView();
175 bool CreateFence();
176 bool CreateRootSignature();
177
178 virtual void ConfigureRenderMode() override;
179 virtual void ConfigureRenderFace() override;
180
181 /// Signals the fence and blocks the CPU until the GPU catches up.
182 void WaitForGPU();
183 /// Logs available DXGI adapters and picks the current one for device creation.
184 void EnumerateDevices(Microsoft::WRL::ComPtr<IDXGIFactory4> factory);
185
186 // Frame count (must be declared before arrays that use it)
187 static constexpr UINT FrameCount = 2;
188
189 // Device and swap chain
190 Microsoft::WRL::ComPtr<ID3D12Device> device;
191 Microsoft::WRL::ComPtr<IDXGISwapChain3> swapChain;
192 Microsoft::WRL::ComPtr<IDXGIAdapter1> adapter;
193
194 // Command objects (per-frame allocators for CPU/GPU overlap)
195 Microsoft::WRL::ComPtr<ID3D12CommandQueue> commandQueue;
196 Microsoft::WRL::ComPtr<ID3D12CommandAllocator> commandAllocators[FrameCount];
197 Microsoft::WRL::ComPtr<ID3D12GraphicsCommandList> commandList;
198
199 // Descriptor heaps
200 Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> rtvHeap;
201 Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> dsvHeap;
202
203 // Render targets and depth
204 Microsoft::WRL::ComPtr<ID3D12Resource> renderTargets[FrameCount];
205 Microsoft::WRL::ComPtr<ID3D12Resource> depthStencilBuffer;
206
207 // Pipeline state (PSOs are owned by the cache)
208 Microsoft::WRL::ComPtr<ID3D12RootSignature> rootSignature;
209 std::vector<
210 std::pair<PipelineKey, Microsoft::WRL::ComPtr<ID3D12PipelineState>>>
211 m_pipelineCache;
212 ID3D12PipelineState* m_defaultPipelineState = nullptr;
213 ID3D12PipelineState* m_shaderPipeline = nullptr;
214 ID3D12PipelineState* m_passPipeline = nullptr;
215
216 // Synchronization: one monotonically increasing fence, and the value
217 // that marks the end of the last frame recorded into each slot
218 Microsoft::WRL::ComPtr<ID3D12Fence> fence;
219 HANDLE fenceEvent = nullptr;
220 UINT64 m_fenceValue = 0;
221 UINT64 fenceValues[FrameCount] = {};
222 uint64_t m_frameSerial = 0;
223 bool m_frameActive = false;
224
225 // Descriptor sizes
226 UINT rtvDescriptorSize = 0;
227 UINT frameIndex = 0;
228
229 // Window
230 Window* window;
231
232 // Viewport and scissor rect
233 D3D12_VIEWPORT viewport = {};
234 D3D12_RECT scissorRect = {};
235
236 bool m_Initialized = false;
237
238 // Default 1x1 white texture (fallback when no texture is bound)
239 DirectX12Texture* m_defaultTexture = nullptr;
240
241 // Skybox PSO (depth write off, LEQUAL, no cull)
242 ID3D12PipelineState* m_skyboxPipelineState = nullptr;
243 bool m_skyboxPipelineFailed = false;
244 /// Builds the skybox PSO (depth write disabled, LEQUAL compare, no culling).
245 bool CreateSkyboxPipelineState();
246
247 // Debug line PSO (line topology)
248 ID3D12PipelineState* m_debugLinePipelineState = nullptr;
249 bool m_debugLinePipelineFailed = false;
250 /// Builds the line-topology PSO used for debug line rendering.
251 bool CreateDebugLinePipelineState();
252
253 // Transient per-frame constant data (constant buffers, light/fog)
254 DirectX12UploadRing m_uploadRing;
255 // Batched init-time and dynamic buffer/texture uploads
256 DirectX12UploadContext m_uploader;
257
258 // Latest light/fog constants, copied into the ring when bound
259 std::vector<uint8_t> m_lightData;
260
261 // Shadow mapping
262 Microsoft::WRL::ComPtr<ID3D12Resource> m_shadowDepthBuffer;
263 Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> m_shadowDsvHeap;
264 D3D12_CPU_DESCRIPTOR_HANDLE m_shadowDsvHandle = {};
265 UINT m_shadowSrvIndex = 0;
266 bool m_shadowMapCreated = false;
267 float m_lightVP[16] = {};
268 float m_pendingLightVP[16] = {};
269 bool m_hasPendingLightVP = false;
270 // Last shadow transform uploaded this pass and the World it was built from
271 float m_shadowWorldCache[16] = {};
272 D3D12_GPU_VIRTUAL_ADDRESS m_shadowCBAddress = 0;
273 bool m_inShadowPass = false;
274 // Depth-only PSO for shadow pass (no PS, no RTV, CULL_NONE)
275 ID3D12PipelineState* m_shadowPassPSO = nullptr;
276 Microsoft::WRL::ComPtr<ID3DBlob> m_shadowVSBlob;
277 bool m_shadowVSCompiled = false;
278 // First shader VS, fallback for the shadow PSO
279 Microsoft::WRL::ComPtr<ID3DBlob> m_cachedVSBlob;
280 void SetLightVP(const float* mat) override;
281 /// Allocates the shadow-pass depth buffer, DSV, and shared-heap SRV slot.
282 bool CreateShadowMapResources();
283 /// Builds the depth-only PSO (no pixel shader, no RTV, no culling) used for the shadow pass.
284 bool CreateShadowPassPSO();
285 /// Replays cached shadow-caster draws into the depth-only shadow map.
286 void RenderShadowPass();
287
288 // ImGUI
289 Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> imguiSrvHeap;
290
291 // Shared SRV descriptor heap (all textures live here — set once per frame)
292 Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> m_sharedSrvHeap;
293 UINT m_srvDescriptorSize = 0;
294 UINT m_nextSrvSlot = 1; // slot 0 reserved for imgui/default
295 static constexpr UINT MAX_SRV_DESCRIPTORS = 512;
296
297 /// Creates the shared, shader-visible SRV descriptor heap used by all textures/cubemaps.
298 bool CreateSharedSrvHeap();
299public:
300 // Allocate a slot in the shared SRV heap; returns the slot index
301 UINT AllocateSRVSlot();
302 D3D12_CPU_DESCRIPTOR_HANDLE GetSharedSrvCPUHandle(UINT slot) const;
303 D3D12_GPU_DESCRIPTOR_HANDLE GetSharedSrvGPUHandle(UINT slot) const;
304 ID3D12DescriptorHeap* GetSharedSrvHeap() const { return m_sharedSrvHeap.Get(); }
305};
306
307} // namespace RenderEngine
308} // namespace Sleak
309
310#endif // _DIRECTX12RENDERER_H
311
312#else
313namespace Sleak::RenderEngine {
314class DirectX12Renderer;
315}
316
317#endif
int width
int height
Abstract interface for high-level graphics command execution and resource management.
Abstract render backend: swapchain, frame lifecycle, and post-effect toggles.
Definition Renderer.hpp:41
Backend-facing rendering layer shared by the four graphics backends.
Root namespace for everything the engine exposes.
Definition Camera.hpp:10
bool operator==(const Pair< T1, T2 > &lhs, const Pair< T1, T2 > &rhs)
Definition Pair.hpp:115
class ENGINE_API Window