SleakEngine 0.1.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
DirectX12Renderer.cpp
Go to the documentation of this file.
2#ifdef PLATFORM_WIN
3
4#include <SDL3/SDL_system.h>
5#include <d3dcompiler.h>
6
7#include <Core/Logger.hpp>
8#include <Core/Window.hpp>
12#include <Runtime/MeshData.hpp>
13#include <algorithm>
14#include <codecvt>
15#include <cstdint>
16#include <cstring>
17#include <locale>
18#include <stdexcept>
19#include <string>
20#include <utility>
21#include <vector>
22
24
25namespace Sleak {
26namespace RenderEngine {
27
28namespace {
29const D3D12_INPUT_ELEMENT_DESC kVertexInputLayout[] = {
30 {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0,
31 static_cast<UINT>(offsetof(Sleak::Vertex, px)),
32 D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
33 {"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0,
34 static_cast<UINT>(offsetof(Sleak::Vertex, nx)),
35 D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
36 {"TANGENT", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0,
37 static_cast<UINT>(offsetof(Sleak::Vertex, tx)),
38 D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
39 {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0,
40 static_cast<UINT>(offsetof(Sleak::Vertex, r)),
41 D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
42 {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0,
43 static_cast<UINT>(offsetof(Sleak::Vertex, u)),
44 D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
45};
46
47uint64_t HashBytecode(ID3DBlob* blob) {
48 if (!blob) return 0;
49 const auto* bytes = static_cast<const uint8_t*>(blob->GetBufferPointer());
50 uint64_t hash = 14695981039346656037ull;
51 for (SIZE_T i = 0; i < blob->GetBufferSize(); ++i) {
52 hash ^= bytes[i];
53 hash *= 1099511628211ull;
54 }
55 return hash;
56}
57
58constexpr const char* VERTEX_ENTRY = "VS_Main";
59constexpr const char* PIXEL_ENTRY = "PS_Main";
60constexpr const char* VERTEX_PROFILE = "vs_5_0";
61constexpr const char* PIXEL_PROFILE = "ps_5_0";
62constexpr const char* SHADOW_SHADER_PATH =
63 "assets/shaders/default_shader_dx12.hlsl";
64constexpr const char* SKYBOX_SHADER_PATH = "assets/shaders/skybox_dx12.hlsl";
65constexpr const char* DEBUG_LINE_SHADER_PATH =
66 "assets/shaders/debug_line_dx12.hlsl";
67#ifdef SLEAK_HOT_RELOAD
68constexpr const char* SHADOW_SHADER_STEM = "default_shader";
69constexpr const char* SKYBOX_STEM = "skybox";
70constexpr const char* DEBUG_LINE_STEM = "debug_line";
71#endif
72
73// Transform CB layout: [WVP][World]; shadow CB: [LightVP*World][World]
74constexpr int MATRIX_DIM = 4;
75constexpr int MATRIX_FLOATS = MATRIX_DIM * MATRIX_DIM;
76constexpr int TRANSFORM_CB_FLOATS = 2 * MATRIX_FLOATS;
77constexpr size_t TRANSFORM_CB_BYTES = TRANSFORM_CB_FLOATS * sizeof(float);
78constexpr size_t TRANSFORM_WORLD_OFFSET = MATRIX_FLOATS * sizeof(float);
79
80/// Writes World * LightVP (row-major) followed by World into out.
81void BuildShadowTransform(const float* world, const float* lightVP,
82 float* out) {
83 for (int r = 0; r < MATRIX_DIM; ++r) {
84 for (int c = 0; c < MATRIX_DIM; ++c) {
85 float sum = 0.0f;
86 for (int k = 0; k < MATRIX_DIM; ++k) {
87 sum += world[r * MATRIX_DIM + k] * lightVP[k * MATRIX_DIM + c];
88 }
89 out[r * MATRIX_DIM + c] = sum;
90 }
91 }
92 memcpy(out + MATRIX_FLOATS, world, MATRIX_FLOATS * sizeof(float));
93}
94
95/// Compiles one fixed-pass stage, logging the compiler output on failure.
96Microsoft::WRL::ComPtr<ID3DBlob> CompileStage(const char* path,
97 const char* entry,
98 const char* profile) {
99 const std::wstring widePath(path, path + std::strlen(path));
100 Microsoft::WRL::ComPtr<ID3DBlob> blob, errorBlob;
101 HRESULT hr = D3DCompileFromFile(widePath.c_str(), nullptr, nullptr, entry,
102 profile, 0, 0, &blob, &errorBlob);
103 if (FAILED(hr)) {
104 if (errorBlob) {
105 SLEAK_ERROR("{} {} ({}) compile error: {}", path, entry, profile,
106 (char*)errorBlob->GetBufferPointer());
107 } else {
108 SLEAK_ERROR("{} {} ({}) compile error: 0x{:08X}", path, entry,
109 profile, static_cast<unsigned int>(hr));
110 }
111 return nullptr;
112 }
113 return blob;
114}
115
116#ifdef SLEAK_HOT_RELOAD
117/// True when the reload batch contains the stem.
118bool HasStem(const std::vector<std::string>& stems, const char* stem) {
119 return std::find(stems.begin(), stems.end(), stem) != stems.end();
120}
121#endif
122} // namespace
123
124/// Registers this backend's buffer/shader/texture factories with ResourceManager.
125DirectX12Renderer::DirectX12Renderer(Window* window) : window(window) {
126 fenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
127 if (fenceEvent == nullptr) {
128 throw std::runtime_error("Failed to create fence event.");
129 }
130 this->Type = RendererType::DirectX12;
131 m_lightData.assign(sizeof(RenderEngine::ShadowLightUBO), 0);
132
133 ResourceManager::RegisterCreateBuffer(
134 this, &DirectX12Renderer::CreateBuffer);
135 ResourceManager::RegisterCreateShader(
136 this, &DirectX12Renderer::CreateShader);
137 ResourceManager::RegisterCreateTexture(
138 this, &DirectX12Renderer::CreateTexture);
139 ResourceManager::RegisterCreateCubemapTexture(
140 this, &DirectX12Renderer::CreateCubemapTexture);
141 ResourceManager::RegisterCreateCubemapTextureFromPanorama(
142 this, &DirectX12Renderer::CreateCubemapTextureFromPanorama);
143 ResourceManager::RegisterCreateTextureFromMemory(
144 [this](const void* data, uint32_t w, uint32_t h, TextureFormat fmt,
145 uint32_t) -> Texture* {
146 auto* tex = new DirectX12Texture(device.Get(), commandQueue.Get(),
147 commandList.Get(), &m_uploader);
148 if (!tex->LoadFromMemory(data, w, h, fmt)) {
149 delete tex;
150 return nullptr;
151 }
152 UINT slot = AllocateSRVSlot();
153 tex->CreateSRVIntoHandle(DXGI_FORMAT_R8G8B8A8_UNORM,
154 GetSharedSrvCPUHandle(slot));
155 tex->SetSharedSrvGPUHandle(GetSharedSrvGPUHandle(slot));
156 return tex;
157 });
158}
159
160DirectX12Renderer::~DirectX12Renderer() {
161 WaitForGPU();
162 delete m_defaultTexture;
163 m_defaultTexture = nullptr;
164 Cleanup();
165 if (fenceEvent) {
166 CloseHandle(fenceEvent);
167 fenceEvent = nullptr;
168 }
169}
170
171bool DirectX12Renderer::Initialize() {
172 if (m_Initialized) return true;
173
174 if (!CreateDevice()) return false;
175 if (!CreateCommandQueue()) return false;
176 if (!CreateCommandAllocatorAndList()) return false;
177 if (!CreateSwapChain()) return false;
178 if (!CreateRenderTargetViews()) return false;
179 if (!CreateDepthStencilView()) return false;
180 if (!CreateFence()) return false;
181 m_uploadRing.Initialize(device.Get(), FrameCount, 64 * 1024);
182 if (!m_uploader.Initialize(device.Get(), commandQueue.Get())) return false;
183 if (!CreateRootSignature()) return false;
184 if (!CreateSharedSrvHeap()) return false;
185 // PSO is created lazily when CreateShader() is called
186
187 // Create a 1x1 white default texture so the SRV table is always valid
188 {
189 uint32_t whitePixel = 0xFFFFFFFF; // RGBA(255,255,255,255)
190 m_defaultTexture = new DirectX12Texture(
191 device.Get(), commandQueue.Get(), commandList.Get(), &m_uploader);
192 if (!m_defaultTexture->LoadFromMemory(
193 &whitePixel, 1, 1, TextureFormat::RGBA8)) {
194 SLEAK_WARN("Failed to create default white texture for DX12");
195 delete m_defaultTexture;
196 m_defaultTexture = nullptr;
197 } else {
198 UINT slot = AllocateSRVSlot();
199 m_defaultTexture->CreateSRVIntoHandle(DXGI_FORMAT_R8G8B8A8_UNORM,
200 GetSharedSrvCPUHandle(slot));
201 m_defaultTexture->SetSharedSrvGPUHandle(GetSharedSrvGPUHandle(slot));
202 }
203 }
204
205 // Set initial viewport
206 int w = Window::GetWidth();
207 int h = Window::GetHeight();
208 viewport.TopLeftX = 0.0f;
209 viewport.TopLeftY = 0.0f;
210 viewport.Width = static_cast<float>(w);
211 viewport.Height = static_cast<float>(h);
212 viewport.MinDepth = 0.0f;
213 viewport.MaxDepth = 1.0f;
214
215 scissorRect.left = 0;
216 scissorRect.top = 0;
217 scissorRect.right = w;
218 scissorRect.bottom = h;
219
220 SetPerformanceCounter(true);
221
222 m_Initialized = true;
223 SLEAK_INFO("DirectX 12 has been initialized successfully!");
224
225 return true;
226}
227
228bool DirectX12Renderer::CreateDevice() {
229 // Try feature level 12.0 first
230 if (SUCCEEDED(D3D12CreateDevice(nullptr, D3D_FEATURE_LEVEL_12_0,
231 IID_PPV_ARGS(&device)))) {
232 SLEAK_INFO("DirectX 12 device created with feature level 12.0");
233 return true;
234 }
235
236 // Fall back to 11.0
237 if (SUCCEEDED(D3D12CreateDevice(nullptr, D3D_FEATURE_LEVEL_11_0,
238 IID_PPV_ARGS(&device)))) {
239 SLEAK_INFO("DirectX 12 device created with feature level 11.0");
240 return true;
241 }
242
243 SLEAK_ERROR("Failed to create DirectX 12 device!");
244 return false;
245}
246
247bool DirectX12Renderer::CreateCommandQueue() {
248 D3D12_COMMAND_QUEUE_DESC queueDesc = {};
249 queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
250 queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
251
252 if (FAILED(device->CreateCommandQueue(&queueDesc,
253 IID_PPV_ARGS(&commandQueue)))) {
254 SLEAK_ERROR("Failed to create command queue!");
255 return false;
256 }
257 return true;
258}
259
260bool DirectX12Renderer::CreateCommandAllocatorAndList() {
261 // Create one command allocator per frame-in-flight so the CPU can
262 // record frame N+1 while the GPU is still executing frame N.
263 for (UINT i = 0; i < FrameCount; i++) {
264 if (FAILED(device->CreateCommandAllocator(
265 D3D12_COMMAND_LIST_TYPE_DIRECT,
266 IID_PPV_ARGS(&commandAllocators[i])))) {
267 SLEAK_ERROR("Failed to create command allocator {}!", i);
268 return false;
269 }
270 }
271
272 if (FAILED(device->CreateCommandList(
273 0, D3D12_COMMAND_LIST_TYPE_DIRECT, commandAllocators[0].Get(),
274 nullptr, IID_PPV_ARGS(&commandList)))) {
275 SLEAK_ERROR("Failed to create command list!");
276 return false;
277 }
278
279 // Close the command list (it starts in an open state)
280 commandList->Close();
281 return true;
282}
283
284bool DirectX12Renderer::CreateSwapChain() {
285 HWND hwnd = (HWND)SDL_GetPointerProperty(
286 SDL_GetWindowProperties(window->GetSDLWindow()),
287 SDL_PROP_WINDOW_WIN32_HWND_POINTER, NULL);
288
289 DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {};
290 swapChainDesc.BufferCount = FrameCount;
291 swapChainDesc.Width = 0;
292 swapChainDesc.Height = 0;
293 swapChainDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
294 swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
295 swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
296 swapChainDesc.SampleDesc.Count = 1;
297
298 Microsoft::WRL::ComPtr<IDXGIFactory4> factory;
299 if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) {
300 SLEAK_ERROR("Failed to create DXGI factory!");
301 return false;
302 }
303
304 HRESULT hr = factory->CreateSwapChainForHwnd(
305 commandQueue.Get(), hwnd, &swapChainDesc, nullptr, nullptr,
306 reinterpret_cast<IDXGISwapChain1**>(swapChain.GetAddressOf()));
307
308 if (FAILED(hr)) {
309 SLEAK_ERROR("Failed to create swap chain!");
310 return false;
311 }
312
313 frameIndex = swapChain->GetCurrentBackBufferIndex();
314
315 EnumerateDevices(factory);
316
317 return true;
318}
319
320bool DirectX12Renderer::CreateRenderTargetViews() {
321 D3D12_DESCRIPTOR_HEAP_DESC rtvHeapDesc = {};
322 rtvHeapDesc.NumDescriptors = FrameCount;
323 rtvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
324 rtvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
325
326 if (FAILED(device->CreateDescriptorHeap(&rtvHeapDesc,
327 IID_PPV_ARGS(&rtvHeap)))) {
328 SLEAK_ERROR("Failed to create RTV descriptor heap!");
329 return false;
330 }
331
332 rtvDescriptorSize = device->GetDescriptorHandleIncrementSize(
333 D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
334
335 D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle =
336 rtvHeap->GetCPUDescriptorHandleForHeapStart();
337
338 for (UINT i = 0; i < FrameCount; i++) {
339 if (FAILED(swapChain->GetBuffer(i,
340 IID_PPV_ARGS(&renderTargets[i])))) {
341 SLEAK_ERROR("Failed to get swap chain buffer {}!", i);
342 return false;
343 }
344 device->CreateRenderTargetView(renderTargets[i].Get(), nullptr,
345 rtvHandle);
346 rtvHandle.ptr += rtvDescriptorSize;
347 }
348
349 return true;
350}
351
352bool DirectX12Renderer::CreateDepthStencilView() {
353 // Create DSV descriptor heap
354 D3D12_DESCRIPTOR_HEAP_DESC dsvHeapDesc = {};
355 dsvHeapDesc.NumDescriptors = 1;
356 dsvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;
357 dsvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
358
359 if (FAILED(device->CreateDescriptorHeap(&dsvHeapDesc,
360 IID_PPV_ARGS(&dsvHeap)))) {
361 SLEAK_ERROR("Failed to create DSV descriptor heap!");
362 return false;
363 }
364
365 // Get swap chain dimensions
366 DXGI_SWAP_CHAIN_DESC1 scDesc;
367 swapChain->GetDesc1(&scDesc);
368 UINT width = scDesc.Width;
369 UINT height = scDesc.Height;
370
371 // Create depth stencil buffer
372 D3D12_RESOURCE_DESC depthDesc = {};
373 depthDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
374 depthDesc.Width = width;
375 depthDesc.Height = height;
376 depthDesc.DepthOrArraySize = 1;
377 depthDesc.MipLevels = 1;
378 depthDesc.Format = DXGI_FORMAT_D32_FLOAT;
379 depthDesc.SampleDesc.Count = 1;
380 depthDesc.SampleDesc.Quality = 0;
381 depthDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
382
383 D3D12_CLEAR_VALUE clearValue = {};
384 clearValue.Format = DXGI_FORMAT_D32_FLOAT;
385 clearValue.DepthStencil.Depth = 1.0f;
386 clearValue.DepthStencil.Stencil = 0;
387
388 D3D12_HEAP_PROPERTIES heapProps = {};
389 heapProps.Type = D3D12_HEAP_TYPE_DEFAULT;
390
391 if (FAILED(device->CreateCommittedResource(
392 &heapProps, D3D12_HEAP_FLAG_NONE, &depthDesc,
393 D3D12_RESOURCE_STATE_DEPTH_WRITE, &clearValue,
394 IID_PPV_ARGS(&depthStencilBuffer)))) {
395 SLEAK_ERROR("Failed to create depth stencil buffer!");
396 return false;
397 }
398
399 // Create depth stencil view
400 D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc = {};
401 dsvDesc.Format = DXGI_FORMAT_D32_FLOAT;
402 dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
403 dsvDesc.Flags = D3D12_DSV_FLAG_NONE;
404
405 device->CreateDepthStencilView(
406 depthStencilBuffer.Get(), &dsvDesc,
407 dsvHeap->GetCPUDescriptorHandleForHeapStart());
408
409 return true;
410}
411
412bool DirectX12Renderer::CreateFence() {
413 if (FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE,
414 IID_PPV_ARGS(&fence)))) {
415 SLEAK_ERROR("Failed to create fence!");
416 return false;
417 }
418 m_fenceValue = 0;
419 for (UINT i = 0; i < FrameCount; i++)
420 fenceValues[i] = 0;
421 return true;
422}
423
424bool DirectX12Renderer::CreateRootSignature() {
425 // Parameter 0: CBV at register(b0) — transform (vertex shader)
426 // Parameter 1: CBV at register(b1) — material (all shaders)
427 // Parameter 2: SRV descriptor table at register(t0) — texture (pixel shader)
428 // Parameter 3: CBV at register(b2) — lighting/fog (all shaders, VS needs LightVP)
429 // Parameter 4: SRV descriptor table at register(t3) — shadow map (pixel shader)
430 D3D12_ROOT_PARAMETER rootParams[5] = {};
431 rootParams[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
432 rootParams[0].Descriptor.ShaderRegister = 0;
433 rootParams[0].Descriptor.RegisterSpace = 0;
434 rootParams[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
435
436 rootParams[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
437 rootParams[1].Descriptor.ShaderRegister = 1;
438 rootParams[1].Descriptor.RegisterSpace = 0;
439 rootParams[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
440
441 D3D12_DESCRIPTOR_RANGE srvRange = {};
442 srvRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
443 srvRange.NumDescriptors = 1;
444 srvRange.BaseShaderRegister = 0;
445 srvRange.RegisterSpace = 0;
446 srvRange.OffsetInDescriptorsFromTableStart =
447 D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
448
449 rootParams[2].ParameterType =
450 D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
451 rootParams[2].DescriptorTable.NumDescriptorRanges = 1;
452 rootParams[2].DescriptorTable.pDescriptorRanges = &srvRange;
453 rootParams[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
454
455 rootParams[3].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
456 rootParams[3].Descriptor.ShaderRegister = 2;
457 rootParams[3].Descriptor.RegisterSpace = 0;
458 rootParams[3].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
459
460 D3D12_DESCRIPTOR_RANGE shadowSrvRange = {};
461 shadowSrvRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
462 shadowSrvRange.NumDescriptors = 1;
463 shadowSrvRange.BaseShaderRegister = 3;
464 shadowSrvRange.RegisterSpace = 0;
465 shadowSrvRange.OffsetInDescriptorsFromTableStart =
466 D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
467
468 rootParams[4].ParameterType =
469 D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
470 rootParams[4].DescriptorTable.NumDescriptorRanges = 1;
471 rootParams[4].DescriptorTable.pDescriptorRanges = &shadowSrvRange;
472 rootParams[4].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
473
474 // Static samplers
475 D3D12_STATIC_SAMPLER_DESC staticSamplers[3] = {};
476
477 // s0: ANISOTROPIC 16x — surface textures (high quality filtering)
478 staticSamplers[0].Filter = D3D12_FILTER_ANISOTROPIC;
479 staticSamplers[0].AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
480 staticSamplers[0].AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
481 staticSamplers[0].AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
482 staticSamplers[0].MipLODBias = 0.0f;
483 staticSamplers[0].MaxAnisotropy = 16;
484 staticSamplers[0].ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER;
485 staticSamplers[0].BorderColor =
486 D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK;
487 staticSamplers[0].MinLOD = 0.0f;
488 staticSamplers[0].MaxLOD = D3D12_FLOAT32_MAX;
489 staticSamplers[0].ShaderRegister = 0;
490 staticSamplers[0].RegisterSpace = 0;
491 staticSamplers[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
492
493 // s1: LINEAR/WRAP — skybox cubemap (smooth filtering)
494 staticSamplers[1].Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
495 staticSamplers[1].AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
496 staticSamplers[1].AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
497 staticSamplers[1].AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
498 staticSamplers[1].MipLODBias = 0.0f;
499 staticSamplers[1].MaxAnisotropy = 1;
500 staticSamplers[1].ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER;
501 staticSamplers[1].BorderColor =
502 D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK;
503 staticSamplers[1].MinLOD = 0.0f;
504 staticSamplers[1].MaxLOD = D3D12_FLOAT32_MAX;
505 staticSamplers[1].ShaderRegister = 1;
506 staticSamplers[1].RegisterSpace = 0;
507 staticSamplers[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
508
509 // s3: COMPARISON sampler — shadow map PCF
510 staticSamplers[2].Filter = D3D12_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT;
511 staticSamplers[2].AddressU = D3D12_TEXTURE_ADDRESS_MODE_BORDER;
512 staticSamplers[2].AddressV = D3D12_TEXTURE_ADDRESS_MODE_BORDER;
513 staticSamplers[2].AddressW = D3D12_TEXTURE_ADDRESS_MODE_BORDER;
514 staticSamplers[2].MipLODBias = 0.0f;
515 staticSamplers[2].MaxAnisotropy = 1;
516 staticSamplers[2].ComparisonFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL;
517 staticSamplers[2].BorderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE;
518 staticSamplers[2].MinLOD = 0.0f;
519 staticSamplers[2].MaxLOD = 0.0f;
520 staticSamplers[2].ShaderRegister = 3;
521 staticSamplers[2].RegisterSpace = 0;
522 staticSamplers[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
523
524 D3D12_ROOT_SIGNATURE_DESC rootSigDesc = {};
525 rootSigDesc.NumParameters = 5;
526 rootSigDesc.pParameters = rootParams;
527 rootSigDesc.NumStaticSamplers = 3;
528 rootSigDesc.pStaticSamplers = staticSamplers;
529 rootSigDesc.Flags =
530 D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
531
532 Microsoft::WRL::ComPtr<ID3DBlob> serializedRootSig;
533 Microsoft::WRL::ComPtr<ID3DBlob> errorBlob;
534
535 HRESULT hr = D3D12SerializeRootSignature(
536 &rootSigDesc, D3D_ROOT_SIGNATURE_VERSION_1,
537 &serializedRootSig, &errorBlob);
538
539 if (FAILED(hr)) {
540 if (errorBlob) {
541 SLEAK_ERROR("Root signature serialization error: {}",
542 (char*)errorBlob->GetBufferPointer());
543 }
544 return false;
545 }
546
547 hr = device->CreateRootSignature(
548 0, serializedRootSig->GetBufferPointer(),
549 serializedRootSig->GetBufferSize(),
550 IID_PPV_ARGS(&rootSignature));
551
552 if (FAILED(hr)) {
553 SLEAK_ERROR("Failed to create root signature!");
554 return false;
555 }
556
557 return true;
558}
559
560ID3D12PipelineState* DirectX12Renderer::GetPipeline(const PipelineKey& key,
561 ID3DBlob* vs,
562 ID3DBlob* ps) {
563 for (auto& [cachedKey, pso] : m_pipelineCache) {
564 if (cachedKey == key) return pso.Get();
565 }
566 if (!vs || key.vertexFormat != 0) return nullptr;
567
568 D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};
569 psoDesc.InputLayout = {kVertexInputLayout, _countof(kVertexInputLayout)};
570 psoDesc.pRootSignature = rootSignature.Get();
571 psoDesc.VS = {vs->GetBufferPointer(), vs->GetBufferSize()};
572 if (ps) psoDesc.PS = {ps->GetBufferPointer(), ps->GetBufferSize()};
573
574 D3D12_RASTERIZER_DESC rasterDesc = {};
575 rasterDesc.FillMode = D3D12_FILL_MODE_SOLID;
576 rasterDesc.CullMode = key.cullMode;
577 rasterDesc.FrontCounterClockwise = FALSE;
578 rasterDesc.DepthBias = key.depthBias;
579 rasterDesc.DepthBiasClamp = key.depthBiasClamp;
580 rasterDesc.SlopeScaledDepthBias = key.slopeScaledDepthBias;
581 rasterDesc.DepthClipEnable = key.depthClip;
582 rasterDesc.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
583 psoDesc.RasterizerState = rasterDesc;
584
585 const bool hasColor = key.rtvFormat != DXGI_FORMAT_UNKNOWN;
586 D3D12_RENDER_TARGET_BLEND_DESC rtBlend = {};
587 rtBlend.BlendEnable = key.blendEnable;
588 rtBlend.SrcBlend =
589 key.blendEnable ? D3D12_BLEND_SRC_ALPHA : D3D12_BLEND_ONE;
590 rtBlend.DestBlend =
591 key.blendEnable ? D3D12_BLEND_INV_SRC_ALPHA : D3D12_BLEND_ZERO;
592 rtBlend.BlendOp = D3D12_BLEND_OP_ADD;
593 rtBlend.SrcBlendAlpha = D3D12_BLEND_ONE;
594 rtBlend.DestBlendAlpha =
595 key.blendEnable ? D3D12_BLEND_INV_SRC_ALPHA : D3D12_BLEND_ZERO;
596 rtBlend.BlendOpAlpha = D3D12_BLEND_OP_ADD;
597 rtBlend.LogicOp = D3D12_LOGIC_OP_NOOP;
598 rtBlend.RenderTargetWriteMask = hasColor ? D3D12_COLOR_WRITE_ENABLE_ALL : 0;
599 for (UINT i = 0; i < D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT; ++i)
600 psoDesc.BlendState.RenderTarget[i] = rtBlend;
601
602 psoDesc.DepthStencilState.DepthEnable = TRUE;
603 psoDesc.DepthStencilState.DepthWriteMask = key.depthWrite;
604 psoDesc.DepthStencilState.DepthFunc = key.depthFunc;
605 psoDesc.DepthStencilState.StencilEnable = FALSE;
606
607 psoDesc.SampleMask = UINT_MAX;
608 psoDesc.PrimitiveTopologyType = key.topology;
609 psoDesc.NumRenderTargets = hasColor ? 1 : 0;
610 psoDesc.RTVFormats[0] = key.rtvFormat;
611 psoDesc.DSVFormat = key.dsvFormat;
612 psoDesc.SampleDesc.Count = 1;
613
614 Microsoft::WRL::ComPtr<ID3D12PipelineState> pso;
615 HRESULT hr =
616 device->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&pso));
617 if (FAILED(hr)) {
618 SLEAK_ERROR("Failed to create pipeline state! HRESULT: 0x{:08X}",
619 static_cast<unsigned int>(hr));
620 return nullptr;
621 }
622
623 m_pipelineCache.emplace_back(key, pso);
624 return pso.Get();
625}
626
627ID3D12PipelineState* DirectX12Renderer::GetShaderPipeline(ID3DBlob* vs,
628 ID3DBlob* ps) {
629 PipelineKey key;
630 key.vsHash = HashBytecode(vs);
631 key.psHash = HashBytecode(ps);
632 return GetPipeline(key, vs, ps);
633}
634
635#ifdef SLEAK_HOT_RELOAD
636bool DirectX12Renderer::ReloadShaders(const std::vector<std::string>& stems) {
637 // Old PSOs are released below, so no frame may still use them
638 WaitForGPU();
639
640 std::vector<ID3D12PipelineState*> replaced;
641 ReloadLiveShaders(stems, replaced);
642 if (HasStem(stems, SHADOW_SHADER_STEM)) ReloadShadowPassPSO(replaced);
643 if (HasStem(stems, SKYBOX_STEM))
644 ReloadPassPipeline(m_skyboxPipelineState, m_skyboxPipelineFailed,
645 &DirectX12Renderer::CreateSkyboxPipelineState,
646 SKYBOX_STEM, replaced);
647 if (HasStem(stems, DEBUG_LINE_STEM))
648 ReloadPassPipeline(m_debugLinePipelineState, m_debugLinePipelineFailed,
649 &DirectX12Renderer::CreateDebugLinePipelineState,
650 DEBUG_LINE_STEM, replaced);
651 PruneReplacedPipelines(replaced);
652 m_shaderPipeline = nullptr;
653 m_passPipeline = nullptr;
654
655 for (const std::string& stem : stems) {
656 const bool used =
657 stem == SHADOW_SHADER_STEM || stem == SKYBOX_STEM ||
658 stem == DEBUG_LINE_STEM ||
659 std::ranges::any_of(DirectX12Shader::GetLiveShaders(),
660 [&stem](const DirectX12Shader* shader) {
661 return shader->UsesStem(stem);
662 });
663 if (!used)
665 "Hot reload: no loaded DirectX 12 shader is built from '{}'",
666 stem);
667 }
668 return true;
669}
670
671void DirectX12Renderer::ReloadLiveShaders(
672 const std::vector<std::string>& stems,
673 std::vector<ID3D12PipelineState*>& replaced) {
674 const auto usesAnyStem = [&stems](const DirectX12Shader* shader) {
675 return std::ranges::any_of(stems, [shader](const std::string& stem) {
676 return shader->UsesStem(stem);
677 });
678 };
679
680 // Shaders built from the same files compile once and share the result
681 std::vector<const DirectX12Shader*> rebuilt;
682 std::vector<const DirectX12Shader*> failed;
683 for (DirectX12Shader* shader : DirectX12Shader::GetLiveShaders()) {
684 if (!usesAnyStem(shader)) continue;
685 const auto sameSources = [shader](const DirectX12Shader* other) {
686 return shader->HasSameSources(*other);
687 };
688 if (std::ranges::any_of(failed, sameSources)) continue;
689
690 Microsoft::WRL::ComPtr<ID3DBlob> vs;
691 Microsoft::WRL::ComPtr<ID3DBlob> ps;
692 ID3D12PipelineState* pso = nullptr;
693 const auto twin = std::ranges::find_if(rebuilt, sameSources);
694 if (twin != rebuilt.end()) {
695 vs = (*twin)->getVertexShaderBlob();
696 ps = (*twin)->getPixelShaderBlob();
697 pso = (*twin)->GetPipelineState();
698 } else if (shader->RecompileStages(vs, ps)) {
699 pso = GetShaderPipeline(vs.Get(), ps.Get());
700 }
701 if (!pso) {
702 failed.push_back(shader);
703 SLEAK_WARN("Shader '{}' failed to reload, keeping the old pipeline",
704 shader->GetStem());
705 continue;
706 }
707 if (twin == rebuilt.end()) {
708 rebuilt.push_back(shader);
709 SLEAK_INFO("Reloaded DirectX 12 shader '{}'", shader->GetStem());
710 }
711
712 // The first shader also provides the default PSO and shadow fallback
713 if (m_cachedVSBlob &&
714 m_cachedVSBlob.Get() == shader->getVertexShaderBlob()) {
715 m_cachedVSBlob = vs;
716 m_defaultPipelineState = pso;
717 }
718 if (ID3D12PipelineState* old = shader->GetPipelineState())
719 replaced.push_back(old);
720 shader->ReplaceStages(std::move(vs), std::move(ps), pso);
721 }
722}
723
724void DirectX12Renderer::ReloadPassPipeline(
725 ID3D12PipelineState*& pso, bool& failed,
726 bool (DirectX12Renderer::*create)(), const char* stem,
727 std::vector<ID3D12PipelineState*>& replaced) {
728 ID3D12PipelineState* old = std::exchange(pso, nullptr);
729 failed = false;
730 // Not built yet, the first pass compiles the new file
731 if (!old) return;
732
733 if ((this->*create)()) {
734 replaced.push_back(old);
735 SLEAK_INFO("Reloaded DirectX 12 pipeline '{}'", stem);
736 return;
737 }
738 pso = old;
739 failed = false;
740 SLEAK_WARN("Pipeline '{}' failed to reload, keeping the old one", stem);
741}
742
743void DirectX12Renderer::ReloadShadowPassPSO(
744 std::vector<ID3D12PipelineState*>& replaced) {
745 // Not built yet, the first shadow pass compiles the new file
746 if (!m_shadowVSCompiled) return;
747
748 Microsoft::WRL::ComPtr<ID3DBlob> vs =
749 CompileStage(SHADOW_SHADER_PATH, VERTEX_ENTRY, VERTEX_PROFILE);
750 if (!vs) {
751 SLEAK_WARN("Shadow pass shader failed to reload, keeping the old one");
752 return;
753 }
754 ID3D12PipelineState* oldPSO = std::exchange(m_shadowPassPSO, nullptr);
755 Microsoft::WRL::ComPtr<ID3DBlob> oldVS = std::exchange(m_shadowVSBlob, vs);
756 if (CreateShadowPassPSO()) {
757 if (oldPSO) replaced.push_back(oldPSO);
758 SLEAK_INFO("Reloaded DirectX 12 pipeline 'shadow pass'");
759 return;
760 }
761 m_shadowPassPSO = oldPSO;
762 m_shadowVSBlob = std::move(oldVS);
763 SLEAK_WARN("Shadow pass PSO failed to rebuild, keeping the old one");
764}
765
766void DirectX12Renderer::PruneReplacedPipelines(
767 const std::vector<ID3D12PipelineState*>& replaced) {
768 const auto inUse = [this](ID3D12PipelineState* pso) {
769 if (pso == m_defaultPipelineState || pso == m_shadowPassPSO ||
770 pso == m_skyboxPipelineState || pso == m_debugLinePipelineState)
771 return true;
772 return std::ranges::any_of(DirectX12Shader::GetLiveShaders(),
773 [pso](const DirectX12Shader* shader) {
774 return shader->GetPipelineState() == pso;
775 });
776 };
777 std::erase_if(m_pipelineCache, [&](const auto& entry) {
778 ID3D12PipelineState* pso = entry.second.Get();
779 return std::find(replaced.begin(), replaced.end(), pso) !=
780 replaced.end() &&
781 !inUse(pso);
782 });
783}
784#endif
785
786bool DirectX12Renderer::CreateShadowPassPSO() {
787 if (m_shadowPassPSO) return true;
788
789 if (!m_shadowVSCompiled) {
790 m_shadowVSCompiled = true;
791 m_shadowVSBlob =
792 CompileStage(SHADOW_SHADER_PATH, VERTEX_ENTRY, VERTEX_PROFILE);
793 }
794 ID3DBlob* vs = m_shadowVSBlob ? m_shadowVSBlob.Get() : m_cachedVSBlob.Get();
795 if (!vs) {
796 SLEAK_WARN("CreateShadowPassPSO: no vertex shader available yet");
797 return false;
798 }
799
800 PipelineKey key;
801 key.vsHash = HashBytecode(vs);
802 key.cullMode = D3D12_CULL_MODE_NONE;
803 key.depthBias = 1000;
804 key.depthBiasClamp = 0.01f;
805 key.slopeScaledDepthBias = 2.0f;
806 key.rtvFormat = DXGI_FORMAT_UNKNOWN;
807
808 m_shadowPassPSO = GetPipeline(key, vs, nullptr);
809 if (!m_shadowPassPSO) return false;
810 SLEAK_INFO("D3D12 shadow pass PSO created");
811 return true;
812}
813
814void DirectX12Renderer::BeginRender() {
815 frameIndex = swapChain->GetCurrentBackBufferIndex();
816
817 // Commit staged lightVP before shadow pass so shadow + main agree.
818 if (m_hasPendingLightVP) {
819 memcpy(m_lightVP, m_pendingLightVP, sizeof(m_lightVP));
820 }
821
822 // Only the frame that last recorded into this slot has to be finished.
823 // Everything the CPU rewrites per frame lives in per-slot memory.
824 const UINT64 slotFence = fenceValues[frameIndex];
825 if (fence->GetCompletedValue() < slotFence) {
826 fence->SetEventOnCompletion(slotFence, fenceEvent);
827 WaitForSingleObject(fenceEvent, INFINITE);
828 }
829
830 DirectX12Buffer::ProcessDeferredCleanup(fence->GetCompletedValue());
831 m_uploader.Retire();
832 m_uploader.Submit();
833 m_uploadRing.BeginFrame(frameIndex);
834 ++m_frameSerial;
835 m_frameActive = true;
836 m_shaderPipeline = nullptr;
837 m_passPipeline = nullptr;
838
839 // Reset the command allocator and command list for this frame
840 commandAllocators[frameIndex]->Reset();
841 commandList->Reset(commandAllocators[frameIndex].Get(),
842 m_defaultPipelineState);
843
844 if (!m_defaultPipelineState) {
845 SLEAK_WARN("BeginRender: no pipeline state yet, nothing will draw");
846 }
847
848 // Set root signature and viewport/scissor
849 commandList->SetGraphicsRootSignature(rootSignature.Get());
850
851 // Bind the shared SRV heap ONCE for the entire frame — never switch heaps
852 ID3D12DescriptorHeap* srvHeaps[] = {m_sharedSrvHeap.Get()};
853 commandList->SetDescriptorHeaps(1, srvHeaps);
854
855 commandList->RSSetViewports(1, &viewport);
856 commandList->RSSetScissorRects(1, &scissorRect);
857
858 // Transition back buffer to render target state
859 D3D12_RESOURCE_BARRIER barrier = {};
860 barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
861 barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
862 barrier.Transition.pResource = renderTargets[frameIndex].Get();
863 barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT;
864 barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET;
865 barrier.Transition.Subresource =
866 D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
867 commandList->ResourceBarrier(1, &barrier);
868
869 // Clear render target
870 const float clearColor[] = {0.39f, 0.58f, 0.93f, 1.0f};
871 D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle =
872 rtvHeap->GetCPUDescriptorHandleForHeapStart();
873 rtvHandle.ptr += frameIndex * rtvDescriptorSize;
874
875 D3D12_CPU_DESCRIPTOR_HANDLE dsvHandle =
876 dsvHeap->GetCPUDescriptorHandleForHeapStart();
877
878 commandList->ClearRenderTargetView(rtvHandle, clearColor, 0, nullptr);
879 commandList->ClearDepthStencilView(dsvHandle, D3D12_CLEAR_FLAG_DEPTH,
880 1.0f, 0, 0, nullptr);
881
882 // Shadow pass before main rendering
883 if (m_shadowPassEnabled) {
884 RenderShadowPass();
885 if (m_defaultPipelineState)
886 commandList->SetPipelineState(m_defaultPipelineState);
887 }
888
889 // Set render targets
890 commandList->OMSetRenderTargets(1, &rtvHandle, FALSE, &dsvHandle);
891 // Restore viewport/scissor after shadow pass
892 commandList->RSSetViewports(1, &viewport);
893 commandList->RSSetScissorRects(1, &scissorRect);
894
895 // Set primitive topology
896 commandList->IASetPrimitiveTopology(
897 D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
898
899 // Re-set root signature after shadow pass (SetGraphicsRootSignature
900 // invalidates all root parameter bindings, so we must rebind everything).
901 commandList->SetGraphicsRootSignature(rootSignature.Get());
902 {
903 ID3D12DescriptorHeap* heaps[] = {m_sharedSrvHeap.Get()};
904 commandList->SetDescriptorHeaps(1, heaps);
905 }
906
907 // Root param 2: SRV table at t0 — default white texture
908 if (m_defaultTexture) {
909 m_defaultTexture->Bind(0);
910 }
911
912 // Root param 3: CBV at b2, light/shadow constants
913 BindLightConstants();
914
915 // Root param 4: SRV table at t3 — shadow map
916 if (m_shadowMapCreated) {
917 commandList->SetGraphicsRootDescriptorTable(
918 4, GetSharedSrvGPUHandle(m_shadowSrvIndex));
919 }
920
921 bImFrameActive = false;
922 if (bImInitialized) {
923 ImGui_ImplDX12_NewFrame();
924 ImGui_ImplSDL3_NewFrame();
925 // Guard against first frames before SDL has reported a valid window size
926 auto& io = ImGui::GetIO();
927 if (io.DisplaySize.x > 0.0f && io.DisplaySize.y > 0.0f) {
928 ImGui::NewFrame();
929 bImFrameActive = true;
930 }
931 }
932}
933
934void DirectX12Renderer::EndRender() {
935 if (bImFrameActive) {
936 ImGui::Render();
937 // Shared SRV heap is already bound from BeginRender — no heap switch needed
938 ImGui_ImplDX12_RenderDrawData(ImGui::GetDrawData(),
939 commandList.Get());
940 }
941
942 // Transition back buffer to present state
943 D3D12_RESOURCE_BARRIER barrier = {};
944 barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
945 barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
946 barrier.Transition.pResource = renderTargets[frameIndex].Get();
947 barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
948 barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT;
949 barrier.Transition.Subresource =
950 D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
951 commandList->ResourceBarrier(1, &barrier);
952
953 // Uploads recorded this frame must land before the draws that use them
954 commandList->Close();
955 m_uploader.Submit();
956 ID3D12CommandList* ppCommandLists[] = {commandList.Get()};
957 commandQueue->ExecuteCommandLists(_countof(ppCommandLists),
958 ppCommandLists);
959
960 swapChain->Present(m_vsync ? 1 : 0, 0);
961
962 // No wait here: BeginRender waits for this value only when the slot
963 // comes around again.
964 fenceValues[frameIndex] = ++m_fenceValue;
965 commandQueue->Signal(fence.Get(), m_fenceValue);
966 DirectX12Buffer::TagDeferredCleanup(m_fenceValue);
967 m_frameActive = false;
968
969 UpdateFrameMetrics();
970}
971
972void DirectX12Renderer::WaitForGPU() {
973 if (!commandQueue || !fence || !fenceEvent) return;
974
975 m_uploader.Submit();
976 const UINT64 waitValue = ++m_fenceValue;
977 commandQueue->Signal(fence.Get(), waitValue);
978
979 if (fence->GetCompletedValue() < waitValue) {
980 fence->SetEventOnCompletion(waitValue, fenceEvent);
981 WaitForSingleObject(fenceEvent, INFINITE);
982 }
983 m_uploader.Retire();
984}
985
986bool DirectX12Renderer::CreateSharedSrvHeap() {
987 D3D12_DESCRIPTOR_HEAP_DESC heapDesc{};
988 heapDesc.NumDescriptors = MAX_SRV_DESCRIPTORS;
989 heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
990 heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
991
992 HRESULT hr = device->CreateDescriptorHeap(
993 &heapDesc, IID_PPV_ARGS(&m_sharedSrvHeap));
994 if (FAILED(hr)) {
995 SLEAK_ERROR("Failed to create shared SRV descriptor heap!");
996 return false;
997 }
998 m_srvDescriptorSize = device->GetDescriptorHandleIncrementSize(
999 D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
1000 m_nextSrvSlot = 0;
1001 return true;
1002}
1003
1004UINT DirectX12Renderer::AllocateSRVSlot() {
1005 if (m_nextSrvSlot >= MAX_SRV_DESCRIPTORS) {
1006 SLEAK_ERROR("Shared SRV heap full! Increase MAX_SRV_DESCRIPTORS.");
1007 return 0;
1008 }
1009 return m_nextSrvSlot++;
1010}
1011
1012D3D12_CPU_DESCRIPTOR_HANDLE DirectX12Renderer::GetSharedSrvCPUHandle(UINT slot) const {
1013 D3D12_CPU_DESCRIPTOR_HANDLE handle = m_sharedSrvHeap->GetCPUDescriptorHandleForHeapStart();
1014 handle.ptr += static_cast<SIZE_T>(slot) * m_srvDescriptorSize;
1015 return handle;
1016}
1017
1018D3D12_GPU_DESCRIPTOR_HANDLE DirectX12Renderer::GetSharedSrvGPUHandle(UINT slot) const {
1019 D3D12_GPU_DESCRIPTOR_HANDLE handle = m_sharedSrvHeap->GetGPUDescriptorHandleForHeapStart();
1020 handle.ptr += static_cast<UINT64>(slot) * m_srvDescriptorSize;
1021 return handle;
1022}
1023
1024void DirectX12Renderer::Cleanup() {
1025 if (!m_Initialized) return;
1026
1027 WaitForGPU();
1028 DirectX12Buffer::TagDeferredCleanup(m_fenceValue);
1029 DirectX12Buffer::ProcessDeferredCleanup(UINT64_MAX);
1030
1031 if (bImInitialized) {
1032 ImGui_ImplDX12_Shutdown();
1033 ImGui_ImplSDL3_Shutdown();
1034 ImGui::DestroyContext();
1035 bImInitialized = false;
1036 }
1037 m_uploader.Release();
1038 m_uploadRing.Release();
1039
1040 imguiSrvHeap.Reset();
1041 m_sharedSrvHeap.Reset();
1042
1043 m_skyboxPipelineState = nullptr;
1044 m_debugLinePipelineState = nullptr;
1045 m_shadowPassPSO = nullptr;
1046 m_defaultPipelineState = nullptr;
1047 m_shaderPipeline = nullptr;
1048 m_passPipeline = nullptr;
1049 m_pipelineCache.clear();
1050 rootSignature.Reset();
1051 depthStencilBuffer.Reset();
1052 dsvHeap.Reset();
1053 for (auto& rt : renderTargets) {
1054 rt.Reset();
1055 }
1056 rtvHeap.Reset();
1057 fence.Reset();
1058 commandList.Reset();
1059 for (UINT i = 0; i < FrameCount; i++)
1060 commandAllocators[i].Reset();
1061 commandQueue.Reset();
1062 swapChain.Reset();
1063 device.Reset();
1064
1065 m_Initialized = false;
1066}
1067
1068void DirectX12Renderer::Resize(uint32_t width, uint32_t height) {
1069 if (!m_Initialized || !swapChain) return;
1070
1071 WaitForGPU();
1072
1073 // Release render target references
1074 for (auto& rt : renderTargets) {
1075 rt.Reset();
1076 }
1077 depthStencilBuffer.Reset();
1078 dsvHeap.Reset();
1079 rtvHeap.Reset();
1080
1081 // Resize swap chain buffers
1082 HRESULT hr = swapChain->ResizeBuffers(FrameCount, width, height,
1083 DXGI_FORMAT_R8G8B8A8_UNORM, 0);
1084 if (FAILED(hr)) {
1085 SLEAK_ERROR("Failed to resize swap chain buffers!");
1086 return;
1087 }
1088
1089 frameIndex = swapChain->GetCurrentBackBufferIndex();
1090
1091 // Recreate render target views and depth stencil
1092 if (!CreateRenderTargetViews() || !CreateDepthStencilView()) {
1093 SLEAK_ERROR("Failed to recreate views after resize!");
1094 return;
1095 }
1096
1097 // Update viewport and scissor
1098 viewport.Width = static_cast<float>(width);
1099 viewport.Height = static_cast<float>(height);
1100 scissorRect.right = width;
1101 scissorRect.bottom = height;
1102
1103 SLEAK_INFO("DirectX 12 resized to {}x{}", width, height);
1104}
1105
1106void DirectX12Renderer::Draw(uint32_t vertexCount) { Draw(vertexCount, 0); }
1107
1108void DirectX12Renderer::Draw(uint32_t vertexCount, uint32_t firstVertex) {
1109 commandList->DrawInstanced(vertexCount, 1, firstVertex, 0);
1110 DrawnVertices += vertexCount;
1111 DrawnTriangles += vertexCount / 3;
1112}
1113
1114void DirectX12Renderer::DrawIndexed(uint32_t indexCount) {
1115 DrawIndexed(indexCount, 0, 0);
1116}
1117
1118void DirectX12Renderer::DrawIndexed(uint32_t indexCount, uint32_t firstIndex,
1119 int32_t baseVertex) {
1120 commandList->DrawIndexedInstanced(indexCount, 1, firstIndex, baseVertex, 0);
1121 DrawnVertices += indexCount;
1122 DrawnTriangles += indexCount / 3;
1123}
1124
1125void DirectX12Renderer::DrawInstance(uint32_t instanceCount,
1126 uint32_t vertexPerInstance) {
1127 commandList->DrawInstanced(vertexPerInstance, instanceCount, 0, 0);
1128 DrawnVertices += vertexPerInstance * instanceCount;
1129 DrawnTriangles += (vertexPerInstance / 3) * instanceCount;
1130}
1131
1132void DirectX12Renderer::DrawIndexedInstance(uint32_t instanceCount,
1133 uint32_t indexPerInstance) {
1134 DrawIndexedInstance(instanceCount, indexPerInstance, 0, 0);
1135}
1136
1137void DirectX12Renderer::DrawIndexedInstance(uint32_t instanceCount,
1138 uint32_t indexPerInstance,
1139 uint32_t firstIndex,
1140 int32_t baseVertex) {
1141 commandList->DrawIndexedInstanced(indexPerInstance, instanceCount,
1142 firstIndex, baseVertex, 0);
1143 DrawnVertices += indexPerInstance * instanceCount;
1144 DrawnTriangles += (indexPerInstance / 3) * instanceCount;
1145}
1146
1147void DirectX12Renderer::SetRenderFace(RenderFace face) {
1148 Face = face;
1149 ConfigureRenderFace();
1150}
1151
1152void DirectX12Renderer::SetRenderMode(RenderMode mode) {
1153 Mode = mode;
1154 ConfigureRenderMode();
1155}
1156
1157void DirectX12Renderer::SetViewport(float x, float y, float width,
1158 float height, float minDepth,
1159 float maxDepth) {
1160 viewport.TopLeftX = x;
1161 viewport.TopLeftY = y;
1162 viewport.Width = width;
1163 viewport.Height = height;
1164 viewport.MinDepth = minDepth;
1165 viewport.MaxDepth = maxDepth;
1166
1167 scissorRect.left = static_cast<LONG>(x);
1168 scissorRect.top = static_cast<LONG>(y);
1169 scissorRect.right = static_cast<LONG>(x + width);
1170 scissorRect.bottom = static_cast<LONG>(y + height);
1171
1172 if (commandList) {
1173 commandList->RSSetViewports(1, &viewport);
1174 commandList->RSSetScissorRects(1, &scissorRect);
1175 }
1176}
1177
1178void DirectX12Renderer::ClearRenderTarget(float r, float g, float b,
1179 float a) {
1180 const float clearColor[] = {r, g, b, a};
1181 D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle =
1182 rtvHeap->GetCPUDescriptorHandleForHeapStart();
1183 rtvHandle.ptr += frameIndex * rtvDescriptorSize;
1184 commandList->ClearRenderTargetView(rtvHandle, clearColor, 0, nullptr);
1185}
1186
1187void DirectX12Renderer::ClearDepthStencil(bool clearDepth,
1188 bool clearStencil, float depth,
1189 uint8_t stencil) {
1190 D3D12_CLEAR_FLAGS flags = {};
1191 if (clearDepth)
1192 flags = static_cast<D3D12_CLEAR_FLAGS>(
1193 flags | D3D12_CLEAR_FLAG_DEPTH);
1194 if (clearStencil)
1195 flags = static_cast<D3D12_CLEAR_FLAGS>(
1196 flags | D3D12_CLEAR_FLAG_STENCIL);
1197
1198 if (flags && dsvHeap) {
1199 D3D12_CPU_DESCRIPTOR_HANDLE dsvHandle =
1200 dsvHeap->GetCPUDescriptorHandleForHeapStart();
1201 commandList->ClearDepthStencilView(dsvHandle, flags, depth,
1202 stencil, 0, nullptr);
1203 }
1204}
1205
1206void DirectX12Renderer::BindVertexBuffer(RefPtr<BufferBase> buffer,
1207 uint32_t slot) {
1208 auto* dx12Buf = static_cast<DirectX12Buffer*>(buffer.get());
1209 if (!dx12Buf) return;
1210
1211 D3D12_VERTEX_BUFFER_VIEW vbView = {};
1212 vbView.BufferLocation =
1213 dx12Buf->GetD3DBuffer()->GetGPUVirtualAddress();
1214 vbView.StrideInBytes = sizeof(Sleak::Vertex);
1215 vbView.SizeInBytes = static_cast<UINT>(dx12Buf->GetSize());
1216
1217 commandList->IASetVertexBuffers(slot, 1, &vbView);
1218}
1219
1220void DirectX12Renderer::BindIndexBuffer(RefPtr<BufferBase> buffer,
1221 uint32_t slot) {
1222 auto* dx12Buf = static_cast<DirectX12Buffer*>(buffer.get());
1223 if (!dx12Buf) return;
1224
1225 D3D12_INDEX_BUFFER_VIEW ibView = {};
1226 ibView.BufferLocation =
1227 dx12Buf->GetD3DBuffer()->GetGPUVirtualAddress();
1228 ibView.Format = DXGI_FORMAT_R32_UINT; // IndexType is uint32_t
1229 ibView.SizeInBytes = static_cast<UINT>(dx12Buf->GetSize());
1230
1231 commandList->IASetIndexBuffer(&ibView);
1232}
1233
1234void DirectX12Renderer::BindConstantBuffer(RefPtr<BufferBase> buffer,
1235 uint32_t slot) {
1236 auto* dx12Buf = static_cast<DirectX12Buffer*>(buffer.get());
1237 if (!dx12Buf) return;
1238
1239 // Shadow pass: use a dedicated shadow CB with LightVP*World for slot 0
1240 if (m_inShadowPass && slot == 0 &&
1241 dx12Buf->GetCPUShadowCopySize() >= TRANSFORM_CB_BYTES) {
1242 const float* srcWorld = reinterpret_cast<const float*>(
1243 static_cast<const char*>(dx12Buf->GetCPUShadowCopy()) +
1244 TRANSFORM_WORLD_OFFSET);
1245
1246 // Casters sharing a World reuse this pass's ring copy
1247 if (!m_shadowCBAddress || memcmp(srcWorld, m_shadowWorldCache,
1248 sizeof(m_shadowWorldCache)) != 0) {
1249 DirectX12UploadRing::Allocation alloc;
1250 if (!m_uploadRing.Allocate(TRANSFORM_CB_BYTES, alloc)) return;
1251 BuildShadowTransform(srcWorld, m_lightVP,
1252 static_cast<float*>(alloc.cpu));
1253 memcpy(m_shadowWorldCache, srcWorld, sizeof(m_shadowWorldCache));
1254 m_shadowCBAddress = alloc.gpu;
1255 }
1256 commandList->SetGraphicsRootConstantBufferView(slot, m_shadowCBAddress);
1257 return;
1258 }
1259
1260 // Constant contents are copied into this frame's ring slice on the
1261 // first bind after an update, so frames in flight keep their own copy.
1262 if (const void* data = dx12Buf->GetConstantData()) {
1263 D3D12_GPU_VIRTUAL_ADDRESS address =
1264 dx12Buf->GetFrameAddress(m_frameSerial);
1265 if (!address) {
1266 const size_t size = dx12Buf->GetConstantDataSize();
1267 DirectX12UploadRing::Allocation alloc;
1268 if (m_uploadRing.Allocate(size, alloc)) {
1269 memcpy(alloc.cpu, data, size);
1270 address = alloc.gpu;
1271 dx12Buf->SetFrameAddress(m_frameSerial, address);
1272 }
1273 }
1274 if (address) {
1275 commandList->SetGraphicsRootConstantBufferView(slot, address);
1276 return;
1277 }
1278 }
1279
1280 if (!dx12Buf->GetD3DBuffer()) return;
1281 commandList->SetGraphicsRootConstantBufferView(
1282 slot, dx12Buf->GetD3DBuffer()->GetGPUVirtualAddress());
1283}
1284
1285BufferBase* DirectX12Renderer::CreateBuffer(BufferType Type, uint32_t size,
1286 void* data) {
1287 assert(size > 0);
1288 auto* buffer = new DirectX12Buffer(device.Get(), commandQueue.Get(), size,
1289 Type, &m_uploader);
1290 if (!buffer->Initialize(data)) {
1291 delete buffer;
1292 return nullptr;
1293 }
1294 return buffer;
1295}
1296
1297Shader* DirectX12Renderer::CreateShader(const std::string& shaderSource) {
1298 auto* shader = new DirectX12Shader(device.Get());
1299 if (!shader->compile(shaderSource)) {
1300 delete shader;
1301 return nullptr;
1302 }
1303
1304 ID3DBlob* vs = shader->getVertexShaderBlob();
1305 ID3DBlob* ps = shader->getPixelShaderBlob();
1306 if (ID3D12PipelineState* pso = GetShaderPipeline(vs, ps)) {
1307 shader->SetPipelineState(
1308 Microsoft::WRL::ComPtr<ID3D12PipelineState>(pso));
1309 if (!m_defaultPipelineState) {
1310 m_defaultPipelineState = pso;
1311 m_cachedVSBlob = vs;
1312 }
1313 }
1314 shader->SetCommandList(commandList.Get());
1315 shader->SetRenderer(this);
1316 return shader;
1317}
1318
1319Texture* DirectX12Renderer::CreateTexture(
1320 const std::string& TexturePath) {
1321 auto* texture = new DirectX12Texture(device.Get(), commandQueue.Get(),
1322 commandList.Get(), &m_uploader);
1323 if (!texture->LoadFromFile(TexturePath)) {
1324 delete texture;
1325 return nullptr;
1326 }
1327 // Place the SRV into the shared heap so we never switch heaps at draw time
1328 UINT slot = AllocateSRVSlot();
1329 texture->CreateSRVIntoHandle(
1330 texture->GetFormat() == TextureFormat::RGBA8 ? DXGI_FORMAT_R8G8B8A8_UNORM : DXGI_FORMAT_R8G8B8A8_UNORM,
1331 GetSharedSrvCPUHandle(slot));
1332 texture->SetSharedSrvGPUHandle(GetSharedSrvGPUHandle(slot));
1333 return texture;
1334}
1335
1336Texture* DirectX12Renderer::CreateTextureFromData(uint32_t width,
1337 uint32_t height,
1338 void* data) {
1339 auto* texture = new DirectX12Texture(device.Get(), commandQueue.Get(),
1340 commandList.Get(), &m_uploader);
1341 if (!texture->LoadFromMemory(data, width, height,
1342 TextureFormat::RGBA8)) {
1343 delete texture;
1344 return nullptr;
1345 }
1346 // Place the SRV into the shared heap
1347 UINT slot = AllocateSRVSlot();
1348 texture->CreateSRVIntoHandle(DXGI_FORMAT_R8G8B8A8_UNORM,
1349 GetSharedSrvCPUHandle(slot));
1350 texture->SetSharedSrvGPUHandle(GetSharedSrvGPUHandle(slot));
1351 return texture;
1352}
1353
1354Texture* DirectX12Renderer::CreateCubemapTexture(
1355 const std::array<std::string, 6>& facePaths) {
1356 auto* texture = new DirectX12CubemapTexture(
1357 device.Get(), commandQueue.Get(), &m_uploader);
1358 if (!texture->LoadCubemap(facePaths)) {
1359 delete texture;
1360 return nullptr;
1361 }
1362 UINT slot = AllocateSRVSlot();
1363 texture->CreateSRVIntoHandle(GetSharedSrvCPUHandle(slot));
1364 texture->SetSharedSrvGPUHandle(GetSharedSrvGPUHandle(slot));
1365 return texture;
1366}
1367
1368Texture* DirectX12Renderer::CreateCubemapTextureFromPanorama(
1369 const std::string& panoramaPath) {
1370 auto* texture = new DirectX12CubemapTexture(
1371 device.Get(), commandQueue.Get(), &m_uploader);
1372 if (!texture->LoadEquirectangular(panoramaPath)) {
1373 delete texture;
1374 return nullptr;
1375 }
1376 UINT slot = AllocateSRVSlot();
1377 texture->CreateSRVIntoHandle(GetSharedSrvCPUHandle(slot));
1378 texture->SetSharedSrvGPUHandle(GetSharedSrvGPUHandle(slot));
1379 return texture;
1380}
1381
1382void DirectX12Renderer::BindTexture(RefPtr<Sleak::Texture> texture,
1383 uint32_t slot) {
1384 if (!texture.IsValid() || !commandList) return;
1385
1386 if (texture->GetType() == TextureType::TextureCube) {
1387 static_cast<DirectX12CubemapTexture*>(texture.get())
1388 ->BindToCommandList(commandList.Get(), 2);
1389 } else {
1390 static_cast<DirectX12Texture*>(texture.get())
1391 ->BindToCommandList(commandList.Get(), 2);
1392 }
1393}
1394
1395void DirectX12Renderer::BindTextureRaw(Sleak::Texture* texture, uint32_t slot) {
1396 if (!texture || !commandList) return;
1397
1398 if (texture->GetType() == TextureType::TextureCube) {
1399 static_cast<DirectX12CubemapTexture*>(texture)
1400 ->BindToCommandList(commandList.Get(), 2);
1401 return;
1402 }
1403
1404 auto* dx12Tex = static_cast<DirectX12Texture*>(texture);
1405 if (dx12Tex) {
1406 dx12Tex->BindToCommandList(commandList.Get(), 2);
1407 }
1408}
1409
1410void DirectX12Renderer::BindLightConstants() {
1411 DirectX12UploadRing::Allocation alloc;
1412 if (!m_uploadRing.Allocate(m_lightData.size(), alloc)) return;
1413 memcpy(alloc.cpu, m_lightData.data(), m_lightData.size());
1414 commandList->SetGraphicsRootConstantBufferView(3, alloc.gpu);
1415}
1416
1417void DirectX12Renderer::UpdateShadowLightUBO(const void* data, uint32_t size) {
1418 if (!data) return;
1419
1420 size_t copySize = size;
1421 if (copySize > m_lightData.size()) copySize = m_lightData.size();
1422 memcpy(m_lightData.data(), data, copySize);
1423
1424 // The ring slice bound at BeginRender holds last frame's values
1425 if (m_frameActive) BindLightConstants();
1426}
1427
1428void DirectX12Renderer::SetLightVP(const float* mat) {
1429 if (mat) {
1430 memcpy(m_pendingLightVP, mat, sizeof(m_pendingLightVP));
1431 m_hasPendingLightVP = true;
1432 }
1433}
1434
1435bool DirectX12Renderer::CreateShadowMapResources() {
1436 if (m_shadowMapCreated) return true;
1437
1438 // Create shadow DSV heap
1439 D3D12_DESCRIPTOR_HEAP_DESC dsvHeapDesc = {};
1440 dsvHeapDesc.NumDescriptors = 1;
1441 dsvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;
1442 dsvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
1443 if (FAILED(device->CreateDescriptorHeap(&dsvHeapDesc, IID_PPV_ARGS(&m_shadowDsvHeap)))) {
1444 SLEAK_ERROR("Failed to create shadow DSV heap!");
1445 return false;
1446 }
1447 m_shadowDsvHandle = m_shadowDsvHeap->GetCPUDescriptorHandleForHeapStart();
1448
1449 // Create shadow depth texture
1450 D3D12_RESOURCE_DESC depthDesc = {};
1451 depthDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
1452 depthDesc.Width = m_shadowMapResolution;
1453 depthDesc.Height = m_shadowMapResolution;
1454 depthDesc.DepthOrArraySize = 1;
1455 depthDesc.MipLevels = 1;
1456 depthDesc.Format = DXGI_FORMAT_R32_TYPELESS;
1457 depthDesc.SampleDesc.Count = 1;
1458 depthDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
1459
1460 D3D12_CLEAR_VALUE clearValue = {};
1461 clearValue.Format = DXGI_FORMAT_D32_FLOAT;
1462 clearValue.DepthStencil.Depth = 1.0f;
1463
1464 D3D12_HEAP_PROPERTIES heapProps = {};
1465 heapProps.Type = D3D12_HEAP_TYPE_DEFAULT;
1466
1467 if (FAILED(device->CreateCommittedResource(
1468 &heapProps, D3D12_HEAP_FLAG_NONE, &depthDesc,
1469 D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, &clearValue,
1470 IID_PPV_ARGS(&m_shadowDepthBuffer)))) {
1471 SLEAK_ERROR("Failed to create shadow depth buffer!");
1472 return false;
1473 }
1474
1475 // Create DSV
1476 D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc = {};
1477 dsvDesc.Format = DXGI_FORMAT_D32_FLOAT;
1478 dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
1479 device->CreateDepthStencilView(m_shadowDepthBuffer.Get(), &dsvDesc, m_shadowDsvHandle);
1480
1481 // Create SRV in shared heap
1482 m_shadowSrvIndex = AllocateSRVSlot();
1483 D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
1484 srvDesc.Format = DXGI_FORMAT_R32_FLOAT;
1485 srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
1486 srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
1487 srvDesc.Texture2D.MipLevels = 1;
1488 device->CreateShaderResourceView(m_shadowDepthBuffer.Get(), &srvDesc,
1489 GetSharedSrvCPUHandle(m_shadowSrvIndex));
1490
1491 m_shadowMapCreated = true;
1492 m_shadowResourcesCreated = true;
1493 SLEAK_INFO("D3D12 shadow map resources created ({}x{})", m_shadowMapResolution, m_shadowMapResolution);
1494 return true;
1495}
1496
1497void DirectX12Renderer::RenderShadowPass() {
1498 // Skip if no cached draws — preserve previous frame's shadow map
1499 auto* queue = RenderCommandQueue::GetInstance();
1500 if (!queue || !queue->HasCachedShadowDraws()) return;
1501
1502 if (!m_shadowMapCreated) {
1503 if (!CreateShadowMapResources()) return;
1504 }
1505 if (!CreateShadowPassPSO()) return;
1506
1507 // Transition shadow buffer to depth write
1508 D3D12_RESOURCE_BARRIER barrier = {};
1509 barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
1510 barrier.Transition.pResource = m_shadowDepthBuffer.Get();
1511 barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
1512 barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_DEPTH_WRITE;
1513 barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
1514 commandList->ResourceBarrier(1, &barrier);
1515
1516 // Set shadow DSV (no RTV)
1517 commandList->OMSetRenderTargets(0, nullptr, FALSE, &m_shadowDsvHandle);
1518 commandList->ClearDepthStencilView(m_shadowDsvHandle, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr);
1519
1520 // Set shadow viewport
1521 D3D12_VIEWPORT shadowViewport = {};
1522 shadowViewport.Width = static_cast<float>(m_shadowMapResolution);
1523 shadowViewport.Height = static_cast<float>(m_shadowMapResolution);
1524 shadowViewport.MinDepth = 0.0f;
1525 shadowViewport.MaxDepth = 1.0f;
1526 commandList->RSSetViewports(1, &shadowViewport);
1527
1528 D3D12_RECT shadowScissor = {};
1529 shadowScissor.right = m_shadowMapResolution;
1530 shadowScissor.bottom = m_shadowMapResolution;
1531 commandList->RSSetScissorRects(1, &shadowScissor);
1532
1533 // Depth-only shadow PSO (no PS, no RTV, CULL_NONE + depth bias)
1534 commandList->SetPipelineState(m_shadowPassPSO);
1535 commandList->SetGraphicsRootSignature(rootSignature.Get());
1536 commandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
1537
1538 // Re-bind SRV heap
1539 ID3D12DescriptorHeap* srvHeaps[] = {m_sharedSrvHeap.Get()};
1540 commandList->SetDescriptorHeaps(1, srvHeaps);
1541
1542 // Bind default texture so draws with texture lookups don't crash
1543 if (m_defaultTexture) {
1544 m_defaultTexture->Bind(0);
1545 }
1546 BindLightConstants();
1547
1548 // Ring memory is per frame and lightVP may have changed since last pass
1549 m_shadowCBAddress = 0;
1550
1551 // Execute shadow draw commands
1552 m_inShadowPass = true;
1553 if (queue) {
1554 queue->ExecuteShadowPass(this);
1555 }
1556 m_inShadowPass = false;
1557
1558 // Transition back to shader resource
1559 barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_DEPTH_WRITE;
1560 barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
1561 commandList->ResourceBarrier(1, &barrier);
1562}
1563
1564bool DirectX12Renderer::CreateSkyboxPipelineState() {
1565 if (m_skyboxPipelineState) return true;
1566 if (m_skyboxPipelineFailed) return false;
1567 m_skyboxPipelineFailed = true;
1568
1569 auto vs = CompileStage(SKYBOX_SHADER_PATH, VERTEX_ENTRY, VERTEX_PROFILE);
1570 auto ps = CompileStage(SKYBOX_SHADER_PATH, PIXEL_ENTRY, PIXEL_PROFILE);
1571 if (!vs || !ps) return false;
1572
1573 // No culling, depth write off with LEQUAL, and depth clip off so the
1574 // .xyww trick at z=1.0 is not clipped
1575 PipelineKey key;
1576 key.vsHash = HashBytecode(vs.Get());
1577 key.psHash = HashBytecode(ps.Get());
1578 key.cullMode = D3D12_CULL_MODE_NONE;
1579 key.depthClip = FALSE;
1580 key.depthWrite = D3D12_DEPTH_WRITE_MASK_ZERO;
1581 key.depthFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL;
1582
1583 m_skyboxPipelineState = GetPipeline(key, vs.Get(), ps.Get());
1584 if (!m_skyboxPipelineState) return false;
1585
1586 m_skyboxPipelineFailed = false;
1587 SLEAK_INFO("DirectX 12 skybox pipeline state created successfully");
1588 return true;
1589}
1590
1591void DirectX12Renderer::BindShaderPipeline(ID3D12PipelineState* pso) {
1592 if (!pso || !commandList) return;
1593 m_shaderPipeline = pso;
1594 if (m_passPipeline) return;
1595 commandList->SetPipelineState(pso);
1596}
1597
1598void DirectX12Renderer::RestoreShaderPipeline() {
1599 ID3D12PipelineState* pso =
1600 m_shaderPipeline ? m_shaderPipeline : m_defaultPipelineState;
1601 if (pso) commandList->SetPipelineState(pso);
1602}
1603
1604void DirectX12Renderer::BeginSkyboxPass() {
1605 if (!CreateSkyboxPipelineState()) {
1606 SLEAK_WARN("BeginSkyboxPass: failed to create skybox PSO");
1607 return;
1608 }
1609 m_passPipeline = m_skyboxPipelineState;
1610 commandList->SetPipelineState(m_skyboxPipelineState);
1611}
1612
1613void DirectX12Renderer::EndSkyboxPass() {
1614 m_passPipeline = nullptr;
1615 RestoreShaderPipeline();
1616}
1617
1618bool DirectX12Renderer::CreateDebugLinePipelineState() {
1619 if (m_debugLinePipelineState) return true;
1620 if (m_debugLinePipelineFailed) return false;
1621 m_debugLinePipelineFailed = true;
1622
1623 auto vs =
1624 CompileStage(DEBUG_LINE_SHADER_PATH, VERTEX_ENTRY, VERTEX_PROFILE);
1625 auto ps = CompileStage(DEBUG_LINE_SHADER_PATH, PIXEL_ENTRY, PIXEL_PROFILE);
1626 if (!vs || !ps) return false;
1627
1628 PipelineKey key;
1629 key.vsHash = HashBytecode(vs.Get());
1630 key.psHash = HashBytecode(ps.Get());
1631 key.cullMode = D3D12_CULL_MODE_NONE;
1632 key.depthFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL;
1633 key.topology = D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE;
1634
1635 m_debugLinePipelineState = GetPipeline(key, vs.Get(), ps.Get());
1636 if (!m_debugLinePipelineState) return false;
1637
1638 m_debugLinePipelineFailed = false;
1639 SLEAK_INFO("DirectX 12 debug line pipeline state created successfully");
1640 return true;
1641}
1642
1643void DirectX12Renderer::BeginDebugLinePass() {
1644 if (!CreateDebugLinePipelineState()) {
1645 SLEAK_WARN("BeginDebugLinePass: failed to create debug line PSO");
1646 return;
1647 }
1648 m_passPipeline = m_debugLinePipelineState;
1649 commandList->SetPipelineState(m_debugLinePipelineState);
1650 commandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_LINELIST);
1651}
1652
1653void DirectX12Renderer::EndDebugLinePass() {
1654 m_passPipeline = nullptr;
1655 RestoreShaderPipeline();
1656 commandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
1657}
1658
1659void DirectX12Renderer::ConfigureRenderMode() {
1660 // In DX12, fill mode and topology are baked into the PSO.
1661 // For now, we only support the default solid fill + triangle list.
1662 // A full implementation would cache multiple PSO variants.
1663}
1664
1665void DirectX12Renderer::ConfigureRenderFace() {
1666 // In DX12, cull mode is baked into the PSO.
1667 // A full implementation would cache multiple PSO variants.
1668}
1669
1670void DirectX12Renderer::EnumerateDevices(
1671 Microsoft::WRL::ComPtr<IDXGIFactory4> factory) {
1672 UINT adapter_index = 0;
1673 IDXGIAdapter1* tempadapter;
1674 while (factory->EnumAdapters1(adapter_index, &tempadapter) !=
1675 DXGI_ERROR_NOT_FOUND) {
1676 DXGI_ADAPTER_DESC1 desc;
1677 tempadapter->GetDesc1(&desc);
1678
1679#ifdef _DEBUG
1680 std::wstring wgpu_name = L"Found GPU: ";
1681 wgpu_name += desc.Description;
1682 std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
1683 std::string gpu_name = converter.to_bytes(wgpu_name);
1684 SLEAK_INFO(gpu_name);
1685#endif
1686
1687 if (adapter == nullptr &&
1688 (desc.VendorId == 0x10DE || desc.VendorId == 0x1002)) {
1689 adapter.Attach(tempadapter);
1690 } else {
1691 tempadapter->Release();
1692 }
1693
1694 adapter_index++;
1695 }
1696
1697 SLEAK_INFO("Found {} GPUs", adapter_index);
1698}
1699
1700bool DirectX12Renderer::IsSupport() {
1701 Microsoft::WRL::ComPtr<ID3D12Device> testDevice;
1702 HRESULT hr = D3D12CreateDevice(nullptr, D3D_FEATURE_LEVEL_11_0,
1703 IID_PPV_ARGS(&testDevice));
1704 return SUCCEEDED(hr);
1705}
1706
1707bool DirectX12Renderer::CreateImGUI() {
1708 if (!device || !commandQueue || !m_sharedSrvHeap)
1709 return false;
1710
1711 // Allocate a slot in the shared SRV heap for ImGui's font texture
1712 UINT imguiSlot = AllocateSRVSlot();
1713 D3D12_CPU_DESCRIPTOR_HANDLE imguiCpuHandle = GetSharedSrvCPUHandle(imguiSlot);
1714 D3D12_GPU_DESCRIPTOR_HANDLE imguiGpuHandle = GetSharedSrvGPUHandle(imguiSlot);
1715
1716 IMGUI_CHECKVERSION();
1717 ImGui::CreateContext();
1718 ImGui::GetIO().ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
1719 ImGui::StyleColorsDark();
1720
1721 if (!ImGui_ImplSDL3_InitForD3D(window->GetSDLWindow()))
1722 return false;
1723
1724 ImGui_ImplDX12_InitInfo imguiInit;
1725 imguiInit.Device = device.Get();
1726 imguiInit.CommandQueue = commandQueue.Get();
1727 imguiInit.NumFramesInFlight = FrameCount;
1728 imguiInit.RTVFormat = DXGI_FORMAT_R8G8B8A8_UNORM;
1729 imguiInit.DSVFormat = DXGI_FORMAT_D32_FLOAT;
1730 imguiInit.SrvDescriptorHeap = m_sharedSrvHeap.Get();
1731 imguiInit.LegacySingleSrvCpuDescriptor = imguiCpuHandle;
1732 imguiInit.LegacySingleSrvGpuDescriptor = imguiGpuHandle;
1733
1734 if (!ImGui_ImplDX12_Init(&imguiInit)) return false;
1735
1736 bImInitialized = true;
1737 return true;
1738}
1739
1740} // namespace RenderEngine
1741} // namespace Sleak
1742
1743#endif
int width
int height
#define SLEAK_ERROR(...)
Definition Logger.hpp:22
#define SLEAK_INFO(...)
Definition Logger.hpp:20
#define SLEAK_WARN(...)
Definition Logger.hpp:21
virtual TextureType GetType() const =0
Backend-facing rendering layer shared by the four graphics backends.
Root namespace for everything the engine exposes.
Definition Camera.hpp:10
class ENGINE_API Window