コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
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
|
検索条件に一致するファイルはありません
+89
-41
@@ -1,5 +1,5 @@
|
||||
========================================
|
||||
波動光学 for YMM4 v3.0.0
|
||||
波動光学 for YMM4 v3.1.0
|
||||
========================================
|
||||
YukkuriMovieMaker4上で動作する、素材を回折も収差もない理想の像とみなし、
|
||||
レンズの開口と波面収差から求めた点像分布関数で畳み込んで、
|
||||
@@ -18,12 +18,16 @@ YukkuriMovieMaker4上で動作する、素材を回折も収差もない理想
|
||||
履歴フレーム、参照画像、深度情報、学習済みモデルは使用しません。
|
||||
にじみの形は光学系と収差の設定から決定論的に決まり、同じ設定では常に
|
||||
同じ形になります。
|
||||
適用量、利得、波長、F値、画素ピッチ、開口回転、中央遮蔽、デフォーカス、
|
||||
縦横非点収差、斜め非点収差、水平コマ収差、垂直コマ収差、球面収差の
|
||||
13項目はアニメーションに対応しています。
|
||||
適用量、利得、ハイライトのしきい値、ハイライトの強さ、波長、F値、画素ピッチ、
|
||||
開口回転、中央遮蔽、デフォーカス、縦横非点収差、斜め非点収差、水平コマ収差、
|
||||
垂直コマ収差、球面収差の15項目はアニメーションに対応しています。
|
||||
畳み込みはGPUで計算します。畳み込みを計算し直したフレームでは、その結果を
|
||||
画面に出す前に検査します。GPUを使えないときと、検査で誤りを見つけたときは、
|
||||
CPUで計算します。
|
||||
「線形光」をオンにすると、
|
||||
画素の値を光の強さに比例する値へ直してから畳み込みます。
|
||||
「ハイライトの強さ」を上げると、光源のような明るい部分を持ち上げて、
|
||||
回折の筋のような小さな光を見えるようにできます。
|
||||
エフェクトの種類一覧では「波動光学」として表示されます。
|
||||
--------------------------------------------------------------------------------
|
||||
■ 動作要件
|
||||
@@ -61,10 +65,46 @@ 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%のときは入力を変更せず、畳み込みの計算も行いません。
|
||||
@@ -102,18 +142,21 @@ CPUで計算します。
|
||||
自己試験にかかった時間は、Intel Iris Xe Graphicsで0.7〜0.8秒でした。
|
||||
|
||||
- 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の異常と呼びます。
|
||||
@@ -138,11 +181,12 @@ CPUで計算します。
|
||||
履歴フレーム、外部画像、深度情報、学習済みモデルは使用しません。
|
||||
素材のすべての画素が透明なときは、エフェクトを適用せず入力映像を表示します。
|
||||
|
||||
- 計算モデル: 計算は単色のフラウンホーファー回折に限ります。白色光の
|
||||
ように波長の混ざった光は扱いません。点像分布関数は画面のどこでも同じで、
|
||||
像の位置や素材の奥行きで変わるにじみは扱いません。畳み込みは、画素の値を
|
||||
そのまま重み付けして足し合わせます。画素の値を光の強さに比例する値へ
|
||||
直してから畳み込む処理はしません。
|
||||
- 計算モデル: 計算は単色のフラウンホーファー回折に限ります。
|
||||
白色光のように波長の混ざった光は扱いません。
|
||||
点像分布関数は画面のどこでも同じで、
|
||||
像の位置や素材の奥行きで変わるにじみは扱いません。畳み込みは、既定では、
|
||||
画素の値をそのまま重み付けして足し合わせます。線形光をオンにしたときだけ、
|
||||
画素の値を光の強さに比例する値へ直してから畳み込みます。
|
||||
|
||||
- 計算領域: 透明な部分も含む素材全体の矩形の上下左右に余白を加えた大きさを
|
||||
計算領域とし、長辺は8192画素が上限です。余白は、
|
||||
@@ -158,21 +202,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バイトです。
|
||||
@@ -193,15 +240,16 @@ CPUで計算します。
|
||||
キャッシュの項目にある保存した値のためのものです。
|
||||
|
||||
- キャッシュ: 素材の大きさと色と不透明度が変わらず、
|
||||
「利得」と「適用量」以外の項目も変わらないフレームでは、
|
||||
畳み込みの計算を再利用します。利得だけを変えたフレームでは、
|
||||
「利得」と「適用量」と「ディザ」以外の項目も変わらないフレームでは、
|
||||
畳み込みの計算を再利用します。利得かディザだけを変えたフレームでは、
|
||||
最初の1回だけ畳み込みを計算し直し、利得を掛ける前の値を保存します。
|
||||
2回目からは、保存した値に利得を掛け直します。素材か、
|
||||
「利得」と「適用量」以外の項目が変わると、保存した値を破棄します。
|
||||
2回目からは、保存した値に利得とディザを反映して描き直します。素材か、
|
||||
「利得」と「適用量」と「ディザ」以外の項目が変わると、保存した値を破棄します。
|
||||
ただし、線形光がオフのときは、ハイライトの2項目が変わっても破棄しません。
|
||||
適用量だけを変えたフレームでは、混ぜる割合だけを変えます。
|
||||
動画や口パクのように素材の内容が変わるフレームと、
|
||||
「利得」と「適用量」以外の項目をアニメーションで変えたフレームでは、
|
||||
毎回計算し直すので処理が重くなります。素材が変わったかどうかを調べる計算は、
|
||||
「利得」と「適用量」と「ディザ」以外の項目をアニメーションで変えたフレームでは
|
||||
、毎回計算し直すので処理が重くなります。素材が変わったかどうかを調べる計算は、
|
||||
再利用するフレームでも毎フレーム行います。開口形状が円形のときは、
|
||||
「羽根枚数」と「開口回転」を変えても、計算し直しません。
|
||||
|
||||
|
||||
@@ -10,8 +10,11 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を回折も収差もな
|
||||
点像分布関数は、瞳関数のフラウンホーファー回折を高速フーリエ変換で解いて求めます。
|
||||
履歴フレーム、参照画像、学習済みモデルを使わず、入力された一枚の映像だけを処理します。
|
||||
にじみの形は光学系と収差の設定から決定論的に決まり、同じ設定では常に同じ形になります。
|
||||
適用量、利得、波長、F値、画素ピッチ、開口回転、中央遮蔽、デフォーカス、縦横非点収差、斜め非点収差、水平コマ収差、垂直コマ収差、球面収差の13項目はアニメーションに対応しています。
|
||||
適用量、利得、ハイライトのしきい値、ハイライトの強さ、波長、F値、画素ピッチ、開口回転、中央遮蔽、デフォーカス、縦横非点収差、斜め非点収差、水平コマ収差、垂直コマ収差、球面収差の15項目はアニメーションに対応しています。
|
||||
畳み込みはGPUで計算します。畳み込みを計算し直したフレームでは、その結果を画面に出す前に検査します。GPUを使えないときと、検査で誤りを見つけたときは、CPUで計算します。
|
||||
「線形光」をオンにすると、画素の値を光の強さに比例する値へ直してから畳み込みます。「ハイライトの強さ」を上げると、光源のような明るい部分を持ち上げて、回折の筋のような小さな光を見えるようにできます。
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
@@ -27,8 +30,9 @@ YukkuriMovieMaker4(YMM4)上で動作する、素材を回折も収差もな
|
||||
- [4. ゼルニケ多項式による波面収差](#4-ゼルニケ多項式による波面収差)
|
||||
- [5. タイルごとの高速フーリエ変換による畳み込み](#5-タイルごとの高速フーリエ変換による畳み込み)
|
||||
- [6. 利得と適用量](#6-利得と適用量)
|
||||
- [7. 品質の選択](#7-品質の選択)
|
||||
- [8. GPUの計算の検査とCPUの経路](#8-gpuの計算の検査とcpuの経路)
|
||||
- [7. 線形光とハイライトとディザ](#7-線形光とハイライトとディザ)
|
||||
- [8. 品質の選択](#8-品質の選択)
|
||||
- [9. GPUの計算の検査とCPUの経路](#9-gpuの計算の検査とcpuの経路)
|
||||
5. [パラメータ一覧](#パラメータ一覧)
|
||||
- [出力グループ](#出力グループ)
|
||||
- [光学系グループ](#光学系グループ)
|
||||
@@ -59,7 +63,7 @@ GPUの経路では、ComputeWeaveの計算シェーダーがDirect3D 12で計算
|
||||
|
||||
GPUにある値をCPUが読み取ることを、読み戻しと呼びます。GPUの経路では、フレームごとに読み戻すのは、素材の全画素ではなく、7個の整数です。7個の整数は、素材の色と不透明度から作る2個のハッシュ、透明でない画素の数、外接矩形の位置を表す4個の値です。ハッシュは、素材の内容を短い数値にまとめた値で、素材が変わったかどうかの判定に使います。畳み込みを計算し直すフレームでは、これに加えて、検査に使う値も読み戻します。検査に使う値には、出力の16か所の値と、各か所の周りの素材の値が含まれます。検査は「GPUの計算の検査とCPUの経路」にあります。CPUの経路では、素材の画素を毎フレーム読み込み、ハッシュと外接矩形を、GPUの経路と同じ定義でCPUが求めます。
|
||||
|
||||
素材が変わらず、「利得」と「適用量」以外の項目も変わらないフレームでは、畳み込みの計算を再利用します。
|
||||
素材が変わらず、「利得」と「適用量」と「ディザ」以外の項目も変わらないフレームでは、畳み込みの計算を再利用します。
|
||||
|
||||
このエフェクトはAviUtl向けのEXO出力には対応していません。
|
||||
|
||||
@@ -95,7 +99,7 @@ GPUにある値をCPUが読み取ることを、読み戻しと呼びます。GP
|
||||
|
||||
畳み込みの重みは、点像分布関数から値を取り出して作ります。取り出すのは、中心から上下左右に「カーネル半径」の画素数までの正方形の範囲です。重みをこの正方形に並べたものを、カーネルと呼びます。カーネルの各画素の値は、画素の中心の位置で点像分布関数を補間した値で、画素の面積にわたる平均ではありません。カーネルの値の和は1になるように正規化します。カーネルの外に届く光は捨てるため、正規化によってカーネルの値がその分だけ大きくなります。
|
||||
|
||||
点像分布関数とカーネルと、カーネルを高速フーリエ変換したスペクトルは、「利得」と「適用量」以外のどれかの項目が変わったフレームでだけ、CPUで作り直します。
|
||||
点像分布関数とカーネルと、カーネルを高速フーリエ変換したスペクトルは、光学系グループと開口グループと波面収差グループのどれかの項目が変わったフレームでだけ、CPUで作り直します。
|
||||
|
||||
### 2. 光学系の項目とにじみの大きさ
|
||||
|
||||
@@ -146,23 +150,38 @@ Tが同じなら、カーネル半径を上げるほど、1枚のタイルが出
|
||||
|
||||
計算時間は、試験用に作った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.5倍ほど違います。そのため、行どうしの比べ方は、表を分けた組の中で、同じ回の値どうしにしてください。組の中の行は、同じ回の中で、順番を無作為に入れ替えて測っています。品質はどの行も標準で、ほかの項目はデフォルトです。ただし、カーネル半径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画素 | 7.7〜8.6ミリ秒 | 9.3〜12.1ミリ秒 |
|
||||
| 素材 | 31画素 | 8.5〜9.5ミリ秒 | 測っていません |
|
||||
| 素材 | 63画素 | 14.9〜19.5ミリ秒 | 24.2〜39.8ミリ秒 |
|
||||
| 素材(検査あり) | 15画素 | 8.2〜10.4ミリ秒 | |
|
||||
| デフォーカス | 15画素 | 8.4〜12.1ミリ秒 | 測っていません |
|
||||
| 利得 | 15画素 | 2.2〜2.7ミリ秒 | 2.4〜2.9ミリ秒 |
|
||||
|
||||
素材と設定が変わらず、畳み込みを再利用するフレームでは、GPUの経路で1.4〜1.9ミリ秒でした。この時間は、素材が変わったかどうかの判定の時間です。
|
||||
| 変えたもの | カーネル半径 | GPUの経路 | CPUの経路 |
|
||||
|---|---:|---:|---:|
|
||||
| 素材 | 15画素 | 7.5〜8.3ミリ秒 | 15.8〜19.7ミリ秒 |
|
||||
| 素材(検査あり) | 15画素 | 8.6〜9.8ミリ秒 | |
|
||||
| 素材の線形光 | 15画素 | 7.7〜8.4ミリ秒 | 17.6〜21.9ミリ秒 |
|
||||
| 素材の線形光(検査あり) | 15画素 | 8.1〜9.2ミリ秒 | |
|
||||
| 素材の線形光とハイライト | 15画素 | 7.3〜8.2ミリ秒 | 22.7〜28.6ミリ秒 |
|
||||
|
||||
2つ目の表では、同じ回の「素材」の行より、線形光の行は、GPUの経路で1〜6%、CPUの経路で9〜24%長くなりました。ハイライトも加えると、CPUの経路は24〜63%長くなりました。2つ目の表は1つ目の表より後に測るので、機器が温まっていて、CPUの経路の「素材」の行が1つ目の表より遅くなっています。
|
||||
|
||||
素材と設定が変わらず、畳み込みを再利用するフレームでは、GPUの経路で1.2〜1.6ミリ秒でした。この時間は、素材が変わったかどうかの判定の時間です。
|
||||
|
||||
素材と利得の行は、前のバージョン(v3.0.0)の同じ行と、同じ時間帯に交互に測って比べました。GPUの経路の行とCPUの経路の行は、別々に測りました。GPUの経路は、前のバージョンの0.99〜1.04倍で、差は測定のばらつきの範囲です。CPUの経路は、素材15画素で約0.35倍、素材63画素で約0.36倍、利得で約0.23倍の時間でした。
|
||||
|
||||
高速フーリエ変換による畳み込みは、画素の値にカーネルの重みを掛けて直接足し合わせる畳み込みと、同じ結果になるはずの計算です。32ビットの浮動小数点数で計算するため、値の丸めによる誤差が生じます。誤差の上限は、タイルの一辺Tごとに導いてあります。導出の全文は、このリポジトリの畳み込みのライブラリ[SpectralConvolution](SpectralConvolution/README.md)の説明にあります。タイルの全画素が不透明な白という最悪の場合について、誤差の上限を、8ビットの値の1階調分を単位にして示します。小数第2位まで切り上げた値です。
|
||||
|
||||
@@ -187,13 +206,63 @@ Tが同じなら、カーネル半径を上げるほど、1枚のタイルが出
|
||||
|
||||
### 6. 利得と適用量
|
||||
|
||||
「利得」は、畳み込んだ結果に掛ける倍率です。100%で画素の値の総和を保ち、上げるほど明るく、下げるほど暗くなります。利得を掛けた結果は、色と不透明度の各成分が表せる最大の値で打ち切り、さらに色の成分が不透明度を超えないように抑えます。
|
||||
「利得」は、畳み込んだ結果に掛ける倍率です。100%で、丸める前の値の総和を保ち、上げるほど明るく、下げるほど暗くなります。出力は8ビットに丸めるので、丸めた後の総和は、小さな明るい点で素材より少なくなることがあります。これは「線形光とハイライトとディザ」で説明します。利得を掛けた結果は、色と不透明度の各成分が表せる最大の値で打ち切り、さらに色の成分が不透明度を超えないように抑えます。
|
||||
|
||||
利得だけを変えたときは、最初の1回だけ畳み込みを計算し直し、利得を掛ける前の結果を保存します。2回目からは、保存した値に利得を掛け直します。
|
||||
利得かディザだけを変えたときは、最初の1回だけ畳み込みを計算し直し、利得を掛ける前の結果を保存します。2回目からは、保存した値に利得とディザを反映して描き直します。
|
||||
|
||||
「適用量」は、入力映像と、利得を掛けた結果を混ぜる割合です。0%では入力を変更せず、100%では利得を掛けた結果だけを出力します。
|
||||
|
||||
### 7. 品質の選択
|
||||
### 7. 線形光とハイライトとディザ
|
||||
|
||||
画素の値は、光の強さに比例していません。光の強さに比例する値を、線形の値と呼びます。sRGBでは、画素の値vから線形の値xを、次の式で求めます。線形の値から画素の値へ戻すときは、この式の逆を使います。
|
||||
|
||||
```
|
||||
v ≤ 0.04045 のとき x = v / 12.92
|
||||
v > 0.04045 のとき x = ((v + 0.055) / 1.055)^2.4
|
||||
```
|
||||
|
||||
光の回折とにじみは、光の強さを足し合わせる現象です。そのため、線形の値で畳み込むほうが、実際の光に合います。白と黒の画素が1画素ずつ交互に並ぶ市松模様を、大きくぼかす場合を考えます。光の強さの平均は白の半分で、これを画素の値に直すと約0.735、8ビットで約188です。画素の値をそのまま平均すると0.5、8ビットで約128になり、実際の光より暗くなります。
|
||||
|
||||
「線形光」をオンにすると、素材の画素の値を線形の値へ直してから畳み込み、結果を画素の値へ戻します。オフのときは、画素の値をそのまま畳み込みます。半透明の画素は、素材の色を不透明度で割って元の色に戻してから変換し、変換した値に不透明度を掛け直します。畳み込んだ結果には、まず利得を掛けます。次に、色と不透明度の各成分を0〜1に打ち切り、色の成分が不透明度を超えないように抑えます。最後に、画素の値へ戻し、不透明度を掛け直して、8ビットに丸めます。
|
||||
|
||||
「ハイライトのしきい値」と「ハイライトの強さ」は、線形光がオンのときだけ働きます。素材は8ビットなので、光源の画素の値は1.0で頭打ちです。実際の光源はもっと明るいはずですが、その明るさは素材に残っていません。回折の筋のように中心よりはるかに小さい光は、そのままでは、出力の8ビットの1階調に届きません。ハイライトの強さを上げると、明るい画素を持ち上げてから畳み込むので、そうした光が見えるようになります。ただし、これは光源の本当の明るさを復元する処理ではなく、指定した倍率で光を足す処理です。
|
||||
|
||||
持ち上げる倍率は、素材の画素ごとに決めます。画素の最も明るいチャンネルの値をmとします。半透明の画素では、素材の色を不透明度で割って元の色に戻した値を使います。しきい値をt、強さをsとすると、倍率は次の式で求めます。
|
||||
|
||||
```
|
||||
e = (m - t) / (1 - t) を0〜1に打ち切った値
|
||||
倍率 = 1 + (s - 1) e^2
|
||||
```
|
||||
|
||||
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階調でした。
|
||||
|
||||
線形光は、GPUの経路では、素材が変わるフレームの時間をほとんど増やしませんでした。CPUの経路では、素材を線形の値へ直す計算が増えて、時間が長くなりました。測った値は、「タイルごとの高速フーリエ変換による畳み込み」の計算時間の表にあります。
|
||||
|
||||
### 8. 品質の選択
|
||||
|
||||
「品質」は、瞳関数を置く格子の大きさを切り替えます。格子は瞳関数の値を縦横に並べた表で、1つ1つの値を標本と呼びます。開口の直径は格子の一辺の4分の1です。格子が大きいほど、開口の縁と波面収差の位相を細かく表せます。
|
||||
|
||||
@@ -209,9 +278,9 @@ Tが同じなら、カーネル半径を上げるほど、1枚のタイルが出
|
||||
|
||||
格子が粗いと、大きな波面収差で位相が急に変わる所を表しきれず、点像分布関数の形が崩れます。水平コマ収差を2 wavesにし、品質ごとに求めたカーネルを、格子が2048×2048のときのカーネルと比べました。ほかの項目はデフォルトです。カーネルの各画素の値の差の絶対値を全画素で足すと、高速で約0.87、標準で約0.38、高精度で約0.03でした。カーネルの値の和は1です。波面収差の絶対値を大きくするときは、品質を上げてください。
|
||||
|
||||
品質を上げると、点像分布関数の計算が重くなります。「利得」と「適用量」以外の項目をアニメーションで変えるときは、フレームごとに点像分布関数を計算し直すので、品質を下げると処理が軽くなります。ただし、開口形状が円形のときは、「羽根枚数」と「開口回転」を変えても、計算し直しません。
|
||||
品質を上げると、点像分布関数の計算が重くなります。光学系グループと開口グループと波面収差グループの項目をアニメーションで変えるときは、フレームごとに点像分布関数を計算し直すので、品質を下げると処理が軽くなります。ただし、開口形状が円形のときは、「羽根枚数」と「開口回転」を変えても、計算し直しません。
|
||||
|
||||
### 8. GPUの計算の検査とCPUの経路
|
||||
### 9. GPUの計算の検査とCPUの経路
|
||||
|
||||
GPUの計算は、ドライバーやハードウェアの不具合で誤った値を返すことがあります。以下では、Windowsが認識しているGPUと、GPUの命令をCPUで実行するソフトウェアを、まとめてアダプターと呼びます。後者をソフトウェア アダプターと呼び、Microsoft Basic Render Driverがこれに当たります。本プラグインは、アダプターが正しく計算できるかを、自己試験と検査で確かめます。自己試験は、決まった入力を計算させて、答えを確かめる処理です。検査は、素材を畳み込んだ結果を確かめる処理です。どちらの詳細も、この節の後半にあります。
|
||||
|
||||
@@ -242,6 +311,8 @@ GPUの経路で畳み込みを計算し直したフレームでは、出力を
|
||||
|
||||
検査では、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回だけです。送信する内容と、送信する報告の数の上限は、「不具合の報告」にあります。
|
||||
@@ -250,7 +321,7 @@ GPUの経路でメモリを確保できなかったときは、YMM4を終了す
|
||||
|
||||
CPUの経路は、論理プロセッサの数までのスレッドで計算します。畳み込むときに、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階調でした。
|
||||
|
||||
[YMM4-ComputeGuard](https://github.com/routersys/YMM4-ComputeGuard)は、計算の経路を選び、検査の合否を判定します。[SpectralConvolution](SpectralConvolution/README.md)は、このリポジトリのフォルダーにあるライブラリで、畳み込みを計算します。YMM4-ComputeGuardは、サブモジュールとして取り込んでいます。
|
||||
|
||||
@@ -263,7 +334,11 @@ GPUの経路とCPUの経路の出力は、1ビット単位では一致しませ
|
||||
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|
||||
|---|---|---|---|---|---|
|
||||
| 適用量 | 数値 | 100% | 0〜100% | 対応 | 入力映像と、利得を掛けた結果を混ぜる割合です。0%では入力を変更しません。 |
|
||||
| 利得 | 数値 | 100% | 0〜400% | 対応 | 畳み込んだ結果に掛ける倍率です。100%で画素の値の総和を保ちます。 |
|
||||
| 利得 | 数値 | 100% | 0〜400% | 対応 | 畳み込んだ結果に掛ける倍率です。100%で、丸める前の値の総和を保ちます。 |
|
||||
| 線形光 | 切り替え | オフ | オフ / オン | 非対応 | 画素の値を光の強さに比例する値へ直してから畳み込み、結果を画素の値へ戻します。 |
|
||||
| ハイライトのしきい値 | 数値 | 95% | 0〜100% | 対応 | 線形光がオンのとき、素材の画素の最も明るいチャンネルがこの割合を超えると、持ち上げ始めます。 |
|
||||
| ハイライトの強さ | 数値 | 1倍 | 1〜100倍 | 対応 | 線形光がオンのとき、最も明るい画素を持ち上げる倍率です。1倍では持ち上げません。直接入力では1000倍まで指定できます。 |
|
||||
| ディザ | 切り替え | オフ | オフ / オン | 非対応 | 8ビットに丸めるとき、画素の位置だけで決まる値を足します。 |
|
||||
|
||||
### 光学系グループ
|
||||
|
||||
@@ -307,7 +382,8 @@ GPUの経路とCPUの経路の出力は、1ビット単位では一致しませ
|
||||
- GPUの異常が起きたアダプターと、GPUの経路でメモリを確保できなかったアダプターは、原因が一時的な不具合でも、YMM4を終了するまでCPUの経路で計算します。このとき、共有テクスチャやタイルの作業領域など、GPUの資源は解放します。
|
||||
- 畳み込みには現在のフレームの色と不透明度だけを使用します。履歴フレーム、外部画像、学習済みモデルは使用しません。素材のすべての画素が透明なときは、エフェクトを適用せず入力映像を表示します。
|
||||
- 計算は単色のフラウンホーファー回折に限ります。白色光のように波長の混ざった光は扱いません。点像分布関数は画面のどこでも同じで、像の位置や素材の奥行きで変わるにじみは扱いません。
|
||||
- 畳み込みは、画素の値をそのまま重み付けして足し合わせます。画素の値を光の強さに比例する値へ直してから畳み込む処理はしません。
|
||||
- 畳み込みは、既定では、画素の値をそのまま重み付けして足し合わせます。「線形光」をオンにしたときだけ、画素の値を光の強さに比例する値へ直してから畳み込みます。
|
||||
- ハイライトは、指定した倍率で明るい画素の光を足す処理です。素材は8ビットで、頭打ちの画素の元の明るさは分からないので、光源の本当の明るさは復元しません。
|
||||
- カーネル半径は1〜63画素です。
|
||||
- 中央遮蔽で開口をほとんどふさぎ、瞳関数の格子に光の通る標本が1つも無くなる設定では、エフェクトを適用せず入力映像を表示します。品質を上げると起きにくくなります。
|
||||
- 計算領域は、透明な部分も含む素材全体の矩形の上下左右に余白を加えた大きさで、長辺は8192画素が上限です。余白は、カーネル半径を4画素単位に切り上げた画素数で、16画素を下回りません。素材の長辺の上限は、8192画素から余白の2倍を引いた値です。カーネル半径が16画素以下なら8160画素、63画素なら8064画素になります。素材の長辺がこの上限を超える場合は、エフェクトを適用せず入力映像を表示します。
|
||||
@@ -321,7 +397,7 @@ GPUの経路とCPUの経路の出力は、1ビット単位では一致しませ
|
||||
|
||||
- 処理負荷: 畳み込む範囲が大きいほど、計算は重くなります。カーネル半径を上げたときの重さの変わり方は、「タイルごとの高速フーリエ変換による畳み込み」にあります。品質を上げた場合は、点像分布関数の計算量が増えます。収差を入れても、畳み込みの計算量は変わりません。ソフトウェア アダプターではないGPUを使える環境では、CPUの経路のほうが、一般に計算が遅くなります。
|
||||
- 品質と収差: 波面収差の絶対値を大きくするときは、品質を上げてください。格子が粗いと点像分布関数の形が崩れます。崩れ方の目安は「品質の選択」にあります。
|
||||
- キャッシュ: 素材の大きさと色と不透明度が変わらず、「利得」と「適用量」以外の項目も変わらないフレームでは、畳み込みの計算を再利用します。利得だけを変えたフレームでは、最初の1回だけ畳み込みを計算し直し、利得を掛ける前の値を保存します。2回目からは、保存した値に利得を掛け直します。素材か、「利得」と「適用量」以外の項目が変わると、保存した値を破棄します。適用量だけを変えたフレームでは、混ぜる割合だけを変えます。動画や口パクのように素材の内容が変わるフレームと、「利得」と「適用量」以外の項目をアニメーションで変えたフレームでは、毎回計算し直すので処理が重くなります。素材が変わったかどうかを調べる計算は、再利用するフレームでも毎フレーム行います。開口形状が円形のときは、「羽根枚数」と「開口回転」を変えても、計算し直しません。
|
||||
- キャッシュ: 素材の大きさと色と不透明度が変わらず、「利得」と「適用量」と「ディザ」以外の項目も変わらないフレームでは、畳み込みの計算を再利用します。利得かディザだけを変えたフレームでは、最初の1回だけ畳み込みを計算し直し、利得を掛ける前の値を保存します。2回目からは、保存した値に利得とディザを反映して描き直します。素材か、「利得」と「適用量」と「ディザ」以外の項目が変わると、保存した値を破棄します。ただし、線形光がオフのときは、ハイライトの2項目が変わっても破棄しません。適用量だけを変えたフレームでは、混ぜる割合だけを変えます。動画や口パクのように素材の内容が変わるフレームと、「利得」と「適用量」と「ディザ」以外の項目をアニメーションで変えたフレームでは、毎回計算し直すので処理が重くなります。素材が変わったかどうかを調べる計算は、再利用するフレームでも毎フレーム行います。開口形状が円形のときは、「羽根枚数」と「開口回転」を変えても、計算し直しません。
|
||||
- 適用量0%: 適用量が0%のときは入力を変更せず、畳み込みの計算も行いません。
|
||||
- 再現性: 計算は決定論的で、時間値や乱数を使用しません。同じ素材と同じ設定から常に同じ結果になるのは、同じ経路で、GPU、ドライバー、CPU、Windows、.NETの組が同じときです。GPUの経路でも結果にCPUが関わるのは、点像分布関数とカーネルのスペクトルをCPUで求めるためです。GPUの経路とCPUの経路では、結果がわずかに違います。GPUの異常でCPUの経路に切り替わったときも、同じ設定で結果がわずかに変わります。
|
||||
- 透明部分: 畳み込みは不透明度にも掛かるので、素材の縁の外にも半透明のにじみが広がります。出力の範囲は、素材の範囲と畳み込む範囲を合わせたものです。適用量が0%のときは、素材の範囲のままです。
|
||||
|
||||
@@ -25,6 +25,7 @@ YMM4 のプラグインが、画像とカーネルの畳み込みを、CPU と G
|
||||
- [4. GPU の経路](#4-gpu-の経路)
|
||||
- [5. 検査の材料と検査](#5-検査の材料と検査)
|
||||
- [6. 自己試験](#6-自己試験)
|
||||
- [7. 線形光とハイライトとディザ](#7-線形光とハイライトとディザ)
|
||||
6. [誤差の上限](#誤差の上限)
|
||||
- [前提](#前提)
|
||||
- [記号](#記号)
|
||||
@@ -136,6 +137,8 @@ SpectralConvolution/ 外側
|
||||
| `DirectCorrelation` | 式 (1) を倍精度でそのまま足し合わせる計算。検査の参照値に使う |
|
||||
| `TileInput` | タイルが読む素材の 2 ノルム。8 ビットの値を 255 で割った値で求める |
|
||||
| `FastFourierTransform` | 倍精度の高速フーリエ変換。カーネルのスペクトルに使う |
|
||||
| `LightOptions` | 線形光、ディザ、ハイライトの設定 |
|
||||
| `LightTransform` | 線形光とハイライトで素材を直す変換と、出力を 8 ビットにする変換。CPU の経路と、検査の参照値に使う |
|
||||
|
||||
表の 2 ノルムは、素材の 8 ビットの値を 255 で割った値の 2 乗の和の平方根です。赤と緑、青と不透明度の 2 組ごとに求めます。スペクトルは、カーネルを高速フーリエ変換した値です。回転因子とスペクトルは、[タイルに分けた畳み込み](#1-タイルに分けた畳み込み)で説明します。
|
||||
|
||||
@@ -160,6 +163,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
|
||||
@@ -224,6 +234,8 @@ var count = SpectralSelfTest.Run(device, maximumRadius, measurements);
|
||||
|
||||
カーネルのスペクトルは、カーネルを 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 +258,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 ビットのベクトルにまとめます。足し算、引き算、掛け算の順番と回数は、スカラーで書いた式と同じで、融合積和は使いません。そのため、結果はスカラーの式と 1 ビットも違いません。`CpuTileConvolver.ButterfliesScalar` が、基準にするスカラーの式です。試験は、`Butterflies` の結果をこの式の結果と、ビットごとに比べます。素材を行に置くときの、8 ビットの値を 255 で割る計算は、256 個の値の表で行います。表の値は、同じ割り算の結果なので、割り算と同じ値です。
|
||||
|
||||
ゲインだけを変えるときは、畳み込みをやり直さずに出力できます。そのために、`Convolve` の最後の引数 `convolvedValues` に配列を渡します。渡した配列に、ゲインを掛ける前の値が float で保存されます。保存する値は、画素ごとに R、G、B、A の順の float 4 つで、出力の BGRA とは順が違います。配列の長さは、畳み込む範囲の幅 × 高さ × 4 以上です。
|
||||
|
||||
`RenderStored` は、保存した値に別のゲインを掛けて出力し直します。結果は、そのゲインで畳み込みと同時に出力した場合と 1 ビットも違いません。`RenderStored` は、16384 画素を 1 単位として、スレッドに割り当てます。
|
||||
@@ -268,6 +282,8 @@ var count = SpectralSelfTest.Run(device, maximumRadius, measurements);
|
||||
|
||||
浮動小数点数を計算するシェーダーは、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. 検査の材料と検査
|
||||
@@ -315,6 +331,65 @@ 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 が足した値なので、総和の検査は、素材を直す計算の誤りを見つけません。この誤りは、抜き取りが見つけます。
|
||||
|
||||
---
|
||||
|
||||
## 誤差の上限
|
||||
@@ -332,11 +407,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 +446,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
|
||||
@@ -517,6 +594,7 @@ Z = G × 511 × 2^-126
|
||||
- タイルどうしは互いに独立しています。CPU の経路では、スレッド数と、どのスレッドがどのタイルを受け持つかを変えても、結果は 1 ビットも変わりません。
|
||||
- GPU の経路では、同じデバイスで同じ入力を 2 回計算すると、結果は 1 ビットも変わりません。単体試験と自己試験で確かめています。
|
||||
- 出力の和は、グループの中では決まった木の形で、グループどうしは CPU が決まった順で足します。NaN と無限大の個数、素材の和と 2 乗の和は、整数のアトミック加算で数えます。整数の加算は順序に左右されないので、毎回同じ値になります。
|
||||
- `LightOptions` が既定でないとき、素材の和と 2 乗の和は、グループの中では決まった木の形で足した float です。同じデバイスで同じ入力を 2 回計算すると、同じ値になります。
|
||||
- CPU の経路と GPU の経路は、結果が 1 ビット単位では一致するとは限りません。Direct3D の規則では、GPU は加算、減算、乗算の結果を、最も近い値へ丸める代わりに切り捨てることも許されているためです。2 つの経路の差は、それぞれの誤差の上限の和を超えません。
|
||||
|
||||
---
|
||||
@@ -559,7 +637,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 +655,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 倍すると、総和の検査で不合格になること
|
||||
- スペクトルの虚部の符号を反転すると、抜き取りの検査で不合格になり、総和の検査は合格のままであること。この反転は、カーネルの上下と左右を反転することに当たります。
|
||||
|
||||
@@ -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,109 @@ 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);
|
||||
}
|
||||
|
||||
// The region starts at (regionX, regionY) of the canvas, and the source lies inside it at (sourceX, sourceY).
|
||||
// The helpers that compare with the exact correlation assume a region at the origin, so a scene made
|
||||
// here is only for comparing two implementations with each other.
|
||||
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];
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using ComputeWeave;
|
||||
|
||||
namespace SpectralConvolution.Tests;
|
||||
|
||||
public sealed class CpuTileConvolverTests
|
||||
@@ -262,4 +264,348 @@ public sealed class CpuTileConvolverTests
|
||||
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(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();
|
||||
|
||||
CpuTileConvolver.ButterfliesScalar(expected, log2, twiddles, direction);
|
||||
CpuTileConvolver.Butterflies(actual, log2, twiddles, direction);
|
||||
CpuTileConvolver.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>(() => CpuTileConvolver.Butterflies(new float[8 * 4 - 1], 3, twiddles, 1f));
|
||||
Assert.Throws<ArgumentException>(() => CpuTileConvolver.Butterflies(new float[8 * 4], 3, twiddles.AsSpan(0, 3), 1f));
|
||||
}
|
||||
|
||||
[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(CpuTileConvolver.ToUnorm(stored[pixel * 4 + 2] * gain), output[pixel * 4]);
|
||||
Assert.Equal(CpuTileConvolver.ToUnorm(stored[pixel * 4 + 1] * gain), output[pixel * 4 + 1]);
|
||||
Assert.Equal(CpuTileConvolver.ToUnorm(stored[pixel * 4] * gain), output[pixel * 4 + 2]);
|
||||
Assert.Equal(CpuTileConvolver.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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
@@ -343,4 +343,398 @@ 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}"));
|
||||
}
|
||||
|
||||
static void AssertOutputIsTheTransformOfTheStore(ConvolutionScene scene, GpuRun run, float gain, LightOptions light)
|
||||
{
|
||||
var width = scene.Plan.RegionWidth;
|
||||
var differing = 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);
|
||||
differing += (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);
|
||||
}
|
||||
}
|
||||
|
||||
// The power function of the GPU differs from the table of the CPU by a few millionths, which moves the
|
||||
// rounded value by one step in a few of ten thousand places. A wrong threshold or a wrong rounding
|
||||
// moves it in about a third of them.
|
||||
Assert.InRange(differing, 0, run.Output.Length / 2000);
|
||||
}
|
||||
|
||||
[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()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,556 @@
|
||||
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 = CpuTileConvolver.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 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();
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.ExceptionServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Intrinsics;
|
||||
using ComputeWeave;
|
||||
|
||||
namespace SpectralConvolution;
|
||||
@@ -9,6 +12,8 @@ internal sealed class CpuTileConvolver : IDisposable
|
||||
public const int StoredChunkPixels = 16384;
|
||||
const int Channels = 4;
|
||||
|
||||
static readonly float[] Units = BuildUnits();
|
||||
|
||||
readonly Worker[] workers;
|
||||
readonly Thread[] threads;
|
||||
readonly SemaphoreSlim start = new(0);
|
||||
@@ -29,10 +34,14 @@ internal sealed class CpuTileConvolver : IDisposable
|
||||
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)
|
||||
@@ -79,7 +88,8 @@ internal sealed class CpuTileConvolver : IDisposable
|
||||
in TilePlan tilePlan,
|
||||
byte[] outputPixels,
|
||||
float outputGain,
|
||||
float[]? convolvedValues)
|
||||
float[]? convolvedValues,
|
||||
LightOptions lightOptions = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sourcePixels);
|
||||
ArgumentNullException.ThrowIfNull(kernelSpectrum);
|
||||
@@ -97,6 +107,7 @@ 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);
|
||||
@@ -112,6 +123,7 @@ internal sealed class CpuTileConvolver : IDisposable
|
||||
plan = tilePlan;
|
||||
output = outputPixels;
|
||||
gain = outputGain;
|
||||
light = lightOptions;
|
||||
convolved = convolvedValues;
|
||||
try
|
||||
{
|
||||
@@ -126,7 +138,15 @@ internal sealed class CpuTileConvolver : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
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 +157,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,8 +169,12 @@ 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));
|
||||
@@ -174,6 +201,14 @@ internal sealed class CpuTileConvolver : IDisposable
|
||||
ExceptionDispatchInfo.Throw(exception);
|
||||
}
|
||||
|
||||
static float[] BuildUnits()
|
||||
{
|
||||
var units = new float[256];
|
||||
for (var level = 0; level < units.Length; level++)
|
||||
units[level] = level / 255f;
|
||||
return units;
|
||||
}
|
||||
|
||||
public static byte ToUnorm(float value)
|
||||
{
|
||||
if (float.IsNaN(value))
|
||||
@@ -277,15 +312,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 || !LoadRow(row, order, sourceRow, left, first, last))
|
||||
{
|
||||
row.Clear();
|
||||
continue;
|
||||
}
|
||||
|
||||
lit = true;
|
||||
Butterflies(line, log2, twiddles, 1f);
|
||||
line.CopyTo(row);
|
||||
Butterflies(row, log2, twiddles, 1f);
|
||||
}
|
||||
|
||||
var regionLeft = plan.OriginX(tile) - plan.RegionX;
|
||||
@@ -298,83 +332,151 @@ internal sealed class CpuTileConvolver : IDisposable
|
||||
return;
|
||||
}
|
||||
|
||||
ref var workStart = ref MemoryMarshal.GetReference(work);
|
||||
ref var lineStart = ref MemoryMarshal.GetReference(line);
|
||||
ref var spareStart = ref MemoryMarshal.GetReference(spare);
|
||||
for (var column = 0; column < size; column++)
|
||||
{
|
||||
for (var y = 0; y < size; y++)
|
||||
work.Slice((y * size + column) * Channels, Channels).CopyTo(line.Slice(order[y] * Channels, Channels));
|
||||
Copy(ref workStart, (y * size + column) * Channels, ref lineStart, order[y] * Channels);
|
||||
|
||||
Butterflies(line, log2, twiddles, 1f);
|
||||
var spectrumColumn = values.Slice(column * size, size);
|
||||
for (var frequency = 0; frequency < size; frequency++)
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
Multiply(line, spare, order, values.Slice(column * size, size));
|
||||
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));
|
||||
Copy(ref spareStart, y * Channels, ref workStart, (y * size + column) * Channels);
|
||||
}
|
||||
|
||||
var scale = 1f / (size * size);
|
||||
var light = this.light;
|
||||
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);
|
||||
var outputRow = regionTop + y - radius;
|
||||
for (var x = radius; x < radius + validWidth; x++)
|
||||
{
|
||||
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 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)
|
||||
Emit(pixels, scale, gain, bytes, store);
|
||||
else
|
||||
Emit(pixels, scale, gain, in light, outputOrigin, plan.RegionY + outputRow, bytes, store);
|
||||
}
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
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(255f) + Vector128.Create(0.5f)).AsUInt32();
|
||||
var words = Vector128.Narrow(levels, levels);
|
||||
return Vector128.Narrow(words, words).AsUInt32().ToScalar();
|
||||
}
|
||||
|
||||
[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 = value * Vector128.Create(weight.X)
|
||||
+ Vector128.Shuffle(value, Vector128.Create(1, 0, 3, 2)) * Vector128.Create(-weight.Y, weight.Y, -weight.Y, 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);
|
||||
Emit(pixels, 1f, gain, bytes, default);
|
||||
return;
|
||||
}
|
||||
|
||||
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;
|
||||
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++;
|
||||
}
|
||||
}
|
||||
|
||||
bool LoadRow(Span<float> line, ReadOnlySpan<int> order, int sourceRow, int left, int first, int last)
|
||||
bool LoadRow(Span<float> row, ReadOnlySpan<int> order, int sourceRow, int left, int first, int last)
|
||||
{
|
||||
line.Clear();
|
||||
row.Clear();
|
||||
var lit = false;
|
||||
var pixels = source.AsSpan(sourceRow * sourceWidth * Channels, sourceWidth * Channels);
|
||||
var light = this.light;
|
||||
var units = Units;
|
||||
for (var x = first; x < last; x++)
|
||||
{
|
||||
var offset = (left + x - sourceX) * Channels;
|
||||
@@ -386,10 +488,21 @@ internal sealed class CpuTileConvolver : IDisposable
|
||||
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;
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -406,7 +519,65 @@ internal sealed class CpuTileConvolver : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
static void Butterflies(Span<float> line, int log2, ReadOnlySpan<Float2> twiddles, float direction)
|
||||
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);
|
||||
for (var stage = 0; stage < log2; stage++)
|
||||
{
|
||||
var half = 1 << stage;
|
||||
var shift = log2 - 1 - stage;
|
||||
var distance = (nuint)(half * Channels);
|
||||
if (allowWide && Vector256.IsHardwareAccelerated && half >= 2)
|
||||
{
|
||||
// Two neighboring positions of a block share one load. Every butterfly is the same
|
||||
// arithmetic as the scalar form, so the results match it bit for bit.
|
||||
for (var position = 0; position < half; position += 2)
|
||||
{
|
||||
var near = Unsafe.Add(ref table, position << shift);
|
||||
var far = Unsafe.Add(ref table, (position + 1) << shift);
|
||||
var nearImaginary = near.Y * direction;
|
||||
var farImaginary = far.Y * direction;
|
||||
var real = Vector256.Create(near.X, near.X, near.X, near.X, far.X, far.X, far.X, far.X);
|
||||
var imaginary = Vector256.Create(-nearImaginary, nearImaginary, -nearImaginary, nearImaginary, -farImaginary, farImaginary, -farImaginary, farImaginary);
|
||||
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 = oddValue * real + Vector256.Shuffle(oddValue, Vector256.Create(1, 0, 3, 2, 5, 4, 7, 6)) * imaginary;
|
||||
(evenValue + product).StoreUnsafe(ref data, even);
|
||||
(evenValue - product).StoreUnsafe(ref data, even + distance);
|
||||
}
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
for (var position = 0; position < half; position++)
|
||||
{
|
||||
var twiddle = Unsafe.Add(ref table, position << shift);
|
||||
var imaginaryPart = twiddle.Y * direction;
|
||||
var real = Vector128.Create(twiddle.X);
|
||||
var imaginary = Vector128.Create(-imaginaryPart, imaginaryPart, -imaginaryPart, imaginaryPart);
|
||||
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 = oddValue * real + Vector128.Shuffle(oddValue, Vector128.Create(1, 0, 3, 2)) * imaginary;
|
||||
(evenValue + product).StoreUnsafe(ref data, even);
|
||||
(evenValue - product).StoreUnsafe(ref data, even + 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++)
|
||||
|
||||
@@ -34,6 +34,41 @@ internal static class DirectCorrelation
|
||||
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)(packed & 255u), (byte)(packed >> 8 & 255u), (byte)(packed >> 16 & 255u), (byte)(packed >> 24), in light);
|
||||
red += linearRed * weight;
|
||||
green += linearGreen * weight;
|
||||
blue += linearBlue * weight;
|
||||
alpha += linearAlpha * weight;
|
||||
}
|
||||
|
||||
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> kernel, int radius, int x, int y, Span<double> result)
|
||||
{
|
||||
var kernelSize = radius * 2 + 1;
|
||||
|
||||
@@ -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]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,9 +178,24 @@ internal static class FastFourierTransform
|
||||
{
|
||||
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,494 @@
|
||||
using ComputeWeave;
|
||||
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal static class LightShaderMath
|
||||
{
|
||||
public static float Decode(float encoded)
|
||||
{
|
||||
if (encoded <= 0.04045f)
|
||||
return encoded / 12.92f;
|
||||
if (encoded >= 1f)
|
||||
return 1f;
|
||||
return Hlsl.Pow((encoded + 0.055f) / 1.055f, 2.4f);
|
||||
}
|
||||
|
||||
public static float Encode(float linear)
|
||||
{
|
||||
if (linear <= 0.0031308f)
|
||||
return 12.92f * linear;
|
||||
if (linear >= 1f)
|
||||
return 1f;
|
||||
return 1.055f * Hlsl.Pow(linear, 0.41666666f) - 0.055f;
|
||||
}
|
||||
}
|
||||
|
||||
internal static class LightShaderOutput
|
||||
{
|
||||
public static float DitherThreshold(int x, int y)
|
||||
{
|
||||
var hash = (uint)x * 0x9E3779B1u ^ (uint)y * 0x85EBCA77u;
|
||||
hash ^= hash >> 16;
|
||||
hash *= 0x7FEB352Du;
|
||||
hash ^= hash >> 15;
|
||||
hash *= 0x846CA68Bu;
|
||||
hash ^= hash >> 16;
|
||||
return (hash >> 8) * (1f / 16777216f);
|
||||
}
|
||||
|
||||
public static float Quantize(float value, int dither, float threshold)
|
||||
{
|
||||
if (dither == 0)
|
||||
return Hlsl.Floor(value * 255f + 0.5f);
|
||||
return Hlsl.Min(Hlsl.Floor(value * 255f + threshold), 255f);
|
||||
}
|
||||
|
||||
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 = DitherThreshold(x, y);
|
||||
return new Float4(
|
||||
Quantize(red, dither, threshold) / 255f,
|
||||
Quantize(green, dither, threshold) / 255f,
|
||||
Quantize(blue, dither, threshold) / 255f,
|
||||
Quantize(alpha, dither, threshold) / 255f);
|
||||
}
|
||||
}
|
||||
|
||||
[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(256, 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(512)]
|
||||
private static readonly Float4[] row = null!;
|
||||
|
||||
[GroupShared(256)]
|
||||
private static readonly Float4[] partialSums = null!;
|
||||
|
||||
[GroupShared(256)]
|
||||
private static readonly Float2[] partialSquares = null!;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var local = GroupIds.X;
|
||||
var groupBase = (ThreadIds.X - local) * 2;
|
||||
var size = (int)(1u << log2Size);
|
||||
var mask = size - 1;
|
||||
var shift = 32 - log2Size;
|
||||
|
||||
// A group of 512 elements never lies in two tiles, so one division serves the whole group.
|
||||
var tileIndex = batchStart + (groupBase >> (log2Size * 2));
|
||||
var tileRow = tileIndex / tilesX;
|
||||
var originX = regionX + (tileIndex - tileRow * tilesX) * validSize - radius;
|
||||
var originY = regionY + tileRow * validSize - radius;
|
||||
|
||||
var sums = new Float4(0f, 0f, 0f, 0f);
|
||||
var squares = new Float2(0f, 0f);
|
||||
for (var pair = 0; pair < 2; pair++)
|
||||
{
|
||||
var element = local * 2 + 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 = (int)(Hlsl.ReverseBits((uint)x) >> shift);
|
||||
row[((element >> log2Size) << log2Size) + reversed] = value;
|
||||
}
|
||||
|
||||
partialSums[local] = sums;
|
||||
partialSquares[local] = squares;
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
for (var stride = 128; 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 + (ThreadIds.X >> 8)) * 6;
|
||||
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, 1f);
|
||||
|
||||
tiles[groupBase + local * 2] = row[local * 2];
|
||||
tiles[groupBase + local * 2 + 1] = row[local * 2 + 1];
|
||||
}
|
||||
|
||||
private Float4 Transform(Float4 value)
|
||||
{
|
||||
if (linear == 0)
|
||||
return value;
|
||||
|
||||
var red = (float)(uint)(value.X * 255f + 0.5f);
|
||||
var green = (float)(uint)(value.Y * 255f + 0.5f);
|
||||
var blue = (float)(uint)(value.Z * 255f + 0.5f);
|
||||
var alpha = (float)(uint)(value.W * 255f + 0.5f);
|
||||
if (alpha == 0f)
|
||||
return new Float4(0f, 0f, 0f, 0f);
|
||||
|
||||
var opacity = alpha / 255f;
|
||||
var straightRed = red / 255f;
|
||||
var straightGreen = green / 255f;
|
||||
var straightBlue = blue / 255f;
|
||||
if (alpha != 255f)
|
||||
{
|
||||
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 halfSize = (int)(1u << (log2Size - 1));
|
||||
var rowBase = (local >> (log2Size - 1)) << log2Size;
|
||||
var pair = local & (halfSize - 1);
|
||||
for (var stage = 0; stage < log2Size; stage++)
|
||||
{
|
||||
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;
|
||||
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;
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[ThreadGroupSize(256, 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(512)]
|
||||
private static readonly Float4[] row = null!;
|
||||
|
||||
[GroupShared(256)]
|
||||
private static readonly Float4[] partial = null!;
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
var local = GroupIds.X;
|
||||
var groupBase = (ThreadIds.X - local) * 2;
|
||||
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];
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
Butterflies(local, -1f);
|
||||
|
||||
// A group of 512 elements never lies in two tiles, so one division serves the whole group. The
|
||||
// samples buffer lists the sample positions first and then, one bit per tile, the tiles that hold a
|
||||
// sample, so that only the threads of those tiles look for samples.
|
||||
var tileIndex = batchStart + (groupBase >> (log2Size * 2));
|
||||
var tileRow = tileIndex / tilesX;
|
||||
var originX = (tileIndex - tileRow * tilesX) * validSize - radius;
|
||||
var originY = tileRow * validSize - radius;
|
||||
var sampled = sampleCount > 0 && IsSampled(tileIndex);
|
||||
partial[local] = Emit(groupBase + element0, row[element0] * scale, size, mask, originX, originY, sampled)
|
||||
+ Emit(groupBase + element1, row[element1] * scale, size, mask, originX, originY, sampled);
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
for (var stride = 128; 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 + (ThreadIds.X >> 8)) * 4;
|
||||
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 IsSampled(int tileIndex)
|
||||
{
|
||||
var entry = samples[sampleTilesOffset + (tileIndex >> 6)];
|
||||
var bits = (tileIndex & 32) == 0 ? (uint)entry.X : (uint)entry.Y;
|
||||
return ((bits >> (tileIndex & 31)) & 1u) != 0u;
|
||||
}
|
||||
|
||||
private Float4 Emit(int flat, Float4 value, int size, int mask, int originX, int originY, bool sampled)
|
||||
{
|
||||
if (IsNonFinite(value.X) || IsNonFinite(value.Y) || IsNonFinite(value.Z) || IsNonFinite(value.W))
|
||||
Hlsl.InterlockedAdd(ref report[0], 1u);
|
||||
|
||||
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 = originX + x;
|
||||
var outputY = originY + 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 (sampled)
|
||||
{
|
||||
for (var sample = 0; sample < sampleCount; sample++)
|
||||
{
|
||||
var position = samples[sample];
|
||||
if (position.X == outputX && position.Y == outputY)
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 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;
|
||||
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;
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,8 @@ internal static class GpuTileCheck
|
||||
public const string NonFiniteName = "nonfinite";
|
||||
public const int GroupAdditions = 9;
|
||||
public const int GroupElements = TilePlan.GroupElements;
|
||||
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"];
|
||||
@@ -36,15 +38,18 @@ internal static class GpuTileCheck
|
||||
if (measurements.Length < MeasurementCount(job.SampleCount))
|
||||
throw new ArgumentException(null, nameof(measurements));
|
||||
|
||||
var light = job.Light;
|
||||
var floating = !light.IsDefault;
|
||||
var relative = ConvolutionBound.Relative(plan.Size, ConvolutionBound.GpuOperationError);
|
||||
var flushed = ConvolutionBound.FlushedOperations(plan.Size) * ConvolutionBound.SmallestNormal;
|
||||
measurements[0] = new ConvolutionMeasurement(NonFiniteName, report[GpuTileLayout.CountOffset], 0d, 0d);
|
||||
|
||||
Span<ulong> totals = stackalloc ulong[4];
|
||||
Span<double> floatTotals = stackalloc double[4];
|
||||
Span<double> errors = stackalloc double[4];
|
||||
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);
|
||||
@@ -54,7 +59,12 @@ internal static class GpuTileCheck
|
||||
{
|
||||
var offset = GpuTileLayout.StatisticsOffset + group * GpuTileLayout.StatisticsPerGroup;
|
||||
for (var channel = 0; channel < 4; channel++)
|
||||
totals[channel] += report[offset + channel];
|
||||
{
|
||||
if (floating)
|
||||
floatTotals[channel] += BitConverter.UInt32BitsToSingle(report[offset + channel]);
|
||||
else
|
||||
totals[channel] += report[offset + channel];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,16 +72,19 @@ internal static class GpuTileCheck
|
||||
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;
|
||||
var inputRounding = ConvolutionBound.Gamma(InputStatisticsOperations, ConvolutionBound.GpuOperationError);
|
||||
for (var channel = 0; channel < 4; 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] / 255d;
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -81,18 +94,39 @@ internal static class GpuTileCheck
|
||||
{
|
||||
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);
|
||||
var (redGreen, blueAlpha) = Norms(report, plan, tile, floating);
|
||||
DirectCorrelation.Evaluate(report.Slice(layout.GatheredOffset + sample * job.KernelArea, job.KernelArea), kernel, light, expected);
|
||||
for (var channel = 0; channel < 4; channel++)
|
||||
{
|
||||
var norm = channel < 2 ? redGreen : blueAlpha;
|
||||
var measured = BitConverter.UInt32BitsToSingle(report[layout.SpotsOffset + sample * GpuTileLayout.ValuesPerSpot + channel]);
|
||||
var tolerance = relative * norm + flushed + referenceError;
|
||||
if (light.Linear)
|
||||
tolerance += LightTransformError * norm;
|
||||
measurements[1 + SumNames.Length + sample * 4 + 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;
|
||||
|
||||
@@ -27,7 +27,8 @@ internal readonly record struct GpuTileJob(
|
||||
int SourceHeight,
|
||||
float Gain,
|
||||
int SampleCount,
|
||||
bool Store)
|
||||
bool Store,
|
||||
LightOptions Light = default)
|
||||
{
|
||||
public int KernelArea => (Plan.Radius * 2 + 1) * (Plan.Radius * 2 + 1);
|
||||
|
||||
@@ -39,8 +40,9 @@ internal sealed class GpuTileConvolver : IDisposable
|
||||
public const int MaximumSamples = 16;
|
||||
|
||||
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;
|
||||
@@ -102,10 +104,12 @@ internal sealed class GpuTileConvolver : IDisposable
|
||||
int sourceHeight,
|
||||
float gain,
|
||||
ReadOnlySpan<Int2> sampleValues,
|
||||
bool storeValues)
|
||||
bool storeValues,
|
||||
LightOptions light = default)
|
||||
{
|
||||
if (plan.Size != spectrumSize || plan.Radius != spectrumRadius)
|
||||
throw new InvalidOperationException();
|
||||
light.Validate();
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sourceWidth);
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sourceHeight);
|
||||
if (!float.IsFinite(gain))
|
||||
@@ -118,7 +122,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);
|
||||
var tileLength = (long)plan.BatchTiles * plan.TileElements;
|
||||
if (tiles is null || tiles.Length < tileLength)
|
||||
{
|
||||
@@ -150,10 +154,39 @@ internal sealed class GpuTileConvolver : IDisposable
|
||||
}
|
||||
|
||||
if (sampleValues.Length > 0)
|
||||
samples.CopyFrom(sampleValues);
|
||||
UploadSamples(sampleValues, plan);
|
||||
return job;
|
||||
}
|
||||
|
||||
// The samples buffer lists the sample positions, then one bit per tile, 64 tiles to an entry, that is set
|
||||
// for the tiles holding a sample. The shaders look for samples only in those tiles.
|
||||
void UploadSamples(ReadOnlySpan<Int2> sampleValues, in TilePlan plan)
|
||||
{
|
||||
var length = MaximumSamples + (plan.TileCount + 63) / 64;
|
||||
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);
|
||||
ref var entry = ref staging[MaximumSamples + (tile >> 6)];
|
||||
if ((tile & 32) == 0)
|
||||
entry.X |= 1 << (tile & 31);
|
||||
else
|
||||
entry.Y |= 1 << (tile & 31);
|
||||
}
|
||||
|
||||
samples.CopyFrom(staging);
|
||||
}
|
||||
|
||||
public ReadWriteBuffer<Float4> StoreFor(in GpuTileJob job)
|
||||
=> job.Store ? store ?? throw new InvalidOperationException() : spare;
|
||||
|
||||
@@ -209,18 +242,38 @@ internal sealed class GpuTileConvolver : IDisposable
|
||||
var count = Math.Min(plan.BatchTiles, plan.TileCount - start);
|
||||
var threads = count * plan.TileElements / 2;
|
||||
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);
|
||||
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, 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);
|
||||
context.For(threads, new ColumnShader(tiles, twiddles, spectrum, plan.Log2Size));
|
||||
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);
|
||||
@@ -235,6 +288,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();
|
||||
|
||||
@@ -157,6 +157,12 @@ internal readonly partial struct ForwardRowShader(
|
||||
statistics[local] = 0u;
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
|
||||
// A group of 512 elements never lies in two tiles, so one division serves the whole group.
|
||||
var tileIndex = batchStart + (groupBase >> (log2Size * 2));
|
||||
var tileRow = tileIndex / tilesX;
|
||||
var originX = regionX + (tileIndex - tileRow * tilesX) * validSize - radius;
|
||||
var originY = regionY + tileRow * validSize - radius;
|
||||
|
||||
var sumRed = 0u;
|
||||
var sumGreen = 0u;
|
||||
var sumBlue = 0u;
|
||||
@@ -167,13 +173,11 @@ internal readonly partial struct ForwardRowShader(
|
||||
{
|
||||
var element = local * 2 + 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;
|
||||
@@ -361,7 +365,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,6 +388,7 @@ 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)]
|
||||
private static readonly Float4[] row = null!;
|
||||
@@ -405,7 +411,16 @@ internal readonly partial struct InverseRowShader(
|
||||
|
||||
Butterflies(local, -1f);
|
||||
|
||||
partial[local] = Emit(groupBase + element0, row[element0] * scale, size, mask) + Emit(groupBase + element1, row[element1] * scale, size, mask);
|
||||
// A group of 512 elements never lies in two tiles, so one division serves the whole group. The
|
||||
// samples buffer lists the sample positions first and then, one bit per tile, the tiles that hold a
|
||||
// sample, so that only the threads of those tiles look for samples.
|
||||
var tileIndex = batchStart + (groupBase >> (log2Size * 2));
|
||||
var tileRow = tileIndex / tilesX;
|
||||
var originX = (tileIndex - tileRow * tilesX) * validSize - radius;
|
||||
var originY = tileRow * validSize - radius;
|
||||
var sampled = sampleCount > 0 && IsSampled(tileIndex);
|
||||
partial[local] = Emit(groupBase + element0, row[element0] * scale, size, mask, originX, originY, sampled)
|
||||
+ Emit(groupBase + element1, row[element1] * scale, size, mask, originX, originY, sampled);
|
||||
Hlsl.GroupMemoryBarrierWithGroupSync();
|
||||
for (var stride = 128; stride > 0; stride >>= 1)
|
||||
{
|
||||
@@ -425,36 +440,44 @@ internal readonly partial struct InverseRowShader(
|
||||
}
|
||||
}
|
||||
|
||||
private Float4 Emit(int flat, Float4 value, int size, int mask)
|
||||
private bool IsSampled(int tileIndex)
|
||||
{
|
||||
var entry = samples[sampleTilesOffset + (tileIndex >> 6)];
|
||||
var bits = (tileIndex & 32) == 0 ? (uint)entry.X : (uint)entry.Y;
|
||||
return ((bits >> (tileIndex & 31)) & 1u) != 0u;
|
||||
}
|
||||
|
||||
private Float4 Emit(int flat, Float4 value, int size, int mask, int originX, int originY, bool sampled)
|
||||
{
|
||||
if (IsNonFinite(value.X) || IsNonFinite(value.Y) || IsNonFinite(value.Z) || IsNonFinite(value.W))
|
||||
Hlsl.InterlockedAdd(ref report[0], 1u);
|
||||
|
||||
var tile = flat >> (log2Size * 2);
|
||||
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 = originX + x;
|
||||
var outputY = originY + 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 (sampled)
|
||||
{
|
||||
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)
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,8 +5,10 @@ namespace SpectralConvolution;
|
||||
internal sealed class KernelSpectrum
|
||||
{
|
||||
double[] kernel = [];
|
||||
double[] real = [];
|
||||
double[] imaginary = [];
|
||||
double[] rowReal = [];
|
||||
double[] rowImaginary = [];
|
||||
double[] columnReal = [];
|
||||
double[] columnImaginary = [];
|
||||
Float2[] twiddles = [];
|
||||
Float2[] spectrum = [];
|
||||
|
||||
@@ -40,17 +42,23 @@ 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)
|
||||
if (rowReal.Length < rowArea)
|
||||
{
|
||||
real = new double[area];
|
||||
imaginary = new double[area];
|
||||
spectrum = new Float2[area];
|
||||
rowReal = new double[rowArea];
|
||||
rowImaginary = new double[rowArea];
|
||||
}
|
||||
if (columnReal.Length < size)
|
||||
{
|
||||
columnReal = new double[size];
|
||||
columnImaginary = new double[size];
|
||||
}
|
||||
if (spectrum.Length < size * size)
|
||||
spectrum = new Float2[size * size];
|
||||
if (twiddles.Length < size / 2)
|
||||
twiddles = new Float2[size / 2];
|
||||
|
||||
@@ -59,26 +67,51 @@ 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++)
|
||||
for (var row = 0; row < kernelSize; row++)
|
||||
{
|
||||
var realLine = rowReal.AsSpan(row * size, size);
|
||||
var imaginaryLine = rowImaginary.AsSpan(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 = columnReal.AsSpan(0, size);
|
||||
var imaginary = columnImaginary.AsSpan(0, 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]));
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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,235 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Intrinsics;
|
||||
|
||||
namespace SpectralConvolution;
|
||||
|
||||
internal static class LightTransform
|
||||
{
|
||||
public const int Channels = 4;
|
||||
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;
|
||||
|
||||
// Encode and Decode read tables of value and slope pairs and interpolate between the entries, because
|
||||
// the power function costs more than everything else the CPU does for one pixel. The tables are
|
||||
// indexed by the bits of the float that is converted, so the steps are as fine in the darks as in the
|
||||
// brights. Encode has 256 steps per power of two from 2^-9 up to 1, and its relative error stays
|
||||
// below 5e-7. Decode has 1024 steps per power of two from 2^-4 up to 1, with the same error.
|
||||
// That is as large as the error of the power function on the GPU, and about 30 times smaller than
|
||||
// the error the checks allow.
|
||||
const int EncodeFractionBits = 15;
|
||||
const int EncodeFirstStep = 0x3B000000 >> EncodeFractionBits;
|
||||
const int EncodeSteps = (0x3F800000 >> EncodeFractionBits) - EncodeFirstStep;
|
||||
const int DecodeFractionBits = 13;
|
||||
const int DecodeFirstStep = 0x3D800000 >> DecodeFractionBits;
|
||||
const int DecodeSteps = (0x3F800000 >> 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 / 255f, green / 255f, blue / 255f, alpha / 255f);
|
||||
if (alpha == 0)
|
||||
return default;
|
||||
|
||||
var opacity = alpha / 255f;
|
||||
float straightRed;
|
||||
float straightGreen;
|
||||
float straightBlue;
|
||||
float linearRed;
|
||||
float linearGreen;
|
||||
float linearBlue;
|
||||
if (alpha == 255)
|
||||
{
|
||||
straightRed = red / 255f;
|
||||
straightGreen = green / 255f;
|
||||
straightBlue = blue / 255f;
|
||||
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);
|
||||
}
|
||||
|
||||
// One threshold serves the four values of a pixel. Rounding is monotonic for a shared threshold, so a
|
||||
// color that does not exceed the opacity before rounding does not exceed it after rounding either.
|
||||
var threshold = options.Dither ? DitherThreshold(x, y) : 0f;
|
||||
return (
|
||||
Quantize(outputBlue, options.Dither, threshold),
|
||||
Quantize(outputGreen, options.Dither, threshold),
|
||||
Quantize(outputRed, options.Dither, threshold),
|
||||
Quantize(outputAlpha, options.Dither, threshold));
|
||||
}
|
||||
|
||||
// The same conversion as ToBytes for one pixel held in a vector (red, green, blue, alpha), returned as
|
||||
// the four bytes (blue, green, red, alpha). Every step is the same IEEE operation in the same order,
|
||||
// so the bytes are the ones ToBytes returns.
|
||||
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(255f);
|
||||
var levels = options.Dither
|
||||
? Vector128.ConvertToInt32(Vector128.Min(scaled + Vector128.Create(DitherThreshold(x, y)), Vector128.Create(255f)))
|
||||
: Vector128.ConvertToInt32(scaled + Vector128.Create(0.5f));
|
||||
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 = unchecked((uint)x * 0x9E3779B1u ^ (uint)y * 0x85EBCA77u);
|
||||
hash ^= hash >> 16;
|
||||
hash = unchecked(hash * 0x7FEB352Du);
|
||||
hash ^= hash >> 15;
|
||||
hash = unchecked(hash * 0x846CA68Bu);
|
||||
hash ^= hash >> 16;
|
||||
return (hash >> 8) * (1f / 16777216f);
|
||||
}
|
||||
|
||||
static byte Quantize(float value, bool dither, float threshold)
|
||||
=> dither
|
||||
? (byte)MathF.Min(value * 255f + threshold, 255f)
|
||||
: (byte)(value * 255f + 0.5f);
|
||||
|
||||
static float Saturate(float value)
|
||||
=> float.IsNaN(value) ? 0f : Math.Clamp(value, 0f, 1f);
|
||||
|
||||
static float[] BuildOpaqueDecode()
|
||||
{
|
||||
var table = new float[256];
|
||||
for (var index = 0; index < table.Length; index++)
|
||||
table[index] = Decode(index / 255f);
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -66,6 +66,46 @@ 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());
|
||||
}
|
||||
|
||||
public static IEnumerable<(string Name, Func<WaveOpticsEffect> Create, Action<WaveOpticsEffect> Change, int Frame)> Transitions()
|
||||
@@ -94,6 +134,21 @@ 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);
|
||||
}
|
||||
|
||||
public static IEnumerable<(string Name, WaveOpticsEffect Effect)> Benchmarks()
|
||||
|
||||
+93
-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,68 @@ static int Convolution(HarnessImage image)
|
||||
return subject;
|
||||
}
|
||||
|
||||
try
|
||||
void Measure(string title, Func<(string Name, Action<bool> Run)[]> create)
|
||||
{
|
||||
try
|
||||
{
|
||||
var variants = create();
|
||||
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)");
|
||||
|
||||
// Each set owns its pipelines while it runs. Keeping the pipelines of the other set alive would
|
||||
// change the memory the GPU has left and slow every row down.
|
||||
Measure("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 +318,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 +331,35 @@ 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);
|
||||
Measure("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 })),
|
||||
];
|
||||
});
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static Bgra32[] ToPixels(HarnessImage image, bool mirror)
|
||||
@@ -461,8 +500,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 +510,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,70 @@
|
||||
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"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -236,6 +236,70 @@
|
||||
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"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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];
|
||||
|
||||
[Theory]
|
||||
[InlineData(nameof(WaveOpticsEffect.Amount), 100d, 0d, 100d)]
|
||||
@@ -34,6 +34,8 @@ 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)]
|
||||
public void AnimatedParametersStartFromTheirDefaultsWithinTheirRange(string name, double defaultValue, double minimum, double maximum)
|
||||
{
|
||||
var effect = new WaveOpticsEffect();
|
||||
@@ -46,6 +48,15 @@ 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 KernelRadiusQualityApertureAndBladesStartFromTheirDefaults()
|
||||
{
|
||||
@@ -106,14 +117,16 @@ public sealed class WaveOpticsEffectTests
|
||||
effect.Quality = WaveOpticsQuality.High;
|
||||
effect.ApertureShape = WaveOpticsApertureShape.RegularPolygon;
|
||||
effect.BladeCount = 9;
|
||||
effect.Linear = true;
|
||||
effect.Dither = 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)], changed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AssigningAnUnchangedOrClampedValueDoesNotNotify()
|
||||
{
|
||||
var effect = new WaveOpticsEffect { KernelRadius = WaveOpticsSettings.MaximumKernelRadius };
|
||||
var effect = new WaveOpticsEffect { KernelRadius = WaveOpticsSettings.MaximumKernelRadius, Linear = true, Dither = true };
|
||||
var changed = new List<string?>();
|
||||
effect.PropertyChanged += (_, e) => changed.Add(e.PropertyName);
|
||||
|
||||
@@ -122,6 +135,8 @@ public sealed class WaveOpticsEffectTests
|
||||
effect.Quality = WaveOpticsQuality.Standard;
|
||||
effect.ApertureShape = WaveOpticsApertureShape.Circular;
|
||||
effect.BladeCount = 6;
|
||||
effect.Linear = true;
|
||||
effect.Dither = true;
|
||||
|
||||
Assert.Empty(changed);
|
||||
}
|
||||
@@ -135,7 +150,7 @@ public sealed class WaveOpticsEffectTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheThirteenNumericParametersReceiveTheAnimationParameters()
|
||||
public void TheFifteenNumericParametersReceiveTheAnimationParameters()
|
||||
{
|
||||
var effect = new WaveOpticsEffect();
|
||||
|
||||
@@ -174,6 +189,10 @@ 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)]
|
||||
@@ -214,6 +233,8 @@ 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)]
|
||||
public void AnimatedParametersAreEditedWithAnimationSliders(string property, string format, string unit, double minimum, double maximum)
|
||||
{
|
||||
var slider = Attribute<AnimationSliderAttribute>(property);
|
||||
@@ -241,6 +262,15 @@ public sealed class WaveOpticsEffectTests
|
||||
Assert.Equal(defaultValue, Attribute<DefaultValueAttribute>(property).Value);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(nameof(WaveOpticsEffect.Linear))]
|
||||
[InlineData(nameof(WaveOpticsEffect.Dither))]
|
||||
public void TheLightSwitchesAreEditedWithToggleSliders(string property)
|
||||
{
|
||||
Assert.NotNull(Property(property).GetCustomAttribute<ToggleSliderAttribute>());
|
||||
Assert.Equal(typeof(bool), Property(property).PropertyType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheQualityAndTheApertureShapeAreChosenFromCombos()
|
||||
{
|
||||
@@ -267,8 +297,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 };
|
||||
var values = new[] { 55d, 150d, 620d, 5.6d, 2.5d, 30d, 40d, 1.5d, -0.5d, 0.25d, -1d, 0.75d, 2d, 80d, 12d };
|
||||
foreach (var (animation, value) in Animations(effect).Zip(values))
|
||||
animation.Values[0].Value = value;
|
||||
|
||||
@@ -279,6 +309,8 @@ 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.Equal(values, Animations(clone).Select(animation => animation.GetValue(0, 1, EffectDescriptions.Fps)));
|
||||
}
|
||||
|
||||
@@ -294,6 +326,10 @@ 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.Equal(95d, effect.HighlightThreshold.GetValue(0, 1, EffectDescriptions.Fps));
|
||||
Assert.Equal(1d, effect.HighlightBoost.GetValue(0, 1, EffectDescriptions.Fps));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -0,0 +1,356 @@
|
||||
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 plain = Total(RenderCpu(source, Size, Size, in parameters)) / reference;
|
||||
var kept = Total(RenderCpu(source, Size, Size, in dithered)) / reference;
|
||||
|
||||
// Each rounding error is about 0.3 of a level, and the sum of the 40000 errors is a few percent of
|
||||
// the light of the spot at most. Without dithering, the faint tails are rounded down to nothing.
|
||||
Assert.InRange(plain, 0.88, 0.97);
|
||||
Assert.InRange(kept, 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);
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -48,3 +48,11 @@ 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.
|
||||
|
@@ -27,6 +27,24 @@ 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))]
|
||||
[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))]
|
||||
[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.Wavelength), Description = nameof(Texts.WavelengthDescription), Order = 10, ResourceType = typeof(Texts))]
|
||||
[AnimationSlider("F1", "nm", 380, 780)]
|
||||
public Animation Wavelength { get; } = new(550, 380, 780);
|
||||
@@ -113,5 +131,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];
|
||||
}
|
||||
@@ -125,7 +125,12 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
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)));
|
||||
Sanitize(_item.Spherical.GetValue(frame, length, fps), -10, 10, 0)),
|
||||
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)));
|
||||
|
||||
if (_isFirst || _amount != amount)
|
||||
_effect.Amount = amount;
|
||||
@@ -245,7 +250,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 +303,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)
|
||||
{
|
||||
@@ -565,5 +570,6 @@ internal sealed class WaveOpticsEffectProcessor : VideoEffectProcessorBase
|
||||
|
||||
private readonly record struct RenderState(
|
||||
float Gain,
|
||||
bool Dither,
|
||||
WaveOpticsPipeline.PixelRect Rect);
|
||||
}
|
||||
@@ -33,19 +33,29 @@ internal sealed class FraunhoferKernelSampler
|
||||
continue;
|
||||
|
||||
var column = (shiftedColumn + center) % gridSize;
|
||||
for (var row = 0; row < gridSize; row++)
|
||||
columnReal.AsSpan(0, firstRow).Clear();
|
||||
columnImaginary.AsSpan(0, firstRow).Clear();
|
||||
for (var row = firstRow; row <= lastRow; row++)
|
||||
{
|
||||
var open = row >= firstRow && row <= lastRow;
|
||||
columnReal[row] = open ? real[row * gridSize + column] : 0d;
|
||||
columnImaginary[row] = open ? imaginary[row * gridSize + column] : 0d;
|
||||
columnReal[row] = real[row * gridSize + column];
|
||||
columnImaginary[row] = imaginary[row * gridSize + column];
|
||||
}
|
||||
columnReal.AsSpan(lastRow + 1, gridSize - lastRow - 1).Clear();
|
||||
columnImaginary.AsSpan(lastRow + 1, gridSize - lastRow - 1).Clear();
|
||||
|
||||
FastFourierTransform.Forward(columnReal.AsSpan(0, gridSize), columnImaginary.AsSpan(0, gridSize));
|
||||
for (var row = 0; row < gridSize; row++)
|
||||
var split = gridSize - center;
|
||||
for (var row = 0; row < split; row++)
|
||||
{
|
||||
var a = columnReal[row];
|
||||
var b = columnImaginary[row];
|
||||
intensity[(row + center) % gridSize * gridSize + shiftedColumn] = a * a + b * b;
|
||||
intensity[(row + center) * gridSize + shiftedColumn] = a * a + b * b;
|
||||
}
|
||||
for (var row = split; row < gridSize; row++)
|
||||
{
|
||||
var a = columnReal[row];
|
||||
var b = columnImaginary[row];
|
||||
intensity[(row - split) * gridSize + shiftedColumn] = a * a + b * b;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -93,9 +93,9 @@ public sealed class FraunhoferPsfGenerator : IPsfGenerator
|
||||
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 angle = TwoPi * waves;
|
||||
real[index] = Math.Cos(angle);
|
||||
imaginary[index] = Math.Sin(angle);
|
||||
openSampleCount++;
|
||||
}
|
||||
else
|
||||
|
||||
@@ -47,7 +47,7 @@ internal sealed class WaveOpticsCpuPipeline : IDisposable
|
||||
_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);
|
||||
_convolver.Convolve(_packed, 0, 0, width, height, _kernel.Spectrum, plan, _output, 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);
|
||||
}
|
||||
|
||||
@@ -120,7 +120,7 @@ internal sealed class WaveOpticsCpuPipeline : IDisposable
|
||||
}
|
||||
|
||||
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);
|
||||
_convolver.Convolve(_source, _sourceRect.X, _sourceRect.Y, _sourceRect.Width, _sourceRect.Height, _kernel.Spectrum, plan, _output, parameters.Gain, store, parameters.Light);
|
||||
return _output.AsSpan(0, length);
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
@@ -260,18 +263,18 @@ internal sealed class WaveOpticsPipeline : IDisposable
|
||||
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)
|
||||
{
|
||||
@@ -290,7 +293,7 @@ internal sealed class WaveOpticsPipeline : IDisposable
|
||||
}
|
||||
|
||||
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 job = _convolver.Prepare(plan, _sourceRect.X, _sourceRect.Y, _sourceRect.Width, _sourceRect.Height, gain, samples, store, light);
|
||||
if (store)
|
||||
_storedJob = job;
|
||||
|
||||
@@ -322,7 +325,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);
|
||||
@@ -395,5 +398,5 @@ internal sealed class WaveOpticsPipeline : IDisposable
|
||||
float ComaVertical,
|
||||
float Spherical);
|
||||
|
||||
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,8 @@
|
||||
using System.Numerics;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Intrinsics;
|
||||
|
||||
namespace WaveOptics.Rendering;
|
||||
|
||||
internal readonly record struct WaveOpticsSourceHash(int LitCount, int MinimumX, int MinimumY, int MaximumX, int MaximumY, int Sum, int Mix)
|
||||
@@ -15,6 +20,16 @@ internal readonly record struct WaveOpticsSourceHash(int LitCount, int MinimumX,
|
||||
scratch[WaveOpticsSettings.ScratchHashMix]);
|
||||
|
||||
public static WaveOpticsSourceHash Compute(ReadOnlySpan<byte> bgra, int sourceX, int sourceY, int sourceWidth, int sourceHeight)
|
||||
{
|
||||
if (bgra.Length < (long)sourceWidth * sourceHeight * 4)
|
||||
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 * 4)
|
||||
throw new ArgumentException(null, nameof(bgra));
|
||||
@@ -35,10 +50,7 @@ internal readonly record struct WaveOpticsSourceHash(int LitCount, int MinimumX,
|
||||
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 = Mixed(y * sourceWidth + x, quantized);
|
||||
sum = unchecked(sum + (int)mixed);
|
||||
mix ^= unchecked((int)(mixed * 0xC2B2AE35u));
|
||||
count++;
|
||||
@@ -52,6 +64,98 @@ internal readonly record struct WaveOpticsSourceHash(int LitCount, int MinimumX,
|
||||
return new WaveOpticsSourceHash(count, minimumX, minimumY, maximumX, maximumY, sum, mix);
|
||||
}
|
||||
|
||||
// The same sums as the scalar form: eight pixels at a time, with the unlit ones masked out. Both sums
|
||||
// do not depend on the order of the pixels, so the result is the same, bit for bit.
|
||||
internal static WaveOpticsSourceHash ComputeVector(ReadOnlySpan<byte> bgra, int sourceX, int sourceY, int sourceWidth, int sourceHeight)
|
||||
{
|
||||
var pixels = MemoryMarshal.Cast<byte, uint>(bgra[..(sourceWidth * sourceHeight * 4)]);
|
||||
ref var origin = ref MemoryMarshal.GetReference(pixels);
|
||||
var lanes = Vector256.Create(0u, 1u, 2u, 3u, 4u, 5u, 6u, 7u);
|
||||
var golden = Vector256.Create(0x9E3779B9u);
|
||||
var first = Vector256.Create(0x85EBCA6Bu);
|
||||
var second = Vector256.Create(0xC2B2AE35u);
|
||||
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 >> 16;
|
||||
mixed *= first;
|
||||
mixed ^= mixed >> 13;
|
||||
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 = Mixed(rowStart + x, quantized);
|
||||
sum = unchecked(sum + mixed);
|
||||
mix ^= unchecked(mixed * 0xC2B2AE35u);
|
||||
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));
|
||||
}
|
||||
|
||||
private static uint Mixed(int index, uint quantized)
|
||||
{
|
||||
var mixed = unchecked((uint)index * 0x9E3779B9u ^ quantized * 0x85EBCA6Bu);
|
||||
mixed ^= mixed >> 16;
|
||||
mixed = unchecked(mixed * 0x85EBCA6Bu);
|
||||
mixed ^= mixed >> 13;
|
||||
return mixed;
|
||||
}
|
||||
|
||||
public bool TryGetVisibleBounds(int canvasWidth, int canvasHeight, int radius, out WaveOpticsPipeline.PixelRect rect)
|
||||
{
|
||||
rect = default;
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<Nullable>enable</Nullable>
|
||||
<AssemblyName>WaveOptics</AssemblyName>
|
||||
<RootNamespace>WaveOptics</RootNamespace>
|
||||
<Version>3.0.0</Version>
|
||||
<Version>3.1.0</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
|
||||
バイナリファイルは表示されません。
|
変更後 幅: | 高さ: | サイズ: 868 KiB |
新しいイシューから参照
ユーザーをブロックする