diff --git a/WaveOptics.Harness/Program.cs b/WaveOptics.Harness/Program.cs index 6573099..8cb16a5 100644 --- a/WaveOptics.Harness/Program.cs +++ b/WaveOptics.Harness/Program.cs @@ -247,7 +247,7 @@ static int Convolution(HarnessImage image) var changed = pipeline.Simulate(source, image.Width, image.Height, 0, 0, image.Width, image.Height, in frameParameters); if ((changed || renderedGain != frameParameters.Gain) && pipeline.TryGetVisibleBounds(image.Width, image.Height, in frameParameters, out var rect)) { - pipeline.RenderVisible(output, rect, in frameParameters); + pipeline.RenderVisible(source, output, rect, in frameParameters); renderedGain = frameParameters.Gain; } pipeline.WaitForCompletion(); diff --git a/WaveOptics.Harness/golden.json b/WaveOptics.Harness/golden.json index 109f943..6fddfd8 100644 --- a/WaveOptics.Harness/golden.json +++ b/WaveOptics.Harness/golden.json @@ -9,7 +9,7 @@ "frames": [ 0 ], - "hash": "9B93219016A028453BF7CCAB7FBC7E3658B363FC51850286BE23B7A388C368BF" + "hash": "B71481CC55FAC4F415BF590D7623D8973DA2EEFC9864D376D6D2BEC07D7A53EC" }, { "name": "default-frames-0-8", @@ -24,7 +24,7 @@ 7, 8 ], - "hash": "A77359A34F3A6C78E616953C1D66DF1CD05595E662E3DE38E68EB2FC81D11AE4" + "hash": "7A46C7D2CDA1F9ABB24C7887993ECC5EA84EBF935B1C9C728FC1A123ECBDB382" }, { "name": "amount-0", @@ -38,189 +38,189 @@ "frames": [ 0 ], - "hash": "E854AFBFE739475EE665D3D4C672BEF9A631A1479E094E339B87D18C38BA50B0" + "hash": "E61EAF07F3AD9B803C0CC66D2081ABFBB9CF8E636139831AF9C07FBE720AE829" }, { "name": "gain-50", "frames": [ 0 ], - "hash": "9032893550EE7D03B58762F9BD8BE6608929D45DA0BFD474E5AF410A1C4C3328" + "hash": "04F6DF30B38FF4F091D1160CD8E58DC9C162DC70B9A7C1A1AED5CBA5CD8B95C9" }, { "name": "gain-400", "frames": [ 0 ], - "hash": "95886976629306C5E0A2BB93208B5E627E3C78A9CFCD6263202248E0E363A2A7" + "hash": "92533C9D79403C5E18C6BEA3F900247FC7C30255810851413A319DFBA435FAC6" }, { "name": "gain-400-amount-50", "frames": [ 0 ], - "hash": "C579D45C3F216492D6219DA8C5CDF1C9B2357B51AA1376C53A6CBE051C3F6F1A" + "hash": "8D92DC9C871DC8ADE21A72C4E50E0330A7B3F01655FC50FA008B70DA17458AAE" }, { "name": "wavelength-380", "frames": [ 0 ], - "hash": "A5B889290FAB95A7BB5B00922B36B504AFA660DDF0F7E3EF3F4829D4E4AA8C75" + "hash": "4E475FC56B2F720262560ECC6CE7FF947B440345ED07EEDA5AC7FFFC1B9E2A3C" }, { "name": "wavelength-780", "frames": [ 0 ], - "hash": "7F8CB99C84EEED6C7ADF4E138085B08A53C3454160EF08A135405F1018B4272D" + "hash": "61674C04EDE9E19E97609C5EEB4FEAD8E2AF41DDF2808BFEBD3278119457986F" }, { "name": "f-number-4", "frames": [ 0 ], - "hash": "9526105CC4F77E47D4174A86A7FB6E50A270CDBDCB5C59C14615A2751AB10AD7" + "hash": "59F2E23935AB662D7D6D40C392B2FEAD59FFEC6B6C7466DA01F2A3970099AC2C" }, { "name": "f-number-64", "frames": [ 0 ], - "hash": "28CD10EE5F789E7D99BBD48E2A2967636E33BF4A4A57253E8F62A0FCD4668733" + "hash": "A0B2BDF726B96A4F71583D67F3FFF03BE5F053EAA757A169D02762045FE3054B" }, { "name": "pixel-pitch-0.25", "frames": [ 0 ], - "hash": "0A35D27FBC8670D8C1F9E75581CE5AA7FC23466D5E64141D5E78AFF3631CB0BF" + "hash": "E561DDA367AF61F78A35949F686F7AA4DC11FC0C2B9F50FDC501E997EA023555" }, { "name": "pixel-pitch-2", "frames": [ 0 ], - "hash": "39B4E14378BAABB03A364D7824BC0C999E1C7D9FD292090A2A8995D6C0890D8E" + "hash": "427043F6DA302D72D5C015CB6FDB691710E55824B66B60971386A6A6DA5A2B52" }, { "name": "kernel-radius-1", "frames": [ 0 ], - "hash": "7873F5E5B2AC64FC73E65746900E0C249E6335A533DFD17E0FE97A4EFE9C36A2" + "hash": "D898D9F66BD5566A55D8570BE5F2CD1210F30BED8ECC23B6152805B35280E58E" }, { "name": "kernel-radius-5", "frames": [ 0 ], - "hash": "34B3BCEC95C18658E45A8832AEB2BE00F0716E2FD78CE45CBA36F644DA5945B9" + "hash": "5AC78F10ABFEB6703327409AF5021676BFADBC8B8271FCBFC9A825C4D54DE3D8" }, { "name": "kernel-radius-40-defocus-2", "frames": [ 0 ], - "hash": "6908E7DFE146500A209D47AD18FF5932FF9B80F8FCD976036179F4CA8503C89C" + "hash": "1B90715CC1735FD7B87D16800698B5FE6AAB65E47B38FDE5A1A71733A85662E6" }, { "name": "kernel-radius-63-polygon-defocus-3", "frames": [ 0 ], - "hash": "55D4485AD5176D4AB6C7BE4BBBDD97343002B675AB0742D8F8224FD57A9296A5" + "hash": "544F004B4E6DE4EF2BBB554F7CC8B6A98A3128413642BE0953331BBD1E290285" }, { "name": "quality-draft", "frames": [ 0 ], - "hash": "0E16A02AE2360DBAB4FD57C28A95E51C61C2C33B81D46076D6D6E4FF81636A22" + "hash": "BFDF5C15934DCE96B2FBC3F32671D3619E3A4863D0F6B6C886003EE137E208EA" }, { "name": "quality-high", "frames": [ 0 ], - "hash": "B28685A19BA25205B8F2716831687D3D63958AE24C65311E39D5F585D1750D82" + "hash": "EE9CA6EA1570279FB7FE22615DF9832D3B891F59A2C88A0B46895E23286889E6" }, { "name": "aperture-polygon", "frames": [ 0 ], - "hash": "876C1DD8767A405F4C24ED6EE289513CFE155FA811E6D6F15A8C0E8F21624948" + "hash": "63714DFA7EF012D7AB6B818E538427DD55BAA4392BD0B3171C325D52BEA727D3" }, { "name": "blade-count-3", "frames": [ 0 ], - "hash": "3EC07AD240914F5CD7C0AAA8F0BEF5C76772922E932853B39AD38FC290C493E8" + "hash": "F9B3EA9580C95536258728CF01E885A4308B4A61B3F68861B8BEA4B45CC093B5" }, { "name": "blade-count-32", "frames": [ 0 ], - "hash": "7D5D5A10503525D51000E4CE2BF538E88878E77893D885B9B195C7FFCBDBCB50" + "hash": "62218C4D673DD03C558F0F3A0AB6699A1AF4A33A0E814DFF52F452B61C720A50" }, { "name": "blade-rotation-30", "frames": [ 0 ], - "hash": "7DF481B8A4E5263100A7C30EF3070BC55D497A9F39CF09FEA1E56E4058D19658" + "hash": "0842E055F3DD3518FFE25A2F3ABB1A205310AAB60C2CD9804C221FE024CA4D38" }, { "name": "obstruction-50", "frames": [ 0 ], - "hash": "D1F583FF2F287987F3D97D48B5C3D0B80A647EECCF0F08C15387C745AFA41069" + "hash": "9F86A17BC9EA4E362F6C785B8672B93C21DEB5748064456058C34E8B1B52E800" }, { "name": "defocus-1", "frames": [ 0 ], - "hash": "7B699943FCC55D026212D9D842F2BFE436F992AD1010B23B41A54A9C643120EC" + "hash": "BF6533B30E4130242CAB252FB7370F6097D10CC85DEA926E8A44273B2706CB12" }, { "name": "astigmatism-vertical-1", "frames": [ 0 ], - "hash": "AB5FACB67EC980806B6FFEE0627161CBE3EEE0F288194C1819072F6C108E372B" + "hash": "0AEC6A3A9070BF1F0AD08118DAFCEA6E6C8D55B35555EA8DF918B8D2E127A2EC" }, { "name": "astigmatism-oblique-1", "frames": [ 0 ], - "hash": "FE7398B928F43E7C3E9722D12F0B2550EA275DF9EB26E02E990DFCF21ECC98AE" + "hash": "15E642C87F192398DA4E38275DD9467D162C31B67E7D02FDA22B820752213AC9" }, { "name": "coma-horizontal-1", "frames": [ 0 ], - "hash": "EB2235CF182171F8D07EE8651D111D8A7483DFFAF934F51CC855E2A595FCAB5D" + "hash": "931357CB85EF96F0BED2AFB7F49BADC130C354EACCF3B3815441CD64F472041C" }, { "name": "coma-vertical-1", "frames": [ 0 ], - "hash": "AA3FFDF4A62272DC0BD0E7A0EF8A4E4ECE03B27C90C665F71A991C2B65F72CC6" + "hash": "2A85D748133BBD1C015892C2C1183D9D069A6FA353CB3D14DEEAED7CAE4C378F" }, { "name": "spherical-1", "frames": [ 0 ], - "hash": "91CF9F66CC46831C357D898E0367814285FE4D62959AB717B54146F8E8CE0D6F" + "hash": "5CE0E3BEE95CAF4E585036FC6048CA63F0B3D42C3F1FC23A83D045A41C700FD8" }, { "name": "defocus-animated-frames-0-8", @@ -235,7 +235,7 @@ 7, 8 ], - "hash": "B0D6919D7AD63BBFC378CD8578033D0F6322EF479EA564385A4E6F50C4905F14" + "hash": "B16C68AB33DE6B661BFF623AE9D3AE7264EF75CF3427AFF0FCA5E16E96BC998A" } ] } \ No newline at end of file diff --git a/WaveOptics.Tests/SeparableKernelTests.cs b/WaveOptics.Tests/SeparableKernelTests.cs deleted file mode 100644 index 7250644..0000000 --- a/WaveOptics.Tests/SeparableKernelTests.cs +++ /dev/null @@ -1,158 +0,0 @@ -using WaveOptics.Optics; - -namespace WaveOptics.Tests.Optics; - -public sealed class SeparableKernelTests -{ - [Fact] - public void FullRankReconstructionMatchesOriginal() - { - const int size = 15; - var random = new Random(2024); - var kernel = new double[size * size]; - for (var index = 0; index < kernel.Length; index++) - kernel[index] = random.NextDouble(); - - var separable = SeparableKernel.Decompose(kernel, size, 0d, size); - var maximumError = ReconstructionError(separable, kernel); - - Assert.Equal(size, separable.Rank); - Assert.True(maximumError < 1e-5, $"{maximumError:R}"); - } - - [Fact] - public void OuterProductKernelIsRankOne() - { - const int size = 11; - var vertical = new double[size]; - var horizontal = new double[size]; - for (var i = 0; i < size; i++) - { - vertical[i] = Math.Exp(-0.2 * (i - 5) * (i - 5)); - horizontal[i] = Math.Exp(-0.35 * (i - 5) * (i - 5)); - } - var kernel = new double[size * size]; - for (var y = 0; y < size; y++) - { - for (var x = 0; x < size; x++) - kernel[y * size + x] = vertical[y] * horizontal[x]; - } - - var separable = SeparableKernel.Decompose(kernel, size, 1e-6, size); - var maximumError = ReconstructionError(separable, kernel); - - Assert.Equal(1, separable.Rank); - Assert.True(maximumError < 1e-5, $"{maximumError:R}"); - } - - [Fact] - public void LowRankApproximationHonorsResidualBudget() - { - const int size = 21; - var center = size / 2; - var kernel = new double[size * size]; - var sum = 0d; - for (var y = 0; y < size; y++) - { - for (var x = 0; x < size; x++) - { - var radiusSquared = (x - center) * (x - center) + (y - center) * (y - center); - var value = Math.Exp(-0.12 * radiusSquared); - kernel[y * size + x] = value; - sum += value; - } - } - for (var index = 0; index < kernel.Length; index++) - kernel[index] /= sum; - - var separable = SeparableKernel.Decompose(kernel, size, 1e-4, size); - var energy = 0d; - var residual = 0d; - for (var y = 0; y < size; y++) - { - for (var x = 0; x < size; x++) - { - var original = kernel[y * size + x]; - var approximation = Reconstruct(separable, x, y); - energy += original * original; - residual += (original - approximation) * (original - approximation); - } - } - - Assert.True(separable.Rank < size); - Assert.True(residual <= 1e-4 * energy, $"{residual / energy:R}"); - } - - [Fact] - public void SumIsTheSumOfTheApproximation() - { - const int size = 21; - var center = size / 2; - var kernel = new double[size * size]; - for (var y = 0; y < size; y++) - { - for (var x = 0; x < size; x++) - kernel[y * size + x] = Math.Exp(-0.3 * Math.Sqrt((x - center) * (x - center) + (y - center) * (y - center))); - } - - var separable = SeparableKernel.Decompose(kernel, size, 1e-4, 2); - var sum = 0d; - for (var y = 0; y < size; y++) - { - for (var x = 0; x < size; x++) - sum += Reconstruct(separable, x, y); - } - - Assert.Equal(sum, separable.Sum, 5); - } - - [Theory] - [InlineData(21, 9)] - [InlineData(9, 21)] - [InlineData(13, 13)] - public void AReusedDecompositionMatchesAFreshOne(int previousSize, int size) - { - var random = new Random(previousSize * 100 + size); - var previous = new double[previousSize * previousSize]; - for (var index = 0; index < previous.Length; index++) - previous[index] = random.NextDouble(); - var kernel = new double[size * size]; - for (var index = 0; index < kernel.Length; index++) - kernel[index] = random.NextDouble() * random.NextDouble(); - var reused = new SeparableKernel(); - reused.Update(previous, previousSize, 1e-4, previousSize); - - reused.Update(kernel, size, 1e-4, size); - var fresh = SeparableKernel.Decompose(kernel, size, 1e-4, size); - - Assert.Equal((fresh.Size, fresh.Rank), (reused.Size, reused.Rank)); - Assert.Equal(BitConverter.DoubleToInt64Bits(fresh.Sum), BitConverter.DoubleToInt64Bits(reused.Sum)); - Assert.Equal(BitConverter.DoubleToInt64Bits(fresh.ResidualEnergyRatio), BitConverter.DoubleToInt64Bits(reused.ResidualEnergyRatio)); - Assert.Equal(fresh.Horizontal.ToArray(), reused.Horizontal.ToArray()); - Assert.Equal(fresh.Vertical.ToArray(), reused.Vertical.ToArray()); - } - - static double Reconstruct(SeparableKernel separable, int x, int y) - { - var size = separable.Size; - var value = 0d; - for (var term = 0; term < separable.Rank; term++) - value += separable.Vertical[term * size + y] * separable.Horizontal[term * size + x]; - return value; - } - - static double ReconstructionError(SeparableKernel separable, double[] kernel) - { - var size = separable.Size; - var maximumError = 0d; - for (var y = 0; y < size; y++) - { - for (var x = 0; x < size; x++) - { - var error = Math.Abs(kernel[y * size + x] - Reconstruct(separable, x, y)); - maximumError = Math.Max(maximumError, error); - } - } - return maximumError; - } -} diff --git a/WaveOptics.Tests/WaveOpticsInteropTests.cs b/WaveOptics.Tests/WaveOpticsInteropTests.cs index 16a96e8..8f6e409 100644 --- a/WaveOptics.Tests/WaveOpticsInteropTests.cs +++ b/WaveOptics.Tests/WaveOpticsInteropTests.cs @@ -124,7 +124,7 @@ public sealed class WaveOpticsInteropTests Assert.True(interop.Pipeline.TryGetVisibleBounds(96, 96, in parameters, out var visible)); var (width, height) = outputSize(visible); Assert.True(interop.Resources.TryEnsureOutput(width, height, out _)); - interop.Pipeline.RenderVisible(interop.Resources.GetOutputComputeBinding(), visible, in parameters); + interop.Pipeline.RenderVisible(interop.Resources.GetSourceComputeBinding(), interop.Resources.GetOutputComputeBinding(), visible, in parameters); return visible; } @@ -155,7 +155,7 @@ public sealed class WaveOpticsInteropTests Assert.True(interop.Pipeline.Simulate(interop.Resources.GetSourceComputeBinding(), size, size, 0, 0, size, size, in parameters)); Assert.True(interop.Pipeline.TryGetVisibleBounds(size, size, in parameters, out var visible)); Assert.True(interop.Resources.TryEnsureOutput(visible.Width, visible.Height, out _)); - interop.Pipeline.RenderVisible(interop.Resources.GetOutputComputeBinding(), visible, in parameters); + interop.Pipeline.RenderVisible(interop.Resources.GetSourceComputeBinding(), interop.Resources.GetOutputComputeBinding(), visible, in parameters); var output = interop.CaptureOutput(context, out var width, out var height); Assert.True(sourceChanged); diff --git a/WaveOptics.Tests/WaveOpticsPipelineTests.cs b/WaveOptics.Tests/WaveOpticsPipelineTests.cs index 117b6d9..2cab2da 100644 --- a/WaveOptics.Tests/WaveOpticsPipelineTests.cs +++ b/WaveOptics.Tests/WaveOpticsPipelineTests.cs @@ -88,7 +88,7 @@ public sealed class WaveOpticsPipelineTests return pixels; using var output = device.AllocateReadWriteTexture2D(rect.Width, rect.Height); - pipeline.RenderVisible(output, rect, in parameters); + pipeline.RenderVisible(source, output, rect, in parameters); var visible = new Bgra32[rect.Width * rect.Height]; output.CopyTo(visible); for (var y = 0; y < rect.Height; y++) @@ -118,12 +118,6 @@ public sealed class WaveOpticsPipelineTests return new FraunhoferPsfGenerator().Generate(descriptor).Kernel; } - static SeparableKernel Decompose(WaveOpticsPipeline.PsfParameters psf) - { - var kernel = Kernel(psf); - return SeparableKernel.Decompose(kernel.Values.Span, kernel.Size, WaveOpticsSettings.SeparableResidualRatio, WaveOpticsSettings.MaximumRank); - } - [Fact] public void ATransparentSourceStaysTransparent() { @@ -153,12 +147,13 @@ public sealed class WaveOpticsPipelineTests [InlineData(0, 0)] [InlineData(32, 32)] [InlineData(3, 29)] - public void AnImpulseSpreadsIntoTheSeparableKernel(int impulseX, int impulseY) + public void AnImpulseSpreadsIntoTheKernelScaledToKeepItsLight(int impulseX, int impulseY) { using var pipeline = CreatePipeline(); var parameters = Parameters(kernelRadius: 6, pixelPitch: 1.5f, comaHorizontal: 0.4f); - var separable = Decompose(parameters.Psf); - var radius = separable.Size / 2; + var kernel = Kernel(parameters.Psf); + var sum = kernel.Values.ToArray().Sum(); + var radius = kernel.Size / 2; var source = Square(33, 33, impulseX, impulseY, 1, 1, White); var rendering = Render(pipeline, source, 33, 33, parameters); @@ -167,16 +162,10 @@ public sealed class WaveOpticsPipelineTests { for (var x = 0; x < 33; x++) { - var expected = 0f; var row = impulseY - y + radius; var column = impulseX - x + radius; - if (row >= 0 && row < separable.Size && column >= 0 && column < separable.Size) - { - for (var term = 0; term < separable.Rank; term++) - expected += separable.Horizontal[term * separable.Size + column] * separable.Vertical[term * separable.Size + row]; - } - - var value = (int)Math.Round(Math.Clamp(expected / separable.Sum, 0d, 1d) * 255d, MidpointRounding.ToEven); + var expected = row >= 0 && row < kernel.Size && column >= 0 && column < kernel.Size ? kernel[column, row] / sum : 0d; + var value = (int)Math.Round(Math.Clamp(expected, 0d, 1d) * 255d, MidpointRounding.ToEven); Assert.InRange(Alpha(rendering[y * 33 + x]), value - 1, value + 1); } } diff --git a/WaveOptics.Tests/WaveOpticsSettingsTests.cs b/WaveOptics.Tests/WaveOpticsSettingsTests.cs index a32e41f..12c4816 100644 --- a/WaveOptics.Tests/WaveOpticsSettingsTests.cs +++ b/WaveOptics.Tests/WaveOpticsSettingsTests.cs @@ -1,3 +1,4 @@ +using SpectralConvolution; using WaveOptics.Abstractions; using WaveOptics.Effects; using WaveOptics.Optics; @@ -28,21 +29,11 @@ public sealed class WaveOpticsSettingsTests => Assert.Equal(size, WaveOpticsSettings.GetKernelSize(radius)); [Fact] - public void TheLargestKernelFitsInEveryWeightSlot() - => Assert.Equal(WaveOpticsSettings.MaximumKernelSize, WaveOpticsSettings.GetKernelSize(WaveOpticsSettings.MaximumKernelRadius)); - - [Fact] - public void EveryTermAndAxisOwnsItsOwnWeightSlot() + public void TheLargestKernelFitsInTheLargestTile() { - var offsets = Enumerable.Range(0, WaveOpticsSettings.MaximumRank) - .SelectMany(term => new[] { WaveOpticsSettings.GetWeightOffset(term, 0), WaveOpticsSettings.GetWeightOffset(term, 1) }) - .Order() - .ToArray(); - - Assert.Equal(WaveOpticsSettings.MaximumRank * 2, offsets.Distinct().Count()); - Assert.Equal(0, offsets[0]); - Assert.All(offsets.Zip(offsets.Skip(1)), pair => Assert.Equal(WaveOpticsSettings.MaximumKernelSize, pair.Second - pair.First)); - Assert.Equal(WaveOpticsSettings.WeightsLength, offsets[^1] + WaveOpticsSettings.MaximumKernelSize); + Assert.Equal(WaveOpticsSettings.MaximumKernelSize, WaveOpticsSettings.GetKernelSize(WaveOpticsSettings.MaximumKernelRadius)); + Assert.True(WaveOpticsSettings.MaximumKernelRadius <= TilePlan.MaximumRadius); + Assert.Equal(TilePlan.LargeSize, TilePlan.SelectSize(WaveOpticsSettings.MaximumKernelRadius)); } public static readonly TheoryData Aberrations = new() @@ -56,7 +47,7 @@ public sealed class WaveOpticsSettingsTests [Theory] [MemberData(nameof(Aberrations))] - public void TheRankLimitKeepsEveryAberrationWithinTheResidualBudget(string aberrationName, WavefrontAberration aberration) + public void EveryAberrationGivesAKernelTheConvolutionAccepts(string aberrationName, WavefrontAberration aberration) { var gridSize = WaveOpticsSettings.GetPupilGridSize(WaveOpticsQuality.Standard); var descriptor = new PsfDescriptor( @@ -65,10 +56,11 @@ public sealed class WaveOpticsSettingsTests WaveOpticsSettings.MaximumKernelSize, 550, 8, 4, ApertureShape.Circular, 6, 0, 0, aberration); var kernel = new FraunhoferPsfGenerator().Generate(descriptor).Kernel; + var spectrum = new KernelSpectrum(); - var separable = SeparableKernel.Decompose(kernel.Values.Span, kernel.Size, WaveOpticsSettings.SeparableResidualRatio, WaveOpticsSettings.MaximumRank); + spectrum.Update(kernel.Values.Span, WaveOpticsSettings.MaximumKernelRadius, TilePlan.SelectSize(WaveOpticsSettings.MaximumKernelRadius)); - Assert.True(separable.ResidualEnergyRatio <= WaveOpticsSettings.SeparableResidualRatio, $"{aberrationName}: {separable.ResidualEnergyRatio}"); + Assert.True(Math.Abs(spectrum.Spectrum[0].X - 1f) <= 1e-6f, aberrationName); } [Theory] diff --git a/WaveOptics/Effects/WaveOpticsEffectProcessor.cs b/WaveOptics/Effects/WaveOpticsEffectProcessor.cs index f728f9e..083c683 100644 --- a/WaveOptics/Effects/WaveOpticsEffectProcessor.cs +++ b/WaveOptics/Effects/WaveOpticsEffectProcessor.cs @@ -160,7 +160,7 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase var renderState = new RenderState(parameters.Gain, rect); if (convolutionChanged || outputChanged || !_hasOutput || !_hasRenderState || _renderState != renderState) { - _pipeline.RenderVisible(_resourceSet.GetOutputComputeBinding(), rect, in parameters); + _pipeline.RenderVisible(_resourceSet.GetSourceComputeBinding(), _resourceSet.GetOutputComputeBinding(), rect, in parameters); _renderState = renderState; _hasRenderState = true; } diff --git a/WaveOptics/Optics/SeparableKernel.cs b/WaveOptics/Optics/SeparableKernel.cs deleted file mode 100644 index bb139c0..0000000 --- a/WaveOptics/Optics/SeparableKernel.cs +++ /dev/null @@ -1,201 +0,0 @@ -using System.Numerics; - -namespace WaveOptics.Optics; - -internal sealed class SeparableKernel -{ - readonly Comparison descending; - double[] work = []; - double[] basis = []; - double[] singularValues = []; - int[] order = []; - float[] horizontal = []; - float[] vertical = []; - - public SeparableKernel() - { - descending = (left, right) => singularValues[right].CompareTo(singularValues[left]); - } - - public int Size { get; private set; } - public int Rank { get; private set; } - public double ResidualEnergyRatio { get; private set; } - public double Sum { get; private set; } - public ReadOnlySpan Horizontal => horizontal.AsSpan(0, Rank * Size); - public ReadOnlySpan Vertical => vertical.AsSpan(0, Rank * Size); - - public static SeparableKernel Decompose(ReadOnlySpan kernel, int size, double residualEnergyRatio, int maximumRank) - { - var separable = new SeparableKernel(); - separable.Update(kernel, size, residualEnergyRatio, maximumRank); - return separable; - } - - public void Update(ReadOnlySpan kernel, int size, double residualEnergyRatio, int maximumRank) - { - var area = size * size; - if (work.Length < area) - { - work = new double[area]; - basis = new double[area]; - horizontal = new float[area]; - vertical = new float[area]; - } - if (order.Length != size) - { - singularValues = new double[size]; - order = new int[size]; - } - - for (var row = 0; row < size; row++) - { - for (var column = 0; column < size; column++) - work[column * size + row] = kernel[row * size + column]; - } - Array.Clear(basis, 0, area); - for (var i = 0; i < size; i++) - basis[i * size + i] = 1d; - - OrthogonalizeColumns(work, basis, size); - - var totalEnergy = 0d; - for (var column = 0; column < size; column++) - { - var norm = 0d; - for (var row = 0; row < size; row++) - { - var value = work[column * size + row]; - norm += value * value; - } - singularValues[column] = Math.Sqrt(norm); - order[column] = column; - totalEnergy += norm; - } - - Array.Sort(order, descending); - - var largest = singularValues[order[0]]; - var significant = 0; - var threshold = largest * 1e-12; - for (var i = 0; i < size && singularValues[order[i]] > threshold; i++) - significant++; - significant = Math.Max(significant, 1); - - var rank = significant; - if (residualEnergyRatio > 0 && totalEnergy > 0) - { - var retained = 0d; - var target = (1d - residualEnergyRatio) * totalEnergy; - rank = 0; - for (var i = 0; i < significant; i++) - { - retained += singularValues[order[i]] * singularValues[order[i]]; - rank++; - if (retained >= target) - break; - } - } - rank = Math.Clamp(rank, 1, Math.Min(maximumRank, significant)); - - var retainedEnergy = 0d; - for (var i = 0; i < rank; i++) - retainedEnergy += singularValues[order[i]] * singularValues[order[i]]; - var residual = totalEnergy > 0 ? Math.Max(0d, (totalEnergy - retainedEnergy) / totalEnergy) : 0d; - - var sum = 0d; - for (var term = 0; term < rank; term++) - { - var column = order[term]; - var singularValue = singularValues[column]; - var inverse = singularValue > 0 ? 1d / singularValue : 0d; - var horizontalBase = term * size; - var horizontalSum = 0d; - var verticalSum = 0d; - for (var k = 0; k < size; k++) - { - horizontal[horizontalBase + k] = (float)(basis[column * size + k]); - vertical[horizontalBase + k] = (float)(work[column * size + k] * inverse * singularValue); - horizontalSum += horizontal[horizontalBase + k]; - verticalSum += vertical[horizontalBase + k]; - } - sum += horizontalSum * verticalSum; - } - - Size = size; - Rank = rank; - ResidualEnergyRatio = residual; - Sum = sum; - } - - static void OrthogonalizeColumns(double[] work, double[] basis, int size) - { - const int maximumSweeps = 60; - const double tolerance = 1e-15; - for (var sweep = 0; sweep < maximumSweeps; sweep++) - { - var converged = true; - for (var p = 0; p < size - 1; p++) - { - var workP = work.AsSpan(p * size, size); - var basisP = basis.AsSpan(p * size, size); - for (var q = p + 1; q < size; q++) - { - var workQ = work.AsSpan(q * size, size); - var alpha = 0d; - var beta = 0d; - var gamma = 0d; - for (var k = 0; k < size; k++) - { - var wp = workP[k]; - var wq = workQ[k]; - alpha += wp * wp; - beta += wq * wq; - gamma += wp * wq; - } - - if (Math.Abs(gamma) <= tolerance * Math.Sqrt(alpha * beta)) - continue; - - converged = false; - var zeta = (beta - alpha) / (2d * gamma); - var t = Math.Sign(zeta) / (Math.Abs(zeta) + Math.Sqrt(1d + zeta * zeta)); - if (zeta == 0d) - t = 1d; - var c = 1d / Math.Sqrt(1d + t * t); - var s = c * t; - - var basisQ = basis.AsSpan(q * size, size); - Rotate(workP, workQ, c, s); - Rotate(basisP, basisQ, c, s); - } - } - if (converged) - break; - } - } - - static void Rotate(Span first, Span second, double c, double s) - { - var index = 0; - var width = Vector.Count; - if (Vector.IsHardwareAccelerated && first.Length >= width) - { - var cosine = new Vector(c); - var sine = new Vector(s); - for (; index + width <= first.Length; index += width) - { - var a = new Vector(first[index..]); - var b = new Vector(second[index..]); - (cosine * a - sine * b).CopyTo(first[index..]); - (sine * a + cosine * b).CopyTo(second[index..]); - } - } - for (; index < first.Length; index++) - { - var a = first[index]; - var b = second[index]; - first[index] = c * a - s * b; - second[index] = s * a + c * b; - } - } -} diff --git a/WaveOptics/Rendering/WaveOpticsGpuShaders.cs b/WaveOptics/Rendering/WaveOpticsGpuShaders.cs index 44f5112..94fe029 100644 --- a/WaveOptics/Rendering/WaveOpticsGpuShaders.cs +++ b/WaveOptics/Rendering/WaveOpticsGpuShaders.cs @@ -105,287 +105,3 @@ internal readonly partial struct SourceHashShader( Hlsl.InterlockedMax(ref scratch[WaveOpticsSettings.ScratchBoundsMaxY], sourceY + y); } } - -[ThreadGroupSize(DefaultThreadGroupSizes.XY)] -[GeneratedComputeShaderDescriptor] -internal readonly partial struct HorizontalPassShader( - ReadWriteTexture2D source, - ReadOnlyBuffer weights, - ReadWriteBuffer horizontal, - int weightOffset, - int radius, - int regionX, - int regionY, - int regionWidth, - int regionHeight, - int canvasWidth, - int sourceX, - int sourceY, - int sourceWidth) : IComputeShader -{ - private readonly ReadWriteTexture2D source = source; - private readonly ReadOnlyBuffer weights = weights; - private readonly ReadWriteBuffer horizontal = horizontal; - private readonly int weightOffset = weightOffset; - private readonly int radius = radius; - private readonly int regionX = regionX; - private readonly int regionY = regionY; - private readonly int regionWidth = regionWidth; - private readonly int regionHeight = regionHeight; - private readonly int canvasWidth = canvasWidth; - private readonly int sourceX = sourceX; - private readonly int sourceY = sourceY; - private readonly int sourceWidth = sourceWidth; - - public void Execute() - { - var offsetX = ThreadIds.X * WaveOpticsSettings.HorizontalConvolutionBlock; - if (offsetX >= regionWidth || ThreadIds.Y >= regionHeight) - return; - - var x = regionX + offsetX; - var y = regionY + ThreadIds.Y; - var column = x - sourceX; - var row = y - sourceY; - var first = Hlsl.Max(-radius, -column); - var last = Hlsl.Min(radius + WaveOpticsSettings.HorizontalConvolutionBlock - 1, sourceWidth - 1 - column); - var weight0 = Weight(first - 1); - var weight1 = Weight(first - 2); - var weight2 = Weight(first - 3); - var weight3 = Weight(first - 4); - var weight4 = Weight(first - 5); - var weight5 = Weight(first - 6); - var weight6 = Weight(first - 7); - var weight7 = Weight(first - 8); - var weight8 = Weight(first - 9); - var weight9 = Weight(first - 10); - var weight10 = Weight(first - 11); - var weight11 = Weight(first - 12); - var weight12 = Weight(first - 13); - var weight13 = Weight(first - 14); - var weight14 = Weight(first - 15); - var sum0 = new Float4(0f, 0f, 0f, 0f); - var sum1 = sum0; - var sum2 = sum0; - var sum3 = sum0; - var sum4 = sum0; - var sum5 = sum0; - var sum6 = sum0; - var sum7 = sum0; - var sum8 = sum0; - var sum9 = sum0; - var sum10 = sum0; - var sum11 = sum0; - var sum12 = sum0; - var sum13 = sum0; - var sum14 = sum0; - var sum15 = sum0; - for (var offset = first; offset <= last; offset++) - { - var weight15 = weight14; - weight14 = weight13; - weight13 = weight12; - weight12 = weight11; - weight11 = weight10; - weight10 = weight9; - weight9 = weight8; - weight8 = weight7; - weight7 = weight6; - weight6 = weight5; - weight5 = weight4; - weight4 = weight3; - weight3 = weight2; - weight2 = weight1; - weight1 = weight0; - weight0 = Weight(offset); - var texel = source[new Int2(column + offset, row)]; - sum0 += texel * weight0; - sum1 += texel * weight1; - sum2 += texel * weight2; - sum3 += texel * weight3; - sum4 += texel * weight4; - sum5 += texel * weight5; - sum6 += texel * weight6; - sum7 += texel * weight7; - sum8 += texel * weight8; - sum9 += texel * weight9; - sum10 += texel * weight10; - sum11 += texel * weight11; - sum12 += texel * weight12; - sum13 += texel * weight13; - sum14 += texel * weight14; - sum15 += texel * weight15; - } - - var index = y * canvasWidth + x; - horizontal[index] = sum0; - if (offsetX + 1 < regionWidth) - horizontal[index + 1] = sum1; - if (offsetX + 2 < regionWidth) - horizontal[index + 2] = sum2; - if (offsetX + 3 < regionWidth) - horizontal[index + 3] = sum3; - if (offsetX + 4 < regionWidth) - horizontal[index + 4] = sum4; - if (offsetX + 5 < regionWidth) - horizontal[index + 5] = sum5; - if (offsetX + 6 < regionWidth) - horizontal[index + 6] = sum6; - if (offsetX + 7 < regionWidth) - horizontal[index + 7] = sum7; - if (offsetX + 8 < regionWidth) - horizontal[index + 8] = sum8; - if (offsetX + 9 < regionWidth) - horizontal[index + 9] = sum9; - if (offsetX + 10 < regionWidth) - horizontal[index + 10] = sum10; - if (offsetX + 11 < regionWidth) - horizontal[index + 11] = sum11; - if (offsetX + 12 < regionWidth) - horizontal[index + 12] = sum12; - if (offsetX + 13 < regionWidth) - horizontal[index + 13] = sum13; - if (offsetX + 14 < regionWidth) - horizontal[index + 14] = sum14; - if (offsetX + 15 < regionWidth) - horizontal[index + 15] = sum15; - } - - private float Weight(int offset) - => offset >= -radius && offset <= radius ? weights[weightOffset + radius + offset] : 0f; -} - -[ThreadGroupSize(DefaultThreadGroupSizes.XY)] -[GeneratedComputeShaderDescriptor] -internal readonly partial struct VerticalPassShader( - ReadWriteBuffer horizontal, - ReadOnlyBuffer weights, - ReadWriteBuffer convolved, - int weightOffset, - int radius, - int rectX, - int rectY, - int rectWidth, - int rectHeight, - int canvasWidth, - int sourceY, - int sourceHeight, - bool accumulate) : IComputeShader -{ - private readonly ReadWriteBuffer horizontal = horizontal; - private readonly ReadOnlyBuffer weights = weights; - private readonly ReadWriteBuffer convolved = convolved; - private readonly int weightOffset = weightOffset; - private readonly int radius = radius; - private readonly int rectX = rectX; - private readonly int rectY = rectY; - private readonly int rectWidth = rectWidth; - private readonly int rectHeight = rectHeight; - private readonly int canvasWidth = canvasWidth; - private readonly int sourceY = sourceY; - private readonly int sourceHeight = sourceHeight; - private readonly bool accumulate = accumulate; - - public void Execute() - { - var offsetY = ThreadIds.Y * WaveOpticsSettings.VerticalConvolutionBlock; - if (ThreadIds.X >= rectWidth || offsetY >= rectHeight) - return; - - var x = rectX + ThreadIds.X; - var y = rectY + offsetY; - var row = y - sourceY; - var first = Hlsl.Max(-radius, -row); - var last = Hlsl.Min(radius + WaveOpticsSettings.VerticalConvolutionBlock - 1, sourceHeight - 1 - row); - var weight0 = Weight(first - 1); - var weight1 = Weight(first - 2); - var weight2 = Weight(first - 3); - var weight3 = Weight(first - 4); - var weight4 = Weight(first - 5); - var weight5 = Weight(first - 6); - var weight6 = Weight(first - 7); - var sum0 = new Float4(0f, 0f, 0f, 0f); - var sum1 = sum0; - var sum2 = sum0; - var sum3 = sum0; - var sum4 = sum0; - var sum5 = sum0; - var sum6 = sum0; - var sum7 = sum0; - for (var offset = first; offset <= last; offset++) - { - var weight7 = weight6; - weight6 = weight5; - weight5 = weight4; - weight4 = weight3; - weight3 = weight2; - weight2 = weight1; - weight1 = weight0; - weight0 = Weight(offset); - var value = horizontal[(y + offset) * canvasWidth + x]; - sum0 += value * weight0; - sum1 += value * weight1; - sum2 += value * weight2; - sum3 += value * weight3; - sum4 += value * weight4; - sum5 += value * weight5; - sum6 += value * weight6; - sum7 += value * weight7; - } - - var index = y * canvasWidth + x; - Store(index, sum0); - if (offsetY + 1 < rectHeight) - Store(index + canvasWidth, sum1); - if (offsetY + 2 < rectHeight) - Store(index + canvasWidth * 2, sum2); - if (offsetY + 3 < rectHeight) - Store(index + canvasWidth * 3, sum3); - if (offsetY + 4 < rectHeight) - Store(index + canvasWidth * 4, sum4); - if (offsetY + 5 < rectHeight) - Store(index + canvasWidth * 5, sum5); - if (offsetY + 6 < rectHeight) - Store(index + canvasWidth * 6, sum6); - if (offsetY + 7 < rectHeight) - Store(index + canvasWidth * 7, sum7); - } - - private float Weight(int offset) - => offset >= -radius && offset <= radius ? weights[weightOffset + radius + offset] : 0f; - - private void Store(int index, Float4 sum) - { - convolved[index] = accumulate ? convolved[index] + sum : sum; - } -} - -[ThreadGroupSize(DefaultThreadGroupSizes.XY)] -[GeneratedComputeShaderDescriptor] -internal readonly partial struct RenderShader( - ReadWriteBuffer convolved, - ReadWriteTexture2D output, - int rectX, - int rectY, - int rectWidth, - int rectHeight, - int canvasWidth, - float gain) : IComputeShader -{ - private readonly ReadWriteBuffer convolved = convolved; - private readonly ReadWriteTexture2D output = output; - private readonly int rectX = rectX; - private readonly int rectY = rectY; - private readonly int rectWidth = rectWidth; - private readonly int rectHeight = rectHeight; - private readonly int canvasWidth = canvasWidth; - private readonly float gain = gain; - - public void Execute() - { - if (ThreadIds.X >= rectWidth || ThreadIds.Y >= rectHeight) - return; - - output[ThreadIds.XY] = convolved[(rectY + ThreadIds.Y) * canvasWidth + rectX + ThreadIds.X] * gain; - } -} diff --git a/WaveOptics/Rendering/WaveOpticsKernel.cs b/WaveOptics/Rendering/WaveOpticsKernel.cs new file mode 100644 index 0000000..3e1b4a4 --- /dev/null +++ b/WaveOptics/Rendering/WaveOpticsKernel.cs @@ -0,0 +1,70 @@ +using SpectralConvolution; +using WaveOptics.Abstractions; +using WaveOptics.Effects; +using WaveOptics.Optics; + +namespace WaveOptics.Rendering; + +internal sealed class WaveOpticsKernel +{ + private readonly double[] _values = new double[WaveOpticsSettings.MaximumKernelSize * WaveOpticsSettings.MaximumKernelSize]; + private readonly FraunhoferKernelSampler _sampler = new(); + private readonly KernelSpectrum _spectrum = new(); + private WaveOpticsPipeline.PsfParameters? _key; + private bool _isValid; + private int _version; + + public KernelSpectrum Spectrum => _spectrum; + + public bool IsValid => _isValid; + + public int Version => _version; + + public bool TryUpdate(in WaveOpticsPipeline.PsfParameters psf) + { + var key = KeyOf(psf); + if (_key == key) + return _isValid; + + _key = key; + _isValid = false; + _version++; + var pupilGridSize = WaveOpticsSettings.GetPupilGridSize(psf.Quality); + var aberration = new WavefrontAberration( + defocusWaves: psf.Defocus, + astigmatismVerticalWaves: psf.AstigmatismVertical, + astigmatismObliqueWaves: psf.AstigmatismOblique, + comaHorizontalWaves: psf.ComaHorizontal, + comaVerticalWaves: psf.ComaVertical, + sphericalWaves: psf.Spherical); + var specification = new PsfSpecification( + pupilGridSize, + WaveOpticsSettings.GetPupilDiameterSamples(pupilGridSize), + WaveOpticsSettings.GetKernelSize(psf.KernelRadius), + psf.Wavelength, + psf.FNumber, + psf.PixelPitch, + psf.ApertureShape == WaveOpticsApertureShape.Circular ? ApertureShape.Circular : ApertureShape.RegularPolygon, + psf.BladeCount, + psf.BladeRotation, + psf.Obstruction, + aberration); + var size = specification.KernelSize; + var values = _values.AsSpan(0, size * size); + if (!_sampler.TrySample(in specification, values)) + return false; + + var sum = 0d; + foreach (var value in values) + sum += value; + if (!double.IsFinite(sum) || sum <= 0d) + return false; + + _spectrum.Update(values, psf.KernelRadius, TilePlan.SelectSize(psf.KernelRadius)); + _isValid = true; + return true; + } + + public static WaveOpticsPipeline.PsfParameters KeyOf(in WaveOpticsPipeline.PsfParameters psf) + => psf.ApertureShape == WaveOpticsApertureShape.Circular ? psf with { BladeCount = 0, BladeRotation = 0f } : psf; +} diff --git a/WaveOptics/Rendering/WaveOpticsPipeline.cs b/WaveOptics/Rendering/WaveOpticsPipeline.cs index f7df879..9705360 100644 --- a/WaveOptics/Rendering/WaveOpticsPipeline.cs +++ b/WaveOptics/Rendering/WaveOpticsPipeline.cs @@ -1,9 +1,8 @@ using System.ComponentModel; using System.Runtime.InteropServices; using ComputeWeave; -using WaveOptics.Abstractions; +using SpectralConvolution; using WaveOptics.Effects; -using WaveOptics.Optics; namespace WaveOptics.Rendering; @@ -13,14 +12,16 @@ internal sealed class WaveOpticsPipeline : IDisposable private readonly WaveOpticsPipelineHost _host; private readonly ReadWriteBuffer _scratch; private readonly ReadBackBuffer _scratchReadBack; - private readonly ReadOnlyBuffer _weights; - private readonly float[] _weightValues = new float[WaveOpticsSettings.WeightsLength]; - private readonly double[] _kernelValues = new double[WaveOpticsSettings.MaximumKernelSize * WaveOpticsSettings.MaximumKernelSize]; - private readonly FraunhoferKernelSampler _sampler = new(); - private readonly SeparableKernel _separable = new(); - private PsfParameters? _kernelPsf; - private Kernel _kernel; + private readonly GpuTileConvolver _convolver; + private readonly WaveOpticsKernel _kernel = new(); + private int _uploadedKernelVersion; private ConvolutionKey? _convolutionKey; + private ConvolutionKey? _renderedKey; + private PixelRect _renderedRect; + private float _renderedGain; + private bool _storeIsValid; + private GpuTileJob _storedJob; + private PixelRect _sourceRect; private int _cachedLitCount; private int _cachedBoundsMinX; private int _cachedBoundsMinY; @@ -39,7 +40,7 @@ internal sealed class WaveOpticsPipeline : IDisposable _host = host; _scratch = device.AllocateReadWriteBuffer(WaveOpticsSettings.ScratchLength); _scratchReadBack = device.AllocateReadBackBuffer(WaveOpticsSettings.ScratchLength); - _weights = device.AllocateReadOnlyBuffer(WaveOpticsSettings.WeightsLength); + _convolver = new GpuTileConvolver(device); } public static WaveOpticsPipeline? TryCreate() @@ -123,11 +124,7 @@ internal sealed class WaveOpticsPipeline : IDisposable { var sourceRect = BeginSimulate(canvasWidth, canvasHeight, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight); _host.RecordSourceHash(source, _scratch, in sourceRect).Wait(); - if (!TryBeginConvolution(in sourceRect, in parameters, out var rect)) - return false; - - _host.RecordConvolution(source, _weights, in sourceRect, in rect, _canvasWidth, in _kernel).Wait(); - return true; + return TryBeginConvolution(in sourceRect, in parameters); } internal bool Simulate( @@ -142,11 +139,7 @@ internal sealed class WaveOpticsPipeline : IDisposable { var sourceRect = BeginSimulate(canvasWidth, canvasHeight, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight); _host.RecordSharedSourceHash(source, _scratch, in sourceRect).Wait(); - if (!TryBeginConvolution(in sourceRect, in parameters, out var rect)) - return false; - - _host.RecordSharedConvolution(source, _weights, in sourceRect, in rect, _canvasWidth, in _kernel).Wait(); - return true; + return TryBeginConvolution(in sourceRect, in parameters); } private PixelRect BeginSimulate(int canvasWidth, int canvasHeight, int sourceOffsetX, int sourceOffsetY, int sourceWidth, int sourceHeight) @@ -155,7 +148,7 @@ internal sealed class WaveOpticsPipeline : IDisposable return new PixelRect(sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight); } - private bool TryBeginConvolution(in PixelRect sourceRect, in Parameters parameters, out PixelRect rect) + private bool TryBeginConvolution(in PixelRect sourceRect, in Parameters parameters) { _scratchReadBack.CopyFrom(_scratch); var hashed = _scratchReadBack.Span; @@ -171,25 +164,22 @@ internal sealed class WaveOpticsPipeline : IDisposable _canvasWidth, _canvasHeight, sourceRect, - KernelKey(parameters.Psf)); - if (_convolutionKey == key || !TryGetVisibleBounds(_canvasWidth, _canvasHeight, in parameters, out rect)) - { - rect = default; + WaveOpticsKernel.KeyOf(parameters.Psf)); + if (_convolutionKey == key || !TryGetVisibleBounds(_canvasWidth, _canvasHeight, in parameters, out _)) return false; - } - if (!TryEnsureKernel(parameters.Psf)) + if (!_kernel.TryUpdate(parameters.Psf)) { _convolutionKey = null; - rect = default; return false; } _convolutionKey = key; + _sourceRect = sourceRect; return true; } - internal bool HasKernel => _kernel.Rank > 0; + internal bool HasKernel => _kernel.IsValid; internal bool TryGetVisibleBounds(int canvasWidth, int canvasHeight, in Parameters parameters, out PixelRect rect) { @@ -211,14 +201,90 @@ internal sealed class WaveOpticsPipeline : IDisposable return true; } - internal void RenderVisible(ReadWriteTexture2D output, PixelRect rect, in Parameters parameters) + internal void RenderVisible( + ReadWriteTexture2D source, + ReadWriteTexture2D output, + PixelRect rect, + in Parameters parameters) { - _host.RecordRender(output, in rect, _canvasWidth, parameters.Gain).Wait(); + var mode = BeginRender(rect, parameters.Gain); + if (mode == RenderMode.Stored) + _host.RecordStoredRender(_convolver.StoreFor(_storedJob), output, in rect, parameters.Gain).Wait(); + else + { + var job = PrepareConvolution(rect, parameters.Gain, mode == RenderMode.ConvolveAndStore); + _host.RecordConvolution( + source, output, _convolver.Tiles, _convolver.Twiddles, _convolver.Spectrum, + _convolver.Report, _convolver.Samples, _convolver.StoreFor(job), in job).Wait(); + } } - internal void RenderVisible(ComputeResourceBinding> output, PixelRect rect, in Parameters parameters) + internal void RenderVisible( + ComputeResourceBinding> source, + ComputeResourceBinding> output, + PixelRect rect, + in Parameters parameters) { - _host.RecordSharedRender(output, in rect, _canvasWidth, parameters.Gain).Wait(); + var mode = BeginRender(rect, parameters.Gain); + if (mode == RenderMode.Stored) + _host.RecordSharedStoredRender(_convolver.StoreFor(_storedJob), output, in rect, parameters.Gain).Wait(); + else + { + var job = PrepareConvolution(rect, parameters.Gain, mode == RenderMode.ConvolveAndStore); + _host.RecordSharedConvolution( + source, output, _convolver.Tiles, _convolver.Twiddles, _convolver.Spectrum, + _convolver.Report, _convolver.Samples, _convolver.StoreFor(job), in job).Wait(); + } + } + + private RenderMode BeginRender(PixelRect rect, float gain) + { + if (_convolutionKey is not { } key || !_kernel.IsValid) + throw new InvalidOperationException(); + + RenderMode mode; + if (_renderedKey != key || _renderedRect != rect) + { + ReleaseStore(); + mode = RenderMode.Convolve; + } + else if (_storeIsValid) + mode = RenderMode.Stored; + else + mode = gain != _renderedGain ? RenderMode.ConvolveAndStore : RenderMode.Convolve; + + _renderedKey = key; + _renderedRect = rect; + _renderedGain = gain; + return mode; + } + + private GpuTileJob PrepareConvolution(PixelRect rect, float gain, bool store) + { + if (_uploadedKernelVersion != _kernel.Version) + { + _convolver.Upload(_kernel.Spectrum); + _uploadedKernelVersion = _kernel.Version; + } + + var plan = TilePlan.Create(_kernel.Spectrum.Size, _kernel.Spectrum.Radius, rect.X, rect.Y, rect.Width, rect.Height); + var job = _convolver.Prepare(plan, _sourceRect.X, _sourceRect.Y, _sourceRect.Width, _sourceRect.Height, gain, [], store); + if (store) + { + _storedJob = job; + _storeIsValid = true; + } + + return job; + } + + private void ReleaseStore() + { + if (!_storeIsValid) + return; + _convolver.ReleaseStore(); + _storeIsValid = false; + _storedJob = default; } private ComputeSubmission SubmitFullPipeline( @@ -229,81 +295,31 @@ internal sealed class WaveOpticsPipeline : IDisposable in Parameters parameters) { EnsureCanvas(width, height); - if (!TryEnsureKernel(parameters.Psf)) + if (!_kernel.TryUpdate(parameters.Psf)) throw new InvalidOperationException(); _convolutionKey = null; - var sourceRect = new PixelRect(0, 0, width, height); - return _host.RecordFullPipeline(source, output, _weights, in sourceRect, in _kernel, parameters.Gain); + _renderedKey = null; + ReleaseStore(); + _sourceRect = new PixelRect(0, 0, width, height); + var job = PrepareConvolution(_sourceRect, parameters.Gain, false); + return _host.RecordConvolution( + source, output, _convolver.Tiles, _convolver.Twiddles, _convolver.Spectrum, + _convolver.Report, _convolver.Samples, _convolver.StoreFor(job), in job); } - private bool TryEnsureKernel(in PsfParameters psf) - { - var key = KernelKey(psf); - if (_kernelPsf == key) - return HasKernel; - - var pupilGridSize = WaveOpticsSettings.GetPupilGridSize(psf.Quality); - var aberration = new WavefrontAberration( - defocusWaves: psf.Defocus, - astigmatismVerticalWaves: psf.AstigmatismVertical, - astigmatismObliqueWaves: psf.AstigmatismOblique, - comaHorizontalWaves: psf.ComaHorizontal, - comaVerticalWaves: psf.ComaVertical, - sphericalWaves: psf.Spherical); - var specification = new PsfSpecification( - pupilGridSize, - WaveOpticsSettings.GetPupilDiameterSamples(pupilGridSize), - WaveOpticsSettings.GetKernelSize(psf.KernelRadius), - psf.Wavelength, - psf.FNumber, - psf.PixelPitch, - psf.ApertureShape == WaveOpticsApertureShape.Circular ? ApertureShape.Circular : ApertureShape.RegularPolygon, - psf.BladeCount, - psf.BladeRotation, - psf.Obstruction, - aberration); - var size = specification.KernelSize; - var kernel = _kernelValues.AsSpan(0, size * size); - if (!_sampler.TrySample(in specification, kernel)) - { - _kernel = default; - _kernelPsf = key; - return false; - } - - _separable.Update(kernel, size, WaveOpticsSettings.SeparableResidualRatio, WaveOpticsSettings.MaximumRank); - var scale = 1d / _separable.Sum; - for (var term = 0; term < _separable.Rank; term++) - { - _separable.Horizontal.Slice(term * size, size).CopyTo(_weightValues.AsSpan(WaveOpticsSettings.GetWeightOffset(term, 0))); - var verticalOffset = WaveOpticsSettings.GetWeightOffset(term, 1); - for (var k = 0; k < size; k++) - _weightValues[verticalOffset + k] = (float)(_separable.Vertical[term * size + k] * scale); - } - _weights.CopyFrom(_weightValues.AsSpan(0, WaveOpticsSettings.GetWeightOffset(_separable.Rank, 0))); - _kernel = new Kernel(_separable.Rank, size / 2); - _kernelPsf = key; - return true; - } - - private static PsfParameters KernelKey(in PsfParameters psf) - => psf.ApertureShape == WaveOpticsApertureShape.Circular ? psf with { BladeCount = 0, BladeRotation = 0f } : psf; - private void EnsureCanvas(int canvasWidth, int canvasHeight) { if (_canvasWidth == canvasWidth && _canvasHeight == canvasHeight) return; - var canvasLength = canvasWidth * canvasHeight; - if (!_host.TryEnsureCanvas(new WaveOpticsCanvasResources.Plan(canvasLength, canvasLength), out _)) - throw new InvalidOperationException(); - _cachedLitCount = 0; _cachedBoundsMinX = int.MaxValue; _cachedBoundsMinY = int.MaxValue; _cachedBoundsMaxX = int.MinValue; _cachedBoundsMaxY = int.MinValue; _convolutionKey = null; + _renderedKey = null; + ReleaseStore(); _canvasWidth = canvasWidth; _canvasHeight = canvasHeight; } @@ -331,18 +347,24 @@ internal sealed class WaveOpticsPipeline : IDisposable _packedOutput = null; _packedWidth = 0; _packedHeight = 0; - _kernelPsf = null; _convolutionKey = null; + _renderedKey = null; + _storeIsValid = false; _canvasWidth = 0; _canvasHeight = 0; - _weights.Dispose(); + _convolver.Dispose(); _scratchReadBack.Dispose(); _scratch.Dispose(); } - internal readonly record struct PixelRect(int X, int Y, int Width, int Height); + private enum RenderMode + { + Convolve, + ConvolveAndStore, + Stored, + } - internal readonly record struct Kernel(int Rank, int Radius); + internal readonly record struct PixelRect(int X, int Y, int Width, int Height); private readonly record struct ConvolutionKey( int HashSum, diff --git a/WaveOptics/Rendering/WaveOpticsPipelineHost.cs b/WaveOptics/Rendering/WaveOpticsPipelineHost.cs index f1e5fc6..ba0a472 100644 --- a/WaveOptics/Rendering/WaveOpticsPipelineHost.cs +++ b/WaveOptics/Rendering/WaveOpticsPipelineHost.cs @@ -1,42 +1,13 @@ using ComputeWeave; +using SpectralConvolution; namespace WaveOptics.Rendering; -[ComputeResourceGroup] -internal sealed partial class WaveOpticsCanvasResources -{ - [ComputePipelineResource(ComputeResourceAccess.ReadWrite)] - internal ReadWriteBuffer Horizontal { get; } - - [ComputePipelineResource(ComputeResourceAccess.ReadWrite)] - internal ReadWriteBuffer Convolved { get; } -} - [ComputePipelineHost("_device", 1)] internal sealed partial class WaveOpticsPipelineHost { private readonly GraphicsDevice _device; - [ComputePipelineResource(ComputeResourceAccess.ReadWrite, ComputeResourceRecovery.Recompute)] - private readonly ComputeResourceGroupSlot _canvas = new(); - - [ComputePipeline] - private void RecordFullPipeline( - in ComputeContext context, - [ComputeOwnedResource(nameof(_canvas))] WaveOpticsCanvasResources canvas, - [ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D source, - [ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D output, - [ComputeResource(ComputeResourceAccess.Read)] ReadOnlyBuffer weights, - in WaveOpticsPipeline.PixelRect sourceRect, - in WaveOpticsPipeline.Kernel kernel, - float gain) - { - _ = _device; - - RecordConvolutionStage(in context, canvas, source, weights, in sourceRect, in sourceRect, sourceRect.Width, in kernel); - RecordRenderStage(in context, canvas, output, in sourceRect, sourceRect.Width, gain); - } - [ComputePipeline] private void RecordSourceHash( in ComputeContext context, @@ -65,63 +36,65 @@ internal sealed partial class WaveOpticsPipelineHost [ComputePipeline] private void RecordConvolution( in ComputeContext context, - [ComputeOwnedResource(nameof(_canvas))] WaveOpticsCanvasResources canvas, [ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D source, - [ComputeResource(ComputeResourceAccess.Read)] ReadOnlyBuffer weights, - in WaveOpticsPipeline.PixelRect sourceRect, - in WaveOpticsPipeline.PixelRect rect, - int canvasWidth, - in WaveOpticsPipeline.Kernel kernel) + [ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D output, + [ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer tiles, + [ComputeResource(ComputeResourceAccess.Read)] ReadOnlyBuffer twiddles, + [ComputeResource(ComputeResourceAccess.Read)] ReadOnlyBuffer spectrum, + [ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer report, + [ComputeResource(ComputeResourceAccess.Read)] ReadOnlyBuffer samples, + [ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer store, + in GpuTileJob job) { _ = _device; - RecordConvolutionStage(in context, canvas, source, weights, in sourceRect, in rect, canvasWidth, in kernel); + GpuTileConvolver.Record(in context, source, output, tiles, twiddles, spectrum, report, samples, store, in job); } [ComputePipeline] [ComputeInterop] private void RecordSharedConvolution( in ComputeContext context, - [ComputeOwnedResource(nameof(_canvas))] WaveOpticsCanvasResources canvas, [ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D source, - [ComputeResource(ComputeResourceAccess.Read)] ReadOnlyBuffer weights, - in WaveOpticsPipeline.PixelRect sourceRect, - in WaveOpticsPipeline.PixelRect rect, - int canvasWidth, - in WaveOpticsPipeline.Kernel kernel) + [ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D output, + [ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer tiles, + [ComputeResource(ComputeResourceAccess.Read)] ReadOnlyBuffer twiddles, + [ComputeResource(ComputeResourceAccess.Read)] ReadOnlyBuffer spectrum, + [ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer report, + [ComputeResource(ComputeResourceAccess.Read)] ReadOnlyBuffer samples, + [ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer store, + in GpuTileJob job) { _ = _device; - RecordConvolutionStage(in context, canvas, source, weights, in sourceRect, in rect, canvasWidth, in kernel); + GpuTileConvolver.Record(in context, source, output, tiles, twiddles, spectrum, report, samples, store, in job); } [ComputePipeline] - private void RecordRender( + private void RecordStoredRender( in ComputeContext context, - [ComputeOwnedResource(nameof(_canvas))] WaveOpticsCanvasResources canvas, + [ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer store, [ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D output, in WaveOpticsPipeline.PixelRect rect, - int canvasWidth, float gain) { _ = _device; - RecordRenderStage(in context, canvas, output, in rect, canvasWidth, gain); + GpuTileConvolver.RecordStored(in context, store, output, rect.Width, rect.Height, gain); } [ComputePipeline] [ComputeInterop] - private void RecordSharedRender( + private void RecordSharedStoredRender( in ComputeContext context, - [ComputeOwnedResource(nameof(_canvas))] WaveOpticsCanvasResources canvas, + [ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer store, [ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D output, in WaveOpticsPipeline.PixelRect rect, - int canvasWidth, float gain) { _ = _device; - RecordRenderStage(in context, canvas, output, in rect, canvasWidth, gain); + GpuTileConvolver.RecordStored(in context, store, output, rect.Width, rect.Height, gain); } private static void RecordSourceHashStage( @@ -137,48 +110,6 @@ internal sealed partial class WaveOpticsPipelineHost context.Barrier(scratch); } - private static void RecordConvolutionStage( - in ComputeContext context, - WaveOpticsCanvasResources canvas, - ReadWriteTexture2D source, - ReadOnlyBuffer weights, - in WaveOpticsPipeline.PixelRect sourceRect, - in WaveOpticsPipeline.PixelRect rect, - int canvasWidth, - in WaveOpticsPipeline.Kernel kernel) - { - var top = Math.Max(rect.Y - kernel.Radius, sourceRect.Y); - var bottom = Math.Min(rect.Y + rect.Height + kernel.Radius, sourceRect.Y + sourceRect.Height); - for (var term = 0; term < kernel.Rank; term++) - { - context.For(GetBlockCount(rect.Width, WaveOpticsSettings.HorizontalConvolutionBlock), bottom - top, new HorizontalPassShader( - source, weights, canvas.Horizontal, - WaveOpticsSettings.GetWeightOffset(term, 0), kernel.Radius, - rect.X, top, rect.Width, bottom - top, canvasWidth, - sourceRect.X, sourceRect.Y, sourceRect.Width)); - context.Barrier(canvas.Horizontal); - context.For(rect.Width, GetBlockCount(rect.Height, WaveOpticsSettings.VerticalConvolutionBlock), new VerticalPassShader( - canvas.Horizontal, weights, canvas.Convolved, - WaveOpticsSettings.GetWeightOffset(term, 1), kernel.Radius, - rect.X, rect.Y, rect.Width, rect.Height, canvasWidth, - sourceRect.Y, sourceRect.Height, term > 0)); - context.Barrier(canvas.Horizontal); - context.Barrier(canvas.Convolved); - } - } - private static int GetBlockCount(int length, int block) => (length + block - 1) / block; - - private static void RecordRenderStage( - in ComputeContext context, - WaveOpticsCanvasResources canvas, - ReadWriteTexture2D output, - in WaveOpticsPipeline.PixelRect rect, - int canvasWidth, - float gain) - { - context.For(rect.Width, rect.Height, new RenderShader( - canvas.Convolved, output, rect.X, rect.Y, rect.Width, rect.Height, canvasWidth, gain)); - } } diff --git a/WaveOptics/WaveOpticsSettings.cs b/WaveOptics/WaveOpticsSettings.cs index 9472049..a0c7558 100644 --- a/WaveOptics/WaveOpticsSettings.cs +++ b/WaveOptics/WaveOpticsSettings.cs @@ -8,11 +8,6 @@ internal static class WaveOpticsSettings public const int DefaultKernelRadius = 15; public const int MaximumKernelRadius = 63; public const int MaximumKernelSize = MaximumKernelRadius * 2 + 1; - public const int MaximumRank = MaximumKernelSize; - public const double SeparableResidualRatio = 1e-4; - public const int WeightsLength = MaximumRank * 2 * MaximumKernelSize; - public const int HorizontalConvolutionBlock = 16; - public const int VerticalConvolutionBlock = 8; public const int SourceHashSpan = 16; public const int DefaultCanvasMargin = (DefaultKernelRadius + 3) & ~3; public const int MaximumCanvasSize = 8192; @@ -39,6 +34,4 @@ internal static class WaveOpticsSettings public static int GetKernelSize(int kernelRadius) => kernelRadius * 2 + 1; public static int GetCanvasMargin(int kernelRadius) => Math.Max(DefaultCanvasMargin, (kernelRadius + 3) & ~3); - - public static int GetWeightOffset(int term, int axis) => (term * 2 + axis) * MaximumKernelSize; }