コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
1afcdf23f7
|
||
|
|
c68f79f62c
|
||
|
|
cd665bc728
|
||
|
|
48055da9fb
|
||
|
|
421a235076
|
||
|
|
31ccabecd2
|
||
|
|
48717aac4d
|
||
|
|
2b06c4ac54
|
||
|
|
f10cc11998
|
||
|
|
4ab05e9225
|
||
|
|
45462c44e6
|
||
|
|
4d75bd0f3c
|
||
|
|
057d551fd9
|
||
|
|
f6fc3e8db7
|
||
|
|
d7862cce7f
|
||
|
|
2b2c36d991
|
||
|
|
c832ba3dd3
|
||
|
|
29585d8924
|
||
|
|
dc97c8c365
|
||
|
|
bdefc58917
|
||
|
|
57ed743687
|
||
|
|
1d201344ff
|
||
|
|
aa8f1da3d2
|
||
|
|
52279eaa4b
|
||
|
|
2d73e70d9c
|
||
|
|
558c352d4c
|
||
|
|
defceb10dd
|
||
|
|
368b52668a
|
||
|
|
b250fbe7b7
|
||
|
|
fcc15d6793
|
||
|
|
0cec7e9f65
|
||
|
|
fbf166aae1
|
||
|
|
9fc4ec53b3
|
||
|
|
a85512ce50
|
||
|
|
3696ed70dd
|
||
|
|
31466f8e27
|
||
|
|
68ce224227
|
||
|
|
722cadf0d5
|
||
|
|
48114f356e
|
||
|
|
ee5ce91feb
|
||
|
|
330617732f
|
||
|
|
1a54bd484f
|
||
|
|
3367d4e95e
|
||
|
|
37f836b6c5
|
||
|
|
ba7994d213
|
||
|
|
1d704af368
|
||
|
|
f770b2bfd6
|
||
|
|
0af60a0df3
|
||
|
|
209157fb5c
|
||
|
|
920579970e
|
||
|
|
c06e808584
|
||
|
|
5d7a62b344
|
||
|
|
72972cae51
|
||
|
|
f9d34ba224
|
||
|
|
61a23e6ada
|
||
|
|
7aa48451c3
|
||
|
|
bb9a8fd0d6
|
||
|
|
6639b03805
|
||
|
|
1ccc09eb80
|
||
|
|
fb81934d4e
|
||
|
|
a5390734ac
|
||
|
|
d6e10c658d
|
||
|
|
c7d29de91a
|
||
|
|
5e70320edc
|
||
|
|
ce7a88bae5
|
||
|
|
1170557baa
|
||
|
|
9032cbc05a
|
||
|
|
c8d4beac50
|
||
|
|
2d4f595eff
|
||
|
|
0d86120872
|
||
|
|
9cea0af8e9
|
||
|
|
8a1a7bae92
|
||
|
|
310fd9d409
|
||
|
|
be010a0361
|
||
|
|
a40f136795
|
||
|
|
19381b9aed
|
||
|
|
4947808f38
|
||
|
|
0ad7ae3d71
|
||
|
|
a645d93ab3
|
||
|
|
0caa4699a2
|
||
|
|
08c9c4b41a
|
||
|
|
fc4425bd83
|
||
|
|
485652cfa7
|
||
|
|
2bda9b4886
|
||
|
|
9b9eca6f2d
|
||
|
|
2b4f7fa5f4
|
||
|
|
cd3a593db4
|
||
|
|
87cdcb39e4
|
||
|
|
cd2272dc41
|
||
|
|
52ef7ad2a3
|
||
|
|
424e2b0671
|
||
|
|
27da67d503
|
||
|
|
f172f41f4a
|
||
|
|
69b8346949
|
||
|
|
8534fa6d77
|
||
|
|
eb7fa93b0e
|
||
|
|
4adcb2d763
|
||
|
|
d8081adec5
|
||
|
|
8353194569
|
||
|
|
3f8700d493
|
||
|
|
a5d2cf1943
|
||
|
|
b63b8c66a1
|
||
|
|
937f1fddae
|
||
|
|
78a6ae7aa5
|
||
|
|
16b97860ab
|
||
|
|
2a622d647d
|
||
|
|
1c5bb168d6
|
||
|
|
670c2a5f5a
|
||
|
|
4dcdf283aa
|
||
|
|
66c76fb566
|
||
|
|
a89d02f57c
|
||
|
|
3294c8fc8f
|
||
|
|
ac22cf48a1
|
||
|
|
0ad23e25f4
|
||
|
|
42c7585bd0
|
||
|
|
a618eb0986
|
||
|
|
2fd4629ffe
|
||
|
|
41261aea5f
|
||
|
|
eafaec9d2e
|
||
|
|
2f576a251e
|
||
|
|
887e375e5f
|
||
|
|
08be582b86
|
||
|
|
d13649596f
|
||
|
|
533a7cabf3
|
||
|
|
1f81f8a7dd
|
||
|
|
3a087d2fec
|
||
|
|
ed0660842c
|
||
|
|
32b1b776a9
|
||
|
|
4625e62ed2
|
||
|
|
c8b4435fa6
|
||
|
|
35f654975d
|
||
|
|
e0a21459d7
|
||
|
|
b575081821
|
||
|
|
29fdd72733
|
||
|
|
ebdf054a9e
|
||
|
|
b61b855858
|
||
|
|
b4a9c977ee
|
||
|
|
f0f2b6c062
|
||
|
|
b20285cff7
|
||
|
|
b3d3f406c6
|
||
|
|
46380000c1
|
||
|
|
5ba03a5201
|
||
|
|
bfb9f1304a
|
||
|
|
4a167b4e88
|
||
|
|
cdabada2e4
|
||
|
|
c540c53d5c
|
||
|
|
744d5ec5e1
|
||
|
|
4b929df70c
|
検索条件に一致するファイルはありません
+159
-54
@@ -1,5 +1,5 @@
|
||||
========================================
|
||||
波動光学 for YMM4 v3.0.0
|
||||
波動光学 for YMM4 v3.4.0
|
||||
========================================
|
||||
YukkuriMovieMaker4上で動作する、素材を回折も収差もない理想の像とみなし、
|
||||
レンズの開口と波面収差から求めた点像分布関数で畳み込んで、
|
||||
@@ -15,15 +15,24 @@ YukkuriMovieMaker4上で動作する、素材を回折も収差もない理想
|
||||
点像分布関数を求めます。フラウンホーファー回折は、開口から十分に遠い面や、
|
||||
レンズの焦点面で見る回折です。高速フーリエ変換は、画像や波形を周波数ごとの成分に
|
||||
分けて表す変換を、速く計算する方法です。
|
||||
履歴フレーム、参照画像、深度情報、学習済みモデルは使用しません。
|
||||
履歴フレーム、参照画像、画素ごとの深度情報、学習済みモデルは使用しません。
|
||||
にじみの形は光学系と収差の設定から決定論的に決まり、同じ設定では常に
|
||||
同じ形になります。
|
||||
適用量、利得、波長、F値、画素ピッチ、開口回転、中央遮蔽、デフォーカス、
|
||||
縦横非点収差、斜め非点収差、水平コマ収差、垂直コマ収差、球面収差の
|
||||
13項目はアニメーションに対応しています。
|
||||
「色の扱い」を三原色か広帯域にすると、赤、緑、青の成分を別の波長で計算して、
|
||||
光源の縁に色づきを描きます。
|
||||
「奥行きを使う」をオンにすると、アイテムのカメラからの距離と合焦距離の差から、
|
||||
デフォーカスを決めます。このときだけ、アイテムの座標とカメラの位置を使います。
|
||||
適用量、利得、ハイライト閾値、ハイライト強度、波長、F値、画素ピッチ、
|
||||
開口回転、中央遮蔽、デフォーカス、縦横非点収差、斜め非点収差、水平コマ収差、
|
||||
垂直コマ収差、球面収差、合焦距離、焦点距離の17項目はアニメーションに
|
||||
対応しています。
|
||||
畳み込みはGPUで計算します。畳み込みを計算し直したフレームでは、その結果を
|
||||
画面に出す前に検査します。GPUを使えないときと、検査で誤りを見つけたときは、
|
||||
CPUで計算します。
|
||||
「線形光」をオンにすると、
|
||||
画素の値を光の強さに比例する値へ直してから畳み込みます。
|
||||
「ハイライト強度」を上げると、光源のような明るい部分を持ち上げて、
|
||||
回折の筋のような小さな光を見えるようにできます。
|
||||
エフェクトの種類一覧では「波動光学」として表示されます。
|
||||
--------------------------------------------------------------------------------
|
||||
■ 動作要件
|
||||
@@ -43,13 +52,40 @@ CPUで計算します。
|
||||
- デフォルトの設定: 追加した直後は、映像はわずかにやわらぐだけです。
|
||||
にじみを大きくするには、デフォーカスの絶対値かF値を上げてください。
|
||||
デフォーカスは、焦点の位置のずれを表す項目です。単位のwavesは、
|
||||
波長を1とした量です。
|
||||
単色では「波長」で指定した波長を、三原色と広帯域では550nmを1とした量です。
|
||||
|
||||
- 色の扱い: 単色は、赤、緑、青の成分と不透明度を、「波長」で指定した
|
||||
1つの波長で計算します。三原色は、赤を610nm、緑を550nm、青を465nmで
|
||||
計算し、光源の縁に色づきが出ます。不透明度は緑と同じ波長で計算します。
|
||||
広帯域は、赤、緑、青のそれぞれを、同じ波長を中心にした帯の平均で計算します。
|
||||
三原色と広帯域では、「波長」を使いません。素材の画素の値から光の分光分布は
|
||||
分からないので、これらの波長と帯の幅は、仮に決めた値です。
|
||||
三原色と広帯域では、波面収差の光路差を波長によらず一定にするので、
|
||||
デフォーカスの玉ボケの大きさは赤、緑、青で同じになります。
|
||||
|
||||
- 奥行き: 「奥行きを使う」をオンにすると、
|
||||
アイテムのカメラからの距離と「合焦距離」の差から、デフォーカスを決めて、
|
||||
波面収差のデフォーカスに加えます。距離が合焦距離と等しいアイテムには、
|
||||
デフォーカスが加わりません。遠いアイテムには正の値、
|
||||
近いアイテムには負の値が加わります。距離は、アイテムの座標の位置から、
|
||||
カメラの光軸に沿って測った長さで、YMM4の座標の1を1mmとして扱います。
|
||||
カメラの位置と画角が既定のとき、座標のZが0のアイテムの距離は1000です。
|
||||
座標とカメラのうち、このエフェクトより後に適用されるものは、
|
||||
距離に含まれません。グループ制御に置いたカメラを動かしても、
|
||||
距離は変わりません。焦点距離をf、F値をN、合焦距離をz_f、距離をzとすると、
|
||||
デフォーカスは、f² / (8 × N²) × (z − z_f) / (z × (z_f − f))を、
|
||||
2√3と基準の波長の積で割った値です。長さの単位はmmで、基準の波長は、
|
||||
単色では「波長」の値、三原色と広帯域では550nmです。
|
||||
このデフォーカスが作るにじみの半径は、
|
||||
薄いレンズの式から求めた錯乱円の半径と一致します。オフのときは、
|
||||
「合焦距離」と「焦点距離」は設定の画面に表示されません。
|
||||
|
||||
- 品質と収差: 品質は、瞳関数を置く格子の大きさを切り替えます。
|
||||
格子は瞳関数の値を縦横に並べた表で、1つ1つの値を標本と呼びます。
|
||||
格子が粗いと、大きな波面収差で位相が急に変わる所を表しきれず、
|
||||
点像分布関数の形が崩れます。波面収差の絶対値を大きくするときは、
|
||||
品質を上げてください。
|
||||
品質を上げてください。広帯域では、品質が、波長ごとに瞳関数を変換する
|
||||
波長の数も決めます。品質を上げるほど、計算し直しが重くなります。
|
||||
|
||||
- カーネル半径: 1〜63画素で、デフォルトは15画素です。カーネルは、
|
||||
畳み込みの重みを正方形に並べたものです。正方形は、
|
||||
@@ -61,10 +97,47 @@ CPUで計算します。
|
||||
品質も上げてください。品質を上げるほど、点像分布関数の計算が重くなります。
|
||||
カーネル半径と計算の重さの関係は、処理負荷の項目にあります。
|
||||
|
||||
- 利得: 利得は、畳み込んだ結果に掛ける倍率です。
|
||||
100%で画素の値の総和を保ちます。利得を掛けた結果は、入力映像と混ぜる前に、
|
||||
各成分が表せる最大の値で打ち切り、さらに色の成分が不透明度を超えないように
|
||||
抑えます。
|
||||
- 利得: 利得は、畳み込んだ結果に掛ける倍率です。100%で、
|
||||
丸める前の値の総和を保ちます。利得を掛けた結果は、入力映像と混ぜる前に、
|
||||
各成分が表せる最大の値で打ち切り、
|
||||
さらに色の成分が不透明度を超えないように抑えます。
|
||||
|
||||
- 線形光: 画素の値は、光の強さに比例していません。光の強さに比例する値を、
|
||||
線形の値と呼びます。線形光をオンにすると、
|
||||
素材の画素の値を線形の値へ直してから畳み込み、結果を画素の値へ戻します。
|
||||
光の回折とにじみは、光の強さを足し合わせる現象なので、
|
||||
線形の値で畳み込むほうが実際の光に合います。
|
||||
白と黒の画素が1画素ずつ交互に並ぶ市松模様を大きくぼかしたときの平均は、
|
||||
画素の値のままでは約128、線形光では約188です。半透明の画素は、
|
||||
素材の色を不透明度で割って元の色に戻してから変換し、
|
||||
変換した値に不透明度を掛け直します。オフのときは、
|
||||
画素の値をそのまま畳み込みます。
|
||||
|
||||
- ハイライト: ハイライト閾値と強度は、線形光がオンのときだけ働き、
|
||||
オフのときは設定の画面に表示されません。
|
||||
素材は8ビットで、光源の画素の値は1.0で頭打ちです。
|
||||
回折の筋のように中心よりはるかに小さい光は、
|
||||
そのままでは出力の1階調に届きません。強さを上げると、
|
||||
明るい画素を持ち上げてから畳み込むので、そうした光が見えるようになります。
|
||||
画素の最も明るいチャンネルの値をmとし、しきい値をtとします。
|
||||
mがt以下の画素は持ち上げません。mがtを超えると、倍率は、
|
||||
(m - t) / (1 - t)の2乗に比例して上がります。mが1のとき、倍率は強さの値です。
|
||||
倍率は、色と不透明度のすべての成分に掛けます。強さが1倍のときと、
|
||||
しきい値が100%のときは、持ち上げません。持ち上げた分の光が加わるので、
|
||||
出力の総和は素材より大きくなります。明るさを戻すには、利得を下げてください。
|
||||
光源の本当の明るさは復元せず、指定した倍率で光を足す処理です。
|
||||
|
||||
- ディザ: 出力は8ビットに丸めます。点のような小さな明るい部分では、
|
||||
広がった光のうちの小さな値が0に丸められて、
|
||||
出力の総和が素材より少なくなります。ディザをオンにすると、丸める前の値に、
|
||||
0以上1未満の値を足してから、小数を切り捨てます。足す値は、
|
||||
画素の位置だけで決まります。1つの画素の赤、緑、青、不透明度には、
|
||||
同じ値を足します。同じ設定では、同じ画素に毎回同じ値を足すので、
|
||||
フレームが変わってもちらつきません。カーネル半径を変えると、
|
||||
計算領域の余白が変わるので、模様は動きます。黒と白は変わりません。
|
||||
測定の条件は、F値16、画素ピッチ2μm、カーネル半径63画素です。
|
||||
黒い背景の半径2画素の白い円の出力の総和は、ディザなしで素材の91.1%、
|
||||
ディザありで100.2%でした。ディザありの値は、模様により2%ほど動きます。
|
||||
|
||||
- 適用量0%: 適用量は、入力映像と、利得を掛けた結果を混ぜる割合です。
|
||||
適用量が0%のときは入力を変更せず、畳み込みの計算も行いません。
|
||||
@@ -99,21 +172,26 @@ CPUで計算します。
|
||||
倍精度で計算した値と比べる処理です。倍精度は、
|
||||
64ビットの浮動小数点数による計算で、GPUで使う32ビットの計算より誤差が
|
||||
小さくなります。同じ計算を2回行い、結果が1ビットも違わないことも確かめます。
|
||||
自己試験にかかった時間は、Intel Iris Xe Graphicsで0.7〜0.8秒でした。
|
||||
カーネルが1つの場合と、赤、緑、青で別のカーネルを使う場合の、2通りで行います。
|
||||
自己試験にかかった時間は、Intel Iris Xe Graphicsで、試験用のプロセスで
|
||||
6回続けて測ると0.47〜0.95秒でした。
|
||||
|
||||
- GPUの検査: GPUの経路で畳み込みを計算し直したフレームでは、
|
||||
出力を画面に出す前に、次の3つを調べます。1つ目は、
|
||||
NaNか無限大が無いことです。NaNは、計算の失敗で生じる、
|
||||
数として扱えない値です。2つ目は、利得を掛ける前の出力の総和が、
|
||||
素材の総和と合うことです。3つ目は、利得を掛ける前の出力の16か所の値が、
|
||||
倍精度で計算した値と合うことです。測定値は、GPUの結果から求めた値です。
|
||||
参照値は、測定値と比べる値で、素材の値から求めた値か、
|
||||
0のように初めから分かっている値です。許容値は、差として許す最大の値です。
|
||||
2つ目と3つ目の許容値は、丸めの誤差の上限から導いた値です。
|
||||
測定値と参照値の差が許容値以下なら合格、超えれば不合格とします。
|
||||
見つけられるのは、この3つに表れた誤りだけです。
|
||||
利得だけを変えたフレームのうち、キャッシュの項目にある保存した値に
|
||||
GPUで利得を掛け直すフレームでは、その計算を検査しません。
|
||||
出力を画面に出す前に、次の3つを調べます。1つ目は、NaNか無限大が無いことです。
|
||||
NaNは、計算の失敗で生じる、数として扱えない値です。2つ目は、
|
||||
利得を掛ける前の出力の総和が、素材の総和と合うことです。3つ目は、
|
||||
利得を掛ける前の出力の16か所の値が、倍精度で計算した値と合うことです。
|
||||
測定値は、GPUの結果から求めた値です。参照値は、測定値と比べる値で、
|
||||
素材の値から求めた値か、0のように初めから分かっている値です。許容値は、
|
||||
差として許す最大の値です。2つ目と3つ目の許容値は、
|
||||
丸めの誤差の上限から導いた値です。測定値と参照値の差が許容値以下なら合格、
|
||||
超えれば不合格とします。見つけられるのは、この3つに表れた誤りだけです。
|
||||
線形光かディザをオンにしたフレームでは、
|
||||
素材の総和をGPUが浮動小数点数で足して求めます。そのため、2つ目の検査は、
|
||||
素材を直す計算の誤りを見つけません。この誤りは、3つ目の検査が見つけます。
|
||||
利得だけを変えたフレームのうち、
|
||||
キャッシュの項目にある保存した値にGPUで利得を掛け直すフレームでは、
|
||||
その計算を検査しません。
|
||||
|
||||
- GPUの異常: 自己試験か検査で不合格になったこと、GPUが突然使えなくなったこと、
|
||||
GPUの経路で想定していない例外が起きたことを、GPUの異常と呼びます。
|
||||
@@ -134,15 +212,21 @@ CPUで計算します。
|
||||
送信する報告の数には、さらに上限があります。
|
||||
上限は、「不具合の報告」で説明しています。
|
||||
|
||||
- 処理対象: 畳み込みには現在のフレームの色と不透明度だけを使用します。
|
||||
履歴フレーム、外部画像、深度情報、学習済みモデルは使用しません。
|
||||
- 処理対象: 畳み込みには現在のフレームの色と不透明度を使用します。
|
||||
「奥行きを使う」がオンのときは、これに加えて、
|
||||
アイテムの座標とカメラの位置を使います。履歴フレーム、外部画像、
|
||||
画素ごとの深度情報、学習済みモデルは使用しません。
|
||||
素材のすべての画素が透明なときは、エフェクトを適用せず入力映像を表示します。
|
||||
|
||||
- 計算モデル: 計算は単色のフラウンホーファー回折に限ります。白色光の
|
||||
ように波長の混ざった光は扱いません。点像分布関数は画面のどこでも同じで、
|
||||
像の位置や素材の奥行きで変わるにじみは扱いません。畳み込みは、画素の値を
|
||||
そのまま重み付けして足し合わせます。画素の値を光の強さに比例する値へ
|
||||
直してから畳み込む処理はしません。
|
||||
- 計算モデル: 計算はフラウンホーファー回折に限ります。
|
||||
「色の扱い」が単色のときは、1つの波長で計算します。三原色と広帯域でも、
|
||||
赤、緑、青の成分を別々に畳み込むだけで、成分の間で光は混ざりません。
|
||||
ガラスの屈折率が波長で変わることによる色収差は扱いません。
|
||||
点像分布関数は画面のどこでも同じで、像の位置で変わるにじみは扱いません。
|
||||
奥行きは、アイテムごとに1つの距離で扱うので、
|
||||
1つのアイテムの中で画素ごとに変わるにじみは扱いません。畳み込みは、既定では、
|
||||
画素の値をそのまま重み付けして足し合わせます。線形光をオンにしたときだけ、
|
||||
画素の値を光の強さに比例する値へ直してから畳み込みます。
|
||||
|
||||
- 計算領域: 透明な部分も含む素材全体の矩形の上下左右に余白を加えた大きさを
|
||||
計算領域とし、長辺は8192画素が上限です。余白は、
|
||||
@@ -158,21 +242,24 @@ CPUで計算します。
|
||||
|
||||
- 処理負荷: 畳み込む範囲が大きいほど、計算は重くなります。畳み込む範囲は、
|
||||
素材の透明でない画素をすべて囲む最小の矩形をカーネル半径だけ広げ、
|
||||
外側の4画素の倍数の位置へそろえた範囲です。広げた範囲が計算領域の外へ
|
||||
出るときは、計算領域の端で切ります。
|
||||
畳み込む範囲を正方形のタイルに分け、タイルごとに高速フーリエ変換で
|
||||
畳み込みます。タイルの一辺Tは、カーネル半径が23画素以下なら128画素、
|
||||
24画素以上なら512画素です。
|
||||
外側の4画素の倍数の位置へそろえた範囲です。
|
||||
広げた範囲が計算領域の外へ出るときは、計算領域の端で切ります。
|
||||
畳み込む範囲を正方形のタイルに分け、
|
||||
タイルごとに高速フーリエ変換で畳み込みます。タイルの一辺Tは、
|
||||
カーネル半径が23画素以下なら128画素、24画素以上なら512画素です。
|
||||
タイルの縁からカーネル半径の幅の値は捨てるので、カーネル半径を上げるほど、
|
||||
1枚のタイルが出力できる範囲は狭まります。カーネル半径を上げても、
|
||||
Tが同じなら、必要なタイルの枚数は減らず、増えることがあります。
|
||||
枚数が増えるほど、計算は重くなります。カーネル半径を23画素から24画素に
|
||||
上げると、タイルが大きくなり、出力できる範囲が広がります。そのため、
|
||||
1枚のタイルが出力できる範囲は狭まります。カーネル半径を上げても、Tが同じなら、
|
||||
必要なタイルの枚数は減らず、増えることがあります。枚数が増えるほど、
|
||||
計算は重くなります。カーネル半径を23画素から24画素に上げると、
|
||||
タイルが大きくなり、出力できる範囲が広がります。そのため、
|
||||
畳み込む範囲が大きい素材では計算が軽くなることがあり、
|
||||
小さい素材ではかえって重くなることがあります。収差を入れても、
|
||||
畳み込みの計算量は変わりません。CPUの経路は、全く透明な行と、
|
||||
全く透明なタイルを省くので、素材の中身によっても時間が変わります。
|
||||
品質を上げると、点像分布関数の計算が重くなります。
|
||||
品質を上げると、点像分布関数の計算が重くなります。線形光をオンにすると、
|
||||
CPUの経路では、素材を線形の値へ直す計算が増えます。そのため、
|
||||
素材が変わるフレームの時間が長くなります。GPUの経路では、
|
||||
ほとんど変わりません。
|
||||
|
||||
- メモリ: エフェクト1つあたり、GPUの経路では、2つの共有テクスチャをGPUに
|
||||
確保します。素材を入れる共有テクスチャは、素材の1画素につき4バイトです。
|
||||
@@ -182,9 +269,11 @@ CPUで計算します。
|
||||
|
||||
- 作業領域: GPUの経路では、共有テクスチャのほかに、
|
||||
16MB以下のタイルの作業領域、カーネルを高速フーリエ変換したスペクトル、
|
||||
検査に使う値を書くバッファーを確保します。CPUの経路では、素材の画素の配列、
|
||||
出力の画素の配列、作業スレッドの作業領域をシステムメモリに確保します。
|
||||
作業領域のうち、タイルの分は合計で64MB以下です。このほかに、
|
||||
検査に使う値を書くバッファーを確保します。CPUの経路では、素材の画素の配列と
|
||||
出力の画素の配列をシステムメモリに確保します。作業スレッドの作業領域は、
|
||||
すべてのエフェクトで共有します。作業領域のうち、タイルの分は合計で
|
||||
64MB以下です。確保した作業領域は、YMM4を終了するまで解放しません。
|
||||
このほかに、
|
||||
素材を読むためのDirect2Dのビットマップと、出力を書くためのDirect2Dの
|
||||
ビットマップも確保します。出力を書くためのビットマップは、
|
||||
畳み込む範囲を収められる大きさで、収まらなくなったときだけ作り直します。
|
||||
@@ -193,18 +282,27 @@ CPUで計算します。
|
||||
キャッシュの項目にある保存した値のためのものです。
|
||||
|
||||
- キャッシュ: 素材の大きさと色と不透明度が変わらず、
|
||||
「利得」と「適用量」以外の項目も変わらないフレームでは、
|
||||
畳み込みの計算を再利用します。利得だけを変えたフレームでは、
|
||||
「利得」と「適用量」と「ディザ」以外の項目も変わらないフレームでは、
|
||||
畳み込みの計算を再利用します。利得かディザだけを変えたフレームでは、
|
||||
最初の1回だけ畳み込みを計算し直し、利得を掛ける前の値を保存します。
|
||||
2回目からは、保存した値に利得を掛け直します。素材か、
|
||||
「利得」と「適用量」以外の項目が変わると、保存した値を破棄します。
|
||||
2回目からは、保存した値に利得とディザを反映して描き直します。素材か、
|
||||
「利得」と「適用量」と「ディザ」以外の項目が変わると、保存した値を破棄します。
|
||||
ただし、線形光がオフのときは、ハイライトの2項目が変わっても破棄しません。
|
||||
適用量だけを変えたフレームでは、混ぜる割合だけを変えます。
|
||||
動画や口パクのように素材の内容が変わるフレームと、
|
||||
「利得」と「適用量」以外の項目をアニメーションで変えたフレームでは、
|
||||
毎回計算し直すので処理が重くなります。素材が変わったかどうかを調べる計算は、
|
||||
再利用するフレームでも毎フレーム行います。開口形状が円形のときは、
|
||||
「利得」と「適用量」と「ディザ」以外の項目をアニメーションで変えたフレームでは
|
||||
、毎回計算し直すので処理が重くなります。「奥行きを使う」がオンのとき、
|
||||
アイテムの距離か合焦距離が変わるフレームでも、毎回計算し直します。
|
||||
素材が変わったかどうかを調べる計算は、再利用するフレームでも毎フレーム
|
||||
行います。開口形状が円形のときは、
|
||||
「羽根枚数」と「開口回転」を変えても、計算し直しません。
|
||||
|
||||
- マネージドヒープ: 素材と設定が変わらず、
|
||||
アニメーションする項目が無いフレームでは、.NETのマネージドヒープに
|
||||
メモリを確保しません。適用量が0%のフレームでも同じです。
|
||||
アニメーションする項目の値をYMM4が取り出すときの確保は、
|
||||
本プラグインでは減らせません。
|
||||
|
||||
- 再現性: 計算は決定論的で、時間値や乱数を使用しません。
|
||||
同じ素材と同じ設定から常に同じ結果になるのは、同じ経路で、GPU、ドライバー、
|
||||
CPU、Windows、.NETの組が同じときです。GPUの経路でも結果にCPUが関わるのは、
|
||||
@@ -227,16 +325,23 @@ CPUで計算します。
|
||||
■ 不具合の報告
|
||||
--------------------------------------------------------------------------------
|
||||
本プラグインは、想定していない例外が起きたときと、GPUの異常でCPUの経路に
|
||||
切り替えたときに、その内容を開発者へ自動で送信します。同意は求めず、
|
||||
常に送信します。
|
||||
切り替えたときに、その内容を開発者へ自動で送信します。同意は求めません。
|
||||
止める設定もありません。
|
||||
|
||||
送信する数には上限があります。YMM4の1回の起動で送る報告は、
|
||||
YMM4-Telemetryで報告する別のプラグインと合わせて20件までです。
|
||||
例外の型と発生位置が同じ報告は3件までです。上限を超えた報告と、
|
||||
送信先から待つよう求められている間に起きた報告は、送信も退避もしません。
|
||||
|
||||
送信する情報は次のとおりです。
|
||||
例外 : 型の完全名、メッセージ、スタックトレース
|
||||
発生位置 : モジュール名、関数名、ファイル名、行番号
|
||||
発生位置 : モジュール名、関数名、ファイル名、行番号、
|
||||
プラグイン自身のコードかどうか
|
||||
プラグイン : アセンブリ名、バージョン
|
||||
実行環境 : OSの名前とバージョン、.NETのバージョン、
|
||||
CPUのアーキテクチャ、論理プロセッサ数
|
||||
識別子 : YMM4の起動ごとに決まるセッション識別子、報告ごとの識別子
|
||||
時刻 : 報告を作った時刻(UTC)
|
||||
GPUの異常 : 切り替えた理由、不合格になった検査の名前と測定値と
|
||||
参照値と許容値、アダプターの名前、ベンダーIDと
|
||||
デバイスIDとサブシステムIDとリビジョン、
|
||||
|
||||
+4
-4
@@ -1,12 +1,12 @@
|
||||
[submodule "YukkuriMovieMaker.Generator"]
|
||||
path = YukkuriMovieMaker.Generator
|
||||
url = https://github.com/manju-summoner/YukkuriMovieMaker.Generator.git
|
||||
url = https://git.routersys.com/manju-summoner/YukkuriMovieMaker.Generator.git
|
||||
[submodule "YMM4-GitHubUpdateNotifier"]
|
||||
path = YMM4-GitHubUpdateNotifier
|
||||
url = https://github.com/routersys/YMM4-GitHubUpdateNotifier.git
|
||||
url = https://git.routersys.com/routersys/YMM4-GitHubUpdateNotifier.git
|
||||
[submodule "YMM4-Telemetry"]
|
||||
path = YMM4-Telemetry
|
||||
url = https://github.com/routersys/YMM4-Telemetry.git
|
||||
url = https://git.routersys.com/routersys/YMM4-Telemetry.git
|
||||
[submodule "YMM4-ComputeGuard"]
|
||||
path = YMM4-ComputeGuard
|
||||
url = https://github.com/routersys/YMM4-ComputeGuard.git
|
||||
url = https://git.routersys.com/routersys/YMM4-ComputeGuard.git
|
||||
@@ -8,10 +8,15 @@
|
||||
|
||||
YukkuriMovieMaker4(YMM4)上で動作する、素材を回折も収差もない理想の像とみなし、レンズの開口と波面収差から求めた点像分布関数で畳み込んで、回折と収差によるにじみを描画する映像エフェクトプラグインです。
|
||||
点像分布関数は、瞳関数のフラウンホーファー回折を高速フーリエ変換で解いて求めます。
|
||||
履歴フレーム、参照画像、学習済みモデルを使わず、入力された一枚の映像だけを処理します。
|
||||
「色の扱い」を三原色か広帯域にすると、赤、緑、青の成分を別の波長で計算して、光源の縁に色づきを描きます。
|
||||
「奥行きを使う」は、デフォーカスの大きさを、アイテムのカメラからの距離と合焦距離の差で決める項目です。
|
||||
履歴フレーム、参照画像、学習済みモデルを使わず、入力された一枚の映像を処理します。アイテムの座標とカメラの位置も使うのは、「奥行きを使う」をオンにしたときだけです。
|
||||
にじみの形は光学系と収差の設定から決定論的に決まり、同じ設定では常に同じ形になります。
|
||||
適用量、利得、波長、F値、画素ピッチ、開口回転、中央遮蔽、デフォーカス、縦横非点収差、斜め非点収差、水平コマ収差、垂直コマ収差、球面収差の13項目はアニメーションに対応しています。
|
||||
適用量、利得、ハイライト閾値、ハイライト強度、波長、F値、画素ピッチ、開口回転、中央遮蔽、デフォーカス、縦横非点収差、斜め非点収差、水平コマ収差、垂直コマ収差、球面収差、合焦距離、焦点距離の17項目はアニメーションに対応しています。
|
||||
畳み込みはGPUで計算します。畳み込みを計算し直したフレームでは、その結果を画面に出す前に検査します。GPUを使えないときと、検査で誤りを見つけたときは、CPUで計算します。
|
||||
「線形光」をオンにすると、画素の値を光の強さに比例する値へ直してから畳み込みます。「ハイライト強度」を上げると、光源のような明るい部分を持ち上げて、回折の筋のような小さな光を見えるようにできます。
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
@@ -25,13 +30,16 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を回折も収差もな
|
||||
- [2. 光学系の項目とにじみの大きさ](#2-光学系の項目とにじみの大きさ)
|
||||
- [3. 開口の形と中央遮蔽](#3-開口の形と中央遮蔽)
|
||||
- [4. ゼルニケ多項式による波面収差](#4-ゼルニケ多項式による波面収差)
|
||||
- [5. タイルごとの高速フーリエ変換による畳み込み](#5-タイルごとの高速フーリエ変換による畳み込み)
|
||||
- [6. 利得と適用量](#6-利得と適用量)
|
||||
- [7. 品質の選択](#7-品質の選択)
|
||||
- [8. GPUの計算の検査とCPUの経路](#8-gpuの計算の検査とcpuの経路)
|
||||
- [5. 奥行きによるデフォーカス](#5-奥行きによるデフォーカス)
|
||||
- [6. タイルごとの高速フーリエ変換による畳み込み](#6-タイルごとの高速フーリエ変換による畳み込み)
|
||||
- [7. 利得と適用量](#7-利得と適用量)
|
||||
- [8. 線形光とハイライトとディザ](#8-線形光とハイライトとディザ)
|
||||
- [9. 品質の選択](#9-品質の選択)
|
||||
- [10. GPUの計算の検査とCPUの経路](#10-gpuの計算の検査とcpuの経路)
|
||||
5. [パラメータ一覧](#パラメータ一覧)
|
||||
- [出力グループ](#出力グループ)
|
||||
- [光学系グループ](#光学系グループ)
|
||||
- [奥行きグループ](#奥行きグループ)
|
||||
- [開口グループ](#開口グループ)
|
||||
- [波面収差グループ](#波面収差グループ)
|
||||
6. [制限事項](#制限事項)
|
||||
@@ -59,7 +67,7 @@ GPUの経路では、ComputeWeaveの計算シェーダーがDirect3D 12で計算
|
||||
|
||||
GPUにある値をCPUが読み取ることを、読み戻しと呼びます。GPUの経路では、フレームごとに読み戻すのは、素材の全画素ではなく、7個の整数です。7個の整数は、素材の色と不透明度から作る2個のハッシュ、透明でない画素の数、外接矩形の位置を表す4個の値です。ハッシュは、素材の内容を短い数値にまとめた値で、素材が変わったかどうかの判定に使います。畳み込みを計算し直すフレームでは、これに加えて、検査に使う値も読み戻します。検査に使う値には、出力の16か所の値と、各か所の周りの素材の値が含まれます。検査は「GPUの計算の検査とCPUの経路」にあります。CPUの経路では、素材の画素を毎フレーム読み込み、ハッシュと外接矩形を、GPUの経路と同じ定義でCPUが求めます。
|
||||
|
||||
素材が変わらず、「利得」と「適用量」以外の項目も変わらないフレームでは、畳み込みの計算を再利用します。
|
||||
素材が変わらず、「利得」と「適用量」と「ディザ」以外の項目も変わらないフレームでは、畳み込みの計算を再利用します。
|
||||
|
||||
このエフェクトはAviUtl向けのEXO出力には対応していません。
|
||||
|
||||
@@ -95,13 +103,23 @@ GPUにある値をCPUが読み取ることを、読み戻しと呼びます。GP
|
||||
|
||||
畳み込みの重みは、点像分布関数から値を取り出して作ります。取り出すのは、中心から上下左右に「カーネル半径」の画素数までの正方形の範囲です。重みをこの正方形に並べたものを、カーネルと呼びます。カーネルの各画素の値は、画素の中心の位置で点像分布関数を補間した値で、画素の面積にわたる平均ではありません。カーネルの値の和は1になるように正規化します。カーネルの外に届く光は捨てるため、正規化によってカーネルの値がその分だけ大きくなります。
|
||||
|
||||
点像分布関数とカーネルと、カーネルを高速フーリエ変換したスペクトルは、「利得」と「適用量」以外のどれかの項目が変わったフレームでだけ、CPUで作り直します。
|
||||
点像分布関数とカーネルと、カーネルを高速フーリエ変換したスペクトルは、光学系グループと開口グループと波面収差グループのどれかの項目が変わったフレームでだけ、CPUで作り直します。「色の扱い」が三原色か広帯域のときは、「波長」を変えても作り直しません。三原色と広帯域では、波長ごとの瞳関数の変換と、色ごとのスペクトルの計算を、最大6スレッドに分けて行います。
|
||||
|
||||
### 2. 光学系の項目とにじみの大きさ
|
||||
|
||||
円形の開口で収差がないときの点像分布関数は、エアリーパターンと呼ばれる、明るい円盤と周りの薄い輪の形になります。明るい円盤の半径は、波長とF値の積の1.22倍です。デフォルトの波長550nm、F値8、画素ピッチ4μmでは、明るい円盤の半径は約5.4μmで、約1.3画素です。そのため、デフォルトの設定では、映像はわずかにやわらぐだけです。にじみを大きくするには、F値か波長を上げるか、画素ピッチを下げます。
|
||||
|
||||
「波長」は、単色光として計算する光の波長です。長いほど回折による広がりが大きくなります。赤、緑、青の成分と不透明度は同じ点像分布関数で畳み込むので、波長を変えても映像の色は変わりません。
|
||||
「色の扱い」は、赤、緑、青の成分を、どの波長の点像分布関数で畳み込むかを選びます。
|
||||
|
||||
- 単色: 赤、緑、青の成分と不透明度を、「波長」で指定した1つの波長の点像分布関数で畳み込みます。デフォルトです。波長を変えても、映像の色は変わりません。
|
||||
- 三原色: 赤を610nm、緑を550nm、青を465nmの点像分布関数で、それぞれ畳み込みます。不透明度は、緑と同じ点像分布関数で畳み込みます。波長が長い赤ほど回折による広がりが大きいので、光源の縁では、赤が外側へ、青が内側へ寄って色づきます。
|
||||
- 広帯域: 赤、緑、青のそれぞれを、三原色と同じ波長を中心にした帯の点像分布関数の、重み付きの平均で畳み込みます。重みは標準偏差21nmのガウス分布で、帯は中心から標準偏差の2.5倍までです。波長ごとに輪の位置がずれるので、平均すると輪がなめらかになります。
|
||||
|
||||
三原色と広帯域では、「波長」を使いません。三原色の波長は、sRGBの原色の主波長を丸めた値です。主波長は、CIE 1931の等色関数の近似式から求めると、赤が約611nm、緑が約549nm、青が約463nmです。帯の幅の21nmは、機器に依らず仮に決めた値で、半値幅は約49nmです。素材の画素の値からは光の分光分布が分からないので、どちらの値も実際の機器の値ではありません。
|
||||
|
||||
三原色と広帯域では、波面収差の係数の単位wavesを、550nmの波長を1とした量にして、光路差を波長によらず一定にします。波長ごとの位相は、光路差を波長で割った値になります。単色では、wavesで位相を固定するので、波長を変えるとデフォーカスの玉ボケの大きさも波長に比例して変わります。三原色と広帯域では、玉ボケの大きさが赤、緑、青で同じになり、色づきは回折の縁だけに出ます。デフォーカスを3 waves、品質を高精度、F値を8、画素ピッチを4μm、カーネル半径を63画素にして、光の90%が収まる中心からの距離を測ると、三原色では赤が42.5画素、緑と青が42.4画素でした。単色で波長を610nm、550nm、465nmにすると、47.0画素、42.4画素、36.1画素でした。
|
||||
|
||||
三原色と広帯域では、点像分布関数の標本の間隔を、全部の波長で550nmのときの間隔にそろえます。波長が短いほど瞳の標本を多く取るので、青でも、点像分布関数を求める範囲が緑とほぼ同じになります。
|
||||
|
||||
「F値」は、開口の直径に対する焦点距離の比です。大きいほど開口が小さくなり、回折による広がりが大きくなります。
|
||||
|
||||
@@ -109,60 +127,117 @@ GPUにある値をCPUが読み取ることを、読み戻しと呼びます。GP
|
||||
|
||||
「カーネル半径」は、カーネルの正方形が中心から上下左右に何画素まで広がるかを決めます。設定できるのは1〜63画素で、デフォルトは15画素です。
|
||||
|
||||
点像分布関数がカーネルの正方形の外まで広がる設定では、外側の輪やにじみの端が切り取られます。デフォーカスは、波面収差グループの項目で、焦点の位置のずれを表します。単位のwavesは、波長を1とした量です。デフォルトの光学系でデフォーカスを1 wavesにすると、にじみは中心から約15画素まで広がります。デフォーカスの絶対値を大きくするときは、カーネル半径を上げてください。
|
||||
点像分布関数がカーネルの正方形の外まで広がる設定では、外側の輪やにじみの端が切り取られます。デフォーカスは、波面収差グループの項目で、焦点の位置のずれを表します。単位のwavesは、単色では「波長」で指定した波長を、三原色と広帯域では550nmを1とした量です。デフォルトの光学系でデフォーカスを1 wavesにすると、にじみは中心から約15画素まで広がります。デフォーカスの絶対値を大きくするときは、カーネル半径を上げてください。デフォーカスは、アイテムの奥行きから決めて加えることもできます。決め方は「奥行きによるデフォーカス」にあります。
|
||||
|
||||
「品質」は、瞳関数を置く格子の大きさを選ぶ項目で、「品質の選択」で説明します。点像分布関数を求める範囲は、「品質」と、波長とF値の積で決まります。カーネルのうち、この範囲の外になる画素は0になります。デフォルトの波長550nmとF値8で、標準の品質のとき、範囲は中心から上下左右に約141μmです。画素ピッチ4μmでは、約35画素です。カーネル半径がこの範囲を超えるときは、品質を上げてください。範囲の大きさは「品質の選択」の表にあります。品質を上げるほど、点像分布関数の計算は重くなります。カーネル半径と計算の重さの関係は、「タイルごとの高速フーリエ変換による畳み込み」にあります。
|
||||
|
||||
### 3. 開口の形と中央遮蔽
|
||||
|
||||
「開口形状」は、円形と正多角形から選びます。正多角形は、カメラの絞りの羽根が作る開口をまねた形で、頂点は円形の開口と同じ直径の円の上にあります。頂点までの距離を開口の半径とします。辺の数は「羽根枚数」で、向きは「開口回転」で決めます。正多角形の開口では、点像分布関数が辺と垂直な向きへ伸びます。デフォーカスでにじみが大きいときは、にじみが、開口と同じ辺の数の正多角形の形になります。にじみが切り取られないよう、カーネル半径と品質を上げてください。「羽根枚数」と「開口回転」は、開口形状が正多角形のときだけ働きます。
|
||||
「開口形状」は、円形と正多角形から選びます。正多角形は、カメラの絞りの羽根が作る開口をまねた形で、頂点は円形の開口と同じ直径の円の上にあります。頂点までの距離を開口の半径とします。辺の数は「羽根枚数」で、向きは「開口回転」で決めます。正多角形の開口では、点像分布関数が辺と垂直な向きへ伸びます。デフォーカスでにじみが大きいときは、にじみが、開口と同じ辺の数の正多角形の形になります。にじみが切り取られないよう、カーネル半径と品質を上げてください。「羽根枚数」と「開口回転」は、開口形状が正多角形のときだけ働くので、円形のときは設定の画面に表示されません。
|
||||
|
||||
「中央遮蔽」は、反射望遠鏡の副鏡のように開口の中央をふさぐ円の大きさで、開口の半径に対する割合です。値を上げると中心の明るさが下がり、周りの輪へ光が移ります。中央遮蔽は、どちらの開口形状でも、中央を円でふさぎます。
|
||||
|
||||
### 4. ゼルニケ多項式による波面収差
|
||||
|
||||
波面収差グループの6項目は、ゼルニケ多項式の6つの項の係数です。ゼルニケ多項式は、円形の開口の上の波面収差を、互いに直交する基本の形の和で表す多項式です。係数の単位はwavesで、波長を1とした量です。本プラグインの各項は、開口と同じ半径の円の内側全体で、二乗平均平方根が1になるように正規化しています。二乗平均平方根は、値の2乗を円の内側全体で平均して平方根を取ったもので、波面収差の大きさの目安です。円形で中央遮蔽の無い開口では、係数1 wavesの項による波面収差は、二乗平均平方根で波長1つ分です。正多角形の開口と中央遮蔽のある開口では、光の通る部分だけで測ると、この値からずれます。
|
||||
波面収差グループの6項目は、ゼルニケ多項式の6つの項の係数です。ゼルニケ多項式は、円形の開口の上の波面収差を、互いに直交する基本の形の和で表す多項式です。係数の単位はwavesで、単色では「波長」で指定した波長を、三原色と広帯域では550nmを1とした量です。本プラグインの各項は、開口と同じ半径の円の内側全体で、二乗平均平方根が1になるように正規化しています。二乗平均平方根は、値の2乗を円の内側全体で平均して平方根を取ったもので、波面収差の大きさの目安です。円形で中央遮蔽の無い開口では、係数1 wavesの項による波面収差は、二乗平均平方根で波長1つ分です。正多角形の開口と中央遮蔽のある開口では、光の通る部分だけで測ると、この値からずれます。
|
||||
|
||||
表のρは開口の半径を1とした中心からの距離、θは水平方向から測った角度です。
|
||||
表の$\rho$は開口の半径を1とした中心からの距離、$\theta$は水平方向から測った角度です。
|
||||
|
||||
| 項目 | 多項式 | 意味 |
|
||||
|---|---|---|
|
||||
| デフォーカス | √3(2ρ²-1) | 焦点の位置のずれ |
|
||||
| 縦横非点収差 | √6ρ²cos2θ | 水平方向と垂直方向で焦点の位置が違うずれ |
|
||||
| 斜め非点収差 | √6ρ²sin2θ | 45度傾いた2つの方向で焦点の位置が違うずれ |
|
||||
| 水平コマ収差 | √8(3ρ³-2ρ)cosθ | 像が水平方向の片側へ尾を引くずれ |
|
||||
| 垂直コマ収差 | √8(3ρ³-2ρ)sinθ | 像が垂直方向の片側へ尾を引くずれ |
|
||||
| 球面収差 | √5(6ρ⁴-6ρ²+1) | 開口の中心と縁で焦点の位置が違うずれ |
|
||||
| デフォーカス | $\sqrt{3}(2\rho^2 - 1)$ | 焦点の位置のずれ |
|
||||
| 縦横非点収差 | $\sqrt{6}\rho^2\cos 2\theta$ | 水平方向と垂直方向で焦点の位置が違うずれ |
|
||||
| 斜め非点収差 | $\sqrt{6}\rho^2\sin 2\theta$ | 45度傾いた2つの方向で焦点の位置が違うずれ |
|
||||
| 水平コマ収差 | $\sqrt{8}(3\rho^3 - 2\rho)\cos\theta$ | 像が水平方向の片側へ尾を引くずれ |
|
||||
| 垂直コマ収差 | $\sqrt{8}(3\rho^3 - 2\rho)\sin\theta$ | 像が垂直方向の片側へ尾を引くずれ |
|
||||
| 球面収差 | $\sqrt{5}(6\rho^4 - 6\rho^2 + 1)$ | 開口の中心と縁で焦点の位置が違うずれ |
|
||||
|
||||
### 5. タイルごとの高速フーリエ変換による畳み込み
|
||||
### 5. 奥行きによるデフォーカス
|
||||
|
||||
「奥行きを使う」をオンにすると、アイテムのカメラからの距離と「合焦距離」の差から、デフォーカスを決めます。決めた値は、波面収差グループの「デフォーカス」に加えます。距離が合焦距離と等しいアイテムには、デフォーカスが加わりません。合焦距離より遠いアイテムには正の値、近いアイテムには負の値が加わり、差が大きいほど絶対値が大きくなります。「合焦距離」はアニメーションに対応しており、値を動かすと、ピントが合う距離が動きます。「奥行きを使う」がオフのときは、距離を使わず、「合焦距離」と「焦点距離」は設定の画面に表示されません。
|
||||
|
||||
球面収差と非点収差が0のとき、コマ収差の有無によらず、正の値と負の値で点像分布関数の形は同じです。球面収差か非点収差を入れると、正の値と負の値で形が違うので、合焦距離より遠いアイテムと近いアイテムで、にじみの形が変わります。
|
||||
|
||||
距離は、アイテムの座標の位置から、カメラの光軸に沿って測った長さです。YMM4の座標の1を1mmとして扱います。カメラの位置と画角が既定のとき、座標のZが0のアイテムの距離は1000で、「合焦距離」のデフォルトと同じです。画面での大きさは距離に反比例するので、アイテムが画面に大きく映るほど、距離は短くなります。
|
||||
|
||||
アイテム自身の座標(X、Y、Z)は、エフェクトの並びによらず、距離に反映されます。座標を変えるエフェクトと、カメラの位置、向き、画角を変えるエフェクトは、このエフェクトより上に並べたものだけが対象です。グループ制御のように、このエフェクトより後に適用されるものは対象外です。アイテムがカメラの位置か、それより後ろにあって距離が0以下のときと、透視距離が無限大のときは、距離が決まらないので、デフォーカスを加えません。
|
||||
|
||||
焦点距離を$f$、F値を$N$、合焦距離を$z_f$、アイテムの距離を$z$とすると、デフォーカスは次の式で決まります。長さの単位はmmです。
|
||||
|
||||
$$
|
||||
\begin{aligned}
|
||||
\text{光路差} &= \frac{f^2}{8 \times N^2} \times \frac{z - z_f}{z \times (z_f - f)} \\
|
||||
\text{デフォーカス} &= \frac{\text{光路差}}{2\sqrt{3} \times \text{基準の波長}}
|
||||
\end{aligned}
|
||||
$$
|
||||
|
||||
基準の波長は、「色の扱い」が単色のときは「波長」の値で、三原色と広帯域のときは550nmです。ゼルニケ多項式のデフォーカスの項は、係数が1 wavesのとき、開口の縁と中心の光路差が、基準の波長の$2\sqrt{3}$倍になります。そのため、光路差を$2\sqrt{3}$と基準の波長の積で割った値が、デフォーカスの係数です。
|
||||
|
||||
この式は、薄いレンズの近軸の式です。デフォーカスが作る円盤状のにじみの半径は、レンズの式から求めた錯乱円の半径と一致します。画素単位の錯乱円の半径は、画素ピッチを$p$(mmで表した値)として、$\dfrac{f^2}{2 \times N \times p} \times \dfrac{\lvert z - z_f \rvert}{z \times (z_f - f)}$です。合焦距離が焦点距離よりはるかに遠いとき、この半径は$\dfrac{f^2}{2 \times N \times p} \times \left\lvert \dfrac{1}{z_f} - \dfrac{1}{z} \right\rvert$に近づきます。回折の広がりはF値で決まり、ピントを合わせたことによる実効F値の変化は含みません。基準の波長が550nm、焦点距離50mm、F値8、画素ピッチ4μm、合焦距離2000mmのとき、距離5000mmのアイテムのデフォーカスは約0.789 wavesで、錯乱円の半径は約12.0画素です。
|
||||
|
||||
距離か合焦距離が焦点距離の1.001倍より短いときは、焦点距離の1.001倍として扱います。デフォーカスは、「デフォーカス」に加えたあと、-10〜10 wavesの範囲に収めます。にじみの半径がカーネル半径を超えると、にじみの端が切り取られるので、デフォーカスの絶対値が大きいときは、カーネル半径を上げてください。
|
||||
|
||||
距離と合焦距離は、フレームごとに読みます。どちらかが変わったフレームでは、「デフォーカス」を変えたフレームと同じく、点像分布関数とカーネルのスペクトルを作り直します。アイテムは1つの距離で扱うので、畳み込みの回数は増えません。
|
||||
|
||||
### 6. タイルごとの高速フーリエ変換による畳み込み
|
||||
|
||||
畳み込む範囲を、一辺T画素の正方形のタイルに分けて畳み込みます。Tは、カーネル半径が23画素以下なら128、24画素以上なら512です。1枚のタイルは、一辺T画素の範囲の素材を読み、高速フーリエ変換で畳み込みます。この畳み込みでは、タイルの縁の近くに、反対側の縁の値が回り込んで混ざります。そのため、タイルの縁からカーネル半径の幅の値は捨て、中央の正方形だけを出力します。この正方形の一辺は、Tからカーネル半径の2倍を引いた画素数です。このようにタイルの縁を捨てて中央だけを使う方法を、オーバーラップセーブ法と呼びます。
|
||||
|
||||
高速フーリエ変換では、赤と緑、青と不透明度をそれぞれ1つの複素数にまとめ、1回の変換で2つの成分を計算します。
|
||||
|
||||
「色の扱い」が三原色か広帯域のときは、行ごとの変換のあとで、実数の行の対称性を使って、赤と緑、青と不透明度を分けます。列ごとの変換のあとで、赤、緑、青にそれぞれのスペクトルを掛け、逆変換のあとで、また1つの複素数にまとめます。不透明度には、緑のスペクトルを掛けます。タイルごとの変換の回数は、単色と同じです。スペクトルは単色の3枚分ですが、GPUへ送るのは、横方向の周波数が0からT/2までの半分だけで、単色の1.5倍です。
|
||||
|
||||
GPUの経路の畳み込みの計算量は、カーネルの形によらず、畳み込む範囲の大きさとカーネル半径で決まります。収差を入れても、畳み込みの計算は重くなりません。ただし、収差を変えるたびに、点像分布関数とカーネルのスペクトルを作り直す時間がかかります。CPUの経路は、全く透明な行と、全く透明なタイルの計算を省くので、素材の中身によっても時間が変わります。
|
||||
|
||||
Tが同じなら、カーネル半径を上げるほど、1枚のタイルが出力できる範囲は狭まります。そのため、必要なタイルの枚数は減らず、増えることがあります。枚数が増えるほど、計算は重くなります。カーネル半径が24画素以上になるとTが512に変わり、出力できる範囲が広がります。このため、畳み込む範囲が大きい素材では、GPUの経路で、カーネル半径が31画素のときの時間が、15画素のときとほぼ同じになります。畳み込む範囲が小さい素材では、24画素以上にするとかえって重くなることがありますが、この場合の実測値は表にありません。畳み込む範囲が大きい素材の実測値は、次の計算時間の表にあります。
|
||||
|
||||
計算時間は、試験用に作った1920×1080の画像で測りました。測った環境は、Intel Core i7-1360PのCPUと、Intel Iris Xe GraphicsのGPUです。CPUの論理プロセッサの数は16です。画像の透明でない部分は、1455×778画素の矩形に収まります。畳み込む範囲は、カーネル半径が15画素のとき1488×808画素、31画素のとき1520×840画素、63画素のとき1584×904画素です。画面全体が透明でない映像では、畳み込む範囲がこれより広くなるので、時間は表より長くなります。
|
||||
|
||||
測定は3回行いました。1回の測定では、表の行ごとに12フレームを計算し、フレームごとの時間を短い順に並べて、7番目の値を求めました。この値は、12フレームの中央に近い値です。表には、3回の測定で得た3つの値の、最小値から最大値までを示します。品質はどの行も標準で、ほかの項目はデフォルトです。ただし、カーネル半径31画素と63画素の行は、デフォーカス2 waves、水平コマ収差1 wavesにしています。「変えたもの」の列は、1フレームごとに値を入れ替えた項目です。入れ替えた値は、次のとおりです。
|
||||
測定は、続けて5回行いました。1回の測定では、表の行ごとに12フレームを計算し、フレームごとの時間を短い順に並べて、7番目の値を求めました。この値は、12フレームの中央に近い値です。表には、5回の測定で得た5つの値の、最小値から最大値までを示します。同じ行でも回によって、最大で1.3倍ほど違います。そのため、行どうしの比べ方は、表を分けた組の中で、同じ回の値どうしにしてください。組の中の行は、同じ回の中で、順番を無作為に入れ替えて測っています。品質はどの行も標準で、ほかの項目はデフォルトです。ただし、カーネル半径31画素と63画素の行は、デフォーカス2 waves、水平コマ収差1 wavesにしています。「変えたもの」の列は、1フレームごとに値を入れ替えた項目です。入れ替えた値は、次のとおりです。
|
||||
|
||||
- 素材: 元の画像と、その左右を反転した画像
|
||||
- デフォーカス: 0と0.1 waves
|
||||
- 利得: 100%と150%
|
||||
|
||||
表の時間は、素材が変わったかどうかの判定と、畳み込みの計算を合わせた値です。デフォーカスの行は、点像分布関数とカーネルのスペクトルをCPUで求める時間と、GPUへ送る時間も含みます。利得の行は、保存した値に利得を掛け直す時間です。保存した値は、「利得と適用量」の節で説明しています。GPUの経路の時間に含まないものは、2つあります。1つは、畳み込みを計算し直すたびの検査で、値を読み戻して比べる時間です。もう1つは、YMM4との間で素材と結果を受け渡す時間です。CPUの経路の時間に含まないものは、Direct2Dのビットマップとの間で画素を読み書きする時間です。表に含まない時間は、実際のフレームでは別にかかります。
|
||||
2つ目の表の「素材」の行は、1つ目の表の「素材」の行と同じ設定の、比べるための行です。素材の線形光の行は、線形光をオンにして、素材を「素材」の行と同じように入れ替えています。素材の線形光とハイライトの行は、さらにハイライト閾値を70%、強さを30倍にしています。合成した画像の画素の最も明るいチャンネルの値は、最大で0.9なので、しきい値を70%にしました。
|
||||
|
||||
表の時間は、素材が変わったかどうかの判定と、畳み込みの計算を合わせた値です。デフォーカスの行は、点像分布関数とカーネルのスペクトルをCPUで求める時間と、GPUへ送る時間も含みます。利得の行は、保存した値に利得を掛け直す時間です。保存した値は、「利得と適用量」の節で説明しています。「検査あり」の行は、畳み込みを計算し直すたびの検査を含みます。検査は、GPUが書いた値を読み戻して、CPUで求めた値と比べる処理です。ほかのGPUの行は、検査を含みません。実際のフレームでは、検査が毎回行われます。GPUの経路の時間に含まないものは、YMM4との間で素材と結果を受け渡す時間です。CPUの経路の時間に含まないものは、Direct2Dのビットマップとの間で画素を読み書きする時間です。表に含まない時間は、実際のフレームでは別にかかります。
|
||||
|
||||
| 変えたもの | カーネル半径 | GPUの経路 | CPUの経路 |
|
||||
|---|---:|---:|---:|
|
||||
| 素材 | 15画素 | 8.4〜9.6ミリ秒 | 61.0〜84.5ミリ秒 |
|
||||
| 素材 | 31画素 | 8.1〜10.0ミリ秒 | 測っていません |
|
||||
| 素材 | 63画素 | 13.4〜14.4ミリ秒 | 141.4〜177.1ミリ秒 |
|
||||
| デフォーカス | 15画素 | 12.5〜15.2ミリ秒 | 測っていません |
|
||||
| 利得 | 15画素 | 2.8〜4.2ミリ秒 | 12.3〜16.8ミリ秒 |
|
||||
| 素材 | 15画素 | 6.3〜8.3ミリ秒 | 10.6〜12.6ミリ秒 |
|
||||
| 素材 | 31画素 | 7.2〜8.0ミリ秒 | 測っていません |
|
||||
| 素材 | 63画素 | 12.6〜14.4ミリ秒 | 27.9〜35.8ミリ秒 |
|
||||
| 素材(検査あり) | 15画素 | 7.4〜8.4ミリ秒 | |
|
||||
| デフォーカス | 15画素 | 7.6〜8.9ミリ秒 | 測っていません |
|
||||
| 利得 | 15画素 | 1.9〜2.2ミリ秒 | 2.5〜2.6ミリ秒 |
|
||||
|
||||
素材と設定が変わらず、畳み込みを再利用するフレームでは、GPUの経路で1.4〜1.9ミリ秒でした。この時間は、素材が変わったかどうかの判定の時間です。
|
||||
| 変えたもの | カーネル半径 | GPUの経路 | CPUの経路 |
|
||||
|---|---:|---:|---:|
|
||||
| 素材 | 15画素 | 6.2〜6.5ミリ秒 | 16.3〜20.6ミリ秒 |
|
||||
| 素材(検査あり) | 15画素 | 7.0〜7.7ミリ秒 | |
|
||||
| 素材の線形光 | 15画素 | 6.8〜7.7ミリ秒 | 20.1〜24.3ミリ秒 |
|
||||
| 素材の線形光(検査あり) | 15画素 | 7.7〜8.6ミリ秒 | |
|
||||
| 素材の線形光とハイライト | 15画素 | 6.8〜7.8ミリ秒 | 25.6〜28.3ミリ秒 |
|
||||
|
||||
2つ目の表で、同じ回の「素材」の行との差は、CPUの経路で、線形光の行が16〜33%、線形光とハイライトの行が33〜59%の増加です。GPUの経路では、線形光の行が5〜25%、線形光とハイライトの行が6〜19%の増加です。
|
||||
|
||||
素材と設定が変わらず、畳み込みを再利用するフレームでは、GPUの経路で1.1〜1.4ミリ秒でした。この時間は、素材が変わったかどうかの判定の時間です。
|
||||
|
||||
色の扱いは、3つ目の表で測りました。測り方は上の表と同じで、5回の測定の最小〜最大です。デフォーカスは1 waves、素材は上の表と同じです。「素材」の行は、光学系を変えずに素材だけを入れ替えた行です。「デフォーカス」の行は、素材を変えずに、デフォーカスを1 wavesと1.1 wavesに交互に変えた行です。表の時間は、素材が変わったかどうかの判定と、畳み込みの計算を合わせた値で、デフォーカスの行は、点像分布関数とカーネルのスペクトルをCPUで求める時間と、GPUへ送る時間も含みます。
|
||||
|
||||
| 変えたもの | 品質とカーネル半径 | 経路 | 単色 | 三原色 | 広帯域 |
|
||||
|---|---|---|---:|---:|---:|
|
||||
| 素材 | 標準、15画素 | GPU | 6.1〜7.1ミリ秒 | 6.2〜6.7ミリ秒 | 6.2〜6.5ミリ秒 |
|
||||
| 素材 | 標準、15画素 | CPU | 14.7〜17.4ミリ秒 | 13.8〜17.1ミリ秒 | 13.2〜15.9ミリ秒 |
|
||||
| 素材 | 高精度、40画素 | GPU | 7.2〜7.7ミリ秒 | 7.0〜7.5ミリ秒 | 6.8〜7.5ミリ秒 |
|
||||
| 素材 | 高精度、40画素 | CPU | 24.9〜29.4ミリ秒 | 27.8〜32.8ミリ秒 | 26.8〜32.3ミリ秒 |
|
||||
| デフォーカス | 標準、15画素 | GPU | 6.9〜7.3ミリ秒 | 7.0〜7.5ミリ秒 | 7.9〜9.5ミリ秒 |
|
||||
| デフォーカス | 標準、15画素 | CPU | 13.0〜14.6ミリ秒 | 13.9〜16.6ミリ秒 | 14.9〜16.3ミリ秒 |
|
||||
| デフォーカス | 高精度、40画素 | GPU | 10.9〜11.7ミリ秒 | 12.9〜13.6ミリ秒 | 21.1〜21.6ミリ秒 |
|
||||
| デフォーカス | 高精度、40画素 | CPU | 27.9〜30.0ミリ秒 | 30.9〜34.2ミリ秒 | 39.3〜41.1ミリ秒 |
|
||||
|
||||
デフォーカスを変えるフレームのGPUの経路では、同じ回の単色の行との差が、三原色で次の値になります。標準の15画素は0.1〜0.5ミリ秒、高精度の40画素は1.5〜2.4ミリ秒です。広帯域の差は、標準の15画素が0.9〜2.2ミリ秒、高精度の40画素が9.5〜10.4ミリ秒です。広帯域は、波長ごとに瞳関数を変換する回数が、標準の品質で9回、高精度で15回あります。素材だけが変わるフレームのGPUの経路では、三原色と広帯域の時間は、同じ回の単色の行の0.88〜1.10倍です。
|
||||
|
||||
高速フーリエ変換による畳み込みは、画素の値にカーネルの重みを掛けて直接足し合わせる畳み込みと、同じ結果になるはずの計算です。32ビットの浮動小数点数で計算するため、値の丸めによる誤差が生じます。誤差の上限は、タイルの一辺Tごとに導いてあります。導出の全文は、このリポジトリの畳み込みのライブラリ[SpectralConvolution](SpectralConvolution/README.md)の説明にあります。タイルの全画素が不透明な白という最悪の場合について、誤差の上限を、8ビットの値の1階調分を単位にして示します。小数第2位まで切り上げた値です。
|
||||
|
||||
@@ -173,6 +248,8 @@ Tが同じなら、カーネル半径を上げるほど、1枚のタイルが出
|
||||
|
||||
表の値は、8ビットに丸める前の出力の誤差の上限で、8ビットに丸めるときの誤差を含みません。利得は100%としています。実際の素材の誤差は、利得が100%のとき、表の値以下になります。
|
||||
|
||||
三原色と広帯域では、色を分けて合わせる計算の誤差が加わります。同じ条件の上限は、Tが128でGPUの経路が0.71階調、CPUの経路が0.40階調、Tが512でGPUの経路が3.58階調、CPUの経路が2.00階調です。
|
||||
|
||||
利得を掛けた値の誤差の上限は、掛ける前の上限に利得を掛けた値です。利得の最大値は400%で、このときのGPUの経路の上限は、表の値のほぼ4倍です。Tが128なら約2.8階調、512なら約14階調です。この上限には、利得を掛けるときの浮動小数点数の丸めと、8ビットに丸めるときの誤差を含みません。
|
||||
|
||||
誤差も利得に比例して大きくなるので、実際の素材の誤差が上限を超えないことを、最大の利得400%で確かめました。192×160の画像の中央の72×60画素に、画素を約6割の確率で置いた素材を作りました。置いた画素の不透明度は64〜255で、色の成分は0から不透明度までの、乱数で決めた値です。この素材を、利得400%で、次の5通りの設定で畳み込みました。
|
||||
@@ -185,15 +262,69 @@ Tが同じなら、カーネル半径を上げるほど、1枚のタイルが出
|
||||
|
||||
品質はどれも標準です。この5通りの畳み込みは、リポジトリに含めていない試験で行い、GPUの経路の出力を、倍精度で直接足し合わせた値と比べました。倍精度は、64ビットの浮動小数点数による計算で、GPUで使う32ビットの計算より誤差が小さくなります。比べる値は、どちらも利得を掛けて、色と不透明度の各成分が表せる最大の値で打ち切った後の値です。この打ち切りは「利得と適用量」の節で説明しています。打ち切られた画素では、2つの値が同じ値になるので、誤差を確かめられません。そのほかの画素の差は、どの設定でも0.51階調以下で、利得400%の上限より小さい値でした。この差には、8ビットに丸める分の0.5階調を含みます。
|
||||
|
||||
### 6. 利得と適用量
|
||||
### 7. 利得と適用量
|
||||
|
||||
「利得」は、畳み込んだ結果に掛ける倍率です。100%で画素の値の総和を保ち、上げるほど明るく、下げるほど暗くなります。利得を掛けた結果は、色と不透明度の各成分が表せる最大の値で打ち切り、さらに色の成分が不透明度を超えないように抑えます。
|
||||
「利得」は、畳み込んだ結果に掛ける倍率です。100%で、丸める前の値の総和を保ち、上げるほど明るく、下げるほど暗くなります。出力は8ビットに丸めるので、丸めた後の総和は、小さな明るい点で素材より少なくなることがあります。これは「線形光とハイライトとディザ」で説明します。利得を掛けた結果は、色と不透明度の各成分が表せる最大の値で打ち切り、さらに色の成分が不透明度を超えないように抑えます。
|
||||
|
||||
利得だけを変えたときは、最初の1回だけ畳み込みを計算し直し、利得を掛ける前の結果を保存します。2回目からは、保存した値に利得を掛け直します。
|
||||
利得かディザだけを変えたときは、最初の1回だけ畳み込みを計算し直し、利得を掛ける前の結果を保存します。2回目からは、保存した値に利得とディザを反映して描き直します。
|
||||
|
||||
「適用量」は、入力映像と、利得を掛けた結果を混ぜる割合です。0%では入力を変更せず、100%では利得を掛けた結果だけを出力します。
|
||||
|
||||
### 7. 品質の選択
|
||||
### 8. 線形光とハイライトとディザ
|
||||
|
||||
画素の値は、光の強さに比例していません。光の強さに比例する値を、線形の値と呼びます。sRGBでは、画素の値$v$から線形の値$x$を、次の式で求めます。線形の値から画素の値へ戻すときは、この式の逆を使います。
|
||||
|
||||
$$
|
||||
x = \begin{cases}
|
||||
\dfrac{v}{12.92} & (v \le 0.04045) \\
|
||||
\left(\dfrac{v + 0.055}{1.055}\right)^{2.4} & (v > 0.04045)
|
||||
\end{cases}
|
||||
$$
|
||||
|
||||
光の回折とにじみは、光の強さを足し合わせる現象です。そのため、線形の値で畳み込むほうが、実際の光に合います。白と黒の画素が1画素ずつ交互に並ぶ市松模様を、大きくぼかす場合を考えます。光の強さの平均は白の半分で、これを画素の値に直すと約0.735、8ビットで約188です。画素の値をそのまま平均すると0.5、8ビットで約128になり、実際の光より暗くなります。
|
||||
|
||||
「線形光」をオンにすると、素材の画素の値を線形の値へ直してから畳み込み、結果を画素の値へ戻します。オフのときは、画素の値をそのまま畳み込みます。半透明の画素は、素材の色を不透明度で割って元の色に戻してから変換し、変換した値に不透明度を掛け直します。畳み込んだ結果には、まず利得を掛けます。次に、色と不透明度の各成分を0〜1に打ち切り、色の成分が不透明度を超えないように抑えます。最後に、画素の値へ戻し、不透明度を掛け直して、8ビットに丸めます。
|
||||
|
||||
「ハイライト閾値」と「ハイライト強度」は、線形光がオンのときだけ働くので、オフのときは設定の画面に表示されません。素材は8ビットなので、光源の画素の値は1.0で頭打ちです。実際の光源はもっと明るいはずですが、その明るさは素材に残っていません。回折の筋のように中心よりはるかに小さい光は、そのままでは、出力の8ビットの1階調に届きません。ハイライト強度を上げると、明るい画素を持ち上げてから畳み込むので、そうした光が見えるようになります。ただし、これは光源の本当の明るさを復元する処理ではなく、指定した倍率で光を足す処理です。
|
||||
|
||||
持ち上げる倍率は、素材の画素ごとに決めます。画素の最も明るいチャンネルの値を$m$とします。半透明の画素では、素材の色を不透明度で割って元の色に戻した値を使います。しきい値を$t$、強さを$s$とすると、倍率は次の式で求めます。
|
||||
|
||||
$$
|
||||
\begin{aligned}
|
||||
e &= \frac{m - t}{1 - t}\ \text{を0〜1に打ち切った値} \\
|
||||
\text{倍率} &= 1 + (s - 1)\,e^2
|
||||
\end{aligned}
|
||||
$$
|
||||
|
||||
mがt以下の画素の倍率は1で、持ち上げません。mが1の画素の倍率は、強さsです。倍率は、色と不透明度のすべての成分に同じ値を掛けるので、色の比は変わりません。強さが1倍のときと、しきい値が100%のときは、持ち上げません。持ち上げた分の光が加わるので、出力の総和は素材の総和より大きくなります。明るさを元に戻すには、利得を下げてください。
|
||||
|
||||
ハイライトの効果を測りました。素材は、黒い背景の中央に、半径5画素の白い円を置いた映像です。F値16、画素ピッチ2μm、カーネル半径63画素、品質は標準、開口は6枚の羽根の正多角形で、ハイライト閾値は90%です。表の値は、出力の緑の成分を0〜255で表し、円の中心から25〜50画素離れた範囲で平均したものです。開口回転が0°のとき、点像分布関数は、中心から見て0°、60°、120°のように60°おきの向きへ、筋のように伸びます。筋の上は、この向きとの角度の差が3度以内の画素です。筋の間は、隣り合う筋の真ん中の向きとの角度の差が3度以内の画素です。
|
||||
|
||||
| 設定 | 筋の上 | 筋の間 |
|
||||
|---|---:|---:|
|
||||
| 線形光とハイライトをオフ | 0.0 | 0.0 |
|
||||
| 線形光とハイライトをオフ、利得400% | 1.0 | 0.0 |
|
||||
| 線形光をオン | 2.7 | 0.0 |
|
||||
| 線形光をオン、ハイライト強度30倍 | 41.5 | 3.7 |
|
||||
| 線形光をオン、ハイライト強度300倍 | 130.8 | 24.2 |
|
||||
|
||||
出力は8ビットに丸めます。点のような小さな明るい部分では、広がった光のうちの小さな値が0に丸められて、出力の総和が素材より少なくなります。「ディザ」をオンにすると、丸める前の値に、0以上1未満の値を足してから、小数を切り捨てます。足す値は、画素の位置だけで決まります。小さな値は、その大きさに応じた確率で1として残るので、総和が保たれます。具体的には、計算領域の中の画素の位置を、整数のハッシュに通して求めます。1つの画素の赤、緑、青、不透明度には、同じ値を足します。そのため、丸めたあとも、色が不透明度を超えることはありません。同じ設定では、同じ画素に毎回同じ値を足すので、フレームが変わってもちらつきません。カーネル半径を変えると、計算領域の余白が変わるので、模様は動きます。値が0の黒と、値が255の白は、変わりません。
|
||||
|
||||
ディザの効果を測りました。素材は、黒い背景に白い円を置いた映像です。円は、画素の中心が円の内側にある画素を白にしました。F値16、画素ピッチ2μm、カーネル半径63画素、品質は標準、開口は円形、利得100%で、線形光はオフです。表の値は、円の中心から上下左右に100画素の範囲で、出力の緑の成分の総和を素材の総和と比べた割合です。
|
||||
|
||||
| 円の半径 | ディザなし | ディザあり |
|
||||
|---:|---:|---:|
|
||||
| 2画素 | 91.1% | 100.2% |
|
||||
| 4画素 | 96.0% | 100.1% |
|
||||
| 8画素 | 97.9% | 100.0% |
|
||||
|
||||
「線形光」と「ハイライト閾値」と「ハイライト強度」を変えると、畳み込みを計算し直します。ただし、線形光がオフのときは、ハイライトの2項目を変えても、計算し直しません。線形光がオンでも、ハイライト強度が1倍のときと、しきい値が100%のときは、持ち上げません。この場合、ハイライトの値の違いでは計算し直しません。利得とディザだけを変えたときは、「利得と適用量」で説明した保存した値から描き直します。
|
||||
|
||||
線形光をオンにすると、畳み込みは、変換した値に対して同じ手順で行います。そのため、誤差は、変換した値の2ノルムに比例します。ハイライトを持ち上げると2ノルムが大きくなり、誤差の上限も同じ割合で大きくなります。誤差の上限は、素材の値が0〜1のときの値です。上限は、「GPUの計算の検査とCPUの経路」と、[SpectralConvolution](SpectralConvolution/README.md)の説明にあります。実際の誤差は、上限よりはるかに小さいです。次の条件で測りました。素材は、黒い背景に半径2〜5画素の白い円を置いた映像です。カーネル半径は15画素と63画素、ハイライト強度は1倍、10倍、100倍、1000倍です。無作為に選んだ1500か所の出力を、倍精度で直接足し合わせた値から求めた出力と比べました。GPUとCPUのどちらも、差は0階調でした。
|
||||
|
||||
線形光をオンにすると、素材を線形の値へ直す計算が増えて、素材が変わるフレームの時間が長くなります。同じ回の「素材」の行との差は、「タイルごとの高速フーリエ変換による畳み込み」の計算時間の表のすぐ下にあります。
|
||||
|
||||
### 9. 品質の選択
|
||||
|
||||
「品質」は、瞳関数を置く格子の大きさを切り替えます。格子は瞳関数の値を縦横に並べた表で、1つ1つの値を標本と呼びます。開口の直径は格子の一辺の4分の1です。格子が大きいほど、開口の縁と波面収差の位相を細かく表せます。
|
||||
|
||||
@@ -209,9 +340,11 @@ Tが同じなら、カーネル半径を上げるほど、1枚のタイルが出
|
||||
|
||||
格子が粗いと、大きな波面収差で位相が急に変わる所を表しきれず、点像分布関数の形が崩れます。水平コマ収差を2 wavesにし、品質ごとに求めたカーネルを、格子が2048×2048のときのカーネルと比べました。ほかの項目はデフォルトです。カーネルの各画素の値の差の絶対値を全画素で足すと、高速で約0.87、標準で約0.38、高精度で約0.03でした。カーネルの値の和は1です。波面収差の絶対値を大きくするときは、品質を上げてください。
|
||||
|
||||
品質を上げると、点像分布関数の計算が重くなります。「利得」と「適用量」以外の項目をアニメーションで変えるときは、フレームごとに点像分布関数を計算し直すので、品質を下げると処理が軽くなります。ただし、開口形状が円形のときは、「羽根枚数」と「開口回転」を変えても、計算し直しません。
|
||||
品質を上げると、点像分布関数の計算が重くなります。光学系グループと開口グループと波面収差グループの項目をアニメーションで変えるときは、フレームごとに点像分布関数を計算し直すので、品質を下げると処理が軽くなります。ただし、開口形状が円形のときは、「羽根枚数」と「開口回転」を変えても、計算し直しません。
|
||||
|
||||
### 8. GPUの計算の検査とCPUの経路
|
||||
「色の扱い」が広帯域のときは、品質が、波長ごとに瞳関数を変換する波長の数も決めます。収差があるとき、赤、緑、青のそれぞれの帯の中で、高速は1つ、標準は3つ、高精度は5つの波長で変換します。その間の波長の点像分布関数は、近い波長の点像分布関数を波長の比で拡大縮小して近似します。収差が無いときは、品質によらず、各色1つの波長で変換します。帯を61点の波長で密に計算したカーネルと比べると、カーネルの各画素の値の差の絶対値の和は、高速で約0.07〜0.08、標準で約0.03〜0.06、高精度で約0.02でした。測った設定は、格子が512×512、F値が8、画素ピッチが4μm、カーネル半径が63画素で、デフォーカス3 waves、水平コマ収差1 waves、球面収差-1 wavesとデフォーカス0.5 wavesの3通りです。値は、緑と青のうち大きい方です。収差が大きいときは、品質を上げてください。
|
||||
|
||||
### 10. GPUの計算の検査とCPUの経路
|
||||
|
||||
GPUの計算は、ドライバーやハードウェアの不具合で誤った値を返すことがあります。以下では、Windowsが認識しているGPUと、GPUの命令をCPUで実行するソフトウェアを、まとめてアダプターと呼びます。後者をソフトウェア アダプターと呼び、Microsoft Basic Render Driverがこれに当たります。本プラグインは、アダプターが正しく計算できるかを、自己試験と検査で確かめます。自己試験は、決まった入力を計算させて、答えを確かめる処理です。検査は、素材を畳み込んだ結果を確かめる処理です。どちらの詳細も、この節の後半にあります。
|
||||
|
||||
@@ -230,7 +363,7 @@ GPUの計算は、ドライバーやハードウェアの不具合で誤った
|
||||
|
||||
ソフトウェア アダプターでは、CPUの経路のほうが速いので、CPUで計算します。素材が大きいと、必要なGPUメモリが容量の4分の1を超えて、CPUの経路になることがあります。
|
||||
|
||||
自己試験は、YMM4を起動するたびに、表の1〜4のどれにも該当しない最初のフレームで、アダプターごとに1回行います。自己試験では、決まったカーネルを使い、決まった模様をGPUで畳み込み、倍精度で計算した値と比べます。同じ計算を2回行い、結果が1ビットも違わないことも確かめます。Intel Iris Xe Graphicsでは、自己試験に0.7〜0.8秒かかりました。
|
||||
自己試験は、YMM4を起動するたびに、表の1〜4のどれにも該当しない最初のフレームで、アダプターごとに1回行います。自己試験では、決まったカーネルを使い、決まった模様をGPUで畳み込み、倍精度で計算した値と比べます。同じ計算を2回行い、結果が1ビットも違わないことも確かめます。単色の畳み込みと、赤、緑、青に別のカーネルを使う畳み込みの、2通りで行います。Intel Iris Xe Graphicsでは、試験用のプロセスで6回続けて測る作業を3回行いました。各プロセスの最初の1回は0.83〜0.93秒、残りは0.40〜0.46秒でした。
|
||||
|
||||
GPUの経路で畳み込みを計算し直したフレームでは、出力を画面に出す前に、次の検査を行います。NaNは、計算の失敗で生じる、数として扱えない値です。
|
||||
|
||||
@@ -240,17 +373,21 @@ GPUの経路で畳み込みを計算し直したフレームでは、出力を
|
||||
| 総和 | 色と不透明度のそれぞれで、利得を掛ける前の出力の総和を素材の総和と比べる |
|
||||
| 抜き取り | 利得を掛ける前の出力の16か所の値を、倍精度で直接足し合わせた値と比べる |
|
||||
|
||||
「色の扱い」が三原色か広帯域のときは、抜き取りの参照値を、赤、緑、青にそれぞれのカーネルを使って求め、不透明度には緑のカーネルを使います。許容値には、色を分けて合わせる計算の誤差を加えます。総和の検査は、どのカーネルの和も1なので、単色と同じです。
|
||||
|
||||
検査では、GPUの結果から求めた値を、測定値と呼びます。参照値は、測定値と比べる値で、素材の値から求めた値か、0のように初めから分かっている値です。許容値は、測定値と参照値の差として許す最大の値です。測定値と参照値の差が許容値以下なら合格とします。総和と抜き取りの許容値は、どちらも丸めの誤差の上限から導いた値で、実際に測った誤差に合わせて広げてはいません。抜き取る16か所のうち、畳み込む範囲の四隅と中央の5か所は固定で、残りの11か所は素材から決まります。そのため、同じ素材と同じ設定では毎回同じ位置になります。
|
||||
|
||||
線形光かディザをオンにしたフレームでは、検査の材料の一部が変わります。GPUは、素材を線形の値などに直した値の総和と2乗和を、タイルごとに求めます。素材が8ビットの整数のままなら整数で足せますが、直した値は整数ではないので、浮動小数点数で足します。総和の参照値は、GPUが足した素材の総和です。そのため、総和の検査は、畳み込みの誤りを見つけますが、素材を直す計算の誤りは見つけません。この誤りは、抜き取りが見つけます。抜き取りの参照値は、次の手順で求めます。抜き取る位置の周りの素材の8ビットの値を、CPUで同じ式で直し、倍精度で足し合わせます。足し合わせの丸めの誤差は、許容値に入れています。許容値には、GPUとCPUのべき乗の計算の差の分として、タイルの2ノルムの2^-16倍を加えます。Intel Iris Xe Graphicsで測ったべき乗の相対誤差は、最大でも約5×10^-7で、2^-16の約30分の1でした。
|
||||
|
||||
GPUの異常が起きたときは、そのフレームをCPUの経路で計算し直します。異常を起こしたアダプターでは、YMM4を終了するまでCPUの経路で計算し、共有テクスチャやタイルの作業領域など、GPUの資源を解放します。
|
||||
|
||||
GPUの異常の内容は、ほかのプラグインと共通のライブラリである[YMM4-Telemetry](https://github.com/routersys/YMM4-Telemetry)で、開発者へ自動で送信します。送信は、YMM4の起動中にアダプターごとに1回だけです。送信する内容と、送信する報告の数の上限は、「不具合の報告」にあります。
|
||||
|
||||
GPUの経路でメモリを確保できなかったときは、YMM4を終了するまでCPUの経路で計算しますが、送信しません。自己試験の最中に確保できなかったときだけは、自己試験の不合格として送信します。
|
||||
|
||||
CPUの経路は、論理プロセッサの数までのスレッドで計算します。畳み込むときに、1つのスレッドは、タイル1枚分の作業領域を使います。同時に動かすスレッドは、タイルの作業領域の合計が64MBを超えない数に抑えます。Tが512のときは16スレッドまでです。
|
||||
CPUの経路は、論理プロセッサの数までのスレッドで計算します。このスレッドと作業領域は、YMM4の中のすべてのエフェクトで共有します。複数のエフェクトのCPUの畳み込みは、1つずつ順に行います。畳み込むときに、1つのスレッドは、タイル1枚分の作業領域を使います。同時に動かすスレッドは、タイルの作業領域の合計が64MBを超えない数に抑えます。Tが512のときは16スレッドまでです。
|
||||
|
||||
GPUの経路とCPUの経路の出力は、1ビット単位では一致しません。差は、開発で使う検証用のプログラムで確かめました。このプログラムを、ハーネスと呼びます。ハーネスは、リポジトリの`WaveOptics.Harness`にあります。ハーネスが合成した640×480の画像に、設定とフレームを変えてエフェクトを適用すると、2つの経路の出力の差は、測った範囲では最大2階調でした。この差には、2つの経路が8ビットに丸める分の、最大1階調を含みます。
|
||||
GPUの経路とCPUの経路の出力は、1ビット単位では一致しません。差は、開発で使う検証用のプログラムで確かめました。このプログラムを、ハーネスと呼びます。ハーネスは、リポジトリの`WaveOptics.Harness`にあります。ハーネスが合成した640×480の画像に、設定とフレームを変えてエフェクトを適用すると、2つの経路の出力の差は、測った範囲では最大2階調でした。この差には、2つの経路が8ビットに丸める分の、最大1階調を含みます。線形光とハイライトとディザを使う場面を加えても、最大2階調でした。「色の扱い」を三原色と広帯域にした場面を加えても、最大2階調でした。
|
||||
|
||||
[YMM4-ComputeGuard](https://github.com/routersys/YMM4-ComputeGuard)は、計算の経路を選び、検査の合否を判定します。[SpectralConvolution](SpectralConvolution/README.md)は、このリポジトリのフォルダーにあるライブラリで、畳み込みを計算します。YMM4-ComputeGuardは、サブモジュールとして取り込んでいます。
|
||||
|
||||
@@ -263,18 +400,31 @@ GPUの経路とCPUの経路の出力は、1ビット単位では一致しませ
|
||||
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|
||||
|---|---|---|---|---|---|
|
||||
| 適用量 | 数値 | 100% | 0〜100% | 対応 | 入力映像と、利得を掛けた結果を混ぜる割合です。0%では入力を変更しません。 |
|
||||
| 利得 | 数値 | 100% | 0〜400% | 対応 | 畳み込んだ結果に掛ける倍率です。100%で画素の値の総和を保ちます。 |
|
||||
| 利得 | 数値 | 100% | 0〜400% | 対応 | 畳み込んだ結果に掛ける倍率です。100%で、丸める前の値の総和を保ちます。 |
|
||||
| 線形光 | 切り替え | オフ | オフ / オン | 非対応 | 画素の値を光の強さに比例する値へ直してから畳み込み、結果を画素の値へ戻します。 |
|
||||
| ハイライト閾値 | 数値 | 95% | 0〜100% | 対応 | 線形光がオンのとき、素材の画素の最も明るいチャンネルがこの割合を超えると、持ち上げ始めます。 |
|
||||
| ハイライト強度 | 数値 | 1倍 | 1〜100倍 | 対応 | 線形光がオンのとき、最も明るい画素を持ち上げる倍率です。1倍では持ち上げません。直接入力では1000倍まで指定できます。 |
|
||||
| ディザ | 切り替え | オフ | オフ / オン | 非対応 | 8ビットに丸めるとき、画素の位置だけで決まる値を足します。 |
|
||||
|
||||
### 光学系グループ
|
||||
|
||||
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|
||||
|---|---|---|---|---|---|
|
||||
| 波長 | 数値 | 550nm | 380〜780nm | 対応 | 単色光として計算する真空中の波長です。 |
|
||||
| 色の扱い | 列挙 | 単色 | 単色 / 三原色 / 広帯域 | 非対応 | 赤、緑、青の成分を、どの波長で計算するかを選択します。 |
|
||||
| 波長 | 数値 | 550nm | 380〜780nm | 対応 | 単色光として計算する真空中の波長です。「色の扱い」が単色のときだけ使います。 |
|
||||
| F値 | 数値 | 8 | 0.5〜32 | 対応 | 開口の直径に対する焦点距離の比です。直接入力では64まで指定できます。 |
|
||||
| 画素ピッチ | 数値 | 4μm | 0.5〜20μm | 対応 | 撮像面での1画素の間隔です。直接入力では0.25〜100μmを指定できます。 |
|
||||
| カーネル半径 | 整数 | 15画素 | 1〜63画素 | 非対応 | カーネルが中心から上下左右に広がる画素数です。カーネルの外に届く光は捨てます。 |
|
||||
| 品質 | 列挙 | 標準 | 高速 / 標準 / 高精度 | 非対応 | 瞳関数を置く格子の大きさを選択します。 |
|
||||
|
||||
### 奥行きグループ
|
||||
|
||||
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|
||||
|---|---|---|---|---|---|
|
||||
| 奥行きを使う | 切り替え | オフ | オフ / オン | 非対応 | アイテムのカメラからの距離と合焦距離の差から、デフォーカスを決めて加えます。 |
|
||||
| 合焦距離 | 数値 | 1000mm | 100〜10000mm | 対応 | 「奥行きを使う」がオンのとき、ピントが合う面の、カメラからの距離です。直接入力では10〜1000000mmを指定できます。 |
|
||||
| 焦点距離 | 数値 | 50mm | 10〜300mm | 対応 | 「奥行きを使う」がオンのとき、レンズの焦点距離です。大きいほど、奥行きによるデフォーカスが大きくなります。直接入力では1〜1000mmを指定できます。 |
|
||||
|
||||
### 開口グループ
|
||||
|
||||
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|
||||
@@ -288,7 +438,7 @@ GPUの経路とCPUの経路の出力は、1ビット単位では一致しませ
|
||||
|
||||
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|
||||
|---|---|---|---|---|---|
|
||||
| デフォーカス | 数値 | 0 waves | -3〜3 waves | 対応 | 焦点の位置のずれの係数です。 |
|
||||
| デフォーカス | 数値 | 0 waves | -3〜3 waves | 対応 | 焦点の位置のずれの係数です。「奥行きを使う」がオンのときは、奥行きから決めた値に加えます。 |
|
||||
| 縦横非点収差 | 数値 | 0 waves | -3〜3 waves | 対応 | 水平方向と垂直方向で焦点の位置が違うずれの係数です。 |
|
||||
| 斜め非点収差 | 数値 | 0 waves | -3〜3 waves | 対応 | 45度傾いた2つの方向で焦点の位置が違うずれの係数です。 |
|
||||
| 水平コマ収差 | 数値 | 0 waves | -3〜3 waves | 対応 | 像が水平方向の片側へ尾を引くずれの係数です。 |
|
||||
@@ -305,15 +455,17 @@ GPUの経路とCPUの経路の出力は、1ビット単位では一致しませ
|
||||
- Direct3D 12デバイスを取得できない場合と、YMM4が使うDirect3D 11デバイスが相互運用に必要なインターフェースを持たない場合は、CPUの経路で計算します。Direct3D 11・12間の共有の準備に失敗した場合と、GPUで計算するための準備に失敗した場合も、CPUの経路で計算します。YMM4が使うアダプターがソフトウェア アダプターの場合と、必要なGPUメモリがアダプターの容量の4分の1を超える場合も同様です。ソフトウェア アダプターではないGPUを使える環境では、CPUの経路のほうが、一般に計算が遅くなります。
|
||||
- GPUの結果の検査で見つけられるのは、NaNと無限大、総和、16か所の抜き取りに表れた誤りだけです。利得だけを変えたフレームで、保存した値にGPUで利得を掛け直す計算は、検査しません。
|
||||
- GPUの異常が起きたアダプターと、GPUの経路でメモリを確保できなかったアダプターは、原因が一時的な不具合でも、YMM4を終了するまでCPUの経路で計算します。このとき、共有テクスチャやタイルの作業領域など、GPUの資源は解放します。
|
||||
- 畳み込みには現在のフレームの色と不透明度だけを使用します。履歴フレーム、外部画像、学習済みモデルは使用しません。素材のすべての画素が透明なときは、エフェクトを適用せず入力映像を表示します。
|
||||
- 計算は単色のフラウンホーファー回折に限ります。白色光のように波長の混ざった光は扱いません。点像分布関数は画面のどこでも同じで、像の位置や素材の奥行きで変わるにじみは扱いません。
|
||||
- 畳み込みは、画素の値をそのまま重み付けして足し合わせます。画素の値を光の強さに比例する値へ直してから畳み込む処理はしません。
|
||||
- 畳み込みには現在のフレームの色と不透明度を使用します。「奥行きを使う」がオンのときは、これに加えて、アイテムの座標とカメラの位置を使います。履歴フレーム、外部画像、学習済みモデルは使用しません。素材のすべての画素が透明なときは、エフェクトを適用せず入力映像を表示します。
|
||||
- 計算はフラウンホーファー回折に限ります。「色の扱い」が単色のときは、1つの波長で計算します。三原色と広帯域でも、赤、緑、青の成分を別々に畳み込むだけで、成分の間で光は混ざりません。素材の画素の値から光の分光分布は分からないので、三原色の波長と広帯域の帯は、仮に決めた値です。ガラスの屈折率が波長で変わることによる色収差は扱いません。点像分布関数は画面のどこでも同じで、像の位置で変わるにじみは扱いません。奥行きは、アイテムごとに1つの距離で扱うので、1つのアイテムの中で画素ごとに変わるにじみは扱いません。傾けたアイテムでも、距離はアイテムの座標の位置の1つの値です。
|
||||
- 奥行きの距離には、このエフェクトより後に適用される座標とカメラを含みません。グループ制御に置いたカメラを動かしても、距離は変わりません。
|
||||
- 畳み込みは、既定では、画素の値をそのまま重み付けして足し合わせます。「線形光」をオンにしたときだけ、画素の値を光の強さに比例する値へ直してから畳み込みます。
|
||||
- ハイライトは、指定した倍率で明るい画素の光を足す処理です。素材は8ビットで、頭打ちの画素の元の明るさは分からないので、光源の本当の明るさは復元しません。
|
||||
- カーネル半径は1〜63画素です。
|
||||
- 中央遮蔽で開口をほとんどふさぎ、瞳関数の格子に光の通る標本が1つも無くなる設定では、エフェクトを適用せず入力映像を表示します。品質を上げると起きにくくなります。
|
||||
- 計算領域は、透明な部分も含む素材全体の矩形の上下左右に余白を加えた大きさで、長辺は8192画素が上限です。余白は、カーネル半径を4画素単位に切り上げた画素数で、16画素を下回りません。素材の長辺の上限は、8192画素から余白の2倍を引いた値です。カーネル半径が16画素以下なら8160画素、63画素なら8064画素になります。素材の長辺がこの上限を超える場合は、エフェクトを適用せず入力映像を表示します。
|
||||
- エフェクト1つあたり、GPUの経路では、2つの共有テクスチャをGPUに確保します。素材を入れる共有テクスチャは、素材の1画素につき4バイトです。結果を入れる共有テクスチャは、畳み込む範囲の1画素につき4バイトです。結果を入れる共有テクスチャは、畳み込む範囲が入りきらなくなったときだけ、そのときの範囲の大きさで作り直します。
|
||||
- GPUの経路では、共有テクスチャのほかに、16MB以下のタイルの作業領域、カーネルのスペクトル、検査に使う値を書くバッファーを確保します。スペクトルは、Tが128なら128KB、512なら2MBです。検査に使う値を書くバッファーは、畳み込む範囲の大きさとカーネル半径に応じて増えます。利得だけを変えたフレームの後は、畳み込む範囲の1画素につき16バイトを追加で確保します。この領域は、「注意事項」のキャッシュの項目にある、保存した値のためのものです。
|
||||
- エフェクト1つあたり、CPUの経路では、素材の画素の配列、出力の画素の配列、作業スレッドの作業領域をシステムメモリに確保します。作業領域のうち、タイルの分は合計で64MB以下です。素材を読むためのDirect2Dのビットマップは2枚あり、どちらも素材の大きさです。出力を書くためのDirect2Dのビットマップは、畳み込む範囲を収められる大きさで、収まらなくなったときだけ作り直します。利得だけを変えたフレームの後は、畳み込む範囲の1画素につき16バイトを追加で確保します。
|
||||
- GPUの経路では、共有テクスチャのほかに、16MB以下のタイルの作業領域、カーネルのスペクトル、検査に使う値を書くバッファーを確保します。スペクトルは、単色ではTが128なら128KB、512なら2MBです。三原色と広帯域では、Tが128なら195KB、512なら約3MBです。検査に使う値を書くバッファーは、畳み込む範囲の大きさとカーネル半径に応じて増えます。利得だけを変えたフレームの後は、畳み込む範囲の1画素につき16バイトを追加で確保します。この領域は、「注意事項」のキャッシュの項目にある、保存した値のためのものです。
|
||||
- エフェクト1つあたり、CPUの経路では、素材の画素の配列と出力の画素の配列をシステムメモリに確保します。作業スレッドの作業領域は、すべてのエフェクトで共有します。作業領域のうち、タイルの分は合計で64MB以下です。確保した作業領域は、YMM4を終了するまで解放しません。素材を読むためのDirect2Dのビットマップは2枚あり、どちらも素材の大きさです。出力を書くためのDirect2Dのビットマップは、畳み込む範囲を収められる大きさで、収まらなくなったときだけ作り直します。利得だけを変えたフレームの後は、畳み込む範囲の1画素につき16バイトを追加で確保します。
|
||||
|
||||
---
|
||||
|
||||
@@ -321,7 +473,8 @@ GPUの経路とCPUの経路の出力は、1ビット単位では一致しませ
|
||||
|
||||
- 処理負荷: 畳み込む範囲が大きいほど、計算は重くなります。カーネル半径を上げたときの重さの変わり方は、「タイルごとの高速フーリエ変換による畳み込み」にあります。品質を上げた場合は、点像分布関数の計算量が増えます。収差を入れても、畳み込みの計算量は変わりません。ソフトウェア アダプターではないGPUを使える環境では、CPUの経路のほうが、一般に計算が遅くなります。
|
||||
- 品質と収差: 波面収差の絶対値を大きくするときは、品質を上げてください。格子が粗いと点像分布関数の形が崩れます。崩れ方の目安は「品質の選択」にあります。
|
||||
- キャッシュ: 素材の大きさと色と不透明度が変わらず、「利得」と「適用量」以外の項目も変わらないフレームでは、畳み込みの計算を再利用します。利得だけを変えたフレームでは、最初の1回だけ畳み込みを計算し直し、利得を掛ける前の値を保存します。2回目からは、保存した値に利得を掛け直します。素材か、「利得」と「適用量」以外の項目が変わると、保存した値を破棄します。適用量だけを変えたフレームでは、混ぜる割合だけを変えます。動画や口パクのように素材の内容が変わるフレームと、「利得」と「適用量」以外の項目をアニメーションで変えたフレームでは、毎回計算し直すので処理が重くなります。素材が変わったかどうかを調べる計算は、再利用するフレームでも毎フレーム行います。開口形状が円形のときは、「羽根枚数」と「開口回転」を変えても、計算し直しません。
|
||||
- キャッシュ: 素材の大きさと色と不透明度が変わらず、「利得」と「適用量」と「ディザ」以外の項目も変わらないフレームでは、畳み込みの計算を再利用します。利得かディザだけを変えたフレームでは、最初の1回だけ畳み込みを計算し直し、利得を掛ける前の値を保存します。2回目からは、保存した値に利得とディザを反映して描き直します。素材か、「利得」と「適用量」と「ディザ」以外の項目が変わると、保存した値を破棄します。ただし、線形光がオフのときは、ハイライトの2項目が変わっても破棄しません。適用量だけを変えたフレームでは、混ぜる割合だけを変えます。動画や口パクのように素材の内容が変わるフレームと、「利得」と「適用量」と「ディザ」以外の項目をアニメーションで変えたフレームでは、毎回計算し直すので処理が重くなります。「奥行きを使う」がオンのとき、アイテムの距離か合焦距離が変わるフレームでも、毎回計算し直します。素材が変わったかどうかを調べる計算は、再利用するフレームでも毎フレーム行います。開口形状が円形のときは、「羽根枚数」と「開口回転」を変えても、計算し直しません。
|
||||
- マネージドヒープ: 素材と設定が変わらず、アニメーションする項目が無いフレームでは、.NETのマネージドヒープにメモリを確保しません。適用量が0%のフレームでも同じです。アニメーションする項目の値をYMM4が取り出すときの確保は、本プラグインでは減らせません。
|
||||
- 適用量0%: 適用量が0%のときは入力を変更せず、畳み込みの計算も行いません。
|
||||
- 再現性: 計算は決定論的で、時間値や乱数を使用しません。同じ素材と同じ設定から常に同じ結果になるのは、同じ経路で、GPU、ドライバー、CPU、Windows、.NETの組が同じときです。GPUの経路でも結果にCPUが関わるのは、点像分布関数とカーネルのスペクトルをCPUで求めるためです。GPUの経路とCPUの経路では、結果がわずかに違います。GPUの異常でCPUの経路に切り替わったときも、同じ設定で結果がわずかに変わります。
|
||||
- 透明部分: 畳み込みは不透明度にも掛かるので、素材の縁の外にも半透明のにじみが広がります。出力の範囲は、素材の範囲と畳み込む範囲を合わせたものです。適用量が0%のときは、素材の範囲のままです。
|
||||
@@ -333,17 +486,20 @@ GPUの経路とCPUの経路の出力は、1ビット単位では一致しませ
|
||||
|
||||
## 不具合の報告
|
||||
|
||||
本プラグインは、想定していない例外が起きたときと、GPUの異常でCPUの経路に切り替えたときに、その内容を開発者へ自動で送信します。同意は求めず、常に送信します。
|
||||
本プラグインは、想定していない例外が起きたときと、GPUの異常でCPUの経路に切り替えたときに、その内容を開発者へ自動で送信します。同意は求めません。止める設定もありません。
|
||||
|
||||
送信する数には上限があります。YMM4の1回の起動で送る報告は、YMM4-Telemetryで報告する別のプラグインと合わせて20件までです。例外の型と発生位置が同じ報告は3件までです。上限を超えた報告と、送信先から待つよう求められている間に起きた報告は、送信も退避もしません。
|
||||
|
||||
送信する情報は次のとおりです。
|
||||
|
||||
| 種類 | 内容 |
|
||||
|---|---|
|
||||
| 例外 | 型の完全名、メッセージ、スタックトレース |
|
||||
| 発生位置 | モジュール名、関数名、ファイル名、行番号 |
|
||||
| 発生位置 | モジュール名、関数名、ファイル名、行番号、プラグイン自身のコードかどうか |
|
||||
| プラグイン | アセンブリ名、バージョン |
|
||||
| 実行環境 | OSの名前とバージョン、.NETのバージョン、CPUのアーキテクチャ、論理プロセッサ数 |
|
||||
| 識別子 | YMM4の起動ごとに決まるセッション識別子、報告ごとの識別子 |
|
||||
| 時刻 | 報告を作った時刻(UTC) |
|
||||
| GPUの異常のとき | 切り替えた理由、不合格になった検査の名前と測定値と参照値と許容値、アダプターの名前、ベンダーIDとデバイスIDとサブシステムIDとリビジョン、ドライバーのバージョン、ソフトウェア アダプターかどうか、計算領域の幅と高さ、必要なGPUメモリの見積もり |
|
||||
|
||||
メッセージとファイル名は、送信の前に置き換えを通します。置き換えるのは、Windowsのユーザー名、ユーザーフォルダー、AppDataのパス、マシン名、ドメイン名、メールアドレス、IPv4アドレスです。送信元のIPアドレスは受信側へ渡す手前で取り除いています。
|
||||
|
||||
+148
-8
@@ -25,6 +25,8 @@ YMM4 のプラグインが、画像とカーネルの畳み込みを、CPU と G
|
||||
- [4. GPU の経路](#4-gpu-の経路)
|
||||
- [5. 検査の材料と検査](#5-検査の材料と検査)
|
||||
- [6. 自己試験](#6-自己試験)
|
||||
- [7. 線形光とハイライトとディザ](#7-線形光とハイライトとディザ)
|
||||
- [8. 色ごとのカーネル](#8-色ごとのカーネル)
|
||||
6. [誤差の上限](#誤差の上限)
|
||||
- [前提](#前提)
|
||||
- [記号](#記号)
|
||||
@@ -38,6 +40,7 @@ YMM4 のプラグインが、画像とカーネルの畳み込みを、CPU と G
|
||||
- [8. 総和の上限](#8-総和の上限)
|
||||
- [9. 参照値の誤差](#9-参照値の誤差)
|
||||
- [10. 式に入れていない誤差と上限の余裕](#10-式に入れていない誤差と上限の余裕)
|
||||
- [11. 色ごとのカーネルの経路](#11-色ごとのカーネルの経路)
|
||||
7. [決定論](#決定論)
|
||||
8. [メモリ](#メモリ)
|
||||
9. [動作の上限値](#動作の上限値)
|
||||
@@ -127,6 +130,8 @@ SpectralConvolution/ 外側
|
||||
| `TilePlan` | 畳み込む範囲のタイルへの分け方 |
|
||||
| `KernelSpectrum` | 和を 1 にそろえたカーネルと、タイルの大きさに合わせた回転因子とスペクトル |
|
||||
| `CpuTileConvolver` | CPU の経路の畳み込み |
|
||||
| `CpuFft` | CPU の経路の高速フーリエ変換。4 つの float を 1 つのベクトルに置いて計算する |
|
||||
| `CpuPixels` | CPU の経路で、8 ビットの素材を float の行に置く変換と、float の出力を 8 ビットにする変換 |
|
||||
| `GpuTileConvolver` | GPU の経路の資源と、ComputeWeave のコンテキストへの記録 |
|
||||
| `GpuTileJob` | GPU の経路の 1 回分の畳み込みの設定。`GpuTileConvolver.Prepare` が返す |
|
||||
| `GpuTileCheck` | GPU が書き出した値から作る検査 |
|
||||
@@ -136,6 +141,9 @@ SpectralConvolution/ 外側
|
||||
| `DirectCorrelation` | 式 (1) を倍精度でそのまま足し合わせる計算。検査の参照値に使う |
|
||||
| `TileInput` | タイルが読む素材の 2 ノルム。8 ビットの値を 255 で割った値で求める |
|
||||
| `FastFourierTransform` | 倍精度の高速フーリエ変換。カーネルのスペクトルに使う |
|
||||
| `ComplexLines` | 倍精度の高速フーリエ変換に渡す、実部と虚部の作業領域。1 つの配列に、間に余白を置いて並べる |
|
||||
| `LightOptions` | 線形光、ディザ、ハイライトの設定 |
|
||||
| `LightTransform` | 線形光とハイライトで素材を直す変換と、出力を 8 ビットにする変換。CPU の経路と、検査の参照値に使う |
|
||||
|
||||
表の 2 ノルムは、素材の 8 ビットの値を 255 で割った値の 2 乗の和の平方根です。赤と緑、青と不透明度の 2 組ごとに求めます。スペクトルは、カーネルを高速フーリエ変換した値です。回転因子とスペクトルは、[タイルに分けた畳み込み](#1-タイルに分けた畳み込み)で説明します。
|
||||
|
||||
@@ -160,6 +168,13 @@ cpu.Convolve(source, sourceX, sourceY, sourceWidth, sourceHeight, spectrum, plan
|
||||
|
||||
`sourceX` と `sourceY` は素材の左上の座標で、畳み込む範囲と同じ座標系で渡します。`sourceWidth` と `sourceHeight` は素材の幅と高さです。`source` と `output` は `byte[]` で、画素を行ごとに隙間なく並べます。長さは、画素数 × 4 バイト以上です。出力は畳み込む範囲の大きさで、左上が範囲の左上に当たります。`gain` は出力に掛ける倍率で、以下ではゲインと呼びます。Wave Optics の「利得」に当たります。最後の引数 `null` は、ゲインを掛ける前の値を保存しない指定です。保存は、[CPU の経路](#3-cpu-の経路)で説明します。
|
||||
|
||||
線形光とハイライトとディザを使うときは、`LightOptions` を渡します。CPU の経路は `Convolve` の最後の引数、GPU の経路は `Prepare` の最後の引数です。保存した値から描き直す `CpuTileConvolver.RenderStored` と `GpuTileConvolver.RecordStored` にも渡します。渡さないと既定になり、これまでと同じ動きです。詳しくは、[線形光とハイライトとディザ](#7-線形光とハイライトとディザ)にあります。
|
||||
|
||||
```csharp
|
||||
var light = new LightOptions(true, false, 0.9f, 30f);
|
||||
cpu.Convolve(source, sourceX, sourceY, sourceWidth, sourceHeight, spectrum, plan, output, gain, store, light);
|
||||
```
|
||||
|
||||
GPU の経路では、素材と出力のテクスチャを使う処理を、ComputeWeave のコンテキストに記録します。ComputeWeave では、`GraphicsDevice` から作った `ComputeContext` に、計算シェーダーの実行を記録します。
|
||||
|
||||
```csharp
|
||||
@@ -220,10 +235,12 @@ var count = SpectralSelfTest.Run(device, maximumRadius, measurements);
|
||||
|
||||
畳み込む範囲全体を 1 回で変換せずにタイルに分けるのは、作業領域の大きさと誤差の上限を、範囲の大きさによらず決めるためです。タイルどうしは互いに独立しているので、どの順に計算しても結果は同じです。
|
||||
|
||||
変換は、基数 2 の時間間引きの高速フーリエ変換です。行に変換をかけてから列に変換をかけ、逆変換は列、行の順に行います。変換に使う回転因子は、j を 0 から T / 2 - 1 までの整数として、exp(-2πi j / T) で表される値です。この値を並べた表を作ります。表の値は、倍精度の `Math.SinCos` で求めた値を float に丸めたものです。CPU と GPU は同じ表を使い、GPU では三角関数を使いません。
|
||||
変換は、基数 2 の時間間引きの高速フーリエ変換です。実装は、連続する 2 段を 1 回の通過にまとめて計算します。まとめても、各要素への足し算、引き算、掛け算の順番と回数は、1 段ずつ計算した場合と同じです。行に変換をかけてから列に変換をかけ、逆変換は列、行の順に行います。変換に使う回転因子は、j を 0 から T / 2 - 1 までの整数として、exp(-2πi j / T) で表される値です。この値を並べた表を作ります。表の値は、倍精度の `Math.SinCos` で求めた値を float に丸めたものです。CPU と GPU は同じ表を使い、GPU では三角関数を使いません。
|
||||
|
||||
カーネルのスペクトルは、カーネルを T × T の配列に置いて、2 次元の高速フーリエ変換をかけたものです。倍精度で求めてから、float に丸めます。高速フーリエ変換で求まるのは数学の定義の畳み込みなので、式 (1) の向きにそろえるために、カーネルの値 k(d) を位置 -d に置きます。位置は T を周期として折り返し、残りは 0 にします。値は、GPU の列の計算で連続して読めるよう、列ごとに並べます。
|
||||
|
||||
実際の計算では、値のある 2r + 1 行だけを行ごとに変換し、列ごとの変換は、横方向の周波数が 0 から T / 2 までの T / 2 + 1 列だけにします。カーネルは実数なので、スペクトルの周波数 (u, v) の値は、周波数 (-u, -v) の値の複素共役になります。周波数は T を周期とします。残りの列は、この対称を使い、float に丸めた値の複素共役を写して求めます。
|
||||
|
||||
2^-126 は float の正の正規化数の最小値で、0 でなく絶対値がこれより小さい値を非正規化数と呼びます。回転因子とスペクトルの非正規化数は、符号を残して 0 にします。GPU は非正規化数を 0 にすることがあるので、CPU の側で先に 0 にそろえておきます。
|
||||
|
||||
### 2. 2 つのチャンネルをまとめる複素数
|
||||
@@ -246,6 +263,8 @@ var count = SpectralSelfTest.Run(device, maximumRadius, measurements);
|
||||
|
||||
出力では、畳み込んだ値にゲインを掛け、Direct3D の規則と同じ式で 8 ビットへ変えます。NaN は 0 にし、0〜1 に切り詰め、255 倍して 0.5 を足し、端数を切り捨てます。
|
||||
|
||||
変換の 1 段の計算、スペクトルを掛ける計算、出力を 8 ビットにする計算は、`System.Runtime.Intrinsics` のベクトル演算で行います。1 回のバタフライは、2 つの複素数(赤と緑、青と不透明度)に同じ回転因子を掛け、足し引きする計算です。4 つの float を 1 つのベクトルに置いて計算します。AVX2 を使えるときは、同じ段で隣り合う 2 つの回転因子の分を、1 つの 256 ビットのベクトルにまとめます。さらに、最初の 2 段と、その後の連続する 2 段ずつを、1 回の通過にまとめます。4 つの値を読み、2 段分の計算をしてから書くので、データを読み書きする回数が半分になります。段の数が奇数のときは、最後の 1 段を単独で計算します。足し算、引き算、掛け算の順番と回数は、スカラーで書いた式と同じで、融合積和は使いません。そのため、結果はスカラーの式と 1 ビットも違いません。`CpuFft.ButterfliesScalar` が、基準にするスカラーの式です。試験は、`Butterflies` の結果をこの式の結果と、ビットごとに比べます。素材を行に置くときの、8 ビットの値を 255 で割る計算は、256 個の値の表で行います。表の値は、同じ割り算の結果なので、割り算と同じ値です。
|
||||
|
||||
ゲインだけを変えるときは、畳み込みをやり直さずに出力できます。そのために、`Convolve` の最後の引数 `convolvedValues` に配列を渡します。渡した配列に、ゲインを掛ける前の値が float で保存されます。保存する値は、画素ごとに R、G、B、A の順の float 4 つで、出力の BGRA とは順が違います。配列の長さは、畳み込む範囲の幅 × 高さ × 4 以上です。
|
||||
|
||||
`RenderStored` は、保存した値に別のゲインを掛けて出力し直します。結果は、そのゲインで畳み込みと同時に出力した場合と 1 ビットも違いません。`RenderStored` は、16384 画素を 1 単位として、スレッドに割り当てます。
|
||||
@@ -266,8 +285,12 @@ var count = SpectralSelfTest.Run(device, maximumRadius, measurements);
|
||||
|
||||
1 つのスレッドグループは 256 スレッドで、512 個の値を受け持ちます。以下では、スレッドグループを単にグループと呼びます。値はグループ共有メモリに置きます。`ColumnShader` は、列を転置せずにその場で変換します。
|
||||
|
||||
変換は、連続する 2 段を 1 回の同期にまとめます。1 つのスレッドが 4 つの値を読み、2 段分の計算をして書くので、グループ内の同期が段の数の約半分になります。512 個の値のグループでは、4 つの値の組が 128 個なので、256 スレッドのうち 128 スレッドが計算し、残りは同期を待ちます。段の数が奇数のときは、最後の 1 段を、256 スレッドが 1 組ずつ受け持って計算します。足し算、引き算、掛け算の順番と回数は、1 段ずつ計算した場合と同じです。
|
||||
|
||||
浮動小数点数を計算するシェーダーは、ComputeWeave の `CompileOptions.IeeeStrictness` を付けてコンパイルします。これは、シェーダーのコンパイラーである DXC の `-Gis` に当たり、精度を緩める最適化を許しません。
|
||||
|
||||
`ForwardRowShader` と `InverseRowShader` は、グループの 512 個の値が必ず 1 枚のタイルの中にあることを使って、タイルの位置を求める割り算を、スレッドごとに 1 回だけ行います。`InverseRowShader` は、抜き取る位置があるタイルでだけ、抜き取る位置を探します。抜き取る位置を渡すバッファー(`Samples`)には、先頭の `MaximumSamples` 個に抜き取る位置を並べ、続けてタイルごとに 1 ビットの印を並べます。印は 64 タイルを 1 要素に入れ、X の下位ビットから順に 32 タイル、Y の下位ビットから順に 32 タイルです。抜き取る位置があるタイルの印が 1 です。`Prepare` が、抜き取る位置を渡すたびに、位置と印を書き込みます。
|
||||
|
||||
出力のテクスチャには、ゲインを掛けた値を書きます。`Prepare` の最後の引数に `true` を渡すと、ゲインを掛ける前の値を、畳み込む範囲の 1 画素につき 16 バイトのバッファーに保存します。`RecordStored` は、保存した値に別のゲインを掛けて出力し直します。結果は、そのゲインで畳み込みと同時に出力した場合と 1 ビットも違いません。保存に使うバッファーは、`ReleaseStore` か `Dispose` を呼ぶまで持ち続けます。
|
||||
|
||||
### 5. 検査の材料と検査
|
||||
@@ -306,7 +329,7 @@ GPU は、検査の材料を 1 つの `uint` のバッファー(`Report`)に
|
||||
|
||||
### 6. 自己試験
|
||||
|
||||
`SpectralSelfTest.Run` は、T が 128 と 512 のそれぞれで次の 2 つの場面を GPU で計算し、検査を引数の `measurements` に書き込みます。戻り値は、書き込んだ件数です。`measurements` には、`SpectralSelfTest.MeasurementCount`(280)件以上の長さが要ります。
|
||||
`SpectralSelfTest.Run` は、T が 128 と 512 のそれぞれで次の 2 つの場面を GPU で計算し、検査を引数の `measurements` に書き込みます。カーネルが 1 つの場面と、赤、緑、青で別のカーネルを使う場面の両方を行うので、場面は合わせて 8 つです。色ごとのカーネルの場面の測定値は、`selftest.chromatic.determinism` と `selftest.chromatic.full` です。戻り値は、書き込んだ件数です。`measurements` には、`SpectralSelfTest.MeasurementCount`(560)件以上の長さが要ります。
|
||||
|
||||
1. 半径 3 のカーネルで、2 × 2 枚のタイルにまたがる模様を 2 回畳み込みます。2 回の結果でビットが違う値の個数を、`selftest.determinism` の測定値にします。全画素の値を `DirectCorrelation` の値と比べ、差を誤差の上限で割った値の最大を、`selftest.full` の測定値にします。1 回目の結果からは、[検査の材料と検査](#5-検査の材料と検査)の表と同じ検査も作ります。
|
||||
2. 半径は、T が 128 のときは `maximumRadius` と 23 の小さいほう、512 のときは `maximumRadius` と 255 の小さいほうにします。この半径のカーネルで、模様を 1 回畳み込み、[検査の材料と検査](#5-検査の材料と検査)の表と同じ検査を作ります。23 は、`TilePlan.SelectSize` が T に 128 を選ぶ半径の上限です。255 は、本ライブラリが扱える半径の上限です。
|
||||
@@ -315,8 +338,91 @@ GPU は、検査の材料を 1 つの `uint` のバッファー(`Report`)に
|
||||
|
||||
模様には、値が 0 の領域、不透明な細い線、さまざまな不透明度の画素を入れます。カーネルは、左右にも上下にも非対称な形にします。抜き取る位置は、四隅と中央の 5 か所、タイルの継ぎ目の両側の 2 か所、決まった式で決めた 9 か所です。全画素の比較に小さなカーネルを使うのは、倍精度の直接の計算を軽く保つためです。高速フーリエ変換の各段の計算はカーネルの大きさによらないので、小さなカーネルでも変換のすべての段を通ります。
|
||||
|
||||
### 7. 線形光とハイライトとディザ
|
||||
|
||||
素材の読み方と出力の書き方は、`LightOptions` で変えます。`LightOptions` は、次の 4 つの値を持ちます。
|
||||
|
||||
| 値 | 意味 |
|
||||
|---|---|
|
||||
| `Linear` | 真なら、素材の値を線形の値へ直して畳み込み、結果を sRGB の値へ戻す |
|
||||
| `Dither` | 真なら、出力を 8 ビットに丸めるとき、画素の位置で決まる 0 以上 1 未満の値を足してから切り捨てる |
|
||||
| `Threshold` | ハイライト閾値 t。0 以上 1 以下 |
|
||||
| `Boost` | ハイライト強度 s。0 以上 1000 以下 |
|
||||
|
||||
線形の値は、光の強さに比例する値です。`Linear` と `Dither` がどちらも偽の `default` が既定です。既定では、この節の処理は何も行わず、[CPU の経路](#3-cpu-の経路)と [GPU の経路](#4-gpu-の経路)の説明のとおりに動きます。ハイライトを持ち上げるのは、`Linear` が真で、s が 1 より大きく、t が 1 未満のときです。`LightOptions.Validate` は、t か s が範囲の外か有限でないと、`ArgumentOutOfRangeException` を投げます。
|
||||
|
||||
素材の変換は、`LightTransform.FromBytes` です。素材の画素 (r, g, b, a) は、premultiplied alpha の 8 ビットの値です。`Linear` が偽なら、各値を 255 で割った float を返します。真のときは、次の順に求めます。計算はすべて float です。
|
||||
|
||||
1. a が 0 なら、4 つとも 0 を返す。
|
||||
2. 不透明度 α を a / 255 とする。色の各成分は、不透明度で割って元の色に戻した sRGB の値 c にする。a が 255 のときは 255 で割り、そうでないときは a で割って、1 を超えたら 1 とする。
|
||||
3. c を線形の値へ直す(`LightTransform.Decode`)。c が 0.04045 以下なら c / 12.92、1 以上なら 1、それ以外は ((c + 0.055) / 1.055)^2.4 とする。
|
||||
4. ハイライトがあるときは、3 つの c の最大値を m とし、e を (m - t) / (1 - t) を 0〜1 に打ち切った値として、倍率 w を 1 + (s - 1) × e × e とする。ないときは、w を 1 とする。
|
||||
5. 戻す値は、線形の値の 3 つに α × w を掛けた値と、α × w とする。
|
||||
|
||||
出力の変換は、`LightTransform.ToBytes` です。畳み込んだ値の赤、緑、青、不透明度と、ゲイン g、画素の位置 (x, y) を受け取り、BGRA の 8 ビットを返します。`Linear` が偽のときは、各成分に g を掛けて 0〜1 に打ち切り(NaN は 0)、丸めます。真のときは、次の順に求めます。
|
||||
|
||||
1. 不透明度に g を掛けて 0〜1 に打ち切り(NaN は 0)、A とする。A が 0 なら、色は 0 とする。
|
||||
2. 色の各成分に g を掛けて 0〜1 に打ち切り、A を超える分を A に抑える。A で割った値を、画素の値へ戻す(`LightTransform.Encode`)。線形の値が 0.0031308 以下なら 12.92 を掛け、1 以上なら 1、それ以外は 1.055 × 値^(1/2.4) - 0.055 とする。
|
||||
3. 戻した値に A を掛ける。
|
||||
4. 8 ビットに丸める。
|
||||
|
||||
丸めは、`Dither` が偽なら、255 を掛けて 0.5 を足し、小数を切り捨てます。真なら、255 を掛けた値に、画素の位置で決まる θ を足し、255 を上限として小数を切り捨てます。上限が要るのは、値が 1 で θ が 1 にごく近いと、float の足し算の結果が 256 になり、byte へ変えると 0 に戻るためです。θ は、1 つの画素の 4 つの値(赤、緑、青、不透明度)に同じ値を使います。θ が同じなら、丸めは値の大小を保ちます。そのため、丸める前に色が不透明度を超えていない画素は、丸めたあとも超えません。チャンネルごとに別の θ を使うと、色が不透明度を 1 階調だけ超える画素が出て、premultiplied alpha として正しくなくなります。θ は、`LightTransform.DitherThreshold` が、x と y から、次の整数のハッシュで求めます。符号なしの 32 ビットの計算で、桁あふれは捨てます。
|
||||
|
||||
```
|
||||
h = (x × 0x9E3779B1) xor (y × 0x85EBCA77)
|
||||
h = h xor (h >> 16)
|
||||
h = h × 0x7FEB352D
|
||||
h = h xor (h >> 15)
|
||||
h = h × 0x846CA68B
|
||||
h = h xor (h >> 16)
|
||||
θ = (h >> 8) / 2^24
|
||||
```
|
||||
|
||||
画素の位置は、畳み込む範囲と同じ座標系です。
|
||||
|
||||
`Decode` と `Encode` のべき乗は、CPU では、表の補間で求めます。表は、値と傾きの組を並べたもので、変換する float のビットを添字にします。そのため、暗い値でも明るい値でも、刻みの細かさは相対的に同じです。`Encode` は、2 のべき乗ごとに 256 刻みで、2^-9 から 1 までの表を持ちます。`Decode` は、2 のべき乗ごとに 1024 刻みで、2^-4 から 1 までの表を持ちます。どちらも相対誤差は 5 × 10^-7 以下です。この大きさは、GPU の `Hlsl.Pow` の誤差と同じです。素材の 8 ビットの値 256 通りを `Decode` した値は、表にして持ちます。
|
||||
|
||||
CPU の経路は、素材を行に置くときに `FromBytes` を通します。出力の書き込みと `RenderStored` は、画素 1 つ分をベクトルに置く `LightTransform.ToPacked` を通します。`ToPacked` は、`ToBytes` と同じ演算を同じ順に行うので、返すバイトは `ToBytes` と同じです。試験が、乱数と端の値で比べます。`RenderStored` には、画素の位置を求めるために、畳み込む範囲の幅と左上の座標も渡します。ディザが偽なら、幅と座標は使いません。ゲインを掛ける前に保存する値は、線形光のときは線形の値で、ハイライトの持ち上げを含みます。
|
||||
|
||||
GPU の経路は、`LightOptions` が既定でないときだけ、別のシェーダーを使います。既定のときは、これまでのシェーダーのままです。別のシェーダーは、`ForwardRowLightShader`、`InverseRowLightShader`、`StoredRenderLightShader` の 3 つで、`ColumnShader` と `GatherShader` は共通です。変換と丸めは、`LightTransform` と同じ順に float で書き、べき乗は `Hlsl.Pow` で求めます。`GpuTileJob` の `Light` には、`Prepare` の最後の引数が入ります。`RecordStored` には、`LightOptions` と、畳み込む範囲の左上の座標を渡します。
|
||||
|
||||
既定でないときは、検査の材料が次の 2 点で変わります。1 つ目は、素材の和と 2 乗の和です。変換した値は整数ではないので、整数のアトミック加算では足せません。`ForwardRowLightShader` は、スレッドごとに 2 個の値を足し、グループの中を深さ 8 の二分木で足して、float のビットを `uint` に入れて書きます。置き場所と並びは変わりません。2 つ目は、`GatherShader` が集める近傍で、変換する前の 8 ビットの値のままです。変換は CPU が行います。
|
||||
|
||||
`GpuTileCheck.Evaluate` は、`job.Light` が既定でないとき、次のように変わります。
|
||||
|
||||
- 素材の和の参照値は、グループごとの float を倍精度で足した値です。255 では割りません。足し合わせの丸めの誤差は、演算 16 回分として、許容値に Gamma(16, 2^-23) / (1 - Gamma(16, 2^-23)) を参照値に掛けた値を足します。
|
||||
- タイルの 2 ノルムは、2 乗の和の float を倍精度で足した値に 1 / (1 - Gamma(16, 2^-23)) を掛け、平方根を取った値です。
|
||||
- 抜き取りの参照値は、`DirectCorrelation.Evaluate` に `LightOptions` を渡して求めます。近傍の 8 ビットの値を `FromBytes` で直し、倍精度で足し合わせます。
|
||||
- `Linear` が真のときは、GPU と CPU のべき乗の差の分として、タイルの 2 ノルムの 2^-16 倍を、抜き取りの許容値に足します。差は、GPU のべき乗の誤差(Intel Iris Xe Graphics で測った最大で約 5 × 10^-7)と、CPU の表の補間の誤差(5 × 10^-7 以下)の和で、約 10^-6 以下です。2^-16 は、その約 15 倍です。
|
||||
|
||||
素材の和の参照値は GPU が足した値なので、総和の検査は、素材を直す計算の誤りを見つけません。この誤りは、抜き取りが見つけます。
|
||||
|
||||
---
|
||||
|
||||
### 8. 色ごとのカーネル
|
||||
|
||||
カーネルを赤、緑、青で変える場合は、`KernelSpectrum` の代わりに `ChromaticKernelSpectrum` を使います。`Update` は、赤、緑、青のカーネルと、半径とタイルの一辺を取ります。3 つのカーネルは、それぞれ和が 1 になるように正規化します。不透明度のカーネルには、緑のカーネルを使います。3 つのスペクトルの計算は、`WorkerPool.Shared` の作業スレッドに分けて行います。作業スレッドは、論理プロセッサの数から 1 を引いた数で、5 本までです。呼び出したスレッドも計算に加わるので、並列度は 6 までです。`CpuTileConvolver.Convolve` と `GpuTileConvolver.Upload` は、`ChromaticKernelSpectrum` を取る形も持ちます。GPU の経路で畳み込みを記録するときは、`GpuTileConvolver.Prepare` の最後の引数に `true` を渡します。
|
||||
|
||||
行ごとの変換の後の値を、赤と緑の組で Z(kx, y) と書きます。Z は、赤の行の変換 R̂ を実部、緑の行の変換 Ĝ を虚部とした R̂ + iĜ です。赤も緑も実数の行なので、R̂(-kx) = conj(R̂(kx)) で、Ĝ も同じです。したがって、次のように分けられます。
|
||||
|
||||
```
|
||||
R̂(kx) = (Z(kx) + conj(Z(-kx))) / 2
|
||||
Ĝ(kx) = (Z(kx) - conj(Z(-kx))) / (2i)
|
||||
```
|
||||
|
||||
分けた値を列ごとに変換し、赤と緑のスペクトルを掛け、逆変換した後で、R̂'(kx) と Ĝ'(kx) から次のように合わせます。
|
||||
|
||||
```
|
||||
Z'(kx) = R̂'(kx) + iĜ'(kx)
|
||||
Z'(-kx) = conj(R̂'(kx)) + i conj(Ĝ'(kx))
|
||||
```
|
||||
|
||||
kx が 0 と T / 2 の列は、-kx が自分自身になるので、実部と虚部がそのまま 2 つのチャンネルです。分けた値は、kx が 0 から T / 2 までの列だけで足りるので、列ごとの変換の回数は、チャンネルをまとめた場合と同じです。青と不透明度の組も、同じ計算を、青と緑のスペクトルで行います。スペクトルは、3 つのカーネルの、kx が 0 から T / 2 までの列を、赤、緑、青の順に並べたものです。1 つの値は、行が kx、列が周波数 ky の順に並びます。
|
||||
|
||||
GPU のシェーダー `ColumnChromaticShader` は、256 スレッドのグループが、kx と T - kx の 2 つの列の組を、512 / T 組ずつ受け持ちます。グループ共有メモリは 1024 個の `Float4` です。変換は、連続する 2 段を 1 回の同期にまとめます。1024 個の値は、4 つの値の組が 256 個なので、256 スレッドのすべてが計算します。同じ Float4 を別のグループが書くことは無いので、タイルの値は、その場で書き換えます。
|
||||
|
||||
`GpuTileCheck.Evaluate` は、赤、緑、青のカーネルを取る形を持ちます。抜き取りの参照値を、赤、緑、青に各自のカーネルを使い、不透明度に緑のカーネルを使って求めます。`DirectCorrelation.Evaluate` も同じ形を持ちます。
|
||||
|
||||
## 誤差の上限
|
||||
|
||||
ここでは、float で計算した畳み込みの値と、厳密な値との差の上限を導きます。差は素材の 2 ノルムに対する相対誤差で追い、1 タイル、1 画素、総和の順に上限を求めます。
|
||||
@@ -332,11 +438,13 @@ GPU は、検査の材料を 1 つの `uint` のバッファー(`Report`)に
|
||||
| 倍精度の演算 | IEEE 754 の最も近い値への丸めに従い、相対誤差は 2^-53 以下 |
|
||||
| 融合演算 | 掛け算と足し算を 1 つの演算にまとめない。GPU のシェーダーは `-Gis` でコンパイルし、CPU の側は .NET の JIT がまとめないものとする |
|
||||
| 8 ビットから float への変換 | 255 で割った値を正しく丸める。相対誤差は 2^-24 以下。[変換の規則](https://learn.microsoft.com/en-us/windows/win32/direct3d10/d3d10-graphics-programming-guide-resources-data-conversion)は許容誤差を書かないので、この丸めを前提に置く |
|
||||
| `Math.SinCos` | 返す値の誤差は、各成分で 2^-51 以下 |
|
||||
| `Math.SinCos`、`Math.Sin`、`Math.Cos` | 返す値の誤差は、各成分で 2^-51 以下 |
|
||||
| カーネル | 値はすべて 0 以上で、和で割って 1 にそろえてある。実際の和は 1 からわずかにずれる |
|
||||
|
||||
カーネルが 0 以上で和が 1 であるという前提から、スペクトルの絶対値はどこでも 1 以下になり、カーネルの 2 ノルムも 1 以下になります。実際の和は 1 から γ_ker までずれます。γ_ker は、次の記号の表で定義します。このずれの扱いは、[式に入れていない誤差と上限の余裕](#10-式に入れていない誤差と上限の余裕)で説明します。
|
||||
|
||||
この上限の数値は、`Linear` と `Dither` が偽で、素材の値が 0〜1 のときの値です。`Linear` が真のときは、畳み込みの入力が、素材の値ではなく変換した値になります。1 タイルの上限の式は、入力の 2 ノルムに比例する形なので、変換した値の 2 ノルムで成り立ちます。ただし、ハイライトで入力が 1 を超えるため、2 ノルムが大きくなり、上限は同じ割合で大きくなります。GPU が素材を変換する計算の誤差は、上限に入れず、[検査の材料と検査](#5-検査の材料と検査)の許容値に別に加えます。
|
||||
|
||||
### 記号
|
||||
|
||||
| 記号 | 意味 |
|
||||
@@ -369,7 +477,7 @@ GPU は、検査の材料を 1 つの `uint` のバッファー(`Report`)に
|
||||
|
||||
回転因子の成分は、0 でないとき絶対値が約 6 × 10^-17 以上で、2^-126 より大きいので、μ には、非正規化数を 0 にそろえる分を入れません。
|
||||
|
||||
スペクトルは、倍精度の 2L 段の変換で求めます。この変換の相対誤差の上限を α_d とします。α_d は、[変換の 1 段](#2-変換の-1-段)と[2 次元の変換](#3-2-次元の変換)の式で、u を 2^-53 に、μ を μ_d に置き換えた値です。
|
||||
スペクトルは、倍精度の 2L 段の変換で求めます。この変換の相対誤差の上限を α_d とします。α_d は、[変換の 1 段](#2-変換の-1-段)と[2 次元の変換](#3-2-次元の変換)の式で、u を 2^-53 に、μ を μ_d に置き換えた値です。複素共役を写した列の値は、写す元の値と複素数の絶対値が等しいので、誤差の上限も同じで、以下の上限はスペクトルのすべての値に成り立ちます。
|
||||
|
||||
```
|
||||
η_d = (1 + 2^-53)(μ_d + (1 + μ_d) √2 γ_2(2^-53)) + 2^-53
|
||||
@@ -510,6 +618,27 @@ Z = G × 511 × 2^-126
|
||||
|
||||
2 つのずれの合計は、2γ_ker が 6 × 10^-11 未満、倍精度の計算の丸めが 10^-9 未満なので、1.1 × 10^-9 未満です。余裕はこの合計の 50 倍を超えるので、上限はずれを含めても成り立ちます。
|
||||
|
||||
### 11. 色ごとのカーネルの経路
|
||||
|
||||
色を分ける計算と合わせる計算は、どちらも要素ごとの足し算と、2 の累乗の掛け算です。足し算 1 回の誤差は、組の 2 つの値の絶対値の和に対する α 以下で、全体の 2 ノルムに対しては √2 α 以下です。この誤差が、列ごとの変換より前と、逆変換より後に 1 回ずつ入ります。どちらも、あとの計算で 2 ノルムを増やさないものとして、1 タイルの相対の上限 B に次の項を加えます。
|
||||
|
||||
```
|
||||
B_c = B + 2 √2 α (1 + B)
|
||||
```
|
||||
|
||||
0 にされる値の数には、分ける計算と合わせる計算の分として、⌈16 √2 T⌉ 個を加えます。この式は、`ConvolutionBound.ChromaticRelative` と `ConvolutionBound.ChromaticFlushedOperations` にあります。上の項は、足し算の丸めから置いた見積もりで、導出は 1 タイルの上限ほど厳密ではありません。実際の誤差が上限を超えないことは、全画素を直接の計算と比べる試験で確かめています。
|
||||
|
||||
[1 画素の上限](#7-1-画素の上限)と同じ条件で、‖x‖ に √2 T を入れて 255 倍し、小数第 3 位までに四捨五入した値を示します。
|
||||
|
||||
| T | GPU の経路(階調、四捨五入) | CPU の経路(階調、四捨五入) |
|
||||
|---:|---:|---:|
|
||||
| 64 | 0.304 | 0.170 |
|
||||
| 128 | 0.704 | 0.393 |
|
||||
| 256 | 1.598 | 0.892 |
|
||||
| 512 | 3.576 | 1.997 |
|
||||
|
||||
総和の上限と参照値の誤差は、どのカーネルの和も 1 なので、カーネルが 1 つの場合と同じです。
|
||||
|
||||
---
|
||||
|
||||
## 決定論
|
||||
@@ -517,6 +646,7 @@ Z = G × 511 × 2^-126
|
||||
- タイルどうしは互いに独立しています。CPU の経路では、スレッド数と、どのスレッドがどのタイルを受け持つかを変えても、結果は 1 ビットも変わりません。
|
||||
- GPU の経路では、同じデバイスで同じ入力を 2 回計算すると、結果は 1 ビットも変わりません。単体試験と自己試験で確かめています。
|
||||
- 出力の和は、グループの中では決まった木の形で、グループどうしは CPU が決まった順で足します。NaN と無限大の個数、素材の和と 2 乗の和は、整数のアトミック加算で数えます。整数の加算は順序に左右されないので、毎回同じ値になります。
|
||||
- `LightOptions` が既定でないとき、素材の和と 2 乗の和は、グループの中では決まった木の形で足した float です。同じデバイスで同じ入力を 2 回計算すると、同じ値になります。
|
||||
- CPU の経路と GPU の経路は、結果が 1 ビット単位では一致するとは限りません。Direct3D の規則では、GPU は加算、減算、乗算の結果を、最も近い値へ丸める代わりに切り捨てることも許されているためです。2 つの経路の差は、それぞれの誤差の上限の和を超えません。
|
||||
|
||||
---
|
||||
@@ -528,7 +658,7 @@ GPU の経路で `GpuTileConvolver` が確保するメモリは、次のとお
|
||||
| 資源 | 大きさ |
|
||||
|---|---|
|
||||
| タイルのバッチ | 16 MB 以下 |
|
||||
| スペクトル | 8 T² バイト。T が 512 のとき 2 MB |
|
||||
| スペクトル | 8 T² バイト。T が 512 のとき 2 MB。色ごとのカーネルでは 24 (T / 2 + 1) T バイトで、T が 512 のとき約 3 MB |
|
||||
| 回転因子 | 4 T バイト |
|
||||
| 検査の材料 | (1 + 10 G + 4 S + S (2r + 1)²) × 4 バイト。CPU から読める写しを含めて、その 2 倍 |
|
||||
| 抜き取る位置 | 128 バイト |
|
||||
@@ -537,7 +667,7 @@ GPU の経路で `GpuTileConvolver` が確保するメモリは、次のとお
|
||||
|
||||
タイルのバッチと検査の材料は、それまでで最も大きかった大きさを持ち続けます。
|
||||
|
||||
CPU の経路で `CpuTileConvolver` が持つメモリは、計算したスレッドごとに 16 T² + 32 T バイトです。タイルの分の合計は 64 MB 以下で、T が変わると捨てます。`WorkingBytes` は、いま持っている作業領域のバイト数を返します。ほかに、高速フーリエ変換の要素の並べ替えに使う順序の表を、それまでで最も大きかった T について 4 T バイト持ちます。素材、出力、保存する値の配列は、呼び出し側が用意します。
|
||||
CPU の経路で `CpuTileConvolver` が持つメモリは、計算したスレッドごとに 16 T² + 32 T バイトです。色ごとのカーネルを計算したスレッドは、さらに 32 T バイトを持ちます。タイルの分の合計は 64 MB 以下で、T が変わると捨てます。`WorkingBytes` は、いま持っている作業領域のバイト数を返します。ほかに、高速フーリエ変換の要素の並べ替えに使う順序の表を、それまでで最も大きかった T について 4 T バイト持ちます。素材、出力、保存する値の配列は、呼び出し側が用意します。
|
||||
|
||||
---
|
||||
|
||||
@@ -559,7 +689,7 @@ CPU の経路で `CpuTileConvolver` が持つメモリは、計算したスレ
|
||||
- 検査で見つけられるのは、NaN と無限大、総和、16 か所までの抜き取りに表れた誤りだけです。抜き取った位置の外の誤りで、総和が変わらないものは見逃します。
|
||||
- 総和の検査には条件があります。条件を外れる素材の画素があると、正常な GPU でも総和の検査で不合格になることがあります。条件は、[検査の材料と検査](#5-検査の材料と検査)にあります。
|
||||
- カーネルの値は 0 以上でなければなりません。負の値を含むカーネルでは、スペクトルの絶対値が 1 を超えることがあり、上限の導出が成り立たないためです。`KernelSpectrum.Update` は、負の値があると `ArgumentOutOfRangeException` を投げます。
|
||||
- 誤差の上限は、[前提](#前提)が成り立つときの値です。`Math.SinCos` の精度は .NET の仕様で保証されていないため、前提として置いています。
|
||||
- 誤差の上限は、[前提](#前提)が成り立つときの値です。`Math.SinCos`、`Math.Sin`、`Math.Cos` の精度は .NET の仕様で保証されていないため、前提として置いています。
|
||||
- 型はどれも 1 つのスレッドから使う前提です。`CpuTileConvolver` の呼び出しを、複数のスレッドから同時に行わないでください。
|
||||
|
||||
---
|
||||
@@ -577,7 +707,17 @@ dotnet test SpectralConvolution/SpectralConvolution.Tests/SpectralConvolution.Te
|
||||
- CPU と GPU の結果が、`DirectCorrelation` の値との差で上限に収まること。素材の 8 ビットの値がすべて 255 の場面も含みます。
|
||||
- GPU の命令を CPU で実行するソフトウェア アダプターである Microsoft Basic Render Driver でも、上限に収まり、検査に合格すること
|
||||
- CPU の結果がスレッド数によらないこと。GPU の結果が 2 回で 1 ビットも違わないこと
|
||||
- 保存した値から描いた結果が、畳み込みと同時に出力した結果と 1 ビットも違わないこと
|
||||
- 保存した値から描いた結果が、畳み込みと同時に出力した結果と 1 ビットも違わないこと。線形光、ハイライト、ディザを使うときも同じです。
|
||||
- 線形光の変換が、値の両端を保ち、標準の曲線に従い、すべての 8 ビットの値を往復して元に戻ること。ハイライトが、しきい値以下を持ち上げず、倍率が強さまで上がり、色の比を保つこと
|
||||
- 線形光とハイライトとディザの結果が、変換した素材からの `DirectCorrelation` の値との差で上限に収まり、GPU の検査にすべて合格すること。ハイライトを間違えると、抜き取りで不合格になること
|
||||
- ディザの値が 0 以上 1 未満で、毎回同じ値になり、平均が 0.5 になること。値が 1 のときに 0 へ戻らないこと。不透明な白の素材が、ディザで黒く欠けないこと。値が、この説明のハッシュの式と一致すること
|
||||
- 色が不透明度を超えない画素の出力が、ディザのときも、色が不透明度を超えないこと。CPU と GPU の両方で、半透明の素材を使って確かめます。
|
||||
- ハイライトの倍率が、画素の最も明るいチャンネルで決まること。それが赤、緑、青のどれでも同じです。しきい値よりはるかに暗い画素は、持ち上げません。
|
||||
- `Encode` の相対誤差が、標準の曲線に対して 10^-6 以下であること。しきい値の前後と、1 の直前を含みます。
|
||||
- `ToPacked` の結果が、乱数と端の値(NaN、無限大、負の値、1 を超える値)で、`ToBytes` の結果と一致すること
|
||||
- `Butterflies` の結果が、スカラーの式 `ButterfliesScalar` の結果と、T が 2 から 512 のすべてでビットごとに一致すること。保存した値の 8 ビットへの変換が、`ToUnorm` と一致すること
|
||||
- GPU の出力が、保存した値を `ToBytes` で変換した値と、ほぼすべての値で一致すること。違う値は 1 階調以内で、全体の 0.05% 以下です。
|
||||
- `Samples` バッファーの印が、抜き取る位置があるタイルだけに付くこと。次の呼び出しでは、前の位置の印が消えること
|
||||
- CPU の経路で持ち続ける作業領域が、計算したスレッドの分だけで、T が変わると捨てられること
|
||||
- GPU に渡すスペクトルを 1.0005 倍すると、総和の検査で不合格になること
|
||||
- スペクトルの虚部の符号を反転すると、抜き取りの検査で不合格になり、総和の検査は合格のままであること。この反転は、カーネルの上下と左右を反転することに当たります。
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
using ComputeWeave;
|
||||
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
public sealed class ByteColorTests
|
||||
{
|
||||
[Fact]
|
||||
public void TheByteRangeIsZeroToTwoHundredFiftyFive()
|
||||
{
|
||||
Assert.Equal(256, ByteColor.Levels);
|
||||
Assert.Equal(255, ByteColor.Maximum);
|
||||
Assert.Equal(255u, ByteColor.Mask);
|
||||
Assert.Equal(255f, ByteColor.Scale);
|
||||
Assert.Equal(255d, ByteColor.ScaleDouble);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0f, 0u)]
|
||||
[InlineData(1f, 255u)]
|
||||
[InlineData(0.5f, 128u)]
|
||||
[InlineData(0.498f, 127u)]
|
||||
[InlineData(0.002f, 1u)]
|
||||
[InlineData(0.001f, 0u)]
|
||||
public void AValueBecomesTheNearestLevel(float value, uint expected)
|
||||
{
|
||||
Assert.Equal(expected, ByteColor.ToLevel(value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChannelsArePackedFromTheLowestByteFirst()
|
||||
{
|
||||
var packed = ByteColor.Pack(new Float4(1f / 255f, 2f / 255f, 3f / 255f, 4f / 255f));
|
||||
|
||||
Assert.Equal(0x04030201u, packed);
|
||||
for (var index = 0; index < 4; index++)
|
||||
Assert.Equal((uint)index + 1u, ByteColor.Channel(packed, index));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PackingMatchesTheDirectCorrelationLayout()
|
||||
{
|
||||
var packed = ByteColor.Pack(new Float4(10f / 255f, 20f / 255f, 30f / 255f, 40f / 255f));
|
||||
|
||||
Assert.Equal(DirectCorrelation.Pack(10, 20, 30, 40), packed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
internal sealed class ChromaticConvolutionScene
|
||||
{
|
||||
(double RedGreen, double BlueAlpha)[]? tileNorms;
|
||||
|
||||
ChromaticConvolutionScene(byte[] source, int sourceX, int sourceY, int sourceWidth, int sourceHeight, ChromaticKernelSpectrum spectrum, TilePlan plan, LightOptions light)
|
||||
{
|
||||
Source = source;
|
||||
SourceX = sourceX;
|
||||
SourceY = sourceY;
|
||||
SourceWidth = sourceWidth;
|
||||
SourceHeight = sourceHeight;
|
||||
Spectrum = spectrum;
|
||||
Plan = plan;
|
||||
Light = light;
|
||||
}
|
||||
|
||||
public byte[] Source { get; }
|
||||
|
||||
public int SourceX { get; }
|
||||
|
||||
public int SourceY { get; }
|
||||
|
||||
public int SourceWidth { get; }
|
||||
|
||||
public int SourceHeight { get; }
|
||||
|
||||
public ChromaticKernelSpectrum Spectrum { get; }
|
||||
|
||||
public TilePlan Plan { get; }
|
||||
|
||||
public LightOptions Light { get; }
|
||||
|
||||
public int RegionLength => Plan.RegionWidth * Plan.RegionHeight * 4;
|
||||
|
||||
public static double[] Kernel(int radius, double spread, double lean)
|
||||
{
|
||||
var size = radius * 2 + 1;
|
||||
var values = new double[size * size];
|
||||
for (var y = 0; y < size; y++)
|
||||
{
|
||||
for (var x = 0; x < size; x++)
|
||||
{
|
||||
var dx = x - radius * lean;
|
||||
var dy = y - radius * (2d - lean);
|
||||
values[y * size + x] = Math.Exp(-(dx * dx * 0.4 + dy * dy * 0.15) / (spread * (radius * radius + 1d))) + (x == 0 && y == size - 1 ? 0.5 : 0d);
|
||||
}
|
||||
}
|
||||
|
||||
return values;
|
||||
}
|
||||
|
||||
public static ChromaticConvolutionScene Create(byte[] source, int sourceWidth, int sourceHeight, int margin, int radius, int size, LightOptions light = default)
|
||||
=> CreateShifted(source, margin, margin, sourceWidth, sourceHeight, 0, 0, sourceWidth + margin * 2, sourceHeight + margin * 2, radius, size, light);
|
||||
|
||||
public static ChromaticConvolutionScene CreateShifted(
|
||||
byte[] source, int sourceX, int sourceY, int sourceWidth, int sourceHeight,
|
||||
int regionX, int regionY, int regionWidth, int regionHeight, int radius, int size, LightOptions light = default)
|
||||
{
|
||||
var spectrum = new ChromaticKernelSpectrum();
|
||||
spectrum.Update(Kernel(radius, 1.3, 0.6), Kernel(radius, 1d, 0.9), Kernel(radius, 0.7, 1.2), radius, size);
|
||||
var plan = TilePlan.Create(size, radius, regionX, regionY, regionWidth, regionHeight);
|
||||
return new ChromaticConvolutionScene(source, sourceX, sourceY, sourceWidth, sourceHeight, spectrum, plan, light);
|
||||
}
|
||||
|
||||
public void Reference(int x, int y, Span<double> result)
|
||||
{
|
||||
var radius = Spectrum.Radius;
|
||||
if (!Light.Linear)
|
||||
{
|
||||
DirectCorrelation.Evaluate(Source, SourceWidth, SourceHeight, Spectrum.Red.Kernel, Spectrum.Green.Kernel, Spectrum.Blue.Kernel, radius, x - SourceX, y - SourceY, result);
|
||||
return;
|
||||
}
|
||||
|
||||
var kernelSize = radius * 2 + 1;
|
||||
var values = Transformed();
|
||||
result[..4].Clear();
|
||||
for (var offsetY = -radius; offsetY <= radius; offsetY++)
|
||||
{
|
||||
var sourceY = y - SourceY + offsetY;
|
||||
if (sourceY < 0 || sourceY >= SourceHeight)
|
||||
continue;
|
||||
for (var offsetX = -radius; offsetX <= radius; offsetX++)
|
||||
{
|
||||
var sourceX = x - SourceX + offsetX;
|
||||
if (sourceX < 0 || sourceX >= SourceWidth)
|
||||
continue;
|
||||
var index = (offsetY + radius) * kernelSize + offsetX + radius;
|
||||
var offset = (sourceY * SourceWidth + sourceX) * 4;
|
||||
result[0] += values[offset] * Spectrum.Red.Kernel[index];
|
||||
result[1] += values[offset + 1] * Spectrum.Green.Kernel[index];
|
||||
result[2] += values[offset + 2] * Spectrum.Blue.Kernel[index];
|
||||
result[3] += values[offset + 3] * Spectrum.Green.Kernel[index];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public (double RedGreen, double BlueAlpha) Norms(int x, int y)
|
||||
{
|
||||
tileNorms ??= [.. Enumerable.Range(0, Plan.TileCount).Select(TileNorms)];
|
||||
return tileNorms[Plan.TileAt(x, y)];
|
||||
}
|
||||
|
||||
public double WorstRatio(ReadOnlySpan<float> convolved, double operationError)
|
||||
{
|
||||
var reference = new double[4];
|
||||
var worst = 0d;
|
||||
var referenceError = DirectCorrelation.ErrorBound(Spectrum.Green.Kernel.Length);
|
||||
for (var y = 0; y < Plan.RegionHeight; y++)
|
||||
{
|
||||
for (var x = 0; x < Plan.RegionWidth; x++)
|
||||
{
|
||||
var canvasX = Plan.RegionX + x;
|
||||
var canvasY = Plan.RegionY + y;
|
||||
Reference(canvasX, canvasY, reference);
|
||||
var (redGreen, blueAlpha) = Norms(canvasX, canvasY);
|
||||
var index = (y * Plan.RegionWidth + x) * 4;
|
||||
for (var channel = 0; channel < 4; channel++)
|
||||
{
|
||||
var norm = channel < 2 ? redGreen : blueAlpha;
|
||||
var bound = ConvolutionBound.ChromaticAbsolute(Plan.Size, operationError, norm) + referenceError;
|
||||
worst = Math.Max(worst, Math.Abs(convolved[index + channel] - reference[channel]) / bound);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return worst;
|
||||
}
|
||||
|
||||
float[] Transformed()
|
||||
{
|
||||
var values = new float[SourceWidth * SourceHeight * 4];
|
||||
for (var index = 0; index < SourceWidth * SourceHeight; index++)
|
||||
{
|
||||
var (red, green, blue, alpha) = LightTransform.FromBytes(Source[index * 4 + 2], Source[index * 4 + 1], Source[index * 4], Source[index * 4 + 3], Light);
|
||||
values[index * 4] = red;
|
||||
values[index * 4 + 1] = green;
|
||||
values[index * 4 + 2] = blue;
|
||||
values[index * 4 + 3] = alpha;
|
||||
}
|
||||
|
||||
return values;
|
||||
}
|
||||
|
||||
(double RedGreen, double BlueAlpha) TileNorms(int tile)
|
||||
{
|
||||
if (!Light.Linear)
|
||||
return TileInput.Norms(Source, SourceX, SourceY, SourceWidth, SourceHeight, Plan, tile);
|
||||
|
||||
var values = Transformed();
|
||||
var left = Plan.OriginX(tile) - Plan.Radius;
|
||||
var top = Plan.OriginY(tile) - Plan.Radius;
|
||||
var redGreen = 0d;
|
||||
var blueAlpha = 0d;
|
||||
var lastY = Math.Min(top + Plan.Size, SourceY + SourceHeight);
|
||||
var lastX = Math.Min(left + Plan.Size, SourceX + SourceWidth);
|
||||
for (var y = Math.Max(top, SourceY); y < lastY; y++)
|
||||
{
|
||||
for (var x = Math.Max(left, SourceX); x < lastX; x++)
|
||||
{
|
||||
var offset = ((y - SourceY) * SourceWidth + x - SourceX) * 4;
|
||||
redGreen += (double)values[offset] * values[offset] + (double)values[offset + 1] * values[offset + 1];
|
||||
blueAlpha += (double)values[offset + 2] * values[offset + 2] + (double)values[offset + 3] * values[offset + 3];
|
||||
}
|
||||
}
|
||||
|
||||
return (Math.Sqrt(redGreen), Math.Sqrt(blueAlpha));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
public sealed class ChromaticCpuConvolverTests
|
||||
{
|
||||
static (byte[] Output, float[] Convolved) Run(ChromaticConvolutionScene scene, int threads, float gain = 1f)
|
||||
{
|
||||
var output = new byte[scene.RegionLength];
|
||||
var convolved = new float[scene.RegionLength];
|
||||
using var convolver = new CpuTileConvolver(threads);
|
||||
convolver.Convolve(scene.Source, scene.SourceX, scene.SourceY, scene.SourceWidth, scene.SourceHeight, scene.Spectrum, scene.Plan, output, gain, convolved, scene.Light);
|
||||
return (output, convolved);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASharedConvolverGivesTheResultOfADedicatedOne()
|
||||
{
|
||||
var scene = ChromaticConvolutionScene.Create(ConvolutionScene.RandomSource(200, 120, 17, 0.5), 200, 120, 14, 9, 64);
|
||||
|
||||
var dedicated = Run(scene, Environment.ProcessorCount, 1.5f);
|
||||
var output = new byte[scene.RegionLength];
|
||||
var convolved = new float[scene.RegionLength];
|
||||
using var shared = CpuTileConvolver.CreateShared();
|
||||
shared.Convolve(scene.Source, scene.SourceX, scene.SourceY, scene.SourceWidth, scene.SourceHeight, scene.Spectrum, scene.Plan, output, 1.5f, convolved, scene.Light);
|
||||
|
||||
Assert.Equal(dedicated.Output, output);
|
||||
Assert.Equal(dedicated.Convolved, convolved);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(64, 5, 150, 97, 11)]
|
||||
[InlineData(128, 23, 140, 90, 24)]
|
||||
[InlineData(256, 40, 110, 70, 44)]
|
||||
[InlineData(64, 0, 70, 70, 3)]
|
||||
public void TheResultStaysWithinTheBoundOfTheExactCorrelationOfEachChannel(int size, int radius, int width, int height, int margin)
|
||||
{
|
||||
var scene = ChromaticConvolutionScene.Create(ConvolutionScene.RandomSource(width, height, size + radius, 0.4), width, height, margin, radius, size);
|
||||
|
||||
var (_, convolved) = Run(scene, 3);
|
||||
|
||||
Assert.True(scene.Plan.TileCount > 1);
|
||||
Assert.InRange(scene.WorstRatio(convolved, ConvolutionBound.CpuOperationError), 0d, 1d);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false, 0f, 0f)]
|
||||
[InlineData(true, 0f, 0f)]
|
||||
[InlineData(true, 0.8f, 20f)]
|
||||
public void TheLinearLightResultStaysWithinTheBound(bool linear, float threshold, float boost)
|
||||
{
|
||||
var light = new LightOptions(linear, false, threshold, boost);
|
||||
var scene = ChromaticConvolutionScene.Create(ConvolutionScene.RandomSource(130, 90, 21, 0.5), 130, 90, 12, 9, 64, light);
|
||||
|
||||
var (_, convolved) = Run(scene, 2);
|
||||
|
||||
Assert.InRange(scene.WorstRatio(convolved, ConvolutionBound.CpuOperationError), 0d, 1d);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IdenticalKernelsGiveTheResultOfASingleKernelWithinTheBound()
|
||||
{
|
||||
const int radius = 7;
|
||||
var kernel = ConvolutionScene.AsymmetricKernel(radius);
|
||||
var single = new KernelSpectrum();
|
||||
single.Update(kernel, radius, 64);
|
||||
var chromatic = new ChromaticKernelSpectrum();
|
||||
chromatic.Update(kernel, kernel, kernel, radius, 64);
|
||||
var source = ConvolutionScene.RandomSource(140, 100, 17, 0.5);
|
||||
var plan = TilePlan.Create(64, radius, 0, 0, 140 + 20, 100 + 20);
|
||||
var expected = new byte[plan.RegionWidth * plan.RegionHeight * 4];
|
||||
var actual = new byte[expected.Length];
|
||||
var expectedValues = new float[expected.Length];
|
||||
var actualValues = new float[expected.Length];
|
||||
using var convolver = new CpuTileConvolver(2);
|
||||
|
||||
convolver.Convolve(source, 10, 10, 140, 100, single, plan, expected, 1f, expectedValues);
|
||||
convolver.Convolve(source, 10, 10, 140, 100, chromatic, plan, actual, 1f, actualValues);
|
||||
|
||||
var tolerance = ConvolutionBound.Absolute(64, ConvolutionBound.CpuOperationError, 1e4) + ConvolutionBound.ChromaticAbsolute(64, ConvolutionBound.CpuOperationError, 1e4);
|
||||
for (var index = 0; index < expectedValues.Length; index++)
|
||||
Assert.True(Math.Abs(expectedValues[index] - actualValues[index]) <= tolerance, $"{index}: {expectedValues[index]} {actualValues[index]}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnOpaqueWhiteSceneStaysWhiteAwayFromTheEdges()
|
||||
{
|
||||
var scene = ChromaticConvolutionScene.Create(ConvolutionScene.Uniform(120, 120, 255), 120, 120, 8, 7, 64);
|
||||
|
||||
var (output, convolved) = Run(scene, 2);
|
||||
|
||||
Assert.InRange(scene.WorstRatio(convolved, ConvolutionBound.CpuOperationError), 0d, 1d);
|
||||
var center = ((scene.Plan.RegionHeight / 2) * scene.Plan.RegionWidth + scene.Plan.RegionWidth / 2) * 4;
|
||||
Assert.Equal([255, 255, 255, 255], output.AsSpan(center, 4).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheResultDoesNotDependOnTheNumberOfThreads()
|
||||
{
|
||||
var scene = ChromaticConvolutionScene.Create(ConvolutionScene.RandomSource(300, 170, 5, 0.6), 300, 170, 16, 9, 64);
|
||||
|
||||
var single = Run(scene, 1, 1.75f);
|
||||
var several = Run(scene, 3, 1.75f);
|
||||
var many = Run(scene, 16, 1.75f);
|
||||
|
||||
Assert.Equal(single.Output, several.Output);
|
||||
Assert.Equal(single.Output, many.Output);
|
||||
Assert.Equal(single.Convolved, several.Convolved);
|
||||
Assert.Equal(single.Convolved, many.Convolved);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ARegionAwayFromTheSourceIsClearedToZero()
|
||||
{
|
||||
var spectrum = new ChromaticKernelSpectrum();
|
||||
spectrum.Update(ConvolutionScene.AsymmetricKernel(3), ConvolutionScene.AsymmetricKernel(3), ConvolutionScene.AsymmetricKernel(3), 3, 64);
|
||||
var plan = TilePlan.Create(64, 3, 500, 500, 130, 70);
|
||||
var output = new byte[plan.RegionWidth * plan.RegionHeight * 4];
|
||||
var convolved = new float[output.Length];
|
||||
Array.Fill(output, (byte)7);
|
||||
Array.Fill(convolved, 7f);
|
||||
using var convolver = new CpuTileConvolver(2);
|
||||
|
||||
convolver.Convolve(ConvolutionScene.Uniform(40, 40, 255), 0, 0, 40, 40, spectrum, plan, output, 1f, convolved);
|
||||
|
||||
Assert.All(output, value => Assert.Equal(0, value));
|
||||
Assert.All(convolved, value => Assert.Equal(0f, value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASpectrumOfAnotherSizeOrRadiusIsRejected()
|
||||
{
|
||||
var spectrum = new ChromaticKernelSpectrum();
|
||||
var kernel = ConvolutionScene.AsymmetricKernel(3);
|
||||
spectrum.Update(kernel, kernel, kernel, 3, 64);
|
||||
using var convolver = new CpuTileConvolver(1);
|
||||
var source = ConvolutionScene.Uniform(10, 10, 9);
|
||||
var output = new byte[40 * 40 * 4];
|
||||
|
||||
Assert.Throws<ArgumentException>(() => convolver.Convolve(source, 0, 0, 10, 10, spectrum, TilePlan.Create(128, 3, 0, 0, 40, 40), output, 1f, null));
|
||||
Assert.Throws<ArgumentException>(() => convolver.Convolve(source, 0, 0, 10, 10, spectrum, TilePlan.Create(64, 4, 0, 0, 40, 40), output, 1f, null));
|
||||
Assert.Throws<ArgumentException>(() => convolver.Convolve(source, 0, 0, 10, 10, new ChromaticKernelSpectrum(), TilePlan.Create(64, 3, 0, 0, 40, 40), output, 1f, null));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeWeave;
|
||||
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
[Collection("Direct3D12")]
|
||||
public sealed class ChromaticGpuConvolverTests
|
||||
{
|
||||
sealed record GpuRun(byte[] Output, float[] Store, uint[] Report, GpuTileJob Job, Int2[] Samples);
|
||||
|
||||
static GraphicsDevice HardwareOrDefault() => GraphicsDevice.GetDefault();
|
||||
|
||||
static Int2[] Samples(in TilePlan plan)
|
||||
{
|
||||
var width = plan.RegionWidth;
|
||||
var height = plan.RegionHeight;
|
||||
var valid = plan.ValidSize;
|
||||
List<Int2> samples =
|
||||
[
|
||||
new(0, 0), new(width - 1, 0), new(0, height - 1), new(width - 1, height - 1), new(width / 2, height / 2),
|
||||
new(Math.Min(valid - 1, width - 1), Math.Min(valid - 1, height - 1)), new(Math.Min(valid, width - 1), Math.Min(valid, height - 1)),
|
||||
];
|
||||
var random = new Random(width * 31 + height);
|
||||
while (samples.Count < GpuTileConvolver.MaximumSamples)
|
||||
samples.Add(new Int2(random.Next(width), random.Next(height)));
|
||||
return [.. samples];
|
||||
}
|
||||
|
||||
static GpuRun Run(GraphicsDevice device, GpuTileConvolver convolver, ChromaticConvolutionScene scene, float gain = 1f)
|
||||
{
|
||||
var plan = scene.Plan;
|
||||
var samples = Samples(plan);
|
||||
convolver.Upload(scene.Spectrum);
|
||||
var job = convolver.Prepare(plan, scene.SourceX, scene.SourceY, scene.SourceWidth, scene.SourceHeight, gain, samples, true, scene.Light, true);
|
||||
using var source = device.AllocateReadWriteTexture2D<Bgra32, Float4>(scene.SourceWidth, scene.SourceHeight);
|
||||
source.CopyFrom(MemoryMarshal.Cast<byte, Bgra32>(scene.Source));
|
||||
using var output = device.AllocateReadWriteTexture2D<Bgra32, Float4>(plan.RegionWidth, plan.RegionHeight);
|
||||
using (var context = device.CreateComputeContext())
|
||||
{
|
||||
GpuTileConvolver.Record(
|
||||
in context, source, output, convolver.Tiles, convolver.Twiddles, convolver.Spectrum,
|
||||
convolver.Report, convolver.Samples, convolver.StoreFor(job), job);
|
||||
}
|
||||
|
||||
var report = convolver.ReadReport(job).ToArray();
|
||||
var store = new Float4[plan.RegionWidth * plan.RegionHeight];
|
||||
convolver.ReadStore(job, store);
|
||||
var pixels = new Bgra32[plan.RegionWidth * plan.RegionHeight];
|
||||
output.CopyTo(pixels);
|
||||
return new GpuRun(MemoryMarshal.Cast<Bgra32, byte>(pixels).ToArray(), MemoryMarshal.Cast<Float4, float>(store).ToArray(), report, job, samples);
|
||||
}
|
||||
|
||||
static GpuRun Run(GraphicsDevice device, ChromaticConvolutionScene scene, float gain = 1f)
|
||||
{
|
||||
using var convolver = new GpuTileConvolver(device);
|
||||
return Run(device, convolver, scene, gain);
|
||||
}
|
||||
|
||||
static ChromaticConvolutionScene Scene(int size, int radius, int width, int height, int margin, int seed, LightOptions light = default)
|
||||
=> ChromaticConvolutionScene.Create(ConvolutionScene.RandomSource(width, height, seed, 0.45), width, height, margin, radius, size, light);
|
||||
|
||||
[Fact]
|
||||
public void AWarmChromaticUploadAllocatesNoManagedMemory()
|
||||
{
|
||||
var device = HardwareOrDefault();
|
||||
var scene = Scene(128, 23, 140, 90, 24, 5);
|
||||
using var convolver = new GpuTileConvolver(device);
|
||||
convolver.Upload(scene.Spectrum);
|
||||
convolver.Upload(scene.Spectrum);
|
||||
|
||||
Assert.Equal(0L, AllocationProbe.MinimumAllocatedBytes(() => convolver.Upload(scene.Spectrum), 16));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(64, 5, 150, 97, 11)]
|
||||
[InlineData(128, 23, 140, 90, 24)]
|
||||
[InlineData(256, 40, 110, 70, 44)]
|
||||
[InlineData(512, 3, 1100, 560, 8)]
|
||||
[InlineData(512, 63, 600, 300, 64)]
|
||||
public void TheResultStaysWithinTheBoundOfTheExactCorrelationOfEachChannel(int size, int radius, int width, int height, int margin)
|
||||
{
|
||||
var scene = Scene(size, radius, width, height, margin, size + radius);
|
||||
|
||||
var run = Run(HardwareOrDefault(), scene);
|
||||
|
||||
Assert.True(scene.Plan.TileCount > 1 || size == 512);
|
||||
Assert.InRange(scene.WorstRatio(run.Store, ConvolutionBound.GpuOperationError), 0d, 1d);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true, 0f, 0f)]
|
||||
[InlineData(true, 0.8f, 20f)]
|
||||
public void TheLinearLightResultStaysWithinTheBound(bool linear, float threshold, float boost)
|
||||
{
|
||||
var scene = Scene(128, 9, 130, 90, 12, 21, new LightOptions(linear, false, threshold, boost));
|
||||
|
||||
var run = Run(HardwareOrDefault(), scene);
|
||||
|
||||
Assert.InRange(scene.WorstRatio(run.Store, ConvolutionBound.GpuOperationError), 0d, 1d);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheResultMatchesTheCpuResultWithinTheBoundsOfBoth()
|
||||
{
|
||||
var scene = Scene(128, 15, 200, 120, 20, 7);
|
||||
var cpu = new float[scene.RegionLength];
|
||||
var cpuOutput = new byte[scene.RegionLength];
|
||||
using (var convolver = new CpuTileConvolver(2))
|
||||
convolver.Convolve(scene.Source, scene.SourceX, scene.SourceY, scene.SourceWidth, scene.SourceHeight, scene.Spectrum, scene.Plan, cpuOutput, 1f, cpu);
|
||||
|
||||
var run = Run(HardwareOrDefault(), scene);
|
||||
|
||||
var tolerance = ConvolutionBound.ChromaticAbsolute(128, ConvolutionBound.GpuOperationError, 1e4) + ConvolutionBound.ChromaticAbsolute(128, ConvolutionBound.CpuOperationError, 1e4);
|
||||
for (var index = 0; index < cpu.Length; index++)
|
||||
Assert.True(Math.Abs(cpu[index] - run.Store[index]) <= tolerance, $"{index}: {cpu[index]} {run.Store[index]}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EveryMeasurementOfTheCheckPasses()
|
||||
{
|
||||
var scene = Scene(512, 20, 700, 400, 24, 3);
|
||||
|
||||
var run = Run(HardwareOrDefault(), scene);
|
||||
|
||||
var measurements = new ConvolutionMeasurement[GpuTileCheck.MeasurementCount(run.Samples.Length)];
|
||||
GpuTileCheck.Evaluate(run.Report, run.Job, run.Samples, scene.Spectrum.Red.Kernel, scene.Spectrum.Green.Kernel, scene.Spectrum.Blue.Kernel, measurements);
|
||||
Assert.All(measurements, measurement => Assert.True(measurement.Passes, $"{measurement}"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ACheckWithTheWrongKernelOfOneChannelFails()
|
||||
{
|
||||
var scene = Scene(128, 12, 160, 100, 16, 11);
|
||||
var run = Run(HardwareOrDefault(), scene);
|
||||
var measurements = new ConvolutionMeasurement[GpuTileCheck.MeasurementCount(run.Samples.Length)];
|
||||
|
||||
GpuTileCheck.Evaluate(run.Report, run.Job, run.Samples, scene.Spectrum.Red.Kernel, scene.Spectrum.Green.Kernel, scene.Spectrum.Green.Kernel, measurements);
|
||||
|
||||
Assert.Contains(measurements, measurement => measurement.Name == "spot.blue" && !measurement.Passes);
|
||||
Assert.All(measurements.Where(measurement => measurement.Name is "spot.red" or "spot.green" or "spot.alpha"), measurement => Assert.True(measurement.Passes, $"{measurement}"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TwoRunsAgreeBitForBit()
|
||||
{
|
||||
var scene = Scene(128, 9, 300, 170, 16, 5);
|
||||
|
||||
var first = Run(HardwareOrDefault(), scene, 1.5f);
|
||||
var second = Run(HardwareOrDefault(), scene, 1.5f);
|
||||
|
||||
Assert.Equal(first.Output, second.Output);
|
||||
Assert.Equal(first.Store, second.Store);
|
||||
Assert.Equal(first.Report, second.Report);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AMonochromeRunAfterAChromaticOneUsesTheMonochromeSpectrum()
|
||||
{
|
||||
var device = HardwareOrDefault();
|
||||
var chromatic = Scene(128, 9, 150, 100, 16, 5);
|
||||
var single = ConvolutionScene.Create(ConvolutionScene.RandomSource(150, 100, 5, 0.45), 150, 100, 16, 9, 128);
|
||||
using var convolver = new GpuTileConvolver(device);
|
||||
|
||||
_ = Run(device, convolver, chromatic);
|
||||
convolver.Upload(single.Spectrum);
|
||||
var job = convolver.Prepare(single.Plan, single.SourceX, single.SourceY, single.SourceWidth, single.SourceHeight, 1f, [], false);
|
||||
|
||||
Assert.False(job.Chromatic);
|
||||
Assert.Throws<InvalidOperationException>(() => convolver.Prepare(single.Plan, single.SourceX, single.SourceY, single.SourceWidth, single.SourceHeight, 1f, [], false, default, true));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheChromaticCheckAllowsMoreErrorThanTheMonochromeCheckForTheSameReport()
|
||||
{
|
||||
var scene = Scene(128, 12, 160, 100, 16, 11);
|
||||
var run = Run(HardwareOrDefault(), scene);
|
||||
var single = new ConvolutionMeasurement[GpuTileCheck.MeasurementCount(run.Samples.Length)];
|
||||
var chromatic = new ConvolutionMeasurement[single.Length];
|
||||
var kernel = scene.Spectrum.Green.Kernel;
|
||||
|
||||
GpuTileCheck.Evaluate(run.Report, run.Job, run.Samples, kernel, single);
|
||||
GpuTileCheck.Evaluate(run.Report, run.Job, run.Samples, kernel, kernel, kernel, chromatic);
|
||||
|
||||
Assert.Equal(single[0], chromatic[0]);
|
||||
for (var index = 1; index < single.Length; index++)
|
||||
{
|
||||
Assert.Equal(single[index].Name, chromatic[index].Name);
|
||||
Assert.Equal(single[index].Reference, chromatic[index].Reference);
|
||||
Assert.True(chromatic[index].Tolerance > single[index].Tolerance, $"{single[index].Name}: {chromatic[index].Tolerance} {single[index].Tolerance}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
public sealed class ChromaticKernelSpectrumTests
|
||||
{
|
||||
static ChromaticKernelSpectrum Updated(int radius, int size)
|
||||
{
|
||||
var spectrum = new ChromaticKernelSpectrum();
|
||||
spectrum.Update(ChromaticConvolutionScene.Kernel(radius, 1.3, 0.6), ChromaticConvolutionScene.Kernel(radius, 1d, 0.9), ChromaticConvolutionScene.Kernel(radius, 0.7, 1.2), radius, size);
|
||||
return spectrum;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASpectrumThatHasNotBeenUpdatedIsEmpty()
|
||||
{
|
||||
var spectrum = new ChromaticKernelSpectrum();
|
||||
|
||||
Assert.Equal(0, spectrum.Size);
|
||||
Assert.Equal(0, spectrum.Radius);
|
||||
Assert.True(spectrum.HalfSpectrum(ChromaticChannel.Green).IsEmpty);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(3, 64)]
|
||||
[InlineData(23, 128)]
|
||||
[InlineData(63, 512)]
|
||||
public void EveryChannelHoldsItsOwnNormalizedKernel(int radius, int size)
|
||||
{
|
||||
var spectrum = Updated(radius, size);
|
||||
|
||||
Assert.Equal(size, spectrum.Size);
|
||||
Assert.Equal(radius, spectrum.Radius);
|
||||
Assert.Equal(1d, spectrum.Red.Kernel.ToArray().Sum(), 12);
|
||||
Assert.Equal(1d, spectrum.Green.Kernel.ToArray().Sum(), 12);
|
||||
Assert.Equal(1d, spectrum.Blue.Kernel.ToArray().Sum(), 12);
|
||||
Assert.NotEqual(spectrum.Red.Kernel.ToArray(), spectrum.Green.Kernel.ToArray());
|
||||
Assert.NotEqual(spectrum.Blue.Kernel.ToArray(), spectrum.Green.Kernel.ToArray());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(64)]
|
||||
[InlineData(128)]
|
||||
[InlineData(512)]
|
||||
public void TheHalfSpectrumHoldsTheColumnsFromZeroToHalfTheSize(int size)
|
||||
{
|
||||
var spectrum = Updated(3, size);
|
||||
|
||||
Assert.Equal(size / 2 + 1, spectrum.HalfColumns);
|
||||
Assert.Equal(spectrum.HalfColumns * size, spectrum.HalfSpectrum(ChromaticChannel.Red).Length);
|
||||
Assert.True(spectrum.HalfSpectrum(ChromaticChannel.Red).SequenceEqual(spectrum.Red.Spectrum[..(spectrum.HalfColumns * size)]));
|
||||
Assert.True(spectrum.HalfSpectrum(ChromaticChannel.Green).SequenceEqual(spectrum.Green.Spectrum[..(spectrum.HalfColumns * size)]));
|
||||
Assert.True(spectrum.HalfSpectrum(ChromaticChannel.Blue).SequenceEqual(spectrum.Blue.Spectrum[..(spectrum.HalfColumns * size)]));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(64)]
|
||||
[InlineData(128)]
|
||||
[InlineData(512)]
|
||||
public void EveryChannelStoresOnlyTheHalfSpectrumAndItMatchesASingleChannelSpectrum(int size)
|
||||
{
|
||||
var spectrum = Updated(3, size);
|
||||
var kernels = new[] { ChromaticConvolutionScene.Kernel(3, 1.3, 0.6), ChromaticConvolutionScene.Kernel(3, 1d, 0.9), ChromaticConvolutionScene.Kernel(3, 0.7, 1.2) };
|
||||
var channels = new[] { spectrum.Red, spectrum.Green, spectrum.Blue };
|
||||
|
||||
for (var channel = 0; channel < channels.Length; channel++)
|
||||
{
|
||||
var single = new KernelSpectrum();
|
||||
single.Update(kernels[channel], 3, size);
|
||||
|
||||
Assert.Equal(spectrum.HalfColumns * size, channels[channel].Spectrum.Length);
|
||||
Assert.True(channels[channel].Spectrum.SequenceEqual(single.Spectrum[..(spectrum.HalfColumns * size)]));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheHalfSpectraAreCopiedOneChannelAfterAnother()
|
||||
{
|
||||
var spectrum = Updated(5, 128);
|
||||
var length = spectrum.HalfColumns * 128;
|
||||
var copy = new ComputeWeave.Float2[3 * length];
|
||||
|
||||
spectrum.CopyHalfSpectra(copy);
|
||||
|
||||
Assert.True(spectrum.HalfSpectrum(ChromaticChannel.Red).SequenceEqual(copy.AsSpan(0, length)));
|
||||
Assert.True(spectrum.HalfSpectrum(ChromaticChannel.Green).SequenceEqual(copy.AsSpan(length, length)));
|
||||
Assert.True(spectrum.HalfSpectrum(ChromaticChannel.Blue).SequenceEqual(copy.AsSpan(2 * length, length)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CopyingToAShortBufferOrFromAnEmptySpectrumIsRejected()
|
||||
{
|
||||
var spectrum = Updated(5, 64);
|
||||
|
||||
Assert.Throws<ArgumentException>(() => spectrum.CopyHalfSpectra(new ComputeWeave.Float2[3 * spectrum.HalfColumns * 64 - 1]));
|
||||
Assert.Throws<ArgumentException>(() => new ChromaticKernelSpectrum().CopyHalfSpectra(new ComputeWeave.Float2[3 * 64]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnUnknownChannelIsRejected()
|
||||
{
|
||||
var spectrum = Updated(3, 64);
|
||||
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => spectrum.HalfSpectrum((ChromaticChannel)7));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AKernelThatCannotBeNormalizedLeavesTheSpectrumEmpty()
|
||||
{
|
||||
var spectrum = Updated(3, 64);
|
||||
var good = ChromaticConvolutionScene.Kernel(3, 1d, 1d);
|
||||
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => spectrum.Update(good, good, new double[good.Length], 3, 64));
|
||||
|
||||
Assert.Equal(0, spectrum.Size);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
public sealed class ChromaticReferenceTests
|
||||
{
|
||||
static double[] Kernel(int radius, double scale)
|
||||
{
|
||||
var size = radius * 2 + 1;
|
||||
var values = new double[size * size];
|
||||
for (var index = 0; index < values.Length; index++)
|
||||
values[index] = (index + 1d) * scale;
|
||||
var sum = values.Sum();
|
||||
for (var index = 0; index < values.Length; index++)
|
||||
values[index] /= sum;
|
||||
values[0] += scale;
|
||||
return values;
|
||||
}
|
||||
|
||||
static byte[] Image(int width, int height, int x, int y, byte blue, byte green, byte red, byte alpha)
|
||||
{
|
||||
var pixels = new byte[width * height * 4];
|
||||
var offset = (y * width + x) * 4;
|
||||
pixels[offset] = blue;
|
||||
pixels[offset + 1] = green;
|
||||
pixels[offset + 2] = red;
|
||||
pixels[offset + 3] = alpha;
|
||||
return pixels;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EachChannelReadsItsOwnKernelAndTheAlphaReadsTheGreenKernel()
|
||||
{
|
||||
const int radius = 1;
|
||||
var red = Kernel(radius, 1d);
|
||||
var green = Kernel(radius, 2d);
|
||||
var blue = Kernel(radius, 5d);
|
||||
var image = Image(3, 3, 1, 1, 30, 20, 10, 40);
|
||||
var result = new double[4];
|
||||
|
||||
DirectCorrelation.Evaluate(image, 3, 3, red, green, blue, radius, 1, 1, result);
|
||||
|
||||
Assert.Equal(10 / 255d * red[4], result[0], 15);
|
||||
Assert.Equal(20 / 255d * green[4], result[1], 15);
|
||||
Assert.Equal(30 / 255d * blue[4], result[2], 15);
|
||||
Assert.Equal(40 / 255d * green[4], result[3], 15);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IdenticalKernelsGiveTheSingleKernelResult()
|
||||
{
|
||||
const int radius = 2;
|
||||
var kernel = Kernel(radius, 3d);
|
||||
var random = new Random(4);
|
||||
var image = new byte[16 * 16 * 4];
|
||||
random.NextBytes(image);
|
||||
var single = new double[4];
|
||||
var chromatic = new double[4];
|
||||
|
||||
DirectCorrelation.Evaluate(image, 16, 16, kernel, radius, 7, 9, single);
|
||||
DirectCorrelation.Evaluate(image, 16, 16, kernel, kernel, kernel, radius, 7, 9, chromatic);
|
||||
|
||||
Assert.Equal(single, chromatic);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void ANeighborhoodIsReadWithTheKernelOfEachChannel(bool linear)
|
||||
{
|
||||
const int radius = 1;
|
||||
var red = Kernel(radius, 1d);
|
||||
var green = Kernel(radius, 2d);
|
||||
var blue = Kernel(radius, 5d);
|
||||
var random = new Random(8);
|
||||
var neighborhood = new uint[9];
|
||||
for (var index = 0; index < neighborhood.Length; index++)
|
||||
neighborhood[index] = DirectCorrelation.Pack((byte)random.Next(256), (byte)random.Next(256), (byte)random.Next(256), (byte)random.Next(256));
|
||||
var light = new LightOptions(linear, false, 0.9f, 4f);
|
||||
var result = new double[4];
|
||||
|
||||
DirectCorrelation.Evaluate(neighborhood, red, green, blue, in light, result);
|
||||
|
||||
var expected = new double[4];
|
||||
for (var index = 0; index < neighborhood.Length; index++)
|
||||
{
|
||||
var packed = neighborhood[index];
|
||||
var (r, g, b, a) = linear
|
||||
? LightTransform.FromBytes((byte)(packed & 255u), (byte)(packed >> 8 & 255u), (byte)(packed >> 16 & 255u), (byte)(packed >> 24), in light)
|
||||
: ((packed & 255u) / 255f, (packed >> 8 & 255u) / 255f, (packed >> 16 & 255u) / 255f, (packed >> 24) / 255f);
|
||||
expected[0] += r * red[index];
|
||||
expected[1] += g * green[index];
|
||||
expected[2] += b * blue[index];
|
||||
expected[3] += a * green[index];
|
||||
}
|
||||
|
||||
Assert.Equal(expected[0], result[0], 6);
|
||||
Assert.Equal(expected[1], result[1], 6);
|
||||
Assert.Equal(expected[2], result[2], 6);
|
||||
Assert.Equal(expected[3], result[3], 6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void KernelsOfDifferentLengthsAreRejected()
|
||||
{
|
||||
var short1 = Kernel(1, 1d);
|
||||
var long1 = Kernel(2, 1d);
|
||||
|
||||
Assert.Throws<ArgumentException>(() => DirectCorrelation.Evaluate(new byte[36], 3, 3, short1, short1, long1, 1, 1, 1, new double[4]));
|
||||
Assert.Throws<ArgumentException>(() => DirectCorrelation.Evaluate(new uint[9], short1, long1, short1, default(LightOptions), new double[4]));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(64)]
|
||||
[InlineData(128)]
|
||||
[InlineData(512)]
|
||||
public void TheChromaticBoundCoversTheSplittingAndMergingOfChannels(int size)
|
||||
{
|
||||
foreach (var unit in new[] { ConvolutionBound.GpuOperationError, ConvolutionBound.CpuOperationError })
|
||||
{
|
||||
var plain = ConvolutionBound.Relative(size, unit);
|
||||
var chromatic = ConvolutionBound.ChromaticRelative(size, unit);
|
||||
|
||||
Assert.True(chromatic > plain);
|
||||
Assert.True(chromatic < plain + 8d * unit);
|
||||
Assert.True(ConvolutionBound.ChromaticFlushedOperations(size) > ConvolutionBound.FlushedOperations(size));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheChromaticAbsoluteBoundIsTheRelativeBoundOfTheNormPlusTheFlushedOperations()
|
||||
{
|
||||
const double norm = 123.5;
|
||||
var unit = ConvolutionBound.GpuOperationError;
|
||||
|
||||
var expected = ConvolutionBound.ChromaticRelative(128, unit) * norm + ConvolutionBound.ChromaticFlushedOperations(128) * ConvolutionBound.SmallestNormal;
|
||||
|
||||
Assert.Equal(expected, ConvolutionBound.ChromaticAbsolute(128, unit, norm));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => ConvolutionBound.ChromaticAbsolute(128, unit, -1d));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => ConvolutionBound.ChromaticAbsolute(128, unit, double.NaN));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(64, 0.304, 0.170)]
|
||||
[InlineData(128, 0.704, 0.393)]
|
||||
[InlineData(256, 1.598, 0.892)]
|
||||
[InlineData(512, 3.576, 1.997)]
|
||||
public void TheWorstCaseTileOfTheChromaticPathStaysWithinTheDerivedNumberOfLevels(int size, double gpuLevels, double cpuLevels)
|
||||
{
|
||||
var norm = Math.Sqrt(2d * size * size);
|
||||
|
||||
Assert.Equal(gpuLevels, ConvolutionBound.ChromaticRelative(size, ConvolutionBound.GpuOperationError) * norm * 255d, 3);
|
||||
Assert.Equal(cpuLevels, ConvolutionBound.ChromaticRelative(size, ConvolutionBound.CpuOperationError) * norm * 255d, 3);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(64, 20276)]
|
||||
[InlineData(128, 46342)]
|
||||
[InlineData(256, 104268)]
|
||||
[InlineData(512, 231706)]
|
||||
public void TheChromaticPathFlushesTheSplittingAndMergingOperationsToo(int size, int operations)
|
||||
{
|
||||
Assert.Equal(operations, ConvolutionBound.ChromaticFlushedOperations(size));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
public sealed class ComplexLinesTests
|
||||
{
|
||||
static long Distance(ComplexLines lines)
|
||||
=> Unsafe.ByteOffset(ref MemoryMarshal.GetReference(lines.Real), ref MemoryMarshal.GetReference(lines.Imaginary));
|
||||
|
||||
[Theory]
|
||||
[InlineData(128)]
|
||||
[InlineData(512)]
|
||||
[InlineData(31 * 128)]
|
||||
[InlineData(81 * 256)]
|
||||
[InlineData(81 * 512)]
|
||||
[InlineData(256 * 256)]
|
||||
[InlineData(512 * 512)]
|
||||
public void TheImaginaryPartStartsAtAFixedOffsetWithinTheFourKilobytePeriod(int count)
|
||||
{
|
||||
var lines = new ComplexLines();
|
||||
|
||||
lines.Ensure(count);
|
||||
|
||||
Assert.Equal(1536L, Distance(lines) % 4096);
|
||||
Assert.True(Distance(lines) >= (count + 64L) * sizeof(double), $"{Distance(lines)}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheStaggerIsThreeEighthsOfAFourKilobytePage()
|
||||
{
|
||||
Assert.Equal(4096, ComplexLines.PageBytes);
|
||||
Assert.Equal(1536, ComplexLines.StaggerBytes);
|
||||
Assert.Equal(0, ComplexLines.StaggerBytes % sizeof(double));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheTwoPartsDoNotOverlap()
|
||||
{
|
||||
var lines = new ComplexLines();
|
||||
lines.Ensure(1000);
|
||||
|
||||
lines.Real.Fill(1d);
|
||||
lines.Imaginary.Fill(2d);
|
||||
|
||||
Assert.All(lines.Real.ToArray(), value => Assert.Equal(1d, value));
|
||||
Assert.All(lines.Imaginary.ToArray(), value => Assert.Equal(2d, value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ABufferThatIsLargeEnoughIsKeptAndAGrownOneKeepsTheOffset()
|
||||
{
|
||||
var lines = new ComplexLines();
|
||||
lines.Ensure(100);
|
||||
|
||||
lines.Ensure(50);
|
||||
|
||||
Assert.Equal(100, lines.Real.Length);
|
||||
Assert.Equal(100, lines.Imaginary.Length);
|
||||
|
||||
lines.Ensure(4096);
|
||||
|
||||
Assert.Equal(4096, lines.Real.Length);
|
||||
Assert.Equal(4096, lines.Imaginary.Length);
|
||||
Assert.Equal(1536L, Distance(lines) % 4096);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnUnusedBufferIsEmpty()
|
||||
{
|
||||
var lines = new ComplexLines();
|
||||
|
||||
Assert.True(lines.Real.IsEmpty);
|
||||
Assert.True(lines.Imaginary.IsEmpty);
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,11 @@ namespace SpectralConvolution.Tests;
|
||||
internal sealed class ConvolutionScene
|
||||
{
|
||||
(double RedGreen, double BlueAlpha)[]? tileNorms;
|
||||
float[]? transformed;
|
||||
|
||||
ConvolutionScene(byte[] source, int sourceX, int sourceY, int sourceWidth, int sourceHeight, KernelSpectrum spectrum, TilePlan plan)
|
||||
ConvolutionScene(byte[] source, int sourceX, int sourceY, int sourceWidth, int sourceHeight, KernelSpectrum spectrum, TilePlan plan, LightOptions light)
|
||||
{
|
||||
Light = light;
|
||||
Source = source;
|
||||
SourceX = sourceX;
|
||||
SourceY = sourceY;
|
||||
@@ -15,6 +17,8 @@ internal sealed class ConvolutionScene
|
||||
Plan = plan;
|
||||
}
|
||||
|
||||
public LightOptions Light { get; }
|
||||
|
||||
public byte[] Source { get; }
|
||||
|
||||
public int SourceX { get; }
|
||||
@@ -73,23 +77,106 @@ internal sealed class ConvolutionScene
|
||||
return pixels;
|
||||
}
|
||||
|
||||
public static ConvolutionScene Create(byte[] source, int sourceWidth, int sourceHeight, int margin, int radius, int size)
|
||||
public static ConvolutionScene Create(byte[] source, int sourceWidth, int sourceHeight, int margin, int radius, int size, LightOptions light = default)
|
||||
{
|
||||
var spectrum = new KernelSpectrum();
|
||||
spectrum.Update(AsymmetricKernel(radius), radius, size);
|
||||
var plan = TilePlan.Create(size, radius, 0, 0, sourceWidth + margin * 2, sourceHeight + margin * 2);
|
||||
return new ConvolutionScene(source, margin, margin, sourceWidth, sourceHeight, spectrum, plan);
|
||||
return new ConvolutionScene(source, margin, margin, sourceWidth, sourceHeight, spectrum, plan, light);
|
||||
}
|
||||
|
||||
public static ConvolutionScene CreateShifted(
|
||||
byte[] source, int sourceX, int sourceY, int sourceWidth, int sourceHeight,
|
||||
int regionX, int regionY, int regionWidth, int regionHeight, int radius, int size, LightOptions light = default)
|
||||
{
|
||||
var spectrum = new KernelSpectrum();
|
||||
spectrum.Update(AsymmetricKernel(radius), radius, size);
|
||||
var plan = TilePlan.Create(size, radius, regionX, regionY, regionWidth, regionHeight);
|
||||
return new ConvolutionScene(source, sourceX, sourceY, sourceWidth, sourceHeight, spectrum, plan, light);
|
||||
}
|
||||
|
||||
public void Reference(int x, int y, Span<double> result)
|
||||
=> DirectCorrelation.Evaluate(Source, SourceWidth, SourceHeight, Spectrum.Kernel, Spectrum.Radius, x - SourceX, y - SourceY, result);
|
||||
{
|
||||
if (!Light.Linear)
|
||||
{
|
||||
DirectCorrelation.Evaluate(Source, SourceWidth, SourceHeight, Spectrum.Kernel, Spectrum.Radius, x - SourceX, y - SourceY, result);
|
||||
return;
|
||||
}
|
||||
|
||||
var values = Transformed();
|
||||
var radius = Spectrum.Radius;
|
||||
var kernelSize = radius * 2 + 1;
|
||||
var kernel = Spectrum.Kernel;
|
||||
result[..4].Clear();
|
||||
for (var offsetY = -radius; offsetY <= radius; offsetY++)
|
||||
{
|
||||
var sourceY = y - SourceY + offsetY;
|
||||
if (sourceY < 0 || sourceY >= SourceHeight)
|
||||
continue;
|
||||
for (var offsetX = -radius; offsetX <= radius; offsetX++)
|
||||
{
|
||||
var sourceX = x - SourceX + offsetX;
|
||||
if (sourceX < 0 || sourceX >= SourceWidth)
|
||||
continue;
|
||||
var weight = kernel[(offsetY + radius) * kernelSize + offsetX + radius];
|
||||
var offset = (sourceY * SourceWidth + sourceX) * 4;
|
||||
for (var channel = 0; channel < 4; channel++)
|
||||
result[channel] += values[offset + channel] * weight;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public (double RedGreen, double BlueAlpha) Norms(int x, int y)
|
||||
{
|
||||
tileNorms ??= [.. Enumerable.Range(0, Plan.TileCount).Select(tile => TileInput.Norms(Source, SourceX, SourceY, SourceWidth, SourceHeight, Plan, tile))];
|
||||
tileNorms ??= [.. Enumerable.Range(0, Plan.TileCount).Select(TileNorms)];
|
||||
return tileNorms[Plan.TileAt(x, y)];
|
||||
}
|
||||
|
||||
public float[] Transformed()
|
||||
{
|
||||
if (transformed is null)
|
||||
{
|
||||
var values = new float[SourceWidth * SourceHeight * 4];
|
||||
for (var index = 0; index < SourceWidth * SourceHeight; index++)
|
||||
{
|
||||
var (red, green, blue, alpha) = LightTransform.FromBytes(Source[index * 4 + 2], Source[index * 4 + 1], Source[index * 4], Source[index * 4 + 3], Light);
|
||||
values[index * 4] = red;
|
||||
values[index * 4 + 1] = green;
|
||||
values[index * 4 + 2] = blue;
|
||||
values[index * 4 + 3] = alpha;
|
||||
}
|
||||
|
||||
transformed = values;
|
||||
}
|
||||
|
||||
return transformed;
|
||||
}
|
||||
|
||||
(double RedGreen, double BlueAlpha) TileNorms(int tile)
|
||||
{
|
||||
if (!Light.Linear)
|
||||
return TileInput.Norms(Source, SourceX, SourceY, SourceWidth, SourceHeight, Plan, tile);
|
||||
|
||||
var values = Transformed();
|
||||
var left = Plan.OriginX(tile) - Plan.Radius;
|
||||
var top = Plan.OriginY(tile) - Plan.Radius;
|
||||
var redGreen = 0d;
|
||||
var blueAlpha = 0d;
|
||||
var lastY = Math.Min(top + Plan.Size, SourceY + SourceHeight);
|
||||
var lastX = Math.Min(left + Plan.Size, SourceX + SourceWidth);
|
||||
for (var y = Math.Max(top, SourceY); y < lastY; y++)
|
||||
{
|
||||
for (var x = Math.Max(left, SourceX); x < lastX; x++)
|
||||
{
|
||||
var offset = ((y - SourceY) * SourceWidth + x - SourceX) * 4;
|
||||
redGreen += (double)values[offset] * values[offset] + (double)values[offset + 1] * values[offset + 1];
|
||||
blueAlpha += (double)values[offset + 2] * values[offset + 2] + (double)values[offset + 3] * values[offset + 3];
|
||||
}
|
||||
}
|
||||
|
||||
return (Math.Sqrt(redGreen), Math.Sqrt(blueAlpha));
|
||||
}
|
||||
|
||||
public double WorstRatio(ReadOnlySpan<float> convolved, double operationError)
|
||||
{
|
||||
var reference = new double[4];
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
using ComputeWeave;
|
||||
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
public sealed class CpuFftTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(1)]
|
||||
[InlineData(2)]
|
||||
[InlineData(3)]
|
||||
[InlineData(4)]
|
||||
[InlineData(5)]
|
||||
[InlineData(6)]
|
||||
[InlineData(7)]
|
||||
[InlineData(8)]
|
||||
[InlineData(9)]
|
||||
public void TheVectorButterfliesMatchTheScalarOnesBitForBit(int log2)
|
||||
{
|
||||
var size = 1 << log2;
|
||||
var twiddles = new Float2[Math.Max(size / 2, 1)];
|
||||
for (var index = 0; index < twiddles.Length; index++)
|
||||
{
|
||||
var angle = -2d * Math.PI * index / size;
|
||||
twiddles[index] = new Float2((float)Math.Cos(angle), (float)Math.Sin(angle));
|
||||
}
|
||||
|
||||
var random = new Random(log2 * 101);
|
||||
foreach (var direction in new[] { 1f, -1f })
|
||||
{
|
||||
var expected = new float[size * 4];
|
||||
for (var index = 0; index < expected.Length; index++)
|
||||
{
|
||||
expected[index] = random.Next(7) switch
|
||||
{
|
||||
0 => 0f,
|
||||
1 => -0f,
|
||||
2 => (float)(random.NextDouble() * 1e-30),
|
||||
3 => (float)(random.NextDouble() * 1e6 - 5e5),
|
||||
_ => (float)(random.NextDouble() * 2 - 1),
|
||||
};
|
||||
}
|
||||
|
||||
var actual = (float[])expected.Clone();
|
||||
|
||||
var narrow = (float[])expected.Clone();
|
||||
|
||||
CpuFft.ButterfliesScalar(expected, log2, twiddles, direction);
|
||||
CpuFft.Butterflies(actual, log2, twiddles, direction);
|
||||
CpuFft.Butterflies(narrow, log2, twiddles, direction, allowWide: false);
|
||||
|
||||
Assert.Equal(expected.Select(BitConverter.SingleToInt32Bits), actual.Select(BitConverter.SingleToInt32Bits));
|
||||
Assert.Equal(expected.Select(BitConverter.SingleToInt32Bits), narrow.Select(BitConverter.SingleToInt32Bits));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheButterfliesRefuseALineThatIsTooShort()
|
||||
{
|
||||
var twiddles = new Float2[4];
|
||||
|
||||
Assert.Throws<ArgumentException>(() => CpuFft.Butterflies(new float[8 * 4 - 1], 3, twiddles, 1f));
|
||||
Assert.Throws<ArgumentException>(() => CpuFft.Butterflies(new float[8 * 4], 3, twiddles.AsSpan(0, 3), 1f));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1, new[] { 0, 1 })]
|
||||
[InlineData(2, new[] { 0, 2, 1, 3 })]
|
||||
[InlineData(3, new[] { 0, 4, 2, 6, 1, 5, 3, 7 })]
|
||||
public void TheReversalListsTheIndicesInBitReversedOrder(int log2, int[] expected)
|
||||
{
|
||||
var order = new int[1 << log2];
|
||||
|
||||
CpuFft.FillReversal(order, log2);
|
||||
|
||||
Assert.Equal(expected, order);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(6)]
|
||||
[InlineData(9)]
|
||||
public void ReversingTwiceReturnsTheSameIndex(int log2)
|
||||
{
|
||||
var order = new int[1 << log2];
|
||||
|
||||
CpuFft.FillReversal(order, log2);
|
||||
|
||||
for (var index = 0; index < order.Length; index++)
|
||||
Assert.Equal(index, order[order[index]]);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
using ComputeWeave;
|
||||
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
public sealed class CpuTileConvolverTests
|
||||
@@ -61,10 +63,10 @@ public sealed class CpuTileConvolverTests
|
||||
|
||||
for (var index = 0; index < output.Length; index += 4)
|
||||
{
|
||||
Assert.Equal(CpuTileConvolver.ToUnorm(convolved[index + 2] * 2.5f), output[index]);
|
||||
Assert.Equal(CpuTileConvolver.ToUnorm(convolved[index + 1] * 2.5f), output[index + 1]);
|
||||
Assert.Equal(CpuTileConvolver.ToUnorm(convolved[index] * 2.5f), output[index + 2]);
|
||||
Assert.Equal(CpuTileConvolver.ToUnorm(convolved[index + 3] * 2.5f), output[index + 3]);
|
||||
Assert.Equal(CpuPixels.ToUnorm(convolved[index + 2] * 2.5f), output[index]);
|
||||
Assert.Equal(CpuPixels.ToUnorm(convolved[index + 1] * 2.5f), output[index + 1]);
|
||||
Assert.Equal(CpuPixels.ToUnorm(convolved[index] * 2.5f), output[index + 2]);
|
||||
Assert.Equal(CpuPixels.ToUnorm(convolved[index + 3] * 2.5f), output[index + 3]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,8 +136,8 @@ public sealed class CpuTileConvolverTests
|
||||
Assert.Equal(single, several);
|
||||
for (var pixel = 0; pixel < pixels; pixel++)
|
||||
{
|
||||
Assert.Equal(CpuTileConvolver.ToUnorm(stored[pixel * 4 + 2] * 1.3f), single[pixel * 4]);
|
||||
Assert.Equal(CpuTileConvolver.ToUnorm(stored[pixel * 4] * 1.3f), single[pixel * 4 + 2]);
|
||||
Assert.Equal(CpuPixels.ToUnorm(stored[pixel * 4 + 2] * 1.3f), single[pixel * 4]);
|
||||
Assert.Equal(CpuPixels.ToUnorm(stored[pixel * 4] * 1.3f), single[pixel * 4 + 2]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -176,7 +178,7 @@ public sealed class CpuTileConvolverTests
|
||||
[InlineData(float.PositiveInfinity, 255)]
|
||||
public void ConversionFollowsTheDirect3DRule(float value, byte expected)
|
||||
{
|
||||
Assert.Equal(expected, CpuTileConvolver.ToUnorm(value));
|
||||
Assert.Equal(expected, CpuPixels.ToUnorm(value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -237,8 +239,103 @@ public sealed class CpuTileConvolverTests
|
||||
Assert.Equal(3, CpuTileConvolver.ActiveThreads(3, size));
|
||||
}
|
||||
|
||||
static (byte[] Output, float[] Convolved) RunShared(ConvolutionScene scene, float gain)
|
||||
{
|
||||
var output = new byte[scene.RegionLength];
|
||||
var convolved = new float[scene.RegionLength];
|
||||
using var convolver = CpuTileConvolver.CreateShared();
|
||||
convolver.Convolve(scene.Source, scene.SourceX, scene.SourceY, scene.SourceWidth, scene.SourceHeight, scene.Spectrum, scene.Plan, output, gain, convolved);
|
||||
return (output, convolved);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OnlyTheThreadsThatComputeKeepAWorkingAreaOfTheCurrentSize()
|
||||
public void ASharedConvolverGivesTheResultOfADedicatedOne()
|
||||
{
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.RandomSource(300, 170, 5, 0.6), 300, 170, 16, 9, 64);
|
||||
|
||||
var dedicated = Run(scene, Environment.ProcessorCount, 1.75f);
|
||||
var shared = RunShared(scene, 1.75f);
|
||||
|
||||
Assert.Equal(dedicated.Output, shared.Output);
|
||||
Assert.Equal(dedicated.Convolved, shared.Convolved);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SharedConvolversShareOneWorkingArea()
|
||||
{
|
||||
static void Convolve(CpuTileConvolver convolver)
|
||||
{
|
||||
var spectrum = new KernelSpectrum();
|
||||
spectrum.Update(ConvolutionScene.AsymmetricKernel(24), 24, 512);
|
||||
var plan = TilePlan.Create(512, 24, 0, 0, 2000, 2000);
|
||||
convolver.Convolve(ConvolutionScene.Uniform(16, 16, 200), 40, 40, 16, 16, spectrum, plan, new byte[plan.RegionWidth * plan.RegionHeight * 4], 1f, null);
|
||||
}
|
||||
|
||||
using var first = CpuTileConvolver.CreateShared();
|
||||
using var second = CpuTileConvolver.CreateShared();
|
||||
|
||||
Convolve(first);
|
||||
var bytes = first.WorkingBytes;
|
||||
Assert.Equal(Environment.ProcessorCount, first.Threads);
|
||||
Assert.True(second.WorkingBytes >= bytes);
|
||||
Convolve(second);
|
||||
|
||||
var active = CpuTileConvolver.ActiveThreads(first.Threads, 512);
|
||||
var tilesAndLines = ((long)512 * 512 * 4 + 512 * 4 * 2) * sizeof(float);
|
||||
var withChromaticLines = tilesAndLines + 512L * 4 * 2 * sizeof(float);
|
||||
Assert.InRange(bytes, active * tilesAndLines, active * withChromaticLines);
|
||||
Assert.Equal(bytes, first.WorkingBytes);
|
||||
Assert.Equal(bytes, second.WorkingBytes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DisposingASharedConvolverLeavesTheSharedThreadsToTheOthers()
|
||||
{
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.RandomSource(120, 80, 3, 0.5), 120, 80, 8, 5, 64);
|
||||
var expected = Run(scene, 2, 1f);
|
||||
var gone = CpuTileConvolver.CreateShared();
|
||||
gone.Dispose();
|
||||
|
||||
var survivor = RunShared(scene, 1f);
|
||||
|
||||
Assert.Equal(expected.Output, survivor.Output);
|
||||
Assert.Throws<ObjectDisposedException>(() => gone.Convolve(scene.Source, scene.SourceX, scene.SourceY, scene.SourceWidth, scene.SourceHeight, scene.Spectrum, scene.Plan, new byte[scene.RegionLength], 1f, null));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SharedConvolversUsedFromSeveralThreadsEachGetTheirOwnResult()
|
||||
{
|
||||
var scenes = new[]
|
||||
{
|
||||
ConvolutionScene.Create(ConvolutionScene.RandomSource(200, 130, 11, 0.5), 200, 130, 12, 9, 64),
|
||||
ConvolutionScene.Create(ConvolutionScene.RandomSource(150, 160, 12, 0.6), 150, 160, 30, 23, 128),
|
||||
ConvolutionScene.Create(ConvolutionScene.RandomSource(90, 70, 13, 0.7), 90, 70, 40, 31, 512),
|
||||
};
|
||||
var expected = scenes.Select(scene => Run(scene, 2, 1.25f)).ToArray();
|
||||
var failures = new List<string>();
|
||||
|
||||
var threads = scenes.Select((scene, index) => new Thread(() =>
|
||||
{
|
||||
for (var round = 0; round < 6; round++)
|
||||
{
|
||||
var actual = RunShared(scene, 1.25f);
|
||||
if (!actual.Output.AsSpan().SequenceEqual(expected[index].Output) || !actual.Convolved.AsSpan().SequenceEqual(expected[index].Convolved))
|
||||
{
|
||||
lock (failures)
|
||||
failures.Add($"scene {index} round {round}");
|
||||
}
|
||||
}
|
||||
})).ToArray();
|
||||
foreach (var thread in threads)
|
||||
thread.Start();
|
||||
foreach (var thread in threads)
|
||||
thread.Join();
|
||||
|
||||
Assert.Empty(failures);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OnlyTheThreadsThatComputeKeepAWorkingArea()
|
||||
{
|
||||
static long PerThread(int size) => ((long)size * size * 4 + size * 4 * 2) * sizeof(float);
|
||||
static void Convolve(CpuTileConvolver convolver, int size, int radius, int regionSide)
|
||||
@@ -258,8 +355,291 @@ public sealed class CpuTileConvolverTests
|
||||
|
||||
Convolve(convolver, 512, 24, 2000);
|
||||
Assert.Equal(16 * PerThread(512), convolver.WorkingBytes);
|
||||
}
|
||||
|
||||
Convolve(convolver, 128, 3, 610);
|
||||
Assert.Equal(24 * PerThread(128), convolver.WorkingBytes);
|
||||
static (byte[] Output, float[] Convolved) RunLight(ConvolutionScene scene, int threads, float gain)
|
||||
{
|
||||
var output = new byte[scene.RegionLength];
|
||||
var convolved = new float[scene.RegionLength];
|
||||
using var convolver = new CpuTileConvolver(threads);
|
||||
convolver.Convolve(scene.Source, scene.SourceX, scene.SourceY, scene.SourceWidth, scene.SourceHeight, scene.Spectrum, scene.Plan, output, gain, convolved, scene.Light);
|
||||
return (output, convolved);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(64, 5, 150, 97, 11, 0f, 0f)]
|
||||
[InlineData(128, 23, 140, 90, 24, 0.9f, 20f)]
|
||||
[InlineData(64, 0, 70, 70, 3, 0.5f, 1000f)]
|
||||
public void ALinearLightConvolutionStaysWithinTheBoundOfTheExactCorrelation(int size, int radius, int width, int height, int margin, float threshold, float boost)
|
||||
{
|
||||
var light = new LightOptions(true, false, threshold, boost);
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.RandomSource(width, height, size + radius, 0.4), width, height, margin, radius, size, light);
|
||||
|
||||
var (_, convolved) = RunLight(scene, 3, 1f);
|
||||
|
||||
Assert.True(scene.Plan.TileCount > 1);
|
||||
Assert.InRange(scene.WorstRatio(convolved, ConvolutionBound.CpuOperationError), 0d, 1d);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false, 1f)]
|
||||
[InlineData(true, 1f)]
|
||||
[InlineData(true, 2.5f)]
|
||||
public void TheLinearOutputIsTheTransformOfTheConvolution(bool dither, float gain)
|
||||
{
|
||||
var light = new LightOptions(true, dither, 0.8f, 8f);
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.RandomSource(90, 60, 9, 0.7), 90, 60, 8, 4, 64, light);
|
||||
|
||||
var (output, convolved) = RunLight(scene, 2, gain);
|
||||
|
||||
for (var y = 0; y < scene.Plan.RegionHeight; y++)
|
||||
{
|
||||
for (var x = 0; x < scene.Plan.RegionWidth; x++)
|
||||
{
|
||||
var index = (y * scene.Plan.RegionWidth + x) * 4;
|
||||
var expected = LightTransform.ToBytes(convolved[index], convolved[index + 1], convolved[index + 2], convolved[index + 3], gain, light, scene.Plan.RegionX + x, scene.Plan.RegionY + y);
|
||||
Assert.Equal((expected.Blue, expected.Green, expected.Red, expected.Alpha), (output[index], output[index + 1], output[index + 2], output[index + 3]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false, false, 1f)]
|
||||
[InlineData(true, false, 2.75f)]
|
||||
[InlineData(true, true, 0.3f)]
|
||||
[InlineData(false, true, 1.5f)]
|
||||
public void RenderingTheStoreMatchesTheLightConvolutionBitForBit(bool linear, bool dither, float gain)
|
||||
{
|
||||
var light = new LightOptions(linear, dither, 0.85f, linear ? 12f : 0f);
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.RandomSource(130, 90, 13, 0.6), 130, 90, 8, 4, 64, light);
|
||||
var (expected, _) = RunLight(scene, 3, gain);
|
||||
var (_, stored) = RunLight(scene, 3, 1f);
|
||||
var output = new byte[scene.RegionLength];
|
||||
using var convolver = new CpuTileConvolver(3);
|
||||
|
||||
convolver.RenderStored(stored, scene.Plan.RegionWidth * scene.Plan.RegionHeight, gain, output, light, scene.Plan.RegionWidth, scene.Plan.RegionX, scene.Plan.RegionY);
|
||||
|
||||
Assert.Equal(expected, output);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheLinearResultDoesNotDependOnTheNumberOfThreads()
|
||||
{
|
||||
var light = new LightOptions(true, true, 0.9f, 30f);
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.RandomSource(300, 170, 5, 0.6), 300, 170, 16, 9, 64, light);
|
||||
|
||||
var single = RunLight(scene, 1, 1.75f);
|
||||
var many = RunLight(scene, 16, 1.75f);
|
||||
|
||||
Assert.Equal(single.Output, many.Output);
|
||||
Assert.Equal(single.Convolved, many.Convolved);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnOpaqueWhiteSceneStaysWhiteInLinearLight()
|
||||
{
|
||||
var light = new LightOptions(true, true, 0f, 0f);
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.Uniform(120, 120, 255), 120, 120, 8, 7, 64, light);
|
||||
|
||||
var (output, convolved) = RunLight(scene, 2, 1f);
|
||||
|
||||
Assert.InRange(scene.WorstRatio(convolved, ConvolutionBound.CpuOperationError), 0d, 1d);
|
||||
var center = ((scene.Plan.RegionHeight / 2) * scene.Plan.RegionWidth + scene.Plan.RegionWidth / 2) * 4;
|
||||
Assert.Equal([255, 255, 255, 255], output.AsSpan(center, 4).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ABrightPointSpreadsFartherWithHighlights()
|
||||
{
|
||||
var pixels = new byte[61 * 61 * 4];
|
||||
var center = (30 * 61 + 30) * 4;
|
||||
pixels[center] = 255;
|
||||
pixels[center + 1] = 255;
|
||||
pixels[center + 2] = 255;
|
||||
pixels[center + 3] = 255;
|
||||
var plain = new LightOptions(true, false, 0f, 0f);
|
||||
var boosted = new LightOptions(true, false, 0.9f, 400f);
|
||||
var spectrum = new KernelSpectrum();
|
||||
spectrum.Update(ConvolutionScene.AsymmetricKernel(20), 20, 128);
|
||||
var plan = TilePlan.Create(128, 20, 0, 0, 101, 101);
|
||||
using var convolver = new CpuTileConvolver(2);
|
||||
var plainOutput = new byte[101 * 101 * 4];
|
||||
var boostedOutput = new byte[101 * 101 * 4];
|
||||
|
||||
convolver.Convolve(pixels, 20, 20, 61, 61, spectrum, plan, plainOutput, 1f, null, plain);
|
||||
convolver.Convolve(pixels, 20, 20, 61, 61, spectrum, plan, boostedOutput, 1f, null, boosted);
|
||||
|
||||
var plainLit = plainOutput.Where((value, index) => index % 4 == 1 && value > 0).Count();
|
||||
var boostedLit = boostedOutput.Where((value, index) => index % 4 == 1 && value > 0).Count();
|
||||
Assert.True(boostedLit > plainLit * 2, $"{plainLit} {boostedLit}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ARegionWithDitheringNeedsAWidthToRenderTheStore()
|
||||
{
|
||||
using var convolver = new CpuTileConvolver(1);
|
||||
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => convolver.RenderStored(new float[8], 2, 1f, new byte[8], new LightOptions(false, true, 0f, 0f)));
|
||||
convolver.RenderStored(new float[8], 2, 1f, new byte[8], new LightOptions(false, true, 0f, 0f), 2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InvalidLightOptionsAreRejected()
|
||||
{
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.RandomSource(40, 40, 1, 0.5), 40, 40, 4, 2, 64);
|
||||
using var convolver = new CpuTileConvolver(1);
|
||||
var output = new byte[scene.RegionLength];
|
||||
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => convolver.Convolve(
|
||||
scene.Source, scene.SourceX, scene.SourceY, scene.SourceWidth, scene.SourceHeight, scene.Spectrum, scene.Plan, output, 1f, null, new LightOptions(true, false, 2f, 5f)));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => convolver.RenderStored(new float[8], 2, 1f, output, new LightOptions(true, false, 0.5f, 5000f)));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void ADitheredOpaqueWhiteSceneNeverDropsToBlackAnywhere(bool linear)
|
||||
{
|
||||
var light = new LightOptions(linear, true, 0f, 0f);
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.Uniform(1100, 700, 255), 1100, 700, 8, 3, 512, light);
|
||||
|
||||
var (output, _) = RunLight(scene, 4, 1f);
|
||||
|
||||
var wrong = 0;
|
||||
for (var y = 8 + 4; y < 8 + 700 - 4; y++)
|
||||
{
|
||||
for (var x = 8 + 4; x < 8 + 1100 - 4; x++)
|
||||
{
|
||||
var index = (y * scene.Plan.RegionWidth + x) * 4;
|
||||
if (output[index] < 250 || output[index + 1] < 250 || output[index + 2] < 250 || output[index + 3] < 250)
|
||||
wrong++;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.Equal(0, wrong);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1f)]
|
||||
[InlineData(0f)]
|
||||
[InlineData(1.75f)]
|
||||
[InlineData(400f)]
|
||||
public void TheStoredValuesBecomeBytesLikeTheScalarConversion(float gain)
|
||||
{
|
||||
float[] edges =
|
||||
[
|
||||
0f, -0f, 1e-12f, 0.5f / 255f, 0.5f / 255f + 1e-7f, 1f / 255f, 127.5f / 255f, 254.5f / 255f, 254.5f / 255f + 1e-7f,
|
||||
0.999f, 1f, 1.0000001f, 2f, 1e9f, -1e-12f, -0.25f, -1e9f, float.NaN, float.PositiveInfinity, float.NegativeInfinity,
|
||||
float.Epsilon, float.MaxValue, float.MinValue,
|
||||
];
|
||||
var pixels = edges.Length;
|
||||
var stored = new float[pixels * 4];
|
||||
for (var pixel = 0; pixel < pixels; pixel++)
|
||||
{
|
||||
for (var channel = 0; channel < 4; channel++)
|
||||
stored[pixel * 4 + channel] = edges[(pixel + channel * 5) % edges.Length];
|
||||
}
|
||||
|
||||
var output = new byte[stored.Length];
|
||||
using var convolver = new CpuTileConvolver(2);
|
||||
|
||||
convolver.RenderStored(stored, pixels, gain, output);
|
||||
|
||||
for (var pixel = 0; pixel < pixels; pixel++)
|
||||
{
|
||||
Assert.Equal(CpuPixels.ToUnorm(stored[pixel * 4 + 2] * gain), output[pixel * 4]);
|
||||
Assert.Equal(CpuPixels.ToUnorm(stored[pixel * 4 + 1] * gain), output[pixel * 4 + 1]);
|
||||
Assert.Equal(CpuPixels.ToUnorm(stored[pixel * 4] * gain), output[pixel * 4 + 2]);
|
||||
Assert.Equal(CpuPixels.ToUnorm(stored[pixel * 4 + 3] * gain), output[pixel * 4 + 3]);
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false, 1f)]
|
||||
[InlineData(true, 1f)]
|
||||
[InlineData(true, 1.8f)]
|
||||
[InlineData(false, 2.5f)]
|
||||
public void ADitheredTranslucentSceneKeepsEveryColorBelowItsOpacity(bool linear, float gain)
|
||||
{
|
||||
var light = new LightOptions(linear, true, 0f, 0f);
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.Uniform(240, 160, 128), 240, 160, 8, 3, 64, light);
|
||||
|
||||
var (output, _) = RunLight(scene, 3, gain);
|
||||
|
||||
var exceeding = 0;
|
||||
var translucent = 0;
|
||||
for (var index = 0; index < output.Length; index += 4)
|
||||
{
|
||||
if (output[index + 3] is > 0 and < 255)
|
||||
translucent++;
|
||||
if (output[index] > output[index + 3] || output[index + 1] > output[index + 3] || output[index + 2] > output[index + 3])
|
||||
exceeding++;
|
||||
}
|
||||
|
||||
Assert.True(translucent > 1000, $"{translucent}");
|
||||
Assert.Equal(0, exceeding);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true, true, 1.3f)]
|
||||
[InlineData(false, true, 2f)]
|
||||
[InlineData(true, false, 0.8f)]
|
||||
public void RenderingTheStoreMatchesTheLightConvolutionForARegionAwayFromTheOrigin(bool linear, bool dither, float gain)
|
||||
{
|
||||
var light = new LightOptions(linear, dither, 0.85f, linear ? 12f : 0f);
|
||||
var source = ConvolutionScene.RandomSource(120, 80, 78, 0.5);
|
||||
var scene = ConvolutionScene.CreateShifted(source, 43, 29, 120, 80, 37, 23, 132, 92, 4, 64, light);
|
||||
var plan = scene.Plan;
|
||||
var (expected, _) = RunLight(scene, 3, gain);
|
||||
var (_, stored) = RunLight(scene, 3, 1f);
|
||||
var output = new byte[scene.RegionLength];
|
||||
using var convolver = new CpuTileConvolver(3);
|
||||
|
||||
convolver.RenderStored(stored, plan.RegionWidth * plan.RegionHeight, gain, output, light, plan.RegionWidth, plan.RegionX, plan.RegionY);
|
||||
|
||||
Assert.Equal(expected, output);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true, 1f)]
|
||||
[InlineData(false, 1f)]
|
||||
public void ADitheredRegionAwayFromTheOriginUsesTheCanvasPosition(bool linear, float gain)
|
||||
{
|
||||
var light = new LightOptions(linear, true, 0f, 0f);
|
||||
var source = ConvolutionScene.RandomSource(120, 80, 79, 0.5);
|
||||
var scene = ConvolutionScene.CreateShifted(source, 43, 29, 120, 80, 37, 23, 132, 92, 4, 64, light);
|
||||
var plan = scene.Plan;
|
||||
var (output, convolved) = RunLight(scene, 3, gain);
|
||||
|
||||
for (var y = 0; y < plan.RegionHeight; y += 3)
|
||||
{
|
||||
for (var x = 0; x < plan.RegionWidth; x += 2)
|
||||
{
|
||||
var index = (y * plan.RegionWidth + x) * 4;
|
||||
var expected = LightTransform.ToBytes(convolved[index], convolved[index + 1], convolved[index + 2], convolved[index + 3], gain, light, plan.RegionX + x, plan.RegionY + y);
|
||||
Assert.Equal((expected.Blue, expected.Green, expected.Red, expected.Alpha), (output[index], output[index + 1], output[index + 2], output[index + 3]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public void RenderingASeveralChunkStoreAwayFromTheOriginKeepsEveryPosition(bool linear)
|
||||
{
|
||||
var light = new LightOptions(linear, true, 0.85f, linear ? 12f : 0f);
|
||||
var source = ConvolutionScene.RandomSource(100, 60, 80, 0.5);
|
||||
var scene = ConvolutionScene.CreateShifted(source, 103, 59, 100, 60, 97, 53, 313, 207, 4, 64, light);
|
||||
var plan = scene.Plan;
|
||||
Assert.True(plan.RegionWidth * plan.RegionHeight > CpuTileConvolver.StoredChunkPixels * 3);
|
||||
Assert.NotEqual(0, CpuTileConvolver.StoredChunkPixels % plan.RegionWidth);
|
||||
var (expected, _) = RunLight(scene, 3, 1.2f);
|
||||
var (_, stored) = RunLight(scene, 3, 1f);
|
||||
var output = new byte[scene.RegionLength];
|
||||
using var convolver = new CpuTileConvolver(4);
|
||||
|
||||
convolver.RenderStored(stored, plan.RegionWidth * plan.RegionHeight, 1.2f, output, light, plan.RegionWidth, plan.RegionX, plan.RegionY);
|
||||
|
||||
Assert.Equal(expected, output);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
public sealed class FastFourierTransformExactnessTests
|
||||
{
|
||||
static void Reference(double[] real, double[] imaginary, bool inverse)
|
||||
{
|
||||
var count = real.Length;
|
||||
for (int source = 1, target = 0; source < count; source++)
|
||||
{
|
||||
var bit = count >> 1;
|
||||
for (; (target & bit) != 0; bit >>= 1)
|
||||
target ^= bit;
|
||||
target ^= bit;
|
||||
if (source < target)
|
||||
{
|
||||
(real[source], real[target]) = (real[target], real[source]);
|
||||
(imaginary[source], imaginary[target]) = (imaginary[target], imaginary[source]);
|
||||
}
|
||||
}
|
||||
|
||||
var sign = inverse ? 1d : -1d;
|
||||
for (var length = 2; length <= count; length <<= 1)
|
||||
{
|
||||
var half = length >> 1;
|
||||
for (var offset = 0; offset < count; offset += length)
|
||||
{
|
||||
for (var index = 0; index < half; index++)
|
||||
{
|
||||
var (sin, cos) = Math.SinCos(sign * 2d * Math.PI * index / length);
|
||||
var even = offset + index;
|
||||
var odd = even + half;
|
||||
var productReal = real[odd] * cos - imaginary[odd] * sin;
|
||||
var productImaginary = real[odd] * sin + imaginary[odd] * cos;
|
||||
var evenReal = real[even];
|
||||
var evenImaginary = imaginary[even];
|
||||
real[even] = evenReal + productReal;
|
||||
imaginary[even] = evenImaginary + productImaginary;
|
||||
real[odd] = evenReal - productReal;
|
||||
imaginary[odd] = evenImaginary - productImaginary;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!inverse)
|
||||
return;
|
||||
|
||||
var scale = 1d / count;
|
||||
for (var index = 0; index < count; index++)
|
||||
{
|
||||
real[index] *= scale;
|
||||
imaginary[index] *= scale;
|
||||
}
|
||||
}
|
||||
|
||||
static (double[] Real, double[] Imaginary) Input(int count, int trial, Random random)
|
||||
{
|
||||
var real = new double[count];
|
||||
var imaginary = new double[count];
|
||||
for (var index = 0; index < count; index++)
|
||||
{
|
||||
real[index] = trial % 3 == 0 && index % 5 != 0 ? 0d : random.NextDouble() * 2 - 1;
|
||||
imaginary[index] = trial % 4 == 0 && index % 7 != 0 ? 0d : (random.NextDouble() * 2 - 1) * (trial % 5 == 0 ? 1e-9 : 1d);
|
||||
}
|
||||
|
||||
return (real, imaginary);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1)]
|
||||
[InlineData(2)]
|
||||
[InlineData(4)]
|
||||
[InlineData(8)]
|
||||
[InlineData(16)]
|
||||
[InlineData(32)]
|
||||
[InlineData(64)]
|
||||
[InlineData(128)]
|
||||
[InlineData(256)]
|
||||
[InlineData(512)]
|
||||
[InlineData(1024)]
|
||||
public void TheTransformPerformsTheSameArithmeticAsTheRadixTwoReference(int count)
|
||||
{
|
||||
var random = new Random(count);
|
||||
for (var trial = 0; trial < 40; trial++)
|
||||
{
|
||||
foreach (var inverse in new[] { false, true })
|
||||
{
|
||||
var (expectedReal, expectedImaginary) = Input(count, trial, random);
|
||||
var actualReal = (double[])expectedReal.Clone();
|
||||
var actualImaginary = (double[])expectedImaginary.Clone();
|
||||
|
||||
Reference(expectedReal, expectedImaginary, inverse);
|
||||
if (inverse)
|
||||
FastFourierTransform.Inverse(actualReal, actualImaginary);
|
||||
else
|
||||
FastFourierTransform.Forward(actualReal, actualImaginary);
|
||||
|
||||
Assert.True(expectedReal.AsSpan().SequenceEqual(actualReal), $"real {count} {trial} {inverse}");
|
||||
Assert.True(expectedImaginary.AsSpan().SequenceEqual(actualImaginary), $"imaginary {count} {trial} {inverse}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ATransformOfALongerArrayThanTheTransformedPartLeavesTheRestUntouched()
|
||||
{
|
||||
var real = new double[600];
|
||||
var imaginary = new double[600];
|
||||
real.AsSpan().Fill(3d);
|
||||
imaginary.AsSpan().Fill(5d);
|
||||
|
||||
FastFourierTransform.Forward(real.AsSpan(40, 256), imaginary.AsSpan(40, 256));
|
||||
|
||||
Assert.All(real.AsSpan(0, 40).ToArray(), value => Assert.Equal(3d, value));
|
||||
Assert.All(real.AsSpan(296).ToArray(), value => Assert.Equal(3d, value));
|
||||
Assert.All(imaginary.AsSpan(0, 40).ToArray(), value => Assert.Equal(5d, value));
|
||||
Assert.All(imaginary.AsSpan(296).ToArray(), value => Assert.Equal(5d, value));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
using System.Numerics;
|
||||
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
public sealed class FftShaderMathTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(64)]
|
||||
[InlineData(128)]
|
||||
[InlineData(256)]
|
||||
[InlineData(512)]
|
||||
public void EveryRadix2StageTouchesEachElementOfTwoRowsOnce(int size)
|
||||
{
|
||||
var log2Size = BitOperations.Log2((uint)size);
|
||||
for (var stage = 0; stage < log2Size; stage++)
|
||||
{
|
||||
var touched = new int[size * 2];
|
||||
for (var index = 0; index < size; index++)
|
||||
{
|
||||
var even = FftShaderMath.Radix2Even(index, log2Size, stage);
|
||||
touched[even]++;
|
||||
touched[even + FftShaderMath.Pow2(stage)]++;
|
||||
}
|
||||
|
||||
Assert.All(touched, count => Assert.Equal(1, count));
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(64)]
|
||||
[InlineData(128)]
|
||||
[InlineData(256)]
|
||||
[InlineData(512)]
|
||||
public void EveryRadix4StageTouchesEachElementOfFourRowsOnce(int size)
|
||||
{
|
||||
var log2Size = BitOperations.Log2((uint)size);
|
||||
for (var stage = 0; stage + 1 < log2Size; stage++)
|
||||
{
|
||||
var step = FftShaderMath.Pow2(stage);
|
||||
var touched = new int[size * FftShaderMath.Radix4Elements];
|
||||
for (var index = 0; index < size; index++)
|
||||
{
|
||||
var first = FftShaderMath.Radix4First(index, log2Size, stage);
|
||||
for (var member = 0; member < FftShaderMath.Radix4Elements; member++)
|
||||
touched[first + member * step]++;
|
||||
}
|
||||
|
||||
Assert.All(touched, count => Assert.Equal(1, count));
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(64)]
|
||||
[InlineData(128)]
|
||||
[InlineData(256)]
|
||||
[InlineData(512)]
|
||||
public void EveryTwiddleIndexStaysInsideTheTable(int size)
|
||||
{
|
||||
var log2Size = BitOperations.Log2((uint)size);
|
||||
for (var stage = 0; stage < log2Size; stage++)
|
||||
{
|
||||
for (var index = 0; index < size; index++)
|
||||
Assert.InRange(FftShaderMath.TwiddleIndex(FftShaderMath.Position(index, stage), log2Size, stage), 0, size / 2 - 1);
|
||||
}
|
||||
|
||||
for (var stage = 0; stage + 1 < log2Size; stage++)
|
||||
{
|
||||
var step = FftShaderMath.Pow2(stage);
|
||||
for (var index = 0; index < size; index++)
|
||||
{
|
||||
var position = FftShaderMath.Position(index, stage);
|
||||
Assert.InRange(FftShaderMath.TwiddleIndex(position, log2Size, stage + 1), 0, size / 2 - 1);
|
||||
Assert.InRange(FftShaderMath.TwiddleIndex(position + step, log2Size, stage + 1), 0, size / 2 - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AGroupHoldsOneRadix4UnitForEveryFourElements()
|
||||
{
|
||||
Assert.Equal(4, FftShaderMath.Radix4Elements);
|
||||
Assert.Equal(TilePlan.GroupThreads / 2, FftShaderMath.StageUnitsPerGroup);
|
||||
Assert.Equal(TilePlan.GroupThreads, TilePlan.ChromaticGroupElements / FftShaderMath.Radix4Elements);
|
||||
}
|
||||
}
|
||||
@@ -28,16 +28,16 @@ public sealed class GpuTileConvolverTests
|
||||
return [.. samples];
|
||||
}
|
||||
|
||||
static GpuRun Run(GraphicsDevice device, ConvolutionScene scene, float gain = 1f, Func<float[], float[]>? tamper = null)
|
||||
static GpuRun Run(GraphicsDevice device, ConvolutionScene scene, float gain = 1f, Func<float[], float[]>? tamper = null, Int2[]? chosenSamples = null)
|
||||
{
|
||||
using var convolver = new GpuTileConvolver(device);
|
||||
return Run(device, convolver, scene, gain, tamper);
|
||||
return Run(device, convolver, scene, gain, tamper, chosenSamples);
|
||||
}
|
||||
|
||||
static GpuRun Run(GraphicsDevice device, GpuTileConvolver convolver, ConvolutionScene scene, float gain = 1f, Func<float[], float[]>? tamper = null)
|
||||
static GpuRun Run(GraphicsDevice device, GpuTileConvolver convolver, ConvolutionScene scene, float gain = 1f, Func<float[], float[]>? tamper = null, Int2[]? chosenSamples = null)
|
||||
{
|
||||
var plan = scene.Plan;
|
||||
var samples = Samples(plan);
|
||||
var samples = chosenSamples ?? Samples(plan);
|
||||
convolver.Upload(scene.Spectrum);
|
||||
var spectrum = MemoryMarshal.Cast<Float2, float>(scene.Spectrum.Spectrum).ToArray();
|
||||
if (tamper is not null)
|
||||
@@ -46,7 +46,7 @@ public sealed class GpuTileConvolverTests
|
||||
convolver.Spectrum.CopyFrom(MemoryMarshal.Cast<float, Float2>(spectrum));
|
||||
}
|
||||
|
||||
var job = convolver.Prepare(plan, scene.SourceX, scene.SourceY, scene.SourceWidth, scene.SourceHeight, gain, samples, true);
|
||||
var job = convolver.Prepare(plan, scene.SourceX, scene.SourceY, scene.SourceWidth, scene.SourceHeight, gain, samples, true, scene.Light);
|
||||
using var source = device.AllocateReadWriteTexture2D<Bgra32, Float4>(scene.SourceWidth, scene.SourceHeight);
|
||||
source.CopyFrom(MemoryMarshal.Cast<byte, Bgra32>(scene.Source));
|
||||
using var output = device.AllocateReadWriteTexture2D<Bgra32, Float4>(plan.RegionWidth, plan.RegionHeight);
|
||||
@@ -139,10 +139,10 @@ public sealed class GpuTileConvolverTests
|
||||
|
||||
for (var index = 0; index < run.Output.Length; index += 4)
|
||||
{
|
||||
Assert.InRange(run.Output[index] - CpuTileConvolver.ToUnorm(run.Store[index + 2] * 2.5f), -1, 1);
|
||||
Assert.InRange(run.Output[index + 1] - CpuTileConvolver.ToUnorm(run.Store[index + 1] * 2.5f), -1, 1);
|
||||
Assert.InRange(run.Output[index + 2] - CpuTileConvolver.ToUnorm(run.Store[index] * 2.5f), -1, 1);
|
||||
Assert.InRange(run.Output[index + 3] - CpuTileConvolver.ToUnorm(run.Store[index + 3] * 2.5f), -1, 1);
|
||||
Assert.InRange(run.Output[index] - CpuPixels.ToUnorm(run.Store[index + 2] * 2.5f), -1, 1);
|
||||
Assert.InRange(run.Output[index + 1] - CpuPixels.ToUnorm(run.Store[index + 1] * 2.5f), -1, 1);
|
||||
Assert.InRange(run.Output[index + 2] - CpuPixels.ToUnorm(run.Store[index] * 2.5f), -1, 1);
|
||||
Assert.InRange(run.Output[index + 3] - CpuPixels.ToUnorm(run.Store[index + 3] * 2.5f), -1, 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -343,4 +343,397 @@ public sealed class GpuTileConvolverTests
|
||||
Assert.False(convolver.HasStore);
|
||||
Assert.Throws<InvalidOperationException>(() => convolver.StoreFor(with));
|
||||
}
|
||||
|
||||
static ConvolutionScene LightScene(int size, int radius, int width, int height, int margin, int seed, LightOptions light)
|
||||
=> ConvolutionScene.Create(ConvolutionScene.RandomSource(width, height, seed, 0.45), width, height, margin, radius, size, light);
|
||||
|
||||
[Theory]
|
||||
[InlineData(64, 5, 150, 97, 11, false, true, 0f, 0f)]
|
||||
[InlineData(64, 5, 150, 97, 11, true, false, 0f, 0f)]
|
||||
[InlineData(128, 23, 140, 90, 24, true, true, 0.9f, 20f)]
|
||||
[InlineData(512, 3, 1100, 560, 8, true, false, 0.8f, 100f)]
|
||||
public void ALightRunPassesEveryCheckAndStaysWithinTheBound(int size, int radius, int width, int height, int margin, bool linear, bool dither, float threshold, float boost)
|
||||
{
|
||||
var scene = LightScene(size, radius, width, height, margin, size + radius, new LightOptions(linear, dither, threshold, boost));
|
||||
|
||||
var run = Run(HardwareOrDefault(), scene);
|
||||
|
||||
Assert.InRange(scene.WorstRatio(run.Store, ConvolutionBound.GpuOperationError), 0d, 1d);
|
||||
Assert.All(Measure(scene, run), measurement => Assert.True(measurement.Passes, $"{measurement}"));
|
||||
}
|
||||
|
||||
const int OutputValuesPerToleratedRoundingFlip = 2000;
|
||||
|
||||
static void AssertOutputIsTheTransformOfTheStore(ConvolutionScene scene, GpuRun run, float gain, LightOptions light)
|
||||
{
|
||||
var width = scene.Plan.RegionWidth;
|
||||
var roundingFlips = 0;
|
||||
for (var y = 0; y < scene.Plan.RegionHeight; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var index = (y * width + x) * 4;
|
||||
var expected = LightTransform.ToBytes(run.Store[index], run.Store[index + 1], run.Store[index + 2], run.Store[index + 3], gain, light, scene.Plan.RegionX + x, scene.Plan.RegionY + y);
|
||||
Assert.InRange(run.Output[index] - expected.Blue, -1, 1);
|
||||
Assert.InRange(run.Output[index + 1] - expected.Green, -1, 1);
|
||||
Assert.InRange(run.Output[index + 2] - expected.Red, -1, 1);
|
||||
Assert.InRange(run.Output[index + 3] - expected.Alpha, -1, 1);
|
||||
roundingFlips += (run.Output[index] != expected.Blue ? 1 : 0) + (run.Output[index + 1] != expected.Green ? 1 : 0)
|
||||
+ (run.Output[index + 2] != expected.Red ? 1 : 0) + (run.Output[index + 3] != expected.Alpha ? 1 : 0);
|
||||
}
|
||||
}
|
||||
|
||||
Assert.InRange(roundingFlips, 0, run.Output.Length / OutputValuesPerToleratedRoundingFlip);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true, false, 1f)]
|
||||
[InlineData(true, true, 1f)]
|
||||
[InlineData(true, true, 2.5f)]
|
||||
[InlineData(false, true, 1f)]
|
||||
[InlineData(false, true, 1.7f)]
|
||||
public void TheLightOutputIsTheTransformOfTheStoredValue(bool linear, bool dither, float gain)
|
||||
{
|
||||
var light = new LightOptions(linear, dither, 0.8f, linear ? 8f : 0f);
|
||||
var scene = LightScene(64, 4, 90, 60, 8, 9, light);
|
||||
|
||||
var run = Run(HardwareOrDefault(), scene, gain);
|
||||
|
||||
AssertOutputIsTheTransformOfTheStore(scene, run, gain, light);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false, true, 1f)]
|
||||
[InlineData(true, false, 2.75f)]
|
||||
[InlineData(true, true, 0.3f)]
|
||||
public void RenderingTheStoreMatchesTheLightConvolutionBitForBit(bool linear, bool dither, float gain)
|
||||
{
|
||||
var light = new LightOptions(linear, dither, 0.85f, linear ? 12f : 0f);
|
||||
var scene = LightScene(64, 5, 150, 97, 11, 47, light);
|
||||
var device = HardwareOrDefault();
|
||||
var fused = Run(device, scene, gain);
|
||||
using var convolver = new GpuTileConvolver(device);
|
||||
var stored = Run(device, convolver, scene, 1f);
|
||||
var width = scene.Plan.RegionWidth;
|
||||
var height = scene.Plan.RegionHeight;
|
||||
using var output = device.AllocateReadWriteTexture2D<Bgra32, Float4>(width, height);
|
||||
|
||||
using (var context = device.CreateComputeContext())
|
||||
GpuTileConvolver.RecordStored(in context, convolver.StoreFor(stored.Job), output, width, height, gain, in light, scene.Plan.RegionX, scene.Plan.RegionY);
|
||||
|
||||
var pixels = new Bgra32[width * height];
|
||||
output.CopyTo(pixels);
|
||||
Assert.Equal(fused.Output, MemoryMarshal.Cast<Bgra32, byte>(pixels).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheLightStatisticsDescribeTheTransformedSource()
|
||||
{
|
||||
var light = new LightOptions(true, false, 0.9f, 20f);
|
||||
var scene = LightScene(64, 5, 150, 97, 11, 3, light);
|
||||
|
||||
var run = Run(HardwareOrDefault(), scene);
|
||||
|
||||
for (var tile = 0; tile < scene.Plan.TileCount; tile++)
|
||||
{
|
||||
var (redGreen, blueAlpha) = scene.Norms(scene.Plan.RegionX + tile % scene.Plan.TilesX * scene.Plan.ValidSize, scene.Plan.RegionY + tile / scene.Plan.TilesX * scene.Plan.ValidSize);
|
||||
var measured = GpuTileCheck.Norms(run.Report, scene.Plan, tile, true);
|
||||
Assert.InRange(measured.RedGreen, redGreen * (1d - 1e-4), redGreen * (1d + 1e-3));
|
||||
Assert.InRange(measured.BlueAlpha, blueAlpha * (1d - 1e-4), blueAlpha * (1d + 1e-3));
|
||||
}
|
||||
|
||||
var measurements = Measure(scene, run);
|
||||
var values = scene.Transformed();
|
||||
var totals = new double[4];
|
||||
for (var index = 0; index < scene.SourceWidth * scene.SourceHeight; index++)
|
||||
{
|
||||
for (var channel = 0; channel < 4; channel++)
|
||||
totals[channel] += values[index * 4 + channel];
|
||||
}
|
||||
for (var channel = 0; channel < 4; channel++)
|
||||
Assert.Equal(totals[channel], measurements[1 + channel].Reference, totals[channel] * 1e-5);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AScaledSpectrumFailsTheLightSumCheck()
|
||||
{
|
||||
var scene = LightScene(64, 5, 150, 97, 11, 21, new LightOptions(true, false, 0.9f, 20f));
|
||||
|
||||
var measurements = Measure(scene, Run(HardwareOrDefault(), scene, tamper: spectrum => [.. spectrum.Select(value => value * 1.0005f)]));
|
||||
|
||||
Assert.Contains(measurements, measurement => measurement.Name.StartsWith("sum.", StringComparison.Ordinal) && !measurement.Passes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AMirroredKernelFailsTheLightSpotCheck()
|
||||
{
|
||||
var scene = LightScene(64, 5, 150, 97, 16, 23, new LightOptions(true, false, 0.9f, 20f));
|
||||
|
||||
var measurements = Measure(scene, Run(HardwareOrDefault(), scene, tamper: spectrum =>
|
||||
{
|
||||
var mirrored = (float[])spectrum.Clone();
|
||||
for (var index = 1; index < mirrored.Length; index += 2)
|
||||
mirrored[index] = -mirrored[index];
|
||||
return mirrored;
|
||||
}));
|
||||
|
||||
Assert.Contains(measurements, measurement => measurement.Name.StartsWith("spot.", StringComparison.Ordinal) && !measurement.Passes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AWrongHighlightFailsTheLightSpotCheck()
|
||||
{
|
||||
var claimed = new LightOptions(true, false, 0.9f, 20f);
|
||||
var actual = LightScene(64, 5, 150, 97, 16, 25, new LightOptions(true, false, 0.9f, 2f));
|
||||
|
||||
var run = Run(HardwareOrDefault(), actual);
|
||||
var measurements = new ConvolutionMeasurement[GpuTileCheck.MeasurementCount(run.Samples.Length)];
|
||||
GpuTileCheck.Evaluate(run.Report, run.Job with { Light = claimed }, run.Samples, actual.Spectrum.Kernel, measurements);
|
||||
|
||||
Assert.Contains(measurements, measurement => !measurement.Passes);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void ADitheredOpaqueWhiteSceneNeverDropsToBlackAnywhere(bool linear)
|
||||
{
|
||||
var light = new LightOptions(linear, true, 0f, 0f);
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.Uniform(1100, 700, 255), 1100, 700, 8, 3, 512, light);
|
||||
|
||||
var run = Run(HardwareOrDefault(), scene);
|
||||
|
||||
var wrong = 0;
|
||||
for (var y = 8 + 4; y < 8 + 700 - 4; y++)
|
||||
{
|
||||
for (var x = 8 + 4; x < 8 + 1100 - 4; x++)
|
||||
{
|
||||
var index = (y * scene.Plan.RegionWidth + x) * 4;
|
||||
if (run.Output[index] < 250 || run.Output[index + 1] < 250 || run.Output[index + 2] < 250 || run.Output[index + 3] < 250)
|
||||
wrong++;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.Equal(0, wrong);
|
||||
}
|
||||
|
||||
static bool Marked(Int2[] entries, int tile)
|
||||
{
|
||||
var entry = entries[GpuTileConvolver.MaximumSamples + (tile >> 6)];
|
||||
return (((tile & 32) == 0 ? entry.X : entry.Y) >> (tile & 31) & 1) != 0;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void TheSamplesBufferMarksTheTilesThatHoldASample(bool linear)
|
||||
{
|
||||
var light = new LightOptions(linear, false, 0f, 0f);
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.RandomSource(1400, 900, 5, 0.4), 1400, 900, 8, 5, 128, light);
|
||||
var plan = scene.Plan;
|
||||
using var convolver = new GpuTileConvolver(HardwareOrDefault());
|
||||
convolver.Upload(scene.Spectrum);
|
||||
var samples = Samples(plan);
|
||||
|
||||
convolver.Prepare(plan, scene.SourceX, scene.SourceY, scene.SourceWidth, scene.SourceHeight, 1f, samples, false, light);
|
||||
|
||||
var entries = new Int2[convolver.Samples.Length];
|
||||
convolver.Samples.CopyTo(entries);
|
||||
Assert.True(plan.TileCount > 64);
|
||||
Assert.Equal(samples, entries.Take(GpuTileConvolver.MaximumSamples));
|
||||
var expected = new HashSet<int>(samples.Select(sample => plan.TileAt(plan.RegionX + sample.X, plan.RegionY + sample.Y)));
|
||||
Assert.True(expected.Count > 1);
|
||||
for (var tile = 0; tile < (plan.TileCount + 63) / 64 * 64; tile++)
|
||||
Assert.Equal(expected.Contains(tile), Marked(entries, tile));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheMarksFollowTheSamplesOfTheLatestJob()
|
||||
{
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.RandomSource(1400, 900, 6, 0.4), 1400, 900, 8, 5, 128);
|
||||
var plan = scene.Plan;
|
||||
using var convolver = new GpuTileConvolver(HardwareOrDefault());
|
||||
convolver.Upload(scene.Spectrum);
|
||||
Int2[] first = [new(0, 0)];
|
||||
Int2[] second = [new(plan.RegionWidth - 1, plan.RegionHeight - 1)];
|
||||
|
||||
convolver.Prepare(plan, scene.SourceX, scene.SourceY, scene.SourceWidth, scene.SourceHeight, 1f, first, false);
|
||||
convolver.Prepare(plan, scene.SourceX, scene.SourceY, scene.SourceWidth, scene.SourceHeight, 1f, second, false);
|
||||
|
||||
var entries = new Int2[convolver.Samples.Length];
|
||||
convolver.Samples.CopyTo(entries);
|
||||
var lastTile = plan.TileAt(plan.RegionX + second[0].X, plan.RegionY + second[0].Y);
|
||||
for (var tile = 0; tile < (plan.TileCount + 63) / 64 * 64; tile++)
|
||||
Assert.Equal(tile == lastTile, Marked(entries, tile));
|
||||
Assert.Equal(second[0], entries[0]);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false, 1f)]
|
||||
[InlineData(true, 1f)]
|
||||
[InlineData(true, 1.8f)]
|
||||
public void ADitheredTranslucentSceneKeepsEveryColorBelowItsOpacity(bool linear, float gain)
|
||||
{
|
||||
var light = new LightOptions(linear, true, 0f, 0f);
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.Uniform(240, 160, 128), 240, 160, 8, 3, 64, light);
|
||||
|
||||
var run = Run(HardwareOrDefault(), scene, gain);
|
||||
|
||||
var exceeding = 0;
|
||||
var translucent = 0;
|
||||
for (var index = 0; index < run.Output.Length; index += 4)
|
||||
{
|
||||
if (run.Output[index + 3] is > 0 and < 255)
|
||||
translucent++;
|
||||
if (run.Output[index] > run.Output[index + 3] || run.Output[index + 1] > run.Output[index + 3] || run.Output[index + 2] > run.Output[index + 3])
|
||||
exceeding++;
|
||||
}
|
||||
|
||||
Assert.True(translucent > 1000, $"{translucent}");
|
||||
Assert.Equal(0, exceeding);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true, false, 1f)]
|
||||
[InlineData(false, true, 1.7f)]
|
||||
[InlineData(true, true, 1f)]
|
||||
[InlineData(true, true, 2.2f)]
|
||||
public void ARegionAwayFromTheOriginDrawsTheSameLightImageAsTheCpu(bool linear, bool dither, float gain)
|
||||
{
|
||||
var light = new LightOptions(linear, dither, 0.8f, linear ? 8f : 0f);
|
||||
var source = ConvolutionScene.RandomSource(120, 80, 77, 0.5);
|
||||
var scene = ConvolutionScene.CreateShifted(source, 43, 29, 120, 80, 37, 23, 132, 92, 4, 64, light);
|
||||
var plan = scene.Plan;
|
||||
var cpu = new byte[scene.RegionLength];
|
||||
using (var convolver = new CpuTileConvolver(3))
|
||||
convolver.Convolve(scene.Source, scene.SourceX, scene.SourceY, scene.SourceWidth, scene.SourceHeight, scene.Spectrum, plan, cpu, gain, null, light);
|
||||
|
||||
var run = Run(HardwareOrDefault(), scene, gain);
|
||||
|
||||
var differing = 0;
|
||||
for (var index = 0; index < cpu.Length; index++)
|
||||
{
|
||||
Assert.InRange(run.Output[index] - cpu[index], -1, 1);
|
||||
if (run.Output[index] != cpu[index])
|
||||
differing++;
|
||||
}
|
||||
|
||||
Assert.InRange(differing, 0, cpu.Length / 2000);
|
||||
Assert.All(Measure(scene, run), measurement => Assert.True(measurement.Passes, $"{measurement}"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true, true, 1.3f)]
|
||||
[InlineData(false, true, 2f)]
|
||||
public void RenderingTheStoreMatchesTheLightConvolutionForARegionAwayFromTheOrigin(bool linear, bool dither, float gain)
|
||||
{
|
||||
var light = new LightOptions(linear, dither, 0.85f, linear ? 12f : 0f);
|
||||
var source = ConvolutionScene.RandomSource(120, 80, 78, 0.5);
|
||||
var scene = ConvolutionScene.CreateShifted(source, 43, 29, 120, 80, 37, 23, 132, 92, 4, 64, light);
|
||||
var device = HardwareOrDefault();
|
||||
var fused = Run(device, scene, gain);
|
||||
using var convolver = new GpuTileConvolver(device);
|
||||
var stored = Run(device, convolver, scene, 1f);
|
||||
var width = scene.Plan.RegionWidth;
|
||||
var height = scene.Plan.RegionHeight;
|
||||
using var output = device.AllocateReadWriteTexture2D<Bgra32, Float4>(width, height);
|
||||
|
||||
using (var context = device.CreateComputeContext())
|
||||
GpuTileConvolver.RecordStored(in context, convolver.StoreFor(stored.Job), output, width, height, gain, in light, scene.Plan.RegionX, scene.Plan.RegionY);
|
||||
|
||||
var pixels = new Bgra32[width * height];
|
||||
output.CopyTo(pixels);
|
||||
Assert.Equal(fused.Output, MemoryMarshal.Cast<Bgra32, byte>(pixels).ToArray());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void EverySampledTileReportsItsSpotWhateverItsIndex(bool linear)
|
||||
{
|
||||
var light = new LightOptions(linear, false, 0f, 0f);
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.RandomSource(1400, 900, 12, 0.6), 1400, 900, 8, 5, 128, light);
|
||||
var plan = scene.Plan;
|
||||
Assert.True(plan.TileCount > 90);
|
||||
int[] tiles = [0, 31, 32, 33, 63, 64, 65, 95];
|
||||
var samples = tiles.Select(tile => new Int2(
|
||||
Math.Min(tile % plan.TilesX * plan.ValidSize + plan.ValidSize / 2, plan.RegionWidth - 1),
|
||||
Math.Min(tile / plan.TilesX * plan.ValidSize + plan.ValidSize / 2, plan.RegionHeight - 1))).ToArray();
|
||||
Assert.Equal(tiles, samples.Select(sample => plan.TileAt(plan.RegionX + sample.X, plan.RegionY + sample.Y)).ToArray());
|
||||
|
||||
var run = Run(HardwareOrDefault(), scene, 1f, null, samples);
|
||||
|
||||
var measurements = Measure(scene, run);
|
||||
Assert.All(measurements, measurement => Assert.True(measurement.Passes, $"{measurement}"));
|
||||
for (var sample = 0; sample < samples.Length; sample++)
|
||||
Assert.True(measurements[1 + 4 + sample * 4 + 3].Measured > 0d, $"tile {tiles[sample]}");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true, false)]
|
||||
[InlineData(true, true)]
|
||||
public void ADarkSceneStaysWithinTheBoundInLinearLight(bool linear, bool dither)
|
||||
{
|
||||
var random = new Random(5);
|
||||
var source = new byte[150 * 97 * 4];
|
||||
for (var index = 0; index < source.Length; index += 4)
|
||||
{
|
||||
source[index] = (byte)random.Next(0, 9);
|
||||
source[index + 1] = (byte)random.Next(0, 9);
|
||||
source[index + 2] = (byte)random.Next(0, 9);
|
||||
source[index + 3] = 255;
|
||||
}
|
||||
|
||||
var light = new LightOptions(linear, dither, 0f, 0f);
|
||||
var scene = ConvolutionScene.Create(source, 150, 97, 11, 5, 64, light);
|
||||
|
||||
var run = Run(HardwareOrDefault(), scene);
|
||||
|
||||
Assert.All(Measure(scene, run), measurement => Assert.True(measurement.Passes, $"{measurement}"));
|
||||
Assert.InRange(scene.WorstRatio(run.Store, ConvolutionBound.GpuOperationError + GpuTileCheck.LightTransformError), 0d, 1d);
|
||||
AssertOutputIsTheTransformOfTheStore(scene, run, 1f, light);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PreparingInvalidLightOptionsIsRejected()
|
||||
{
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.RandomSource(100, 60, 3, 0.5), 100, 60, 8, 4, 64);
|
||||
var plan = scene.Plan;
|
||||
using var convolver = new GpuTileConvolver(HardwareOrDefault());
|
||||
convolver.Upload(scene.Spectrum);
|
||||
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => convolver.Prepare(plan, 8, 8, 100, 60, 1f, [], false, new LightOptions(true, false, 1.5f, 5f)));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => convolver.Prepare(plan, 8, 8, 100, 60, 1f, [], false, new LightOptions(true, false, 0.5f, 2000f)));
|
||||
convolver.Prepare(plan, 8, 8, 100, 60, 1f, [], false, new LightOptions(true, false, 0.5f, 5f));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheLinearLightToleranceExceedsTheOtherOneByTheTransformError()
|
||||
{
|
||||
var scene = ConvolutionScene.Create(ConvolutionScene.RandomSource(150, 97, 31, 0.45), 150, 97, 11, 5, 64, new LightOptions(true, false, 0f, 0f));
|
||||
var run = Run(HardwareOrDefault(), scene);
|
||||
var plan = scene.Plan;
|
||||
var sampleCount = run.Samples.Length;
|
||||
var linear = new ConvolutionMeasurement[GpuTileCheck.MeasurementCount(sampleCount)];
|
||||
var plain = new ConvolutionMeasurement[linear.Length];
|
||||
var linearJob = run.Job with { Light = new LightOptions(true, true, 0f, 0f) };
|
||||
var plainJob = run.Job with { Light = new LightOptions(false, true, 0f, 0f) };
|
||||
|
||||
GpuTileCheck.Evaluate(run.Report, linearJob, run.Samples, scene.Spectrum.Kernel, linear);
|
||||
GpuTileCheck.Evaluate(run.Report, plainJob, run.Samples, scene.Spectrum.Kernel, plain);
|
||||
|
||||
for (var sample = 0; sample < sampleCount; sample++)
|
||||
{
|
||||
var tile = plan.TileAt(plan.RegionX + run.Samples[sample].X, plan.RegionY + run.Samples[sample].Y);
|
||||
var (redGreen, blueAlpha) = GpuTileCheck.Norms(run.Report, plan, tile, true);
|
||||
for (var channel = 0; channel < 4; channel++)
|
||||
{
|
||||
var index = 1 + 4 + sample * 4 + channel;
|
||||
var norm = channel < 2 ? redGreen : blueAlpha;
|
||||
Assert.Equal(GpuTileCheck.LightTransformError * norm, linear[index].Tolerance - plain[index].Tolerance, norm * 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
Assert.Equal(Math.ScaleB(1d, -16), GpuTileCheck.LightTransformError);
|
||||
}
|
||||
}
|
||||
@@ -89,6 +89,45 @@ public sealed class KernelSpectrumTests
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(5, 64)]
|
||||
[InlineData(20, 128)]
|
||||
[InlineData(63, 512)]
|
||||
public void EveryElementOfTheSpectrumAgreesWithAFullTwoDimensionalTransform(int radius, int size)
|
||||
{
|
||||
var values = AsymmetricKernel(radius);
|
||||
var spectrum = new KernelSpectrum();
|
||||
|
||||
spectrum.Update(values, radius, size);
|
||||
|
||||
var kernelSize = radius * 2 + 1;
|
||||
var sum = values.Sum();
|
||||
var mask = size - 1;
|
||||
var real = new double[size * size];
|
||||
var imaginary = new double[size * size];
|
||||
for (var offsetY = -radius; offsetY <= radius; offsetY++)
|
||||
{
|
||||
for (var offsetX = -radius; offsetX <= radius; offsetX++)
|
||||
real[(-offsetY & mask) * size + (-offsetX & mask)] = values[(offsetY + radius) * kernelSize + offsetX + radius] / sum;
|
||||
}
|
||||
|
||||
FastFourierTransform.Forward2D(real, imaginary, size, size);
|
||||
|
||||
var excess = double.NegativeInfinity;
|
||||
for (var frequencyY = 0; frequencyY < size; frequencyY++)
|
||||
{
|
||||
for (var frequencyX = 0; frequencyX < size; frequencyX++)
|
||||
{
|
||||
var value = spectrum.Spectrum[frequencyX * size + frequencyY];
|
||||
var index = frequencyY * size + frequencyX;
|
||||
excess = Math.Max(excess, Math.Abs(value.X - real[index]) - (1e-12 + Math.Abs(real[index]) * 1e-6));
|
||||
excess = Math.Max(excess, Math.Abs(value.Y - imaginary[index]) - (1e-12 + Math.Abs(imaginary[index]) * 1e-6));
|
||||
}
|
||||
}
|
||||
|
||||
Assert.True(excess <= 0d, $"{excess}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSpectrumAtZeroFrequencyIsTheKernelSum()
|
||||
{
|
||||
@@ -116,6 +155,27 @@ public sealed class KernelSpectrumTests
|
||||
Assert.Equal(fresh.Spectrum.ToArray(), reused.Spectrum.ToArray());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(3, 64)]
|
||||
[InlineData(20, 128)]
|
||||
[InlineData(40, 512)]
|
||||
public void AHalfSpectrumIsTheFirstColumnsOfTheFullOne(int radius, int size)
|
||||
{
|
||||
var full = new KernelSpectrum();
|
||||
full.Update(AsymmetricKernel(radius), radius, size);
|
||||
var half = new KernelSpectrum(SpectrumPlane.Half);
|
||||
|
||||
half.Update(AsymmetricKernel(radius), radius, size);
|
||||
|
||||
var columns = size / 2 + 1;
|
||||
Assert.Equal(columns * size, half.Spectrum.Length);
|
||||
Assert.Equal(full.Spectrum[..(columns * size)].ToArray(), half.Spectrum.ToArray());
|
||||
Assert.Equal(full.Kernel.ToArray(), half.Kernel.ToArray());
|
||||
Assert.Equal(full.Twiddles.ToArray(), half.Twiddles.ToArray());
|
||||
Assert.Equal(size, half.Size);
|
||||
Assert.Equal(radius, half.Radius);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ANegativeWeightIsRejected()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,573 @@
|
||||
using System.Runtime.Intrinsics;
|
||||
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
public sealed class LightTransformTests
|
||||
{
|
||||
static readonly LightOptions Linear = new(true, false, 0f, 0f);
|
||||
|
||||
static double ReferenceDecode(double encoded)
|
||||
=> encoded <= 0.04045 ? encoded / 12.92 : Math.Pow((encoded + 0.055) / 1.055, 2.4);
|
||||
|
||||
static double ReferenceEncode(double linear)
|
||||
=> linear <= 0.0031308 ? linear * 12.92 : 1.055 * Math.Pow(linear, 1d / 2.4) - 0.055;
|
||||
|
||||
[Fact]
|
||||
public void TheEndpointsAreFixed()
|
||||
{
|
||||
Assert.Equal(0f, LightTransform.Decode(0f));
|
||||
Assert.Equal(1f, LightTransform.Decode(1f));
|
||||
Assert.Equal(0f, LightTransform.Encode(0f));
|
||||
Assert.Equal(1f, LightTransform.Encode(1f));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0.01f)]
|
||||
[InlineData(0.04045f)]
|
||||
[InlineData(0.05f)]
|
||||
[InlineData(0.2f)]
|
||||
[InlineData(0.5f)]
|
||||
[InlineData(0.8f)]
|
||||
public void DecodeFollowsTheStandardCurve(float encoded)
|
||||
{
|
||||
var expected = ReferenceDecode(encoded);
|
||||
|
||||
Assert.Equal(expected, LightTransform.Decode(encoded), expected * 1e-6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EncodeReturnsEveryByteThatDecodeStarted()
|
||||
{
|
||||
for (var value = 0; value < 256; value++)
|
||||
{
|
||||
var encoded = LightTransform.Encode(LightTransform.Decode(value / 255f));
|
||||
|
||||
Assert.Equal(value, (byte)(encoded * 255f + 0.5f));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithoutLinearLightTheBytesPassThrough()
|
||||
{
|
||||
var (red, green, blue, alpha) = LightTransform.FromBytes(10, 200, 33, 128, default);
|
||||
|
||||
Assert.Equal(10 / 255f, red);
|
||||
Assert.Equal(200 / 255f, green);
|
||||
Assert.Equal(33 / 255f, blue);
|
||||
Assert.Equal(128 / 255f, alpha);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnOpaquePixelIsDecodedChannelByChannel()
|
||||
{
|
||||
var (red, green, blue, alpha) = LightTransform.FromBytes(10, 128, 255, 255, Linear);
|
||||
|
||||
Assert.Equal(LightTransform.Decode(10 / 255f), red);
|
||||
Assert.Equal(LightTransform.Decode(128 / 255f), green);
|
||||
Assert.Equal(1f, blue);
|
||||
Assert.Equal(1f, alpha);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ATranslucentPixelIsDecodedFromItsStraightColorAndPremultipliedAgain()
|
||||
{
|
||||
var (red, green, blue, alpha) = LightTransform.FromBytes(128, 64, 32, 128, Linear);
|
||||
|
||||
var opacity = 128 / 255f;
|
||||
Assert.Equal(opacity, alpha);
|
||||
Assert.Equal(1.0, red / opacity, 1e-6);
|
||||
Assert.Equal(ReferenceDecode(64 / 128d), green / opacity, 1e-6);
|
||||
Assert.Equal(ReferenceDecode(32 / 128d), blue / opacity, 1e-6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AFullyTransparentPixelIsZeroWhateverItsColor()
|
||||
{
|
||||
Assert.Equal((0f, 0f, 0f, 0f), LightTransform.FromBytes(200, 100, 50, 0, Linear));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HighlightsRaiseAWhitePixelByTheBoost()
|
||||
{
|
||||
var options = new LightOptions(true, false, 0.9f, 10f);
|
||||
|
||||
var (red, green, blue, alpha) = LightTransform.FromBytes(255, 255, 255, 255, options);
|
||||
|
||||
Assert.Equal(10f, red);
|
||||
Assert.Equal(10f, green);
|
||||
Assert.Equal(10f, blue);
|
||||
Assert.Equal(10f, alpha);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HighlightsLeaveAPixelAtOrBelowTheThresholdAlone()
|
||||
{
|
||||
var options = new LightOptions(true, false, 230 / 255f, 10f);
|
||||
|
||||
var raised = LightTransform.FromBytes(230, 230, 230, 255, options);
|
||||
var plain = LightTransform.FromBytes(230, 230, 230, 255, Linear);
|
||||
|
||||
Assert.Equal(plain, raised);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HighlightsRaiseByTheSquareOfTheExcess()
|
||||
{
|
||||
var options = new LightOptions(true, false, 0.9f, 10f);
|
||||
var peak = 242 / 255d;
|
||||
var expectedWeight = 1d + 9d * Math.Pow((peak - 0.9f) / (1d - 0.9f), 2d);
|
||||
|
||||
var raised = LightTransform.FromBytes(242, 242, 242, 255, options);
|
||||
var plain = LightTransform.FromBytes(242, 242, 242, 255, Linear);
|
||||
|
||||
Assert.Equal(expectedWeight, raised.Red / plain.Red, expectedWeight * 1e-3);
|
||||
Assert.Equal(raised.Red / plain.Red, raised.Alpha / plain.Alpha, 1e-3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HighlightsKeepTheRatioBetweenTheChannels()
|
||||
{
|
||||
var options = new LightOptions(true, false, 0.5f, 30f);
|
||||
|
||||
var raised = LightTransform.FromBytes(255, 128, 64, 255, options);
|
||||
var plain = LightTransform.FromBytes(255, 128, 64, 255, Linear);
|
||||
|
||||
Assert.Equal(raised.Red / plain.Red, raised.Green / plain.Green, 1e-4);
|
||||
Assert.Equal(raised.Red / plain.Red, raised.Blue / plain.Blue, 1e-4);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1f, 0.5f)]
|
||||
[InlineData(0f, 0.5f)]
|
||||
[InlineData(10f, 1f)]
|
||||
public void HighlightsDoNothingWithoutABoostAboveOneOrAThresholdBelowOne(float boost, float threshold)
|
||||
{
|
||||
var options = new LightOptions(true, false, threshold, boost);
|
||||
|
||||
Assert.False(options.Highlights);
|
||||
Assert.Equal(LightTransform.FromBytes(255, 200, 100, 255, Linear), LightTransform.FromBytes(255, 200, 100, 255, options));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HighlightsNeedLinearLight()
|
||||
{
|
||||
var options = new LightOptions(false, false, 0.5f, 10f);
|
||||
|
||||
Assert.False(options.Highlights);
|
||||
Assert.Equal(LightTransform.FromBytes(255, 200, 100, 255, default), LightTransform.FromBytes(255, 200, 100, 255, options));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ForTheConvolutionOnlyTheInputAffectingFieldsRemain()
|
||||
{
|
||||
Assert.Equal(new LightOptions(true, false, 0.9f, 10f), new LightOptions(true, true, 0.9f, 10f).ForConvolution());
|
||||
Assert.Equal(new LightOptions(true, false, 0f, 0f), new LightOptions(true, true, 0.9f, 1f).ForConvolution());
|
||||
Assert.Equal(new LightOptions(false, false, 0f, 0f), new LightOptions(false, true, 0.9f, 10f).ForConvolution());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EveryOpaqueByteSurvivesTheRoundTrip()
|
||||
{
|
||||
for (var value = 0; value < 256; value++)
|
||||
{
|
||||
var (red, green, blue, alpha) = LightTransform.FromBytes((byte)value, (byte)value, (byte)value, 255, Linear);
|
||||
var (outputBlue, outputGreen, outputRed, outputAlpha) = LightTransform.ToBytes(red, green, blue, alpha, 1f, Linear, 0, 0);
|
||||
|
||||
Assert.Equal((byte)value, outputRed);
|
||||
Assert.Equal((byte)value, outputGreen);
|
||||
Assert.Equal((byte)value, outputBlue);
|
||||
Assert.Equal((byte)255, outputAlpha);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ATranslucentPixelSurvivesTheRoundTripWithinOneStep()
|
||||
{
|
||||
for (var alpha = 1; alpha < 256; alpha += 7)
|
||||
{
|
||||
for (var value = 0; value <= alpha; value += 5)
|
||||
{
|
||||
var (red, green, blue, opacity) = LightTransform.FromBytes((byte)value, (byte)(value / 2), (byte)(value / 3), (byte)alpha, Linear);
|
||||
var (outputBlue, outputGreen, outputRed, outputAlpha) = LightTransform.ToBytes(red, green, blue, opacity, 1f, Linear, 0, 0);
|
||||
|
||||
Assert.InRange(outputRed, value - 1, value + 1);
|
||||
Assert.InRange(outputGreen, value / 2 - 1, value / 2 + 1);
|
||||
Assert.InRange(outputBlue, value / 3 - 1, value / 3 + 1);
|
||||
Assert.Equal((byte)alpha, outputAlpha);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheGainBrightensAndSaturates()
|
||||
{
|
||||
var half = LightTransform.Decode(0.5f);
|
||||
|
||||
var doubled = LightTransform.ToBytes(half, half, half, 1f, 2f, Linear, 0, 0);
|
||||
var saturated = LightTransform.ToBytes(half, half, half, 1f, 100f, Linear, 0, 0);
|
||||
|
||||
Assert.Equal((byte)(LightTransform.Encode(MathF.Min(half * 2f, 1f)) * 255f + 0.5f), doubled.Red);
|
||||
Assert.Equal(((byte)255, (byte)255, (byte)255, (byte)255), saturated);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AColorBeyondTheOpacityIsHeldAtTheOpacity()
|
||||
{
|
||||
var (blue, green, red, alpha) = LightTransform.ToBytes(2f, 0.1f, 0f, 0.5f, 1f, Linear, 0, 0);
|
||||
|
||||
Assert.Equal((byte)128, alpha);
|
||||
Assert.Equal((byte)128, red);
|
||||
Assert.True(green < 128);
|
||||
Assert.Equal((byte)0, blue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithoutLinearLightTheOutputIsTheClampedValue()
|
||||
{
|
||||
float[] values = [float.NaN, -1f, 0f, 0.2f, 0.5f, 0.999f, 1f, 2f, float.PositiveInfinity];
|
||||
foreach (var value in values)
|
||||
{
|
||||
var (blue, green, red, alpha) = LightTransform.ToBytes(value, value, value, value, 1.5f, default, 3, 4);
|
||||
|
||||
var expected = CpuPixels.ToUnorm(value * 1.5f);
|
||||
Assert.Equal(expected, red);
|
||||
Assert.Equal(expected, green);
|
||||
Assert.Equal(expected, blue);
|
||||
Assert.Equal(expected, alpha);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheDitherThresholdStaysBelowOneAndAveragesOneHalf()
|
||||
{
|
||||
var sum = 0d;
|
||||
var count = 0;
|
||||
for (var y = 0; y < 300; y++)
|
||||
{
|
||||
for (var x = 0; x < 300; x++)
|
||||
{
|
||||
var threshold = LightTransform.DitherThreshold(x, y);
|
||||
Assert.InRange(threshold, 0f, 0.99999994f);
|
||||
sum += threshold;
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.Equal(0.5, sum / count, 0.01);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheDitherThresholdIsDeterministicAndDiffersByPosition()
|
||||
{
|
||||
Assert.Equal(LightTransform.DitherThreshold(12, 34), LightTransform.DitherThreshold(12, 34));
|
||||
var differing = 0;
|
||||
for (var x = 0; x < 64; x++)
|
||||
{
|
||||
if (LightTransform.DitherThreshold(x, 7) != LightTransform.DitherThreshold(x + 1, 7)
|
||||
&& LightTransform.DitherThreshold(x, 7) != LightTransform.DitherThreshold(x, 8))
|
||||
differing++;
|
||||
}
|
||||
|
||||
Assert.True(differing > 60);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ADitheredValueKeepsItsFractionOnAverage()
|
||||
{
|
||||
var options = new LightOptions(false, true, 0f, 0f);
|
||||
var value = 100.3f / 255f;
|
||||
var sum = 0d;
|
||||
var count = 0;
|
||||
for (var y = 0; y < 200; y++)
|
||||
{
|
||||
for (var x = 0; x < 200; x++)
|
||||
{
|
||||
var (_, _, red, _) = LightTransform.ToBytes(value, 0f, 0f, 1f, 1f, options, x, y);
|
||||
Assert.InRange(red, 100, 101);
|
||||
sum += red;
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.Equal(100.3, sum / count, 0.02);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ADitheredBlackAndWhiteAreUnchanged()
|
||||
{
|
||||
var options = new LightOptions(false, true, 0f, 0f);
|
||||
for (var y = 0; y < 100; y++)
|
||||
{
|
||||
for (var x = 0; x < 100; x++)
|
||||
{
|
||||
Assert.Equal(((byte)0, (byte)0, (byte)0, (byte)255), LightTransform.ToBytes(0f, 0f, 0f, 1f, 1f, options, x, y));
|
||||
Assert.Equal(((byte)255, (byte)255, (byte)255, (byte)255), LightTransform.ToBytes(1f, 1f, 1f, 1f, 1f, options, x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ALinearWhiteStaysWhiteWhenDithered()
|
||||
{
|
||||
var options = new LightOptions(true, true, 0f, 0f);
|
||||
for (var y = 0; y < 100; y++)
|
||||
{
|
||||
for (var x = 0; x < 100; x++)
|
||||
Assert.Equal(((byte)255, (byte)255, (byte)255, (byte)255), LightTransform.ToBytes(1f, 1f, 1f, 1f, 1f, options, x, y));
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(float.NaN, 0f)]
|
||||
[InlineData(-0.1f, 0f)]
|
||||
[InlineData(1.1f, 0f)]
|
||||
[InlineData(0.5f, float.NaN)]
|
||||
[InlineData(0.5f, -1f)]
|
||||
[InlineData(0.5f, 1001f)]
|
||||
public void InvalidOptionsAreRejected(float threshold, float boost)
|
||||
{
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => new LightOptions(true, false, threshold, boost).Validate());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheDefaultOptionsAreValidAndDefault()
|
||||
{
|
||||
var options = default(LightOptions);
|
||||
|
||||
options.Validate();
|
||||
Assert.True(options.IsDefault);
|
||||
Assert.False(options.Highlights);
|
||||
Assert.False(new LightOptions(true, false, 0f, 0f).IsDefault);
|
||||
Assert.False(new LightOptions(false, true, 0f, 0f).IsDefault);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ADitheredFullValueNeverWrapsAroundWhateverTheThreshold()
|
||||
{
|
||||
var options = new LightOptions(false, true, 0f, 0f);
|
||||
var nearOne = 0;
|
||||
for (var y = 0; y < 2048; y++)
|
||||
{
|
||||
for (var x = 0; x < 2048; x++)
|
||||
{
|
||||
if (LightTransform.DitherThreshold(x, y) < 0.99999f)
|
||||
continue;
|
||||
|
||||
nearOne++;
|
||||
var (_, _, red, alpha) = LightTransform.ToBytes(1f, 1f, 1f, 1f, 1f, options, x, y);
|
||||
Assert.Equal(((byte)255, (byte)255), (red, alpha));
|
||||
}
|
||||
}
|
||||
|
||||
Assert.True(nearOne > 10, $"{nearOne}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EncodeStaysWithinAMillionthOfTheStandardCurve()
|
||||
{
|
||||
var first = BitConverter.SingleToInt32Bits(0.0031308f) - 1000;
|
||||
var last = BitConverter.SingleToInt32Bits(1f);
|
||||
var worst = 0d;
|
||||
for (var bits = first; bits <= last; bits += 331)
|
||||
{
|
||||
var linear = BitConverter.Int32BitsToSingle(bits);
|
||||
var expected = ReferenceEncode(linear);
|
||||
|
||||
worst = Math.Max(worst, Math.Abs(LightTransform.Encode(linear) - expected) / expected);
|
||||
}
|
||||
|
||||
Assert.InRange(worst, 0d, 1e-6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DecodeStaysWithinAMillionthOfTheStandardCurve()
|
||||
{
|
||||
var first = BitConverter.SingleToInt32Bits(0.04045f) + 1;
|
||||
var last = BitConverter.SingleToInt32Bits(1f) - 1;
|
||||
var worst = 0d;
|
||||
for (var bits = first; bits <= last; bits += 331)
|
||||
{
|
||||
var encoded = BitConverter.Int32BitsToSingle(bits);
|
||||
var expected = ReferenceDecode(encoded);
|
||||
|
||||
worst = Math.Max(worst, Math.Abs(LightTransform.Decode(encoded) - expected) / expected);
|
||||
}
|
||||
|
||||
Assert.InRange(worst, 0d, 1e-6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EncodeIsExactAtTheJointsOfItsTable()
|
||||
{
|
||||
for (var exponent = -8; exponent < 0; exponent++)
|
||||
{
|
||||
for (var step = 0; step < 256; step += 17)
|
||||
{
|
||||
var linear = (float)(Math.Pow(2d, exponent) * (1d + step / 256d));
|
||||
if (linear <= 0.0031308f)
|
||||
continue;
|
||||
|
||||
Assert.Equal(ReferenceEncode(linear), LightTransform.Encode(linear), 1e-6);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EncodeHandlesTheValuesOutsideTheCurve()
|
||||
{
|
||||
Assert.True(float.IsNaN(LightTransform.Encode(float.NaN)));
|
||||
Assert.Equal(1f, LightTransform.Encode(float.PositiveInfinity));
|
||||
Assert.Equal(1f, LightTransform.Encode(1.0000001f));
|
||||
Assert.Equal(-12.92f, LightTransform.Encode(-1f));
|
||||
Assert.Equal(0.0031308f * 12.92f, LightTransform.Encode(0.0031308f));
|
||||
Assert.Equal(ReferenceEncode(0.0031309f), LightTransform.Encode(0.0031309f), 1e-6);
|
||||
Assert.Equal(ReferenceEncode(0.99999994f), LightTransform.Encode(0.99999994f), 1e-6);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false, false, 1f)]
|
||||
[InlineData(true, false, 1f)]
|
||||
[InlineData(true, false, 2.5f)]
|
||||
[InlineData(true, false, 0f)]
|
||||
[InlineData(false, true, 1.7f)]
|
||||
[InlineData(true, true, 1f)]
|
||||
[InlineData(true, true, 400f)]
|
||||
public void TheVectorConversionReturnsTheBytesOfTheScalarOne(bool linear, bool dither, float gain)
|
||||
{
|
||||
float[] specials =
|
||||
[
|
||||
0f, -0f, 0.5f / 255f, 1f, 1.5f, -0.5f, float.NaN, float.PositiveInfinity, float.NegativeInfinity, 1e-30f,
|
||||
0.0031308f, 0.0031309f, 0.9999999f, 0.25f, 0.5f,
|
||||
];
|
||||
var options = new LightOptions(linear, dither, 0f, 0f);
|
||||
var random = new Random(97);
|
||||
float Pick() => random.Next(4) switch
|
||||
{
|
||||
0 => specials[random.Next(specials.Length)],
|
||||
_ => (float)(random.NextDouble() * 1.3),
|
||||
};
|
||||
|
||||
for (var index = 0; index < 150_000; index++)
|
||||
{
|
||||
var alpha = Pick();
|
||||
var scale = random.Next(3) == 0 ? 1f : (float)random.NextDouble();
|
||||
var red = random.Next(3) == 0 ? Pick() : alpha * scale * (float)random.NextDouble();
|
||||
var green = random.Next(3) == 0 ? Pick() : alpha * scale * (float)random.NextDouble();
|
||||
var blue = random.Next(3) == 0 ? Pick() : alpha * scale * (float)random.NextDouble();
|
||||
var x = random.Next(-100, 5000);
|
||||
var y = random.Next(-100, 5000);
|
||||
|
||||
var expected = LightTransform.ToBytes(red, green, blue, alpha, gain, options, x, y);
|
||||
var packed = LightTransform.ToPacked(Vector128.Create(red, green, blue, alpha), gain, options, x, y);
|
||||
|
||||
Assert.Equal(
|
||||
(expected.Blue, expected.Green, expected.Red, expected.Alpha),
|
||||
((byte)packed, (byte)(packed >> 8), (byte)(packed >> 16), (byte)(packed >> 24)));
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false, true, 1f)]
|
||||
[InlineData(false, true, 3f)]
|
||||
[InlineData(true, true, 1f)]
|
||||
[InlineData(true, true, 2f)]
|
||||
[InlineData(true, false, 1f)]
|
||||
public void AColorNeverExceedsItsOpacityEvenWhenDithered(bool linear, bool dither, float gain)
|
||||
{
|
||||
var options = new LightOptions(linear, dither, 0f, 0f);
|
||||
var random = new Random(31);
|
||||
for (var index = 0; index < 100_000; index++)
|
||||
{
|
||||
var alpha = (float)random.NextDouble();
|
||||
var red = random.Next(3) == 0 ? alpha : alpha * (float)random.NextDouble();
|
||||
var green = random.Next(3) == 0 ? alpha : alpha * (float)random.NextDouble();
|
||||
var blue = random.Next(3) == 0 ? alpha : alpha * (float)random.NextDouble();
|
||||
var x = random.Next(0, 4000);
|
||||
var y = random.Next(0, 4000);
|
||||
|
||||
var expected = LightTransform.ToBytes(red, green, blue, alpha, gain, options, x, y);
|
||||
|
||||
Assert.InRange(expected.Red, 0, expected.Alpha);
|
||||
Assert.InRange(expected.Green, 0, expected.Alpha);
|
||||
Assert.InRange(expected.Blue, 0, expected.Alpha);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ATranslucentWhiteStaysPremultipliedWhenDithered()
|
||||
{
|
||||
var options = new LightOptions(false, true, 0f, 0f);
|
||||
for (var y = 0; y < 100; y++)
|
||||
{
|
||||
for (var x = 0; x < 100; x++)
|
||||
{
|
||||
var (blue, green, red, alpha) = LightTransform.ToBytes(127.5f / 255f, 127.5f / 255f, 127.5f / 255f, 127.5f / 255f, 1f, options, x, y);
|
||||
|
||||
Assert.InRange(red, 0, alpha);
|
||||
Assert.InRange(green, 0, alpha);
|
||||
Assert.InRange(blue, 0, alpha);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0)]
|
||||
[InlineData(1)]
|
||||
[InlineData(2)]
|
||||
public void HighlightsFollowTheBrightestChannelWhicheverItIs(int brightest)
|
||||
{
|
||||
var options = new LightOptions(true, false, 0.5f, 10f);
|
||||
byte[] channels = [40, 40, 40];
|
||||
channels[brightest] = 230;
|
||||
|
||||
var raised = LightTransform.FromBytes(channels[0], channels[1], channels[2], 255, options);
|
||||
|
||||
var excess = (230 / 255d - 0.5) / 0.5;
|
||||
Assert.Equal(1d + 9d * excess * excess, raised.Alpha, 1e-4);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HighlightsLeaveADarkPixelFarBelowTheThresholdAlone()
|
||||
{
|
||||
var options = new LightOptions(true, false, 0.9f, 100f);
|
||||
|
||||
var raised = LightTransform.FromBytes(30, 30, 30, 255, options);
|
||||
|
||||
Assert.Equal(LightTransform.FromBytes(30, 30, 30, 255, Linear), raised);
|
||||
Assert.Equal(1f, raised.Alpha);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheDitherThresholdFollowsTheDocumentedHash()
|
||||
{
|
||||
static float Documented(int x, int y)
|
||||
{
|
||||
var h = unchecked((uint)x * 0x9E3779B1u ^ (uint)y * 0x85EBCA77u);
|
||||
h ^= h >> 16;
|
||||
h = unchecked(h * 0x7FEB352Du);
|
||||
h ^= h >> 15;
|
||||
h = unchecked(h * 0x846CA68Bu);
|
||||
h ^= h >> 16;
|
||||
return (h >> 8) / 16777216f;
|
||||
}
|
||||
|
||||
Assert.Equal(0f, LightTransform.DitherThreshold(0, 0));
|
||||
for (var y = -40; y < 300; y += 7)
|
||||
{
|
||||
for (var x = -40; x < 300; x += 3)
|
||||
Assert.Equal(Documented(x, y), LightTransform.DitherThreshold(x, y));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AThresholdOfOneIsValidButRaisesNothing()
|
||||
{
|
||||
var options = new LightOptions(true, false, 1f, 5f);
|
||||
|
||||
options.Validate();
|
||||
|
||||
Assert.False(options.Highlights);
|
||||
new LightOptions(true, false, 0f, 5f).Validate();
|
||||
new LightOptions(true, false, 0.5f, LightOptions.MaximumBoost).Validate();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
public sealed class ScratchPoolTests
|
||||
{
|
||||
[Fact]
|
||||
public void AReturnedItemIsHandedOutAgain()
|
||||
{
|
||||
var pool = new ScratchPool<Item>(2);
|
||||
Item first;
|
||||
using (var lease = pool.Rent())
|
||||
first = lease.Value;
|
||||
|
||||
using var again = pool.Rent();
|
||||
|
||||
Assert.Same(first, again.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ItemsRentedAtTheSameTimeAreDistinct()
|
||||
{
|
||||
var pool = new ScratchPool<Item>(2);
|
||||
using (pool.Rent())
|
||||
{
|
||||
}
|
||||
|
||||
using var first = pool.Rent();
|
||||
using var second = pool.Rent();
|
||||
|
||||
Assert.NotSame(first.Value, second.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnItemReturnedBeyondTheCapacityIsDropped()
|
||||
{
|
||||
var pool = new ScratchPool<Item>(1);
|
||||
var first = pool.Rent();
|
||||
var second = pool.Rent();
|
||||
var kept = first.Value;
|
||||
var dropped = second.Value;
|
||||
first.Dispose();
|
||||
second.Dispose();
|
||||
|
||||
using var rentedKept = pool.Rent();
|
||||
using var rentedNew = pool.Rent();
|
||||
|
||||
Assert.Same(kept, rentedKept.Value);
|
||||
Assert.NotSame(kept, rentedNew.Value);
|
||||
Assert.NotSame(dropped, rentedNew.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ARentedItemIsNeverSharedBetweenThreads()
|
||||
{
|
||||
var pool = new ScratchPool<Item>(Environment.ProcessorCount);
|
||||
var collisions = 0;
|
||||
|
||||
Parallel.For(0, 8, new ParallelOptions { MaxDegreeOfParallelism = 8 }, _ =>
|
||||
{
|
||||
for (var round = 0; round < 20000; round++)
|
||||
{
|
||||
using var lease = pool.Rent();
|
||||
if (Interlocked.Exchange(ref lease.Value.Busy, 1) != 0)
|
||||
Interlocked.Increment(ref collisions);
|
||||
Thread.SpinWait(20);
|
||||
Volatile.Write(ref lease.Value.Busy, 0);
|
||||
}
|
||||
});
|
||||
|
||||
Assert.Equal(0, collisions);
|
||||
}
|
||||
|
||||
sealed class Item
|
||||
{
|
||||
public int Busy;
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,9 @@ public sealed class SpectralSelfTestTests
|
||||
Assert.All(measurements, measurement => Assert.True(measurement.Passes, $"{measurement}"));
|
||||
Assert.Equal(2, measurements.Count(measurement => measurement.Name == SpectralSelfTest.DeterminismName));
|
||||
Assert.Equal(2, measurements.Count(measurement => measurement.Name == SpectralSelfTest.FullName));
|
||||
Assert.All(measurements.Where(measurement => measurement.Name == SpectralSelfTest.DeterminismName), measurement => Assert.Equal(0d, measurement.Measured));
|
||||
Assert.Equal(2, measurements.Count(measurement => measurement.Name == SpectralSelfTest.ChromaticDeterminismName));
|
||||
Assert.Equal(2, measurements.Count(measurement => measurement.Name == SpectralSelfTest.ChromaticFullName));
|
||||
Assert.All(measurements.Where(measurement => measurement.Name is SpectralSelfTest.DeterminismName or SpectralSelfTest.ChromaticDeterminismName), measurement => Assert.Equal(0d, measurement.Measured));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -58,6 +60,19 @@ public sealed class SpectralSelfTestTests
|
||||
Assert.NotEqual(pattern, SpectralSelfTest.Pattern(200, 150, 8));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheChromaticKernelsArePositiveAndDifferPerChannel()
|
||||
{
|
||||
var red = SpectralSelfTest.ChromaticKernel(5, ChromaticChannel.Red);
|
||||
var green = SpectralSelfTest.ChromaticKernel(5, ChromaticChannel.Green);
|
||||
var blue = SpectralSelfTest.ChromaticKernel(5, ChromaticChannel.Blue);
|
||||
|
||||
Assert.All(red.Concat(green).Concat(blue), value => Assert.True(value > 0d));
|
||||
Assert.NotEqual(red, green);
|
||||
Assert.NotEqual(blue, green);
|
||||
Assert.NotEqual(red, blue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheKernelIsPositiveAndAsymmetric()
|
||||
{
|
||||
|
||||
@@ -145,4 +145,52 @@ public sealed class TilePlanTests
|
||||
Assert.Equal(expected, plan.GroupsPerTile);
|
||||
Assert.Equal(plan.TileCount * expected, plan.GroupCount);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(64, 6)]
|
||||
[InlineData(128, 7)]
|
||||
[InlineData(256, 8)]
|
||||
[InlineData(512, 9)]
|
||||
public void TheLogarithmOfASupportedSizeIsItsExponent(int size, int expected)
|
||||
{
|
||||
Assert.Equal(expected, TilePlan.Log2Of(size));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(32)]
|
||||
[InlineData(96)]
|
||||
[InlineData(1024)]
|
||||
public void TheLogarithmOfAnUnsupportedSizeIsRejected(int size)
|
||||
{
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => TilePlan.Log2Of(size));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AKernelThatDoesNotFitTheTileIsRejected()
|
||||
{
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => TilePlan.ValidateKernel(64, 32));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => TilePlan.ValidateKernel(63, 1));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => TilePlan.ValidateKernel(64, -1));
|
||||
TilePlan.ValidateKernel(64, 31);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheShadersHoldTwoValuesPerThreadInEveryGroup()
|
||||
{
|
||||
Assert.Equal(2, TilePlan.ValuesPerThread);
|
||||
Assert.Equal(TilePlan.GroupElements, TilePlan.GroupThreads * 2);
|
||||
Assert.Equal(TilePlan.GroupElements, 1 << TilePlan.GroupElementsLog2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheChromaticGroupHoldsFourValuesPerThread()
|
||||
{
|
||||
Assert.Equal(4, TilePlan.ChromaticGroupElements / TilePlan.GroupThreads);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AGroupHoldsAtLeastOneColumnOfTheLargestTile()
|
||||
{
|
||||
Assert.True(TilePlan.MaximumSize <= TilePlan.GroupElements);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
public sealed class TileShaderMathTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(64, 3, 100, 100)]
|
||||
[InlineData(128, 5, 300, 200)]
|
||||
[InlineData(512, 40, 1920, 1080)]
|
||||
public void TheTileOriginIsTheValidOriginMinusTheRadius(int size, int radius, int width, int height)
|
||||
{
|
||||
var plan = TilePlan.Create(size, radius, 7, 11, width, height);
|
||||
|
||||
for (var tile = 0; tile < plan.TileCount; tile++)
|
||||
{
|
||||
var origin = TileShaderMath.TileOrigin(tile, plan.TilesX, plan.ValidSize, plan.Radius);
|
||||
|
||||
Assert.Equal(plan.OriginX(tile) - plan.RegionX - plan.Radius, origin.X);
|
||||
Assert.Equal(plan.OriginY(tile) - plan.RegionY - plan.Radius, origin.Y);
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(64, 0)]
|
||||
[InlineData(128, 3)]
|
||||
[InlineData(512, 9)]
|
||||
public void TheTileIndexAddsTheGroupOffsetToTheBatchStart(int size, int batchStart)
|
||||
{
|
||||
var plan = TilePlan.Create(size, 1, 0, 0, 300, 300);
|
||||
|
||||
for (var tile = 0; tile < plan.TileCount; tile++)
|
||||
Assert.Equal(batchStart + tile, TileShaderMath.TileIndex(batchStart, tile * plan.TileElements, plan.Log2Size));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
public sealed class WorkerPoolTests
|
||||
{
|
||||
sealed class CountingJob(int items) : IParallelJob
|
||||
{
|
||||
public readonly int[] Runs = new int[items];
|
||||
public readonly HashSet<int> Workers = [];
|
||||
public readonly int[] BeginCounts = new int[16];
|
||||
public int Delay;
|
||||
|
||||
public IEnumerable<int> Begun => Enumerable.Range(0, BeginCounts.Length).Where(worker => BeginCounts[worker] > 0);
|
||||
|
||||
public void Begin(int worker) => Interlocked.Increment(ref BeginCounts[worker]);
|
||||
|
||||
public void Execute(int index, int worker)
|
||||
{
|
||||
Interlocked.Increment(ref Runs[index]);
|
||||
lock (Workers)
|
||||
Workers.Add(worker);
|
||||
if (Delay > 0)
|
||||
Thread.Sleep(Delay);
|
||||
}
|
||||
}
|
||||
|
||||
sealed class FailingJob(int failing) : IParallelJob
|
||||
{
|
||||
public int Completed;
|
||||
|
||||
public void Execute(int index, int worker)
|
||||
{
|
||||
if (index == failing)
|
||||
throw new InvalidOperationException();
|
||||
Interlocked.Increment(ref Completed);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheCallerAndTheHelpersAreAtLeastOneWorker()
|
||||
{
|
||||
Assert.InRange(WorkerPool.Shared.Parallelism, 1, WorkerPool.MaximumHelpers + 1);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1)]
|
||||
[InlineData(2)]
|
||||
[InlineData(15)]
|
||||
[InlineData(1000)]
|
||||
public void EveryItemRunsExactlyOnceOnAWorkerWithinRange(int items)
|
||||
{
|
||||
var job = new CountingJob(items);
|
||||
|
||||
WorkerPool.Shared.Run(job, items);
|
||||
|
||||
Assert.All(job.Runs, runs => Assert.Equal(1, runs));
|
||||
Assert.All(job.Workers, worker => Assert.InRange(worker, 0, WorkerPool.Shared.Parallelism - 1));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0)]
|
||||
[InlineData(-3)]
|
||||
public void NothingRunsWithoutItems(int items)
|
||||
{
|
||||
var job = new CountingJob(4);
|
||||
|
||||
WorkerPool.Shared.Run(job, items);
|
||||
|
||||
Assert.All(job.Runs, runs => Assert.Equal(0, runs));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SlowItemsAreSharedAmongTheWorkers()
|
||||
{
|
||||
if (WorkerPool.Shared.Parallelism == 1)
|
||||
return;
|
||||
var job = new CountingJob(48) { Delay = 4 };
|
||||
|
||||
WorkerPool.Shared.Run(job, 48);
|
||||
|
||||
Assert.True(job.Workers.Count > 1, $"{job.Workers.Count}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnExceptionInAnItemIsRethrownToTheCallerAndThePoolStaysUsable()
|
||||
{
|
||||
var failing = new FailingJob(7);
|
||||
|
||||
Assert.Throws<InvalidOperationException>(() => WorkerPool.Shared.Run(failing, 20));
|
||||
|
||||
var job = new CountingJob(20);
|
||||
WorkerPool.Shared.Run(job, 20);
|
||||
Assert.All(job.Runs, runs => Assert.Equal(1, runs));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CallersFromSeveralThreadsEachGetTheirItemsRun()
|
||||
{
|
||||
var jobs = Enumerable.Range(0, 4).Select(_ => new CountingJob(200)).ToArray();
|
||||
|
||||
Parallel.ForEach(jobs, new ParallelOptions { MaxDegreeOfParallelism = 4 }, job => WorkerPool.Shared.Run(job, 200));
|
||||
|
||||
Assert.All(jobs, job => Assert.All(job.Runs, runs => Assert.Equal(1, runs)));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1)]
|
||||
[InlineData(2)]
|
||||
[InlineData(3)]
|
||||
public void AParallelismLimitKeepsTheWorkerNumbersBelowTheLimit(int limit)
|
||||
{
|
||||
using var pool = new WorkerPool(5);
|
||||
var job = new CountingJob(200) { Delay = 1 };
|
||||
|
||||
pool.Run(job, 200, limit);
|
||||
|
||||
Assert.All(job.Runs, runs => Assert.Equal(1, runs));
|
||||
Assert.All(job.Workers, worker => Assert.InRange(worker, 0, limit - 1));
|
||||
Assert.Equal(Enumerable.Range(0, limit), job.Begun);
|
||||
Assert.All(job.BeginCounts, count => Assert.InRange(count, 0, 1));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EachWorkerBeginsOnceBeforeItTakesItems()
|
||||
{
|
||||
using var pool = new WorkerPool(3);
|
||||
var job = new CountingJob(64) { Delay = 1 };
|
||||
|
||||
pool.Run(job, 64);
|
||||
|
||||
Assert.Equal(Enumerable.Range(0, pool.Parallelism), job.Begun);
|
||||
Assert.All(job.BeginCounts, count => Assert.InRange(count, 0, 1));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void APoolWithoutHelpersRunsEveryItemOnTheCaller()
|
||||
{
|
||||
using var pool = new WorkerPool(0);
|
||||
var job = new CountingJob(10);
|
||||
|
||||
pool.Run(job, 10);
|
||||
|
||||
Assert.Equal(1, pool.Parallelism);
|
||||
Assert.All(job.Runs, runs => Assert.Equal(1, runs));
|
||||
Assert.Equal([0], job.Workers);
|
||||
Assert.Equal([0], job.Begun);
|
||||
Assert.Equal(1, job.BeginCounts[0]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ADisposedPoolRefusesToRun()
|
||||
{
|
||||
var pool = new WorkerPool(2);
|
||||
pool.Run(new CountingJob(8), 8);
|
||||
|
||||
pool.Dispose();
|
||||
pool.Dispose();
|
||||
|
||||
Assert.Throws<ObjectDisposedException>(() => pool.Run(new CountingJob(8), 8));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ARunNeedsAtLeastOneWorker()
|
||||
{
|
||||
using var pool = new WorkerPool(1);
|
||||
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => pool.Run(new CountingJob(4), 4, 0));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => new WorkerPool(-1));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AWarmRunAllocatesNothingOnTheCallingThread()
|
||||
{
|
||||
var job = new CountingJob(32);
|
||||
WorkerPool.Shared.Run(job, 32);
|
||||
WorkerPool.Shared.Run(job, 32);
|
||||
|
||||
Assert.Equal(0L, AllocationProbe.MinimumAllocatedBytes(() => WorkerPool.Shared.Run(job, 32), 20));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using ComputeWeave;
|
||||
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal static class ByteColor
|
||||
{
|
||||
public const int Channels = 4;
|
||||
public const int Bits = 8;
|
||||
public const int Levels = 1 << Bits;
|
||||
public const int Maximum = Levels - 1;
|
||||
public const uint Mask = Maximum;
|
||||
public const float Scale = Maximum;
|
||||
public const double ScaleDouble = Maximum;
|
||||
public const float Rounding = 0.5f;
|
||||
|
||||
public static uint ToLevel(float value) => (uint)(value * Scale + Rounding);
|
||||
|
||||
public static uint Channel(uint packed, int index) => packed >> (index * Bits) & Mask;
|
||||
|
||||
public static uint Pack(Float4 value)
|
||||
=> ToLevel(value.X) | (ToLevel(value.Y) << Bits) | (ToLevel(value.Z) << (2 * Bits)) | (ToLevel(value.W) << (3 * Bits));
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
using ComputeWeave;
|
||||
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal sealed class ChromaticKernelSpectrum
|
||||
{
|
||||
public const int ChannelCount = 3;
|
||||
|
||||
readonly KernelSpectrum red = new(SpectrumPlane.Half);
|
||||
readonly KernelSpectrum green = new(SpectrumPlane.Half);
|
||||
readonly KernelSpectrum blue = new(SpectrumPlane.Half);
|
||||
readonly UpdateJob updates = new();
|
||||
bool ready;
|
||||
|
||||
public KernelSpectrum Red => red;
|
||||
|
||||
public KernelSpectrum Green => green;
|
||||
|
||||
public KernelSpectrum Blue => blue;
|
||||
|
||||
public int Size => ready ? green.Size : 0;
|
||||
|
||||
public int Radius => Size == 0 ? 0 : green.Radius;
|
||||
|
||||
public int HalfColumns => HalfColumnsOf(Size);
|
||||
|
||||
public static int HalfColumnsOf(int size) => KernelSpectrum.HalfColumnsOf(size);
|
||||
|
||||
public ReadOnlySpan<Float2> Twiddles => green.Twiddles;
|
||||
|
||||
public void Update(ReadOnlyMemory<double> redValues, ReadOnlyMemory<double> greenValues, ReadOnlyMemory<double> blueValues, int radius, int size)
|
||||
{
|
||||
ready = false;
|
||||
updates.Prepare(red, green, blue, redValues, greenValues, blueValues, radius, size);
|
||||
WorkerPool.Shared.Run(updates, ChannelCount);
|
||||
ready = true;
|
||||
}
|
||||
|
||||
public ReadOnlySpan<Float2> HalfSpectrum(ChromaticChannel channel)
|
||||
{
|
||||
var size = Size;
|
||||
if (size == 0)
|
||||
return default;
|
||||
|
||||
return channel switch
|
||||
{
|
||||
ChromaticChannel.Red => red.Spectrum,
|
||||
ChromaticChannel.Green => green.Spectrum,
|
||||
ChromaticChannel.Blue => blue.Spectrum,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(channel)),
|
||||
};
|
||||
}
|
||||
|
||||
public void CopyHalfSpectra(Span<Float2> destination)
|
||||
{
|
||||
var length = HalfColumns * Size;
|
||||
if (Size == 0 || destination.Length < ChannelCount * length)
|
||||
throw new ArgumentException(null, nameof(destination));
|
||||
|
||||
for (var channel = 0; channel < ChannelCount; channel++)
|
||||
HalfSpectrum((ChromaticChannel)channel).CopyTo(destination.Slice(channel * length, length));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
internal sealed class UpdateJob : IParallelJob
|
||||
{
|
||||
readonly KernelSpectrum[] spectra = new KernelSpectrum[ChromaticKernelSpectrum.ChannelCount];
|
||||
readonly ReadOnlyMemory<double>[] values = new ReadOnlyMemory<double>[ChromaticKernelSpectrum.ChannelCount];
|
||||
int radius;
|
||||
int size;
|
||||
|
||||
public void Prepare(KernelSpectrum red, KernelSpectrum green, KernelSpectrum blue, ReadOnlyMemory<double> redValues, ReadOnlyMemory<double> greenValues, ReadOnlyMemory<double> blueValues, int kernelRadius, int spectrumSize)
|
||||
{
|
||||
spectra[0] = red;
|
||||
spectra[1] = green;
|
||||
spectra[2] = blue;
|
||||
values[0] = redValues;
|
||||
values[1] = greenValues;
|
||||
values[2] = blueValues;
|
||||
radius = kernelRadius;
|
||||
size = spectrumSize;
|
||||
}
|
||||
|
||||
public void Execute(int index, int worker) => spectra[index].Update(values[index].Span, radius, size);
|
||||
}
|
||||
|
||||
internal static class ChromaticChannels
|
||||
{
|
||||
public const int Red = 0;
|
||||
public const int Green = 1;
|
||||
public const int Blue = 2;
|
||||
}
|
||||
|
||||
internal enum ChromaticChannel
|
||||
{
|
||||
Red = ChromaticChannels.Red,
|
||||
Green = ChromaticChannels.Green,
|
||||
Blue = ChromaticChannels.Blue,
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal sealed class ComplexLines
|
||||
{
|
||||
public const int PageBytes = 4096;
|
||||
public const int StaggerBytes = PageBytes * 3 / 8;
|
||||
public const int MinimumSeparation = 64;
|
||||
|
||||
const int Period = PageBytes / sizeof(double);
|
||||
const int Offset = StaggerBytes / sizeof(double);
|
||||
|
||||
double[] storage = [];
|
||||
int length;
|
||||
int separation;
|
||||
|
||||
public Span<double> Real => storage.AsSpan(0, length);
|
||||
|
||||
public Span<double> Imaginary => storage.AsSpan(length + separation, length);
|
||||
|
||||
public void Ensure(int count)
|
||||
{
|
||||
if (length >= count)
|
||||
return;
|
||||
|
||||
length = count;
|
||||
separation = (Offset - count % Period + Period) % Period;
|
||||
if (separation < MinimumSeparation)
|
||||
separation += Period;
|
||||
storage = new double[count * 2 + separation];
|
||||
}
|
||||
}
|
||||
@@ -36,26 +36,40 @@ internal static class ConvolutionBound
|
||||
|
||||
public static double SpectrumError(int size)
|
||||
{
|
||||
var plan = TilePlan.Create(size, 0, 0, 0, 1, 1);
|
||||
var transform = Transform(2 * plan.Log2Size, DoubleRounding, DoubleTwiddleError) * size;
|
||||
var transform = Transform(2 * TilePlan.Log2Of(size), DoubleRounding, DoubleTwiddleError) * size;
|
||||
return SingleRounding * (1d + transform) + transform + Math.Sqrt(2d) * SmallestNormal;
|
||||
}
|
||||
|
||||
public static double Relative(int size, double operationError)
|
||||
{
|
||||
var plan = TilePlan.Create(size, 0, 0, 0, 1, 1);
|
||||
var multiplication = ComplexMultiplication(operationError);
|
||||
var transform = Transform(2 * plan.Log2Size, operationError, SingleTwiddleError);
|
||||
var transform = Transform(2 * TilePlan.Log2Of(size), operationError, SingleTwiddleError);
|
||||
var spectrum = SpectrumError(size);
|
||||
var product = transform * (1d + spectrum) * (1d + multiplication) + spectrum * (1d + multiplication) + multiplication;
|
||||
var convolution = product + transform * (1d + product);
|
||||
return convolution + SingleRounding * (1d + convolution);
|
||||
}
|
||||
|
||||
public static double ChromaticRelative(int size, double operationError)
|
||||
{
|
||||
var relative = Relative(size, operationError);
|
||||
var splitAndMerge = 2d * Math.Sqrt(2d) * operationError;
|
||||
return relative + splitAndMerge * (1d + relative);
|
||||
}
|
||||
|
||||
public static int ChromaticFlushedOperations(int size)
|
||||
=> FlushedOperations(size) + (int)Math.Ceiling(16d * Math.Sqrt(2d) * size);
|
||||
|
||||
public static double ChromaticAbsolute(int size, double operationError, double norm)
|
||||
{
|
||||
if (!double.IsFinite(norm) || norm < 0d)
|
||||
throw new ArgumentOutOfRangeException(nameof(norm));
|
||||
return ChromaticRelative(size, operationError) * norm + ChromaticFlushedOperations(size) * SmallestNormal;
|
||||
}
|
||||
|
||||
public static int FlushedOperations(int size)
|
||||
{
|
||||
var plan = TilePlan.Create(size, 0, 0, 0, 1, 1);
|
||||
return (int)Math.Ceiling(2d * (4 * plan.Log2Size + 2) * 4d * Math.Sqrt(2d) * size);
|
||||
return (int)Math.Ceiling(2d * (4 * TilePlan.Log2Of(size) + 2) * 4d * Math.Sqrt(2d) * size);
|
||||
}
|
||||
|
||||
public static double Absolute(int size, double operationError, double norm)
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Intrinsics;
|
||||
using ComputeWeave;
|
||||
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal static class CpuFft
|
||||
{
|
||||
const int Channels = ByteColor.Channels;
|
||||
const int UIntBits = sizeof(uint) * 8;
|
||||
const int StagesPerPass = 2;
|
||||
|
||||
internal static void FillReversal(Span<int> order, int log2)
|
||||
{
|
||||
var shift = UIntBits - log2;
|
||||
for (var index = 0; index < order.Length; index++)
|
||||
order[index] = (int)(ReverseBits((uint)index) >> shift);
|
||||
}
|
||||
|
||||
internal static void Butterflies(Span<float> line, int log2, ReadOnlySpan<Float2> twiddles, float direction, bool allowWide = true)
|
||||
{
|
||||
var size = 1 << log2;
|
||||
if (line.Length < size * Channels || twiddles.Length < size / 2)
|
||||
throw new ArgumentException(null, nameof(line));
|
||||
|
||||
ref var data = ref MemoryMarshal.GetReference(line);
|
||||
ref var table = ref MemoryMarshal.GetReference(twiddles);
|
||||
var wide = allowWide && Vector256.IsHardwareAccelerated;
|
||||
var stage = 0;
|
||||
if (wide && log2 >= StagesPerPass)
|
||||
{
|
||||
FirstTwoStages(ref data, ref table, size, log2, direction);
|
||||
for (stage = StagesPerPass; stage + 1 < log2; stage += StagesPerPass)
|
||||
StagePair(ref data, ref table, size, log2, stage, direction);
|
||||
}
|
||||
|
||||
for (; stage < log2; stage++)
|
||||
{
|
||||
var half = 1 << stage;
|
||||
var shift = log2 - 1 - stage;
|
||||
var distance = (nuint)(half * Channels);
|
||||
if (wide && half >= 2)
|
||||
StageWithPairedTwiddles(ref data, ref table, size, half, shift, direction, distance);
|
||||
else
|
||||
StageWithSingleTwiddles(ref data, ref table, size, half, shift, direction, distance);
|
||||
}
|
||||
}
|
||||
|
||||
internal static void ButterfliesScalar(Span<float> line, int log2, ReadOnlySpan<Float2> twiddles, float direction)
|
||||
{
|
||||
var pairs = 1 << (log2 - 1);
|
||||
for (var stage = 0; stage < log2; stage++)
|
||||
{
|
||||
var half = 1 << stage;
|
||||
var shift = log2 - 1 - stage;
|
||||
for (var pair = 0; pair < pairs; pair++)
|
||||
{
|
||||
var position = pair & (half - 1);
|
||||
var even = (((pair >> stage) << (stage + 1)) + position) * Channels;
|
||||
var odd = even + half * Channels;
|
||||
var twiddle = twiddles[position << shift];
|
||||
var real = twiddle.X;
|
||||
var imaginary = twiddle.Y * direction;
|
||||
var odd0 = line[odd];
|
||||
var odd1 = line[odd + 1];
|
||||
var odd2 = line[odd + 2];
|
||||
var odd3 = line[odd + 3];
|
||||
var product0 = odd0 * real - odd1 * imaginary;
|
||||
var product1 = odd0 * imaginary + odd1 * real;
|
||||
var product2 = odd2 * real - odd3 * imaginary;
|
||||
var product3 = odd2 * imaginary + odd3 * real;
|
||||
var even0 = line[even];
|
||||
var even1 = line[even + 1];
|
||||
var even2 = line[even + 2];
|
||||
var even3 = line[even + 3];
|
||||
line[even] = even0 + product0;
|
||||
line[even + 1] = even1 + product1;
|
||||
line[even + 2] = even2 + product2;
|
||||
line[even + 3] = even3 + product3;
|
||||
line[odd] = even0 - product0;
|
||||
line[odd + 1] = even1 - product1;
|
||||
line[odd + 2] = even2 - product2;
|
||||
line[odd + 3] = even3 - product3;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal static Vector128<float> Rotate(Vector128<float> value, Vector128<float> real, Vector128<float> imaginary)
|
||||
=> value * real + Vector128.Shuffle(value, Vector128.Create(1, 0, 3, 2)) * imaginary;
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal static Vector256<float> Rotate(Vector256<float> value, Vector256<float> real, Vector256<float> imaginary)
|
||||
=> value * real + Vector256.Shuffle(value, Vector256.Create(1, 0, 3, 2, 5, 4, 7, 6)) * imaginary;
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal static Vector128<float> Imaginary(float value) => Vector128.Create(-value, value, -value, value);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
static void PairedTwiddles(ref Float2 table, int nearIndex, int farIndex, float direction, out Vector256<float> real, out Vector256<float> imaginary)
|
||||
{
|
||||
var near = Unsafe.Add(ref table, nearIndex);
|
||||
var far = Unsafe.Add(ref table, farIndex);
|
||||
var nearImaginary = near.Y * direction;
|
||||
var farImaginary = far.Y * direction;
|
||||
real = Vector256.Create(near.X, near.X, near.X, near.X, far.X, far.X, far.X, far.X);
|
||||
imaginary = Vector256.Create(-nearImaginary, nearImaginary, -nearImaginary, nearImaginary, -farImaginary, farImaginary, -farImaginary, farImaginary);
|
||||
}
|
||||
|
||||
static void FirstTwoStages(ref float data, ref Float2 table, int size, int log2, float direction)
|
||||
{
|
||||
var first = Unsafe.Add(ref table, 0);
|
||||
var second = Unsafe.Add(ref table, 1 << (log2 - 2));
|
||||
var firstReal = Vector128.Create(first.X);
|
||||
var firstImaginary = Imaginary(first.Y * direction);
|
||||
var secondReal = Vector128.Create(second.X);
|
||||
var secondImaginary = Imaginary(second.Y * direction);
|
||||
for (var block = 0; block < size; block += 4)
|
||||
{
|
||||
var start = (nuint)(block * Channels);
|
||||
var value0 = Vector128.LoadUnsafe(ref data, start);
|
||||
var value1 = Vector128.LoadUnsafe(ref data, start + Channels);
|
||||
var value2 = Vector128.LoadUnsafe(ref data, start + Channels * 2);
|
||||
var value3 = Vector128.LoadUnsafe(ref data, start + Channels * 3);
|
||||
var product1 = Rotate(value1, firstReal, firstImaginary);
|
||||
var product3 = Rotate(value3, firstReal, firstImaginary);
|
||||
var sum0 = value0 + product1;
|
||||
var sum1 = value0 - product1;
|
||||
var sum2 = value2 + product3;
|
||||
var sum3 = value2 - product3;
|
||||
var evenProduct = Rotate(sum2, firstReal, firstImaginary);
|
||||
var oddProduct = Rotate(sum3, secondReal, secondImaginary);
|
||||
(sum0 + evenProduct).StoreUnsafe(ref data, start);
|
||||
(sum1 + oddProduct).StoreUnsafe(ref data, start + Channels);
|
||||
(sum0 - evenProduct).StoreUnsafe(ref data, start + Channels * 2);
|
||||
(sum1 - oddProduct).StoreUnsafe(ref data, start + Channels * 3);
|
||||
}
|
||||
}
|
||||
|
||||
static void StagePair(ref float data, ref Float2 table, int size, int log2, int stage, float direction)
|
||||
{
|
||||
var half = 1 << stage;
|
||||
var firstShift = log2 - 1 - stage;
|
||||
var secondShift = log2 - 2 - stage;
|
||||
var distance = (nuint)(half * Channels);
|
||||
for (var position = 0; position < half; position += 2)
|
||||
{
|
||||
PairedTwiddles(ref table, position << firstShift, (position + 1) << firstShift, direction, out var firstReal, out var firstImaginary);
|
||||
PairedTwiddles(ref table, position << secondShift, (position + 1) << secondShift, direction, out var evenReal, out var evenImaginary);
|
||||
PairedTwiddles(ref table, (position + half) << secondShift, (position + half + 1) << secondShift, direction, out var oddReal, out var oddImaginary);
|
||||
for (var block = 0; block < size; block += half * 4)
|
||||
{
|
||||
var start = (nuint)((block + position) * Channels);
|
||||
var value0 = Vector256.LoadUnsafe(ref data, start);
|
||||
var value1 = Vector256.LoadUnsafe(ref data, start + distance);
|
||||
var value2 = Vector256.LoadUnsafe(ref data, start + distance * 2);
|
||||
var value3 = Vector256.LoadUnsafe(ref data, start + distance * 3);
|
||||
var product1 = Rotate(value1, firstReal, firstImaginary);
|
||||
var product3 = Rotate(value3, firstReal, firstImaginary);
|
||||
var sum0 = value0 + product1;
|
||||
var sum1 = value0 - product1;
|
||||
var sum2 = value2 + product3;
|
||||
var sum3 = value2 - product3;
|
||||
var evenProduct = Rotate(sum2, evenReal, evenImaginary);
|
||||
var oddProduct = Rotate(sum3, oddReal, oddImaginary);
|
||||
(sum0 + evenProduct).StoreUnsafe(ref data, start);
|
||||
(sum1 + oddProduct).StoreUnsafe(ref data, start + distance);
|
||||
(sum0 - evenProduct).StoreUnsafe(ref data, start + distance * 2);
|
||||
(sum1 - oddProduct).StoreUnsafe(ref data, start + distance * 3);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void StageWithPairedTwiddles(ref float data, ref Float2 table, int size, int half, int shift, float direction, nuint distance)
|
||||
{
|
||||
for (var position = 0; position < half; position += 2)
|
||||
{
|
||||
PairedTwiddles(ref table, position << shift, (position + 1) << shift, direction, out var real, out var imaginary);
|
||||
for (var block = 0; block < size; block += half * 2)
|
||||
{
|
||||
var even = (nuint)((block + position) * Channels);
|
||||
var evenValue = Vector256.LoadUnsafe(ref data, even);
|
||||
var oddValue = Vector256.LoadUnsafe(ref data, even + distance);
|
||||
var product = Rotate(oddValue, real, imaginary);
|
||||
(evenValue + product).StoreUnsafe(ref data, even);
|
||||
(evenValue - product).StoreUnsafe(ref data, even + distance);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void StageWithSingleTwiddles(ref float data, ref Float2 table, int size, int half, int shift, float direction, nuint distance)
|
||||
{
|
||||
for (var position = 0; position < half; position++)
|
||||
{
|
||||
var twiddle = Unsafe.Add(ref table, position << shift);
|
||||
var real = Vector128.Create(twiddle.X);
|
||||
var imaginary = Imaginary(twiddle.Y * direction);
|
||||
for (var block = 0; block < size; block += half * 2)
|
||||
{
|
||||
var even = (nuint)((block + position) * Channels);
|
||||
var evenValue = Vector128.LoadUnsafe(ref data, even);
|
||||
var oddValue = Vector128.LoadUnsafe(ref data, even + distance);
|
||||
var product = Rotate(oddValue, real, imaginary);
|
||||
(evenValue + product).StoreUnsafe(ref data, even);
|
||||
(evenValue - product).StoreUnsafe(ref data, even + distance);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static uint ReverseBits(uint value)
|
||||
{
|
||||
value = ((value >> 1) & 0x55555555u) | ((value & 0x55555555u) << 1);
|
||||
value = ((value >> 2) & 0x33333333u) | ((value & 0x33333333u) << 2);
|
||||
value = ((value >> 4) & 0x0F0F0F0Fu) | ((value & 0x0F0F0F0Fu) << 4);
|
||||
value = ((value >> 8) & 0x00FF00FFu) | ((value & 0x00FF00FFu) << 8);
|
||||
return (value >> 16) | (value << 16);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Intrinsics;
|
||||
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal static class CpuPixels
|
||||
{
|
||||
const int Channels = ByteColor.Channels;
|
||||
|
||||
static readonly float[] Units = BuildUnits();
|
||||
|
||||
public static byte ToUnorm(float value)
|
||||
{
|
||||
if (float.IsNaN(value))
|
||||
return 0;
|
||||
return (byte)(Math.Clamp(value, 0f, 1f) * ByteColor.Scale + ByteColor.Rounding);
|
||||
}
|
||||
|
||||
public static bool LoadRow(Span<float> row, ReadOnlySpan<byte> pixels, ReadOnlySpan<int> order, int sourceX, int left, int first, int last, in LightOptions light)
|
||||
{
|
||||
row.Clear();
|
||||
var lit = false;
|
||||
var units = Units;
|
||||
for (var x = first; x < last; x++)
|
||||
{
|
||||
var offset = (left + x - sourceX) * Channels;
|
||||
var blue = pixels[offset];
|
||||
var green = pixels[offset + 1];
|
||||
var red = pixels[offset + 2];
|
||||
var alpha = pixels[offset + 3];
|
||||
if ((blue | green | red | alpha) == 0)
|
||||
continue;
|
||||
|
||||
var target = order[x] * Channels;
|
||||
if (light.Linear)
|
||||
{
|
||||
var (linearRed, linearGreen, linearBlue, linearAlpha) = LightTransform.FromBytes(red, green, blue, alpha, in light);
|
||||
row[target] = linearRed;
|
||||
row[target + 1] = linearGreen;
|
||||
row[target + 2] = linearBlue;
|
||||
row[target + 3] = linearAlpha;
|
||||
}
|
||||
else
|
||||
{
|
||||
row[target] = units[red];
|
||||
row[target + 1] = units[green];
|
||||
row[target + 2] = units[blue];
|
||||
row[target + 3] = units[alpha];
|
||||
}
|
||||
lit = true;
|
||||
}
|
||||
|
||||
return lit;
|
||||
}
|
||||
|
||||
public static void Emit(ReadOnlySpan<float> pixels, float scale, float gain, Span<byte> bytes, Span<float> store)
|
||||
{
|
||||
var count = pixels.Length / Channels;
|
||||
if (bytes.Length < count * Channels || (!store.IsEmpty && store.Length < count * Channels))
|
||||
throw new ArgumentException(null, nameof(bytes));
|
||||
|
||||
ref var from = ref MemoryMarshal.GetReference(pixels);
|
||||
ref var to = ref MemoryMarshal.GetReference(bytes);
|
||||
ref var kept = ref MemoryMarshal.GetReference(store);
|
||||
var scaleVector = Vector128.Create(scale);
|
||||
var gainVector = Vector128.Create(gain);
|
||||
var keep = !store.IsEmpty;
|
||||
for (var pixel = 0; pixel < count; pixel++)
|
||||
{
|
||||
var value = Vector128.LoadUnsafe(ref from, (nuint)(pixel * Channels)) * scaleVector;
|
||||
if (keep)
|
||||
value.StoreUnsafe(ref kept, (nuint)(pixel * Channels));
|
||||
Unsafe.WriteUnaligned(ref Unsafe.Add(ref to, pixel * Channels), PackBgra(value * gainVector));
|
||||
}
|
||||
}
|
||||
|
||||
public static void Emit(ReadOnlySpan<float> pixels, float scale, float gain, in LightOptions light, int x, int y, Span<byte> bytes, Span<float> store)
|
||||
{
|
||||
var count = pixels.Length / Channels;
|
||||
if (bytes.Length < count * Channels || (!store.IsEmpty && store.Length < count * Channels))
|
||||
throw new ArgumentException(null, nameof(bytes));
|
||||
|
||||
ref var from = ref MemoryMarshal.GetReference(pixels);
|
||||
ref var to = ref MemoryMarshal.GetReference(bytes);
|
||||
ref var kept = ref MemoryMarshal.GetReference(store);
|
||||
var scaleVector = Vector128.Create(scale);
|
||||
var keep = !store.IsEmpty;
|
||||
for (var pixel = 0; pixel < count; pixel++)
|
||||
{
|
||||
var value = Vector128.LoadUnsafe(ref from, (nuint)(pixel * Channels)) * scaleVector;
|
||||
if (keep)
|
||||
value.StoreUnsafe(ref kept, (nuint)(pixel * Channels));
|
||||
Unsafe.WriteUnaligned(ref Unsafe.Add(ref to, pixel * Channels), LightTransform.ToPacked(value, gain, in light, x + pixel, y));
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
static uint PackBgra(Vector128<float> rgba)
|
||||
{
|
||||
var ordered = Vector128.Shuffle(rgba, Vector128.Create(2, 1, 0, 3));
|
||||
ordered = Vector128.ConditionalSelect(Vector128.Equals(ordered, ordered), ordered, Vector128<float>.Zero);
|
||||
var clamped = Vector128.Min(Vector128.Max(ordered, Vector128<float>.Zero), Vector128<float>.One);
|
||||
var levels = Vector128.ConvertToInt32(clamped * Vector128.Create(ByteColor.Scale) + Vector128.Create(ByteColor.Rounding)).AsUInt32();
|
||||
var words = Vector128.Narrow(levels, levels);
|
||||
return Vector128.Narrow(words, words).AsUInt32().ToScalar();
|
||||
}
|
||||
|
||||
static float[] BuildUnits()
|
||||
{
|
||||
var units = new float[ByteColor.Levels];
|
||||
for (var level = 0; level < units.Length; level++)
|
||||
units[level] = level / ByteColor.Scale;
|
||||
return units;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
using System.Runtime.ExceptionServices;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Intrinsics;
|
||||
using ComputeWeave;
|
||||
|
||||
namespace SpectralConvolution;
|
||||
@@ -7,32 +9,36 @@ internal sealed class CpuTileConvolver : IDisposable
|
||||
{
|
||||
public const long WorkingBudgetBytes = 64L << 20;
|
||||
public const int StoredChunkPixels = 16384;
|
||||
const int Channels = 4;
|
||||
const int Channels = ByteColor.Channels;
|
||||
|
||||
static readonly Lazy<Engine> SharedEngine = new(static () => new Engine(Environment.ProcessorCount));
|
||||
|
||||
readonly Worker[] workers;
|
||||
readonly Thread[] threads;
|
||||
readonly SemaphoreSlim start = new(0);
|
||||
readonly SemaphoreSlim finished = new(0);
|
||||
readonly WorkerPool pool;
|
||||
readonly bool ownsEngine;
|
||||
readonly ConvolveJob convolveJob;
|
||||
readonly RenderJob renderJob;
|
||||
bool disposed;
|
||||
int[] reversal = [];
|
||||
int reversalSize;
|
||||
int next;
|
||||
int claimed;
|
||||
int workingSize;
|
||||
Exception? failure;
|
||||
byte[] source = [];
|
||||
int sourceX;
|
||||
int sourceY;
|
||||
int sourceWidth;
|
||||
int sourceHeight;
|
||||
KernelSpectrum? spectrum;
|
||||
ChromaticKernelSpectrum? chromatic;
|
||||
TilePlan plan;
|
||||
byte[] output = [];
|
||||
float gain;
|
||||
LightOptions light;
|
||||
float[]? convolved;
|
||||
float[]? stored;
|
||||
int storedPixels;
|
||||
int storedChunks;
|
||||
int storedWidth;
|
||||
int storedOriginX;
|
||||
int storedOriginY;
|
||||
|
||||
public CpuTileConvolver()
|
||||
: this(Environment.ProcessorCount)
|
||||
@@ -40,19 +46,21 @@ internal sealed class CpuTileConvolver : IDisposable
|
||||
}
|
||||
|
||||
public CpuTileConvolver(int threadCount)
|
||||
: this(new Engine(threadCount), true)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(threadCount);
|
||||
workers = new Worker[threadCount];
|
||||
for (var index = 0; index < threadCount; index++)
|
||||
workers[index] = new Worker();
|
||||
threads = new Thread[threadCount - 1];
|
||||
for (var index = 0; index < threads.Length; index++)
|
||||
{
|
||||
threads[index] = new Thread(Serve) { IsBackground = true, Name = nameof(CpuTileConvolver) };
|
||||
threads[index].Start();
|
||||
}
|
||||
}
|
||||
|
||||
CpuTileConvolver(Engine engine, bool ownsEngine)
|
||||
{
|
||||
workers = engine.Workers;
|
||||
pool = engine.Pool;
|
||||
this.ownsEngine = ownsEngine;
|
||||
convolveJob = new ConvolveJob(this);
|
||||
renderJob = new RenderJob(this);
|
||||
}
|
||||
|
||||
public static CpuTileConvolver CreateShared() => new(SharedEngine.Value, false);
|
||||
|
||||
public int Threads => workers.Length;
|
||||
|
||||
public long WorkingBytes
|
||||
@@ -79,17 +87,54 @@ internal sealed class CpuTileConvolver : IDisposable
|
||||
in TilePlan tilePlan,
|
||||
byte[] outputPixels,
|
||||
float outputGain,
|
||||
float[]? convolvedValues)
|
||||
float[]? convolvedValues,
|
||||
LightOptions lightOptions = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(kernelSpectrum);
|
||||
if (kernelSpectrum.Size != tilePlan.Size || kernelSpectrum.Radius != tilePlan.Radius)
|
||||
throw new ArgumentException(null, nameof(kernelSpectrum));
|
||||
Convolve(sourcePixels, sourceLeft, sourceTop, sourceColumns, sourceRows, kernelSpectrum, null, in tilePlan, outputPixels, outputGain, convolvedValues, lightOptions);
|
||||
}
|
||||
|
||||
public void Convolve(
|
||||
byte[] sourcePixels,
|
||||
int sourceLeft,
|
||||
int sourceTop,
|
||||
int sourceColumns,
|
||||
int sourceRows,
|
||||
ChromaticKernelSpectrum chromaticSpectrum,
|
||||
in TilePlan tilePlan,
|
||||
byte[] outputPixels,
|
||||
float outputGain,
|
||||
float[]? convolvedValues,
|
||||
LightOptions lightOptions = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(chromaticSpectrum);
|
||||
if (chromaticSpectrum.Size != tilePlan.Size || chromaticSpectrum.Radius != tilePlan.Radius)
|
||||
throw new ArgumentException(null, nameof(chromaticSpectrum));
|
||||
Convolve(sourcePixels, sourceLeft, sourceTop, sourceColumns, sourceRows, null, chromaticSpectrum, in tilePlan, outputPixels, outputGain, convolvedValues, lightOptions);
|
||||
}
|
||||
|
||||
void Convolve(
|
||||
byte[] sourcePixels,
|
||||
int sourceLeft,
|
||||
int sourceTop,
|
||||
int sourceColumns,
|
||||
int sourceRows,
|
||||
KernelSpectrum? kernelSpectrum,
|
||||
ChromaticKernelSpectrum? chromaticSpectrum,
|
||||
in TilePlan tilePlan,
|
||||
byte[] outputPixels,
|
||||
float outputGain,
|
||||
float[]? convolvedValues,
|
||||
LightOptions lightOptions)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sourcePixels);
|
||||
ArgumentNullException.ThrowIfNull(kernelSpectrum);
|
||||
ArgumentNullException.ThrowIfNull(outputPixels);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(sourceColumns);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(sourceRows);
|
||||
if (sourcePixels.Length < (long)sourceColumns * sourceRows * Channels)
|
||||
throw new ArgumentException(null, nameof(sourcePixels));
|
||||
if (kernelSpectrum.Size != tilePlan.Size || kernelSpectrum.Radius != tilePlan.Radius)
|
||||
throw new ArgumentException(null, nameof(kernelSpectrum));
|
||||
var regionLength = (long)tilePlan.RegionWidth * tilePlan.RegionHeight * Channels;
|
||||
if (outputPixels.Length < regionLength)
|
||||
throw new ArgumentException(null, nameof(outputPixels));
|
||||
@@ -97,11 +142,10 @@ internal sealed class CpuTileConvolver : IDisposable
|
||||
throw new ArgumentException(null, nameof(convolvedValues));
|
||||
if (!float.IsFinite(outputGain))
|
||||
throw new ArgumentOutOfRangeException(nameof(outputGain));
|
||||
lightOptions.Validate();
|
||||
|
||||
ObjectDisposedException.ThrowIf(disposed, this);
|
||||
EnsureReversal(tilePlan.Size, tilePlan.Log2Size);
|
||||
EnsureWorkingSize(tilePlan.Size);
|
||||
var active = Math.Min(ActiveThreads(workers.Length, tilePlan.Size), tilePlan.TileCount);
|
||||
|
||||
source = sourcePixels;
|
||||
sourceX = sourceLeft;
|
||||
@@ -109,24 +153,35 @@ internal sealed class CpuTileConvolver : IDisposable
|
||||
sourceWidth = sourceColumns;
|
||||
sourceHeight = sourceRows;
|
||||
spectrum = kernelSpectrum;
|
||||
chromatic = chromaticSpectrum;
|
||||
plan = tilePlan;
|
||||
output = outputPixels;
|
||||
gain = outputGain;
|
||||
light = lightOptions;
|
||||
convolved = convolvedValues;
|
||||
try
|
||||
{
|
||||
Dispatch(active);
|
||||
pool.Run(convolveJob, plan.TileCount, ActiveThreads(workers.Length, plan.Size));
|
||||
}
|
||||
finally
|
||||
{
|
||||
source = [];
|
||||
spectrum = null;
|
||||
chromatic = null;
|
||||
output = [];
|
||||
convolved = null;
|
||||
}
|
||||
}
|
||||
|
||||
public void RenderStored(float[] storedValues, int pixels, float outputGain, byte[] outputPixels)
|
||||
public void RenderStored(
|
||||
float[] storedValues,
|
||||
int pixels,
|
||||
float outputGain,
|
||||
byte[] outputPixels,
|
||||
LightOptions lightOptions = default,
|
||||
int regionWidth = 0,
|
||||
int regionX = 0,
|
||||
int regionY = 0)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(storedValues);
|
||||
ArgumentNullException.ThrowIfNull(outputPixels);
|
||||
@@ -137,6 +192,9 @@ internal sealed class CpuTileConvolver : IDisposable
|
||||
throw new ArgumentException(null, nameof(outputPixels));
|
||||
if (!float.IsFinite(outputGain))
|
||||
throw new ArgumentOutOfRangeException(nameof(outputGain));
|
||||
lightOptions.Validate();
|
||||
if (lightOptions.Dither && pixels > 0)
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(regionWidth);
|
||||
|
||||
ObjectDisposedException.ThrowIf(disposed, this);
|
||||
var chunks = (pixels + StoredChunkPixels - 1) / StoredChunkPixels;
|
||||
@@ -146,11 +204,15 @@ internal sealed class CpuTileConvolver : IDisposable
|
||||
stored = storedValues;
|
||||
storedPixels = pixels;
|
||||
storedChunks = chunks;
|
||||
storedWidth = regionWidth;
|
||||
storedOriginX = regionX;
|
||||
storedOriginY = regionY;
|
||||
output = outputPixels;
|
||||
gain = outputGain;
|
||||
light = lightOptions;
|
||||
try
|
||||
{
|
||||
Dispatch(Math.Min(workers.Length, chunks));
|
||||
pool.Run(renderJob, chunks);
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -159,50 +221,13 @@ internal sealed class CpuTileConvolver : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
void Dispatch(int active)
|
||||
{
|
||||
next = 0;
|
||||
claimed = 0;
|
||||
failure = null;
|
||||
if (active > 1)
|
||||
start.Release(active - 1);
|
||||
Drain();
|
||||
for (var index = 0; index < active; index++)
|
||||
finished.Wait();
|
||||
|
||||
if (failure is { } exception)
|
||||
ExceptionDispatchInfo.Throw(exception);
|
||||
}
|
||||
|
||||
public static byte ToUnorm(float value)
|
||||
{
|
||||
if (float.IsNaN(value))
|
||||
return 0;
|
||||
return (byte)(Math.Clamp(value, 0f, 1f) * 255f + 0.5f);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (disposed)
|
||||
return;
|
||||
disposed = true;
|
||||
if (threads.Length > 0)
|
||||
start.Release(threads.Length);
|
||||
foreach (var thread in threads)
|
||||
thread.Join();
|
||||
start.Dispose();
|
||||
finished.Dispose();
|
||||
}
|
||||
|
||||
void Serve()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
start.Wait();
|
||||
if (disposed)
|
||||
return;
|
||||
Drain();
|
||||
}
|
||||
if (ownsEngine)
|
||||
pool.Dispose();
|
||||
}
|
||||
|
||||
void EnsureReversal(int size, int log2)
|
||||
@@ -211,50 +236,10 @@ internal sealed class CpuTileConvolver : IDisposable
|
||||
return;
|
||||
if (reversal.Length < size)
|
||||
reversal = new int[size];
|
||||
var shift = 32 - log2;
|
||||
for (var index = 0; index < size; index++)
|
||||
reversal[index] = (int)(ReverseBits((uint)index) >> shift);
|
||||
CpuFft.FillReversal(reversal.AsSpan(0, size), log2);
|
||||
reversalSize = size;
|
||||
}
|
||||
|
||||
void EnsureWorkingSize(int size)
|
||||
{
|
||||
if (workingSize == size)
|
||||
return;
|
||||
foreach (var worker in workers)
|
||||
worker.Release();
|
||||
workingSize = size;
|
||||
}
|
||||
|
||||
void Drain()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (stored is { } values)
|
||||
{
|
||||
int chunk;
|
||||
while ((chunk = Interlocked.Increment(ref next) - 1) < storedChunks)
|
||||
RenderChunk(values, chunk);
|
||||
}
|
||||
else
|
||||
{
|
||||
var worker = workers[Interlocked.Increment(ref claimed) - 1];
|
||||
worker.Prepare(plan.Size);
|
||||
int tile;
|
||||
while ((tile = Interlocked.Increment(ref next) - 1) < plan.TileCount)
|
||||
ConvolveTile(tile, worker);
|
||||
}
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Interlocked.CompareExchange(ref failure, exception, null);
|
||||
}
|
||||
finally
|
||||
{
|
||||
finished.Release();
|
||||
}
|
||||
}
|
||||
|
||||
void ConvolveTile(int tile, Worker worker)
|
||||
{
|
||||
var size = plan.Size;
|
||||
@@ -267,8 +252,9 @@ internal sealed class CpuTileConvolver : IDisposable
|
||||
var line = worker.Line.AsSpan(0, rowLength);
|
||||
var spare = worker.Spare.AsSpan(0, rowLength);
|
||||
var order = reversal.AsSpan(0, size);
|
||||
var twiddles = spectrum!.Twiddles;
|
||||
var values = spectrum.Spectrum;
|
||||
var twiddles = chromatic is { } multi ? multi.Twiddles : spectrum!.Twiddles;
|
||||
var values = spectrum is { } single ? single.Spectrum : default;
|
||||
var light = this.light;
|
||||
|
||||
var lit = false;
|
||||
var first = Math.Max(0, sourceX - left);
|
||||
@@ -277,15 +263,14 @@ internal sealed class CpuTileConvolver : IDisposable
|
||||
{
|
||||
var row = work.Slice(y * rowLength, rowLength);
|
||||
var sourceRow = top + y - sourceY;
|
||||
if (sourceRow < 0 || sourceRow >= sourceHeight || first >= last || !LoadRow(line, order, sourceRow, left, first, last))
|
||||
if (sourceRow < 0 || sourceRow >= sourceHeight || first >= last || !CpuPixels.LoadRow(row, source.AsSpan(sourceRow * sourceWidth * Channels, sourceWidth * Channels), order, sourceX, left, first, last, in light))
|
||||
{
|
||||
row.Clear();
|
||||
continue;
|
||||
}
|
||||
|
||||
lit = true;
|
||||
Butterflies(line, log2, twiddles, 1f);
|
||||
line.CopyTo(row);
|
||||
CpuFft.Butterflies(row, log2, twiddles, 1f);
|
||||
}
|
||||
|
||||
var regionLeft = plan.OriginX(tile) - plan.RegionX;
|
||||
@@ -298,102 +283,170 @@ internal sealed class CpuTileConvolver : IDisposable
|
||||
return;
|
||||
}
|
||||
|
||||
for (var column = 0; column < size; column++)
|
||||
ref var workStart = ref MemoryMarshal.GetReference(work);
|
||||
ref var lineStart = ref MemoryMarshal.GetReference(line);
|
||||
ref var spareStart = ref MemoryMarshal.GetReference(spare);
|
||||
if (chromatic is not null)
|
||||
ConvolveColumnsChromatic(work, worker, size, log2, order, twiddles);
|
||||
else
|
||||
{
|
||||
for (var y = 0; y < size; y++)
|
||||
work.Slice((y * size + column) * Channels, Channels).CopyTo(line.Slice(order[y] * Channels, Channels));
|
||||
|
||||
Butterflies(line, log2, twiddles, 1f);
|
||||
var spectrumColumn = values.Slice(column * size, size);
|
||||
for (var frequency = 0; frequency < size; frequency++)
|
||||
for (var column = 0; column < size; column++)
|
||||
{
|
||||
var weight = spectrumColumn[frequency];
|
||||
var from = frequency * Channels;
|
||||
var to = order[frequency] * Channels;
|
||||
var value0 = line[from];
|
||||
var value1 = line[from + 1];
|
||||
var value2 = line[from + 2];
|
||||
var value3 = line[from + 3];
|
||||
spare[to] = value0 * weight.X - value1 * weight.Y;
|
||||
spare[to + 1] = value0 * weight.Y + value1 * weight.X;
|
||||
spare[to + 2] = value2 * weight.X - value3 * weight.Y;
|
||||
spare[to + 3] = value2 * weight.Y + value3 * weight.X;
|
||||
}
|
||||
for (var y = 0; y < size; y++)
|
||||
Copy(ref workStart, (y * size + column) * Channels, ref lineStart, order[y] * Channels);
|
||||
|
||||
Butterflies(spare, log2, twiddles, -1f);
|
||||
for (var y = 0; y < size; y++)
|
||||
spare.Slice(y * Channels, Channels).CopyTo(work.Slice((y * size + column) * Channels, Channels));
|
||||
CpuFft.Butterflies(line, log2, twiddles, 1f);
|
||||
Multiply(line, spare, order, values.Slice(column * size, size));
|
||||
CpuFft.Butterflies(spare, log2, twiddles, -1f);
|
||||
for (var y = 0; y < size; y++)
|
||||
Copy(ref spareStart, y * Channels, ref workStart, (y * size + column) * Channels);
|
||||
}
|
||||
}
|
||||
|
||||
var scale = 1f / (size * size);
|
||||
var outputOrigin = plan.RegionX + regionLeft;
|
||||
for (var y = radius; y < radius + validHeight; y++)
|
||||
{
|
||||
var row = work.Slice(y * rowLength, rowLength);
|
||||
ref var rowStart = ref MemoryMarshal.GetReference(row);
|
||||
for (var x = 0; x < size; x++)
|
||||
row.Slice(x * Channels, Channels).CopyTo(line.Slice(order[x] * Channels, Channels));
|
||||
Copy(ref rowStart, x * Channels, ref lineStart, order[x] * Channels);
|
||||
|
||||
Butterflies(line, log2, twiddles, -1f);
|
||||
CpuFft.Butterflies(line, log2, twiddles, -1f);
|
||||
var outputRow = regionTop + y - radius;
|
||||
for (var x = radius; x < radius + validWidth; x++)
|
||||
var index = (outputRow * plan.RegionWidth + regionLeft) * Channels;
|
||||
var pixels = line.Slice(radius * Channels, validWidth * Channels);
|
||||
var bytes = output.AsSpan(index, validWidth * Channels);
|
||||
var store = convolved is { } convolvedValues ? convolvedValues.AsSpan(index, validWidth * Channels) : default;
|
||||
if (light.IsDefault)
|
||||
CpuPixels.Emit(pixels, scale, gain, bytes, store);
|
||||
else
|
||||
CpuPixels.Emit(pixels, scale, gain, in light, outputOrigin, plan.RegionY + outputRow, bytes, store);
|
||||
}
|
||||
}
|
||||
|
||||
void ConvolveColumnsChromatic(Span<float> work, Worker worker, int size, int log2, ReadOnlySpan<int> order, ReadOnlySpan<Float2> twiddles)
|
||||
{
|
||||
var spectra = chromatic!;
|
||||
var rowLength = size * Channels;
|
||||
var redGreen = worker.Line.AsSpan(0, rowLength);
|
||||
var redGreenSpare = worker.Spare.AsSpan(0, rowLength);
|
||||
var blueAlpha = worker.BlueAlphaLine.AsSpan(0, rowLength);
|
||||
var blueAlphaSpare = worker.BlueAlphaSpare.AsSpan(0, rowLength);
|
||||
var mask = size - 1;
|
||||
ref var workStart = ref MemoryMarshal.GetReference(work);
|
||||
ref var redGreenStart = ref MemoryMarshal.GetReference(redGreen);
|
||||
ref var redGreenSpareStart = ref MemoryMarshal.GetReference(redGreenSpare);
|
||||
ref var blueAlphaStart = ref MemoryMarshal.GetReference(blueAlpha);
|
||||
ref var blueAlphaSpareStart = ref MemoryMarshal.GetReference(blueAlphaSpare);
|
||||
for (var column = 0; column < spectra.HalfColumns; column++)
|
||||
{
|
||||
var mirror = (size - column) & mask;
|
||||
for (var y = 0; y < size; y++)
|
||||
{
|
||||
var red = line[x * Channels] * scale;
|
||||
var green = line[x * Channels + 1] * scale;
|
||||
var blue = line[x * Channels + 2] * scale;
|
||||
var alpha = line[x * Channels + 3] * scale;
|
||||
var index = (outputRow * plan.RegionWidth + regionLeft + x - radius) * Channels;
|
||||
output[index] = ToUnorm(blue * gain);
|
||||
output[index + 1] = ToUnorm(green * gain);
|
||||
output[index + 2] = ToUnorm(red * gain);
|
||||
output[index + 3] = ToUnorm(alpha * gain);
|
||||
if (convolved is { } store)
|
||||
{
|
||||
store[index] = red;
|
||||
store[index + 1] = green;
|
||||
store[index + 2] = blue;
|
||||
store[index + 3] = alpha;
|
||||
}
|
||||
var near = Vector128.LoadUnsafe(ref workStart, (nuint)((y * size + column) * Channels));
|
||||
var far = Vector128.LoadUnsafe(ref workStart, (nuint)((y * size + mirror) * Channels));
|
||||
SplitRedGreen(near, far).StoreUnsafe(ref redGreenStart, (nuint)(order[y] * Channels));
|
||||
SplitBlueAlpha(near, far).StoreUnsafe(ref blueAlphaStart, (nuint)(order[y] * Channels));
|
||||
}
|
||||
|
||||
CpuFft.Butterflies(redGreen, log2, twiddles, 1f);
|
||||
CpuFft.Butterflies(blueAlpha, log2, twiddles, 1f);
|
||||
var green = spectra.Green.Spectrum.Slice(column * size, size);
|
||||
MultiplyPair(redGreen, redGreenSpare, order, spectra.Red.Spectrum.Slice(column * size, size), green);
|
||||
MultiplyPair(blueAlpha, blueAlphaSpare, order, spectra.Blue.Spectrum.Slice(column * size, size), green);
|
||||
CpuFft.Butterflies(redGreenSpare, log2, twiddles, -1f);
|
||||
CpuFft.Butterflies(blueAlphaSpare, log2, twiddles, -1f);
|
||||
for (var y = 0; y < size; y++)
|
||||
{
|
||||
var redGreenValue = Vector128.LoadUnsafe(ref redGreenSpareStart, (nuint)(y * Channels));
|
||||
var blueAlphaValue = Vector128.LoadUnsafe(ref blueAlphaSpareStart, (nuint)(y * Channels));
|
||||
MergeChannels(redGreenValue, blueAlphaValue, out var near, out var far);
|
||||
near.StoreUnsafe(ref workStart, (nuint)((y * size + column) * Channels));
|
||||
if (mirror != column)
|
||||
far.StoreUnsafe(ref workStart, (nuint)((y * size + mirror) * Channels));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
static Vector128<float> SplitRedGreen(Vector128<float> near, Vector128<float> far)
|
||||
=> Vector128.Create(near[0] + far[0], near[1] - far[1], near[1] + far[1], far[0] - near[0]) * Vector128.Create(0.5f);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
static Vector128<float> SplitBlueAlpha(Vector128<float> near, Vector128<float> far)
|
||||
=> Vector128.Create(near[2] + far[2], near[3] - far[3], near[3] + far[3], far[2] - near[2]) * Vector128.Create(0.5f);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
static void MergeChannels(Vector128<float> redGreen, Vector128<float> blueAlpha, out Vector128<float> near, out Vector128<float> far)
|
||||
{
|
||||
near = Vector128.Create(redGreen[0] - redGreen[3], redGreen[1] + redGreen[2], blueAlpha[0] - blueAlpha[3], blueAlpha[1] + blueAlpha[2]);
|
||||
far = Vector128.Create(redGreen[0] + redGreen[3], redGreen[2] - redGreen[1], blueAlpha[0] + blueAlpha[3], blueAlpha[2] - blueAlpha[1]);
|
||||
}
|
||||
|
||||
static void MultiplyPair(ReadOnlySpan<float> line, Span<float> spare, ReadOnlySpan<int> order, ReadOnlySpan<Float2> first, ReadOnlySpan<Float2> second)
|
||||
{
|
||||
var size = first.Length;
|
||||
if (line.Length < size * Channels || spare.Length < size * Channels || order.Length < size || second.Length != size)
|
||||
throw new ArgumentException(null, nameof(first));
|
||||
|
||||
ref var from = ref MemoryMarshal.GetReference(line);
|
||||
ref var to = ref MemoryMarshal.GetReference(spare);
|
||||
for (var frequency = 0; frequency < size; frequency++)
|
||||
{
|
||||
var near = first[frequency];
|
||||
var far = second[frequency];
|
||||
var value = Vector128.LoadUnsafe(ref from, (nuint)(frequency * Channels));
|
||||
var product = CpuFft.Rotate(value, Vector128.Create(near.X, near.X, far.X, far.X), Vector128.Create(-near.Y, near.Y, -far.Y, far.Y));
|
||||
product.StoreUnsafe(ref to, (nuint)(order[frequency] * Channels));
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
static void Copy(ref float from, int fromIndex, ref float to, int toIndex)
|
||||
=> Vector128.LoadUnsafe(ref from, (nuint)fromIndex).StoreUnsafe(ref to, (nuint)toIndex);
|
||||
|
||||
static void Multiply(ReadOnlySpan<float> line, Span<float> spare, ReadOnlySpan<int> order, ReadOnlySpan<Float2> weights)
|
||||
{
|
||||
var size = weights.Length;
|
||||
if (line.Length < size * Channels || spare.Length < size * Channels || order.Length < size)
|
||||
throw new ArgumentException(null, nameof(weights));
|
||||
|
||||
ref var from = ref MemoryMarshal.GetReference(line);
|
||||
ref var to = ref MemoryMarshal.GetReference(spare);
|
||||
for (var frequency = 0; frequency < size; frequency++)
|
||||
{
|
||||
var weight = weights[frequency];
|
||||
var value = Vector128.LoadUnsafe(ref from, (nuint)(frequency * Channels));
|
||||
var product = CpuFft.Rotate(value, Vector128.Create(weight.X), CpuFft.Imaginary(weight.Y));
|
||||
product.StoreUnsafe(ref to, (nuint)(order[frequency] * Channels));
|
||||
}
|
||||
}
|
||||
|
||||
void RenderChunk(float[] values, int chunk)
|
||||
{
|
||||
var first = chunk * StoredChunkPixels;
|
||||
var last = Math.Min(first + StoredChunkPixels, storedPixels);
|
||||
for (var pixel = first; pixel < last; pixel++)
|
||||
var count = Math.Min(first + StoredChunkPixels, storedPixels) - first;
|
||||
var light = this.light;
|
||||
var pixels = values.AsSpan(first * Channels, count * Channels);
|
||||
var bytes = output.AsSpan(first * Channels, count * Channels);
|
||||
if (light.IsDefault)
|
||||
{
|
||||
var index = pixel * Channels;
|
||||
output[index] = ToUnorm(values[index + 2] * gain);
|
||||
output[index + 1] = ToUnorm(values[index + 1] * gain);
|
||||
output[index + 2] = ToUnorm(values[index] * gain);
|
||||
output[index + 3] = ToUnorm(values[index + 3] * gain);
|
||||
}
|
||||
}
|
||||
|
||||
bool LoadRow(Span<float> line, ReadOnlySpan<int> order, int sourceRow, int left, int first, int last)
|
||||
{
|
||||
line.Clear();
|
||||
var lit = false;
|
||||
var pixels = source.AsSpan(sourceRow * sourceWidth * Channels, sourceWidth * Channels);
|
||||
for (var x = first; x < last; x++)
|
||||
{
|
||||
var offset = (left + x - sourceX) * Channels;
|
||||
var blue = pixels[offset];
|
||||
var green = pixels[offset + 1];
|
||||
var red = pixels[offset + 2];
|
||||
var alpha = pixels[offset + 3];
|
||||
if ((blue | green | red | alpha) == 0)
|
||||
continue;
|
||||
|
||||
var target = order[x] * Channels;
|
||||
line[target] = red / 255f;
|
||||
line[target + 1] = green / 255f;
|
||||
line[target + 2] = blue / 255f;
|
||||
line[target + 3] = alpha / 255f;
|
||||
lit = true;
|
||||
CpuPixels.Emit(pixels, 1f, gain, bytes, default);
|
||||
return;
|
||||
}
|
||||
|
||||
return lit;
|
||||
var column = storedWidth > 0 ? first % storedWidth : 0;
|
||||
var row = storedWidth > 0 ? first / storedWidth : 0;
|
||||
for (var done = 0; done < count;)
|
||||
{
|
||||
var run = storedWidth > 0 ? Math.Min(count - done, storedWidth - column) : count - done;
|
||||
CpuPixels.Emit(pixels.Slice(done * Channels, run * Channels), 1f, gain, in light, storedOriginX + column, storedOriginY + row,
|
||||
bytes.Slice(done * Channels, run * Channels), default);
|
||||
done += run;
|
||||
column = 0;
|
||||
row++;
|
||||
}
|
||||
}
|
||||
|
||||
void ClearValid(int regionLeft, int regionTop, int validWidth, int validHeight)
|
||||
@@ -406,52 +459,32 @@ internal sealed class CpuTileConvolver : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
static void Butterflies(Span<float> line, int log2, ReadOnlySpan<Float2> twiddles, float direction)
|
||||
sealed class ConvolveJob(CpuTileConvolver owner) : IParallelJob
|
||||
{
|
||||
var pairs = 1 << (log2 - 1);
|
||||
for (var stage = 0; stage < log2; stage++)
|
||||
{
|
||||
var half = 1 << stage;
|
||||
var shift = log2 - 1 - stage;
|
||||
for (var pair = 0; pair < pairs; pair++)
|
||||
{
|
||||
var position = pair & (half - 1);
|
||||
var even = (((pair >> stage) << (stage + 1)) + position) * Channels;
|
||||
var odd = even + half * Channels;
|
||||
var twiddle = twiddles[position << shift];
|
||||
var real = twiddle.X;
|
||||
var imaginary = twiddle.Y * direction;
|
||||
var odd0 = line[odd];
|
||||
var odd1 = line[odd + 1];
|
||||
var odd2 = line[odd + 2];
|
||||
var odd3 = line[odd + 3];
|
||||
var product0 = odd0 * real - odd1 * imaginary;
|
||||
var product1 = odd0 * imaginary + odd1 * real;
|
||||
var product2 = odd2 * real - odd3 * imaginary;
|
||||
var product3 = odd2 * imaginary + odd3 * real;
|
||||
var even0 = line[even];
|
||||
var even1 = line[even + 1];
|
||||
var even2 = line[even + 2];
|
||||
var even3 = line[even + 3];
|
||||
line[even] = even0 + product0;
|
||||
line[even + 1] = even1 + product1;
|
||||
line[even + 2] = even2 + product2;
|
||||
line[even + 3] = even3 + product3;
|
||||
line[odd] = even0 - product0;
|
||||
line[odd + 1] = even1 - product1;
|
||||
line[odd + 2] = even2 - product2;
|
||||
line[odd + 3] = even3 - product3;
|
||||
}
|
||||
}
|
||||
public void Begin(int worker) => owner.workers[worker].Prepare(owner.plan.Size, owner.chromatic is not null);
|
||||
|
||||
public void Execute(int index, int worker) => owner.ConvolveTile(index, owner.workers[worker]);
|
||||
}
|
||||
|
||||
static uint ReverseBits(uint value)
|
||||
sealed class RenderJob(CpuTileConvolver owner) : IParallelJob
|
||||
{
|
||||
value = ((value >> 1) & 0x55555555u) | ((value & 0x55555555u) << 1);
|
||||
value = ((value >> 2) & 0x33333333u) | ((value & 0x33333333u) << 2);
|
||||
value = ((value >> 4) & 0x0F0F0F0Fu) | ((value & 0x0F0F0F0Fu) << 4);
|
||||
value = ((value >> 8) & 0x00FF00FFu) | ((value & 0x00FF00FFu) << 8);
|
||||
return (value >> 16) | (value << 16);
|
||||
public void Execute(int index, int worker) => owner.RenderChunk(owner.stored!, index);
|
||||
}
|
||||
|
||||
sealed class Engine
|
||||
{
|
||||
public Engine(int threadCount)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(threadCount);
|
||||
Workers = new Worker[threadCount];
|
||||
for (var index = 0; index < threadCount; index++)
|
||||
Workers[index] = new Worker();
|
||||
Pool = new WorkerPool(threadCount - 1);
|
||||
}
|
||||
|
||||
public Worker[] Workers { get; }
|
||||
|
||||
public WorkerPool Pool { get; }
|
||||
}
|
||||
|
||||
sealed class Worker
|
||||
@@ -462,9 +495,13 @@ internal sealed class CpuTileConvolver : IDisposable
|
||||
|
||||
public float[] Spare { get; private set; } = [];
|
||||
|
||||
public long Bytes => ((long)Tile.Length + Line.Length + Spare.Length) * sizeof(float);
|
||||
public float[] BlueAlphaLine { get; private set; } = [];
|
||||
|
||||
public void Prepare(int size)
|
||||
public float[] BlueAlphaSpare { get; private set; } = [];
|
||||
|
||||
public long Bytes => ((long)Tile.Length + Line.Length + Spare.Length + BlueAlphaLine.Length + BlueAlphaSpare.Length) * sizeof(float);
|
||||
|
||||
public void Prepare(int size, bool chromatic)
|
||||
{
|
||||
var rowLength = size * Channels;
|
||||
if (Tile.Length < size * rowLength)
|
||||
@@ -474,13 +511,11 @@ internal sealed class CpuTileConvolver : IDisposable
|
||||
Line = new float[rowLength];
|
||||
Spare = new float[rowLength];
|
||||
}
|
||||
}
|
||||
|
||||
public void Release()
|
||||
{
|
||||
Tile = [];
|
||||
Line = [];
|
||||
Spare = [];
|
||||
if (chromatic && BlueAlphaLine.Length < rowLength)
|
||||
{
|
||||
BlueAlphaLine = new float[rowLength];
|
||||
BlueAlphaSpare = new float[rowLength];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,10 @@ namespace SpectralConvolution;
|
||||
|
||||
internal static class DirectCorrelation
|
||||
{
|
||||
public const int Channels = 4;
|
||||
public const int Channels = ByteColor.Channels;
|
||||
|
||||
public static uint Pack(byte red, byte green, byte blue, byte alpha)
|
||||
=> red | (uint)green << 8 | (uint)blue << 16 | (uint)alpha << 24;
|
||||
=> red | (uint)green << ByteColor.Bits | (uint)blue << 2 * ByteColor.Bits | (uint)alpha << 3 * ByteColor.Bits;
|
||||
|
||||
public static void Evaluate(ReadOnlySpan<uint> neighborhood, ReadOnlySpan<double> kernel, Span<double> result)
|
||||
{
|
||||
@@ -22,10 +22,45 @@ internal static class DirectCorrelation
|
||||
{
|
||||
var packed = neighborhood[index];
|
||||
var weight = kernel[index];
|
||||
red += (packed & 255u) / 255d * weight;
|
||||
green += (packed >> 8 & 255u) / 255d * weight;
|
||||
blue += (packed >> 16 & 255u) / 255d * weight;
|
||||
alpha += (packed >> 24) / 255d * weight;
|
||||
red += ByteColor.Channel(packed, 0) / ByteColor.ScaleDouble * weight;
|
||||
green += ByteColor.Channel(packed, 1) / ByteColor.ScaleDouble * weight;
|
||||
blue += ByteColor.Channel(packed, 2) / ByteColor.ScaleDouble * weight;
|
||||
alpha += ByteColor.Channel(packed, 3) / ByteColor.ScaleDouble * weight;
|
||||
}
|
||||
|
||||
result[0] = red;
|
||||
result[1] = green;
|
||||
result[2] = blue;
|
||||
result[3] = alpha;
|
||||
}
|
||||
|
||||
public static void Evaluate(ReadOnlySpan<uint> neighborhood, ReadOnlySpan<double> kernel, in LightOptions light, Span<double> result)
|
||||
{
|
||||
if (!light.Linear)
|
||||
{
|
||||
Evaluate(neighborhood, kernel, result);
|
||||
return;
|
||||
}
|
||||
|
||||
if (neighborhood.Length != kernel.Length)
|
||||
throw new ArgumentException(null, nameof(neighborhood));
|
||||
if (result.Length < Channels)
|
||||
throw new ArgumentException(null, nameof(result));
|
||||
|
||||
var red = 0d;
|
||||
var green = 0d;
|
||||
var blue = 0d;
|
||||
var alpha = 0d;
|
||||
for (var index = 0; index < kernel.Length; index++)
|
||||
{
|
||||
var packed = neighborhood[index];
|
||||
var weight = kernel[index];
|
||||
var (linearRed, linearGreen, linearBlue, linearAlpha) = LightTransform.FromBytes(
|
||||
(byte)ByteColor.Channel(packed, 0), (byte)ByteColor.Channel(packed, 1), (byte)ByteColor.Channel(packed, 2), (byte)ByteColor.Channel(packed, 3), in light);
|
||||
red += linearRed * weight;
|
||||
green += linearGreen * weight;
|
||||
blue += linearBlue * weight;
|
||||
alpha += linearAlpha * weight;
|
||||
}
|
||||
|
||||
result[0] = red;
|
||||
@@ -60,10 +95,94 @@ internal static class DirectCorrelation
|
||||
continue;
|
||||
var weight = kernel[(offsetY + radius) * kernelSize + offsetX + radius];
|
||||
var offset = (sourceY * width + sourceX) * Channels;
|
||||
red += bgra[offset + 2] / 255d * weight;
|
||||
green += bgra[offset + 1] / 255d * weight;
|
||||
blue += bgra[offset] / 255d * weight;
|
||||
alpha += bgra[offset + 3] / 255d * weight;
|
||||
red += bgra[offset + 2] / ByteColor.ScaleDouble * weight;
|
||||
green += bgra[offset + 1] / ByteColor.ScaleDouble * weight;
|
||||
blue += bgra[offset] / ByteColor.ScaleDouble * weight;
|
||||
alpha += bgra[offset + 3] / ByteColor.ScaleDouble * weight;
|
||||
}
|
||||
}
|
||||
|
||||
result[0] = red;
|
||||
result[1] = green;
|
||||
result[2] = blue;
|
||||
result[3] = alpha;
|
||||
}
|
||||
|
||||
public static void Evaluate(
|
||||
ReadOnlySpan<uint> neighborhood,
|
||||
ReadOnlySpan<double> redKernel,
|
||||
ReadOnlySpan<double> greenKernel,
|
||||
ReadOnlySpan<double> blueKernel,
|
||||
in LightOptions light,
|
||||
Span<double> result)
|
||||
{
|
||||
if (neighborhood.Length != redKernel.Length || neighborhood.Length != greenKernel.Length || neighborhood.Length != blueKernel.Length)
|
||||
throw new ArgumentException(null, nameof(neighborhood));
|
||||
if (result.Length < Channels)
|
||||
throw new ArgumentException(null, nameof(result));
|
||||
|
||||
var red = 0d;
|
||||
var green = 0d;
|
||||
var blue = 0d;
|
||||
var alpha = 0d;
|
||||
for (var index = 0; index < greenKernel.Length; index++)
|
||||
{
|
||||
var packed = neighborhood[index];
|
||||
var (linearRed, linearGreen, linearBlue, linearAlpha) = light.Linear
|
||||
? LightTransform.FromBytes((byte)ByteColor.Channel(packed, 0), (byte)ByteColor.Channel(packed, 1), (byte)ByteColor.Channel(packed, 2), (byte)ByteColor.Channel(packed, 3), in light)
|
||||
: (ByteColor.Channel(packed, 0) / ByteColor.ScaleDouble, ByteColor.Channel(packed, 1) / ByteColor.ScaleDouble, ByteColor.Channel(packed, 2) / ByteColor.ScaleDouble, ByteColor.Channel(packed, 3) / ByteColor.ScaleDouble);
|
||||
red += linearRed * redKernel[index];
|
||||
green += linearGreen * greenKernel[index];
|
||||
blue += linearBlue * blueKernel[index];
|
||||
alpha += linearAlpha * greenKernel[index];
|
||||
}
|
||||
|
||||
result[0] = red;
|
||||
result[1] = green;
|
||||
result[2] = blue;
|
||||
result[3] = alpha;
|
||||
}
|
||||
|
||||
public static void Evaluate(
|
||||
ReadOnlySpan<byte> bgra,
|
||||
int width,
|
||||
int height,
|
||||
ReadOnlySpan<double> redKernel,
|
||||
ReadOnlySpan<double> greenKernel,
|
||||
ReadOnlySpan<double> blueKernel,
|
||||
int radius,
|
||||
int x,
|
||||
int y,
|
||||
Span<double> result)
|
||||
{
|
||||
var kernelSize = radius * 2 + 1;
|
||||
if (redKernel.Length != kernelSize * kernelSize || greenKernel.Length != redKernel.Length || blueKernel.Length != redKernel.Length)
|
||||
throw new ArgumentException(null, nameof(redKernel));
|
||||
if (bgra.Length < width * height * Channels)
|
||||
throw new ArgumentException(null, nameof(bgra));
|
||||
if (result.Length < Channels)
|
||||
throw new ArgumentException(null, nameof(result));
|
||||
|
||||
var red = 0d;
|
||||
var green = 0d;
|
||||
var blue = 0d;
|
||||
var alpha = 0d;
|
||||
for (var offsetY = -radius; offsetY <= radius; offsetY++)
|
||||
{
|
||||
var sourceY = y + offsetY;
|
||||
if (sourceY < 0 || sourceY >= height)
|
||||
continue;
|
||||
for (var offsetX = -radius; offsetX <= radius; offsetX++)
|
||||
{
|
||||
var sourceX = x + offsetX;
|
||||
if (sourceX < 0 || sourceX >= width)
|
||||
continue;
|
||||
var index = (offsetY + radius) * kernelSize + offsetX + radius;
|
||||
var offset = (sourceY * width + sourceX) * Channels;
|
||||
red += bgra[offset + 2] / ByteColor.ScaleDouble * redKernel[index];
|
||||
green += bgra[offset + 1] / ByteColor.ScaleDouble * greenKernel[index];
|
||||
blue += bgra[offset] / ByteColor.ScaleDouble * blueKernel[index];
|
||||
alpha += bgra[offset + 3] / ByteColor.ScaleDouble * greenKernel[index];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ namespace SpectralConvolution;
|
||||
|
||||
internal static class FastFourierTransform
|
||||
{
|
||||
static readonly ConcurrentDictionary<long, Twiddles> TwiddleCache = new();
|
||||
static readonly ConcurrentDictionary<TwiddleKey, Twiddles> TwiddleCache = new();
|
||||
|
||||
public static void Forward(Span<double> real, Span<double> imaginary) => Transform(real, imaginary, false);
|
||||
|
||||
@@ -25,7 +25,7 @@ internal static class FastFourierTransform
|
||||
throw new ArgumentException(nameof(real));
|
||||
|
||||
var twiddles = GetTwiddles(count, inverse);
|
||||
Reorder(real, imaginary);
|
||||
Reorder(real, imaginary, twiddles.Swaps);
|
||||
Butterflies(real, imaginary, twiddles);
|
||||
if (inverse)
|
||||
Scale(real, imaginary, 1d / count);
|
||||
@@ -77,20 +77,14 @@ internal static class FastFourierTransform
|
||||
}
|
||||
}
|
||||
|
||||
static void Reorder(Span<double> real, Span<double> imaginary)
|
||||
static void Reorder(Span<double> real, Span<double> imaginary, int[] swaps)
|
||||
{
|
||||
var count = real.Length;
|
||||
for (int source = 1, target = 0; source < count; source++)
|
||||
for (var index = 0; index < swaps.Length; index += 2)
|
||||
{
|
||||
var bit = count >> 1;
|
||||
for (; (target & bit) != 0; bit >>= 1)
|
||||
target ^= bit;
|
||||
target ^= bit;
|
||||
if (source < target)
|
||||
{
|
||||
(real[source], real[target]) = (real[target], real[source]);
|
||||
(imaginary[source], imaginary[target]) = (imaginary[target], imaginary[source]);
|
||||
}
|
||||
var source = swaps[index];
|
||||
var target = swaps[index + 1];
|
||||
(real[source], real[target]) = (real[target], real[source]);
|
||||
(imaginary[source], imaginary[target]) = (imaginary[target], imaginary[source]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,57 +94,179 @@ internal static class FastFourierTransform
|
||||
ref var realBase = ref MemoryMarshal.GetReference(real);
|
||||
ref var imaginaryBase = ref MemoryMarshal.GetReference(imaginary);
|
||||
var width = Vector<double>.Count;
|
||||
var stages = twiddles.Cos.Length;
|
||||
|
||||
for (int length = 2, stage = 0; length <= count; length <<= 1, stage++)
|
||||
var stage = 0;
|
||||
if (stages >= 2)
|
||||
{
|
||||
var half = length >> 1;
|
||||
var cos = twiddles.Cos[stage];
|
||||
var sin = twiddles.Sin[stage];
|
||||
ref var cosBase = ref MemoryMarshal.GetArrayDataReference(cos);
|
||||
ref var sinBase = ref MemoryMarshal.GetArrayDataReference(sin);
|
||||
var vectorized = Vector.IsHardwareAccelerated && half >= width;
|
||||
FirstTwoStages(ref realBase, ref imaginaryBase, count, twiddles);
|
||||
stage = 2;
|
||||
}
|
||||
|
||||
for (var offset = 0; offset < count; offset += length)
|
||||
for (; stage + 1 < stages && Vector.IsHardwareAccelerated && (1 << stage) >= width; stage += 2)
|
||||
StagePair(ref realBase, ref imaginaryBase, count, stage, twiddles);
|
||||
|
||||
for (; stage < stages; stage++)
|
||||
SingleStage(ref realBase, ref imaginaryBase, count, stage, twiddles);
|
||||
}
|
||||
|
||||
static void FirstTwoStages(ref double realBase, ref double imaginaryBase, int count, Twiddles twiddles)
|
||||
{
|
||||
var cosFirst = twiddles.Cos[0][0];
|
||||
var sinFirst = twiddles.Sin[0][0];
|
||||
var cosSecondEven = twiddles.Cos[1][0];
|
||||
var sinSecondEven = twiddles.Sin[1][0];
|
||||
var cosSecondOdd = twiddles.Cos[1][1];
|
||||
var sinSecondOdd = twiddles.Sin[1][1];
|
||||
for (var offset = 0; offset < count; offset += 4)
|
||||
{
|
||||
var real0 = Unsafe.Add(ref realBase, offset);
|
||||
var imaginary0 = Unsafe.Add(ref imaginaryBase, offset);
|
||||
var real1 = Unsafe.Add(ref realBase, offset + 1);
|
||||
var imaginary1 = Unsafe.Add(ref imaginaryBase, offset + 1);
|
||||
var real2 = Unsafe.Add(ref realBase, offset + 2);
|
||||
var imaginary2 = Unsafe.Add(ref imaginaryBase, offset + 2);
|
||||
var real3 = Unsafe.Add(ref realBase, offset + 3);
|
||||
var imaginary3 = Unsafe.Add(ref imaginaryBase, offset + 3);
|
||||
|
||||
var product1Real = real1 * cosFirst - imaginary1 * sinFirst;
|
||||
var product1Imaginary = real1 * sinFirst + imaginary1 * cosFirst;
|
||||
var sum0Real = real0 + product1Real;
|
||||
var sum0Imaginary = imaginary0 + product1Imaginary;
|
||||
var sum1Real = real0 - product1Real;
|
||||
var sum1Imaginary = imaginary0 - product1Imaginary;
|
||||
var product3Real = real3 * cosFirst - imaginary3 * sinFirst;
|
||||
var product3Imaginary = real3 * sinFirst + imaginary3 * cosFirst;
|
||||
var sum2Real = real2 + product3Real;
|
||||
var sum2Imaginary = imaginary2 + product3Imaginary;
|
||||
var sum3Real = real2 - product3Real;
|
||||
var sum3Imaginary = imaginary2 - product3Imaginary;
|
||||
|
||||
var evenProductReal = sum2Real * cosSecondEven - sum2Imaginary * sinSecondEven;
|
||||
var evenProductImaginary = sum2Real * sinSecondEven + sum2Imaginary * cosSecondEven;
|
||||
var oddProductReal = sum3Real * cosSecondOdd - sum3Imaginary * sinSecondOdd;
|
||||
var oddProductImaginary = sum3Real * sinSecondOdd + sum3Imaginary * cosSecondOdd;
|
||||
Unsafe.Add(ref realBase, offset) = sum0Real + evenProductReal;
|
||||
Unsafe.Add(ref imaginaryBase, offset) = sum0Imaginary + evenProductImaginary;
|
||||
Unsafe.Add(ref realBase, offset + 2) = sum0Real - evenProductReal;
|
||||
Unsafe.Add(ref imaginaryBase, offset + 2) = sum0Imaginary - evenProductImaginary;
|
||||
Unsafe.Add(ref realBase, offset + 1) = sum1Real + oddProductReal;
|
||||
Unsafe.Add(ref imaginaryBase, offset + 1) = sum1Imaginary + oddProductImaginary;
|
||||
Unsafe.Add(ref realBase, offset + 3) = sum1Real - oddProductReal;
|
||||
Unsafe.Add(ref imaginaryBase, offset + 3) = sum1Imaginary - oddProductImaginary;
|
||||
}
|
||||
}
|
||||
|
||||
static void StagePair(ref double realBase, ref double imaginaryBase, int count, int stage, Twiddles twiddles)
|
||||
{
|
||||
var width = Vector<double>.Count;
|
||||
var half = 1 << stage;
|
||||
ref var firstCosBase = ref MemoryMarshal.GetArrayDataReference(twiddles.Cos[stage]);
|
||||
ref var firstSinBase = ref MemoryMarshal.GetArrayDataReference(twiddles.Sin[stage]);
|
||||
ref var secondCosBase = ref MemoryMarshal.GetArrayDataReference(twiddles.Cos[stage + 1]);
|
||||
ref var secondSinBase = ref MemoryMarshal.GetArrayDataReference(twiddles.Sin[stage + 1]);
|
||||
for (var block = 0; block < count; block += half * 4)
|
||||
{
|
||||
for (var index = 0; index < half; index += width)
|
||||
{
|
||||
var index = 0;
|
||||
if (vectorized)
|
||||
{
|
||||
for (; index + width <= half; index += width)
|
||||
{
|
||||
var even = offset + index;
|
||||
var odd = even + half;
|
||||
var evenReal = Vector.LoadUnsafe(ref Unsafe.Add(ref realBase, even));
|
||||
var evenImaginary = Vector.LoadUnsafe(ref Unsafe.Add(ref imaginaryBase, even));
|
||||
var oddReal = Vector.LoadUnsafe(ref Unsafe.Add(ref realBase, odd));
|
||||
var oddImaginary = Vector.LoadUnsafe(ref Unsafe.Add(ref imaginaryBase, odd));
|
||||
var weightReal = Vector.LoadUnsafe(ref Unsafe.Add(ref cosBase, index));
|
||||
var weightImaginary = Vector.LoadUnsafe(ref Unsafe.Add(ref sinBase, index));
|
||||
var productReal = oddReal * weightReal - oddImaginary * weightImaginary;
|
||||
var productImaginary = oddReal * weightImaginary + oddImaginary * weightReal;
|
||||
(evenReal + productReal).StoreUnsafe(ref Unsafe.Add(ref realBase, even));
|
||||
(evenImaginary + productImaginary).StoreUnsafe(ref Unsafe.Add(ref imaginaryBase, even));
|
||||
(evenReal - productReal).StoreUnsafe(ref Unsafe.Add(ref realBase, odd));
|
||||
(evenImaginary - productImaginary).StoreUnsafe(ref Unsafe.Add(ref imaginaryBase, odd));
|
||||
}
|
||||
}
|
||||
for (; index < half; index++)
|
||||
var position0 = block + index;
|
||||
var position1 = position0 + half;
|
||||
var position2 = position1 + half;
|
||||
var position3 = position2 + half;
|
||||
var firstWeightReal = Vector.LoadUnsafe(ref Unsafe.Add(ref firstCosBase, index));
|
||||
var firstWeightImaginary = Vector.LoadUnsafe(ref Unsafe.Add(ref firstSinBase, index));
|
||||
var secondEvenWeightReal = Vector.LoadUnsafe(ref Unsafe.Add(ref secondCosBase, index));
|
||||
var secondEvenWeightImaginary = Vector.LoadUnsafe(ref Unsafe.Add(ref secondSinBase, index));
|
||||
var secondOddWeightReal = Vector.LoadUnsafe(ref Unsafe.Add(ref secondCosBase, index + half));
|
||||
var secondOddWeightImaginary = Vector.LoadUnsafe(ref Unsafe.Add(ref secondSinBase, index + half));
|
||||
|
||||
var real0 = Vector.LoadUnsafe(ref Unsafe.Add(ref realBase, position0));
|
||||
var imaginary0 = Vector.LoadUnsafe(ref Unsafe.Add(ref imaginaryBase, position0));
|
||||
var real1 = Vector.LoadUnsafe(ref Unsafe.Add(ref realBase, position1));
|
||||
var imaginary1 = Vector.LoadUnsafe(ref Unsafe.Add(ref imaginaryBase, position1));
|
||||
var real2 = Vector.LoadUnsafe(ref Unsafe.Add(ref realBase, position2));
|
||||
var imaginary2 = Vector.LoadUnsafe(ref Unsafe.Add(ref imaginaryBase, position2));
|
||||
var real3 = Vector.LoadUnsafe(ref Unsafe.Add(ref realBase, position3));
|
||||
var imaginary3 = Vector.LoadUnsafe(ref Unsafe.Add(ref imaginaryBase, position3));
|
||||
|
||||
var product1Real = real1 * firstWeightReal - imaginary1 * firstWeightImaginary;
|
||||
var product1Imaginary = real1 * firstWeightImaginary + imaginary1 * firstWeightReal;
|
||||
var sum0Real = real0 + product1Real;
|
||||
var sum0Imaginary = imaginary0 + product1Imaginary;
|
||||
var sum1Real = real0 - product1Real;
|
||||
var sum1Imaginary = imaginary0 - product1Imaginary;
|
||||
var product3Real = real3 * firstWeightReal - imaginary3 * firstWeightImaginary;
|
||||
var product3Imaginary = real3 * firstWeightImaginary + imaginary3 * firstWeightReal;
|
||||
var sum2Real = real2 + product3Real;
|
||||
var sum2Imaginary = imaginary2 + product3Imaginary;
|
||||
var sum3Real = real2 - product3Real;
|
||||
var sum3Imaginary = imaginary2 - product3Imaginary;
|
||||
|
||||
var evenProductReal = sum2Real * secondEvenWeightReal - sum2Imaginary * secondEvenWeightImaginary;
|
||||
var evenProductImaginary = sum2Real * secondEvenWeightImaginary + sum2Imaginary * secondEvenWeightReal;
|
||||
var oddProductReal = sum3Real * secondOddWeightReal - sum3Imaginary * secondOddWeightImaginary;
|
||||
var oddProductImaginary = sum3Real * secondOddWeightImaginary + sum3Imaginary * secondOddWeightReal;
|
||||
(sum0Real + evenProductReal).StoreUnsafe(ref Unsafe.Add(ref realBase, position0));
|
||||
(sum0Imaginary + evenProductImaginary).StoreUnsafe(ref Unsafe.Add(ref imaginaryBase, position0));
|
||||
(sum0Real - evenProductReal).StoreUnsafe(ref Unsafe.Add(ref realBase, position2));
|
||||
(sum0Imaginary - evenProductImaginary).StoreUnsafe(ref Unsafe.Add(ref imaginaryBase, position2));
|
||||
(sum1Real + oddProductReal).StoreUnsafe(ref Unsafe.Add(ref realBase, position1));
|
||||
(sum1Imaginary + oddProductImaginary).StoreUnsafe(ref Unsafe.Add(ref imaginaryBase, position1));
|
||||
(sum1Real - oddProductReal).StoreUnsafe(ref Unsafe.Add(ref realBase, position3));
|
||||
(sum1Imaginary - oddProductImaginary).StoreUnsafe(ref Unsafe.Add(ref imaginaryBase, position3));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void SingleStage(ref double realBase, ref double imaginaryBase, int count, int stage, Twiddles twiddles)
|
||||
{
|
||||
var width = Vector<double>.Count;
|
||||
var half = 1 << stage;
|
||||
var length = half << 1;
|
||||
ref var cosBase = ref MemoryMarshal.GetArrayDataReference(twiddles.Cos[stage]);
|
||||
ref var sinBase = ref MemoryMarshal.GetArrayDataReference(twiddles.Sin[stage]);
|
||||
var vectorized = Vector.IsHardwareAccelerated && half >= width;
|
||||
|
||||
for (var offset = 0; offset < count; offset += length)
|
||||
{
|
||||
var index = 0;
|
||||
if (vectorized)
|
||||
{
|
||||
for (; index + width <= half; index += width)
|
||||
{
|
||||
var even = offset + index;
|
||||
var odd = even + half;
|
||||
var weightReal = Unsafe.Add(ref cosBase, index);
|
||||
var weightImaginary = Unsafe.Add(ref sinBase, index);
|
||||
var oddReal = Unsafe.Add(ref realBase, odd);
|
||||
var oddImaginary = Unsafe.Add(ref imaginaryBase, odd);
|
||||
var evenReal = Vector.LoadUnsafe(ref Unsafe.Add(ref realBase, even));
|
||||
var evenImaginary = Vector.LoadUnsafe(ref Unsafe.Add(ref imaginaryBase, even));
|
||||
var oddReal = Vector.LoadUnsafe(ref Unsafe.Add(ref realBase, odd));
|
||||
var oddImaginary = Vector.LoadUnsafe(ref Unsafe.Add(ref imaginaryBase, odd));
|
||||
var weightReal = Vector.LoadUnsafe(ref Unsafe.Add(ref cosBase, index));
|
||||
var weightImaginary = Vector.LoadUnsafe(ref Unsafe.Add(ref sinBase, index));
|
||||
var productReal = oddReal * weightReal - oddImaginary * weightImaginary;
|
||||
var productImaginary = oddReal * weightImaginary + oddImaginary * weightReal;
|
||||
var evenReal = Unsafe.Add(ref realBase, even);
|
||||
var evenImaginary = Unsafe.Add(ref imaginaryBase, even);
|
||||
Unsafe.Add(ref realBase, even) = evenReal + productReal;
|
||||
Unsafe.Add(ref imaginaryBase, even) = evenImaginary + productImaginary;
|
||||
Unsafe.Add(ref realBase, odd) = evenReal - productReal;
|
||||
Unsafe.Add(ref imaginaryBase, odd) = evenImaginary - productImaginary;
|
||||
(evenReal + productReal).StoreUnsafe(ref Unsafe.Add(ref realBase, even));
|
||||
(evenImaginary + productImaginary).StoreUnsafe(ref Unsafe.Add(ref imaginaryBase, even));
|
||||
(evenReal - productReal).StoreUnsafe(ref Unsafe.Add(ref realBase, odd));
|
||||
(evenImaginary - productImaginary).StoreUnsafe(ref Unsafe.Add(ref imaginaryBase, odd));
|
||||
}
|
||||
}
|
||||
for (; index < half; index++)
|
||||
{
|
||||
var even = offset + index;
|
||||
var odd = even + half;
|
||||
var weightReal = Unsafe.Add(ref cosBase, index);
|
||||
var weightImaginary = Unsafe.Add(ref sinBase, index);
|
||||
var oddReal = Unsafe.Add(ref realBase, odd);
|
||||
var oddImaginary = Unsafe.Add(ref imaginaryBase, odd);
|
||||
var productReal = oddReal * weightReal - oddImaginary * weightImaginary;
|
||||
var productImaginary = oddReal * weightImaginary + oddImaginary * weightReal;
|
||||
var evenReal = Unsafe.Add(ref realBase, even);
|
||||
var evenImaginary = Unsafe.Add(ref imaginaryBase, even);
|
||||
Unsafe.Add(ref realBase, even) = evenReal + productReal;
|
||||
Unsafe.Add(ref imaginaryBase, even) = evenImaginary + productImaginary;
|
||||
Unsafe.Add(ref realBase, odd) = evenReal - productReal;
|
||||
Unsafe.Add(ref imaginaryBase, odd) = evenImaginary - productImaginary;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -178,15 +294,32 @@ internal static class FastFourierTransform
|
||||
}
|
||||
|
||||
static Twiddles GetTwiddles(int count, bool inverse) =>
|
||||
TwiddleCache.GetOrAdd(((long)count << 1) | (inverse ? 1L : 0L), static key => new Twiddles((int)(key >> 1), (key & 1L) != 0));
|
||||
TwiddleCache.GetOrAdd(new TwiddleKey(count, inverse), static key => new Twiddles(key.Count, key.Inverse));
|
||||
|
||||
readonly record struct TwiddleKey(int Count, bool Inverse);
|
||||
|
||||
sealed class Twiddles
|
||||
{
|
||||
public double[][] Cos { get; }
|
||||
public double[][] Sin { get; }
|
||||
public int[] Swaps { get; }
|
||||
|
||||
public Twiddles(int count, bool inverse)
|
||||
{
|
||||
var swaps = new List<int>();
|
||||
for (int source = 1, target = 0; source < count; source++)
|
||||
{
|
||||
var bit = count >> 1;
|
||||
for (; (target & bit) != 0; bit >>= 1)
|
||||
target ^= bit;
|
||||
target ^= bit;
|
||||
if (source < target)
|
||||
{
|
||||
swaps.Add(source);
|
||||
swaps.Add(target);
|
||||
}
|
||||
}
|
||||
Swaps = [.. swaps];
|
||||
var stages = BitOperations.TrailingZeroCount(count);
|
||||
Cos = new double[stages][];
|
||||
Sin = new double[stages][];
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
using ComputeWeave;
|
||||
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal static class FftShaderMath
|
||||
{
|
||||
public const float Forward = 1f;
|
||||
public const float Inverse = -1f;
|
||||
public const int Radix4Elements = 1 << Radix4Bits;
|
||||
public const int StageUnitsPerGroup = TilePlan.GroupElements / Radix4Elements;
|
||||
|
||||
const int UIntBits = 32;
|
||||
const int Radix2Bits = 1;
|
||||
const int Radix4Bits = 2;
|
||||
|
||||
public static int Pow2(int exponent) => (int)(1u << exponent);
|
||||
|
||||
public static int BitReverse(int index, int log2Size) => (int)(Hlsl.ReverseBits((uint)index) >> (UIntBits - log2Size));
|
||||
|
||||
public static int Position(int index, int stage) => index & (Pow2(stage) - 1);
|
||||
|
||||
public static int TwiddleIndex(int position, int log2Size, int stage) => position << (log2Size - 1 - stage);
|
||||
|
||||
public static int Radix2Even(int index, int log2Size, int stage) => Locate(index, log2Size, stage, Radix2Bits);
|
||||
|
||||
public static int Radix4First(int index, int log2Size, int stage) => Locate(index, log2Size, stage, Radix4Bits);
|
||||
|
||||
public static Float4 Rotate(Float4 value, float real, float imaginary)
|
||||
=> new(
|
||||
value.X * real - value.Y * imaginary,
|
||||
value.X * imaginary + value.Y * real,
|
||||
value.Z * real - value.W * imaginary,
|
||||
value.Z * imaginary + value.W * real);
|
||||
|
||||
public static Float4 Multiply(Float4 value, Float2 weight) => Rotate(value, weight.X, weight.Y);
|
||||
|
||||
public static Float4 Multiply(Float4 value, Float2 firstWeight, Float2 secondWeight)
|
||||
=> new(
|
||||
value.X * firstWeight.X - value.Y * firstWeight.Y,
|
||||
value.X * firstWeight.Y + value.Y * firstWeight.X,
|
||||
value.Z * secondWeight.X - value.W * secondWeight.Y,
|
||||
value.Z * secondWeight.Y + value.W * secondWeight.X);
|
||||
|
||||
public static void Radix2(ref Float4 even, ref Float4 odd, Float2 twiddle, float direction)
|
||||
{
|
||||
var product = Rotate(odd, twiddle.X, twiddle.Y * direction);
|
||||
var evenValue = even;
|
||||
even = evenValue + product;
|
||||
odd = evenValue - product;
|
||||
}
|
||||
|
||||
public static void Radix4(
|
||||
ref Float4 first,
|
||||
ref Float4 second,
|
||||
ref Float4 third,
|
||||
ref Float4 fourth,
|
||||
Float2 stageTwiddle,
|
||||
Float2 nextEvenTwiddle,
|
||||
Float2 nextOddTwiddle,
|
||||
float direction)
|
||||
{
|
||||
var secondProduct = Rotate(second, stageTwiddle.X, stageTwiddle.Y * direction);
|
||||
var fourthProduct = Rotate(fourth, stageTwiddle.X, stageTwiddle.Y * direction);
|
||||
var firstSum = first + secondProduct;
|
||||
var secondSum = first - secondProduct;
|
||||
var thirdSum = third + fourthProduct;
|
||||
var fourthSum = third - fourthProduct;
|
||||
var evenProduct = Rotate(thirdSum, nextEvenTwiddle.X, nextEvenTwiddle.Y * direction);
|
||||
var oddProduct = Rotate(fourthSum, nextOddTwiddle.X, nextOddTwiddle.Y * direction);
|
||||
first = firstSum + evenProduct;
|
||||
third = firstSum - evenProduct;
|
||||
second = secondSum + oddProduct;
|
||||
fourth = secondSum - oddProduct;
|
||||
}
|
||||
|
||||
static int Locate(int index, int log2Size, int stage, int radixBits)
|
||||
{
|
||||
var laneBits = log2Size - radixBits;
|
||||
var row = (index >> laneBits) << log2Size;
|
||||
var lane = index & (Pow2(laneBits) - 1);
|
||||
return row + ((lane >> stage) << (stage + radixBits)) + Position(lane, stage);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
using ComputeWeave;
|
||||
|
||||
namespace SpectralConvolution;
|
||||
|
||||
[ThreadGroupSize(TilePlan.GroupThreads, 1, 1)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
[CompileOptions(CompileOptions.Default | CompileOptions.IeeeStrictness)]
|
||||
internal readonly partial struct ColumnChromaticShader(
|
||||
ReadWriteBuffer<Float4> tiles,
|
||||
ReadOnlyBuffer<Float2> twiddles,
|
||||
ReadOnlyBuffer<Float2> spectrum,
|
||||
int log2Size) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<Float4> tiles = tiles;
|
||||
private readonly ReadOnlyBuffer<Float2> twiddles = twiddles;
|
||||
private readonly ReadOnlyBuffer<Float2> spectrum = spectrum;
|
||||
private readonly int log2Size = log2Size;
|
||||
|
||||
[GroupShared(TilePlan.ChromaticGroupElements)]
|
||||
private static readonly Float4[] row = null!;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var local = GroupIds.X;
|
||||
var group = GridIds.X;
|
||||
var size = (int)(1u << log2Size);
|
||||
var mask = size - 1;
|
||||
var halfColumns = ChromaticKernelSpectrum.HalfColumnsOf(size);
|
||||
var unitsPerGroup = TilePlan.GroupElements / size;
|
||||
var groupsPerTile = (halfColumns + unitsPerGroup - 1) / unitsPerGroup;
|
||||
var tile = group / groupsPerTile;
|
||||
var firstColumn = group % groupsPerTile * unitsPerGroup;
|
||||
var tileBase = tile << (log2Size * 2);
|
||||
var planeLength = halfColumns * size;
|
||||
|
||||
for (var step = 0; step < TilePlan.ValuesPerThread; step++)
|
||||
{
|
||||
var pair = local + step * TilePlan.GroupThreads;
|
||||
var unit = pair % unitsPerGroup;
|
||||
var y = pair / unitsPerGroup;
|
||||
var column = firstColumn + unit;
|
||||
var redGreen = new Float4(0f, 0f, 0f, 0f);
|
||||
var blueAlpha = new Float4(0f, 0f, 0f, 0f);
|
||||
if (column < halfColumns)
|
||||
{
|
||||
var near = tiles[tileBase + (y << log2Size) + column];
|
||||
var far = tiles[tileBase + (y << log2Size) + ((size - column) & mask)];
|
||||
redGreen = new Float4(near.X + far.X, near.Y - far.Y, near.Y + far.Y, far.X - near.X) * 0.5f;
|
||||
blueAlpha = new Float4(near.Z + far.Z, near.W - far.W, near.W + far.W, far.Z - near.Z) * 0.5f;
|
||||
}
|
||||
|
||||
var reversed = FftShaderMath.BitReverse(y, log2Size);
|
||||
var redGreenRow = (unit * TilePlan.ChromaticPlanes) << log2Size;
|
||||
row[redGreenRow + reversed] = redGreen;
|
||||
row[redGreenRow + size + reversed] = blueAlpha;
|
||||
}
|
||||
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
Butterflies(local, FftShaderMath.Forward);
|
||||
|
||||
var product0 = Multiply(local, planeLength, halfColumns, firstColumn, mask, 0);
|
||||
var product1 = Multiply(local, planeLength, halfColumns, firstColumn, mask, 1);
|
||||
var product2 = Multiply(local, planeLength, halfColumns, firstColumn, mask, 2);
|
||||
var product3 = Multiply(local, planeLength, halfColumns, firstColumn, mask, 3);
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
row[ReversedIndex(local, mask, 0)] = product0;
|
||||
row[ReversedIndex(local, mask, 1)] = product1;
|
||||
row[ReversedIndex(local, mask, 2)] = product2;
|
||||
row[ReversedIndex(local, mask, 3)] = product3;
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
Butterflies(local, FftShaderMath.Inverse);
|
||||
|
||||
for (var step = 0; step < TilePlan.ValuesPerThread; step++)
|
||||
{
|
||||
var pair = local + step * TilePlan.GroupThreads;
|
||||
var unit = pair % unitsPerGroup;
|
||||
var y = pair / unitsPerGroup;
|
||||
var column = firstColumn + unit;
|
||||
if (column >= halfColumns)
|
||||
continue;
|
||||
|
||||
var redGreenRow = (unit * TilePlan.ChromaticPlanes) << log2Size;
|
||||
var redGreen = row[redGreenRow + y];
|
||||
var blueAlpha = row[redGreenRow + size + y];
|
||||
var address = tileBase + (y << log2Size);
|
||||
tiles[address + column] = new Float4(
|
||||
redGreen.X - redGreen.W,
|
||||
redGreen.Y + redGreen.Z,
|
||||
blueAlpha.X - blueAlpha.W,
|
||||
blueAlpha.Y + blueAlpha.Z);
|
||||
var mirror = (size - column) & mask;
|
||||
if (mirror != column)
|
||||
{
|
||||
tiles[address + mirror] = new Float4(
|
||||
redGreen.X + redGreen.W,
|
||||
redGreen.Z - redGreen.Y,
|
||||
blueAlpha.X + blueAlpha.W,
|
||||
blueAlpha.Z - blueAlpha.Y);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int ReversedIndex(int local, int mask, int part)
|
||||
{
|
||||
var element = local + part * TilePlan.GroupThreads;
|
||||
return (element & ~mask) + FftShaderMath.BitReverse(element & mask, log2Size);
|
||||
}
|
||||
|
||||
private Float4 Multiply(int local, int planeLength, int halfColumns, int firstColumn, int mask, int part)
|
||||
{
|
||||
var element = local + part * TilePlan.GroupThreads;
|
||||
var line = element >> log2Size;
|
||||
var frequency = element & mask;
|
||||
var column = firstColumn + (line / TilePlan.ChromaticPlanes);
|
||||
if (column >= halfColumns)
|
||||
return new Float4(0f, 0f, 0f, 0f);
|
||||
|
||||
var value = row[element];
|
||||
var index = (column << log2Size) + frequency;
|
||||
var firstChannel = line % TilePlan.ChromaticPlanes == 0 ? ChromaticChannels.Red : ChromaticChannels.Blue;
|
||||
var first = spectrum[firstChannel * planeLength + index];
|
||||
var second = spectrum[ChromaticChannels.Green * planeLength + index];
|
||||
return FftShaderMath.Multiply(value, first, second);
|
||||
}
|
||||
|
||||
private void Butterflies(int local, float direction)
|
||||
{
|
||||
var stage = 0;
|
||||
for (; stage + 1 < log2Size; stage += 2)
|
||||
{
|
||||
var step = FftShaderMath.Pow2(stage);
|
||||
var position = FftShaderMath.Position(local, stage);
|
||||
var first = FftShaderMath.Radix4First(local, log2Size, stage);
|
||||
var second = first + step;
|
||||
var third = second + step;
|
||||
var fourth = third + step;
|
||||
var value0 = row[first];
|
||||
var value1 = row[second];
|
||||
var value2 = row[third];
|
||||
var value3 = row[fourth];
|
||||
FftShaderMath.Radix4(
|
||||
ref value0,
|
||||
ref value1,
|
||||
ref value2,
|
||||
ref value3,
|
||||
twiddles[FftShaderMath.TwiddleIndex(position, log2Size, stage)],
|
||||
twiddles[FftShaderMath.TwiddleIndex(position, log2Size, stage + 1)],
|
||||
twiddles[FftShaderMath.TwiddleIndex(position + step, log2Size, stage + 1)],
|
||||
direction);
|
||||
row[first] = value0;
|
||||
row[second] = value1;
|
||||
row[third] = value2;
|
||||
row[fourth] = value3;
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
|
||||
for (; stage < log2Size; stage++)
|
||||
{
|
||||
for (var step = 0; step < TilePlan.ValuesPerThread; step++)
|
||||
{
|
||||
var index = local + step * TilePlan.GroupThreads;
|
||||
var even = FftShaderMath.Radix2Even(index, log2Size, stage);
|
||||
var odd = even + FftShaderMath.Pow2(stage);
|
||||
var evenValue = row[even];
|
||||
var oddValue = row[odd];
|
||||
FftShaderMath.Radix2(
|
||||
ref evenValue,
|
||||
ref oddValue,
|
||||
twiddles[FftShaderMath.TwiddleIndex(FftShaderMath.Position(index, stage), log2Size, stage)],
|
||||
direction);
|
||||
row[even] = evenValue;
|
||||
row[odd] = oddValue;
|
||||
}
|
||||
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,527 @@
|
||||
using ComputeWeave;
|
||||
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal static class LightShaderMath
|
||||
{
|
||||
public static float Decode(float encoded)
|
||||
{
|
||||
if (encoded <= LightTransform.DecodeToeLimit)
|
||||
return encoded / LightTransform.ToeSlope;
|
||||
if (encoded >= 1f)
|
||||
return 1f;
|
||||
return Hlsl.Pow((encoded + LightTransform.Offset) / LightTransform.Scale, LightTransform.DecodeExponent);
|
||||
}
|
||||
|
||||
public static float Encode(float linear)
|
||||
{
|
||||
if (linear <= LightTransform.EncodeToeLimit)
|
||||
return LightTransform.ToeSlope * linear;
|
||||
if (linear >= 1f)
|
||||
return 1f;
|
||||
return LightTransform.Scale * Hlsl.Pow(linear, LightTransform.EncodeExponent) - LightTransform.Offset;
|
||||
}
|
||||
}
|
||||
|
||||
internal static class LightShaderOutput
|
||||
{
|
||||
public static float Quantize(float value, int dither, float threshold)
|
||||
{
|
||||
if (dither == 0)
|
||||
return Hlsl.Floor(value * ByteColor.Scale + ByteColor.Rounding);
|
||||
return Hlsl.Min(Hlsl.Floor(value * ByteColor.Scale + threshold), ByteColor.Scale);
|
||||
}
|
||||
|
||||
public static Float4 Convert(Float4 value, float gain, int linear, int dither, int x, int y)
|
||||
{
|
||||
var red = 0f;
|
||||
var green = 0f;
|
||||
var blue = 0f;
|
||||
var alpha = 0f;
|
||||
if (linear != 0)
|
||||
{
|
||||
alpha = Hlsl.Saturate(value.W * gain);
|
||||
if (alpha > 0f)
|
||||
{
|
||||
red = LightShaderMath.Encode(Hlsl.Min(Hlsl.Saturate(value.X * gain), alpha) / alpha) * alpha;
|
||||
green = LightShaderMath.Encode(Hlsl.Min(Hlsl.Saturate(value.Y * gain), alpha) / alpha) * alpha;
|
||||
blue = LightShaderMath.Encode(Hlsl.Min(Hlsl.Saturate(value.Z * gain), alpha) / alpha) * alpha;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
red = Hlsl.Saturate(value.X * gain);
|
||||
green = Hlsl.Saturate(value.Y * gain);
|
||||
blue = Hlsl.Saturate(value.Z * gain);
|
||||
alpha = Hlsl.Saturate(value.W * gain);
|
||||
}
|
||||
|
||||
var threshold = 0f;
|
||||
if (dither != 0)
|
||||
threshold = LightTransform.DitherThreshold(x, y);
|
||||
return new Float4(
|
||||
Quantize(red, dither, threshold) / ByteColor.Scale,
|
||||
Quantize(green, dither, threshold) / ByteColor.Scale,
|
||||
Quantize(blue, dither, threshold) / ByteColor.Scale,
|
||||
Quantize(alpha, dither, threshold) / ByteColor.Scale);
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(DefaultThreadGroupSizes.XY)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
[CompileOptions(CompileOptions.Default | CompileOptions.IeeeStrictness)]
|
||||
internal readonly partial struct StoredRenderLightShader(
|
||||
ReadWriteBuffer<Float4> store,
|
||||
ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
int width,
|
||||
int height,
|
||||
float gain,
|
||||
int linear,
|
||||
int dither,
|
||||
int originX,
|
||||
int originY) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<Float4> store = store;
|
||||
private readonly ReadWriteTexture2D<Bgra32, Float4> output = output;
|
||||
private readonly int width = width;
|
||||
private readonly int height = height;
|
||||
private readonly float gain = gain;
|
||||
private readonly int linear = linear;
|
||||
private readonly int dither = dither;
|
||||
private readonly int originX = originX;
|
||||
private readonly int originY = originY;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
if (ThreadIds.X >= width || ThreadIds.Y >= height)
|
||||
return;
|
||||
output[ThreadIds.XY] = LightShaderOutput.Convert(
|
||||
store[ThreadIds.Y * width + ThreadIds.X], gain, linear, dither, originX + ThreadIds.X, originY + ThreadIds.Y);
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(TilePlan.GroupThreads, 1, 1)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
[CompileOptions(CompileOptions.Default | CompileOptions.IeeeStrictness)]
|
||||
internal readonly partial struct ForwardRowLightShader(
|
||||
ReadWriteTexture2D<Bgra32, Float4> source,
|
||||
ReadWriteBuffer<Float4> tiles,
|
||||
ReadOnlyBuffer<Float2> twiddles,
|
||||
ReadWriteBuffer<uint> report,
|
||||
int log2Size,
|
||||
int radius,
|
||||
int validSize,
|
||||
int tilesX,
|
||||
int batchStart,
|
||||
int regionX,
|
||||
int regionY,
|
||||
int regionWidth,
|
||||
int regionHeight,
|
||||
int sourceX,
|
||||
int sourceY,
|
||||
int sourceWidth,
|
||||
int sourceHeight,
|
||||
int statisticsOffset,
|
||||
int groupStart,
|
||||
int linear,
|
||||
int highlights,
|
||||
float threshold,
|
||||
float boost) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteTexture2D<Bgra32, Float4> source = source;
|
||||
private readonly ReadWriteBuffer<Float4> tiles = tiles;
|
||||
private readonly ReadOnlyBuffer<Float2> twiddles = twiddles;
|
||||
private readonly ReadWriteBuffer<uint> report = report;
|
||||
private readonly int log2Size = log2Size;
|
||||
private readonly int radius = radius;
|
||||
private readonly int validSize = validSize;
|
||||
private readonly int tilesX = tilesX;
|
||||
private readonly int batchStart = batchStart;
|
||||
private readonly int regionX = regionX;
|
||||
private readonly int regionY = regionY;
|
||||
private readonly int regionWidth = regionWidth;
|
||||
private readonly int regionHeight = regionHeight;
|
||||
private readonly int sourceX = sourceX;
|
||||
private readonly int sourceY = sourceY;
|
||||
private readonly int sourceWidth = sourceWidth;
|
||||
private readonly int sourceHeight = sourceHeight;
|
||||
private readonly int statisticsOffset = statisticsOffset;
|
||||
private readonly int groupStart = groupStart;
|
||||
private readonly int linear = linear;
|
||||
private readonly int highlights = highlights;
|
||||
private readonly float threshold = threshold;
|
||||
private readonly float boost = boost;
|
||||
|
||||
[GroupShared(TilePlan.GroupElements)]
|
||||
private static readonly Float4[] row = null!;
|
||||
|
||||
[GroupShared(TilePlan.GroupThreads)]
|
||||
private static readonly Float4[] partialSums = null!;
|
||||
|
||||
[GroupShared(TilePlan.GroupThreads)]
|
||||
private static readonly Float2[] partialSquares = null!;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var local = GroupIds.X;
|
||||
var groupBase = GridIds.X * TilePlan.GroupElements;
|
||||
var size = (int)(1u << log2Size);
|
||||
var mask = size - 1;
|
||||
|
||||
var origin = TileShaderMath.TileOrigin(TileShaderMath.TileIndex(batchStart, groupBase, log2Size), tilesX, validSize, radius);
|
||||
var originX = regionX + origin.X;
|
||||
var originY = regionY + origin.Y;
|
||||
|
||||
var sums = new Float4(0f, 0f, 0f, 0f);
|
||||
var squares = new Float2(0f, 0f);
|
||||
for (var pair = 0; pair < TilePlan.ValuesPerThread; pair++)
|
||||
{
|
||||
var element = local * TilePlan.ValuesPerThread + pair;
|
||||
var flat = groupBase + element;
|
||||
var rest = flat & (size * size - 1);
|
||||
var y = rest >> log2Size;
|
||||
var x = rest & mask;
|
||||
var canvasX = originX + x;
|
||||
var canvasY = originY + y;
|
||||
var value = new Float4(0f, 0f, 0f, 0f);
|
||||
var column = canvasX - sourceX;
|
||||
var line = canvasY - sourceY;
|
||||
if (column >= 0 && column < sourceWidth && line >= 0 && line < sourceHeight)
|
||||
{
|
||||
value = Transform(source[new Int2(column, line)]);
|
||||
squares = new Float2(
|
||||
squares.X + (value.X * value.X + value.Y * value.Y),
|
||||
squares.Y + (value.Z * value.Z + value.W * value.W));
|
||||
if (x >= radius && x < size - radius && y >= radius && y < size - radius
|
||||
&& canvasX < regionX + regionWidth && canvasY < regionY + regionHeight)
|
||||
sums = sums + value;
|
||||
}
|
||||
|
||||
var reversed = FftShaderMath.BitReverse(x, log2Size);
|
||||
row[((element >> log2Size) << log2Size) + reversed] = value;
|
||||
}
|
||||
|
||||
partialSums[local] = sums;
|
||||
partialSquares[local] = squares;
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
for (var stride = TilePlan.GroupThreads / 2; stride > 0; stride >>= 1)
|
||||
{
|
||||
if (local < stride)
|
||||
{
|
||||
partialSums[local] = partialSums[local] + partialSums[local + stride];
|
||||
partialSquares[local] = partialSquares[local] + partialSquares[local + stride];
|
||||
}
|
||||
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
|
||||
if (local == 0)
|
||||
{
|
||||
var offset = statisticsOffset + (groupStart + GridIds.X) * GpuTileLayout.StatisticsPerGroup;
|
||||
report[offset] = Hlsl.AsUInt(partialSums[0].X);
|
||||
report[offset + 1] = Hlsl.AsUInt(partialSums[0].Y);
|
||||
report[offset + 2] = Hlsl.AsUInt(partialSums[0].Z);
|
||||
report[offset + 3] = Hlsl.AsUInt(partialSums[0].W);
|
||||
report[offset + 4] = Hlsl.AsUInt(partialSquares[0].X);
|
||||
report[offset + 5] = Hlsl.AsUInt(partialSquares[0].Y);
|
||||
}
|
||||
|
||||
Butterflies(local, FftShaderMath.Forward);
|
||||
|
||||
var element0 = local * TilePlan.ValuesPerThread;
|
||||
var element1 = element0 + 1;
|
||||
tiles[groupBase + element0] = row[element0];
|
||||
tiles[groupBase + element1] = row[element1];
|
||||
}
|
||||
|
||||
private Float4 Transform(Float4 value)
|
||||
{
|
||||
if (linear == 0)
|
||||
return value;
|
||||
|
||||
var red = (float)ByteColor.ToLevel(value.X);
|
||||
var green = (float)ByteColor.ToLevel(value.Y);
|
||||
var blue = (float)ByteColor.ToLevel(value.Z);
|
||||
var alpha = (float)ByteColor.ToLevel(value.W);
|
||||
if (alpha == 0f)
|
||||
return new Float4(0f, 0f, 0f, 0f);
|
||||
|
||||
var opacity = alpha / ByteColor.Scale;
|
||||
var straightRed = red / ByteColor.Scale;
|
||||
var straightGreen = green / ByteColor.Scale;
|
||||
var straightBlue = blue / ByteColor.Scale;
|
||||
if (alpha != ByteColor.Scale)
|
||||
{
|
||||
straightRed = Hlsl.Min(red / alpha, 1f);
|
||||
straightGreen = Hlsl.Min(green / alpha, 1f);
|
||||
straightBlue = Hlsl.Min(blue / alpha, 1f);
|
||||
}
|
||||
|
||||
var linearRed = LightShaderMath.Decode(straightRed);
|
||||
var linearGreen = LightShaderMath.Decode(straightGreen);
|
||||
var linearBlue = LightShaderMath.Decode(straightBlue);
|
||||
var weight = 1f;
|
||||
if (highlights != 0)
|
||||
{
|
||||
var peak = Hlsl.Max(Hlsl.Max(straightRed, straightGreen), straightBlue);
|
||||
var excess = Hlsl.Min(Hlsl.Max((peak - threshold) / (1f - threshold), 0f), 1f);
|
||||
weight = 1f + (boost - 1f) * excess * excess;
|
||||
}
|
||||
|
||||
var scale = opacity * weight;
|
||||
return new Float4(linearRed * scale, linearGreen * scale, linearBlue * scale, scale);
|
||||
}
|
||||
|
||||
private void Butterflies(int local, float direction)
|
||||
{
|
||||
var stage = 0;
|
||||
for (; stage + 1 < log2Size; stage += 2)
|
||||
{
|
||||
if (local < FftShaderMath.StageUnitsPerGroup)
|
||||
{
|
||||
var step = FftShaderMath.Pow2(stage);
|
||||
var position = FftShaderMath.Position(local, stage);
|
||||
var first = FftShaderMath.Radix4First(local, log2Size, stage);
|
||||
var second = first + step;
|
||||
var third = second + step;
|
||||
var fourth = third + step;
|
||||
var value0 = row[first];
|
||||
var value1 = row[second];
|
||||
var value2 = row[third];
|
||||
var value3 = row[fourth];
|
||||
FftShaderMath.Radix4(
|
||||
ref value0,
|
||||
ref value1,
|
||||
ref value2,
|
||||
ref value3,
|
||||
twiddles[FftShaderMath.TwiddleIndex(position, log2Size, stage)],
|
||||
twiddles[FftShaderMath.TwiddleIndex(position, log2Size, stage + 1)],
|
||||
twiddles[FftShaderMath.TwiddleIndex(position + step, log2Size, stage + 1)],
|
||||
direction);
|
||||
row[first] = value0;
|
||||
row[second] = value1;
|
||||
row[third] = value2;
|
||||
row[fourth] = value3;
|
||||
}
|
||||
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
|
||||
for (; stage < log2Size; stage++)
|
||||
{
|
||||
var even = FftShaderMath.Radix2Even(local, log2Size, stage);
|
||||
var odd = even + FftShaderMath.Pow2(stage);
|
||||
var evenValue = row[even];
|
||||
var oddValue = row[odd];
|
||||
FftShaderMath.Radix2(
|
||||
ref evenValue,
|
||||
ref oddValue,
|
||||
twiddles[FftShaderMath.TwiddleIndex(FftShaderMath.Position(local, stage), log2Size, stage)],
|
||||
direction);
|
||||
row[even] = evenValue;
|
||||
row[odd] = oddValue;
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(TilePlan.GroupThreads, 1, 1)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
[CompileOptions(CompileOptions.Default | CompileOptions.IeeeStrictness)]
|
||||
internal readonly partial struct InverseRowLightShader(
|
||||
ReadWriteBuffer<Float4> tiles,
|
||||
ReadOnlyBuffer<Float2> twiddles,
|
||||
ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
ReadWriteBuffer<uint> report,
|
||||
ReadOnlyBuffer<Int2> samples,
|
||||
ReadWriteBuffer<Float4> store,
|
||||
int log2Size,
|
||||
int radius,
|
||||
int validSize,
|
||||
int tilesX,
|
||||
int batchStart,
|
||||
int regionX,
|
||||
int regionY,
|
||||
int regionWidth,
|
||||
int regionHeight,
|
||||
float scale,
|
||||
float gain,
|
||||
int sampleCount,
|
||||
int sumsOffset,
|
||||
int spotsOffset,
|
||||
int groupStart,
|
||||
int storeValues,
|
||||
int linear,
|
||||
int dither,
|
||||
int sampleTilesOffset) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<Float4> tiles = tiles;
|
||||
private readonly ReadOnlyBuffer<Float2> twiddles = twiddles;
|
||||
private readonly ReadWriteTexture2D<Bgra32, Float4> output = output;
|
||||
private readonly ReadWriteBuffer<uint> report = report;
|
||||
private readonly ReadOnlyBuffer<Int2> samples = samples;
|
||||
private readonly ReadWriteBuffer<Float4> store = store;
|
||||
private readonly int log2Size = log2Size;
|
||||
private readonly int radius = radius;
|
||||
private readonly int validSize = validSize;
|
||||
private readonly int tilesX = tilesX;
|
||||
private readonly int batchStart = batchStart;
|
||||
private readonly int regionX = regionX;
|
||||
private readonly int regionY = regionY;
|
||||
private readonly int regionWidth = regionWidth;
|
||||
private readonly int regionHeight = regionHeight;
|
||||
private readonly float scale = scale;
|
||||
private readonly float gain = gain;
|
||||
private readonly int sampleCount = sampleCount;
|
||||
private readonly int sumsOffset = sumsOffset;
|
||||
private readonly int spotsOffset = spotsOffset;
|
||||
private readonly int groupStart = groupStart;
|
||||
private readonly int storeValues = storeValues;
|
||||
private readonly int linear = linear;
|
||||
private readonly int dither = dither;
|
||||
private readonly int sampleTilesOffset = sampleTilesOffset;
|
||||
|
||||
[GroupShared(TilePlan.GroupElements)]
|
||||
private static readonly Float4[] row = null!;
|
||||
|
||||
[GroupShared(TilePlan.GroupThreads)]
|
||||
private static readonly Float4[] partial = null!;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var local = GroupIds.X;
|
||||
var groupBase = GridIds.X * TilePlan.GroupElements;
|
||||
var size = (int)(1u << log2Size);
|
||||
var mask = size - 1;
|
||||
var element0 = local * TilePlan.ValuesPerThread;
|
||||
var element1 = element0 + 1;
|
||||
row[((element0 >> log2Size) << log2Size) + FftShaderMath.BitReverse(element0 & mask, log2Size)] = tiles[groupBase + element0];
|
||||
row[((element1 >> log2Size) << log2Size) + FftShaderMath.BitReverse(element1 & mask, log2Size)] = tiles[groupBase + element1];
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
Butterflies(local, FftShaderMath.Inverse);
|
||||
|
||||
var tileIndex = TileShaderMath.TileIndex(batchStart, groupBase, log2Size);
|
||||
var origin = TileShaderMath.TileOrigin(tileIndex, tilesX, validSize, radius);
|
||||
var tileHoldsSample = sampleCount > 0 && TileHoldsSample(tileIndex);
|
||||
partial[local] = Emit(groupBase + element0, row[element0] * scale, origin, tileHoldsSample)
|
||||
+ Emit(groupBase + element1, row[element1] * scale, origin, tileHoldsSample);
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
for (var stride = TilePlan.GroupThreads / 2; stride > 0; stride >>= 1)
|
||||
{
|
||||
if (local < stride)
|
||||
partial[local] = partial[local] + partial[local + stride];
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
|
||||
if (local == 0)
|
||||
{
|
||||
var sum = partial[0];
|
||||
var offset = sumsOffset + (groupStart + GridIds.X) * GpuTileLayout.SumsPerGroup;
|
||||
report[offset] = Hlsl.AsUInt(sum.X);
|
||||
report[offset + 1] = Hlsl.AsUInt(sum.Y);
|
||||
report[offset + 2] = Hlsl.AsUInt(sum.Z);
|
||||
report[offset + 3] = Hlsl.AsUInt(sum.W);
|
||||
}
|
||||
}
|
||||
|
||||
private bool TileHoldsSample(int tileIndex)
|
||||
{
|
||||
var word = tileIndex / GpuTileConvolver.SampleTilesPerWord;
|
||||
var entry = samples[sampleTilesOffset + word / GpuTileConvolver.WordsPerSampleEntry];
|
||||
var bits = word % GpuTileConvolver.WordsPerSampleEntry == 0 ? (uint)entry.X : (uint)entry.Y;
|
||||
return ((bits >> (tileIndex % GpuTileConvolver.SampleTilesPerWord)) & 1u) != 0u;
|
||||
}
|
||||
|
||||
private Float4 Emit(int flat, Float4 value, Int2 origin, bool tileHoldsSample)
|
||||
{
|
||||
if (TileShaderMath.IsNonFinite(value))
|
||||
Hlsl.InterlockedAdd(ref report[GpuTileLayout.CountOffset], 1u);
|
||||
|
||||
var size = (int)(1u << log2Size);
|
||||
var mask = size - 1;
|
||||
var rest = flat & (size * size - 1);
|
||||
var y = rest >> log2Size;
|
||||
var x = rest & mask;
|
||||
if (x < radius || x >= size - radius || y < radius || y >= size - radius)
|
||||
return new Float4(0f, 0f, 0f, 0f);
|
||||
|
||||
var outputX = origin.X + x;
|
||||
var outputY = origin.Y + y;
|
||||
if (outputX >= regionWidth || outputY >= regionHeight)
|
||||
return new Float4(0f, 0f, 0f, 0f);
|
||||
|
||||
output[new Int2(outputX, outputY)] = LightShaderOutput.Convert(value, gain, linear, dither, regionX + outputX, regionY + outputY);
|
||||
if (storeValues != 0)
|
||||
store[outputY * regionWidth + outputX] = value;
|
||||
if (tileHoldsSample)
|
||||
{
|
||||
for (var sample = 0; sample < sampleCount; sample++)
|
||||
{
|
||||
var position = samples[sample];
|
||||
if (position.X == outputX && position.Y == outputY)
|
||||
{
|
||||
var spot = spotsOffset + sample * GpuTileLayout.ValuesPerSpot;
|
||||
report[spot] = Hlsl.AsUInt(value.X);
|
||||
report[spot + 1] = Hlsl.AsUInt(value.Y);
|
||||
report[spot + 2] = Hlsl.AsUInt(value.Z);
|
||||
report[spot + 3] = Hlsl.AsUInt(value.W);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
private void Butterflies(int local, float direction)
|
||||
{
|
||||
var stage = 0;
|
||||
for (; stage + 1 < log2Size; stage += 2)
|
||||
{
|
||||
if (local < FftShaderMath.StageUnitsPerGroup)
|
||||
{
|
||||
var step = FftShaderMath.Pow2(stage);
|
||||
var position = FftShaderMath.Position(local, stage);
|
||||
var first = FftShaderMath.Radix4First(local, log2Size, stage);
|
||||
var second = first + step;
|
||||
var third = second + step;
|
||||
var fourth = third + step;
|
||||
var value0 = row[first];
|
||||
var value1 = row[second];
|
||||
var value2 = row[third];
|
||||
var value3 = row[fourth];
|
||||
FftShaderMath.Radix4(
|
||||
ref value0,
|
||||
ref value1,
|
||||
ref value2,
|
||||
ref value3,
|
||||
twiddles[FftShaderMath.TwiddleIndex(position, log2Size, stage)],
|
||||
twiddles[FftShaderMath.TwiddleIndex(position, log2Size, stage + 1)],
|
||||
twiddles[FftShaderMath.TwiddleIndex(position + step, log2Size, stage + 1)],
|
||||
direction);
|
||||
row[first] = value0;
|
||||
row[second] = value1;
|
||||
row[third] = value2;
|
||||
row[fourth] = value3;
|
||||
}
|
||||
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
|
||||
for (; stage < log2Size; stage++)
|
||||
{
|
||||
var even = FftShaderMath.Radix2Even(local, log2Size, stage);
|
||||
var odd = even + FftShaderMath.Pow2(stage);
|
||||
var evenValue = row[even];
|
||||
var oddValue = row[odd];
|
||||
FftShaderMath.Radix2(
|
||||
ref evenValue,
|
||||
ref oddValue,
|
||||
twiddles[FftShaderMath.TwiddleIndex(FftShaderMath.Position(local, stage), log2Size, stage)],
|
||||
direction);
|
||||
row[even] = evenValue;
|
||||
row[odd] = oddValue;
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,8 +10,9 @@ internal readonly record struct ConvolutionMeasurement(string Name, double Measu
|
||||
internal static class GpuTileCheck
|
||||
{
|
||||
public const string NonFiniteName = "nonfinite";
|
||||
public const int GroupAdditions = 9;
|
||||
public const int GroupElements = TilePlan.GroupElements;
|
||||
public const int GroupAdditions = TilePlan.GroupElementsLog2;
|
||||
public const int InputStatisticsOperations = 16;
|
||||
public static readonly double LightTransformError = Math.ScaleB(1d, -16);
|
||||
|
||||
static readonly string[] SumNames = ["sum.red", "sum.green", "sum.blue", "sum.alpha"];
|
||||
static readonly string[] SpotNames = ["spot.red", "spot.green", "spot.blue", "spot.alpha"];
|
||||
@@ -24,6 +25,27 @@ internal static class GpuTileCheck
|
||||
ReadOnlySpan<Int2> samples,
|
||||
ReadOnlySpan<double> kernel,
|
||||
Span<ConvolutionMeasurement> measurements)
|
||||
=> Evaluate(report, in job, samples, kernel, kernel, kernel, false, measurements);
|
||||
|
||||
public static void Evaluate(
|
||||
ReadOnlySpan<uint> report,
|
||||
in GpuTileJob job,
|
||||
ReadOnlySpan<Int2> samples,
|
||||
ReadOnlySpan<double> redKernel,
|
||||
ReadOnlySpan<double> greenKernel,
|
||||
ReadOnlySpan<double> blueKernel,
|
||||
Span<ConvolutionMeasurement> measurements)
|
||||
=> Evaluate(report, in job, samples, redKernel, greenKernel, blueKernel, true, measurements);
|
||||
|
||||
static void Evaluate(
|
||||
ReadOnlySpan<uint> report,
|
||||
in GpuTileJob job,
|
||||
ReadOnlySpan<Int2> samples,
|
||||
ReadOnlySpan<double> redKernel,
|
||||
ReadOnlySpan<double> greenKernel,
|
||||
ReadOnlySpan<double> blueKernel,
|
||||
bool chromatic,
|
||||
Span<ConvolutionMeasurement> measurements)
|
||||
{
|
||||
var plan = job.Plan;
|
||||
var layout = job.Layout;
|
||||
@@ -31,20 +53,25 @@ internal static class GpuTileCheck
|
||||
throw new ArgumentException(null, nameof(report));
|
||||
if (samples.Length != job.SampleCount)
|
||||
throw new ArgumentException(null, nameof(samples));
|
||||
if (kernel.Length != job.KernelArea)
|
||||
throw new ArgumentException(null, nameof(kernel));
|
||||
if (redKernel.Length != job.KernelArea || greenKernel.Length != job.KernelArea || blueKernel.Length != job.KernelArea)
|
||||
throw new ArgumentException(null, nameof(greenKernel));
|
||||
if (measurements.Length < MeasurementCount(job.SampleCount))
|
||||
throw new ArgumentException(null, nameof(measurements));
|
||||
|
||||
var relative = ConvolutionBound.Relative(plan.Size, ConvolutionBound.GpuOperationError);
|
||||
var flushed = ConvolutionBound.FlushedOperations(plan.Size) * ConvolutionBound.SmallestNormal;
|
||||
var light = job.Light;
|
||||
var floating = !light.IsDefault;
|
||||
var relative = chromatic
|
||||
? ConvolutionBound.ChromaticRelative(plan.Size, ConvolutionBound.GpuOperationError)
|
||||
: ConvolutionBound.Relative(plan.Size, ConvolutionBound.GpuOperationError);
|
||||
var flushed = (chromatic ? ConvolutionBound.ChromaticFlushedOperations(plan.Size) : ConvolutionBound.FlushedOperations(plan.Size)) * ConvolutionBound.SmallestNormal;
|
||||
measurements[0] = new ConvolutionMeasurement(NonFiniteName, report[GpuTileLayout.CountOffset], 0d, 0d);
|
||||
|
||||
Span<ulong> totals = stackalloc ulong[4];
|
||||
Span<double> errors = stackalloc double[4];
|
||||
Span<ulong> totals = stackalloc ulong[ByteColor.Channels];
|
||||
Span<double> floatTotals = stackalloc double[ByteColor.Channels];
|
||||
Span<double> errors = stackalloc double[ByteColor.Channels];
|
||||
for (var tile = 0; tile < plan.TileCount; tile++)
|
||||
{
|
||||
var (redGreen, blueAlpha) = Norms(report, plan, tile);
|
||||
var (redGreen, blueAlpha) = Norms(report, plan, tile, floating);
|
||||
var root = Math.Sqrt((double)plan.ValidWidth(tile) * plan.ValidHeight(tile));
|
||||
errors[0] += root * (relative * redGreen + flushed);
|
||||
errors[1] += root * (relative * redGreen + flushed);
|
||||
@@ -53,46 +80,79 @@ internal static class GpuTileCheck
|
||||
for (var group = tile * plan.GroupsPerTile; group < (tile + 1) * plan.GroupsPerTile; group++)
|
||||
{
|
||||
var offset = GpuTileLayout.StatisticsOffset + group * GpuTileLayout.StatisticsPerGroup;
|
||||
for (var channel = 0; channel < 4; channel++)
|
||||
totals[channel] += report[offset + channel];
|
||||
for (var channel = 0; channel < ByteColor.Channels; channel++)
|
||||
{
|
||||
if (floating)
|
||||
floatTotals[channel] += BitConverter.UInt32BitsToSingle(report[offset + channel]);
|
||||
else
|
||||
totals[channel] += report[offset + channel];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var groupRounding = ConvolutionBound.Gamma(GroupAdditions, ConvolutionBound.GpuOperationError);
|
||||
var kernelRounding = ConvolutionBound.Gamma(job.KernelArea + 1, ConvolutionBound.DoubleRounding);
|
||||
var accumulation = ConvolutionBound.Gamma(plan.GroupCount, ConvolutionBound.DoubleRounding);
|
||||
var groupFlushes = (double)plan.GroupCount * (GroupElements - 1) * ConvolutionBound.SmallestNormal;
|
||||
for (var channel = 0; channel < 4; channel++)
|
||||
var groupFlushes = (double)plan.GroupCount * (TilePlan.GroupElements - 1) * ConvolutionBound.SmallestNormal;
|
||||
var inputRounding = ConvolutionBound.Gamma(InputStatisticsOperations, ConvolutionBound.GpuOperationError);
|
||||
for (var channel = 0; channel < ByteColor.Channels; channel++)
|
||||
{
|
||||
var measured = 0d;
|
||||
for (var group = 0; group < plan.GroupCount; group++)
|
||||
measured += BitConverter.UInt32BitsToSingle(report[layout.SumsOffset + group * GpuTileLayout.SumsPerGroup + channel]);
|
||||
|
||||
var reference = totals[channel] / 255d;
|
||||
var reference = floating ? floatTotals[channel] : totals[channel] / ByteColor.ScaleDouble;
|
||||
var magnitude = reference * (1d + kernelRounding) + errors[channel];
|
||||
var tolerance = errors[channel] + groupRounding * magnitude + groupFlushes
|
||||
+ accumulation * ((1d + groupRounding) * magnitude + groupFlushes) + reference * kernelRounding;
|
||||
if (floating)
|
||||
tolerance += reference * inputRounding / (1d - inputRounding);
|
||||
measurements[1 + channel] = new ConvolutionMeasurement(SumNames[channel], measured, reference, tolerance);
|
||||
}
|
||||
|
||||
Span<double> expected = stackalloc double[4];
|
||||
var referenceError = DirectCorrelation.ErrorBound(kernel.Length);
|
||||
Span<double> expected = stackalloc double[ByteColor.Channels];
|
||||
var referenceError = DirectCorrelation.ErrorBound(greenKernel.Length);
|
||||
for (var sample = 0; sample < job.SampleCount; sample++)
|
||||
{
|
||||
var position = samples[sample];
|
||||
var tile = plan.TileAt(plan.RegionX + position.X, plan.RegionY + position.Y);
|
||||
var (redGreen, blueAlpha) = Norms(report, plan, tile);
|
||||
DirectCorrelation.Evaluate(report.Slice(layout.GatheredOffset + sample * job.KernelArea, job.KernelArea), kernel, expected);
|
||||
for (var channel = 0; channel < 4; channel++)
|
||||
var (redGreen, blueAlpha) = Norms(report, plan, tile, floating);
|
||||
var neighborhood = report.Slice(layout.GatheredOffset + sample * job.KernelArea, job.KernelArea);
|
||||
if (chromatic)
|
||||
DirectCorrelation.Evaluate(neighborhood, redKernel, greenKernel, blueKernel, light, expected);
|
||||
else
|
||||
DirectCorrelation.Evaluate(neighborhood, greenKernel, light, expected);
|
||||
for (var channel = 0; channel < ByteColor.Channels; channel++)
|
||||
{
|
||||
var norm = channel < 2 ? redGreen : blueAlpha;
|
||||
var measured = BitConverter.UInt32BitsToSingle(report[layout.SpotsOffset + sample * GpuTileLayout.ValuesPerSpot + channel]);
|
||||
var tolerance = relative * norm + flushed + referenceError;
|
||||
measurements[1 + SumNames.Length + sample * 4 + channel] = new ConvolutionMeasurement(SpotNames[channel], measured, expected[channel], tolerance);
|
||||
if (light.Linear)
|
||||
tolerance += LightTransformError * norm;
|
||||
measurements[1 + SumNames.Length + sample * SpotNames.Length + channel] = new ConvolutionMeasurement(SpotNames[channel], measured, expected[channel], tolerance);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static (double RedGreen, double BlueAlpha) Norms(ReadOnlySpan<uint> report, in TilePlan plan, int tile, bool floating)
|
||||
{
|
||||
if (!floating)
|
||||
return Norms(report, plan, tile);
|
||||
|
||||
var redGreenSquares = 0d;
|
||||
var blueAlphaSquares = 0d;
|
||||
for (var group = tile * plan.GroupsPerTile; group < (tile + 1) * plan.GroupsPerTile; group++)
|
||||
{
|
||||
var offset = GpuTileLayout.StatisticsOffset + group * GpuTileLayout.StatisticsPerGroup;
|
||||
redGreenSquares += BitConverter.UInt32BitsToSingle(report[offset + 4]);
|
||||
blueAlphaSquares += BitConverter.UInt32BitsToSingle(report[offset + 5]);
|
||||
}
|
||||
|
||||
var rounding = ConvolutionBound.Gamma(InputStatisticsOperations, ConvolutionBound.GpuOperationError);
|
||||
var inflate = 1d / (1d - rounding);
|
||||
return (Math.Sqrt(redGreenSquares * inflate), Math.Sqrt(blueAlphaSquares * inflate));
|
||||
}
|
||||
|
||||
public static (double RedGreen, double BlueAlpha) Norms(ReadOnlySpan<uint> report, in TilePlan plan, int tile)
|
||||
{
|
||||
var redGreen = 0UL;
|
||||
@@ -104,6 +164,6 @@ internal static class GpuTileCheck
|
||||
blueAlpha += report[offset + 5];
|
||||
}
|
||||
|
||||
return (Math.Sqrt(redGreen) / 255d, Math.Sqrt(blueAlpha) / 255d);
|
||||
return (Math.Sqrt(redGreen) / ByteColor.ScaleDouble, Math.Sqrt(blueAlpha) / ByteColor.ScaleDouble);
|
||||
}
|
||||
}
|
||||
@@ -27,20 +27,37 @@ internal readonly record struct GpuTileJob(
|
||||
int SourceHeight,
|
||||
float Gain,
|
||||
int SampleCount,
|
||||
bool Store)
|
||||
bool Store,
|
||||
LightOptions Light = default,
|
||||
bool Chromatic = false)
|
||||
{
|
||||
public int KernelArea => (Plan.Radius * 2 + 1) * (Plan.Radius * 2 + 1);
|
||||
|
||||
public GpuTileLayout Layout => new(Plan.GroupCount, SampleCount, KernelArea);
|
||||
}
|
||||
|
||||
internal sealed class SpectrumStaging
|
||||
{
|
||||
Float2[] values = [];
|
||||
|
||||
public Span<Float2> Ensure(int length)
|
||||
{
|
||||
if (values.Length < length)
|
||||
values = new Float2[length];
|
||||
return values.AsSpan(0, length);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class GpuTileConvolver : IDisposable
|
||||
{
|
||||
public const int MaximumSamples = 16;
|
||||
public const int SampleTilesPerWord = 32;
|
||||
public const int WordsPerSampleEntry = 2;
|
||||
|
||||
readonly GraphicsDevice device;
|
||||
readonly ReadOnlyBuffer<Int2> samples;
|
||||
readonly ReadWriteBuffer<Float4> spare;
|
||||
ReadOnlyBuffer<Int2> samples;
|
||||
Int2[] sampleStaging = [];
|
||||
ReadWriteBuffer<Float4>? tiles;
|
||||
ReadOnlyBuffer<Float2>? twiddles;
|
||||
ReadOnlyBuffer<Float2>? spectrum;
|
||||
@@ -48,7 +65,9 @@ internal sealed class GpuTileConvolver : IDisposable
|
||||
ReadBackBuffer<uint>? readBack;
|
||||
ReadWriteBuffer<Float4>? store;
|
||||
int spectrumSize;
|
||||
int spectrumLength;
|
||||
int spectrumRadius = -1;
|
||||
bool spectrumChromatic;
|
||||
|
||||
public GpuTileConvolver(GraphicsDevice device)
|
||||
{
|
||||
@@ -76,24 +95,46 @@ internal sealed class GpuTileConvolver : IDisposable
|
||||
if (kernelSpectrum.Size == 0)
|
||||
throw new ArgumentException(null, nameof(kernelSpectrum));
|
||||
|
||||
spectrumRadius = -1;
|
||||
if (spectrumSize != kernelSpectrum.Size)
|
||||
{
|
||||
twiddles?.Dispose();
|
||||
spectrum?.Dispose();
|
||||
twiddles = null;
|
||||
spectrum = null;
|
||||
spectrumSize = 0;
|
||||
twiddles = device.AllocateReadOnlyBuffer<Float2>(kernelSpectrum.Size / 2);
|
||||
spectrum = device.AllocateReadOnlyBuffer<Float2>(kernelSpectrum.Size * kernelSpectrum.Size);
|
||||
spectrumSize = kernelSpectrum.Size;
|
||||
}
|
||||
|
||||
EnsureSpectrumBuffers(kernelSpectrum.Size, kernelSpectrum.Size * kernelSpectrum.Size, false);
|
||||
twiddles!.CopyFrom(kernelSpectrum.Twiddles);
|
||||
spectrum!.CopyFrom(kernelSpectrum.Spectrum);
|
||||
spectrumRadius = kernelSpectrum.Radius;
|
||||
}
|
||||
|
||||
public void Upload(ChromaticKernelSpectrum kernelSpectrum)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(kernelSpectrum);
|
||||
if (kernelSpectrum.Size == 0)
|
||||
throw new ArgumentException(null, nameof(kernelSpectrum));
|
||||
|
||||
var length = ChromaticKernelSpectrum.ChannelCount * kernelSpectrum.HalfColumns * kernelSpectrum.Size;
|
||||
EnsureSpectrumBuffers(kernelSpectrum.Size, length, true);
|
||||
using var lease = ScratchPool<SpectrumStaging>.Shared.Rent();
|
||||
var staging = lease.Value.Ensure(length);
|
||||
kernelSpectrum.CopyHalfSpectra(staging);
|
||||
twiddles!.CopyFrom(kernelSpectrum.Twiddles);
|
||||
spectrum!.CopyFrom(staging);
|
||||
spectrumRadius = kernelSpectrum.Radius;
|
||||
}
|
||||
|
||||
void EnsureSpectrumBuffers(int size, int length, bool chromatic)
|
||||
{
|
||||
spectrumRadius = -1;
|
||||
if (spectrumSize == size && spectrumLength == length && spectrumChromatic == chromatic)
|
||||
return;
|
||||
|
||||
twiddles?.Dispose();
|
||||
spectrum?.Dispose();
|
||||
twiddles = null;
|
||||
spectrum = null;
|
||||
spectrumSize = 0;
|
||||
twiddles = device.AllocateReadOnlyBuffer<Float2>(size / 2);
|
||||
spectrum = device.AllocateReadOnlyBuffer<Float2>(length);
|
||||
spectrumSize = size;
|
||||
spectrumLength = length;
|
||||
spectrumChromatic = chromatic;
|
||||
}
|
||||
|
||||
public GpuTileJob Prepare(
|
||||
in TilePlan plan,
|
||||
int sourceX,
|
||||
@@ -102,10 +143,13 @@ internal sealed class GpuTileConvolver : IDisposable
|
||||
int sourceHeight,
|
||||
float gain,
|
||||
ReadOnlySpan<Int2> sampleValues,
|
||||
bool storeValues)
|
||||
bool storeValues,
|
||||
LightOptions light = default,
|
||||
bool chromatic = false)
|
||||
{
|
||||
if (plan.Size != spectrumSize || plan.Radius != spectrumRadius)
|
||||
if (plan.Size != spectrumSize || plan.Radius != spectrumRadius || chromatic != spectrumChromatic)
|
||||
throw new InvalidOperationException();
|
||||
light.Validate();
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sourceWidth);
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sourceHeight);
|
||||
if (!float.IsFinite(gain))
|
||||
@@ -118,7 +162,7 @@ internal sealed class GpuTileConvolver : IDisposable
|
||||
throw new ArgumentOutOfRangeException(nameof(sampleValues));
|
||||
}
|
||||
|
||||
var job = new GpuTileJob(plan, sourceX, sourceY, sourceWidth, sourceHeight, gain, sampleValues.Length, storeValues);
|
||||
var job = new GpuTileJob(plan, sourceX, sourceY, sourceWidth, sourceHeight, gain, sampleValues.Length, storeValues, light, chromatic);
|
||||
var tileLength = (long)plan.BatchTiles * plan.TileElements;
|
||||
if (tiles is null || tiles.Length < tileLength)
|
||||
{
|
||||
@@ -150,10 +194,38 @@ internal sealed class GpuTileConvolver : IDisposable
|
||||
}
|
||||
|
||||
if (sampleValues.Length > 0)
|
||||
samples.CopyFrom(sampleValues);
|
||||
UploadSamples(sampleValues, plan);
|
||||
return job;
|
||||
}
|
||||
|
||||
void UploadSamples(ReadOnlySpan<Int2> sampleValues, in TilePlan plan)
|
||||
{
|
||||
var length = MaximumSamples + (plan.TileCount + SampleTilesPerWord * WordsPerSampleEntry - 1) / (SampleTilesPerWord * WordsPerSampleEntry);
|
||||
if (samples.Length < length)
|
||||
{
|
||||
samples.Dispose();
|
||||
samples = device.AllocateReadOnlyBuffer<Int2>(length);
|
||||
}
|
||||
|
||||
if (sampleStaging.Length < length)
|
||||
sampleStaging = new Int2[length];
|
||||
var staging = sampleStaging.AsSpan(0, length);
|
||||
staging.Clear();
|
||||
sampleValues.CopyTo(staging);
|
||||
foreach (var sample in sampleValues)
|
||||
{
|
||||
var tile = plan.TileAt(plan.RegionX + sample.X, plan.RegionY + sample.Y);
|
||||
var word = tile / SampleTilesPerWord;
|
||||
ref var entry = ref staging[MaximumSamples + word / WordsPerSampleEntry];
|
||||
if (word % WordsPerSampleEntry == 0)
|
||||
entry.X |= 1 << (tile % SampleTilesPerWord);
|
||||
else
|
||||
entry.Y |= 1 << (tile % SampleTilesPerWord);
|
||||
}
|
||||
|
||||
samples.CopyFrom(staging);
|
||||
}
|
||||
|
||||
public ReadWriteBuffer<Float4> StoreFor(in GpuTileJob job)
|
||||
=> job.Store ? store ?? throw new InvalidOperationException() : spare;
|
||||
|
||||
@@ -208,24 +280,60 @@ internal sealed class GpuTileConvolver : IDisposable
|
||||
{
|
||||
var count = Math.Min(plan.BatchTiles, plan.TileCount - start);
|
||||
var threads = count * plan.TileElements / 2;
|
||||
var columnThreads = job.Chromatic ? count * plan.ChromaticGroupsPerTile * TilePlan.GroupThreads : threads;
|
||||
var groupStart = start * plan.GroupsPerTile;
|
||||
context.For(threads, new ForwardRowShader(
|
||||
source, tiles, twiddles, report, plan.Log2Size, plan.Radius, plan.ValidSize, plan.TilesX, start,
|
||||
plan.RegionX, plan.RegionY, plan.RegionWidth, plan.RegionHeight,
|
||||
job.SourceX, job.SourceY, job.SourceWidth, job.SourceHeight, GpuTileLayout.StatisticsOffset, groupStart));
|
||||
context.Barrier(tiles);
|
||||
context.For(threads, new ColumnShader(tiles, twiddles, spectrum, plan.Log2Size));
|
||||
context.Barrier(tiles);
|
||||
context.For(threads, new InverseRowShader(
|
||||
tiles, twiddles, output, report, samples, store, plan.Log2Size, plan.Radius, plan.ValidSize, plan.TilesX, start,
|
||||
plan.RegionWidth, plan.RegionHeight, scale, job.Gain, job.SampleCount, layout.SumsOffset, layout.SpotsOffset,
|
||||
groupStart, job.Store ? 1 : 0));
|
||||
context.Barrier(tiles);
|
||||
if (job.Light.IsDefault)
|
||||
{
|
||||
context.For(threads, new ForwardRowShader(
|
||||
source, tiles, twiddles, report, plan.Log2Size, plan.Radius, plan.ValidSize, plan.TilesX, start,
|
||||
plan.RegionX, plan.RegionY, plan.RegionWidth, plan.RegionHeight,
|
||||
job.SourceX, job.SourceY, job.SourceWidth, job.SourceHeight, GpuTileLayout.StatisticsOffset, groupStart));
|
||||
context.Barrier(tiles);
|
||||
RecordColumns(in context, tiles, twiddles, spectrum, plan.Log2Size, columnThreads, job.Chromatic);
|
||||
context.Barrier(tiles);
|
||||
context.For(threads, new InverseRowShader(
|
||||
tiles, twiddles, output, report, samples, store, plan.Log2Size, plan.Radius, plan.ValidSize, plan.TilesX, start,
|
||||
plan.RegionWidth, plan.RegionHeight, scale, job.Gain, job.SampleCount, layout.SumsOffset, layout.SpotsOffset,
|
||||
groupStart, job.Store ? 1 : 0, MaximumSamples));
|
||||
context.Barrier(tiles);
|
||||
}
|
||||
else
|
||||
{
|
||||
var light = job.Light;
|
||||
context.For(threads, new ForwardRowLightShader(
|
||||
source, tiles, twiddles, report, plan.Log2Size, plan.Radius, plan.ValidSize, plan.TilesX, start,
|
||||
plan.RegionX, plan.RegionY, plan.RegionWidth, plan.RegionHeight,
|
||||
job.SourceX, job.SourceY, job.SourceWidth, job.SourceHeight, GpuTileLayout.StatisticsOffset, groupStart,
|
||||
light.Linear ? 1 : 0, light.Highlights ? 1 : 0, light.Threshold, light.Boost));
|
||||
context.Barrier(tiles);
|
||||
RecordColumns(in context, tiles, twiddles, spectrum, plan.Log2Size, columnThreads, job.Chromatic);
|
||||
context.Barrier(tiles);
|
||||
context.For(threads, new InverseRowLightShader(
|
||||
tiles, twiddles, output, report, samples, store, plan.Log2Size, plan.Radius, plan.ValidSize, plan.TilesX, start,
|
||||
plan.RegionX, plan.RegionY, plan.RegionWidth, plan.RegionHeight, scale, job.Gain, job.SampleCount, layout.SumsOffset, layout.SpotsOffset,
|
||||
groupStart, job.Store ? 1 : 0, light.Linear ? 1 : 0, light.Dither ? 1 : 0, MaximumSamples));
|
||||
context.Barrier(tiles);
|
||||
}
|
||||
}
|
||||
|
||||
context.Barrier(report);
|
||||
}
|
||||
|
||||
static void RecordColumns(
|
||||
in ComputeContext context,
|
||||
ReadWriteBuffer<Float4> tiles,
|
||||
ReadOnlyBuffer<Float2> twiddles,
|
||||
ReadOnlyBuffer<Float2> spectrum,
|
||||
int log2Size,
|
||||
int threads,
|
||||
bool chromatic)
|
||||
{
|
||||
if (chromatic)
|
||||
context.For(threads, new ColumnChromaticShader(tiles, twiddles, spectrum, log2Size));
|
||||
else
|
||||
context.For(threads, new ColumnShader(tiles, twiddles, spectrum, log2Size));
|
||||
}
|
||||
|
||||
public static void RecordStored(
|
||||
in ComputeContext context,
|
||||
ReadWriteBuffer<Float4> store,
|
||||
@@ -235,6 +343,23 @@ internal sealed class GpuTileConvolver : IDisposable
|
||||
float gain)
|
||||
=> context.For(width, height, new StoredRenderShader(store, output, width, height, gain));
|
||||
|
||||
public static void RecordStored(
|
||||
in ComputeContext context,
|
||||
ReadWriteBuffer<Float4> store,
|
||||
ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
int width,
|
||||
int height,
|
||||
float gain,
|
||||
in LightOptions light,
|
||||
int originX,
|
||||
int originY)
|
||||
{
|
||||
if (light.IsDefault)
|
||||
context.For(width, height, new StoredRenderShader(store, output, width, height, gain));
|
||||
else
|
||||
context.For(width, height, new StoredRenderLightShader(store, output, width, height, gain, light.Linear ? 1 : 0, light.Dither ? 1 : 0, originX, originY));
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
tiles?.Dispose();
|
||||
@@ -252,6 +377,8 @@ internal sealed class GpuTileConvolver : IDisposable
|
||||
readBack = null;
|
||||
store = null;
|
||||
spectrumSize = 0;
|
||||
spectrumLength = 0;
|
||||
spectrumRadius = -1;
|
||||
spectrumChromatic = false;
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ internal readonly partial struct ReportResetShader(
|
||||
public void Execute()
|
||||
{
|
||||
if (ThreadIds.X == 0)
|
||||
report[0] = 0u;
|
||||
report[GpuTileLayout.CountOffset] = 0u;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,17 +86,14 @@ internal readonly partial struct GatherShader(
|
||||
if (x >= 0 && x < sourceWidth && y >= 0 && y < sourceHeight)
|
||||
{
|
||||
var value = source[new Int2(x, y)];
|
||||
packed = (uint)(value.X * 255f + 0.5f)
|
||||
| ((uint)(value.Y * 255f + 0.5f) << 8)
|
||||
| ((uint)(value.Z * 255f + 0.5f) << 16)
|
||||
| ((uint)(value.W * 255f + 0.5f) << 24);
|
||||
packed = ByteColor.Pack(value);
|
||||
}
|
||||
|
||||
report[gatheredOffset + sample * area + index] = packed;
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(256, 1, 1)]
|
||||
[ThreadGroupSize(TilePlan.GroupThreads, 1, 1)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
[CompileOptions(CompileOptions.Default | CompileOptions.IeeeStrictness)]
|
||||
internal readonly partial struct ForwardRowShader(
|
||||
@@ -140,50 +137,51 @@ internal readonly partial struct ForwardRowShader(
|
||||
private readonly int statisticsOffset = statisticsOffset;
|
||||
private readonly int groupStart = groupStart;
|
||||
|
||||
[GroupShared(512)]
|
||||
[GroupShared(TilePlan.GroupElements)]
|
||||
private static readonly Float4[] row = null!;
|
||||
|
||||
[GroupShared(6)]
|
||||
[GroupShared(GpuTileLayout.StatisticsPerGroup)]
|
||||
private static readonly uint[] statistics = null!;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var local = GroupIds.X;
|
||||
var groupBase = (ThreadIds.X - local) * 2;
|
||||
var groupBase = GridIds.X * TilePlan.GroupElements;
|
||||
var size = (int)(1u << log2Size);
|
||||
var mask = size - 1;
|
||||
var shift = 32 - log2Size;
|
||||
if (local < 6)
|
||||
if (local < GpuTileLayout.StatisticsPerGroup)
|
||||
statistics[local] = 0u;
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
var origin = TileShaderMath.TileOrigin(TileShaderMath.TileIndex(batchStart, groupBase, log2Size), tilesX, validSize, radius);
|
||||
var originX = regionX + origin.X;
|
||||
var originY = regionY + origin.Y;
|
||||
|
||||
var sumRed = 0u;
|
||||
var sumGreen = 0u;
|
||||
var sumBlue = 0u;
|
||||
var sumAlpha = 0u;
|
||||
var squareRedGreen = 0u;
|
||||
var squareBlueAlpha = 0u;
|
||||
for (var pair = 0; pair < 2; pair++)
|
||||
for (var pair = 0; pair < TilePlan.ValuesPerThread; pair++)
|
||||
{
|
||||
var element = local * 2 + pair;
|
||||
var element = local * TilePlan.ValuesPerThread + pair;
|
||||
var flat = groupBase + element;
|
||||
var tile = flat >> (log2Size * 2);
|
||||
var rest = flat & (size * size - 1);
|
||||
var y = rest >> log2Size;
|
||||
var x = rest & mask;
|
||||
var tileIndex = batchStart + tile;
|
||||
var canvasX = regionX + tileIndex % tilesX * validSize - radius + x;
|
||||
var canvasY = regionY + tileIndex / tilesX * validSize - radius + y;
|
||||
var canvasX = originX + x;
|
||||
var canvasY = originY + y;
|
||||
var value = new Float4(0f, 0f, 0f, 0f);
|
||||
var column = canvasX - sourceX;
|
||||
var line = canvasY - sourceY;
|
||||
if (column >= 0 && column < sourceWidth && line >= 0 && line < sourceHeight)
|
||||
{
|
||||
value = source[new Int2(column, line)];
|
||||
var red = (uint)(value.X * 255f + 0.5f);
|
||||
var green = (uint)(value.Y * 255f + 0.5f);
|
||||
var blue = (uint)(value.Z * 255f + 0.5f);
|
||||
var alpha = (uint)(value.W * 255f + 0.5f);
|
||||
var red = ByteColor.ToLevel(value.X);
|
||||
var green = ByteColor.ToLevel(value.Y);
|
||||
var blue = ByteColor.ToLevel(value.Z);
|
||||
var alpha = ByteColor.ToLevel(value.W);
|
||||
squareRedGreen += red * red + green * green;
|
||||
squareBlueAlpha += blue * blue + alpha * alpha;
|
||||
if (x >= radius && x < size - radius && y >= radius && y < size - radius
|
||||
@@ -196,7 +194,7 @@ internal readonly partial struct ForwardRowShader(
|
||||
}
|
||||
}
|
||||
|
||||
var reversed = (int)(Hlsl.ReverseBits((uint)x) >> shift);
|
||||
var reversed = FftShaderMath.BitReverse(x, log2Size);
|
||||
row[((element >> log2Size) << log2Size) + reversed] = value;
|
||||
}
|
||||
|
||||
@@ -207,44 +205,71 @@ internal readonly partial struct ForwardRowShader(
|
||||
Hlsl.InterlockedAdd(ref statistics[4], squareRedGreen);
|
||||
Hlsl.InterlockedAdd(ref statistics[5], squareBlueAlpha);
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
if (local < 6)
|
||||
report[statisticsOffset + (groupStart + (ThreadIds.X >> 8)) * 6 + local] = statistics[local];
|
||||
if (local < GpuTileLayout.StatisticsPerGroup)
|
||||
report[statisticsOffset + (groupStart + GridIds.X) * GpuTileLayout.StatisticsPerGroup + local] = statistics[local];
|
||||
|
||||
Butterflies(local, 1f);
|
||||
Butterflies(local, FftShaderMath.Forward);
|
||||
|
||||
tiles[groupBase + local * 2] = row[local * 2];
|
||||
tiles[groupBase + local * 2 + 1] = row[local * 2 + 1];
|
||||
var element0 = local * TilePlan.ValuesPerThread;
|
||||
var element1 = element0 + 1;
|
||||
tiles[groupBase + element0] = row[element0];
|
||||
tiles[groupBase + element1] = row[element1];
|
||||
}
|
||||
|
||||
private void Butterflies(int local, float direction)
|
||||
{
|
||||
var halfSize = (int)(1u << (log2Size - 1));
|
||||
var rowBase = (local >> (log2Size - 1)) << log2Size;
|
||||
var pair = local & (halfSize - 1);
|
||||
for (var stage = 0; stage < log2Size; stage++)
|
||||
var stage = 0;
|
||||
for (; stage + 1 < log2Size; stage += 2)
|
||||
{
|
||||
var half = (int)(1u << stage);
|
||||
var position = pair & (half - 1);
|
||||
var even = rowBase + ((pair >> stage) << (stage + 1)) + position;
|
||||
var odd = even + half;
|
||||
var twiddle = twiddles[position << (log2Size - 1 - stage)];
|
||||
var real = twiddle.X;
|
||||
var imaginary = twiddle.Y * direction;
|
||||
if (local < FftShaderMath.StageUnitsPerGroup)
|
||||
{
|
||||
var step = FftShaderMath.Pow2(stage);
|
||||
var position = FftShaderMath.Position(local, stage);
|
||||
var first = FftShaderMath.Radix4First(local, log2Size, stage);
|
||||
var second = first + step;
|
||||
var third = second + step;
|
||||
var fourth = third + step;
|
||||
var value0 = row[first];
|
||||
var value1 = row[second];
|
||||
var value2 = row[third];
|
||||
var value3 = row[fourth];
|
||||
FftShaderMath.Radix4(
|
||||
ref value0,
|
||||
ref value1,
|
||||
ref value2,
|
||||
ref value3,
|
||||
twiddles[FftShaderMath.TwiddleIndex(position, log2Size, stage)],
|
||||
twiddles[FftShaderMath.TwiddleIndex(position, log2Size, stage + 1)],
|
||||
twiddles[FftShaderMath.TwiddleIndex(position + step, log2Size, stage + 1)],
|
||||
direction);
|
||||
row[first] = value0;
|
||||
row[second] = value1;
|
||||
row[third] = value2;
|
||||
row[fourth] = value3;
|
||||
}
|
||||
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
|
||||
for (; stage < log2Size; stage++)
|
||||
{
|
||||
var even = FftShaderMath.Radix2Even(local, log2Size, stage);
|
||||
var odd = even + FftShaderMath.Pow2(stage);
|
||||
var evenValue = row[even];
|
||||
var oddValue = row[odd];
|
||||
var product = new Float4(
|
||||
oddValue.X * real - oddValue.Y * imaginary,
|
||||
oddValue.X * imaginary + oddValue.Y * real,
|
||||
oddValue.Z * real - oddValue.W * imaginary,
|
||||
oddValue.Z * imaginary + oddValue.W * real);
|
||||
row[even] = evenValue + product;
|
||||
row[odd] = evenValue - product;
|
||||
FftShaderMath.Radix2(
|
||||
ref evenValue,
|
||||
ref oddValue,
|
||||
twiddles[FftShaderMath.TwiddleIndex(FftShaderMath.Position(local, stage), log2Size, stage)],
|
||||
direction);
|
||||
row[even] = evenValue;
|
||||
row[odd] = oddValue;
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(256, 1, 1)]
|
||||
[ThreadGroupSize(TilePlan.GroupThreads, 1, 1)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
[CompileOptions(CompileOptions.Default | CompileOptions.IeeeStrictness)]
|
||||
internal readonly partial struct ColumnShader(
|
||||
@@ -258,87 +283,104 @@ internal readonly partial struct ColumnShader(
|
||||
private readonly ReadOnlyBuffer<Float2> spectrum = spectrum;
|
||||
private readonly int log2Size = log2Size;
|
||||
|
||||
[GroupShared(512)]
|
||||
[GroupShared(TilePlan.GroupElements)]
|
||||
private static readonly Float4[] row = null!;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var local = GroupIds.X;
|
||||
var group = ThreadIds.X >> 8;
|
||||
var group = GridIds.X;
|
||||
var mask = (int)(1u << log2Size) - 1;
|
||||
var shift = 32 - log2Size;
|
||||
var log2Columns = 9 - log2Size;
|
||||
var log2Columns = TilePlan.GroupElementsLog2 - log2Size;
|
||||
var columnMask = (int)(1u << log2Columns) - 1;
|
||||
var groupsPerTile = (int)(1u << (log2Size - log2Columns));
|
||||
var tile = group / groupsPerTile;
|
||||
var firstColumn = (group % groupsPerTile) << log2Columns;
|
||||
var tileBase = tile << (log2Size * 2);
|
||||
|
||||
var element0 = local * 2;
|
||||
var element1 = local * 2 + 1;
|
||||
var element0 = local * TilePlan.ValuesPerThread;
|
||||
var element1 = element0 + 1;
|
||||
var y0 = element0 >> log2Columns;
|
||||
var column0 = element0 & columnMask;
|
||||
var y1 = element1 >> log2Columns;
|
||||
var column1 = element1 & columnMask;
|
||||
var global0 = tileBase + (y0 << log2Size) + firstColumn + column0;
|
||||
var global1 = tileBase + (y1 << log2Size) + firstColumn + column1;
|
||||
row[(column0 << log2Size) + (int)(Hlsl.ReverseBits((uint)y0) >> shift)] = tiles[global0];
|
||||
row[(column1 << log2Size) + (int)(Hlsl.ReverseBits((uint)y1) >> shift)] = tiles[global1];
|
||||
row[(column0 << log2Size) + FftShaderMath.BitReverse(y0, log2Size)] = tiles[global0];
|
||||
row[(column1 << log2Size) + FftShaderMath.BitReverse(y1, log2Size)] = tiles[global1];
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
Butterflies(local, 1f);
|
||||
Butterflies(local, FftShaderMath.Forward);
|
||||
|
||||
var frequency0 = element0 & mask;
|
||||
var frequency1 = element1 & mask;
|
||||
var product0 = Multiply(row[element0], spectrum[((firstColumn + (element0 >> log2Size)) << log2Size) + frequency0]);
|
||||
var product1 = Multiply(row[element1], spectrum[((firstColumn + (element1 >> log2Size)) << log2Size) + frequency1]);
|
||||
var product0 = FftShaderMath.Multiply(row[element0], spectrum[((firstColumn + (element0 >> log2Size)) << log2Size) + frequency0]);
|
||||
var product1 = FftShaderMath.Multiply(row[element1], spectrum[((firstColumn + (element1 >> log2Size)) << log2Size) + frequency1]);
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
row[((element0 >> log2Size) << log2Size) + (int)(Hlsl.ReverseBits((uint)frequency0) >> shift)] = product0;
|
||||
row[((element1 >> log2Size) << log2Size) + (int)(Hlsl.ReverseBits((uint)frequency1) >> shift)] = product1;
|
||||
row[((element0 >> log2Size) << log2Size) + FftShaderMath.BitReverse(frequency0, log2Size)] = product0;
|
||||
row[((element1 >> log2Size) << log2Size) + FftShaderMath.BitReverse(frequency1, log2Size)] = product1;
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
Butterflies(local, -1f);
|
||||
Butterflies(local, FftShaderMath.Inverse);
|
||||
|
||||
tiles[global0] = row[(column0 << log2Size) + y0];
|
||||
tiles[global1] = row[(column1 << log2Size) + y1];
|
||||
}
|
||||
|
||||
private static Float4 Multiply(Float4 value, Float2 weight)
|
||||
=> new(
|
||||
value.X * weight.X - value.Y * weight.Y,
|
||||
value.X * weight.Y + value.Y * weight.X,
|
||||
value.Z * weight.X - value.W * weight.Y,
|
||||
value.Z * weight.Y + value.W * weight.X);
|
||||
|
||||
private void Butterflies(int local, float direction)
|
||||
{
|
||||
var halfSize = (int)(1u << (log2Size - 1));
|
||||
var rowBase = (local >> (log2Size - 1)) << log2Size;
|
||||
var pair = local & (halfSize - 1);
|
||||
for (var stage = 0; stage < log2Size; stage++)
|
||||
var stage = 0;
|
||||
for (; stage + 1 < log2Size; stage += 2)
|
||||
{
|
||||
var half = (int)(1u << stage);
|
||||
var position = pair & (half - 1);
|
||||
var even = rowBase + ((pair >> stage) << (stage + 1)) + position;
|
||||
var odd = even + half;
|
||||
var twiddle = twiddles[position << (log2Size - 1 - stage)];
|
||||
var real = twiddle.X;
|
||||
var imaginary = twiddle.Y * direction;
|
||||
if (local < FftShaderMath.StageUnitsPerGroup)
|
||||
{
|
||||
var step = FftShaderMath.Pow2(stage);
|
||||
var position = FftShaderMath.Position(local, stage);
|
||||
var first = FftShaderMath.Radix4First(local, log2Size, stage);
|
||||
var second = first + step;
|
||||
var third = second + step;
|
||||
var fourth = third + step;
|
||||
var value0 = row[first];
|
||||
var value1 = row[second];
|
||||
var value2 = row[third];
|
||||
var value3 = row[fourth];
|
||||
FftShaderMath.Radix4(
|
||||
ref value0,
|
||||
ref value1,
|
||||
ref value2,
|
||||
ref value3,
|
||||
twiddles[FftShaderMath.TwiddleIndex(position, log2Size, stage)],
|
||||
twiddles[FftShaderMath.TwiddleIndex(position, log2Size, stage + 1)],
|
||||
twiddles[FftShaderMath.TwiddleIndex(position + step, log2Size, stage + 1)],
|
||||
direction);
|
||||
row[first] = value0;
|
||||
row[second] = value1;
|
||||
row[third] = value2;
|
||||
row[fourth] = value3;
|
||||
}
|
||||
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
|
||||
for (; stage < log2Size; stage++)
|
||||
{
|
||||
var even = FftShaderMath.Radix2Even(local, log2Size, stage);
|
||||
var odd = even + FftShaderMath.Pow2(stage);
|
||||
var evenValue = row[even];
|
||||
var oddValue = row[odd];
|
||||
var product = new Float4(
|
||||
oddValue.X * real - oddValue.Y * imaginary,
|
||||
oddValue.X * imaginary + oddValue.Y * real,
|
||||
oddValue.Z * real - oddValue.W * imaginary,
|
||||
oddValue.Z * imaginary + oddValue.W * real);
|
||||
row[even] = evenValue + product;
|
||||
row[odd] = evenValue - product;
|
||||
FftShaderMath.Radix2(
|
||||
ref evenValue,
|
||||
ref oddValue,
|
||||
twiddles[FftShaderMath.TwiddleIndex(FftShaderMath.Position(local, stage), log2Size, stage)],
|
||||
direction);
|
||||
row[even] = evenValue;
|
||||
row[odd] = oddValue;
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(256, 1, 1)]
|
||||
[ThreadGroupSize(TilePlan.GroupThreads, 1, 1)]
|
||||
[GeneratedComputeShaderDescriptor]
|
||||
[CompileOptions(CompileOptions.Default | CompileOptions.IeeeStrictness)]
|
||||
internal readonly partial struct InverseRowShader(
|
||||
@@ -361,7 +403,8 @@ internal readonly partial struct InverseRowShader(
|
||||
int sumsOffset,
|
||||
int spotsOffset,
|
||||
int groupStart,
|
||||
int storeValues) : IComputeShader
|
||||
int storeValues,
|
||||
int sampleTilesOffset) : IComputeShader
|
||||
{
|
||||
private readonly ReadWriteBuffer<Float4> tiles = tiles;
|
||||
private readonly ReadOnlyBuffer<Float2> twiddles = twiddles;
|
||||
@@ -383,31 +426,35 @@ internal readonly partial struct InverseRowShader(
|
||||
private readonly int spotsOffset = spotsOffset;
|
||||
private readonly int groupStart = groupStart;
|
||||
private readonly int storeValues = storeValues;
|
||||
private readonly int sampleTilesOffset = sampleTilesOffset;
|
||||
|
||||
[GroupShared(512)]
|
||||
[GroupShared(TilePlan.GroupElements)]
|
||||
private static readonly Float4[] row = null!;
|
||||
|
||||
[GroupShared(256)]
|
||||
[GroupShared(TilePlan.GroupThreads)]
|
||||
private static readonly Float4[] partial = null!;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var local = GroupIds.X;
|
||||
var groupBase = (ThreadIds.X - local) * 2;
|
||||
var groupBase = GridIds.X * TilePlan.GroupElements;
|
||||
var size = (int)(1u << log2Size);
|
||||
var mask = size - 1;
|
||||
var shift = 32 - log2Size;
|
||||
var element0 = local * 2;
|
||||
var element1 = local * 2 + 1;
|
||||
row[((element0 >> log2Size) << log2Size) + (int)(Hlsl.ReverseBits((uint)(element0 & mask)) >> shift)] = tiles[groupBase + element0];
|
||||
row[((element1 >> log2Size) << log2Size) + (int)(Hlsl.ReverseBits((uint)(element1 & mask)) >> shift)] = tiles[groupBase + element1];
|
||||
var element0 = local * TilePlan.ValuesPerThread;
|
||||
var element1 = element0 + 1;
|
||||
row[((element0 >> log2Size) << log2Size) + FftShaderMath.BitReverse(element0 & mask, log2Size)] = tiles[groupBase + element0];
|
||||
row[((element1 >> log2Size) << log2Size) + FftShaderMath.BitReverse(element1 & mask, log2Size)] = tiles[groupBase + element1];
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
Butterflies(local, -1f);
|
||||
Butterflies(local, FftShaderMath.Inverse);
|
||||
|
||||
partial[local] = Emit(groupBase + element0, row[element0] * scale, size, mask) + Emit(groupBase + element1, row[element1] * scale, size, mask);
|
||||
var tileIndex = TileShaderMath.TileIndex(batchStart, groupBase, log2Size);
|
||||
var origin = TileShaderMath.TileOrigin(tileIndex, tilesX, validSize, radius);
|
||||
var tileHoldsSample = sampleCount > 0 && TileHoldsSample(tileIndex);
|
||||
partial[local] = Emit(groupBase + element0, row[element0] * scale, origin, tileHoldsSample)
|
||||
+ Emit(groupBase + element1, row[element1] * scale, origin, tileHoldsSample);
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
for (var stride = 128; stride > 0; stride >>= 1)
|
||||
for (var stride = TilePlan.GroupThreads / 2; stride > 0; stride >>= 1)
|
||||
{
|
||||
if (local < stride)
|
||||
partial[local] = partial[local] + partial[local + stride];
|
||||
@@ -417,7 +464,7 @@ internal readonly partial struct InverseRowShader(
|
||||
if (local == 0)
|
||||
{
|
||||
var sum = partial[0];
|
||||
var offset = sumsOffset + (groupStart + (ThreadIds.X >> 8)) * 4;
|
||||
var offset = sumsOffset + (groupStart + GridIds.X) * GpuTileLayout.SumsPerGroup;
|
||||
report[offset] = Hlsl.AsUInt(sum.X);
|
||||
report[offset + 1] = Hlsl.AsUInt(sum.Y);
|
||||
report[offset + 2] = Hlsl.AsUInt(sum.Z);
|
||||
@@ -425,68 +472,102 @@ internal readonly partial struct InverseRowShader(
|
||||
}
|
||||
}
|
||||
|
||||
private Float4 Emit(int flat, Float4 value, int size, int mask)
|
||||
private bool TileHoldsSample(int tileIndex)
|
||||
{
|
||||
if (IsNonFinite(value.X) || IsNonFinite(value.Y) || IsNonFinite(value.Z) || IsNonFinite(value.W))
|
||||
Hlsl.InterlockedAdd(ref report[0], 1u);
|
||||
var word = tileIndex / GpuTileConvolver.SampleTilesPerWord;
|
||||
var entry = samples[sampleTilesOffset + word / GpuTileConvolver.WordsPerSampleEntry];
|
||||
var bits = word % GpuTileConvolver.WordsPerSampleEntry == 0 ? (uint)entry.X : (uint)entry.Y;
|
||||
return ((bits >> (tileIndex % GpuTileConvolver.SampleTilesPerWord)) & 1u) != 0u;
|
||||
}
|
||||
|
||||
var tile = flat >> (log2Size * 2);
|
||||
private Float4 Emit(int flat, Float4 value, Int2 origin, bool tileHoldsSample)
|
||||
{
|
||||
if (TileShaderMath.IsNonFinite(value))
|
||||
Hlsl.InterlockedAdd(ref report[GpuTileLayout.CountOffset], 1u);
|
||||
|
||||
var size = (int)(1u << log2Size);
|
||||
var mask = size - 1;
|
||||
var rest = flat & (size * size - 1);
|
||||
var y = rest >> log2Size;
|
||||
var x = rest & mask;
|
||||
if (x < radius || x >= size - radius || y < radius || y >= size - radius)
|
||||
return new Float4(0f, 0f, 0f, 0f);
|
||||
|
||||
var tileIndex = batchStart + tile;
|
||||
var outputX = tileIndex % tilesX * validSize + x - radius;
|
||||
var outputY = tileIndex / tilesX * validSize + y - radius;
|
||||
var outputX = origin.X + x;
|
||||
var outputY = origin.Y + y;
|
||||
if (outputX >= regionWidth || outputY >= regionHeight)
|
||||
return new Float4(0f, 0f, 0f, 0f);
|
||||
|
||||
output[new Int2(outputX, outputY)] = value * gain;
|
||||
if (storeValues != 0)
|
||||
store[outputY * regionWidth + outputX] = value;
|
||||
for (var sample = 0; sample < sampleCount; sample++)
|
||||
if (tileHoldsSample)
|
||||
{
|
||||
var position = samples[sample];
|
||||
if (position.X == outputX && position.Y == outputY)
|
||||
for (var sample = 0; sample < sampleCount; sample++)
|
||||
{
|
||||
report[spotsOffset + sample * 4] = Hlsl.AsUInt(value.X);
|
||||
report[spotsOffset + sample * 4 + 1] = Hlsl.AsUInt(value.Y);
|
||||
report[spotsOffset + sample * 4 + 2] = Hlsl.AsUInt(value.Z);
|
||||
report[spotsOffset + sample * 4 + 3] = Hlsl.AsUInt(value.W);
|
||||
var position = samples[sample];
|
||||
if (position.X == outputX && position.Y == outputY)
|
||||
{
|
||||
var spot = spotsOffset + sample * GpuTileLayout.ValuesPerSpot;
|
||||
report[spot] = Hlsl.AsUInt(value.X);
|
||||
report[spot + 1] = Hlsl.AsUInt(value.Y);
|
||||
report[spot + 2] = Hlsl.AsUInt(value.Z);
|
||||
report[spot + 3] = Hlsl.AsUInt(value.W);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
private static bool IsNonFinite(float value)
|
||||
=> (Hlsl.AsUInt(value) & 0x7F800000u) == 0x7F800000u;
|
||||
|
||||
private void Butterflies(int local, float direction)
|
||||
{
|
||||
var halfSize = (int)(1u << (log2Size - 1));
|
||||
var rowBase = (local >> (log2Size - 1)) << log2Size;
|
||||
var pair = local & (halfSize - 1);
|
||||
for (var stage = 0; stage < log2Size; stage++)
|
||||
var stage = 0;
|
||||
for (; stage + 1 < log2Size; stage += 2)
|
||||
{
|
||||
var half = (int)(1u << stage);
|
||||
var position = pair & (half - 1);
|
||||
var even = rowBase + ((pair >> stage) << (stage + 1)) + position;
|
||||
var odd = even + half;
|
||||
var twiddle = twiddles[position << (log2Size - 1 - stage)];
|
||||
var real = twiddle.X;
|
||||
var imaginary = twiddle.Y * direction;
|
||||
if (local < FftShaderMath.StageUnitsPerGroup)
|
||||
{
|
||||
var step = FftShaderMath.Pow2(stage);
|
||||
var position = FftShaderMath.Position(local, stage);
|
||||
var first = FftShaderMath.Radix4First(local, log2Size, stage);
|
||||
var second = first + step;
|
||||
var third = second + step;
|
||||
var fourth = third + step;
|
||||
var value0 = row[first];
|
||||
var value1 = row[second];
|
||||
var value2 = row[third];
|
||||
var value3 = row[fourth];
|
||||
FftShaderMath.Radix4(
|
||||
ref value0,
|
||||
ref value1,
|
||||
ref value2,
|
||||
ref value3,
|
||||
twiddles[FftShaderMath.TwiddleIndex(position, log2Size, stage)],
|
||||
twiddles[FftShaderMath.TwiddleIndex(position, log2Size, stage + 1)],
|
||||
twiddles[FftShaderMath.TwiddleIndex(position + step, log2Size, stage + 1)],
|
||||
direction);
|
||||
row[first] = value0;
|
||||
row[second] = value1;
|
||||
row[third] = value2;
|
||||
row[fourth] = value3;
|
||||
}
|
||||
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
|
||||
for (; stage < log2Size; stage++)
|
||||
{
|
||||
var even = FftShaderMath.Radix2Even(local, log2Size, stage);
|
||||
var odd = even + FftShaderMath.Pow2(stage);
|
||||
var evenValue = row[even];
|
||||
var oddValue = row[odd];
|
||||
var product = new Float4(
|
||||
oddValue.X * real - oddValue.Y * imaginary,
|
||||
oddValue.X * imaginary + oddValue.Y * real,
|
||||
oddValue.Z * real - oddValue.W * imaginary,
|
||||
oddValue.Z * imaginary + oddValue.W * real);
|
||||
row[even] = evenValue + product;
|
||||
row[odd] = evenValue - product;
|
||||
FftShaderMath.Radix2(
|
||||
ref evenValue,
|
||||
ref oddValue,
|
||||
twiddles[FftShaderMath.TwiddleIndex(FftShaderMath.Position(local, stage), log2Size, stage)],
|
||||
direction);
|
||||
row[even] = evenValue;
|
||||
row[odd] = oddValue;
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,11 +2,15 @@ using ComputeWeave;
|
||||
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal sealed class KernelSpectrum
|
||||
internal enum SpectrumPlane
|
||||
{
|
||||
Full,
|
||||
Half,
|
||||
}
|
||||
|
||||
internal sealed class KernelSpectrum(SpectrumPlane plane = SpectrumPlane.Full)
|
||||
{
|
||||
double[] kernel = [];
|
||||
double[] real = [];
|
||||
double[] imaginary = [];
|
||||
Float2[] twiddles = [];
|
||||
Float2[] spectrum = [];
|
||||
|
||||
@@ -20,11 +24,15 @@ internal sealed class KernelSpectrum
|
||||
|
||||
public ReadOnlySpan<Float2> Twiddles => twiddles.AsSpan(0, Size / 2);
|
||||
|
||||
public ReadOnlySpan<Float2> Spectrum => spectrum.AsSpan(0, Size * Size);
|
||||
public int StoredColumns => StoredColumnsOf(Size);
|
||||
|
||||
public ReadOnlySpan<Float2> Spectrum => spectrum.AsSpan(0, StoredColumns * Size);
|
||||
|
||||
public static int HalfColumnsOf(int size) => size / 2 + 1;
|
||||
|
||||
public void Update(ReadOnlySpan<double> values, int radius, int size)
|
||||
{
|
||||
_ = TilePlan.Create(size, radius, 0, 0, 1, 1);
|
||||
TilePlan.ValidateKernel(size, radius);
|
||||
var kernelSize = radius * 2 + 1;
|
||||
var kernelArea = kernelSize * kernelSize;
|
||||
if (values.Length != kernelArea)
|
||||
@@ -40,17 +48,19 @@ internal sealed class KernelSpectrum
|
||||
if (!double.IsFinite(sum) || sum <= 0d)
|
||||
throw new ArgumentOutOfRangeException(nameof(values));
|
||||
|
||||
var area = size * size;
|
||||
var rowArea = kernelSize * size;
|
||||
Size = 0;
|
||||
Radius = 0;
|
||||
if (kernel.Length < kernelArea)
|
||||
kernel = new double[kernelArea];
|
||||
if (real.Length < area)
|
||||
{
|
||||
real = new double[area];
|
||||
imaginary = new double[area];
|
||||
spectrum = new Float2[area];
|
||||
}
|
||||
using var lease = ScratchPool<TransformScratch>.Shared.Rent();
|
||||
var rows = lease.Value.Rows;
|
||||
var column = lease.Value.Column;
|
||||
rows.Ensure(rowArea);
|
||||
column.Ensure(size);
|
||||
var length = StoredColumnsOf(size) * size;
|
||||
if (spectrum.Length < length)
|
||||
spectrum = new Float2[length];
|
||||
if (twiddles.Length < size / 2)
|
||||
twiddles = new Float2[size / 2];
|
||||
|
||||
@@ -59,26 +69,56 @@ internal sealed class KernelSpectrum
|
||||
|
||||
for (var index = 0; index < size / 2; index++)
|
||||
{
|
||||
var (sin, cos) = Math.SinCos(-2d * Math.PI * index / size);
|
||||
twiddles[index] = new Float2(Flush((float)cos), Flush((float)sin));
|
||||
var angle = -2d * Math.PI * index / size;
|
||||
twiddles[index] = new Float2(Flush((float)Math.Cos(angle)), Flush((float)Math.Sin(angle)));
|
||||
}
|
||||
|
||||
real.AsSpan(0, area).Clear();
|
||||
imaginary.AsSpan(0, area).Clear();
|
||||
var mask = size - 1;
|
||||
for (var offsetY = -radius; offsetY <= radius; offsetY++)
|
||||
var rowReal = rows.Real;
|
||||
var rowImaginary = rows.Imaginary;
|
||||
for (var row = 0; row < kernelSize; row++)
|
||||
{
|
||||
var realLine = rowReal.Slice(row * size, size);
|
||||
var imaginaryLine = rowImaginary.Slice(row * size, size);
|
||||
realLine.Clear();
|
||||
imaginaryLine.Clear();
|
||||
for (var offsetX = -radius; offsetX <= radius; offsetX++)
|
||||
real[(-offsetY & mask) * size + (-offsetX & mask)] = kernel[(offsetY + radius) * kernelSize + offsetX + radius];
|
||||
realLine[(-offsetX) & mask] = kernel[row * kernelSize + offsetX + radius];
|
||||
|
||||
FastFourierTransform.Forward(realLine, imaginaryLine);
|
||||
}
|
||||
|
||||
FastFourierTransform.Forward2D(real, imaginary, size, size);
|
||||
for (var frequencyY = 0; frequencyY < size; frequencyY++)
|
||||
var half = size / 2;
|
||||
var real = column.Real[..size];
|
||||
var imaginary = column.Imaginary[..size];
|
||||
for (var frequencyX = 0; frequencyX <= half; frequencyX++)
|
||||
{
|
||||
for (var frequencyX = 0; frequencyX < size; frequencyX++)
|
||||
real.Clear();
|
||||
imaginary.Clear();
|
||||
for (var row = 0; row < kernelSize; row++)
|
||||
{
|
||||
var index = frequencyY * size + frequencyX;
|
||||
spectrum[frequencyX * size + frequencyY] = new Float2(Flush((float)real[index]), Flush((float)imaginary[index]));
|
||||
var target = (radius - row) & mask;
|
||||
real[target] = rowReal[row * size + frequencyX];
|
||||
imaginary[target] = rowImaginary[row * size + frequencyX];
|
||||
}
|
||||
|
||||
FastFourierTransform.Forward(real, imaginary);
|
||||
var stored = spectrum.AsSpan(frequencyX * size, size);
|
||||
for (var frequencyY = 0; frequencyY < size; frequencyY++)
|
||||
stored[frequencyY] = new Float2(Flush((float)real[frequencyY]), Flush((float)imaginary[frequencyY]));
|
||||
}
|
||||
|
||||
if (plane == SpectrumPlane.Full)
|
||||
{
|
||||
for (var frequencyX = half + 1; frequencyX < size; frequencyX++)
|
||||
{
|
||||
var source = spectrum.AsSpan((size - frequencyX) * size, size);
|
||||
var stored = spectrum.AsSpan(frequencyX * size, size);
|
||||
for (var frequencyY = 0; frequencyY < size; frequencyY++)
|
||||
{
|
||||
var conjugate = source[(size - frequencyY) & mask];
|
||||
stored[frequencyY] = new Float2(conjugate.X, -conjugate.Y);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,4 +127,12 @@ internal sealed class KernelSpectrum
|
||||
}
|
||||
|
||||
public static float Flush(float value) => float.IsSubnormal(value) ? float.CopySign(0f, value) : value;
|
||||
|
||||
int StoredColumnsOf(int size) => plane == SpectrumPlane.Half ? HalfColumnsOf(size) : size;
|
||||
|
||||
sealed class TransformScratch
|
||||
{
|
||||
public readonly ComplexLines Rows = new();
|
||||
public readonly ComplexLines Column = new();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal readonly record struct LightOptions(bool Linear, bool Dither, float Threshold, float Boost)
|
||||
{
|
||||
public const float MaximumBoost = 1000f;
|
||||
|
||||
public bool IsDefault => !Linear && !Dither;
|
||||
|
||||
public bool Highlights => Linear && Boost > 1f && Threshold < 1f;
|
||||
|
||||
public LightOptions ForConvolution()
|
||||
=> new(Linear, false, Highlights ? Threshold : 0f, Highlights ? Boost : 0f);
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (!float.IsFinite(Threshold) || Threshold < 0f || Threshold > 1f)
|
||||
throw new ArgumentOutOfRangeException(nameof(Threshold));
|
||||
if (!float.IsFinite(Boost) || Boost < 0f || Boost > MaximumBoost)
|
||||
throw new ArgumentOutOfRangeException(nameof(Boost));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Intrinsics;
|
||||
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal static class LightTransform
|
||||
{
|
||||
public const int Channels = ByteColor.Channels;
|
||||
public const float DecodeToeLimit = 0.04045f;
|
||||
public const float EncodeToeLimit = 0.0031308f;
|
||||
public const float ToeSlope = 12.92f;
|
||||
public const float Offset = 0.055f;
|
||||
public const float Scale = 1.055f;
|
||||
public const float DecodeExponent = 2.4f;
|
||||
public const float EncodeExponent = 0.41666666f;
|
||||
|
||||
const uint DitherColumnMultiplier = 0x9E3779B1u;
|
||||
const uint DitherRowMultiplier = 0x85EBCA77u;
|
||||
const uint DitherFirstMultiplier = 0x7FEB352Du;
|
||||
const uint DitherSecondMultiplier = 0x846CA68Bu;
|
||||
const int DitherFirstShift = 16;
|
||||
const int DitherSecondShift = 15;
|
||||
const int DitherThresholdBits = 24;
|
||||
const int HashBits = 32;
|
||||
const float DitherThresholdScale = 1f / (1 << DitherThresholdBits);
|
||||
const int MantissaBits = 23;
|
||||
const int ExponentBias = 127;
|
||||
const int OneBits = ExponentBias << MantissaBits;
|
||||
const int EncodeStepsPerOctaveLog2 = 8;
|
||||
const int EncodeFirstOctave = -9;
|
||||
const int EncodeFractionBits = MantissaBits - EncodeStepsPerOctaveLog2;
|
||||
const int EncodeFirstStep = ((ExponentBias + EncodeFirstOctave) << MantissaBits) >> EncodeFractionBits;
|
||||
const int EncodeSteps = (OneBits >> EncodeFractionBits) - EncodeFirstStep;
|
||||
const int DecodeStepsPerOctaveLog2 = 10;
|
||||
const int DecodeFirstOctave = -4;
|
||||
const int DecodeFractionBits = MantissaBits - DecodeStepsPerOctaveLog2;
|
||||
const int DecodeFirstStep = ((ExponentBias + DecodeFirstOctave) << MantissaBits) >> DecodeFractionBits;
|
||||
const int DecodeSteps = (OneBits >> DecodeFractionBits) - DecodeFirstStep;
|
||||
const float EncodeFractionScale = 1f / (1 << EncodeFractionBits);
|
||||
const float DecodeFractionScale = 1f / (1 << DecodeFractionBits);
|
||||
|
||||
static readonly float[] EncodePairs = BuildPairs(EncodeFractionBits, EncodeFirstStep, EncodeSteps, linear => Scale * Math.Pow(linear, EncodeExponent) - Offset);
|
||||
static readonly float[] DecodePairs = BuildPairs(DecodeFractionBits, DecodeFirstStep, DecodeSteps, power => Math.Pow(power, DecodeExponent));
|
||||
static readonly float[] OpaqueDecode = BuildOpaqueDecode();
|
||||
static readonly Vector128<float> AlphaLane = Vector128.Create(0, 0, 0, -1).AsSingle();
|
||||
|
||||
public static float Decode(float encoded)
|
||||
{
|
||||
if (!(encoded > DecodeToeLimit))
|
||||
return encoded / ToeSlope;
|
||||
if (encoded >= 1f)
|
||||
return 1f;
|
||||
|
||||
var bits = BitConverter.SingleToInt32Bits((encoded + Offset) / Scale);
|
||||
var step = (bits >> DecodeFractionBits) - DecodeFirstStep;
|
||||
var fraction = (bits & ((1 << DecodeFractionBits) - 1)) * DecodeFractionScale;
|
||||
ref var pair = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(DecodePairs), step * 2);
|
||||
return pair + Unsafe.Add(ref pair, 1) * fraction;
|
||||
}
|
||||
|
||||
public static float Encode(float linear)
|
||||
{
|
||||
if (!(linear > EncodeToeLimit))
|
||||
return ToeSlope * linear;
|
||||
if (linear >= 1f)
|
||||
return 1f;
|
||||
|
||||
var bits = BitConverter.SingleToInt32Bits(linear);
|
||||
var step = (bits >> EncodeFractionBits) - EncodeFirstStep;
|
||||
var fraction = (bits & ((1 << EncodeFractionBits) - 1)) * EncodeFractionScale;
|
||||
ref var pair = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(EncodePairs), step * 2);
|
||||
return pair + Unsafe.Add(ref pair, 1) * fraction;
|
||||
}
|
||||
|
||||
public static (float Red, float Green, float Blue, float Alpha) FromBytes(byte red, byte green, byte blue, byte alpha, in LightOptions options)
|
||||
{
|
||||
if (!options.Linear)
|
||||
return (red / ByteColor.Scale, green / ByteColor.Scale, blue / ByteColor.Scale, alpha / ByteColor.Scale);
|
||||
if (alpha == 0)
|
||||
return default;
|
||||
|
||||
var opacity = alpha / ByteColor.Scale;
|
||||
float straightRed;
|
||||
float straightGreen;
|
||||
float straightBlue;
|
||||
float linearRed;
|
||||
float linearGreen;
|
||||
float linearBlue;
|
||||
if (alpha == ByteColor.Maximum)
|
||||
{
|
||||
straightRed = red / ByteColor.Scale;
|
||||
straightGreen = green / ByteColor.Scale;
|
||||
straightBlue = blue / ByteColor.Scale;
|
||||
linearRed = OpaqueDecode[red];
|
||||
linearGreen = OpaqueDecode[green];
|
||||
linearBlue = OpaqueDecode[blue];
|
||||
}
|
||||
else
|
||||
{
|
||||
straightRed = MathF.Min(red / (float)alpha, 1f);
|
||||
straightGreen = MathF.Min(green / (float)alpha, 1f);
|
||||
straightBlue = MathF.Min(blue / (float)alpha, 1f);
|
||||
linearRed = Decode(straightRed);
|
||||
linearGreen = Decode(straightGreen);
|
||||
linearBlue = Decode(straightBlue);
|
||||
}
|
||||
|
||||
var weight = 1f;
|
||||
if (options.Highlights)
|
||||
{
|
||||
var peak = MathF.Max(MathF.Max(straightRed, straightGreen), straightBlue);
|
||||
var excess = MathF.Min(MathF.Max((peak - options.Threshold) / (1f - options.Threshold), 0f), 1f);
|
||||
weight = 1f + (options.Boost - 1f) * excess * excess;
|
||||
}
|
||||
|
||||
var scale = opacity * weight;
|
||||
return (linearRed * scale, linearGreen * scale, linearBlue * scale, scale);
|
||||
}
|
||||
|
||||
public static (byte Blue, byte Green, byte Red, byte Alpha) ToBytes(
|
||||
float red,
|
||||
float green,
|
||||
float blue,
|
||||
float alpha,
|
||||
float gain,
|
||||
in LightOptions options,
|
||||
int x,
|
||||
int y)
|
||||
{
|
||||
float outputRed;
|
||||
float outputGreen;
|
||||
float outputBlue;
|
||||
float outputAlpha;
|
||||
if (options.Linear)
|
||||
{
|
||||
outputAlpha = Saturate(alpha * gain);
|
||||
if (outputAlpha > 0f)
|
||||
{
|
||||
outputRed = Encode(MathF.Min(Saturate(red * gain), outputAlpha) / outputAlpha) * outputAlpha;
|
||||
outputGreen = Encode(MathF.Min(Saturate(green * gain), outputAlpha) / outputAlpha) * outputAlpha;
|
||||
outputBlue = Encode(MathF.Min(Saturate(blue * gain), outputAlpha) / outputAlpha) * outputAlpha;
|
||||
}
|
||||
else
|
||||
{
|
||||
outputRed = 0f;
|
||||
outputGreen = 0f;
|
||||
outputBlue = 0f;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
outputRed = Saturate(red * gain);
|
||||
outputGreen = Saturate(green * gain);
|
||||
outputBlue = Saturate(blue * gain);
|
||||
outputAlpha = Saturate(alpha * gain);
|
||||
}
|
||||
|
||||
var thresholdSharedByChannels = options.Dither ? DitherThreshold(x, y) : 0f;
|
||||
return (
|
||||
Quantize(outputBlue, options.Dither, thresholdSharedByChannels),
|
||||
Quantize(outputGreen, options.Dither, thresholdSharedByChannels),
|
||||
Quantize(outputRed, options.Dither, thresholdSharedByChannels),
|
||||
Quantize(outputAlpha, options.Dither, thresholdSharedByChannels));
|
||||
}
|
||||
|
||||
public static uint ToPacked(Vector128<float> value, float gain, in LightOptions options, int x, int y)
|
||||
{
|
||||
var saturated = Saturate(value * Vector128.Create(gain));
|
||||
var color = saturated;
|
||||
if (options.Linear)
|
||||
{
|
||||
var alpha = Vector128.Shuffle(saturated, Vector128.Create(3, 3, 3, 3));
|
||||
var visible = Vector128.GreaterThan(alpha, Vector128<float>.Zero);
|
||||
var encoded = Encode(Vector128.Min(saturated, alpha) / alpha) * alpha;
|
||||
color = Vector128.ConditionalSelect(AlphaLane, saturated, Vector128.ConditionalSelect(visible, encoded, Vector128<float>.Zero));
|
||||
}
|
||||
|
||||
var scaled = color * Vector128.Create(ByteColor.Scale);
|
||||
var levels = options.Dither
|
||||
? Vector128.ConvertToInt32(Vector128.Min(scaled + Vector128.Create(DitherThreshold(x, y)), Vector128.Create(ByteColor.Scale)))
|
||||
: Vector128.ConvertToInt32(scaled + Vector128.Create(ByteColor.Rounding));
|
||||
var ordered = Vector128.Shuffle(levels, Vector128.Create(2, 1, 0, 3)).AsUInt32();
|
||||
var words = Vector128.Narrow(ordered, ordered);
|
||||
return Vector128.Narrow(words, words).AsUInt32().ToScalar();
|
||||
}
|
||||
|
||||
static Vector128<float> Encode(Vector128<float> linear)
|
||||
=> Vector128.Create(Encode(linear.GetElement(0)), Encode(linear.GetElement(1)), Encode(linear.GetElement(2)), 0f);
|
||||
|
||||
static Vector128<float> Saturate(Vector128<float> value)
|
||||
{
|
||||
value = Vector128.ConditionalSelect(Vector128.Equals(value, value), value, Vector128<float>.Zero);
|
||||
return Vector128.Min(Vector128.Max(value, Vector128<float>.Zero), Vector128<float>.One);
|
||||
}
|
||||
|
||||
public static float DitherThreshold(int x, int y)
|
||||
{
|
||||
var hash = (uint)x * DitherColumnMultiplier ^ (uint)y * DitherRowMultiplier;
|
||||
hash ^= hash >> DitherFirstShift;
|
||||
hash *= DitherFirstMultiplier;
|
||||
hash ^= hash >> DitherSecondShift;
|
||||
hash *= DitherSecondMultiplier;
|
||||
hash ^= hash >> DitherFirstShift;
|
||||
return (hash >> (HashBits - DitherThresholdBits)) * DitherThresholdScale;
|
||||
}
|
||||
|
||||
static byte Quantize(float value, bool dither, float threshold)
|
||||
=> dither
|
||||
? (byte)MathF.Min(value * ByteColor.Scale + threshold, ByteColor.Scale)
|
||||
: (byte)(value * ByteColor.Scale + ByteColor.Rounding);
|
||||
|
||||
static float Saturate(float value)
|
||||
=> float.IsNaN(value) ? 0f : Math.Clamp(value, 0f, 1f);
|
||||
|
||||
static float[] BuildOpaqueDecode()
|
||||
{
|
||||
var table = new float[ByteColor.Levels];
|
||||
for (var index = 0; index < table.Length; index++)
|
||||
table[index] = Decode(index / ByteColor.Scale);
|
||||
return table;
|
||||
}
|
||||
|
||||
static float[] BuildPairs(int fractionBits, int firstStep, int steps, Func<double, double> curve)
|
||||
{
|
||||
var values = new float[steps + 1];
|
||||
for (var index = 0; index < values.Length; index++)
|
||||
values[index] = (float)curve(BitConverter.Int32BitsToSingle((firstStep + index) << fractionBits));
|
||||
|
||||
var pairs = new float[(steps + 1) * 2];
|
||||
for (var index = 0; index <= steps; index++)
|
||||
{
|
||||
pairs[index * 2] = values[index];
|
||||
pairs[index * 2 + 1] = index < steps ? values[index + 1] - values[index] : 0f;
|
||||
}
|
||||
|
||||
return pairs;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal sealed class ScratchPool<T>(int capacity) where T : class, new()
|
||||
{
|
||||
readonly T?[] slots = new T?[capacity];
|
||||
readonly object gate = new();
|
||||
|
||||
public static ScratchPool<T> Shared { get; } = new(Environment.ProcessorCount);
|
||||
|
||||
public Lease Rent()
|
||||
{
|
||||
T? item = null;
|
||||
lock (gate)
|
||||
{
|
||||
for (var index = 0; index < slots.Length; index++)
|
||||
{
|
||||
if (slots[index] is not { } found)
|
||||
continue;
|
||||
|
||||
item = found;
|
||||
slots[index] = null;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return new Lease(this, item ?? new T());
|
||||
}
|
||||
|
||||
void Return(T item)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
for (var index = 0; index < slots.Length; index++)
|
||||
{
|
||||
if (slots[index] is not null)
|
||||
continue;
|
||||
|
||||
slots[index] = item;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct Lease(ScratchPool<T> pool, T value) : IDisposable
|
||||
{
|
||||
public T Value { get; } = value;
|
||||
|
||||
public void Dispose() => pool.Return(Value);
|
||||
}
|
||||
}
|
||||
@@ -7,12 +7,14 @@ internal static class SpectralSelfTest
|
||||
{
|
||||
public const string DeterminismName = "selftest.determinism";
|
||||
public const string FullName = "selftest.full";
|
||||
public const string ChromaticDeterminismName = "selftest.chromatic.determinism";
|
||||
public const string ChromaticFullName = "selftest.chromatic.full";
|
||||
public const int FullRadius = 3;
|
||||
public const int Margin = 4;
|
||||
|
||||
static readonly int[] Sizes = [TilePlan.SmallSize, TilePlan.LargeSize];
|
||||
|
||||
public static int MeasurementCount => Sizes.Length * (2 + 2 * GpuTileCheck.MeasurementCount(GpuTileConvolver.MaximumSamples));
|
||||
public static int MeasurementCount => 2 * Sizes.Length * (2 + 2 * GpuTileCheck.MeasurementCount(GpuTileConvolver.MaximumSamples));
|
||||
|
||||
public static int Run(GraphicsDevice device, int maximumRadius, Span<ConvolutionMeasurement> measurements)
|
||||
{
|
||||
@@ -23,16 +25,45 @@ internal static class SpectralSelfTest
|
||||
|
||||
var written = 0;
|
||||
using var convolver = new GpuTileConvolver(device);
|
||||
foreach (var size in Sizes)
|
||||
for (var pass = 0; pass < 2; pass++)
|
||||
{
|
||||
written += RunFull(device, convolver, size, measurements[written..]);
|
||||
var radius = Math.Min(maximumRadius, size == TilePlan.SmallSize ? TilePlan.SmallSizeRadiusLimit : TilePlan.MaximumRadius);
|
||||
written += RunChecked(device, convolver, size, Math.Min(radius, (size - 2) / 2), measurements[written..]);
|
||||
var chromatic = pass == 1;
|
||||
foreach (var size in Sizes)
|
||||
{
|
||||
written += RunFull(device, convolver, size, chromatic, measurements[written..]);
|
||||
var radius = Math.Min(maximumRadius, size == TilePlan.SmallSize ? TilePlan.SmallSizeRadiusLimit : TilePlan.MaximumRadius);
|
||||
written += RunChecked(device, convolver, size, Math.Min(radius, (size - 2) / 2), chromatic, measurements[written..]);
|
||||
}
|
||||
}
|
||||
|
||||
return written;
|
||||
}
|
||||
|
||||
public static double[] ChromaticKernel(int radius, ChromaticChannel channel)
|
||||
{
|
||||
var (spread, lean) = channel switch
|
||||
{
|
||||
ChromaticChannel.Red => (1.35, 0.5),
|
||||
ChromaticChannel.Green => (1d, 0.6),
|
||||
_ => (0.7, 0.7),
|
||||
};
|
||||
var kernelSize = radius * 2 + 1;
|
||||
var values = new double[kernelSize * kernelSize];
|
||||
var scale = (radius * radius + 1d) * spread;
|
||||
for (var y = 0; y < kernelSize; y++)
|
||||
{
|
||||
for (var x = 0; x < kernelSize; x++)
|
||||
{
|
||||
var dx = x - radius * lean;
|
||||
var dy = y - radius * (1.9 - lean);
|
||||
values[y * kernelSize + x] = Math.Exp(-(dx * dx * 0.4 + dy * dy * 0.15) / scale);
|
||||
}
|
||||
}
|
||||
|
||||
values[(kernelSize - 1) * kernelSize] += 0.5;
|
||||
return values;
|
||||
}
|
||||
|
||||
public static double[] Kernel(int radius)
|
||||
{
|
||||
var kernelSize = radius * 2 + 1;
|
||||
@@ -54,7 +85,7 @@ internal static class SpectralSelfTest
|
||||
|
||||
public static byte[] Pattern(int width, int height, int seed)
|
||||
{
|
||||
var pixels = new byte[width * height * 4];
|
||||
var pixels = new byte[width * height * ByteColor.Channels];
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
@@ -63,11 +94,11 @@ internal static class SpectralSelfTest
|
||||
continue;
|
||||
|
||||
var hash = Hash((uint)x, (uint)y, (uint)seed);
|
||||
var alpha = x % 61 < 3 ? 255u : hash & 255u;
|
||||
var offset = (y * width + x) * 4;
|
||||
pixels[offset] = (byte)(alpha * (hash >> 8 & 255u) / 255u);
|
||||
pixels[offset + 1] = (byte)(alpha * (hash >> 16 & 255u) / 255u);
|
||||
pixels[offset + 2] = (byte)(alpha * (hash >> 24) / 255u);
|
||||
var alpha = x % 61 < 3 ? ByteColor.Mask : hash & ByteColor.Mask;
|
||||
var offset = (y * width + x) * ByteColor.Channels;
|
||||
pixels[offset] = (byte)(alpha * (hash >> 8 & ByteColor.Mask) / ByteColor.Mask);
|
||||
pixels[offset + 1] = (byte)(alpha * (hash >> 16 & ByteColor.Mask) / ByteColor.Mask);
|
||||
pixels[offset + 2] = (byte)(alpha * (hash >> 24) / ByteColor.Mask);
|
||||
pixels[offset + 3] = (byte)alpha;
|
||||
}
|
||||
}
|
||||
@@ -90,17 +121,21 @@ internal static class SpectralSelfTest
|
||||
samples[index] = new Int2((int)(index * 7919L % width), (int)(index * 104729L % height));
|
||||
}
|
||||
|
||||
static int RunFull(GraphicsDevice device, GpuTileConvolver convolver, int size, Span<ConvolutionMeasurement> measurements)
|
||||
static int RunFull(GraphicsDevice device, GpuTileConvolver convolver, int size, bool chromatic, Span<ConvolutionMeasurement> measurements)
|
||||
{
|
||||
var spectrum = new KernelSpectrum();
|
||||
spectrum.Update(Kernel(FullRadius), FullRadius, size);
|
||||
var spectra = new ChromaticKernelSpectrum();
|
||||
if (chromatic)
|
||||
spectra.Update(ChromaticKernel(FullRadius, ChromaticChannel.Red), ChromaticKernel(FullRadius, ChromaticChannel.Green), ChromaticKernel(FullRadius, ChromaticChannel.Blue), FullRadius, size);
|
||||
else
|
||||
spectrum.Update(Kernel(FullRadius), FullRadius, size);
|
||||
var validSize = size - FullRadius * 2;
|
||||
var sourceWidth = validSize + 17;
|
||||
var sourceHeight = validSize + 13;
|
||||
var plan = TilePlan.Create(size, FullRadius, 0, 0, sourceWidth + Margin * 2, sourceHeight + Margin * 2);
|
||||
var source = Pattern(sourceWidth, sourceHeight, size);
|
||||
var first = Convolve(device, convolver, spectrum, plan, source, sourceWidth, sourceHeight, measurements[2..]);
|
||||
var second = Convolve(device, convolver, spectrum, plan, source, sourceWidth, sourceHeight, []);
|
||||
var first = Convolve(device, convolver, chromatic ? null : spectrum, chromatic ? spectra : null, plan, source, sourceWidth, sourceHeight, measurements[2..]);
|
||||
var second = Convolve(device, convolver, chromatic ? null : spectrum, chromatic ? spectra : null, plan, source, sourceWidth, sourceHeight, []);
|
||||
|
||||
var different = 0;
|
||||
for (var index = 0; index < first.Length; index++)
|
||||
@@ -108,52 +143,63 @@ internal static class SpectralSelfTest
|
||||
if (BitConverter.SingleToUInt32Bits(first[index]) != BitConverter.SingleToUInt32Bits(second[index]))
|
||||
different++;
|
||||
}
|
||||
measurements[0] = new ConvolutionMeasurement(DeterminismName, different, 0d, 0d);
|
||||
measurements[0] = new ConvolutionMeasurement(chromatic ? ChromaticDeterminismName : DeterminismName, different, 0d, 0d);
|
||||
|
||||
var norms = new (double RedGreen, double BlueAlpha)[plan.TileCount];
|
||||
for (var tile = 0; tile < plan.TileCount; tile++)
|
||||
norms[tile] = TileInput.Norms(source, Margin, Margin, sourceWidth, sourceHeight, plan, tile);
|
||||
|
||||
Span<double> expected = stackalloc double[4];
|
||||
var relative = ConvolutionBound.Relative(size, ConvolutionBound.GpuOperationError);
|
||||
var absolute = ConvolutionBound.FlushedOperations(size) * ConvolutionBound.SmallestNormal + DirectCorrelation.ErrorBound(spectrum.Kernel.Length);
|
||||
var relative = chromatic
|
||||
? ConvolutionBound.ChromaticRelative(size, ConvolutionBound.GpuOperationError)
|
||||
: ConvolutionBound.Relative(size, ConvolutionBound.GpuOperationError);
|
||||
var flushed = chromatic ? ConvolutionBound.ChromaticFlushedOperations(size) : ConvolutionBound.FlushedOperations(size);
|
||||
var absolute = flushed * ConvolutionBound.SmallestNormal + DirectCorrelation.ErrorBound((FullRadius * 2 + 1) * (FullRadius * 2 + 1));
|
||||
var worst = 0d;
|
||||
for (var y = 0; y < plan.RegionHeight; y++)
|
||||
{
|
||||
for (var x = 0; x < plan.RegionWidth; x++)
|
||||
{
|
||||
DirectCorrelation.Evaluate(source, sourceWidth, sourceHeight, spectrum.Kernel, FullRadius, x - Margin, y - Margin, expected);
|
||||
if (chromatic)
|
||||
DirectCorrelation.Evaluate(source, sourceWidth, sourceHeight, spectra.Red.Kernel, spectra.Green.Kernel, spectra.Blue.Kernel, FullRadius, x - Margin, y - Margin, expected);
|
||||
else
|
||||
DirectCorrelation.Evaluate(source, sourceWidth, sourceHeight, spectrum.Kernel, FullRadius, x - Margin, y - Margin, expected);
|
||||
var (redGreen, blueAlpha) = norms[plan.TileAt(x, y)];
|
||||
for (var channel = 0; channel < 4; channel++)
|
||||
{
|
||||
var bound = relative * (channel < 2 ? redGreen : blueAlpha) + absolute;
|
||||
var error = Math.Abs(first[(y * plan.RegionWidth + x) * 4 + channel] - expected[channel]);
|
||||
var error = Math.Abs(first[(y * plan.RegionWidth + x) * ByteColor.Channels + channel] - expected[channel]);
|
||||
worst = Math.Max(worst, double.IsNaN(error) ? double.PositiveInfinity : error / bound);
|
||||
}
|
||||
}
|
||||
}
|
||||
measurements[1] = new ConvolutionMeasurement(FullName, worst, 0d, 1d);
|
||||
measurements[1] = new ConvolutionMeasurement(chromatic ? ChromaticFullName : FullName, worst, 0d, 1d);
|
||||
return 2 + GpuTileCheck.MeasurementCount(GpuTileConvolver.MaximumSamples);
|
||||
}
|
||||
|
||||
static int RunChecked(GraphicsDevice device, GpuTileConvolver convolver, int size, int radius, Span<ConvolutionMeasurement> measurements)
|
||||
static int RunChecked(GraphicsDevice device, GpuTileConvolver convolver, int size, int radius, bool chromatic, Span<ConvolutionMeasurement> measurements)
|
||||
{
|
||||
var spectrum = new KernelSpectrum();
|
||||
spectrum.Update(Kernel(radius), radius, size);
|
||||
var spectra = new ChromaticKernelSpectrum();
|
||||
if (chromatic)
|
||||
spectra.Update(ChromaticKernel(radius, ChromaticChannel.Red), ChromaticKernel(radius, ChromaticChannel.Green), ChromaticKernel(radius, ChromaticChannel.Blue), radius, size);
|
||||
else
|
||||
spectrum.Update(Kernel(radius), radius, size);
|
||||
var validSize = size - radius * 2;
|
||||
var sourceWidth = validSize + 9;
|
||||
var sourceHeight = validSize + 5;
|
||||
var margin = radius + Margin;
|
||||
var plan = TilePlan.Create(size, radius, 0, 0, sourceWidth + margin * 2, sourceHeight + margin * 2);
|
||||
var source = Pattern(sourceWidth, sourceHeight, size + radius);
|
||||
_ = Convolve(device, convolver, spectrum, plan, source, sourceWidth, sourceHeight, measurements, margin);
|
||||
_ = Convolve(device, convolver, chromatic ? null : spectrum, chromatic ? spectra : null, plan, source, sourceWidth, sourceHeight, measurements, margin);
|
||||
return GpuTileCheck.MeasurementCount(GpuTileConvolver.MaximumSamples);
|
||||
}
|
||||
|
||||
static float[] Convolve(
|
||||
GraphicsDevice device,
|
||||
GpuTileConvolver convolver,
|
||||
KernelSpectrum spectrum,
|
||||
KernelSpectrum? spectrum,
|
||||
ChromaticKernelSpectrum? spectra,
|
||||
in TilePlan plan,
|
||||
byte[] source,
|
||||
int sourceWidth,
|
||||
@@ -163,8 +209,11 @@ internal static class SpectralSelfTest
|
||||
{
|
||||
Span<Int2> samples = stackalloc Int2[GpuTileConvolver.MaximumSamples];
|
||||
Samples(plan.RegionWidth, plan.RegionHeight, plan.ValidSize, samples);
|
||||
convolver.Upload(spectrum);
|
||||
var job = convolver.Prepare(plan, margin, margin, sourceWidth, sourceHeight, 1f, samples, true);
|
||||
if (spectra is not null)
|
||||
convolver.Upload(spectra);
|
||||
else
|
||||
convolver.Upload(spectrum!);
|
||||
var job = convolver.Prepare(plan, margin, margin, sourceWidth, sourceHeight, 1f, samples, true, default, spectra is not null);
|
||||
using var sourceTexture = device.AllocateReadWriteTexture2D<Bgra32, Float4>(sourceWidth, sourceHeight);
|
||||
sourceTexture.CopyFrom(MemoryMarshal.Cast<byte, Bgra32>(source));
|
||||
using var output = device.AllocateReadWriteTexture2D<Bgra32, Float4>(plan.RegionWidth, plan.RegionHeight);
|
||||
@@ -176,7 +225,12 @@ internal static class SpectralSelfTest
|
||||
}
|
||||
|
||||
if (!measurements.IsEmpty)
|
||||
GpuTileCheck.Evaluate(convolver.ReadReport(job), job, samples, spectrum.Kernel, measurements);
|
||||
{
|
||||
if (spectra is not null)
|
||||
GpuTileCheck.Evaluate(convolver.ReadReport(job), job, samples, spectra.Red.Kernel, spectra.Green.Kernel, spectra.Blue.Kernel, measurements);
|
||||
else
|
||||
GpuTileCheck.Evaluate(convolver.ReadReport(job), job, samples, spectrum!.Kernel, measurements);
|
||||
}
|
||||
var values = new Float4[plan.RegionWidth * plan.RegionHeight];
|
||||
convolver.ReadStore(job, values);
|
||||
convolver.ReleaseStore();
|
||||
|
||||
@@ -2,7 +2,7 @@ namespace SpectralConvolution;
|
||||
|
||||
internal static class TileInput
|
||||
{
|
||||
const int Channels = 4;
|
||||
const int Channels = ByteColor.Channels;
|
||||
|
||||
public static (double RedGreen, double BlueAlpha) Norms(
|
||||
ReadOnlySpan<byte> bgra,
|
||||
@@ -36,6 +36,6 @@ internal static class TileInput
|
||||
}
|
||||
}
|
||||
|
||||
return (Math.Sqrt(redGreen) / 255d, Math.Sqrt(blueAlpha) / 255d);
|
||||
return (Math.Sqrt(redGreen) / ByteColor.ScaleDouble, Math.Sqrt(blueAlpha) / ByteColor.ScaleDouble);
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,12 @@ internal readonly record struct TilePlan
|
||||
public const int LargeSize = 512;
|
||||
public const int SmallSizeRadiusLimit = 23;
|
||||
public const int MaximumRadius = (LargeSize - 1) / 2;
|
||||
public const int GroupElements = 512;
|
||||
public const int GroupElementsLog2 = 9;
|
||||
public const int GroupElements = 1 << GroupElementsLog2;
|
||||
public const int ValuesPerThread = 2;
|
||||
public const int GroupThreads = GroupElements / ValuesPerThread;
|
||||
public const int ChromaticPlanes = 2;
|
||||
public const int ChromaticGroupElements = GroupElements * ChromaticPlanes;
|
||||
public const int ElementBytes = 16;
|
||||
public const long BatchBudgetBytes = 16L << 20;
|
||||
|
||||
@@ -55,6 +60,10 @@ internal readonly record struct TilePlan
|
||||
|
||||
public int GroupCount => TileCount * GroupsPerTile;
|
||||
|
||||
public int ColumnUnitsPerGroup => GroupElements / Size;
|
||||
|
||||
public int ChromaticGroupsPerTile => (ChromaticKernelSpectrum.HalfColumnsOf(Size) + ColumnUnitsPerGroup - 1) / ColumnUnitsPerGroup;
|
||||
|
||||
public int BatchTiles => (int)Math.Min(TileCount, Math.Max(1L, BatchBudgetBytes / ((long)ElementBytes * TileElements)));
|
||||
|
||||
public static int SelectSize(int radius)
|
||||
@@ -67,12 +76,24 @@ internal readonly record struct TilePlan
|
||||
public static TilePlan Create(int radius, int regionX, int regionY, int regionWidth, int regionHeight)
|
||||
=> Create(SelectSize(radius), radius, regionX, regionY, regionWidth, regionHeight);
|
||||
|
||||
public static TilePlan Create(int size, int radius, int regionX, int regionY, int regionWidth, int regionHeight)
|
||||
public static int Log2Of(int size)
|
||||
{
|
||||
if (!IsSupportedSize(size))
|
||||
throw new ArgumentOutOfRangeException(nameof(size));
|
||||
return BitOperations.Log2((uint)size);
|
||||
}
|
||||
|
||||
public static void ValidateKernel(int size, int radius)
|
||||
{
|
||||
if (!IsSupportedSize(size))
|
||||
throw new ArgumentOutOfRangeException(nameof(size));
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(radius);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(radius * 2, size);
|
||||
}
|
||||
|
||||
public static TilePlan Create(int size, int radius, int regionX, int regionY, int regionWidth, int regionHeight)
|
||||
{
|
||||
ValidateKernel(size, radius);
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(regionWidth);
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(regionHeight);
|
||||
return new TilePlan(size, radius, regionX, regionY, regionWidth, regionHeight);
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
using ComputeWeave;
|
||||
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal static class TileShaderMath
|
||||
{
|
||||
const uint ExponentMask = 0x7F800000u;
|
||||
|
||||
public static bool IsNonFinite(float value) => (Hlsl.AsUInt(value) & ExponentMask) == ExponentMask;
|
||||
|
||||
public static bool IsNonFinite(Float4 value)
|
||||
=> IsNonFinite(value.X) || IsNonFinite(value.Y) || IsNonFinite(value.Z) || IsNonFinite(value.W);
|
||||
|
||||
public static int TileIndex(int batchStart, int groupBase, int log2Size) => batchStart + (groupBase >> (log2Size * 2));
|
||||
|
||||
public static Int2 TileOrigin(int tileIndex, int tilesX, int validSize, int radius)
|
||||
{
|
||||
var tileRow = tileIndex / tilesX;
|
||||
return new Int2((tileIndex - tileRow * tilesX) * validSize - radius, tileRow * validSize - radius);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
using System.Runtime.ExceptionServices;
|
||||
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal interface IParallelJob
|
||||
{
|
||||
void Begin(int worker)
|
||||
{
|
||||
}
|
||||
|
||||
void Execute(int index, int worker);
|
||||
}
|
||||
|
||||
internal sealed class WorkerPool : IDisposable
|
||||
{
|
||||
public const int MaximumHelpers = 5;
|
||||
|
||||
readonly Thread[] threads;
|
||||
readonly SemaphoreSlim start = new(0);
|
||||
readonly SemaphoreSlim finished = new(0);
|
||||
readonly object gate = new();
|
||||
IParallelJob? job;
|
||||
bool disposed;
|
||||
int count;
|
||||
int next;
|
||||
int claimed;
|
||||
Exception? failure;
|
||||
|
||||
public WorkerPool(int helpers)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(helpers);
|
||||
threads = new Thread[helpers];
|
||||
for (var index = 0; index < helpers; index++)
|
||||
{
|
||||
threads[index] = new Thread(Serve) { IsBackground = true, Name = nameof(WorkerPool) };
|
||||
threads[index].Start();
|
||||
}
|
||||
}
|
||||
|
||||
public static WorkerPool Shared { get; } = new(Math.Clamp(Environment.ProcessorCount - 1, 0, MaximumHelpers));
|
||||
|
||||
public int Parallelism => threads.Length + 1;
|
||||
|
||||
public void Run(IParallelJob parallelJob, int itemCount, int maximumParallelism = int.MaxValue)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(parallelJob);
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maximumParallelism);
|
||||
ObjectDisposedException.ThrowIf(disposed, this);
|
||||
if (itemCount <= 0)
|
||||
return;
|
||||
lock (gate)
|
||||
{
|
||||
var helpers = Math.Min(Math.Min(threads.Length, itemCount - 1), maximumParallelism - 1);
|
||||
if (helpers == 0)
|
||||
{
|
||||
parallelJob.Begin(0);
|
||||
for (var index = 0; index < itemCount; index++)
|
||||
parallelJob.Execute(index, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
job = parallelJob;
|
||||
count = itemCount;
|
||||
next = 0;
|
||||
claimed = 0;
|
||||
failure = null;
|
||||
start.Release(helpers);
|
||||
Drain();
|
||||
for (var index = 0; index < helpers; index++)
|
||||
finished.Wait();
|
||||
|
||||
job = null;
|
||||
if (failure is { } exception)
|
||||
ExceptionDispatchInfo.Throw(exception);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (disposed)
|
||||
return;
|
||||
disposed = true;
|
||||
if (threads.Length > 0)
|
||||
start.Release(threads.Length);
|
||||
foreach (var thread in threads)
|
||||
thread.Join();
|
||||
start.Dispose();
|
||||
finished.Dispose();
|
||||
}
|
||||
|
||||
void Serve()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
start.Wait();
|
||||
if (disposed)
|
||||
return;
|
||||
Drain();
|
||||
finished.Release();
|
||||
}
|
||||
}
|
||||
|
||||
void Drain()
|
||||
{
|
||||
try
|
||||
{
|
||||
var worker = Interlocked.Increment(ref claimed) - 1;
|
||||
job!.Begin(worker);
|
||||
int index;
|
||||
while ((index = Interlocked.Increment(ref next) - 1) < count)
|
||||
job.Execute(index, worker);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Interlocked.CompareExchange(ref failure, exception, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -66,6 +66,85 @@ internal static class HarnessCases
|
||||
yield return ("coma-vertical-1", Create(effect => effect.ComaVertical.Values[0].Value = 1), [0]);
|
||||
yield return ("spherical-1", Create(effect => effect.Spherical.Values[0].Value = 1), [0]);
|
||||
yield return ("defocus-animated-frames-0-8", Create(effect => effect.Defocus.CopyFrom(Linear(0d, 3d))), Enumerable.Range(0, 9).ToArray());
|
||||
yield return ("linear", Create(effect => effect.Linear = true), [0]);
|
||||
yield return ("linear-gain-150", Create(effect =>
|
||||
{
|
||||
effect.Linear = true;
|
||||
effect.Gain.Values[0].Value = 150;
|
||||
}), [0]);
|
||||
yield return ("linear-highlight-boost-30", Create(effect =>
|
||||
{
|
||||
effect.Linear = true;
|
||||
effect.HighlightThreshold.Values[0].Value = 70;
|
||||
effect.HighlightBoost.Values[0].Value = 30;
|
||||
}), [0]);
|
||||
yield return ("linear-highlight-threshold-50-boost-8", Create(effect =>
|
||||
{
|
||||
effect.Linear = true;
|
||||
effect.HighlightThreshold.Values[0].Value = 50;
|
||||
effect.HighlightBoost.Values[0].Value = 8;
|
||||
}), [0]);
|
||||
yield return ("dither", Create(effect => effect.Dither = true), [0]);
|
||||
yield return ("linear-dither-defocus-1", Create(effect =>
|
||||
{
|
||||
effect.Linear = true;
|
||||
effect.Dither = true;
|
||||
effect.Defocus.Values[0].Value = 1;
|
||||
}), [0]);
|
||||
yield return ("linear-highlight-polygon-defocus-2-radius-40", Create(effect =>
|
||||
{
|
||||
effect.Linear = true;
|
||||
effect.HighlightThreshold.Values[0].Value = 70;
|
||||
effect.HighlightBoost.Values[0].Value = 20;
|
||||
effect.ApertureShape = WaveOpticsApertureShape.RegularPolygon;
|
||||
effect.KernelRadius = 40;
|
||||
effect.Defocus.Values[0].Value = 2;
|
||||
}), [0]);
|
||||
yield return ("linear-highlight-animated-frames-0-8", Create(effect =>
|
||||
{
|
||||
effect.Linear = true;
|
||||
effect.HighlightThreshold.Values[0].Value = 70;
|
||||
effect.HighlightBoost.CopyFrom(Linear(1d, 40d));
|
||||
}), Enumerable.Range(0, 9).ToArray());
|
||||
yield return ("color-primaries-defocus-1", Create(effect =>
|
||||
{
|
||||
effect.ColorMode = WaveOpticsColorMode.Primaries;
|
||||
effect.Defocus.Values[0].Value = 1;
|
||||
}), [0]);
|
||||
yield return ("color-broadband-defocus-1", Create(effect =>
|
||||
{
|
||||
effect.ColorMode = WaveOpticsColorMode.Broadband;
|
||||
effect.Defocus.Values[0].Value = 1;
|
||||
}), [0]);
|
||||
yield return ("color-primaries-polygon-radius-40-clear", Create(effect =>
|
||||
{
|
||||
effect.ColorMode = WaveOpticsColorMode.Primaries;
|
||||
effect.ApertureShape = WaveOpticsApertureShape.RegularPolygon;
|
||||
effect.KernelRadius = 40;
|
||||
effect.FNumber.Values[0].Value = 16;
|
||||
effect.PixelPitch.Values[0].Value = 2;
|
||||
}), [0]);
|
||||
yield return ("color-broadband-high-coma-radius-63", Create(effect =>
|
||||
{
|
||||
effect.ColorMode = WaveOpticsColorMode.Broadband;
|
||||
effect.Quality = WaveOpticsQuality.High;
|
||||
effect.KernelRadius = WaveOpticsSettings.MaximumKernelRadius;
|
||||
effect.ComaHorizontal.Values[0].Value = 1;
|
||||
}), [0]);
|
||||
yield return ("color-primaries-linear-highlight-defocus-1", Create(effect =>
|
||||
{
|
||||
effect.ColorMode = WaveOpticsColorMode.Primaries;
|
||||
effect.Linear = true;
|
||||
effect.HighlightThreshold.Values[0].Value = 70;
|
||||
effect.HighlightBoost.Values[0].Value = 20;
|
||||
effect.Defocus.Values[0].Value = 1;
|
||||
}), [0]);
|
||||
yield return ("color-broadband-defocus-animated-frames-0-8", Create(effect =>
|
||||
{
|
||||
effect.ColorMode = WaveOpticsColorMode.Broadband;
|
||||
effect.Quality = WaveOpticsQuality.Draft;
|
||||
effect.Defocus.CopyFrom(Linear(0d, 3d));
|
||||
}), Enumerable.Range(0, 9).ToArray());
|
||||
}
|
||||
|
||||
public static IEnumerable<(string Name, Func<WaveOpticsEffect> Create, Action<WaveOpticsEffect> Change, int Frame)> Transitions()
|
||||
@@ -94,6 +173,37 @@ internal static class HarnessCases
|
||||
yield return ("coma-vertical-0-to-1", () => Create(), effect => effect.ComaVertical.Values[0].Value = 1, 0);
|
||||
yield return ("spherical-0-to-1", () => Create(), effect => effect.Spherical.Values[0].Value = 1, 0);
|
||||
yield return ("amount-100-to-0", () => Create(), effect => effect.Amount.Values[0].Value = 0, 0);
|
||||
yield return ("linear-off-to-on", () => Create(), effect => effect.Linear = true, 0);
|
||||
yield return ("linear-on-to-off", () => Create(effect => effect.Linear = true), effect => effect.Linear = false, 0);
|
||||
yield return ("dither-off-to-on", () => Create(), effect => effect.Dither = true, 0);
|
||||
yield return ("dither-on-to-off", () => Create(effect => effect.Dither = true), effect => effect.Dither = false, 0);
|
||||
yield return ("highlight-boost-1-to-30", () => Create(effect =>
|
||||
{
|
||||
effect.Linear = true;
|
||||
effect.HighlightThreshold.Values[0].Value = 70;
|
||||
}), effect => effect.HighlightBoost.Values[0].Value = 30, 0);
|
||||
yield return ("highlight-threshold-95-to-50", () => Create(effect =>
|
||||
{
|
||||
effect.Linear = true;
|
||||
effect.HighlightBoost.Values[0].Value = 8;
|
||||
}), effect => effect.HighlightThreshold.Values[0].Value = 50, 0);
|
||||
yield return ("linear-gain-100-to-150", () => Create(effect => effect.Linear = true), effect => effect.Gain.Values[0].Value = 150, 0);
|
||||
yield return ("color-monochrome-to-primaries", () => Create(effect => effect.Defocus.Values[0].Value = 1), effect => effect.ColorMode = WaveOpticsColorMode.Primaries, 0);
|
||||
yield return ("color-primaries-to-broadband", () => Create(effect =>
|
||||
{
|
||||
effect.ColorMode = WaveOpticsColorMode.Primaries;
|
||||
effect.Defocus.Values[0].Value = 1;
|
||||
}), effect => effect.ColorMode = WaveOpticsColorMode.Broadband, 0);
|
||||
yield return ("color-broadband-to-monochrome", () => Create(effect =>
|
||||
{
|
||||
effect.ColorMode = WaveOpticsColorMode.Broadband;
|
||||
effect.Defocus.Values[0].Value = 1;
|
||||
}), effect => effect.ColorMode = WaveOpticsColorMode.Monochrome, 0);
|
||||
yield return ("color-primaries-defocus-1-to-2", () => Create(effect =>
|
||||
{
|
||||
effect.ColorMode = WaveOpticsColorMode.Primaries;
|
||||
effect.Defocus.Values[0].Value = 1;
|
||||
}), effect => effect.Defocus.Values[0].Value = 2, 0);
|
||||
}
|
||||
|
||||
public static IEnumerable<(string Name, WaveOpticsEffect Effect)> Benchmarks()
|
||||
@@ -109,6 +219,25 @@ internal static class HarnessCases
|
||||
}));
|
||||
yield return ("defocus-animated", Create(effect => effect.Defocus.CopyFrom(Linear(0d, 3d))));
|
||||
yield return ("amount-0", Create(effect => effect.Amount.Values[0].Value = 0));
|
||||
yield return ("color-primaries", Create(effect => effect.ColorMode = WaveOpticsColorMode.Primaries));
|
||||
yield return ("color-broadband", Create(effect => effect.ColorMode = WaveOpticsColorMode.Broadband));
|
||||
yield return ("color-primaries-defocus-animated", Create(effect =>
|
||||
{
|
||||
effect.ColorMode = WaveOpticsColorMode.Primaries;
|
||||
effect.Defocus.CopyFrom(Linear(0d, 3d));
|
||||
}));
|
||||
yield return ("color-broadband-defocus-animated", Create(effect =>
|
||||
{
|
||||
effect.ColorMode = WaveOpticsColorMode.Broadband;
|
||||
effect.Defocus.CopyFrom(Linear(0d, 3d));
|
||||
}));
|
||||
yield return ("color-broadband-high-defocus-animated", Create(effect =>
|
||||
{
|
||||
effect.ColorMode = WaveOpticsColorMode.Broadband;
|
||||
effect.Quality = WaveOpticsQuality.High;
|
||||
effect.KernelRadius = 40;
|
||||
effect.Defocus.CopyFrom(Linear(0d, 3d));
|
||||
}));
|
||||
}
|
||||
|
||||
static Animation Linear(double from, double to)
|
||||
|
||||
+137
-53
@@ -236,9 +236,9 @@ static int Convolution(HarnessImage image)
|
||||
WaveOpticsPipeline.Parameters Radius(int radius) => parameters with { Psf = parameters.Psf with { KernelRadius = radius, Defocus = 2f, ComaHorizontal = 1f } };
|
||||
|
||||
var subjects = new List<IDisposable>();
|
||||
GpuSubject Gpu()
|
||||
GpuSubject Gpu(bool check = false)
|
||||
{
|
||||
var subject = new GpuSubject(WaveOpticsPipeline.TryCreate(device) ?? throw new HarnessException("Direct3D 12を利用できません。"), output, image.Width, image.Height);
|
||||
var subject = new GpuSubject(WaveOpticsPipeline.TryCreate(device) ?? throw new HarnessException("Direct3D 12を利用できません。"), output, image.Width, image.Height, check);
|
||||
subjects.Add(subject);
|
||||
return subject;
|
||||
}
|
||||
@@ -249,11 +249,66 @@ static int Convolution(HarnessImage image)
|
||||
return subject;
|
||||
}
|
||||
|
||||
try
|
||||
void MeasureSet(string title, Func<(string Name, Action<bool> Run)[]> createOwnedSubjects)
|
||||
{
|
||||
try
|
||||
{
|
||||
var variants = createOwnedSubjects();
|
||||
var samples = new List<double>[variants.Length];
|
||||
for (var index = 0; index < samples.Length; index++)
|
||||
samples[index] = new List<double>(Rounds);
|
||||
|
||||
foreach (var (_, run) in variants)
|
||||
{
|
||||
run(true);
|
||||
run(false);
|
||||
}
|
||||
|
||||
var stopwatch = new Stopwatch();
|
||||
var order = Enumerable.Range(0, variants.Length).ToArray();
|
||||
var random = new Random(Seed);
|
||||
for (var round = 0; round < Rounds; round++)
|
||||
{
|
||||
for (var index = order.Length - 1; index > 0; index--)
|
||||
{
|
||||
var swap = random.Next(index + 1);
|
||||
(order[index], order[swap]) = (order[swap], order[index]);
|
||||
}
|
||||
|
||||
foreach (var index in order)
|
||||
{
|
||||
var flip = round % 2 == 0;
|
||||
stopwatch.Restart();
|
||||
variants[index].Run(flip);
|
||||
stopwatch.Stop();
|
||||
samples[index].Add(stopwatch.Elapsed.TotalMilliseconds);
|
||||
}
|
||||
}
|
||||
|
||||
Console.WriteLine($"{title}");
|
||||
for (var index = 0; index < variants.Length; index++)
|
||||
{
|
||||
var sorted = samples[index].OrderBy(static value => value).ToArray();
|
||||
var median = sorted[sorted.Length / 2];
|
||||
Console.WriteLine($" {variants[index].Name,-20} min={sorted[0],7:F2} median={median,7:F2} max={sorted[^1],7:F2}");
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var subject in subjects)
|
||||
subject.Dispose();
|
||||
subjects.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
Console.WriteLine($"convolution recompute at {image.Width}x{image.Height} over {Rounds} interleaved rounds (ms)");
|
||||
|
||||
MeasureSet("default options", () =>
|
||||
{
|
||||
var cached = Gpu();
|
||||
var gain = Gpu();
|
||||
var source = Gpu();
|
||||
var checkedSource = Gpu(true);
|
||||
var defocus = Gpu();
|
||||
var qualityHigh = Gpu();
|
||||
var source31 = Gpu();
|
||||
@@ -261,11 +316,12 @@ static int Convolution(HarnessImage image)
|
||||
var cpuSource = Cpu();
|
||||
var cpuGain = Cpu();
|
||||
var cpuSource63 = Cpu();
|
||||
var variants = new (string Name, Action<bool> Run)[]
|
||||
{
|
||||
return
|
||||
[
|
||||
("cached", _ => cached.Frame(original, parameters)),
|
||||
("gain", flip => gain.Frame(original, parameters with { Gain = flip ? 1.5f : 1f })),
|
||||
("source", flip => source.Frame(flip ? mirrored : original, parameters)),
|
||||
("source-checked", flip => checkedSource.Frame(flip ? mirrored : original, parameters)),
|
||||
("defocus", flip => defocus.Frame(original, parameters with { Psf = parameters.Psf with { Defocus = flip ? 0.1f : 0f } })),
|
||||
("quality-high", flip => qualityHigh.Frame(original, parameters with { Psf = parameters.Psf with { Quality = flip ? WaveOpticsQuality.High : WaveOpticsQuality.Standard } })),
|
||||
("source-r31", flip => source31.Frame(flip ? mirrored : original, Radius(31))),
|
||||
@@ -273,54 +329,81 @@ static int Convolution(HarnessImage image)
|
||||
("cpu-source", flip => cpuSource.Frame(flip ? mirroredBytes : originalBytes, parameters)),
|
||||
("cpu-gain", flip => cpuGain.Frame(originalBytes, parameters with { Gain = flip ? 1.5f : 1f })),
|
||||
("cpu-source-r63", flip => cpuSource63.Frame(flip ? mirroredBytes : originalBytes, Radius(63))),
|
||||
};
|
||||
];
|
||||
});
|
||||
|
||||
var samples = new List<double>[variants.Length];
|
||||
for (var index = 0; index < samples.Length; index++)
|
||||
samples[index] = new List<double>(Rounds);
|
||||
|
||||
foreach (var (_, run) in variants)
|
||||
{
|
||||
run(true);
|
||||
run(false);
|
||||
}
|
||||
|
||||
var stopwatch = new Stopwatch();
|
||||
var order = Enumerable.Range(0, variants.Length).ToArray();
|
||||
var random = new Random(Seed);
|
||||
for (var round = 0; round < Rounds; round++)
|
||||
{
|
||||
for (var index = order.Length - 1; index > 0; index--)
|
||||
{
|
||||
var swap = random.Next(index + 1);
|
||||
(order[index], order[swap]) = (order[swap], order[index]);
|
||||
}
|
||||
|
||||
foreach (var index in order)
|
||||
{
|
||||
var flip = round % 2 == 0;
|
||||
stopwatch.Restart();
|
||||
variants[index].Run(flip);
|
||||
stopwatch.Stop();
|
||||
samples[index].Add(stopwatch.Elapsed.TotalMilliseconds);
|
||||
}
|
||||
}
|
||||
|
||||
Console.WriteLine($"convolution recompute at {image.Width}x{image.Height} over {Rounds} interleaved rounds (ms)");
|
||||
for (var index = 0; index < variants.Length; index++)
|
||||
{
|
||||
var sorted = samples[index].OrderBy(static value => value).ToArray();
|
||||
var median = sorted[sorted.Length / 2];
|
||||
Console.WriteLine($" {variants[index].Name,-14} min={sorted[0],7:F2} median={median,7:F2} max={sorted[^1],7:F2}");
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
finally
|
||||
var linearLight = new SpectralConvolution.LightOptions(true, false, 0f, 0f);
|
||||
var highlightLight = new SpectralConvolution.LightOptions(true, false, 0.7f, 30f);
|
||||
MeasureSet("light options", () =>
|
||||
{
|
||||
foreach (var subject in subjects)
|
||||
subject.Dispose();
|
||||
}
|
||||
var source = Gpu();
|
||||
var checkedSource = Gpu(true);
|
||||
var linear = Gpu();
|
||||
var checkedLinear = Gpu(true);
|
||||
var linearHighlight = Gpu();
|
||||
var cpuSource = Cpu();
|
||||
var cpuLinear = Cpu();
|
||||
var cpuLinearHighlight = Cpu();
|
||||
return
|
||||
[
|
||||
("source", flip => source.Frame(flip ? mirrored : original, parameters)),
|
||||
("source-checked", flip => checkedSource.Frame(flip ? mirrored : original, parameters)),
|
||||
("linear", flip => linear.Frame(flip ? mirrored : original, parameters with { Light = linearLight })),
|
||||
("linear-checked", flip => checkedLinear.Frame(flip ? mirrored : original, parameters with { Light = linearLight })),
|
||||
("linear-highlight", flip => linearHighlight.Frame(flip ? mirrored : original, parameters with { Light = highlightLight })),
|
||||
("cpu-source", flip => cpuSource.Frame(flip ? mirroredBytes : originalBytes, parameters)),
|
||||
("cpu-linear", flip => cpuLinear.Frame(flip ? mirroredBytes : originalBytes, parameters with { Light = linearLight })),
|
||||
("cpu-linear-highlight", flip => cpuLinearHighlight.Frame(flip ? mirroredBytes : originalBytes, parameters with { Light = highlightLight })),
|
||||
];
|
||||
});
|
||||
|
||||
WaveOpticsPipeline.Parameters Colored(WaveOpticsColorMode mode, int radius = 15, WaveOpticsQuality quality = WaveOpticsQuality.Standard, float defocus = 1f)
|
||||
=> parameters with { Psf = parameters.Psf with { ColorMode = mode, KernelRadius = radius, Quality = quality, Defocus = defocus } };
|
||||
WaveOpticsPipeline.Parameters Retuned(WaveOpticsPipeline.Parameters source, bool flip)
|
||||
=> source with { Psf = source.Psf with { Defocus = source.Psf.Defocus + (flip ? 0.1f : 0f) } };
|
||||
var modes = new[] { WaveOpticsColorMode.Monochrome, WaveOpticsColorMode.Primaries, WaveOpticsColorMode.Broadband };
|
||||
var settings = new[] { (Name: "r15", Radius: 15, Quality: WaveOpticsQuality.Standard), (Name: "r40-high", Radius: 40, Quality: WaveOpticsQuality.High) };
|
||||
string Label(WaveOpticsColorMode mode) => mode switch { WaveOpticsColorMode.Primaries => "primaries", WaveOpticsColorMode.Broadband => "broadband", _ => "mono" };
|
||||
MeasureSet("color modes, source changes", () =>
|
||||
{
|
||||
var variants = new List<(string Name, Action<bool> Run)>();
|
||||
foreach (var (name, radius, quality) in settings)
|
||||
{
|
||||
foreach (var mode in modes)
|
||||
{
|
||||
var colored = Colored(mode, radius, quality);
|
||||
var gpu = Gpu();
|
||||
var cpu = Cpu();
|
||||
variants.Add(($"{Label(mode)}-{name}", flip => gpu.Frame(flip ? mirrored : original, colored)));
|
||||
variants.Add(($"cpu-{Label(mode)}-{name}", flip => cpu.Frame(flip ? mirroredBytes : originalBytes, colored)));
|
||||
}
|
||||
}
|
||||
|
||||
var checkedGpu = Gpu(true);
|
||||
var primaries = Colored(WaveOpticsColorMode.Primaries);
|
||||
variants.Add(("primaries-r15-checked", flip => checkedGpu.Frame(flip ? mirrored : original, primaries)));
|
||||
return [.. variants];
|
||||
});
|
||||
|
||||
MeasureSet("color modes, optics change", () =>
|
||||
{
|
||||
var variants = new List<(string Name, Action<bool> Run)>();
|
||||
foreach (var (name, radius, quality) in settings)
|
||||
{
|
||||
foreach (var mode in modes)
|
||||
{
|
||||
var colored = Colored(mode, radius, quality);
|
||||
var gpu = Gpu();
|
||||
var cpu = Cpu();
|
||||
variants.Add(($"{Label(mode)}-{name}", flip => gpu.Frame(original, Retuned(colored, flip))));
|
||||
variants.Add(($"cpu-{Label(mode)}-{name}", flip => cpu.Frame(originalBytes, Retuned(colored, flip))));
|
||||
}
|
||||
}
|
||||
|
||||
return [.. variants];
|
||||
});
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static Bgra32[] ToPixels(HarnessImage image, bool mirror)
|
||||
@@ -461,8 +544,9 @@ static int CountOpaque(byte[] pixels)
|
||||
return count;
|
||||
}
|
||||
|
||||
sealed class GpuSubject(WaveOpticsPipeline pipeline, ReadWriteTexture2D<Bgra32, Float4> output, int width, int height) : IDisposable
|
||||
sealed class GpuSubject(WaveOpticsPipeline pipeline, ReadWriteTexture2D<Bgra32, Float4> output, int width, int height, bool check) : IDisposable
|
||||
{
|
||||
readonly SpectralConvolution.ConvolutionMeasurement[] measurements = check ? new SpectralConvolution.ConvolutionMeasurement[WaveOpticsPipeline.MeasurementCount] : [];
|
||||
float renderedGain = float.NaN;
|
||||
|
||||
public void Frame(ReadWriteTexture2D<Bgra32, Float4> source, in WaveOpticsPipeline.Parameters parameters)
|
||||
@@ -470,7 +554,7 @@ sealed class GpuSubject(WaveOpticsPipeline pipeline, ReadWriteTexture2D<Bgra32,
|
||||
var changed = pipeline.Simulate(source, width, height, 0, 0, width, height, in parameters);
|
||||
if ((changed || renderedGain != parameters.Gain) && pipeline.TryGetVisibleBounds(width, height, in parameters, out var rect))
|
||||
{
|
||||
pipeline.RenderVisible(source, output, rect, in parameters);
|
||||
pipeline.RenderVisible(source, output, rect, in parameters, measurements);
|
||||
renderedGain = parameters.Gain;
|
||||
}
|
||||
pipeline.WaitForCompletion();
|
||||
|
||||
@@ -236,6 +236,120 @@
|
||||
8
|
||||
],
|
||||
"hash": "EA104F2B819F36C8D21E9098D98EC52899812D88905EA708CC1FD5594F9E04FC"
|
||||
},
|
||||
{
|
||||
"name": "linear",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "3EED06FE0B0B59C46C20E7328748B3252A83C416A667530987DFDAFAD3812C99"
|
||||
},
|
||||
{
|
||||
"name": "linear-gain-150",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "54954AC3C99C0E5A3399EAA19660E68AB3CB94A453CEB649238A7BBEC88B97B8"
|
||||
},
|
||||
{
|
||||
"name": "linear-highlight-boost-30",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "1989982E87CF8A3446FD889A893466C6FD5419E66F3EE4498959A3E5F9539AC7"
|
||||
},
|
||||
{
|
||||
"name": "linear-highlight-threshold-50-boost-8",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "FF7DD316FBB2745168837D079820FD392115A774385FFE8B99144C5AC9080901"
|
||||
},
|
||||
{
|
||||
"name": "dither",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "A4E7E124F0D854BEC41C70597C27434E2F92228543008429736B209F419EEE50"
|
||||
},
|
||||
{
|
||||
"name": "linear-dither-defocus-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "FFB41C48B77A347074828F587F22793595BD366574941519FDE46AB65AEBBA6C"
|
||||
},
|
||||
{
|
||||
"name": "linear-highlight-polygon-defocus-2-radius-40",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "33CE14E973508DD57A569BC2AB7BF0DAD9952A9A0182D3EFACD9C5CADD379E3D"
|
||||
},
|
||||
{
|
||||
"name": "linear-highlight-animated-frames-0-8",
|
||||
"frames": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6,
|
||||
7,
|
||||
8
|
||||
],
|
||||
"hash": "0DDC7963278242EB3888A81D542BBCD02D8552E2A2C71C560F5D62DAAE2B080E"
|
||||
},
|
||||
{
|
||||
"name": "color-primaries-defocus-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "FE83215DE0F27B7B8336453A04146E65FDF0596A25B90B2D5618E693FC6CE874"
|
||||
},
|
||||
{
|
||||
"name": "color-broadband-defocus-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "0D9B2E26C6730F01213251D5AF130A37A3573880B7D87E277EE1CAB41F3CBE04"
|
||||
},
|
||||
{
|
||||
"name": "color-primaries-polygon-radius-40-clear",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "48D33FFEC9C5E08FDDDDD3A64C689F51C1F57260637FC7BD4609A21C8C93A51D"
|
||||
},
|
||||
{
|
||||
"name": "color-broadband-high-coma-radius-63",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "BD42E3AA56E65EDD1562ED065B6814171EE660AFB5005E5E666AC780AA6A9E8B"
|
||||
},
|
||||
{
|
||||
"name": "color-primaries-linear-highlight-defocus-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "5F39ECE9802DEA9EE8FEAF3FF3E4EC3E58A4D2DE70840E6F27543CE3C70C3B42"
|
||||
},
|
||||
{
|
||||
"name": "color-broadband-defocus-animated-frames-0-8",
|
||||
"frames": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6,
|
||||
7,
|
||||
8
|
||||
],
|
||||
"hash": "33CABC6CC0C520431DDB09769BA4AA7AF03A36708AF0E61422C279E84260C1DC"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -236,6 +236,120 @@
|
||||
8
|
||||
],
|
||||
"hash": "B16C68AB33DE6B661BFF623AE9D3AE7264EF75CF3427AFF0FCA5E16E96BC998A"
|
||||
},
|
||||
{
|
||||
"name": "linear",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "E7A46523EADA5966E9655FFB991D6C600B747FE81EBAD746BA7EADD8AA1E1689"
|
||||
},
|
||||
{
|
||||
"name": "linear-gain-150",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "DFDD975BC7310F9D59900C3132D5E226360CE26DB836CA11AF2FAC838B247EFD"
|
||||
},
|
||||
{
|
||||
"name": "linear-highlight-boost-30",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "4F3DA5EF23F20E5621AAECA7BEA99B9484F203411F033A06BF8398A26F92E512"
|
||||
},
|
||||
{
|
||||
"name": "linear-highlight-threshold-50-boost-8",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "4324A1C29CD13435ABD4E65647A9A076E83CF66FBFE93F831C5CA0962FBAD468"
|
||||
},
|
||||
{
|
||||
"name": "dither",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "620506E95C258C25FDB2106809F2F376C61BE750A1AC26A4046198AE32CB9140"
|
||||
},
|
||||
{
|
||||
"name": "linear-dither-defocus-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "D311BDC0B33B1D1082108CDB8B4C0150C2878DAB55B3E8CE97C5F035F47026F7"
|
||||
},
|
||||
{
|
||||
"name": "linear-highlight-polygon-defocus-2-radius-40",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "1EF8C3B15AC95EB5469B32226052E1D4B7DDB808B2A94CD66DD951D2FC402921"
|
||||
},
|
||||
{
|
||||
"name": "linear-highlight-animated-frames-0-8",
|
||||
"frames": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6,
|
||||
7,
|
||||
8
|
||||
],
|
||||
"hash": "BF21AA5A0124E008B4BA51D538A225F90C9F94465BD5A238BF69B3E1F7513CE9"
|
||||
},
|
||||
{
|
||||
"name": "color-primaries-defocus-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "17AC710C1CE50AA5839566740501F2E2D327AFB15BF1ABF24590BCF18235F5C7"
|
||||
},
|
||||
{
|
||||
"name": "color-broadband-defocus-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "F4264140CC5F767A3266E968F9A59C0C7DF576A372DBA3EBFA7F5F44C0B5198C"
|
||||
},
|
||||
{
|
||||
"name": "color-primaries-polygon-radius-40-clear",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "D013980D5DF7232CAA650AE8AB5C0793F7F6EC36295A85DC4B65B9A21B6C7ADF"
|
||||
},
|
||||
{
|
||||
"name": "color-broadband-high-coma-radius-63",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "910E74CB21036F708B084950B228C7C45555EEB1DCB9B0A3ABBDB060D96D010B"
|
||||
},
|
||||
{
|
||||
"name": "color-primaries-linear-highlight-defocus-1",
|
||||
"frames": [
|
||||
0
|
||||
],
|
||||
"hash": "102037B8E9D7F257EE1DD8A2FAEDC0E47F59E8A75C82D5CEB32002ABD1B2AA4F"
|
||||
},
|
||||
{
|
||||
"name": "color-broadband-defocus-animated-frames-0-8",
|
||||
"frames": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6,
|
||||
7,
|
||||
8
|
||||
],
|
||||
"hash": "B465593F4DADE624A911F0F75CD1F5765F8AB45FB5A746D3AB3B3DA9232872F7"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
internal static class AllocationProbe
|
||||
{
|
||||
public static long MinimumAllocatedBytes(Action action, int rounds)
|
||||
{
|
||||
var minimum = long.MaxValue;
|
||||
for (var round = 0; round < rounds; round++)
|
||||
{
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
action();
|
||||
minimum = Math.Min(minimum, GC.GetAllocatedBytesForCurrentThread() - before);
|
||||
}
|
||||
|
||||
return minimum;
|
||||
}
|
||||
|
||||
public static void Settle()
|
||||
{
|
||||
GC.Collect();
|
||||
GC.WaitForPendingFinalizers();
|
||||
GC.Collect();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
using WaveOptics.Abstractions;
|
||||
using WaveOptics.Effects;
|
||||
using WaveOptics.Optics;
|
||||
|
||||
namespace WaveOptics.Tests.Psf;
|
||||
|
||||
public sealed class BroadbandAccuracyTests
|
||||
{
|
||||
const int DenseSamples = 61;
|
||||
|
||||
static PsfSpecification Specification(WavefrontAberration aberration)
|
||||
=> new(512, 128, 63 * 2 + 1, SpectralPlan.ReferenceWavelength, 8, 4, ApertureShape.Circular, 6, 0, 0, aberration);
|
||||
|
||||
static double[] DenseKernel(in PsfSpecification specification, double center)
|
||||
{
|
||||
var sampler = new FraunhoferKernelSampler();
|
||||
var area = specification.KernelSize * specification.KernelSize;
|
||||
var kernel = new double[area];
|
||||
var values = new double[area];
|
||||
var weights = new double[DenseSamples];
|
||||
var sum = 0d;
|
||||
for (var index = 0; index < DenseSamples; index++)
|
||||
{
|
||||
var offset = -SpectralPlan.BandSpan + 2d * SpectralPlan.BandSpan * index / (DenseSamples - 1);
|
||||
weights[index] = Math.Exp(-0.5 * offset * offset);
|
||||
sum += weights[index];
|
||||
}
|
||||
|
||||
for (var index = 0; index < DenseSamples; index++)
|
||||
{
|
||||
var offset = -SpectralPlan.BandSpan + 2d * SpectralPlan.BandSpan * index / (DenseSamples - 1);
|
||||
var wavelength = center + SpectralPlan.BandSigma * offset;
|
||||
var phaseScale = SpectralPlan.ReferenceWavelength / wavelength;
|
||||
Assert.True(sampler.TryComputeIntensity(in specification, specification.PupilDiameterSamples * phaseScale, phaseScale, [1d]));
|
||||
Assert.True(sampler.TrySampleKernel(in specification, 1d, values));
|
||||
for (var element = 0; element < area; element++)
|
||||
kernel[element] += weights[index] / sum * values[element];
|
||||
}
|
||||
|
||||
return kernel;
|
||||
}
|
||||
|
||||
static double Distance(ReadOnlySpan<double> left, ReadOnlySpan<double> right)
|
||||
{
|
||||
var sum = 0d;
|
||||
for (var index = 0; index < left.Length; index++)
|
||||
sum += Math.Abs(left[index] - right[index]);
|
||||
return sum;
|
||||
}
|
||||
|
||||
public static TheoryData<string> Names => ["defocus", "coma", "spherical"];
|
||||
|
||||
static WavefrontAberration Aberration(string name)
|
||||
=> name switch
|
||||
{
|
||||
"defocus" => new WavefrontAberration(defocusWaves: 3),
|
||||
"coma" => new WavefrontAberration(comaHorizontalWaves: 1),
|
||||
_ => new WavefrontAberration(sphericalWaves: -1, defocusWaves: 0.5),
|
||||
};
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Names))]
|
||||
public void TheQualityTiersApproachTheDenseBroadbandKernelInTheirOwnOrder(string name)
|
||||
{
|
||||
var specification = Specification(Aberration(name));
|
||||
var area = specification.KernelSize * specification.KernelSize;
|
||||
var sampler = new ChromaticKernelSampler();
|
||||
double[] distances = new double[3];
|
||||
foreach (var quality in Enum.GetValues<WaveOpticsQuality>())
|
||||
{
|
||||
var red = new double[area];
|
||||
var green = new double[area];
|
||||
var blue = new double[area];
|
||||
Assert.True(sampler.TrySample(in specification, WaveOpticsColorMode.Broadband, quality, red, green, blue));
|
||||
distances[(int)quality] = Math.Max(Distance(green, DenseKernel(in specification, SpectralPlan.GreenWavelength)), Distance(blue, DenseKernel(in specification, SpectralPlan.BlueWavelength)));
|
||||
}
|
||||
|
||||
Assert.True(distances[0] > distances[1], $"{name}: {string.Join(" ", distances)}");
|
||||
Assert.True(distances[1] > distances[2], $"{name}: {string.Join(" ", distances)}");
|
||||
Assert.InRange(distances[0], 0.06, 0.1);
|
||||
Assert.InRange(distances[1], 0.025, 0.07);
|
||||
Assert.InRange(distances[2], 0.01, 0.03);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
using WaveOptics.Abstractions;
|
||||
using WaveOptics.Effects;
|
||||
using WaveOptics.Optics;
|
||||
|
||||
namespace WaveOptics.Tests.Psf;
|
||||
|
||||
public sealed class ChromaticKernelSamplerTests
|
||||
{
|
||||
readonly FraunhoferKernelSampler single = new();
|
||||
readonly ChromaticKernelSampler sampler = new();
|
||||
|
||||
static PsfSpecification Specification(
|
||||
int gridSize = 256,
|
||||
int kernelRadius = 15,
|
||||
double fNumber = 8,
|
||||
double pixelPitch = 4,
|
||||
ApertureShape shape = ApertureShape.Circular,
|
||||
int blades = 6,
|
||||
double obstruction = 0,
|
||||
WavefrontAberration aberration = default,
|
||||
double wavelength = SpectralPlan.ReferenceWavelength)
|
||||
=> new(gridSize, gridSize / 4, kernelRadius * 2 + 1, wavelength, fNumber, pixelPitch, shape, blades, 0, obstruction, aberration);
|
||||
|
||||
static double Radius(ReadOnlySpan<double> kernel, double fraction)
|
||||
{
|
||||
var size = (int)Math.Sqrt(kernel.Length);
|
||||
var center = size / 2;
|
||||
var pairs = new List<(double Distance, double Value)>();
|
||||
for (var index = 0; index < kernel.Length; index++)
|
||||
pairs.Add((Math.Sqrt(Math.Pow(index % size - center, 2) + Math.Pow(index / size - center, 2)), kernel[index]));
|
||||
pairs.Sort((left, right) => left.Distance.CompareTo(right.Distance));
|
||||
var total = 0d;
|
||||
foreach (var (distance, value) in pairs)
|
||||
{
|
||||
total += value;
|
||||
if (total >= fraction)
|
||||
return distance;
|
||||
}
|
||||
|
||||
return pairs[^1].Distance;
|
||||
}
|
||||
|
||||
static double Distance(ReadOnlySpan<double> left, ReadOnlySpan<double> right)
|
||||
{
|
||||
var sum = 0d;
|
||||
for (var index = 0; index < left.Length; index++)
|
||||
sum += Math.Abs(left[index] - right[index]);
|
||||
return sum;
|
||||
}
|
||||
|
||||
(double[] Red, double[] Green, double[] Blue) Sample(in PsfSpecification specification, WaveOpticsColorMode mode, WaveOpticsQuality quality)
|
||||
{
|
||||
var area = specification.KernelSize * specification.KernelSize;
|
||||
var red = new double[area];
|
||||
var green = new double[area];
|
||||
var blue = new double[area];
|
||||
Assert.True(sampler.TrySample(in specification, mode, quality, red, green, blue));
|
||||
return (red, green, blue);
|
||||
}
|
||||
|
||||
public static TheoryData<string> CaseNames => ["clear", "defocus", "coma", "polygon", "obstructed", "astigmatism"];
|
||||
|
||||
static PsfSpecification Case(string name)
|
||||
=> name switch
|
||||
{
|
||||
"clear" => Specification(),
|
||||
"defocus" => Specification(aberration: new WavefrontAberration(defocusWaves: 1.5)),
|
||||
"coma" => Specification(kernelRadius: 30, aberration: new WavefrontAberration(comaHorizontalWaves: 1.2, sphericalWaves: -0.4)),
|
||||
"polygon" => Specification(shape: ApertureShape.RegularPolygon, blades: 7, fNumber: 16, pixelPitch: 2),
|
||||
"obstructed" => Specification(gridSize: 512, obstruction: 0.5, aberration: new WavefrontAberration(defocusWaves: 2)),
|
||||
_ => Specification(aberration: new WavefrontAberration(astigmatismVerticalWaves: 0.8, astigmatismObliqueWaves: -0.6)),
|
||||
};
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(CaseNames))]
|
||||
public void TheGreenKernelOfThePrimariesIsTheMonochromeKernelAtTheReferenceWavelength(string name)
|
||||
{
|
||||
var specification = Case(name);
|
||||
var expected = new double[specification.KernelSize * specification.KernelSize];
|
||||
Assert.True(single.TrySample(in specification, expected));
|
||||
|
||||
var (_, green, _) = Sample(in specification, WaveOpticsColorMode.Primaries, WaveOpticsQuality.Standard);
|
||||
|
||||
Assert.Equal(expected, green);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(CaseNames))]
|
||||
public void EveryChannelOfEveryModeIsANormalizedNonNegativeKernel(string name)
|
||||
{
|
||||
var specification = Case(name);
|
||||
|
||||
foreach (var mode in new[] { WaveOpticsColorMode.Primaries, WaveOpticsColorMode.Broadband })
|
||||
{
|
||||
foreach (var quality in Enum.GetValues<WaveOpticsQuality>())
|
||||
{
|
||||
var (red, green, blue) = Sample(in specification, mode, quality);
|
||||
|
||||
foreach (var kernel in new[] { red, green, blue })
|
||||
{
|
||||
Assert.Equal(1d, kernel.Sum(), 9);
|
||||
Assert.All(kernel, value => Assert.True(value >= 0d && double.IsFinite(value)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AGeometricBlurHasTheSameSizeInEveryChannelWhereAFixedNumberOfWavesDoesNot()
|
||||
{
|
||||
var aberration = new WavefrontAberration(defocusWaves: 3);
|
||||
var specification = Specification(gridSize: 512, kernelRadius: 63, aberration: aberration);
|
||||
|
||||
var (red, green, blue) = Sample(in specification, WaveOpticsColorMode.Primaries, WaveOpticsQuality.High);
|
||||
|
||||
var chromaticRatio = Radius(red, 0.9) / Radius(blue, 0.9);
|
||||
Assert.InRange(chromaticRatio, 0.94, 1.06);
|
||||
Assert.InRange(Radius(green, 0.9) / Radius(blue, 0.9), 0.94, 1.06);
|
||||
var redWaves = new double[red.Length];
|
||||
var blueWaves = new double[red.Length];
|
||||
var redSpecification = Specification(gridSize: 512, kernelRadius: 63, aberration: aberration, wavelength: SpectralPlan.RedWavelength);
|
||||
var blueSpecification = Specification(gridSize: 512, kernelRadius: 63, aberration: aberration, wavelength: SpectralPlan.BlueWavelength);
|
||||
Assert.True(single.TrySample(in redSpecification, redWaves));
|
||||
Assert.True(single.TrySample(in blueSpecification, blueWaves));
|
||||
Assert.True(Radius(redWaves, 0.9) / Radius(blueWaves, 0.9) > 1.2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithoutAberrationTheDiffractionPatternGrowsWithTheWavelength()
|
||||
{
|
||||
var specification = Specification(kernelRadius: 40, fNumber: 16, pixelPitch: 2);
|
||||
|
||||
var (red, green, blue) = Sample(in specification, WaveOpticsColorMode.Primaries, WaveOpticsQuality.Standard);
|
||||
|
||||
var redPeak = red.Max();
|
||||
var greenPeak = green.Max();
|
||||
var bluePeak = blue.Max();
|
||||
Assert.True(redPeak < greenPeak && greenPeak < bluePeak, $"{redPeak} {greenPeak} {bluePeak}");
|
||||
var expected = Math.Pow(SpectralPlan.BlueWavelength / SpectralPlan.RedWavelength, 2);
|
||||
Assert.InRange(redPeak / bluePeak, expected * 0.85, expected * 1.15);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(WaveOpticsColorMode.Primaries, 1e-6)]
|
||||
[InlineData(WaveOpticsColorMode.Broadband, 0.05)]
|
||||
public void AVanishingAberrationGivesTheKernelOfNoAberration(WaveOpticsColorMode mode, double tolerance)
|
||||
{
|
||||
var clear = Specification(kernelRadius: 30);
|
||||
var nearlyClear = Specification(kernelRadius: 30, aberration: new WavefrontAberration(defocusWaves: 1e-9));
|
||||
|
||||
var (clearRed, clearGreen, clearBlue) = Sample(in clear, mode, WaveOpticsQuality.Standard);
|
||||
var (nearRed, nearGreen, nearBlue) = Sample(in nearlyClear, mode, WaveOpticsQuality.High);
|
||||
|
||||
Assert.True(Distance(clearRed, nearRed) < tolerance, $"{Distance(clearRed, nearRed)}");
|
||||
Assert.True(Distance(clearGreen, nearGreen) < tolerance, $"{Distance(clearGreen, nearGreen)}");
|
||||
Assert.True(Distance(clearBlue, nearBlue) < tolerance, $"{Distance(clearBlue, nearBlue)}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithoutAberrationTheQualityOnlyChangesTheGridNotTheWavelengthSampling()
|
||||
{
|
||||
var specification = Specification(kernelRadius: 30);
|
||||
|
||||
var draft = Sample(in specification, WaveOpticsColorMode.Broadband, WaveOpticsQuality.Draft);
|
||||
var high = Sample(in specification, WaveOpticsColorMode.Broadband, WaveOpticsQuality.High);
|
||||
|
||||
Assert.Equal(draft.Red, high.Red);
|
||||
Assert.Equal(draft.Green, high.Green);
|
||||
Assert.Equal(draft.Blue, high.Blue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ABroadbandKernelIsASmoothedVersionOfThePrimaryKernel()
|
||||
{
|
||||
var specification = Specification(kernelRadius: 30, fNumber: 16, pixelPitch: 2);
|
||||
|
||||
var (_, primary, _) = Sample(in specification, WaveOpticsColorMode.Primaries, WaveOpticsQuality.Standard);
|
||||
var (_, broadband, _) = Sample(in specification, WaveOpticsColorMode.Broadband, WaveOpticsQuality.Standard);
|
||||
|
||||
Assert.InRange(Distance(primary, broadband), 0.005, 0.8);
|
||||
Assert.Equal(primary.Sum(), broadband.Sum(), 9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ALowerQualityApproachesTheHighestQualityOnlyAsCloselyAsItsNodesAllow()
|
||||
{
|
||||
var specification = Specification(gridSize: 256, kernelRadius: 30, aberration: new WavefrontAberration(comaHorizontalWaves: 1d, defocusWaves: 1d));
|
||||
|
||||
var draft = Sample(in specification, WaveOpticsColorMode.Broadband, WaveOpticsQuality.Draft);
|
||||
var standard = Sample(in specification, WaveOpticsColorMode.Broadband, WaveOpticsQuality.Standard);
|
||||
var high = Sample(in specification, WaveOpticsColorMode.Broadband, WaveOpticsQuality.High);
|
||||
|
||||
var draftDistance = Distance(draft.Blue, high.Blue) + Distance(draft.Green, high.Green) + Distance(draft.Red, high.Red);
|
||||
var standardDistance = Distance(standard.Blue, high.Blue) + Distance(standard.Green, high.Green) + Distance(standard.Red, high.Red);
|
||||
Assert.True(standardDistance < draftDistance, $"{standardDistance} {draftDistance}");
|
||||
Assert.True(draftDistance < 0.45, $"{draftDistance}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheChannelsOfAnAberratedLensDifferWhileTheirSumsStayEqual()
|
||||
{
|
||||
var specification = Case("coma");
|
||||
|
||||
var (red, green, blue) = Sample(in specification, WaveOpticsColorMode.Primaries, WaveOpticsQuality.Standard);
|
||||
|
||||
Assert.True(Distance(red, green) > 0.01);
|
||||
Assert.True(Distance(blue, green) > 0.01);
|
||||
Assert.Equal(red.Sum(), blue.Sum(), 9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ARequestForTheMonochromeModeIsRejected()
|
||||
{
|
||||
var specification = Specification();
|
||||
var area = specification.KernelSize * specification.KernelSize;
|
||||
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => sampler.TrySample(in specification, WaveOpticsColorMode.Monochrome, WaveOpticsQuality.Standard, new double[area], new double[area], new double[area]));
|
||||
Assert.Throws<ArgumentException>(() => sampler.TrySample(in specification, WaveOpticsColorMode.Primaries, WaveOpticsQuality.Standard, new double[area], new double[area - 1], new double[area]));
|
||||
Assert.Throws<ArgumentException>(() => sampler.TrySample(in specification, WaveOpticsColorMode.Primaries, WaveOpticsQuality.Standard, new double[area], new double[area], new double[area + 1]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AClosedApertureFailsWithoutThrowing()
|
||||
{
|
||||
var specification = Specification(gridSize: 64, shape: ApertureShape.RegularPolygon, blades: 4, obstruction: 0.95, kernelRadius: 3);
|
||||
var area = specification.KernelSize * specification.KernelSize;
|
||||
|
||||
var sampled = sampler.TrySample(in specification, WaveOpticsColorMode.Broadband, WaveOpticsQuality.Draft, new double[area], new double[area], new double[area]);
|
||||
|
||||
Assert.False(sampled);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(WaveOpticsColorMode.Primaries, "clear")]
|
||||
[InlineData(WaveOpticsColorMode.Broadband, "clear")]
|
||||
[InlineData(WaveOpticsColorMode.Primaries, "coma")]
|
||||
[InlineData(WaveOpticsColorMode.Broadband, "coma")]
|
||||
public void AWarmSamplerAllocatesNoManagedMemory(WaveOpticsColorMode mode, string name)
|
||||
{
|
||||
var specification = Case(name);
|
||||
var area = specification.KernelSize * specification.KernelSize;
|
||||
var red = new double[area];
|
||||
var green = new double[area];
|
||||
var blue = new double[area];
|
||||
void Sample() => Assert.True(sampler.TrySample(in specification, mode, WaveOpticsQuality.High, red, green, blue));
|
||||
|
||||
Sample();
|
||||
Sample();
|
||||
AllocationProbe.Settle();
|
||||
|
||||
Assert.Equal(0, AllocationProbe.MinimumAllocatedBytes(Sample, 8));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(WaveOpticsColorMode.Primaries)]
|
||||
[InlineData(WaveOpticsColorMode.Broadband)]
|
||||
public void TheOutputBuffersNeedNotBeEmpty(WaveOpticsColorMode mode)
|
||||
{
|
||||
var specification = Case("defocus");
|
||||
var area = specification.KernelSize * specification.KernelSize;
|
||||
var fresh = Sample(in specification, mode, WaveOpticsQuality.High);
|
||||
var red = new double[area];
|
||||
var green = new double[area];
|
||||
var blue = new double[area];
|
||||
Array.Fill(red, 3d);
|
||||
Array.Fill(green, 5d);
|
||||
Array.Fill(blue, 7d);
|
||||
|
||||
Assert.True(sampler.TrySample(in specification, mode, WaveOpticsQuality.High, red, green, blue));
|
||||
|
||||
Assert.Equal(fresh.Red, red);
|
||||
Assert.Equal(fresh.Green, green);
|
||||
Assert.Equal(fresh.Blue, blue);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0)]
|
||||
[InlineData(1)]
|
||||
[InlineData(2)]
|
||||
[InlineData(3)]
|
||||
[InlineData(4)]
|
||||
[InlineData(5)]
|
||||
[InlineData(6)]
|
||||
[InlineData(7)]
|
||||
public void EveryAberrationTermMakesTheBroadbandUseTheNodesOfTheQuality(int term)
|
||||
{
|
||||
var values = new double[8];
|
||||
values[term] = 0.8;
|
||||
var aberration = new WavefrontAberration(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]);
|
||||
var specification = Specification(aberration: aberration);
|
||||
|
||||
var draft = Sample(in specification, WaveOpticsColorMode.Broadband, WaveOpticsQuality.Draft);
|
||||
var standard = Sample(in specification, WaveOpticsColorMode.Broadband, WaveOpticsQuality.Standard);
|
||||
|
||||
Assert.NotEqual(draft.Green, standard.Green);
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,12 @@ internal static class EffectDescriptions
|
||||
|
||||
static readonly Size ScreenSize = new(1920, 1080);
|
||||
|
||||
public static EffectDescription At(int frame, int length)
|
||||
public static DrawDescription Draw(Vector3 position, Matrix4x4? camera = null)
|
||||
=> new(position, Vector2.Zero, Vector2.One, Vector3.Zero, camera ?? Matrix4x4.Identity, InterpolationMode.Linear, 1d, false, []);
|
||||
|
||||
public static EffectDescription At(int frame, int length) => At(frame, length, Draw(Vector3.Zero));
|
||||
|
||||
public static EffectDescription At(int frame, int length, DrawDescription draw)
|
||||
{
|
||||
var timeline = new TimelineSourceDescription(
|
||||
ScreenSize,
|
||||
@@ -22,7 +27,6 @@ internal static class EffectDescriptions
|
||||
Guid.Empty,
|
||||
[]);
|
||||
var item = new TimelineItemSourceDescription(timeline, frame, length, 0);
|
||||
var draw = new DrawDescription(Vector3.Zero, Vector2.Zero, Vector2.One, Vector3.Zero, Matrix4x4.Identity, InterpolationMode.Linear, 1d, false, []);
|
||||
return new EffectDescription(item, draw, 0, 1, 0, 1);
|
||||
}
|
||||
}
|
||||
@@ -82,6 +82,41 @@ public sealed class FraunhoferKernelSamplerTests
|
||||
Assert.Empty(mismatches);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(256, 15, 8d, 4d, 1d)]
|
||||
[InlineData(512, 40, 8d, 4d, 0.8d)]
|
||||
[InlineData(128, 40, 8d, 4d, 1.31d)]
|
||||
[InlineData(128, 63, 0.5d, 100d, 1d)]
|
||||
[InlineData(256, 3, 64d, 0.25d, 0.5d)]
|
||||
[InlineData(64, 40, 8d, 4d, 1d)]
|
||||
public void TheTransposedSamplingIsTheRowMajorSampling(int gridSize, int radius, double fNumber, double pixelPitch, double positionScale)
|
||||
{
|
||||
var specification = PsfSpecification.Of(Descriptor(gridSize: gridSize, diameter: gridSize / 4, kernelRadius: radius, fNumber: fNumber, pixelPitch: pixelPitch));
|
||||
var random = new Random(7);
|
||||
var rowMajor = new double[gridSize * gridSize];
|
||||
var transposed = new double[gridSize * gridSize];
|
||||
for (var row = 0; row < gridSize; row++)
|
||||
{
|
||||
for (var column = 0; column < gridSize; column++)
|
||||
{
|
||||
var value = random.NextDouble() * random.NextDouble();
|
||||
rowMajor[row * gridSize + column] = value;
|
||||
transposed[column * gridSize + row] = value;
|
||||
}
|
||||
}
|
||||
|
||||
var size = specification.KernelSize;
|
||||
var expected = new double[size * size];
|
||||
var actual = new double[size * size];
|
||||
actual.AsSpan().Fill(double.NaN);
|
||||
|
||||
var expectedEnergy = FraunhoferPsfGenerator.SampleKernel(in specification, rowMajor, expected, positionScale);
|
||||
var actualEnergy = FraunhoferPsfGenerator.SampleKernelTransposed(in specification, transposed, actual, positionScale);
|
||||
|
||||
Assert.Equal(BitConverter.DoubleToInt64Bits(expectedEnergy), BitConverter.DoubleToInt64Bits(actualEnergy));
|
||||
Assert.True(expected.AsSpan().SequenceEqual(actual));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AClosedApertureIsNotSampled()
|
||||
{
|
||||
@@ -94,15 +129,34 @@ public sealed class FraunhoferKernelSamplerTests
|
||||
public void AWarmSamplerAllocatesNoManagedMemory()
|
||||
{
|
||||
var specification = PsfSpecification.Of(Descriptor());
|
||||
sampler.TrySample(in specification, kernel.AsSpan(0, 31 * 31));
|
||||
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
for (var step = 0; step < 4; step++)
|
||||
void SampleEveryDefocusStep()
|
||||
{
|
||||
var animated = specification with { Aberration = new WavefrontAberration(defocusWaves: step * 0.25) };
|
||||
sampler.TrySample(in animated, kernel.AsSpan(0, 31 * 31));
|
||||
for (var step = 0; step < 4; step++)
|
||||
{
|
||||
var animated = specification with { Aberration = new WavefrontAberration(defocusWaves: step * 0.25) };
|
||||
sampler.TrySample(in animated, kernel.AsSpan(0, 31 * 31));
|
||||
}
|
||||
}
|
||||
|
||||
Assert.Equal(0, GC.GetAllocatedBytesForCurrentThread() - before);
|
||||
SampleEveryDefocusStep();
|
||||
SampleEveryDefocusStep();
|
||||
AllocationProbe.Settle();
|
||||
|
||||
Assert.Equal(0, AllocationProbe.MinimumAllocatedBytes(SampleEveryDefocusStep, 16));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASamplerHoldsOnlyTheRowsTheApertureReaches()
|
||||
{
|
||||
const int GridSize = 512;
|
||||
var specification = PsfSpecification.Of(Descriptor(gridSize: GridSize, diameter: 16));
|
||||
Assert.True(new FraunhoferKernelSampler().TrySample(in specification, kernel.AsSpan(0, 31 * 31)));
|
||||
var fresh = new FraunhoferKernelSampler();
|
||||
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
Assert.True(fresh.TrySample(in specification, kernel.AsSpan(0, 31 * 31)));
|
||||
var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
|
||||
|
||||
Assert.True(allocated < (long)GridSize * GridSize * sizeof(double) * 2, allocated.ToString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
using WaveOptics.Abstractions;
|
||||
using WaveOptics.Optics;
|
||||
|
||||
namespace WaveOptics.Tests.Psf;
|
||||
|
||||
public sealed class FraunhoferPupilTests
|
||||
{
|
||||
static PsfSpecification Specification(int gridSize, ApertureShape shape, int blades, double rotation, double obstruction, WavefrontAberration aberration)
|
||||
=> new(gridSize, gridSize / 4, 31, 550d, 8d, 4d, shape, blades, rotation, obstruction, aberration);
|
||||
|
||||
static int Reference(in PsfSpecification specification, double pupilDiameter, double phaseScale, double[] real, double[] imaginary, int firstRow, int lastRow)
|
||||
{
|
||||
var gridSize = specification.PupilGridSize;
|
||||
var center = gridSize / 2;
|
||||
var radius = pupilDiameter / 2d;
|
||||
var rotation = specification.BladeRotationDegrees * Math.PI / 180d;
|
||||
var count = 0;
|
||||
for (var y = firstRow; y <= lastRow; y++)
|
||||
{
|
||||
for (var x = 0; x < gridSize; x++)
|
||||
{
|
||||
var normalizedX = (x - center) / radius;
|
||||
var normalizedY = (y - center) / radius;
|
||||
var index = y * gridSize + x;
|
||||
if (FraunhoferPsfGenerator.IsInsideAperture(normalizedX, normalizedY, in specification, rotation))
|
||||
{
|
||||
var waves = ZernikeWavefront.Evaluate(normalizedX, normalizedY, specification.Aberration) * phaseScale;
|
||||
var angle = 2 * Math.PI * waves;
|
||||
real[index] = Math.Cos(angle);
|
||||
imaginary[index] = Math.Sin(angle);
|
||||
count++;
|
||||
}
|
||||
else
|
||||
{
|
||||
real[index] = 0;
|
||||
imaginary[index] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
static IEnumerable<(string Name, PsfSpecification Specification, double Diameter, double PhaseScale)> Cases()
|
||||
{
|
||||
var aberration = new WavefrontAberration(1.5, -0.8, 0.6, 2.2, -1.1, 0.7, -0.4, -0.9);
|
||||
var shapes = new[]
|
||||
{
|
||||
("circle", ApertureShape.Circular, 6, 0d, 0d),
|
||||
("obstructed", ApertureShape.Circular, 6, 0d, 0.4d),
|
||||
("triangle", ApertureShape.RegularPolygon, 3, 17d, 0d),
|
||||
("pentagon", ApertureShape.RegularPolygon, 5, -33d, 0.3d),
|
||||
("octagon", ApertureShape.RegularPolygon, 8, 22.5d, 0d),
|
||||
};
|
||||
foreach (var gridSize in new[] { 64, 128, 256, 512 })
|
||||
{
|
||||
var diameters = new[]
|
||||
{
|
||||
(gridSize / 4d, 1d),
|
||||
(gridSize / 4d * 550d / 610d, 610d / 550d),
|
||||
(gridSize / 4d * 550d / 465d, 465d / 550d),
|
||||
(gridSize / 4d + 0.5d, 1d),
|
||||
(gridSize / 2d - 1d, 1d),
|
||||
(gridSize / 4d * 1.0000000000000002d, 1d),
|
||||
(gridSize / 4d - 1e-13d, 1d),
|
||||
(Math.BitDecrement(gridSize / 4d), 1d),
|
||||
(Math.BitIncrement(gridSize / 4d), 1d),
|
||||
};
|
||||
foreach (var (shapeName, shape, blades, rotation, obstruction) in shapes)
|
||||
{
|
||||
foreach (var (diameter, phaseScale) in diameters)
|
||||
yield return ($"{shapeName} {gridSize} {diameter}", Specification(gridSize, shape, blades, rotation, obstruction, aberration), diameter, phaseScale);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ThePupilIsTheApertureAndWavefrontEvaluatedAtEverySampleOfTheRows()
|
||||
{
|
||||
var mismatches = new List<string>();
|
||||
foreach (var (name, specification, diameter, phaseScale) in Cases())
|
||||
{
|
||||
var gridSize = specification.PupilGridSize;
|
||||
var center = gridSize / 2;
|
||||
var reach = (int)(diameter / 2d);
|
||||
foreach (var (firstRow, lastRow) in new[] { (Math.Max(center - reach, 0), Math.Min(center + reach, gridSize - 1)), (0, gridSize - 1) })
|
||||
{
|
||||
var expectedReal = new double[gridSize * gridSize];
|
||||
var expectedImaginary = new double[gridSize * gridSize];
|
||||
var actualReal = new double[gridSize * gridSize];
|
||||
var actualImaginary = new double[gridSize * gridSize];
|
||||
expectedReal.AsSpan().Fill(double.NaN);
|
||||
expectedImaginary.AsSpan().Fill(double.NaN);
|
||||
actualReal.AsSpan().Fill(double.NaN);
|
||||
actualImaginary.AsSpan().Fill(double.NaN);
|
||||
|
||||
var expectedCount = Reference(in specification, diameter, phaseScale, expectedReal, expectedImaginary, firstRow, lastRow);
|
||||
var actualCount = FraunhoferPsfGenerator.BuildPupil(in specification, diameter, phaseScale, actualReal, actualImaginary, firstRow, lastRow);
|
||||
|
||||
if (expectedCount != actualCount || !expectedReal.AsSpan().SequenceEqual(actualReal) || !expectedImaginary.AsSpan().SequenceEqual(actualImaginary))
|
||||
mismatches.Add($"{name} rows {firstRow}-{lastRow}");
|
||||
}
|
||||
}
|
||||
|
||||
Assert.Empty(mismatches);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RowsOutsideTheRequestedRangeAreNotTouched()
|
||||
{
|
||||
var specification = Specification(128, ApertureShape.Circular, 6, 0d, 0d, new WavefrontAberration(1d, 0d, 0d, 0d, 0d, 0d));
|
||||
var real = new double[128 * 128];
|
||||
var imaginary = new double[128 * 128];
|
||||
real.AsSpan().Fill(7d);
|
||||
imaginary.AsSpan().Fill(7d);
|
||||
|
||||
FraunhoferPsfGenerator.BuildPupil(in specification, 32d, 1d, real, imaginary, 48, 80);
|
||||
|
||||
Assert.All(real.AsSpan(0, 48 * 128).ToArray(), value => Assert.Equal(7d, value));
|
||||
Assert.All(real.AsSpan(81 * 128).ToArray(), value => Assert.Equal(7d, value));
|
||||
Assert.All(imaginary.AsSpan(0, 48 * 128).ToArray(), value => Assert.Equal(7d, value));
|
||||
Assert.All(imaginary.AsSpan(81 * 128).ToArray(), value => Assert.Equal(7d, value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASampleOnTheEdgeOfTheCircleIsOpen()
|
||||
{
|
||||
var specification = Specification(128, ApertureShape.Circular, 6, 0d, 0d, default);
|
||||
var real = new double[128 * 128];
|
||||
var imaginary = new double[128 * 128];
|
||||
|
||||
var count = FraunhoferPsfGenerator.BuildPupil(in specification, 32d, 1d, real, imaginary, 0, 127);
|
||||
|
||||
Assert.Equal(1d, real[64 * 128 + 64 + 16]);
|
||||
Assert.Equal(1d, real[64 * 128 + 64 - 16]);
|
||||
Assert.Equal(0d, real[64 * 128 + 64 + 17]);
|
||||
Assert.Equal(0d, real[64 * 128 + 64 - 17]);
|
||||
Assert.True(count > 700);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
using WaveOptics.Abstractions;
|
||||
using WaveOptics.Optics;
|
||||
|
||||
namespace WaveOptics.Tests.Psf;
|
||||
|
||||
public sealed class KernelSamplingTests
|
||||
{
|
||||
static double[] Grid(int size, int seed)
|
||||
{
|
||||
var random = new Random(seed);
|
||||
var values = new double[size * size];
|
||||
for (var index = 0; index < values.Length; index++)
|
||||
values[index] = random.NextDouble() * Math.Exp(-random.NextDouble() * 12);
|
||||
return values;
|
||||
}
|
||||
|
||||
static double Bilinear(double[] values, int size, double x, double y)
|
||||
{
|
||||
if (x < 0 || y < 0 || x > size - 1 || y > size - 1)
|
||||
return 0;
|
||||
|
||||
var x0 = (int)Math.Floor(x);
|
||||
var y0 = (int)Math.Floor(y);
|
||||
var x1 = Math.Min(x0 + 1, size - 1);
|
||||
var y1 = Math.Min(y0 + 1, size - 1);
|
||||
var tx = x - x0;
|
||||
var ty = y - y0;
|
||||
var top = values[y0 * size + x0] * (1 - tx) + values[y0 * size + x1] * tx;
|
||||
var bottom = values[y1 * size + x0] * (1 - tx) + values[y1 * size + x1] * tx;
|
||||
return top * (1 - ty) + bottom * ty;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(128, 5, 4, 8, 1)]
|
||||
[InlineData(256, 15, 4, 8, 1)]
|
||||
[InlineData(256, 30, 2, 16, 0.86)]
|
||||
[InlineData(512, 63, 4, 8, 1.19)]
|
||||
[InlineData(256, 40, 100, 0.5, 1)]
|
||||
[InlineData(256, 20, 0.25, 64, 0.9)]
|
||||
[InlineData(64, 31, 4, 8, 1.3)]
|
||||
public void TheKernelIsTheBilinearInterpolationOfTheGridAtTheScaledPositions(int gridSize, int radius, double pitch, double fNumber, double scale)
|
||||
{
|
||||
var specification = new PsfSpecification(gridSize, gridSize / 4, radius * 2 + 1, 550, fNumber, pitch, ApertureShape.Circular, 6, 0, 0, default);
|
||||
var grid = Grid(gridSize, gridSize + radius);
|
||||
var kernel = new double[specification.KernelSize * specification.KernelSize];
|
||||
var pixelPitch = specification.SensorPixelPitchMicrometers;
|
||||
var focalPitch = FraunhoferPsfGenerator.FocalPlaneSamplePitch(in specification);
|
||||
|
||||
var energy = FraunhoferPsfGenerator.SampleKernel(in specification, grid, kernel, scale);
|
||||
|
||||
var expectedEnergy = 0d;
|
||||
for (var y = 0; y < specification.KernelSize; y++)
|
||||
{
|
||||
var sampleY = gridSize / 2 + (y - radius) * pixelPitch / focalPitch * scale;
|
||||
for (var x = 0; x < specification.KernelSize; x++)
|
||||
{
|
||||
var sampleX = gridSize / 2 + (x - radius) * pixelPitch / focalPitch * scale;
|
||||
var expected = Bilinear(grid, gridSize, sampleX, sampleY);
|
||||
Assert.Equal(expected, kernel[y * specification.KernelSize + x]);
|
||||
expectedEnergy += expected;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.Equal(expectedEnergy, energy);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
using WaveOptics.Effects;
|
||||
using WaveOptics.Optics;
|
||||
|
||||
namespace WaveOptics.Tests.Psf;
|
||||
|
||||
public sealed class SpectralPlanTests
|
||||
{
|
||||
[Fact]
|
||||
public void ThePrimariesUseOneWavelengthPerChannelWithFullWeight()
|
||||
{
|
||||
var plan = SpectralPlan.For(WaveOpticsColorMode.Primaries, WaveOpticsQuality.High, false);
|
||||
|
||||
Assert.Equal(3, plan.Length);
|
||||
double[] wavelengths = [SpectralPlan.RedWavelength, SpectralPlan.GreenWavelength, SpectralPlan.BlueWavelength];
|
||||
for (var channel = 0; channel < 3; channel++)
|
||||
{
|
||||
var node = Assert.Single(plan[channel]);
|
||||
Assert.Equal(wavelengths[channel], node.Wavelength);
|
||||
var sample = Assert.Single(node.Samples);
|
||||
Assert.Equal(wavelengths[channel], sample.Wavelength);
|
||||
Assert.Equal(1d, sample.Weight);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheWavelengthsAndTheWidthOfTheBandsAreTheDocumentedValues()
|
||||
{
|
||||
Assert.Equal(610d, SpectralPlan.RedWavelength);
|
||||
Assert.Equal(550d, SpectralPlan.GreenWavelength);
|
||||
Assert.Equal(465d, SpectralPlan.BlueWavelength);
|
||||
Assert.Equal(550d, SpectralPlan.ReferenceWavelength);
|
||||
Assert.Equal(21d, SpectralPlan.BandSigma);
|
||||
Assert.Equal(2.5, SpectralPlan.BandSpan);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheGreenPrimaryIsTheReferenceWavelength()
|
||||
{
|
||||
Assert.Equal(SpectralPlan.ReferenceWavelength, SpectralPlan.GreenWavelength);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(WaveOpticsQuality.Draft, 1, 25)]
|
||||
[InlineData(WaveOpticsQuality.Standard, 3, 27)]
|
||||
[InlineData(WaveOpticsQuality.High, 5, 25)]
|
||||
public void ABroadbandIsDividedIntoNodesAndSamplesByQuality(WaveOpticsQuality quality, int nodes, int samples)
|
||||
{
|
||||
var plan = SpectralPlan.For(WaveOpticsColorMode.Broadband, quality, false);
|
||||
|
||||
foreach (var channel in plan)
|
||||
{
|
||||
Assert.Equal(nodes, channel.Length);
|
||||
Assert.Equal(samples, SpectralPlan.SampleCount(channel));
|
||||
Assert.True(SpectralPlan.SampleCount(channel) <= SpectralPlan.MaximumSamples);
|
||||
Assert.All(channel, node => Assert.True(node.Samples.Length <= SpectralPlan.MaximumSamples));
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(WaveOpticsQuality.Draft)]
|
||||
[InlineData(WaveOpticsQuality.Standard)]
|
||||
[InlineData(WaveOpticsQuality.High)]
|
||||
public void TheWeightsOfABandSumToOneAndFollowAGaussian(WaveOpticsQuality quality)
|
||||
{
|
||||
var plan = SpectralPlan.For(WaveOpticsColorMode.Broadband, quality, false);
|
||||
double[] centers = [SpectralPlan.RedWavelength, SpectralPlan.GreenWavelength, SpectralPlan.BlueWavelength];
|
||||
|
||||
for (var channel = 0; channel < 3; channel++)
|
||||
{
|
||||
var samples = plan[channel].SelectMany(node => node.Samples).ToArray();
|
||||
Assert.Equal(1d, samples.Sum(sample => sample.Weight), 12);
|
||||
Assert.Equal(centers[channel], samples.Sum(sample => sample.Weight * sample.Wavelength), 3);
|
||||
var middle = samples[samples.Length / 2];
|
||||
Assert.Equal(centers[channel], middle.Wavelength, 9);
|
||||
Assert.Equal(samples.Max(sample => sample.Weight), middle.Weight);
|
||||
Assert.InRange(samples[0].Wavelength, centers[channel] - SpectralPlan.BandSpan * SpectralPlan.BandSigma, centers[channel] - 2d * SpectralPlan.BandSigma);
|
||||
Assert.True(samples.Zip(samples.Skip(1)).All(pair => pair.Second.Wavelength > pair.First.Wavelength));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ANodeSitsAtTheMiddleSampleOfItsGroup()
|
||||
{
|
||||
var plan = SpectralPlan.For(WaveOpticsColorMode.Broadband, WaveOpticsQuality.Standard, false);
|
||||
|
||||
foreach (var channel in plan)
|
||||
{
|
||||
foreach (var node in channel)
|
||||
Assert.Equal(node.Samples[node.Samples.Length / 2].Wavelength, node.Wavelength);
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(WaveOpticsQuality.Standard)]
|
||||
[InlineData(WaveOpticsQuality.High)]
|
||||
public void WithoutAberrationABroadbandUsesOneNodePerChannel(WaveOpticsQuality quality)
|
||||
{
|
||||
var plan = SpectralPlan.For(WaveOpticsColorMode.Broadband, quality, true);
|
||||
|
||||
Assert.All(plan, channel => Assert.Single(channel));
|
||||
Assert.Same(SpectralPlan.For(WaveOpticsColorMode.Broadband, WaveOpticsQuality.Draft, false), plan);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheMonochromeModeHasNoPlan()
|
||||
{
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => SpectralPlan.For(WaveOpticsColorMode.Monochrome, WaveOpticsQuality.Standard, false));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeWeave;
|
||||
using SpectralConvolution;
|
||||
using WaveOptics.Effects;
|
||||
using WaveOptics.Rendering;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
[Collection("Direct3D12")]
|
||||
public sealed class WaveOpticsChromaticPipelineTests
|
||||
{
|
||||
const int Width = 160;
|
||||
const int Height = 144;
|
||||
const int White = unchecked((int)0xFFFFFFFF);
|
||||
const int Opaque = unchecked((int)0xFFC0A080);
|
||||
|
||||
static WaveOpticsPipeline.Parameters Parameters(
|
||||
WaveOpticsColorMode mode,
|
||||
int kernelRadius = 15,
|
||||
float defocus = 0.5f,
|
||||
float wavelength = 550f,
|
||||
float fNumber = 8f,
|
||||
float pixelPitch = 4f,
|
||||
WaveOpticsQuality quality = WaveOpticsQuality.Standard,
|
||||
LightOptions light = default,
|
||||
float coma = 0.3f)
|
||||
=> new(1f, new WaveOpticsPipeline.PsfParameters(
|
||||
quality, kernelRadius, wavelength, fNumber, pixelPitch, WaveOpticsApertureShape.Circular, 6, 0f, 0f, defocus, 0f, 0f, coma, 0f, 0f, mode), light);
|
||||
|
||||
static int[] Square(int left, int top, int size, int color)
|
||||
{
|
||||
var pixels = new int[Width * Height];
|
||||
for (var y = top; y < top + size; y++)
|
||||
{
|
||||
for (var x = left; x < left + size; x++)
|
||||
pixels[y * Width + x] = color;
|
||||
}
|
||||
|
||||
return pixels;
|
||||
}
|
||||
|
||||
static int[] Pattern()
|
||||
{
|
||||
var pixels = new int[Width * Height];
|
||||
for (var y = 50; y < 90; y++)
|
||||
{
|
||||
for (var x = 40; x < 110; x++)
|
||||
pixels[y * Width + x] = (x + y) % 7 == 0 ? 0 : Opaque;
|
||||
}
|
||||
|
||||
return pixels;
|
||||
}
|
||||
|
||||
static int[] RenderCpu(WaveOpticsCpuPipeline pipeline, int[] source, in WaveOpticsPipeline.Parameters parameters)
|
||||
{
|
||||
var destination = new int[source.Length];
|
||||
pipeline.Process(source, destination, Width, Height, in parameters);
|
||||
return destination;
|
||||
}
|
||||
|
||||
static int[] RenderGpu(WaveOpticsPipeline pipeline, int[] source, in WaveOpticsPipeline.Parameters parameters)
|
||||
{
|
||||
var destination = new int[source.Length];
|
||||
pipeline.Process(source, destination, Width, Height, in parameters);
|
||||
return destination;
|
||||
}
|
||||
|
||||
static byte Channel(int pixel, int shift) => (byte)(pixel >> shift);
|
||||
|
||||
public static TheoryData<WaveOpticsColorMode, int, WaveOpticsQuality> Modes => new()
|
||||
{
|
||||
{ WaveOpticsColorMode.Primaries, 15, WaveOpticsQuality.Standard },
|
||||
{ WaveOpticsColorMode.Primaries, 40, WaveOpticsQuality.High },
|
||||
{ WaveOpticsColorMode.Broadband, 15, WaveOpticsQuality.Draft },
|
||||
{ WaveOpticsColorMode.Broadband, 30, WaveOpticsQuality.Standard },
|
||||
};
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Modes))]
|
||||
public void TheCpuAndTheGpuDrawTheSameImageWithinTwoLevels(WaveOpticsColorMode mode, int kernelRadius, WaveOpticsQuality quality)
|
||||
{
|
||||
using var cpu = new WaveOpticsCpuPipeline(3);
|
||||
using var gpu = WaveOpticsPipeline.TryCreate();
|
||||
Assert.NotNull(gpu);
|
||||
var source = Pattern();
|
||||
var parameters = Parameters(mode, kernelRadius, quality: quality);
|
||||
|
||||
var expected = RenderGpu(gpu, source, in parameters);
|
||||
var actual = RenderCpu(cpu, source, in parameters);
|
||||
|
||||
var expectedBytes = MemoryMarshal.AsBytes(expected.AsSpan());
|
||||
var actualBytes = MemoryMarshal.AsBytes(actual.AsSpan());
|
||||
for (var index = 0; index < expectedBytes.Length; index++)
|
||||
Assert.InRange(actualBytes[index] - expectedBytes[index], -2, 2);
|
||||
Assert.Contains(actualBytes.ToArray(), value => value > 0);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(WaveOpticsColorMode.Primaries, 15)]
|
||||
[InlineData(WaveOpticsColorMode.Primaries, 40)]
|
||||
[InlineData(WaveOpticsColorMode.Broadband, 30)]
|
||||
public void AHealthyChromaticConvolutionPassesEveryCheck(WaveOpticsColorMode mode, int kernelRadius)
|
||||
{
|
||||
using var pipeline = WaveOpticsPipeline.TryCreate();
|
||||
Assert.NotNull(pipeline);
|
||||
var device = GraphicsDevice.GetDefault();
|
||||
using var source = device.AllocateReadWriteTexture2D<Bgra32, Float4>(Width, Height);
|
||||
source.CopyFrom(MemoryMarshal.Cast<int, Bgra32>(Pattern().AsSpan()));
|
||||
using var output = device.AllocateReadWriteTexture2D<Bgra32, Float4>(Width, Height);
|
||||
var parameters = Parameters(mode, kernelRadius);
|
||||
var measurements = new ConvolutionMeasurement[WaveOpticsPipeline.MeasurementCount];
|
||||
|
||||
pipeline.Simulate(source, Width, Height, 0, 0, Width, Height, in parameters);
|
||||
Assert.True(pipeline.TryGetVisibleBounds(Width, Height, in parameters, out var rect));
|
||||
var count = pipeline.RenderVisible(source, output, rect, in parameters, measurements);
|
||||
|
||||
Assert.Equal(WaveOpticsPipeline.MeasurementCount, count);
|
||||
Assert.All(measurements, measurement => Assert.True(measurement.Passes, $"{measurement}"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ACorruptedSpectrumOfTheChromaticModeIsFoundByTheCheck()
|
||||
{
|
||||
using var pipeline = WaveOpticsPipeline.TryCreate();
|
||||
Assert.NotNull(pipeline);
|
||||
var device = GraphicsDevice.GetDefault();
|
||||
using var source = device.AllocateReadWriteTexture2D<Bgra32, Float4>(Width, Height);
|
||||
source.CopyFrom(MemoryMarshal.Cast<int, Bgra32>(Pattern().AsSpan()));
|
||||
using var output = device.AllocateReadWriteTexture2D<Bgra32, Float4>(Width, Height);
|
||||
var parameters = Parameters(WaveOpticsColorMode.Primaries, 40);
|
||||
var measurements = new ConvolutionMeasurement[WaveOpticsPipeline.MeasurementCount];
|
||||
pipeline.SpectrumTamper = values =>
|
||||
{
|
||||
var copy = (Float2[])values.Clone();
|
||||
var blueStart = 2 * copy.Length / 3;
|
||||
for (var index = blueStart; index < copy.Length; index++)
|
||||
copy[index] = new Float2(copy[index].X * 0.5f, copy[index].Y * 0.5f);
|
||||
return copy;
|
||||
};
|
||||
|
||||
pipeline.Simulate(source, Width, Height, 0, 0, Width, Height, in parameters);
|
||||
Assert.True(pipeline.TryGetVisibleBounds(Width, Height, in parameters, out var rect));
|
||||
pipeline.RenderVisible(source, output, rect, in parameters, measurements);
|
||||
|
||||
Assert.Contains(measurements, measurement => !measurement.Passes && measurement.Name.EndsWith("blue", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void ARedChannelSpreadsFurtherThanABlueChannelAroundAWhiteSquare(bool onTheGpu)
|
||||
{
|
||||
var source = Square(60, 50, 40, White);
|
||||
var parameters = Parameters(WaveOpticsColorMode.Primaries, 30, defocus: 0f, fNumber: 16f, pixelPitch: 2f, coma: 0f);
|
||||
int[] result;
|
||||
if (onTheGpu)
|
||||
{
|
||||
using var gpu = WaveOpticsPipeline.TryCreate();
|
||||
Assert.NotNull(gpu);
|
||||
result = RenderGpu(gpu, source, in parameters);
|
||||
}
|
||||
else
|
||||
{
|
||||
using var cpu = new WaveOpticsCpuPipeline(2);
|
||||
result = RenderCpu(cpu, source, in parameters);
|
||||
}
|
||||
|
||||
var red = 0d;
|
||||
var green = 0d;
|
||||
var blue = 0d;
|
||||
for (var y = 38; y < 112; y++)
|
||||
{
|
||||
for (var x = 48; x < 112; x++)
|
||||
{
|
||||
if (x >= 58 && x < 102 && y >= 48 && y < 92)
|
||||
continue;
|
||||
var pixel = result[y * Width + x];
|
||||
red += Channel(pixel, 16);
|
||||
green += Channel(pixel, 8);
|
||||
blue += Channel(pixel, 0);
|
||||
}
|
||||
}
|
||||
|
||||
Assert.True(red > green && green > blue, $"{red} {green} {blue}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AMonochromeFrameAfterAChromaticFrameIsTheMonochromeFrameOfAFreshPipeline()
|
||||
{
|
||||
var source = Pattern();
|
||||
var mono = Parameters(WaveOpticsColorMode.Monochrome);
|
||||
var chromatic = Parameters(WaveOpticsColorMode.Primaries);
|
||||
using var cpu = new WaveOpticsCpuPipeline(2);
|
||||
using var gpu = WaveOpticsPipeline.TryCreate();
|
||||
Assert.NotNull(gpu);
|
||||
using var freshCpu = new WaveOpticsCpuPipeline(2);
|
||||
using var freshGpu = WaveOpticsPipeline.TryCreate();
|
||||
Assert.NotNull(freshGpu);
|
||||
|
||||
_ = RenderCpu(cpu, source, in mono);
|
||||
_ = RenderCpu(cpu, source, in chromatic);
|
||||
_ = RenderGpu(gpu, source, in mono);
|
||||
_ = RenderGpu(gpu, source, in chromatic);
|
||||
|
||||
Assert.Equal(RenderCpu(freshCpu, source, in mono), RenderCpu(cpu, source, in mono));
|
||||
Assert.Equal(RenderGpu(freshGpu, source, in mono), RenderGpu(gpu, source, in mono));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(WaveOpticsColorMode.Primaries)]
|
||||
[InlineData(WaveOpticsColorMode.Broadband)]
|
||||
public void TheWavelengthDoesNotChangeAChromaticFrame(WaveOpticsColorMode mode)
|
||||
{
|
||||
var source = Pattern();
|
||||
using var cpu = new WaveOpticsCpuPipeline(2);
|
||||
var first = Parameters(mode, wavelength: 450f);
|
||||
var second = Parameters(mode, wavelength: 700f);
|
||||
|
||||
Assert.Equal(RenderCpu(cpu, source, in first), RenderCpu(cpu, source, in second));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AChromaticFrameIsLinearLightAware()
|
||||
{
|
||||
var source = Square(60, 50, 4, White);
|
||||
var light = new LightOptions(true, false, 0.5f, 20f);
|
||||
using var cpu = new WaveOpticsCpuPipeline(2);
|
||||
using var gpu = WaveOpticsPipeline.TryCreate();
|
||||
Assert.NotNull(gpu);
|
||||
var parameters = Parameters(WaveOpticsColorMode.Primaries, 30, defocus: 0f, fNumber: 16f, pixelPitch: 2f, light: light);
|
||||
|
||||
var expected = RenderGpu(gpu, source, in parameters);
|
||||
var actual = RenderCpu(cpu, source, in parameters);
|
||||
|
||||
var expectedBytes = MemoryMarshal.AsBytes(expected.AsSpan());
|
||||
var actualBytes = MemoryMarshal.AsBytes(actual.AsSpan());
|
||||
for (var index = 0; index < expectedBytes.Length; index++)
|
||||
Assert.InRange(actualBytes[index] - expectedBytes[index], -3, 3);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(WaveOpticsColorMode.Primaries)]
|
||||
[InlineData(WaveOpticsColorMode.Broadband)]
|
||||
public void AWarmChromaticFrameAllocatesNothingOnTheCallingThread(WaveOpticsColorMode mode)
|
||||
{
|
||||
using var pipeline = new WaveOpticsCpuPipeline(3);
|
||||
var sources = new[] { MemoryMarshal.AsBytes(Square(30, 28, 36, Opaque).AsSpan()).ToArray(), MemoryMarshal.AsBytes(Square(31, 28, 36, Opaque).AsSpan()).ToArray() };
|
||||
var parameters = Parameters(mode);
|
||||
for (var warmUp = 0; warmUp < 4; warmUp++)
|
||||
{
|
||||
pipeline.Simulate(sources[warmUp % 2], Width, Height, 0, 0, Width, Height, in parameters);
|
||||
pipeline.TryGetVisibleBounds(Width, Height, in parameters, out var warmRect);
|
||||
pipeline.RenderVisible(warmRect, in parameters);
|
||||
}
|
||||
|
||||
void RenderFrames()
|
||||
{
|
||||
for (var frame = 0; frame < 8; frame++)
|
||||
{
|
||||
pipeline.Simulate(sources[frame % 2], Width, Height, 0, 0, Width, Height, in parameters);
|
||||
pipeline.TryGetVisibleBounds(Width, Height, in parameters, out var rect);
|
||||
pipeline.RenderVisible(rect, in parameters);
|
||||
}
|
||||
}
|
||||
|
||||
RenderFrames();
|
||||
AllocationProbe.Settle();
|
||||
|
||||
Assert.Equal(0L, AllocationProbe.MinimumAllocatedBytes(RenderFrames, 8));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using SpectralConvolution;
|
||||
using WaveOptics.Rendering;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
public sealed class WaveOpticsComputeTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(15, 128)]
|
||||
[InlineData(63, 512)]
|
||||
public void TheChromaticModeNeedsThreeHalfSpectraInsteadOfOneFullSpectrum(int radius, int size)
|
||||
{
|
||||
var single = WaveOpticsCompute.GpuMemoryBytes(1920, 1080, radius);
|
||||
var chromatic = WaveOpticsCompute.GpuMemoryBytes(1920, 1080, radius, true);
|
||||
|
||||
var expected = (3L * (size / 2 + 1) * size - (long)size * size) * sizeof(float) * 2;
|
||||
Assert.Equal(expected, chromatic - single);
|
||||
Assert.Equal(single, WaveOpticsCompute.GpuMemoryBytes(1920, 1080, radius, false));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheWorkloadCarriesTheMemoryOfTheChosenMode()
|
||||
{
|
||||
var single = WaveOpticsCompute.Workload(1280, 720, 40);
|
||||
var chromatic = WaveOpticsCompute.Workload(1280, 720, 40, true);
|
||||
|
||||
Assert.Equal(WaveOpticsCompute.GpuMemoryBytes(1280, 720, 40), single.GpuMemoryBytes);
|
||||
Assert.Equal(WaveOpticsCompute.GpuMemoryBytes(1280, 720, 40, true), chromatic.GpuMemoryBytes);
|
||||
Assert.True(chromatic.GpuMemoryBytes > single.GpuMemoryBytes);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using SpectralConvolution;
|
||||
using WaveOptics.Effects;
|
||||
using WaveOptics.Rendering;
|
||||
|
||||
@@ -34,6 +36,25 @@ public sealed class WaveOpticsCpuPipelineTests
|
||||
return pipeline.RenderVisible(rect, in parameters).ToArray();
|
||||
}
|
||||
|
||||
static CpuTileConvolver Convolver(WaveOpticsCpuPipeline pipeline)
|
||||
=> (CpuTileConvolver)typeof(WaveOpticsCpuPipeline).GetField("_convolver", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(pipeline)!;
|
||||
|
||||
[Fact]
|
||||
public void PipelinesShareTheThreadsAndTheWorkingArea()
|
||||
{
|
||||
using var first = new WaveOpticsCpuPipeline();
|
||||
using var second = new WaveOpticsCpuPipeline();
|
||||
var source = Bytes(Square(150, 120, 30, 20, 70));
|
||||
var parameters = Parameters(gain: 1.5f, defocus: 1f);
|
||||
|
||||
RenderFrame(first, source, 150, 120, 16, in parameters, out _);
|
||||
var bytes = Convolver(first).WorkingBytes;
|
||||
|
||||
Assert.True(bytes > 0);
|
||||
Assert.Equal(Environment.ProcessorCount, Convolver(second).Threads);
|
||||
Assert.True(Convolver(second).WorkingBytes >= bytes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheCpuAndTheGpuDrawTheSameImageWithinTwoLevels()
|
||||
{
|
||||
@@ -157,16 +178,20 @@ public sealed class WaveOpticsCpuPipelineTests
|
||||
for (var warmUp = 0; warmUp < 4; warmUp++)
|
||||
RenderFrame(pipeline, sources[warmUp % 2], 96, 96, 16, in parameters, out _);
|
||||
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
for (var frame = 0; frame < 8; frame++)
|
||||
void RenderFrames()
|
||||
{
|
||||
pipeline.Simulate(sources[frame % 2], 128, 128, 16, 16, 96, 96, in parameters);
|
||||
pipeline.TryGetVisibleBounds(128, 128, in parameters, out var rect);
|
||||
pipeline.RenderVisible(rect, in parameters);
|
||||
for (var frame = 0; frame < 8; frame++)
|
||||
{
|
||||
pipeline.Simulate(sources[frame % 2], 128, 128, 16, 16, 96, 96, in parameters);
|
||||
pipeline.TryGetVisibleBounds(128, 128, in parameters, out var rect);
|
||||
pipeline.RenderVisible(rect, in parameters);
|
||||
}
|
||||
}
|
||||
var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
|
||||
|
||||
Assert.Equal(0L, allocated);
|
||||
RenderFrames();
|
||||
AllocationProbe.Settle();
|
||||
|
||||
Assert.Equal(0L, AllocationProbe.MinimumAllocatedBytes(RenderFrames, 8));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
using System.Globalization;
|
||||
using System.Numerics;
|
||||
using ComputeGuard;
|
||||
using WaveOptics.Effects;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Json;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
[Collection("Direct2D")]
|
||||
public sealed class WaveOpticsDepthProcessorTests
|
||||
{
|
||||
const int Size = 96;
|
||||
const int Length = 30;
|
||||
const double Wavelength = 550d;
|
||||
|
||||
static readonly Bgra Warm = Bgra.Opaque(220, 160, 90);
|
||||
|
||||
static Bgra Shape(int x, int y)
|
||||
=> x is >= 32 and < 64 && y is >= 32 and < 64 && (x + 2 * y) % 9 != 0 ? Warm : Bgra.Transparent;
|
||||
|
||||
static Animation Linear(double from, double to)
|
||||
=> Json.LoadFromText<Animation>(string.Create(CultureInfo.InvariantCulture, $$"""{"AnimationType":"直線移動","Values":[{"Value":{{from}}},{"Value":{{to}}}]}"""))!;
|
||||
|
||||
static WaveOpticsEffect Effect(bool useDepth = true, WaveOpticsColorMode colorMode = WaveOpticsColorMode.Monochrome)
|
||||
=> new() { UseDepth = useDepth, ColorMode = colorMode };
|
||||
|
||||
static Rendering Render(WaveOpticsEffect effect, Vector3 position, Matrix4x4? camera = null, int frame = 0)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Size, Size, Shape);
|
||||
using var processor = new WaveOpticsEffectProcessor(context, effect, new ComputeGuardian(new ComputeGuardianOptions { Report = _ => { } }), null, false);
|
||||
processor.SetInput(source.Bitmap);
|
||||
processor.Update(EffectDescriptions.At(frame, Length, EffectDescriptions.Draw(position, camera)));
|
||||
return Rendering.Capture(context, processor.Output);
|
||||
}
|
||||
|
||||
static Vector3 At(float z) => new(0f, 0f, z);
|
||||
|
||||
static int DistanceFromSquare(int x, int y)
|
||||
=> Math.Max(Math.Max(Math.Max(32 - x, x - 63), Math.Max(32 - y, y - 63)), 0);
|
||||
|
||||
static double LightBeyond(Rendering rendering, int distance)
|
||||
=> rendering.Coordinates().Where(point => DistanceFromSquare(point.X, point.Y) > distance).Sum(point => (double)rendering[point.X, point.Y].Alpha);
|
||||
|
||||
static void AssertIdentical(Rendering expected, Rendering actual) => Assert.True(expected.SamePixelsAs(actual));
|
||||
|
||||
static void AssertDiffers(Rendering expected, Rendering actual) => Assert.False(expected.SamePixelsAs(actual));
|
||||
|
||||
static double DepthWaves(float z, double focusDistance = 1000d, double focalLength = 50d, double fNumber = 8d, double wavelength = Wavelength)
|
||||
=> WaveOpticsDepth.DefocusWaves(focalLength, fNumber, focusDistance, 1000d - z, wavelength);
|
||||
|
||||
[Fact]
|
||||
public void AnItemAtTheFocusDistanceIsRenderedAsWithoutDepth()
|
||||
=> AssertIdentical(Render(Effect(false), At(0f)), Render(Effect(), At(0f)));
|
||||
|
||||
[Fact]
|
||||
public void WithoutDepthTheDistanceOfTheItemChangesNothing()
|
||||
=> AssertIdentical(Render(Effect(false), At(0f)), Render(Effect(false), At(-500f)));
|
||||
|
||||
[Theory]
|
||||
[InlineData(-500f)]
|
||||
[InlineData(-200f)]
|
||||
[InlineData(300f)]
|
||||
public void TheDepthDefocusIsTheDefocusOfTheSameNumberOfWaves(float z)
|
||||
{
|
||||
var manual = Effect(false);
|
||||
manual.Defocus.Values[0].Value = DepthWaves(z);
|
||||
|
||||
AssertIdentical(Render(manual, At(0f)), Render(Effect(), At(z)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheDepthDefocusAddsToTheDefocusTheUserSet()
|
||||
{
|
||||
const double set = 0.3d;
|
||||
var manual = Effect(false);
|
||||
manual.Defocus.Values[0].Value = (double)(float)set + DepthWaves(-500f);
|
||||
var combined = Effect();
|
||||
combined.Defocus.Values[0].Value = set;
|
||||
|
||||
AssertIdentical(Render(manual, At(0f)), Render(combined, At(-500f)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ABlurredItemSpreadsFartherThanAnItemAtTheFocus()
|
||||
{
|
||||
var sharp = Render(Effect(), At(0f));
|
||||
|
||||
var behind = Render(Effect(), At(-500f));
|
||||
var inFront = Render(Effect(), At(500f));
|
||||
|
||||
Assert.True(LightBeyond(behind, 3) > 4d * LightBeyond(sharp, 3));
|
||||
Assert.True(LightBeyond(inFront, 3) > 4d * LightBeyond(sharp, 3));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheFocusDistanceChoosesThePlaneThatStaysSharp()
|
||||
{
|
||||
var focused = Effect();
|
||||
focused.FocusDistance.Values[0].Value = 1500d;
|
||||
|
||||
AssertIdentical(Render(Effect(false), At(0f)), Render(focused, At(-500f)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheFocalLengthChangesHowFastTheBlurGrows()
|
||||
{
|
||||
var longLens = Effect();
|
||||
longLens.FocalLength.Values[0].Value = 100d;
|
||||
|
||||
var reference = Render(Effect(), At(-300f));
|
||||
var stronger = Render(longLens, At(-300f));
|
||||
|
||||
Assert.True(LightBeyond(stronger, 8) > 1.5d * LightBeyond(reference, 8));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MovingTheCameraBlursTheItem()
|
||||
{
|
||||
var camera = Matrix4x4.CreateTranslation(0f, 0f, 300f);
|
||||
|
||||
var sharp = Render(Effect(), At(0f));
|
||||
var moved = Render(Effect(), At(0f), camera);
|
||||
|
||||
AssertDiffers(sharp, moved);
|
||||
AssertIdentical(Render(Effect(), At(300f)), moved);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1000f)]
|
||||
[InlineData(1500f)]
|
||||
public void AnItemWithoutADistanceKeepsTheDefocusTheUserSet(float z)
|
||||
{
|
||||
var effect = Effect();
|
||||
effect.Defocus.Values[0].Value = 0.4d;
|
||||
var manual = Effect(false);
|
||||
manual.Defocus.Values[0].Value = 0.4d;
|
||||
|
||||
AssertIdentical(Render(manual, At(0f)), Render(effect, At(z)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ThePrimariesAndBroadbandCountWavesIn550Nanometres()
|
||||
{
|
||||
var violet = Effect(true, WaveOpticsColorMode.Primaries);
|
||||
violet.Wavelength.Values[0].Value = 400d;
|
||||
|
||||
AssertIdentical(Render(Effect(true, WaveOpticsColorMode.Primaries), At(-500f)), Render(violet, At(-500f)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AMonochromeWaveCountFollowsTheChosenWavelength()
|
||||
{
|
||||
var red = Effect();
|
||||
red.Wavelength.Values[0].Value = 650d;
|
||||
var manual = Effect(false);
|
||||
manual.Wavelength.Values[0].Value = 650d;
|
||||
manual.Defocus.Values[0].Value = DepthWaves(-500f, wavelength: 650d);
|
||||
|
||||
AssertIdentical(Render(manual, At(0f)), Render(red, At(-500f)));
|
||||
AssertDiffers(Render(Effect(), At(-500f)), Render(red, At(-500f)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheFNumberAndTheFocalLengthAreTakenFromTheFrame()
|
||||
{
|
||||
var effect = Effect();
|
||||
effect.FNumber.Values[0].Value = 4d;
|
||||
effect.FocalLength.Values[0].Value = 35d;
|
||||
var manual = Effect(false);
|
||||
manual.FNumber.Values[0].Value = 4d;
|
||||
manual.Defocus.Values[0].Value = DepthWaves(-500f, focalLength: 35d, fNumber: 4d);
|
||||
|
||||
AssertIdentical(Render(manual, At(0f)), Render(effect, At(-500f)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ALongFocalLengthIsUsedAsSet()
|
||||
{
|
||||
var effect = Effect();
|
||||
effect.FocalLength.Values[0].Value = 300d;
|
||||
effect.FNumber.Values[0].Value = 32d;
|
||||
var manual = Effect(false);
|
||||
manual.FNumber.Values[0].Value = 32d;
|
||||
manual.Defocus.Values[0].Value = DepthWaves(-500f, focalLength: 300d, fNumber: 32d);
|
||||
|
||||
AssertIdentical(Render(manual, At(0f)), Render(effect, At(-500f)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AShortFocalLengthIsUsedAsSet()
|
||||
{
|
||||
var effect = Effect();
|
||||
effect.FocalLength.Values[0].Value = 1d;
|
||||
effect.FNumber.Values[0].Value = 0.5d;
|
||||
var manual = Effect(false);
|
||||
manual.FNumber.Values[0].Value = 0.5d;
|
||||
manual.Defocus.Values[0].Value = DepthWaves(-500f, focalLength: 1d, fNumber: 0.5d);
|
||||
|
||||
AssertIdentical(Render(manual, At(0f)), Render(effect, At(-500f)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AFarFocusDistanceIsUsedAsSet()
|
||||
{
|
||||
var effect = Effect();
|
||||
effect.FocusDistance.Values[0].Value = 500000d;
|
||||
effect.FocalLength.Values[0].Value = 31d;
|
||||
effect.FNumber.Values[0].Value = 1d;
|
||||
var manual = Effect(false);
|
||||
manual.FNumber.Values[0].Value = 1d;
|
||||
manual.Defocus.Values[0].Value = DepthWaves(-999000f, focusDistance: 500000d, focalLength: 31d, fNumber: 1d);
|
||||
|
||||
AssertIdentical(Render(manual, At(0f)), Render(effect, At(-999000f)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ANearFocusDistanceIsUsedAsSet()
|
||||
{
|
||||
var effect = Effect();
|
||||
effect.FocusDistance.Values[0].Value = 10d;
|
||||
effect.FocalLength.Values[0].Value = 1d;
|
||||
effect.FNumber.Values[0].Value = 2d;
|
||||
var manual = Effect(false);
|
||||
manual.FNumber.Values[0].Value = 2d;
|
||||
manual.Defocus.Values[0].Value = DepthWaves(-500f, focusDistance: 10d, focalLength: 1d, fNumber: 2d);
|
||||
|
||||
AssertIdentical(Render(manual, At(0f)), Render(effect, At(-500f)));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-999000f, 10d)]
|
||||
[InlineData(699f, -10d)]
|
||||
public void TheTotalDefocusStopsAtTenWaves(float z, double expected)
|
||||
{
|
||||
var effect = Effect();
|
||||
effect.FocalLength.Values[0].Value = 300d;
|
||||
effect.FNumber.Values[0].Value = 1d;
|
||||
var manual = Effect(false);
|
||||
manual.FNumber.Values[0].Value = 1d;
|
||||
manual.Defocus.Values[0].Value = expected;
|
||||
|
||||
Assert.True(Math.Abs(DepthWaves(z, focalLength: 300d, fNumber: 1d)) > 100d);
|
||||
AssertIdentical(Render(manual, At(0f)), Render(effect, At(z)));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(nameof(WaveOpticsEffect.Defocus))]
|
||||
[InlineData(nameof(WaveOpticsEffect.AstigmatismVertical))]
|
||||
[InlineData(nameof(WaveOpticsEffect.AstigmatismOblique))]
|
||||
[InlineData(nameof(WaveOpticsEffect.ComaHorizontal))]
|
||||
[InlineData(nameof(WaveOpticsEffect.ComaVertical))]
|
||||
[InlineData(nameof(WaveOpticsEffect.Spherical))]
|
||||
public void AnAberrationIsKeptUpToTenWavesAndClampedBeyond(string aberration)
|
||||
{
|
||||
static Rendering With(string name, double waves)
|
||||
{
|
||||
var effect = Effect(false);
|
||||
((Animation)typeof(WaveOpticsEffect).GetProperty(name)!.GetValue(effect)!).Values[0].Value = waves;
|
||||
return Render(effect, At(0f));
|
||||
}
|
||||
|
||||
AssertDiffers(With(aberration, 9.5d), With(aberration, 10d));
|
||||
AssertIdentical(With(aberration, 10d), With(aberration, 12d));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(nameof(WaveOpticsEffect.FocalLength))]
|
||||
[InlineData(nameof(WaveOpticsEffect.FocusDistance))]
|
||||
public void AValueThatIsNotANumberFallsBackToTheDefault(string setting)
|
||||
{
|
||||
var broken = Effect();
|
||||
((Animation)typeof(WaveOpticsEffect).GetProperty(setting)!.GetValue(broken)!).Values[0].Value = double.NaN;
|
||||
|
||||
AssertIdentical(Render(Effect(), At(-500f)), Render(broken, At(-500f)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnAnimatedFocusDistancePullsTheFocusToTheItem()
|
||||
{
|
||||
var pulled = Effect();
|
||||
pulled.FocusDistance.CopyFrom(Linear(1000d, 1500d));
|
||||
|
||||
var first = Render(pulled, At(-500f), null, 0);
|
||||
var middle = Render(pulled, At(-500f), null, Length / 2);
|
||||
var last = Render(pulled, At(-500f), null, Length - 1);
|
||||
|
||||
Assert.True(LightBeyond(first, 3) > 1.2d * LightBeyond(middle, 3));
|
||||
Assert.True(LightBeyond(middle, 3) > 1.5d * LightBeyond(last, 3));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
using System.Numerics;
|
||||
using System.Reflection;
|
||||
using Vortice.Direct2D1;
|
||||
using WaveOptics.Abstractions;
|
||||
using WaveOptics.Effects;
|
||||
using WaveOptics.Optics;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
public sealed class WaveOpticsDepthTests
|
||||
{
|
||||
const double Wavelength = 550d;
|
||||
|
||||
static DrawDescription Draw(Vector3 position, Matrix4x4? camera = null, float? perspectiveDistance = null)
|
||||
=> new DrawDescription(position, Vector2.Zero, Vector2.One, Vector3.Zero, camera ?? Matrix4x4.Identity, InterpolationMode.Linear, 1d, false, [])
|
||||
{
|
||||
PerspectiveDistance = perspectiveDistance,
|
||||
};
|
||||
|
||||
static DrawDescription AtDepth(float z, Matrix4x4? camera = null, float? perspectiveDistance = null)
|
||||
=> Draw(new Vector3(300f, -200f, z), camera, perspectiveDistance);
|
||||
|
||||
static double DistanceOf(DrawDescription drawDescription)
|
||||
{
|
||||
Assert.True(WaveOpticsDepth.TryGetDistance(drawDescription, out var distance));
|
||||
return distance;
|
||||
}
|
||||
|
||||
static double CircleOfConfusionRadius(double focalLength, double fNumber, double pixelPitchMicrometers, double focusDistance, double distance)
|
||||
{
|
||||
var focusImage = 1d / (1d / focalLength - 1d / focusDistance);
|
||||
var subjectImage = 1d / (1d / focalLength - 1d / distance);
|
||||
var apertureDiameter = focalLength / fNumber;
|
||||
return apertureDiameter * Math.Abs(focusImage - subjectImage) / (2d * subjectImage) / (pixelPitchMicrometers / 1000d);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0f, 1000d)]
|
||||
[InlineData(250f, 750d)]
|
||||
[InlineData(-500f, 1500d)]
|
||||
[InlineData(999f, 1d)]
|
||||
public void TheDistanceIsTheBasePerspectiveDistanceMinusZ(float z, double expected)
|
||||
{
|
||||
Assert.Equal(1000f, WaveOpticsDepth.BasePerspectiveDistance);
|
||||
|
||||
Assert.Equal(expected, DistanceOf(AtDepth(z)), 6);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0f, 0f, 1000d)]
|
||||
[InlineData(5000f, -3000f, 1000d)]
|
||||
[InlineData(-20000f, 20000f, 1000d)]
|
||||
public void TheDistanceDoesNotDependOnTheSidewaysPosition(float x, float y, double expected)
|
||||
=> Assert.Equal(expected, DistanceOf(Draw(new Vector3(x, y, 0f))), 6);
|
||||
|
||||
[Fact]
|
||||
public void MovingTheCameraForwardShortensTheDistance()
|
||||
{
|
||||
var camera = Matrix4x4.CreateTranslation(0f, 0f, 300f);
|
||||
|
||||
Assert.Equal(700d, DistanceOf(AtDepth(0f, camera)), 4);
|
||||
Assert.Equal(600d, DistanceOf(AtDepth(100f, camera)), 4);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(60d, 500d)]
|
||||
[InlineData(-60d, 500d)]
|
||||
[InlineData(80d, 173.64817766693033d)]
|
||||
[InlineData(0d, 1000d)]
|
||||
public void ARotatedCameraMeasuresTheDepthAlongTheViewingAxis(double degrees, double expected)
|
||||
{
|
||||
var camera = Matrix4x4.CreateRotationY((float)(Math.PI * degrees / 180d), new Vector3(0f, 0f, 1000f));
|
||||
|
||||
var found = WaveOpticsDepth.TryGetDistance(Draw(Vector3.Zero, camera), out var distance);
|
||||
|
||||
Assert.Equal(expected > 1d, found);
|
||||
if (found)
|
||||
Assert.Equal(expected, distance, 3);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(2000f, 0f, 2000d)]
|
||||
[InlineData(2000f, 500f, 1500d)]
|
||||
[InlineData(400f, 100f, 300d)]
|
||||
public void APerspectiveDistanceReplacesTheBaseDistance(float perspectiveDistance, float z, double expected)
|
||||
=> Assert.Equal(expected, DistanceOf(AtDepth(z, null, perspectiveDistance)), 4);
|
||||
|
||||
[Theory]
|
||||
[InlineData(float.NaN)]
|
||||
[InlineData(0f)]
|
||||
[InlineData(-5f)]
|
||||
[InlineData(float.NegativeInfinity)]
|
||||
public void AnInvalidPerspectiveDistanceIsTheBaseDistanceAsInTheHost(float perspectiveDistance)
|
||||
=> Assert.Equal(750d, DistanceOf(AtDepth(250f, null, perspectiveDistance)), 4);
|
||||
|
||||
[Fact]
|
||||
public void AnInfinitePerspectiveDistanceHasNoDistance()
|
||||
{
|
||||
Assert.False(WaveOpticsDepth.TryGetDistance(AtDepth(0f, null, float.PositiveInfinity), out var distance));
|
||||
Assert.Equal(0d, distance);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1000f)]
|
||||
[InlineData(1000.5f)]
|
||||
[InlineData(1500f)]
|
||||
[InlineData(float.NaN)]
|
||||
[InlineData(float.PositiveInfinity)]
|
||||
[InlineData(float.NegativeInfinity)]
|
||||
public void AnItemAtOrBehindTheCameraHasNoDistance(float z)
|
||||
{
|
||||
Assert.False(WaveOpticsDepth.TryGetDistance(AtDepth(z), out var distance));
|
||||
Assert.Equal(0d, distance);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ACameraThatIsNotFiniteHasNoDistance()
|
||||
{
|
||||
var camera = Matrix4x4.Identity;
|
||||
camera.M43 = float.NaN;
|
||||
|
||||
Assert.False(WaveOpticsDepth.TryGetDistance(AtDepth(0f, camera), out _));
|
||||
}
|
||||
|
||||
static Matrix4x4 Camera(float x, float y, float z, double yaw, double pitch)
|
||||
=> Matrix4x4.CreateTranslation(x, y, z)
|
||||
* Matrix4x4.CreateRotationY((float)(Math.PI * yaw / 180d), new Vector3(0f, 0f, 1000f))
|
||||
* Matrix4x4.CreateRotationX((float)(Math.PI * pitch / 180d), new Vector3(0f, 0f, 1000f));
|
||||
|
||||
public static TheoryData<float, float, float, double, double, float?, BillboardMode> HostCases { get; } = new()
|
||||
{
|
||||
{ 0f, 0f, 0f, 0d, 0d, null, BillboardMode.None },
|
||||
{ 40f, -20f, 300f, 0d, 0d, null, BillboardMode.None },
|
||||
{ 0f, 0f, -250f, 25d, -10d, null, BillboardMode.None },
|
||||
{ 80f, 30f, 120f, -35d, 20d, 400f, BillboardMode.None },
|
||||
{ 80f, 30f, 120f, -35d, 20d, 2500f, BillboardMode.Spherical },
|
||||
{ -60f, 10f, -90f, 50d, 15d, null, BillboardMode.Spherical },
|
||||
{ 10f, 10f, 60f, 70d, -25d, 1800f, BillboardMode.Cylindrical },
|
||||
{ 0f, 0f, 0f, 0d, 0d, 1200f, BillboardMode.Cylindrical },
|
||||
};
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(HostCases))]
|
||||
public void TheDistanceMatchesTheCameraTheHostFinalizes(float x, float y, float z, double yaw, double pitch, float? perspectiveDistance, BillboardMode billboard)
|
||||
{
|
||||
var finalizer = Type.GetType("YukkuriMovieMaker.Player.Video.CameraFinalizer, YukkuriMovieMaker");
|
||||
var apply = finalizer?.GetMethod("Apply", BindingFlags.Public | BindingFlags.Static);
|
||||
if (apply is null)
|
||||
Assert.Skip("The host camera finalizer is unavailable.");
|
||||
|
||||
foreach (var position in new[] { new Vector3(120f, -80f, 200f), new Vector3(0f, 0f, -700f), new Vector3(-30f, 55f, 0f) })
|
||||
{
|
||||
var drawDescription = Draw(position, Camera(x, y, z, yaw, pitch), perspectiveDistance) with { Billboard = billboard };
|
||||
var finalized = (DrawDescription)apply.Invoke(null, [drawDescription])!;
|
||||
var projection = new Matrix4x4(1f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1f, -0.001f, 0f, 0f, 0f, 1f);
|
||||
var matrix = Matrix4x4.CreateTranslation(finalized.Draw) * finalized.Camera * projection;
|
||||
var w = Vector4.Transform(new Vector4(0f, 0f, 0f, 1f), matrix).W;
|
||||
var expected = (perspectiveDistance is > 0f ? perspectiveDistance.Value : WaveOpticsDepth.BasePerspectiveDistance) * (double)w;
|
||||
|
||||
var found = WaveOpticsDepth.TryGetDistance(drawDescription, out var distance);
|
||||
|
||||
Assert.Equal(expected > 0d, found);
|
||||
if (found)
|
||||
Assert.Equal(expected, distance, expected * 1e-4);
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(380d)]
|
||||
[InlineData(550d)]
|
||||
[InlineData(650d)]
|
||||
public void AMonochromeWaveCountIsMeasuredInTheChosenWavelength(double wavelength)
|
||||
=> Assert.Equal(wavelength, WaveOpticsDepth.ReferenceWavelength(WaveOpticsColorMode.Monochrome, wavelength));
|
||||
|
||||
[Theory]
|
||||
[InlineData(WaveOpticsColorMode.Primaries, 380d)]
|
||||
[InlineData(WaveOpticsColorMode.Primaries, 650d)]
|
||||
[InlineData(WaveOpticsColorMode.Broadband, 380d)]
|
||||
[InlineData(WaveOpticsColorMode.Broadband, 780d)]
|
||||
public void APrimariesOrBroadbandWaveCountIsMeasuredIn550Nanometres(WaveOpticsColorMode colorMode, double wavelength)
|
||||
=> Assert.Equal(550d, WaveOpticsDepth.ReferenceWavelength(colorMode, wavelength));
|
||||
|
||||
[Fact]
|
||||
public void TheDefocusIsZeroAtTheFocusDistance()
|
||||
=> Assert.Equal(0d, WaveOpticsDepth.DefocusWaves(50d, 8d, 1500d, 1500d, Wavelength));
|
||||
|
||||
[Fact]
|
||||
public void ADistantSubjectOfAFiftyMillimetreLensAtF8NeedsAboutEightTenthsOfAWave()
|
||||
=> Assert.Equal(0.7885575136440475, WaveOpticsDepth.DefocusWaves(50d, 8d, 2000d, 5000d, Wavelength), 9);
|
||||
|
||||
[Theory]
|
||||
[InlineData(2000d, 5000d)]
|
||||
[InlineData(1000d, 400d)]
|
||||
[InlineData(300d, 8000d)]
|
||||
[InlineData(80d, 90d)]
|
||||
public void TheDefocusIsPositiveBeyondTheFocusAndNegativeBeforeIt(double focus, double subject)
|
||||
{
|
||||
var waves = WaveOpticsDepth.DefocusWaves(35d, 4d, focus, subject, Wavelength);
|
||||
|
||||
Assert.NotEqual(0d, waves);
|
||||
Assert.Equal(subject > focus, waves > 0d);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheDefocusShrinksWithTheSquareOfTheFNumber()
|
||||
{
|
||||
var reference = WaveOpticsDepth.DefocusWaves(50d, 8d, 2000d, 5000d, Wavelength);
|
||||
|
||||
Assert.Equal(reference / 4d, WaveOpticsDepth.DefocusWaves(50d, 16d, 2000d, 5000d, Wavelength), 12);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ForAFocusFarBeyondTheFocalLengthTheDefocusApproachesTheFarFieldValue()
|
||||
{
|
||||
var farField = 50d / 8d * (50d / 8d) / 8d * (1d / 1e7 - 1d / 2e7) / (2d * Math.Sqrt(3d) * Wavelength * 1e-6);
|
||||
|
||||
Assert.Equal(farField, WaveOpticsDepth.DefocusWaves(50d, 8d, 1e7, 2e7, Wavelength), farField * 1e-5);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheDefocusInWavesIsInverselyProportionalToTheWavelength()
|
||||
{
|
||||
var green = WaveOpticsDepth.DefocusWaves(50d, 8d, 2000d, 5000d, 550d);
|
||||
|
||||
Assert.Equal(green * 550d / 650d, WaveOpticsDepth.DefocusWaves(50d, 8d, 2000d, 5000d, 650d), 9);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(50d, 8d, 4d, 2000d, 5000d)]
|
||||
[InlineData(35d, 2.8d, 2d, 1200d, 700d)]
|
||||
[InlineData(85d, 16d, 6d, 3000d, 1200d)]
|
||||
[InlineData(50d, 8d, 4d, 300d, 1000d)]
|
||||
[InlineData(50d, 8d, 4d, 120d, 500d)]
|
||||
[InlineData(100d, 4d, 3d, 400d, 250d)]
|
||||
public void TheDefocusReproducesTheThinLensCircleOfConfusion(double focalLength, double fNumber, double pixelPitch, double focus, double subject)
|
||||
{
|
||||
var waves = WaveOpticsDepth.DefocusWaves(focalLength, fNumber, focus, subject, Wavelength);
|
||||
|
||||
var edge = 4d * fNumber * (2d * Math.Sqrt(3d) * Math.Abs(waves) * Wavelength / 1000d) / pixelPitch;
|
||||
|
||||
var expected = CircleOfConfusionRadius(focalLength, fNumber, pixelPitch, focus, subject);
|
||||
Assert.Equal(expected, edge, expected * 1e-9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ThePointSpreadFunctionHasTheRadiusOfTheCircleOfConfusion()
|
||||
{
|
||||
const double focalLength = 50d;
|
||||
const double fNumber = 8d;
|
||||
const double pixelPitch = 4d;
|
||||
const double focus = 1000d;
|
||||
const double subject = 3000d;
|
||||
const int radius = 63;
|
||||
var waves = WaveOpticsDepth.DefocusWaves(focalLength, fNumber, focus, subject, Wavelength);
|
||||
var descriptor = new PsfDescriptor(512, 128, radius * 2 + 1, Wavelength, fNumber, pixelPitch, ApertureShape.Circular, 6, 0, 0, new WavefrontAberration(defocusWaves: waves));
|
||||
|
||||
var kernel = new FraunhoferPsfGenerator().Generate(descriptor).Kernel;
|
||||
|
||||
var distances = new List<(double Distance, double Value)>();
|
||||
for (var y = 0; y < kernel.Size; y++)
|
||||
{
|
||||
for (var x = 0; x < kernel.Size; x++)
|
||||
distances.Add((Math.Sqrt((x - radius) * (x - radius) + (y - radius) * (y - radius)), kernel[x, y]));
|
||||
}
|
||||
var energy = 0d;
|
||||
var ninetyPercentRadius = 0d;
|
||||
foreach (var (distance, value) in distances.OrderBy(entry => entry.Distance))
|
||||
{
|
||||
energy += value;
|
||||
ninetyPercentRadius = distance;
|
||||
if (energy >= 0.9)
|
||||
break;
|
||||
}
|
||||
|
||||
var expected = CircleOfConfusionRadius(focalLength, fNumber, pixelPitch, focus, subject);
|
||||
Assert.InRange(ninetyPercentRadius, Math.Sqrt(0.9) * expected - 1d, Math.Sqrt(0.9) * expected + 1d);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(20d, 55d)]
|
||||
[InlineData(-3d, 55d)]
|
||||
[InlineData(10000d, 50d)]
|
||||
public void DistancesInsideTheFocalLengthAreHeldJustOutsideIt(double distance, double focalLength)
|
||||
{
|
||||
var held = WaveOpticsDepth.DefocusWaves(focalLength, 8d, 2000d, focalLength * WaveOpticsDepth.MinimumDistanceRatio, Wavelength);
|
||||
|
||||
var waves = WaveOpticsDepth.DefocusWaves(focalLength, 8d, 2000d, distance, Wavelength);
|
||||
|
||||
Assert.True(double.IsFinite(waves));
|
||||
if (distance < focalLength)
|
||||
Assert.Equal(held, waves, 12);
|
||||
else
|
||||
Assert.NotEqual(held, waves);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AFocusDistanceInsideTheFocalLengthIsHeldJustOutsideIt()
|
||||
{
|
||||
var held = WaveOpticsDepth.DefocusWaves(50d, 8d, 50d * WaveOpticsDepth.MinimumDistanceRatio, 1000d, Wavelength);
|
||||
|
||||
Assert.Equal(held, WaveOpticsDepth.DefocusWaves(50d, 8d, 10d, 1000d, Wavelength), 12);
|
||||
Assert.Equal(held, WaveOpticsDepth.DefocusWaves(50d, 8d, 50d, 1000d, Wavelength), 12);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheMinimumDistanceIsOnePointZeroZeroOneTimesTheFocalLength()
|
||||
{
|
||||
Assert.Equal(1.001, WaveOpticsDepth.MinimumDistanceRatio);
|
||||
|
||||
var held = WaveOpticsDepth.DefocusWaves(50d, 8d, 50.05d, 1000d, Wavelength);
|
||||
|
||||
Assert.Equal(held, WaveOpticsDepth.DefocusWaves(50d, 8d, 50d, 1000d, Wavelength), 12);
|
||||
Assert.Equal(held, WaveOpticsDepth.DefocusWaves(50d, 8d, 20d, 1000d, Wavelength), 12);
|
||||
Assert.NotEqual(held, WaveOpticsDepth.DefocusWaves(50d, 8d, 50.1d, 1000d, Wavelength));
|
||||
|
||||
var heldSubject = WaveOpticsDepth.DefocusWaves(50d, 8d, 1000d, 50.05d, Wavelength);
|
||||
|
||||
Assert.Equal(heldSubject, WaveOpticsDepth.DefocusWaves(50d, 8d, 1000d, 50d, Wavelength), 12);
|
||||
Assert.Equal(heldSubject, WaveOpticsDepth.DefocusWaves(50d, 8d, 1000d, 20d, Wavelength), 12);
|
||||
Assert.NotEqual(heldSubject, WaveOpticsDepth.DefocusWaves(50d, 8d, 1000d, 50.1d, Wavelength));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData(700f)]
|
||||
public void ACameraWithAProjectionPartIsMeasuredThroughTheWholeMatrix(float? perspectiveDistance)
|
||||
{
|
||||
var camera = new Matrix4x4(1f, 0f, 0f, 0.0002f, 0f, 1f, 0f, 0.0001f, 0f, 0f, 1f, 0.0003f, 10f, 20f, 30f, 1.5f);
|
||||
var position = new Vector3(120f, -80f, 200f);
|
||||
var distance = perspectiveDistance ?? WaveOpticsDepth.BasePerspectiveDistance;
|
||||
var projection = new Matrix4x4(1f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1f, -1f / distance, 0f, 0f, 0f, 1f);
|
||||
var w = Vector4.Transform(new Vector4(position, 1f), camera * projection).W;
|
||||
|
||||
Assert.Equal(distance * (double)w, DistanceOf(Draw(position, camera, perspectiveDistance)), 3);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0d, 0d, 0d, 0d, 0d, false)]
|
||||
[InlineData(0.5d, 0d, 0d, 0d, 0d, true)]
|
||||
[InlineData(0d, 0.5d, 0d, 0d, 0d, true)]
|
||||
[InlineData(0d, 0d, 0.5d, 0d, 0d, true)]
|
||||
[InlineData(0d, 0d, 0d, 0.5d, 0d, false)]
|
||||
[InlineData(0d, 0d, 0d, 0d, 0.5d, false)]
|
||||
[InlineData(0d, 0d, 0d, 0.5d, 0.3d, false)]
|
||||
[InlineData(0.3d, 0d, 0d, 0.5d, 0d, true)]
|
||||
public void TheSignOfTheDefocusChangesThePointSpreadWithSphericalAberrationOrAstigmatismOnly(
|
||||
double spherical, double astigmatismVertical, double astigmatismOblique, double comaHorizontal, double comaVertical, bool differs)
|
||||
{
|
||||
PsfKernel Kernel(double defocus)
|
||||
=> new FraunhoferPsfGenerator().Generate(new PsfDescriptor(256, 64, 57, Wavelength, 8d, 4d, ApertureShape.Circular, 6, 0, 0,
|
||||
new WavefrontAberration(
|
||||
defocusWaves: defocus,
|
||||
astigmatismVerticalWaves: astigmatismVertical,
|
||||
astigmatismObliqueWaves: astigmatismOblique,
|
||||
comaHorizontalWaves: comaHorizontal,
|
||||
comaVerticalWaves: comaVertical,
|
||||
sphericalWaves: spherical))).Kernel;
|
||||
|
||||
var positive = Kernel(1d).Values.Span;
|
||||
var negative = Kernel(-1d).Values.Span;
|
||||
var difference = 0d;
|
||||
for (var index = 0; index < positive.Length; index++)
|
||||
difference += Math.Abs(positive[index] - negative[index]);
|
||||
|
||||
if (differs)
|
||||
Assert.True(difference > 0.5, difference.ToString());
|
||||
else
|
||||
Assert.True(difference < 1e-9, difference.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddingTheDepthDefocusKeepsTheDefocusTheUserSet()
|
||||
{
|
||||
var drawDescription = AtDepth(-1000f);
|
||||
var depth = WaveOpticsDepth.DefocusWaves(50d, 8d, 1000d, 2000d, Wavelength);
|
||||
|
||||
Assert.NotEqual(0d, depth);
|
||||
Assert.Equal(0.5d + depth, WaveOpticsDepth.AddDefocus(0.5d, drawDescription, 50d, 8d, 1000d, Wavelength), 12);
|
||||
Assert.Equal(-1.25d + depth, WaveOpticsDepth.AddDefocus(-1.25d, drawDescription, 50d, 8d, 1000d, Wavelength), 12);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1000f, float.NaN)]
|
||||
[InlineData(0f, float.PositiveInfinity)]
|
||||
public void AnItemWithoutADistanceKeepsTheDefocusTheUserSet(float z, float perspectiveDistance)
|
||||
=> Assert.Equal(0.5d, WaveOpticsDepth.AddDefocus(0.5d, AtDepth(z, null, perspectiveDistance), 50d, 8d, 500d, Wavelength));
|
||||
|
||||
[Fact]
|
||||
public void AnItemAtTheFocusDistanceAddsNothing()
|
||||
=> Assert.Equal(0.75d, WaveOpticsDepth.AddDefocus(0.75d, AtDepth(250f), 50d, 8d, 750d, Wavelength));
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
using ComputeGuard;
|
||||
using ComputeWeave;
|
||||
using WaveOptics.Effects;
|
||||
using WaveOptics.Rendering;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
[Collection("Direct2D")]
|
||||
public sealed class WaveOpticsEffectProcessorAllocationTests
|
||||
{
|
||||
internal const int Size = 128;
|
||||
internal const int Length = 60;
|
||||
const int Rounds = 24;
|
||||
|
||||
internal static Bgra Shape(int x, int y) => x is >= 32 and < 96 && y is >= 32 and < 96 && (x + 2 * y) % 9 != 0 ? Bgra.Opaque(220, 160, 90) : Bgra.Transparent;
|
||||
|
||||
internal static void RequireInterop(IGraphicsDevicesAndContext devices)
|
||||
{
|
||||
using var scheduler = ComputeExternalQueueScheduler.Create();
|
||||
using var provider = WaveOpticsInteropProvider.TryCreate(devices, scheduler, out var device);
|
||||
if (provider is null || device is null)
|
||||
Assert.Skip("Direct3D 11 and Direct3D 12 sharing is unavailable.");
|
||||
}
|
||||
|
||||
internal static WaveOpticsEffectProcessor Processor(IGraphicsDevicesAndContext devices, WaveOpticsEffect effect, bool allowGpu)
|
||||
=> new(devices, effect, new ComputeGuardian(new ComputeGuardianOptions { Report = _ => { } }), null, allowGpu);
|
||||
|
||||
static long MinimumAllocatedPerUpdate(bool allowGpu, Action<WaveOpticsEffect> configure)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
if (allowGpu)
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, Shape);
|
||||
var effect = new WaveOpticsEffect();
|
||||
configure(effect);
|
||||
using var processor = Processor(context, effect, allowGpu);
|
||||
processor.SetInput(source.Bitmap);
|
||||
var description = EffectDescriptions.At(7, Length);
|
||||
for (var warmUp = 0; warmUp < 8; warmUp++)
|
||||
processor.Update(description);
|
||||
AllocationProbe.Settle();
|
||||
|
||||
return AllocationProbe.MinimumAllocatedBytes(() => processor.Update(description), Rounds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnUnchangedFrameOnTheGpuRouteAllocatesNothing()
|
||||
=> Assert.Equal(0L, MinimumAllocatedPerUpdate(true, _ => { }));
|
||||
|
||||
[Fact]
|
||||
public void AnUnchangedFrameOnTheCpuRouteAllocatesNothing()
|
||||
=> Assert.Equal(0L, MinimumAllocatedPerUpdate(false, _ => { }));
|
||||
|
||||
[Fact]
|
||||
public void AFrameWithoutAmountOnTheGpuRouteAllocatesNothing()
|
||||
=> Assert.Equal(0L, MinimumAllocatedPerUpdate(true, effect => effect.Amount.Values[0].Value = 0d));
|
||||
|
||||
[Fact]
|
||||
public void AFrameWithoutAmountOnTheCpuRouteAllocatesNothing()
|
||||
=> Assert.Equal(0L, MinimumAllocatedPerUpdate(false, effect => effect.Amount.Values[0].Value = 0d));
|
||||
|
||||
[Fact]
|
||||
public void AnUnchangedFrameWithDepthOnTheGpuRouteAllocatesNothing()
|
||||
=> Assert.Equal(0L, MinimumAllocatedPerUpdate(true, effect =>
|
||||
{
|
||||
effect.UseDepth = true;
|
||||
effect.FocusDistance.Values[0].Value = 800d;
|
||||
}));
|
||||
|
||||
[Fact]
|
||||
public void AnUnchangedChromaticFrameOnTheGpuRouteAllocatesNothing()
|
||||
=> Assert.Equal(0L, MinimumAllocatedPerUpdate(true, effect => effect.ColorMode = WaveOpticsColorMode.Broadband));
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using Vortice.Direct2D1;
|
||||
using WaveOptics.Effects;
|
||||
using WaveOptics.Rendering;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
[Collection("Direct2D")]
|
||||
public sealed class WaveOpticsEffectProcessorBitmapTests
|
||||
{
|
||||
static object Field(WaveOpticsEffectProcessor processor, string name)
|
||||
=> typeof(WaveOpticsEffectProcessor).GetField(name, BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(processor)!;
|
||||
|
||||
static int SourceBitmapReferences(WaveOpticsEffectProcessor processor)
|
||||
{
|
||||
var resources = (WaveOpticsResourceSet)Field(processor, "_resourceSet");
|
||||
using var borrow = resources.BeginSourceExternalOperation();
|
||||
return Marshal.Release(borrow.DangerousGetView().AddRefBitmap());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EveryFrameLeavesTheReferencesOfTheSourceBitmapBalanced()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
WaveOpticsEffectProcessorAllocationTests.RequireInterop(context);
|
||||
using var source = new SourceImage(context, WaveOpticsEffectProcessorAllocationTests.Size, WaveOpticsEffectProcessorAllocationTests.Size, WaveOpticsEffectProcessorAllocationTests.Shape);
|
||||
using var processor = WaveOpticsEffectProcessorAllocationTests.Processor(context, new WaveOpticsEffect(), true);
|
||||
processor.SetInput(source.Bitmap);
|
||||
var description = EffectDescriptions.At(7, WaveOpticsEffectProcessorAllocationTests.Length);
|
||||
processor.Update(description);
|
||||
var baseline = SourceBitmapReferences(processor);
|
||||
|
||||
for (var frame = 0; frame < 10; frame++)
|
||||
processor.Update(description);
|
||||
|
||||
Assert.Equal(baseline, SourceBitmapReferences(processor));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSourceBitmapWrapperHoldsNoPointerBetweenFrames()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
WaveOpticsEffectProcessorAllocationTests.RequireInterop(context);
|
||||
using var source = new SourceImage(context, WaveOpticsEffectProcessorAllocationTests.Size, WaveOpticsEffectProcessorAllocationTests.Size, WaveOpticsEffectProcessorAllocationTests.Shape);
|
||||
using var processor = WaveOpticsEffectProcessorAllocationTests.Processor(context, new WaveOpticsEffect(), true);
|
||||
processor.SetInput(source.Bitmap);
|
||||
var description = EffectDescriptions.At(7, WaveOpticsEffectProcessorAllocationTests.Length);
|
||||
|
||||
processor.Update(description);
|
||||
processor.Update(description);
|
||||
|
||||
Assert.Equal(IntPtr.Zero, ((ID2D1Bitmap1)Field(processor, "_sourceBitmap")).NativePointer);
|
||||
}
|
||||
}
|
||||
@@ -241,4 +241,54 @@ public sealed class WaveOpticsEffectProcessorRouteTests
|
||||
Assert.Equal((0, 0, Size, Size), (rendering.Left, rendering.Top, rendering.Width, rendering.Height));
|
||||
Assert.All(rendering.Coordinates(), point => Assert.Equal(source[point.X, point.Y], rendering[point.X, point.Y]));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void OnTheCpuAProcessorThatOnlyToggledTheDitherDrawsLikeAFreshOne(bool linear)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Size, Size, Shape);
|
||||
var effect = Effect();
|
||||
effect.Linear = linear;
|
||||
effect.Gain.Values[0].Value = 60d;
|
||||
using var processor = Processor(context, effect, new Reports().CreateGuardian(), false);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
foreach (var dither in new[] { false, true, false, true })
|
||||
{
|
||||
effect.Dither = dither;
|
||||
var expected = CpuReference(context, source, effect, 0);
|
||||
|
||||
var reused = RenderFrame(context, processor, 0);
|
||||
|
||||
Assert.True(reused.SamePixelsAs(expected), $"dither {dither}");
|
||||
}
|
||||
}
|
||||
|
||||
static Bgra TwoTone(int x, int y)
|
||||
=> x is >= 20 and < 52 && y is >= 18 and < 50 ? (x < 36 ? Bgra.Opaque(255, 255, 255) : Bgra.Opaque(0, 0, 0)) : Bgra.Transparent;
|
||||
|
||||
[Fact]
|
||||
public void OnTheCpuTheLightSettingsReachTheEffect()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = new SourceImage(context, Size, Size, TwoTone);
|
||||
var effect = Effect();
|
||||
using var processor = Processor(context, effect, new Reports().CreateGuardian(), false);
|
||||
processor.SetInput(source.Bitmap);
|
||||
var plain = RenderFrame(context, processor, 0);
|
||||
|
||||
effect.Linear = true;
|
||||
var linear = RenderFrame(context, processor, 0);
|
||||
effect.HighlightThreshold.Values[0].Value = 40d;
|
||||
effect.HighlightBoost.Values[0].Value = 30d;
|
||||
var boosted = RenderFrame(context, processor, 0);
|
||||
|
||||
Assert.False(plain.SamePixelsAs(linear), "plain linear");
|
||||
Assert.False(linear.SamePixelsAs(boosted), "linear boosted");
|
||||
Assert.True(boosted.SamePixelsAs(CpuReference(context, source, effect, 0)));
|
||||
}
|
||||
}
|
||||
@@ -232,6 +232,8 @@ public sealed class WaveOpticsEffectProcessorTests
|
||||
{ nameof(WaveOpticsEffect.Amount), effect => effect.Amount.CopyFrom(Linear(20d, 100d)) },
|
||||
{ nameof(WaveOpticsEffect.Gain), effect => effect.Gain.CopyFrom(Linear(50d, 150d)) },
|
||||
{ nameof(WaveOpticsEffect.Defocus), effect => effect.Defocus.CopyFrom(Linear(0d, 2d)) },
|
||||
{ nameof(WaveOpticsEffect.HighlightBoost), effect => { effect.Linear = true; effect.Gain.Values[0].Value = 5d; effect.HighlightThreshold.Values[0].Value = 50d; effect.HighlightBoost.CopyFrom(Linear(1d, 20d)); } },
|
||||
{ nameof(WaveOpticsEffect.HighlightThreshold), effect => { effect.Linear = true; effect.Gain.Values[0].Value = 5d; effect.HighlightBoost.Values[0].Value = 20d; effect.HighlightThreshold.CopyFrom(Linear(30d, 95d)); } },
|
||||
};
|
||||
|
||||
[Theory]
|
||||
@@ -337,8 +339,70 @@ public sealed class WaveOpticsEffectProcessorTests
|
||||
{ nameof(WaveOpticsEffect.ComaHorizontal), effect => effect.ComaHorizontal.Values[0].Value = 1d },
|
||||
{ nameof(WaveOpticsEffect.ComaVertical), effect => effect.ComaVertical.Values[0].Value = 1d },
|
||||
{ nameof(WaveOpticsEffect.Spherical), effect => effect.Spherical.Values[0].Value = 1d },
|
||||
{ nameof(WaveOpticsEffect.Linear), effect => effect.Linear = true },
|
||||
{ nameof(WaveOpticsEffect.Dither), effect => { effect.Dither = true; effect.Gain.Values[0].Value = 50d; } },
|
||||
};
|
||||
|
||||
public static readonly TheoryData<string, Action<WaveOpticsEffect>> LaterLightChanges = new()
|
||||
{
|
||||
{ nameof(WaveOpticsEffect.Linear), effect => effect.Linear = false },
|
||||
{ nameof(WaveOpticsEffect.Dither), effect => effect.Dither = true },
|
||||
{ nameof(WaveOpticsEffect.HighlightThreshold), effect => effect.HighlightThreshold.Values[0].Value = 90d },
|
||||
{ nameof(WaveOpticsEffect.HighlightBoost), effect => effect.HighlightBoost.Values[0].Value = 500d },
|
||||
};
|
||||
|
||||
static Bgra TwoTone(int x, int y)
|
||||
=> x is >= Start and < End && y is >= Start and < End ? (x < Size / 2 ? Bgra.Opaque(190, 190, 190) : Bgra.Opaque(40, 40, 40)) : Bgra.Transparent;
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(LaterLightChanges))]
|
||||
public void EveryLightSettingChangedAfterTheFirstFrameReachesTheEffect(string setting, Action<WaveOpticsEffect> change)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, TwoTone);
|
||||
var effect = new WaveOpticsEffect { ApertureShape = WaveOpticsApertureShape.RegularPolygon, Linear = true };
|
||||
effect.Gain.Values[0].Value = 3d;
|
||||
effect.HighlightThreshold.Values[0].Value = 50d;
|
||||
effect.HighlightBoost.Values[0].Value = 100d;
|
||||
using var processor = effect.CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
var before = RenderFrame(context, processor, 0);
|
||||
change(effect);
|
||||
var after = RenderFrame(context, processor, 0);
|
||||
|
||||
Assert.False(before.SamePixelsAs(after), setting);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void AProcessorThatOnlyToggledTheDitherDrawsLikeAFreshOne(bool linear)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
RequireInterop(context);
|
||||
using var source = new SourceImage(context, Size, Size, CenteredSquare);
|
||||
var effect = new WaveOpticsEffect { Linear = linear };
|
||||
effect.Gain.Values[0].Value = 60d;
|
||||
using var processor = effect.CreateVideoEffect(context);
|
||||
processor.SetInput(source.Bitmap);
|
||||
|
||||
foreach (var dither in new[] { false, true, false, true })
|
||||
{
|
||||
effect.Dither = dither;
|
||||
using var fresh = effect.CreateVideoEffect(context);
|
||||
fresh.SetInput(source.Bitmap);
|
||||
var expected = RenderFrame(context, fresh, 0);
|
||||
|
||||
var reused = RenderFrame(context, processor, 0);
|
||||
|
||||
Assert.True(reused.SamePixelsAs(expected), $"dither {dither}");
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(LaterChanges))]
|
||||
public void EverySettingChangedAfterTheFirstFrameReachesTheEffect(string setting, Action<WaveOpticsEffect> change)
|
||||
|
||||
@@ -18,7 +18,7 @@ public sealed class WaveOpticsEffectTests
|
||||
static T Attribute<T>(string property) where T : Attribute => Property(property).GetCustomAttribute<T>()!;
|
||||
|
||||
static Animation[] Animations(WaveOpticsEffect effect)
|
||||
=> [effect.Amount, effect.Gain, effect.Wavelength, effect.FNumber, effect.PixelPitch, effect.BladeRotation, effect.Obstruction, effect.Defocus, effect.AstigmatismVertical, effect.AstigmatismOblique, effect.ComaHorizontal, effect.ComaVertical, effect.Spherical];
|
||||
=> [effect.Amount, effect.Gain, effect.Wavelength, effect.FNumber, effect.PixelPitch, effect.BladeRotation, effect.Obstruction, effect.Defocus, effect.AstigmatismVertical, effect.AstigmatismOblique, effect.ComaHorizontal, effect.ComaVertical, effect.Spherical, effect.HighlightThreshold, effect.HighlightBoost, effect.FocusDistance, effect.FocalLength];
|
||||
|
||||
[Theory]
|
||||
[InlineData(nameof(WaveOpticsEffect.Amount), 100d, 0d, 100d)]
|
||||
@@ -34,6 +34,10 @@ public sealed class WaveOpticsEffectTests
|
||||
[InlineData(nameof(WaveOpticsEffect.ComaHorizontal), 0d, -10d, 10d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.ComaVertical), 0d, -10d, 10d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.Spherical), 0d, -10d, 10d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.HighlightThreshold), 95d, 0d, 100d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.HighlightBoost), 1d, 1d, 1000d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.FocusDistance), 1000d, 10d, 1000000d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.FocalLength), 50d, 1d, 1000d)]
|
||||
public void AnimatedParametersStartFromTheirDefaultsWithinTheirRange(string name, double defaultValue, double minimum, double maximum)
|
||||
{
|
||||
var effect = new WaveOpticsEffect();
|
||||
@@ -46,6 +50,19 @@ public sealed class WaveOpticsEffectTests
|
||||
Assert.Equal(defaultValue, animation.GetValue(0, 1, EffectDescriptions.Fps));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LinearLightAndDitherAreOffByDefault()
|
||||
{
|
||||
var effect = new WaveOpticsEffect();
|
||||
|
||||
Assert.False(effect.Linear);
|
||||
Assert.False(effect.Dither);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DepthIsOffByDefault()
|
||||
=> Assert.False(new WaveOpticsEffect().UseDepth);
|
||||
|
||||
[Fact]
|
||||
public void KernelRadiusQualityApertureAndBladesStartFromTheirDefaults()
|
||||
{
|
||||
@@ -106,14 +123,17 @@ public sealed class WaveOpticsEffectTests
|
||||
effect.Quality = WaveOpticsQuality.High;
|
||||
effect.ApertureShape = WaveOpticsApertureShape.RegularPolygon;
|
||||
effect.BladeCount = 9;
|
||||
effect.Linear = true;
|
||||
effect.Dither = true;
|
||||
effect.UseDepth = true;
|
||||
|
||||
Assert.Equal([nameof(WaveOpticsEffect.KernelRadius), nameof(WaveOpticsEffect.Quality), nameof(WaveOpticsEffect.ApertureShape), nameof(WaveOpticsEffect.BladeCount)], changed);
|
||||
Assert.Equal([nameof(WaveOpticsEffect.KernelRadius), nameof(WaveOpticsEffect.Quality), nameof(WaveOpticsEffect.ApertureShape), nameof(WaveOpticsEffect.BladeCount), nameof(WaveOpticsEffect.Linear), nameof(WaveOpticsEffect.Dither), nameof(WaveOpticsEffect.UseDepth)], changed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AssigningAnUnchangedOrClampedValueDoesNotNotify()
|
||||
{
|
||||
var effect = new WaveOpticsEffect { KernelRadius = WaveOpticsSettings.MaximumKernelRadius };
|
||||
var effect = new WaveOpticsEffect { KernelRadius = WaveOpticsSettings.MaximumKernelRadius, Linear = true, Dither = true, UseDepth = true };
|
||||
var changed = new List<string?>();
|
||||
effect.PropertyChanged += (_, e) => changed.Add(e.PropertyName);
|
||||
|
||||
@@ -122,6 +142,9 @@ public sealed class WaveOpticsEffectTests
|
||||
effect.Quality = WaveOpticsQuality.Standard;
|
||||
effect.ApertureShape = WaveOpticsApertureShape.Circular;
|
||||
effect.BladeCount = 6;
|
||||
effect.Linear = true;
|
||||
effect.Dither = true;
|
||||
effect.UseDepth = true;
|
||||
|
||||
Assert.Empty(changed);
|
||||
}
|
||||
@@ -135,7 +158,7 @@ public sealed class WaveOpticsEffectTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheThirteenNumericParametersReceiveTheAnimationParameters()
|
||||
public void TheSeventeenNumericParametersReceiveTheAnimationParameters()
|
||||
{
|
||||
var effect = new WaveOpticsEffect();
|
||||
|
||||
@@ -174,11 +197,18 @@ public sealed class WaveOpticsEffectTests
|
||||
[Theory]
|
||||
[InlineData(nameof(WaveOpticsEffect.Amount), nameof(Texts.OutputGroup), nameof(Texts.Amount), nameof(Texts.AmountDescription), 0)]
|
||||
[InlineData(nameof(WaveOpticsEffect.Gain), nameof(Texts.OutputGroup), nameof(Texts.Gain), nameof(Texts.GainDescription), 1)]
|
||||
[InlineData(nameof(WaveOpticsEffect.Linear), nameof(Texts.OutputGroup), nameof(Texts.Linear), nameof(Texts.LinearDescription), 2)]
|
||||
[InlineData(nameof(WaveOpticsEffect.HighlightThreshold), nameof(Texts.OutputGroup), nameof(Texts.HighlightThreshold), nameof(Texts.HighlightThresholdDescription), 3)]
|
||||
[InlineData(nameof(WaveOpticsEffect.HighlightBoost), nameof(Texts.OutputGroup), nameof(Texts.HighlightBoost), nameof(Texts.HighlightBoostDescription), 4)]
|
||||
[InlineData(nameof(WaveOpticsEffect.Dither), nameof(Texts.OutputGroup), nameof(Texts.Dither), nameof(Texts.DitherDescription), 5)]
|
||||
[InlineData(nameof(WaveOpticsEffect.Wavelength), nameof(Texts.OpticsGroup), nameof(Texts.Wavelength), nameof(Texts.WavelengthDescription), 10)]
|
||||
[InlineData(nameof(WaveOpticsEffect.FNumber), nameof(Texts.OpticsGroup), nameof(Texts.FNumber), nameof(Texts.FNumberDescription), 11)]
|
||||
[InlineData(nameof(WaveOpticsEffect.PixelPitch), nameof(Texts.OpticsGroup), nameof(Texts.PixelPitch), nameof(Texts.PixelPitchDescription), 12)]
|
||||
[InlineData(nameof(WaveOpticsEffect.KernelRadius), nameof(Texts.OpticsGroup), nameof(Texts.KernelRadius), nameof(Texts.KernelRadiusDescription), 13)]
|
||||
[InlineData(nameof(WaveOpticsEffect.Quality), nameof(Texts.OpticsGroup), nameof(Texts.Quality), nameof(Texts.QualityDescription), 14)]
|
||||
[InlineData(nameof(WaveOpticsEffect.UseDepth), nameof(Texts.DepthGroup), nameof(Texts.UseDepth), nameof(Texts.UseDepthDescription), 15)]
|
||||
[InlineData(nameof(WaveOpticsEffect.FocusDistance), nameof(Texts.DepthGroup), nameof(Texts.FocusDistance), nameof(Texts.FocusDistanceDescription), 16)]
|
||||
[InlineData(nameof(WaveOpticsEffect.FocalLength), nameof(Texts.DepthGroup), nameof(Texts.FocalLength), nameof(Texts.FocalLengthDescription), 17)]
|
||||
[InlineData(nameof(WaveOpticsEffect.ApertureShape), nameof(Texts.ApertureGroup), nameof(Texts.ApertureShape), nameof(Texts.ApertureShapeDescription), 20)]
|
||||
[InlineData(nameof(WaveOpticsEffect.BladeCount), nameof(Texts.ApertureGroup), nameof(Texts.BladeCount), nameof(Texts.BladeCountDescription), 21)]
|
||||
[InlineData(nameof(WaveOpticsEffect.BladeRotation), nameof(Texts.ApertureGroup), nameof(Texts.BladeRotation), nameof(Texts.BladeRotationDescription), 22)]
|
||||
@@ -214,6 +244,10 @@ public sealed class WaveOpticsEffectTests
|
||||
[InlineData(nameof(WaveOpticsEffect.ComaHorizontal), "F3", "waves", -3d, 3d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.ComaVertical), "F3", "waves", -3d, 3d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.Spherical), "F3", "waves", -3d, 3d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.HighlightThreshold), "F1", "%", 0d, 100d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.HighlightBoost), "F1", "x", 1d, 100d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.FocusDistance), "F0", "mm", 100d, 10000d)]
|
||||
[InlineData(nameof(WaveOpticsEffect.FocalLength), "F1", "mm", 10d, 300d)]
|
||||
public void AnimatedParametersAreEditedWithAnimationSliders(string property, string format, string unit, double minimum, double maximum)
|
||||
{
|
||||
var slider = Attribute<AnimationSliderAttribute>(property);
|
||||
@@ -241,6 +275,16 @@ public sealed class WaveOpticsEffectTests
|
||||
Assert.Equal(defaultValue, Attribute<DefaultValueAttribute>(property).Value);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(nameof(WaveOpticsEffect.Linear))]
|
||||
[InlineData(nameof(WaveOpticsEffect.Dither))]
|
||||
[InlineData(nameof(WaveOpticsEffect.UseDepth))]
|
||||
public void TheSwitchesAreEditedWithToggleSliders(string property)
|
||||
{
|
||||
Assert.NotNull(Property(property).GetCustomAttribute<ToggleSliderAttribute>());
|
||||
Assert.Equal(typeof(bool), Property(property).PropertyType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheQualityAndTheApertureShapeAreChosenFromCombos()
|
||||
{
|
||||
@@ -267,8 +311,8 @@ public sealed class WaveOpticsEffectTests
|
||||
[Fact]
|
||||
public void EverySettingSurvivesAProjectRoundTrip()
|
||||
{
|
||||
var effect = new WaveOpticsEffect { KernelRadius = 7, Quality = WaveOpticsQuality.High, ApertureShape = WaveOpticsApertureShape.RegularPolygon, BladeCount = 9 };
|
||||
var values = new[] { 55d, 150d, 620d, 5.6d, 2.5d, 30d, 40d, 1.5d, -0.5d, 0.25d, -1d, 0.75d, 2d };
|
||||
var effect = new WaveOpticsEffect { KernelRadius = 7, Quality = WaveOpticsQuality.High, ApertureShape = WaveOpticsApertureShape.RegularPolygon, BladeCount = 9, Linear = true, Dither = true, UseDepth = true };
|
||||
var values = new[] { 55d, 150d, 620d, 5.6d, 2.5d, 30d, 40d, 1.5d, -0.5d, 0.25d, -1d, 0.75d, 2d, 80d, 12d, 2500d, 85d };
|
||||
foreach (var (animation, value) in Animations(effect).Zip(values))
|
||||
animation.Values[0].Value = value;
|
||||
|
||||
@@ -279,6 +323,9 @@ public sealed class WaveOpticsEffectTests
|
||||
Assert.Equal(WaveOpticsQuality.High, clone.Quality);
|
||||
Assert.Equal(WaveOpticsApertureShape.RegularPolygon, clone.ApertureShape);
|
||||
Assert.Equal(9, clone.BladeCount);
|
||||
Assert.True(clone.Linear);
|
||||
Assert.True(clone.Dither);
|
||||
Assert.True(clone.UseDepth);
|
||||
Assert.Equal(values, Animations(clone).Select(animation => animation.GetValue(0, 1, EffectDescriptions.Fps)));
|
||||
}
|
||||
|
||||
@@ -294,6 +341,13 @@ public sealed class WaveOpticsEffectTests
|
||||
Assert.Equal(WaveOpticsApertureShape.RegularPolygon, effect.ApertureShape);
|
||||
Assert.Equal(9, effect.BladeCount);
|
||||
Assert.Equal(1.5d, effect.Defocus.GetValue(0, 1, EffectDescriptions.Fps));
|
||||
Assert.False(effect.Linear);
|
||||
Assert.False(effect.Dither);
|
||||
Assert.False(effect.UseDepth);
|
||||
Assert.Equal(1000d, effect.FocusDistance.GetValue(0, 1, EffectDescriptions.Fps));
|
||||
Assert.Equal(50d, effect.FocalLength.GetValue(0, 1, EffectDescriptions.Fps));
|
||||
Assert.Equal(95d, effect.HighlightThreshold.GetValue(0, 1, EffectDescriptions.Fps));
|
||||
Assert.Equal(1d, effect.HighlightBoost.GetValue(0, 1, EffectDescriptions.Fps));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
using WaveOptics.Effects;
|
||||
using WaveOptics.Rendering;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
public sealed class WaveOpticsKernelChromaticTests
|
||||
{
|
||||
static WaveOpticsPipeline.PsfParameters Psf(WaveOpticsColorMode mode, float wavelength = 550f, int radius = 15, float defocus = 0f, WaveOpticsApertureShape shape = WaveOpticsApertureShape.Circular, int blades = 6)
|
||||
=> new(WaveOpticsQuality.Standard, radius, wavelength, 8f, 4f, shape, blades, 0f, 0f, defocus, 0f, 0f, 0f, 0f, 0f, mode);
|
||||
|
||||
[Fact]
|
||||
public void AMonochromeKernelIsNotChromatic()
|
||||
{
|
||||
var kernel = new WaveOpticsKernel();
|
||||
|
||||
Assert.True(kernel.TryUpdate(Psf(WaveOpticsColorMode.Monochrome)));
|
||||
|
||||
Assert.False(kernel.IsChromatic);
|
||||
Assert.Equal(128, kernel.Size);
|
||||
Assert.Equal(15, kernel.Radius);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(WaveOpticsColorMode.Primaries)]
|
||||
[InlineData(WaveOpticsColorMode.Broadband)]
|
||||
public void AChromaticKernelHoldsASpectrumForEveryChannel(WaveOpticsColorMode mode)
|
||||
{
|
||||
var kernel = new WaveOpticsKernel();
|
||||
|
||||
Assert.True(kernel.TryUpdate(Psf(mode, radius: 30, defocus: 0.5f)));
|
||||
|
||||
Assert.True(kernel.IsChromatic);
|
||||
Assert.True(kernel.IsValid);
|
||||
Assert.Equal(512, kernel.Size);
|
||||
Assert.Equal(30, kernel.Radius);
|
||||
Assert.Equal(kernel.ChromaticSpectrum.Size, kernel.Size);
|
||||
Assert.NotEqual(kernel.ChromaticSpectrum.Red.Kernel.ToArray(), kernel.ChromaticSpectrum.Blue.Kernel.ToArray());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(WaveOpticsColorMode.Primaries)]
|
||||
[InlineData(WaveOpticsColorMode.Broadband)]
|
||||
public void TheWavelengthIsNotPartOfTheKeyInAChromaticMode(WaveOpticsColorMode mode)
|
||||
{
|
||||
var kernel = new WaveOpticsKernel();
|
||||
Assert.True(kernel.TryUpdate(Psf(mode, 450f)));
|
||||
var version = kernel.Version;
|
||||
|
||||
Assert.True(kernel.TryUpdate(Psf(mode, 700f)));
|
||||
|
||||
Assert.Equal(version, kernel.Version);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheWavelengthIsPartOfTheKeyInTheMonochromeMode()
|
||||
{
|
||||
var kernel = new WaveOpticsKernel();
|
||||
Assert.True(kernel.TryUpdate(Psf(WaveOpticsColorMode.Monochrome, 450f)));
|
||||
var version = kernel.Version;
|
||||
|
||||
Assert.True(kernel.TryUpdate(Psf(WaveOpticsColorMode.Monochrome, 700f)));
|
||||
|
||||
Assert.NotEqual(version, kernel.Version);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangingTheModeRecomputesTheKernel()
|
||||
{
|
||||
var kernel = new WaveOpticsKernel();
|
||||
Assert.True(kernel.TryUpdate(Psf(WaveOpticsColorMode.Primaries)));
|
||||
var version = kernel.Version;
|
||||
|
||||
Assert.True(kernel.TryUpdate(Psf(WaveOpticsColorMode.Broadband)));
|
||||
var second = kernel.Version;
|
||||
Assert.True(kernel.TryUpdate(Psf(WaveOpticsColorMode.Monochrome)));
|
||||
|
||||
Assert.NotEqual(version, second);
|
||||
Assert.NotEqual(second, kernel.Version);
|
||||
Assert.False(kernel.IsChromatic);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ABladeCountOfACircularApertureIsNotPartOfTheKeyInAChromaticMode()
|
||||
{
|
||||
var kernel = new WaveOpticsKernel();
|
||||
Assert.True(kernel.TryUpdate(Psf(WaveOpticsColorMode.Primaries, blades: 5)));
|
||||
var version = kernel.Version;
|
||||
|
||||
Assert.True(kernel.TryUpdate(Psf(WaveOpticsColorMode.Primaries, blades: 9)));
|
||||
|
||||
Assert.Equal(version, kernel.Version);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheKeyOfAChromaticKernelIgnoresTheWavelengthOnly()
|
||||
{
|
||||
var first = WaveOpticsKernel.KeyOf(Psf(WaveOpticsColorMode.Primaries, 450f, defocus: 1f));
|
||||
var second = WaveOpticsKernel.KeyOf(Psf(WaveOpticsColorMode.Primaries, 700f, defocus: 1f));
|
||||
var third = WaveOpticsKernel.KeyOf(Psf(WaveOpticsColorMode.Primaries, 700f, defocus: 2f));
|
||||
|
||||
Assert.Equal(first, second);
|
||||
Assert.NotEqual(second, third);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AKernelThatCannotBeSampledIsInvalidAndStaysSoUntilTheKeyChanges()
|
||||
{
|
||||
var kernel = new WaveOpticsKernel();
|
||||
var closed = Psf(WaveOpticsColorMode.Primaries, shape: WaveOpticsApertureShape.RegularPolygon, blades: 4) with { Obstruction = 0.95f, Quality = WaveOpticsQuality.Draft, KernelRadius = 1 };
|
||||
Assert.True(kernel.TryUpdate(Psf(WaveOpticsColorMode.Primaries)));
|
||||
|
||||
var updated = kernel.TryUpdate(closed);
|
||||
|
||||
Assert.Equal(updated, kernel.IsValid);
|
||||
Assert.True(kernel.TryUpdate(Psf(WaveOpticsColorMode.Primaries)));
|
||||
Assert.True(kernel.IsValid);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,354 @@
|
||||
using ComputeWeave;
|
||||
using System.Runtime.InteropServices;
|
||||
using SpectralConvolution;
|
||||
using WaveOptics.Effects;
|
||||
using WaveOptics.Rendering;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
[Collection("Direct3D12")]
|
||||
public sealed class WaveOpticsLightTests
|
||||
{
|
||||
const int Black = unchecked((int)0xFF000000);
|
||||
const int White = unchecked((int)0xFFFFFFFF);
|
||||
|
||||
static WaveOpticsPipeline.Parameters Parameters(LightOptions light = default, float gain = 1f, float defocus = 0f, int kernelRadius = 15)
|
||||
=> new(gain, new WaveOpticsPipeline.PsfParameters(
|
||||
WaveOpticsQuality.Standard, kernelRadius, 550f, 8f, 4f, WaveOpticsApertureShape.Circular, 6, 0f, 0f, defocus, 0f, 0f, 0f, 0f, 0f), light);
|
||||
|
||||
static int[] Checkerboard(int width, int height)
|
||||
{
|
||||
var pixels = new int[width * height];
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
pixels[y * width + x] = (x + y & 1) == 0 ? White : Black;
|
||||
}
|
||||
|
||||
return pixels;
|
||||
}
|
||||
|
||||
static int[] BrightPoint(int width, int height)
|
||||
{
|
||||
var pixels = new int[width * height];
|
||||
Array.Fill(pixels, Black);
|
||||
pixels[(height / 2) * width + width / 2] = White;
|
||||
return pixels;
|
||||
}
|
||||
|
||||
static byte[] Bytes(int[] pixels) => MemoryMarshal.AsBytes(pixels.AsSpan()).ToArray();
|
||||
|
||||
static int GreenAt(int[] pixels, int width, int x, int y) => (pixels[y * width + x] >> 8) & 255;
|
||||
|
||||
static int LitCount(int[] pixels) => pixels.Count(pixel => ((pixel >> 8) & 255) > 0);
|
||||
|
||||
static int[] RenderGpu(int[] source, int width, int height, in WaveOpticsPipeline.Parameters parameters)
|
||||
{
|
||||
using var pipeline = WaveOpticsPipeline.TryCreate();
|
||||
Assert.NotNull(pipeline);
|
||||
var destination = new int[source.Length];
|
||||
pipeline.Process(source, destination, width, height, in parameters);
|
||||
return destination;
|
||||
}
|
||||
|
||||
static int[] RenderCpu(int[] source, int width, int height, in WaveOpticsPipeline.Parameters parameters)
|
||||
{
|
||||
using var pipeline = new WaveOpticsCpuPipeline(3);
|
||||
var destination = new int[source.Length];
|
||||
pipeline.Process(source, destination, width, height, in parameters);
|
||||
return destination;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LinearLightAveragesABlackAndWhiteCheckerboardByLightIntensity()
|
||||
{
|
||||
var source = Checkerboard(160, 160);
|
||||
var plain = Parameters(defocus: 3f, kernelRadius: 40);
|
||||
var linear = Parameters(new LightOptions(true, false, 0f, 0f), defocus: 3f, kernelRadius: 40);
|
||||
|
||||
foreach (var render in new Func<int[], WaveOpticsPipeline.Parameters, int[]>[]
|
||||
{
|
||||
(pixels, parameters) => RenderGpu(pixels, 160, 160, in parameters),
|
||||
(pixels, parameters) => RenderCpu(pixels, 160, 160, in parameters),
|
||||
})
|
||||
{
|
||||
var gamma = GreenAt(render(source, plain), 160, 80, 80);
|
||||
var light = GreenAt(render(source, linear), 160, 80, 80);
|
||||
|
||||
Assert.InRange(gamma, 116, 140);
|
||||
Assert.InRange(light, 176, 200);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HighlightsSpreadABrightPointFartherOnBothRoutes()
|
||||
{
|
||||
var source = BrightPoint(121, 121);
|
||||
var plain = Parameters(new LightOptions(true, false, 0f, 0f), kernelRadius: 20);
|
||||
var boosted = Parameters(new LightOptions(true, false, 0.9f, 400f), kernelRadius: 20);
|
||||
|
||||
var gpuPlain = LitCount(RenderGpu(source, 121, 121, in plain));
|
||||
var gpuBoosted = LitCount(RenderGpu(source, 121, 121, in boosted));
|
||||
var cpuPlain = LitCount(RenderCpu(source, 121, 121, in plain));
|
||||
var cpuBoosted = LitCount(RenderCpu(source, 121, 121, in boosted));
|
||||
|
||||
Assert.True(gpuBoosted > gpuPlain * 2, $"{gpuPlain} {gpuBoosted}");
|
||||
Assert.True(cpuBoosted > cpuPlain * 2, $"{cpuPlain} {cpuBoosted}");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false, true, 0f, 0f)]
|
||||
[InlineData(true, false, 0f, 0f)]
|
||||
[InlineData(true, true, 0.8f, 10f)]
|
||||
public void TheCpuAndTheGpuDrawTheSameLightImageWithinTwoLevels(bool linear, bool dither, float threshold, float boost)
|
||||
{
|
||||
var random = new Random(9);
|
||||
var source = new int[128 * 128];
|
||||
for (var index = 0; index < source.Length; index++)
|
||||
{
|
||||
if (random.NextDouble() < 0.25)
|
||||
{
|
||||
var value = random.Next(40, 256);
|
||||
source[index] = unchecked((int)(0xFF000000u | (uint)value << 16 | (uint)Math.Max(0, value - random.Next(60)) << 8 | (uint)Math.Max(0, value - random.Next(120))));
|
||||
}
|
||||
else
|
||||
source[index] = Black;
|
||||
}
|
||||
|
||||
var parameters = Parameters(new LightOptions(linear, dither, threshold, boost), 1.3f, 0.7f);
|
||||
|
||||
var expected = Bytes(RenderGpu(source, 128, 128, in parameters));
|
||||
var actual = Bytes(RenderCpu(source, 128, 128, in parameters));
|
||||
|
||||
for (var index = 0; index < expected.Length; index++)
|
||||
Assert.InRange(actual[index] - expected[index], -2, 2);
|
||||
Assert.Contains(actual, value => value > 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DitheringChangesTheOutputByAtMostOneLevelAndRepeats()
|
||||
{
|
||||
var source = BrightPoint(121, 121);
|
||||
var plain = Parameters(defocus: 1f);
|
||||
var dithered = Parameters(new LightOptions(false, true, 0f, 0f), defocus: 1f);
|
||||
|
||||
var rounded = Bytes(RenderCpu(source, 121, 121, in plain));
|
||||
var first = Bytes(RenderCpu(source, 121, 121, in dithered));
|
||||
var second = Bytes(RenderCpu(source, 121, 121, in dithered));
|
||||
|
||||
Assert.Equal(first, second);
|
||||
Assert.NotEqual(rounded, first);
|
||||
for (var index = 0; index < rounded.Length; index++)
|
||||
Assert.InRange(first[index] - rounded[index], -1, 1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangingOnlyTheDitherDrawsFromTheStoreAndMatchesAFreshConvolution()
|
||||
{
|
||||
using var pipeline = new WaveOpticsCpuPipeline(2);
|
||||
var source = Bytes(BrightPoint(96, 96));
|
||||
var plain = Parameters(new LightOptions(true, false, 0.9f, 30f), defocus: 0.5f);
|
||||
pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in plain);
|
||||
Assert.True(pipeline.TryGetVisibleBounds(128, 128, in plain, out var rect));
|
||||
pipeline.RenderVisible(rect, in plain);
|
||||
|
||||
foreach (var dither in new[] { true, false, true })
|
||||
{
|
||||
var changed = plain with { Light = plain.Light with { Dither = dither } };
|
||||
Assert.False(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in changed));
|
||||
var reused = pipeline.RenderVisible(rect, in changed).ToArray();
|
||||
using var fresh = new WaveOpticsCpuPipeline(2);
|
||||
fresh.Simulate(source, 128, 128, 16, 16, 96, 96, in changed);
|
||||
fresh.TryGetVisibleBounds(128, 128, in changed, out var freshRect);
|
||||
var expected = fresh.RenderVisible(freshRect, in changed).ToArray();
|
||||
|
||||
Assert.True(pipeline.HasStore);
|
||||
Assert.Equal(expected, reused);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheConvolutionIsRecomputedOnlyWhenTheLightSettingsAffectTheInput()
|
||||
{
|
||||
using var pipeline = new WaveOpticsCpuPipeline(2);
|
||||
var source = Bytes(BrightPoint(96, 96));
|
||||
var parameters = Parameters();
|
||||
|
||||
Assert.True(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in parameters));
|
||||
var dither = parameters with { Light = new LightOptions(false, true, 0.9f, 20f) };
|
||||
Assert.False(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in dither));
|
||||
var linear = parameters with { Light = new LightOptions(true, false, 0.9f, 20f) };
|
||||
Assert.True(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in linear));
|
||||
var dithered = linear with { Light = linear.Light with { Dither = true } };
|
||||
Assert.False(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in dithered));
|
||||
var otherBoost = linear with { Light = linear.Light with { Boost = 40f } };
|
||||
Assert.True(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in otherBoost));
|
||||
var unusedBoost = otherBoost with { Light = new LightOptions(true, false, 0.9f, 1f) };
|
||||
Assert.True(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in unusedBoost));
|
||||
var unusedThreshold = unusedBoost with { Light = unusedBoost.Light with { Threshold = 0.5f } };
|
||||
Assert.False(pipeline.Simulate(source, 128, 128, 16, 16, 96, 96, in unusedThreshold));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheGpuRedrawsFromTheStoreWhenOnlyTheDitherChanges()
|
||||
{
|
||||
using var pipeline = WaveOpticsPipeline.TryCreate();
|
||||
Assert.NotNull(pipeline);
|
||||
var device = ComputeWeave.GraphicsDevice.GetDefault();
|
||||
var source = BrightPoint(96, 96);
|
||||
using var texture = device.AllocateReadWriteTexture2D<ComputeWeave.Bgra32, ComputeWeave.Float4>(96, 96);
|
||||
texture.CopyFrom(source.Select(pixel => new ComputeWeave.Bgra32 { PackedValue = unchecked((uint)pixel) }).ToArray());
|
||||
var plain = Parameters(new LightOptions(true, false, 0.9f, 30f), defocus: 0.5f);
|
||||
|
||||
int[] Draw(WaveOpticsPipeline.Parameters parameters, out bool convolved)
|
||||
{
|
||||
convolved = pipeline.Simulate(texture, 128, 128, 16, 16, 96, 96, in parameters);
|
||||
Assert.True(pipeline.TryGetVisibleBounds(128, 128, in parameters, out var rect));
|
||||
using var output = device.AllocateReadWriteTexture2D<ComputeWeave.Bgra32, ComputeWeave.Float4>(rect.Width, rect.Height);
|
||||
pipeline.RenderVisible(texture, output, rect, in parameters);
|
||||
var pixels = new ComputeWeave.Bgra32[rect.Width * rect.Height];
|
||||
output.CopyTo(pixels);
|
||||
return pixels.Select(pixel => unchecked((int)pixel.PackedValue)).ToArray();
|
||||
}
|
||||
|
||||
var first = Draw(plain, out var firstConvolved);
|
||||
Assert.False(pipeline.HasStore);
|
||||
var dithered = plain with { Light = plain.Light with { Dither = true } };
|
||||
var second = Draw(dithered, out var secondConvolved);
|
||||
Assert.True(pipeline.HasStore);
|
||||
var third = Draw(plain, out var thirdConvolved);
|
||||
var fourth = Draw(dithered, out var fourthConvolved);
|
||||
|
||||
Assert.True(firstConvolved);
|
||||
Assert.False(secondConvolved);
|
||||
Assert.False(thirdConvolved);
|
||||
Assert.False(fourthConvolved);
|
||||
Assert.NotEqual(first, second);
|
||||
Assert.Equal(first, third);
|
||||
Assert.Equal(second, fourth);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheGpuConvolutionIsRecomputedOnlyWhenTheLightSettingsAffectTheInput()
|
||||
{
|
||||
using var pipeline = WaveOpticsPipeline.TryCreate();
|
||||
Assert.NotNull(pipeline);
|
||||
var device = ComputeWeave.GraphicsDevice.GetDefault();
|
||||
var source = BrightPoint(96, 96);
|
||||
using var texture = device.AllocateReadWriteTexture2D<ComputeWeave.Bgra32, ComputeWeave.Float4>(96, 96);
|
||||
texture.CopyFrom(source.Select(pixel => new ComputeWeave.Bgra32 { PackedValue = unchecked((uint)pixel) }).ToArray());
|
||||
var parameters = Parameters();
|
||||
|
||||
Assert.True(pipeline.Simulate(texture, 128, 128, 16, 16, 96, 96, in parameters));
|
||||
var dither = parameters with { Light = new LightOptions(false, true, 0.9f, 20f) };
|
||||
Assert.False(pipeline.Simulate(texture, 128, 128, 16, 16, 96, 96, in dither));
|
||||
var linear = parameters with { Light = new LightOptions(true, false, 0.9f, 20f) };
|
||||
Assert.True(pipeline.Simulate(texture, 128, 128, 16, 16, 96, 96, in linear));
|
||||
var dithered = linear with { Light = linear.Light with { Dither = true } };
|
||||
Assert.False(pipeline.Simulate(texture, 128, 128, 16, 16, 96, 96, in dithered));
|
||||
var otherBoost = linear with { Light = linear.Light with { Boost = 40f } };
|
||||
Assert.True(pipeline.Simulate(texture, 128, 128, 16, 16, 96, 96, in otherBoost));
|
||||
var otherThreshold = otherBoost with { Light = otherBoost.Light with { Threshold = 0.5f } };
|
||||
Assert.True(pipeline.Simulate(texture, 128, 128, 16, 16, 96, 96, in otherThreshold));
|
||||
var unusedBoost = otherThreshold with { Light = new LightOptions(true, false, 0.9f, 1f) };
|
||||
Assert.True(pipeline.Simulate(texture, 128, 128, 16, 16, 96, 96, in unusedBoost));
|
||||
var unusedThreshold = unusedBoost with { Light = unusedBoost.Light with { Threshold = 0.5f } };
|
||||
Assert.False(pipeline.Simulate(texture, 128, 128, 16, 16, 96, 96, in unusedThreshold));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public void AStoredDitherUsesTheCanvasPositionOfTheVisibleRegion(bool linear)
|
||||
{
|
||||
using var pipeline = new WaveOpticsCpuPipeline(2);
|
||||
var source = Bytes(BrightPoint(96, 96));
|
||||
var plain = Parameters(new LightOptions(linear, false, 0f, 0f), 0.4f, 0.5f);
|
||||
pipeline.Simulate(source, 200, 200, 52, 52, 96, 96, in plain);
|
||||
Assert.True(pipeline.TryGetVisibleBounds(200, 200, in plain, out var rect));
|
||||
Assert.True(rect.X > 0 && rect.Y > 0);
|
||||
pipeline.RenderVisible(rect, in plain);
|
||||
|
||||
foreach (var dither in new[] { true, false, true })
|
||||
{
|
||||
var changed = plain with { Light = plain.Light with { Dither = dither } };
|
||||
pipeline.Simulate(source, 200, 200, 52, 52, 96, 96, in changed);
|
||||
var reused = pipeline.RenderVisible(rect, in changed).ToArray();
|
||||
using var fresh = new WaveOpticsCpuPipeline(2);
|
||||
fresh.Simulate(source, 200, 200, 52, 52, 96, 96, in changed);
|
||||
fresh.TryGetVisibleBounds(200, 200, in changed, out var freshRect);
|
||||
var expected = fresh.RenderVisible(freshRect, in changed).ToArray();
|
||||
|
||||
Assert.True(pipeline.HasStore);
|
||||
Assert.Equal(expected, reused);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AWarmLightPipelineAllocatesNoManagedMemory()
|
||||
{
|
||||
using var pipeline = WaveOpticsPipeline.TryCreate();
|
||||
Assert.NotNull(pipeline);
|
||||
var source = BrightPoint(64, 64);
|
||||
var destination = new int[source.Length];
|
||||
var parameters = Parameters(new LightOptions(true, true, 0.9f, 30f));
|
||||
for (var iteration = 0; iteration < 4; iteration++)
|
||||
pipeline.Process(source, destination, 64, 64, in parameters);
|
||||
GC.Collect();
|
||||
GC.WaitForPendingFinalizers();
|
||||
GC.Collect();
|
||||
|
||||
var minimum = long.MaxValue;
|
||||
for (var iteration = 0; iteration < 16; iteration++)
|
||||
{
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
pipeline.Process(source, destination, 64, 64, in parameters);
|
||||
minimum = Math.Min(minimum, GC.GetAllocatedBytesForCurrentThread() - before);
|
||||
}
|
||||
|
||||
Assert.Equal(0, minimum);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(2)]
|
||||
[InlineData(4)]
|
||||
public void DitheringKeepsTheTotalLightOfASmallSpot(int radius)
|
||||
{
|
||||
const int Size = 400;
|
||||
var source = new int[Size * Size];
|
||||
Array.Fill(source, Black);
|
||||
for (var y = 0; y < Size; y++)
|
||||
{
|
||||
for (var x = 0; x < Size; x++)
|
||||
{
|
||||
var dx = x - Size / 2 + 0.5;
|
||||
var dy = y - Size / 2 + 0.5;
|
||||
if (dx * dx + dy * dy <= radius * radius)
|
||||
source[y * Size + x] = White;
|
||||
}
|
||||
}
|
||||
|
||||
static double Total(int[] pixels)
|
||||
{
|
||||
var sum = 0d;
|
||||
for (var y = 100; y < 300; y++)
|
||||
{
|
||||
for (var x = 100; x < 300; x++)
|
||||
sum += GreenAt(pixels, Size, x, y);
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
var parameters = new WaveOpticsPipeline.Parameters(1f, new WaveOpticsPipeline.PsfParameters(
|
||||
WaveOpticsQuality.Standard, 63, 550f, 16f, 2f, WaveOpticsApertureShape.Circular, 6, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f));
|
||||
var dithered = parameters with { Light = new LightOptions(false, true, 0f, 0f) };
|
||||
|
||||
var reference = Total(source);
|
||||
var retainedWithoutDither = Total(RenderCpu(source, Size, Size, in parameters)) / reference;
|
||||
var retainedWithDither = Total(RenderCpu(source, Size, Size, in dithered)) / reference;
|
||||
|
||||
Assert.InRange(retainedWithoutDither, 0.88, 0.97);
|
||||
Assert.InRange(retainedWithDither, 0.97, 1.03);
|
||||
}
|
||||
}
|
||||
@@ -83,4 +83,39 @@ public sealed class WaveOpticsRenderTrackerTests
|
||||
Assert.NotEqual(First.SamplingKey, Second.SamplingKey);
|
||||
Assert.Equal(First.SamplingKey, (First with { Psf = Psf with { Defocus = 1f } }).SamplingKey);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangingTheDitherStoresLikeAGainChange()
|
||||
{
|
||||
var tracker = new WaveOpticsRenderTracker();
|
||||
tracker.Next(First, Rect, 1f, false, out _);
|
||||
|
||||
Assert.Equal(WaveOpticsRenderMode.ConvolveAndStore, tracker.Next(First, Rect, 1f, true, out _));
|
||||
Assert.True(tracker.HasStore);
|
||||
Assert.Equal(WaveOpticsRenderMode.Stored, tracker.Next(First, Rect, 1f, false, out _));
|
||||
Assert.Equal(WaveOpticsRenderMode.Stored, tracker.Next(First, Rect, 1f, false, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSameDitherWithoutAStoreConvolvesAgain()
|
||||
{
|
||||
var tracker = new WaveOpticsRenderTracker();
|
||||
tracker.Next(First, Rect, 1f, true, out _);
|
||||
|
||||
Assert.Equal(WaveOpticsRenderMode.Convolve, tracker.Next(First, Rect, 1f, true, out _));
|
||||
Assert.False(tracker.HasStore);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnotherLightSettingIsAnotherConvolution()
|
||||
{
|
||||
var tracker = new WaveOpticsRenderTracker();
|
||||
tracker.Next(First, Rect, 1f, out _);
|
||||
tracker.Next(First, Rect, 1.5f, out _);
|
||||
var light = First with { Light = new SpectralConvolution.LightOptions(true, false, 0.9f, 10f) };
|
||||
|
||||
Assert.Equal(WaveOpticsRenderMode.Convolve, tracker.Next(light, Rect, 1.5f, out var release));
|
||||
Assert.True(release);
|
||||
Assert.False(tracker.HasStore);
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,20 @@ public sealed class WaveOpticsSettingsTests
|
||||
public void ThePupilSpansAQuarterOfTheGrid(int gridSize, int diameter)
|
||||
=> Assert.Equal(diameter, WaveOpticsSettings.GetPupilDiameterSamples(gridSize));
|
||||
|
||||
[Theory]
|
||||
[InlineData(-5, -8, -4)]
|
||||
[InlineData(-4, -4, -4)]
|
||||
[InlineData(0, 0, 0)]
|
||||
[InlineData(1, 0, 4)]
|
||||
[InlineData(4, 4, 4)]
|
||||
[InlineData(15, 12, 16)]
|
||||
public void TheCanvasAlignsToMultiplesOfFour(int value, int down, int up)
|
||||
{
|
||||
Assert.Equal(4, WaveOpticsSettings.CanvasAlignment);
|
||||
Assert.Equal(down, WaveOpticsSettings.AlignDown(value));
|
||||
Assert.Equal(up, WaveOpticsSettings.AlignUp(value));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1, 3)]
|
||||
[InlineData(7, 15)]
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Intrinsics;
|
||||
using ComputeWeave;
|
||||
using WaveOptics.Effects;
|
||||
using WaveOptics.Rendering;
|
||||
@@ -70,4 +71,53 @@ public sealed class WaveOpticsSourceHashTests
|
||||
{
|
||||
Assert.Throws<ArgumentException>(() => WaveOpticsSourceHash.Compute(new byte[15], 0, 0, 2, 2));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1, 1, 0.0)]
|
||||
[InlineData(1, 5, 1.0)]
|
||||
[InlineData(7, 3, 0.5)]
|
||||
[InlineData(8, 4, 0.01)]
|
||||
[InlineData(9, 4, 0.3)]
|
||||
[InlineData(15, 6, 1.0)]
|
||||
[InlineData(16, 6, 0.0)]
|
||||
[InlineData(17, 3, 0.02)]
|
||||
[InlineData(63, 9, 0.6)]
|
||||
[InlineData(64, 9, 1.0)]
|
||||
[InlineData(1000, 7, 0.001)]
|
||||
[InlineData(1000, 7, 0.9)]
|
||||
public void TheVectorHashMatchesTheScalarOneBitForBit(int width, int height, double litFraction)
|
||||
{
|
||||
var pixels = RandomPixels(width, height, width * 31 + height, litFraction);
|
||||
var bytes = MemoryMarshal.AsBytes(pixels.AsSpan());
|
||||
|
||||
var expected = WaveOpticsSourceHash.ComputeScalar(bytes, 12, 7, width, height);
|
||||
var actual = WaveOpticsSourceHash.Compute(bytes, 12, 7, width, height);
|
||||
|
||||
Assert.Equal(expected, actual);
|
||||
if (Vector256.IsHardwareAccelerated)
|
||||
Assert.Equal(expected, WaveOpticsSourceHash.ComputeVector(bytes, 12, 7, width, height));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(19)]
|
||||
[InlineData(32)]
|
||||
public void ASingleLitPixelIsFoundWhereverItSits(int width)
|
||||
{
|
||||
const int Height = 3;
|
||||
for (var y = 0; y < Height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var pixels = new int[width * Height];
|
||||
pixels[y * width + x] = 0x01020304;
|
||||
var bytes = MemoryMarshal.AsBytes(pixels.AsSpan());
|
||||
|
||||
var expected = WaveOpticsSourceHash.ComputeScalar(bytes, 5, 9, width, Height);
|
||||
var actual = Vector256.IsHardwareAccelerated ? WaveOpticsSourceHash.ComputeVector(bytes, 5, 9, width, Height) : WaveOpticsSourceHash.Compute(bytes, 5, 9, width, Height);
|
||||
|
||||
Assert.Equal(expected, actual);
|
||||
Assert.Equal((1, 5 + x, 9 + y, 5 + x, 9 + y), (actual.LitCount, actual.MinimumX, actual.MinimumY, actual.MaximumX, actual.MaximumY));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Globalization;
|
||||
using System.Numerics;
|
||||
using System.Reflection;
|
||||
using System.Windows;
|
||||
using SpectralConvolution;
|
||||
using Vortice.Direct2D1;
|
||||
using WaveOptics.Effects;
|
||||
using WaveOptics.Rendering;
|
||||
using YukkuriMovieMaker.ItemEditor;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
|
||||
namespace WaveOptics.Tests;
|
||||
|
||||
public sealed class WaveOpticsVisibilityTests
|
||||
{
|
||||
const int Width = 96;
|
||||
const int Height = 96;
|
||||
const int Black = unchecked((int)0xFF000000);
|
||||
const int White = unchecked((int)0xFFFFFFFF);
|
||||
const int Gray = unchecked((int)0xFFCCCCCC);
|
||||
|
||||
sealed record Setting(
|
||||
float Gain, WaveOpticsQuality Quality, int KernelRadius, float Wavelength, float FNumber, float PixelPitch,
|
||||
WaveOpticsApertureShape Shape, int Blades, float Rotation, float Obstruction,
|
||||
float Defocus, float AstigmatismVertical, float AstigmatismOblique, float ComaHorizontal, float ComaVertical, float Spherical,
|
||||
bool Linear, bool Dither, float Threshold, float Boost, WaveOpticsColorMode ColorMode,
|
||||
bool UseDepth, float FocusDistance, float FocalLength);
|
||||
|
||||
static readonly DrawDescription Subject = new(new Vector3(0f, 0f, -500f), Vector2.Zero, Vector2.One, Vector3.Zero, Matrix4x4.Identity, InterpolationMode.Linear, 1d, false, []);
|
||||
|
||||
static readonly Dictionary<string, Func<Setting, Setting>> Variants = new()
|
||||
{
|
||||
[nameof(WaveOpticsEffect.Gain)] = s => s with { Gain = 2f },
|
||||
[nameof(WaveOpticsEffect.Linear)] = s => s with { Linear = !s.Linear },
|
||||
[nameof(WaveOpticsEffect.HighlightThreshold)] = s => s with { Threshold = 0.5f },
|
||||
[nameof(WaveOpticsEffect.HighlightBoost)] = s => s with { Boost = 10f },
|
||||
[nameof(WaveOpticsEffect.Dither)] = s => s with { Dither = true },
|
||||
[nameof(WaveOpticsEffect.ColorMode)] = s => s with { ColorMode = s.ColorMode == WaveOpticsColorMode.Monochrome ? WaveOpticsColorMode.Primaries : WaveOpticsColorMode.Monochrome },
|
||||
[nameof(WaveOpticsEffect.Wavelength)] = s => s with { Wavelength = 650f },
|
||||
[nameof(WaveOpticsEffect.FNumber)] = s => s with { FNumber = 20f },
|
||||
[nameof(WaveOpticsEffect.PixelPitch)] = s => s with { PixelPitch = 2.5f },
|
||||
[nameof(WaveOpticsEffect.KernelRadius)] = s => s with { KernelRadius = 20 },
|
||||
[nameof(WaveOpticsEffect.Quality)] = s => s with { Quality = WaveOpticsQuality.High },
|
||||
[nameof(WaveOpticsEffect.ApertureShape)] = s => s with { Shape = s.Shape == WaveOpticsApertureShape.Circular ? WaveOpticsApertureShape.RegularPolygon : WaveOpticsApertureShape.Circular },
|
||||
[nameof(WaveOpticsEffect.BladeCount)] = s => s with { Blades = 8 },
|
||||
[nameof(WaveOpticsEffect.BladeRotation)] = s => s with { Rotation = 30f },
|
||||
[nameof(WaveOpticsEffect.Obstruction)] = s => s with { Obstruction = 0.3f },
|
||||
[nameof(WaveOpticsEffect.Defocus)] = s => s with { Defocus = 0.5f },
|
||||
[nameof(WaveOpticsEffect.AstigmatismVertical)] = s => s with { AstigmatismVertical = 0.5f },
|
||||
[nameof(WaveOpticsEffect.AstigmatismOblique)] = s => s with { AstigmatismOblique = 0.5f },
|
||||
[nameof(WaveOpticsEffect.ComaHorizontal)] = s => s with { ComaHorizontal = 0.5f },
|
||||
[nameof(WaveOpticsEffect.ComaVertical)] = s => s with { ComaVertical = 0.5f },
|
||||
[nameof(WaveOpticsEffect.Spherical)] = s => s with { Spherical = 0.5f },
|
||||
[nameof(WaveOpticsEffect.UseDepth)] = s => s with { UseDepth = !s.UseDepth },
|
||||
[nameof(WaveOpticsEffect.FocusDistance)] = s => s with { FocusDistance = 1200f },
|
||||
[nameof(WaveOpticsEffect.FocalLength)] = s => s with { FocalLength = 80f },
|
||||
};
|
||||
|
||||
static IEnumerable<PropertyInfo> ParameterProperties
|
||||
=> typeof(WaveOpticsEffect).GetProperties().Where(property => property.GetCustomAttribute<DisplayAttribute>() is not null);
|
||||
|
||||
static int[] Scene()
|
||||
{
|
||||
var pixels = new int[Width * Height];
|
||||
Array.Fill(pixels, Black);
|
||||
pixels[Height / 2 * Width + Width / 2] = White;
|
||||
for (var y = 20; y < 26; y++)
|
||||
{
|
||||
for (var x = 20; x < 26; x++)
|
||||
pixels[y * Width + x] = Gray;
|
||||
}
|
||||
|
||||
return pixels;
|
||||
}
|
||||
|
||||
static float DefocusOf(Setting setting)
|
||||
=> setting.UseDepth
|
||||
? (float)WaveOpticsDepth.AddDefocus(setting.Defocus, Subject, setting.FocalLength, setting.FNumber, setting.FocusDistance, WaveOpticsDepth.ReferenceWavelength(setting.ColorMode, setting.Wavelength))
|
||||
: setting.Defocus;
|
||||
|
||||
static int[] Render(Setting setting)
|
||||
{
|
||||
var parameters = new WaveOpticsPipeline.Parameters(
|
||||
setting.Gain,
|
||||
new WaveOpticsPipeline.PsfParameters(
|
||||
setting.Quality, setting.KernelRadius, setting.Wavelength, setting.FNumber, setting.PixelPitch, setting.Shape, setting.Blades,
|
||||
setting.Rotation, setting.Obstruction, DefocusOf(setting), setting.AstigmatismVertical, setting.AstigmatismOblique,
|
||||
setting.ComaHorizontal, setting.ComaVertical, setting.Spherical, setting.ColorMode),
|
||||
new LightOptions(setting.Linear, setting.Dither, setting.Threshold, setting.Boost));
|
||||
var source = Scene();
|
||||
var destination = new int[source.Length];
|
||||
using var pipeline = new WaveOpticsCpuPipeline(2);
|
||||
pipeline.Process(source, destination, Width, Height, in parameters);
|
||||
return destination;
|
||||
}
|
||||
|
||||
static bool IsVisible(WaveOpticsEffect effect, string name)
|
||||
{
|
||||
var attribute = typeof(WaveOpticsEffect).GetProperty(name)!.GetCustomAttributes().OfType<ICustomVisibilityAttribute2>().SingleOrDefault();
|
||||
if (attribute is null)
|
||||
return true;
|
||||
|
||||
var binding = attribute.GetBinding(effect, effect);
|
||||
var value = typeof(WaveOpticsEffect).GetProperty(binding.Path.Path)!.GetValue(binding.Source);
|
||||
return (Visibility)binding.Converter.Convert(value, typeof(Visibility), null!, CultureInfo.InvariantCulture) == Visibility.Visible;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EveryParameterExceptAmountHasAVariantToTest()
|
||||
{
|
||||
var names = ParameterProperties.Select(property => property.Name).Where(name => name != nameof(WaveOpticsEffect.Amount)).Order().ToArray();
|
||||
|
||||
Assert.Equal(Variants.Keys.Order().ToArray(), names);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(WaveOpticsApertureShape.Circular, false, WaveOpticsColorMode.Monochrome, false)]
|
||||
[InlineData(WaveOpticsApertureShape.Circular, true, WaveOpticsColorMode.Monochrome, true)]
|
||||
[InlineData(WaveOpticsApertureShape.RegularPolygon, false, WaveOpticsColorMode.Monochrome, true)]
|
||||
[InlineData(WaveOpticsApertureShape.RegularPolygon, true, WaveOpticsColorMode.Monochrome, false)]
|
||||
[InlineData(WaveOpticsApertureShape.Circular, false, WaveOpticsColorMode.Primaries, true)]
|
||||
[InlineData(WaveOpticsApertureShape.RegularPolygon, true, WaveOpticsColorMode.Primaries, false)]
|
||||
[InlineData(WaveOpticsApertureShape.Circular, true, WaveOpticsColorMode.Broadband, true)]
|
||||
[InlineData(WaveOpticsApertureShape.RegularPolygon, false, WaveOpticsColorMode.Broadband, false)]
|
||||
public void AParameterIsShownExactlyWhenChangingItChangesTheOutput(WaveOpticsApertureShape shape, bool linear, WaveOpticsColorMode colorMode, bool useDepth)
|
||||
{
|
||||
var effect = new WaveOpticsEffect { ApertureShape = shape, Linear = linear, ColorMode = colorMode, UseDepth = useDepth };
|
||||
var baseline = new Setting(
|
||||
1f, WaveOpticsQuality.Standard, 31, 550f, 16f, 2f, shape, 6, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, linear, false, 0.9f, 30f, colorMode, useDepth, 1000f, 50f);
|
||||
var reference = Render(baseline);
|
||||
|
||||
foreach (var (name, variant) in Variants)
|
||||
{
|
||||
var changes = !reference.AsSpan().SequenceEqual(Render(variant(baseline)));
|
||||
|
||||
Assert.True(changes == IsVisible(effect, name), $"{name}: changes the output = {changes}, shown = {IsVisible(effect, name)}, shape = {shape}, linear = {linear}, color mode = {colorMode}, depth = {useDepth}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,13 @@ QualityDescription,,瞳関数とPSFを計算するFFT格子の大きさを指定
|
||||
QualityDraft,,高速,Draft,草稿,草稿,초안,Borrador,مسودة,Draf
|
||||
QualityStandard,,標準,Standard,标准,標準,표준,Estándar,قياسي,Standar
|
||||
QualityHigh,,高精度,High,高精度,高精度,높음,Alto,مرتفع,Tinggi
|
||||
DepthGroup,,奥行き,Depth,深度,深度,깊이,Profundidad,العمق,Kedalaman
|
||||
UseDepth,,奥行きを使う,Use Depth,使用深度,使用深度,깊이 사용,Usar profundidad,استخدام العمق,Gunakan Kedalaman
|
||||
UseDepthDescription,,アイテムのカメラからの距離と合焦距離の差から、デフォーカスを決めて波面収差のデフォーカスに加えます。,"Determines the defocus from the difference between the item's distance from the camera and the focus distance, and adds it to the wavefront aberration defocus.",根据项目与相机的距离和对焦距离之差确定离焦量,并加到波前像差的离焦上。,根據項目與相機的距離和對焦距離之差決定離焦量,並加到波前像差的離焦上。,아이템과 카메라의 거리와 초점을 맞추는 거리의 차이로 디포커스를 정하여 파면 수차의 디포커스에 더합니다.,"Determina el desenfoque a partir de la diferencia entre la distancia del elemento a la cámara y la distancia de enfoque, y lo suma al desenfoque de la aberración de frente de onda.",يحدد إزالة التركيز من الفرق بين بُعد العنصر عن الكاميرا ومسافة التركيز، ويضيفه إلى إزالة التركيز في انحراف جبهة الموجة.,"Menentukan defokus dari selisih antara jarak item ke kamera dan jarak fokus, lalu menambahkannya ke defokus aberasi muka gelombang."
|
||||
FocusDistance,,合焦距離,Focus Distance,对焦距离,對焦距離,합초 거리,Distancia de enfoque,مسافة التركيز,Jarak Fokus
|
||||
FocusDistanceDescription,,ピントが合う面の、カメラからの距離です。座標の1を1mmとして扱います。,Sets the distance from the camera to the plane in focus. One coordinate unit is treated as 1 mm.,设置对焦平面到相机的距离。坐标的1按1毫米处理。,設定對焦平面到相機的距離。座標的1視為1毫米。,초점이 맞는 면까지 카메라로부터의 거리를 설정합니다. 좌표 1을 1mm로 취급합니다.,Establece la distancia desde la cámara hasta el plano enfocado. Una unidad de coordenada equivale a 1 mm.,يضبط المسافة من الكاميرا إلى المستوى البؤري. تُعامل وحدة الإحداثيات الواحدة على أنها 1 مم.,Mengatur jarak dari kamera ke bidang yang fokus. Satu satuan koordinat dianggap 1 mm.
|
||||
FocalLength,,焦点距離,Focal Length,焦距,焦距,초점 거리,Distancia focal,البعد البؤري,Panjang Fokus
|
||||
FocalLengthDescription,,レンズの焦点距離です。大きいほど、奥行きによるデフォーカスが大きくなります。,"Sets the focal length of the lens. The larger it is, the larger the defocus caused by depth.",设置镜头的焦距。焦距越大,深度造成的离焦越大。,設定鏡頭的焦距。焦距越大,深度造成的離焦越大。,렌즈의 초점 거리를 설정합니다. 클수록 깊이에 따른 디포커스가 커집니다.,"Establece la distancia focal del objetivo. Cuanto mayor es, mayor es el desenfoque causado por la profundidad.",يضبط البعد البؤري للعدسة. كلما زاد، زاد إزالة التركيز الناتج عن العمق.,"Mengatur panjang fokus lensa. Semakin besar, semakin besar defokus akibat kedalaman."
|
||||
ApertureShape,,開口形状,Aperture Shape,光圈形状,光圈形狀,조리개 형태,Forma de apertura,شكل الفتحة,Bentuk Apertur
|
||||
ApertureShapeDescription,,瞳関数の外周形状を指定します。,Sets the outer shape of the pupil function.,设置瞳孔函数的外部形状。,設定瞳孔函數的外部形狀。,동공 함수의 외부 형태를 설정합니다.,Establece la forma exterior de la función pupilar.,يضبط الشكل الخارجي لدالة الحدقة.,Mengatur bentuk luar fungsi pupil.
|
||||
CircularAperture,,円形,Circular,圆形,圓形,원형,Circular,دائري,Melingkar
|
||||
@@ -48,3 +55,16 @@ TagLens,,レンズ,lens,镜头,鏡頭,렌즈,lente,العدسة,lensa
|
||||
TagPsf,,点像分布関数,point spread function,点扩散函数,點擴散函數,점 확산 함수,función de dispersión puntual,دالة انتشار النقطة,fungsi penyebaran titik
|
||||
TagOptics,,光学,optics,光学,光學,광학,óptica,البصريات,optik
|
||||
UpdateAvailableMessage,,新しいバージョン {0} が公開されています。,A new version {0} is available.,新版本 {0} 已发布。,新版本 {0} 已發布。,새 버전 {0}이(가) 공개되었습니다.,La nueva versión {0} ya está disponible.,تم إصدار نسخة جديدة {0}.,Versi baru {0} telah dirilis.
|
||||
Linear,,線形光,Linear Light,线性光,線性光,선형 광,Luz lineal,الضوء الخطي,Cahaya Linear
|
||||
LinearDescription,,畳み込みの前に画素の値を光の強さに比例する値へ直し、結果を表示用の値へ戻します。,"Converts pixel values to values proportional to light intensity before the convolution, and converts the result back for display.",在卷积前将像素值转换为与光强成正比的值,并将结果转换回显示值。,在卷積前將像素值轉換為與光強成正比的值,並將結果轉換回顯示值。,"컨볼루션 전에 픽셀 값을 빛의 세기에 비례하는 값으로 변환하고, 결과를 표시용 값으로 되돌립니다.",Convierte los valores de píxel en valores proporcionales a la intensidad de la luz antes de la convolución y devuelve el resultado a valores de visualización.,يحوّل قيم البكسل إلى قيم تتناسب مع شدة الضوء قبل الالتفاف، ثم يعيد النتيجة إلى قيم العرض.,"Mengubah nilai piksel menjadi nilai yang sebanding dengan intensitas cahaya sebelum konvolusi, lalu mengembalikan hasilnya ke nilai tampilan."
|
||||
HighlightThreshold,,ハイライト閾値,Highlight Threshold,高光阈值,高光閾值,하이라이트 임계값,Umbral de altas luces,عتبة الإضاءة العالية,Ambang Sorotan
|
||||
HighlightThresholdDescription,,線形光のとき、画素の最も明るいチャンネルがこの割合を超えると、ハイライトの持ち上げを始めます。,"In linear light, highlight boosting starts when the brightest channel of a pixel exceeds this level.",在线性光下,当像素最亮的通道超过此比例时,开始提升高光。,在線性光下,當像素最亮的通道超過此比例時,開始提升高光。,선형 광에서 픽셀의 가장 밝은 채널이 이 비율을 넘으면 하이라이트를 끌어올리기 시작합니다.,"En luz lineal, el realce de las altas luces comienza cuando el canal más brillante de un píxel supera este nivel.",في الضوء الخطي، يبدأ تعزيز الإضاءة العالية عندما تتجاوز أسطع قناة في البكسل هذا المستوى.,"Pada cahaya linear, peningkatan sorotan dimulai saat kanal paling terang suatu piksel melebihi tingkat ini."
|
||||
HighlightBoost,,ハイライト強度,Highlight Boost,高光强度,高光強度,하이라이트 강도,Intensidad de altas luces,شدة الإضاءة العالية,Intensitas Sorotan
|
||||
HighlightBoostDescription,,線形光のとき、しきい値を超えた画素の明るさを最大で何倍に持ち上げるかを指定します。1倍では持ち上げません。,"In linear light, sets the maximum factor by which pixels above the threshold are brightened. 1x applies no boost.",在线性光下,设置超过阈值的像素亮度最多提升的倍数。1倍时不提升。,在線性光下,設定超過閾值的像素亮度最多提升的倍數。1倍時不提升。,선형 광에서 임계값을 넘은 픽셀의 밝기를 최대 몇 배로 끌어올릴지 설정합니다. 1배에서는 끌어올리지 않습니다.,"En luz lineal, establece el factor máximo por el que se aclaran los píxeles por encima del umbral. Con 1x no se aplica realce.",في الضوء الخطي، يضبط أقصى عامل يتم به تفتيح البكسلات التي تتجاوز العتبة. عند 1x لا يُطبَّق أي تعزيز.,"Pada cahaya linear, mengatur faktor maksimum untuk mencerahkan piksel di atas ambang. Pada 1x tidak ada peningkatan."
|
||||
Dither,,ディザ,Dither,抖动,抖動,디더,Tramado,التنقيط,Dither
|
||||
DitherDescription,,出力を8ビットに丸めるとき、画素の位置だけで決まる揺らぎを加えます。段差が目立たなくなり、淡い光が失われにくくなります。,Adds a variation that depends only on pixel position when rounding the output to 8 bits. This hides banding and keeps faint light from being lost.,将输出舍入为8位时,加入仅由像素位置决定的扰动。这能减轻色阶断层,并避免微弱的光丢失。,將輸出捨入為8位元時,加入僅由像素位置決定的擾動。這能減輕色階斷層,並避免微弱的光流失。,출력을 8비트로 반올림할 때 픽셀 위치로만 결정되는 흔들림을 더합니다. 계조의 단차가 눈에 덜 띄고 옅은 빛이 사라지지 않습니다.,Añade una variación que depende solo de la posición del píxel al redondear la salida a 8 bits. Oculta el bandeo y evita que se pierda la luz tenue.,يضيف تغييرًا يعتمد على موضع البكسل فقط عند تقريب المخرجات إلى 8 بت. يخفي ذلك تدرج النطاقات ويمنع فقدان الضوء الخافت.,Menambahkan variasi yang hanya bergantung pada posisi piksel saat membulatkan keluaran ke 8 bit. Ini menyamarkan pita warna dan mencegah cahaya redup hilang.
|
||||
ColorMode,,色の扱い,Color Handling,颜色处理,顏色處理,색 처리,Tratamiento del color,معالجة اللون,Penanganan Warna
|
||||
ColorModeDescription,,単色は、全チャンネルを「波長」の単色光として計算します。三原色は、赤、緑、青を別の波長(610、550、465 nm)で、広帯域は各色を波長の幅で積分して計算し、縁に色ずれが出ます。どちらも収差は光路差を一定にして求め、「波長」は使いません。,"Monochrome calculates every channel as monochromatic light at the Wavelength. Primaries calculates red, green and blue at separate wavelengths (610, 550, 465 nm), and Broadband integrates each color over a band of wavelengths, so edges show color fringes. Both keep the optical path difference of the aberrations fixed and ignore Wavelength.",单色将所有通道按“波长”的单色光计算。三原色将红、绿、蓝按不同波长(610、550、465 nm)计算,宽带则对每种颜色在一段波长范围内积分,边缘会出现色差。两者都保持像差的光程差不变,并且不使用“波长”。,單色將所有通道依「波長」的單色光計算。三原色將紅、綠、藍依不同波長(610、550、465 nm)計算,寬頻則對每種顏色在一段波長範圍內積分,邊緣會出現色差。兩者都保持像差的光程差不變,並且不使用「波長」。,"단색은 모든 채널을 '파장'의 단색광으로 계산합니다. 삼원색은 빨강, 초록, 파랑을 서로 다른 파장(610, 550, 465 nm)으로, 광대역은 각 색을 파장 범위에 걸쳐 적분하여 계산하므로 가장자리에 색 번짐이 생깁니다. 둘 다 수차의 광경로차를 일정하게 유지하며 '파장'은 사용하지 않습니다.","Monocromo calcula todos los canales como luz monocromática de la longitud de onda indicada. Tres primarios calcula rojo, verde y azul con longitudes de onda distintas (610, 550, 465 nm), y Banda ancha integra cada color en un rango de longitudes de onda, por lo que los bordes muestran franjas de color. Ambos mantienen constante la diferencia de camino óptico de las aberraciones y no usan la longitud de onda.",أحادي اللون يحسب كل القنوات كضوء أحادي اللون بالطول الموجي المحدد. الأوليات الثلاثة تحسب الأحمر والأخضر والأزرق بأطوال موجية مختلفة (610 و550 و465 نانومتر)، والنطاق العريض يكامل كل لون على مدى من الأطوال الموجية، فتظهر حواف ملونة. كلاهما يُبقي فرق المسار البصري للزيوغ ثابتًا ولا يستخدم الطول الموجي.,"Monokromatik menghitung semua kanal sebagai cahaya monokromatik pada panjang gelombang yang ditentukan. Tiga primer menghitung merah, hijau, dan biru pada panjang gelombang berbeda (610, 550, 465 nm), dan Pita lebar mengintegrasikan setiap warna pada rentang panjang gelombang sehingga tepi menampilkan pinggiran warna. Keduanya menjaga selisih jalur optik aberasi tetap dan tidak menggunakan panjang gelombang."
|
||||
ColorModeMonochrome,,単色,Monochrome,单色,單色,단색,Monocromo,أحادي اللون,Monokromatik
|
||||
ColorModePrimaries,,三原色,Primaries,三原色,三原色,삼원색,Tres primarios,الأوليات الثلاثة,Tiga primer
|
||||
ColorModeBroadband,,広帯域,Broadband,宽带,寬頻,광대역,Banda ancha,نطاق عريض,Pita lebar
|
||||
|
@@ -0,0 +1,15 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace WaveOptics.Effects;
|
||||
|
||||
public enum WaveOpticsColorMode
|
||||
{
|
||||
[Display(Name = nameof(Texts.ColorModeMonochrome), ResourceType = typeof(Texts))]
|
||||
Monochrome,
|
||||
|
||||
[Display(Name = nameof(Texts.ColorModePrimaries), ResourceType = typeof(Texts))]
|
||||
Primaries,
|
||||
|
||||
[Display(Name = nameof(Texts.ColorModeBroadband), ResourceType = typeof(Texts))]
|
||||
Broadband,
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using System.Numerics;
|
||||
using WaveOptics.Optics;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
|
||||
namespace WaveOptics.Effects;
|
||||
|
||||
internal static class WaveOpticsDepth
|
||||
{
|
||||
public const float BasePerspectiveDistance = 1000f;
|
||||
public const double MinimumDistanceRatio = 1.001;
|
||||
const double PathDifferenceDivisor = 8d;
|
||||
const double Sqrt12 = 3.4641016151377544;
|
||||
const double MillimetresPerNanometre = 1e-6;
|
||||
|
||||
public static bool TryGetDistance(DrawDescription drawDescription, out double distance)
|
||||
{
|
||||
distance = 0d;
|
||||
var requested = drawDescription.PerspectiveDistance;
|
||||
var perspectiveDistance = requested > 0f ? requested.Value : BasePerspectiveDistance;
|
||||
var position = Vector4.Transform(new Vector4(drawDescription.Draw, 1f), drawDescription.Camera);
|
||||
var result = perspectiveDistance * (double)position.W - position.Z;
|
||||
if (!double.IsFinite(result) || result <= 0d)
|
||||
return false;
|
||||
|
||||
distance = result;
|
||||
return true;
|
||||
}
|
||||
|
||||
public static double ReferenceWavelength(WaveOpticsColorMode colorMode, double wavelength)
|
||||
=> colorMode == WaveOpticsColorMode.Monochrome ? wavelength : SpectralPlan.ReferenceWavelength;
|
||||
|
||||
public static double DefocusWaves(double focalLength, double fNumber, double focusDistance, double distance, double wavelength)
|
||||
{
|
||||
var minimum = focalLength * MinimumDistanceRatio;
|
||||
var focus = Math.Max(focusDistance, minimum);
|
||||
var subject = Math.Max(distance, minimum);
|
||||
var pathDifference = focalLength * focalLength / (PathDifferenceDivisor * fNumber * fNumber) * (subject - focus) / (subject * (focus - focalLength));
|
||||
return pathDifference / (Sqrt12 * wavelength * MillimetresPerNanometre);
|
||||
}
|
||||
|
||||
public static double AddDefocus(double defocus, DrawDescription drawDescription, double focalLength, double fNumber, double focusDistance, double wavelength)
|
||||
=> TryGetDistance(drawDescription, out var distance)
|
||||
? defocus + DefocusWaves(focalLength, fNumber, focusDistance, distance, wavelength)
|
||||
: defocus;
|
||||
}
|
||||
@@ -27,7 +27,33 @@ public sealed class WaveOpticsEffect : VideoEffectBase
|
||||
[AnimationSlider("F1", "%", 0, 400)]
|
||||
public Animation Gain { get; } = new(100, 0, 400);
|
||||
|
||||
[Display(GroupName = nameof(Texts.OutputGroup), Name = nameof(Texts.Linear), Description = nameof(Texts.LinearDescription), Order = 2, ResourceType = typeof(Texts))]
|
||||
[ToggleSlider]
|
||||
public bool Linear { get => _linear; set => Set(ref _linear, value); }
|
||||
private bool _linear;
|
||||
|
||||
[Display(GroupName = nameof(Texts.OutputGroup), Name = nameof(Texts.HighlightThreshold), Description = nameof(Texts.HighlightThresholdDescription), Order = 3, ResourceType = typeof(Texts))]
|
||||
[LinearLightVisible]
|
||||
[AnimationSlider("F1", "%", 0, 100)]
|
||||
public Animation HighlightThreshold { get; } = new(95, 0, 100);
|
||||
|
||||
[Display(GroupName = nameof(Texts.OutputGroup), Name = nameof(Texts.HighlightBoost), Description = nameof(Texts.HighlightBoostDescription), Order = 4, ResourceType = typeof(Texts))]
|
||||
[LinearLightVisible]
|
||||
[AnimationSlider("F1", "x", 1, 100)]
|
||||
public Animation HighlightBoost { get; } = new(1, 1, 1000);
|
||||
|
||||
[Display(GroupName = nameof(Texts.OutputGroup), Name = nameof(Texts.Dither), Description = nameof(Texts.DitherDescription), Order = 5, ResourceType = typeof(Texts))]
|
||||
[ToggleSlider]
|
||||
public bool Dither { get => _dither; set => Set(ref _dither, value); }
|
||||
private bool _dither;
|
||||
|
||||
[Display(GroupName = nameof(Texts.OpticsGroup), Name = nameof(Texts.ColorMode), Description = nameof(Texts.ColorModeDescription), Order = 9, ResourceType = typeof(Texts))]
|
||||
[EnumComboBox]
|
||||
public WaveOpticsColorMode ColorMode { get => _colorMode; set => Set(ref _colorMode, value); }
|
||||
private WaveOpticsColorMode _colorMode;
|
||||
|
||||
[Display(GroupName = nameof(Texts.OpticsGroup), Name = nameof(Texts.Wavelength), Description = nameof(Texts.WavelengthDescription), Order = 10, ResourceType = typeof(Texts))]
|
||||
[MonochromeVisible]
|
||||
[AnimationSlider("F1", "nm", 380, 780)]
|
||||
public Animation Wavelength { get; } = new(550, 380, 780);
|
||||
|
||||
@@ -51,12 +77,28 @@ public sealed class WaveOpticsEffect : VideoEffectBase
|
||||
public WaveOpticsQuality Quality { get => _quality; set => Set(ref _quality, value); }
|
||||
private WaveOpticsQuality _quality = WaveOpticsQuality.Standard;
|
||||
|
||||
[Display(GroupName = nameof(Texts.DepthGroup), Name = nameof(Texts.UseDepth), Description = nameof(Texts.UseDepthDescription), Order = 15, ResourceType = typeof(Texts))]
|
||||
[ToggleSlider]
|
||||
public bool UseDepth { get => _useDepth; set => Set(ref _useDepth, value); }
|
||||
private bool _useDepth;
|
||||
|
||||
[Display(GroupName = nameof(Texts.DepthGroup), Name = nameof(Texts.FocusDistance), Description = nameof(Texts.FocusDistanceDescription), Order = 16, ResourceType = typeof(Texts))]
|
||||
[DepthVisible]
|
||||
[AnimationSlider("F0", "mm", 100, 10000)]
|
||||
public Animation FocusDistance { get; } = new(1000, 10, 1000000);
|
||||
|
||||
[Display(GroupName = nameof(Texts.DepthGroup), Name = nameof(Texts.FocalLength), Description = nameof(Texts.FocalLengthDescription), Order = 17, ResourceType = typeof(Texts))]
|
||||
[DepthVisible]
|
||||
[AnimationSlider("F1", "mm", 10, 300)]
|
||||
public Animation FocalLength { get; } = new(50, 1, 1000);
|
||||
|
||||
[Display(GroupName = nameof(Texts.ApertureGroup), Name = nameof(Texts.ApertureShape), Description = nameof(Texts.ApertureShapeDescription), Order = 20, ResourceType = typeof(Texts))]
|
||||
[EnumComboBox]
|
||||
public WaveOpticsApertureShape ApertureShape { get => _apertureShape; set => Set(ref _apertureShape, value); }
|
||||
private WaveOpticsApertureShape _apertureShape;
|
||||
|
||||
[Display(GroupName = nameof(Texts.ApertureGroup), Name = nameof(Texts.BladeCount), Description = nameof(Texts.BladeCountDescription), Order = 21, ResourceType = typeof(Texts))]
|
||||
[PolygonApertureVisible]
|
||||
[TextBoxSlider("F0", "", 3, 16)]
|
||||
[Range(3, 32)]
|
||||
[DefaultValue(6)]
|
||||
@@ -64,6 +106,7 @@ public sealed class WaveOpticsEffect : VideoEffectBase
|
||||
private int _bladeCount = 6;
|
||||
|
||||
[Display(GroupName = nameof(Texts.ApertureGroup), Name = nameof(Texts.BladeRotation), Description = nameof(Texts.BladeRotationDescription), Order = 22, ResourceType = typeof(Texts))]
|
||||
[PolygonApertureVisible]
|
||||
[AnimationSlider("F1", "°", -180, 180)]
|
||||
public Animation BladeRotation { get; } = new(0, -360, 360);
|
||||
|
||||
@@ -113,5 +156,5 @@ public sealed class WaveOpticsEffect : VideoEffectBase
|
||||
}
|
||||
|
||||
protected override IEnumerable<IAnimatable> GetAnimatables()
|
||||
=> _animatables ??= [Amount, Gain, Wavelength, FNumber, PixelPitch, BladeRotation, Obstruction, Defocus, AstigmatismVertical, AstigmatismOblique, ComaHorizontal, ComaVertical, Spherical];
|
||||
=> _animatables ??= [Amount, Gain, HighlightThreshold, HighlightBoost, Wavelength, FNumber, PixelPitch, BladeRotation, Obstruction, Defocus, AstigmatismVertical, AstigmatismOblique, ComaHorizontal, ComaVertical, Spherical, FocusDistance, FocalLength];
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.ComponentModel;
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeGuard;
|
||||
using ComputeWeave;
|
||||
using SpectralConvolution;
|
||||
@@ -37,7 +38,6 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
private ID2D1Image? _outputCropOutput;
|
||||
private AffineTransform2D? _outputTransform;
|
||||
private ID2D1Image? _outputTransformOutput;
|
||||
private bool _isFirst = true;
|
||||
private bool _hasOutput;
|
||||
private bool _hasOutputOffset;
|
||||
private bool _hasCropRect;
|
||||
@@ -45,7 +45,8 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
private OutputKind _outputKind;
|
||||
private Vector2 _outputOffset;
|
||||
private Vector4 _cropRect;
|
||||
private float _amount;
|
||||
private float _appliedAmount = float.NaN;
|
||||
private readonly ID2D1Bitmap1 _sourceBitmap = new(IntPtr.Zero);
|
||||
private RenderState _renderState;
|
||||
|
||||
public WaveOpticsEffectProcessor(IGraphicsDevicesAndContext devices, WaveOpticsEffect item)
|
||||
@@ -108,35 +109,37 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
var length = effectDescription.ItemDuration.Frame;
|
||||
var fps = effectDescription.FPS;
|
||||
var amount = Sanitize(_item.Amount.GetValue(frame, length, fps) / 100d, 0, 1, 0);
|
||||
var wavelength = Sanitize(_item.Wavelength.GetValue(frame, length, fps), 380, 780, 550);
|
||||
var fNumber = Sanitize(_item.FNumber.GetValue(frame, length, fps), 0.5, 64, 8);
|
||||
var defocus = ResolveDefocus(effectDescription, wavelength, fNumber);
|
||||
var parameters = new WaveOpticsPipeline.Parameters(
|
||||
Sanitize(_item.Gain.GetValue(frame, length, fps) / 100d, 0, 4, 1),
|
||||
new WaveOpticsPipeline.PsfParameters(
|
||||
_item.Quality,
|
||||
Math.Clamp(_item.KernelRadius, WaveOpticsSettings.MinimumKernelRadius, WaveOpticsSettings.MaximumKernelRadius),
|
||||
Sanitize(_item.Wavelength.GetValue(frame, length, fps), 380, 780, 550),
|
||||
Sanitize(_item.FNumber.GetValue(frame, length, fps), 0.5, 64, 8),
|
||||
wavelength,
|
||||
fNumber,
|
||||
Sanitize(_item.PixelPitch.GetValue(frame, length, fps), 0.25, 100, 4),
|
||||
_item.ApertureShape,
|
||||
Math.Clamp(_item.BladeCount, 3, 32),
|
||||
Sanitize(_item.BladeRotation.GetValue(frame, length, fps), -360, 360, 0),
|
||||
Sanitize(_item.Obstruction.GetValue(frame, length, fps) / 100d, 0, 0.95, 0),
|
||||
Sanitize(_item.Defocus.GetValue(frame, length, fps), -10, 10, 0),
|
||||
Sanitize(_item.AstigmatismVertical.GetValue(frame, length, fps), -10, 10, 0),
|
||||
Sanitize(_item.AstigmatismOblique.GetValue(frame, length, fps), -10, 10, 0),
|
||||
Sanitize(_item.ComaHorizontal.GetValue(frame, length, fps), -10, 10, 0),
|
||||
Sanitize(_item.ComaVertical.GetValue(frame, length, fps), -10, 10, 0),
|
||||
Sanitize(_item.Spherical.GetValue(frame, length, fps), -10, 10, 0)));
|
||||
|
||||
if (_isFirst || _amount != amount)
|
||||
_effect.Amount = amount;
|
||||
defocus,
|
||||
SanitizeAberration(_item.AstigmatismVertical.GetValue(frame, length, fps)),
|
||||
SanitizeAberration(_item.AstigmatismOblique.GetValue(frame, length, fps)),
|
||||
SanitizeAberration(_item.ComaHorizontal.GetValue(frame, length, fps)),
|
||||
SanitizeAberration(_item.ComaVertical.GetValue(frame, length, fps)),
|
||||
SanitizeAberration(_item.Spherical.GetValue(frame, length, fps)),
|
||||
_item.ColorMode),
|
||||
new LightOptions(
|
||||
_item.Linear,
|
||||
_item.Dither,
|
||||
Sanitize(_item.HighlightThreshold.GetValue(frame, length, fps) / 100d, 0, 1, 0.95),
|
||||
Sanitize(_item.HighlightBoost.GetValue(frame, length, fps), 1, LightOptions.MaximumBoost, 1)));
|
||||
|
||||
ApplyAmount(amount);
|
||||
if (amount <= 0f)
|
||||
{
|
||||
_effect.Amount = 0f;
|
||||
_amount = amount;
|
||||
_isFirst = true;
|
||||
return effectDescription.DrawDescription;
|
||||
}
|
||||
|
||||
var bounds = _devices.DeviceContext.GetImageLocalBounds(input);
|
||||
var widthValue = Math.Ceiling((double)bounds.Right - bounds.Left);
|
||||
@@ -145,8 +148,7 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
!float.IsFinite(bounds.Left) || !float.IsFinite(bounds.Top) ||
|
||||
widthValue <= 0d || heightValue <= 0d)
|
||||
{
|
||||
_effect.Amount = 0f;
|
||||
_isFirst = true;
|
||||
ApplyAmount(0f);
|
||||
return effectDescription.DrawDescription;
|
||||
}
|
||||
|
||||
@@ -154,8 +156,7 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
var longSide = Math.Max(widthValue, heightValue);
|
||||
if ((WaveOpticsSettings.MaximumCanvasSize - longSide) / 2d < margin)
|
||||
{
|
||||
_effect.Amount = 0f;
|
||||
_isFirst = true;
|
||||
ApplyAmount(0f);
|
||||
return effectDescription.DrawDescription;
|
||||
}
|
||||
|
||||
@@ -169,7 +170,7 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
(int)heightValue + margin * 2);
|
||||
|
||||
EnsureGpu();
|
||||
var workload = WaveOpticsCompute.Workload(geometry.CanvasWidth, geometry.CanvasHeight, parameters.Psf.KernelRadius);
|
||||
var workload = WaveOpticsCompute.Workload(geometry.CanvasWidth, geometry.CanvasHeight, parameters.Psf.KernelRadius, parameters.Psf.ColorMode != WaveOpticsColorMode.Monochrome);
|
||||
var device = _pipeline is null ? null : _computeDevice;
|
||||
var decision = _guardian.Select(device, workload, _selfTest);
|
||||
if (decision.Reason is ComputeRouteReason.Pinned or ComputeRouteReason.SoftwareAdapter)
|
||||
@@ -182,9 +183,7 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
|
||||
if (outcome == FrameOutcome.PassThrough)
|
||||
{
|
||||
_effect.Amount = 0f;
|
||||
_amount = amount;
|
||||
_isFirst = true;
|
||||
ApplyAmount(0f);
|
||||
_hasRenderState = false;
|
||||
return effectDescription.DrawDescription;
|
||||
}
|
||||
@@ -205,8 +204,6 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
_hasOutputOffset = true;
|
||||
}
|
||||
_hasOutput = true;
|
||||
_amount = amount;
|
||||
_isFirst = false;
|
||||
return effectDescription.DrawDescription;
|
||||
}
|
||||
|
||||
@@ -245,7 +242,7 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
}
|
||||
|
||||
var kindChanged = _outputKind != OutputKind.Gpu;
|
||||
var renderState = new RenderState(parameters.Gain, rect);
|
||||
var renderState = new RenderState(parameters.Gain, parameters.Light.Dither, rect);
|
||||
if (convolutionChanged || outputChanged || kindChanged || !_hasOutput || !_hasRenderState || _renderState != renderState)
|
||||
{
|
||||
var count = pipeline.RenderVisible(resourceSet.GetSourceComputeBinding(), resourceSet.GetOutputComputeBinding(), rect, in parameters, _measurements);
|
||||
@@ -298,7 +295,7 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
return FrameOutcome.PassThrough;
|
||||
|
||||
var kindChanged = _outputKind != OutputKind.Cpu;
|
||||
var renderState = new RenderState(parameters.Gain, rect);
|
||||
var renderState = new RenderState(parameters.Gain, parameters.Light.Dither, rect);
|
||||
var outputChanged = false;
|
||||
if (convolutionChanged || kindChanged || !_hasOutput || !_hasRenderState || _renderState != renderState)
|
||||
{
|
||||
@@ -380,20 +377,47 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
var renderContext = _interopProvider!.RenderContext;
|
||||
using var borrow = _resourceSet!.BeginSourceExternalOperation();
|
||||
var previousTarget = renderContext.Target;
|
||||
using var sourceBitmap = new ID2D1Bitmap1(borrow.DangerousGetView().AddRefBitmap());
|
||||
renderContext.Target = sourceBitmap;
|
||||
renderContext.BeginDraw();
|
||||
renderContext.Clear(null);
|
||||
renderContext.DrawImage(
|
||||
input,
|
||||
new Vector2(-bounds.Left, -bounds.Top),
|
||||
null,
|
||||
InterpolationMode.NearestNeighbor,
|
||||
CompositeMode.SourceCopy);
|
||||
renderContext.EndDraw();
|
||||
renderContext.Target = previousTarget;
|
||||
var bitmapPointer = borrow.DangerousGetView().AddRefBitmap();
|
||||
_sourceBitmap.NativePointer = bitmapPointer;
|
||||
try
|
||||
{
|
||||
renderContext.Target = _sourceBitmap;
|
||||
renderContext.BeginDraw();
|
||||
renderContext.Clear(null);
|
||||
renderContext.DrawImage(
|
||||
input,
|
||||
new Vector2(-bounds.Left, -bounds.Top),
|
||||
null,
|
||||
InterpolationMode.NearestNeighbor,
|
||||
CompositeMode.SourceCopy);
|
||||
renderContext.EndDraw();
|
||||
renderContext.Target = previousTarget;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_sourceBitmap.NativePointer = IntPtr.Zero;
|
||||
Marshal.Release(bitmapPointer);
|
||||
}
|
||||
}
|
||||
|
||||
private float ResolveDefocus(EffectDescription effectDescription, double wavelength, double fNumber)
|
||||
{
|
||||
var frame = effectDescription.ItemPosition.Frame;
|
||||
var length = effectDescription.ItemDuration.Frame;
|
||||
var fps = effectDescription.FPS;
|
||||
var defocus = SanitizeAberration(_item.Defocus.GetValue(frame, length, fps));
|
||||
if (!_item.UseDepth)
|
||||
return defocus;
|
||||
|
||||
var focalLength = Sanitize(_item.FocalLength.GetValue(frame, length, fps), 1, 1000, 50);
|
||||
var focusDistance = Sanitize(_item.FocusDistance.GetValue(frame, length, fps), 10, 1000000, 1000);
|
||||
var referenceWavelength = WaveOpticsDepth.ReferenceWavelength(_item.ColorMode, wavelength);
|
||||
return SanitizeAberration(WaveOpticsDepth.AddDefocus(defocus, effectDescription.DrawDescription, focalLength, fNumber, focusDistance, referenceWavelength));
|
||||
}
|
||||
|
||||
private static float SanitizeAberration(double waves)
|
||||
=> Sanitize(waves, -WaveOpticsSettings.MaximumAberrationWaves, WaveOpticsSettings.MaximumAberrationWaves, 0);
|
||||
|
||||
private static float Sanitize(double value, double minimum, double maximum, double fallback)
|
||||
{
|
||||
if (!double.IsFinite(value))
|
||||
@@ -401,6 +425,15 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
return (float)Math.Clamp(value, minimum, maximum);
|
||||
}
|
||||
|
||||
private void ApplyAmount(float amount)
|
||||
{
|
||||
if (_appliedAmount == amount)
|
||||
return;
|
||||
|
||||
_effect!.Amount = amount;
|
||||
_appliedAmount = amount;
|
||||
}
|
||||
|
||||
private void ReleaseInterop()
|
||||
{
|
||||
if (_outputKind == OutputKind.Gpu)
|
||||
@@ -510,7 +543,6 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
_effect?.SetInput(0, null, true);
|
||||
_effect?.SetInput(1, null, true);
|
||||
_outputCrop?.SetInput(0, null, true);
|
||||
_isFirst = true;
|
||||
_hasOutput = false;
|
||||
_hasOutputOffset = false;
|
||||
_hasCropRect = false;
|
||||
@@ -565,5 +597,6 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
|
||||
private readonly record struct RenderState(
|
||||
float Gain,
|
||||
bool Dither,
|
||||
WaveOpticsPipeline.PixelRect Rect);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using System.Globalization;
|
||||
using System.Windows;
|
||||
using System.Windows.Data;
|
||||
using YukkuriMovieMaker.ItemEditor;
|
||||
|
||||
namespace WaveOptics.Effects;
|
||||
|
||||
internal abstract class PropertyVisibilityAttribute(string propertyName) : Attribute, ICustomVisibilityAttribute2
|
||||
{
|
||||
protected abstract bool IsVisible(object? value);
|
||||
|
||||
public Binding GetBinding(object item, object propertyOwner) => new(propertyName)
|
||||
{
|
||||
Source = item,
|
||||
Converter = new VisibilityConverter(IsVisible)
|
||||
};
|
||||
}
|
||||
|
||||
[AttributeUsage(AttributeTargets.Property)]
|
||||
internal sealed class PolygonApertureVisibleAttribute() : PropertyVisibilityAttribute(nameof(WaveOpticsEffect.ApertureShape))
|
||||
{
|
||||
protected override bool IsVisible(object? value) => value is WaveOpticsApertureShape.RegularPolygon;
|
||||
}
|
||||
|
||||
[AttributeUsage(AttributeTargets.Property)]
|
||||
internal sealed class LinearLightVisibleAttribute() : PropertyVisibilityAttribute(nameof(WaveOpticsEffect.Linear))
|
||||
{
|
||||
protected override bool IsVisible(object? value) => value is true;
|
||||
}
|
||||
|
||||
[AttributeUsage(AttributeTargets.Property)]
|
||||
internal sealed class DepthVisibleAttribute() : PropertyVisibilityAttribute(nameof(WaveOpticsEffect.UseDepth))
|
||||
{
|
||||
protected override bool IsVisible(object? value) => value is true;
|
||||
}
|
||||
|
||||
[AttributeUsage(AttributeTargets.Property)]
|
||||
internal sealed class MonochromeVisibleAttribute() : PropertyVisibilityAttribute(nameof(WaveOpticsEffect.ColorMode))
|
||||
{
|
||||
protected override bool IsVisible(object? value) => value is WaveOpticsColorMode.Monochrome;
|
||||
}
|
||||
|
||||
internal sealed class VisibilityConverter(Func<object?, bool> isVisible) : IValueConverter
|
||||
{
|
||||
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
|
||||
=> isVisible(value) ? Visibility.Visible : Visibility.Collapsed;
|
||||
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
|
||||
=> throw new NotSupportedException();
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
using SpectralConvolution;
|
||||
using WaveOptics.Abstractions;
|
||||
using WaveOptics.Effects;
|
||||
|
||||
namespace WaveOptics.Optics;
|
||||
|
||||
internal sealed class ChromaticKernelSampler
|
||||
{
|
||||
static readonly WorkerScratch[] Scratches = [.. Enumerable.Range(0, WorkerPool.Shared.Parallelism).Select(static _ => new WorkerScratch())];
|
||||
|
||||
readonly NodeJob job = new();
|
||||
double[][] contributions = [];
|
||||
|
||||
public bool TrySample(
|
||||
in PsfSpecification reference,
|
||||
WaveOpticsColorMode mode,
|
||||
WaveOpticsQuality quality,
|
||||
Span<double> red,
|
||||
Span<double> green,
|
||||
Span<double> blue)
|
||||
{
|
||||
if (red.Length != green.Length || red.Length != blue.Length)
|
||||
throw new ArgumentException(null, nameof(green));
|
||||
|
||||
var bands = SpectralPlan.For(mode, quality, IsAberrationFree(reference.Aberration));
|
||||
var items = 0;
|
||||
foreach (var nodes in bands)
|
||||
items += nodes.Length;
|
||||
if (contributions.Length < items)
|
||||
Array.Resize(ref contributions, items);
|
||||
var item = 0;
|
||||
for (var channel = 0; channel < SpectralPlan.ChannelCount; channel++)
|
||||
{
|
||||
for (var node = 0; node < bands[channel].Length; node++, item++)
|
||||
{
|
||||
if (contributions[item] is null || contributions[item].Length < red.Length)
|
||||
contributions[item] = new double[red.Length];
|
||||
job.Assign(item, channel, node);
|
||||
}
|
||||
}
|
||||
|
||||
job.Prepare(bands, in reference, contributions, red.Length);
|
||||
WorkerPool.Shared.Run(job, items);
|
||||
if (job.Failed)
|
||||
return false;
|
||||
|
||||
item = 0;
|
||||
for (var channel = 0; channel < SpectralPlan.ChannelCount; channel++)
|
||||
{
|
||||
var kernel = channel switch { 0 => red, 1 => green, _ => blue };
|
||||
for (var node = 0; node < bands[channel].Length; node++, item++)
|
||||
{
|
||||
var values = contributions[item];
|
||||
if (node == 0)
|
||||
{
|
||||
values.AsSpan(0, kernel.Length).CopyTo(kernel);
|
||||
continue;
|
||||
}
|
||||
|
||||
for (var index = 0; index < kernel.Length; index++)
|
||||
kernel[index] += values[index];
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool IsAberrationFree(WavefrontAberration aberration)
|
||||
=> aberration.DefocusWaves == 0d
|
||||
&& aberration.AstigmatismVerticalWaves == 0d
|
||||
&& aberration.AstigmatismObliqueWaves == 0d
|
||||
&& aberration.ComaHorizontalWaves == 0d
|
||||
&& aberration.ComaVerticalWaves == 0d
|
||||
&& aberration.TrefoilHorizontalWaves == 0d
|
||||
&& aberration.TrefoilVerticalWaves == 0d
|
||||
&& aberration.SphericalWaves == 0d;
|
||||
|
||||
sealed class WorkerScratch
|
||||
{
|
||||
public readonly FraunhoferKernelSampler Sampler = new();
|
||||
public readonly double[] Scales = new double[SpectralPlan.MaximumSamples];
|
||||
public double[] Kernel = [];
|
||||
}
|
||||
|
||||
sealed class NodeJob : IParallelJob
|
||||
{
|
||||
readonly int[] itemChannels = new int[SpectralPlan.ChannelCount * SpectralPlan.MaximumNodes];
|
||||
readonly int[] itemNodes = new int[SpectralPlan.ChannelCount * SpectralPlan.MaximumNodes];
|
||||
SpectralNode[][] bands = [];
|
||||
PsfSpecification reference;
|
||||
double[][] outputs = [];
|
||||
int area;
|
||||
int failed;
|
||||
|
||||
public bool Failed => Volatile.Read(ref failed) != 0;
|
||||
|
||||
public void Assign(int item, int channel, int node)
|
||||
{
|
||||
itemChannels[item] = channel;
|
||||
itemNodes[item] = node;
|
||||
}
|
||||
|
||||
public void Prepare(SpectralNode[][] plan, in PsfSpecification specification, double[][] buffers, int kernelArea)
|
||||
{
|
||||
bands = plan;
|
||||
reference = specification;
|
||||
outputs = buffers;
|
||||
area = kernelArea;
|
||||
failed = 0;
|
||||
}
|
||||
|
||||
public void Execute(int item, int worker)
|
||||
{
|
||||
if (Failed)
|
||||
return;
|
||||
|
||||
var node = bands[itemChannels[item]][itemNodes[item]];
|
||||
var scratch = Scratches[worker];
|
||||
if (scratch.Kernel.Length < area)
|
||||
scratch.Kernel = new double[area];
|
||||
var count = node.Samples.Length;
|
||||
for (var index = 0; index < count; index++)
|
||||
scratch.Scales[index] = node.Wavelength / node.Samples[index].Wavelength;
|
||||
var phaseScale = SpectralPlan.ReferenceWavelength / node.Wavelength;
|
||||
if (!scratch.Sampler.TryComputeIntensity(in reference, reference.PupilDiameterSamples * phaseScale, phaseScale, scratch.Scales.AsSpan(0, count)))
|
||||
{
|
||||
Volatile.Write(ref failed, 1);
|
||||
return;
|
||||
}
|
||||
|
||||
var output = outputs[item].AsSpan(0, area);
|
||||
output.Clear();
|
||||
var values = scratch.Kernel.AsSpan(0, area);
|
||||
foreach (var sample in node.Samples)
|
||||
{
|
||||
if (!scratch.Sampler.TrySampleKernel(in reference, node.Wavelength / sample.Wavelength, values))
|
||||
{
|
||||
Volatile.Write(ref failed, 1);
|
||||
return;
|
||||
}
|
||||
|
||||
for (var index = 0; index < area; index++)
|
||||
output[index] += sample.Weight * values[index];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,52 +4,79 @@ namespace WaveOptics.Optics;
|
||||
|
||||
internal sealed class FraunhoferKernelSampler
|
||||
{
|
||||
double[] real = [];
|
||||
double[] imaginary = [];
|
||||
readonly ComplexLines grid = new();
|
||||
readonly ComplexLines line = new();
|
||||
double[] intensity = [];
|
||||
double[] columnReal = [];
|
||||
double[] columnImaginary = [];
|
||||
bool[] sampledColumns = [];
|
||||
|
||||
public bool TrySample(in PsfSpecification specification, Span<double> kernel)
|
||||
=> TryComputeIntensity(in specification, specification.PupilDiameterSamples, 1d, [1d])
|
||||
&& TrySampleKernel(in specification, 1d, kernel);
|
||||
|
||||
public bool TryComputeIntensity(in PsfSpecification specification, double pupilDiameter, double phaseScale, ReadOnlySpan<double> positionScales)
|
||||
{
|
||||
var gridSize = specification.PupilGridSize;
|
||||
EnsureCapacity(gridSize);
|
||||
|
||||
var center = gridSize / 2;
|
||||
var reach = (int)(specification.PupilDiameterSamples / 2d);
|
||||
var reach = (int)(pupilDiameter / 2d);
|
||||
var firstRow = Math.Max(center - reach, 0);
|
||||
var lastRow = Math.Min(center + reach, gridSize - 1);
|
||||
if (FraunhoferPsfGenerator.BuildPupil(in specification, real, imaginary, firstRow, lastRow) == 0)
|
||||
EnsureCapacity(gridSize, lastRow - firstRow + 1);
|
||||
if (FraunhoferPsfGenerator.BuildPupil(in specification, pupilDiameter, phaseScale, grid.Real, grid.Imaginary, firstRow, lastRow, firstRow) == 0)
|
||||
return false;
|
||||
|
||||
for (var row = firstRow; row <= lastRow; row++)
|
||||
FastFourierTransform.Forward(real.AsSpan(row * gridSize, gridSize), imaginary.AsSpan(row * gridSize, gridSize));
|
||||
|
||||
MarkSampledColumns(in specification, center);
|
||||
for (var shiftedColumn = 0; shiftedColumn < gridSize; shiftedColumn++)
|
||||
{
|
||||
if (!sampledColumns[shiftedColumn])
|
||||
continue;
|
||||
|
||||
var column = (shiftedColumn + center) % gridSize;
|
||||
for (var row = 0; row < gridSize; row++)
|
||||
{
|
||||
var open = row >= firstRow && row <= lastRow;
|
||||
columnReal[row] = open ? real[row * gridSize + column] : 0d;
|
||||
columnImaginary[row] = open ? imaginary[row * gridSize + column] : 0d;
|
||||
}
|
||||
|
||||
FastFourierTransform.Forward(columnReal.AsSpan(0, gridSize), columnImaginary.AsSpan(0, gridSize));
|
||||
for (var row = 0; row < gridSize; row++)
|
||||
{
|
||||
var a = columnReal[row];
|
||||
var b = columnImaginary[row];
|
||||
intensity[(row + center) % gridSize * gridSize + shiftedColumn] = a * a + b * b;
|
||||
}
|
||||
var offset = (row - firstRow) * gridSize;
|
||||
FastFourierTransform.Forward(grid.Real.Slice(offset, gridSize), grid.Imaginary.Slice(offset, gridSize));
|
||||
}
|
||||
|
||||
var energy = FraunhoferPsfGenerator.SampleKernel(in specification, intensity, kernel);
|
||||
MarkSampledColumns(in specification, center, positionScales);
|
||||
for (var shiftedColumn = 0; shiftedColumn < gridSize; shiftedColumn++)
|
||||
{
|
||||
if (sampledColumns[shiftedColumn])
|
||||
TransformColumn(shiftedColumn, gridSize, firstRow, lastRow);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void TransformColumn(int shiftedColumn, int gridSize, int firstRow, int lastRow)
|
||||
{
|
||||
var center = gridSize / 2;
|
||||
var column = (shiftedColumn + center) % gridSize;
|
||||
GatherColumn(column, gridSize, firstRow, lastRow);
|
||||
|
||||
var columnReal = line.Real[..gridSize];
|
||||
var columnImaginary = line.Imaginary[..gridSize];
|
||||
FastFourierTransform.Forward(columnReal, columnImaginary);
|
||||
var split = gridSize - center;
|
||||
var destination = intensity.AsSpan(shiftedColumn * gridSize, gridSize);
|
||||
FraunhoferPsfGenerator.Power(columnReal[..split], columnImaginary[..split], destination[center..]);
|
||||
FraunhoferPsfGenerator.Power(columnReal[split..], columnImaginary[split..], destination[..center]);
|
||||
}
|
||||
|
||||
void GatherColumn(int column, int gridSize, int firstRow, int lastRow)
|
||||
{
|
||||
var real = grid.Real;
|
||||
var imaginary = grid.Imaginary;
|
||||
var columnReal = line.Real;
|
||||
var columnImaginary = line.Imaginary;
|
||||
columnReal[..firstRow].Clear();
|
||||
columnImaginary[..firstRow].Clear();
|
||||
for (var row = firstRow; row <= lastRow; row++)
|
||||
{
|
||||
var index = (row - firstRow) * gridSize + column;
|
||||
columnReal[row] = real[index];
|
||||
columnImaginary[row] = imaginary[index];
|
||||
}
|
||||
|
||||
columnReal.Slice(lastRow + 1, gridSize - lastRow - 1).Clear();
|
||||
columnImaginary.Slice(lastRow + 1, gridSize - lastRow - 1).Clear();
|
||||
}
|
||||
|
||||
public bool TrySampleKernel(in PsfSpecification specification, double positionScale, Span<double> kernel)
|
||||
{
|
||||
var energy = FraunhoferPsfGenerator.SampleKernelTransposed(in specification, intensity, kernel, positionScale);
|
||||
if (!double.IsFinite(energy) || energy <= 0)
|
||||
return false;
|
||||
|
||||
@@ -58,38 +85,35 @@ internal sealed class FraunhoferKernelSampler
|
||||
return true;
|
||||
}
|
||||
|
||||
void MarkSampledColumns(in PsfSpecification specification, int center)
|
||||
void MarkSampledColumns(in PsfSpecification specification, int center, ReadOnlySpan<double> positionScales)
|
||||
{
|
||||
var gridSize = specification.PupilGridSize;
|
||||
var focalPlaneSamplePitch = FraunhoferPsfGenerator.FocalPlaneSamplePitch(in specification);
|
||||
var kernelRadius = specification.KernelSize / 2;
|
||||
Array.Clear(sampledColumns, 0, gridSize);
|
||||
for (var index = 0; index < specification.KernelSize; index++)
|
||||
foreach (var positionScale in positionScales)
|
||||
{
|
||||
var position = FraunhoferPsfGenerator.SamplePosition(index, kernelRadius, center, specification.SensorPixelPitchMicrometers, focalPlaneSamplePitch);
|
||||
if (position < 0 || position > gridSize - 1)
|
||||
continue;
|
||||
for (var index = 0; index < specification.KernelSize; index++)
|
||||
{
|
||||
var position = FraunhoferPsfGenerator.SamplePosition(index, kernelRadius, center, specification.SensorPixelPitchMicrometers, focalPlaneSamplePitch, positionScale);
|
||||
if (position < 0 || position > gridSize - 1)
|
||||
continue;
|
||||
|
||||
var lower = (int)Math.Floor(position);
|
||||
sampledColumns[lower] = true;
|
||||
sampledColumns[Math.Min(lower + 1, gridSize - 1)] = true;
|
||||
var lower = (int)Math.Floor(position);
|
||||
sampledColumns[lower] = true;
|
||||
sampledColumns[Math.Min(lower + 1, gridSize - 1)] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void EnsureCapacity(int gridSize)
|
||||
void EnsureCapacity(int gridSize, int pupilRows)
|
||||
{
|
||||
var area = gridSize * gridSize;
|
||||
if (real.Length < area)
|
||||
{
|
||||
real = new double[area];
|
||||
imaginary = new double[area];
|
||||
grid.Ensure(pupilRows * gridSize);
|
||||
line.Ensure(gridSize);
|
||||
if (intensity.Length < area)
|
||||
intensity = new double[area];
|
||||
}
|
||||
if (columnReal.Length < gridSize)
|
||||
{
|
||||
columnReal = new double[gridSize];
|
||||
columnImaginary = new double[gridSize];
|
||||
if (sampledColumns.Length < gridSize)
|
||||
sampledColumns = new bool[gridSize];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -74,28 +74,36 @@ public sealed class FraunhoferPsfGenerator : IPsfGenerator
|
||||
}
|
||||
}
|
||||
|
||||
internal static int BuildPupil(in PsfSpecification specification, double[] real, double[] imaginary, int firstRow, int lastRow)
|
||||
internal static int BuildPupil(in PsfSpecification specification, Span<double> real, Span<double> imaginary, int firstRow, int lastRow)
|
||||
=> BuildPupil(in specification, specification.PupilDiameterSamples, 1d, real, imaginary, firstRow, lastRow);
|
||||
|
||||
internal static int BuildPupil(in PsfSpecification specification, double pupilDiameter, double phaseScale, Span<double> real, Span<double> imaginary, int firstRow, int lastRow, int storedFirstRow = 0)
|
||||
{
|
||||
var gridSize = specification.PupilGridSize;
|
||||
var center = gridSize / 2;
|
||||
var pupilRadius = specification.PupilDiameterSamples / 2d;
|
||||
var pupilRadius = pupilDiameter / 2d;
|
||||
var rotation = specification.BladeRotationDegrees * Math.PI / 180d;
|
||||
var openSampleCount = 0;
|
||||
var reach = (int)pupilRadius;
|
||||
var firstColumn = Math.Max(center - reach, 0);
|
||||
var lastColumn = Math.Min(center + reach, gridSize - 1);
|
||||
|
||||
for (var y = firstRow; y <= lastRow; y++)
|
||||
{
|
||||
var normalizedY = (y - center) / pupilRadius;
|
||||
var row = y * gridSize;
|
||||
for (var x = 0; x < gridSize; x++)
|
||||
var row = (y - storedFirstRow) * gridSize;
|
||||
real.Slice(row, firstColumn).Clear();
|
||||
imaginary.Slice(row, firstColumn).Clear();
|
||||
for (var x = firstColumn; x <= lastColumn; x++)
|
||||
{
|
||||
var index = row + x;
|
||||
var normalizedX = (x - center) / pupilRadius;
|
||||
if (IsInsideAperture(normalizedX, normalizedY, in specification, rotation))
|
||||
{
|
||||
var waves = ZernikeWavefront.Evaluate(normalizedX, normalizedY, specification.Aberration);
|
||||
var (sin, cos) = Math.SinCos(TwoPi * waves);
|
||||
real[index] = cos;
|
||||
imaginary[index] = sin;
|
||||
var waves = ZernikeWavefront.Evaluate(normalizedX, normalizedY, specification.Aberration) * phaseScale;
|
||||
var angle = TwoPi * waves;
|
||||
real[index] = Math.Cos(angle);
|
||||
imaginary[index] = Math.Sin(angle);
|
||||
openSampleCount++;
|
||||
}
|
||||
else
|
||||
@@ -104,6 +112,9 @@ public sealed class FraunhoferPsfGenerator : IPsfGenerator
|
||||
imaginary[index] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
real.Slice(row + lastColumn + 1, gridSize - lastColumn - 1).Clear();
|
||||
imaginary.Slice(row + lastColumn + 1, gridSize - lastColumn - 1).Clear();
|
||||
}
|
||||
|
||||
return openSampleCount;
|
||||
@@ -115,26 +126,135 @@ public sealed class FraunhoferPsfGenerator : IPsfGenerator
|
||||
return wavelengthMicrometers * specification.FNumber * specification.PupilDiameterSamples / specification.PupilGridSize;
|
||||
}
|
||||
|
||||
internal static double SamplePosition(int index, int kernelRadius, int center, double pixelPitch, double focalPlaneSamplePitch)
|
||||
=> center + (index - kernelRadius) * pixelPitch / focalPlaneSamplePitch;
|
||||
internal static double SamplePosition(int index, int kernelRadius, int center, double pixelPitch, double focalPlaneSamplePitch, double positionScale = 1d)
|
||||
=> center + (index - kernelRadius) * pixelPitch / focalPlaneSamplePitch * positionScale;
|
||||
|
||||
internal static double SampleKernel(in PsfSpecification specification, double[] intensity, Span<double> kernel)
|
||||
static void PrepareSamples(in PsfSpecification specification, double positionScale, Span<double> positions, Span<int> lower, Span<int> upper, Span<double> fractions)
|
||||
{
|
||||
var gridSize = specification.PupilGridSize;
|
||||
var focalPlaneSamplePitch = FocalPlaneSamplePitch(in specification);
|
||||
var center = gridSize / 2;
|
||||
var kernelRadius = specification.KernelSize / 2;
|
||||
for (var index = 0; index < positions.Length; index++)
|
||||
{
|
||||
var position = SamplePosition(index, kernelRadius, center, specification.SensorPixelPitchMicrometers, focalPlaneSamplePitch, positionScale);
|
||||
positions[index] = position;
|
||||
if (position < 0 || position > gridSize - 1)
|
||||
continue;
|
||||
|
||||
var floor = (int)Math.Floor(position);
|
||||
lower[index] = floor;
|
||||
upper[index] = Math.Min(floor + 1, gridSize - 1);
|
||||
fractions[index] = position - floor;
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
static double Blend(double upperLeft, double upperRight, double lowerLeft, double lowerRight, double tx, double ty)
|
||||
{
|
||||
var top = upperLeft * (1 - tx) + upperRight * tx;
|
||||
var bottom = lowerLeft * (1 - tx) + lowerRight * tx;
|
||||
return top * (1 - ty) + bottom * ty;
|
||||
}
|
||||
|
||||
internal static double SampleKernelTransposed(in PsfSpecification specification, double[] intensity, Span<double> kernel, double positionScale = 1d)
|
||||
{
|
||||
var gridSize = specification.PupilGridSize;
|
||||
var kernelSize = specification.KernelSize;
|
||||
var kernelRadius = kernelSize / 2;
|
||||
|
||||
Span<double> positions = stackalloc double[kernelSize];
|
||||
Span<int> lower = stackalloc int[kernelSize];
|
||||
Span<int> upper = stackalloc int[kernelSize];
|
||||
Span<double> fractions = stackalloc double[kernelSize];
|
||||
PrepareSamples(in specification, positionScale, positions, lower, upper, fractions);
|
||||
|
||||
for (var x = 0; x < kernelSize; x++)
|
||||
{
|
||||
var sampleX = positions[x];
|
||||
var insideX = sampleX >= 0 && sampleX <= gridSize - 1;
|
||||
var leftColumn = lower[x] * gridSize;
|
||||
var rightColumn = upper[x] * gridSize;
|
||||
var tx = fractions[x];
|
||||
for (var y = 0; y < kernelSize; y++)
|
||||
{
|
||||
var sampleY = positions[y];
|
||||
if (!insideX || sampleY < 0 || sampleY > gridSize - 1)
|
||||
{
|
||||
kernel[y * kernelSize + x] = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
var top = lower[y];
|
||||
var bottom = upper[y];
|
||||
kernel[y * kernelSize + x] = Blend(
|
||||
intensity[leftColumn + top],
|
||||
intensity[rightColumn + top],
|
||||
intensity[leftColumn + bottom],
|
||||
intensity[rightColumn + bottom],
|
||||
tx,
|
||||
fractions[y]);
|
||||
}
|
||||
}
|
||||
|
||||
var first = kernelSize;
|
||||
var last = -1;
|
||||
for (var index = 0; index < kernelSize; index++)
|
||||
{
|
||||
if (positions[index] < 0 || positions[index] > gridSize - 1)
|
||||
continue;
|
||||
|
||||
first = Math.Min(first, index);
|
||||
last = index;
|
||||
}
|
||||
|
||||
var rawKernelEnergy = 0d;
|
||||
for (var y = first; y <= last; y++)
|
||||
{
|
||||
for (var x = first; x <= last; x++)
|
||||
rawKernelEnergy += kernel[y * kernelSize + x];
|
||||
}
|
||||
|
||||
return rawKernelEnergy;
|
||||
}
|
||||
|
||||
internal static double SampleKernel(in PsfSpecification specification, double[] intensity, Span<double> kernel, double positionScale = 1d)
|
||||
{
|
||||
var gridSize = specification.PupilGridSize;
|
||||
var kernelSize = specification.KernelSize;
|
||||
var rawKernelEnergy = 0d;
|
||||
|
||||
Span<double> positions = stackalloc double[kernelSize];
|
||||
Span<int> lower = stackalloc int[kernelSize];
|
||||
Span<int> upper = stackalloc int[kernelSize];
|
||||
Span<double> fractions = stackalloc double[kernelSize];
|
||||
PrepareSamples(in specification, positionScale, positions, lower, upper, fractions);
|
||||
|
||||
for (var y = 0; y < kernelSize; y++)
|
||||
{
|
||||
var sampleY = SamplePosition(y, kernelRadius, center, specification.SensorPixelPitchMicrometers, focalPlaneSamplePitch);
|
||||
var row = kernel.Slice(y * kernelSize, kernelSize);
|
||||
var sampleY = positions[y];
|
||||
if (sampleY < 0 || sampleY > gridSize - 1)
|
||||
{
|
||||
row.Clear();
|
||||
continue;
|
||||
}
|
||||
|
||||
var topRow = lower[y] * gridSize;
|
||||
var bottomRow = upper[y] * gridSize;
|
||||
var ty = fractions[y];
|
||||
for (var x = 0; x < kernelSize; x++)
|
||||
{
|
||||
var sampleX = SamplePosition(x, kernelRadius, center, specification.SensorPixelPitchMicrometers, focalPlaneSamplePitch);
|
||||
var value = SampleBilinear(intensity, gridSize, sampleX, sampleY);
|
||||
kernel[y * kernelSize + x] = value;
|
||||
var sampleX = positions[x];
|
||||
if (sampleX < 0 || sampleX > gridSize - 1)
|
||||
{
|
||||
row[x] = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
var left = lower[x];
|
||||
var right = upper[x];
|
||||
var value = Blend(intensity[topRow + left], intensity[topRow + right], intensity[bottomRow + left], intensity[bottomRow + right], fractions[x], ty);
|
||||
row[x] = value;
|
||||
rawKernelEnergy += value;
|
||||
}
|
||||
}
|
||||
@@ -162,7 +282,7 @@ public sealed class FraunhoferPsfGenerator : IPsfGenerator
|
||||
return fullEnergy;
|
||||
}
|
||||
|
||||
static double Power(ReadOnlySpan<double> real, ReadOnlySpan<double> imaginary, Span<double> intensity)
|
||||
internal static double Power(ReadOnlySpan<double> real, ReadOnlySpan<double> imaginary, Span<double> intensity)
|
||||
{
|
||||
var count = real.Length;
|
||||
ref var realBase = ref MemoryMarshal.GetReference(real);
|
||||
@@ -206,7 +326,7 @@ public sealed class FraunhoferPsfGenerator : IPsfGenerator
|
||||
return peak;
|
||||
}
|
||||
|
||||
static bool IsInsideAperture(double x, double y, in PsfSpecification specification, double rotation)
|
||||
internal static bool IsInsideAperture(double x, double y, in PsfSpecification specification, double rotation)
|
||||
{
|
||||
var radiusSquared = x * x + y * y;
|
||||
var obstructionSquared = specification.CentralObstructionRatio * specification.CentralObstructionRatio;
|
||||
@@ -224,20 +344,4 @@ public sealed class FraunhoferPsfGenerator : IPsfGenerator
|
||||
var boundary = Math.Cos(Math.PI / specification.BladeCount) / Math.Cos(folded);
|
||||
return radius <= boundary;
|
||||
}
|
||||
|
||||
static double SampleBilinear(double[] values, int size, double x, double y)
|
||||
{
|
||||
if (x < 0 || y < 0 || x > size - 1 || y > size - 1)
|
||||
return 0;
|
||||
|
||||
var x0 = (int)Math.Floor(x);
|
||||
var y0 = (int)Math.Floor(y);
|
||||
var x1 = Math.Min(x0 + 1, size - 1);
|
||||
var y1 = Math.Min(y0 + 1, size - 1);
|
||||
var tx = x - x0;
|
||||
var ty = y - y0;
|
||||
var top = values[y0 * size + x0] * (1 - tx) + values[y0 * size + x1] * tx;
|
||||
var bottom = values[y1 * size + x0] * (1 - tx) + values[y1 * size + x1] * tx;
|
||||
return top * (1 - ty) + bottom * ty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
namespace WaveOptics.Optics;
|
||||
|
||||
internal sealed class PsfScratch
|
||||
{
|
||||
public FraunhoferKernelSampler Sampler { get; } = new();
|
||||
|
||||
public ChromaticKernelSampler ChromaticSampler { get; } = new();
|
||||
|
||||
public double[] Green { get; private set; } = [];
|
||||
|
||||
public double[] Red { get; private set; } = [];
|
||||
|
||||
public double[] Blue { get; private set; } = [];
|
||||
|
||||
public void Ensure(int area, bool chromatic)
|
||||
{
|
||||
if (Green.Length < area)
|
||||
Green = new double[area];
|
||||
if (!chromatic)
|
||||
return;
|
||||
|
||||
if (Red.Length < area)
|
||||
Red = new double[area];
|
||||
if (Blue.Length < area)
|
||||
Blue = new double[area];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
using WaveOptics.Effects;
|
||||
|
||||
namespace WaveOptics.Optics;
|
||||
|
||||
internal readonly record struct SpectralSample(double Wavelength, double Weight);
|
||||
|
||||
internal readonly record struct SpectralNode(double Wavelength, SpectralSample[] Samples);
|
||||
|
||||
internal static class SpectralPlan
|
||||
{
|
||||
public const double ReferenceWavelength = 550d;
|
||||
public const double RedWavelength = 610d;
|
||||
public const double GreenWavelength = 550d;
|
||||
public const double BlueWavelength = 465d;
|
||||
public const double BandSigma = 21d;
|
||||
public const double BandSpan = 2.5;
|
||||
public const int ChannelCount = 3;
|
||||
public const int MaximumSamples = 27;
|
||||
public const int MaximumNodes = 5;
|
||||
|
||||
static readonly SpectralNode[][] Primaries =
|
||||
[
|
||||
[new(RedWavelength, [new(RedWavelength, 1d)])],
|
||||
[new(GreenWavelength, [new(GreenWavelength, 1d)])],
|
||||
[new(BlueWavelength, [new(BlueWavelength, 1d)])],
|
||||
];
|
||||
|
||||
static readonly SpectralNode[][][] Broadband =
|
||||
[
|
||||
Bands(1, 25),
|
||||
Bands(3, 9),
|
||||
Bands(5, 5),
|
||||
];
|
||||
|
||||
public static SpectralNode[][] For(WaveOpticsColorMode mode, WaveOpticsQuality quality, bool aberrationFree)
|
||||
=> mode switch
|
||||
{
|
||||
WaveOpticsColorMode.Primaries => Primaries,
|
||||
WaveOpticsColorMode.Broadband => Broadband[aberrationFree ? (int)WaveOpticsQuality.Draft : (int)quality],
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(mode)),
|
||||
};
|
||||
|
||||
public static int SampleCount(SpectralNode[] nodes)
|
||||
{
|
||||
var count = 0;
|
||||
foreach (var node in nodes)
|
||||
count += node.Samples.Length;
|
||||
return count;
|
||||
}
|
||||
|
||||
static SpectralNode[][] Bands(int nodeCount, int samplesPerNode)
|
||||
=> [Band(RedWavelength, nodeCount, samplesPerNode), Band(GreenWavelength, nodeCount, samplesPerNode), Band(BlueWavelength, nodeCount, samplesPerNode)];
|
||||
|
||||
static SpectralNode[] Band(double center, int nodeCount, int samplesPerNode)
|
||||
{
|
||||
var total = nodeCount * samplesPerNode;
|
||||
var samples = new SpectralSample[total];
|
||||
var sum = 0d;
|
||||
for (var index = 0; index < total; index++)
|
||||
{
|
||||
var offset = -BandSpan + (index + 0.5) * 2d * BandSpan / total;
|
||||
var weight = Math.Exp(-0.5 * offset * offset);
|
||||
samples[index] = new SpectralSample(center + BandSigma * offset, weight);
|
||||
sum += weight;
|
||||
}
|
||||
|
||||
var nodes = new SpectralNode[nodeCount];
|
||||
for (var node = 0; node < nodeCount; node++)
|
||||
{
|
||||
var group = samples.AsSpan(node * samplesPerNode, samplesPerNode).ToArray();
|
||||
for (var index = 0; index < group.Length; index++)
|
||||
group[index] = group[index] with { Weight = group[index].Weight / sum };
|
||||
nodes[node] = new SpectralNode(group[samplesPerNode / 2].Wavelength, group);
|
||||
}
|
||||
|
||||
return nodes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using ComputeWeave;
|
||||
using SpectralConvolution;
|
||||
|
||||
namespace WaveOptics.Rendering;
|
||||
|
||||
internal static class SourceHashMath
|
||||
{
|
||||
public const uint IndexMultiplier = 0x9E3779B9u;
|
||||
public const uint MixMultiplier = 0x85EBCA6Bu;
|
||||
public const uint AccumulateMultiplier = 0xC2B2AE35u;
|
||||
public const int FirstShift = 16;
|
||||
public const int SecondShift = 13;
|
||||
|
||||
public static uint Quantize(Float4 color)
|
||||
=> ByteColor.ToLevel(color.X) << 3 * ByteColor.Bits
|
||||
| ByteColor.ToLevel(color.Y) << 2 * ByteColor.Bits
|
||||
| ByteColor.ToLevel(color.Z) << ByteColor.Bits
|
||||
| ByteColor.ToLevel(color.W);
|
||||
|
||||
public static uint Mixed(int index, uint quantized)
|
||||
{
|
||||
var mixed = (uint)index * IndexMultiplier ^ quantized * MixMultiplier;
|
||||
mixed ^= mixed >> FirstShift;
|
||||
mixed *= MixMultiplier;
|
||||
mixed ^= mixed >> SecondShift;
|
||||
return mixed;
|
||||
}
|
||||
}
|
||||
@@ -19,10 +19,10 @@ internal static class WaveOpticsCompute
|
||||
return ComputeDevice.FromAdapter(devices.DXGI.Adapter, options.UnifiedMemoryArchitecture);
|
||||
}
|
||||
|
||||
public static ComputeWorkload Workload(int canvasWidth, int canvasHeight, int kernelRadius)
|
||||
=> new(canvasWidth, canvasHeight, GpuMemoryBytes(canvasWidth, canvasHeight, kernelRadius));
|
||||
public static ComputeWorkload Workload(int canvasWidth, int canvasHeight, int kernelRadius, bool chromatic = false)
|
||||
=> new(canvasWidth, canvasHeight, GpuMemoryBytes(canvasWidth, canvasHeight, kernelRadius, chromatic));
|
||||
|
||||
public static long GpuMemoryBytes(int canvasWidth, int canvasHeight, int kernelRadius)
|
||||
public static long GpuMemoryBytes(int canvasWidth, int canvasHeight, int kernelRadius, bool chromatic = false)
|
||||
{
|
||||
var plan = TilePlan.Create(kernelRadius, 0, 0, canvasWidth, canvasHeight);
|
||||
var pixels = (long)canvasWidth * canvasHeight;
|
||||
@@ -30,7 +30,7 @@ internal static class WaveOpticsCompute
|
||||
var layout = new GpuTileLayout(plan.GroupCount, GpuTileConvolver.MaximumSamples, kernelArea);
|
||||
return pixels * (ColorBytes * 2 + StoredBytes)
|
||||
+ (long)plan.BatchTiles * plan.TileElements * TilePlan.ElementBytes
|
||||
+ (long)plan.TileElements * sizeof(float) * 2
|
||||
+ (chromatic ? (long)ChromaticKernelSpectrum.ChannelCount * ChromaticKernelSpectrum.HalfColumnsOf(plan.Size) * plan.Size : plan.TileElements) * sizeof(float) * 2
|
||||
+ (long)plan.Size / 2 * sizeof(float) * 2
|
||||
+ (long)layout.Length * sizeof(uint) * 2
|
||||
+ WaveOpticsSettings.ScratchLength * sizeof(int) * 2;
|
||||
|
||||
@@ -5,7 +5,7 @@ namespace WaveOptics.Rendering;
|
||||
|
||||
internal sealed class WaveOpticsCpuPipeline : IDisposable
|
||||
{
|
||||
private const int Channels = 4;
|
||||
private const int Channels = ByteColor.Channels;
|
||||
|
||||
private readonly CpuTileConvolver _convolver;
|
||||
private readonly WaveOpticsKernel _kernel = new();
|
||||
@@ -21,8 +21,8 @@ internal sealed class WaveOpticsCpuPipeline : IDisposable
|
||||
private float[] _store = [];
|
||||
|
||||
public WaveOpticsCpuPipeline()
|
||||
: this(Environment.ProcessorCount)
|
||||
{
|
||||
_convolver = CpuTileConvolver.CreateShared();
|
||||
}
|
||||
|
||||
public WaveOpticsCpuPipeline(int threads)
|
||||
@@ -46,8 +46,8 @@ internal sealed class WaveOpticsCpuPipeline : IDisposable
|
||||
if (_output.Length < length)
|
||||
_output = new byte[length];
|
||||
MemoryMarshal.AsBytes(source[..(width * height)]).CopyTo(_packed);
|
||||
var plan = TilePlan.Create(_kernel.Spectrum.Size, _kernel.Spectrum.Radius, 0, 0, width, height);
|
||||
_convolver.Convolve(_packed, 0, 0, width, height, _kernel.Spectrum, plan, _output, parameters.Gain, null);
|
||||
var plan = TilePlan.Create(_kernel.Size, _kernel.Radius, 0, 0, width, height);
|
||||
Convolve(_packed, 0, 0, width, height, in plan, parameters.Gain, null, parameters.Light);
|
||||
_output.AsSpan(0, length).CopyTo(MemoryMarshal.AsBytes(destination[..(width * height)]));
|
||||
}
|
||||
|
||||
@@ -74,7 +74,7 @@ internal sealed class WaveOpticsCpuPipeline : IDisposable
|
||||
_source = source;
|
||||
_sourceHash = WaveOpticsSourceHash.Compute(source, sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight);
|
||||
var sourceRect = new WaveOpticsPipeline.PixelRect(sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight);
|
||||
var key = new WaveOpticsConvolutionKey(_sourceHash.Sum, _sourceHash.Mix, canvasWidth, canvasHeight, sourceRect, WaveOpticsKernel.KeyOf(parameters.Psf));
|
||||
var key = new WaveOpticsConvolutionKey(_sourceHash.Sum, _sourceHash.Mix, canvasWidth, canvasHeight, sourceRect, WaveOpticsKernel.KeyOf(parameters.Psf), parameters.Light.ForConvolution());
|
||||
if (_convolutionKey == key || !TryGetVisibleBounds(canvasWidth, canvasHeight, in parameters, out _))
|
||||
return false;
|
||||
|
||||
@@ -97,7 +97,7 @@ internal sealed class WaveOpticsCpuPipeline : IDisposable
|
||||
if (_convolutionKey is not { } key || !_kernel.IsValid)
|
||||
throw new InvalidOperationException();
|
||||
|
||||
var mode = _tracker.Next(key, rect, parameters.Gain, out var releaseStore);
|
||||
var mode = _tracker.Next(key, rect, parameters.Gain, parameters.Light.Dither, out var releaseStore);
|
||||
if (releaseStore)
|
||||
_store = [];
|
||||
|
||||
@@ -107,7 +107,7 @@ internal sealed class WaveOpticsCpuPipeline : IDisposable
|
||||
|
||||
if (mode == WaveOpticsRenderMode.Stored)
|
||||
{
|
||||
_convolver.RenderStored(_store, rect.Width * rect.Height, parameters.Gain, _output);
|
||||
_convolver.RenderStored(_store, rect.Width * rect.Height, parameters.Gain, _output, parameters.Light, rect.Width, rect.X, rect.Y);
|
||||
return _output.AsSpan(0, length);
|
||||
}
|
||||
|
||||
@@ -119,11 +119,19 @@ internal sealed class WaveOpticsCpuPipeline : IDisposable
|
||||
store = _store;
|
||||
}
|
||||
|
||||
var plan = TilePlan.Create(_kernel.Spectrum.Size, _kernel.Spectrum.Radius, rect.X, rect.Y, rect.Width, rect.Height);
|
||||
_convolver.Convolve(_source, _sourceRect.X, _sourceRect.Y, _sourceRect.Width, _sourceRect.Height, _kernel.Spectrum, plan, _output, parameters.Gain, store);
|
||||
var plan = TilePlan.Create(_kernel.Size, _kernel.Radius, rect.X, rect.Y, rect.Width, rect.Height);
|
||||
Convolve(_source, _sourceRect.X, _sourceRect.Y, _sourceRect.Width, _sourceRect.Height, in plan, parameters.Gain, store, parameters.Light);
|
||||
return _output.AsSpan(0, length);
|
||||
}
|
||||
|
||||
private void Convolve(byte[] source, int sourceX, int sourceY, int sourceWidth, int sourceHeight, in TilePlan plan, float gain, float[]? store, LightOptions light)
|
||||
{
|
||||
if (_kernel.IsChromatic)
|
||||
_convolver.Convolve(source, sourceX, sourceY, sourceWidth, sourceHeight, _kernel.ChromaticSpectrum, in plan, _output, gain, store, light);
|
||||
else
|
||||
_convolver.Convolve(source, sourceX, sourceY, sourceWidth, sourceHeight, _kernel.Spectrum, in plan, _output, gain, store, light);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_convolver.Dispose();
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Numerics;
|
||||
using SpectralConvolution;
|
||||
using Vortice.DCommon;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Mathematics;
|
||||
@@ -7,7 +8,7 @@ namespace WaveOptics.Rendering;
|
||||
|
||||
internal sealed class WaveOpticsCpuSurface : IDisposable
|
||||
{
|
||||
private const int Channels = 4;
|
||||
private const int Channels = ByteColor.Channels;
|
||||
private const float Dpi = 96f;
|
||||
|
||||
private static readonly PixelFormat SurfaceFormat = new(Vortice.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied);
|
||||
|
||||
@@ -76,19 +76,13 @@ internal readonly partial struct SourceHashShader(
|
||||
for (var x = first; x < last; x++)
|
||||
{
|
||||
var color = source[new Int2(x, y)];
|
||||
var quantized = ((uint)(color.X * 255f + 0.5f) << 24)
|
||||
| ((uint)(color.Y * 255f + 0.5f) << 16)
|
||||
| ((uint)(color.Z * 255f + 0.5f) << 8)
|
||||
| (uint)(color.W * 255f + 0.5f);
|
||||
var quantized = SourceHashMath.Quantize(color);
|
||||
if (quantized == 0u)
|
||||
continue;
|
||||
|
||||
var mixed = ((uint)(y * sourceWidth + x) * 0x9E3779B9u) ^ (quantized * 0x85EBCA6Bu);
|
||||
mixed ^= mixed >> 16;
|
||||
mixed *= 0x85EBCA6Bu;
|
||||
mixed ^= mixed >> 13;
|
||||
var mixed = SourceHashMath.Mixed(y * sourceWidth + x, quantized);
|
||||
sum += (int)mixed;
|
||||
mix ^= (int)(mixed * 0xC2B2AE35u);
|
||||
mix ^= (int)(mixed * SourceHashMath.AccumulateMultiplier);
|
||||
count++;
|
||||
minimumX = Hlsl.Min(minimumX, sourceX + x);
|
||||
maximumX = Hlsl.Max(maximumX, sourceX + x);
|
||||
|
||||
@@ -7,15 +7,22 @@ namespace WaveOptics.Rendering;
|
||||
|
||||
internal sealed class WaveOpticsKernel
|
||||
{
|
||||
private readonly double[] _values = new double[WaveOpticsSettings.MaximumKernelSize * WaveOpticsSettings.MaximumKernelSize];
|
||||
private readonly FraunhoferKernelSampler _sampler = new();
|
||||
private readonly KernelSpectrum _spectrum = new();
|
||||
private readonly ChromaticKernelSpectrum _chromaticSpectrum = new();
|
||||
private WaveOpticsPipeline.PsfParameters? _key;
|
||||
private bool _isValid;
|
||||
private int _version;
|
||||
|
||||
public KernelSpectrum Spectrum => _spectrum;
|
||||
|
||||
public ChromaticKernelSpectrum ChromaticSpectrum => _chromaticSpectrum;
|
||||
|
||||
public bool IsChromatic => _key is { ColorMode: not WaveOpticsColorMode.Monochrome };
|
||||
|
||||
public int Size => IsChromatic ? _chromaticSpectrum.Size : _spectrum.Size;
|
||||
|
||||
public int Radius => IsChromatic ? _chromaticSpectrum.Radius : _spectrum.Radius;
|
||||
|
||||
public bool IsValid => _isValid;
|
||||
|
||||
public int Version => _version;
|
||||
@@ -37,11 +44,12 @@ internal sealed class WaveOpticsKernel
|
||||
comaHorizontalWaves: psf.ComaHorizontal,
|
||||
comaVerticalWaves: psf.ComaVertical,
|
||||
sphericalWaves: psf.Spherical);
|
||||
var chromatic = psf.ColorMode != WaveOpticsColorMode.Monochrome;
|
||||
var specification = new PsfSpecification(
|
||||
pupilGridSize,
|
||||
WaveOpticsSettings.GetPupilDiameterSamples(pupilGridSize),
|
||||
WaveOpticsSettings.GetKernelSize(psf.KernelRadius),
|
||||
psf.Wavelength,
|
||||
chromatic ? SpectralPlan.ReferenceWavelength : psf.Wavelength,
|
||||
psf.FNumber,
|
||||
psf.PixelPitch,
|
||||
psf.ApertureShape == WaveOpticsApertureShape.Circular ? ApertureShape.Circular : ApertureShape.RegularPolygon,
|
||||
@@ -49,9 +57,15 @@ internal sealed class WaveOpticsKernel
|
||||
psf.BladeRotation,
|
||||
psf.Obstruction,
|
||||
aberration);
|
||||
var size = specification.KernelSize;
|
||||
var values = _values.AsSpan(0, size * size);
|
||||
if (!_sampler.TrySample(in specification, values))
|
||||
var area = specification.KernelSize * specification.KernelSize;
|
||||
using var lease = ScratchPool<PsfScratch>.Shared.Rent();
|
||||
var scratch = lease.Value;
|
||||
scratch.Ensure(area, chromatic);
|
||||
var values = scratch.Green.AsSpan(0, area);
|
||||
if (chromatic)
|
||||
return TryUpdateChromatic(scratch, in specification, psf, values);
|
||||
|
||||
if (!scratch.Sampler.TrySample(in specification, values))
|
||||
return false;
|
||||
|
||||
var sum = 0d;
|
||||
@@ -65,6 +79,32 @@ internal sealed class WaveOpticsKernel
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool TryUpdateChromatic(PsfScratch scratch, in PsfSpecification specification, in WaveOpticsPipeline.PsfParameters psf, Span<double> green)
|
||||
{
|
||||
var size = green.Length;
|
||||
var red = scratch.Red.AsSpan(0, size);
|
||||
var blue = scratch.Blue.AsSpan(0, size);
|
||||
if (!scratch.ChromaticSampler.TrySample(in specification, psf.ColorMode, psf.Quality, red, green, blue))
|
||||
return false;
|
||||
if (!HasEnergy(red) || !HasEnergy(green) || !HasEnergy(blue))
|
||||
return false;
|
||||
|
||||
_chromaticSpectrum.Update(scratch.Red.AsMemory(0, size), scratch.Green.AsMemory(0, size), scratch.Blue.AsMemory(0, size), psf.KernelRadius, TilePlan.SelectSize(psf.KernelRadius));
|
||||
_isValid = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool HasEnergy(ReadOnlySpan<double> values)
|
||||
{
|
||||
var sum = 0d;
|
||||
foreach (var value in values)
|
||||
sum += value;
|
||||
return double.IsFinite(sum) && sum > 0d;
|
||||
}
|
||||
|
||||
public static WaveOpticsPipeline.PsfParameters KeyOf(in WaveOpticsPipeline.PsfParameters psf)
|
||||
=> psf.ApertureShape == WaveOpticsApertureShape.Circular ? psf with { BladeCount = 0, BladeRotation = 0f } : psf;
|
||||
{
|
||||
var key = psf.ApertureShape == WaveOpticsApertureShape.Circular ? psf with { BladeCount = 0, BladeRotation = 0f } : psf;
|
||||
return key.ColorMode == WaveOpticsColorMode.Monochrome ? key : key with { Wavelength = 0f };
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,8 @@ internal sealed class WaveOpticsPipeline : IDisposable
|
||||
|
||||
internal bool IsDeviceLost => Volatile.Read(ref _deviceLost);
|
||||
|
||||
internal bool HasStore => _tracker.HasStore;
|
||||
|
||||
internal Func<Float2[], Float2[]>? SpectrumTamper
|
||||
{
|
||||
get => _spectrumTamper;
|
||||
@@ -170,7 +172,8 @@ internal sealed class WaveOpticsPipeline : IDisposable
|
||||
_canvasWidth,
|
||||
_canvasHeight,
|
||||
sourceRect,
|
||||
WaveOpticsKernel.KeyOf(parameters.Psf));
|
||||
WaveOpticsKernel.KeyOf(parameters.Psf),
|
||||
parameters.Light.ForConvolution());
|
||||
if (_convolutionKey == key || !TryGetVisibleBounds(_canvasWidth, _canvasHeight, in parameters, out _))
|
||||
return false;
|
||||
|
||||
@@ -206,15 +209,15 @@ internal sealed class WaveOpticsPipeline : IDisposable
|
||||
in Parameters parameters,
|
||||
Span<ConvolutionMeasurement> measurements)
|
||||
{
|
||||
var mode = BeginRender(rect, parameters.Gain);
|
||||
var mode = BeginRender(rect, parameters.Gain, parameters.Light.Dither);
|
||||
if (mode == WaveOpticsRenderMode.Stored)
|
||||
{
|
||||
_host.RecordStoredRender(_convolver.StoreFor(_storedJob), output, in rect, parameters.Gain).Wait();
|
||||
_host.RecordStoredRender(_convolver.StoreFor(_storedJob), output, in rect, parameters.Gain, parameters.Light).Wait();
|
||||
return 0;
|
||||
}
|
||||
|
||||
Span<Int2> samples = stackalloc Int2[GpuTileConvolver.MaximumSamples];
|
||||
var job = PrepareConvolution(rect, parameters.Gain, mode == WaveOpticsRenderMode.ConvolveAndStore, measurements.IsEmpty ? [] : samples);
|
||||
var job = PrepareConvolution(rect, parameters.Gain, mode == WaveOpticsRenderMode.ConvolveAndStore, measurements.IsEmpty ? [] : samples, parameters.Light);
|
||||
_host.RecordConvolution(
|
||||
source, output, _convolver.Tiles, _convolver.Twiddles, _convolver.Spectrum,
|
||||
_convolver.Report, _convolver.Samples, _convolver.StoreFor(job), in job).Wait();
|
||||
@@ -235,15 +238,15 @@ internal sealed class WaveOpticsPipeline : IDisposable
|
||||
in Parameters parameters,
|
||||
Span<ConvolutionMeasurement> measurements)
|
||||
{
|
||||
var mode = BeginRender(rect, parameters.Gain);
|
||||
var mode = BeginRender(rect, parameters.Gain, parameters.Light.Dither);
|
||||
if (mode == WaveOpticsRenderMode.Stored)
|
||||
{
|
||||
_host.RecordSharedStoredRender(_convolver.StoreFor(_storedJob), output, in rect, parameters.Gain).Wait();
|
||||
_host.RecordSharedStoredRender(_convolver.StoreFor(_storedJob), output, in rect, parameters.Gain, parameters.Light).Wait();
|
||||
return 0;
|
||||
}
|
||||
|
||||
Span<Int2> samples = stackalloc Int2[GpuTileConvolver.MaximumSamples];
|
||||
var job = PrepareConvolution(rect, parameters.Gain, mode == WaveOpticsRenderMode.ConvolveAndStore, measurements.IsEmpty ? [] : samples);
|
||||
var job = PrepareConvolution(rect, parameters.Gain, mode == WaveOpticsRenderMode.ConvolveAndStore, measurements.IsEmpty ? [] : samples, parameters.Light);
|
||||
_host.RecordSharedConvolution(
|
||||
source, output, _convolver.Tiles, _convolver.Twiddles, _convolver.Spectrum,
|
||||
_convolver.Report, _convolver.Samples, _convolver.StoreFor(job), in job).Wait();
|
||||
@@ -256,28 +259,39 @@ internal sealed class WaveOpticsPipeline : IDisposable
|
||||
return 0;
|
||||
|
||||
var count = GpuTileCheck.MeasurementCount(job.SampleCount);
|
||||
GpuTileCheck.Evaluate(_convolver.ReadReport(in job), in job, samples, _kernel.Spectrum.Kernel, measurements[..count]);
|
||||
if (_kernel.IsChromatic)
|
||||
{
|
||||
var spectrum = _kernel.ChromaticSpectrum;
|
||||
GpuTileCheck.Evaluate(_convolver.ReadReport(in job), in job, samples, spectrum.Red.Kernel, spectrum.Green.Kernel, spectrum.Blue.Kernel, measurements[..count]);
|
||||
}
|
||||
else
|
||||
{
|
||||
GpuTileCheck.Evaluate(_convolver.ReadReport(in job), in job, samples, _kernel.Spectrum.Kernel, measurements[..count]);
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
private WaveOpticsRenderMode BeginRender(PixelRect rect, float gain)
|
||||
private WaveOpticsRenderMode BeginRender(PixelRect rect, float gain, bool dither)
|
||||
{
|
||||
if (_convolutionKey is not { } key || !_kernel.IsValid)
|
||||
throw new InvalidOperationException();
|
||||
|
||||
var mode = _tracker.Next(key, rect, gain, out var releaseStore);
|
||||
var mode = _tracker.Next(key, rect, gain, dither, out var releaseStore);
|
||||
if (releaseStore)
|
||||
ReleaseStoreBuffer();
|
||||
return mode;
|
||||
}
|
||||
|
||||
private GpuTileJob PrepareConvolution(PixelRect rect, float gain, bool store, Span<Int2> samples)
|
||||
private GpuTileJob PrepareConvolution(PixelRect rect, float gain, bool store, Span<Int2> samples, in LightOptions light)
|
||||
{
|
||||
if (_uploadedKernelVersion != _kernel.Version)
|
||||
{
|
||||
_convolver.Upload(_kernel.Spectrum);
|
||||
if (_kernel.IsChromatic)
|
||||
_convolver.Upload(_kernel.ChromaticSpectrum);
|
||||
else
|
||||
_convolver.Upload(_kernel.Spectrum);
|
||||
if (_spectrumTamper is { } tamper)
|
||||
_convolver.Spectrum.CopyFrom(tamper(_kernel.Spectrum.Spectrum.ToArray()));
|
||||
_convolver.Spectrum.CopyFrom(tamper(UploadedSpectrum()));
|
||||
_uploadedKernelVersion = _kernel.Version;
|
||||
}
|
||||
|
||||
@@ -289,14 +303,25 @@ internal sealed class WaveOpticsPipeline : IDisposable
|
||||
samples[index] = new Int2(picks[index].X, picks[index].Y);
|
||||
}
|
||||
|
||||
var plan = TilePlan.Create(_kernel.Spectrum.Size, _kernel.Spectrum.Radius, rect.X, rect.Y, rect.Width, rect.Height);
|
||||
var job = _convolver.Prepare(plan, _sourceRect.X, _sourceRect.Y, _sourceRect.Width, _sourceRect.Height, gain, samples, store);
|
||||
var plan = TilePlan.Create(_kernel.Size, _kernel.Radius, rect.X, rect.Y, rect.Width, rect.Height);
|
||||
var job = _convolver.Prepare(plan, _sourceRect.X, _sourceRect.Y, _sourceRect.Width, _sourceRect.Height, gain, samples, store, light, _kernel.IsChromatic);
|
||||
if (store)
|
||||
_storedJob = job;
|
||||
|
||||
return job;
|
||||
}
|
||||
|
||||
private Float2[] UploadedSpectrum()
|
||||
{
|
||||
if (!_kernel.IsChromatic)
|
||||
return _kernel.Spectrum.Spectrum.ToArray();
|
||||
|
||||
var spectra = _kernel.ChromaticSpectrum;
|
||||
var values = new Float2[ChromaticKernelSpectrum.ChannelCount * spectra.HalfColumns * spectra.Size];
|
||||
spectra.CopyHalfSpectra(values);
|
||||
return values;
|
||||
}
|
||||
|
||||
private void ResetRendering()
|
||||
{
|
||||
if (_tracker.Reset())
|
||||
@@ -322,7 +347,7 @@ internal sealed class WaveOpticsPipeline : IDisposable
|
||||
_convolutionKey = null;
|
||||
ResetRendering();
|
||||
_sourceRect = new PixelRect(0, 0, width, height);
|
||||
var job = PrepareConvolution(_sourceRect, parameters.Gain, false, []);
|
||||
var job = PrepareConvolution(_sourceRect, parameters.Gain, false, [], parameters.Light);
|
||||
return _host.RecordConvolution(
|
||||
source, output, _convolver.Tiles, _convolver.Twiddles, _convolver.Spectrum,
|
||||
_convolver.Report, _convolver.Samples, _convolver.StoreFor(job), in job);
|
||||
@@ -393,7 +418,8 @@ internal sealed class WaveOpticsPipeline : IDisposable
|
||||
float AstigmatismOblique,
|
||||
float ComaHorizontal,
|
||||
float ComaVertical,
|
||||
float Spherical);
|
||||
float Spherical,
|
||||
WaveOpticsColorMode ColorMode = WaveOpticsColorMode.Monochrome);
|
||||
|
||||
internal readonly record struct Parameters(float Gain, PsfParameters Psf);
|
||||
internal readonly record struct Parameters(float Gain, PsfParameters Psf, LightOptions Light = default);
|
||||
}
|
||||
@@ -76,11 +76,12 @@ internal sealed partial class WaveOpticsPipelineHost
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<Float4> store,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
in WaveOpticsPipeline.PixelRect rect,
|
||||
float gain)
|
||||
float gain,
|
||||
in LightOptions light)
|
||||
{
|
||||
_ = _device;
|
||||
|
||||
GpuTileConvolver.RecordStored(in context, store, output, rect.Width, rect.Height, gain);
|
||||
GpuTileConvolver.RecordStored(in context, store, output, rect.Width, rect.Height, gain, in light, rect.X, rect.Y);
|
||||
}
|
||||
|
||||
[ComputePipeline]
|
||||
@@ -90,11 +91,12 @@ internal sealed partial class WaveOpticsPipelineHost
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite)] ReadWriteBuffer<Float4> store,
|
||||
[ComputeResource(ComputeResourceAccess.ReadWrite, Sharing = ComputeResourceSharing.External)] ReadWriteTexture2D<Bgra32, Float4> output,
|
||||
in WaveOpticsPipeline.PixelRect rect,
|
||||
float gain)
|
||||
float gain,
|
||||
in LightOptions light)
|
||||
{
|
||||
_ = _device;
|
||||
|
||||
GpuTileConvolver.RecordStored(in context, store, output, rect.Width, rect.Height, gain);
|
||||
GpuTileConvolver.RecordStored(in context, store, output, rect.Width, rect.Height, gain, in light, rect.X, rect.Y);
|
||||
}
|
||||
|
||||
private static void RecordSourceHashStage(
|
||||
|
||||
@@ -6,7 +6,8 @@ internal readonly record struct WaveOpticsConvolutionKey(
|
||||
int CanvasWidth,
|
||||
int CanvasHeight,
|
||||
WaveOpticsPipeline.PixelRect Source,
|
||||
WaveOpticsPipeline.PsfParameters Psf)
|
||||
WaveOpticsPipeline.PsfParameters Psf,
|
||||
SpectralConvolution.LightOptions Light = default)
|
||||
{
|
||||
public ulong SamplingKey => (ulong)(uint)HashSum << 32 | (uint)HashMix;
|
||||
}
|
||||
@@ -23,10 +24,14 @@ internal sealed class WaveOpticsRenderTracker
|
||||
private WaveOpticsConvolutionKey? _renderedKey;
|
||||
private WaveOpticsPipeline.PixelRect _renderedRect;
|
||||
private float _renderedGain;
|
||||
private bool _renderedDither;
|
||||
|
||||
public bool HasStore { get; private set; }
|
||||
|
||||
public WaveOpticsRenderMode Next(in WaveOpticsConvolutionKey key, WaveOpticsPipeline.PixelRect rect, float gain, out bool releaseStore)
|
||||
=> Next(in key, rect, gain, false, out releaseStore);
|
||||
|
||||
public WaveOpticsRenderMode Next(in WaveOpticsConvolutionKey key, WaveOpticsPipeline.PixelRect rect, float gain, bool dither, out bool releaseStore)
|
||||
{
|
||||
WaveOpticsRenderMode mode;
|
||||
releaseStore = false;
|
||||
@@ -38,7 +43,7 @@ internal sealed class WaveOpticsRenderTracker
|
||||
}
|
||||
else if (HasStore)
|
||||
mode = WaveOpticsRenderMode.Stored;
|
||||
else if (gain != _renderedGain)
|
||||
else if (gain != _renderedGain || dither != _renderedDither)
|
||||
{
|
||||
HasStore = true;
|
||||
mode = WaveOpticsRenderMode.ConvolveAndStore;
|
||||
@@ -49,6 +54,7 @@ internal sealed class WaveOpticsRenderTracker
|
||||
_renderedKey = key;
|
||||
_renderedRect = rect;
|
||||
_renderedGain = gain;
|
||||
_renderedDither = dither;
|
||||
return mode;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
using System.Numerics;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Intrinsics;
|
||||
using SpectralConvolution;
|
||||
|
||||
namespace WaveOptics.Rendering;
|
||||
|
||||
internal readonly record struct WaveOpticsSourceHash(int LitCount, int MinimumX, int MinimumY, int MaximumX, int MaximumY, int Sum, int Mix)
|
||||
@@ -16,7 +22,17 @@ internal readonly record struct WaveOpticsSourceHash(int LitCount, int MinimumX,
|
||||
|
||||
public static WaveOpticsSourceHash Compute(ReadOnlySpan<byte> bgra, int sourceX, int sourceY, int sourceWidth, int sourceHeight)
|
||||
{
|
||||
if (bgra.Length < (long)sourceWidth * sourceHeight * 4)
|
||||
if (bgra.Length < (long)sourceWidth * sourceHeight * ByteColor.Channels)
|
||||
throw new ArgumentException(null, nameof(bgra));
|
||||
|
||||
return Vector256.IsHardwareAccelerated && BitConverter.IsLittleEndian
|
||||
? ComputeVector(bgra, sourceX, sourceY, sourceWidth, sourceHeight)
|
||||
: ComputeScalar(bgra, sourceX, sourceY, sourceWidth, sourceHeight);
|
||||
}
|
||||
|
||||
internal static WaveOpticsSourceHash ComputeScalar(ReadOnlySpan<byte> bgra, int sourceX, int sourceY, int sourceWidth, int sourceHeight)
|
||||
{
|
||||
if (bgra.Length < (long)sourceWidth * sourceHeight * ByteColor.Channels)
|
||||
throw new ArgumentException(null, nameof(bgra));
|
||||
|
||||
var count = 0;
|
||||
@@ -28,19 +44,16 @@ internal readonly record struct WaveOpticsSourceHash(int LitCount, int MinimumX,
|
||||
var maximumY = int.MinValue;
|
||||
for (var y = 0; y < sourceHeight; y++)
|
||||
{
|
||||
var row = bgra.Slice(y * sourceWidth * 4, sourceWidth * 4);
|
||||
var row = bgra.Slice(y * sourceWidth * ByteColor.Channels, sourceWidth * ByteColor.Channels);
|
||||
for (var x = 0; x < sourceWidth; x++)
|
||||
{
|
||||
var quantized = (uint)row[x * 4 + 2] << 24 | (uint)row[x * 4 + 1] << 16 | (uint)row[x * 4] << 8 | row[x * 4 + 3];
|
||||
var quantized = (uint)row[x * ByteColor.Channels + 2] << 24 | (uint)row[x * ByteColor.Channels + 1] << 16 | (uint)row[x * ByteColor.Channels] << 8 | row[x * ByteColor.Channels + 3];
|
||||
if (quantized == 0u)
|
||||
continue;
|
||||
|
||||
var mixed = unchecked((uint)(y * sourceWidth + x) * 0x9E3779B9u ^ quantized * 0x85EBCA6Bu);
|
||||
mixed ^= mixed >> 16;
|
||||
mixed = unchecked(mixed * 0x85EBCA6Bu);
|
||||
mixed ^= mixed >> 13;
|
||||
var mixed = SourceHashMath.Mixed(y * sourceWidth + x, quantized);
|
||||
sum = unchecked(sum + (int)mixed);
|
||||
mix ^= unchecked((int)(mixed * 0xC2B2AE35u));
|
||||
mix ^= unchecked((int)(mixed * SourceHashMath.AccumulateMultiplier));
|
||||
count++;
|
||||
minimumX = Math.Min(minimumX, sourceX + x);
|
||||
maximumX = Math.Max(maximumX, sourceX + x);
|
||||
@@ -52,18 +65,99 @@ internal readonly record struct WaveOpticsSourceHash(int LitCount, int MinimumX,
|
||||
return new WaveOpticsSourceHash(count, minimumX, minimumY, maximumX, maximumY, sum, mix);
|
||||
}
|
||||
|
||||
internal static WaveOpticsSourceHash ComputeVector(ReadOnlySpan<byte> bgra, int sourceX, int sourceY, int sourceWidth, int sourceHeight)
|
||||
{
|
||||
var pixels = MemoryMarshal.Cast<byte, uint>(bgra[..(sourceWidth * sourceHeight * ByteColor.Channels)]);
|
||||
ref var origin = ref MemoryMarshal.GetReference(pixels);
|
||||
var lanes = Vector256.Create(0u, 1u, 2u, 3u, 4u, 5u, 6u, 7u);
|
||||
var golden = Vector256.Create(SourceHashMath.IndexMultiplier);
|
||||
var first = Vector256.Create(SourceHashMath.MixMultiplier);
|
||||
var second = Vector256.Create(SourceHashMath.AccumulateMultiplier);
|
||||
var sumVector = Vector256<uint>.Zero;
|
||||
var mixVector = Vector256<uint>.Zero;
|
||||
var countVector = Vector256<int>.Zero;
|
||||
var count = 0;
|
||||
var sum = 0u;
|
||||
var mix = 0u;
|
||||
var minimumX = int.MaxValue;
|
||||
var minimumY = int.MaxValue;
|
||||
var maximumX = int.MinValue;
|
||||
var maximumY = int.MinValue;
|
||||
for (var y = 0; y < sourceHeight; y++)
|
||||
{
|
||||
var rowStart = y * sourceWidth;
|
||||
var rowMinimum = int.MaxValue;
|
||||
var rowMaximum = int.MinValue;
|
||||
var x = 0;
|
||||
for (; x + 8 <= sourceWidth; x += 8)
|
||||
{
|
||||
var pixel = Vector256.LoadUnsafe(ref origin, (nuint)(rowStart + x));
|
||||
var lit = ~Vector256.Equals(pixel, Vector256<uint>.Zero);
|
||||
var bits = lit.ExtractMostSignificantBits();
|
||||
if (bits == 0u)
|
||||
continue;
|
||||
|
||||
var quantized = (pixel << 8) | (pixel >> 24);
|
||||
var mixed = (Vector256.Create((uint)(rowStart + x)) + lanes) * golden ^ quantized * first;
|
||||
mixed ^= mixed >> SourceHashMath.FirstShift;
|
||||
mixed *= first;
|
||||
mixed ^= mixed >> SourceHashMath.SecondShift;
|
||||
mixed &= lit;
|
||||
sumVector += mixed;
|
||||
mixVector ^= mixed * second;
|
||||
countVector -= lit.AsInt32();
|
||||
rowMinimum = Math.Min(rowMinimum, x + BitOperations.TrailingZeroCount(bits));
|
||||
rowMaximum = Math.Max(rowMaximum, x + 31 - BitOperations.LeadingZeroCount(bits));
|
||||
}
|
||||
|
||||
for (; x < sourceWidth; x++)
|
||||
{
|
||||
var quantized = BitOperations.RotateLeft(Unsafe.Add(ref origin, rowStart + x), 8);
|
||||
if (quantized == 0u)
|
||||
continue;
|
||||
|
||||
var mixed = SourceHashMath.Mixed(rowStart + x, quantized);
|
||||
sum = unchecked(sum + mixed);
|
||||
mix ^= unchecked(mixed * SourceHashMath.AccumulateMultiplier);
|
||||
count++;
|
||||
rowMinimum = Math.Min(rowMinimum, x);
|
||||
rowMaximum = Math.Max(rowMaximum, x);
|
||||
}
|
||||
|
||||
if (rowMaximum < rowMinimum)
|
||||
continue;
|
||||
|
||||
minimumX = Math.Min(minimumX, sourceX + rowMinimum);
|
||||
maximumX = Math.Max(maximumX, sourceX + rowMaximum);
|
||||
minimumY = Math.Min(minimumY, sourceY + y);
|
||||
maximumY = Math.Max(maximumY, sourceY + y);
|
||||
}
|
||||
|
||||
for (var lane = 0; lane < Vector256<uint>.Count; lane++)
|
||||
mix ^= mixVector.GetElement(lane);
|
||||
|
||||
return new WaveOpticsSourceHash(
|
||||
count + Vector256.Sum(countVector),
|
||||
minimumX,
|
||||
minimumY,
|
||||
maximumX,
|
||||
maximumY,
|
||||
unchecked((int)(sum + Vector256.Sum(sumVector))),
|
||||
unchecked((int)mix));
|
||||
}
|
||||
|
||||
public bool TryGetVisibleBounds(int canvasWidth, int canvasHeight, int radius, out WaveOpticsPipeline.PixelRect rect)
|
||||
{
|
||||
rect = default;
|
||||
if (LitCount <= 0 || MinimumX > MaximumX)
|
||||
return false;
|
||||
|
||||
var left = Math.Clamp((MinimumX - radius) & ~3, 0, canvasWidth);
|
||||
var top = Math.Clamp((MinimumY - radius) & ~3, 0, canvasHeight);
|
||||
var left = Math.Clamp(WaveOpticsSettings.AlignDown(MinimumX - radius), 0, canvasWidth);
|
||||
var top = Math.Clamp(WaveOpticsSettings.AlignDown(MinimumY - radius), 0, canvasHeight);
|
||||
var right = Math.Clamp(MaximumX + 1 + radius, 0, canvasWidth);
|
||||
var bottom = Math.Clamp(MaximumY + 1 + radius, 0, canvasHeight);
|
||||
var width = Math.Min((right - left + 3) & ~3, canvasWidth - left);
|
||||
var height = Math.Min((bottom - top + 3) & ~3, canvasHeight - top);
|
||||
var width = Math.Min(WaveOpticsSettings.AlignUp(right - left), canvasWidth - left);
|
||||
var height = Math.Min(WaveOpticsSettings.AlignUp(bottom - top), canvasHeight - top);
|
||||
if (width <= 0 || height <= 0)
|
||||
return false;
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<Nullable>enable</Nullable>
|
||||
<AssemblyName>WaveOptics</AssemblyName>
|
||||
<RootNamespace>WaveOptics</RootNamespace>
|
||||
<Version>3.0.0</Version>
|
||||
<Version>3.4.0</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
|
||||
@@ -9,8 +9,10 @@ internal static class WaveOpticsSettings
|
||||
public const int MaximumKernelRadius = 63;
|
||||
public const int MaximumKernelSize = MaximumKernelRadius * 2 + 1;
|
||||
public const int SourceHashSpan = 16;
|
||||
public const int DefaultCanvasMargin = (DefaultKernelRadius + 3) & ~3;
|
||||
public const int CanvasAlignment = 4;
|
||||
public const int DefaultCanvasMargin = (DefaultKernelRadius + CanvasAlignment - 1) & ~(CanvasAlignment - 1);
|
||||
public const int MaximumCanvasSize = 8192;
|
||||
public const double MaximumAberrationWaves = 10d;
|
||||
public const int ScratchLength = 7;
|
||||
public const int ScratchLitCount = 0;
|
||||
public const int ScratchBoundsMinX = 1;
|
||||
@@ -20,18 +22,26 @@ internal static class WaveOpticsSettings
|
||||
public const int ScratchHashSum = 5;
|
||||
public const int ScratchHashMix = 6;
|
||||
public const int MaximumPendingSubmissions = 32;
|
||||
public const int DraftPupilGridSize = 128;
|
||||
public const int StandardPupilGridSize = 256;
|
||||
public const int HighPupilGridSize = 512;
|
||||
public const int PupilGridPerPupilDiameter = 4;
|
||||
|
||||
public static int GetPupilGridSize(WaveOpticsQuality quality)
|
||||
=> quality switch
|
||||
{
|
||||
WaveOpticsQuality.Draft => 128,
|
||||
WaveOpticsQuality.High => 512,
|
||||
_ => 256,
|
||||
WaveOpticsQuality.Draft => DraftPupilGridSize,
|
||||
WaveOpticsQuality.High => HighPupilGridSize,
|
||||
_ => StandardPupilGridSize,
|
||||
};
|
||||
|
||||
public static int GetPupilDiameterSamples(int pupilGridSize) => pupilGridSize / 4;
|
||||
public static int GetPupilDiameterSamples(int pupilGridSize) => pupilGridSize / PupilGridPerPupilDiameter;
|
||||
|
||||
public static int GetKernelSize(int kernelRadius) => kernelRadius * 2 + 1;
|
||||
|
||||
public static int GetCanvasMargin(int kernelRadius) => Math.Max(DefaultCanvasMargin, (kernelRadius + 3) & ~3);
|
||||
public static int GetCanvasMargin(int kernelRadius) => Math.Max(DefaultCanvasMargin, AlignUp(kernelRadius));
|
||||
|
||||
public static int AlignUp(int value) => (value + CanvasAlignment - 1) & ~(CanvasAlignment - 1);
|
||||
|
||||
public static int AlignDown(int value) => value & ~(CanvasAlignment - 1);
|
||||
}
|
||||
バイナリファイルは表示されません。
|
変更後 幅: | 高さ: | サイズ: 868 KiB |
新しいイシューから参照
ユーザーをブロックする