物理ベースの色の計算を、sRGBの変換式と光の量での補間にする

・「物理ベース」の色の足し合わせと画素の間の補間を、sRGBの変換式による光の量で行うよう変更-M
このコミットが含まれているのは:
routersys committed 2026-10-12 22:23:09 +09:00
1 親 cd9b17e057
コミット 709ec11404
10ファイル変更
+290 -70

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

+9 -9
ファイルの表示
@@ -121,63 +121,63 @@
"frames": [
0
],
"hash": "16D9D6B646BCF4AFA1B3C6D959487EBA73257EB967478A24560CC0A7156A3BB9"
"hash": "872E6C69B6384487C4455B575FED039B973D8F0CD0C86E83476DB7F8C4D6C5E9"
},
{
"name": "physical-distance-24",
"frames": [
0
],
"hash": "DAE1580D442344C99B8492735767A627DD7F61CA41F72FF655BD996D8F10518B"
"hash": "C3EFCE6A5A4E9A737926D359AF302FFA10D15ED56E58EA8EB040ADAEF6F083D7"
},
{
"name": "physical-distance-100-steps-64",
"frames": [
0
],
"hash": "E67EAB5E79A39DD2A148E88699749B87791A446E9EBA60552DFD1899F923B39C"
"hash": "514B1C1FF62D4C5F28AFC9D4158B5182B7A55E7CDBFC1D02531D86E22C0019AC"
},
{
"name": "physical-radial-24",
"frames": [
0
],
"hash": "AECA3F2441B29DF59BC63142B34F6A6E9F1BC59F7FD3599D4EA947AE34C392DC"
"hash": "09C9FFD797F751E21CDB8A1AC4487193D0C2701FDD404F91B3AD452D1D5B61C1"
},
{
"name": "physical-rotational-24",
"frames": [
0
],
"hash": "B9ECB23D9F4AC9BD4D720331FAB459BBEDF2CC9137BE2AB4E2830955C33D6A75"
"hash": "7A86209757529922BB33B2C5060E80A7DEC7D853F1F45536FEEB09C53D15A2D2"
},
{
"name": "physical-prism",
"frames": [
0
],
"hash": "17C539709E188E6DECF8E0DB4C1B0974CC118F5D063845CE9AE863BE51464482"
"hash": "F118C51CD7930A110A7842776BF9F55035FF91A83974FE525E632101BC23AF3C"
},
{
"name": "physical-reference-450",
"frames": [
0
],
"hash": "0B0D9C03EA35F2F301574FEE3EA68828FF7689A78FAEC216D3BC27B0135D33CE"
"hash": "4D5C824E9F9A790F546F27F2D6DB891C4AA10CFF3AAF0F5A64E92403C760BDDD"
},
{
"name": "physical-steps-8",
"frames": [
0
],
"hash": "F5507D6B98A2D4AE9622DE0F478B5CC28BA7C78A29DB9DA2504658E17B5BDFDF"
"hash": "160C24673BB43AE035287C22DB8366D0DB89D9D27CA65F9473E3DF3469BB747C"
},
{
"name": "physical-strength-50",
"frames": [
0
],
"hash": "0EE7E79190F70A7B2CC0D24C89512E8ACF4E4C135751E187876B18D80EC0BC44"
"hash": "9491C6D44879AD71A7BAAA7AB7330D31507003C89F06179B056AE8415D19C7A0"
}
]
}
+17 -22
ファイルの表示
@@ -1,5 +1,7 @@
Texture2D SourceTexture : register(t0);
SamplerState SourceSampler : register(s0);
#include "Srgb.hlsli"
Texture2D LinearTexture : register(t1);
SamplerState LinearSampler : register(s1);
static const int MaxSteps = 64;
static const int TableSize = 128;
@@ -8,7 +10,6 @@ static const int ModeRadial = 2;
static const int ModeRotational = 4;
static const float MaxRadialShift = 0.5;
static const float InteriorGuard = 0.51;
static const float MinimumAlpha = 0.0001;
cbuffer Constants : register(b0)
{
@@ -24,12 +25,6 @@ cbuffer Constants : register(b0)
float4 samples[TableSize] : packoffset(c4);
};
float4 Linearize(float4 color)
{
float3 clamped = min(color.rgb, color.a);
return float4(clamped * clamped * rcp(max(color.a, MinimumAlpha)), color.a);
}
float2 SamplePosition(float2 scenePosition, float2 offset, float coefficient)
{
float shift = coefficient * shiftDistance;
@@ -67,23 +62,22 @@ float4 SampleCovered(float2 uv, float2 pixelStep, float2 scenePosition, float2 t
float2 minimum = inputBounds.xy + 0.5;
float2 maximum = inputBounds.zw - 0.5;
float2 clamped = clamp(target, minimum, maximum);
float4 color = SourceTexture.SampleLevel(SourceSampler, uv + (clamped - scenePosition) * pixelStep, 0);
float4 color = LinearTexture.SampleLevel(LinearSampler, uv + (clamped - scenePosition) * pixelStep, 0);
float2 coverage = saturate(min(target - inputBounds.xy, inputBounds.zw - target) + 0.5);
return color * (coverage.x * coverage.y);
}
void Accumulate(float4 gain, float3 basis, float4 shifted, inout float3 color, inout float alpha)
{
float4 lit = Linearize(shifted);
color += gain.rgb * dot(basis, lit.rgb);
alpha += gain.w * lit.a;
color += gain.rgb * dot(basis, shifted.rgb);
alpha += gain.w * shifted.a;
}
float4 Resolve(float3 color, float alpha)
{
float3 positive = max(color, 0.0);
float resolved = saturate(max(alpha, max(positive.r, max(positive.g, positive.b))));
return float4(sqrt(min(positive, resolved) * resolved), resolved);
return EncodePremultiplied(float4(positive, resolved));
}
void AccumulateCovered(int index, float2 uv, float2 pixelStep, float2 scenePosition, float2 offset, inout float3 color, inout float alpha)
@@ -98,7 +92,7 @@ void AccumulateRadial(int index, float2 uv, float2 offsetStep, float rate, inout
float4 gain = samples[index * 2];
float4 basis = samples[index * 2 + 1];
float scale = clamp(basis.w * rate, -MaxRadialShift, MaxRadialShift);
Accumulate(gain, basis.rgb, SourceTexture.SampleLevel(SourceSampler, uv - offsetStep * scale, 0), color, alpha);
Accumulate(gain, basis.rgb, LinearTexture.SampleLevel(LinearSampler, uv - offsetStep * scale, 0), color, alpha);
}
void AccumulateRotational(int index, float2 uv, float2 offset, float2 pixelStep, float rate, inout float3 color, inout float alpha)
@@ -109,14 +103,14 @@ void AccumulateRotational(int index, float2 uv, float2 offset, float2 pixelStep,
float cosine;
sincos(basis.w * rate, sine, cosine);
float2 delta = float2((cosine - 1.0) * offset.x + sine * offset.y, (cosine - 1.0) * offset.y - sine * offset.x);
Accumulate(gain, basis.rgb, SourceTexture.SampleLevel(SourceSampler, uv + delta * pixelStep, 0), color, alpha);
Accumulate(gain, basis.rgb, LinearTexture.SampleLevel(LinearSampler, uv + delta * pixelStep, 0), color, alpha);
}
void AccumulateLinear(int index, float2 uv, float2 stride, inout float3 color, inout float alpha)
{
float4 gain = samples[index * 2];
float4 basis = samples[index * 2 + 1];
Accumulate(gain, basis.rgb, SourceTexture.SampleLevel(SourceSampler, uv - basis.w * stride, 0), color, alpha);
Accumulate(gain, basis.rgb, LinearTexture.SampleLevel(LinearSampler, uv - basis.w * stride, 0), color, alpha);
}
float4 GatherCovered(float2 uv, float2 pixelStep, float2 scenePosition)
@@ -185,11 +179,12 @@ float4 GatherInside(float2 uv, float2 pixelStep, float2 scenePosition)
float4 main(
float4 position : SV_POSITION,
float4 scenePosition : SCENE_POSITION,
float4 uv0 : TEXCOORD0
float4 uv0 : TEXCOORD0,
float4 uv1 : TEXCOORD1
) : SV_TARGET
{
if (shiftDistance == 0.0 || strength <= 0.0)
return SampleCovered(uv0.xy, uv0.zw, scenePosition.xy, scenePosition.xy);
return EncodePremultiplied(SampleCovered(uv1.xy, uv1.zw, scenePosition.xy, scenePosition.xy));
float2 margin = Spread(scenePosition.xy - center) + InteriorGuard;
bool inside = all(scenePosition.xy >= inputBounds.xy + margin) && all(scenePosition.xy <= inputBounds.zw - margin);
@@ -197,12 +192,12 @@ float4 main(
float4 result;
[branch]
if (inside)
result = GatherInside(uv0.xy, uv0.zw, scenePosition.xy);
result = GatherInside(uv1.xy, uv1.zw, scenePosition.xy);
else
result = GatherCovered(uv0.xy, uv0.zw, scenePosition.xy);
result = GatherCovered(uv1.xy, uv1.zw, scenePosition.xy);
if (strength >= 1.0)
return result;
return lerp(SampleCovered(uv0.xy, uv0.zw, scenePosition.xy, scenePosition.xy), result, strength);
return lerp(EncodePremultiplied(SampleCovered(uv1.xy, uv1.zw, scenePosition.xy, scenePosition.xy)), result, strength);
}
+7 -18
ファイルの表示
@@ -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);
}
}
+84 -6
ファイルの表示
@@ -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]
+52 -3
ファイルの表示
@@ -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()
{
+26
ファイルの表示
@@ -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);
}
}
+27
ファイルの表示
@@ -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);
}
+26
ファイルの表示
@@ -0,0 +1,26 @@
using Vortice.Direct2D1;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Player.Video;
namespace SpectrumColorShift;
internal sealed class LinearizeCustomEffect : D2D1CustomShaderEffectBase
{
public LinearizeCustomEffect(IGraphicsDevicesAndContext devices) : base(Create<EffectImpl>(devices))
{
if (IsEnabled)
SetValue((int)Property.Precision, BufferPrecision.PerChannel16Float);
}
[CustomEffect(1)]
internal sealed class EffectImpl : D2D1CustomShaderEffectImplBase<EffectImpl>
{
public EffectImpl() : base(ShaderResourceUri.Get("SpectrumColorShiftLinearize"))
{
}
protected override void UpdateConstants()
{
}
}
}
+41 -11
ファイルの表示
@@ -1,6 +1,7 @@
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using SharpGen.Runtime;
using Vortice;
using Vortice.Direct2D1;
using YukkuriMovieMaker.Commons;
@@ -8,8 +9,40 @@ using YukkuriMovieMaker.Player.Video;
namespace SpectrumColorShift;
internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext devices) : D2D1CustomShaderEffectBase(Create<EffectImpl>(devices))
internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBase
{
private const int SourceInput = 0;
private const int LinearInput = 1;
private readonly LinearizeCustomEffect _linearized;
public SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext devices) : base(Create<EffectImpl>(devices))
{
_linearized = new LinearizeCustomEffect(devices);
if (!IsEnabled)
return;
using var linearized = _linearized.Output;
base.SetInput(LinearInput, linearized, true);
}
public new bool IsEnabled => base.IsEnabled && _linearized.IsEnabled;
public new void SetInput(int index, ID2D1Image? input, RawBool invalidate)
{
base.SetInput(index, input, invalidate);
if (index == SourceInput)
_linearized.SetInput(SourceInput, input, invalidate);
}
protected override void DisposeCore(nint nativePointer, bool disposing)
{
if (disposing)
_linearized.Dispose();
base.DisposeCore(nativePointer, disposing);
}
internal enum PropertyIndex
{
Distance = 0,
@@ -35,7 +68,7 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
public int Steps { set => SetValue((int)PropertyIndex.Steps, value); }
public int Physical { set => SetValue((int)PropertyIndex.Physical, value); }
[CustomEffect(1)]
[CustomEffect(2)]
internal sealed class EffectImpl : D2D1CustomShaderEffectImplBase<EffectImpl>
{
private const string PhysicalShaderName = "SpectrumColorShiftPhysical";
@@ -274,16 +307,13 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
public override void MapOutputRectToInputRects(RawRect outputRect, RawRect[] inputRects)
{
if (inputRects.Length == 0)
return;
var requested = inputRect.Right <= inputRect.Left || inputRect.Bottom <= inputRect.Top
? inputRect
: ShiftGeometry.Input(outputRect, _mode, _cb.Distance, _cb.Direction, _cb.Center, _cb.Radius);
var used = _physical ? LinearInput : SourceInput;
if (inputRect.Right <= inputRect.Left || inputRect.Bottom <= inputRect.Top)
{
inputRects[0] = inputRect;
return;
}
inputRects[0] = ShiftGeometry.Input(outputRect, _mode, _cb.Distance, _cb.Direction, _cb.Center, _cb.Radius);
for (var index = 0; index < inputRects.Length; index++)
inputRects[index] = index == used ? requested : default;
}
public override RawRect MapInvalidRect(int inputIndex, RawRect invalidInputRect)
+1 -1
ファイルの表示
@@ -31,7 +31,7 @@ ReferenceWavelengthDescription,,ずれずにその位置に残る色の波長で
Steps,,ステップ数,Steps,步数,步數,단계 수,Pasos,عدد الخطوات,Langkah
StepsDescription,,スペクトルを分ける数です。距離を大きくするときは増やすと、色が段になって見えるのを防げます,"Sets how many wavelengths the spectrum is divided into. For large distances, raise it to keep the colors from appearing as separate copies.",设置光谱的分割数。距离较大时请增大该值,以免颜色呈分层的重影。,設定光譜的分割數。距離較大時請增大此值,以免顏色呈分層的重影。,스펙트럼을 나누는 수입니다. 거리를 크게 할 때는 늘리면 색이 계단처럼 보이는 것을 막을 수 있습니다.,"Establece en cuántas longitudes de onda se divide el espectro. Con distancias grandes, auméntelo para evitar que los colores se vean como copias separadas.",يحدد عدد الأطوال الموجية التي يقسم إليها الطيف. عند المسافات الكبيرة، ارفعه لتجنب ظهور الألوان كنسخ منفصلة.,"Mengatur jumlah panjang gelombang yang dipakai untuk membagi spektrum. Untuk jarak besar, naikkan agar warna tidak tampak sebagai salinan terpisah."
Physical,,物理ベース,Physically Based,基于物理,基於物理,물리 기반,Basado en física,قائم على الفيزياء,Berbasis fisika
PhysicalDescription,,オンにすると、映像の色から光のスペクトルを推定し、波長ごとの光をずらして足し合わせます。色の足し合わせは、光の量に近い値で行います。オフでは、赤、緑、青を別々にずらします,"When on, the spectrum of light is estimated from the color of the image, and the light of each wavelength is shifted before being summed. Colors are summed in values close to the amount of light. When off, red, green and blue are shifted separately.",开启后,根据图像的颜色估计光的光谱,将各波长的光错开后再叠加。颜色的叠加使用接近光量的值进行。关闭时,红、绿、蓝分别错开。,開啟後,根據影像的顏色估計光的光譜,將各波長的光錯開後再疊加。顏色的疊加使用接近光量的值進行。關閉時,紅、綠、藍分別錯開。,"켜면 영상의 색에서 빛의 스펙트럼을 추정하고, 파장별 빛을 어긋나게 한 뒤 더합니다. 색의 합산은 빛의 양에 가까운 값으로 합니다. 끄면 빨강, 초록, 파랑을 따로 어긋나게 합니다.","Al activarlo, se estima el espectro de la luz a partir del color de la imagen y se desplaza la luz de cada longitud de onda antes de sumarla. Los colores se suman con valores cercanos a la cantidad de luz. Desactivado, el rojo, el verde y el azul se desplazan por separado.",عند التفعيل، يُقدَّر طيف الضوء من لون الصورة، ويُزاح ضوء كل طول موجي ثم تُجمع الأطوال الموجية. يتم جمع الألوان بقيم قريبة من كمية الضوء. عند الإيقاف، تُزاح ألوان الأحمر والأخضر والأزرق بشكل منفصل.,"Jika diaktifkan, spektrum cahaya diperkirakan dari warna gambar, lalu cahaya tiap panjang gelombang digeser sebelum dijumlahkan. Warna dijumlahkan dengan nilai yang mendekati jumlah cahaya. Jika dinonaktifkan, merah, hijau, dan biru digeser secara terpisah."
PhysicalDescription,,オンにすると、映像の色から光のスペクトルを推定し、波長ごとの光をずらして足し合わせます。色の足し合わせは、光の量で行います。オフでは、赤、緑、青を別々にずらします,"When on, the spectrum of light is estimated from the color of the image, and the light of each wavelength is shifted before being summed. Colors are summed as amounts of light. When off, red, green and blue are shifted separately.",开启后,根据图像的颜色估计光的光谱,将各波长的光错开后再叠加。颜色的叠加以光量进行。关闭时,红、绿、蓝分别错开。,開啟後,根據影像的顏色估計光的光譜,將各波長的光錯開後再疊加。顏色的疊加以光量進行。關閉時,紅、綠、藍分別錯開。,"켜면 영상의 색에서 빛의 스펙트럼을 추정하고, 파장별 빛을 어긋나게 한 뒤 더합니다. 색의 합산은 빛의 양으로 합니다. 끄면 빨강, 초록, 파랑을 따로 어긋나게 합니다.","Al activarlo, se estima el espectro de la luz a partir del color de la imagen y se desplaza la luz de cada longitud de onda antes de sumarla. Los colores se suman como cantidades de luz. Desactivado, el rojo, el verde y el azul se desplazan por separado.",عند التفعيل، يُقدَّر طيف الضوء من لون الصورة، ويُزاح ضوء كل طول موجي ثم تُجمع الأطوال الموجية. يتم جمع الألوان بوصفها كميات من الضوء. عند الإيقاف، تُزاح ألوان الأحمر والأخضر والأزرق بشكل منفصل.,"Jika diaktifkan, spektrum cahaya diperkirakan dari warna gambar, lalu cahaya tiap panjang gelombang digeser sebelum dijumlahkan. Warna dijumlahkan sebagai jumlah cahaya. Jika dinonaktifkan, merah, hijau, dan biru digeser secara terpisah."
TagColorShift,,色ずれ,color shift,色偏,色偏,색 어긋남,desfase de color,إزاحة اللون,pergeseran warna
TagChromaticAberration,,色収差,chromatic aberration,色差,色差,색수차,aberración cromática,الزيغ اللوني,aberasi kromatik
TagSpectrum,,スペクトル,spectrum,光谱,光譜,스펙트럼,espectro,الطيف,spektrum
1 Key Parameter ja-jp en-us zh-cn zh-tw ko-kr es-es ar-sa id-id
31 Steps ステップ数 Steps 步数 步數 단계 수 Pasos عدد الخطوات Langkah
32 StepsDescription スペクトルを分ける数です。距離を大きくするときは増やすと、色が段になって見えるのを防げます Sets how many wavelengths the spectrum is divided into. For large distances, raise it to keep the colors from appearing as separate copies. 设置光谱的分割数。距离较大时请增大该值,以免颜色呈分层的重影。 設定光譜的分割數。距離較大時請增大此值,以免顏色呈分層的重影。 스펙트럼을 나누는 수입니다. 거리를 크게 할 때는 늘리면 색이 계단처럼 보이는 것을 막을 수 있습니다. Establece en cuántas longitudes de onda se divide el espectro. Con distancias grandes, auméntelo para evitar que los colores se vean como copias separadas. يحدد عدد الأطوال الموجية التي يقسم إليها الطيف. عند المسافات الكبيرة، ارفعه لتجنب ظهور الألوان كنسخ منفصلة. Mengatur jumlah panjang gelombang yang dipakai untuk membagi spektrum. Untuk jarak besar, naikkan agar warna tidak tampak sebagai salinan terpisah.
33 Physical 物理ベース Physically Based 基于物理 基於物理 물리 기반 Basado en física قائم على الفيزياء Berbasis fisika
34 PhysicalDescription オンにすると、映像の色から光のスペクトルを推定し、波長ごとの光をずらして足し合わせます。色の足し合わせは、光の量に近い値で行います。オフでは、赤、緑、青を別々にずらします オンにすると、映像の色から光のスペクトルを推定し、波長ごとの光をずらして足し合わせます。色の足し合わせは、光の量で行います。オフでは、赤、緑、青を別々にずらします When on, the spectrum of light is estimated from the color of the image, and the light of each wavelength is shifted before being summed. Colors are summed in values close to the amount of light. When off, red, green and blue are shifted separately. When on, the spectrum of light is estimated from the color of the image, and the light of each wavelength is shifted before being summed. Colors are summed as amounts of light. When off, red, green and blue are shifted separately. 开启后,根据图像的颜色估计光的光谱,将各波长的光错开后再叠加。颜色的叠加使用接近光量的值进行。关闭时,红、绿、蓝分别错开。 开启后,根据图像的颜色估计光的光谱,将各波长的光错开后再叠加。颜色的叠加以光量进行。关闭时,红、绿、蓝分别错开。 開啟後,根據影像的顏色估計光的光譜,將各波長的光錯開後再疊加。顏色的疊加使用接近光量的值進行。關閉時,紅、綠、藍分別錯開。 開啟後,根據影像的顏色估計光的光譜,將各波長的光錯開後再疊加。顏色的疊加以光量進行。關閉時,紅、綠、藍分別錯開。 켜면 영상의 색에서 빛의 스펙트럼을 추정하고, 파장별 빛을 어긋나게 한 뒤 더합니다. 색의 합산은 빛의 양에 가까운 값으로 합니다. 끄면 빨강, 초록, 파랑을 따로 어긋나게 합니다. 켜면 영상의 색에서 빛의 스펙트럼을 추정하고, 파장별 빛을 어긋나게 한 뒤 더합니다. 색의 합산은 빛의 양으로 합니다. 끄면 빨강, 초록, 파랑을 따로 어긋나게 합니다. Al activarlo, se estima el espectro de la luz a partir del color de la imagen y se desplaza la luz de cada longitud de onda antes de sumarla. Los colores se suman con valores cercanos a la cantidad de luz. Desactivado, el rojo, el verde y el azul se desplazan por separado. Al activarlo, se estima el espectro de la luz a partir del color de la imagen y se desplaza la luz de cada longitud de onda antes de sumarla. Los colores se suman como cantidades de luz. Desactivado, el rojo, el verde y el azul se desplazan por separado. عند التفعيل، يُقدَّر طيف الضوء من لون الصورة، ويُزاح ضوء كل طول موجي ثم تُجمع الأطوال الموجية. يتم جمع الألوان بقيم قريبة من كمية الضوء. عند الإيقاف، تُزاح ألوان الأحمر والأخضر والأزرق بشكل منفصل. عند التفعيل، يُقدَّر طيف الضوء من لون الصورة، ويُزاح ضوء كل طول موجي ثم تُجمع الأطوال الموجية. يتم جمع الألوان بوصفها كميات من الضوء. عند الإيقاف، تُزاح ألوان الأحمر والأخضر والأزرق بشكل منفصل. Jika diaktifkan, spektrum cahaya diperkirakan dari warna gambar, lalu cahaya tiap panjang gelombang digeser sebelum dijumlahkan. Warna dijumlahkan dengan nilai yang mendekati jumlah cahaya. Jika dinonaktifkan, merah, hijau, dan biru digeser secara terpisah. Jika diaktifkan, spektrum cahaya diperkirakan dari warna gambar, lalu cahaya tiap panjang gelombang digeser sebelum dijumlahkan. Warna dijumlahkan sebagai jumlah cahaya. Jika dinonaktifkan, merah, hijau, dan biru digeser secara terpisah.
35 TagColorShift 色ずれ color shift 色偏 色偏 색 어긋남 desfase de color إزاحة اللون pergeseran warna
36 TagChromaticAberration 色収差 chromatic aberration 色差 色差 색수차 aberración cromática الزيغ اللوني aberasi kromatik
37 TagSpectrum スペクトル spectrum 光谱 光譜 스펙트럼 espectro الطيف spektrum