imgui_impl_dx12.cpp
Go to the documentation of this file.
1 // dear imgui: Renderer for DirectX12
2 // This needs to be used along with a Platform Binding (e.g. Win32)
3 
4 // Implemented features:
5 // [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID!
6 // [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices.
7 // Issues:
8 // [ ] 64-bit only for now! (Because sizeof(ImTextureId) == sizeof(void*)). See github.com/ocornut/imgui/pull/301
9 
10 // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
11 // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp.
12 // https://github.com/ocornut/imgui
13 
14 // CHANGELOG
15 // (minor and older changes stripped away, please see git history for details)
16 // 2019-10-18: DirectX12: *BREAKING CHANGE* Added extra ID3D12DescriptorHeap parameter to ImGui_ImplDX12_Init() function.
17 // 2019-05-29: DirectX12: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
18 // 2019-04-30: DirectX12: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
19 // 2019-03-29: Misc: Various minor tidying up.
20 // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile().
21 // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
22 // 2018-06-12: DirectX12: Moved the ID3D12GraphicsCommandList* parameter from NewFrame() to RenderDrawData().
23 // 2018-06-08: Misc: Extracted imgui_impl_dx12.cpp/.h away from the old combined DX12+Win32 example.
24 // 2018-06-08: DirectX12: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle (to ease support for future multi-viewport).
25 // 2018-02-22: Merged into master with all Win32 code synchronized to other examples.
26 
27 #include "imgui.h"
28 #include "imgui_impl_dx12.h"
29 
30 // DirectX
31 #include <d3d12.h>
32 #include <dxgi1_4.h>
33 #include <d3dcompiler.h>
34 #ifdef _MSC_VER
35 #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below.
36 #endif
37 
38 // DirectX data
39 static ID3D12Device* g_pd3dDevice = NULL;
40 static ID3D10Blob* g_pVertexShaderBlob = NULL;
41 static ID3D10Blob* g_pPixelShaderBlob = NULL;
42 static ID3D12RootSignature* g_pRootSignature = NULL;
43 static ID3D12PipelineState* g_pPipelineState = NULL;
44 static DXGI_FORMAT g_RTVFormat = DXGI_FORMAT_UNKNOWN;
45 static ID3D12Resource* g_pFontTextureResource = NULL;
46 static D3D12_CPU_DESCRIPTOR_HANDLE g_hFontSrvCpuDescHandle = {};
47 static D3D12_GPU_DESCRIPTOR_HANDLE g_hFontSrvGpuDescHandle = {};
48 
50 {
51  ID3D12Resource* IndexBuffer;
52  ID3D12Resource* VertexBuffer;
55 };
57 static UINT g_numFramesInFlight = 0;
58 static UINT g_frameIndex = UINT_MAX;
59 
60 template<typename T>
61 static void SafeRelease(T*& res)
62 {
63  if (res)
64  res->Release();
65  res = NULL;
66 }
67 
69 {
70  float mvp[4][4];
71 };
72 
73 static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12GraphicsCommandList* ctx, FrameResources* fr)
74 {
75  // Setup orthographic projection matrix into our constant buffer
76  // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
77  VERTEX_CONSTANT_BUFFER vertex_constant_buffer;
78  {
79  float L = draw_data->DisplayPos.x;
80  float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
81  float T = draw_data->DisplayPos.y;
82  float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
83  float mvp[4][4] =
84  {
85  { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
86  { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
87  { 0.0f, 0.0f, 0.5f, 0.0f },
88  { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
89  };
90  memcpy(&vertex_constant_buffer.mvp, mvp, sizeof(mvp));
91  }
92 
93  // Setup viewport
94  D3D12_VIEWPORT vp;
95  memset(&vp, 0, sizeof(D3D12_VIEWPORT));
96  vp.Width = draw_data->DisplaySize.x;
97  vp.Height = draw_data->DisplaySize.y;
98  vp.MinDepth = 0.0f;
99  vp.MaxDepth = 1.0f;
100  vp.TopLeftX = vp.TopLeftY = 0.0f;
101  ctx->RSSetViewports(1, &vp);
102 
103  // Bind shader and vertex buffers
104  unsigned int stride = sizeof(ImDrawVert);
105  unsigned int offset = 0;
106  D3D12_VERTEX_BUFFER_VIEW vbv;
107  memset(&vbv, 0, sizeof(D3D12_VERTEX_BUFFER_VIEW));
108  vbv.BufferLocation = fr->VertexBuffer->GetGPUVirtualAddress() + offset;
109  vbv.SizeInBytes = fr->VertexBufferSize * stride;
110  vbv.StrideInBytes = stride;
111  ctx->IASetVertexBuffers(0, 1, &vbv);
112  D3D12_INDEX_BUFFER_VIEW ibv;
113  memset(&ibv, 0, sizeof(D3D12_INDEX_BUFFER_VIEW));
114  ibv.BufferLocation = fr->IndexBuffer->GetGPUVirtualAddress();
115  ibv.SizeInBytes = fr->IndexBufferSize * sizeof(ImDrawIdx);
116  ibv.Format = sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT;
117  ctx->IASetIndexBuffer(&ibv);
118  ctx->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
119  ctx->SetPipelineState(g_pPipelineState);
120  ctx->SetGraphicsRootSignature(g_pRootSignature);
121  ctx->SetGraphicsRoot32BitConstants(0, 16, &vertex_constant_buffer, 0);
122 
123  // Setup blend factor
124  const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
125  ctx->OMSetBlendFactor(blend_factor);
126 }
127 
128 // Render function
129 // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
130 void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* ctx)
131 {
132  // Avoid rendering when minimized
133  if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
134  return;
135 
136  // FIXME: I'm assuming that this only gets called once per frame!
137  // If not, we can't just re-allocate the IB or VB, we'll have to do a proper allocator.
140 
141  // Create and grow vertex/index buffers if needed
142  if (fr->VertexBuffer == NULL || fr->VertexBufferSize < draw_data->TotalVtxCount)
143  {
145  fr->VertexBufferSize = draw_data->TotalVtxCount + 5000;
146  D3D12_HEAP_PROPERTIES props;
147  memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
148  props.Type = D3D12_HEAP_TYPE_UPLOAD;
149  props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
150  props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
151  D3D12_RESOURCE_DESC desc;
152  memset(&desc, 0, sizeof(D3D12_RESOURCE_DESC));
153  desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
154  desc.Width = fr->VertexBufferSize * sizeof(ImDrawVert);
155  desc.Height = 1;
156  desc.DepthOrArraySize = 1;
157  desc.MipLevels = 1;
158  desc.Format = DXGI_FORMAT_UNKNOWN;
159  desc.SampleDesc.Count = 1;
160  desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
161  desc.Flags = D3D12_RESOURCE_FLAG_NONE;
162  if (g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&fr->VertexBuffer)) < 0)
163  return;
164  }
165  if (fr->IndexBuffer == NULL || fr->IndexBufferSize < draw_data->TotalIdxCount)
166  {
168  fr->IndexBufferSize = draw_data->TotalIdxCount + 10000;
169  D3D12_HEAP_PROPERTIES props;
170  memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
171  props.Type = D3D12_HEAP_TYPE_UPLOAD;
172  props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
173  props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
174  D3D12_RESOURCE_DESC desc;
175  memset(&desc, 0, sizeof(D3D12_RESOURCE_DESC));
176  desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
177  desc.Width = fr->IndexBufferSize * sizeof(ImDrawIdx);
178  desc.Height = 1;
179  desc.DepthOrArraySize = 1;
180  desc.MipLevels = 1;
181  desc.Format = DXGI_FORMAT_UNKNOWN;
182  desc.SampleDesc.Count = 1;
183  desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
184  desc.Flags = D3D12_RESOURCE_FLAG_NONE;
185  if (g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&fr->IndexBuffer)) < 0)
186  return;
187  }
188 
189  // Upload vertex/index data into a single contiguous GPU buffer
190  void* vtx_resource, *idx_resource;
191  D3D12_RANGE range;
192  memset(&range, 0, sizeof(D3D12_RANGE));
193  if (fr->VertexBuffer->Map(0, &range, &vtx_resource) != S_OK)
194  return;
195  if (fr->IndexBuffer->Map(0, &range, &idx_resource) != S_OK)
196  return;
197  ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource;
198  ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource;
199  for (int n = 0; n < draw_data->CmdListsCount; n++)
200  {
201  const ImDrawList* cmd_list = draw_data->CmdLists[n];
202  memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
203  memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
204  vtx_dst += cmd_list->VtxBuffer.Size;
205  idx_dst += cmd_list->IdxBuffer.Size;
206  }
207  fr->VertexBuffer->Unmap(0, &range);
208  fr->IndexBuffer->Unmap(0, &range);
209 
210  // Setup desired DX state
211  ImGui_ImplDX12_SetupRenderState(draw_data, ctx, fr);
212 
213  // Render command lists
214  // (Because we merged all buffers into a single one, we maintain our own offset into them)
215  int global_vtx_offset = 0;
216  int global_idx_offset = 0;
217  ImVec2 clip_off = draw_data->DisplayPos;
218  for (int n = 0; n < draw_data->CmdListsCount; n++)
219  {
220  const ImDrawList* cmd_list = draw_data->CmdLists[n];
221  for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
222  {
223  const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
224  if (pcmd->UserCallback != NULL)
225  {
226  // User callback, registered via ImDrawList::AddCallback()
227  // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
229  ImGui_ImplDX12_SetupRenderState(draw_data, ctx, fr);
230  else
231  pcmd->UserCallback(cmd_list, pcmd);
232  }
233  else
234  {
235  // Apply Scissor, Bind texture, Draw
236  const D3D12_RECT r = { (LONG)(pcmd->ClipRect.x - clip_off.x), (LONG)(pcmd->ClipRect.y - clip_off.y), (LONG)(pcmd->ClipRect.z - clip_off.x), (LONG)(pcmd->ClipRect.w - clip_off.y) };
237  ctx->SetGraphicsRootDescriptorTable(1, *(D3D12_GPU_DESCRIPTOR_HANDLE*)&pcmd->TextureId);
238  ctx->RSSetScissorRects(1, &r);
239  ctx->DrawIndexedInstanced(pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
240  }
241  }
242  global_idx_offset += cmd_list->IdxBuffer.Size;
243  global_vtx_offset += cmd_list->VtxBuffer.Size;
244  }
245 }
246 
248 {
249  // Build texture atlas
250  ImGuiIO& io = ImGui::GetIO();
251  unsigned char* pixels;
252  int width, height;
254 
255  // Upload texture to graphics system
256  {
257  D3D12_HEAP_PROPERTIES props;
258  memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
259  props.Type = D3D12_HEAP_TYPE_DEFAULT;
260  props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
261  props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
262 
263  D3D12_RESOURCE_DESC desc;
264  ZeroMemory(&desc, sizeof(desc));
265  desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
266  desc.Alignment = 0;
267  desc.Width = width;
268  desc.Height = height;
269  desc.DepthOrArraySize = 1;
270  desc.MipLevels = 1;
271  desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
272  desc.SampleDesc.Count = 1;
273  desc.SampleDesc.Quality = 0;
274  desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
275  desc.Flags = D3D12_RESOURCE_FLAG_NONE;
276 
277  ID3D12Resource* pTexture = NULL;
278  g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
279  D3D12_RESOURCE_STATE_COPY_DEST, NULL, IID_PPV_ARGS(&pTexture));
280 
281  UINT uploadPitch = (width * 4 + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u);
282  UINT uploadSize = height * uploadPitch;
283  desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
284  desc.Alignment = 0;
285  desc.Width = uploadSize;
286  desc.Height = 1;
287  desc.DepthOrArraySize = 1;
288  desc.MipLevels = 1;
289  desc.Format = DXGI_FORMAT_UNKNOWN;
290  desc.SampleDesc.Count = 1;
291  desc.SampleDesc.Quality = 0;
292  desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
293  desc.Flags = D3D12_RESOURCE_FLAG_NONE;
294 
295  props.Type = D3D12_HEAP_TYPE_UPLOAD;
296  props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
297  props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
298 
299  ID3D12Resource* uploadBuffer = NULL;
300  HRESULT hr = g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
301  D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&uploadBuffer));
302  IM_ASSERT(SUCCEEDED(hr));
303 
304  void* mapped = NULL;
305  D3D12_RANGE range = { 0, uploadSize };
306  hr = uploadBuffer->Map(0, &range, &mapped);
307  IM_ASSERT(SUCCEEDED(hr));
308  for (int y = 0; y < height; y++)
309  memcpy((void*) ((uintptr_t) mapped + y * uploadPitch), pixels + y * width * 4, width * 4);
310  uploadBuffer->Unmap(0, &range);
311 
312  D3D12_TEXTURE_COPY_LOCATION srcLocation = {};
313  srcLocation.pResource = uploadBuffer;
314  srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
315  srcLocation.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
316  srcLocation.PlacedFootprint.Footprint.Width = width;
317  srcLocation.PlacedFootprint.Footprint.Height = height;
318  srcLocation.PlacedFootprint.Footprint.Depth = 1;
319  srcLocation.PlacedFootprint.Footprint.RowPitch = uploadPitch;
320 
321  D3D12_TEXTURE_COPY_LOCATION dstLocation = {};
322  dstLocation.pResource = pTexture;
323  dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
324  dstLocation.SubresourceIndex = 0;
325 
326  D3D12_RESOURCE_BARRIER barrier = {};
327  barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
328  barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
329  barrier.Transition.pResource = pTexture;
330  barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
331  barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST;
332  barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
333 
334  ID3D12Fence* fence = NULL;
335  hr = g_pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence));
336  IM_ASSERT(SUCCEEDED(hr));
337 
338  HANDLE event = CreateEvent(0, 0, 0, 0);
339  IM_ASSERT(event != NULL);
340 
341  D3D12_COMMAND_QUEUE_DESC queueDesc = {};
342  queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
343  queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
344  queueDesc.NodeMask = 1;
345 
346  ID3D12CommandQueue* cmdQueue = NULL;
347  hr = g_pd3dDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&cmdQueue));
348  IM_ASSERT(SUCCEEDED(hr));
349 
350  ID3D12CommandAllocator* cmdAlloc = NULL;
351  hr = g_pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&cmdAlloc));
352  IM_ASSERT(SUCCEEDED(hr));
353 
354  ID3D12GraphicsCommandList* cmdList = NULL;
355  hr = g_pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, cmdAlloc, NULL, IID_PPV_ARGS(&cmdList));
356  IM_ASSERT(SUCCEEDED(hr));
357 
358  cmdList->CopyTextureRegion(&dstLocation, 0, 0, 0, &srcLocation, NULL);
359  cmdList->ResourceBarrier(1, &barrier);
360 
361  hr = cmdList->Close();
362  IM_ASSERT(SUCCEEDED(hr));
363 
364  cmdQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*) &cmdList);
365  hr = cmdQueue->Signal(fence, 1);
366  IM_ASSERT(SUCCEEDED(hr));
367 
368  fence->SetEventOnCompletion(1, event);
369  WaitForSingleObject(event, INFINITE);
370 
371  cmdList->Release();
372  cmdAlloc->Release();
373  cmdQueue->Release();
374  CloseHandle(event);
375  fence->Release();
376  uploadBuffer->Release();
377 
378  // Create texture view
379  D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc;
380  ZeroMemory(&srvDesc, sizeof(srvDesc));
381  srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
382  srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
383  srvDesc.Texture2D.MipLevels = desc.MipLevels;
384  srvDesc.Texture2D.MostDetailedMip = 0;
385  srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
386  g_pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, g_hFontSrvCpuDescHandle);
388  g_pFontTextureResource = pTexture;
389  }
390 
391  // Store our identifier
392  static_assert(sizeof(ImTextureID) >= sizeof(g_hFontSrvGpuDescHandle.ptr), "Can't pack descriptor handle into TexID, 32-bit not supported yet.");
394 }
395 
397 {
398  if (!g_pd3dDevice)
399  return false;
400  if (g_pPipelineState)
402 
403  // Create the root signature
404  {
405  D3D12_DESCRIPTOR_RANGE descRange = {};
406  descRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
407  descRange.NumDescriptors = 1;
408  descRange.BaseShaderRegister = 0;
409  descRange.RegisterSpace = 0;
410  descRange.OffsetInDescriptorsFromTableStart = 0;
411 
412  D3D12_ROOT_PARAMETER param[2] = {};
413 
414  param[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
415  param[0].Constants.ShaderRegister = 0;
416  param[0].Constants.RegisterSpace = 0;
417  param[0].Constants.Num32BitValues = 16;
418  param[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
419 
420  param[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
421  param[1].DescriptorTable.NumDescriptorRanges = 1;
422  param[1].DescriptorTable.pDescriptorRanges = &descRange;
423  param[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
424 
425  D3D12_STATIC_SAMPLER_DESC staticSampler = {};
426  staticSampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
427  staticSampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
428  staticSampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
429  staticSampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
430  staticSampler.MipLODBias = 0.f;
431  staticSampler.MaxAnisotropy = 0;
432  staticSampler.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS;
433  staticSampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK;
434  staticSampler.MinLOD = 0.f;
435  staticSampler.MaxLOD = 0.f;
436  staticSampler.ShaderRegister = 0;
437  staticSampler.RegisterSpace = 0;
438  staticSampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
439 
440  D3D12_ROOT_SIGNATURE_DESC desc = {};
441  desc.NumParameters = _countof(param);
442  desc.pParameters = param;
443  desc.NumStaticSamplers = 1;
444  desc.pStaticSamplers = &staticSampler;
445  desc.Flags =
446  D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT |
447  D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |
448  D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |
449  D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS;
450 
451  ID3DBlob* blob = NULL;
452  if (D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, NULL) != S_OK)
453  return false;
454 
455  g_pd3dDevice->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&g_pRootSignature));
456  blob->Release();
457  }
458 
459  // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
460  // If you would like to use this DX12 sample code but remove this dependency you can:
461  // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution]
462  // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
463  // See https://github.com/ocornut/imgui/pull/638 for sources and details.
464 
465  D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc;
466  memset(&psoDesc, 0, sizeof(D3D12_GRAPHICS_PIPELINE_STATE_DESC));
467  psoDesc.NodeMask = 1;
468  psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
469  psoDesc.pRootSignature = g_pRootSignature;
470  psoDesc.SampleMask = UINT_MAX;
471  psoDesc.NumRenderTargets = 1;
472  psoDesc.RTVFormats[0] = g_RTVFormat;
473  psoDesc.SampleDesc.Count = 1;
474  psoDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
475 
476  // Create the vertex shader
477  {
478  static const char* vertexShader =
479  "cbuffer vertexBuffer : register(b0) \
480  {\
481  float4x4 ProjectionMatrix; \
482  };\
483  struct VS_INPUT\
484  {\
485  float2 pos : POSITION;\
486  float4 col : COLOR0;\
487  float2 uv : TEXCOORD0;\
488  };\
489  \
490  struct PS_INPUT\
491  {\
492  float4 pos : SV_POSITION;\
493  float4 col : COLOR0;\
494  float2 uv : TEXCOORD0;\
495  };\
496  \
497  PS_INPUT main(VS_INPUT input)\
498  {\
499  PS_INPUT output;\
500  output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
501  output.col = input.col;\
502  output.uv = input.uv;\
503  return output;\
504  }";
505 
506  D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_5_0", 0, 0, &g_pVertexShaderBlob, NULL);
507  if (g_pVertexShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
508  return false;
509  psoDesc.VS = { g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize() };
510 
511  // Create the input layout
512  static D3D12_INPUT_ELEMENT_DESC local_layout[] = {
513  { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, pos), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
514  { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, uv), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
515  { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)IM_OFFSETOF(ImDrawVert, col), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
516  };
517  psoDesc.InputLayout = { local_layout, 3 };
518  }
519 
520  // Create the pixel shader
521  {
522  static const char* pixelShader =
523  "struct PS_INPUT\
524  {\
525  float4 pos : SV_POSITION;\
526  float4 col : COLOR0;\
527  float2 uv : TEXCOORD0;\
528  };\
529  SamplerState sampler0 : register(s0);\
530  Texture2D texture0 : register(t0);\
531  \
532  float4 main(PS_INPUT input) : SV_Target\
533  {\
534  float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
535  return out_col; \
536  }";
537 
538  D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_5_0", 0, 0, &g_pPixelShaderBlob, NULL);
539  if (g_pPixelShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
540  return false;
541  psoDesc.PS = { g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize() };
542  }
543 
544  // Create the blending setup
545  {
546  D3D12_BLEND_DESC& desc = psoDesc.BlendState;
547  desc.AlphaToCoverageEnable = false;
548  desc.RenderTarget[0].BlendEnable = true;
549  desc.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA;
550  desc.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA;
551  desc.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD;
552  desc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA;
553  desc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_ZERO;
554  desc.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD;
555  desc.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
556  }
557 
558  // Create the rasterizer state
559  {
560  D3D12_RASTERIZER_DESC& desc = psoDesc.RasterizerState;
561  desc.FillMode = D3D12_FILL_MODE_SOLID;
562  desc.CullMode = D3D12_CULL_MODE_NONE;
563  desc.FrontCounterClockwise = FALSE;
564  desc.DepthBias = D3D12_DEFAULT_DEPTH_BIAS;
565  desc.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;
566  desc.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS;
567  desc.DepthClipEnable = true;
568  desc.MultisampleEnable = FALSE;
569  desc.AntialiasedLineEnable = FALSE;
570  desc.ForcedSampleCount = 0;
571  desc.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
572  }
573 
574  // Create depth-stencil State
575  {
576  D3D12_DEPTH_STENCIL_DESC& desc = psoDesc.DepthStencilState;
577  desc.DepthEnable = false;
578  desc.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
579  desc.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS;
580  desc.StencilEnable = false;
581  desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D12_STENCIL_OP_KEEP;
582  desc.FrontFace.StencilFunc = D3D12_COMPARISON_FUNC_ALWAYS;
583  desc.BackFace = desc.FrontFace;
584  }
585 
586  if (g_pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&g_pPipelineState)) != S_OK)
587  return false;
588 
590 
591  return true;
592 }
593 
595 {
596  if (!g_pd3dDevice)
597  return;
598 
604 
605  ImGuiIO& io = ImGui::GetIO();
606  io.Fonts->TexID = NULL; // We copied g_pFontTextureView to io.Fonts->TexID so let's clear that as well.
607 
608  for (UINT i = 0; i < g_numFramesInFlight; i++)
609  {
613  }
614 }
615 
616 bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, ID3D12DescriptorHeap* cbv_srv_heap,
617  D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle)
618 {
619  // Setup back-end capabilities flags
620  ImGuiIO& io = ImGui::GetIO();
621  io.BackendRendererName = "imgui_impl_dx12";
622  io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
623 
624  g_pd3dDevice = device;
625  g_RTVFormat = rtv_format;
626  g_hFontSrvCpuDescHandle = font_srv_cpu_desc_handle;
627  g_hFontSrvGpuDescHandle = font_srv_gpu_desc_handle;
628  g_pFrameResources = new FrameResources[num_frames_in_flight];
629  g_numFramesInFlight = num_frames_in_flight;
630  g_frameIndex = UINT_MAX;
631  IM_UNUSED(cbv_srv_heap); // Unused in master branch (will be used by multi-viewports)
632 
633  // Create buffers with a default size (they will later be grown as needed)
634  for (int i = 0; i < num_frames_in_flight; i++)
635  {
637  fr->IndexBuffer = NULL;
638  fr->VertexBuffer = NULL;
639  fr->IndexBufferSize = 10000;
640  fr->VertexBufferSize = 5000;
641  }
642 
643  return true;
644 }
645 
647 {
649  delete[] g_pFrameResources;
651  g_pd3dDevice = NULL;
652  g_hFontSrvCpuDescHandle.ptr = 0;
653  g_hFontSrvGpuDescHandle.ptr = 0;
655  g_frameIndex = UINT_MAX;
656 }
657 
659 {
660  if (!g_pPipelineState)
662 }
ImGui_ImplDX12_SetupRenderState
static void ImGui_ImplDX12_SetupRenderState(ImDrawData *draw_data, ID3D12GraphicsCommandList *ctx, FrameResources *fr)
Definition: imgui_impl_dx12.cpp:73
ImDrawIdx
unsigned short ImDrawIdx
Definition: imgui.h:1888
height
GLint GLsizei GLsizei height
Definition: glcorearb.h:2768
ImDrawCmd::VtxOffset
unsigned int VtxOffset
Definition: imgui.h:1876
ImDrawData::DisplayPos
ImVec2 DisplayPos
Definition: imgui.h:2075
ImGuiIO::Fonts
ImFontAtlas * Fonts
Definition: imgui.h:1435
ImDrawList::IdxBuffer
ImVector< ImDrawIdx > IdxBuffer
Definition: imgui.h:1965
ImFontAtlas::TexID
ImTextureID TexID
Definition: imgui.h:2247
ImDrawData::CmdListsCount
int CmdListsCount
Definition: imgui.h:2072
NULL
NULL
Definition: test_security_zap.cpp:405
ImGui_ImplDX12_Init
bool ImGui_ImplDX12_Init(ID3D12Device *device, int num_frames_in_flight, DXGI_FORMAT rtv_format, ID3D12DescriptorHeap *cbv_srv_heap, D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle)
Definition: imgui_impl_dx12.cpp:616
ImVec4::z
float z
Definition: imgui.h:223
g_pFrameResources
static FrameResources * g_pFrameResources
Definition: imgui_impl_dx12.cpp:56
VERTEX_CONSTANT_BUFFER
Definition: imgui_impl_dx10.cpp:57
ImDrawData::CmdLists
ImDrawList ** CmdLists
Definition: imgui.h:2071
g_numFramesInFlight
static UINT g_numFramesInFlight
Definition: imgui_impl_dx12.cpp:57
g_pFontTextureResource
static ID3D12Resource * g_pFontTextureResource
Definition: imgui_impl_dx12.cpp:45
FrameResources::IndexBufferSize
int IndexBufferSize
Definition: imgui_impl_dx12.cpp:53
FrameResources
Definition: imgui_impl_dx12.cpp:49
desc
#define desc
Definition: extension_set.h:342
ImDrawList
Definition: imgui.h:1961
ImTextureID
void * ImTextureID
Definition: imgui.h:172
imgui.h
y
GLint y
Definition: glcorearb.h:2768
props
GLenum GLuint GLsizei const GLenum * props
Definition: glcorearb.h:4475
ImVec2
Definition: imgui.h:208
ImGui::GetIO
IMGUI_API ImGuiIO & GetIO()
Definition: imgui.cpp:3286
IM_UNUSED
#define IM_UNUSED(_VAR)
Definition: imgui.h:89
T
#define T(upbtypeconst, upbtype, ctype, default_value)
ImDrawList::CmdBuffer
ImVector< ImDrawCmd > CmdBuffer
Definition: imgui.h:1964
ImGui_ImplDX12_CreateFontsTexture
static void ImGui_ImplDX12_CreateFontsTexture()
Definition: imgui_impl_dx12.cpp:247
ImDrawCmd
Definition: imgui.h:1871
ImDrawCmd::TextureId
ImTextureID TextureId
Definition: imgui.h:1875
ImDrawCmd::UserCallback
ImDrawCallback UserCallback
Definition: imgui.h:1878
param
GLenum GLfloat param
Definition: glcorearb.h:2769
range
GLenum GLint * range
Definition: glcorearb.h:3963
g_pPipelineState
static ID3D12PipelineState * g_pPipelineState
Definition: imgui_impl_dx12.cpp:43
ImVec4::y
float y
Definition: imgui.h:223
g_frameIndex
static UINT g_frameIndex
Definition: imgui_impl_dx12.cpp:58
ImGui_ImplDX12_Shutdown
void ImGui_ImplDX12_Shutdown()
Definition: imgui_impl_dx12.cpp:646
ImVector::Data
T * Data
Definition: imgui.h:1305
stride
GLint GLenum GLboolean GLsizei stride
Definition: glcorearb.h:3141
event
struct _cl_event * event
Definition: glcorearb.h:4163
offset
GLintptr offset
Definition: glcorearb.h:2944
ImDrawData
Definition: imgui.h:2068
ImGui_ImplDX12_NewFrame
void ImGui_ImplDX12_NewFrame()
Definition: imgui_impl_dx12.cpp:658
ImVector::Size
int Size
Definition: imgui.h:1303
ImDrawVert
Definition: imgui.h:1893
ImVec2::x
float x
Definition: imgui.h:210
ImDrawCmd::ClipRect
ImVec4 ClipRect
Definition: imgui.h:1874
imgui_impl_dx12.h
SafeRelease
static void SafeRelease(T *&res)
Definition: imgui_impl_dx12.cpp:61
IM_OFFSETOF
#define IM_OFFSETOF(_TYPE, _MEMBER)
Definition: imgui.h:93
g_pPixelShaderBlob
static ID3D10Blob * g_pPixelShaderBlob
Definition: imgui_impl_dx12.cpp:41
g_pVertexShaderBlob
static ID3D10Blob * g_pVertexShaderBlob
Definition: imgui_impl_dx12.cpp:40
ImDrawData::TotalVtxCount
int TotalVtxCount
Definition: imgui.h:2074
ImVec4::x
float x
Definition: imgui.h:223
ImGuiBackendFlags_RendererHasVtxOffset
@ ImGuiBackendFlags_RendererHasVtxOffset
Definition: imgui.h:1080
n
GLdouble n
Definition: glcorearb.h:4153
ImDrawList::VtxBuffer
ImVector< ImDrawVert > VtxBuffer
Definition: imgui.h:1966
i
int i
Definition: gmock-matchers_test.cc:764
ImGui_ImplDX12_CreateDeviceObjects
bool ImGui_ImplDX12_CreateDeviceObjects()
Definition: imgui_impl_dx12.cpp:396
FrameResources::IndexBuffer
ID3D12Resource * IndexBuffer
Definition: imgui_impl_dx12.cpp:51
ImVec4::w
float w
Definition: imgui.h:223
ImDrawCallback_ResetRenderState
#define ImDrawCallback_ResetRenderState
Definition: imgui.h:1866
ImGuiIO::BackendRendererName
const char * BackendRendererName
Definition: imgui.h:1456
VERTEX_CONSTANT_BUFFER::mvp
float mvp[4][4]
Definition: imgui_impl_dx10.cpp:59
r
GLboolean r
Definition: glcorearb.h:3228
HANDLE
void * HANDLE
Definition: wepoll.c:70
ImGui_ImplDX12_RenderDrawData
void ImGui_ImplDX12_RenderDrawData(ImDrawData *draw_data, ID3D12GraphicsCommandList *ctx)
Definition: imgui_impl_dx12.cpp:130
ImGui_ImplDX12_InvalidateDeviceObjects
void ImGui_ImplDX12_InvalidateDeviceObjects()
Definition: imgui_impl_dx12.cpp:594
ImGuiIO
Definition: imgui.h:1414
g_pd3dDevice
static ID3D12Device * g_pd3dDevice
Definition: imgui_impl_dx12.cpp:39
g_pRootSignature
static ID3D12RootSignature * g_pRootSignature
Definition: imgui_impl_dx12.cpp:42
ImDrawData::TotalIdxCount
int TotalIdxCount
Definition: imgui.h:2073
g_RTVFormat
static DXGI_FORMAT g_RTVFormat
Definition: imgui_impl_dx12.cpp:44
IM_ASSERT
#define IM_ASSERT(_EXPR)
Definition: imgui.h:79
g_hFontSrvCpuDescHandle
static D3D12_CPU_DESCRIPTOR_HANDLE g_hFontSrvCpuDescHandle
Definition: imgui_impl_dx12.cpp:46
g_hFontSrvGpuDescHandle
static D3D12_GPU_DESCRIPTOR_HANDLE g_hFontSrvGpuDescHandle
Definition: imgui_impl_dx12.cpp:47
ImDrawData::DisplaySize
ImVec2 DisplaySize
Definition: imgui.h:2076
f
GLfloat f
Definition: glcorearb.h:3964
ImDrawCmd::IdxOffset
unsigned int IdxOffset
Definition: imgui.h:1877
pixels
GLint GLint GLsizei GLint GLenum GLenum const GLvoid * pixels
Definition: glcorearb.h:2773
FrameResources::VertexBuffer
ID3D12Resource * VertexBuffer
Definition: imgui_impl_dx12.cpp:52
ImGuiIO::BackendFlags
ImGuiBackendFlags BackendFlags
Definition: imgui.h:1421
ImVec2::y
float y
Definition: imgui.h:210
width
GLint GLsizei width
Definition: glcorearb.h:2768
ImDrawCmd::ElemCount
unsigned int ElemCount
Definition: imgui.h:1873
FrameResources::VertexBufferSize
int VertexBufferSize
Definition: imgui_impl_dx12.cpp:54
ImFontAtlas::GetTexDataAsRGBA32
IMGUI_API void GetTexDataAsRGBA32(unsigned char **out_pixels, int *out_width, int *out_height, int *out_bytes_per_pixel=NULL)
Definition: imgui_draw.cpp:1679


libaditof
Author(s):
autogenerated on Wed May 21 2025 02:06:54