diff --git a/Inflate/InflatePipeline.cs b/Inflate/InflatePipeline.cs new file mode 100644 index 0000000..5fb0a0c --- /dev/null +++ b/Inflate/InflatePipeline.cs @@ -0,0 +1,318 @@ +using System.ComponentModel; +using System.Runtime.InteropServices; +using ComputeWeave; + +namespace Inflate; + +internal sealed class InflatePipeline : IDisposable +{ + private readonly GraphicsDevice _device; + private readonly InflatePipelineHost _host; + private readonly ReadWriteBuffer _syncBuffer; + private readonly ReadWriteBuffer _sourceHash; + private readonly ReadBackBuffer _sourceHashReadBack; + private StructureKey? _structureKey; + private ComputeSubmission _pendingHash; + private bool _hasPendingHash; + private SourceHashes? _lastHashes; + private bool _shapeChanging; + private int _gridWidth; + private int _gridHeight; + private ReadWriteTexture2D? _packedSource; + private ReadWriteTexture2D? _packedOutput; + private int _packedWidth; + private int _packedHeight; + + private InflatePipeline(GraphicsDevice device, InflatePipelineHost host) + { + _device = device; + _host = host; + _syncBuffer = device.AllocateReadWriteBuffer(1); + _sourceHash = device.AllocateReadWriteBuffer(InflateSettings.SourceHashLength); + _sourceHashReadBack = device.AllocateReadBackBuffer(InflateSettings.SourceHashLength); + } + + internal void WaitForCompletion() => SynchronizeDevice(); + + private void SynchronizeDevice() + { + using ComputeContext context = _device.CreateComputeContext(); + context.Clear(_syncBuffer); + } + + public static InflatePipeline? TryCreate() + { + try + { + return TryCreate(GraphicsDevice.GetDefault()); + } + catch + { + return null; + } + } + + public static InflatePipeline? TryCreate(GraphicsDevice device) + { + InflatePipelineHost? host = null; + try + { + host = InflatePipelineHost.Create(device, InflateSettings.MaximumPendingSubmissions); + var pipeline = new InflatePipeline(device, host); + host = null; + return pipeline; + } + catch (Win32Exception) + { + return null; + } + finally + { + host?.Dispose(); + host?.WaitForDisposal(); + } + } + + public void Process(ReadOnlySpan source, Span destination, int width, int height, in Parameters parameters) + { + var pixelCount = checked(width * height); + EnsureResources(width, height, parameters.Quality); + EnsurePackedTextures(width, height); + var sourceTexture = _packedSource!; + var outputTexture = _packedOutput!; + sourceTexture.CopyFrom(MemoryMarshal.Cast(source[..pixelCount])); + SubmitFullPipeline(sourceTexture, outputTexture, width, height, in parameters).Wait(); + outputTexture.CopyTo(MemoryMarshal.Cast(destination[..pixelCount])); + } + + public void Process( + ReadWriteTexture2D source, + ReadWriteTexture2D destination, + int width, + int height, + in Parameters parameters) + { + EnsureResources(width, height, parameters.Quality); + _ = SubmitFullPipeline(source, destination, width, height, in parameters); + } + + internal void ProcessSharedAndWait( + ReadWriteTexture2D source, + ReadWriteTexture2D destination, + int width, + int height, + in Parameters parameters) + { + EnsureResources(width, height, parameters.Quality); + SubmitFullPipeline(source, destination, width, height, in parameters).Wait(); + } + + public void Process( + ComputeResourceBinding> source, + ComputeResourceBinding> destination, + int width, + int height, + in Parameters parameters) + { + _ = Simulate(source, width, height, in parameters); + Render(source, destination, width, height, in parameters); + } + + internal SimulationResult Simulate( + ComputeResourceBinding> source, + int width, + int height, + in Parameters parameters) + { + EnsureResources(width, height, parameters.Quality); + var derived = Derive(width, height, in parameters); + ResolvePendingHash(); + var covered = _host.RecordSharedCoverage(source, _sourceHash, width, height, in derived); + var structure = new StructureParameters(width, height, parameters.Quality); + SourceHashes? hashes = null; + if (!_shapeChanging && _structureKey is { Shape: not null } current && current.Parameters == structure) + { + covered.Wait(); + hashes = ReadHashes(); + if (current.Shape == hashes.Value.Shape) + return new SimulationResult(false, hashes.Value.Content); + } + else + { + _pendingHash = covered; + _hasPendingHash = true; + } + + _ = _host.RecordSolve(in derived); + _structureKey = new StructureKey(structure, hashes?.Shape); + return new SimulationResult(true, hashes?.Content); + } + + private void ResolvePendingHash() + { + if (!_hasPendingHash) + return; + + _hasPendingHash = false; + _pendingHash.Wait(); + var hashes = ReadHashes(); + if (_structureKey is { Shape: null } key) + _structureKey = key with { Shape = hashes.Shape }; + } + + private SourceHashes ReadHashes() + { + _sourceHashReadBack.CopyFrom(_sourceHash); + var hashed = _sourceHashReadBack.Span; + var hashes = new SourceHashes( + new ContentHash(hashed[InflateSettings.ShapeHashSum], hashed[InflateSettings.ShapeHashMix]), + new ContentHash(hashed[InflateSettings.ContentHashSum], hashed[InflateSettings.ContentHashMix])); + _shapeChanging = _lastHashes is { } last && last.Shape != hashes.Shape; + _lastHashes = hashes; + return hashes; + } + + internal void Render( + ComputeResourceBinding> source, + ComputeResourceBinding> output, + int width, + int height, + in Parameters parameters) + { + var derived = Derive(width, height, in parameters); + _ = _host.RecordSharedRender(source, output, width, height, in derived, in parameters); + } + + internal float[] ReadPotential(int width, int height, InflateQuality quality) + { + EnsureResources(width, height, quality); + var length = _gridWidth * _gridHeight; + using var destination = _device.AllocateReadWriteBuffer(length); + _host.RecordReadPotential(destination, length).Wait(); + var values = new float[length]; + destination.CopyTo(values); + return values; + } + + internal (int Width, int Height) GridSize => (_gridWidth, _gridHeight); + + internal int? CycleOverride { get; set; } + + internal int? SmoothingOverride { get; set; } + + private ComputeSubmission SubmitFullPipeline( + ReadWriteTexture2D source, + ReadWriteTexture2D output, + int width, + int height, + in Parameters parameters) + { + _structureKey = null; + _hasPendingHash = false; + _lastHashes = null; + _shapeChanging = false; + var derived = Derive(width, height, in parameters); + return _host.RecordFullPipeline(source, output, _sourceHash, width, height, in derived, in parameters); + } + + private DerivedValues Derive(int width, int height, in Parameters parameters) + { + var settings = InflateSettings.GetQuality(parameters.Quality); + return new DerivedValues( + _gridWidth, + _gridHeight, + InflateSettings.GetLevelCount(_gridWidth, _gridHeight), + CycleOverride ?? settings.Cycles, + SmoothingOverride ?? settings.Smoothing); + } + + private void EnsureResources(int width, int height, InflateQuality quality) + { + var settings = InflateSettings.GetQuality(quality); + var (gridWidth, gridHeight) = InflateSettings.GetGridSize(width, height, settings.GridResolution); + var levelCount = InflateSettings.GetLevelCount(gridWidth, gridHeight); + if (levelCount > InflateSettings.MaximumLevelCount) + throw new InvalidOperationException(); + + var pyramidLength = InflateSettings.GetPyramidLength(gridWidth, gridHeight); + if (!_host.TryEnsureGrid( + new InflateGridResources.Plan( + maskLength: pyramidLength, + potentialLength: pyramidLength, + residualLength: pyramidLength, + partialLength: 2 * InflateSettings.GetCorrectionGroupCount(gridWidth, gridHeight), + scaleLength: 1), + out var changed)) + throw new InvalidOperationException(); + + if (changed) + _structureKey = null; + _gridWidth = gridWidth; + _gridHeight = gridHeight; + } + + private void EnsurePackedTextures(int width, int height) + { + if (_packedWidth == width && _packedHeight == height) + return; + + _packedSource?.Dispose(); + _packedOutput?.Dispose(); + _packedSource = _device.AllocateReadWriteTexture2D(width, height); + _packedOutput = _device.AllocateReadWriteTexture2D(width, height); + _packedWidth = width; + _packedHeight = height; + } + + public void Dispose() + { + _host.Dispose(); + _host.WaitForDisposal(); + _structureKey = null; + _gridWidth = 0; + _gridHeight = 0; + _packedSource?.Dispose(); + _packedOutput?.Dispose(); + _packedSource = null; + _packedOutput = null; + _packedWidth = 0; + _packedHeight = 0; + _syncBuffer.Dispose(); + _sourceHash.Dispose(); + _sourceHashReadBack.Dispose(); + } + + internal readonly record struct ContentHash(int Sum, int Mix); + + private readonly record struct SourceHashes(ContentHash Shape, ContentHash Content); + + internal readonly record struct SimulationResult(bool StructureChanged, ContentHash? Content); + + private readonly record struct StructureParameters( + int Width, + int Height, + InflateQuality Quality); + + private readonly record struct StructureKey( + StructureParameters Parameters, + ContentHash? Shape); + + internal readonly record struct DerivedValues( + int GridWidth, + int GridHeight, + int LevelCount, + int Cycles, + int Smoothing); + + internal readonly record struct Parameters( + InflateQuality Quality, + float Height, + float LightAzimuth, + float LightElevation, + float Ambient, + float Specular, + float Sharpness, + float Reflection, + float Rim, + float ColorKeep); +} diff --git a/Inflate/InflatePipelineHost.cs b/Inflate/InflatePipelineHost.cs new file mode 100644 index 0000000..a2c994f --- /dev/null +++ b/Inflate/InflatePipelineHost.cs @@ -0,0 +1,360 @@ +using ComputeWeave; + +namespace Inflate; + +[ComputeResourceGroup] +internal sealed partial class InflateGridResources +{ + [ComputePipelineResource(ComputeResourceAccess.ReadWrite)] + internal ReadWriteBuffer Mask { get; } + + [ComputePipelineResource(ComputeResourceAccess.ReadWrite)] + internal ReadWriteBuffer Potential { get; } + + [ComputePipelineResource(ComputeResourceAccess.ReadWrite)] + internal ReadWriteBuffer Residual { get; } + + [ComputePipelineResource(ComputeResourceAccess.ReadWrite)] + internal ReadWriteBuffer Partial { get; } + + [ComputePipelineResource(ComputeResourceAccess.ReadWrite)] + internal ReadWriteBuffer Scale { get; } +} + +[ComputePipelineHost("_device", 1)] +internal sealed partial class InflatePipelineHost +{ + private readonly GraphicsDevice _device; + + [ComputePipelineResource(ComputeResourceAccess.ReadWrite, ComputeResourceRecovery.Recompute)] + private readonly ComputeResourceGroupSlot _grid = new(); + + [ComputePipeline] + private void RecordFullPipeline( + in ComputeContext context, + [ComputeOwnedResource(nameof(_grid))] InflateGridResources grid, + [ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D source, + [ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D output, + [ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer sourceHash, + int width, + int height, + in InflatePipeline.DerivedValues derived, + in InflatePipeline.Parameters parameters) + { + _ = _device; + + RecordCoverageStage(in context, grid, source, sourceHash, width, height, in derived); + RecordSolveStage(in context, grid, in derived); + RecordRenderStage(in context, grid, source, output, width, height, in derived, in parameters); + } + + [ComputePipeline] + [ComputeInterop] + private void RecordSharedCoverage( + in ComputeContext context, + [ComputeOwnedResource(nameof(_grid))] InflateGridResources grid, + [ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D source, + [ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer sourceHash, + int width, + int height, + in InflatePipeline.DerivedValues derived) + { + _ = _device; + + RecordCoverageStage(in context, grid, source, sourceHash, width, height, in derived); + } + + [ComputePipeline] + private void RecordSolve( + in ComputeContext context, + [ComputeOwnedResource(nameof(_grid))] InflateGridResources grid, + in InflatePipeline.DerivedValues derived) + { + _ = _device; + + RecordSolveStage(in context, grid, in derived); + } + + [ComputePipeline] + [ComputeInterop] + private void RecordSharedRender( + in ComputeContext context, + [ComputeOwnedResource(nameof(_grid))] InflateGridResources grid, + [ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D source, + [ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D output, + int width, + int height, + in InflatePipeline.DerivedValues derived, + in InflatePipeline.Parameters parameters) + { + _ = _device; + + RecordRenderStage(in context, grid, source, output, width, height, in derived, in parameters); + } + + [ComputePipeline] + private void RecordReadPotential( + in ComputeContext context, + [ComputeOwnedResource(nameof(_grid))] InflateGridResources grid, + [ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer destination, + int length) + { + _ = _device; + + context.For(length, new CopyShader(grid.Potential, destination, length)); + } + + private static void RecordCoverageStage( + in ComputeContext context, + InflateGridResources grid, + ReadWriteTexture2D source, + ReadWriteBuffer sourceHash, + int width, + int height, + in InflatePipeline.DerivedValues derived) + { + var gridWidth = derived.GridWidth; + var gridHeight = derived.GridHeight; + + context.Clear(sourceHash); + context.Barrier(sourceHash); + context.For( + ThreadGroupAlignment.AlignX(gridWidth), + ThreadGroupAlignment.AlignY(gridHeight), + new CoverageShader(source, grid.Mask, sourceHash, width, height, gridWidth, gridHeight)); + context.Barrier(grid.Mask); + } + + private static void RecordSolveStage( + in ComputeContext context, + InflateGridResources grid, + in InflatePipeline.DerivedValues derived) + { + var gridWidth = derived.GridWidth; + var gridHeight = derived.GridHeight; + var levelCount = derived.LevelCount; + var coarsestLevel = levelCount - 1; + + context.Clear(grid.Potential); + context.Barrier(grid.Potential); + + context.For( + gridWidth, + gridHeight, + new MaskNeighborShader(grid.Mask, 0, gridWidth, gridHeight)); + context.Barrier(grid.Mask); + + for (var level = 1; level < levelCount; level++) + { + var (fineWidth, fineHeight) = InflateSettings.GetLevelSize(gridWidth, gridHeight, level - 1); + var (coarseWidth, coarseHeight) = InflateSettings.GetLevelSize(gridWidth, gridHeight, level); + var fineOffset = InflateSettings.GetLevelOffset(gridWidth, gridHeight, level - 1); + var coarseOffset = InflateSettings.GetLevelOffset(gridWidth, gridHeight, level); + context.For( + coarseWidth, + coarseHeight, + new MaskRestrictShader(grid.Mask, fineOffset, fineWidth, fineHeight, coarseOffset, coarseWidth, coarseHeight)); + context.Barrier(grid.Mask); + context.For( + coarseWidth, + coarseHeight, + new CoarseNeighborShader(grid.Mask, fineOffset, fineWidth, fineHeight, coarseOffset, coarseWidth, coarseHeight)); + context.Barrier(grid.Mask); + } + + if (coarsestLevel == 0) + { + context.For( + gridWidth, + gridHeight, + new ResidualShader(grid.Potential, grid.Mask, grid.Residual, 0, gridWidth, gridHeight, InflateSettings.GetRightHandSide(0))); + context.Barrier(grid.Residual); + RecordCoarseSolve(in context, grid, 0, gridWidth, gridHeight); + return; + } + + for (var cycle = 0; cycle < derived.Cycles; cycle++) + RecordCycle(in context, grid, gridWidth, gridHeight, coarsestLevel, 0, derived.Smoothing); + } + + private static void RecordCycle( + in ComputeContext context, + InflateGridResources grid, + int gridWidth, + int gridHeight, + int coarsestLevel, + int topLevel, + int sweeps) + { + var (topWidth, topHeight) = InflateSettings.GetLevelSize(gridWidth, gridHeight, topLevel); + var topOffset = InflateSettings.GetLevelOffset(gridWidth, gridHeight, topLevel); + var topRightHandSide = InflateSettings.GetRightHandSide(topLevel); + context.Barrier(grid.Residual); + context.For( + topWidth, + topHeight, + new ResidualShader(grid.Potential, grid.Mask, grid.Residual, topOffset, topWidth, topHeight, topRightHandSide)); + context.Barrier(grid.Residual); + + for (var level = topLevel + 1; level <= coarsestLevel; level++) + { + var (fineWidth, fineHeight) = InflateSettings.GetLevelSize(gridWidth, gridHeight, level - 1); + var (coarseWidth, coarseHeight) = InflateSettings.GetLevelSize(gridWidth, gridHeight, level); + context.For( + coarseWidth, + coarseHeight, + new RestrictResidualShader( + grid.Residual, + grid.Mask, + InflateSettings.GetLevelOffset(gridWidth, gridHeight, level - 1), + fineWidth, + fineHeight, + InflateSettings.GetLevelOffset(gridWidth, gridHeight, level), + coarseWidth, + coarseHeight)); + context.Barrier(grid.Residual); + } + + var (coarsestWidth, coarsestHeight) = InflateSettings.GetLevelSize(gridWidth, gridHeight, coarsestLevel); + RecordCoarseSolve(in context, grid, InflateSettings.GetLevelOffset(gridWidth, gridHeight, coarsestLevel), coarsestWidth, coarsestHeight); + + for (var level = coarsestLevel - 1; level >= topLevel; level--) + { + if (level == topLevel) + RecordCorrectionScale(in context, grid, gridWidth, gridHeight, level + 1); + RecordProlong(in context, grid, gridWidth, gridHeight, level + 1, level, level == topLevel); + var (levelWidth, levelHeight) = InflateSettings.GetLevelSize(gridWidth, gridHeight, level); + RecordSmoothing(in context, grid, InflateSettings.GetLevelOffset(gridWidth, gridHeight, level), levelWidth, levelHeight, level == topLevel, topRightHandSide, sweeps); + } + } + + private static void RecordCoarseSolve( + in ComputeContext context, + InflateGridResources grid, + int offset, + int width, + int height) + { + context.For( + InflateSettings.CoarseSolveThreads, + new CoarseSolveShader(grid.Mask, grid.Residual, grid.Potential, offset, width, height, InflateSettings.CoarseSolveIterations)); + context.Barrier(grid.Potential); + } + + private static void RecordCorrectionScale( + in ComputeContext context, + InflateGridResources grid, + int gridWidth, + int gridHeight, + int coarseLevel) + { + var (coarseWidth, coarseHeight) = InflateSettings.GetLevelSize(gridWidth, gridHeight, coarseLevel); + var groupCount = InflateSettings.GetCorrectionGroupCount(gridWidth, gridHeight); + context.Barrier(grid.Partial); + context.For( + ThreadGroupAlignment.AlignX(gridWidth), + ThreadGroupAlignment.AlignY(gridHeight), + new CorrectionDotShader( + grid.Potential, + grid.Mask, + grid.Residual, + grid.Partial, + InflateSettings.GetLevelOffset(gridWidth, gridHeight, coarseLevel), + coarseWidth, + coarseHeight, + gridWidth, + gridHeight, + (gridWidth + InflateSettings.CorrectionGroupSize - 1) / InflateSettings.CorrectionGroupSize)); + context.Barrier(grid.Partial); + context.Barrier(grid.Scale); + context.For( + InflateSettings.CorrectionReduceThreads, + new CorrectionScaleShader(grid.Partial, grid.Scale, groupCount, InflateSettings.MaximumCorrectionScale)); + context.Barrier(grid.Scale); + } + + private static void RecordProlong( + in ComputeContext context, + InflateGridResources grid, + int gridWidth, + int gridHeight, + int coarseLevel, + int fineLevel, + bool accumulate) + { + var (coarseWidth, coarseHeight) = InflateSettings.GetLevelSize(gridWidth, gridHeight, coarseLevel); + var (fineWidth, fineHeight) = InflateSettings.GetLevelSize(gridWidth, gridHeight, fineLevel); + context.For( + fineWidth, + fineHeight, + new ProlongShader( + grid.Potential, + grid.Mask, + grid.Scale, + InflateSettings.GetLevelOffset(gridWidth, gridHeight, coarseLevel), + coarseWidth, + coarseHeight, + InflateSettings.GetLevelOffset(gridWidth, gridHeight, fineLevel), + fineWidth, + fineHeight, + accumulate ? 1 : 0)); + context.Barrier(grid.Potential); + } + + private static void RecordSmoothing( + in ComputeContext context, + InflateGridResources grid, + int offset, + int width, + int height, + bool constantRhs, + float rhsValue, + int sweeps) + { + for (var sweep = 0; sweep < sweeps; sweep++) + { + for (var color = 0; color < 2; color++) + { + context.For( + (width + 1) / 2, + height, + new GaussSeidelShader(grid.Mask, grid.Residual, grid.Potential, offset, width, height, color, constantRhs ? 1 : 0, rhsValue)); + context.Barrier(grid.Potential); + } + } + } + + private static void RecordRenderStage( + in ComputeContext context, + InflateGridResources grid, + ReadWriteTexture2D source, + ReadWriteTexture2D output, + int width, + int height, + in InflatePipeline.DerivedValues derived, + in InflatePipeline.Parameters parameters) + { + var (lightX, lightY, lightZ) = InflateSettings.GetLightVector(parameters.LightAzimuth, parameters.LightElevation); + context.For( + width, + height, + new RenderShader( + source, + grid.Potential, + output, + width, + height, + derived.GridWidth, + derived.GridHeight, + parameters.Height, + lightX, + lightY, + lightZ, + parameters.Ambient, + parameters.Specular, + InflateSettings.GetSpecularExponent(parameters.Sharpness), + parameters.Reflection, + parameters.Rim, + parameters.ColorKeep)); + } +}