From 4d7cfd800067bf04dff7752c76e4334a28dfaaff Mon Sep 17 00:00:00 2001 From: routersys Date: Wed, 23 Sep 2026 15:09:45 +0900 Subject: [PATCH] =?UTF-8?q?=E7=9B=B8=E4=BA=92=E9=81=8B=E7=94=A8=E3=82=92?= =?UTF-8?q?=E5=A4=96=E9=83=A8=E6=8F=90=E4=BE=9B=E8=80=85=E3=81=A8=E5=85=B1?= =?UTF-8?q?=E6=9C=89=E3=83=86=E3=82=AF=E3=82=B9=E3=83=81=E3=83=A3=E9=9B=86?= =?UTF-8?q?=E5=90=88=E3=81=B8=E7=A7=BB=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../LowPolyAbstractionEffectTests.cs | 87 +++-- .../LowPolyAbstractionEffectProcessor.cs | 185 +++++++--- .../LowPolyAbstractionGpuInterop.cs | 344 +++--------------- .../LowPolyAbstractionPipeline.cs | 40 +- .../LowPolyAbstractionPipelineHost.cs | 33 ++ 5 files changed, 314 insertions(+), 375 deletions(-) diff --git a/LowPolyAbstraction.Tests/LowPolyAbstractionEffectTests.cs b/LowPolyAbstraction.Tests/LowPolyAbstractionEffectTests.cs index e958a3f..b4ba095 100644 --- a/LowPolyAbstraction.Tests/LowPolyAbstractionEffectTests.cs +++ b/LowPolyAbstraction.Tests/LowPolyAbstractionEffectTests.cs @@ -524,21 +524,47 @@ public sealed class LowPolyAbstractionEffectTests { using var devices = new GraphicsDevices(); using var graphicsContext = devices.CreateContext(); - using var interop = LowPolyAbstractionGpuInterop.TryCreate(graphicsContext); - if (interop is null) + using var scheduler = ComputeExternalQueueScheduler.Create(); + using var provider = LowPolyAbstractionInteropProvider.TryCreate(graphicsContext, scheduler, out var interopDevice); + if (provider is null || interopDevice is null) { Assert.Skip("Direct3D 11 and Direct3D 12 sharing is unavailable."); return; } - using var pipeline = LowPolyAbstractionPipeline.TryCreate(interop.Device); + using var domain = interopDevice.RegisterExternalDomain(provider); + using var resourceSet = LowPolyAbstractionResourceSet.Create(interopDevice, domain); + using var pipeline = LowPolyAbstractionPipeline.TryCreate(interopDevice); Assert.NotNull(pipeline); const int width = 96; const int height = 96; - var pixels = CreateTwoToneSource(width, height, 24, 24, 48, 48); + using var inputBitmap = CreateInputBitmap(graphicsContext.DeviceContext, CreateTwoToneSource(width, height, 24, 24, 48, 48), width, height); + + Assert.True(resourceSet.TryEnsureSource(width, height, out _)); + var parameters = CreateParameters(); + LowPolyAbstractionPipeline.PixelRect visible = default; + for (var iteration = 0; iteration < 2; iteration++) + { + DrawSource(resourceSet, provider.RenderContext, inputBitmap); + pipeline!.Simulate( + resourceSet.GetSourceComputeBinding(), width, height, 0, 0, width, height, in parameters); + Assert.True(pipeline.TryGetVisibleBounds(width, height, in parameters, out visible)); + Assert.True(resourceSet.TryEnsureOutput(visible.Width, visible.Height, out _)); + pipeline.RenderVisible( + resourceSet.GetOutputComputeBinding(), width, height, visible, in parameters); + } + + using var outputLease = resourceSet.AcquireOutputExternalViewLease(); + Assert.Equal(visible.Width, outputLease.Width); + Assert.Equal(visible.Height, outputLease.Height); + Assert.True(CountLitOutput(graphicsContext.DeviceContext, outputLease, visible) > 0); + } + + private static ID2D1Bitmap1 CreateInputBitmap(ID2D1DeviceContext6 deviceContext, int[] pixels, int width, int height) + { var handle = GCHandle.Alloc(pixels, GCHandleType.Pinned); - using var inputBitmap = graphicsContext.DeviceContext.CreateBitmap( + var inputBitmap = deviceContext.CreateBitmap( new SizeI(width, height), new BitmapProperties1( new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied), @@ -553,40 +579,45 @@ public sealed class LowPolyAbstractionEffectTests { handle.Free(); } + return inputBitmap; + } - Assert.True(interop.EnsureResources(width, height)); - var bounds = new RawRectF(0f, 0f, width, height); - var parameters = CreateParameters(); - for (var iteration = 0; iteration < 2; iteration++) - { - interop.RenderInput(inputBitmap, bounds); - interop.BeginCompute(); - try - { - pipeline!.Process(interop.SourceTexture, interop.OutputTexture, width, height, in parameters); - } - finally - { - interop.EndCompute(); - } - } - interop.WaitForIdle(); + private static void DrawSource(LowPolyAbstractionResourceSet resourceSet, ID2D1DeviceContext6 renderContext, ID2D1Bitmap1 inputBitmap) + { + using var borrow = resourceSet.BeginSourceExternalOperation(); + var previousTarget = renderContext.Target; + using var sourceBitmap = new ID2D1Bitmap1(borrow.DangerousGetView().AddRefBitmap()); + renderContext.Target = sourceBitmap; + renderContext.BeginDraw(); + renderContext.Clear(null); + renderContext.DrawImage( + inputBitmap, + new System.Numerics.Vector2(0f, 0f), + null, + InterpolationMode.NearestNeighbor, + CompositeMode.SourceCopy); + renderContext.EndDraw(); + renderContext.Target = previousTarget; + } - using var staging = graphicsContext.DeviceContext.CreateBitmap( - new SizeI(width, height), + private static int CountLitOutput(ID2D1DeviceContext6 deviceContext, ExternalTextureLease outputLease, LowPolyAbstractionPipeline.PixelRect visible) + { + using var staging = deviceContext.CreateBitmap( + new SizeI(visible.Width, visible.Height), new BitmapProperties1( new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied), 96f, 96f, BitmapOptions.CpuRead | BitmapOptions.CannotDraw)); - staging.CopyFromBitmap(interop.OutputBitmap); + using var outputBitmap = new ID2D1Bitmap1(outputLease.DangerousGetView().AddRefBitmap()); + staging.CopyFromBitmap(Vortice.Mathematics.Int2.Zero, outputBitmap, new RectI(0, 0, visible.Width, visible.Height)); var mapped = staging.Map(MapOptions.Read); try { var lit = 0; - for (var y = 0; y < height; y++) + for (var y = 0; y < visible.Height; y++) { - for (var x = 0; x < width; x++) + for (var x = 0; x < visible.Width; x++) { var actual = Marshal.ReadInt32(mapped.Bits + (nint)(y * mapped.Pitch + x * sizeof(int))); var alpha = (actual >> 24) & 255; @@ -597,7 +628,7 @@ public sealed class LowPolyAbstractionEffectTests lit++; } } - Assert.True(lit > 0); + return lit; } finally { diff --git a/LowPolyAbstraction/LowPolyAbstractionEffectProcessor.cs b/LowPolyAbstraction/LowPolyAbstractionEffectProcessor.cs index 9a658ac..78dc6bb 100644 --- a/LowPolyAbstraction/LowPolyAbstractionEffectProcessor.cs +++ b/LowPolyAbstraction/LowPolyAbstractionEffectProcessor.cs @@ -1,4 +1,5 @@ using System.Numerics; +using ComputeWeave; using Vortice.Direct2D1; using Vortice.Direct2D1.Effects; using YukkuriMovieMaker.Commons; @@ -11,7 +12,11 @@ internal sealed class LowPolyAbstractionEffectProcessor : VideoEffectProcessorBa { private readonly IGraphicsDevicesAndContext _devices; private readonly LowPolyAbstractionEffect _item; - private LowPolyAbstractionGpuInterop? _interop; + private ComputeExternalQueueScheduler? _scheduler; + private LowPolyAbstractionInteropProvider? _interopProvider; + private ComputeInteropDomain? _interopDomain; + private LowPolyAbstractionResourceSet? _resourceSet; + private ExternalTextureLease? _outputLease; private LowPolyAbstractionPipeline? _pipeline; private LowPolyAbstractionCustomEffect? _effect; private Crop? _outputCrop; @@ -37,7 +42,7 @@ internal sealed class LowPolyAbstractionEffectProcessor : VideoEffectProcessorBa public override DrawDescription Update(EffectDescription effectDescription) { - if (IsPassThroughEffect || _effect is null || _outputCrop is null || _outputTransform is null || _outputTransformOutput is null || _interop is null || _pipeline is null || input is null) + if (IsPassThroughEffect || _effect is null || _outputCrop is null || _outputTransform is null || _outputTransformOutput is null || _resourceSet is null || _interopProvider is null || _pipeline is null || input is null) return effectDescription.DrawDescription; var frame = effectDescription.ItemPosition.Frame; @@ -93,8 +98,14 @@ internal sealed class LowPolyAbstractionEffectProcessor : VideoEffectProcessorBa var itemWidth = (int)widthValue; var itemHeight = (int)heightValue; - _interop.EnsureSource(itemWidth, itemHeight); - _interop.RenderInput(input, new Vortice.RawRectF(bounds.Left, bounds.Top, bounds.Left + itemWidth, bounds.Top + itemHeight)); + if (!EnsureSource(itemWidth, itemHeight)) + { + _effect.Amount = 0f; + _isFirst = true; + return effectDescription.DrawDescription; + } + + RenderInput(new Vortice.RawRectF(bounds.Left, bounds.Top, bounds.Left + itemWidth, bounds.Top + itemHeight)); var pipelineParameters = new LowPolyAbstractionPipeline.Parameters( parameters.Quality, @@ -107,24 +118,15 @@ internal sealed class LowPolyAbstractionEffectProcessor : VideoEffectProcessorBa Math.Clamp(parameters.Jitter, 0f, 1f), Math.Max(parameters.Seed, 0)); - bool structureChanged; - _interop.BeginCompute(); - try - { - structureChanged = _pipeline.Simulate( - _interop.SourceTexture, - canvasWidth, - canvasHeight, - margin, - margin, - itemWidth, - itemHeight, - in pipelineParameters); - } - finally - { - _interop.EndCompute(); - } + var structureChanged = _pipeline.Simulate( + _resourceSet.GetSourceComputeBinding(), + canvasWidth, + canvasHeight, + margin, + margin, + itemWidth, + itemHeight, + in pipelineParameters); if (!_pipeline.TryGetVisibleBounds(canvasWidth, canvasHeight, in pipelineParameters, out var rect)) { @@ -135,9 +137,16 @@ internal sealed class LowPolyAbstractionEffectProcessor : VideoEffectProcessorBa return effectDescription.DrawDescription; } - if (!_interop.OutputCovers(rect.Width, rect.Height)) + if (!OutputCovers(rect.Width, rect.Height)) _outputCrop.SetInput(0, null, true); - var outputChanged = _interop.EnsureOutput(rect.Width, rect.Height); + if (!EnsureOutput(rect.Width, rect.Height, out var outputChanged)) + { + _effect.Amount = 0f; + _parameters = parameters; + _isFirst = true; + _hasRenderState = false; + return effectDescription.DrawDescription; + } var renderState = new RenderState( pipelineParameters.Gradient, pipelineParameters.Wireframe, @@ -146,27 +155,22 @@ internal sealed class LowPolyAbstractionEffectProcessor : VideoEffectProcessorBa rect); if (structureChanged || outputChanged || !_hasOutput || !_hasRenderState || _renderState != renderState) { - _interop.BeginCompute(); - try - { - _pipeline.RenderVisible( - _interop.OutputTexture, - canvasWidth, - canvasHeight, - rect, - in pipelineParameters); - } - finally - { - _interop.EndCompute(); - } + _pipeline.RenderVisible( + _resourceSet.GetOutputComputeBinding(), + canvasWidth, + canvasHeight, + rect, + in pipelineParameters); _renderState = renderState; _hasRenderState = true; } + _outputLease ??= _resourceSet.AcquireOutputExternalViewLease(); + if (outputChanged || !_hasOutput) { - _outputCrop.SetInput(0, _interop.OutputBitmap, true); + using var outputBitmap = new ID2D1Bitmap1(_outputLease.DangerousGetView().AddRefBitmap()); + _outputCrop.SetInput(0, outputBitmap, true); _effect.SetInput(1, _outputTransformOutput, true); } var cropRect = new Vector4(0f, 0f, rect.Width, rect.Height); @@ -189,15 +193,92 @@ internal sealed class LowPolyAbstractionEffectProcessor : VideoEffectProcessorBa return effectDescription.DrawDescription; } + private bool EnsureSource(int width, int height) + { + return _resourceSet!.TryEnsureSource(width, height, out _); + } + + private bool OutputCovers(int width, int height) + => _outputLease is { IsDisposed: false } lease && + lease.Width >= width && + lease.Height >= height; + + private bool EnsureOutput(int width, int height, out bool changed) + { + changed = false; + if (OutputCovers(width, height)) + return true; + + _outputLease?.Dispose(); + _outputLease = null; + return _resourceSet!.TryEnsureOutput(width, height, out changed); + } + + private void RenderInput(Vortice.RawRectF bounds) + { + var renderContext = _interopProvider!.RenderContext; + using var borrow = _resourceSet!.BeginSourceExternalOperation(); + var previousTarget = renderContext.Target; + using var sourceBitmap = new ID2D1Bitmap1(borrow.DangerousGetView().AddRefBitmap()); + renderContext.Target = sourceBitmap; + renderContext.BeginDraw(); + renderContext.Clear(null); + renderContext.DrawImage( + input, + new Vector2(-bounds.Left, -bounds.Top), + null, + InterpolationMode.NearestNeighbor, + CompositeMode.SourceCopy); + renderContext.EndDraw(); + renderContext.Target = previousTarget; + } + + private void ReleaseInterop() + { + _outputLease?.Dispose(); + _outputLease = null; + _pipeline?.Dispose(); + _pipeline = null; + _resourceSet?.Dispose(); + _resourceSet?.WaitForDisposal(); + _resourceSet = null; + _interopDomain?.Dispose(); + _interopDomain?.WaitForDisposal(); + _interopDomain = null; + _interopProvider?.Dispose(); + _interopProvider = null; + _scheduler?.Dispose(); + _scheduler = null; + } + protected override ID2D1Image? CreateEffect(IGraphicsDevicesAndContext devices) { - var interop = LowPolyAbstractionGpuInterop.TryCreate(devices); - if (interop is null) - return null; - var pipeline = LowPolyAbstractionPipeline.TryCreate(interop.Device); - if (pipeline is null) + var scheduler = ComputeExternalQueueScheduler.Create(); + var interopProvider = LowPolyAbstractionInteropProvider.TryCreate(devices, scheduler, out var interopDevice); + if (interopProvider is null || interopDevice is null) { - interop.Dispose(); + scheduler.Dispose(); + return null; + } + + _scheduler = scheduler; + + try + { + _interopProvider = interopProvider; + _interopDomain = interopDevice.RegisterExternalDomain(interopProvider); + _resourceSet = LowPolyAbstractionResourceSet.Create(interopDevice, _interopDomain); + _pipeline = LowPolyAbstractionPipeline.TryCreate(interopDevice); + } + catch + { + ReleaseInterop(); + return null; + } + + if (_pipeline is null) + { + ReleaseInterop(); return null; } @@ -213,8 +294,7 @@ internal sealed class LowPolyAbstractionEffectProcessor : VideoEffectProcessorBa if (!effect.IsEnabled) { effect.Dispose(); - pipeline.Dispose(); - interop.Dispose(); + ReleaseInterop(); return null; } outputCrop = new Crop(devices.DeviceContext); @@ -226,8 +306,6 @@ internal sealed class LowPolyAbstractionEffectProcessor : VideoEffectProcessorBa outputTransform.SetInput(0, outputCropOutput, true); outputTransformOutput = outputTransform.Output; output = effect.Output; - _interop = interop; - _pipeline = pipeline; _effect = effect; _outputCrop = outputCrop; _outputCropOutput = outputCropOutput; @@ -249,8 +327,7 @@ internal sealed class LowPolyAbstractionEffectProcessor : VideoEffectProcessorBa outputCropOutput?.Dispose(); outputCrop?.Dispose(); effect?.Dispose(); - pipeline.Dispose(); - interop.Dispose(); + ReleaseInterop(); throw; } } @@ -281,11 +358,7 @@ internal sealed class LowPolyAbstractionEffectProcessor : VideoEffectProcessorBa if (disposing) { ClearEffectChain(); - _interop?.WaitForIdle(); - _pipeline?.Dispose(); - _pipeline = null; - _interop?.Dispose(); - _interop = null; + ReleaseInterop(); } } finally diff --git a/LowPolyAbstraction/LowPolyAbstractionGpuInterop.cs b/LowPolyAbstraction/LowPolyAbstractionGpuInterop.cs index 776e566..2d42f69 100644 --- a/LowPolyAbstraction/LowPolyAbstractionGpuInterop.cs +++ b/LowPolyAbstraction/LowPolyAbstractionGpuInterop.cs @@ -1,323 +1,89 @@ -using System.Runtime.InteropServices; using ComputeWeave; -using ComputeWeave.Interop; -using Vortice; using Vortice.Direct2D1; using Vortice.Direct3D11; -using Vortice.DXGI; using YukkuriMovieMaker.Commons; -using PixelFormat = Vortice.DCommon.PixelFormat; namespace LowPolyAbstraction; -internal sealed class LowPolyAbstractionGpuInterop : IDisposable +internal sealed class LowPolyAbstractionInteropProvider : ComputeExternalDirect3D11Provider { - private static readonly Guid D3D12FenceGuid = new("0a753dcf-c4d8-4b91-adf6-be5a60d95a76"); - - private readonly GraphicsDevice _device; - private readonly ID3D11Device1 _d3dDevice; - private readonly ID3D11DeviceContext4 _d3dContext; - private readonly ID3D11Fence _fence; private readonly ID2D1DeviceContext6 _renderContext; - private nint _d3d12Fence; - private ReadWriteTexture2D? _sourceTexture; - private ReadWriteTexture2D? _outputTexture; - private ID3D11Texture2D? _sourceD3D11Texture; - private ID3D11Texture2D? _outputD3D11Texture; - private ID2D1Bitmap1? _sourceBitmap; - private ID2D1Bitmap1? _outputBitmap; - private int _sourceWidth; - private int _sourceHeight; - private int _outputWidth; - private int _outputHeight; - private ulong _fenceValue; - private bool _computeActive; - private bool _disposed; - private LowPolyAbstractionGpuInterop( - GraphicsDevice device, - ID3D11Device1 d3dDevice, - ID3D11DeviceContext4 d3dContext, - ID3D11Fence fence, + private LowPolyAbstractionInteropProvider( + ID3D11Device1 device, + ID3D11DeviceContext4 context, ID2D1DeviceContext6 renderContext, - nint d3d12Fence) + ComputeExternalQueueScheduler scheduler) + : base(device.NativePointer, context.NativePointer, renderContext.NativePointer, scheduler) { - _device = device; - _d3dDevice = d3dDevice; - _d3dContext = d3dContext; - _fence = fence; _renderContext = renderContext; - _d3d12Fence = d3d12Fence; } - public GraphicsDevice Device => _device; + public ID2D1DeviceContext6 RenderContext => _renderContext; - public ReadWriteTexture2D SourceTexture => _sourceTexture!; - - public ReadWriteTexture2D OutputTexture => _outputTexture!; - - public ID2D1Bitmap1 OutputBitmap => _outputBitmap!; - - public bool SourceMatches(int width, int height) - => _sourceTexture is not null && _sourceWidth == width && _sourceHeight == height; - - public bool OutputCovers(int width, int height) - => _outputTexture is not null && _outputWidth >= width && _outputHeight >= height; - - public static unsafe LowPolyAbstractionGpuInterop? TryCreate(IGraphicsDevicesAndContext devices) + public static LowPolyAbstractionInteropProvider? TryCreate( + IGraphicsDevicesAndContext devices, + ComputeExternalQueueScheduler scheduler, + out GraphicsDevice? graphicsDevice) { - ID3D11Device1? d3dDevice = null; - ID3D11DeviceContext4? d3dContext = null; - ID3D11Fence? fence = null; + ArgumentNullException.ThrowIfNull(scheduler); + + graphicsDevice = null; + + ID3D11Device1? device = null; + ID3D11DeviceContext4? context = null; ID2D1DeviceContext6? renderContext = null; - nint d3d12Fence = 0; - nint fenceHandle = 0; try { - var device = GetMatchingDevice(devices); - d3dDevice = devices.D3D.Device.QueryInterface(); - d3dContext = devices.D3D.DeviceContext.QueryInterface(); - using var d3dDevice5 = devices.D3D.Device.QueryInterface(); - var fenceGuid = D3D12FenceGuid; - InteropServices.CreateSharedFence(device, &fenceGuid, (void**)&d3d12Fence, &fenceHandle); - fence = d3dDevice5.OpenSharedFence(fenceHandle); + if (!GraphicsDevice.TryGetDevice(new ExternalAdapterIdentity(devices.DXGI.Adapter.Description.Luid), out graphicsDevice)) + return null; + + device = devices.D3D.Device.QueryInterface(); + context = devices.D3D.DeviceContext.QueryInterface(); renderContext = devices.D2D.Device.CreateDeviceContext(DeviceContextOptions.EnableMultithreadedOptimizations); - return new LowPolyAbstractionGpuInterop(device, d3dDevice, d3dContext, fence, renderContext, d3d12Fence); + var provider = new LowPolyAbstractionInteropProvider(device, context, renderContext, scheduler); + renderContext = null; + return provider; } catch { - renderContext?.Dispose(); - fence?.Dispose(); - d3dContext?.Dispose(); - d3dDevice?.Dispose(); - if (d3d12Fence != 0) - Marshal.Release(d3d12Fence); + graphicsDevice = null; return null; } finally { - if (fenceHandle != 0) - CloseHandle(fenceHandle); + renderContext?.Dispose(); + context?.Dispose(); + device?.Dispose(); } } - public bool EnsureResources(int width, int height) + protected override void DisposeCore() { - var sourceChanged = EnsureSource(width, height); - var outputChanged = EnsureOutput(width, height); - return sourceChanged || outputChanged; + _renderContext.Dispose(); } - - public bool EnsureSource(int width, int height) - { - if (SourceMatches(width, height)) - return false; - - if (_sourceTexture is not null) - WaitForIdle(); - ReleaseSourceResources(); - CreateSourceResources(width, height); - return true; - } - - public bool EnsureOutput(int width, int height) - { - if (OutputCovers(width, height)) - return false; - - var capacityWidth = Math.Max(width, _outputWidth); - var capacityHeight = Math.Max(height, _outputHeight); - if (_outputTexture is not null) - WaitForIdle(); - ReleaseOutputResources(); - CreateOutputResources(capacityWidth, capacityHeight); - return true; - } - - public void RenderInput(ID2D1Image source, RawRectF bounds) - { - _renderContext.BeginDraw(); - _renderContext.Clear(null); - _renderContext.DrawImage( - source, - new System.Numerics.Vector2(-bounds.Left, -bounds.Top), - null, - InterpolationMode.NearestNeighbor, - CompositeMode.SourceCopy); - _renderContext.EndDraw(); - } - - public unsafe void BeginCompute() - { - if (_computeActive) - throw new InvalidOperationException(); - var value = ++_fenceValue; - _d3dContext.Signal(_fence, value); - _d3dContext.Flush(); - InteropServices.WaitForSharedFence(_device, (void*)_d3d12Fence, value); - _computeActive = true; - } - - public unsafe void EndCompute() - { - if (!_computeActive) - throw new InvalidOperationException(); - try - { - var value = ++_fenceValue; - InteropServices.SignalSharedFence(_device, (void*)_d3d12Fence, value); - _d3dContext.Wait(_fence, value); - } - finally - { - _computeActive = false; - } - } - - public void WaitForIdle() - { - if (_computeActive) - throw new InvalidOperationException(); - var value = ++_fenceValue; - _d3dContext.Signal(_fence, value); - _d3dContext.Flush(); - _fence.SetEventOnCompletion(value, 0); - } - - private static GraphicsDevice GetMatchingDevice(IGraphicsDevicesAndContext devices) - { - var adapterLuid = devices.DXGI.Adapter.Description.Luid.ToString(); - using var enumerator = GraphicsDevice.QueryDevices( - device => string.Equals(device.Luid.ToString(), adapterLuid, StringComparison.Ordinal)).GetEnumerator(); - if (!enumerator.MoveNext()) - throw new NotSupportedException(); - return enumerator.Current; - } - - private void CreateSourceResources(int width, int height) - { - ReadWriteTexture2D? sourceTexture = null; - ID3D11Texture2D? sourceD3D11Texture = null; - ID2D1Bitmap1? sourceBitmap = null; - nint sourceHandle = 0; - try - { - sourceTexture = InteropServices.AllocateSharedReadWriteTexture2D(_device, width, height); - sourceHandle = InteropServices.CreateSharedHandle(sourceTexture); - sourceD3D11Texture = _d3dDevice.OpenSharedResource1(sourceHandle); - using var sourceSurface = sourceD3D11Texture.QueryInterface(); - var pixelFormat = new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied); - sourceBitmap = _renderContext.CreateBitmapFromDxgiSurface( - sourceSurface, - new BitmapProperties1(pixelFormat, 96f, 96f, BitmapOptions.Target)); - _renderContext.Target = sourceBitmap; - - _sourceTexture = sourceTexture; - _sourceD3D11Texture = sourceD3D11Texture; - _sourceBitmap = sourceBitmap; - _sourceWidth = width; - _sourceHeight = height; - sourceTexture = null; - sourceD3D11Texture = null; - sourceBitmap = null; - } - finally - { - if (sourceHandle != 0) - CloseHandle(sourceHandle); - sourceBitmap?.Dispose(); - sourceD3D11Texture?.Dispose(); - sourceTexture?.Dispose(); - } - } - - private void CreateOutputResources(int width, int height) - { - ReadWriteTexture2D? outputTexture = null; - ID3D11Texture2D? outputD3D11Texture = null; - ID2D1Bitmap1? outputBitmap = null; - nint outputHandle = 0; - try - { - outputTexture = InteropServices.AllocateSharedReadWriteTexture2D(_device, width, height); - outputHandle = InteropServices.CreateSharedHandle(outputTexture); - outputD3D11Texture = _d3dDevice.OpenSharedResource1(outputHandle); - using var outputSurface = outputD3D11Texture.QueryInterface(); - var pixelFormat = new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied); - outputBitmap = _renderContext.CreateBitmapFromDxgiSurface( - outputSurface, - new BitmapProperties1(pixelFormat, 96f, 96f, BitmapOptions.None)); - - _outputTexture = outputTexture; - _outputD3D11Texture = outputD3D11Texture; - _outputBitmap = outputBitmap; - _outputWidth = width; - _outputHeight = height; - outputTexture = null; - outputD3D11Texture = null; - outputBitmap = null; - } - finally - { - if (outputHandle != 0) - CloseHandle(outputHandle); - outputBitmap?.Dispose(); - outputD3D11Texture?.Dispose(); - outputTexture?.Dispose(); - } - } - - private void ReleaseSourceResources() - { - _renderContext.Target = null; - _sourceBitmap?.Dispose(); - _sourceD3D11Texture?.Dispose(); - _sourceTexture?.Dispose(); - _sourceBitmap = null; - _sourceD3D11Texture = null; - _sourceTexture = null; - _sourceWidth = 0; - _sourceHeight = 0; - } - - private void ReleaseOutputResources() - { - _outputBitmap?.Dispose(); - _outputD3D11Texture?.Dispose(); - _outputTexture?.Dispose(); - _outputBitmap = null; - _outputD3D11Texture = null; - _outputTexture = null; - _outputWidth = 0; - _outputHeight = 0; - } - - public void Dispose() - { - if (_disposed) - return; - try - { - WaitForIdle(); - } - finally - { - _disposed = true; - ReleaseOutputResources(); - ReleaseSourceResources(); - _renderContext.Dispose(); - _fence.Dispose(); - _d3dContext.Dispose(); - _d3dDevice.Dispose(); - if (_d3d12Fence != 0) - { - Marshal.Release(_d3d12Fence); - _d3d12Fence = 0; - } - } - } - - [DllImport("kernel32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool CloseHandle(nint handle); +} + +[ComputeInteropResourceSet] +internal sealed partial class LowPolyAbstractionResourceSet +{ + [ComputeSharedTexture( + ComputeResourceResizePolicy.Exact, + ComputeResourceAccess.ReadWrite, + ExternalResourceAccess.Write, + ExternalTextureUsage.RenderTarget, + ComputeAlphaMode.Premultiplied, + ComputeSharedTextureInitialOwner.External, + ComputeResourceRecovery.RecreateFromHost)] + private readonly SharedTextureSlot _source; + + [ComputeSharedTexture( + ComputeResourceResizePolicy.GrowOnly, + ComputeResourceAccess.ReadWrite, + ExternalResourceAccess.Read, + ExternalTextureUsage.Sampled, + ComputeAlphaMode.Premultiplied, + ComputeSharedTextureInitialOwner.Compute, + ComputeResourceRecovery.Recompute)] + private readonly SharedTextureSlot _output; } diff --git a/LowPolyAbstraction/LowPolyAbstractionPipeline.cs b/LowPolyAbstraction/LowPolyAbstractionPipeline.cs index 455b50f..2e294b4 100644 --- a/LowPolyAbstraction/LowPolyAbstractionPipeline.cs +++ b/LowPolyAbstraction/LowPolyAbstractionPipeline.cs @@ -108,9 +108,34 @@ internal sealed class LowPolyAbstractionPipeline : IDisposable int sourceHeight, in Parameters parameters) { - EnsureGridFor(canvasWidth, canvasHeight, parameters.Quality); - var derived = Derive(canvasWidth, canvasHeight, in parameters); + var derived = BeginSimulate(canvasWidth, canvasHeight, in parameters); _host.RecordAnalyze(source, _scratch, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, in derived).Wait(); + return CompleteSimulate(canvasWidth, canvasHeight, in parameters, in derived); + } + + internal bool Simulate( + ComputeResourceBinding> source, + int canvasWidth, + int canvasHeight, + int sourceOffsetX, + int sourceOffsetY, + int sourceWidth, + int sourceHeight, + in Parameters parameters) + { + var derived = BeginSimulate(canvasWidth, canvasHeight, in parameters); + _host.RecordSharedAnalyze(source, _scratch, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, in derived).Wait(); + return CompleteSimulate(canvasWidth, canvasHeight, in parameters, in derived); + } + + private DerivedValues BeginSimulate(int canvasWidth, int canvasHeight, in Parameters parameters) + { + EnsureGridFor(canvasWidth, canvasHeight, parameters.Quality); + return Derive(canvasWidth, canvasHeight, in parameters); + } + + private bool CompleteSimulate(int canvasWidth, int canvasHeight, in Parameters parameters, in DerivedValues derived) + { _scratchReadBack.CopyFrom(_scratch); var hashed = _scratchReadBack.Span; _cachedMinX = hashed[LowPolyAbstractionSettings.ScratchBoundsMinX]; @@ -168,6 +193,17 @@ internal sealed class LowPolyAbstractionPipeline : IDisposable _host.RecordRender(output, in rect, in derived, in parameters).Wait(); } + internal void RenderVisible( + ComputeResourceBinding> output, + int canvasWidth, + int canvasHeight, + PixelRect rect, + in Parameters parameters) + { + var derived = Derive(canvasWidth, canvasHeight, in parameters); + _host.RecordSharedRender(output, in rect, in derived, in parameters).Wait(); + } + private ComputeSubmission SubmitFullPipeline( ReadWriteTexture2D source, ReadWriteTexture2D output, diff --git a/LowPolyAbstraction/LowPolyAbstractionPipelineHost.cs b/LowPolyAbstraction/LowPolyAbstractionPipelineHost.cs index 0b741ba..2fd3c7e 100644 --- a/LowPolyAbstraction/LowPolyAbstractionPipelineHost.cs +++ b/LowPolyAbstraction/LowPolyAbstractionPipelineHost.cs @@ -117,6 +117,39 @@ internal sealed partial class LowPolyAbstractionPipelineHost RecordAnalyzeStage(in context, grid, source, scratch, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, in derived); } + [ComputePipeline] + [ComputeInterop] + private void RecordSharedAnalyze( + in ComputeContext context, + [ComputeOwnedResource(nameof(_grid))] LowPolyAbstractionGridResources grid, + [ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D source, + [ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer scratch, + int sourceOffsetX, + int sourceOffsetY, + int sourceWidth, + int sourceHeight, + in LowPolyAbstractionPipeline.DerivedValues derived) + { + _ = _device; + + RecordAnalyzeStage(in context, grid, source, scratch, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, in derived); + } + + [ComputePipeline] + [ComputeInterop] + private void RecordSharedRender( + in ComputeContext context, + [ComputeOwnedResource(nameof(_grid))] LowPolyAbstractionGridResources grid, + [ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D output, + in LowPolyAbstractionPipeline.PixelRect rect, + in LowPolyAbstractionPipeline.DerivedValues derived, + in LowPolyAbstractionPipeline.Parameters parameters) + { + _ = _device; + + RecordRenderStage(in context, grid, output, rect, in derived, in parameters); + } + [ComputePipeline] private void RecordStructure( in ComputeContext context,