共有GPU処理の非待機送信と同期を厳密化

このコミットが含まれているのは:
routersys committed 2026-07-15 20:33:52 +09:00
1 親 012e9fa73e
コミット 132fc66b82
14ファイル変更
+566 -54

検索条件に一致するファイルはありません

+8 -1
ファイルの表示
@@ -156,10 +156,17 @@ internal unsafe struct CommandList : IDisposable
return this.device.ExecuteCommandListAsync(ref this);
}
public void ExecuteWithoutWaiting()
{
this.d3D12GraphicsCommandList.Get()->Close().Assert();
this.device.ExecuteCommandListWithoutWaiting(ref this);
}
/// <inheritdoc/>
public void Dispose()
{
this.d3D12CommandAllocator.Dispose();
this.d3D12GraphicsCommandList.Dispose();
}
}
}
+70 -3
ファイルの表示
@@ -11,12 +11,17 @@ namespace ComputeSharp.Graphics.Commands.Interop;
/// A type that acts as a pool to get new <see cref="ID3D12CommandList"/> instances wheen needed.
/// </summary>
/// <param name="d3D12CommandListType">The command list type to use.</param>
internal readonly unsafe struct ID3D12CommandListPool(D3D12_COMMAND_LIST_TYPE d3D12CommandListType) : IDisposable
/// <param name="d3D12Fence">The fence used to track deferred command list completion.</param>
internal readonly unsafe struct ID3D12CommandListPool(D3D12_COMMAND_LIST_TYPE d3D12CommandListType, ID3D12Fence* d3D12Fence) : IDisposable
{
private const int MaximumPendingCommandListCount = 16;
/// <summary>
/// The queue of <see cref="D3D12CommandListBundle"/> items with the available command lists.
/// </summary>
private readonly Queue<D3D12CommandListBundle> d3D12CommandListBundleQueue = [];
private readonly Queue<D3D12CommandListBundle> d3D12CommandListBundleQueue = new(MaximumPendingCommandListCount * 2);
private readonly Queue<PendingD3D12CommandListBundle> pendingD3D12CommandListBundleQueue = new(MaximumPendingCommandListCount);
/// <summary>
/// Rents a <see cref="ID3D12GraphicsCommandList"/> and <see cref="ID3D12CommandAllocator"/> pair.
@@ -29,6 +34,8 @@ internal readonly unsafe struct ID3D12CommandListPool(D3D12_COMMAND_LIST_TYPE d3
{
lock (this.d3D12CommandListBundleQueue)
{
ReclaimCompletedCommandLists();
if (this.d3D12CommandListBundleQueue.TryDequeue(out D3D12CommandListBundle d3D12CommandListBundle))
{
d3D12CommandList = d3D12CommandListBundle.D3D12CommandList;
@@ -68,18 +75,71 @@ internal readonly unsafe struct ID3D12CommandListPool(D3D12_COMMAND_LIST_TYPE d3
}
}
public void ReturnWhenCompleted(ID3D12GraphicsCommandList* d3D12CommandList, ID3D12CommandAllocator* d3D12CommandAllocator, ulong fenceValue)
{
lock (this.d3D12CommandListBundleQueue)
{
ReclaimCompletedCommandLists();
if (this.pendingD3D12CommandListBundleQueue.Count == MaximumPendingCommandListCount)
{
PendingD3D12CommandListBundle pendingD3D12CommandListBundle = this.pendingD3D12CommandListBundleQueue.Dequeue();
if (pendingD3D12CommandListBundle.FenceValue > d3D12Fence->GetCompletedValue())
{
d3D12Fence->SetEventOnCompletion(pendingD3D12CommandListBundle.FenceValue, default).Assert();
}
this.d3D12CommandListBundleQueue.Enqueue(pendingD3D12CommandListBundle.D3D12CommandListBundle);
}
this.pendingD3D12CommandListBundleQueue.Enqueue(new PendingD3D12CommandListBundle(d3D12CommandList, d3D12CommandAllocator, fenceValue));
}
}
/// <inheritdoc/>
public void Dispose()
{
lock (this.d3D12CommandListBundleQueue)
{
ulong pendingFenceValue = 0;
foreach (PendingD3D12CommandListBundle current in this.pendingD3D12CommandListBundleQueue)
{
pendingFenceValue = Math.Max(pendingFenceValue, current.FenceValue);
}
if (pendingFenceValue > d3D12Fence->GetCompletedValue())
{
d3D12Fence->SetEventOnCompletion(pendingFenceValue, default).Assert();
}
foreach (D3D12CommandListBundle d3D12CommandListBundle in this.d3D12CommandListBundleQueue)
{
_ = d3D12CommandListBundle.D3D12CommandList->Release();
_ = d3D12CommandListBundle.D3D12CommandAllocator->Release();
}
foreach (PendingD3D12CommandListBundle current in this.pendingD3D12CommandListBundleQueue)
{
_ = current.D3D12CommandListBundle.D3D12CommandList->Release();
_ = current.D3D12CommandListBundle.D3D12CommandAllocator->Release();
}
this.d3D12CommandListBundleQueue.Clear();
this.pendingD3D12CommandListBundleQueue.Clear();
}
}
private void ReclaimCompletedCommandLists()
{
ulong completedValue = d3D12Fence->GetCompletedValue();
while (this.pendingD3D12CommandListBundleQueue.TryPeek(out PendingD3D12CommandListBundle pendingD3D12CommandListBundle) &&
pendingD3D12CommandListBundle.FenceValue <= completedValue)
{
_ = this.pendingD3D12CommandListBundleQueue.Dequeue();
this.d3D12CommandListBundleQueue.Enqueue(pendingD3D12CommandListBundle.D3D12CommandListBundle);
}
}
@@ -121,4 +181,11 @@ internal readonly unsafe struct ID3D12CommandListPool(D3D12_COMMAND_LIST_TYPE d3
/// </summary>
public readonly ID3D12CommandAllocator* D3D12CommandAllocator = d3D12CommandAllocator;
}
}
private readonly struct PendingD3D12CommandListBundle(ID3D12GraphicsCommandList* d3D12CommandList, ID3D12CommandAllocator* d3D12CommandAllocator, ulong fenceValue)
{
public readonly D3D12CommandListBundle D3D12CommandListBundle = new(d3D12CommandList, d3D12CommandAllocator);
public readonly ulong FenceValue = fenceValue;
}
}
+8 -1
ファイルの表示
@@ -278,6 +278,7 @@ internal static unsafe class ID3D12DeviceExtensions
/// <param name="dxgiFormat">使用する <see cref="DXGI_FORMAT"/> 値。</param>
/// <param name="width">テクスチャの幅。</param>
/// <param name="height">テクスチャの高さ。</param>
/// <param name="isRenderTarget">レンダーターゲットとして使用可能にするかどうか。</param>
/// <param name="d3D12ResourceStates">生成されたリソースの初期 <see cref="D3D12_RESOURCE_STATES"/> 値。</param>
/// <returns>共有可能な <see cref="ID3D12Resource"/> への参照。</returns>
public static ComPtr<ID3D12Resource> CreateSharedCommittedResource(
@@ -286,6 +287,7 @@ internal static unsafe class ID3D12DeviceExtensions
DXGI_FORMAT dxgiFormat,
uint width,
uint height,
bool isRenderTarget,
out D3D12_RESOURCE_STATES d3D12ResourceStates)
{
D3D12_RESOURCE_FLAGS d3D12ResourceFlags = resourceType switch
@@ -295,6 +297,11 @@ internal static unsafe class ID3D12DeviceExtensions
_ => default(ArgumentException).Throw<D3D12_RESOURCE_FLAGS>(nameof(resourceType))
};
if (isRenderTarget)
{
d3D12ResourceFlags |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
}
d3D12ResourceStates = D3D12_RESOURCE_STATE_COMMON;
using ComPtr<ID3D12Resource> d3D12Resource = default;
@@ -828,4 +835,4 @@ internal static unsafe class ID3D12DeviceExtensions
return d3D12ShaderModel.HighestShaderModel == d3DShaderModel;
}
}
}
+53 -23
ファイルの表示
@@ -26,6 +26,7 @@ unsafe partial class GraphicsDevice
ref readonly ID3D12CommandListPool commandListPool = ref Unsafe.NullRef<ID3D12CommandListPool>();
ID3D12CommandQueue* d3D12CommandQueue;
ID3D12Fence* d3D12Fence;
object d3D12CommandQueueLock;
ref ulong d3D12FenceValue = ref Unsafe.NullRef<ulong>();
// Get the target command queue, fence and pool for the list type
@@ -35,28 +36,25 @@ unsafe partial class GraphicsDevice
commandListPool = ref this.computeCommandListPool;
d3D12CommandQueue = this.d3D12ComputeCommandQueue.Get();
d3D12Fence = this.d3D12ComputeFence.Get();
d3D12CommandQueueLock = this.d3D12ComputeCommandQueueLock;
d3D12FenceValue = ref this.nextD3D12ComputeFenceValue;
break;
case D3D12_COMMAND_LIST_TYPE_COPY:
commandListPool = ref this.copyCommandListPool;
d3D12CommandQueue = this.d3D12CopyCommandQueue.Get();
d3D12Fence = this.d3D12CopyFence.Get();
d3D12CommandQueueLock = this.d3D12CopyCommandQueueLock;
d3D12FenceValue = ref this.nextD3D12CopyFenceValue;
break;
default: default(ArgumentException).Throw(nameof(commandList)); return;
}
// Execute the command list
fixed (ID3D12CommandList** d3D12CommandList = &commandList.GetD3D12CommandListPinnableAddressOf())
{
d3D12CommandQueue->ExecuteCommandLists(1, d3D12CommandList);
}
ulong updatedFenceValue = Interlocked.Increment(ref d3D12FenceValue);
// Signal to the target fence with the updated value. Note that incrementing the
// target fence value to signal must be done after executing the command list.
d3D12CommandQueue->Signal(d3D12Fence, updatedFenceValue).Assert();
ulong updatedFenceValue = ExecuteCommandListCore(
ref commandList,
d3D12CommandQueue,
d3D12Fence,
ref d3D12FenceValue,
d3D12CommandQueueLock);
// If the fence value hasn't been reached, wait until the operation completes
if (updatedFenceValue > d3D12Fence->GetCompletedValue())
@@ -76,17 +74,12 @@ unsafe partial class GraphicsDevice
/// <remarks>This method is only supported for compute operations.</remarks>
internal ValueTask ExecuteCommandListAsync(ref CommandList commandList)
{
// Execute the command list
fixed (ID3D12CommandList** d3D12CommandList = &commandList.GetD3D12CommandListPinnableAddressOf())
{
this.d3D12ComputeCommandQueue.Get()->ExecuteCommandLists(1, d3D12CommandList);
}
ulong updatedFenceValue = Interlocked.Increment(ref this.nextD3D12ComputeFenceValue);
// Signal to the target fence with the updated value. Note that incrementing the
// target fence value to signal must be done after executing the command list.
this.d3D12ComputeCommandQueue.Get()->Signal(this.d3D12ComputeFence.Get(), updatedFenceValue).Assert();
ulong updatedFenceValue = ExecuteCommandListCore(
ref commandList,
this.d3D12ComputeCommandQueue.Get(),
this.d3D12ComputeFence.Get(),
ref this.nextD3D12ComputeFenceValue,
this.d3D12ComputeCommandQueueLock);
// If the fence value has been reached, complete synchronously
if (updatedFenceValue <= this.d3D12ComputeFence.Get()->GetCompletedValue())
@@ -105,6 +98,43 @@ unsafe partial class GraphicsDevice
commandList.DetachD3D12CommandAllocator()).AsValueTask();
}
internal void ExecuteCommandListWithoutWaiting(ref CommandList commandList)
{
ulong updatedFenceValue = ExecuteCommandListCore(
ref commandList,
this.d3D12ComputeCommandQueue.Get(),
this.d3D12ComputeFence.Get(),
ref this.nextD3D12ComputeFenceValue,
this.d3D12ComputeCommandQueueLock);
this.computeCommandListPool.ReturnWhenCompleted(
commandList.DetachD3D12CommandList(),
commandList.DetachD3D12CommandAllocator(),
updatedFenceValue);
}
private static ulong ExecuteCommandListCore(
ref CommandList commandList,
ID3D12CommandQueue* d3D12CommandQueue,
ID3D12Fence* d3D12Fence,
ref ulong d3D12FenceValue,
object d3D12CommandQueueLock)
{
lock (d3D12CommandQueueLock)
{
fixed (ID3D12CommandList** d3D12CommandList = &commandList.GetD3D12CommandListPinnableAddressOf())
{
d3D12CommandQueue->ExecuteCommandLists(1, d3D12CommandList);
}
ulong updatedFenceValue = ++d3D12FenceValue;
d3D12CommandQueue->Signal(d3D12Fence, updatedFenceValue).Assert();
return updatedFenceValue;
}
}
/// <summary>
/// A context to support <see cref="WaitForSingleObjectCallbackForWaitForFenceAsync"/>.
/// </summary>
@@ -306,4 +336,4 @@ unsafe partial class GraphicsDevice
this.manualResetValueTaskSource.OnCompleted(continuation, state, token, flags);
}
}
}
}
+11 -3
ファイルの表示
@@ -15,6 +15,7 @@ unsafe partial class GraphicsDevice
/// <param name="dxgiFormat">使用する <see cref="DXGI_FORMAT"/> 値。</param>
/// <param name="width">テクスチャの幅。</param>
/// <param name="height">テクスチャの高さ。</param>
/// <param name="isRenderTarget">レンダーターゲットとして使用可能にするかどうか。</param>
/// <param name="d3D12Resource">生成された <see cref="ID3D12Resource"/> オブジェクト。</param>
/// <param name="d3D12ResourceStates">生成されたリソースの初期 <see cref="D3D12_RESOURCE_STATES"/> 値。</param>
internal void CreateSharedResource(
@@ -22,10 +23,11 @@ unsafe partial class GraphicsDevice
DXGI_FORMAT dxgiFormat,
uint width,
uint height,
bool isRenderTarget,
out ComPtr<ID3D12Resource> d3D12Resource,
out D3D12_RESOURCE_STATES d3D12ResourceStates)
{
d3D12Resource = this.d3D12Device.Get()->CreateSharedCommittedResource(resourceType, dxgiFormat, width, height, out d3D12ResourceStates);
d3D12Resource = this.d3D12Device.Get()->CreateSharedCommittedResource(resourceType, dxgiFormat, width, height, isRenderTarget, out d3D12ResourceStates);
}
/// <summary>
@@ -74,7 +76,10 @@ unsafe partial class GraphicsDevice
/// <param name="value">シグナルする値。</param>
internal void SignalSharedFence(ID3D12Fence* d3D12Fence, ulong value)
{
this.d3D12ComputeCommandQueue.Get()->Signal(d3D12Fence, value).Assert();
lock (this.d3D12ComputeCommandQueueLock)
{
this.d3D12ComputeCommandQueue.Get()->Signal(d3D12Fence, value).Assert();
}
}
/// <summary>
@@ -84,6 +89,9 @@ unsafe partial class GraphicsDevice
/// <param name="value">待機する目標値。</param>
internal void WaitForSharedFence(ID3D12Fence* d3D12Fence, ulong value)
{
this.d3D12ComputeCommandQueue.Get()->Wait(d3D12Fence, value).Assert();
lock (this.d3D12ComputeCommandQueueLock)
{
this.d3D12ComputeCommandQueue.Get()->Wait(d3D12Fence, value).Assert();
}
}
}
+9 -5
ファイルの表示
@@ -43,6 +43,10 @@ public sealed unsafe partial class GraphicsDevice : IReferenceTrackedObject
/// </summary>
private ComPtr<ID3D12CommandQueue> d3D12CopyCommandQueue;
private readonly object d3D12ComputeCommandQueueLock = new();
private readonly object d3D12CopyCommandQueueLock = new();
/// <summary>
/// The <see cref="ID3D12Fence"/> instance used for compute operations.
/// </summary>
@@ -150,8 +154,8 @@ public sealed unsafe partial class GraphicsDevice : IReferenceTrackedObject
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.computeCommandListPool = new ID3D12CommandListPool(D3D12_COMMAND_LIST_TYPE_COMPUTE, this.d3D12ComputeFence.Get());
this.copyCommandListPool = new ID3D12CommandListPool(D3D12_COMMAND_LIST_TYPE_COPY, this.d3D12CopyFence.Get());
this.allocator = new ComPtr<ID3D12MemoryAllocator>(allocator);
Luid = Luid.FromLUID(dxgiDescription1->AdapterLuid);
@@ -423,13 +427,13 @@ public sealed unsafe partial class GraphicsDevice : IReferenceTrackedObject
{
DeviceHelper.NotifyDisposedDevice(this);
this.computeCommandListPool.Dispose();
this.copyCommandListPool.Dispose();
this.d3D12Device.Dispose();
this.d3D12ComputeCommandQueue.Dispose();
this.d3D12CopyCommandQueue.Dispose();
this.d3D12ComputeFence.Dispose();
this.d3D12CopyFence.Dispose();
this.computeCommandListPool.Dispose();
this.copyCommandListPool.Dispose();
this.shaderResourceViewDescriptorAllocator.Dispose();
this.allocator.Dispose();
@@ -451,4 +455,4 @@ public sealed unsafe partial class GraphicsDevice : IReferenceTrackedObject
{
return $"[{Luid}] {Name}";
}
}
}
+52 -1
ファイルの表示
@@ -19,7 +19,8 @@ public static unsafe partial class InteropServices
/// <exception cref="ArgumentNullException"><paramref name="device"/> が <see langword="null"/> の場合にスローされます。</exception>
/// <remarks>
/// 返されるテクスチャは <see cref="CreateSharedHandle{T}(Texture2D{T})"/> で共有 NT ハンドルをエクスポートでき、
/// D3D11 など他 API から <c>OpenSharedResource1</c> で開けます。クロス API の同期は共有フェンスで行ってください。
/// 対応する外部 API から開けます。D3D11およびDirect2Dの共有ターゲットには正規化オーバーロードを使用してください。
/// クロス API の同期は共有フェンスで行ってください。
/// </remarks>
public static ReadWriteTexture2D<T> AllocateSharedReadWriteTexture2D<T>(GraphicsDevice device, int width, int height)
where T : unmanaged
@@ -29,6 +30,30 @@ public static unsafe partial class InteropServices
return new ReadWriteTexture2D<T>(device, width, height);
}
/// <summary>
/// クロス API 共有が可能な正規化 <see cref="ReadWriteTexture2D{T, TPixel}"/> を確保します。
/// </summary>
/// <typeparam name="T">CPU側で使用するピクセルの型。</typeparam>
/// <typeparam name="TPixel">GPU側で使用する正規化ピクセルの型。</typeparam>
/// <param name="device">テクスチャの確保に使用する <see cref="GraphicsDevice"/>。</param>
/// <param name="width">テクスチャの幅。</param>
/// <param name="height">テクスチャの高さ。</param>
/// <returns>共有可能な正規化 <see cref="ReadWriteTexture2D{T, TPixel}"/> インスタンス。</returns>
/// <exception cref="ArgumentNullException"><paramref name="device"/> が <see langword="null"/> の場合にスローされます。</exception>
/// <remarks>
/// 返されるテクスチャはUAV、同時アクセス、レンダーターゲットに対応します。D3D11から共有リソースとして開け、
/// 互換性のある形式ではDirect2Dの共有ターゲットとして開けます。
/// クロス API の同期は共有フェンスで行ってください。
/// </remarks>
public static ReadWriteTexture2D<T, TPixel> AllocateSharedReadWriteTexture2D<T, TPixel>(GraphicsDevice device, int width, int height)
where T : unmanaged, IPixel<T, TPixel>
where TPixel : unmanaged
{
default(ArgumentNullException).ThrowIfNull(device);
return new ReadWriteTexture2D<T, TPixel>(device, width, height);
}
/// <summary>
/// クロス API 共有が可能な <see cref="ReadOnlyTexture2D{T}"/> を確保します。
/// </summary>
@@ -70,6 +95,32 @@ public static unsafe partial class InteropServices
return new ReadWriteTexture2D<T>(device, d3D12Resource.Get());
}
/// <summary>
/// 外部 API が所有する共有 NT ハンドルを正規化 <see cref="ReadWriteTexture2D{T, TPixel}"/> として開きます。
/// </summary>
/// <typeparam name="T">CPU側で使用するピクセルの型。</typeparam>
/// <typeparam name="TPixel">GPU側で使用する正規化ピクセルの型。</typeparam>
/// <param name="device">リソースを開くために使用する <see cref="GraphicsDevice"/>。</param>
/// <param name="handle">開く対象の共有 NT ハンドル。</param>
/// <returns>共有リソースをラップする正規化 <see cref="ReadWriteTexture2D{T, TPixel}"/> インスタンス。</returns>
/// <exception cref="ArgumentNullException"><paramref name="device"/> が <see langword="null"/> の場合にスローされます。</exception>
/// <exception cref="ArgumentException">共有リソースが2Dテクスチャでない、またはフォーマットが <typeparamref name="T"/> と一致しない場合にスローされます。</exception>
/// <remarks>
/// 書き込み用に使用する場合、元のリソースはUAV対応かつ同時アクセス可能として作成されている必要があります。
/// クロス API の同期は共有フェンスで行ってください。
/// </remarks>
public static ReadWriteTexture2D<T, TPixel> OpenSharedReadWriteTexture2D<T, TPixel>(GraphicsDevice device, nint handle)
where T : unmanaged, IPixel<T, TPixel>
where TPixel : unmanaged
{
default(ArgumentNullException).ThrowIfNull(device);
using ReferenceTracker.Lease _0 = device.GetReferenceTracker().GetLease();
using ComPtr<ID3D12Resource> d3D12Resource = device.OpenSharedResource(new HANDLE((void*)handle));
return new ReadWriteTexture2D<T, TPixel>(device, d3D12Resource.Get());
}
/// <summary>
/// 外部 API が所有する共有 NT ハンドルを <see cref="ReadOnlyTexture2D{T}"/> として開きます。
/// </summary>
+4 -2
ファイルの表示
@@ -136,7 +136,8 @@ public abstract unsafe partial class Texture2D<T> : IReferenceTrackedObject, IGr
/// <param name="height">テクスチャの高さ。</param>
/// <param name="resourceType">現在のテクスチャのリソース種別。</param>
/// <param name="d3D12FormatSupport">現在のテクスチャ型のフォーマット サポート。</param>
private protected Texture2D(GraphicsDevice device, int width, int height, ResourceType resourceType, D3D12_FORMAT_SUPPORT1 d3D12FormatSupport)
/// <param name="isRenderTarget">レンダーターゲットとして使用可能にするかどうか。</param>
private protected Texture2D(GraphicsDevice device, int width, int height, ResourceType resourceType, D3D12_FORMAT_SUPPORT1 d3D12FormatSupport, bool isRenderTarget)
{
using ReferenceTracker.Lease _0 = ReferenceTracker.Create(this, out this.referenceTracker);
@@ -159,6 +160,7 @@ public abstract unsafe partial class Texture2D<T> : IReferenceTrackedObject, IGr
DXGIFormatHelper.GetForType<T>(),
(uint)width,
(uint)height,
isRenderTarget,
out this.d3D12Resource,
out this.d3D12ResourceState);
@@ -762,4 +764,4 @@ public abstract unsafe partial class Texture2D<T> : IReferenceTrackedObject, IGr
{
return ValidateAndGetID3D12ResourceAndTransitionStates(device, resourceState, out d3D12Resource, out lease);
}
}
}
+2 -2
ファイルの表示
@@ -35,7 +35,7 @@ public sealed class ReadOnlyTexture2D<T> : Texture2D<T>
/// <param name="width">テクスチャの幅。</param>
/// <param name="height">テクスチャの高さ。</param>
internal ReadOnlyTexture2D(GraphicsDevice device, int width, int height)
: base(device, width, height, ResourceType.ReadOnly, D3D12_FORMAT_SUPPORT1_TEXTURE2D)
: base(device, width, height, ResourceType.ReadOnly, D3D12_FORMAT_SUPPORT1_TEXTURE2D, false)
{
}
@@ -69,4 +69,4 @@ public sealed class ReadOnlyTexture2D<T> : Texture2D<T>
{
return $"ComputeSharp.ReadOnlyTexture2D<{typeof(T)}>[{Width}, {Height}]";
}
}
}
+12 -1
ファイルの表示
@@ -2,6 +2,7 @@ using System.Diagnostics;
using ComputeSharp.Graphics.Resources.Enums;
using ComputeSharp.Resources;
using ComputeSharp.Resources.Debug;
using ComputeSharp.Win32;
using static ComputeSharp.Win32.D3D12_FORMAT_SUPPORT1;
namespace ComputeSharp;
@@ -29,6 +30,16 @@ public sealed partial class ReadWriteTexture2D<T, TPixel> : Texture2D<T>, IReadW
{
}
internal ReadWriteTexture2D(GraphicsDevice device, int width, int height)
: base(device, width, height, ResourceType.ReadWrite, D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW | D3D12_FORMAT_SUPPORT1_RENDER_TARGET, true)
{
}
internal unsafe ReadWriteTexture2D(GraphicsDevice device, ID3D12Resource* d3D12Resource)
: base(device, d3D12Resource, ResourceType.ReadWrite, D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW)
{
}
/// <inheritdoc/>
public ref TPixel this[int x, int y] => throw new InvalidExecutionContextException($"{typeof(ReadWriteTexture2D<T, TPixel>)}[{typeof(int)}, {typeof(int)}]");
@@ -40,4 +51,4 @@ public sealed partial class ReadWriteTexture2D<T, TPixel> : Texture2D<T>, IReadW
{
return $"ComputeSharp.ReadWriteTexture2D<{typeof(T)}, {typeof(TPixel)}>[{Width}, {Height}]";
}
}
}
+2 -2
ファイルの表示
@@ -35,7 +35,7 @@ public sealed partial class ReadWriteTexture2D<T> : Texture2D<T>
/// <param name="width">テクスチャの幅。</param>
/// <param name="height">テクスチャの高さ。</param>
internal ReadWriteTexture2D(GraphicsDevice device, int width, int height)
: base(device, width, height, ResourceType.ReadWrite, D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW)
: base(device, width, height, ResourceType.ReadWrite, D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW, false)
{
}
@@ -69,4 +69,4 @@ public sealed partial class ReadWriteTexture2D<T> : Texture2D<T>
{
return $"ComputeSharp.ReadWriteTexture2D<{typeof(T)}>[{Width}, {Height}]";
}
}
}
+50 -1
ファイルの表示
@@ -36,6 +36,8 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
/// </summary>
private CommandList commandList;
private bool isSubmitted;
/// <summary>
/// Creates a new <see cref="ComputeContext"/> instance with the specified parameters.
/// </summary>
@@ -44,6 +46,7 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
{
this.device = device;
this.commandList = default;
this.isSubmitted = false;
// Increment the reference count for the device. This has to be released when disposing the context.
// Not disposing the context is undefined behavior, so we can rely on that to release the reference.
@@ -245,6 +248,11 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
{
if (this.isSubmitted)
{
return;
}
default(InvalidOperationException).ThrowIf(this.device is null);
GraphicsDevice device = this.device;
@@ -272,6 +280,11 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ValueTask DisposeAsync()
{
if (this.isSubmitted)
{
return ValueTask.CompletedTask;
}
default(InvalidOperationException).ThrowIf(this.device is null);
GraphicsDevice device = this.device;
@@ -295,6 +308,42 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
}
}
/// <summary>
/// 現在のコンテキストに記録されたコマンドをGPUへ送信します。
/// </summary>
/// <remarks>
/// 通常はGPUでの完了を待たずに戻ります。内部の保留上限に達した場合は、最古の送信が完了するまで待機します。
/// コンテキストが参照するすべてのGPUリソースは、共有フェンスなどで送信した処理の完了を確認するまで保持する必要があります。
/// このメソッドを呼び出した後、スコープ終端の<see cref="Dispose()"/>および<see cref="DisposeAsync()"/>は何も行いません。
/// </remarks>
/// <exception cref="InvalidOperationException">コンテキストが既に破棄または送信されている場合にスローされます。</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Submit()
{
default(InvalidOperationException).ThrowIf(this.device is null);
GraphicsDevice device = this.device;
this.device = null;
this.isSubmitted = true;
if (!this.commandList.IsAllocated)
{
device.GetReferenceTracker().DangerousRelease();
return;
}
try
{
this.commandList.ExecuteWithoutWaiting();
}
finally
{
device.GetReferenceTracker().DangerousRelease();
}
}
/// <summary>
/// Gets the current <see cref="CommandList"/> instance.
/// </summary>
@@ -341,4 +390,4 @@ public struct ComputeContext : IDisposable, IAsyncDisposable
return ref commandList;
}
}
}
+23 -9
ファイルの表示
@@ -21,6 +21,8 @@ internal static unsafe class PipelineDataLoader<T>
/// </summary>
private static readonly ConditionalWeakTable<GraphicsDevice, PipelineData> CachedPipelines = [];
private static readonly object PipelineCreationLock = new();
/// <summary>
/// Gets the <see cref="PipelineData"/> instance for a given shader.
/// </summary>
@@ -28,11 +30,29 @@ internal static unsafe class PipelineDataLoader<T>
/// <returns>The <see cref="PipelineData"/> instance for a given shader.</returns>
public static PipelineData GetPipelineData(GraphicsDevice device)
{
return CachedPipelines.GetValue(device, CreatePipelineData);
if (CachedPipelines.TryGetValue(device, out PipelineData? pipelineData))
{
return pipelineData;
}
lock (PipelineCreationLock)
{
if (CachedPipelines.TryGetValue(device, out pipelineData))
{
return pipelineData;
}
pipelineData = CreatePipelineData(device);
CachedPipelines.Add(device, pipelineData);
device.RegisterPipelineData(pipelineData);
return pipelineData;
}
}
/// <summary>
/// Creates and caches a <see cref="PipelineData"/> instance for a given shader.
/// Creates a <see cref="PipelineData"/> instance for a given shader.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <returns>The resulting <see cref="PipelineData"/> instance to use to run the shader.</returns>
@@ -49,12 +69,6 @@ internal static unsafe class PipelineDataLoader<T>
pipelineData = new PipelineData(d3D12RootSignature.Get(), d3D12PipelineState.Get());
}
// Add the pipeline to the cache for this type
CachedPipelines.Add(device, pipelineData);
// Register the newly created pipeline data to enable early disposal
device.RegisterPipelineData(pipelineData);
return pipelineData;
}
@@ -123,4 +137,4 @@ internal static unsafe class PipelineDataLoader<T>
d3D12Device->CreateComputePipelineState(d3D12RootSignature, d3D12ShaderBytecode, d3D12PipelineState);
}
}
}
}
+262
ファイルの表示
@@ -1,5 +1,7 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using ComputeSharp.Interop;
using ComputeSharp.Tests.Attributes;
using ComputeSharp.Tests.Extensions;
@@ -72,6 +74,222 @@ public unsafe partial class InteropServicesTests
}
}
[CombinatorialTestMethod]
[AllDevices]
public void SharedNormalizedReadWriteTexture2D_RoundTripThroughSharedHandle(Device device)
{
using ReadWriteTexture2D<Bgra32, Float4> source = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device.Get(), 16, 16);
using ComPtr<ID3D12Resource> d3D12Resource = default;
InteropServices.GetID3D12Resource(source, Windows.__uuidof<ID3D12Resource>(), (void**)d3D12Resource.GetAddressOf());
D3D12_RESOURCE_FLAGS expectedFlags = D3D12_RESOURCE_FLAGS.D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET |
D3D12_RESOURCE_FLAGS.D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS |
D3D12_RESOURCE_FLAGS.D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS;
Assert.AreEqual(expectedFlags, d3D12Resource.Get()->GetDesc().Flags & expectedFlags);
device.Get().For(16, 16, new SharedNormalizedTextureFillShader(source));
nint handle = InteropServices.CreateSharedHandle(source);
Assert.AreNotEqual(0, handle);
try
{
using ReadWriteTexture2D<Bgra32, Float4> opened = InteropServices.OpenSharedReadWriteTexture2D<Bgra32, Float4>(device.Get(), handle);
Bgra32[] result = new Bgra32[16 * 16];
opened.CopyTo(result);
foreach (Bgra32 pixel in result)
{
Assert.AreEqual(0xFF808080u, pixel.PackedValue);
}
}
finally
{
_ = CloseHandle(handle);
}
}
[CombinatorialTestMethod]
[AllDevices]
public void SharedNormalizedReadWriteTexture2D_AllPixelFormats(Device device)
{
AssertSharedNormalizedTextureFlags<Bgra32, Float4>(device.Get());
AssertSharedNormalizedTextureFlags<R16, float>(device.Get());
AssertSharedNormalizedTextureFlags<R8, float>(device.Get());
AssertSharedNormalizedTextureFlags<Rg16, Float2>(device.Get());
AssertSharedNormalizedTextureFlags<Rg32, Float2>(device.Get());
AssertSharedNormalizedTextureFlags<Rgba32, Float4>(device.Get());
AssertSharedNormalizedTextureFlags<Rgba64, Float4>(device.Get());
}
[CombinatorialTestMethod]
[AllDevices]
public void ComputeContext_SubmitDoesNotWaitForCompletion(Device device)
{
using ReadWriteTexture2D<Bgra32, Float4> texture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device.Get(), 16, 16);
using ComPtr<ID3D12Fence> d3D12Fence = default;
nint handle = 0;
InteropServices.CreateSharedFence(device.Get(), Windows.__uuidof<ID3D12Fence>(), (void**)d3D12Fence.GetAddressOf(), &handle);
try
{
InteropServices.WaitForSharedFence(device.Get(), d3D12Fence.Get(), 1);
Task submitTask = Task.Run(() =>
{
using ComputeContext context = device.Get().CreateComputeContext();
context.For(16, 16, new SharedNormalizedTextureFillShader(texture));
context.Submit();
InteropServices.SignalSharedFence(device.Get(), d3D12Fence.Get(), 2);
});
bool completedWithoutFence;
try
{
completedWithoutFence = submitTask.Wait(TimeSpan.FromSeconds(5));
}
finally
{
Assert.IsTrue(d3D12Fence.Get()->Signal(1).SUCCEEDED);
submitTask.Wait();
}
Assert.IsTrue(completedWithoutFence);
while (d3D12Fence.Get()->GetCompletedValue() < 2)
{
_ = Thread.Yield();
}
Bgra32[] result = new Bgra32[16 * 16];
texture.CopyTo(result);
Assert.AreEqual(0xFF808080u, result[0].PackedValue);
}
finally
{
_ = CloseHandle(handle);
}
}
[CombinatorialTestMethod]
[AllDevices]
public void ComputeContext_SubmitDoesNotAllocateAfterWarmup(Device device)
{
using ReadWriteTexture2D<Bgra32, Float4> texture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device.Get(), 16, 16);
using ComPtr<ID3D12Fence> d3D12Fence = default;
nint handle = 0;
InteropServices.CreateSharedFence(device.Get(), Windows.__uuidof<ID3D12Fence>(), (void**)d3D12Fence.GetAddressOf(), &handle);
try
{
ulong fenceValue = 0;
for (int i = 0; i < 4; i++)
{
SubmitAndWait(device.Get(), texture, d3D12Fence.Get(), ref fenceValue);
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
long before = GC.GetAllocatedBytesForCurrentThread();
for (int i = 0; i < 32; i++)
{
SubmitAndWait(device.Get(), texture, d3D12Fence.Get(), ref fenceValue);
}
long allocated = GC.GetAllocatedBytesForCurrentThread() - before;
Assert.AreEqual(0, allocated);
}
finally
{
_ = CloseHandle(handle);
}
}
[CombinatorialTestMethod]
[AllDevices]
public void ComputeContext_SubmitAppliesBackpressureAtPendingLimit(Device device)
{
using ReadWriteTexture2D<Bgra32, Float4> texture = InteropServices.AllocateSharedReadWriteTexture2D<Bgra32, Float4>(device.Get(), 16, 16);
using ComPtr<ID3D12Fence> d3D12Fence = default;
nint handle = 0;
InteropServices.CreateSharedFence(device.Get(), Windows.__uuidof<ID3D12Fence>(), (void**)d3D12Fence.GetAddressOf(), &handle);
try
{
InteropServices.WaitForSharedFence(device.Get(), d3D12Fence.Get(), 1);
for (int i = 0; i < 16; i++)
{
using ComputeContext context = device.Get().CreateComputeContext();
context.For(16, 16, new SharedNormalizedTextureFillShader(texture));
context.Submit();
}
using ManualResetEventSlim started = new();
Task overflowTask = Task.Run(() =>
{
using ComputeContext context = device.Get().CreateComputeContext();
context.For(16, 16, new SharedNormalizedTextureFillShader(texture));
started.Set();
context.Submit();
InteropServices.SignalSharedFence(device.Get(), d3D12Fence.Get(), 2);
});
started.Wait();
bool completedBeforeRelease;
try
{
completedBeforeRelease = overflowTask.Wait(TimeSpan.FromMilliseconds(100));
}
finally
{
Assert.IsTrue(d3D12Fence.Get()->Signal(1).SUCCEEDED);
Assert.IsTrue(overflowTask.Wait(TimeSpan.FromSeconds(5)));
}
Assert.IsFalse(completedBeforeRelease);
while (d3D12Fence.Get()->GetCompletedValue() < 2)
{
_ = Thread.Yield();
}
Bgra32[] result = new Bgra32[16 * 16];
texture.CopyTo(result);
Assert.AreEqual(0xFF808080u, result[0].PackedValue);
}
finally
{
_ = CloseHandle(handle);
}
}
[CombinatorialTestMethod]
[AllDevices]
public void SharedReadOnlyTexture2D_AllocateAndExportHandle(Device device)
@@ -134,4 +352,48 @@ public unsafe partial class InteropServicesTests
this.texture[ThreadIds.XY] = ThreadIds.X + ThreadIds.Y;
}
}
[AutoConstructor]
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
[GeneratedComputeShaderDescriptor]
internal readonly partial struct SharedNormalizedTextureFillShader : IComputeShader
{
public readonly ReadWriteTexture2D<Bgra32, Float4> texture;
public void Execute()
{
this.texture[ThreadIds.XY] = new Float4(0.5f, 0.5f, 0.5f, 1f);
}
}
private static void SubmitAndWait(GraphicsDevice device, ReadWriteTexture2D<Bgra32, Float4> texture, ID3D12Fence* d3D12Fence, ref ulong fenceValue)
{
using ComputeContext context = device.CreateComputeContext();
context.For(16, 16, new SharedNormalizedTextureFillShader(texture));
context.Submit();
InteropServices.SignalSharedFence(device, d3D12Fence, ++fenceValue);
while (d3D12Fence->GetCompletedValue() < fenceValue)
{
_ = Thread.Yield();
}
}
private static void AssertSharedNormalizedTextureFlags<T, TPixel>(GraphicsDevice device)
where T : unmanaged, IPixel<T, TPixel>
where TPixel : unmanaged
{
using ReadWriteTexture2D<T, TPixel> texture = InteropServices.AllocateSharedReadWriteTexture2D<T, TPixel>(device, 1, 1);
using ComPtr<ID3D12Resource> d3D12Resource = default;
InteropServices.GetID3D12Resource(texture, Windows.__uuidof<ID3D12Resource>(), (void**)d3D12Resource.GetAddressOf());
D3D12_RESOURCE_FLAGS expectedFlags = D3D12_RESOURCE_FLAGS.D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET |
D3D12_RESOURCE_FLAGS.D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS |
D3D12_RESOURCE_FLAGS.D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS;
Assert.AreEqual(expectedFlags, d3D12Resource.Get()->GetDesc().Flags & expectedFlags);
}
}