diff --git a/SpectrumColorShift.Tests/ShaderVariantsTests.cs b/SpectrumColorShift.Tests/ShaderVariantsTests.cs new file mode 100644 index 0000000..e90cd40 --- /dev/null +++ b/SpectrumColorShift.Tests/ShaderVariantsTests.cs @@ -0,0 +1,104 @@ +using System.Globalization; +using System.IO; +using System.Runtime.CompilerServices; +using System.Text.RegularExpressions; +using YukkuriMovieMaker.Commons; + +namespace SpectrumColorShift.Tests; + +public sealed partial class ShaderVariantsTests +{ + static string Project { get; } = File.ReadAllText(Path.Combine(Path.GetDirectoryName(Here())!, "..", "SpectrumColorShift.Shader", "SpectrumColorShift.Shader.vcxproj")); + + static string Here([CallerFilePath] string path = "") => path; + + static IEnumerable<(ShaderFamily Family, bool Physical)> SteppedFamilies => [(ShaderVariants.Legacy, false), (ShaderVariants.Physical, true)]; + + [GeneratedRegex(@"[^""]+)""")] + private static partial Regex StepCountsPattern(); + + [GeneratedRegex(@"[^""]+)""")] + private static partial Regex TapCountsPattern(); + + [GeneratedRegex(@"ShaderMode=(?\d+)\s*\$\(OutDir\)(?SpectrumColorShiftPhysicalFilter|SpectrumColorShiftPhysical|SpectrumColorShift)(?[A-Za-z]+)%\((?StepCount|TapCount)\.Identity\)\.cso")] + private static partial Regex VariantPattern(); + + static IEnumerable Listed(Regex pattern) => pattern.Match(Project).Groups["counts"].Value.Split(';').Select(count => int.Parse(count, CultureInfo.InvariantCulture)); + + [Fact] + public void TheStepCountsCoverTheWholeRangeInWholeQuanta() + { + Assert.Equal(0, Spectrum.MinSteps % Spectrum.StepQuantum); + Assert.Equal(0, Spectrum.MaxSteps % Spectrum.StepQuantum); + Assert.Equal(Enumerable.Range(0, (Spectrum.MaxSteps - Spectrum.MinSteps) / Spectrum.StepQuantum + 1).Select(index => Spectrum.MinSteps + index * Spectrum.StepQuantum), ShaderVariants.Legacy.Counts); + Assert.Equal(ShaderVariants.Legacy.Counts, ShaderVariants.Physical.Counts); + } + + [Fact] + public void TheTapCountsCoverTheWholeRangeInWholeQuanta() + { + Assert.Equal(0, SpectralFilter.MaxTaps % SpectralFilter.TapQuantum); + Assert.Equal(Enumerable.Range(1, SpectralFilter.MaxTaps / SpectralFilter.TapQuantum).Select(index => index * SpectralFilter.TapQuantum), ShaderVariants.Filter.Counts); + } + + [Fact] + public void TheShaderProjectCompilesExactlyTheseCounts() + { + Assert.Equal(ShaderVariants.Legacy.Counts, Listed(StepCountsPattern())); + Assert.Equal(ShaderVariants.Filter.Counts, Listed(TapCountsPattern())); + } + + [Fact] + public void TheShaderProjectCompilesEveryModeOfEveryFamilyWithItsEnumValue() + { + var compiled = VariantPattern().Matches(Project).Select(match => (match.Groups["prefix"].Value, match.Groups["mode"].Value, int.Parse(match.Groups["value"].Value, CultureInfo.InvariantCulture), match.Groups["list"].Value)); + var stepped = from mode in ShaderVariants.Legacy.Modes from prefix in new[] { "SpectrumColorShift", "SpectrumColorShiftPhysical" } select (prefix, mode.ToString(), (int)mode, "StepCount"); + var expected = stepped.Append(("SpectrumColorShiftPhysicalFilter", ShiftMode.Linear.ToString(), (int)ShiftMode.Linear, "TapCount")); + + Assert.Equal(expected.Order(), compiled.Order()); + } + + [Fact] + public void EveryModeAndCountHasItsOwnShaderInEveryFamily() + { + var families = new[] { ShaderVariants.Legacy, ShaderVariants.Physical, ShaderVariants.Filter }; + var ids = (from family in families from mode in family.Modes from count in family.Counts select family.Id(mode, count)).ToList(); + + Assert.Equal(families.Sum(family => family.Modes.Count * family.Counts.Count()), ids.Distinct().Count()); + } + + [Fact] + public void StepsShareTheShaderOfTheirPaddedCount() + { + foreach (var (family, _) in SteppedFamilies) + { + foreach (var mode in family.Modes) + { + foreach (var steps in Enumerable.Range(Spectrum.MinSteps, Spectrum.MaxSteps - Spectrum.MinSteps + 1)) + Assert.Equal(family.Id(mode, Spectrum.Padded(steps)), family.Id(mode, steps)); + } + } + } + + [Fact] + public void AModeOutsideAFamilyHasNoShader() + { + Assert.Throws(() => ShaderVariants.Filter.Id(ShiftMode.Radial, 8)); + } + + [Fact] + public void EveryVariantIsShippedAsAResource() + { + foreach (var family in new[] { ShaderVariants.Legacy, ShaderVariants.Physical, ShaderVariants.Filter }) + { + foreach (var mode in family.Modes) + { + foreach (var count in family.Counts) + { + var name = family.ResourceName(mode, count); + Assert.True(PackResourceReader.ReadAllBytes(ShaderResourceUri.Get(name)).Length > 0, name); + } + } + } + } +} diff --git a/SpectrumColorShift.Tests/SpectralFilterTests.cs b/SpectrumColorShift.Tests/SpectralFilterTests.cs index 3131d24..4d6fbb9 100644 --- a/SpectrumColorShift.Tests/SpectralFilterTests.cs +++ b/SpectrumColorShift.Tests/SpectralFilterTests.cs @@ -201,7 +201,7 @@ public sealed class SpectralFilterTests used++; Assert.Equal(0, layout.Taps % SpectralFilter.TapQuantum); Assert.InRange(layout.Taps, SpectralFilter.TapQuantum, SpectralFilter.MaxTaps); - Assert.True(layout.Taps * 20 <= Spectrum.Padded(steps) * 13, $"{layout.Taps} taps for {steps} steps at {distance}"); + Assert.True(layout.Taps <= Spectrum.Padded(steps) * SpectralFilter.MaxTapShare, $"{layout.Taps} taps for {steps} steps at {distance}"); } } @@ -218,11 +218,4 @@ public sealed class SpectralFilterTests Assert.All(taps[(layout.Taps * SpectralFilter.EntriesPerTap)..], entry => Assert.Equal(Vector4.Zero, entry)); } - - [Fact] - public void TheTapCountsRunFromOneQuantumToTheMaximum() - { - Assert.Equal(0, SpectralFilter.MaxTaps % SpectralFilter.TapQuantum); - Assert.Equal(Enumerable.Range(1, SpectralFilter.MaxTaps / SpectralFilter.TapQuantum).Select(index => index * SpectralFilter.TapQuantum), SpectralFilter.Counts); - } } diff --git a/SpectrumColorShift.Tests/StepShadersTests.cs b/SpectrumColorShift.Tests/StepShadersTests.cs deleted file mode 100644 index 185d431..0000000 --- a/SpectrumColorShift.Tests/StepShadersTests.cs +++ /dev/null @@ -1,104 +0,0 @@ -using System.Globalization; -using System.IO; -using System.Runtime.CompilerServices; -using System.Text.RegularExpressions; -using YukkuriMovieMaker.Commons; - -namespace SpectrumColorShift.Tests; - -public sealed partial class StepShadersTests -{ - static string Project { get; } = File.ReadAllText(Path.Combine(Path.GetDirectoryName(Here())!, "..", "SpectrumColorShift.Shader", "SpectrumColorShift.Shader.vcxproj")); - - static string Here([CallerFilePath] string path = "") => path; - - [GeneratedRegex(@"[^""]+)""")] - private static partial Regex CountsPattern(); - - [GeneratedRegex(@"[^""]+)""")] - private static partial Regex TapCountsPattern(); - - [GeneratedRegex(@"ShaderMode=(?\d+)\s*\$\(OutDir\)(?SpectrumColorShiftPhysicalFilter|SpectrumColorShiftPhysical|SpectrumColorShift)(?[A-Za-z]+)%\((?StepCount|TapCount)\.Identity\)\.cso")] - private static partial Regex VariantPattern(); - - [Fact] - public void TheCountsCoverTheWholeRangeInWholeQuanta() - { - Assert.Equal(0, Spectrum.MinSteps % Spectrum.StepQuantum); - Assert.Equal(0, Spectrum.MaxSteps % Spectrum.StepQuantum); - Assert.Equal(Enumerable.Range(0, (Spectrum.MaxSteps - Spectrum.MinSteps) / Spectrum.StepQuantum + 1).Select(index => Spectrum.MinSteps + index * Spectrum.StepQuantum), StepShaders.Counts); - } - - [Fact] - public void TheShaderProjectCompilesExactlyTheseCounts() - { - var compiled = CountsPattern().Match(Project).Groups["counts"].Value.Split(';').Select(count => int.Parse(count, CultureInfo.InvariantCulture)); - - Assert.Equal(StepShaders.Counts, compiled); - } - - [Fact] - public void TheShaderProjectCompilesEveryModeOfBothFamiliesWithItsEnumValue() - { - var compiled = VariantPattern().Matches(Project).Select(match => (match.Groups["prefix"].Value, match.Groups["mode"].Value, int.Parse(match.Groups["value"].Value, CultureInfo.InvariantCulture), match.Groups["list"].Value)); - var stepped = from prefix in new[] { "SpectrumColorShift", "SpectrumColorShiftPhysical" } from mode in StepShaders.Modes select (prefix, mode.ToString(), (int)mode, "StepCount"); - var expected = stepped.Append(("SpectrumColorShiftPhysicalFilter", ShiftMode.Linear.ToString(), (int)ShiftMode.Linear, "TapCount")); - - Assert.Equal(expected.Order(), compiled.Order()); - } - - [Fact] - public void TheShaderProjectCompilesExactlyTheseTapCounts() - { - var compiled = TapCountsPattern().Match(Project).Groups["counts"].Value.Split(';').Select(count => int.Parse(count, CultureInfo.InvariantCulture)); - - Assert.Equal(SpectralFilter.Counts, compiled); - Assert.Equal(SpectralFilter.Counts, StepShaders.FilterCounts); - } - - [Fact] - public void EveryModeAndCountHasItsOwnShaderInEachFamily() - { - var stepped = from physical in new[] { false, true } from mode in StepShaders.Modes from count in StepShaders.Counts select StepShaders.Select(physical, mode, count); - var ids = stepped.Concat(StepShaders.FilterCounts.Select(StepShaders.SelectFilter)).ToList(); - - Assert.Equal(2 * StepShaders.Modes.Count() * StepShaders.Counts.Count() + StepShaders.FilterCounts.Count(), ids.Distinct().Count()); - } - - [Fact] - public void EveryTapCountIsShippedAsAResource() - { - foreach (var count in StepShaders.FilterCounts) - { - var name = StepShaders.FilterResourceName(count); - Assert.True(PackResourceReader.ReadAllBytes(ShaderResourceUri.Get(name)).Length > 0, name); - } - } - - [Theory] - [InlineData(false)] - [InlineData(true)] - public void StepsShareTheShaderOfTheirPaddedCount(bool physical) - { - foreach (var mode in StepShaders.Modes) - { - foreach (var steps in Enumerable.Range(Spectrum.MinSteps, Spectrum.MaxSteps - Spectrum.MinSteps + 1)) - Assert.Equal(StepShaders.Select(physical, mode, Spectrum.Padded(steps)), StepShaders.Select(physical, mode, steps)); - } - } - - [Theory] - [InlineData(false)] - [InlineData(true)] - public void EveryVariantIsShippedAsAResource(bool physical) - { - foreach (var mode in StepShaders.Modes) - { - foreach (var count in StepShaders.Counts) - { - var name = StepShaders.ResourceName(physical, mode, count); - Assert.True(PackResourceReader.ReadAllBytes(ShaderResourceUri.Get(name)).Length > 0, name); - } - } - } -} diff --git a/SpectrumColorShift/Quantum.cs b/SpectrumColorShift/Quantum.cs new file mode 100644 index 0000000..fdf96d8 --- /dev/null +++ b/SpectrumColorShift/Quantum.cs @@ -0,0 +1,6 @@ +namespace SpectrumColorShift; + +internal static class Quantum +{ + public static int RoundUp(int value, int quantum) => (value + quantum - 1) / quantum * quantum; +} diff --git a/SpectrumColorShift/ShaderFamily.cs b/SpectrumColorShift/ShaderFamily.cs new file mode 100644 index 0000000..ac11e51 --- /dev/null +++ b/SpectrumColorShift/ShaderFamily.cs @@ -0,0 +1,69 @@ +using Vortice.Direct2D1; +using YukkuriMovieMaker.Commons; + +namespace SpectrumColorShift; + +internal sealed class ShaderFamily +{ + private readonly string _name; + private readonly int _minimum; + private readonly int _maximum; + private readonly int _quantum; + private readonly int _length; + private readonly Guid[] _ids; + private readonly Lazy[] _bytes; + + public ShaderFamily(string name, IReadOnlyList modes, int minimum, int maximum, int quantum) + { + _name = name; + Modes = modes; + _minimum = minimum; + _maximum = maximum; + _quantum = quantum; + _length = (maximum - minimum) / quantum + 1; + _ids = [.. Enumerable.Range(0, modes.Count * _length).Select(_ => Guid.NewGuid())]; + _bytes = [.. Enumerable.Range(0, modes.Count * _length).Select(index => new Lazy(() => Read(index)))]; + } + + public IReadOnlyList Modes { get; } + + public IEnumerable Counts => Enumerable.Range(0, _length).Select(CountAt); + + public string ResourceName(ShiftMode mode, int count) => $"{_name}{mode}{count}"; + + public Guid Id(ShiftMode mode, int count) => _ids[IndexOf(mode, count)]; + + public byte[] Bytes(ShiftMode mode, int count) => _bytes[IndexOf(mode, count)].Value; + + public void LoadAll(ID2D1EffectContext effectContext) + { + for (var index = 0; index < _ids.Length; index++) + { + var bytes = _bytes[index].Value; + effectContext.LoadPixelShader(_ids[index], bytes, bytes.Length); + } + } + + private int CountAt(int index) => _minimum + index * _quantum; + + private int IndexOf(ShiftMode mode, int count) + { + var offset = Quantum.RoundUp(Math.Clamp(count, _minimum, _maximum) - _minimum, _quantum) / _quantum; + + return IndexOfMode(mode) * _length + offset; + } + + private int IndexOfMode(ShiftMode mode) + { + for (var index = 0; index < Modes.Count; index++) + { + if (Modes[index] == mode) + return index; + } + + throw new ArgumentOutOfRangeException(nameof(mode), mode, null); + } + + private byte[] Read(int index) + => PackResourceReader.ReadAllBytes(ShaderResourceUri.Get(ResourceName(Modes[index / _length], CountAt(index % _length)))); +} diff --git a/SpectrumColorShift/ShaderVariants.cs b/SpectrumColorShift/ShaderVariants.cs new file mode 100644 index 0000000..be3d6a1 --- /dev/null +++ b/SpectrumColorShift/ShaderVariants.cs @@ -0,0 +1,23 @@ +using Vortice.Direct2D1; + +namespace SpectrumColorShift; + +internal static class ShaderVariants +{ + public static ShaderFamily Legacy { get; } = new("SpectrumColorShift", Enum.GetValues(), Spectrum.MinSteps, Spectrum.MaxSteps, Spectrum.StepQuantum); + + public static ShaderFamily Physical { get; } = new("SpectrumColorShiftPhysical", Enum.GetValues(), Spectrum.MinSteps, Spectrum.MaxSteps, Spectrum.StepQuantum); + + public static ShaderFamily Filter { get; } = new("SpectrumColorShiftPhysicalFilter", [ShiftMode.Linear], SpectralFilter.TapQuantum, SpectralFilter.MaxTaps, SpectralFilter.TapQuantum); + + public static byte[] DefaultBytes => Legacy.Bytes(ShiftMode.Linear, Spectrum.DefaultSteps); + + public static ShaderFamily Stepped(bool physical) => physical ? Physical : Legacy; + + public static void LoadAll(ID2D1EffectContext effectContext) + { + Legacy.LoadAll(effectContext); + Physical.LoadAll(effectContext); + Filter.LoadAll(effectContext); + } +} diff --git a/SpectrumColorShift/SpectralFilter.cs b/SpectrumColorShift/SpectralFilter.cs index 1f0ffa2..6104c42 100644 --- a/SpectrumColorShift/SpectralFilter.cs +++ b/SpectrumColorShift/SpectralFilter.cs @@ -8,65 +8,60 @@ internal static class SpectralFilter public const int TapQuantum = 4; public const int MaxTaps = 44; public const int TableLength = MaxTaps * EntriesPerTap; + public const float MaxTapShare = 0.65f; private const float AxisTolerance = 1e-5f; - private const int ShareNumerator = 13; - private const int ShareDenominator = 20; private const int Channels = 3; private const int ValuesPerTap = Channels * Channels + 1; - public static IEnumerable Counts => Enumerable.Range(1, MaxTaps / TapQuantum).Select(index => index * TapQuantum); - public readonly record struct Layout(int Taps, int Origin, bool Vertical); + private readonly record struct Placement(int Floor, double Fraction); + public static Layout Fill(Span table, ReadOnlySpan spectral, int steps, float distance, Vector2 direction) { if (distance == 0f || !TryAxis(direction, out var vertical, out var along)) return default; steps = Spectrum.ClampSteps(steps); - Span floors = stackalloc int[Spectrum.MaxSteps]; - Span fractions = stackalloc double[Spectrum.MaxSteps]; + Span placements = stackalloc Placement[Spectrum.MaxSteps]; + var layout = Plan(spectral, steps, distance * along, vertical, placements); + if (layout.Taps == 0) + return default; + + Span sums = stackalloc double[layout.Taps * ValuesPerTap]; + sums.Clear(); + for (var step = 0; step < steps; step++) + { + var spectralStep = SpectralStep.Read(spectral, step); + var placement = placements[step]; + Add(sums, placement.Floor - layout.Origin, 1d - placement.Fraction, spectralStep); + Add(sums, placement.Floor + 1 - layout.Origin, placement.Fraction, spectralStep); + } + + Write(table, sums, layout.Taps); + + return layout; + } + + private static Layout Plan(ReadOnlySpan spectral, int steps, float signedDistance, bool vertical, Span placements) + { var low = int.MaxValue; var high = int.MinValue; for (var step = 0; step < steps; step++) { - var offset = -(double)spectral[step * Spectrum.EntriesPerStep + 1].W * distance * along; - floors[step] = (int)Math.Floor(offset); - fractions[step] = offset - floors[step]; - low = Math.Min(low, floors[step]); - high = Math.Max(high, floors[step] + 1); + var offset = -(double)SpectralStep.Read(spectral, step).Displacement * signedDistance; + var floor = (int)Math.Floor(offset); + placements[step] = new Placement(floor, offset - floor); + low = Math.Min(low, floor); + high = Math.Max(high, floor + 1); } - var taps = Padded(high - low + 1); - if (taps > MaxTaps || taps * ShareDenominator > Spectrum.Padded(steps) * ShareNumerator) - return default; + var taps = Quantum.RoundUp(high - low + 1, TapQuantum); - Span sums = stackalloc double[MaxTaps * ValuesPerTap]; - sums[..(taps * ValuesPerTap)].Clear(); - for (var step = 0; step < steps; step++) - { - var gain = spectral[step * Spectrum.EntriesPerStep]; - var basis = spectral[step * Spectrum.EntriesPerStep + 1]; - Add(sums, floors[step] - low, 1d - fractions[step], gain, basis); - Add(sums, floors[step] + 1 - low, fractions[step], gain, basis); - } - - for (var tap = 0; tap < taps; tap++) - { - var values = sums.Slice(tap * ValuesPerTap, ValuesPerTap); - table[tap * EntriesPerTap] = new Vector4((float)values[0], (float)values[1], (float)values[2], (float)values[Channels * Channels]); - table[tap * EntriesPerTap + 1] = new Vector4((float)values[3], (float)values[4], (float)values[5], 0f); - table[tap * EntriesPerTap + 2] = new Vector4((float)values[6], (float)values[7], (float)values[8], 0f); - } - - table[(taps * EntriesPerTap)..].Clear(); - - return new Layout(taps, low, vertical); + return taps <= MaxTaps && taps <= Spectrum.Padded(steps) * MaxTapShare ? new Layout(taps, low, vertical) : default; } - private static int Padded(int taps) => (taps + TapQuantum - 1) / TapQuantum * TapQuantum; - private static bool TryAxis(Vector2 direction, out bool vertical, out float along) { vertical = false; @@ -79,17 +74,28 @@ internal static class SpectralFilter return MathF.Abs(direction.X) <= AxisTolerance; } - private static void Add(Span sums, int tap, double weight, Vector4 gain, Vector4 basis) + private static void Add(Span sums, int tap, double weight, SpectralStep step) { var values = sums.Slice(tap * ValuesPerTap, ValuesPerTap); for (var row = 0; row < Channels; row++) { for (var column = 0; column < Channels; column++) - values[row * Channels + column] += weight * Component(gain, row) * Component(basis, column); + values[row * Channels + column] += weight * step.Gain[row] * step.Basis[column]; } - values[Channels * Channels] += weight * gain.W; + values[Channels * Channels] += weight * step.AlphaGain; } - private static float Component(Vector4 vector, int index) => index switch { 0 => vector.X, 1 => vector.Y, _ => vector.Z }; + private static void Write(Span table, ReadOnlySpan sums, int taps) + { + for (var tap = 0; tap < taps; tap++) + { + var values = sums.Slice(tap * ValuesPerTap, ValuesPerTap); + table[tap * EntriesPerTap] = new Vector4((float)values[0], (float)values[1], (float)values[2], (float)values[Channels * Channels]); + table[tap * EntriesPerTap + 1] = new Vector4((float)values[3], (float)values[4], (float)values[5], 0f); + table[tap * EntriesPerTap + 2] = new Vector4((float)values[6], (float)values[7], (float)values[8], 0f); + } + + table[(taps * EntriesPerTap)..].Clear(); + } } diff --git a/SpectrumColorShift/SpectralStep.cs b/SpectrumColorShift/SpectralStep.cs new file mode 100644 index 0000000..e4e7e2d --- /dev/null +++ b/SpectrumColorShift/SpectralStep.cs @@ -0,0 +1,20 @@ +using System.Numerics; + +namespace SpectrumColorShift; + +internal readonly record struct SpectralStep(Vector3 Gain, float AlphaGain, Vector3 Basis, float Displacement) +{ + public static SpectralStep Read(ReadOnlySpan table, int step) + { + var gain = table[step * Spectrum.EntriesPerStep]; + var basis = table[step * Spectrum.EntriesPerStep + 1]; + + return new SpectralStep(new Vector3(gain.X, gain.Y, gain.Z), gain.W, new Vector3(basis.X, basis.Y, basis.Z), basis.W); + } + + public void Write(Span table, int step) + { + table[step * Spectrum.EntriesPerStep] = new Vector4(Gain, AlphaGain); + table[step * Spectrum.EntriesPerStep + 1] = new Vector4(Basis, Displacement); + } +} diff --git a/SpectrumColorShift/Spectrum.cs b/SpectrumColorShift/Spectrum.cs index cd40828..e2bd2df 100644 --- a/SpectrumColorShift/Spectrum.cs +++ b/SpectrumColorShift/Spectrum.cs @@ -16,7 +16,7 @@ internal static class Spectrum public static int ClampSteps(int steps) => Math.Clamp(steps, MinSteps, MaxSteps); - public static int Padded(int steps) => (ClampSteps(steps) + StepQuantum - 1) / StepQuantum * StepQuantum; + public static int Padded(int steps) => Quantum.RoundUp(ClampSteps(steps), StepQuantum); public static float ClampReference(float wavelength) => float.IsNaN(wavelength) ? DefaultReferenceWavelength : Math.Clamp(wavelength, ShortestWavelength, LongestWavelength); @@ -125,8 +125,7 @@ internal static class Spectrum (float)(inverse[0] * x + inverse[1] * y + inverse[2] * z), (float)(inverse[3] * x + inverse[4] * y + inverse[5] * z), (float)(inverse[6] * x + inverse[7] * y + inverse[8] * z)); - table[index * EntriesPerStep] = new Vector4(gain, (float)(y / luminance)); - table[index * EntriesPerStep + 1] = new Vector4(basis, (float)(Displacement(law, wavelength, reference) / norm)); + new SpectralStep(gain, (float)(y / luminance), basis, (float)(Displacement(law, wavelength, reference) / norm)).Write(table, index); } table[(steps * EntriesPerStep)..].Clear(); diff --git a/SpectrumColorShift/SpectrumColorShiftCustomEffect.cs b/SpectrumColorShift/SpectrumColorShiftCustomEffect.cs index 2c29a72..c9b4494 100644 --- a/SpectrumColorShift/SpectrumColorShiftCustomEffect.cs +++ b/SpectrumColorShift/SpectrumColorShiftCustomEffect.cs @@ -221,7 +221,7 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas } } - public EffectImpl() : base(StepShaders.DefaultBytes) + public EffectImpl() : base(ShaderVariants.DefaultBytes) { _cb.Direction = Vector2.UnitX; _cb.Radius = 1f; @@ -233,7 +233,7 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas public override void Initialize(ID2D1EffectContext effectContext, ID2D1TransformGraph transformGraph) { base.Initialize(effectContext, transformGraph); - StepShaders.Load(effectContext); + ShaderVariants.LoadAll(effectContext); } protected override void UpdateConstants() @@ -248,7 +248,7 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas if (_physical) RefreshPhysical(); - var shader = _physical && _filter.Taps > 0 ? StepShaders.SelectFilter(_filter.Taps) : StepShaders.Select(_physical, _mode, _steps); + var shader = _physical && _filter.Taps > 0 ? ShaderVariants.Filter.Id(ShiftMode.Linear, _filter.Taps) : ShaderVariants.Stepped(_physical).Id(_mode, _steps); if (shader != _shader) { drawInformation.SetPixelShader(shader, PixelOptions.None); diff --git a/SpectrumColorShift/StepShaders.cs b/SpectrumColorShift/StepShaders.cs deleted file mode 100644 index e19f007..0000000 --- a/SpectrumColorShift/StepShaders.cs +++ /dev/null @@ -1,89 +0,0 @@ -using Vortice.Direct2D1; -using YukkuriMovieMaker.Commons; - -namespace SpectrumColorShift; - -internal static class StepShaders -{ - private const string LegacyName = "SpectrumColorShift"; - private const string PhysicalName = "SpectrumColorShiftPhysical"; - private const string FilterName = "SpectrumColorShiftPhysicalFilter"; - - private static readonly ShiftMode[] AllModes = Enum.GetValues(); - - private static readonly Variants Legacy = new(LegacyName, AllModes, Spectrum.MinSteps, Spectrum.MaxSteps, Spectrum.StepQuantum); - private static readonly Variants Physical = new(PhysicalName, AllModes, Spectrum.MinSteps, Spectrum.MaxSteps, Spectrum.StepQuantum); - private static readonly Variants Filter = new(FilterName, [ShiftMode.Linear], SpectralFilter.TapQuantum, SpectralFilter.MaxTaps, SpectralFilter.TapQuantum); - - public static IEnumerable Counts => Legacy.Counts; - - public static IEnumerable FilterCounts => Filter.Counts; - - public static IEnumerable Modes => AllModes; - - public static byte[] DefaultBytes => Legacy.Bytes(ShiftMode.Linear, Spectrum.DefaultSteps); - - public static string ResourceName(bool physical, ShiftMode mode, int count) => (physical ? Physical : Legacy).ResourceName(mode, count); - - public static string FilterResourceName(int taps) => Filter.ResourceName(ShiftMode.Linear, taps); - - public static Guid Select(bool physical, ShiftMode mode, int steps) => (physical ? Physical : Legacy).Id(mode, steps); - - public static Guid SelectFilter(int taps) => Filter.Id(ShiftMode.Linear, taps); - - public static void Load(ID2D1EffectContext effectContext) - { - Legacy.Load(effectContext); - Physical.Load(effectContext); - Filter.Load(effectContext); - } - - private sealed class Variants - { - private readonly string _name; - private readonly ShiftMode[] _modes; - private readonly int _minimum; - private readonly int _maximum; - private readonly int _quantum; - private readonly int _length; - private readonly Guid[] _ids; - private readonly Lazy[] _bytes; - - public Variants(string name, ShiftMode[] modes, int minimum, int maximum, int quantum) - { - _name = name; - _modes = modes; - _minimum = minimum; - _maximum = maximum; - _quantum = quantum; - _length = (maximum - minimum) / quantum + 1; - _ids = [.. Enumerable.Range(0, modes.Length * _length).Select(_ => Guid.NewGuid())]; - _bytes = [.. Enumerable.Range(0, modes.Length * _length).Select(index => new Lazy(() => Read(index)))]; - } - - public IEnumerable Counts => Enumerable.Range(0, _length).Select(CountAt); - - public string ResourceName(ShiftMode mode, int count) => $"{_name}{mode}{count}"; - - public Guid Id(ShiftMode mode, int count) => _ids[IndexOf(mode, count)]; - - public byte[] Bytes(ShiftMode mode, int count) => _bytes[IndexOf(mode, count)].Value; - - public void Load(ID2D1EffectContext effectContext) - { - for (var index = 0; index < _ids.Length; index++) - { - var bytes = _bytes[index].Value; - effectContext.LoadPixelShader(_ids[index], bytes, bytes.Length); - } - } - - private int CountAt(int index) => _minimum + index * _quantum; - - private int IndexOf(ShiftMode mode, int count) - => Array.IndexOf(_modes, mode) * _length + (Math.Clamp(count, _minimum, _maximum) - _minimum + _quantum - 1) / _quantum; - - private byte[] Read(int index) - => PackResourceReader.ReadAllBytes(ShaderResourceUri.Get(ResourceName(_modes[index / _length], CountAt(index % _length)))); - } -}