10 コミット
作成者 SHA1 メッセージ 日付
routersys de6901f898 バージョンをv1.2.1へ更新する
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.2.1 のコミットから作成しました
2026-10-13 16:12:22 +09:00
routersys c627206917 sRGBの変換の名前に接頭辞を付け、使われない定数を除く 2026-10-13 16:05:50 +09:00
routersys 0c097c3eb8 シェーダーの個数の一覧を共有の設定に集め、同梱するシェーダーを一覧から決める 2026-10-13 15:59:39 +09:00
routersys a77dbbe13f エフェクトが基底を継承せずに前処理のエフェクトを持つ形にし、光の入力の名前を直す 2026-10-13 15:55:26 +09:00
routersys 31a052feb1 エフェクトの更新の管理を設定の組から決まる形にし、使われない定数を除く 2026-10-13 15:46:46 +09:00
routersys 38d280b3e8 シェーダーの系統と分光表の1ステップを型にして、切り上げの重複をなくす 2026-10-13 15:37:25 +09:00
routersys 6f23e211de 軸に平行な直線のずれを、タップを減らしたフィルターで描いて速くする
・「物理ベース」で軸に平行な短い直線のずれを、ステップの合計を畳み込んだタップのフィルターで描くよう変更-M
2026-10-13 15:03:11 +09:00
routersys 5579e7a4ed 物理ベースのシェーダーの共通部分を別ファイルに取り出す 2026-10-13 12:35:48 +09:00
routersys 307acd1f22 方式ごとに分けたシェーダーで64ステップの描画と初回描画を速くする
・直線、放射、回転の方式ごとにコンパイルしたシェーダーを選んで使うよう変更-M
2026-10-13 11:12:46 +09:00
routersys d5a114d14c 表示名を「色ズレ(スペクトラム)」へ変更する
・プラグインの表示名を「色ずれ(スペクトラム)」から「色ズレ(スペクトラム)」へ変更-M
2026-10-13 10:24:35 +09:00
38個のファイルの変更、1187行の追加、477行の削除

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

