[idd] project: organize driver sources by responsibility

Group the IDD sources and Visual Studio filters by subsystem.

Split the device and swap-chain implementations into focused units,
rename the context classes, and reduce header coupling.
This commit is contained in:
Geoffrey McRae
2026-08-07 14:38:36 +10:00
parent 3ddc199bec
commit 30a1383d5e
76 changed files with 5067 additions and 3923 deletions

View File

@@ -0,0 +1,75 @@
/**
* Looking Glass
* Copyright © 2017-2026 The Looking Glass Authors
* https://looking-glass.io
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc., 59
* Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "d3d/CD3D11Device.h"
#include "CDebug.h"
HRESULT CD3D11Device::Init()
{
HRESULT hr = CreateDXGIFactory2(0, IID_PPV_ARGS(&m_factory));
if (FAILED(hr))
return hr;
hr = m_factory->EnumAdapterByLuid(m_adapterLuid, IID_PPV_ARGS(&m_adapter));
if (FAILED(hr))
return hr;
DXGI_ADAPTER_DESC1 desc = {};
hr = m_adapter->GetDesc1(&desc);
if (FAILED(hr))
return hr;
m_isSoftware = (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) != 0;
// only 11.1 supports DX12 interoperabillity
static const D3D_FEATURE_LEVEL featureLevels[] =
{
D3D_FEATURE_LEVEL_11_1
};
D3D_FEATURE_LEVEL featureLevel;
ComPtr<ID3D11Device> device;
ComPtr<ID3D11DeviceContext> context;
hr = D3D11CreateDevice(
m_adapter.Get(),
D3D_DRIVER_TYPE_UNKNOWN,
nullptr,
D3D11_CREATE_DEVICE_BGRA_SUPPORT,
featureLevels,
ARRAYSIZE(featureLevels),
D3D11_SDK_VERSION,
&device,
&featureLevel,
&context);
if (FAILED(hr))
return hr;
DEBUG_INFO("Feature Level: 0x%x", featureLevel);
hr = device.As(&m_device);
if (FAILED(hr))
return hr;
hr = context.As(&m_context);
if (FAILED(hr))
return hr;
return S_OK;
}

View File

@@ -0,0 +1,57 @@
/**
* Looking Glass
* Copyright © 2017-2026 The Looking Glass Authors
* https://looking-glass.io
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc., 59
* Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#pragma once
#include <Windows.h>
#include <wdf.h>
#include <wrl.h>
#include <dxgi1_5.h>
#include <d3d11_4.h>
using namespace Microsoft::WRL;
struct CD3D11Device
{
private:
LUID m_adapterLuid;
ComPtr<IDXGIFactory5 > m_factory;
ComPtr<IDXGIAdapter1 > m_adapter;
ComPtr<ID3D11Device5 > m_device;
ComPtr<ID3D11DeviceContext4> m_context;
bool m_isSoftware = false;
public:
CD3D11Device(LUID adapterLuid) :
m_adapterLuid(adapterLuid) {};
CD3D11Device()
{
m_adapterLuid = LUID{};
}
HRESULT Init();
ComPtr<ID3D11Device5> GetDevice() { return m_device; }
ComPtr<ID3D11DeviceContext4> GetContext() { return m_context; }
bool IsSoftware() { return m_isSoftware; }
};

View File

@@ -0,0 +1,679 @@
/**
* Looking Glass
* Copyright © 2017-2026 The Looking Glass Authors
* https://looking-glass.io
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc., 59
* Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "d3d/CD3D12CommandQueue.h"
#include "CDebug.h"
static uint64_t ScaleTicks(uint64_t ticks, uint64_t targetFrequency,
uint64_t sourceFrequency)
{
return ticks / sourceFrequency * targetFrequency +
ticks % sourceFrequency * targetFrequency / sourceFrequency;
}
static uint64_t TicksToNanoseconds(uint64_t ticks, uint64_t frequency)
{
return ScaleTicks(ticks, 1000000000ULL, frequency);
}
static bool ConvertGPUTimestamp(UINT64 timestamp, UINT64 timestampFrequency,
UINT64 calibrationGPU, UINT64 calibrationCPU, UINT64 qpcFrequency,
uint64_t& result)
{
UINT64 cpuTimestamp;
if (timestamp < calibrationGPU)
{
const UINT64 delta = ScaleTicks(
calibrationGPU - timestamp, qpcFrequency, timestampFrequency);
if (delta > calibrationCPU)
return false;
cpuTimestamp = calibrationCPU - delta;
}
else
{
const UINT64 delta = ScaleTicks(
timestamp - calibrationGPU, qpcFrequency, timestampFrequency);
if (UINT64_MAX - calibrationCPU < delta)
return false;
cpuTimestamp = calibrationCPU + delta;
}
result = TicksToNanoseconds(cpuTimestamp, qpcFrequency);
return true;
}
bool CD3D12CommandSlot::Init(ID3D12Device3 * device,
CD3D12CommandQueue * queue, const WCHAR * name, UINT queryBase,
ULONG waitFlags)
{
m_queue = queue;
m_name = name;
m_queryBase = queryBase;
HRESULT hr = device->CreateCommandAllocator(
queue->m_queue->GetDesc().Type, IID_PPV_ARGS(&m_allocator));
if (FAILED(hr))
{
DEBUG_ERROR_HR(hr, "Failed to create the CommandAllocator (%ls)", name);
return false;
}
hr = device->CreateCommandList(0, queue->m_queue->GetDesc().Type,
m_allocator.Get(), NULL, IID_PPV_ARGS(&m_gfxList));
if (FAILED(hr))
{
DEBUG_ERROR_HR(hr, "Failed to create the Graphics CommandList (%ls)", name);
return false;
}
m_gfxList->SetName(name);
m_cmdList = m_gfxList;
if (!m_cmdList)
{
DEBUG_ERROR("Failed to get the CommandList (%ls)", name);
return false;
}
m_event.Attach(CreateEvent(NULL, FALSE, FALSE, NULL));
if (!m_event.Get())
{
DEBUG_ERROR_HR(GetLastError(),
"Failed to create the completion event (%ls)", name);
return false;
}
m_availableEvent.Attach(CreateEvent(NULL, FALSE, FALSE, NULL));
if (!m_availableEvent.Get())
{
DEBUG_ERROR_HR(GetLastError(),
"Failed to create the availability event (%ls)", name);
return false;
}
if (!RegisterWaitForSingleObject(
&m_waitHandle,
m_event.Get(),
[](PVOID param, BOOLEAN timeout){
static_cast<CD3D12CommandSlot *>(param)->OnCompletion(!!timeout);
},
this,
INFINITE,
waitFlags))
{
DEBUG_ERROR_HR(GetLastError(),
"Failed to register the completion wait (%ls)", name);
m_waitHandle = INVALID_HANDLE_VALUE;
return false;
}
DEBUG_INFO("Created CD3D12CommandSlot(%ls)", name);
return true;
}
void CD3D12CommandSlot::DeInit()
{
if (m_waitHandle != INVALID_HANDLE_VALUE)
{
if (!UnregisterWaitEx(m_waitHandle, INVALID_HANDLE_VALUE))
DEBUG_WARN_HR(GetLastError(),
"Failed to unregister the completion wait (%ls)", m_name);
m_waitHandle = INVALID_HANDLE_VALUE;
}
m_event.Close();
m_availableEvent.Close();
m_cmdList.Reset();
m_gfxList.Reset();
m_allocator.Reset();
m_queue = nullptr;
}
bool CD3D12CommandSlot::Acquire()
{
if (!m_queue || m_queue->m_failed.load(std::memory_order_acquire))
return false;
State expected = STATE_FREE;
if (!m_state.compare_exchange_strong(expected, STATE_RECORDING,
std::memory_order_acq_rel))
return false;
m_completionCallback = nullptr;
m_completionParams[0] = nullptr;
m_completionParams[1] = nullptr;
m_completionResult = true;
m_fenceTarget = 0;
m_fenceWaitCount = 0;
m_timingActive = false;
m_timestampFrequency = 0;
m_calibrationGPU = 0;
m_calibrationCPU = 0;
m_submitted.store(false, std::memory_order_release);
for (UINT i = 0; i < MAX_FENCE_WAITS; ++i)
{
m_fenceWaits[i].fence.Reset();
m_fenceWaits[i].value = 0;
}
if (!m_needsReset)
return true;
HRESULT hr = m_allocator->Reset();
if (FAILED(hr))
{
DEBUG_ERROR_HR(hr, "Failed to reset the CommandAllocator (%ls)", m_name);
m_queue->m_failed.store(true, std::memory_order_release);
m_state.store(STATE_FAILED, std::memory_order_release);
return false;
}
hr = m_gfxList->Reset(m_allocator.Get(), NULL);
if (FAILED(hr))
{
DEBUG_ERROR_HR(hr, "Failed to reset the CommandList (%ls)", m_name);
m_queue->m_failed.store(true, std::memory_order_release);
m_state.store(STATE_FAILED, std::memory_order_release);
return false;
}
m_needsReset = false;
return true;
}
void CD3D12CommandSlot::Cancel()
{
State expected = STATE_RECORDING;
if (!m_state.compare_exchange_strong(expected, STATE_CANCELLING,
std::memory_order_acq_rel))
{
DEBUG_ERROR("Command slot cancelled while not recording (%ls)", m_name);
return;
}
const HRESULT hr = m_gfxList->Close();
m_needsReset = true;
m_timingActive = false;
for (UINT i = 0; i < m_fenceWaitCount; ++i)
{
m_fenceWaits[i].fence.Reset();
m_fenceWaits[i].value = 0;
}
m_fenceWaitCount = 0;
if (FAILED(hr))
{
DEBUG_ERROR_HR(hr, "Failed to close the cancelled CommandList (%ls)",
m_name);
m_queue->m_failed.store(true, std::memory_order_release);
m_state.store(STATE_FAILED, std::memory_order_release);
return;
}
m_completionCallback = nullptr;
m_completionParams[0] = nullptr;
m_completionParams[1] = nullptr;
m_submitted.store(false, std::memory_order_release);
m_state.store(STATE_FREE, std::memory_order_release);
SetEvent(m_availableEvent.Get());
}
bool CD3D12CommandSlot::Execute()
{
State expected = STATE_RECORDING;
if (!m_state.compare_exchange_strong(expected, STATE_SUBMITTED,
std::memory_order_acq_rel))
{
DEBUG_ERROR("Command slot executed while not recording (%ls)", m_name);
return false;
}
m_needsReset = true;
HRESULT hr = m_gfxList->Close();
if (FAILED(hr))
{
DEBUG_ERROR_HR(hr, "Failed to close the CommandList (%ls)", m_name);
m_queue->m_failed.store(true, std::memory_order_release);
m_state.store(STATE_FAILED, std::memory_order_release);
return false;
}
if (m_queue->Submit(*this))
return true;
if (!m_submitted.load(std::memory_order_acquire))
{
m_state.store(STATE_FREE, std::memory_order_release);
SetEvent(m_availableEvent.Get());
}
return false;
}
bool CD3D12CommandSlot::WaitFor(ID3D12Fence * fence, UINT64 value)
{
if (!fence || !value ||
m_state.load(std::memory_order_acquire) != STATE_RECORDING)
return false;
if (m_fenceWaitCount == MAX_FENCE_WAITS)
{
DEBUG_ERROR("Too many fence waits for CommandSlot(%ls)", m_name);
return false;
}
FenceWait& wait = m_fenceWaits[m_fenceWaitCount++];
wait.fence = fence;
wait.value = value;
return true;
}
bool CD3D12CommandSlot::WaitFor(const CD3D12CommandSlot& slot)
{
if (!slot.m_queue || !slot.m_fenceTarget)
return false;
return WaitFor(slot.m_queue->m_fence.Get(), slot.m_fenceTarget);
}
bool CD3D12CommandSlot::BeginTiming()
{
m_timingActive = m_queue && m_queue->m_timingSupported;
if (!m_timingActive)
return false;
m_gfxList->EndQuery(m_queue->m_timestampHeap.Get(),
D3D12_QUERY_TYPE_TIMESTAMP, m_queryBase);
return true;
}
void CD3D12CommandSlot::EndTiming()
{
if (!m_timingActive)
return;
if (!m_queue->SnapshotTiming(*this))
{
m_timingActive = false;
return;
}
m_gfxList->EndQuery(m_queue->m_timestampHeap.Get(),
D3D12_QUERY_TYPE_TIMESTAMP, m_queryBase + 1);
m_gfxList->ResolveQueryData(m_queue->m_timestampHeap.Get(),
D3D12_QUERY_TYPE_TIMESTAMP, m_queryBase, 2,
m_queue->m_timestampReadback.Get(),
(UINT64)m_queryBase * sizeof(UINT64));
}
bool CD3D12CommandSlot::GetGPUTimes(
uint64_t& start, uint64_t& end) const
{
return m_queue && m_queue->GetGPUTimes(*this, start, end);
}
void CD3D12CommandSlot::OnCompletion(bool timeout)
{
if (!m_queue || !m_submitted.load(std::memory_order_acquire))
return;
const UINT64 completed = m_queue->m_fence->GetCompletedValue();
if (completed != UINT64_MAX && completed < m_fenceTarget)
return;
State expected = STATE_SUBMITTED;
if (!m_state.compare_exchange_strong(expected, STATE_COMPLETING,
std::memory_order_acq_rel))
return;
m_completionResult = !timeout && completed != UINT64_MAX;
if (!m_completionResult)
m_queue->m_failed.store(true, std::memory_order_release);
if (m_completionCallback)
m_completionCallback(this, m_completionResult,
m_completionParams[0], m_completionParams[1]);
m_completionCallback = nullptr;
m_completionParams[0] = nullptr;
m_completionParams[1] = nullptr;
m_submitted.store(false, std::memory_order_release);
m_state.store(STATE_FREE, std::memory_order_release);
SetEvent(m_availableEvent.Get());
}
bool CD3D12CommandQueue::InitTiming(ID3D12Device3 * device, UINT slotCount)
{
D3D12_FEATURE_DATA_D3D12_OPTIONS3 options = {};
HRESULT hr = device->CheckFeatureSupport(
D3D12_FEATURE_D3D12_OPTIONS3, &options, sizeof(options));
if (FAILED(hr) || !options.CopyQueueTimestampQueriesSupported)
return false;
LARGE_INTEGER qpcFrequency;
if (!QueryPerformanceFrequency(&qpcFrequency))
return false;
m_qpcFrequency = (UINT64)qpcFrequency.QuadPart;
D3D12_QUERY_HEAP_DESC queryDesc = {};
queryDesc.Type = D3D12_QUERY_HEAP_TYPE_COPY_QUEUE_TIMESTAMP;
queryDesc.Count = slotCount * 2;
hr = device->CreateQueryHeap(&queryDesc,
IID_PPV_ARGS(&m_timestampHeap));
if (FAILED(hr))
return false;
D3D12_HEAP_PROPERTIES heapProps = {};
heapProps.Type = D3D12_HEAP_TYPE_READBACK;
heapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
heapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
heapProps.CreationNodeMask = 1;
heapProps.VisibleNodeMask = 1;
D3D12_RESOURCE_DESC resourceDesc = {};
resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
resourceDesc.Width = sizeof(UINT64) * queryDesc.Count;
resourceDesc.Height = 1;
resourceDesc.DepthOrArraySize = 1;
resourceDesc.MipLevels = 1;
resourceDesc.SampleDesc.Count = 1;
resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
hr = device->CreateCommittedResource(
&heapProps,
D3D12_HEAP_FLAG_NONE,
&resourceDesc,
D3D12_RESOURCE_STATE_COPY_DEST,
NULL,
IID_PPV_ARGS(&m_timestampReadback));
if (FAILED(hr))
{
m_timestampHeap.Reset();
return false;
}
const SIZE_T timingSize = sizeof(UINT64) * queryDesc.Count;
D3D12_RANGE readRange = { 0, timingSize };
void * timestampMap = nullptr;
hr = m_timestampReadback->Map(0, &readRange, &timestampMap);
if (FAILED(hr))
{
m_timestampReadback.Reset();
m_timestampHeap.Reset();
return false;
}
m_timestampMap = static_cast<UINT64 *>(timestampMap);
m_timingSupported = true;
return true;
}
bool CD3D12CommandQueue::Init(ID3D12Device3 * device,
D3D12_COMMAND_LIST_TYPE type, const WCHAR * name,
CD3D12CommandSlot::CallbackMode callbackMode, UINT slotCount,
bool enableTiming)
{
if (!slotCount || slotCount > MAX_SLOTS)
{
DEBUG_ERROR("Invalid slot count for CommandQueue(%ls): %u",
name, slotCount);
return false;
}
D3D12_COMMAND_QUEUE_DESC queueDesc = {};
queueDesc.Type = type;
queueDesc.Priority = D3D12_COMMAND_QUEUE_PRIORITY_HIGH;
queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
HRESULT hr = device->CreateCommandQueue(
&queueDesc, IID_PPV_ARGS(&m_queue));
if (FAILED(hr))
{
DEBUG_ERROR_HR(hr, "Failed to create the CommandQueue (%ls)", name);
return false;
}
m_queue->SetName(name);
hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE,
IID_PPV_ARGS(&m_fence));
if (FAILED(hr))
{
DEBUG_ERROR_HR(hr, "Failed to create the CommandQueue fence (%ls)", name);
return false;
}
if (enableTiming && !InitTiming(device, slotCount))
DEBUG_WARN("GPU timing is unavailable for CommandQueue(%ls)", name);
const ULONG waitFlags = callbackMode == CD3D12CommandSlot::FAST ?
WT_EXECUTEINWAITTHREAD : WT_EXECUTEINPERSISTENTTHREAD;
m_name = name;
for (UINT i = 0; i < slotCount; ++i)
{
if (!m_slots[i].Init(device, this, name, i * 2, waitFlags))
return false;
++m_slotCount;
}
DEBUG_INFO("Created CD3D12CommandQueue(%ls) with %u slots",
name, slotCount);
return true;
}
void CD3D12CommandQueue::DeInit()
{
WaitForIdle();
for (UINT i = 0; i < MAX_SLOTS; ++i)
m_slots[i].DeInit();
m_slotCount = 0;
if (m_timestampMap)
{
D3D12_RANGE writeRange = { 0, 0 };
m_timestampReadback->Unmap(0, &writeRange);
m_timestampMap = nullptr;
}
m_timestampReadback.Reset();
m_timestampHeap.Reset();
m_fence.Reset();
m_queue.Reset();
m_timingSupported = false;
m_qpcFrequency = 0;
}
CD3D12CommandSlot * CD3D12CommandQueue::Acquire(UINT slotIndex)
{
if (slotIndex >= m_slotCount)
return nullptr;
const ULONGLONG deadline = GetTickCount64() + 100;
for (;;)
{
if (m_slots[slotIndex].Acquire())
return &m_slots[slotIndex];
// The GPU may already be finished while its thread-pool callback is
// still pending. Complete it here before sleeping on callback dispatch.
m_slots[slotIndex].OnCompletion(false);
if (m_slots[slotIndex].Acquire())
return &m_slots[slotIndex];
if (m_failed.load(std::memory_order_acquire))
break;
const ULONGLONG now = GetTickCount64();
if (now >= deadline)
break;
const DWORD result =
WaitForSingleObject(m_slots[slotIndex].m_availableEvent.Get(),
static_cast<DWORD>(deadline - now));
if (result != WAIT_OBJECT_0)
break;
}
DEBUG_ERROR("Failed to acquire CommandSlot(%ls:%u)", m_name, slotIndex);
return nullptr;
}
CD3D12CommandSlot * CD3D12CommandQueue::Acquire()
{
if (!m_slotCount)
return nullptr;
// The unindexed path is used for immediate software publication. Keep at
// most one copy in flight so a newer frame is dropped instead of queued
// behind bandwidth-bound work which is already stale.
CD3D12CommandSlot& slot = m_slots[0];
if (slot.Acquire())
return &slot;
// Complete already-fenced work without waiting for callback dispatch.
slot.OnCompletion(false);
if (slot.Acquire())
return &slot;
return nullptr;
}
void CD3D12CommandQueue::WaitForIdle()
{
for (UINT slot = 0; slot < m_slotCount; ++slot)
{
while (!m_slots[slot].IsIdle())
{
// The callback may be delayed behind other thread-pool work. If its
// fence has completed, finish it here before releasing callback state.
m_slots[slot].OnCompletion(false);
if (m_slots[slot].IsIdle())
break;
Sleep(1);
}
}
}
bool CD3D12CommandQueue::Submit(CD3D12CommandSlot& slot)
{
bool result = false;
AcquireSRWLockExclusive(&m_submitLock);
do
{
if (m_failed.load(std::memory_order_relaxed))
break;
for (UINT i = 0; i < slot.m_fenceWaitCount; ++i)
{
const CD3D12CommandSlot::FenceWait& wait = slot.m_fenceWaits[i];
const HRESULT hr = m_queue->Wait(wait.fence.Get(), wait.value);
if (FAILED(hr))
{
DEBUG_ERROR_HR(hr, "Failed to queue a fence wait (%ls)", m_name);
m_failed.store(true, std::memory_order_release);
break;
}
}
if (m_failed.load(std::memory_order_relaxed))
break;
const UINT64 fenceTarget = ++m_fenceValue;
slot.m_fenceTarget = fenceTarget;
slot.m_submitted.store(true, std::memory_order_release);
ID3D12CommandList * lists[] = { slot.m_cmdList.Get() };
m_queue->ExecuteCommandLists(1, lists);
HRESULT hr = m_queue->Signal(m_fence.Get(), fenceTarget);
if (FAILED(hr))
{
DEBUG_ERROR_HR(hr, "Failed to signal the CommandQueue (%ls)", m_name);
m_failed.store(true, std::memory_order_release);
slot.OnCompletion(false);
break;
}
hr = m_fence->SetEventOnCompletion(fenceTarget, slot.m_event.Get());
if (FAILED(hr))
{
DEBUG_ERROR_HR(hr,
"Failed to register CommandSlot completion (%ls)", m_name);
// The work is already submitted and fenced. Poll only on this rare
// error path so allocator, callback, and framebuffer ownership remain
// valid until completion or confirmed device removal.
while (slot.m_submitted.load(std::memory_order_acquire))
{
slot.OnCompletion(false);
if (slot.m_submitted.load(std::memory_order_acquire))
Sleep(1);
}
result = slot.m_completionResult;
break;
}
result = true;
}
while (false);
ReleaseSRWLockExclusive(&m_submitLock);
return result;
}
bool CD3D12CommandQueue::SnapshotTiming(
CD3D12CommandSlot& slot) const
{
UINT64 frequency;
UINT64 gpu;
UINT64 cpu;
if (FAILED(m_queue->GetTimestampFrequency(&frequency)) || !frequency ||
FAILED(m_queue->GetClockCalibration(&gpu, &cpu)))
return false;
slot.m_timestampFrequency = frequency;
slot.m_calibrationGPU = gpu;
slot.m_calibrationCPU = cpu;
return true;
}
bool CD3D12CommandQueue::GetGPUTimes(const CD3D12CommandSlot& slot,
uint64_t& start, uint64_t& end) const
{
if (!slot.m_timingActive || !m_timestampMap ||
!slot.m_timestampFrequency || !m_qpcFrequency)
return false;
const UINT64 gpuStart = m_timestampMap[slot.m_queryBase];
const UINT64 gpuEnd = m_timestampMap[slot.m_queryBase + 1];
if (gpuEnd < gpuStart ||
!ConvertGPUTimestamp(gpuStart, slot.m_timestampFrequency,
slot.m_calibrationGPU, slot.m_calibrationCPU,
m_qpcFrequency, start) ||
!ConvertGPUTimestamp(gpuEnd, slot.m_timestampFrequency,
slot.m_calibrationGPU, slot.m_calibrationCPU,
m_qpcFrequency, end) ||
end < start)
return false;
return true;
}

View File

@@ -0,0 +1,179 @@
/**
* Looking Glass
* Copyright © 2017-2026 The Looking Glass Authors
* https://looking-glass.io
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc., 59
* Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#pragma once
#include <Windows.h>
#include <wdf.h>
#include <wrl.h>
#include <d3d12.h>
#include <atomic>
#include <stdint.h>
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;
using namespace Microsoft::WRL::Wrappers::HandleTraits;
class CD3D12CommandQueue;
class CD3D12CommandSlot
{
friend class CD3D12CommandQueue;
private:
enum State
{
STATE_FREE,
STATE_RECORDING,
STATE_CANCELLING,
STATE_SUBMITTED,
STATE_COMPLETING,
STATE_FAILED,
};
struct FenceWait
{
ComPtr<ID3D12Fence> fence;
UINT64 value = 0;
};
static const UINT MAX_FENCE_WAITS = 2;
const WCHAR * m_name = nullptr;
CD3D12CommandQueue * m_queue = nullptr;
ComPtr<ID3D12CommandAllocator > m_allocator;
ComPtr<ID3D12GraphicsCommandList> m_gfxList;
ComPtr<ID3D12CommandList > m_cmdList;
std::atomic<State> m_state = STATE_FREE;
std::atomic<bool> m_submitted = false;
HandleT<HANDLENullTraits> m_event;
HandleT<HANDLENullTraits> m_availableEvent;
HANDLE m_waitHandle = INVALID_HANDLE_VALUE;
bool m_needsReset = false;
UINT64 m_fenceTarget = 0;
FenceWait m_fenceWaits[MAX_FENCE_WAITS];
UINT m_fenceWaitCount = 0;
typedef void (*CompletionFunction)(CD3D12CommandSlot * slot,
bool result, void * param1, void * param2);
CompletionFunction m_completionCallback = nullptr;
void * m_completionParams[2] = {};
bool m_completionResult = true;
UINT m_queryBase = 0;
bool m_timingActive = false;
UINT64 m_timestampFrequency = 0;
UINT64 m_calibrationGPU = 0;
UINT64 m_calibrationCPU = 0;
bool Init(ID3D12Device3 * device, CD3D12CommandQueue * queue,
const WCHAR * name, UINT queryBase, ULONG waitFlags);
void DeInit();
void OnCompletion(bool timeout);
public:
enum CallbackMode
{
FAST,
NORMAL,
};
~CD3D12CommandSlot() { DeInit(); }
bool Acquire();
void Cancel();
bool Execute();
bool BeginTiming();
void EndTiming();
bool GetGPUTimes(uint64_t& start, uint64_t& end) const;
bool WaitFor(ID3D12Fence * fence, UINT64 value);
bool WaitFor(const CD3D12CommandSlot& slot);
void SetCompletionCallback(CompletionFunction fn,
void * param1, void * param2)
{
m_completionCallback = fn;
m_completionParams[0] = param1;
m_completionParams[1] = param2;
}
bool IsIdle() const
{
const State state = m_state.load(std::memory_order_acquire);
return state == STATE_FREE ||
(state == STATE_FAILED &&
!m_submitted.load(std::memory_order_acquire));
}
bool HasSubmittedWork() const
{
return m_submitted.load(std::memory_order_acquire);
}
ComPtr<ID3D12GraphicsCommandList> GetGfxList() { return m_gfxList; }
};
class CD3D12CommandQueue
{
friend class CD3D12CommandSlot;
private:
static const UINT MAX_SLOTS = 2;
const WCHAR * m_name = nullptr;
ComPtr<ID3D12CommandQueue> m_queue;
ComPtr<ID3D12Fence > m_fence;
UINT64 m_fenceValue = 0;
SRWLOCK m_submitLock = SRWLOCK_INIT;
std::atomic<bool> m_failed = false;
CD3D12CommandSlot m_slots[MAX_SLOTS];
UINT m_slotCount = 0;
ComPtr<ID3D12QueryHeap> m_timestampHeap;
ComPtr<ID3D12Resource > m_timestampReadback;
UINT64 * m_timestampMap = nullptr;
UINT64 m_qpcFrequency = 0;
bool m_timingSupported = false;
bool InitTiming(ID3D12Device3 * device, UINT slotCount);
bool Submit(CD3D12CommandSlot& slot);
bool SnapshotTiming(CD3D12CommandSlot& slot) const;
bool GetGPUTimes(const CD3D12CommandSlot& slot,
uint64_t& start, uint64_t& end) const;
public:
~CD3D12CommandQueue() { DeInit(); }
bool Init(ID3D12Device3 * device, D3D12_COMMAND_LIST_TYPE type,
const WCHAR * name, CD3D12CommandSlot::CallbackMode callbackMode,
UINT slotCount, bool enableTiming = false);
void DeInit();
CD3D12CommandSlot * Acquire(UINT slotIndex);
CD3D12CommandSlot * Acquire();
void WaitForIdle();
};

View File

@@ -0,0 +1,229 @@
/**
* Looking Glass
* Copyright © 2017-2026 The Looking Glass Authors
* https://looking-glass.io
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc., 59
* Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "d3d/CD3D12Device.h"
#include "CDebug.h"
bool CD3D12Device::m_indirectCopy = false;
CD3D12Device::CD3D12Device(LUID adapterLuid) :
m_adapterLuid(adapterLuid),
m_debug(false)
{
if (m_debug)
{
HRESULT hr = D3D12GetDebugInterface(IID_PPV_ARGS(&m_dxDebug));
if (FAILED(hr))
{
DEBUG_ERROR_HR(hr, "Failed to get the debug interface");
return;
}
m_dxDebug->EnableDebugLayer();
m_dxDebug->SetEnableGPUBasedValidation(TRUE);
m_dxDebug->SetEnableSynchronizedCommandQueueValidation(TRUE);
m_dxDebug->SetForceLegacyBarrierValidation(TRUE);
}
}
static void CALLBACK _D3D12DebugCallback(
D3D12_MESSAGE_CATEGORY category,
D3D12_MESSAGE_SEVERITY severity,
D3D12_MESSAGE_ID id,
LPCSTR description,
void *context
)
{
(void)context;
DEBUG_INFO("category:%d severity:%d id:%d desc:%s",
category,
severity,
id,
description);
}
CD3D12Device::InitResult CD3D12Device::Init(CIVSHMEM &ivshmem,
UINT64 &alignSize, bool enableCompute)
{
HRESULT hr;
m_computeEnabled = enableCompute;
hr = CreateDXGIFactory2(m_debug ? DXGI_CREATE_FACTORY_DEBUG : 0, IID_PPV_ARGS(&m_factory));
if (FAILED(hr))
{
DEBUG_ERROR_HR(hr, "Failed to create the DXGI factory");
return InitResult::FAILURE;
}
hr = m_factory->EnumAdapterByLuid(m_adapterLuid, IID_PPV_ARGS(&m_adapter));
if (FAILED(hr))
{
DEBUG_ERROR_HR(hr, "Failed to enumerate the adapter");
return InitResult::FAILURE;
}
hr = D3D12CreateDevice(m_adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&m_device));
if (FAILED(hr))
{
DEBUG_ERROR_HR(hr, "Failed to create the DirectX12 device");
return InitResult::FAILURE;
}
if (m_debug)
{
hr = m_device.As(&m_infoQueue);
if (FAILED(hr))
{
DEBUG_WARN_HR(hr, "Failed to get the ID3D12InfoQueue1 interface");
//non-fatal do not exit
}
else
{
m_infoQueue->RegisterMessageCallback(
_D3D12DebugCallback, D3D12_MESSAGE_CALLBACK_FLAG_NONE, NULL, &m_callbackCookie);
}
}
if (!m_indirectCopy)
{
hr = m_device->OpenExistingHeapFromAddress(ivshmem.GetMem(), IID_PPV_ARGS(&m_ivshmemHeap));
if (FAILED(hr))
{
DEBUG_ERROR_HR(hr, "Failed to open IVSHMEM as a D3D12Heap");
m_indirectCopy = true;
return InitResult::RETRY;
}
m_ivshmemHeap->SetName(L"IVSHMEM");
D3D12_HEAP_DESC heapDesc = m_ivshmemHeap->GetDesc();
alignSize = heapDesc.Alignment;
m_ivshmemTextureSupported =
(heapDesc.Flags & D3D12_HEAP_FLAG_SHARED_CROSS_ADAPTER) &&
!(heapDesc.Flags & D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES);
// test that the heap is usable
if (!HeapTest())
{
DEBUG_WARN("Unable to create resources in the IVSHMEM heap, falling back to indirect copy");
// failure often results in the device being removed and we need to completely reinit when this occurs
m_indirectCopy = true;
return InitResult::RETRY;
}
DEBUG_INFO("Using IVSHMEM as a D3D12Heap");
if (!m_ivshmemTextureSupported)
DEBUG_WARN("IVSHMEM heap does not support placed textures");
}
if (!m_copyQueue.Init(m_device.Get(), D3D12_COMMAND_LIST_TYPE_COPY,
L"Copy", m_indirectCopy ? CD3D12CommandSlot::NORMAL :
CD3D12CommandSlot::FAST, 2, true))
return InitResult::FAILURE;
if (m_computeEnabled &&
!m_computeQueue.Init(m_device.Get(), D3D12_COMMAND_LIST_TYPE_COMPUTE,
L"Compute", CD3D12CommandSlot::FAST, 2))
return InitResult::FAILURE;
DEBUG_INFO("Created CD3D12Device");
return InitResult::SUCCESS;
}
void CD3D12Device::DeInit()
{
if (m_debug && m_infoQueue)
m_infoQueue->UnregisterMessageCallback(m_callbackCookie);
m_infoQueue.Reset();
}
void CD3D12Device::WaitForIdle()
{
m_copyQueue.WaitForIdle();
if (m_computeEnabled)
m_computeQueue.WaitForIdle();
}
bool CD3D12Device::HeapTest()
{
D3D12_RESOURCE_DESC desc = {};
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
desc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT;
desc.Width = 1048576;
desc.Height = 1;
desc.DepthOrArraySize = 1;
desc.MipLevels = 1;
desc.Format = DXGI_FORMAT_UNKNOWN;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER;
HRESULT hr;
ComPtr<ID3D12Resource> resource;
hr = m_device->CreatePlacedResource(
m_ivshmemHeap.Get(),
0,
&desc,
D3D12_RESOURCE_STATE_COPY_DEST,
NULL,
IID_PPV_ARGS(&resource));
if (FAILED(hr))
{
DEBUG_ERROR_HR(hr, "Failed to create the ivshmem ID3D12Resource");
return false;
}
resource->SetName(L"HeapTest");
/* the above may succeed even if there was a fault, as such we also need to check
* check if the device was removed */
hr = m_device->GetDeviceRemovedReason();
if (hr != S_OK)
{
DEBUG_ERROR_HR(hr, "Device Removed");
return false;
}
return true;
}
CD3D12CommandSlot * CD3D12Device::GetCopySlot(unsigned frameIndex)
{
return m_copyQueue.Acquire(frameIndex);
}
CD3D12CommandSlot * CD3D12Device::GetCopySlot()
{
return m_copyQueue.Acquire();
}
CD3D12CommandSlot * CD3D12Device::GetComputeSlot(unsigned frameIndex)
{
if (!m_computeEnabled)
{
DEBUG_ERROR("Compute queue requested while compute processing is disabled");
return nullptr;
}
return m_computeQueue.Acquire(frameIndex);
}

