物理ベースの色の計算を、sRGBの変換式と光の量での補間にする
・「物理ベース」の色の足し合わせと画素の間の補間を、sRGBの変換式による光の量で行うよう変更-M
このコミットが含まれているのは:
10ファイル変更
+290
-70
検索条件に一致するファイルはありません
@@ -28,14 +28,14 @@ internal sealed class SpectralReferenceRenderer
|
||||
public Vector4 Pixel(int x, int y)
|
||||
{
|
||||
var position = new Vector2(x + 0.5f, y + 0.5f);
|
||||
var original = Covered(position);
|
||||
var original = Srgb.EncodePremultiplied(Covered(position));
|
||||
if (settings.Distance == 0f || settings.Strength <= 0f)
|
||||
return original;
|
||||
|
||||
var (color, alpha) = Accumulated(position);
|
||||
var positive = Vector3.Max(color, Vector3.Zero);
|
||||
var resolved = Math.Clamp(Math.Max(alpha, Math.Max(positive.X, Math.Max(positive.Y, positive.Z))), 0f, 1f);
|
||||
var result = new Vector4(Vector3.SquareRoot(Vector3.Min(positive, new Vector3(resolved)) * resolved), resolved);
|
||||
var result = Srgb.EncodePremultiplied(new Vector4(positive, resolved));
|
||||
|
||||
return Vector4.Lerp(original, result, Math.Clamp(settings.Strength, 0f, 1f));
|
||||
}
|
||||
@@ -49,7 +49,7 @@ internal sealed class SpectralReferenceRenderer
|
||||
var gain = table[index * Spectrum.EntriesPerStep];
|
||||
var basis = table[index * Spectrum.EntriesPerStep + 1];
|
||||
var target = ShiftReference.SamplePosition(settings.Mode, position, basis.W, settings.Distance, direction, center, radius);
|
||||
var lit = Linear(target);
|
||||
var lit = Covered(target);
|
||||
color += new Vector3(gain.X, gain.Y, gain.Z) * Vector3.Dot(new Vector3(basis.X, basis.Y, basis.Z), new Vector3(lit.X, lit.Y, lit.Z));
|
||||
alpha += gain.W * lit.W;
|
||||
}
|
||||
@@ -57,25 +57,14 @@ internal sealed class SpectralReferenceRenderer
|
||||
return (color, alpha);
|
||||
}
|
||||
|
||||
Vector4 Linear(Vector2 target)
|
||||
{
|
||||
var (raw, coverage) = Sample(target);
|
||||
if (raw.W <= 0f)
|
||||
return Vector4.Zero;
|
||||
|
||||
var premultiplied = new Vector3(raw.X, raw.Y, raw.Z);
|
||||
|
||||
return new Vector4(premultiplied * premultiplied / raw.W, raw.W) * coverage;
|
||||
}
|
||||
|
||||
Vector4 Covered(Vector2 target)
|
||||
{
|
||||
var (raw, coverage) = Sample(target);
|
||||
var (light, coverage) = Sample(target);
|
||||
|
||||
return raw * coverage;
|
||||
return light * coverage;
|
||||
}
|
||||
|
||||
(Vector4 Raw, float Coverage) Sample(Vector2 target)
|
||||
(Vector4 Light, float Coverage) Sample(Vector2 target)
|
||||
{
|
||||
var size = new Vector2(source.Width, source.Height);
|
||||
var clamped = Vector2.Clamp(target, new Vector2(0.5f), size - new Vector2(0.5f));
|
||||
@@ -102,6 +91,6 @@ internal sealed class SpectralReferenceRenderer
|
||||
{
|
||||
var pixel = source[Math.Clamp(x, 0, source.Width - 1), Math.Clamp(y, 0, source.Height - 1)];
|
||||
|
||||
return new Vector4(pixel.Red, pixel.Green, pixel.Blue, pixel.Alpha) / 255f;
|
||||
return Srgb.DecodePremultiplied(new Vector4(pixel.Red, pixel.Green, pixel.Blue, pixel.Alpha) / 255f);
|
||||
}
|
||||
}
|
||||
@@ -106,13 +106,33 @@ public sealed class SpectralRenderingTests
|
||||
var basis = table[step * Spectrum.EntriesPerStep + 1];
|
||||
var position = index + 0.5 - basis.W * settings.Distance * axisDirection;
|
||||
var value = Math.Clamp(Seam + 0.5 - position, 0d, 1d);
|
||||
sum += (channel switch { 0 => gain.X, 1 => gain.Y, _ => gain.Z }) * (basis.X + basis.Y + basis.Z) * value * value;
|
||||
sum += (channel switch { 0 => gain.X, 1 => gain.Y, _ => gain.Z }) * (basis.X + basis.Y + basis.Z) * value;
|
||||
}
|
||||
|
||||
return (byte)Math.Round(Math.Sqrt(Math.Clamp(sum, 0d, 1d)) * 255d);
|
||||
return (byte)Math.Round(Srgb.Encode(Math.Clamp(sum, 0d, 1d)) * 255d);
|
||||
};
|
||||
}
|
||||
|
||||
static Bgra Blob(int x, int y)
|
||||
{
|
||||
var distance = Math.Sqrt(Math.Pow(x + 0.5 - 64, 2) + Math.Pow(y + 0.5 - 64, 2));
|
||||
var coverage = Math.Clamp((26 - distance) / 8, 0d, 1d);
|
||||
|
||||
return new Bgra(160, 160, 160, (byte)Math.Round(coverage * 255d));
|
||||
}
|
||||
|
||||
static Vector3 TotalLight(IEnumerable<Bgra> pixels)
|
||||
{
|
||||
var total = Vector3.Zero;
|
||||
foreach (var pixel in pixels)
|
||||
{
|
||||
var light = Srgb.DecodePremultiplied(new Vector4(pixel.Red, pixel.Green, pixel.Blue, pixel.Alpha) / 255f);
|
||||
total += new Vector3(light.X, light.Y, light.Z);
|
||||
}
|
||||
|
||||
return total;
|
||||
}
|
||||
|
||||
static Func<int, byte> Channel(Rendering rendering, int channel, Func<int, (int X, int Y)> position)
|
||||
=> index =>
|
||||
{
|
||||
@@ -145,6 +165,22 @@ public sealed class SpectralRenderingTests
|
||||
Assert.All(rendering.Coordinates(), point => Assert.Equal(source[point.X, point.Y], rendering[point.X, point.Y]));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(255)]
|
||||
[InlineData(200)]
|
||||
[InlineData(128)]
|
||||
[InlineData(7)]
|
||||
public void EveryGrayLevelSurvivesTheRoundTripThroughLinearLight(int alpha)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, 256, 4, (x, _) => new Bgra((byte)x, (byte)x, (byte)x, (byte)alpha));
|
||||
|
||||
var rendering = Render(context, source, Settings(Distance: 0f));
|
||||
|
||||
Assert.All(rendering.Coordinates(), point => Assert.Equal(source[point.X, point.Y], rendering[point.X, point.Y]));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Modes))]
|
||||
public void WithoutStrengthTheImageIsUntouchedAndTheSpillStaysTransparent(ShiftMode mode)
|
||||
@@ -274,6 +310,50 @@ public sealed class SpectralRenderingTests
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(10f, 0f)]
|
||||
[InlineData(10f, 37f)]
|
||||
[InlineData(18f, 90f)]
|
||||
[InlineData(-14f, 200f)]
|
||||
public void ALinearShiftLosesNoLightAndGainsOnlyWhatClippingAdds(float distance, float angle)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, 128, 128, Blob);
|
||||
|
||||
var rendering = Render(context, source, Settings(Distance: distance, Angle: angle));
|
||||
|
||||
var before = TotalLight(Enumerable.Range(0, source.Width * source.Height).Select(index => source[index % source.Width, index / source.Width]));
|
||||
var after = TotalLight(rendering.Coordinates().Select(point => rendering[point.X, point.Y]));
|
||||
var ratio = after / before;
|
||||
foreach (var (channel, value) in new[] { ("red", ratio.X), ("green", ratio.Y), ("blue", ratio.Z) })
|
||||
Assert.True(value is >= 0.995f and <= 1.08f, $"{channel} {value}");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(8f, 0f, DispersionLaw.Grating, 32)]
|
||||
[InlineData(8f, 180f, DispersionLaw.Prism, 33)]
|
||||
[InlineData(16f, 0f, DispersionLaw.Grating, 64)]
|
||||
public void TheEdgeProfileOfEachChannelFollowsTheOneDimensionalModel(float distance, float angle, DispersionLaw law, int steps)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, 64, 32, HalfAndHalf);
|
||||
var settings = Settings(Distance: distance, Angle: angle, Dispersion: law, Steps: steps);
|
||||
var direction = MathF.Cos(angle * MathF.PI / 180f);
|
||||
var margin = (int)MathF.Ceiling(MathF.Abs(distance)) + 1;
|
||||
|
||||
var rendering = Render(context, source, settings);
|
||||
|
||||
for (var channel = 0; channel < 3; channel++)
|
||||
{
|
||||
var actual = Channel(rendering, channel, x => (x, 16));
|
||||
var expected = ExpectedProfile(settings, channel, direction);
|
||||
for (var x = margin; x < 64 - margin; x++)
|
||||
Assert.True(Math.Abs(actual(x) - expected(x)) <= 2, $"channel {channel}, x {x}: {actual(x)} against {expected(x)}");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BlueMovesAheadOfGreenAndRedAlongTheDirection()
|
||||
{
|
||||
@@ -286,9 +366,7 @@ public sealed class SpectralRenderingTests
|
||||
var green = Crossing(Channel(rendering, 1, x => (x, 16)), 4, 58);
|
||||
var blue = Crossing(Channel(rendering, 2, x => (x, 16)), 4, 58);
|
||||
|
||||
Assert.InRange(red, 27d, 30.5d);
|
||||
Assert.InRange(green, 31.5d, 33.5d);
|
||||
Assert.InRange(blue, 36d, 38.5d);
|
||||
Assert.True(red is >= 28d and <= 30.5d && green is >= 32.5d and <= 34.5d && blue is >= 37d and <= 39.5d, $"red {red}, green {green}, blue {blue}");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -321,7 +399,7 @@ public sealed class SpectralRenderingTests
|
||||
var gratingWidth = EdgeWidth(Channel(grating, 0, x => (x, 16)), 4, 58);
|
||||
var prismWidth = EdgeWidth(Channel(prism, 0, x => (x, 16)), 4, 58);
|
||||
|
||||
Assert.True(prismWidth < gratingWidth * 0.6, $"prism {prismWidth}, grating {gratingWidth}");
|
||||
Assert.True(prismWidth < gratingWidth * 0.7, $"prism {prismWidth}, grating {gratingWidth}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -24,20 +24,34 @@ public sealed partial class SpectralShaderContractTests
|
||||
["samples"] = "Samples",
|
||||
};
|
||||
|
||||
static string Source { get; } = File.ReadAllText(Path.Combine(Path.GetDirectoryName(Here())!, "..", "SpectrumColorShift.Shader", "SpectrumColorShiftPhysical.hlsl"));
|
||||
static string Source { get; } = ShaderSource("SpectrumColorShiftPhysical.hlsl");
|
||||
|
||||
static string SrgbSource { get; } = ShaderSource("Srgb.hlsli");
|
||||
|
||||
static string ShaderSource(string name) => File.ReadAllText(Path.Combine(Path.GetDirectoryName(Here())!, "..", "SpectrumColorShift.Shader", name));
|
||||
|
||||
static string Here([CallerFilePath] string path = "") => path;
|
||||
|
||||
static int LinearInput { get; } = (int)typeof(SpectrumColorShiftCustomEffect).GetField("LinearInput", BindingFlags.NonPublic | BindingFlags.Static)!.GetRawConstantValue()!;
|
||||
|
||||
static Type ConstantBuffer => typeof(EffectImpl).GetNestedType("PhysicalConstantBuffer", BindingFlags.NonPublic)!;
|
||||
|
||||
[GeneratedRegex(@"static const (?:int|float) (?<name>\w+) = (?<value>[0-9.]+);")]
|
||||
private static partial Regex ConstantPattern();
|
||||
|
||||
[GeneratedRegex(@"Texture2D\s+LinearTexture\s*:\s*register\(t(?<register>\d+)\)")]
|
||||
private static partial Regex TexturePattern();
|
||||
|
||||
[GeneratedRegex(@"float4\s+\w+\s*:\s*TEXCOORD(?<index>\d+)")]
|
||||
private static partial Regex CoordinatePattern();
|
||||
|
||||
[GeneratedRegex(@"^\s*(?:float4|float2|float|int)\s+(?<name>\w+)(?:\[\w+\])?\s*:\s*packoffset\(c(?<register>\d+)(?:\.(?<component>[xyzw]))?\);", RegexOptions.Multiline)]
|
||||
private static partial Regex MemberPattern();
|
||||
|
||||
static float Constant(string name)
|
||||
=> float.Parse(ConstantPattern().Matches(Source).Single(match => match.Groups["name"].Value == name).Groups["value"].Value, CultureInfo.InvariantCulture);
|
||||
static float Constant(string name) => Constant(Source, name);
|
||||
|
||||
static float Constant(string source, string name)
|
||||
=> float.Parse(ConstantPattern().Matches(source).Single(match => match.Groups["name"].Value == name).Groups["value"].Value, CultureInfo.InvariantCulture);
|
||||
|
||||
[Fact]
|
||||
public void TheShaderAndTheEffectAgreeOnTheConstants()
|
||||
@@ -50,6 +64,41 @@ public sealed partial class SpectralShaderContractTests
|
||||
Assert.Equal(ShiftGeometry.MaxRadialShift, Constant("MaxRadialShift"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheShaderReadsTheTextureOfTheLinearizedInput()
|
||||
{
|
||||
Assert.Equal(LinearInput, int.Parse(TexturePattern().Match(Source).Groups["register"].Value, CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheShaderDeclaresTheTextureCoordinateOfEveryInputUpToTheOneItReads()
|
||||
{
|
||||
var declared = CoordinatePattern().Matches(Source).Select(match => int.Parse(match.Groups["index"].Value, CultureInfo.InvariantCulture));
|
||||
|
||||
Assert.Equal(Enumerable.Range(0, LinearInput + 1), declared.Order());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("DecodeThreshold", 0.04045f)]
|
||||
[InlineData("EncodeThreshold", 0.0031308f)]
|
||||
[InlineData("LowSlope", 12.92f)]
|
||||
[InlineData("Offset", 0.055f)]
|
||||
[InlineData("Scale", 1.055f)]
|
||||
[InlineData("Exponent", 2.4f)]
|
||||
public void TheSrgbHeaderHoldsTheStandardTransferConstants(string name, float expected)
|
||||
=> Assert.Equal(expected, Constant(SrgbSource, name));
|
||||
|
||||
[Fact]
|
||||
public void TheSrgbCurvesMeetAtTheThresholds()
|
||||
{
|
||||
var slope = Constant(SrgbSource, "LowSlope");
|
||||
var linearEnd = Constant(SrgbSource, "EncodeThreshold");
|
||||
var power = Constant(SrgbSource, "Scale") * MathF.Pow(linearEnd, 1f / Constant(SrgbSource, "Exponent")) - Constant(SrgbSource, "Offset");
|
||||
|
||||
Assert.Equal(Constant(SrgbSource, "DecodeThreshold"), slope * linearEnd, 1e-5f);
|
||||
Assert.Equal(slope * linearEnd, power, 1e-5f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheConstantBufferMatchesTheShaderLayout()
|
||||
{
|
||||
|
||||
@@ -69,6 +69,30 @@ public sealed class SpectrumColorShiftEffectImplTests
|
||||
Assert.Equal(new RawRect(-7, -2, 57, 52), requested);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheLegacyShaderRequestsOnlyTheSourceInput()
|
||||
{
|
||||
var impl = new EffectImpl { Distance = 5f };
|
||||
Map(impl, new RawRect(0, 0, 40, 24));
|
||||
var inputs = new RawRect[2];
|
||||
|
||||
impl.MapOutputRectToInputRects(new RawRect(0, 0, 50, 50), inputs);
|
||||
|
||||
Assert.Equal([new RawRect(-7, -2, 57, 52), default], inputs);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ThePhysicalShaderRequestsOnlyTheLinearizedInput()
|
||||
{
|
||||
var impl = new EffectImpl { Distance = 5f, Physical = 1 };
|
||||
Map(impl, new RawRect(0, 0, 40, 24));
|
||||
var inputs = new RawRect[2];
|
||||
|
||||
impl.MapOutputRectToInputRects(new RawRect(0, 0, 50, 50), inputs);
|
||||
|
||||
Assert.Equal([default, new RawRect(-7, -2, 57, 52)], inputs);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ANoInputRequestIsIgnored()
|
||||
{
|
||||
@@ -103,6 +127,7 @@ public sealed class SpectrumColorShiftEffectImplTests
|
||||
Dispersion = (int)DispersionLaw.Prism,
|
||||
ReferenceWavelength = 480f,
|
||||
Steps = 16,
|
||||
Physical = 1,
|
||||
};
|
||||
|
||||
Assert.Equal(12f, impl.Distance);
|
||||
@@ -114,5 +139,6 @@ public sealed class SpectrumColorShiftEffectImplTests
|
||||
Assert.Equal((int)DispersionLaw.Prism, impl.Dispersion);
|
||||
Assert.Equal(480f, impl.ReferenceWavelength);
|
||||
Assert.Equal(16, impl.Steps);
|
||||
Assert.Equal(1, impl.Physical);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using System.Numerics;
|
||||
|
||||
namespace SpectrumColorShift.Tests;
|
||||
|
||||
internal static class Srgb
|
||||
{
|
||||
public static double Decode(double encoded)
|
||||
=> encoded <= 0.04045 ? encoded / 12.92 : Math.Pow((encoded + 0.055) / 1.055, 2.4);
|
||||
|
||||
public static double Encode(double linear)
|
||||
=> linear <= 0.0031308 ? linear * 12.92 : 1.055 * Math.Pow(linear, 1d / 2.4) - 0.055;
|
||||
|
||||
public static Vector3 Decode(Vector3 encoded)
|
||||
=> new((float)Decode(encoded.X), (float)Decode(encoded.Y), (float)Decode(encoded.Z));
|
||||
|
||||
public static Vector3 Encode(Vector3 linear)
|
||||
=> new((float)Encode(linear.X), (float)Encode(linear.Y), (float)Encode(linear.Z));
|
||||
|
||||
public static Vector4 DecodePremultiplied(Vector4 encoded)
|
||||
=> encoded.W <= 0f ? Vector4.Zero : new Vector4(Decode(Straight(encoded)) * encoded.W, encoded.W);
|
||||
|
||||
public static Vector4 EncodePremultiplied(Vector4 linear)
|
||||
=> linear.W <= 0f ? Vector4.Zero : new Vector4(Encode(Straight(linear)) * linear.W, linear.W);
|
||||
|
||||
static Vector3 Straight(Vector4 premultiplied)
|
||||
=> Vector3.Clamp(new Vector3(premultiplied.X, premultiplied.Y, premultiplied.Z) / premultiplied.W, Vector3.Zero, Vector3.One);
|
||||
}
|
||||
新しいイシューから参照
ユーザーをブロックする