diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index c2e22221..40c20c35 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -122,6 +122,29 @@ jobs: - name: Run ComputeSharp.D2D1.Tests.AssemblyLevelAttributes run: dotnet test tests\ComputeSharp.D2D1.Tests.AssemblyLevelAttributes\ComputeSharp.D2D1.Tests.AssemblyLevelAttributes.csproj -c Release -f ${{matrix.framework}} -v n -l "console;verbosity=detailed" + # Run all unit tests using D3D12MA + run-tests-d3d12ma: + needs: [build-solution] + strategy: + matrix: + framework: [net7.0, net6.0] + runs-on: windows-2022 + env: + CI_RUNNER_DOTNET_TEST_PLATFORM: x64 + steps: + - name: Git checkout + uses: actions/checkout@v3 + + # D3D12MA tests (main ComputeSharp tests, as well as the device lost ones) + - name: Run ComputeSharp.Tests + run: dotnet test tests\ComputeSharp.Tests\ComputeSharp.Tests.csproj -c Release -f ${{matrix.framework}} /p:Platform=x64 /p:UseD3D12MemoryAllocator=true -v n -l "console;verbosity=detailed" + - name: Run ComputeSharp.Tests.DeviceLost "DeviceDisposal" + run: dotnet test tests\ComputeSharp.Tests.DeviceLost\ComputeSharp.Tests.DeviceLost.csproj --filter "TestCategory=DeviceDisposal" -c Release -f ${{matrix.framework}} /p:UseD3D12MemoryAllocator=true -v n -l "console;verbosity=detailed" + - name: Run ComputeSharp.Tests.DeviceLost "DeviceLost" + run: dotnet test tests\ComputeSharp.Tests.DeviceLost\ComputeSharp.Tests.DeviceLost.csproj --filter "TestCategory=DeviceLost" -c Release -f ${{matrix.framework}} /p:UseD3D12MemoryAllocator=true -v n -l "console;verbosity=detailed" + - name: Run ComputeSharp.Tests.DeviceLost "GetDefaultDevice" + run: dotnet test tests\ComputeSharp.Tests.DeviceLost\ComputeSharp.Tests.DeviceLost.csproj --filter "TestCategory=GetDefaultDevice" -c Release -f ${{matrix.framework}} /p:UseD3D12MemoryAllocator=true -v n -l "console;verbosity=detailed" + # Run all Win2D tests (separately, as they need VS Test) run-tests-win2d: needs: [build-solution] @@ -299,7 +322,7 @@ jobs: # Publish the packages to GitHub packages publish-nightlies-github: - needs: [run-tests, run-tests-win2d, run-samples, run-samples-aot, verify-packages] + needs: [run-tests, run-tests-d3d12ma, run-tests-win2d, run-samples, run-samples-aot, verify-packages] runs-on: windows-2022 if: ${{github.event_name == 'push'}} steps: @@ -311,7 +334,7 @@ jobs: # Publish the packages to Azure DevOps publish-nightlies-azure-devops: - needs: [run-tests, run-tests-win2d, run-samples, run-samples-aot, verify-packages] + needs: [run-tests, run-tests-d3d12ma, run-tests-win2d, run-samples, run-samples-aot, verify-packages] runs-on: windows-2022 if: ${{github.event_name == 'push'}} steps: diff --git a/ComputeSharp.sln b/ComputeSharp.sln index 0ad476a6..a6a67a14 100644 --- a/ComputeSharp.sln +++ b/ComputeSharp.sln @@ -156,6 +156,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.D2D1.Uwp.Tests EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.D2D1.WinUI.Tests", "tests\ComputeSharp.D2D1.WinUI.Tests\ComputeSharp.D2D1.WinUI.Tests.csproj", "{73C32D0F-64DB-4674-84E9-8FCC41228474}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.D3D12MemoryAllocator", "src\ComputeSharp.D3D12MemoryAllocator\ComputeSharp.D3D12MemoryAllocator.csproj", "{E017B3B6-C7D3-4E53-A7F6-1036178E98C3}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 @@ -444,6 +446,14 @@ Global {73C32D0F-64DB-4674-84E9-8FCC41228474}.Release|x64.ActiveCfg = Release|x64 {73C32D0F-64DB-4674-84E9-8FCC41228474}.Release|x64.Build.0 = Release|x64 {73C32D0F-64DB-4674-84E9-8FCC41228474}.Release|x64.Deploy.0 = Release|x64 + {E017B3B6-C7D3-4E53-A7F6-1036178E98C3}.Debug|ARM64.ActiveCfg = Debug|Any CPU + {E017B3B6-C7D3-4E53-A7F6-1036178E98C3}.Debug|ARM64.Build.0 = Debug|Any CPU + {E017B3B6-C7D3-4E53-A7F6-1036178E98C3}.Debug|x64.ActiveCfg = Debug|Any CPU + {E017B3B6-C7D3-4E53-A7F6-1036178E98C3}.Debug|x64.Build.0 = Debug|Any CPU + {E017B3B6-C7D3-4E53-A7F6-1036178E98C3}.Release|ARM64.ActiveCfg = Release|Any CPU + {E017B3B6-C7D3-4E53-A7F6-1036178E98C3}.Release|ARM64.Build.0 = Release|Any CPU + {E017B3B6-C7D3-4E53-A7F6-1036178E98C3}.Release|x64.ActiveCfg = Release|Any CPU + {E017B3B6-C7D3-4E53-A7F6-1036178E98C3}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/src/ComputeSharp.Core/ComputeSharp.Core.csproj b/src/ComputeSharp.Core/ComputeSharp.Core.csproj index e9817bf9..af45fa55 100644 --- a/src/ComputeSharp.Core/ComputeSharp.Core.csproj +++ b/src/ComputeSharp.Core/ComputeSharp.Core.csproj @@ -5,6 +5,7 @@ + diff --git a/src/ComputeSharp.D3D12MemoryAllocator/ComputeSharp.D3D12MemoryAllocator.csproj b/src/ComputeSharp.D3D12MemoryAllocator/ComputeSharp.D3D12MemoryAllocator.csproj new file mode 100644 index 00000000..a4655ba8 --- /dev/null +++ b/src/ComputeSharp.D3D12MemoryAllocator/ComputeSharp.D3D12MemoryAllocator.csproj @@ -0,0 +1,14 @@ + + + net6.0 + windows6.2 + + + + + + + + + + diff --git a/src/ComputeSharp.D3D12MemoryAllocator/D3D12MemoryAllocatorFactory.cs b/src/ComputeSharp.D3D12MemoryAllocator/D3D12MemoryAllocatorFactory.cs new file mode 100644 index 00000000..24343f83 --- /dev/null +++ b/src/ComputeSharp.D3D12MemoryAllocator/D3D12MemoryAllocatorFactory.cs @@ -0,0 +1,70 @@ +using System; +using System.Runtime.InteropServices; +using ComputeSharp.Core.Extensions; +using ComputeSharp.D3D12MemoryAllocator.Interop; +using TerraFX.Interop.Windows; + +namespace ComputeSharp.D3D12MemoryAllocator; + +/// +/// The entry point to obtain ID3D12MemoryAllocatorFactory instances using D3D12MA. +/// +public sealed unsafe class D3D12MemoryAllocatorFactory : ICustomQueryInterface +{ + /// + /// The object wrapped by the current instance. + /// + private readonly ID3D12MemoryAllocatorFactoryImpl* allocatorFactory; + + /// + /// Creates a new instance (implementing ID3D12MemoryAllocatorFactory). + /// + /// + /// The resulting object should only be used to provide an argument for . + /// + public D3D12MemoryAllocatorFactory() + { + fixed (ID3D12MemoryAllocatorFactoryImpl** allocatorFactory = &this.allocatorFactory) + { + ID3D12MemoryAllocatorFactoryImpl.Factory(allocatorFactory).Assert(); + } + } + + /// + /// Releases the underlying ID3D12MemoryAllocatorFactory object. + /// + ~D3D12MemoryAllocatorFactory() + { + if (this.allocatorFactory is not null) + { + _ = this.allocatorFactory->Release(); + } + } + + /// + CustomQueryInterfaceResult ICustomQueryInterface.GetInterface(ref Guid iid, out IntPtr ppv) + { + // Handle invalid cases where the object was not constructed correctly. + // Practically speaking, this should never happen in a real world scenario. + if (this.allocatorFactory is null) + { + ppv = default; + + return CustomQueryInterfaceResult.Failed; + } + + fixed (Guid* riid = &iid) + fixed (IntPtr* ppResult = &ppv) + { + int hresult = this.allocatorFactory->QueryInterface(riid, (void**)ppResult); + + GC.KeepAlive(this); + + return hresult switch + { + S.S_OK => CustomQueryInterfaceResult.Handled, + _ => CustomQueryInterfaceResult.Failed + }; + } + } +} diff --git a/src/ComputeSharp.D3D12MemoryAllocator/Extensions/AllocatorExtensions.cs b/src/ComputeSharp.D3D12MemoryAllocator/Extensions/AllocatorExtensions.cs new file mode 100644 index 00000000..7d5156f3 --- /dev/null +++ b/src/ComputeSharp.D3D12MemoryAllocator/Extensions/AllocatorExtensions.cs @@ -0,0 +1,35 @@ +using ComputeSharp.Core.Extensions; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +using static TerraFX.Interop.DirectX.D3D12_CPU_PAGE_PROPERTY; +using static TerraFX.Interop.DirectX.D3D12_HEAP_TYPE; +using static TerraFX.Interop.DirectX.D3D12_MEMORY_POOL; + +namespace ComputeSharp.D3D12MemoryAllocator.Extensions; + +/// +/// A with extensions for the type. +/// +internal static unsafe class AllocatorExtensions +{ + /// + /// Creates a instance suited to be used for cache coherent UMA devices. + /// + /// The instance in use. + /// A instance suited to be used for cache coherent UMA devices. + public static ComPtr CreatePoolForCacheCoherentUMA(this ref D3D12MA_Allocator allocator) + { + using ComPtr pool = default; + + D3D12MA_POOL_DESC poolDesc = default; + poolDesc.HeapProperties.CreationNodeMask = 1; + poolDesc.HeapProperties.VisibleNodeMask = 1; + poolDesc.HeapProperties.Type = D3D12_HEAP_TYPE_CUSTOM; + poolDesc.HeapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK; + poolDesc.HeapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0; + + allocator.CreatePool(&poolDesc, pool.GetAddressOf()).Assert(); + + return pool.Move(); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D3D12MemoryAllocator/Extensions/ID3D12DeviceExtensions.cs b/src/ComputeSharp.D3D12MemoryAllocator/Extensions/ID3D12DeviceExtensions.cs new file mode 100644 index 00000000..d6e79ace --- /dev/null +++ b/src/ComputeSharp.D3D12MemoryAllocator/Extensions/ID3D12DeviceExtensions.cs @@ -0,0 +1,31 @@ +using ComputeSharp.Core.Extensions; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +using System.Runtime.CompilerServices; + +namespace ComputeSharp.Graphics.Extensions; + +/// +/// A with extensions for the type. +/// +internal static unsafe class ID3D12DeviceExtensions +{ + /// + /// Creates a instance for a given device. + /// + /// The target to use to create the allocator. + /// The that was created from. + /// A instance to create resources on the device in use. + public static ComPtr CreateAllocator(this ref ID3D12Device d3D12Device, IDXGIAdapter* dxgiAdapter) + { + using ComPtr allocator = default; + + D3D12MA_ALLOCATOR_DESC allocatorDesc = default; + allocatorDesc.pDevice = (ID3D12Device*)Unsafe.AsPointer(ref d3D12Device); + allocatorDesc.pAdapter = dxgiAdapter; + + D3D12MemAlloc.D3D12MA_CreateAllocator(&allocatorDesc, allocator.GetAddressOf()).Assert(); + + return allocator.Move(); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12AllocationImpl.cs b/src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12AllocationImpl.cs new file mode 100644 index 00000000..f8d20d4b --- /dev/null +++ b/src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12AllocationImpl.cs @@ -0,0 +1,174 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using ComputeSharp.Interop.Allocation; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +namespace ComputeSharp.D3D12MemoryAllocator.Interop; + +/// +/// An implementation of the interface. +/// +internal unsafe struct ID3D12AllocationImpl +{ + /// + /// The shared method table pointer for all instances. + /// + private static readonly void** Vtbl = InitVtbl(); + + /// + /// Builds the custom method table pointer for . + /// + /// The method table pointer for . + private static void** InitVtbl() + { + void** lpVtbl = (void**)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(ID3D12AllocationImpl), sizeof(void*) * 4); + + lpVtbl[0] = (delegate* unmanaged)&QueryInterface; + lpVtbl[1] = (delegate* unmanaged)&AddRef; + lpVtbl[2] = (delegate* unmanaged)&Release; + lpVtbl[3] = (delegate* unmanaged)&GetD3D12Resource; + + return lpVtbl; + } + + /// + /// The vtable pointer for the current instance. + /// + private void** lpVtbl; + + /// + /// The current reference count for the object (from ). + /// + private volatile int referenceCount; + + /// + /// The parent instance. + /// + private ID3D12MemoryAllocatorImpl* allocatorImpl; + + /// + /// The wrapped instance. + /// + private D3D12MA_Allocation* allocation; + + /// + /// The underlying instance. + /// + private ID3D12Resource* d3D12Resource; + + /// + /// The factory method for instances. + /// + /// The resulting instance. + /// The parent instance. + /// The wrapped instance. + /// The underlying instance. + /// An for the operation. + public static HRESULT Factory( + ID3D12AllocationImpl** allocationImpl, + ID3D12MemoryAllocatorImpl* allocatorImpl, + D3D12MA_Allocation* allocation, + ID3D12Resource* d3D12Resource) + { + ID3D12AllocationImpl* @this; + + try + { + @this = (ID3D12AllocationImpl*)NativeMemory.Alloc((nuint)sizeof(ID3D12AllocationImpl)); + } + catch (OutOfMemoryException) + { + *allocationImpl = null; + + return E.E_OUTOFMEMORY; + } + + _ = allocatorImpl->AddRef(); + _ = allocation->AddRef(); + _ = d3D12Resource->AddRef(); + + @this->lpVtbl = Vtbl; + @this->referenceCount = 1; + @this->allocatorImpl = allocatorImpl; + @this->allocation = allocation; + @this->d3D12Resource = d3D12Resource; + + *allocationImpl = @this; + + return S.S_OK; + } + + /// + [UnmanagedCallersOnly] + private static int QueryInterface(ID3D12AllocationImpl* @this, Guid* riid, void** ppvObject) + { + if (ppvObject is null) + { + return E.E_POINTER; + } + + if (riid->Equals(Windows.__uuidof()) || + riid->Equals(ID3D12Allocation.Guid)) + { + _ = Interlocked.Increment(ref @this->referenceCount); + + *ppvObject = @this; + + return S.S_OK; + } + + *ppvObject = null; + + return E.E_NOINTERFACE; + } + + /// + [UnmanagedCallersOnly] + private static uint AddRef(ID3D12AllocationImpl* @this) + { + return (uint)Interlocked.Increment(ref @this->referenceCount); + } + + /// + [UnmanagedCallersOnly] + private static uint Release(ID3D12AllocationImpl* @this) + { + uint referenceCount = (uint)Interlocked.Decrement(ref @this->referenceCount); + + if (referenceCount == 0) + { + _ = @this->allocation->Release(); + _ = @this->d3D12Resource->Release(); + + // Release the parent allocator as well as last thing. This is needed because the D3D12MA allocator + // will fail if an allocator is released while there are still outstanding allocations. So here we + // increment the reference count of the allocator when creating a new allocation object, and then we + // decrement it after the underlying allocation has been released. This means that if this allocation + // is the last thing keeping the allocator alive, it'll be disposed correctly after this last object. + _ = @this->allocatorImpl->Release(); + + NativeMemory.Free(@this); + } + + return referenceCount; + } + + /// + [UnmanagedCallersOnly] + private static int GetD3D12Resource(ID3D12AllocationImpl* @this, ID3D12Resource** resource) + { + if (resource is null) + { + return E.E_POINTER; + } + + _ = @this->d3D12Resource->AddRef(); + + *resource = @this->d3D12Resource; + + return S.S_OK; + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12MemoryAllocatorFactoryImpl.cs b/src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12MemoryAllocatorFactoryImpl.cs new file mode 100644 index 00000000..2795efa4 --- /dev/null +++ b/src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12MemoryAllocatorFactoryImpl.cs @@ -0,0 +1,171 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using ComputeSharp.D3D12MemoryAllocator.Extensions; +using ComputeSharp.Graphics.Extensions; +using ComputeSharp.Interop.Allocation; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +using static TerraFX.Interop.DirectX.D3D12_FEATURE; + +namespace ComputeSharp.D3D12MemoryAllocator.Interop; + +/// +/// An implementation of the interface. +/// +internal unsafe struct ID3D12MemoryAllocatorFactoryImpl +{ + /// + /// The shared method table pointer for all instances. + /// + private static readonly void** Vtbl = InitVtbl(); + + /// + /// Builds the custom method table pointer for . + /// + /// The method table pointer for . + private static void** InitVtbl() + { + void** lpVtbl = (void**)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(ID3D12MemoryAllocatorFactoryImpl), sizeof(void*) * 4); + + lpVtbl[0] = (delegate* unmanaged)&QueryInterface; + lpVtbl[1] = (delegate* unmanaged)&AddRef; + lpVtbl[2] = (delegate* unmanaged)&Release; + lpVtbl[3] = (delegate* unmanaged)&CreateAllocator; + + return lpVtbl; + } + + /// + /// The vtable pointer for the current instance. + /// + private void** lpVtbl; + + /// + /// The current reference count for the object (from ). + /// + private volatile int referenceCount; + + /// + /// The factory method for instances. + /// + /// The resulting instance. + /// An for the operation. + public static HRESULT Factory(ID3D12MemoryAllocatorFactoryImpl** allocatorFactoryImpl) + { + ID3D12MemoryAllocatorFactoryImpl* @this; + + try + { + @this = (ID3D12MemoryAllocatorFactoryImpl*)NativeMemory.Alloc((nuint)sizeof(ID3D12MemoryAllocatorFactoryImpl)); + } + catch (OutOfMemoryException) + { + *allocatorFactoryImpl = null; + + return E.E_OUTOFMEMORY; + } + + @this->lpVtbl = Vtbl; + @this->referenceCount = 1; + + *allocatorFactoryImpl = @this; + + return S.S_OK; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int QueryInterface(Guid* riid, void** ppvObject) + { + if (ppvObject is null) + { + return E.E_POINTER; + } + + if (riid->Equals(Windows.__uuidof()) || + riid->Equals(ID3D12MemoryAllocatorFactory.Guid)) + { + _ = Interlocked.Increment(ref this.referenceCount); + + *ppvObject = Unsafe.AsPointer(ref this); + + return S.S_OK; + } + + *ppvObject = null; + + return E.E_NOINTERFACE; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public uint Release() + { + uint referenceCount = (uint)Interlocked.Decrement(ref this.referenceCount); + + if (referenceCount == 0) + { + NativeMemory.Free(Unsafe.AsPointer(ref this)); + } + + return referenceCount; + } + + /// + [UnmanagedCallersOnly] + private static int QueryInterface(ID3D12MemoryAllocatorFactoryImpl* @this, Guid* riid, void** ppvObject) + { + return @this->QueryInterface(riid, ppvObject); + } + + /// + [UnmanagedCallersOnly] + private static uint AddRef(ID3D12MemoryAllocatorFactoryImpl* @this) + { + return (uint)Interlocked.Increment(ref @this->referenceCount); + } + + /// + [UnmanagedCallersOnly] + private static uint Release(ID3D12MemoryAllocatorFactoryImpl* @this) + { + return @this->Release(); + } + + /// + [UnmanagedCallersOnly] + private static int CreateAllocator( + ID3D12MemoryAllocatorFactoryImpl* @this, + ID3D12Device* device, + IDXGIAdapter* adapter, + ID3D12MemoryAllocator** allocator) + { + try + { + using ComPtr d3D12MA_allocator = device->CreateAllocator(adapter); + + // If the target device is a UMA device, also create a pool and use that in the allocator + if (device->CheckFeatureSupport(D3D12_FEATURE_ARCHITECTURE1).CacheCoherentUMA) + { + using ComPtr pool = d3D12MA_allocator.Get()->CreatePoolForCacheCoherentUMA(); + + return ID3D12MemoryAllocatorImpl.Factory( + allocatorImpl: (ID3D12MemoryAllocatorImpl**)allocator, + allocator: d3D12MA_allocator.Get(), + pool: pool.Get()); + } + + // Otherwise create a standard allocator with no explicit pool + return ID3D12MemoryAllocatorImpl.Factory( + allocatorImpl: (ID3D12MemoryAllocatorImpl**)allocator, + allocator: d3D12MA_allocator.Get(), + pool: null); + } + catch (Exception e) + { + return e.HResult; + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12MemoryAllocatorImpl.cs b/src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12MemoryAllocatorImpl.cs new file mode 100644 index 00000000..eb601f4e --- /dev/null +++ b/src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12MemoryAllocatorImpl.cs @@ -0,0 +1,216 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using ComputeSharp.Core.Extensions; +using ComputeSharp.Interop.Allocation; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +using static TerraFX.Interop.DirectX.D3D12MA_ALLOCATION_FLAGS; + +namespace ComputeSharp.D3D12MemoryAllocator.Interop; + +/// +/// An implementation of the interface. +/// +internal unsafe struct ID3D12MemoryAllocatorImpl +{ + /// + /// The shared method table pointer for all instances. + /// + private static readonly void** Vtbl = InitVtbl(); + + /// + /// Builds the custom method table pointer for . + /// + /// The method table pointer for . + private static void** InitVtbl() + { + void** lpVtbl = (void**)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(ID3D12MemoryAllocator), sizeof(void*) * 4); + + lpVtbl[0] = (delegate* unmanaged)&QueryInterface; + lpVtbl[1] = (delegate* unmanaged)&AddRef; + lpVtbl[2] = (delegate* unmanaged)&Release; + lpVtbl[3] = (delegate* unmanaged)&AllocateResource; + + return lpVtbl; + } + + /// + /// The vtable pointer for the current instance. + /// + private void** lpVtbl; + + /// + /// The current reference count for the object (from ). + /// + private volatile int referenceCount; + + /// + /// The in use associated to the current device. + /// + private D3D12MA_Allocator* allocator; + + /// + /// The instance in use, if the device is using cache coherent UMA. + /// + private D3D12MA_Pool* pool; + + /// + /// The factory method for instances. + /// + /// The resulting instance. + /// The input instance. + /// The input instance, if available. + /// An for the operation. + public static HRESULT Factory( + ID3D12MemoryAllocatorImpl** allocatorImpl, + D3D12MA_Allocator* allocator, + D3D12MA_Pool* pool) + { + ID3D12MemoryAllocatorImpl* @this; + + try + { + @this = (ID3D12MemoryAllocatorImpl*)NativeMemory.Alloc((nuint)sizeof(ID3D12MemoryAllocatorImpl)); + } + catch (OutOfMemoryException) + { + *allocatorImpl = null; + + return E.E_OUTOFMEMORY; + } + + _ = allocator->AddRef(); + + // The pool is not necessarily available (it's only used for UMA devices), as it allows creating + // resources in a CPU readable memory region. With non UMA devices, we use the default behavior. + if (pool is not null) + { + _ = pool->AddRef(); + } + + @this->lpVtbl = Vtbl; + @this->referenceCount = 1; + @this->allocator = allocator; + @this->pool = pool; + + *allocatorImpl = @this; + + return S.S_OK; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public uint AddRef() + { + return (uint)Interlocked.Increment(ref this.referenceCount); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public uint Release() + { + uint referenceCount = (uint)Interlocked.Decrement(ref this.referenceCount); + + if (referenceCount == 0) + { + // The pool must be released before its associated allocator is disposed. Note that in + // order for the disposal to work correctly, all resources created from the allocator + // must have been disposed already before the allocator is released. This is done by + // having the allocator also increment the reference count of their associated allocator. + // So here we just have to release first the pool, if present, and then the allocator. + if (this.pool is not null) + { + _ = this.pool->Release(); + } + + _ = this.allocator->Release(); + + NativeMemory.Free(Unsafe.AsPointer(ref this)); + } + + return referenceCount; + } + + /// + [UnmanagedCallersOnly] + private static int QueryInterface(ID3D12MemoryAllocatorImpl* @this, Guid* riid, void** ppvObject) + { + if (ppvObject is null) + { + return E.E_POINTER; + } + + if (riid->Equals(Windows.__uuidof()) || + riid->Equals(ID3D12MemoryAllocator.Guid)) + { + _ = Interlocked.Increment(ref @this->referenceCount); + + *ppvObject = @this; + + return S.S_OK; + } + + *ppvObject = null; + + return E.E_NOINTERFACE; + } + + /// + [UnmanagedCallersOnly] + private static uint AddRef(ID3D12MemoryAllocatorImpl* @this) + { + return @this->AddRef(); + } + + /// + [UnmanagedCallersOnly] + private static uint Release(ID3D12MemoryAllocatorImpl* @this) + { + return @this->Release(); + } + + /// + [UnmanagedCallersOnly] + private static int AllocateResource( + ID3D12MemoryAllocatorImpl* @this, + D3D12_RESOURCE_DESC* resourceDescription, + D3D12_HEAP_TYPE heapType, + D3D12_RESOURCE_STATES resourceStates, + BOOL clearAllocation, + ID3D12Allocation** allocation) + { + D3D12MA_ALLOCATION_FLAGS allocationFlags = clearAllocation ? D3D12MA_ALLOCATION_FLAG_COMMITTED : D3D12MA_ALLOCATION_FLAG_NONE; + + D3D12MA_ALLOCATION_DESC allocationDesc = default; + allocationDesc.HeapType = heapType; + allocationDesc.Flags = allocationFlags; + allocationDesc.CustomPool = @this->pool; + + using ComPtr d3D12MA_allocation = default; + using ComPtr d3D12Resource = default; + + // Invoke D3D12MA and create an allocation and resource + HRESULT hresult = @this->allocator->CreateResource( + pAllocDesc: &allocationDesc, + pResourceDesc: resourceDescription, + InitialResourceState: resourceStates, + pOptimizedClearValue: null, + ppAllocation: d3D12MA_allocation.GetAddressOf(), + riidResource: Windows.__uuidof(), + ppvResource: d3D12Resource.GetVoidAddressOf()); + + if (!Windows.SUCCEEDED(hresult)) + { + return hresult; + } + + // Create the allocation wrapper + return ID3D12AllocationImpl.Factory( + allocationImpl: (ID3D12AllocationImpl**)allocation, + allocatorImpl: @this, + allocation: d3D12MA_allocation.Get(), + d3D12Resource: d3D12Resource.Get()); + } +} \ No newline at end of file diff --git a/src/ComputeSharp/ComputeSharp.csproj b/src/ComputeSharp/ComputeSharp.csproj index 0ad1927a..a5d08ede 100644 --- a/src/ComputeSharp/ComputeSharp.csproj +++ b/src/ComputeSharp/ComputeSharp.csproj @@ -5,6 +5,7 @@ + @@ -16,12 +17,12 @@ - + - + - + diff --git a/src/ComputeSharp/Graphics/Extensions/Interop/ID3D12AllocationExtensions.cs b/src/ComputeSharp/Graphics/Extensions/Interop/ID3D12AllocationExtensions.cs new file mode 100644 index 00000000..ff1a050b --- /dev/null +++ b/src/ComputeSharp/Graphics/Extensions/Interop/ID3D12AllocationExtensions.cs @@ -0,0 +1,29 @@ +using ComputeSharp.Core.Extensions; +using ComputeSharp.Interop.Allocation; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +namespace ComputeSharp.Graphics.Extensions; + +/// +/// A with extensions for the type. +/// +internal static unsafe class ID3D12AllocationExtensions +{ + /// + /// Gets the underlying for a given object. + /// + /// The input object. + /// An reference for the current object. + /// + /// The returned resource should not be used after the current allocation instance has been released. + /// + public static ComPtr GetD3D12Resource(this ref ID3D12Allocation allocation) + { + using ComPtr d3D12Resource = default; + + allocation.GetD3D12Resource(d3D12Resource.GetAddressOf()).Assert(); + + return d3D12Resource.Move(); + } +} \ No newline at end of file diff --git a/src/ComputeSharp/Graphics/Extensions/Interop/ID3D12DeviceExtensions.cs b/src/ComputeSharp/Graphics/Extensions/Interop/ID3D12DeviceExtensions.cs index a6707113..c77fd2a2 100644 --- a/src/ComputeSharp/Graphics/Extensions/Interop/ID3D12DeviceExtensions.cs +++ b/src/ComputeSharp/Graphics/Extensions/Interop/ID3D12DeviceExtensions.cs @@ -1,32 +1,21 @@ using System; -#if NET6_0_OR_GREATER -using System.Runtime.CompilerServices; -#endif using ComputeSharp.Core.Extensions; -#if !NET6_0_OR_GREATER using ComputeSharp.Graphics.Resources.Enums; -#endif using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using static TerraFX.Interop.DirectX.D3D12_COMMAND_QUEUE_FLAGS; using static TerraFX.Interop.DirectX.D3D12_COMMAND_QUEUE_PRIORITY; -#if !NET6_0_OR_GREATER using static TerraFX.Interop.DirectX.D3D12_CPU_PAGE_PROPERTY; -#endif using static TerraFX.Interop.DirectX.D3D12_DESCRIPTOR_HEAP_FLAGS; using static TerraFX.Interop.DirectX.D3D12_DESCRIPTOR_HEAP_TYPE; using static TerraFX.Interop.DirectX.D3D12_FEATURE; using static TerraFX.Interop.DirectX.D3D12_FENCE_FLAGS; -#if !NET6_0_OR_GREATER using static TerraFX.Interop.DirectX.D3D12_HEAP_FLAGS; using static TerraFX.Interop.DirectX.D3D12_MEMORY_POOL; -#endif using static TerraFX.Interop.DirectX.D3D12_MESSAGE_ID; -#if !NET6_0_OR_GREATER using static TerraFX.Interop.DirectX.D3D12_HEAP_TYPE; using static TerraFX.Interop.DirectX.D3D12_RESOURCE_FLAGS; using static TerraFX.Interop.DirectX.D3D12_RESOURCE_STATES; -#endif using static TerraFX.Interop.DirectX.D3D12_SRV_DIMENSION; using static TerraFX.Interop.DirectX.D3D12_UAV_DIMENSION; @@ -37,26 +26,6 @@ namespace ComputeSharp.Graphics.Extensions; /// internal static unsafe class ID3D12DeviceExtensions { -#if NET6_0_OR_GREATER - /// - /// Creates a instance for a given device. - /// - /// The target to use to create the allocator. - /// The that was created from. - /// A instance to create resources on the device in use. - public static ComPtr CreateAllocator(this ref ID3D12Device d3D12Device, IDXGIAdapter* dxgiAdapter) - { - using ComPtr allocator = default; - - D3D12MA_ALLOCATOR_DESC allocatorDesc = default; - allocatorDesc.pDevice = (ID3D12Device*)Unsafe.AsPointer(ref d3D12Device); - allocatorDesc.pAdapter = dxgiAdapter; - - D3D12MemAlloc.D3D12MA_CreateAllocator(&allocatorDesc, allocator.GetAddressOf()).Assert(); - - return allocator.Move(); - } -#else /// /// Creates a committed resource for a given buffer type. /// @@ -301,7 +270,6 @@ internal static unsafe class ID3D12DeviceExtensions return d3D12Resource.Move(); } -#endif /// /// Creates a new for a given device. diff --git a/src/ComputeSharp/Graphics/Extensions/Interop/AllocatorExtensions.cs b/src/ComputeSharp/Graphics/Extensions/Interop/ID3D12MemoryAllocatorExtensions.cs similarity index 50% rename from src/ComputeSharp/Graphics/Extensions/Interop/AllocatorExtensions.cs rename to src/ComputeSharp/Graphics/Extensions/Interop/ID3D12MemoryAllocatorExtensions.cs index 973b978d..58e6f2e9 100644 --- a/src/ComputeSharp/Graphics/Extensions/Interop/AllocatorExtensions.cs +++ b/src/ComputeSharp/Graphics/Extensions/Interop/ID3D12MemoryAllocatorExtensions.cs @@ -1,62 +1,34 @@ -#if NET6_0_OR_GREATER - using System; using ComputeSharp.Core.Extensions; +using ComputeSharp.Interop.Allocation; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; -using static TerraFX.Interop.DirectX.D3D12_CPU_PAGE_PROPERTY; using static TerraFX.Interop.DirectX.D3D12_HEAP_TYPE; -using static TerraFX.Interop.DirectX.D3D12_MEMORY_POOL; using static TerraFX.Interop.DirectX.D3D12_RESOURCE_FLAGS; using static TerraFX.Interop.DirectX.D3D12_RESOURCE_STATES; -using static TerraFX.Interop.DirectX.D3D12MA_ALLOCATION_FLAGS; using ResourceType = ComputeSharp.Graphics.Resources.Enums.ResourceType; namespace ComputeSharp.Graphics.Extensions; /// -/// A with extensions for the type. +/// A with extensions for the type. /// -internal static unsafe class AllocatorExtensions +internal static unsafe class ID3D12MemoryAllocatorExtensions { /// - /// Creates a instance suited to be used for cache coherent UMA devices. + /// Allocates a resource for a given buffer type. /// - /// The instance in use. - /// A instance suited to be used for cache coherent UMA devices. - public static ComPtr CreatePoolForCacheCoherentUMA(this ref D3D12MA_Allocator allocator) - { - using ComPtr pool = default; - - D3D12MA_POOL_DESC poolDesc = default; - poolDesc.HeapProperties.CreationNodeMask = 1; - poolDesc.HeapProperties.VisibleNodeMask = 1; - poolDesc.HeapProperties.Type = D3D12_HEAP_TYPE_CUSTOM; - poolDesc.HeapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK; - poolDesc.HeapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0; - - allocator.CreatePool(&poolDesc, pool.GetAddressOf()).Assert(); - - return pool.Move(); - } - - /// - /// Creates a resource for a given buffer type. - /// - /// The instance in use. - /// The instance to use, if any. + /// The instance in use. /// The resource type currently in use. /// The allocation mode to use for the new resource. /// The size in bytes of the current buffer. - /// An reference for the current object. - public static ComPtr CreateResource( - this ref D3D12MA_Allocator allocator, - D3D12MA_Pool* pool, + /// An reference for the current object. + public static ComPtr AllocateResource( + this ref ID3D12MemoryAllocator allocator, ResourceType resourceType, AllocationMode allocationMode, ulong sizeInBytes) { - D3D12MA_ALLOCATION_FLAGS allocationFlags = allocationMode == AllocationMode.Default ? D3D12MA_ALLOCATION_FLAG_NONE : D3D12MA_ALLOCATION_FLAG_COMMITTED; (D3D12_HEAP_TYPE d3D12HeapType, D3D12_RESOURCE_FLAGS d3D12ResourceFlags, D3D12_RESOURCE_STATES d3D12ResourceStates) = resourceType switch @@ -69,93 +41,72 @@ internal static unsafe class AllocatorExtensions _ => default(ArgumentException).Throw<(D3D12_HEAP_TYPE, D3D12_RESOURCE_FLAGS, D3D12_RESOURCE_STATES)>(nameof(resourceType)) }; - using ComPtr allocation = default; + using ComPtr allocation = default; D3D12_RESOURCE_DESC d3D12ResourceDescription = D3D12_RESOURCE_DESC.Buffer(sizeInBytes, d3D12ResourceFlags); - D3D12MA_ALLOCATION_DESC allocationDesc = default; - allocationDesc.HeapType = d3D12HeapType; - allocationDesc.Flags = allocationFlags; - allocationDesc.CustomPool = pool; - - allocator.CreateResource( - &allocationDesc, - &d3D12ResourceDescription, - d3D12ResourceStates, - null, - allocation.GetAddressOf(), - null, - null).Assert(); + allocator.AllocateResource( + resourceDescription: &d3D12ResourceDescription, + heapType: d3D12HeapType, + resourceStates: d3D12ResourceStates, + clearAllocation: allocationMode == AllocationMode.Clear, + allocation: allocation.GetAddressOf()).Assert(); return allocation.Move(); } /// - /// Creates a resource for a given 1D texture type. + /// Allocates a resource for a given 1D texture type. /// - /// The instance in use. - /// The instance to use, if any. + /// The instance in use. /// The resource type currently in use. /// The allocation mode to use for the new resource. /// The value to use. /// The width of the texture resource. /// The default value for the resource. - /// An reference for the current object. - public static ComPtr CreateResource( - this ref D3D12MA_Allocator allocator, - D3D12MA_Pool* pool, + /// An reference for the current object. + public static ComPtr AllocateResource( + this ref ID3D12MemoryAllocator allocator, ResourceType resourceType, AllocationMode allocationMode, DXGI_FORMAT dxgiFormat, uint width, out D3D12_RESOURCE_STATES d3D12ResourceStates) { - D3D12MA_ALLOCATION_FLAGS allocationFlags = allocationMode == AllocationMode.Default ? D3D12MA_ALLOCATION_FLAG_NONE : D3D12MA_ALLOCATION_FLAG_COMMITTED; - D3D12_RESOURCE_FLAGS d3D12ResourceFlags; - - (d3D12ResourceFlags, d3D12ResourceStates) = resourceType switch + (D3D12_RESOURCE_FLAGS d3D12ResourceFlags, d3D12ResourceStates) = resourceType switch { ResourceType.ReadOnly => (D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COMMON), ResourceType.ReadWrite => (D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), _ => default(ArgumentException).Throw<(D3D12_RESOURCE_FLAGS, D3D12_RESOURCE_STATES)>(nameof(resourceType)) }; - using ComPtr allocation = default; + using ComPtr allocation = default; D3D12_RESOURCE_DESC d3D12ResourceDescription = D3D12_RESOURCE_DESC.Tex1D(dxgiFormat, width, mipLevels: 1, flags: d3D12ResourceFlags); - D3D12MA_ALLOCATION_DESC allocationDesc = default; - allocationDesc.HeapType = D3D12_HEAP_TYPE_DEFAULT; - allocationDesc.Flags = allocationFlags; - allocationDesc.CustomPool = pool; - - allocator.CreateResource( - &allocationDesc, - &d3D12ResourceDescription, - d3D12ResourceStates, - null, - allocation.GetAddressOf(), - null, - null).Assert(); + allocator.AllocateResource( + resourceDescription: &d3D12ResourceDescription, + heapType: D3D12_HEAP_TYPE_DEFAULT, + resourceStates: d3D12ResourceStates, + clearAllocation: allocationMode == AllocationMode.Clear, + allocation: allocation.GetAddressOf()).Assert(); return allocation.Move(); } /// - /// Creates a resource for a given 2D texture type. + /// Allocates a resource for a given 2D texture type. /// - /// The instance in use. - /// The instance to use, if any. + /// The instance in use. /// The resource type currently in use. /// The allocation mode to use for the new resource. /// The value to use. /// The width of the texture resource. /// The height of the texture resource. /// The default value for the resource. - /// An reference for the current object. - public static ComPtr CreateResource( - this ref D3D12MA_Allocator allocator, - D3D12MA_Pool* pool, + /// An reference for the current object. + public static ComPtr AllocateResource( + this ref ID3D12MemoryAllocator allocator, ResourceType resourceType, AllocationMode allocationMode, DXGI_FORMAT dxgiFormat, @@ -163,42 +114,31 @@ internal static unsafe class AllocatorExtensions uint height, out D3D12_RESOURCE_STATES d3D12ResourceStates) { - D3D12MA_ALLOCATION_FLAGS allocationFlags = allocationMode == AllocationMode.Default ? D3D12MA_ALLOCATION_FLAG_NONE : D3D12MA_ALLOCATION_FLAG_COMMITTED; - D3D12_RESOURCE_FLAGS d3D12ResourceFlags; - - (d3D12ResourceFlags, d3D12ResourceStates) = resourceType switch + (D3D12_RESOURCE_FLAGS d3D12ResourceFlags, d3D12ResourceStates) = resourceType switch { ResourceType.ReadOnly => (D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COMMON), ResourceType.ReadWrite => (D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), _ => default(ArgumentException).Throw<(D3D12_RESOURCE_FLAGS, D3D12_RESOURCE_STATES)>(nameof(resourceType)) }; - using ComPtr allocation = default; + using ComPtr allocation = default; D3D12_RESOURCE_DESC d3D12ResourceDescription = D3D12_RESOURCE_DESC.Tex2D(dxgiFormat, width, height, mipLevels: 1, flags: d3D12ResourceFlags); - D3D12MA_ALLOCATION_DESC allocationDesc = default; - allocationDesc.HeapType = D3D12_HEAP_TYPE_DEFAULT; - allocationDesc.Flags = allocationFlags; - allocationDesc.CustomPool = pool; - - allocator.CreateResource( - &allocationDesc, - &d3D12ResourceDescription, - d3D12ResourceStates, - null, - allocation.GetAddressOf(), - null, - null).Assert(); + allocator.AllocateResource( + resourceDescription: &d3D12ResourceDescription, + heapType: D3D12_HEAP_TYPE_DEFAULT, + resourceStates: d3D12ResourceStates, + clearAllocation: allocationMode == AllocationMode.Clear, + allocation: allocation.GetAddressOf()).Assert(); return allocation.Move(); } /// - /// Creates a resource for a given 3D texture type. + /// Allocates a resource for a given 3D texture type. /// - /// The instance in use. - /// The instance to use, if any. + /// The instance in use. /// The resource type currently in use. /// The allocation mode to use for the new resource. /// The value to use. @@ -206,10 +146,9 @@ internal static unsafe class AllocatorExtensions /// The height of the texture resource. /// The depth of the texture resource. /// The default value for the resource. - /// An reference for the current object. - public static ComPtr CreateResource( - this ref D3D12MA_Allocator allocator, - D3D12MA_Pool* pool, + /// An reference for the current object. + public static ComPtr AllocateResource( + this ref ID3D12MemoryAllocator allocator, ResourceType resourceType, AllocationMode allocationMode, DXGI_FORMAT dxgiFormat, @@ -218,36 +157,24 @@ internal static unsafe class AllocatorExtensions ushort depth, out D3D12_RESOURCE_STATES d3D12ResourceStates) { - D3D12MA_ALLOCATION_FLAGS allocationFlags = allocationMode == AllocationMode.Default ? D3D12MA_ALLOCATION_FLAG_NONE : D3D12MA_ALLOCATION_FLAG_COMMITTED; - D3D12_RESOURCE_FLAGS d3D12ResourceFlags; - - (d3D12ResourceFlags, d3D12ResourceStates) = resourceType switch + (D3D12_RESOURCE_FLAGS d3D12ResourceFlags, d3D12ResourceStates) = resourceType switch { ResourceType.ReadOnly => (D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COMMON), ResourceType.ReadWrite => (D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), _ => default(ArgumentException).Throw<(D3D12_RESOURCE_FLAGS, D3D12_RESOURCE_STATES)>(nameof(resourceType)) }; - using ComPtr allocation = default; + using ComPtr allocation = default; D3D12_RESOURCE_DESC d3D12ResourceDescription = D3D12_RESOURCE_DESC.Tex3D(dxgiFormat, width, height, depth, mipLevels: 1, flags: d3D12ResourceFlags); - D3D12MA_ALLOCATION_DESC allocationDesc = default; - allocationDesc.HeapType = D3D12_HEAP_TYPE_DEFAULT; - allocationDesc.Flags = allocationFlags; - allocationDesc.CustomPool = pool; - - allocator.CreateResource( - &allocationDesc, - &d3D12ResourceDescription, - d3D12ResourceStates, - null, - allocation.GetAddressOf(), - null, - null).Assert(); + allocator.AllocateResource( + resourceDescription: &d3D12ResourceDescription, + heapType: D3D12_HEAP_TYPE_DEFAULT, + resourceStates: d3D12ResourceStates, + clearAllocation: allocationMode == AllocationMode.Clear, + allocation: allocation.GetAddressOf()).Assert(); return allocation.Move(); } -} - -#endif \ No newline at end of file +} \ No newline at end of file diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.GetDevice.cs b/src/ComputeSharp/Graphics/GraphicsDevice.GetDevice.cs index 5d9a5c6b..5df13dbd 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.GetDevice.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.GetDevice.cs @@ -21,13 +21,13 @@ partial class GraphicsDevice /// support device lost scenarios (see ) and due to how the DirectX 12 /// runtime handles caching of device instances, this method has the following behavior: /// - /// If no device has been created, create the default one, cache it, and return it. - /// If a cached device is available, return that. - /// If the returned device is disposed, the cache is reset. - /// - /// If is called again after that, the returned device might map to a different adapter. - /// This would be the case if the first device was lost due to the adapter being removed from the system. - /// + /// If no device has been created, create the default one, cache it, and return it. + /// If a cached device is available, return that. + /// If the returned device is disposed, the cache is reset. + /// + /// If is called again after that, the returned device might map to a different adapter. + /// This would be the case if the first device was lost due to the adapter being removed from the system. + /// /// /// There is one additional caveat to the list above: if is called, then that device is lost, then /// the returned instance is disposed incorrectly (eg. with some existing resources not being diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.Resources.cs b/src/ComputeSharp/Graphics/GraphicsDevice.Resources.cs new file mode 100644 index 00000000..24cfa1a5 --- /dev/null +++ b/src/ComputeSharp/Graphics/GraphicsDevice.Resources.cs @@ -0,0 +1,179 @@ +using ComputeSharp.Graphics.Extensions; +using ComputeSharp.Interop.Allocation; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +using ResourceType = ComputeSharp.Graphics.Resources.Enums.ResourceType; + +namespace ComputeSharp; + +/// +unsafe partial class GraphicsDevice +{ + /// + /// Creates or allocates a resource for a given buffer type. + /// + /// The resource type currently in use. + /// The allocation mode to use for the new resource. + /// The size in bytes of the current buffer. + /// The resulting object, if one is used. + /// The resulting object for the buffer. + internal void CreateOrAllocateResource( + ResourceType resourceType, + AllocationMode allocationMode, + ulong sizeInBytes, + out ComPtr allocation, + out ComPtr d3D12Resource) + { + if (this.allocator.Get() is not null) + { + allocation = this.allocator.Get()->AllocateResource(resourceType, allocationMode, sizeInBytes); + d3D12Resource = allocation.Get()->GetD3D12Resource(); + } + else + { + allocation = null; + d3D12Resource = this.d3D12Device.Get()->CreateCommittedResource(resourceType, sizeInBytes, IsCacheCoherentUMA); + } + } + + /// + /// Creates or allocates a resource for a given 1D texture type. + /// + /// The resource type currently in use. + /// The allocation mode to use for the new resource. + /// The value to use. + /// The width of the texture resource. + /// The default value for the resource. + /// The resulting object, if one is used. + /// The resulting object for the 1D texture. + internal void CreateOrAllocateResource( + ResourceType resourceType, + AllocationMode allocationMode, + DXGI_FORMAT dxgiFormat, + uint width, + out ComPtr allocation, + out ComPtr d3D12Resource, + out D3D12_RESOURCE_STATES d3D12ResourceStates) + { + if (this.allocator.Get() is not null) + { + allocation = this.allocator.Get()->AllocateResource( + resourceType, + allocationMode, + dxgiFormat, + width, + out d3D12ResourceStates); + + d3D12Resource = allocation.Get()->GetD3D12Resource(); + } + else + { + allocation = null; + + d3D12Resource = this.d3D12Device.Get()->CreateCommittedResource( + resourceType, + dxgiFormat, + width, + IsCacheCoherentUMA, + out d3D12ResourceStates); + } + } + + /// + /// Creates or allocates a resource for a given 2D texture type. + /// + /// The resource type currently in use. + /// The allocation mode to use for the new resource. + /// The value to use. + /// The width of the texture resource. + /// The height of the texture resource. + /// The default value for the resource. + /// The resulting object, if one is used. + /// The resulting object for the 2D texture. + internal void CreateOrAllocateResource( + ResourceType resourceType, + AllocationMode allocationMode, + DXGI_FORMAT dxgiFormat, + uint width, + uint height, + out ComPtr allocation, + out ComPtr d3D12Resource, + out D3D12_RESOURCE_STATES d3D12ResourceStates) + { + if (this.allocator.Get() is not null) + { + allocation = this.allocator.Get()->AllocateResource( + resourceType, + allocationMode, + dxgiFormat, + width, + height, + out d3D12ResourceStates); + + d3D12Resource = allocation.Get()->GetD3D12Resource(); + } + else + { + allocation = null; + + d3D12Resource = this.d3D12Device.Get()->CreateCommittedResource( + resourceType, + dxgiFormat, + width, + height, + IsCacheCoherentUMA, + out d3D12ResourceStates); + } + } + + /// + /// Creates or allocates a resource for a given 3D texture type. + /// + /// The resource type currently in use. + /// The allocation mode to use for the new resource. + /// The value to use. + /// The width of the texture resource. + /// The height of the texture resource. + /// The depth of the texture resource. + /// The default value for the resource. + /// The resulting object, if one is used. + /// The resulting object for the 3D texture. + internal void CreateOrAllocateResource( + ResourceType resourceType, + AllocationMode allocationMode, + DXGI_FORMAT dxgiFormat, + uint width, + uint height, + ushort depth, + out ComPtr allocation, + out ComPtr d3D12Resource, + out D3D12_RESOURCE_STATES d3D12ResourceStates) + { + if (this.allocator.Get() is not null) + { + allocation = this.allocator.Get()->AllocateResource( + resourceType, + allocationMode, + dxgiFormat, + width, + height, + depth, + out d3D12ResourceStates); + + d3D12Resource = allocation.Get()->GetD3D12Resource(); + } + else + { + allocation = null; + + d3D12Resource = this.d3D12Device.Get()->CreateCommittedResource( + resourceType, + dxgiFormat, + width, + height, + depth, + IsCacheCoherentUMA, + out d3D12ResourceStates); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.cs b/src/ComputeSharp/Graphics/GraphicsDevice.cs index 16b1e412..0470f306 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.cs @@ -4,12 +4,10 @@ using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using ComputeSharp.Graphics.Commands.Interop; -#if NET6_0_OR_GREATER -using ComputeSharp.Core.Extensions; -#endif using ComputeSharp.Graphics.Extensions; using ComputeSharp.Graphics.Helpers; using ComputeSharp.Interop; +using ComputeSharp.Interop.Allocation; using ComputeSharp.Shaders.Models; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; @@ -81,17 +79,10 @@ public sealed unsafe partial class GraphicsDevice : IReferenceTrackedObject /// private ulong nextD3D12CopyFenceValue; -#if NET6_0_OR_GREATER /// - /// The in use associated to the current device. + /// The in use associated to the current device, if available. /// - private ComPtr allocator; - - /// - /// The instance in use, if is . - /// - private ComPtr pool; -#endif + private ComPtr allocator; /// /// A weak to the current instance (used to support the device lost callback). @@ -149,20 +140,20 @@ public sealed unsafe partial class GraphicsDevice : IReferenceTrackedObject /// The to use for the new instance. /// The that was created from. /// The available info for the new instance. - internal GraphicsDevice(ID3D12Device* d3D12Device, IDXGIAdapter* dxgiAdapter, DXGI_ADAPTER_DESC1* dxgiDescription1) + /// The optional instance to use. + internal GraphicsDevice(ID3D12Device* d3D12Device, IDXGIAdapter* dxgiAdapter, DXGI_ADAPTER_DESC1* dxgiDescription1, ID3D12MemoryAllocator* allocator) { using ReferenceTracker.Lease _0 = ReferenceTracker.Create(this, out this.referenceTracker); this.d3D12Device = new ComPtr(d3D12Device); - this.d3D12ComputeCommandQueue = d3D12Device->CreateCommandQueue(D3D12_COMMAND_LIST_TYPE_COMPUTE); this.d3D12CopyCommandQueue = d3D12Device->CreateCommandQueue(D3D12_COMMAND_LIST_TYPE_COPY); this.d3D12ComputeFence = d3D12Device->CreateFence(); this.d3D12CopyFence = d3D12Device->CreateFence(); - this.shaderResourceViewDescriptorAllocator = new ID3D12DescriptorHandleAllocator(d3D12Device); this.computeCommandListPool = new ID3D12CommandListPool(D3D12_COMMAND_LIST_TYPE_COMPUTE); this.copyCommandListPool = new ID3D12CommandListPool(D3D12_COMMAND_LIST_TYPE_COPY); + this.allocator = new ComPtr(allocator); Luid = Luid.FromLUID(dxgiDescription1->AdapterLuid); Name = new string((char*)dxgiDescription1->Description); @@ -179,15 +170,6 @@ public sealed unsafe partial class GraphicsDevice : IReferenceTrackedObject IsCacheCoherentUMA = d3D12Architecture1Data.CacheCoherentUMA != 0; -#if NET6_0_OR_GREATER - this.allocator = d3D12Device->CreateAllocator(dxgiAdapter); - - if (IsCacheCoherentUMA) - { - this.pool = this.allocator.Get()->CreatePoolForCacheCoherentUMA(); - } -#endif - this.deviceRemovedReason = S.S_OK; this.cachedPipelineData = new List(); @@ -233,19 +215,7 @@ public sealed unsafe partial class GraphicsDevice : IReferenceTrackedObject /// /// Gets the underlying wrapped by the current instance. /// - internal ID3D12Device* D3D12Device => this.d3D12Device; - -#if NET6_0_OR_GREATER - /// - /// Gets the underlying wrapped by the current instance. - /// - internal D3D12MA_Allocator* Allocator => this.allocator; - - /// - /// Gets the underlying wrapped by the current instance, if any. - /// - internal D3D12MA_Pool* Pool => this.pool; -#endif + internal ID3D12Device* D3D12Device => this.d3D12Device.Get(); /// /// Gets whether or not the current device has a cache coherent UMA architecture. @@ -369,28 +339,6 @@ public sealed unsafe partial class GraphicsDevice : IReferenceTrackedObject D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW); } - /// - /// Registers that a new resource has been allocated on the current device. - /// - internal void RegisterAllocatedResource() - { -#if NET6_0_OR_GREATER - this.pool.AddRef(); - this.allocator.AddRef(); -#endif - } - - /// - /// Unregisters a generic resource that was allocated on the current device. - /// - internal void UnregisterAllocatedResource() - { -#if NET6_0_OR_GREATER - this.pool.Release(); - this.allocator.Release(); -#endif - } - /// /// Registers a object for the current device to enable early disposal. /// @@ -484,17 +432,7 @@ public sealed unsafe partial class GraphicsDevice : IReferenceTrackedObject this.computeCommandListPool.Dispose(); this.copyCommandListPool.Dispose(); this.shaderResourceViewDescriptorAllocator.Dispose(); - - // On .NET 6, D3D12MA is used. In this case, the pool and allocator must be kept alive - // until all associated resources are returned and destroyed. Because of this, when the - // device is disposed (since there might be outstanding resources that are still alive), - // the pool and allocator are only released, but not disposed. This allows reosurces to - // also release them when disposed (since each resource keeps a reference back to the - // parent device). When the last one is disposed, the pool and allocator will be deleted. -#if NET6_0_OR_GREATER - this.pool.Release(); - this.allocator.Release(); -#endif + this.allocator.Dispose(); UnregisterDeviceLostCallback(this); diff --git a/src/ComputeSharp/Graphics/Helpers/DeviceHelper.Factory.cs b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.Factory.cs index d964ffab..4cef9487 100644 --- a/src/ComputeSharp/Graphics/Helpers/DeviceHelper.Factory.cs +++ b/src/ComputeSharp/Graphics/Helpers/DeviceHelper.Factory.cs @@ -1,13 +1,16 @@ +using System; using System.Collections.Generic; using System.Runtime.CompilerServices; +using ComputeSharp.Core.Extensions; using ComputeSharp.Graphics.Extensions; +using ComputeSharp.Interop.Allocation; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; namespace ComputeSharp.Graphics.Helpers; /// -partial class DeviceHelper +unsafe partial class DeviceHelper { /// /// The local cache of instances that are currently usable. @@ -24,11 +27,16 @@ partial class DeviceHelper /// private static GraphicsDevice? defaultDevice; + /// + /// The global instance to use, if any. + /// + private static ID3D12MemoryAllocatorFactory* globalAllocatorFactory; + /// /// Gets the cached instance or creates and caches a new one. /// /// The default instance. - public static unsafe GraphicsDevice GetDefaultDeviceFromCacheOrCreateInstance() + public static GraphicsDevice GetDefaultDeviceFromCacheOrCreateInstance() { lock (DevicesCache) { @@ -57,35 +65,6 @@ partial class DeviceHelper } } - /// - /// Retrieves a instance for an object. - /// - /// The to use to get a instance. - /// The that was created from. - /// The available info for the instance. - /// A instance for the input device. - private static unsafe GraphicsDevice GetOrCreateDevice(ID3D12Device* d3D12Device, IDXGIAdapter* dxgiAdapter, DXGI_ADAPTER_DESC1* dxgiDescription1) - { - lock (DevicesCache) - { - Luid luid = Luid.FromLUID(dxgiDescription1->AdapterLuid); - - if (!DevicesCache.TryGetValue(luid, out GraphicsDevice? device)) - { - device = new GraphicsDevice(d3D12Device, dxgiAdapter, dxgiDescription1); - - DevicesCache.Add(luid, device); - - if (Configuration.IsDebugOutputEnabled) - { - D3D12InfoQueueMap.Add(luid, d3D12Device->CreateInfoQueue()); - } - } - - return device; - } - } - /// /// Removes a from the internal cache. /// @@ -110,4 +89,79 @@ partial class DeviceHelper } } } + + /// + /// Configures the global ID3D12MemoryAllocatorFactory instance to use for the current process. + /// + /// + public static void ConfigureAllocatorFactory(ID3D12MemoryAllocatorFactory* allocatorFactory) + { + lock (DevicesCache) + { + default(InvalidOperationException).ThrowIf(DevicesCache.Count != 0, "The allocator factory can only be configured before creating devices."); + default(InvalidOperationException).ThrowIf(globalAllocatorFactory is not null, "The allocator factory can only be configured once."); + + _ = ((IUnknown*)allocatorFactory)->AddRef(); + + globalAllocatorFactory = allocatorFactory; + } + } + + /// + /// Retrieves a instance for an object. + /// + /// The to use to get a instance. + /// The that was created from. + /// The available info for the instance. + /// A instance for the input device. + private static GraphicsDevice GetOrCreateDevice(ID3D12Device* d3D12Device, IDXGIAdapter* dxgiAdapter, DXGI_ADAPTER_DESC1* dxgiDescription1) + { + lock (DevicesCache) + { + Luid luid = Luid.FromLUID(dxgiDescription1->AdapterLuid); + + if (!DevicesCache.TryGetValue(luid, out GraphicsDevice? device)) + { + using ComPtr memoryAllocator = default; + + // Try to create a new ID3D12MemoryAllocator instance for the new device + _ = TryGetMemoryAllocator(d3D12Device, dxgiAdapter, memoryAllocator.GetAddressOf()); + + // Create the device passing the underlying device, adapter, and optional allocator + device = new GraphicsDevice(d3D12Device, dxgiAdapter, dxgiDescription1, memoryAllocator.Get()); + + DevicesCache.Add(luid, device); + + if (Configuration.IsDebugOutputEnabled) + { + D3D12InfoQueueMap.Add(luid, d3D12Device->CreateInfoQueue()); + } + } + + return device; + } + } + + /// + /// Tries to create a new instance for a given device. + /// + /// The to try to create an allocator for. + /// The that was created from. + /// The resulting instance. + /// Whether an instance could be created successfully. + private static bool TryGetMemoryAllocator(ID3D12Device* d3D12Device, IDXGIAdapter* dxgiAdapter, ID3D12MemoryAllocator** memoryAllocator) + { + ID3D12MemoryAllocatorFactory* allocatorFactory = globalAllocatorFactory; + + if (allocatorFactory is null) + { + *memoryAllocator = null; + + return false; + } + + allocatorFactory->CreateAllocator(d3D12Device, dxgiAdapter, memoryAllocator).Assert(); + + return true; + } } \ No newline at end of file diff --git a/src/ComputeSharp/Graphics/Interop/Allocation/ID3D12Allocation.cs b/src/ComputeSharp/Graphics/Interop/Allocation/ID3D12Allocation.cs new file mode 100644 index 00000000..4ddfb0ec --- /dev/null +++ b/src/ComputeSharp/Graphics/Interop/Allocation/ID3D12Allocation.cs @@ -0,0 +1,93 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if NET6_0_OR_GREATER +using TerraFX.Interop; +#endif +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0649 + +namespace ComputeSharp.Interop.Allocation; + +/// +/// An allocation wrapper for a native object. +/// +[Guid("D42D5782-2DE7-4539-A817-482E3AA01E2E")] +internal unsafe struct ID3D12Allocation +#if NET6_0_OR_GREATER + : IUnknown.Interface +#endif +{ + /// + /// Gets the for (D42D5782-2DE7-4539-A817-482E3AA01E2E). + /// + public static ref readonly Guid Guid + { + get + { + ReadOnlySpan data = new byte[] { + 0x82, 0x57, 0x2D, 0xD4, + 0xE7, 0x2D, + 0x39, 0x45, + 0xA8, 0x17, + 0x48, + 0x2E, + 0x3A, + 0xA0, + 0x1E, + 0x2E + }; + + return ref Unsafe.As(ref MemoryMarshal.GetReference(data)); + } + } + +#if NET6_0_OR_GREATER + /// + static Guid* INativeGuid.NativeGuid => (Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in Guid)); +#endif + + /// + /// The vtable for the current instance. + /// + private readonly void** lpVtbl; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public HRESULT QueryInterface(Guid* riid, void** ppvObject) + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[0])((ID3D12Allocation*)Unsafe.AsPointer(ref this), riid, ppvObject); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public uint AddRef() + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[1])((ID3D12Allocation*)Unsafe.AsPointer(ref this)); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public uint Release() + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[2])((ID3D12Allocation*)Unsafe.AsPointer(ref this)); + } + + /// + /// Gets the underlying for the current instance. + /// + /// The resulting object. + /// An for the operation. + /// + /// The returned resource should not be used after the current allocation instance has been released. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public HRESULT GetD3D12Resource(ID3D12Resource** resource) + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[3])( + (ID3D12Allocation*)Unsafe.AsPointer(ref this), + resource); + } +} \ No newline at end of file diff --git a/src/ComputeSharp/Graphics/Interop/Allocation/ID3D12MemoryAllocator.cs b/src/ComputeSharp/Graphics/Interop/Allocation/ID3D12MemoryAllocator.cs new file mode 100644 index 00000000..7557a5df --- /dev/null +++ b/src/ComputeSharp/Graphics/Interop/Allocation/ID3D12MemoryAllocator.cs @@ -0,0 +1,103 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if NET6_0_OR_GREATER +using TerraFX.Interop; +#endif +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0649 + +namespace ComputeSharp.Interop.Allocation; + +/// +/// An object that can allocate resources for a given instance. +/// +[Guid("2D5E55D2-9244-431F-868E-0D90AAB6E575")] +internal unsafe struct ID3D12MemoryAllocator +#if NET6_0_OR_GREATER + : IUnknown.Interface +#endif +{ + /// + /// Gets the for (2D5E55D2-9244-431F-868E-0D90AAB6E575). + /// + public static ref readonly Guid Guid + { + get + { + ReadOnlySpan data = new byte[] { + 0xD2, 0x55, 0x5E, 0x2D, + 0x44, 0x92, + 0x1F, 0x43, + 0x86, 0x8E, + 0x0D, + 0x90, + 0xAA, + 0xB6, + 0xE5, + 0x75 + }; + + return ref Unsafe.As(ref MemoryMarshal.GetReference(data)); + } + } + +#if NET6_0_OR_GREATER + /// + static Guid* INativeGuid.NativeGuid => (Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in Guid)); +#endif + + /// + /// The vtable for the current instance. + /// + private readonly void** lpVtbl; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public HRESULT QueryInterface(Guid* riid, void** ppvObject) + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[0])((ID3D12MemoryAllocator*)Unsafe.AsPointer(ref this), riid, ppvObject); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public uint AddRef() + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[1])((ID3D12MemoryAllocator*)Unsafe.AsPointer(ref this)); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public uint Release() + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[2])((ID3D12MemoryAllocator*)Unsafe.AsPointer(ref this)); + } + + /// + /// Creates a new resource allocation from the current allocator. + /// + /// The description of the resource to allocate. + /// The type of heap to use for the allocation. + /// The resource states to use initially for the resource. + /// Whether to clear the allocation after creating it. + /// The resulting allocation. + /// An for the operation. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public HRESULT AllocateResource( + D3D12_RESOURCE_DESC* resourceDescription, + D3D12_HEAP_TYPE heapType, + D3D12_RESOURCE_STATES resourceStates, + BOOL clearAllocation, + ID3D12Allocation** allocation) + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[3])( + (ID3D12MemoryAllocator*)Unsafe.AsPointer(ref this), + resourceDescription, + heapType, + resourceStates, + clearAllocation, + allocation); + } +} \ No newline at end of file diff --git a/src/ComputeSharp/Graphics/Interop/Allocation/ID3D12MemoryAllocatorFactory.cs b/src/ComputeSharp/Graphics/Interop/Allocation/ID3D12MemoryAllocatorFactory.cs new file mode 100644 index 00000000..a5496fdb --- /dev/null +++ b/src/ComputeSharp/Graphics/Interop/Allocation/ID3D12MemoryAllocatorFactory.cs @@ -0,0 +1,97 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#if NET6_0_OR_GREATER +using TerraFX.Interop; +#endif +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0649 + +namespace ComputeSharp.Interop.Allocation; + +/// +/// A factory type for objects. +/// +[Guid("CC1E74A7-786D-40F4-8AE2-F8B7A255587E")] +internal unsafe struct ID3D12MemoryAllocatorFactory +#if NET6_0_OR_GREATER + : IUnknown.Interface +#endif +{ + /// + /// Gets the for (CC1E74A7-786D-40F4-8AE2-F8B7A255587E). + /// + public static ref readonly Guid Guid + { + get + { + ReadOnlySpan data = new byte[] { + 0xA7, 0x74, 0x1E, 0xCC, + 0x6D, 0x78, + 0xF4, 0x40, + 0x8A, 0xE2, + 0xF8, + 0xB7, + 0xA2, + 0x55, + 0x58, + 0x7E + }; + + return ref Unsafe.As(ref MemoryMarshal.GetReference(data)); + } + } + +#if NET6_0_OR_GREATER + /// + static Guid* INativeGuid.NativeGuid => (Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in Guid)); +#endif + + /// + /// The vtable for the current instance. + /// + private readonly void** lpVtbl; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public HRESULT QueryInterface(Guid* riid, void** ppvObject) + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[0])((ID3D12MemoryAllocatorFactory*)Unsafe.AsPointer(ref this), riid, ppvObject); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public uint AddRef() + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[1])((ID3D12MemoryAllocatorFactory*)Unsafe.AsPointer(ref this)); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public uint Release() + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[2])((ID3D12MemoryAllocatorFactory*)Unsafe.AsPointer(ref this)); + } + + /// + /// Creates a new for a given device. + /// + /// The device to create the allocator for. + /// The for . + /// The resulting instance. + /// An for the operation. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public HRESULT CreateAllocator( + ID3D12Device* device, + IDXGIAdapter* adapter, + ID3D12MemoryAllocator** allocator) + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[3])( + (ID3D12MemoryAllocatorFactory*)Unsafe.AsPointer(ref this), + device, + adapter, + allocator); + } +} \ No newline at end of file diff --git a/src/ComputeSharp/Graphics/Interop/AllocationServices.cs b/src/ComputeSharp/Graphics/Interop/AllocationServices.cs new file mode 100644 index 00000000..a926644c --- /dev/null +++ b/src/ComputeSharp/Graphics/Interop/AllocationServices.cs @@ -0,0 +1,86 @@ +using System; +using System.Runtime.InteropServices; +using ComputeSharp.Graphics.Helpers; +using ComputeSharp.Interop.Allocation; +using TerraFX.Interop.Windows; + +namespace ComputeSharp.Interop; + +/// +/// Provides methods to configure the global allocator factory instance that will be used by all objects. +/// +/// +/// +/// By default, all resources will be created as committed resources. The APIs make it possible to change +/// this behavior, and instead use a pluggable memory allocator implementing any desired custom logic to manage how resources are created. +/// +/// +/// Memory allocators are created through a factory object that can be configured via . This object +/// needs to implement the ID3D12MemoryAllocatorFactory COM interface, which has the following definition: +/// +/// [uuid(CC1E74A7-786D-40F4-8AE2-F8B7A255587E)] +/// interface ID3D12MemoryAllocatorFactory : IUnknown +/// { +/// HRESULT CreateAllocator( +/// [in] const ID3D12Device* device, +/// [in] const IDXGIAdapter* adapter, +/// [out] ID3D12MemoryAllocator allocator); +/// }; +/// +/// +/// +/// This is a simple, possibly stateless factory, responsible for creating per-device memory allocators. Those use the following interface: +/// +/// [uuid(2D5E55D2-9244-431F-868E-0D90AAB6E575)] +/// interface ID3D12MemoryAllocator : IUnknown +/// { +/// HRESULT AllocateResource( +/// [in] const D3D12_RESOURCE_DESC* resourceDescription, +/// const D3D12_HEAP_TYPE heapType, +/// const D3D12_RESOURCE_STATES resourceState, +/// const BOOL clearAllocation, +/// [out] ID3D12Allocation** allocation); +/// }; +/// +/// +/// +/// Finally, each returned allocation object wraps a given native resource, and uses the following interface: +/// +/// [uuid(D42D5782-2DE7-4539-A817-482E3AA01E2E)] +/// interface ID3D12Allocation : IUnknown +/// { +/// HRESULT GetD3D12Resource([out] ID3D12Resource** resource); +/// }; +/// +/// +/// +/// The implementation of these types can be done in any language, as long as the COM interfaces defined above are correctly supported. +/// +/// +public static class AllocationServices +{ + /// + /// Configures the global ID3D12MemoryAllocatorFactory instance to use for the current process. + /// + /// The input instance to use (implementing ID3D12MemoryAllocatorFactory). + /// Thrown if is . + /// Thrown if the allocator factory cannot be configured at this time. + /// + /// The allocatory factory can only be configured once, and before any instance has been created. + /// + public static unsafe void ConfigureAllocatorFactory(ICustomQueryInterface allocatorFactory) + { + default(ArgumentNullException).ThrowIfNull(allocatorFactory); + + using ComPtr allocatorFactoryAbi = default; + + // Unwrap the underlying ID3D12MemoryAllocatorFactory object + CustomQueryInterfaceResult result = allocatorFactory.GetInterface( + iid: ref *(Guid*)Windows.__uuidof(), + ppv: out *(IntPtr*)allocatorFactoryAbi.GetAddressOf()); + + default(InvalidOperationException).ThrowIf(result != CustomQueryInterfaceResult.Handled, "Failed to retrieve the underlying ID3D12MemoryAllocatorFactory object."); + + DeviceHelper.ConfigureAllocatorFactory(allocatorFactoryAbi.Get()); + } +} \ No newline at end of file diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Buffer{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Buffer{T}.cs index 34e8bfa8..481e58a5 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Buffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Buffer{T}.cs @@ -13,6 +13,7 @@ using TerraFX.Interop.Windows; using static TerraFX.Interop.DirectX.D3D12_FEATURE; using static TerraFX.Interop.DirectX.DXGI_FORMAT; using ResourceType = ComputeSharp.Graphics.Resources.Enums.ResourceType; +using ComputeSharp.Interop.Allocation; #if NET6_0_OR_GREATER using MemoryMarshal = System.Runtime.InteropServices.MemoryMarshal; #else @@ -33,12 +34,10 @@ public abstract unsafe partial class Buffer : IReferenceTrackedObject, IGraph /// private ReferenceTracker referenceTracker; -#if NET6_0_OR_GREATER /// - /// The instance used to retrieve . + /// The instance used to retrieve , if available. /// - private ComPtr allocation; -#endif + private ComPtr allocation; /// /// The instance currently mapped. @@ -100,14 +99,13 @@ public abstract unsafe partial class Buffer : IReferenceTrackedObject, IGraph GraphicsDevice = device; Length = length; -#if NET6_0_OR_GREATER - this.allocation = device.Allocator->CreateResource(device.Pool, resourceType, allocationMode, (ulong)effectiveSizeInBytes); - this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); -#else - this.d3D12Resource = device.D3D12Device->CreateCommittedResource(resourceType, (ulong)effectiveSizeInBytes, device.IsCacheCoherentUMA); -#endif + device.CreateOrAllocateResource( + resourceType, + allocationMode, + (ulong)effectiveSizeInBytes, + out this.allocation, + out this.d3D12Resource); - device.RegisterAllocatedResource(); device.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); device.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandlesForTypedUnorderedAccessView); @@ -214,13 +212,10 @@ public abstract unsafe partial class Buffer : IReferenceTrackedObject, IGraph void IReferenceTrackedObject.DangerousOnDispose() { this.d3D12Resource.Dispose(); -#if NET6_0_OR_GREATER this.allocation.Dispose(); -#endif if (GraphicsDevice is GraphicsDevice device) { - device.UnregisterAllocatedResource(); device.ReturnShaderResourceViewDescriptorHandles(in this.d3D12ResourceDescriptorHandles); device.ReturnShaderResourceViewDescriptorHandles(in this.d3D12ResourceDescriptorHandlesForTypedUnorderedAccessView); } diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs index 9416d22a..a76d6154 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/StructuredBuffer{T}.cs @@ -5,6 +5,7 @@ using ComputeSharp.Graphics.Extensions; using ComputeSharp.Graphics.Helpers; using ComputeSharp.Graphics.Resources.Interop; using ComputeSharp.Interop; +using ComputeSharp.Interop.Allocation; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using static TerraFX.Interop.DirectX.D3D12_COMMAND_LIST_TYPE; @@ -65,30 +66,23 @@ public abstract class StructuredBuffer : Buffer nint byteOffset = (nint)sourceOffset * sizeof(T); nint byteLength = count * sizeof(T); -#if NET6_0_OR_GREATER - using ComPtr allocation = GraphicsDevice.Allocator->CreateResource(GraphicsDevice.Pool, ResourceType.ReadBack, AllocationMode.Default, (ulong)byteLength); -#else - using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( + using ComPtr allocation = default; + using ComPtr d3D12Resource = default; + + GraphicsDevice.CreateOrAllocateResource( ResourceType.ReadBack, + AllocationMode.Default, (ulong)byteLength, - GraphicsDevice.IsCacheCoherentUMA); -#endif + out *&allocation, + out *&d3D12Resource); using (CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY)) { -#if NET6_0_OR_GREATER - copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion(allocation.Get()->GetResource(), 0, D3D12Resource, (ulong)byteOffset, (ulong)byteLength); -#else copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion(d3D12Resource.Get(), 0, D3D12Resource, (ulong)byteOffset, (ulong)byteLength); -#endif copyCommandList.ExecuteAndWaitForCompletion(); } -#if NET6_0_OR_GREATER - using ID3D12ResourceMap resource = allocation.Get()->GetResource()->Map(); -#else using ID3D12ResourceMap resource = d3D12Resource.Get()->Map(); -#endif fixed (void* destinationPointer = &destination) { @@ -229,20 +223,18 @@ public abstract class StructuredBuffer : Buffer nint byteOffset = (nint)offset * sizeof(T); nint byteLength = length * sizeof(T); -#if NET6_0_OR_GREATER - using ComPtr allocation = GraphicsDevice.Allocator->CreateResource(GraphicsDevice.Pool, ResourceType.Upload, AllocationMode.Default, (ulong)byteLength); -#else - using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( + using ComPtr allocation = default; + using ComPtr d3D12Resource = default; + + GraphicsDevice.CreateOrAllocateResource( ResourceType.Upload, + AllocationMode.Default, (ulong)byteLength, - GraphicsDevice.IsCacheCoherentUMA); -#endif + out *&allocation, + out *&d3D12Resource); -#if NET6_0_OR_GREATER - using (ID3D12ResourceMap resource = allocation.Get()->GetResource()->Map()) -#else using (ID3D12ResourceMap resource = d3D12Resource.Get()->Map()) -#endif + { fixed (void* sourcePointer = &source) { MemoryHelper.Copy( @@ -254,14 +246,11 @@ public abstract class StructuredBuffer : Buffer destinationElementPitchInBytes: (uint)sizeof(T), count: (uint)length); } + } using CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY); -#if NET6_0_OR_GREATER - copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion(D3D12Resource, (ulong)byteOffset, allocation.Get()->GetResource(), 0, (ulong)byteLength); -#else copyCommandList.D3D12GraphicsCommandList->CopyBufferRegion(D3D12Resource, (ulong)byteOffset, d3D12Resource.Get(), 0, (ulong)byteLength); -#endif copyCommandList.ExecuteAndWaitForCompletion(); } } diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Texture1D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Texture1D{T}.cs index d04db4c8..a527c406 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Texture1D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Texture1D{T}.cs @@ -9,6 +9,7 @@ using ComputeSharp.Graphics.Helpers; using ComputeSharp.Graphics.Resources.Helpers; using ComputeSharp.Graphics.Resources.Interop; using ComputeSharp.Interop; +using ComputeSharp.Interop.Allocation; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using static TerraFX.Interop.DirectX.D3D12_COMMAND_LIST_TYPE; @@ -33,12 +34,10 @@ public abstract unsafe partial class Texture1D : IReferenceTrackedObject, IGr /// private ReferenceTracker referenceTracker; -#if NET6_0_OR_GREATER /// - /// The instance used to retrieve . + /// The instance used to retrieve , if available. /// - private ComPtr allocation; -#endif + private ComPtr allocation; /// /// The instance currently mapped. @@ -90,25 +89,15 @@ public abstract unsafe partial class Texture1D : IReferenceTrackedObject, IGr GraphicsDevice = device; -#if NET6_0_OR_GREATER - this.allocation = device.Allocator->CreateResource( - device.Pool, + device.CreateOrAllocateResource( resourceType, allocationMode, DXGIFormatHelper.GetForType(), (uint)width, + out this.allocation, + out this.d3D12Resource, out this.d3D12ResourceState); - this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); -#else - this.d3D12Resource = device.D3D12Device->CreateCommittedResource( - resourceType, - DXGIFormatHelper.GetForType(), - (uint)width, - device.IsCacheCoherentUMA, - out this.d3D12ResourceState); -#endif - this.d3D12CommandListType = this.d3D12ResourceState == D3D12_RESOURCE_STATE_COMMON ? D3D12_COMMAND_LIST_TYPE_COPY : D3D12_COMMAND_LIST_TYPE_COMPUTE; @@ -120,7 +109,6 @@ public abstract unsafe partial class Texture1D : IReferenceTrackedObject, IGr out _, out _); - device.RegisterAllocatedResource(); device.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); switch (resourceType) @@ -181,20 +169,15 @@ public abstract unsafe partial class Texture1D : IReferenceTrackedObject, IGr out ulong rowSizeInBytes, out ulong totalSizeInBytes); -#if NET6_0_OR_GREATER - using ComPtr allocation = GraphicsDevice.Allocator->CreateResource( - GraphicsDevice.Pool, + using ComPtr allocation = default; + using ComPtr d3D12Resource = default; + + GraphicsDevice.CreateOrAllocateResource( ResourceType.ReadBack, AllocationMode.Default, - totalSizeInBytes); - - using ComPtr d3D12Resource = new(allocation.Get()->GetResource()); -#else - using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( - ResourceType.ReadBack, totalSizeInBytes, - GraphicsDevice.IsCacheCoherentUMA); -#endif + out *&allocation, + out *&d3D12Resource); using (CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType)) { @@ -379,20 +362,15 @@ public abstract unsafe partial class Texture1D : IReferenceTrackedObject, IGr out ulong rowSizeInBytes, out ulong totalSizeInBytes); -#if NET6_0_OR_GREATER - using ComPtr allocation = GraphicsDevice.Allocator->CreateResource( - GraphicsDevice.Pool, + using ComPtr allocation = default; + using ComPtr d3D12Resource = default; + + GraphicsDevice.CreateOrAllocateResource( ResourceType.Upload, AllocationMode.Default, - totalSizeInBytes); - - using ComPtr d3D12Resource = new(allocation.Get()->GetResource()); -#else - using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( - ResourceType.Upload, totalSizeInBytes, - GraphicsDevice.IsCacheCoherentUMA); -#endif + out *&allocation, + out *&d3D12Resource); using (ID3D12ResourceMap resource = d3D12Resource.Get()->Map()) { @@ -495,13 +473,10 @@ public abstract unsafe partial class Texture1D : IReferenceTrackedObject, IGr protected virtual partial void DangerousOnDispose() { this.d3D12Resource.Dispose(); -#if NET6_0_OR_GREATER this.allocation.Dispose(); -#endif if (GraphicsDevice is GraphicsDevice device) { - device.UnregisterAllocatedResource(); device.ReturnShaderResourceViewDescriptorHandles(in this.d3D12ResourceDescriptorHandles); } } diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs index 5759bcf9..6d27d4c3 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Texture2D{T}.cs @@ -9,6 +9,7 @@ using ComputeSharp.Graphics.Helpers; using ComputeSharp.Graphics.Resources.Helpers; using ComputeSharp.Graphics.Resources.Interop; using ComputeSharp.Interop; +using ComputeSharp.Interop.Allocation; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using static TerraFX.Interop.DirectX.D3D12_COMMAND_LIST_TYPE; @@ -33,12 +34,10 @@ public abstract unsafe partial class Texture2D : IReferenceTrackedObject, IGr /// private ReferenceTracker referenceTracker; -#if NET6_0_OR_GREATER /// - /// The instance used to retrieve . + /// The instance used to retrieve , if available. /// - private ComPtr allocation; -#endif + private ComPtr allocation; /// /// The instance currently mapped. @@ -92,27 +91,16 @@ public abstract unsafe partial class Texture2D : IReferenceTrackedObject, IGr GraphicsDevice = device; -#if NET6_0_OR_GREATER - this.allocation = device.Allocator->CreateResource( - device.Pool, + device.CreateOrAllocateResource( resourceType, allocationMode, DXGIFormatHelper.GetForType(), (uint)width, (uint)height, + out this.allocation, + out this.d3D12Resource, out this.d3D12ResourceState); - this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); -#else - this.d3D12Resource = device.D3D12Device->CreateCommittedResource( - resourceType, - DXGIFormatHelper.GetForType(), - (uint)width, - (uint)height, - device.IsCacheCoherentUMA, - out this.d3D12ResourceState); -#endif - this.d3D12CommandListType = this.d3D12ResourceState == D3D12_RESOURCE_STATE_COMMON ? D3D12_COMMAND_LIST_TYPE_COPY : D3D12_COMMAND_LIST_TYPE_COMPUTE; @@ -125,7 +113,6 @@ public abstract unsafe partial class Texture2D : IReferenceTrackedObject, IGr out _, out _); - device.RegisterAllocatedResource(); device.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); switch (resourceType) @@ -197,20 +184,15 @@ public abstract unsafe partial class Texture2D : IReferenceTrackedObject, IGr out ulong rowSizeInBytes, out ulong totalSizeInBytes); -#if NET6_0_OR_GREATER - using ComPtr allocation = GraphicsDevice.Allocator->CreateResource( - GraphicsDevice.Pool, + using ComPtr allocation = default; + using ComPtr d3D12Resource = default; + + GraphicsDevice.CreateOrAllocateResource( ResourceType.ReadBack, AllocationMode.Default, - totalSizeInBytes); - - using ComPtr d3D12Resource = new(allocation.Get()->GetResource()); -#else - using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( - ResourceType.ReadBack, totalSizeInBytes, - GraphicsDevice.IsCacheCoherentUMA); -#endif + out *&allocation, + out *&d3D12Resource); using (CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType)) { @@ -420,20 +402,15 @@ public abstract unsafe partial class Texture2D : IReferenceTrackedObject, IGr out ulong rowSizeInBytes, out ulong totalSizeInBytes); -#if NET6_0_OR_GREATER - using ComPtr allocation = GraphicsDevice.Allocator->CreateResource( - GraphicsDevice.Pool, + using ComPtr allocation = default; + using ComPtr d3D12Resource = default; + + GraphicsDevice.CreateOrAllocateResource( ResourceType.Upload, AllocationMode.Default, - totalSizeInBytes); - - using ComPtr d3D12Resource = new(allocation.Get()->GetResource()); -#else - using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( - ResourceType.Upload, totalSizeInBytes, - GraphicsDevice.IsCacheCoherentUMA); -#endif + out *&allocation, + out *&d3D12Resource); using (ID3D12ResourceMap resource = d3D12Resource.Get()->Map()) { @@ -546,13 +523,10 @@ public abstract unsafe partial class Texture2D : IReferenceTrackedObject, IGr protected virtual partial void DangerousOnDispose() { this.d3D12Resource.Dispose(); -#if NET6_0_OR_GREATER this.allocation.Dispose(); -#endif if (GraphicsDevice is GraphicsDevice device) { - device.UnregisterAllocatedResource(); device.ReturnShaderResourceViewDescriptorHandles(in this.d3D12ResourceDescriptorHandles); } } diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs index b3acb736..62e819ca 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/Texture3D{T}.cs @@ -9,6 +9,7 @@ using ComputeSharp.Graphics.Helpers; using ComputeSharp.Graphics.Resources.Helpers; using ComputeSharp.Graphics.Resources.Interop; using ComputeSharp.Interop; +using ComputeSharp.Interop.Allocation; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using static TerraFX.Interop.DirectX.D3D12_COMMAND_LIST_TYPE; @@ -33,12 +34,10 @@ public abstract unsafe partial class Texture3D : IReferenceTrackedObject, IGr /// private ReferenceTracker referenceTracker; -#if NET6_0_OR_GREATER /// - /// The instance used to retrieve . + /// The instance used to retrieve , if available. /// - private ComPtr allocation; -#endif + private ComPtr allocation; /// /// The instance currently mapped. @@ -94,29 +93,17 @@ public abstract unsafe partial class Texture3D : IReferenceTrackedObject, IGr GraphicsDevice = device; -#if NET6_0_OR_GREATER - this.allocation = device.Allocator->CreateResource( - device.Pool, + device.CreateOrAllocateResource( resourceType, allocationMode, DXGIFormatHelper.GetForType(), (uint)width, (uint)height, (ushort)depth, + out this.allocation, + out this.d3D12Resource, out this.d3D12ResourceState); - this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); -#else - this.d3D12Resource = device.D3D12Device->CreateCommittedResource( - resourceType, - DXGIFormatHelper.GetForType(), - (uint)width, - (uint)height, - (ushort)depth, - device.IsCacheCoherentUMA, - out this.d3D12ResourceState); -#endif - this.d3D12CommandListType = this.d3D12ResourceState == D3D12_RESOURCE_STATE_COMMON ? D3D12_COMMAND_LIST_TYPE_COPY : D3D12_COMMAND_LIST_TYPE_COMPUTE; @@ -130,7 +117,6 @@ public abstract unsafe partial class Texture3D : IReferenceTrackedObject, IGr out _, out _); - device.RegisterAllocatedResource(); device.RentShaderResourceViewDescriptorHandles(out this.d3D12ResourceDescriptorHandles); switch (resourceType) @@ -213,20 +199,15 @@ public abstract unsafe partial class Texture3D : IReferenceTrackedObject, IGr out ulong rowSizeInBytes, out ulong totalSizeInBytes); -#if NET6_0_OR_GREATER - using ComPtr allocation = GraphicsDevice.Allocator->CreateResource( - GraphicsDevice.Pool, + using ComPtr allocation = default; + using ComPtr d3D12Resource = default; + + GraphicsDevice.CreateOrAllocateResource( ResourceType.ReadBack, AllocationMode.Default, - totalSizeInBytes); - - using ComPtr d3D12Resource = new(allocation.Get()->GetResource()); -#else - using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( - ResourceType.ReadBack, totalSizeInBytes, - GraphicsDevice.IsCacheCoherentUMA); -#endif + out *&allocation, + out *&d3D12Resource); using (CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType)) { @@ -462,20 +443,15 @@ public abstract unsafe partial class Texture3D : IReferenceTrackedObject, IGr out ulong rowSizeInBytes, out ulong totalSizeInBytes); -#if NET6_0_OR_GREATER - using ComPtr allocation = GraphicsDevice.Allocator->CreateResource( - GraphicsDevice.Pool, + using ComPtr allocation = default; + using ComPtr d3D12Resource = default; + + GraphicsDevice.CreateOrAllocateResource( ResourceType.Upload, AllocationMode.Default, - totalSizeInBytes); - - using ComPtr d3D12Resource = new(allocation.Get()->GetResource()); -#else - using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource( - ResourceType.Upload, totalSizeInBytes, - GraphicsDevice.IsCacheCoherentUMA); -#endif + out *&allocation, + out *&d3D12Resource); using (ID3D12ResourceMap resource = d3D12Resource.Get()->Map()) { @@ -599,13 +575,10 @@ public abstract unsafe partial class Texture3D : IReferenceTrackedObject, IGr protected virtual partial void DangerousOnDispose() { this.d3D12Resource.Dispose(); -#if NET6_0_OR_GREATER this.allocation.Dispose(); -#endif if (GraphicsDevice is GraphicsDevice device) { - device.UnregisterAllocatedResource(); device.ReturnShaderResourceViewDescriptorHandles(in this.d3D12ResourceDescriptorHandles); } } diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs index e72a5462..8fcbe06f 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/TransferBuffer{T}.cs @@ -6,6 +6,7 @@ using ComputeSharp.Exceptions; using ComputeSharp.Graphics.Extensions; using ComputeSharp.Graphics.Helpers; using ComputeSharp.Interop; +using ComputeSharp.Interop.Allocation; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using static TerraFX.Interop.DirectX.D3D12_FEATURE; @@ -27,12 +28,10 @@ public abstract unsafe partial class TransferBuffer : IReferenceTrackedObject /// private ReferenceTracker referenceTracker; -#if NET6_0_OR_GREATER /// - /// The instance used to retrieve . + /// The instance used to retrieve , if available. /// - private ComPtr allocation; -#endif + private ComPtr allocation; /// /// The instance currently mapped. @@ -74,14 +73,12 @@ public abstract unsafe partial class TransferBuffer : IReferenceTrackedObject ulong sizeInBytes = (uint)length * (uint)sizeof(T); -#if NET6_0_OR_GREATER - this.allocation = device.Allocator->CreateResource(device.Pool, resourceType, allocationMode, sizeInBytes); - this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); -#else - this.d3D12Resource = device.D3D12Device->CreateCommittedResource(resourceType, sizeInBytes, device.IsCacheCoherentUMA); -#endif - - device.RegisterAllocatedResource(); + device.CreateOrAllocateResource( + resourceType, + allocationMode, + sizeInBytes, + out this.allocation, + out this.d3D12Resource); this.mappedData = (T*)this.d3D12Resource.Get()->Map().Pointer; @@ -134,14 +131,7 @@ public abstract unsafe partial class TransferBuffer : IReferenceTrackedObject void IReferenceTrackedObject.DangerousOnDispose() { this.d3D12Resource.Dispose(); -#if NET6_0_OR_GREATER this.allocation.Dispose(); -#endif - - if (GraphicsDevice is GraphicsDevice device) - { - device.UnregisterAllocatedResource(); - } } /// diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture1D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture1D{T}.cs index f33dc3e4..b1ba8b0b 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture1D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture1D{T}.cs @@ -5,6 +5,7 @@ using ComputeSharp.Exceptions; using ComputeSharp.Graphics.Extensions; using ComputeSharp.Graphics.Helpers; using ComputeSharp.Interop; +using ComputeSharp.Interop.Allocation; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using static TerraFX.Interop.DirectX.D3D12_FORMAT_SUPPORT1; @@ -26,12 +27,10 @@ public abstract unsafe partial class TransferTexture1D : IReferenceTrackedObj /// private ReferenceTracker referenceTracker; -#if NET6_0_OR_GREATER /// - /// The instance used to retrieve . + /// The instance used to retrieve , if available. /// - private ComPtr allocation; -#endif + private ComPtr allocation; /// /// The instance currently mapped. @@ -79,14 +78,12 @@ public abstract unsafe partial class TransferTexture1D : IReferenceTrackedObj out _, out ulong totalSizeInBytes); -#if NET6_0_OR_GREATER - this.allocation = device.Allocator->CreateResource(device.Pool, resourceType, allocationMode, totalSizeInBytes); - this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); -#else - this.d3D12Resource = device.D3D12Device->CreateCommittedResource(resourceType, totalSizeInBytes, device.IsCacheCoherentUMA); -#endif - - device.RegisterAllocatedResource(); + device.CreateOrAllocateResource( + resourceType, + allocationMode, + totalSizeInBytes, + out this.allocation, + out this.d3D12Resource); this.mappedData = (T*)this.d3D12Resource.Get()->Map().Pointer; @@ -139,14 +136,7 @@ public abstract unsafe partial class TransferTexture1D : IReferenceTrackedObj void IReferenceTrackedObject.DangerousOnDispose() { this.d3D12Resource.Dispose(); -#if NET6_0_OR_GREATER this.allocation.Dispose(); -#endif - - if (GraphicsDevice is GraphicsDevice device) - { - device.UnregisterAllocatedResource(); - } } /// diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs index 61da3915..164ac349 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture2D{T}.cs @@ -4,6 +4,7 @@ using ComputeSharp.Exceptions; using ComputeSharp.Graphics.Extensions; using ComputeSharp.Graphics.Helpers; using ComputeSharp.Interop; +using ComputeSharp.Interop.Allocation; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using static TerraFX.Interop.DirectX.D3D12_FORMAT_SUPPORT1; @@ -25,12 +26,10 @@ public abstract unsafe partial class TransferTexture2D : IReferenceTrackedObj /// private ReferenceTracker referenceTracker; -#if NET6_0_OR_GREATER /// - /// The instance used to retrieve . + /// The instance used to retrieve , if available. /// - private ComPtr allocation; -#endif + private ComPtr allocation; /// /// The instance currently mapped. @@ -81,14 +80,12 @@ public abstract unsafe partial class TransferTexture2D : IReferenceTrackedObj out _, out ulong totalSizeInBytes); -#if NET6_0_OR_GREATER - this.allocation = device.Allocator->CreateResource(device.Pool, resourceType, allocationMode, totalSizeInBytes); - this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); -#else - this.d3D12Resource = device.D3D12Device->CreateCommittedResource(resourceType, totalSizeInBytes, device.IsCacheCoherentUMA); -#endif - - device.RegisterAllocatedResource(); + device.CreateOrAllocateResource( + resourceType, + allocationMode, + totalSizeInBytes, + out this.allocation, + out this.d3D12Resource); this.mappedData = (T*)this.d3D12Resource.Get()->Map().Pointer; @@ -134,14 +131,7 @@ public abstract unsafe partial class TransferTexture2D : IReferenceTrackedObj void IReferenceTrackedObject.DangerousOnDispose() { this.d3D12Resource.Dispose(); -#if NET6_0_OR_GREATER this.allocation.Dispose(); -#endif - - if (GraphicsDevice is GraphicsDevice device) - { - device.UnregisterAllocatedResource(); - } } /// diff --git a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs index a2d79929..62db3795 100644 --- a/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs +++ b/src/ComputeSharp/Graphics/Resources/Abstract/TransferTexture3D{T}.cs @@ -4,6 +4,7 @@ using ComputeSharp.Exceptions; using ComputeSharp.Graphics.Extensions; using ComputeSharp.Graphics.Helpers; using ComputeSharp.Interop; +using ComputeSharp.Interop.Allocation; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using static TerraFX.Interop.DirectX.D3D12_FORMAT_SUPPORT1; @@ -25,12 +26,10 @@ public abstract unsafe partial class TransferTexture3D : IReferenceTrackedObj /// private ReferenceTracker referenceTracker; -#if NET6_0_OR_GREATER /// - /// The instance used to retrieve . + /// The instance used to retrieve , if available. /// - private ComPtr allocation; -#endif + private ComPtr allocation; /// /// The instance currently mapped. @@ -84,14 +83,12 @@ public abstract unsafe partial class TransferTexture3D : IReferenceTrackedObj out _, out ulong totalSizeInBytes); -#if NET6_0_OR_GREATER - this.allocation = device.Allocator->CreateResource(device.Pool, resourceType, allocationMode, totalSizeInBytes); - this.d3D12Resource = new ComPtr(this.allocation.Get()->GetResource()); -#else - this.d3D12Resource = device.D3D12Device->CreateCommittedResource(resourceType, totalSizeInBytes, device.IsCacheCoherentUMA); -#endif - - device.RegisterAllocatedResource(); + device.CreateOrAllocateResource( + resourceType, + allocationMode, + totalSizeInBytes, + out this.allocation, + out this.d3D12Resource); this.mappedData = (T*)this.d3D12Resource.Get()->Map().Pointer; @@ -142,14 +139,7 @@ public abstract unsafe partial class TransferTexture3D : IReferenceTrackedObj void IReferenceTrackedObject.DangerousOnDispose() { this.d3D12Resource.Dispose(); -#if NET6_0_OR_GREATER this.allocation.Dispose(); -#endif - - if (GraphicsDevice is GraphicsDevice device) - { - device.UnregisterAllocatedResource(); - } } /// diff --git a/src/Directory.Build.props b/src/Directory.Build.props index bedb99bb..12dce312 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -19,6 +19,9 @@ + + + diff --git a/tests/ComputeSharp.Tests.DeviceLost/ComputeSharp.Tests.DeviceLost.csproj b/tests/ComputeSharp.Tests.DeviceLost/ComputeSharp.Tests.DeviceLost.csproj index 89272596..54517b20 100644 --- a/tests/ComputeSharp.Tests.DeviceLost/ComputeSharp.Tests.DeviceLost.csproj +++ b/tests/ComputeSharp.Tests.DeviceLost/ComputeSharp.Tests.DeviceLost.csproj @@ -1,9 +1,15 @@ - net472;net6.0;net7.0 + net472;net6.0;net7.0 + net6.0;net7.0 AnyCPU;x64;ARM64 + + + $(DefineConstants);USE_D3D12MA + + @@ -16,6 +22,7 @@ + diff --git a/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs b/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs index dcfb7041..9efe9cc2 100644 --- a/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs +++ b/tests/ComputeSharp.Tests.DeviceLost/DeviceDisposalTests.cs @@ -1,4 +1,7 @@ using System; +#if USE_D3D12MA +using ComputeSharp.D3D12MemoryAllocator; +#endif using ComputeSharp.Interop; using ComputeSharp.Tests.Attributes; using ComputeSharp.Tests.DeviceLost.Helpers; @@ -15,6 +18,15 @@ using Win32 = Win32.Apis; [TestCategory("DeviceDisposal")] public partial class DeviceDisposalTests { + [AssemblyInitialize] + public static void ConfigureImageSharp(TestContext _) + { +#if USE_D3D12MA + // If requested by the test runner, configure D3D12MA + AllocationServices.ConfigureAllocatorFactory(new D3D12MemoryAllocatorFactory()); +#endif + } + [TestMethod] public void DeviceDisposal_GetDefault_ReferenceCounting() { diff --git a/tests/ComputeSharp.Tests/AllocationServicesTests.cs b/tests/ComputeSharp.Tests/AllocationServicesTests.cs new file mode 100644 index 00000000..e5f0f074 --- /dev/null +++ b/tests/ComputeSharp.Tests/AllocationServicesTests.cs @@ -0,0 +1,178 @@ +#if USE_D3D12MA + +using System; +using System.Reflection; +using System.Runtime.InteropServices; +using CommunityToolkit.HighPerformance.Helpers; +using ComputeSharp.D3D12MemoryAllocator; +using ComputeSharp.Interop; +using ComputeSharp.Tests.Attributes; +using ComputeSharp.Tests.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Win32; +using HRESULT = Win32.HResult; + +namespace ComputeSharp.Tests; + +[TestClass] +[TestCategory("AllocationServices")] +public unsafe class AllocationServicesTests +{ + [TestMethod] + public void ConfigureAllocationFactory_CorrectLogic() + { + D3D12MemoryAllocatorFactory allocatorFactory = new(); + Guid uuidOfID3D12MemoryAllocatorFactory = new("CC1E74A7-786D-40F4-8AE2-F8B7A255587E"); + + using ComPtr d3D12MemoryAllocatorFactory = default; + + CustomQueryInterfaceResult result = ((ICustomQueryInterface)allocatorFactory).GetInterface( + iid: ref uuidOfID3D12MemoryAllocatorFactory, + ppv: out *(IntPtr*)d3D12MemoryAllocatorFactory.GetAddressOf()); + + Assert.AreEqual(CustomQueryInterfaceResult.Handled, result); + Assert.IsTrue(d3D12MemoryAllocatorFactory.Get() is not null); + + // There's two references: one from the managed object, one from the local ComPtr + Assert.AreEqual(2u, d3D12MemoryAllocatorFactory.GetReferenceCount()); + + try + { + // Try to configure the allocator (this should fail) + AllocationServices.ConfigureAllocatorFactory(allocatorFactory); + } + catch (InvalidOperationException) + { + // This is expected + } + catch + { + Assert.Fail(); + } + + // No additional references should've been added + Assert.AreEqual(2u, d3D12MemoryAllocatorFactory.GetReferenceCount()); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void ConfigureAllocationFactory_ValidatesArgument() + { + AllocationServices.ConfigureAllocatorFactory(null!); + } + + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ConstantBuffer<>))] + [Resource(typeof(ReadOnlyBuffer<>))] + [Resource(typeof(ReadWriteBuffer<>))] + public void ValidateAllocatorFunctionalityWithBuffer(Device device, Type bufferType) + { + ValidateAllocationState(device.Get().AllocateBuffer(bufferType, 128)); + } + + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ReadOnlyTexture2D<>))] + [Resource(typeof(ReadWriteTexture2D<>))] + public void ValidateAllocatorFunctionalityWithTexture2D(Device device, Type bufferType) + { + ValidateAllocationState(device.Get().AllocateTexture2D(bufferType, 16, 16)); + } + + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ReadOnlyTexture3D<>))] + [Resource(typeof(ReadWriteTexture3D<>))] + public void ValidateAllocatorFunctionalityWithTexture3D(Device device, Type bufferType) + { + ValidateAllocationState(device.Get().AllocateTexture3D(bufferType, 16, 16, 4)); + } + + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(UploadBuffer<>))] + [Resource(typeof(ReadBackBuffer<>))] + public void ValidateAllocatorFunctionalityWithTransferBuffer(Device device, Type bufferType) + { + ValidateAllocationState(device.Get().AllocateTransferBuffer(bufferType, 128)); + } + + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(UploadTexture2D<>))] + [Resource(typeof(ReadBackTexture2D<>))] + public void ValidateAllocatorFunctionalityWithTransferTexture2D(Device device, Type bufferType) + { + ValidateAllocationState(device.Get().AllocateTransferTexture2D(bufferType, 16, 16)); + } + + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(UploadTexture3D<>))] + [Resource(typeof(ReadBackTexture3D<>))] + public void ValidateAllocatorFunctionalityWithTransferTexture3D(Device device, Type bufferType) + { + ValidateAllocationState(device.Get().AllocateTransferTexture3D(bufferType, 16, 16, 4)); + } + + private static void ValidateAllocationState(IGraphicsResource resource) + { + using ComPtr allocationPtr = default; + + Type? instanceType = resource.GetType(); + FieldInfo? allocationFieldInfo = null; + FieldInfo? d3D12ResourceFieldInfo = null; + + // Get the allocation field (might be in a base type) + do + { + allocationFieldInfo = instanceType?.GetField("allocation", BindingFlags.Instance | BindingFlags.NonPublic); + d3D12ResourceFieldInfo = instanceType?.GetField("d3D12Resource", BindingFlags.Instance | BindingFlags.NonPublic); + + instanceType = instanceType?.BaseType; + } + while (allocationFieldInfo is null && instanceType is not null); + + Assert.IsNotNull(allocationFieldInfo); + Assert.IsNotNull(d3D12ResourceFieldInfo); + + // Get the allocation and D3D12 resource pointers (we use reflection as they're private fields) + object allocation = allocationFieldInfo.GetValue(resource)!; + object d3D12Resource = d3D12ResourceFieldInfo.GetValue(resource)!; + + *&allocationPtr = new ComPtr((IUnknown*)ObjectMarshal.DangerousGetObjectDataReferenceAt(allocation, default)); + + using ComPtr d3D12ResourcePtr = new((IUnknown*)ObjectMarshal.DangerousGetObjectDataReferenceAt(d3D12Resource, default)); + + Assert.AreNotEqual(0, (nint)allocationPtr.Get()); + Assert.AreNotEqual(0, (nint)d3D12ResourcePtr.Get()); + + using ComPtr wrappedD3D12ResourcePtr = default; + + // Invoke ID3D12Allocation::GetD3D12Resource (manually, as the type definition is internal) + HRESULT hresult = ((delegate* unmanaged[Stdcall])(*(void***)allocationPtr.Get())[3])( + allocationPtr.Get(), + wrappedD3D12ResourcePtr.GetAddressOf()); + + Assert.IsTrue(hresult.Success); + + using ComPtr d3D12ResourceUnknown = default; + using ComPtr wrappedD3D12ResourceUnknown = default; + + // Compare the identity of the D3D12 resource from the managed resource, and the one from the allocation + Assert.IsTrue(d3D12ResourcePtr.CopyTo(d3D12ResourceUnknown.GetAddressOf()).Success); + Assert.IsTrue(wrappedD3D12ResourcePtr.CopyTo(wrappedD3D12ResourceUnknown.GetAddressOf()).Success); + Assert.AreEqual((nint)d3D12ResourceUnknown.Get(), (nint)wrappedD3D12ResourceUnknown.Get()); + + // The allocation is kept alive by the resource at this point + Assert.IsTrue(allocationPtr.GetReferenceCount() > 1); + + ((IDisposable)resource).Dispose(); + + // The local reference is the only thing keeping the allocation alive at this point + Assert.AreEqual(1u, allocationPtr.GetReferenceCount()); + } +} + +#endif \ No newline at end of file diff --git a/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj b/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj index d4b67d61..4604dc32 100644 --- a/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj +++ b/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj @@ -1,9 +1,15 @@ - net472;net6.0;net7.0 + net472;net6.0;net7.0 + net6.0;net7.0 AnyCPU;x64;ARM64 + + + $(DefineConstants);USE_D3D12MA + + @@ -17,6 +23,7 @@ + diff --git a/tests/ComputeSharp.Tests/ImagingTests.cs b/tests/ComputeSharp.Tests/ImagingTests.cs index 7008bbcb..72a62e51 100644 --- a/tests/ComputeSharp.Tests/ImagingTests.cs +++ b/tests/ComputeSharp.Tests/ImagingTests.cs @@ -3,6 +3,10 @@ using System.Buffers; using System.IO; using System.Reflection; using CommunityToolkit.HighPerformance.Buffers; +#if USE_D3D12MA +using ComputeSharp.D3D12MemoryAllocator; +using ComputeSharp.Interop; +#endif using ComputeSharp.Resources; using ComputeSharp.Tests.Attributes; using ComputeSharp.Tests.Extensions; @@ -23,6 +27,11 @@ public class ImagingTests public static void ConfigureImageSharp(TestContext _) { Configuration.Default.PreferContiguousImageBuffers = true; + +#if USE_D3D12MA + // If requested by the test runner, configure D3D12MA + AllocationServices.ConfigureAllocatorFactory(new D3D12MemoryAllocatorFactory()); +#endif } [CombinatorialTestMethod]