View File

@@ -0,0 +1,87 @@
/**
* Looking Glass
* Copyright © 2017-2026 The Looking Glass Authors
* https://looking-glass.io
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc., 59
* Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#pragma once
#include <Windows.h>
#include <wdf.h>
#include <wrl.h>
#include <dxgi1_5.h>
#include <d3d12.h>
#include "transport/CIVSHMEM.h"
#include "d3d/CD3D12CommandQueue.h"
using namespace Microsoft::WRL;
struct CD3D12Device
{
private:
LUID m_adapterLuid;
bool m_debug;
// static as this needs to persist if set
static bool m_indirectCopy;
ComPtr<ID3D12Debug6 > m_dxDebug;
ComPtr<ID3D12InfoQueue1> m_infoQueue;
DWORD m_callbackCookie;
ComPtr<IDXGIFactory5> m_factory;
ComPtr<IDXGIAdapter1> m_adapter;
ComPtr<ID3D12Device3> m_device;
ComPtr<ID3D12Heap > m_ivshmemHeap;
CD3D12CommandQueue m_copyQueue;
CD3D12CommandQueue m_computeQueue;
bool m_computeEnabled = false;
bool m_ivshmemTextureSupported = false;
bool HeapTest();
public:
CD3D12Device(LUID adapterLUID);
~CD3D12Device() { DeInit(); }
enum InitResult
{
RETRY,
FAILURE,
SUCCESS
};
InitResult Init(CIVSHMEM &ivshmem, UINT64 &alignSize,
bool enableCompute);
void DeInit();
// Wait for all command queues to finish in-flight GPU work and run their
// completion callbacks. Used at swap-chain teardown so no callback touches
// resources we are about to release.
void WaitForIdle();
ComPtr<ID3D12Device3> GetDevice() { return m_device; }
ComPtr<ID3D12Heap > GetHeap() { return m_ivshmemHeap; }
bool IsIndirectCopy() { return m_indirectCopy; }
bool CanUseIVSHMEMTexture() { return m_ivshmemTextureSupported; }
CD3D12CommandSlot * GetCopySlot ();
CD3D12CommandSlot * GetCopySlot (unsigned frameIndex);
CD3D12CommandSlot * GetComputeSlot(unsigned frameIndex);
};

View File

@@ -0,0 +1,182 @@
/**
* Looking Glass
* Copyright © 2017-2026 The Looking Glass Authors
* https://looking-glass.io
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc., 59
* Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "d3d/CInteropResource.h"
#include "CDebug.h"
bool CInteropResource::Init(
std::shared_ptr<CD3D11Device> dx11Device,
std::shared_ptr<CD3D12Device> dx12Device,
ComPtr<ID3D11Texture2D> srcTex)
{
HRESULT hr;
D3D11_TEXTURE2D_DESC srcDesc;
srcTex->GetDesc(&srcDesc);
ComPtr<IDXGIResource1> rSrcTex;
hr = srcTex.As(&rSrcTex);
if (FAILED(hr))
{
DEBUG_ERROR_HR(hr, "Failed to obtain the IDXGIResource1 interface");
return false;
}
HANDLE h;
Wrappers::HandleT<Wrappers::HandleTraits::HANDLENullTraits> sharedHandle;
hr = rSrcTex->CreateSharedHandle(NULL, DXGI_SHARED_RESOURCE_READ, NULL, &h);
if (FAILED(hr))
{
DEBUG_ERROR_HR(hr, "Failed to create the shared handle");
return false;
}
sharedHandle.Attach(h);
ComPtr<ID3D12Resource> dst;
hr = dx12Device->GetDevice()->OpenSharedHandle(sharedHandle.Get(), IID_PPV_ARGS(&dst));
if (FAILED(hr))
{
DEBUG_ERROR_HR(hr, "Failed to open the D3D12Resource from the handle");
return false;
}
sharedHandle.Close();
ComPtr<ID3D11Fence> d11Fence;
hr = dx11Device->GetDevice()->CreateFence(0, D3D11_FENCE_FLAG_SHARED, IID_PPV_ARGS(&d11Fence));
if (FAILED(hr))
{
DEBUG_ERROR_HR(hr, "Failed to create the d3d11 fence");
return false;
}
hr = d11Fence->CreateSharedHandle(NULL, GENERIC_ALL, NULL, &h);
if (FAILED(hr))
{
DEBUG_ERROR_HR(hr, "Failed to create the d3d11 fence shared handle");
return false;
}
sharedHandle.Attach(h);
ComPtr<ID3D12Fence> d12Fence;
hr = dx12Device->GetDevice()->OpenSharedHandle(sharedHandle.Get(), IID_PPV_ARGS(&d12Fence));
if (FAILED(hr))
{
DEBUG_ERROR_HR(hr, "Failed to open the D3D12Fence from the handle");
return false;
}
sharedHandle.Close();
m_dx11Device = dx11Device;
m_dx12Device = dx12Device;
memcpy(&m_format, &srcDesc, sizeof(m_format));
m_srcTex = srcTex.Get();
m_d12Res = dst;
m_d11Fence = d11Fence;
m_d12Fence = d12Fence;
m_fenceValue = 0;
m_nbDirtyRects = 0;
m_ready = true;
return true;
}
void CInteropResource::Reset()
{
m_ready = false;
m_fenceValue = 0;
m_d12Fence.Reset();
m_d11Fence.Reset();
m_d12Res .Reset();
m_srcTex = NULL;
m_nbDirtyRects = 0;
memset(&m_format, 0, sizeof(m_format));
m_dx12Device.reset();
m_dx11Device.reset();
}
bool CInteropResource::Compare(
const ComPtr<ID3D11Texture2D>& srcTex) const
{
if (srcTex.Get() != m_srcTex)
return false;
D3D11_TEXTURE2D_DESC format;
srcTex->GetDesc(&format);
return
m_format.Width == format.Width &&
m_format.Height == format.Height &&
m_format.Format == format.Format;
}
bool CInteropResource::Signal()
{
const UINT64 fenceValue = m_fenceValue + 1;
const HRESULT hr =
m_dx11Device->GetContext()->Signal(m_d11Fence.Get(), fenceValue);
if (FAILED(hr))
{
DEBUG_ERROR_HR(hr, "Failed to signal the D3D11 source fence");
return false;
}
m_fenceValue = fenceValue;
return true;
}
bool CInteropResource::Sync(CD3D12CommandSlot& slot)
{
if (m_d11Fence->GetCompletedValue() >= m_fenceValue)
return true;
if (!slot.WaitFor(m_d12Fence.Get(), m_fenceValue))
{
DEBUG_ERROR("Failed to queue a wait for the D3D11 source fence");
return false;
}
return true;
}
void CInteropResource::SetFullDamage()
{
m_dirtyRects[0].left = 0;
m_dirtyRects[0].top = 0;
m_dirtyRects[0].right = m_format.Width;
m_dirtyRects[0].bottom = m_format.Height;
m_nbDirtyRects = 1;
}
void CInteropResource::SetDirtyRects(const RECT * dirtyRects, unsigned nbDirtyRects)
{
if (nbDirtyRects > LG_MAX_DIRTY_RECTS)
{
SetFullDamage();
return;
}
if (nbDirtyRects)
memcpy(m_dirtyRects, dirtyRects, nbDirtyRects * sizeof(*m_dirtyRects));
m_nbDirtyRects = nbDirtyRects;
}

View File

@@ -0,0 +1,73 @@
/**
* Looking Glass
* Copyright © 2017-2026 The Looking Glass Authors
* https://looking-glass.io
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc., 59
* Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#pragma once
#include <Windows.h>
#include <wdf.h>
#include <wrl.h>
#include <memory>
#include "d3d/CD3D11Device.h"
#include "d3d/CD3D12Device.h"
#include "d3d/CD3D12CommandQueue.h"
using namespace Microsoft::WRL;
#define LG_MAX_DIRTY_RECTS 256
class CInteropResource
{
private:
std::shared_ptr<CD3D11Device> m_dx11Device;
std::shared_ptr<CD3D12Device> m_dx12Device;
// This value is likely released. It is only used to check if the supplied
// texture is different; do not rely on it pointing to valid memory.
void * m_srcTex;
ComPtr<ID3D12Resource > m_d12Res;
D3D11_TEXTURE2D_DESC m_format;
ComPtr<ID3D11Fence > m_d11Fence;
ComPtr<ID3D12Fence > m_d12Fence;
UINT64 m_fenceValue;
bool m_ready;
RECT m_dirtyRects[LG_MAX_DIRTY_RECTS];
unsigned m_nbDirtyRects;
public:
bool Init(std::shared_ptr<CD3D11Device> dx11Device,
std::shared_ptr<CD3D12Device> dx12Device,
ComPtr<ID3D11Texture2D> srcTex);
void Reset();
bool IsReady() const { return m_ready; }
bool Compare(const ComPtr<ID3D11Texture2D>& srcTex) const;
bool Signal();
bool Sync(CD3D12CommandSlot& slot);
void SetFullDamage();
void SetDirtyRects(const RECT * dirtyRects, unsigned nbDirtyRects);
const ComPtr<ID3D12Resource>& GetRes() const { return m_d12Res; }
const D3D11_TEXTURE2D_DESC& GetFormat() const { return m_format; }
const RECT * GetDirtyRects() const { return m_dirtyRects; }
unsigned GetDirtyRectCount() const { return m_nbDirtyRects; }
};

View File

@@ -0,0 +1,70 @@
/**
* Looking Glass
* Copyright © 2017-2026 The Looking Glass Authors
* https://looking-glass.io
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc., 59
* Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "d3d/CInteropResourcePool.h"
#include "CDebug.h"
void CInteropResourcePool::Init(
std::shared_ptr<CD3D11Device> dx11Device,
std::shared_ptr<CD3D12Device> dx12Device)
{
Reset();
m_dx11Device = dx11Device;
m_dx12Device = dx12Device;
}
void CInteropResourcePool::Reset()
{
for (unsigned i = 0; i < POOL_SIZE; ++i)
m_pool[i].Reset();
m_dx11Device.reset();
m_dx12Device.reset();
}
CInteropResource * CInteropResourcePool::Get(
ComPtr<ID3D11Texture2D> srcTex)
{
CInteropResource * res;
unsigned freeSlot = POOL_SIZE;
for (unsigned i = 0; i < POOL_SIZE; ++i)
{
res = &m_pool[i];
if (!res->IsReady())
{
freeSlot = min(freeSlot, i);
continue;
}
if (res->Compare(srcTex))
return res;
}
if (freeSlot == POOL_SIZE)
{
DEBUG_ERROR("Interop Resouce Pool Full");
return nullptr;
}
res = &m_pool[freeSlot];
if (!res->Init(m_dx11Device, m_dx12Device, srcTex))
return nullptr;
return res;
}

View File

@@ -0,0 +1,47 @@
/**
* Looking Glass
* Copyright © 2017-2026 The Looking Glass Authors
* https://looking-glass.io
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc., 59
* Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#pragma once
#include <Windows.h>
#include <wdf.h>
#include <wrl.h>
#include <d3d11_4.h>
#include "d3d/CInteropResource.h"
using namespace Microsoft::WRL;
class CInteropResourcePool
{
private:
static constexpr unsigned POOL_SIZE = 10;
CInteropResource m_pool[POOL_SIZE];
std::shared_ptr<CD3D11Device> m_dx11Device;
std::shared_ptr<CD3D12Device> m_dx12Device;
public:
void Init(std::shared_ptr<CD3D11Device> dx11Device,
std::shared_ptr<CD3D12Device> dx12Device);
void Reset();
CInteropResource * Get(ComPtr<ID3D11Texture2D> srcTex);
};