+2 -2
ファイルの表示
@@ -1,5 +1,5 @@
========================================
色ずれ(スペクトラム) for YMM4 v1.2.0
色ズレ(スペクトラム) for YMM4 v1.2.1
========================================
YukkuriMovieMaker4上で動作する、映像の色を400nmから700nmの波長に分け、波長ごとに
異なる量だけずらして足し合わせ、虹色の縁として描画する
@@ -17,7 +17,7 @@ Reflectance」(Eurographics Symposium on Rendering、2019年)に基づきま
絵になります。
距離、角度、中心X、中心Y、強さ、基準波長の6項目はアニメーションに
対応しています。
エフェクトの種類一覧では「色ずれ(スペクトラム)」として表示されます。
エフェクトの種類一覧では「色ズレ(スペクトラム)」として表示されます。
--------------------------------------------------------------------------------
■ 動作要件
--------------------------------------------------------------------------------
+3 -3
ファイルの表示
@@ -69,8 +69,8 @@ jobs:
$readmePath = ".github/Plugin_Readme.txt"
$readme = Get-Content $readmePath -Raw
if (-not $readme.Contains(" 色ずれ(スペクトラム) for YMM4 $tag")) {
$current = if ($readme -match '(?m)^ 色ずれ(スペクトラム) for YMM4 (\S+)') { $Matches[1] } else { "記載なし" }
if (-not $readme.Contains(" 色ズレ(スペクトラム) for YMM4 $tag")) {
$current = if ($readme -match '(?m)^ 色ズレ(スペクトラム) for YMM4 (\S+)') { $Matches[1] } else { "記載なし" }
$problems += "$readmePath の見出しが $current です。$tag にしてください。"
}
@@ -133,7 +133,7 @@ jobs:
Copy-Item ".github/Plugin_Readme.txt" "$stageRoot/Readme.txt"
$readme = Get-Content "$stageRoot/Readme.txt" -Raw
if (-not $readme.Contains(" 色ずれ(スペクトラム) for YMM4 $version")) {
if (-not $readme.Contains(" 色ズレ(スペクトラム) for YMM4 $version")) {
Write-Error "同梱する Readme.txt の見出しが $version と一致しません"
exit 1
}
+3 -3
ファイルの表示
@@ -1,4 +1,4 @@
# 色ずれ(スペクトラム) for YMM4
# 色ズレ(スペクトラム) for YMM4
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](#)
[![.NET](https://img.shields.io/badge/.NET-10.0-purple.svg)](#)
@@ -41,7 +41,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、映像の色を400nmから700nm
## 概要
本プラグインはYMM4の映像エフェクトとして動作し、エフェクトの種類一覧では「色ずれ(スペクトラム)」として表示されます。カテゴリは加工です。
本プラグインはYMM4の映像エフェクトとして動作し、エフェクトの種類一覧では「色ズレ(スペクトラム)」として表示されます。カテゴリは加工です。
波長は光の色を表す値で、短いほど青く、長いほど赤くなります。400nmから700nmまでの波長の並びが、スペクトルです。映像の各画素について、波長ごとにずらした位置の色を読み取り、波長ごとの重みを掛けて足し合わせた色で描き直します。ずらす量は波長と「基準波長」との違いから決め、「分散」で回折格子とプリズムのどちらの決め方にするかを選びます。
@@ -72,7 +72,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、映像の色を400nmから700nm
1. [Releases](https://github.com/routersys/YMM4-SpectrumColorShift/releases/latest)ページから最新のプラグインファイル(`.ymme`)をダウンロードしてください。
2. YMM4が起動していないことを確認し、ダウンロードしたファイルを実行してインストールします。
3. YMM4を起動し、タイムライン上のアイテムに映像エフェクトを追加します。
4. 映像エフェクトの種類として「色ずれ(スペクトラム)」を選択してください。
4. 映像エフェクトの種類として「色ズレ(スペクトラム)」を選択してください。
---
+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"
}
]
}
+135
ファイルの表示
@@ -0,0 +1,135 @@
#ifndef ShaderMode
#error ShaderMode must be defined by the build.
#endif
#include "Srgb.hlsli"
Texture2D LightTexture : register(t1);
SamplerState LightSampler : register(s1);
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;
static const float MaxRadialShift = 0.5;
static const float InteriorGuard = 0.51;
cbuffer Constants : register(b0)
{
float4 inputBounds : packoffset(c0);
float2 direction : packoffset(c1.x);
float2 center : packoffset(c1.z);
float shiftDistance : packoffset(c2.x);
float radius : packoffset(c2.y);
float strength : packoffset(c2.z);
int steps : packoffset(c2.w);
float spreadScale : packoffset(c3.x);
float filterOrigin : packoffset(c3.y);
int filterVertical : packoffset(c3.z);
float4 samples[TableSize] : packoffset(c4);
float4 taps[FilterTableSize] : packoffset(c132);
};
float2 SamplePosition(float2 scenePosition, float2 offset, float coefficient)
{
float shift = coefficient * shiftDistance;
if (CompiledMode == ModeRadial)
{
float scale = 1.0 - clamp(shift / radius, -MaxRadialShift, MaxRadialShift);
return center + offset * scale;
}
if (CompiledMode == ModeRotational)
{
float sine;
float cosine;
sincos(shift / radius, sine, cosine);
return center + float2(cosine * offset.x + sine * offset.y, cosine * offset.y - sine * offset.x);
}
return scenePosition - shift * direction;
}
float2 Spread(float2 offset)
{
if (CompiledMode == ModeRadial)
return abs(offset) * spreadScale;
if (CompiledMode == ModeRotational)
return length(offset) * spreadScale;
return abs(shiftDistance) * abs(direction);
}
float4 SampleCovered(float2 uv, float2 pixelStep, float2 scenePosition, float2 target)
{
float2 minimum = inputBounds.xy + 0.5;
float2 maximum = inputBounds.zw - 0.5;
float2 clamped = clamp(target, minimum, maximum);
float4 color = LightTexture.SampleLevel(LightSampler, 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)
{
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 EncodePremultiplied(float4(positive, resolved));
}
void AccumulateCovered(int index, float2 uv, float2 pixelStep, float2 scenePosition, float2 offset, inout float3 color, inout float alpha)
{
float4 gain = samples[index * 2];
float4 basis = samples[index * 2 + 1];
Accumulate(gain, basis.rgb, SampleCovered(uv, pixelStep, scenePosition, SamplePosition(scenePosition, offset, basis.w)), color, alpha);
}
float4 GatherCovered(float2 uv, float2 pixelStep, float2 scenePosition)
{
float2 offset = scenePosition - center;
float3 color = 0.0;
float alpha = 0.0;
[loop]
for (int index = 0; index < steps; index++)
AccumulateCovered(index, uv, pixelStep, scenePosition, offset, color, alpha);
return Resolve(color, alpha);
}
float4 GatherInside(float2 uv, float2 pixelStep, float2 scenePosition);
float4 main(
float4 position : SV_POSITION,
float4 scenePosition : SCENE_POSITION,
float4 uv0 : TEXCOORD0,
float4 uv1 : TEXCOORD1
) : SV_TARGET
{
if (shiftDistance == 0.0 || strength <= 0.0)
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);
float4 result;
[branch]
if (inside)
result = GatherInside(uv1.xy, uv1.zw, scenePosition.xy);
else
result = GatherCovered(uv1.xy, uv1.zw, scenePosition.xy);
if (strength >= 1.0)
return result;
return lerp(EncodePremultiplied(SampleCovered(uv1.xy, uv1.zw, scenePosition.xy, scenePosition.xy)), result, strength);
}
+6
ファイルの表示
@@ -0,0 +1,6 @@
<Project>
<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>
</Project>
+37 -8
ファイルの表示
@@ -154,22 +154,51 @@
<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" />
</ItemGroup>
<Target Name="AddStepCountShaders" BeforeTargets="FxCompile">
<Import Project="ShaderVariants.props" />
<Target Name="AddVariantShaders" BeforeTargets="FxCompile">
<ItemGroup>
<StaleShader Include="$(OutDir)SpectrumColorShift*.cso" />
</ItemGroup>
<Delete Files="@(StaleShader)" />
<ItemGroup>
<FxCompile Include="SpectrumColorShift.hlsl">
<ShaderType>Pixel</ShaderType>
<PreprocessorDefinitions>StepCount=%(StepCount.Identity)</PreprocessorDefinitions>
<ObjectFileOutput>$(OutDir)SpectrumColorShift%(StepCount.Identity).cso</ObjectFileOutput>
<PreprocessorDefinitions>StepCount=%(StepCount.Identity);ShaderMode=1</PreprocessorDefinitions>
<ObjectFileOutput>$(OutDir)SpectrumColorShiftLinear%(StepCount.Identity).cso</ObjectFileOutput>
</FxCompile>
<FxCompile Include="SpectrumColorShift.hlsl">
<ShaderType>Pixel</ShaderType>
<PreprocessorDefinitions>StepCount=%(StepCount.Identity);ShaderMode=2</PreprocessorDefinitions>
<ObjectFileOutput>$(OutDir)SpectrumColorShiftRadial%(StepCount.Identity).cso</ObjectFileOutput>
</FxCompile>
<FxCompile Include="SpectrumColorShift.hlsl">
<ShaderType>Pixel</ShaderType>
<PreprocessorDefinitions>StepCount=%(StepCount.Identity);ShaderMode=4</PreprocessorDefinitions>
<ObjectFileOutput>$(OutDir)SpectrumColorShiftRotational%(StepCount.Identity).cso</ObjectFileOutput>
</FxCompile>
<FxCompile Include="SpectrumColorShiftPhysical.hlsl">
<ShaderType>Pixel</ShaderType>
<PreprocessorDefinitions>StepCount=%(StepCount.Identity)</PreprocessorDefinitions>
<ObjectFileOutput>$(OutDir)SpectrumColorShiftPhysical%(StepCount.Identity).cso</ObjectFileOutput>
<PreprocessorDefinitions>StepCount=%(StepCount.Identity);ShaderMode=1</PreprocessorDefinitions>
<ObjectFileOutput>$(OutDir)SpectrumColorShiftPhysicalLinear%(StepCount.Identity).cso</ObjectFileOutput>
</FxCompile>
<FxCompile Include="SpectrumColorShiftPhysical.hlsl">
<ShaderType>Pixel</ShaderType>
<PreprocessorDefinitions>StepCount=%(StepCount.Identity);ShaderMode=2</PreprocessorDefinitions>
<ObjectFileOutput>$(OutDir)SpectrumColorShiftPhysicalRadial%(StepCount.Identity).cso</ObjectFileOutput>
</FxCompile>
<FxCompile Include="SpectrumColorShiftPhysical.hlsl">
<ShaderType>Pixel</ShaderType>
<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>
+6
ファイルの表示
@@ -26,6 +26,12 @@
<None Include="SpectrumColorShiftPhysical.hlsl">
<Filter>ソース ファイル</Filter>
</None>
<None Include="SpectrumColorShiftPhysicalFilter.hlsl">
<Filter>ソース ファイル</Filter>
</None>
<None Include="Physical.hlsli">
<Filter>ヘッダー ファイル</Filter>
</None>
<None Include="Srgb.hlsli">
<Filter>ヘッダー ファイル</Filter>
</None>
+13 -9
ファイルの表示
@@ -2,12 +2,17 @@
#error StepCount must be defined by the build.
#endif
#ifndef ShaderMode
#error ShaderMode must be defined by the build.
#endif
Texture2D SourceTexture : register(t0);
SamplerState SourceSampler : register(s0);
static const int MaxSteps = 64;
static const int ModeRadial = 2;
static const int ModeRotational = 4;
static const int CompiledMode = ShaderMode;
static const float MaxRadialShift = 0.5;
static const float InteriorGuard = 0.51;
@@ -19,9 +24,8 @@ cbuffer Constants : register(b0)
float shiftDistance : packoffset(c2.x);
float radius : packoffset(c2.y);
float strength : packoffset(c2.z);
int mode : packoffset(c2.w);
int steps : packoffset(c3.x);
float spreadScale : packoffset(c3.y);
int steps : packoffset(c2.w);
float spreadScale : packoffset(c3.x);
float4 samples[MaxSteps] : packoffset(c4);
};
@@ -29,13 +33,13 @@ float2 SamplePosition(float2 scenePosition, float2 offset, float coefficient)
{
float shift = coefficient * shiftDistance;
if (mode == ModeRadial)
if (CompiledMode == ModeRadial)
{
float scale = 1.0 - clamp(shift / radius, -MaxRadialShift, MaxRadialShift);
return center + offset * scale;
}
if (mode == ModeRotational)
if (CompiledMode == ModeRotational)
{
float sine;
float cosine;
@@ -48,10 +52,10 @@ float2 SamplePosition(float2 scenePosition, float2 offset, float coefficient)
float2 Spread(float2 offset)
{
if (mode == ModeRadial)
if (CompiledMode == ModeRadial)
return abs(offset) * spreadScale;
if (mode == ModeRotational)
if (CompiledMode == ModeRotational)
return length(offset) * spreadScale;
return abs(shiftDistance) * abs(direction);
@@ -124,7 +128,7 @@ float4 GatherInside(float2 uv, float2 pixelStep, float2 scenePosition)
float3 color = 0.0;
float3 coverage = 0.0;
if (mode == ModeRadial)
if (CompiledMode == ModeRadial)
{
float2 offsetStep = offset * pixelStep;
float rate = shiftDistance / radius;
@@ -133,7 +137,7 @@ float4 GatherInside(float2 uv, float2 pixelStep, float2 scenePosition)
for (int index = 0; index < StepCount; index++)
AccumulateRadial(index, uv, offsetStep, rate, color, coverage);
}
else if (mode == ModeRotational)
else if (CompiledMode == ModeRotational)
{
float rate = shiftDistance / radius;
+6 -131
ファイルの表示
@@ -2,100 +2,14 @@
#error StepCount must be defined by the build.
#endif
#include "Srgb.hlsli"
Texture2D LinearTexture : register(t1);
SamplerState LinearSampler : register(s1);
static const int MaxSteps = 64;
static const int TableSize = 128;
static const int ModeRadial = 2;
static const int ModeRotational = 4;
static const float MaxRadialShift = 0.5;
static const float InteriorGuard = 0.51;
cbuffer Constants : register(b0)
{
float4 inputBounds : packoffset(c0);
float2 direction : packoffset(c1.x);
float2 center : packoffset(c1.z);
float shiftDistance : packoffset(c2.x);
float radius : packoffset(c2.y);
float strength : packoffset(c2.z);
int mode : packoffset(c2.w);
int steps : packoffset(c3.x);
float spreadScale : packoffset(c3.y);
float4 samples[TableSize] : packoffset(c4);
};
float2 SamplePosition(float2 scenePosition, float2 offset, float coefficient)
{
float shift = coefficient * shiftDistance;
if (mode == ModeRadial)
{
float scale = 1.0 - clamp(shift / radius, -MaxRadialShift, MaxRadialShift);
return center + offset * scale;
}
if (mode == ModeRotational)
{
float sine;
float cosine;
sincos(shift / radius, sine, cosine);
return center + float2(cosine * offset.x + sine * offset.y, cosine * offset.y - sine * offset.x);
}
return scenePosition - shift * direction;
}
float2 Spread(float2 offset)
{
if (mode == ModeRadial)
return abs(offset) * spreadScale;
if (mode == ModeRotational)
return length(offset) * spreadScale;
return abs(shiftDistance) * abs(direction);
}
float4 SampleCovered(float2 uv, float2 pixelStep, float2 scenePosition, float2 target)
{
float2 minimum = inputBounds.xy + 0.5;
float2 maximum = inputBounds.zw - 0.5;
float2 clamped = clamp(target, minimum, maximum);
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)
{
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 EncodePremultiplied(float4(positive, resolved));
}
void AccumulateCovered(int index, float2 uv, float2 pixelStep, float2 scenePosition, float2 offset, inout float3 color, inout float alpha)
{
float4 gain = samples[index * 2];
float4 basis = samples[index * 2 + 1];
Accumulate(gain, basis.rgb, SampleCovered(uv, pixelStep, scenePosition, SamplePosition(scenePosition, offset, basis.w)), color, alpha);
}
#include "Physical.hlsli"
void AccumulateRadial(int index, float2 uv, float2 offsetStep, float rate, inout float3 color, inout float alpha)
{
float4 gain = samples[index * 2];
float4 basis = samples[index * 2 + 1];
float scale = clamp(basis.w * rate, -MaxRadialShift, MaxRadialShift);
Accumulate(gain, basis.rgb, LinearTexture.SampleLevel(LinearSampler, uv - offsetStep * scale, 0), color, alpha);
Accumulate(gain, basis.rgb, LightTexture.SampleLevel(LightSampler, uv - offsetStep * scale, 0), color, alpha);
}
void AccumulateRotational(int index, float2 uv, float2 offset, float2 pixelStep, float rate, inout float3 color, inout float alpha)
@@ -106,27 +20,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, LinearTexture.SampleLevel(LinearSampler, uv + delta * pixelStep, 0), color, alpha);
Accumulate(gain, basis.rgb, LightTexture.SampleLevel(LightSampler, 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, LinearTexture.SampleLevel(LinearSampler, uv - basis.w * stride, 0), color, alpha);
}
float4 GatherCovered(float2 uv, float2 pixelStep, float2 scenePosition)
{
float2 offset = scenePosition - center;
float3 color = 0.0;
float alpha = 0.0;
[loop]
for (int index = 0; index < steps; index++)
AccumulateCovered(index, uv, pixelStep, scenePosition, offset, color, alpha);
return Resolve(color, alpha);
Accumulate(gain, basis.rgb, LightTexture.SampleLevel(LightSampler, uv - basis.w * stride, 0), color, alpha);
}
float4 GatherInside(float2 uv, float2 pixelStep, float2 scenePosition)
@@ -135,7 +36,7 @@ float4 GatherInside(float2 uv, float2 pixelStep, float2 scenePosition)
float3 color = 0.0;
float alpha = 0.0;
if (mode == ModeRadial)
if (CompiledMode == ModeRadial)
{
float2 offsetStep = offset * pixelStep;
float rate = shiftDistance / radius;
@@ -144,7 +45,7 @@ float4 GatherInside(float2 uv, float2 pixelStep, float2 scenePosition)
for (int index = 0; index < StepCount; index++)
AccumulateRadial(index, uv, offsetStep, rate, color, alpha);
}
else if (mode == ModeRotational)
else if (CompiledMode == ModeRotational)
{
float rate = shiftDistance / radius;
@@ -163,29 +64,3 @@ float4 GatherInside(float2 uv, float2 pixelStep, float2 scenePosition)
return Resolve(color, alpha);
}
float4 main(
float4 position : SV_POSITION,
float4 scenePosition : SCENE_POSITION,
float4 uv0 : TEXCOORD0,
float4 uv1 : TEXCOORD1
) : SV_TARGET
{
if (shiftDistance == 0.0 || strength <= 0.0)
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);
float4 result;
[branch]
if (inside)
result = GatherInside(uv1.xy, uv1.zw, scenePosition.xy);
else
result = GatherCovered(uv1.xy, uv1.zw, scenePosition.xy);
if (strength >= 1.0)
return result;
return lerp(EncodePremultiplied(SampleCovered(uv1.xy, uv1.zw, scenePosition.xy, scenePosition.xy)), result, strength);
}
+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 = LightTexture.SampleLevel(LightSampler, 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);
}
+16 -16
ファイルの表示
@@ -1,22 +1,22 @@
static const float DecodeThreshold = 0.04045;
static const float EncodeThreshold = 0.0031308;
static const float LowSlope = 12.92;
static const float Offset = 0.055;
static const float Scale = 1.055;
static const float Exponent = 2.4;
static const float SrgbDecodeThreshold = 0.04045;
static const float SrgbEncodeThreshold = 0.0031308;
static const float SrgbLowSlope = 12.92;
static const float SrgbOffset = 0.055;
static const float SrgbScale = 1.055;
static const float SrgbExponent = 2.4;
float3 Decode(float3 encoded)
float3 SrgbDecode(float3 encoded)
{
float3 low = encoded / LowSlope;
float3 high = pow((encoded + Offset) / Scale, Exponent);
return encoded <= DecodeThreshold ? low : high;
float3 low = encoded / SrgbLowSlope;
float3 high = pow((encoded + SrgbOffset) / SrgbScale, SrgbExponent);
return encoded <= SrgbDecodeThreshold ? low : high;
}
float3 Encode(float3 linearColor)
float3 SrgbEncode(float3 linearColor)
{
float3 low = linearColor * LowSlope;
float3 high = Scale * pow(linearColor, 1.0 / Exponent) - Offset;
return linearColor <= EncodeThreshold ? low : high;
float3 low = linearColor * SrgbLowSlope;
float3 high = SrgbScale * pow(linearColor, 1.0 / SrgbExponent) - SrgbOffset;
return linearColor <= SrgbEncodeThreshold ? low : high;
}
float3 Unpremultiply(float4 premultiplied)
@@ -26,10 +26,10 @@ float3 Unpremultiply(float4 premultiplied)
float4 DecodePremultiplied(float4 encoded)
{
return float4(Decode(Unpremultiply(encoded)) * encoded.a, encoded.a);
return float4(SrgbDecode(Unpremultiply(encoded)) * encoded.a, encoded.a);
}
float4 EncodePremultiplied(float4 linearColor)
{
return float4(Encode(Unpremultiply(linearColor)) * linearColor.a, linearColor.a);
return float4(SrgbEncode(Unpremultiply(linearColor)) * linearColor.a, linearColor.a);
}
+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)]
+31
ファイルの表示
@@ -0,0 +1,31 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
namespace SpectrumColorShift.Tests;
internal static partial class ConstantBufferContract
{
[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();
public static IReadOnlyDictionary<string, int> Declared(string source)
=> MemberPattern().Matches(source).ToDictionary(
match => match.Groups["name"].Value,
match => int.Parse(match.Groups["register"].Value) * 16 + (match.Groups["component"].Success ? "xyzw".IndexOf(match.Groups["component"].Value[0]) * 4 : 0));
public static int OffsetOf(Type type, string path)
{
var offset = 0;
foreach (var name in path.Split('.'))
{
offset += (int)Marshal.OffsetOf(type, name);
type = type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)!.FieldType;
}
return offset;
}
public static int SizeOf(Type type) => (int)typeof(Unsafe).GetMethod(nameof(Unsafe.SizeOf))!.MakeGenericMethod(type).Invoke(null, null)!;
}
+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.SetSource(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.SetSource(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}");
}
}
}
}
+10 -21
ファイルの表示
@@ -2,7 +2,6 @@ using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using static SpectrumColorShift.SpectrumColorShiftCustomEffect;
@@ -12,14 +11,13 @@ public sealed partial class ShaderContractTests
{
static readonly Dictionary<string, string> Fields = new()
{
["inputBounds"] = "InputBounds",
["direction"] = "Direction",
["center"] = "Center",
["shiftDistance"] = "Distance",
["radius"] = "Radius",
["strength"] = "Strength",
["mode"] = "Mode",
["steps"] = "Steps",
["inputBounds"] = "Header.InputBounds",
["direction"] = "Header.Direction",
["center"] = "Header.Center",
["shiftDistance"] = "Header.Distance",
["radius"] = "Header.Radius",
["strength"] = "Header.Strength",
["steps"] = "Header.Steps",
["spreadScale"] = "SpreadScale",
["samples"] = "Samples",
};
@@ -33,9 +31,6 @@ public sealed partial class ShaderContractTests
[GeneratedRegex(@"static const (?:int|float) (?<name>\w+) = (?<value>[0-9.]+);")]
private static partial Regex ConstantPattern();
[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);
@@ -51,21 +46,15 @@ public sealed partial class ShaderContractTests
[Fact]
public void TheConstantBufferMatchesTheShaderLayout()
{
var members = MemberPattern().Matches(Source)
.ToDictionary(
match => match.Groups["name"].Value,
match => int.Parse(match.Groups["register"].Value, CultureInfo.InvariantCulture) * 16
+ (match.Groups["component"].Success ? "xyzw".IndexOf(match.Groups["component"].Value[0]) * 4 : 0));
var members = ConstantBufferContract.Declared(Source);
Assert.Equal(Fields.Keys.Order(), members.Keys.Order());
Assert.All(members, member => Assert.Equal(member.Value, (int)Marshal.OffsetOf(ConstantBuffer, Fields[member.Key])));
Assert.All(members, member => Assert.Equal(member.Value, ConstantBufferContract.OffsetOf(ConstantBuffer, Fields[member.Key])));
}
[Fact]
public void TheConstantBufferFillsWholeRegistersAndHoldsTheTable()
{
var size = (int)typeof(Unsafe).GetMethod(nameof(Unsafe.SizeOf))!.MakeGenericMethod(ConstantBuffer).Invoke(null, null)!;
Assert.Equal(16 * (4 + Spectrum.MaxSteps), size);
Assert.Equal(16 * (4 + Spectrum.MaxSteps), ConstantBufferContract.SizeOf(ConstantBuffer));
}
}
+108
ファイルの表示
@@ -0,0 +1,108 @@
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; } = ShaderProjectFile("SpectrumColorShift.Shader.vcxproj");
static string Props { get; } = ShaderProjectFile("ShaderVariants.props");
static string ShaderProjectFile(string name) => File.ReadAllText(Path.Combine(Path.GetDirectoryName(Here())!, "..", "SpectrumColorShift.Shader", name));
static string Here([CallerFilePath] string path = "") => path;
static IEnumerable<(ShaderFamily Family, bool Physical)> SteppedFamilies => [(ShaderVariants.Legacy, false), (ShaderVariants.Physical, true)];
[GeneratedRegex(@"<StepCount Include=""(?<counts>[^""]+)""")]
private static partial Regex StepCountsPattern();
[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();
static IEnumerable<int> Listed(Regex pattern) => pattern.Match(Props).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 TheSharedPropsListExactlyTheseCounts()
{
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<ArgumentOutOfRangeException>(() => 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);
}
}
}
}
}
+221
ファイルの表示
@@ -0,0 +1,221 @@
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 <= Spectrum.Padded(steps) * SpectralFilter.MaxTapShare, $"{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));
}
}
+4 -4
ファイルの表示
@@ -48,7 +48,7 @@ public sealed class SpectralRenderingTests
static Rendering Render(IGraphicsDevicesAndContext devices, SourceImage source, ShiftSettings settings)
{
using var effect = new SpectrumColorShiftCustomEffect(devices);
effect.SetInput(0, source.Bitmap, true);
effect.SetSource(source.Bitmap, true);
settings.Apply(effect);
using var output = effect.Output;
@@ -602,7 +602,7 @@ public sealed class SpectralRenderingTests
var inPlace = Render(context, source, settings);
using var effect = new SpectrumColorShiftCustomEffect(context);
effect.SetInput(0, movedOutput, true);
effect.SetSource(movedOutput, true);
settings.Apply(effect);
using var output = effect.Output;
var travelled = Rendering.Capture(context, output);
@@ -698,7 +698,7 @@ public sealed class SpectralRenderingTests
using var bitmap = context.DeviceContext.CreateBitmap(new SizeI(96, 96), nint.Zero, stride, new BitmapProperties1(SourceImage.PixelFormat, SourceImage.Dpi, SourceImage.Dpi, BitmapOptions.None));
bitmap.CopyFromMemory(pixels, stride);
using var effect = new SpectrumColorShiftCustomEffect(context);
effect.SetInput(0, bitmap, true);
effect.SetSource(bitmap, true);
Settings(Mode: mode, Distance: 12f).Apply(effect);
using var output = effect.Output;
@@ -735,7 +735,7 @@ public sealed class SpectralRenderingTests
var expected = Render(context, source, legacy);
using var effect = new SpectrumColorShiftCustomEffect(context);
effect.SetInput(0, source.Bitmap, true);
effect.SetSource(source.Bitmap, true);
legacy.Apply(effect);
effect.Physical = 1;
using var output = effect.Output;
+28 -38
ファイルの表示
@@ -2,7 +2,6 @@ using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using static SpectrumColorShift.SpectrumColorShiftCustomEffect;
@@ -12,19 +11,21 @@ public sealed partial class SpectralShaderContractTests
{
static readonly Dictionary<string, string> Fields = new()
{
["inputBounds"] = "InputBounds",
["direction"] = "Direction",
["center"] = "Center",
["shiftDistance"] = "Distance",
["radius"] = "Radius",
["strength"] = "Strength",
["mode"] = "Mode",
["steps"] = "Steps",
["inputBounds"] = "Header.InputBounds",
["direction"] = "Header.Direction",
["center"] = "Header.Center",
["shiftDistance"] = "Header.Distance",
["radius"] = "Header.Radius",
["strength"] = "Header.Strength",
["steps"] = "Header.Steps",
["spreadScale"] = "SpreadScale",
["filterOrigin"] = "FilterOrigin",
["filterVertical"] = "FilterVertical",
["samples"] = "Samples",
["taps"] = "Taps",
};
static string Source { get; } = ShaderSource("SpectrumColorShiftPhysical.hlsl");
static string Source { get; } = ShaderSource("Physical.hlsli");
static string SrgbSource { get; } = ShaderSource("Srgb.hlsli");
@@ -32,22 +33,17 @@ public sealed partial class SpectralShaderContractTests
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+)\)")]
[GeneratedRegex(@"Texture2D\s+LightTexture\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) => Constant(Source, name);
static float Constant(string source, string name)
@@ -56,8 +52,8 @@ public sealed partial class SpectralShaderContractTests
[Fact]
public void TheShaderAndTheEffectAgreeOnTheConstants()
{
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"));
@@ -66,7 +62,7 @@ public sealed partial class SpectralShaderContractTests
[Fact]
public void TheShaderReadsTheTextureOfTheLinearizedInput()
{
Assert.Equal(LinearInput, int.Parse(TexturePattern().Match(Source).Groups["register"].Value, CultureInfo.InvariantCulture));
Assert.Equal(SpectrumColorShiftCustomEffect.LightInput, int.Parse(TexturePattern().Match(Source).Groups["register"].Value, CultureInfo.InvariantCulture));
}
[Fact]
@@ -74,48 +70,42 @@ public sealed partial class SpectralShaderContractTests
{
var declared = CoordinatePattern().Matches(Source).Select(match => int.Parse(match.Groups["index"].Value, CultureInfo.InvariantCulture));
Assert.Equal(Enumerable.Range(0, LinearInput + 1), declared.Order());
Assert.Equal(Enumerable.Range(0, SpectrumColorShiftCustomEffect.LightInput + 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)]
[InlineData("SrgbDecodeThreshold", 0.04045f)]
[InlineData("SrgbEncodeThreshold", 0.0031308f)]
[InlineData("SrgbLowSlope", 12.92f)]
[InlineData("SrgbOffset", 0.055f)]
[InlineData("SrgbScale", 1.055f)]
[InlineData("SrgbExponent", 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");
var slope = Constant(SrgbSource, "SrgbLowSlope");
var linearEnd = Constant(SrgbSource, "SrgbEncodeThreshold");
var power = Constant(SrgbSource, "SrgbScale") * MathF.Pow(linearEnd, 1f / Constant(SrgbSource, "SrgbExponent")) - Constant(SrgbSource, "SrgbOffset");
Assert.Equal(Constant(SrgbSource, "DecodeThreshold"), slope * linearEnd, 1e-5f);
Assert.Equal(Constant(SrgbSource, "SrgbDecodeThreshold"), slope * linearEnd, 1e-5f);
Assert.Equal(slope * linearEnd, power, 1e-5f);
}
[Fact]
public void TheConstantBufferMatchesTheShaderLayout()
{
var members = MemberPattern().Matches(Source)
.ToDictionary(
match => match.Groups["name"].Value,
match => int.Parse(match.Groups["register"].Value, CultureInfo.InvariantCulture) * 16
+ (match.Groups["component"].Success ? "xyzw".IndexOf(match.Groups["component"].Value[0]) * 4 : 0));
var members = ConstantBufferContract.Declared(Source);
Assert.Equal(Fields.Keys.Order(), members.Keys.Order());
Assert.All(members, member => Assert.Equal(member.Value, (int)Marshal.OffsetOf(ConstantBuffer, Fields[member.Key])));
Assert.All(members, member => Assert.Equal(member.Value, ConstantBufferContract.OffsetOf(ConstantBuffer, Fields[member.Key])));
}
[Fact]
public void TheConstantBufferFillsWholeRegistersAndHoldsTheTable()
{
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), ConstantBufferContract.SizeOf(ConstantBuffer));
}
}
+5 -5
ファイルの表示
@@ -10,14 +10,14 @@ public sealed class SpectrumColorShiftCustomEffectTests
{
const float MaxInputPixel = 4096f;
static float Read(SpectrumColorShiftCustomEffect effect, PropertyIndex index) => effect.GetFloatValue((int)index);
static float Read(SpectrumColorShiftCustomEffect effect, PropertyIndex index) => effect.ReadFloat(index);
static int ReadInt(SpectrumColorShiftCustomEffect effect, PropertyIndex index) => effect.GetIntValue((int)index);
static int ReadInt(SpectrumColorShiftCustomEffect effect, PropertyIndex index) => effect.ReadInt(index);
static (float Left, float Top, float Right, float Bottom) Bounds(IGraphicsDevicesAndContext devices, SourceImage source, Action<SpectrumColorShiftCustomEffect> configure)
{
using var effect = new SpectrumColorShiftCustomEffect(devices);
effect.SetInput(0, source.Bitmap, true);
effect.SetSource(source.Bitmap, true);
configure(effect);
using var output = effect.Output;
var bounds = devices.DeviceContext.GetImageLocalBounds(output);
@@ -318,7 +318,7 @@ public sealed class SpectrumColorShiftCustomEffectTests
using var context = devices.CreateContext();
using var source = SourceImage.Solid(context, 40, 30, Bgra.Opaque(10, 20, 30));
using var effect = new SpectrumColorShiftCustomEffect(context);
effect.SetInput(0, source.Bitmap, true);
effect.SetSource(source.Bitmap, true);
effect.Mode = (int)ShiftMode.Rotational;
effect.Distance = MaxInputPixel;
using var output = effect.Output;
@@ -388,7 +388,7 @@ public sealed class SpectrumColorShiftCustomEffectTests
crop.SetInput(0, source.Bitmap, true);
using var cropped = crop.Output;
using var effect = new SpectrumColorShiftCustomEffect(context);
effect.SetInput(0, cropped, true);
effect.SetSource(cropped, true);
effect.Mode = (int)mode;
effect.Distance = 3f;
using var output = effect.Output;
+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()
{
+1 -1
ファイルの表示
@@ -228,7 +228,7 @@ public sealed class SpectrumColorShiftEffectProcessorTests
using var processor = effect.CreateVideoEffect(context);
processor.SetInput(source.Bitmap);
using var direct = new SpectrumColorShiftCustomEffect(context);
direct.SetInput(0, source.Bitmap, true);
direct.SetSource(source.Bitmap, true);
direct.Distance = 14.5f;
direct.Mode = (int)ShiftMode.Rotational;
direct.Angle = 33f;
+3 -3
ファイルの表示
@@ -37,7 +37,7 @@ public sealed class SpectrumColorShiftRenderingTests
static Rendering Render(IGraphicsDevicesAndContext devices, SourceImage source, ShiftSettings settings)
{
using var effect = new SpectrumColorShiftCustomEffect(devices);
effect.SetInput(0, source.Bitmap, true);
effect.SetSource(source.Bitmap, true);
settings.Apply(effect);
using var output = effect.Output;
@@ -476,7 +476,7 @@ public sealed class SpectrumColorShiftRenderingTests
var inPlace = Render(context, source, settings);
using var effect = new SpectrumColorShiftCustomEffect(context);
effect.SetInput(0, movedOutput, true);
effect.SetSource(movedOutput, true);
settings.Apply(effect);
using var output = effect.Output;
var travelled = Rendering.Capture(context, output);
@@ -572,7 +572,7 @@ public sealed class SpectrumColorShiftRenderingTests
using var bitmap = context.DeviceContext.CreateBitmap(new SizeI(96, 96), nint.Zero, stride, new BitmapProperties1(SourceImage.PixelFormat, SourceImage.Dpi, SourceImage.Dpi, BitmapOptions.None));
bitmap.CopyFromMemory(pixels, stride);
using var effect = new SpectrumColorShiftCustomEffect(context);
effect.SetInput(0, bitmap, true);
effect.SetSource(bitmap, true);
new ShiftSettings(Mode: mode, Distance: 12f).Apply(effect);
using var output = effect.Output;
+1 -1
ファイルの表示
@@ -24,7 +24,7 @@ public sealed class StepCountRenderingTests
using var context = devices.CreateContext();
using var source = new SourceImage(context, 48, 32, Gradient);
using var effect = new SpectrumColorShiftCustomEffect(context);
effect.SetInput(0, source.Bitmap, true);
effect.SetSource(source.Bitmap, true);
using var output = effect.Output;
foreach (var steps in Enumerable.Range(Spectrum.MinSteps, Spectrum.MaxSteps - Spectrum.MinSteps + 1))
-61
ファイルの表示
@@ -1,61 +0,0 @@
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
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(@"<StepCount Include=""(?<counts>[^""]+)""")]
private static partial Regex CountsPattern();
[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 EveryCountHasItsOwnShaderInEachFamily()
{
var ids = StepShaders.Counts.SelectMany(count => new[] { StepShaders.Select(false, count), StepShaders.Select(true, count) }).ToList();
Assert.Equal(2 * StepShaders.Counts.Count(), ids.Distinct().Count());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void StepsShareTheShaderOfTheirPaddedCount(bool physical)
{
foreach (var steps in Enumerable.Range(Spectrum.MinSteps, Spectrum.MaxSteps - Spectrum.MinSteps + 1))
Assert.Equal(StepShaders.Select(physical, Spectrum.Padded(steps)), StepShaders.Select(physical, steps));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void EveryCountIsShippedAsAResource(bool physical)
{
foreach (var count in StepShaders.Counts)
{
var bytes = YukkuriMovieMaker.Commons.PackResourceReader.ReadAllBytes(ShaderResourceUri.Get(StepShaders.ResourceName(physical, count)));
Assert.True(bytes.Length > 0, $"{StepShaders.ResourceName(physical, count)}");
}
}
}
+1 -1
ファイルの表示
@@ -46,7 +46,7 @@ public sealed class TextsTests
{
var neutral = Texts.ResourceManager.GetString(nameof(Texts.SpectrumColorShift), CultureInfo.InvariantCulture);
Assert.Equal("色ずれ(スペクトラム)", neutral);
Assert.Equal("色ズレ(スペクトラム)", neutral);
Assert.Equal(neutral, Texts.ResourceManager.GetString(nameof(Texts.SpectrumColorShift), CultureInfo.GetCultureInfo("ja-JP")));
}
+6
ファイルの表示
@@ -0,0 +1,6 @@
namespace SpectrumColorShift;
internal static class Quantum
{
public static int RoundUp(int value, int quantum) => (value + quantum - 1) / quantum * quantum;
}
+69
ファイルの表示
@@ -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<byte[]>[] _bytes;
public ShaderFamily(string name, IReadOnlyList<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.Count * _length).Select(_ => Guid.NewGuid())];
_bytes = [.. Enumerable.Range(0, modes.Count * _length).Select(index => new Lazy<byte[]>(() => Read(index)))];
}
public IReadOnlyList<ShiftMode> Modes { get; }
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 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))));
}
+23
ファイルの表示
@@ -0,0 +1,23 @@
using Vortice.Direct2D1;
namespace SpectrumColorShift;
internal static class ShaderVariants
{
public static ShaderFamily Legacy { get; } = new("SpectrumColorShift", Enum.GetValues<ShiftMode>(), Spectrum.MinSteps, Spectrum.MaxSteps, Spectrum.StepQuantum);
public static ShaderFamily Physical { get; } = new("SpectrumColorShiftPhysical", Enum.GetValues<ShiftMode>(), 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);
}
}
+101
ファイルの表示
@@ -0,0 +1,101 @@
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;
public const float MaxTapShare = 0.65f;
private const float AxisTolerance = 1e-5f;
private const int Channels = 3;
private const int ValuesPerTap = Channels * Channels + 1;
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<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<Placement> placements = stackalloc Placement[Spectrum.MaxSteps];
var layout = Plan(spectral, steps, distance * along, vertical, placements);
if (layout.Taps == 0)
return default;
Span<double> 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<Vector4> spectral, int steps, float signedDistance, bool vertical, Span<Placement> placements)
{
var low = int.MaxValue;
var high = int.MinValue;
for (var step = 0; step < steps; step++)
{
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 = Quantum.RoundUp(high - low + 1, TapQuantum);
return taps <= MaxTaps && taps <= Spectrum.Padded(steps) * MaxTapShare ? new Layout(taps, low, vertical) : default;
}
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, 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 * step.Gain[row] * step.Basis[column];
}
values[Channels * Channels] += weight * step.AlphaGain;
}
private static void Write(Span<Vector4> table, ReadOnlySpan<double> 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();
}
}
+20
ファイルの表示
@@ -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<Vector4> 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<Vector4> table, int step)
{
table[step * Spectrum.EntriesPerStep] = new Vector4(Gain, AlphaGain);
table[step * Spectrum.EntriesPerStep + 1] = new Vector4(Basis, Displacement);
}
}
+2 -3
ファイルの表示
@@ -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();
+11 -2
ファイルの表示
@@ -5,12 +5,14 @@
<UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Version>1.2.0</Version>
<Version>1.2.1</Version>
<Platforms>AnyCPU;x64</Platforms>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
<ShaderDirPath>..\Release\</ShaderDirPath>
</PropertyGroup>
<Import Project="..\SpectrumColorShift.Shader\ShaderVariants.props" />
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
<_Parameter1>SpectrumColorShift.Tests</_Parameter1>
@@ -61,7 +63,14 @@
</ItemGroup>
<ItemGroup>
<Resource Include="$(ShaderDirPath)SpectrumColorShift*.cso" Link="Resources\Shader\%(Filename)%(Extension)" />
<Resource Include="$(ShaderDirPath)SpectrumColorShiftLinearize.cso" Link="Resources\Shader\%(Filename)%(Extension)" />
<Resource Include="@(StepCount->'$(ShaderDirPath)SpectrumColorShiftLinear%(Identity).cso')" Link="Resources\Shader\%(Filename)%(Extension)" />
<Resource Include="@(StepCount->'$(ShaderDirPath)SpectrumColorShiftRadial%(Identity).cso')" Link="Resources\Shader\%(Filename)%(Extension)" />
<Resource Include="@(StepCount->'$(ShaderDirPath)SpectrumColorShiftRotational%(Identity).cso')" Link="Resources\Shader\%(Filename)%(Extension)" />
<Resource Include="@(StepCount->'$(ShaderDirPath)SpectrumColorShiftPhysicalLinear%(Identity).cso')" Link="Resources\Shader\%(Filename)%(Extension)" />
<Resource Include="@(StepCount->'$(ShaderDirPath)SpectrumColorShiftPhysicalRadial%(Identity).cso')" Link="Resources\Shader\%(Filename)%(Extension)" />
<Resource Include="@(StepCount->'$(ShaderDirPath)SpectrumColorShiftPhysicalRotational%(Identity).cso')" Link="Resources\Shader\%(Filename)%(Extension)" />
<Resource Include="@(TapCount->'$(ShaderDirPath)SpectrumColorShiftPhysicalFilterLinear%(Identity).cso')" Link="Resources\Shader\%(Filename)%(Extension)" />
</ItemGroup>
<ItemGroup>
+138 -102
ファイルの表示
@@ -9,38 +9,40 @@ using YukkuriMovieMaker.Player.Video;
namespace SpectrumColorShift;
internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBase
internal sealed class SpectrumColorShiftCustomEffect : IDisposable
{
private const int SourceInput = 0;
private const int LinearInput = 1;
internal const int SourceInput = 0;
internal const int LightInput = 1;
private const int EffectInputs = LightInput + 1;
private readonly ShiftEffect _shift;
private readonly LinearizeCustomEffect _linearized;
public SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext devices) : base(Create<EffectImpl>(devices))
public SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext devices)
{
_shift = new ShiftEffect(devices);
_linearized = new LinearizeCustomEffect(devices);
if (!IsEnabled)
return;
using var linearized = _linearized.Output;
base.SetInput(LinearInput, linearized, true);
using var light = _linearized.Output;
_shift.SetInput(LightInput, light, true);
}
public new bool IsEnabled => base.IsEnabled && _linearized.IsEnabled;
public bool IsEnabled => _shift.IsEnabled && _linearized.IsEnabled;
public new void SetInput(int index, ID2D1Image? input, RawBool invalidate)
public ID2D1Image Output => _shift.Output;
public void SetSource(ID2D1Image? source, RawBool invalidate)
{
base.SetInput(index, input, invalidate);
if (index == SourceInput)
_linearized.SetInput(SourceInput, input, invalidate);
_shift.SetInput(SourceInput, source, invalidate);
_linearized.SetInput(0, source, invalidate);
}
protected override void DisposeCore(nint nativePointer, bool disposing)
public void Dispose()
{
if (disposing)
_linearized.Dispose();
base.DisposeCore(nativePointer, disposing);
_linearized.Dispose();
_shift.Dispose();
}
internal enum PropertyIndex
@@ -57,20 +59,27 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
Physical,
}
public float Distance { set => SetValue((int)PropertyIndex.Distance, value); }
public int Mode { set => SetValue((int)PropertyIndex.Mode, value); }
public float Angle { set => SetValue((int)PropertyIndex.Angle, value); }
public float CenterX { set => SetValue((int)PropertyIndex.CenterX, value); }
public float CenterY { set => SetValue((int)PropertyIndex.CenterY, value); }
public float Strength { set => SetValue((int)PropertyIndex.Strength, value); }
public int Dispersion { set => SetValue((int)PropertyIndex.Dispersion, value); }
public float ReferenceWavelength { set => SetValue((int)PropertyIndex.ReferenceWavelength, value); }
public int Steps { set => SetValue((int)PropertyIndex.Steps, value); }
public int Physical { set => SetValue((int)PropertyIndex.Physical, value); }
public float Distance { set => _shift.SetValue((int)PropertyIndex.Distance, value); }
public int Mode { set => _shift.SetValue((int)PropertyIndex.Mode, value); }
public float Angle { set => _shift.SetValue((int)PropertyIndex.Angle, value); }
public float CenterX { set => _shift.SetValue((int)PropertyIndex.CenterX, value); }
public float CenterY { set => _shift.SetValue((int)PropertyIndex.CenterY, value); }
public float Strength { set => _shift.SetValue((int)PropertyIndex.Strength, value); }
public int Dispersion { set => _shift.SetValue((int)PropertyIndex.Dispersion, value); }
public float ReferenceWavelength { set => _shift.SetValue((int)PropertyIndex.ReferenceWavelength, value); }
public int Steps { set => _shift.SetValue((int)PropertyIndex.Steps, value); }
public int Physical { set => _shift.SetValue((int)PropertyIndex.Physical, value); }
[CustomEffect(2)]
internal float ReadFloat(PropertyIndex index) => _shift.GetFloatValue((int)index);
internal int ReadInt(PropertyIndex index) => _shift.GetIntValue((int)index);
private sealed class ShiftEffect(IGraphicsDevicesAndContext devices) : D2D1CustomShaderEffectBase(Create<EffectImpl>(devices));
[CustomEffect(EffectInputs)]
internal sealed class EffectImpl : D2D1CustomShaderEffectImplBase<EffectImpl>
{
private ShiftHeader _header;
private ConstantBuffer _cb;
private PhysicalConstantBuffer _physicalCb;
private ShiftMode _mode = ShiftMode.Linear;
@@ -78,18 +87,20 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
private Vector2 _centerOffset;
private float _referenceWavelength = Spectrum.DefaultReferenceWavelength;
private int _steps = Spectrum.DefaultSteps;
private bool _tableStale = true;
private bool _spectralStale = true;
private bool _physical;
private SpectrumKey? _tableKey;
private SpectrumKey? _spectralKey;
private FilterKey? _filterKey;
private SpectralFilter.Layout _filter;
private Guid _shader = GUID_PixelShader;
[CustomEffectProperty(PropertyType.Float, (int)PropertyIndex.Distance)]
public float Distance
{
get => _cb.Distance;
get => _header.Distance;
set
{
_cb.Distance = Sanitize(value, -MaxInputPixel, MaxInputPixel);
_header.Distance = Sanitize(value, -MaxInputPixel, MaxInputPixel);
UpdateConstants();
}
}
@@ -101,7 +112,6 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
set
{
_mode = value is (int)ShiftMode.Radial or (int)ShiftMode.Rotational ? (ShiftMode)value : ShiftMode.Linear;
_cb.Mode = (int)_mode;
UpdateConstants();
}
}
@@ -109,11 +119,11 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
[CustomEffectProperty(PropertyType.Float, (int)PropertyIndex.Angle)]
public float Angle
{
get => MathF.Atan2(_cb.Direction.Y, _cb.Direction.X) * 180f / MathF.PI;
get => MathF.Atan2(_header.Direction.Y, _header.Direction.X) * 180f / MathF.PI;
set
{
var radians = float.IsFinite(value) ? value * MathF.PI / 180f : 0f;
_cb.Direction = new Vector2(MathF.Cos(radians), MathF.Sin(radians));
_header.Direction = new Vector2(MathF.Cos(radians), MathF.Sin(radians));
UpdateConstants();
}
}
@@ -145,10 +155,10 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
[CustomEffectProperty(PropertyType.Float, (int)PropertyIndex.Strength)]
public float Strength
{
get => _cb.Strength;
get => _header.Strength;
set
{
_cb.Strength = Sanitize(value, 0f, 1f);
_header.Strength = Sanitize(value, 0f, 1f);
UpdateConstants();
}
}
@@ -160,8 +170,6 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
set
{
_dispersion = value == (int)DispersionLaw.Prism ? DispersionLaw.Prism : DispersionLaw.Grating;
_tableStale = true;
_spectralStale = true;
UpdateConstants();
}
}
@@ -173,8 +181,6 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
set
{
_referenceWavelength = Spectrum.ClampReference(value);
_tableStale = true;
_spectralStale = true;
UpdateConstants();
}
}
@@ -186,9 +192,7 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
set
{
_steps = Spectrum.ClampSteps(value);
_cb.Steps = _steps;
_tableStale = true;
_spectralStale = true;
_header.Steps = _steps;
UpdateConstants();
}
}
@@ -204,19 +208,22 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
}
}
public EffectImpl() : base(StepShaders.DefaultBytes)
internal int FilterTaps => _physical ? CurrentFilter().Taps : 0;
private SpectrumKey CurrentSpectrum => new(_steps, _referenceWavelength, _dispersion);
public EffectImpl() : base(ShaderVariants.DefaultBytes)
{
_cb.Direction = Vector2.UnitX;
_cb.Radius = 1f;
_cb.Strength = 1f;
_cb.Mode = (int)ShiftMode.Linear;
_cb.Steps = Spectrum.DefaultSteps;
_header.Direction = Vector2.UnitX;
_header.Radius = 1f;
_header.Strength = 1f;
_header.Steps = Spectrum.DefaultSteps;
}
public override void Initialize(ID2D1EffectContext effectContext, ID2D1TransformGraph transformGraph)
{
base.Initialize(effectContext, transformGraph);
StepShaders.Load(effectContext);
ShaderVariants.LoadAll(effectContext);
}
protected override void UpdateConstants()
@@ -226,19 +233,14 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
try
{
_cb.SpreadScale = ShiftGeometry.Spread(_mode, _cb.Distance, _cb.Radius);
var shader = StepShaders.Select(_physical, _steps);
if (shader != _shader)
{
drawInformation.SetPixelShader(shader, PixelOptions.None);
_shader = shader;
}
var spread = ShiftGeometry.Spread(_mode, _header.Distance, _header.Radius);
var filter = _physical ? CurrentFilter() : default;
SelectShader(filter);
if (_physical)
SendPhysicalConstants();
SendPhysicalConstants(spread, filter);
else
SendConstants();
SendConstants(spread);
}
catch (Exception exception)
{
@@ -247,34 +249,57 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
}
}
private void SendConstants()
private SpectralFilter.Layout CurrentFilter()
{
if (_tableStale)
var spectral = CurrentSpectrum;
if (_spectralKey != spectral)
{
Spectrum.Fill(_cb.Samples, _steps, _referenceWavelength, _dispersion);
_tableStale = false;
Spectrum.FillSpectral(_physicalCb.Samples, spectral.Steps, spectral.Reference, spectral.Law);
_spectralKey = spectral;
}
var key = new FilterKey(spectral, _header.Distance, _header.Direction, _mode);
if (_filterKey != key)
{
_filter = _mode == ShiftMode.Linear ? SpectralFilter.Fill(_physicalCb.Taps, _physicalCb.Samples, _steps, _header.Distance, _header.Direction) : default;
_filterKey = key;
}
return _filter;
}
private void SelectShader(SpectralFilter.Layout filter)
{
var shader = filter.Taps > 0
? ShaderVariants.Filter.Id(ShiftMode.Linear, filter.Taps)
: ShaderVariants.Stepped(_physical).Id(_mode, _steps);
if (shader == _shader)
return;
drawInformation!.SetPixelShader(shader, PixelOptions.None);
_shader = shader;
}
private void SendConstants(float spread)
{
var spectral = CurrentSpectrum;
if (_tableKey != spectral)
{
Spectrum.Fill(_cb.Samples, spectral.Steps, spectral.Reference, spectral.Law);
_tableKey = spectral;
}
_cb.Header = _header;
_cb.SpreadScale = spread;
drawInformation!.SetPixelShaderConstantBuffer(_cb);
}
private void SendPhysicalConstants()
private void SendPhysicalConstants(float spread, SpectralFilter.Layout filter)
{
if (_spectralStale)
{
Spectrum.FillSpectral(_physicalCb.Samples, _steps, _referenceWavelength, _dispersion);
_spectralStale = false;
}
_physicalCb.InputBounds = _cb.InputBounds;
_physicalCb.Direction = _cb.Direction;
_physicalCb.Center = _cb.Center;
_physicalCb.Distance = _cb.Distance;
_physicalCb.Radius = _cb.Radius;
_physicalCb.Strength = _cb.Strength;
_physicalCb.Mode = _cb.Mode;
_physicalCb.Steps = Spectrum.Padded(_steps);
_physicalCb.SpreadScale = _cb.SpreadScale;
_physicalCb.Header = _header;
_physicalCb.SpreadScale = spread;
_physicalCb.FilterOrigin = filter.Origin;
_physicalCb.FilterVertical = filter.Vertical ? 1 : 0;
drawInformation!.SetPixelShaderConstantBuffer(_physicalCb);
}
@@ -292,11 +317,11 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
return;
}
_cb.InputBounds = new Vector4(inputRect.Left, inputRect.Top, inputRect.Right, inputRect.Bottom);
_header.InputBounds = new Vector4(inputRect.Left, inputRect.Top, inputRect.Right, inputRect.Bottom);
RefreshGeometry();
UpdateConstants();
outputRect = ShiftGeometry.Output(inputRect, _mode, _cb.Distance, _cb.Direction, _cb.Center, _cb.Radius);
outputRect = ShiftGeometry.Output(inputRect, _mode, _header.Distance, _header.Direction, _header.Center, _header.Radius);
outputOpaqueSubRect = default;
}
@@ -304,15 +329,15 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
{
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;
: ShiftGeometry.Input(outputRect, _mode, _header.Distance, _header.Direction, _header.Center, _header.Radius);
var activeInput = _physical ? LightInput : SourceInput;
for (var index = 0; index < inputRects.Length; index++)
inputRects[index] = index == used ? requested : default;
inputRects[index] = index == activeInput ? requested : default;
}
public override RawRect MapInvalidRect(int inputIndex, RawRect invalidInputRect)
=> ShiftGeometry.Output(invalidInputRect, _mode, _cb.Distance, _cb.Direction, _cb.Center, _cb.Radius);
=> ShiftGeometry.Output(invalidInputRect, _mode, _header.Distance, _header.Direction, _header.Center, _header.Radius);
private static float Sanitize(float value, float minimum, float maximum)
=> float.IsNaN(value) ? 0f : Math.Clamp(value, minimum, maximum);
@@ -322,10 +347,14 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
if (inputRect.Right <= inputRect.Left || inputRect.Bottom <= inputRect.Top)
return;
_cb.Center = ShiftGeometry.Center(inputRect, _centerOffset);
_cb.Radius = ShiftGeometry.Radius(inputRect, _cb.Center);
_header.Center = ShiftGeometry.Center(inputRect, _centerOffset);
_header.Radius = ShiftGeometry.Radius(inputRect, _header.Center);
}
private readonly record struct SpectrumKey(int Steps, float Reference, DispersionLaw Law);
private readonly record struct FilterKey(SpectrumKey Spectral, float Distance, Vector2 Direction, ShiftMode Mode);
[InlineArray(Spectrum.MaxSteps)]
private struct SampleTable
{
@@ -338,8 +367,14 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
private Vector4 _element;
}
[InlineArray(SpectralFilter.TableLength)]
private struct FilterTapTable
{
private Vector4 _element;
}
[StructLayout(LayoutKind.Sequential)]
private struct PhysicalConstantBuffer
private struct ShiftHeader
{
public Vector4 InputBounds;
public Vector2 Direction;
@@ -347,29 +382,30 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
public float Distance;
public float Radius;
public float Strength;
public int Mode;
public int Steps;
public float SpreadScale;
public float Pad1;
public float Pad2;
public SpectralSampleTable Samples;
}
[StructLayout(LayoutKind.Sequential)]
private struct ConstantBuffer
{
public Vector4 InputBounds;
public Vector2 Direction;
public Vector2 Center;
public float Distance;
public float Radius;
public float Strength;
public int Mode;
public int Steps;
public ShiftHeader Header;
public float SpreadScale;
public float Pad1;
public float Pad2;
public float Pad3;
public SampleTable Samples;
}
[StructLayout(LayoutKind.Sequential)]
private struct PhysicalConstantBuffer
{
public ShiftHeader Header;
public float SpreadScale;
public float FilterOrigin;
public int FilterVertical;
public float Pad;
public SpectralSampleTable Samples;
public FilterTapTable Taps;
}
}
}
+2 -2
ファイルの表示
@@ -94,7 +94,7 @@ internal sealed class SpectrumColorShiftEffectProcessor(
protected override void setInput(ID2D1Image? input)
{
_effect?.SetInput(0, input, true);
_effect?.SetSource(input, true);
}
protected override void ClearEffectChain()
@@ -112,7 +112,7 @@ internal sealed class SpectrumColorShiftEffectProcessor(
private void ClearEffectChainCore()
{
_effect?.SetInput(0, null, true);
_effect?.SetSource(null, true);
_isFirst = true;
}
-56
ファイルの表示
@@ -1,56 +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 static readonly Variants Legacy = new(LegacyName);
private static readonly Variants Physical = new(PhysicalName);
public static IEnumerable<int> Counts => Enumerable.Range(0, Variants.Length).Select(CountAt);
public static byte[] DefaultBytes => Legacy.Bytes(Spectrum.DefaultSteps);
public static string ResourceName(bool physical, int count) => (physical ? Physical : Legacy).ResourceName(count);
public static Guid Select(bool physical, int steps) => (physical ? Physical : Legacy).Id(steps);
public static void Load(ID2D1EffectContext effectContext)
{
Legacy.Load(effectContext);
Physical.Load(effectContext);
}
private static int CountAt(int index) => Spectrum.MinSteps + index * Spectrum.StepQuantum;
private sealed class Variants(string name)
{
public static int Length { get; } = (Spectrum.MaxSteps - Spectrum.MinSteps) / Spectrum.StepQuantum + 1;
private readonly Guid[] _ids = [.. Enumerable.Range(0, Length).Select(_ => Guid.NewGuid())];
private readonly Lazy<byte[]>[] _bytes = [.. Enumerable.Range(0, Length).Select(index => new Lazy<byte[]>(() => Read(name, CountAt(index))))];
public string ResourceName(int count) => $"{name}{count}";
public Guid Id(int steps) => _ids[IndexOf(steps)];
public byte[] Bytes(int steps) => _bytes[IndexOf(steps)].Value;
public void Load(ID2D1EffectContext effectContext)
{
for (var index = 0; index < Length; index++)
{
var bytes = _bytes[index].Value;
effectContext.LoadPixelShader(_ids[index], bytes, bytes.Length);
}
}
private static int IndexOf(int steps) => (Spectrum.Padded(steps) - Spectrum.MinSteps) / Spectrum.StepQuantum;
private static byte[] Read(string name, int count) => PackResourceReader.ReadAllBytes(ShaderResourceUri.Get($"{name}{count}"));
}
}
+1 -1
ファイルの表示
@@ -1,5 +1,5 @@
Key,Parameter,ja-jp,en-us,zh-cn,zh-tw,ko-kr,es-es,ar-sa,id-id
SpectrumColorShift,,色ずれ(スペクトラム),Color Shift (Spectrum),色偏(光谱),色偏(光譜),색 어긋남 (스펙트럼),Desfase de color (espectro),إزاحة اللون (الطيف),Pergeseran Warna (Spektrum)
SpectrumColorShift,,色ズレ(スペクトラム),Color Shift (Spectrum),色偏(光谱),色偏(光譜),색 어긋남 (스펙트럼),Desfase de color (espectro),إزاحة اللون (الطيف),Pergeseran Warna (Spektrum)
ShiftGroup,,色ずれ,Color Shift,色偏,色偏,색 어긋남,Desfase de color,إزاحة اللون,Pergeseran Warna
SpectrumGroup,,スペクトル,Spectrum,光谱,光譜,스펙트럼,Espectro,الطيف,Spektrum
Distance,,距離,Distance,距离,距離,거리,Distancia,المسافة,Jarak
1 Key Parameter ja-jp en-us zh-cn zh-tw ko-kr es-es ar-sa id-id
2 SpectrumColorShift 色ずれ(スペクトラム) 色ズレ(スペクトラム) Color Shift (Spectrum) 色偏(光谱) 色偏(光譜) 색 어긋남 (스펙트럼) Desfase de color (espectro) إزاحة اللون (الطيف) Pergeseran Warna (Spektrum)
3 ShiftGroup 色ずれ Color Shift 色偏 色偏 색 어긋남 Desfase de color إزاحة اللون Pergeseran Warna
4 SpectrumGroup スペクトル Spectrum 光谱 光譜 스펙트럼 Espectro الطيف Spektrum
5 Distance 距離 Distance 距离 距離 거리 Distancia المسافة Jarak