軸に平行な直線のずれを、タップを減らしたフィルターで描いて速くする

・「物理ベース」で軸に平行な短い直線のずれを、ステップの合計を畳み込んだタップのフィルターで描くよう変更-M
このコミットが含まれているのは:
routersys committed 2026-10-13 15:03:11 +09:00
1 親 5579e7a4ed
コミット 6f23e211de
14ファイル変更
+624 -31

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

+4 -4
ファイルの表示
@@ -121,7 +121,7 @@
"frames": [
0
],
"hash": "872E6C69B6384487C4455B575FED039B973D8F0CD0C86E83476DB7F8C4D6C5E9"
"hash": "BFCB9E307B4EC0823A9DA134EC63CC8989F1B978EE89B8CED3576DBB972C2F98"
},
{
"name": "physical-distance-24",
@@ -156,14 +156,14 @@
"frames": [
0
],
"hash": "F118C51CD7930A110A7842776BF9F55035FF91A83974FE525E632101BC23AF3C"
"hash": "7CFAFE05228475887147E95781919A4A961C4C0D467513824B517327A05BB249"
},
{
"name": "physical-reference-450",
"frames": [
0
],
"hash": "4D5C824E9F9A790F546F27F2D6DB891C4AA10CFF3AAF0F5A64E92403C760BDDD"
"hash": "B792437ECF90657E41E3164FAB3A1967548938A7F38747A4B75B177FF7F44ED2"
},
{
"name": "physical-steps-8",
@@ -177,7 +177,7 @@
"frames": [
0
],
"hash": "9491C6D44879AD71A7BAAA7AB7330D31507003C89F06179B056AE8415D19C7A0"
"hash": "C562CBC11A831C10C1ACEFF8742C89FD9695629B753DC31EECC6541042242E8D"
}
]
}
+4
ファイルの表示
@@ -9,6 +9,7 @@ SamplerState LinearSampler : register(s1);
static const int MaxSteps = 64;
static const int TableSize = 128;
static const int FilterTableSize = 132;
static const int ModeRadial = 2;
static const int ModeRotational = 4;
static const int CompiledMode = ShaderMode;
@@ -26,7 +27,10 @@ cbuffer Constants : register(b0)
int mode : packoffset(c2.w);
int steps : packoffset(c3.x);
float spreadScale : packoffset(c3.y);
float filterOrigin : packoffset(c3.z);
int filterVertical : packoffset(c3.w);
float4 samples[TableSize] : packoffset(c4);
float4 taps[FilterTableSize] : packoffset(c132);
};
float2 SamplePosition(float2 scenePosition, float2 offset, float coefficient)
+7
ファイルの表示
@@ -154,11 +154,13 @@
<ItemGroup>
<None Include="SpectrumColorShift.hlsl" />
<None Include="SpectrumColorShiftPhysical.hlsl" />
<None Include="SpectrumColorShiftPhysicalFilter.hlsl" />
<None Include="Physical.hlsli" />
<None Include="Srgb.hlsli" />
</ItemGroup>
<ItemGroup>
<StepCount Include="8;12;16;20;24;28;32;36;40;44;48;52;56;60;64" />
<TapCount Include="4;8;12;16;20;24;28;32;36;40;44" />
</ItemGroup>
<Target Name="AddStepCountShaders" BeforeTargets="FxCompile">
<ItemGroup>
@@ -192,6 +194,11 @@
<PreprocessorDefinitions>StepCount=%(StepCount.Identity);ShaderMode=4</PreprocessorDefinitions>
<ObjectFileOutput>$(OutDir)SpectrumColorShiftPhysicalRotational%(StepCount.Identity).cso</ObjectFileOutput>
</FxCompile>
<FxCompile Include="SpectrumColorShiftPhysicalFilter.hlsl">
<ShaderType>Pixel</ShaderType>
<PreprocessorDefinitions>TapCount=%(TapCount.Identity);ShaderMode=1</PreprocessorDefinitions>
<ObjectFileOutput>$(OutDir)SpectrumColorShiftPhysicalFilterLinear%(TapCount.Identity).cso</ObjectFileOutput>
</FxCompile>
</ItemGroup>
</Target>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+3
ファイルの表示
@@ -26,6 +26,9 @@
<None Include="SpectrumColorShiftPhysical.hlsl">
<Filter>ソース ファイル</Filter>
</None>
<None Include="SpectrumColorShiftPhysicalFilter.hlsl">
<Filter>ソース ファイル</Filter>
</None>
<None Include="Physical.hlsli">
<Filter>ヘッダー ファイル</Filter>
</None>
+29
ファイルの表示
@@ -0,0 +1,29 @@
#ifndef TapCount
#error TapCount must be defined by the build.
#endif
#include "Physical.hlsli"
void AccumulateTap(int tap, float2 position, inout float3 color, inout float alpha)
{
float4 shifted = LinearTexture.SampleLevel(LinearSampler, position, 0);
float4 red = taps[tap * 3];
float4 green = taps[tap * 3 + 1];
float4 blue = taps[tap * 3 + 2];
color += float3(dot(red.rgb, shifted.rgb), dot(green.rgb, shifted.rgb), dot(blue.rgb, shifted.rgb));
alpha += red.w * shifted.a;
}
float4 GatherInside(float2 uv, float2 pixelStep, float2 scenePosition)
{
float2 tapStep = filterVertical != 0 ? float2(0.0, pixelStep.y) : float2(pixelStep.x, 0.0);
float2 first = uv + filterOrigin * tapStep;
float3 color = 0.0;
float alpha = 0.0;
[unroll]
for (int tap = 0; tap < TapCount; tap++)
AccumulateTap(tap, first + tap * tapStep, color, alpha);
return Resolve(color, alpha);
}
+19
ファイルの表示
@@ -69,6 +69,25 @@ public sealed class AllocationTests
Assert.Equal(0, allocated);
}
[Fact]
public void RefreshingTheFilterAllocatesNothing()
{
var impl = new EffectImpl { Physical = 1 };
var step = 0;
var allocated = Allocation.Of(() =>
{
step++;
impl.Angle = step % 4 * 90f;
impl.Distance = step % 40 - 20;
impl.Steps = Spectrum.MinSteps + step % (Spectrum.MaxSteps - Spectrum.MinSteps + 1);
impl.Dispersion = step & 1;
_ = impl.FilterTaps;
});
Assert.Equal(0, allocated);
}
[Theory]
[InlineData(DispersionLaw.Grating)]
[InlineData(DispersionLaw.Prism)]
+84
ファイルの表示
@@ -0,0 +1,84 @@
using System.Numerics;
using YukkuriMovieMaker.Commons;
namespace SpectrumColorShift.Tests;
[Collection("Direct2D")]
public sealed class FilterRenderingTests
{
static Bgra Gradient(int x, int y)
{
if ((x / 5 + y / 7) % 5 == 4)
return Bgra.Transparent;
return new Bgra((byte)(25 + x * 5 % 225), (byte)(15 + y * 9 % 235), (byte)(250 - (x * 2 + y * 3) % 210), (byte)(100 + (x * 3 + y * 5) % 156));
}
public static readonly TheoryData<float, float, int, DispersionLaw> Shifts = new()
{
{ 0f, 8f, 32, DispersionLaw.Grating },
{ 0f, 2.5f, 16, DispersionLaw.Prism },
{ 0f, -9f, 32, DispersionLaw.Grating },
{ 180f, 6f, 24, DispersionLaw.Grating },
{ 90f, 8f, 32, DispersionLaw.Grating },
{ 270f, 5.25f, 20, DispersionLaw.Prism },
{ 0f, 19f, 64, DispersionLaw.Grating },
{ 90f, 0.6f, 12, DispersionLaw.Grating },
{ 0f, 4f, 8, DispersionLaw.Grating },
};
[Theory]
[MemberData(nameof(Shifts))]
public void AnAxisAlignedShiftMatchesTheCpuRendering(float angle, float distance, int steps, DispersionLaw law)
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, 64, 40, Gradient);
using var effect = new SpectrumColorShiftCustomEffect(context);
effect.SetInput(0, source.Bitmap, true);
using var output = effect.Output;
var settings = new ShiftSettings(ShiftMode.Linear, distance, angle, default, 1f, law, 550f, steps, true);
settings.Apply(effect);
var reference = new SpectralReferenceRenderer(source, settings);
var rendering = Rendering.Capture(context, output);
foreach (var (x, y) in rendering.Coordinates())
{
var expected = reference.Pixel(x, y) * 255f;
var actual = rendering[x, y];
Assert.True(
Math.Abs(expected.X - actual.Red) <= 2f && Math.Abs(expected.Y - actual.Green) <= 2f && Math.Abs(expected.Z - actual.Blue) <= 2f && Math.Abs(expected.W - actual.Alpha) <= 2f,
$"({x}, {y}) expected {expected}, actual {actual}");
}
}
[Fact]
public void SwitchingBetweenTheFilterAndTheStepwiseShaderKeepsTheReferenceImage()
{
using var devices = new GraphicsDevices();
using var context = devices.CreateContext();
using var source = new SourceImage(context, 64, 40, Gradient);
using var effect = new SpectrumColorShiftCustomEffect(context);
effect.SetInput(0, source.Bitmap, true);
using var output = effect.Output;
foreach (var (angle, distance) in new[] { (0f, 8f), (30f, 8f), (0f, 8f), (0f, 40f), (90f, 8f), (0f, 0f), (0f, 8f) })
{
var settings = new ShiftSettings(ShiftMode.Linear, distance, angle, default, 1f, DispersionLaw.Grating, 550f, 32, true);
settings.Apply(effect);
var reference = new SpectralReferenceRenderer(source, settings);
var rendering = Rendering.Capture(context, output);
foreach (var (x, y) in rendering.Coordinates())
{
var expected = reference.Pixel(x, y) * 255f;
var actual = rendering[x, y];
Assert.True(
Math.Abs(expected.X - actual.Red) <= 2f && Math.Abs(expected.Y - actual.Green) <= 2f && Math.Abs(expected.Z - actual.Blue) <= 2f && Math.Abs(expected.W - actual.Alpha) <= 2f,
$"angle {angle}, distance {distance}: ({x}, {y}) expected {expected}, actual {actual}");
}
}
}
}
+228
ファイルの表示
@@ -0,0 +1,228 @@
using System.Numerics;
namespace SpectrumColorShift.Tests;
public sealed class SpectralFilterTests
{
const int SignalLength = 256;
static Vector4[] Spectral(int steps, DispersionLaw law, float reference = 550f)
{
var table = new Vector4[Spectrum.SpectralTableLength];
Spectrum.FillSpectral(table, steps, reference, law);
return table;
}
static Vector2 Direction(float degrees)
{
var radians = degrees * MathF.PI / 180f;
return new Vector2(MathF.Cos(radians), MathF.Sin(radians));
}
static Vector4 Signal(int position)
{
var seed = (uint)(position * 2654435761u);
float Next()
{
seed = seed * 1664525u + 1013904223u;
return (seed >> 8) / (float)(1 << 24);
}
return new Vector4(Next(), Next(), Next(), Next());
}
static Vector3 Rgb(Vector4 value) => new(value.X, value.Y, value.Z);
static (Vector3 Color, float Alpha) Stepwise(Vector4[] table, int steps, float distance, float along, int pixel)
{
var color = Vector3.Zero;
var alpha = 0f;
for (var step = 0; step < steps; step++)
{
var gain = table[step * Spectrum.EntriesPerStep];
var basis = table[step * Spectrum.EntriesPerStep + 1];
var offset = -(double)basis.W * distance * along;
var floor = (int)Math.Floor(offset);
var fraction = (float)(offset - floor);
var shifted = Vector4.Lerp(Signal(pixel + floor), Signal(pixel + floor + 1), fraction);
color += Rgb(gain) * Vector3.Dot(Rgb(basis), Rgb(shifted));
alpha += gain.W * shifted.W;
}
return (color, alpha);
}
static (Vector3 Color, float Alpha) Filtered(Vector4[] taps, SpectralFilter.Layout layout, int pixel)
{
var color = Vector3.Zero;
var alpha = 0f;
for (var tap = 0; tap < layout.Taps; tap++)
{
var shifted = Signal(pixel + layout.Origin + tap);
var red = taps[tap * SpectralFilter.EntriesPerTap];
var green = taps[tap * SpectralFilter.EntriesPerTap + 1];
var blue = taps[tap * SpectralFilter.EntriesPerTap + 2];
color += new Vector3(Vector3.Dot(Rgb(red), Rgb(shifted)), Vector3.Dot(Rgb(green), Rgb(shifted)), Vector3.Dot(Rgb(blue), Rgb(shifted)));
alpha += red.W * shifted.W;
}
return (color, alpha);
}
public static readonly TheoryData<float, float, int, DispersionLaw> Shifts = new()
{
{ 0f, 8f, 32, DispersionLaw.Grating },
{ 180f, 8f, 32, DispersionLaw.Grating },
{ 90f, 6.5f, 24, DispersionLaw.Prism },
{ 270f, -5f, 24, DispersionLaw.Grating },
{ 0f, 2f, 16, DispersionLaw.Grating },
{ 0f, 0.4f, 32, DispersionLaw.Prism },
{ 180f, 18.75f, 64, DispersionLaw.Grating },
{ 90f, -12.3f, 48, DispersionLaw.Prism },
};
[Theory]
[MemberData(nameof(Shifts))]
public void TheTapsReproduceTheStepwiseBilinearSum(float angle, float distance, int steps, DispersionLaw law)
{
var table = Spectral(steps, law);
var taps = new Vector4[SpectralFilter.TableLength];
var direction = Direction(angle);
var layout = SpectralFilter.Fill(taps, table, steps, distance, direction);
Assert.True(layout.Taps > 0);
var along = layout.Vertical ? direction.Y : direction.X;
for (var pixel = 64; pixel < 128; pixel++)
{
var expected = Stepwise(table, steps, distance, along, pixel);
var actual = Filtered(taps, layout, pixel);
Assert.True(Vector3.Distance(expected.Color, actual.Color) <= 2e-5f && Math.Abs(expected.Alpha - actual.Alpha) <= 2e-5f, $"pixel {pixel}: {expected} against {actual}");
}
}
[Theory]
[MemberData(nameof(Shifts))]
public void TheTapsSumToTheIdentityAndAUnitAlpha(float angle, float distance, int steps, DispersionLaw law)
{
var table = Spectral(steps, law);
var taps = new Vector4[SpectralFilter.TableLength];
var layout = SpectralFilter.Fill(taps, table, steps, distance, Direction(angle));
var rows = new Vector3[3];
var alpha = 0f;
for (var tap = 0; tap < layout.Taps; tap++)
{
for (var row = 0; row < 3; row++)
rows[row] += Rgb(taps[tap * SpectralFilter.EntriesPerTap + row]);
alpha += taps[tap * SpectralFilter.EntriesPerTap].W;
}
Assert.True(Vector3.Distance(rows[0], Vector3.UnitX) <= 1e-5f, $"{rows[0]}");
Assert.True(Vector3.Distance(rows[1], Vector3.UnitY) <= 1e-5f, $"{rows[1]}");
Assert.True(Vector3.Distance(rows[2], Vector3.UnitZ) <= 1e-5f, $"{rows[2]}");
Assert.Equal(1f, alpha, 1e-5f);
}
[Theory]
[InlineData(0f, false)]
[InlineData(180f, false)]
[InlineData(90f, true)]
[InlineData(270f, true)]
public void TheAxisOfTheDirectionDecidesWhetherTheTapsRunVertically(float angle, bool vertical)
{
var taps = new Vector4[SpectralFilter.TableLength];
var layout = SpectralFilter.Fill(taps, Spectral(32, DispersionLaw.Grating), 32, 8f, Direction(angle));
Assert.True(layout.Taps > 0);
Assert.Equal(vertical, layout.Vertical);
}
[Theory]
[InlineData(1f)]
[InlineData(30f)]
[InlineData(45f)]
[InlineData(89f)]
[InlineData(135f)]
[InlineData(200f)]
public void ADirectionOffTheAxesUsesNoTaps(float angle)
{
var taps = new Vector4[SpectralFilter.TableLength];
var layout = SpectralFilter.Fill(taps, Spectral(32, DispersionLaw.Grating), 32, 8f, Direction(angle));
Assert.Equal(default, layout);
}
[Theory]
[InlineData(0f, 32, 40f)]
[InlineData(0f, 64, 60f)]
[InlineData(0f, 8, 6f)]
[InlineData(90f, 32, 24f)]
public void ADistanceTooLongForTheTapsUsesNoTaps(float angle, int steps, float distance)
{
var taps = new Vector4[SpectralFilter.TableLength];
var layout = SpectralFilter.Fill(taps, Spectral(steps, DispersionLaw.Grating), steps, distance, Direction(angle));
Assert.Equal(default, layout);
}
[Fact]
public void NoDistanceUsesNoTaps()
{
var taps = new Vector4[SpectralFilter.TableLength];
var layout = SpectralFilter.Fill(taps, Spectral(32, DispersionLaw.Grating), 32, 0f, Direction(0f));
Assert.Equal(default, layout);
}
[Fact]
public void TheTapsAreWholeQuantaAndStayWithinTheShareOfTheSteps()
{
var taps = new Vector4[SpectralFilter.TableLength];
var used = 0;
foreach (var steps in new[] { 8, 12, 16, 24, 32, 40, 48, 64 })
{
var table = Spectral(steps, DispersionLaw.Grating);
for (var distance = 0.25f; distance <= 30f; distance += 0.25f)
{
var layout = SpectralFilter.Fill(taps, table, steps, distance, Direction(0f));
if (layout.Taps == 0)
continue;
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(used > 100, $"{used}");
}
[Fact]
public void TheEntriesBeyondTheTapsAreCleared()
{
var taps = new Vector4[SpectralFilter.TableLength];
Array.Fill(taps, new Vector4(7f));
var layout = SpectralFilter.Fill(taps, Spectral(32, DispersionLaw.Grating), 32, 8f, Direction(0f));
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);
}
}
+5 -1
ファイルの表示
@@ -21,7 +21,10 @@ public sealed partial class SpectralShaderContractTests
["mode"] = "Mode",
["steps"] = "Steps",
["spreadScale"] = "SpreadScale",
["filterOrigin"] = "FilterOrigin",
["filterVertical"] = "FilterVertical",
["samples"] = "Samples",
["taps"] = "Taps",
};
static string Source { get; } = ShaderSource("Physical.hlsli");
@@ -58,6 +61,7 @@ public sealed partial class SpectralShaderContractTests
{
Assert.Equal(Spectrum.MaxSteps, Constant("MaxSteps"));
Assert.Equal(Spectrum.SpectralTableLength, Constant("TableSize"));
Assert.Equal(SpectralFilter.TableLength, Constant("FilterTableSize"));
Assert.Equal((int)ShiftMode.Radial, Constant("ModeRadial"));
Assert.Equal((int)ShiftMode.Rotational, Constant("ModeRotational"));
Assert.Equal(ShiftGeometry.MaxRadialShift, Constant("MaxRadialShift"));
@@ -116,6 +120,6 @@ public sealed partial class SpectralShaderContractTests
{
var size = (int)typeof(Unsafe).GetMethod(nameof(Unsafe.SizeOf))!.MakeGenericMethod(ConstantBuffer).Invoke(null, null)!;
Assert.Equal(16 * (4 + Spectrum.SpectralTableLength), size);
Assert.Equal(16 * (4 + Spectrum.SpectralTableLength + SpectralFilter.TableLength), size);
}
}
+38
ファイルの表示
@@ -113,6 +113,44 @@ public sealed class SpectrumColorShiftEffectImplTests
Assert.Equal(new RawRect(-12, -2, 52, 26), invalid);
}
[Theory]
[InlineData(0f, 8f, 1, ShiftMode.Linear, true)]
[InlineData(90f, 8f, 1, ShiftMode.Linear, true)]
[InlineData(180f, -6f, 1, ShiftMode.Linear, true)]
[InlineData(45f, 8f, 1, ShiftMode.Linear, false)]
[InlineData(0f, 40f, 1, ShiftMode.Linear, false)]
[InlineData(0f, 0f, 1, ShiftMode.Linear, false)]
[InlineData(0f, 8f, 1, ShiftMode.Radial, false)]
[InlineData(0f, 8f, 1, ShiftMode.Rotational, false)]
[InlineData(0f, 8f, 0, ShiftMode.Linear, false)]
public void TheFilterIsUsedOnlyForAnAxisAlignedPhysicalShiftThatIsShortEnough(float angle, float distance, int physical, ShiftMode mode, bool used)
{
var impl = new EffectImpl { Mode = (int)mode, Angle = angle, Distance = distance, Physical = physical };
Assert.Equal(used, impl.FilterTaps > 0);
}
[Fact]
public void TheFilterFollowsTheSettingsThatChangeIt()
{
var impl = new EffectImpl { Physical = 1, Distance = 8f };
Assert.True(impl.FilterTaps > 0);
impl.Angle = 30f;
Assert.Equal(0, impl.FilterTaps);
impl.Angle = 0f;
impl.Distance = 60f;
Assert.Equal(0, impl.FilterTaps);
impl.Distance = 8f;
impl.Steps = 8;
Assert.Equal(0, impl.FilterTaps);
impl.Steps = 32;
Assert.True(impl.FilterTaps > 0);
}
[Fact]
public void EveryPropertyCanBeSetBeforeTheEffectIsDrawn()
{
+29 -5
ファイルの表示
@@ -15,7 +15,10 @@ public sealed partial class StepShadersTests
[GeneratedRegex(@"<StepCount Include=""(?<counts>[^""]+)""")]
private static partial Regex CountsPattern();
[GeneratedRegex(@"ShaderMode=(?<value>\d+)</PreprocessorDefinitions>\s*<ObjectFileOutput>\$\(OutDir\)(?<prefix>SpectrumColorShift(?:Physical)?)(?<mode>[A-Za-z]+)%\(StepCount\.Identity\)\.cso")]
[GeneratedRegex(@"<TapCount Include=""(?<counts>[^""]+)""")]
private static partial Regex TapCountsPattern();
[GeneratedRegex(@"ShaderMode=(?<value>\d+)</PreprocessorDefinitions>\s*<ObjectFileOutput>\$\(OutDir\)(?<prefix>SpectrumColorShiftPhysicalFilter|SpectrumColorShiftPhysical|SpectrumColorShift)(?<mode>[A-Za-z]+)%\((?<list>StepCount|TapCount)\.Identity\)\.cso")]
private static partial Regex VariantPattern();
[Fact]
@@ -37,18 +40,39 @@ public sealed partial class StepShadersTests
[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)));
var expected = from prefix in new[] { "SpectrumColorShift", "SpectrumColorShiftPhysical" } from mode in StepShaders.Modes select (prefix, mode.ToString(), (int)mode);
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 ids = (from physical in new[] { false, true } from mode in StepShaders.Modes from count in StepShaders.Counts select StepShaders.Select(physical, mode, count)).ToList();
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(), ids.Distinct().Count());
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]
+95
ファイルの表示
@@ -0,0 +1,95 @@
using System.Numerics;
namespace SpectrumColorShift;
internal static class SpectralFilter
{
public const int EntriesPerTap = 3;
public const int TapQuantum = 4;
public const int MaxTaps = 44;
public const int TableLength = MaxTaps * EntriesPerTap;
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<int> Counts => Enumerable.Range(1, MaxTaps / TapQuantum).Select(index => index * TapQuantum);
public readonly record struct Layout(int Taps, int Origin, bool Vertical);
public static Layout Fill(Span<Vector4> table, ReadOnlySpan<Vector4> 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<int> floors = stackalloc int[Spectrum.MaxSteps];
Span<double> fractions = stackalloc double[Spectrum.MaxSteps];
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 taps = Padded(high - low + 1);
if (taps > MaxTaps || taps * ShareDenominator > Spectrum.Padded(steps) * ShareNumerator)
return default;
Span<double> 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);
}
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;
along = direction.X;
if (MathF.Abs(direction.Y) <= AxisTolerance)
return true;
vertical = true;
along = direction.Y;
return MathF.Abs(direction.X) <= AxisTolerance;
}
private static void Add(Span<double> sums, int tap, double weight, Vector4 gain, Vector4 basis)
{
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[Channels * Channels] += weight * gain.W;
}
private static float Component(Vector4 vector, int index) => index switch { 0 => vector.X, 1 => vector.Y, _ => vector.Z };
}
+43 -4
ファイルの表示
@@ -80,6 +80,8 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
private int _steps = Spectrum.DefaultSteps;
private bool _tableStale = true;
private bool _spectralStale = true;
private bool _filterStale = true;
private SpectralFilter.Layout _filter;
private bool _physical;
private Guid _shader = GUID_PixelShader;
@@ -90,6 +92,7 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
set
{
_cb.Distance = Sanitize(value, -MaxInputPixel, MaxInputPixel);
_filterStale = true;
UpdateConstants();
}
}
@@ -102,6 +105,7 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
{
_mode = value is (int)ShiftMode.Radial or (int)ShiftMode.Rotational ? (ShiftMode)value : ShiftMode.Linear;
_cb.Mode = (int)_mode;
_filterStale = true;
UpdateConstants();
}
}
@@ -114,6 +118,7 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
{
var radians = float.IsFinite(value) ? value * MathF.PI / 180f : 0f;
_cb.Direction = new Vector2(MathF.Cos(radians), MathF.Sin(radians));
_filterStale = true;
UpdateConstants();
}
}
@@ -204,6 +209,18 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
}
}
internal int FilterTaps
{
get
{
if (!_physical)
return 0;
RefreshPhysical();
return _filter.Taps;
}
}
public EffectImpl() : base(StepShaders.DefaultBytes)
{
_cb.Direction = Vector2.UnitX;
@@ -228,7 +245,10 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
{
_cb.SpreadScale = ShiftGeometry.Spread(_mode, _cb.Distance, _cb.Radius);
var shader = StepShaders.Select(_physical, _mode, _steps);
if (_physical)
RefreshPhysical();
var shader = _physical && _filter.Taps > 0 ? StepShaders.SelectFilter(_filter.Taps) : StepShaders.Select(_physical, _mode, _steps);
if (shader != _shader)
{
drawInformation.SetPixelShader(shader, PixelOptions.None);
@@ -258,14 +278,24 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
drawInformation!.SetPixelShaderConstantBuffer(_cb);
}
private void SendPhysicalConstants()
private void RefreshPhysical()
{
if (_spectralStale)
{
Spectrum.FillSpectral(_physicalCb.Samples, _steps, _referenceWavelength, _dispersion);
_spectralStale = false;
_filterStale = true;
}
if (_filterStale)
{
_filter = _mode == ShiftMode.Linear ? SpectralFilter.Fill(_physicalCb.Taps, _physicalCb.Samples, _steps, _cb.Distance, _cb.Direction) : default;
_filterStale = false;
}
}
private void SendPhysicalConstants()
{
_physicalCb.InputBounds = _cb.InputBounds;
_physicalCb.Direction = _cb.Direction;
_physicalCb.Center = _cb.Center;
@@ -275,6 +305,8 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
_physicalCb.Mode = _cb.Mode;
_physicalCb.Steps = Spectrum.Padded(_steps);
_physicalCb.SpreadScale = _cb.SpreadScale;
_physicalCb.FilterOrigin = _filter.Origin;
_physicalCb.FilterVertical = _filter.Vertical ? 1 : 0;
drawInformation!.SetPixelShaderConstantBuffer(_physicalCb);
}
@@ -338,6 +370,12 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
private Vector4 _element;
}
[InlineArray(SpectralFilter.TableLength)]
private struct FilterTapTable
{
private Vector4 _element;
}
[StructLayout(LayoutKind.Sequential)]
private struct PhysicalConstantBuffer
{
@@ -350,9 +388,10 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
public int Mode;
public int Steps;
public float SpreadScale;
public float Pad1;
public float Pad2;
public float FilterOrigin;
public int FilterVertical;
public SpectralSampleTable Samples;
public FilterTapTable Taps;
}
[StructLayout(LayoutKind.Sequential)]
+36 -17
ファイルの表示
@@ -7,50 +7,67 @@ internal static class StepShaders
{
private const string LegacyName = "SpectrumColorShift";
private const string PhysicalName = "SpectrumColorShiftPhysical";
private const string FilterName = "SpectrumColorShiftPhysicalFilter";
private static readonly Variants Legacy = new(LegacyName);
private static readonly Variants Physical = new(PhysicalName);
private static readonly ShiftMode[] AllModes = Enum.GetValues<ShiftMode>();
public static IEnumerable<int> Counts => Enumerable.Range(0, Variants.CountLength).Select(Variants.CountAt);
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<ShiftMode> Modes => Variants.Modes;
public static IEnumerable<int> Counts => Legacy.Counts;
public static IEnumerable<int> FilterCounts => Filter.Counts;
public static IEnumerable<ShiftMode> 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
{
public static ShiftMode[] Modes { get; } = Enum.GetValues<ShiftMode>();
public static int CountLength { get; } = (Spectrum.MaxSteps - Spectrum.MinSteps) / Spectrum.StepQuantum + 1;
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<byte[]>[] _bytes;
public Variants(string name)
public Variants(string name, ShiftMode[] modes, int minimum, int maximum, int quantum)
{
_name = name;
_ids = [.. Enumerable.Range(0, Modes.Length * CountLength).Select(_ => Guid.NewGuid())];
_bytes = [.. Enumerable.Range(0, Modes.Length * CountLength).Select(index => new Lazy<byte[]>(() => Read(index)))];
_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<byte[]>(() => Read(index)))];
}
public static int CountAt(int index) => Spectrum.MinSteps + index * Spectrum.StepQuantum;
public IEnumerable<int> Counts => Enumerable.Range(0, _length).Select(CountAt);
public string ResourceName(ShiftMode mode, int count) => $"{_name}{mode}{count}";
public Guid Id(ShiftMode mode, int steps) => _ids[IndexOf(mode, steps)];
public Guid Id(ShiftMode mode, int count) => _ids[IndexOf(mode, count)];
public byte[] Bytes(ShiftMode mode, int steps) => _bytes[IndexOf(mode, steps)].Value;
public byte[] Bytes(ShiftMode mode, int count) => _bytes[IndexOf(mode, count)].Value;
public void Load(ID2D1EffectContext effectContext)
{
@@ -61,10 +78,12 @@ internal static class StepShaders
}
}
private static int IndexOf(ShiftMode mode, int steps)
=> Array.IndexOf(Modes, mode) * CountLength + (Spectrum.Padded(steps) - Spectrum.MinSteps) / Spectrum.StepQuantum;
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 / CountLength], CountAt(index % CountLength))));
=> PackResourceReader.ReadAllBytes(ShaderResourceUri.Get(ResourceName(_modes[index / _length], CountAt(index % _length))));
}
}