155static HRESULT
CreateReadback(ID3D12CommandQueue* Queue,
const D3D12_RESOURCE_DESC* SourceDesc,
156 const RECT* SourceRect, PHYDRAHOOK_D3D12_READBACK* Readback)
161 if (!SourceDesc || !Queue || Queue->GetDesc().Type != D3D12_COMMAND_LIST_TYPE_DIRECT)
164 const auto& desc = *SourceDesc;
165 const auto pixelSize = PixelSize(desc.Format);
166 if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.SampleDesc.Count != 1 ||
167 desc.DepthOrArraySize != 1 || desc.MipLevels != 1 || pixelSize == 0)
168 return DXGI_ERROR_UNSUPPORTED;
169 if (desc.Width == 0 || desc.Width > (std::numeric_limits<UINT>::max)() || desc.Height == 0)
172 D3D12_BOX region{0, 0, 0,
static_cast<UINT
>(desc.Width), desc.Height, 1};
175 const auto& rect = *SourceRect;
176 if (rect.left < 0 || rect.top < 0 || rect.right <= rect.left || rect.bottom <= rect.top ||
177 static_cast<UINT64
>(rect.right) > desc.Width ||
static_cast<UINT
>(rect.bottom) > desc.Height)
179 region = {
static_cast<UINT
>(rect.left),
static_cast<UINT
>(rect.top), 0,
180 static_cast<UINT
>(rect.right),
static_cast<UINT
>(rect.bottom), 1};
182 auto copyDesc = desc;
183 copyDesc.Width = region.right - region.left;
184 copyDesc.Height = region.bottom - region.top;
188 return E_OUTOFMEMORY;
189 state->queue = Queue;
190 HRESULT hr = state->queue.As(&state->queueIdentity);
193 hr = Queue->GetDevice(IID_PPV_ARGS(&state->device));
196 hr = state->device.As(&state->deviceIdentity);
199 if (state->device->GetNodeCount() != 1)
200 return DXGI_ERROR_UNSUPPORTED;
202 state->region = region;
203 state->sourceWidth = desc.Width;
204 state->sourceHeight = desc.Height;
207 state->device->GetCopyableFootprints(
208 ©Desc, 0, 1, 0, &state->footprint, &rows, &rowBytes, &state->readbackBytes);
209 if (rows != copyDesc.Height || rowBytes != copyDesc.Width * pixelSize || rowBytes > (std::numeric_limits<UINT>::max)() ||
210 state->readbackBytes > (std::numeric_limits<std::size_t>::max)())
212 state->rowBytes =
static_cast<UINT
>(rowBytes);
214 hr = state->device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&state->fence));
217 state->fenceEvent = CreateEventW(
nullptr, FALSE, FALSE,
nullptr);
218 if (!state->fenceEvent)
219 return HRESULT_FROM_WIN32(GetLastError());
221 D3D12_HEAP_PROPERTIES heap{};
222 heap.Type = D3D12_HEAP_TYPE_READBACK;
223 heap.CreationNodeMask = 1;
224 heap.VisibleNodeMask = 1;
226 D3D12_RESOURCE_DESC buffer{};
227 buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
228 buffer.Width = state->readbackBytes;
230 buffer.DepthOrArraySize = 1;
231 buffer.MipLevels = 1;
232 buffer.SampleDesc.Count = 1;
233 buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
235 for (
auto& slot : state->slots)
237 hr = state->device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&slot.allocator));
240 hr = state->device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT,
241 slot.allocator.Get(),
nullptr, IID_PPV_ARGS(&slot.list));
244 hr = slot.list->Close();
247 hr = state->device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer,
248 D3D12_RESOURCE_STATE_COPY_DEST,
nullptr, IID_PPV_ARGS(&slot.readback));
252 g_activeSessions.fetch_add(1, std::memory_order_relaxed);
253 *Readback = state.release();
283 auto& state = **Readback;
284 if (FAILED(state.submissionError) && state.fence->GetCompletedValue() != RemovedFence)
287 const HRESULT hr = state.queue->Signal(state.fence.Get(), state.lastFence);
288 if (FAILED(hr) && state.fence->GetCompletedValue() != RemovedFence)
291 state.submissionError = S_OK;
294 const auto started = Clock::now();
295 if (state.fence->GetCompletedValue() < state.lastFence)
298 return HRESULT_FROM_WIN32(WAIT_TIMEOUT);
299 if (state.fenceEvent)
301 const HRESULT waitHr = state.fence->SetEventOnCompletion(state.lastFence, state.fenceEvent);
304 while (state.fence->GetCompletedValue() < state.lastFence)
306 if (state.fence->GetCompletedValue() == RemovedFence)
308 const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
309 Clock::now() - started);
310 const auto limit = std::chrono::milliseconds(TimeoutMs);
311 if (elapsed >= limit)
312 return HRESULT_FROM_WIN32(WAIT_TIMEOUT);
313 const DWORD remaining =
static_cast<DWORD
>((limit - elapsed).count());
314 WaitForSingleObject(state.fenceEvent, remaining);
319 while (state.fence->GetCompletedValue() < state.lastFence)
321 if (state.fence->GetCompletedValue() == RemovedFence)
323 if (std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - started)
324 >= std::chrono::milliseconds(TimeoutMs))
325 return HRESULT_FROM_WIN32(WAIT_TIMEOUT);
331 while (state.readers.load(std::memory_order_acquire) > 0)
334 return HRESULT_FROM_WIN32(WAIT_TIMEOUT);
335 if (std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - started)
336 >= std::chrono::milliseconds(TimeoutMs))
337 return HRESULT_FROM_WIN32(WAIT_TIMEOUT);
343 if (g_activeSessions.fetch_sub(1, std::memory_order_acq_rel) == 1)
344 ClearPixelPoolIfIdle();
349 ID3D12Resource* Source, ID3D12CommandQueue* CurrentQueue)
351 if (!Readback || !Source || !CurrentQueue)
354 auto& state = *Readback;
355 if (CurrentQueue != state.queue.Get())
357 ComPtr<IUnknown> identity;
358 if (FAILED(CurrentQueue->QueryInterface(IID_PPV_ARGS(&identity))) ||
359 identity.Get() != state.queueIdentity.Get())
362 std::unique_lock lock(state.mutex, std::try_to_lock);
363 if (!lock.owns_lock())
365 const auto completed = state.fence->GetCompletedValue();
366 if (completed == RemovedFence)
368 (void)state.device->GetDeviceRemovedReason();
369 return DXGI_ERROR_DEVICE_REMOVED;
371 if (FAILED(state.submissionError))
372 return state.submissionError;
374 ComPtr<ID3D12Resource> retired[3];
375 std::size_t retiredCount = 0;
377 for (
auto& slot : state.slots)
380 || slot.fenceValue > completed)
382 retired[retiredCount++] = std::move(slot.source);
390 newestCompleted = &slot;
399 const auto slot = std::ranges::find_if(state.slots, [](
const auto& entry)
401 return entry.state == _HYDRAHOOK_D3D12_READBACK::SlotState::Free;
403 if (slot == state.slots.end())
409 const auto desc = Source->GetDesc();
410 const auto& footprint = state.footprint.Footprint;
411 if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.SampleDesc.Count != 1 ||
412 desc.DepthOrArraySize != 1 || desc.MipLevels != 1 || desc.Width != state.sourceWidth ||
413 desc.Height != state.sourceHeight || desc.Format != footprint.Format)
416 return DXGI_ERROR_INVALID_CALL;
419 ComPtr<IUnknown> sourceDevice;
420 HRESULT hr = Source->GetDevice(IID_PPV_ARGS(&sourceDevice));
426 if (sourceDevice.Get() != state.deviceIdentity.Get())
432 hr = slot->allocator->Reset();
438 hr = slot->list->Reset(slot->allocator.Get(),
nullptr);
445 D3D12_RESOURCE_BARRIER barrier{};
446 barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
447 barrier.Transition = {Source, 0, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_SOURCE};
448 slot->list->ResourceBarrier(1, &barrier);
450 D3D12_TEXTURE_COPY_LOCATION source{};
451 source.pResource = Source;
452 source.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
453 D3D12_TEXTURE_COPY_LOCATION dest{};
454 dest.pResource = slot->readback.Get();
455 dest.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
456 dest.PlacedFootprint = state.footprint;
457 const bool fullFrame = state.region.left == 0 && state.region.top == 0 &&
458 state.region.right == state.sourceWidth && state.region.bottom == state.sourceHeight;
459 slot->list->CopyTextureRegion(&dest, 0, 0, 0, &source, fullFrame ?
nullptr : &state.region);
461 std::swap(barrier.Transition.StateBefore, barrier.Transition.StateAfter);
462 slot->list->ResourceBarrier(1, &barrier);
463 hr = slot->list->Close();
470 slot->source = Source;
471 slot->fenceValue = ++state.lastFence;
472 slot->id = state.nextFrameId++;
474 LARGE_INTEGER timestamp{};
475 QueryPerformanceCounter(×tamp);
476 slot->timestampQpc = timestamp.QuadPart;
477 ID3D12CommandList* lists[]{slot->list.Get()};
480 state.queue->ExecuteCommandLists(1, lists);
482 hr = state.queue->Signal(state.fence.Get(), slot->fenceValue);
484 state.submissionError = hr;
487 for (std::size_t i = 0; i < retiredCount; ++i)
495 if (!Readback || !Frame || Frame->
Pixels)
497 auto& state = *Readback;
498 std::unique_lock lock(state.mutex, std::try_to_lock);
499 if (!lock.owns_lock())
502 const auto completed = state.fence->GetCompletedValue();
503 if (completed == RemovedFence)
505 (void)state.device->GetDeviceRemovedReason();
506 return DXGI_ERROR_DEVICE_REMOVED;
508 if (FAILED(state.submissionError))
509 return state.submissionError;
512 ComPtr<ID3D12Resource> retired[3];
513 std::size_t retiredCount = 0;
514 for (
auto& slot : state.slots)
517 || slot.fenceValue > completed)
523 retired[retiredCount++] = std::move(newest->
source);
531 retired[retiredCount++] = std::move(slot.source);
540 state.readers.fetch_add(1, std::memory_order_acq_rel);
541 retired[retiredCount++] = std::move(newest->
source);
544 const auto& footprint = state.footprint.Footprint;
545 const std::size_t bytes =
static_cast<std::size_t
>(state.rowBytes) * footprint.Height;
546 BYTE* pixels = AcquirePixelBuffer(bytes);
550 std::lock_guard relock(state.mutex);
554 state.readers.fetch_sub(1, std::memory_order_release);
555 return E_OUTOFMEMORY;
558 const D3D12_RANGE readRange{
static_cast<SIZE_T
>(state.footprint.Offset),
static_cast<SIZE_T
>(state.readbackBytes)};
559 void* mapped =
nullptr;
560 const HRESULT hr = newest->
readback->Map(0, &readRange, &mapped);
563 ReleasePixelBuffer(pixels, bytes);
565 std::lock_guard relock(state.mutex);
569 state.readers.fetch_sub(1, std::memory_order_release);
573 const auto* src =
static_cast<const std::byte*
>(mapped) +
static_cast<std::size_t
>(state.footprint.Offset);
574 for (UINT row = 0; row < footprint.Height; ++row)
576 std::memcpy(pixels +
static_cast<SIZE_T
>(row) * state.rowBytes,
577 src +
static_cast<std::size_t
>(row) * footprint.RowPitch, state.rowBytes);
579 const D3D12_RANGE noWrites{};
580 newest->
readback->Unmap(0, &noWrites);
582 const auto id = newest->
id;
585 std::lock_guard relock(state.mutex);
589 state.readers.fetch_sub(1, std::memory_order_release);
591 *Frame = {footprint.Width, footprint.Height, state.rowBytes, footprint.Format,
592 id, timestampQpc, pixels};